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 |
---|---|---|---|---|---|---|---|---|
31eb243f6c3d30f57f146f5ff40f17474e2c12f8
|
Bump version to 0.9.2
|
ar3cka/Journalist
|
src/SolutionInfo.cs
|
src/SolutionInfo.cs
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.9.2")]
[assembly: AssemblyInformationalVersionAttribute("0.9.2")]
[assembly: AssemblyFileVersionAttribute("0.9.2")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.2";
}
}
|
// <auto-generated/>
using System.Reflection;
[assembly: AssemblyProductAttribute("Journalist")]
[assembly: AssemblyVersionAttribute("0.9.1")]
[assembly: AssemblyInformationalVersionAttribute("0.9.1")]
[assembly: AssemblyFileVersionAttribute("0.9.1")]
[assembly: AssemblyCompanyAttribute("Anton Mednonogov")]
namespace System {
internal static class AssemblyVersionInformation {
internal const string Version = "0.9.1";
}
}
|
apache-2.0
|
C#
|
1925573ffd37f640ba5cc2d3b4b04fcef74f6e9b
|
Fix FarseerPhysics not compiling in release mode
|
Blucky87/Nez,prime31/Nez,prime31/Nez,ericmbernier/Nez,prime31/Nez
|
Nez.FarseerPhysics/Nez/Common/FSWorld.cs
|
Nez.FarseerPhysics/Nez/Common/FSWorld.cs
|
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Joints;
using Microsoft.Xna.Framework;
using Nez.Analysis;
namespace Nez.Farseer
{
public class FSWorld : SceneComponent
{
public World world;
/// <summary>
/// minimum delta time step for the simulation. The min of Time.deltaTime and this will be used for the physics step
/// </summary>
public float minimumUpdateDeltaTime = 1f / 30;
/// <summary>
/// if true, the left mouse button will be used for picking and dragging physics objects around
/// </summary>
public bool enableMousePicking;
FixedMouseJoint _mouseJoint;
public FSWorld() : this( new Vector2( 0, 9.82f ) )
{}
public FSWorld( Vector2 gravity )
{
world = new World( gravity );
}
public FSWorld setEnableMousePicking( bool enableMousePicking )
{
this.enableMousePicking = enableMousePicking;
return this;
}
#region SceneComponent
public override void onEnabled()
{
world.enabled = true;
}
public override void onDisabled()
{
world.enabled = false;
}
public override void onRemovedFromScene()
{
world.clear();
world = null;
}
public override void update()
{
if( enableMousePicking )
{
if( Input.leftMouseButtonPressed )
{
var pos = Core.scene.camera.screenToWorldPoint( Input.mousePosition );
var fixture = world.testPoint( FSConvert.displayToSim * pos );
if( fixture != null && !fixture.body.isStatic && !fixture.body.isKinematic )
_mouseJoint = fixture.body.createFixedMouseJoint( pos );
}
if( Input.leftMouseButtonDown && _mouseJoint != null )
{
var pos = Core.scene.camera.screenToWorldPoint( Input.mousePosition );
_mouseJoint.worldAnchorB = FSConvert.displayToSim * pos;
}
if( Input.leftMouseButtonReleased && _mouseJoint != null )
{
world.removeJoint( _mouseJoint );
_mouseJoint = null;
}
}
#if DEBUG
TimeRuler.instance.beginMark( "physics", Color.Blue );
#endif
world.step( MathHelper.Min( Time.deltaTime, minimumUpdateDeltaTime ) );
#if DEBUG
TimeRuler.instance.endMark( "physics" );
#endif
}
#endregion
#region World Querying
#endregion
public static implicit operator World( FSWorld self )
{
return self.world;
}
}
}
|
using FarseerPhysics.Dynamics;
using FarseerPhysics.Dynamics.Joints;
using Microsoft.Xna.Framework;
using Nez.Analysis;
namespace Nez.Farseer
{
public class FSWorld : SceneComponent
{
public World world;
/// <summary>
/// minimum delta time step for the simulation. The min of Time.deltaTime and this will be used for the physics step
/// </summary>
public float minimumUpdateDeltaTime = 1f / 30;
/// <summary>
/// if true, the left mouse button will be used for picking and dragging physics objects around
/// </summary>
public bool enableMousePicking;
FixedMouseJoint _mouseJoint;
public FSWorld() : this( new Vector2( 0, 9.82f ) )
{}
public FSWorld( Vector2 gravity )
{
world = new World( gravity );
}
public FSWorld setEnableMousePicking( bool enableMousePicking )
{
this.enableMousePicking = enableMousePicking;
return this;
}
#region SceneComponent
public override void onEnabled()
{
world.enabled = true;
}
public override void onDisabled()
{
world.enabled = false;
}
public override void onRemovedFromScene()
{
world.clear();
world = null;
}
public override void update()
{
if( enableMousePicking )
{
if( Input.leftMouseButtonPressed )
{
var pos = Core.scene.camera.screenToWorldPoint( Input.mousePosition );
var fixture = world.testPoint( FSConvert.displayToSim * pos );
if( fixture != null && !fixture.body.isStatic && !fixture.body.isKinematic )
_mouseJoint = fixture.body.createFixedMouseJoint( pos );
}
if( Input.leftMouseButtonDown && _mouseJoint != null )
{
var pos = Core.scene.camera.screenToWorldPoint( Input.mousePosition );
_mouseJoint.worldAnchorB = FSConvert.displayToSim * pos;
}
if( Input.leftMouseButtonReleased && _mouseJoint != null )
{
world.removeJoint( _mouseJoint );
_mouseJoint = null;
}
}
TimeRuler.instance.beginMark( "physics", Color.Blue );
world.step( MathHelper.Min( Time.deltaTime, minimumUpdateDeltaTime ) );
TimeRuler.instance.endMark( "physics" );
}
#endregion
#region World Querying
#endregion
public static implicit operator World( FSWorld self )
{
return self.world;
}
}
}
|
mit
|
C#
|
c6cf0d40ee6868d5ee04e9b5dff63065acc194f6
|
Simplify ReaderTests
|
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
|
tests/SharpCompress.Test/ReaderTests.cs
|
tests/SharpCompress.Test/ReaderTests.cs
|
using System.IO;
using SharpCompress.Common;
using SharpCompress.IO;
using SharpCompress.Readers;
using SharpCompress.Test.Mocks;
using Xunit;
namespace SharpCompress.Test
{
public class ReaderTests : TestBase
{
protected void Read(string testArchive, CompressionType expectedCompression)
{
testArchive = Path.Combine(TEST_ARCHIVES_PATH, testArchive);
using (var stream = new NonDisposingStream(new ForwardOnlyStream(File.OpenRead(testArchive)), true))
using (var reader = ReaderFactory.Open(stream, new ReaderOptions { LeaveStreamOpen = true }))
{
UseReader(this, reader, expectedCompression);
stream.ThrowOnDispose = false;
}
}
public static void UseReader(TestBase test, IReader reader, CompressionType expectedCompression)
{
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Assert.Equal(reader.Entry.CompressionType, expectedCompression);
reader.WriteEntryToDirectory(test.SCRATCH_FILES_PATH, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
}
test.VerifyFiles();
}
}
}
|
using System.Collections.Generic;
using System.IO;
using SharpCompress.Common;
using SharpCompress.IO;
using SharpCompress.Readers;
using SharpCompress.Test.Mocks;
using Xunit;
namespace SharpCompress.Test
{
public class ReaderTests : TestBase
{
protected void Read(string testArchive, CompressionType expectedCompression)
{
testArchive = Path.Combine(TEST_ARCHIVES_PATH, testArchive);
Read(testArchive.AsEnumerable(), expectedCompression);
}
protected void Read(IEnumerable<string> testArchives, CompressionType expectedCompression)
{
foreach (var path in testArchives)
{
using (var stream = new NonDisposingStream(new ForwardOnlyStream(File.OpenRead(path)), true))
using (var reader = ReaderFactory.Open(stream, new ReaderOptions()
{
LeaveStreamOpen = true
}))
{
UseReader(this, reader, expectedCompression);
stream.ThrowOnDispose = false;
}
}
}
public static void UseReader(TestBase test, IReader reader, CompressionType expectedCompression)
{
while (reader.MoveToNextEntry())
{
if (!reader.Entry.IsDirectory)
{
Assert.Equal(reader.Entry.CompressionType, expectedCompression);
reader.WriteEntryToDirectory(test.SCRATCH_FILES_PATH, new ExtractionOptions()
{
ExtractFullPath = true,
Overwrite = true
});
}
}
test.VerifyFiles();
}
}
}
|
mit
|
C#
|
adaad3303645fecd888dfe9e20a8fe53e07aff6b
|
Refactor tests for F.Always
|
farity/farity
|
Farity.Tests/AlwaysTests.cs
|
Farity.Tests/AlwaysTests.cs
|
using Xunit;
namespace Farity.Tests
{
public class AlwaysTests
{
[Theory]
[InlineData()]
[InlineData(1)]
[InlineData(null, null)]
[InlineData(null, null, "string")]
[InlineData(null, null, "string", 3)]
[InlineData(null, null, "string", 3, 7)]
[InlineData(null, null, "string", 3, 7, 9U)]
[InlineData(null, null, "string", 3, 7, 9U, 7L)]
[InlineData(null, null, "string", 3, 7, 9U, 7L, 9UL)]
public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways(params object[] args)
{
const int expected = 42;
var answerToLifeUniverseAndEverything = F.Always(expected);
var actual = answerToLifeUniverseAndEverything(args);
Assert.Equal(expected, actual);
}
}
}
|
using Xunit;
namespace Farity.Tests
{
public class AlwaysTests
{
[Fact]
public void AlwaysReturnsAFunctionThatReturnsTheSameValueAlways()
{
const int expected = 42;
var answerToLifeUniverseAndEverything = F.Always(expected);
Assert.Equal(expected, answerToLifeUniverseAndEverything());
Assert.Equal(expected, answerToLifeUniverseAndEverything(1));
Assert.Equal(expected, answerToLifeUniverseAndEverything("string", null));
Assert.Equal(expected, answerToLifeUniverseAndEverything(null, "str", 3));
Assert.Equal(expected, answerToLifeUniverseAndEverything(null, null, null, null));
}
}
}
|
mit
|
C#
|
c270225e9e513afdd0d7d902519a36b3fc9b72bb
|
Update MqttTopicFilterBuilder.cs
|
chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet,chkr1011/MQTTnet
|
Source/MQTTnet/MqttTopicFilterBuilder.cs
|
Source/MQTTnet/MqttTopicFilterBuilder.cs
|
using MQTTnet.Exceptions;
using MQTTnet.Protocol;
using System;
namespace MQTTnet
{
[Obsolete("Use MqttTopicFilterBuilder instead. It is just a renamed version to align with general namings in this lib.")]
public class TopicFilterBuilder : MqttTopicFilterBuilder
{
}
public class MqttTopicFilterBuilder
{
MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
string _topic;
public MqttTopicFilterBuilder WithTopic(string topic)
{
_topic = topic;
return this;
}
public MqttTopicFilterBuilder WithQualityOfServiceLevel(MqttQualityOfServiceLevel qualityOfServiceLevel)
{
_qualityOfServiceLevel = qualityOfServiceLevel;
return this;
}
public MqttTopicFilterBuilder WithAtLeastOnceQoS()
{
_qualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
return this;
}
public MqttTopicFilterBuilder WithAtMostOnceQoS()
{
_qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
return this;
}
public MqttTopicFilterBuilder WithExactlyOnceQoS()
{
_qualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce;
return this;
}
public MqttTopicFilter Build()
{
if (string.IsNullOrEmpty(_topic))
{
throw new MqttProtocolViolationException("Topic is not set.");
}
return new MqttTopicFilter { Topic = _topic, QualityOfServiceLevel = _qualityOfServiceLevel };
}
}
}
|
using MQTTnet.Exceptions;
using MQTTnet.Protocol;
using System;
namespace MQTTnet
{
[Obsolete("Use MqttTopicFilter instead. It is just a renamed version to align with general namings in this lib.")]
public class TopicFilterBuilder : MqttTopicFilterBuilder
{
}
public class MqttTopicFilterBuilder
{
MqttQualityOfServiceLevel _qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
string _topic;
public MqttTopicFilterBuilder WithTopic(string topic)
{
_topic = topic;
return this;
}
public MqttTopicFilterBuilder WithQualityOfServiceLevel(MqttQualityOfServiceLevel qualityOfServiceLevel)
{
_qualityOfServiceLevel = qualityOfServiceLevel;
return this;
}
public MqttTopicFilterBuilder WithAtLeastOnceQoS()
{
_qualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce;
return this;
}
public MqttTopicFilterBuilder WithAtMostOnceQoS()
{
_qualityOfServiceLevel = MqttQualityOfServiceLevel.AtMostOnce;
return this;
}
public MqttTopicFilterBuilder WithExactlyOnceQoS()
{
_qualityOfServiceLevel = MqttQualityOfServiceLevel.ExactlyOnce;
return this;
}
public MqttTopicFilter Build()
{
if (string.IsNullOrEmpty(_topic))
{
throw new MqttProtocolViolationException("Topic is not set.");
}
return new MqttTopicFilter { Topic = _topic, QualityOfServiceLevel = _qualityOfServiceLevel };
}
}
}
|
mit
|
C#
|
098b6d0f86457aee5c1ea3aa5c44ea48861d3994
|
Add preprocessor directive to integration tests
|
zapadi/vies-dotnetcore,zapadi/vies-dotnetcore
|
tests/vies-test/ViesIntegrationTests.cs
|
tests/vies-test/ViesIntegrationTests.cs
|
using System;
using System.Threading.Tasks;
using Xunit;
namespace Padi.Vies.Test
{
[Collection("ViesCollection")]
public class ViesIntegrationTests
{
private readonly ViesManagerFixture _fixture;
public ViesIntegrationTests(ViesManagerFixture fixture)
{
_fixture = fixture;
}
[Theory]
[InlineData("LU26375245")]
[InlineData("SE 556656688001")]
[InlineData("FI 09073468")]
[InlineData("NL 107452613B01")]
[InlineData("FR 66322120916")]
[InlineData("IT 01640320360")]
[InlineData("RO26129093")]
[InlineData("SK2120046819")]
public async Task Should_Return_Vat_Active(string vat)
{
var actual = await CheckIfActive(vat, true);
Assert.True(actual.IsValid, "Inactive vat number");
}
[Theory]
[InlineData("RO123456789")]
[InlineData("ATU12345675")]
[InlineData("CZ612345670")]
[InlineData("ESK1234567L")]
[InlineData("IE1234567T")]
[InlineData("NL123456782B90")]
public async Task Should_Return_Vat_Inactive(string vat)
{
var actual = await CheckIfActive(vat, false);
Assert.False(actual.IsValid, "Inactive vat number");
}
private async Task<ViesCheckVatResponse> CheckIfActive(string vat, bool mockValue){
ViesCheckVatResponse actual;
#if DEBUG
actual = await _fixture.ViesManager.IsActive(vat);
#else
actual = await Task.FromResult<ViesCheckVatResponse>(new ViesCheckVatResponse(null, null, DateTimeOffset.Now, isValid: mockValue));
#endif
return actual;
}
}
}
|
using System.Threading.Tasks;
using Xunit;
namespace Padi.Vies.Test
{
[Collection("ViesCollection")]
public class ViesIntegrationTests
{
private readonly ViesManagerFixture _fixture;
public ViesIntegrationTests(ViesManagerFixture fixture)
{
_fixture = fixture;
}
[Theory]
[InlineData("LU26375245")]
[InlineData("SE 556656688001")]
[InlineData("FI 09073468")]
[InlineData("NL 107452613B01")]
[InlineData("FR 66322120916")]
[InlineData("IT 01640320360")]
[InlineData("RO26129093")]
[InlineData("SK2120046819")]
public async Task Should_Return_Vat_Active(string vat)
{
var actual = await _fixture.ViesManager.IsActive(vat );
Assert.True(actual.IsValid, "Inactive vat number");
}
[Theory]
[InlineData("RO123456789")]
[InlineData("ATU12345675")]
[InlineData("CZ612345670")]
[InlineData("ESK1234567L")]
[InlineData("IE1234567T")]
[InlineData("NL123456782B90")]
public async Task Should_Return_Vat_Inactive(string vat)
{
var actual = await _fixture.ViesManager.IsActive(vat);
Assert.False(actual.IsValid, "Inactive vat number");
}
}
}
|
apache-2.0
|
C#
|
4a36859804522178a383d9bd21e5bdd60e152244
|
Ajuste en clase DataCreate
|
davidjhurtado/MobileTest,davidjhurtado/MobileTest
|
MobileTest/Library/DataCreate.cs
|
MobileTest/Library/DataCreate.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public class DataCreate
{
public DataCreate() {
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library
{
public static class DataCreate
{
public DataCreate() {
}
}
}
|
mit
|
C#
|
9470220fa13bd3c1e6c0f408833a34bdc5cfcc7c
|
move with force
|
nikibobi/LD36
|
Assets/Move.cs
|
Assets/Move.cs
|
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
[Range(10, 100)]
public float Speed;
private Rigidbody2D body;
// Use this for initialization
void Start() {
body = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update() {
var speed = new Vector2(Speed * Input.GetAxis("Horizontal") * Time.fixedDeltaTime, 0);
body.AddForce(speed, ForceMode2D.Impulse);
}
}
|
using UnityEngine;
using System.Collections;
public class Move : MonoBehaviour {
[Range(10, 100)]
public float Speed;
// Use this for initialization
void Start() {
}
// Update is called once per frame
void Update() {
this.transform.Translate(Speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0, 0, Space.World);
}
}
|
mit
|
C#
|
9d92089f9a22cae4b2981f976e7fd3e1a9d93514
|
Update WidgetEvents Sample
|
mminns/xwt,residuum/xwt,antmicro/xwt,cra0zy/xwt,hwthomas/xwt,directhex/xwt,TheBrainTech/xwt,mminns/xwt,mono/xwt,hamekoz/xwt,akrisiun/xwt,steffenWi/xwt,iainx/xwt,lytico/xwt,sevoku/xwt
|
TestApps/Samples/Samples/WidgetEvents.cs
|
TestApps/Samples/Samples/WidgetEvents.cs
|
//
// WidgetEvents.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
using Xwt.Drawing;
namespace Samples
{
public class WidgetEvents: VBox
{
Label la = new Label ("Move the mouse here");
Label res = new Label ("");
bool inside = false;
bool moved = false;
public WidgetEvents ()
{
PackStart (la);
PackStart (res);
la.MouseEntered += delegate {
inside = true;
Application.TimeoutInvoke (100, CheckMouse);
};
la.MouseExited += delegate {
inside = false;
};
la.MouseMoved += delegate {
moved = true;
};
}
bool CheckMouse ()
{
if (!inside) {
res.Text = "Mouse has Exited label";
la.TextColor = Colors.Black;
la.BackgroundColor = Colors.LightGray;
la.Text = "Move the mouse here";
} else {
res.Text = "Mouse has Entered label";
la.TextColor = Colors.White;
if (moved) {
la.BackgroundColor = Colors.Green;
la.Text = "Mouse is moving";
moved = false; // reset and check next time
} else {
la.BackgroundColor = Colors.Red;
la.Text = "Mouse has stopped";
}
}
return inside;
}
}
}
|
//
// WidgetEvents.cs
//
// Author:
// Lluis Sanchez <lluis@xamarin.com>
//
// Copyright (c) 2012 Xamarin Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt;
namespace Samples
{
public class WidgetEvents: VBox
{
Label res;
public WidgetEvents ()
{
Label la = new Label ("Move the mouse here");
res = new Label ();
PackStart (la);
PackStart (res);
la.MouseEntered += delegate {
la.Text = "Mouse has Entered label";
};
la.MouseExited += delegate {
la.Text = "Mouse has Exited label";
res.Text = "Mouse has moved out of label";
};
la.MouseMoved += delegate {
res.Text = "Mouse is moving in label";
Application.TimeoutInvoke (800, MouseStopped);
};
}
bool MouseStopped ()
{
res.Text = "Mouse has stopped in label";
return false;
}
}
}
|
mit
|
C#
|
f722f0af8b8fbf3d08406b45452e95ac2e9ddedb
|
Update LogLevel for DebugLogger
|
SourceHollandaise/TriggerSol
|
TriggerSol.JStore.Shared/Bootstrapper.cs
|
TriggerSol.JStore.Shared/Bootstrapper.cs
|
using System;
using System.IO;
using TriggerSol.Dependency;
using TriggerSol.JStore;
using TriggerSol.Logging;
namespace TriggerSol.Boost
{
public class Bootstrapper : DependencyObject
{
public Bootstrapper()
{
RegisterLogger(new DebugLogger { Level = LogLevel.Detailed });
}
public void InitDataStore<T>(string dataStorePath) where T: IDataStore, new()
{
SetStoreConfiguration(dataStorePath);
InitializeDataStore<T>();
}
public void RegisterLogger(ILogger logger)
{
TypeResolver.ClearSingle<ILogger>();
TypeResolver.RegisterSingle<ILogger>(logger);
}
protected virtual void SetStoreConfiguration(string dataStorePath)
{
var config = new StoreConfiguration(dataStorePath);
config.InitStore();
TypeResolver.RegisterSingle<IStoreConfiguration>(config);
}
protected virtual void InitializeDataStore<T>() where T: IDataStore, new()
{
TypeResolver.RegisterObjectType<IMappingIdGenerator, GuidIdGenerator>();
TypeResolver.RegisterObjectType<IFileDataService, FileDataService>();
DataStoreManager.RegisterStore<CachedFileDataStore>();
}
}
}
|
using System;
using System.IO;
using TriggerSol.Dependency;
using TriggerSol.JStore;
using TriggerSol.Logging;
namespace TriggerSol.Boost
{
public class Bootstrapper : DependencyObject
{
public Bootstrapper()
{
RegisterLogger(new DebugLogger { Level = LogLevel.OnlyException });
}
public void InitDataStore<T>(string dataStorePath) where T: IDataStore, new()
{
SetStoreConfiguration(dataStorePath);
InitializeDataStore<T>();
}
public void RegisterLogger(ILogger logger)
{
TypeResolver.ClearSingle<ILogger>();
TypeResolver.RegisterSingle<ILogger>(logger);
}
protected virtual void SetStoreConfiguration(string dataStorePath)
{
var config = new StoreConfiguration(dataStorePath);
config.InitStore();
TypeResolver.RegisterSingle<IStoreConfiguration>(config);
}
protected virtual void InitializeDataStore<T>() where T: IDataStore, new()
{
TypeResolver.RegisterObjectType<IMappingIdGenerator, GuidIdGenerator>();
TypeResolver.RegisterObjectType<IFileDataService, FileDataService>();
DataStoreManager.RegisterStore<CachedFileDataStore>();
}
}
}
|
mit
|
C#
|
a14e68912efcd03fa598fc55914b5b1465e2c1bd
|
use AppDomain root to locate the logs directory
|
jmptrader/SuperSocket,mdavid/SuperSocket,fryderykhuang/SuperSocket,mdavid/SuperSocket,kerryjiang/SuperSocket,ZixiangBoy/SuperSocket,ZixiangBoy/SuperSocket,chucklu/SuperSocket,jmptrader/SuperSocket,kerryjiang/SuperSocket,memleaks/SuperSocket,fryderykhuang/SuperSocket,ZixiangBoy/SuperSocket,mdavid/SuperSocket,fryderykhuang/SuperSocket,jmptrader/SuperSocket,chucklu/SuperSocket,chucklu/SuperSocket
|
mainline/Common/LogUtil.cs
|
mainline/Common/LogUtil.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using log4net.Config;
namespace SuperSocket.Common
{
public class LogUtil
{
private static ILogger m_logger;
public static void Setup()
{
Setup(@"Config\log4net.config");
}
public static void Setup(string log4netConfig)
{
if (!Path.IsPathRooted(log4netConfig))
log4netConfig = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, log4netConfig);
XmlConfigurator.Configure(new FileInfo(log4netConfig));
m_logger = new Log4NetLogger();
}
public static void Setup(ILogger logger)
{
m_logger = logger;
}
public static ILogger GetRootLogger()
{
return m_logger;
}
public static void LogError(Exception e)
{
if (m_logger != null)
m_logger.LogError(e);
}
public static void LogError(string title, Exception e)
{
if (m_logger != null)
m_logger.LogError(title, e);
}
public static void LogError(string message)
{
if (m_logger != null)
m_logger.LogError(message);
}
public static void LogDebug(string message)
{
if (m_logger != null)
m_logger.LogDebug(message);
}
public static void LogInfo(string message)
{
if (m_logger != null)
m_logger.LogInfo(message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using log4net.Config;
namespace SuperSocket.Common
{
public class LogUtil
{
private static ILogger m_logger;
public static void Setup()
{
Setup(@"Config\log4net.config");
}
public static void Setup(string log4netConfig)
{
XmlConfigurator.Configure(new FileInfo(log4netConfig));
m_logger = new Log4NetLogger();
}
public static void Setup(ILogger logger)
{
m_logger = logger;
}
public static ILogger GetRootLogger()
{
return m_logger;
}
public static void LogError(Exception e)
{
if (m_logger != null)
m_logger.LogError(e);
}
public static void LogError(string title, Exception e)
{
if (m_logger != null)
m_logger.LogError(title, e);
}
public static void LogError(string message)
{
if (m_logger != null)
m_logger.LogError(message);
}
public static void LogDebug(string message)
{
if (m_logger != null)
m_logger.LogDebug(message);
}
public static void LogInfo(string message)
{
if (m_logger != null)
m_logger.LogInfo(message);
}
}
}
|
apache-2.0
|
C#
|
afd6a9f9f83163070b85ae81d7e95add1cdd56a3
|
fix cocoapods github auth
|
xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents
|
Util/VersionChecker/common/CocoaPods.csx
|
Util/VersionChecker/common/CocoaPods.csx
|
#load "VersionFetcher.csx"
using Newtonsoft.Json.Linq;
using Semver;
public class CocoaPods : VersionFetcher
{
public CocoaPods (string component, string version, string podId, string owner)
: base (component, version, owner)
{
PodId = podId;
}
public string PodId { get; private set; }
public override string FetchNewestAvailableVersion ()
{
var githubClientId = System.Environment.GetEnvironmentVariable ("GITHUB_CLIENT_ID");
var githubClientSecret = System.Environment.GetEnvironmentVariable ("GITHUB_CLIENT_SECRET");
// CocoaPods moved to using a folder prefix in their Specs repo in order to avoid
// having all the specs in a single directory
// The formula is the first 3 chars of the md5 value of the Pod ID
// where each of the 3 letters is a folder/subfolder/subsubfolder
// So we'll hash the PodID, and construct the path using this formula
var podIdBytes = System.Text.Encoding.Default.GetBytes (PodId);
var podIdMd5 = string.Empty;
using (var md5 = System.Security.Cryptography.MD5.Create ()) {
podIdMd5 = System.BitConverter.ToString (md5.ComputeHash (podIdBytes)).Replace ("-", "").ToLowerInvariant ();
}
var podIdPath = podIdMd5[0] + "/" + podIdMd5[1] + "/" + podIdMd5[2] + "/" + PodId;
var http = new HttpClient ();
http.DefaultRequestHeaders.UserAgent.ParseAdd ("Xamarin-Internal/1.0");
var tree = string.Format ("master:Specs/{0}", podIdPath);
var url = string.Format ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", System.Net.WebUtility.UrlEncode (tree));
if (!string.IsNullOrEmpty (githubClientId) && !string.IsNullOrEmpty (githubClientSecret))
url += "?client_id=" + githubClientId + "&client_secret=" + githubClientSecret;
var data = http.GetStringAsync (url).Result;
var json = JObject.Parse (data);
var items = json["tree"] as JArray;
var highestVersion = SemVersion.Parse ("0.0.0");
foreach (var item in items) {
var path = item["path"].ToString ();
try {
var v = SemVersion.Parse (path);
if (v > highestVersion)
highestVersion = v;
} catch { }
}
return highestVersion.ToString ();
}
}
|
#load "VersionFetcher.csx"
using Newtonsoft.Json.Linq;
using Semver;
public class CocoaPods : VersionFetcher
{
public CocoaPods (string component, string version, string podId, string owner)
: base (component, version, owner)
{
PodId = podId;
}
public string PodId { get; private set; }
public override string FetchNewestAvailableVersion ()
{
// CocoaPods moved to using a folder prefix in their Specs repo in order to avoid
// having all the specs in a single directory
// The formula is the first 3 chars of the md5 value of the Pod ID
// where each of the 3 letters is a folder/subfolder/subsubfolder
// So we'll hash the PodID, and construct the path using this formula
var podIdBytes = System.Text.Encoding.Default.GetBytes (PodId);
var podIdMd5 = string.Empty;
using (var md5 = System.Security.Cryptography.MD5.Create ()) {
podIdMd5 = System.BitConverter.ToString (md5.ComputeHash (podIdBytes)).Replace ("-", "").ToLowerInvariant ();
}
var podIdPath = podIdMd5[0] + "/" + podIdMd5[1] + "/" + podIdMd5[2] + "/" + PodId;
var http = new HttpClient ();
http.DefaultRequestHeaders.UserAgent.ParseAdd ("Xamarin-Internal/1.0");
var tree = string.Format ("master:Specs/{0}", podIdPath);
//Console.WriteLine ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", tree);
var url = string.Format ("https://api.github.com/repos/{0}/{1}/git/trees/{2}", "CocoaPods", "Specs", System.Net.WebUtility.UrlEncode (tree));
if (!string.IsNullOrEmpty (githubClientId) && !string.IsNullOrEmpty (githubClientSecret))
url += "?client_id=" + githubClientId + "&client_secret=" + githubClientSecret;
var data = http.GetStringAsync (url).Result;
var json = JObject.Parse (data);
var items = json["tree"] as JArray;
var highestVersion = SemVersion.Parse ("0.0.0");
foreach (var item in items) {
var path = item["path"].ToString ();
try {
var v = SemVersion.Parse (path);
if (v > highestVersion)
highestVersion = v;
} catch { }
}
return highestVersion.ToString ();
}
}
|
mit
|
C#
|
37ed0e4cb5464611fdef8d888ceaf3608cfc9eae
|
Fix schedule for evals
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Jobs/JobHandler.cs
|
Battery-Commander.Web/Jobs/JobHandler.cs
|
using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;
namespace BatteryCommander.Web.Jobs
{
internal static class JobHandler
{
public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(typeof(JobHandler));
JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);
JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);
JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);
JobManager.UseUtcTime();
JobManager.JobFactory = new JobFactory(app.ApplicationServices);
var registry = new Registry();
registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0);
registry.Schedule<EvaluationDueReminderJob>().ToRunEvery(1).Weeks().On(DayOfWeek.Friday).At(hours: 12, minutes: 0);
JobManager.Initialize(registry);
}
private class JobFactory : IJobFactory
{
private readonly IServiceProvider serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public IJob GetJobInstance<T>() where T : IJob
{
return serviceProvider.GetService(typeof(T)) as IJob;
}
}
}
}
|
using FluentScheduler;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Logging;
using System;
namespace BatteryCommander.Web.Jobs
{
internal static class JobHandler
{
public static void UseJobScheduler(this IApplicationBuilder app, ILoggerFactory loggerFactory)
{
var logger = loggerFactory.CreateLogger(typeof(JobHandler));
JobManager.JobStart += (job) => logger.LogInformation("{job} started", job.Name);
JobManager.JobEnd += (job) => logger.LogInformation("{job} completed in {time}", job.Name, job.Duration);
JobManager.JobException += (context) => logger.LogError(context.Exception, "{job} failed", context.Name);
JobManager.UseUtcTime();
JobManager.JobFactory = new JobFactory(app.ApplicationServices);
var registry = new Registry();
registry.Schedule<SqliteBackupJob>().ToRunEvery(1).Days().At(hours: 11, minutes: 0);
registry.Schedule<EvaluationDueReminderJob>().ToRunNow();
JobManager.Initialize(registry);
}
private class JobFactory : IJobFactory
{
private readonly IServiceProvider serviceProvider;
public JobFactory(IServiceProvider serviceProvider)
{
this.serviceProvider = serviceProvider;
}
public IJob GetJobInstance<T>() where T : IJob
{
return serviceProvider.GetService(typeof(T)) as IJob;
}
}
}
}
|
mit
|
C#
|
0361cc70a18cb4df41c92e0bfcc1d8e3ee390de3
|
Add url to get unicorns
|
fpellet/Bbl.KnockoutJs,fpellet/Bbl.KnockoutJs,fpellet/Bbl.KnockoutJs
|
Bbl.KnockoutJs/Bbl.KnockoutJs/Startup.cs
|
Bbl.KnockoutJs/Bbl.KnockoutJs/Startup.cs
|
using System.IO;
using System.Linq;
using System.Web.Hosting;
using Nancy;
using Owin;
namespace Bbl.KnockoutJs
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
}
public class IndexModule : NancyModule
{
private const string UnicornsPath = "/Content/Unicorn/";
public IndexModule()
{
Get["/"] = parameters => View["index"];
Get["/api/unicorns"] = parameters =>
{
var imagesDirectory = HostingEnvironment.MapPath("~" + UnicornsPath);
return new DirectoryInfo(imagesDirectory)
.EnumerateFiles()
.Select(ConvertToDto);
};
}
private dynamic ConvertToDto(FileInfo file)
{
var name = Path.GetFileNameWithoutExtension(file.Name);
return new
{
Key = name,
ImagePath = UnicornsPath + file.Name,
Name = name.Replace('_', ' '),
Keywords = name.Split('_'),
CreationDate = file.CreationTime
};
}
}
}
|
using Nancy;
using Owin;
namespace Bbl.KnockoutJs
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseNancy();
}
}
public class IndexModule : NancyModule
{
public IndexModule()
{
Get["/"] = parameters => View["index"];
}
}
}
|
mit
|
C#
|
ea5ea443f91d667223ede870787794fa16af8f46
|
update WPF
|
IdentityModel/IdentityModel.OidcClient.Samples,IdentityModel/IdentityModel.OidcClient.Samples
|
WpfWebView/WpfWebView/MainWindow.xaml.cs
|
WpfWebView/WpfWebView/MainWindow.xaml.cs
|
using IdentityModel.OidcClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfWebView
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private OidcClient _oidcClient = null;
public MainWindow()
{
InitializeComponent();
Loaded += Start;
}
public async void Start(object sender, RoutedEventArgs e)
{
var options = new OidcClientOptions()
{
Authority = "https://demo.identityserver.io/",
ClientId = "interactive.public",
Scope = "openid profile email",
RedirectUri = "http://127.0.0.1/sample-wpf-app",
Browser = new WpfEmbeddedBrowser()
};
_oidcClient = new OidcClient(options);
LoginResult result;
try
{
result = await _oidcClient.LoginAsync();
}
catch (Exception ex)
{
Message.Text = $"Unexpected Error: {ex.Message}";
return;
}
if (result.IsError)
{
Message.Text = result.Error == "UserCancel" ? "The sign-in window was closed before authorization was completed." : result.Error;
}
else
{
var name = result.User.Identity.Name;
Message.Text = $"Hello {name}";
}
}
}
}
|
using IdentityModel.OidcClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace WpfWebView
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private OidcClient _oidcClient = null;
public MainWindow()
{
InitializeComponent();
Loaded += Start;
}
public async void Start(object sender, RoutedEventArgs e)
{
var options = new OidcClientOptions()
{
Authority = "https://demo.identityserver.io/",
ClientId = "native.code",
Scope = "openid profile email",
RedirectUri = "http://127.0.0.1/sample-wpf-app",
Browser = new WpfEmbeddedBrowser()
};
_oidcClient = new OidcClient(options);
LoginResult result;
try
{
result = await _oidcClient.LoginAsync();
}
catch (Exception ex)
{
Message.Text = $"Unexpected Error: {ex.Message}";
return;
}
if (result.IsError)
{
Message.Text = result.Error == "UserCancel" ? "The sign-in window was closed before authorization was completed." : result.Error;
}
else
{
var name = result.User.Identity.Name;
Message.Text = $"Hello {name}";
}
}
}
}
|
apache-2.0
|
C#
|
1809d97221458371619745e8792f52b07bde8f94
|
fix staging endpoint urls
|
omise/omise-dotnet
|
Omise/Environments.cs
|
Omise/Environments.cs
|
using System;
using System.Collections.Generic;
namespace Omise
{
public sealed class Environments
{
public static readonly IEnvironment Production =
new CustomEnvironment(new Dictionary<Endpoint, string> {
{ Endpoint.Api, "https://api.omise.co" },
{ Endpoint.Vault, "https://vault.omise.co" },
});
public static readonly IEnvironment Staging =
new CustomEnvironment(new Dictionary<Endpoint, string> {
{ Endpoint.Api, "https://api.staging-omise.co" },
{ Endpoint.Vault, "https://vault.staging-omise.co" },
});
public static readonly IEnvironment LocalMachine =
new CustomEnvironment(new Dictionary<Endpoint, string> {
{ Endpoint.Api, "https://api.lvh.me:3000" },
{ Endpoint.Vault, "https://vault.lvh.me:4500" },
});
}
}
|
using System;
using System.Collections.Generic;
namespace Omise
{
public sealed class Environments
{
public static readonly IEnvironment Production =
new CustomEnvironment(new Dictionary<Endpoint, string> {
{ Endpoint.Api, "https://api.omise.co" },
{ Endpoint.Vault, "https://vault.omise.co" },
});
public static readonly IEnvironment Staging =
new CustomEnvironment(new Dictionary<Endpoint, string> {
{ Endpoint.Api, "https://api-staging.omise.co" },
{ Endpoint.Vault, "https://vault-staging.omise.co" },
});
public static readonly IEnvironment LocalMachine =
new CustomEnvironment(new Dictionary<Endpoint, string> {
{ Endpoint.Api, "https://api.lvh.me:3000" },
{ Endpoint.Vault, "https://vault.lvh.me:4500" },
});
}
}
|
mit
|
C#
|
c575d66480eabec51f44ee4a6f8873b32578ad30
|
Fix case when project directory already exists
|
DamianEdwards/dotnet-new2
|
src/dotnet-new2/ProjectCreator.cs
|
src/dotnet-new2/ProjectCreator.cs
|
using System;
using System.Diagnostics;
using System.IO;
namespace dotnet_new2
{
public class ProjectCreator
{
public bool CreateProject(string name, string path, Template template)
{
Directory.CreateDirectory(path);
if (Directory.GetFileSystemEntries(path).Length > 0)
{
// Files already exist in the directory
Console.WriteLine($"Directory {path} already contains files. Please specify a different project name.");
return false;
}
foreach (var file in template.Files)
{
var dest = Path.Combine(path, file.DestPath);
File.Copy(file.SourcePath, dest);
ProcessFile(dest, name);
}
Console.WriteLine();
Console.WriteLine($"Created \"{name}\" in {path}");
Console.WriteLine();
return true;
}
private void ProcessFile(string destPath, string name)
{
// TODO: Make this good
var contents = File.ReadAllText(destPath);
File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name));
}
}
}
|
using System;
using System.Diagnostics;
using System.IO;
namespace dotnet_new2
{
public class ProjectCreator
{
public bool CreateProject(string name, string path, Template template)
{
Directory.CreateDirectory(path);
foreach (var file in template.Files)
{
var dest = Path.Combine(path, file.DestPath);
File.Copy(file.SourcePath, dest);
ProcessFile(dest, name);
}
Console.WriteLine();
Console.WriteLine($"Created \"{name}\" in {path}");
return true;
}
private void ProcessFile(string destPath, string name)
{
// TODO: Make this good
var contents = File.ReadAllText(destPath);
File.WriteAllText(destPath, contents.Replace("$DefaultNamespace$", name));
}
}
}
|
mit
|
C#
|
8c5aa48f28f87699bf78bbffdb57e0de077624a6
|
Set AssemblyConfiguration details
|
StevenLiekens/Txt,StevenLiekens/TextFx
|
SharedAssemblyInfo.cs
|
SharedAssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
// 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: AssemblyCompany("Steven Liekens")]
[assembly: AssemblyProduct("TextFx")]
[assembly: AssemblyCopyright("The MIT License (MIT)")]
[assembly: AssemblyTrademark("")]
[assembly: NeutralResourcesLanguage("en")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
# endif
// Version information for an assembly consists of the following four values:
// Major Version
// Minor Version
// Build Number
// Revision
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
|
using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Steven Liekens")]
[assembly: AssemblyProduct("TextFx")]
[assembly: AssemblyCopyright("The MIT License (MIT)")]
[assembly: AssemblyTrademark("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
// Major Version
// Minor Version
// Build Number
// Revision
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
|
mit
|
C#
|
b5bf329ff034c24c87ac99b5d91a53f3fda54017
|
Make Skeletal Anim optional on MM aswell (OR/AS)
|
gdkchan/SPICA
|
SPICA.WinForms/Formats/GFOWCharaModel.cs
|
SPICA.WinForms/Formats/GFOWCharaModel.cs
|
using SPICA.Formats.CtrH3D;
using SPICA.Formats.CtrH3D.Animation;
using SPICA.Formats.GFL;
using SPICA.Formats.GFL.Motion;
using System.IO;
namespace SPICA.WinForms.Formats
{
class GFOWCharaModel
{
public static H3D OpenAsH3D(Stream Input, GFPackage.Header Header)
{
H3D Output;
//Model
byte[] Buffer = new byte[Header.Entries[0].Length];
Input.Seek(Header.Entries[0].Address, SeekOrigin.Begin);
Input.Read(Buffer, 0, Buffer.Length);
using (MemoryStream MS = new MemoryStream(Buffer))
{
Output = H3D.Open(MS);
}
//Skeletal Animations
if (Header.Entries.Length > 1)
{
Input.Seek(Header.Entries[1].Address, SeekOrigin.Begin);
GFMotionPack MotPack = new GFMotionPack(Input);
foreach (GFMotion Mot in MotPack)
{
H3DAnimation SklAnim = Mot.ToH3DSkeletalAnimation();
SklAnim.Name = $"Motion_{Mot.Index}";
Output.SkeletalAnimations.Add(SklAnim);
}
}
//Material Animations
if (Header.Entries.Length > 2)
{
Input.Seek(Header.Entries[2].Address, SeekOrigin.Begin);
byte[] Data = new byte[Header.Entries[2].Length];
Input.Read(Data, 0, Data.Length);
H3D MatAnims = H3D.Open(Data);
Output.Merge(MatAnims);
}
return Output;
}
}
}
|
using SPICA.Formats.CtrH3D;
using SPICA.Formats.CtrH3D.Animation;
using SPICA.Formats.GFL;
using SPICA.Formats.GFL.Motion;
using System.IO;
namespace SPICA.WinForms.Formats
{
class GFOWCharaModel
{
public static H3D OpenAsH3D(Stream Input, GFPackage.Header Header)
{
H3D Output;
//Model
byte[] Buffer = new byte[Header.Entries[0].Length];
Input.Seek(Header.Entries[0].Address, SeekOrigin.Begin);
Input.Read(Buffer, 0, Buffer.Length);
using (MemoryStream MS = new MemoryStream(Buffer))
{
Output = H3D.Open(MS);
}
//Skeletal Animations
Input.Seek(Header.Entries[1].Address, SeekOrigin.Begin);
GFMotionPack MotPack = new GFMotionPack(Input);
foreach (GFMotion Mot in MotPack)
{
H3DAnimation SklAnim = Mot.ToH3DSkeletalAnimation();
SklAnim.Name = $"Motion_{Mot.Index}";
Output.SkeletalAnimations.Add(SklAnim);
}
//Material Animations
if (Header.Entries.Length > 2)
{
Input.Seek(Header.Entries[2].Address, SeekOrigin.Begin);
byte[] Data = new byte[Header.Entries[2].Length];
Input.Read(Data, 0, Data.Length);
H3D MatAnims = H3D.Open(Data);
Output.Merge(MatAnims);
}
return Output;
}
}
}
|
unlicense
|
C#
|
6783b1d841a2ca69a1e0517c270537e70ab081be
|
Use ManyString in WhitespaceString
|
benjamin-hodgson/Pidgin
|
Pidgin/Parser.Whitespace.cs
|
Pidgin/Parser.Whitespace.cs
|
using System.Collections.Generic;
using static Pidgin.Parser<char>;
namespace Pidgin
{
public static partial class Parser
{
/// <summary>
/// Gets a parser that parses and returns a single whitespace character
/// </summary>
/// <returns>A parser that parses and returns a single whitespace character</returns>
public static Parser<char, char> Whitespace { get; }
= Token(char.IsWhiteSpace).Labelled("whitespace");
/// <summary>
/// Gets a parser that parses and returns a sequence of whitespace characters
/// </summary>
/// <returns>A parser that parses and returns a sequence of whitespace characters</returns>
public static Parser<char, IEnumerable<char>> Whitespaces { get; }
= Whitespace.Many().Labelled("whitespace");
/// <summary>
/// Gets a parser that parses and returns a sequence of whitespace characters packed into a string
/// </summary>
/// <returns>A parser that parses and returns a sequence of whitespace characters packed into a string</returns>
public static Parser<char, string> WhitespaceString { get; }
= Whitespace.ManyString().Labelled("whitespace");
/// <summary>
/// Gets a parser that discards a sequence of whitespace characters
/// </summary>
/// <returns>A parser that discards a sequence of whitespace characters</returns>
public static Parser<char, Unit> SkipWhitespaces { get; }
= Whitespace.SkipMany().Labelled("whitespace");
}
}
|
using System.Collections.Generic;
using static Pidgin.Parser<char>;
namespace Pidgin
{
public static partial class Parser
{
/// <summary>
/// Gets a parser that parses and returns a single whitespace character
/// </summary>
/// <returns>A parser that parses and returns a single whitespace character</returns>
public static Parser<char, char> Whitespace { get; }
= Token(char.IsWhiteSpace).Labelled("whitespace");
/// <summary>
/// Gets a parser that parses and returns a sequence of whitespace characters
/// </summary>
/// <returns>A parser that parses and returns a sequence of whitespace characters</returns>
public static Parser<char, IEnumerable<char>> Whitespaces { get; }
= Whitespace.Many().Labelled("whitespace");
/// <summary>
/// Gets a parser that parses and returns a sequence of whitespace characters packed into a string
/// </summary>
/// <returns>A parser that parses and returns a sequence of whitespace characters packed into a string</returns>
public static Parser<char, string> WhitespaceString { get; }
= Whitespaces.Select(string.Concat).Labelled("whitespace");
/// <summary>
/// Gets a parser that discards a sequence of whitespace characters
/// </summary>
/// <returns>A parser that discards a sequence of whitespace characters</returns>
public static Parser<char, Unit> SkipWhitespaces { get; }
= Whitespace.SkipMany().Labelled("whitespace");
}
}
|
mit
|
C#
|
afa05f6700cf8b5a9a864eabec82d131d6272993
|
Change signature of Instruction#ctor
|
lury-lang/lury-ir
|
LuryIR/Compiling/IR/Instruction.cs
|
LuryIR/Compiling/IR/Instruction.cs
|
//
// Instruction.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace Lury.Compiling.IR
{
public class Instruction
{
#region -- Public Properties --
public string Destination { get; private set; }
public Operation Operation { get; private set; }
public IReadOnlyList<Parameter> Parameters { get; private set; }
#endregion
#region -- Constructors --
public Instruction(string destination, Operation operation, params Parameter[] parameters)
{
if (!Enum.IsDefined(typeof(Operation), operation))
throw new ArgumentOutOfRangeException("operation");
this.Destination = destination;
this.Operation = operation;
this.Parameters = parameters ?? new Parameter[0];
}
public Instruction(string destination, Operation operation)
: this(destination, operation, null)
{
}
public Instruction(Operation operation, params Parameter[] parameters)
: this(null, operation, parameters)
{
}
public Instruction(Operation operation)
: this(null, operation, null)
{
}
#endregion
}
}
|
//
// Instruction.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
namespace Lury.Compiling.IR
{
public class Instruction
{
#region -- Public Properties --
public string Destination { get; private set; }
public Operation Operation { get; private set; }
public IReadOnlyList<Parameter> Parameters { get; private set; }
#endregion
#region -- Constructors --
public Instruction(string destination, Operation operation, IReadOnlyList<Parameter> parameters)
{
if (!Enum.IsDefined(typeof(Operation), operation))
throw new ArgumentOutOfRangeException("operation");
this.Destination = destination;
this.Operation = operation;
this.Parameters = parameters ?? new Parameter[0];
}
public Instruction(string destination, Operation operation)
: this(destination, operation, null)
{
}
public Instruction(Operation operation, IReadOnlyList<Parameter> parameters)
: this(null, operation, parameters)
{
}
public Instruction(Operation operation)
: this(null, operation, null)
{
}
#endregion
}
}
|
mit
|
C#
|
1d2441b1ba501afd8526476477a6f0dedb567a6d
|
add edit.enable
|
2sic/app-mobius-forms,2sic/app-mobius-forms,2sic/app-mobius-forms,2sic/app-mobius-forms
|
staging/shared/_Assets.cshtml
|
staging/shared/_Assets.cshtml
|
@{
string Edition = PageData["Edition"];
}
@Edit.Enable(api: true)
<script src="@App.Path/node_modules/smokejs/dist/js/smoke.min.js" data-enableoptimizations="100"></script>
<script src="@App.Path/@Edition/dist/app-bundle.min.js" data-enableoptimizations="true"></script>
<link rel="stylesheet" type="text/css" href="@App.Path/@Edition/dist/style.min.css" data-enableoptimizations="true">
<script>
// initialize the javascripts which will collect the data and send it to the server on send
mobius = new mobiusforms.App(@Dnn.Module.ModuleID);
mobius.initialize();
</script>
|
@{
string Edition = PageData["Edition"];
}
@* todo: use @Edit.Enable(...) *@
<script type="text/javascript" src="/desktopmodules/tosic_sexycontent/js/2sxc.api.min.js" data-enableoptimizations="100" ></script>
<script src="@App.Path/node_modules/smokejs/dist/js/smoke.min.js" data-enableoptimizations="100"></script>
<script src="@App.Path/@Edition/dist/app-bundle.min.js" data-enableoptimizations="true"></script>
<link rel="stylesheet" type="text/css" href="@App.Path/@Edition/dist/style.min.css" data-enableoptimizations="true">
<script>
// initialize the javascripts which will collect the data and send it to the server on send
mobius = new mobiusforms.App(@Dnn.Module.ModuleID);
mobius.initialize();
</script>
|
mit
|
C#
|
3cd6e55e2af8cfdd2b415dffe8dff444872bfee5
|
Throw all dispatcher exceptions on the non-service build.
|
VoiDeD/steam-irc-bot
|
SteamIrcBot/Service/ServiceDispatcher.cs
|
SteamIrcBot/Service/ServiceDispatcher.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SteamIrcBot
{
class ServiceDispatcher
{
static ServiceDispatcher _instance = new ServiceDispatcher();
public static ServiceDispatcher Instance { get { return _instance; } }
Task dispatcher;
CancellationTokenSource cancelToken;
ServiceDispatcher()
{
cancelToken = new CancellationTokenSource();
dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning );
}
void ServiceTick()
{
while ( true )
{
if ( cancelToken.IsCancellationRequested )
break;
Steam.Instance.Tick();
IRC.Instance.Tick();
RSS.Instance.Tick();
}
}
public void Start()
{
dispatcher.Start();
}
public void Stop()
{
cancelToken.Cancel();
}
public void Wait()
{
dispatcher.Wait();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace SteamIrcBot
{
class ServiceDispatcher
{
static ServiceDispatcher _instance = new ServiceDispatcher();
public static ServiceDispatcher Instance { get { return _instance; } }
Task dispatcher;
CancellationTokenSource cancelToken;
ServiceDispatcher()
{
cancelToken = new CancellationTokenSource();
dispatcher = new Task( ServiceTick, cancelToken.Token, TaskCreationOptions.LongRunning );
}
void ServiceTick()
{
while ( true )
{
if ( cancelToken.IsCancellationRequested )
break;
Steam.Instance.Tick();
IRC.Instance.Tick();
RSS.Instance.Tick();
}
}
public void Start()
{
dispatcher.Start();
}
public void Stop()
{
cancelToken.Cancel();
}
public void Wait()
{
try
{
dispatcher.Wait();
}
catch ( AggregateException )
{
// we'll ignore any cancelled/failed tasks
}
}
}
}
|
mit
|
C#
|
b252a9106bebe19a7ae7b85654c46ac5aa44f750
|
Fix the XML docs generic class references
|
bartsokol/Monacs
|
Monacs.Core/Unit/Result.Unit.Extensions.cs
|
Monacs.Core/Unit/Result.Unit.Extensions.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Monacs.Core.Unit
{
///<summary>
/// Extensions for <see cref="Result{Unit}" /> type.
///</summary>
public static class Result
{
///<summary>
/// Creates successful <see cref="Result{Unit}" />.
///</summary>
public static Result<Unit> Ok() =>
Core.Result.Ok(Unit.Default);
///<summary>
/// Creates failed <see cref="Result{Unit}" /> with provided error details.
///</summary>
public static Result<Unit> Error(ErrorDetails error) =>
Core.Result.Error<Unit>(error);
///<summary>
/// Rejects the value of the <see cref="Result{T}" /> and returns <see cref="Result{Unit}" /> instead.
/// If the input <see cref="Result{T}" /> is Error then the error details are preserved.
///</summary>
public static Result<Unit> Ignore<T>(this Result<T> result) =>
result.Map(_ => Unit.Default);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Monacs.Core.Unit
{
///<summary>
/// Extensions for <see cref="Result<Unit>" /> type.
///</summary>
public static class Result
{
///<summary>
/// Creates successful <see cref="Result<Unit>" />.
///</summary>
public static Result<Unit> Ok() =>
Core.Result.Ok(Unit.Default);
///<summary>
/// Creates failed <see cref="Result<Unit>" /> with provided error details.
///</summary>
public static Result<Unit> Error(ErrorDetails error) =>
Core.Result.Error<Unit>(error);
///<summary>
/// Rejects the value of the <see cref="Result<T>" /> and returns <see cref="Result<Unit>" /> instead.
/// If the input <see cref="Result<T>" /> is Error then the error details are preserved.
///</summary>
public static Result<Unit> Ignore<T>(this Result<T> result) =>
result.Map(_ => Unit.Default);
}
}
|
mit
|
C#
|
7d24a07fc8015d75609a20c0dfe1365c971ade5f
|
add remove duplicates extension method
|
IUMDPI/IUMediaHelperApps
|
Packager/Extensions/FileModelExtensions.cs
|
Packager/Extensions/FileModelExtensions.cs
|
using System.Collections.Generic;
using System.Linq;
using Packager.Models.FileModels;
namespace Packager.Extensions
{
public static class FileModelExtensions
{
public static bool IsObjectModel(this AbstractFileModel fileModel)
{
return fileModel is ObjectFileModel;
}
public static bool IsXmlModel(this AbstractFileModel fileModel)
{
return fileModel is XmlFileModel;
}
public static bool IsUnknownModel(this AbstractFileModel fileModel)
{
return fileModel is UnknownFileModel;
}
public static ObjectFileModel GetPreservationOrIntermediateModel<T>(this IGrouping<T, ObjectFileModel> grouping)
{
var preservationIntermediate = grouping.SingleOrDefault(m => m.IsPreservationIntermediateVersion());
return preservationIntermediate ?? grouping.SingleOrDefault(m => m.IsPreservationVersion());
}
public static ObjectFileModel GetPreservationOrIntermediateModel(this IEnumerable<ObjectFileModel> models)
{
var list = models.ToList();
var preservationIntermediate = list.FirstOrDefault(m => m.IsPreservationIntermediateVersion());
return preservationIntermediate ?? list.FirstOrDefault(m => m.IsPreservationVersion());
}
public static List<ObjectFileModel> RemoveDuplicates(this List<ObjectFileModel> models)
{
return models.GroupBy(o => o.ToFileName())
.Select(g => g.First()).ToList();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Packager.Models.FileModels;
namespace Packager.Extensions
{
public static class FileModelExtensions
{
public static bool IsObjectModel(this AbstractFileModel fileModel)
{
return fileModel is ObjectFileModel;
}
public static bool IsXmlModel(this AbstractFileModel fileModel)
{
return fileModel is XmlFileModel;
}
public static bool IsUnknownModel(this AbstractFileModel fileModel)
{
return fileModel is UnknownFileModel;
}
public static ObjectFileModel GetPreservationOrIntermediateModel<T>(this IGrouping<T, ObjectFileModel> grouping)
{
var preservationIntermediate = grouping.SingleOrDefault(m => m.IsPreservationIntermediateVersion());
return preservationIntermediate ?? grouping.SingleOrDefault(m => m.IsPreservationVersion());
}
public static ObjectFileModel GetPreservationOrIntermediateModel(this IEnumerable<ObjectFileModel> models)
{
var list = models.ToList();
var preservationIntermediate = list.FirstOrDefault(m => m.IsPreservationIntermediateVersion());
return preservationIntermediate ?? list.FirstOrDefault(m => m.IsPreservationVersion());
}
}
}
|
apache-2.0
|
C#
|
7512746e1b377df44d097a88a6fa31ed3e27341c
|
add meta property
|
Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore
|
src/JsonApiDotNetCore/Models/DocumentBase.cs
|
src/JsonApiDotNetCore/Models/DocumentBase.cs
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JsonApiDotNetCore.Models
{
public class DocumentBase
{
[JsonProperty("included")]
public List<DocumentData> Included { get; set; }
public Dictionary<string, object> Meta { get; set; }
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
namespace JsonApiDotNetCore.Models
{
public class DocumentBase
{
[JsonProperty("included")]
public List<DocumentData> Included { get; set; }
}
}
|
mit
|
C#
|
f801aae82f70c1852356e145f851dcfef15e1b37
|
Support byte[] parameter values.
|
mysql-net/MySqlConnector,gitsno/MySqlConnector,gitsno/MySqlConnector,mysql-net/MySqlConnector
|
src/MySql.Data/MySqlClient/MySqlParameter.cs
|
src/MySql.Data/MySqlClient/MySqlParameter.cs
|
using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Text;
using static System.FormattableString;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlParameter : DbParameter
{
public override DbType DbType { get; set; }
public override ParameterDirection Direction { get; set; }
public override bool IsNullable { get; set; }
public override string ParameterName { get; set; }
public override int Size { get; set; }
public override string SourceColumn
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override bool SourceColumnNullMapping
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#if !DNXCORE50
public override DataRowVersion SourceVersion
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#endif
public override object Value { get; set; }
public override void ResetDbType()
{
DbType = default(DbType);
}
internal bool ParameterNameMatches(string name)
{
if (string.IsNullOrEmpty(ParameterName) || string.IsNullOrEmpty(name))
return false;
int thisNameIndex = 0, thisNameLength = ParameterName.Length;
if (ParameterName[0] == '?' || ParameterName[0] == '@')
{
thisNameIndex++;
thisNameLength--;
}
int otherNameIndex = 0, otherNameLength = name.Length;
if (name[0] == '?' || name[0] == '@')
{
otherNameIndex++;
otherNameLength--;
}
return thisNameLength == otherNameLength &&
string.Compare(ParameterName, thisNameIndex, name, otherNameIndex, thisNameLength, StringComparison.OrdinalIgnoreCase) == 0;
}
internal void AppendSqlString(StringBuilder output)
{
if (Value == DBNull.Value)
{
output.Append("NULL");
}
else if (Value is string)
{
output.Append('\'');
output.Append(((string) Value).Replace("\\", "\\\\").Replace("'", "\\'"));
output.Append('\'');
}
else if (Value is short || Value is int || Value is long || Value is ushort || Value is uint || Value is ulong)
{
output.AppendFormat(CultureInfo.InvariantCulture, "{0}", Value);
}
else if (Value is byte[])
{
// TODO: use a _binary'...' string for more efficient data transmission
output.Append("X'");
foreach (var by in (byte[]) Value)
output.AppendFormat(CultureInfo.InvariantCulture, "{0:X2}", by);
output.Append("'");
}
else
{
throw new NotSupportedException(Invariant($"Parameter type {Value.GetType().Name} (DbType: {DbType}) not currently supported. Value: {Value}"));
}
}
}
}
|
using System;
using System.Data;
using System.Data.Common;
using System.Globalization;
using System.Text;
using static System.FormattableString;
namespace MySql.Data.MySqlClient
{
public sealed class MySqlParameter : DbParameter
{
public override DbType DbType { get; set; }
public override ParameterDirection Direction { get; set; }
public override bool IsNullable { get; set; }
public override string ParameterName { get; set; }
public override int Size { get; set; }
public override string SourceColumn
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
public override bool SourceColumnNullMapping
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#if !DNXCORE50
public override DataRowVersion SourceVersion
{
get { throw new NotSupportedException(); }
set { throw new NotSupportedException(); }
}
#endif
public override object Value { get; set; }
public override void ResetDbType()
{
DbType = default(DbType);
}
internal bool ParameterNameMatches(string name)
{
if (string.IsNullOrEmpty(ParameterName) || string.IsNullOrEmpty(name))
return false;
int thisNameIndex = 0, thisNameLength = ParameterName.Length;
if (ParameterName[0] == '?' || ParameterName[0] == '@')
{
thisNameIndex++;
thisNameLength--;
}
int otherNameIndex = 0, otherNameLength = name.Length;
if (name[0] == '?' || name[0] == '@')
{
otherNameIndex++;
otherNameLength--;
}
return thisNameLength == otherNameLength &&
string.Compare(ParameterName, thisNameIndex, name, otherNameIndex, thisNameLength, StringComparison.OrdinalIgnoreCase) == 0;
}
internal void AppendSqlString(StringBuilder output)
{
if (Value == DBNull.Value)
{
output.Append("NULL");
}
else if (Value is string)
{
output.Append('\'');
output.Append(((string) Value).Replace("\\", "\\\\").Replace("'", "\\'"));
output.Append('\'');
}
else if (Value is short || Value is int || Value is long || Value is ushort || Value is uint || Value is ulong)
{
output.AppendFormat(CultureInfo.InvariantCulture, "{0}", Value);
}
else
{
throw new NotSupportedException(Invariant($"Parameter type {Value.GetType().Name} (DbType: {DbType}) not currently supported. Value: {Value}"));
}
}
}
}
|
mit
|
C#
|
1e97f935c48cb55e9889dc039e002b2635fb47ec
|
Set assembly culture to neutral
|
eallegretta/providermodel
|
src/ProviderModel/Properties/AssemblyInfo.cs
|
src/ProviderModel/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ProviderModel")]
[assembly: AssemblyDescription("An improvment over the bundled .NET provider model")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Enrique Alejandro Allegretta")]
[assembly: AssemblyProduct("ProviderModel")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")]
[assembly: AssemblyVersion("1.0.1")]
[assembly: AssemblyFileVersion("1.0.1")]
[assembly: AssemblyInformationalVersion("1.0.1")]
|
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("ProviderModel")]
[assembly: AssemblyDescription("An improvment over the bundled .NET provider model")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Enrique Alejandro Allegretta")]
[assembly: AssemblyProduct("ProviderModel")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("en-US")]
[assembly: ComVisible(false)]
[assembly: Guid("9d02304c-cda1-4d3b-afbc-725731a794b5")]
[assembly: AssemblyVersion("1.0.0")]
[assembly: AssemblyFileVersion("1.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
|
mit
|
C#
|
3068b422f74444331af9cdb224f22cd1e588e9c3
|
Remove MessageBroadcast event IMessagingChannel.
|
dingjimmy/primer
|
Primer/IMessagingChannel.cs
|
Primer/IMessagingChannel.cs
|
// Copyright (c) James Dingle
namespace Primer
{
using System;
using System.Linq;
/// <summary>
///
/// </summary>
public interface IMessagingChannel
{
/// <summary>
/// Broadcasts a message to anyone who is listening to the channel.
/// </summary>
/// <param name="message">The message to broadcast.</param>
void Broadcast(IMessage message);
/// <summary>
/// Listens to the channel for a particular message type and executes the provided delegate.
/// </summary>
/// <typeparam name="T">The type of message to listen out for.</typeparam>
/// <param name="messageHandler">The delegate to invoke when a message of the desired type is broadcast.</param>
void Listen<T>(Action<T> messageHandler) where T : IMessage;
/// <summary>
/// Listens to the channel for a particular message type and executes the provided delegate.
/// </summary>
/// <typeparam name="T">The type of message to listen out for.</typeparam>
/// <param name="messageHandler">The delegate to invoke when a message of the desired type is broadcast.</param>
/// <param name="criteria">An expression that provides additional criteria to control when the messageHander is to be executed.</param>
void Listen<T>(Func<T, bool> criteria, Action<T> messageHandler) where T : IMessage;
/// <summary>
/// Listens to the channel for a particular message type and provides options for when and how to execute a delegate.
/// </summary>
/// <typeparam name="T">The type of message to listen out for.</typeparam>
IMessageHandlerBuilder<T> Listen<T>();
/// <summary>
/// Stops listening to the channel for a particular message type. Removes all message handler delegates for the specified type, so that when a message of that type is broadcast nothing will happen.
/// </summary>
/// <typeparam name="T">The type of message to ingore.</typeparam>
void Ignore<T>() where T : IMessage;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IMessageHandlerBuilder<T>
{
IMessageHandlerBuilder<T> AndInvoke(Action<T> messageHandler);
void When(Func<T,bool> condition);
void Always();
}
}
|
// Copyright (c) James Dingle
namespace Primer
{
using System;
using System.Linq;
/// <summary>
///
/// </summary>
public interface IMessagingChannel
{
/// <summary>
/// Occurs when a message has been broadcast on this channel.
/// </summary>
event Action<IMessage> MessageBroadcast;
/// <summary>
/// Broadcasts a message to anyone who is listening to the channel.
/// </summary>
/// <param name="message">The message to broadcast.</param>
void Broadcast(IMessage message);
/// <summary>
/// Listens to the channel for a particular message type and executes the provided delegate.
/// </summary>
/// <typeparam name="T">The type of message to listen out for.</typeparam>
/// <param name="messageHandler">The delegate to invoke when a message of the desired type is broadcast.</param>
void Listen<T>(Action<T> messageHandler) where T : IMessage;
/// <summary>
/// Listens to the channel for a particular message type and executes the provided delegate.
/// </summary>
/// <typeparam name="T">The type of message to listen out for.</typeparam>
/// <param name="messageHandler">The delegate to invoke when a message of the desired type is broadcast.</param>
/// <param name="criteria">An expression that provides additional criteria to control when the messageHander is to be executed.</param>
void Listen<T>(Func<T, bool> criteria, Action<T> messageHandler) where T : IMessage;
/// <summary>
/// Listens to the channel for a particular message type and provides options for when and how to execute a delegate.
/// </summary>
/// <typeparam name="T">The type of message to listen out for.</typeparam>
IMessageHandlerBuilder<T> Listen<T>();
/// <summary>
/// Stops listening to the channel for a particular message type. Removes all message handler delegates for the specified type, so that when a message of that type is broadcast nothing will happen.
/// </summary>
/// <typeparam name="T">The type of message to ingore.</typeparam>
void Ignore<T>() where T : IMessage;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IMessageHandlerBuilder<T>
{
IMessageHandlerBuilder<T> AndInvoke(Action<T> messageHandler);
void When(Func<T,bool> condition);
void Always();
}
}
|
mit
|
C#
|
cd063e1137890d52fd1648d87f4544ba306753ca
|
add extension methods
|
Weingartner/SolidworksAddinFramework
|
SolidworksAddinFramework/MathVectorExtensions.cs
|
SolidworksAddinFramework/MathVectorExtensions.cs
|
using System;
using System.Linq;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework
{
public static class MathVectorExtensions
{
/// <summary>
/// gives the multiplier for b which would be the projection of a on b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double Project(this IMathVector a, IMathVector b)
{
return a.Dot(b)/(b.Dot(b));
}
public static double[] Cross(this IMathUtility math, double[] a, double[] b)
{
var v0 = (IMathVector) math.CreateVector(a);
var v1 = (IMathVector) math.CreateVector(b);
return (double[]) ((IMathVector)v0.Cross(v1)).ArrayData;
}
public static MathVector ScaleTs(this IMathVector a, double b)
{
return (MathVector) a.Scale(b);
}
public static MathVector CrossTs(this IMathVector a, IMathVector b)
{
return (MathVector) a.Cross(b);
}
public static MathVector MultiplyTransformTs(this IMathVector v, IMathTransform t)
{
return (MathVector) v.MultiplyTransform(t);
}
public static double LengthOfProjectionXY(this double[] vector)
{
return Math.Sqrt(vector.Take(2).Sum(c => Math.Pow(c, 2)));
}
public static double AngleBetweenVectorsSigned(this IMathVector v0, IMathVector v1)
{
if (((double[])v0.ArrayData).Length==((double[])v1.ArrayData).Length)
{
var sign = Math.Sign(((IMathVector) (v0.Cross(v1))).ArrayData.CastArray<double>()[2]);
var ret = Math.Acos(v0.Dot(v1)/(v0.GetLength()*v1.GetLength()));
return sign*ret;
}
throw new Exception("Vectors must have the same dimension!");
}
}
}
|
using System;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework
{
public static class MathVectorExtensions
{
/// <summary>
/// gives the multiplier for b which would be the projection of a on b
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <returns></returns>
public static double Project(this IMathVector a, IMathVector b)
{
return a.Dot(b)/(b.Dot(b));
}
public static double[] Cross(this IMathUtility math, double[] a, double[] b)
{
var v0 = (IMathVector) math.CreateVector(a);
var v1 = (IMathVector) math.CreateVector(b);
return (double[]) ((IMathVector)v0.Cross(v1)).ArrayData;
}
public static MathVector ScaleTs(this IMathVector a, double b)
{
return (MathVector) a.Scale(b);
}
public static MathVector CrossTs(this IMathVector a, IMathVector b)
{
return (MathVector) a.Cross(b);
}
public static MathVector MultiplyTransformTs(this IMathVector v, IMathTransform t)
{
return (MathVector) v.MultiplyTransform(t);
}
public static double AngleBetweenVectors(this IMathVector v0, IMathVector v1)
{
if (((double[])v0.ArrayData).Length==((double[])v1.ArrayData).Length)
{
return Math.Acos(v0.Dot(v1)/(v0.GetLength()*v1.GetLength()));
}
throw new Exception("Vectors must have the same dimension!");
}
}
}
|
mit
|
C#
|
35c8bf564e03f1f8cfa76cc5ae6413040364ab5c
|
Add Script as a shortcut type
|
intentor/shortcuter
|
src/Assets/Plugins/Editor/Shortcuter/Util/TypeUtils.cs
|
src/Assets/Plugins/Editor/Shortcuter/Util/TypeUtils.cs
|
using UnityEngine;
using UnityEditor.Animations;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Intentor.Shortcuter.Util {
/// <summary>
/// Utility class for types.
/// </summary>
public static class TypeUtils {
/// <summary>
/// Gets all available shortcut types.
/// </summary>
/// <returns>The shortcut types.</returns>
public static Dictionary<string, System.Type> GetShortcutTypes() {
var types = new Dictionary<string, System.Type>();
types.Add("Scene", null);
types.Add("Prefab", typeof(UnityEngine.Object));
types.Add("Script", typeof(UnityEngine.Object));
types.Add("AnimatorController", typeof(AnimatorController));
types.Add("Animation", typeof(Animation));
types.Add("Material", typeof(Material));
var scriptableObjects = GetTypesDerivedOf(typeof(ScriptableObject));
for (var index = 0; index < scriptableObjects.Length; index++) {
var type = scriptableObjects[index];
types.Add(type.FullName, type);
}
return types;
}
/// <summary>
/// Gets a shortcut type from a type name.
/// </summary>
/// <param name="typeName">Type name.</param>
public static Type GetShortcutType(string typeName) {
var shortcutTypes = GetShortcutTypes();
return shortcutTypes[typeName];
}
/// <summary>
/// Gets all available types derived of a given type.
/// </summary>
/// <remarks>>
/// All types from Unity are not considered on the search.
/// </remarks>
/// <param name="baseType">Base type.</param>
/// <returns>The types derived of.</returns>
public static Type[] GetTypesDerivedOf(Type baseType) {
var types = new List<Type>();
//Looks for assignable types in all available assemblies.
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int assemblyIndex = 0; assemblyIndex < assemblies.Length; assemblyIndex++) {
var assembly = assemblies[assemblyIndex];
if (assembly.FullName.StartsWith("Unity") ||
assembly.FullName.StartsWith("Boo") ||
assembly.FullName.StartsWith("Mono") ||
assembly.FullName.StartsWith("System") ||
assembly.FullName.StartsWith("mscorlib")) {
continue;
}
try {
var allTypes = assemblies[assemblyIndex].GetTypes();
for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) {
var type = allTypes[typeIndex];
if (type.IsSubclassOf(baseType)) {
types.Add(type);
}
}
} catch (ReflectionTypeLoadException) {
//If the assembly can't be read, just continue.
continue;
}
}
return types.ToArray();
}
}
}
|
using UnityEngine;
using UnityEditor.Animations;
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Intentor.Shortcuter.Util {
/// <summary>
/// Utility class for types.
/// </summary>
public static class TypeUtils {
/// <summary>
/// Gets all available shortcut types.
/// </summary>
/// <returns>The shortcut types.</returns>
public static Dictionary<string, System.Type> GetShortcutTypes() {
var types = new Dictionary<string, System.Type>();
types.Add("Scene", null);
types.Add("Prefab", typeof(UnityEngine.Object));
types.Add("AnimatorController", typeof(AnimatorController));
types.Add("Animation", typeof(Animation));
types.Add("Material", typeof(Material));
var scriptableObjects = GetTypesDerivedOf(typeof(ScriptableObject));
for (var index = 0; index < scriptableObjects.Length; index++) {
var type = scriptableObjects[index];
types.Add(type.FullName, type);
}
return types;
}
/// <summary>
/// Gets a shortcut type from a type name.
/// </summary>
/// <param name="typeName">Type name.</param>
public static Type GetShortcutType(string typeName) {
var shortcutTypes = GetShortcutTypes();
return shortcutTypes[typeName];
}
/// <summary>
/// Gets all available types derived of a given type.
/// </summary>
/// <remarks>>
/// All types from Unity are not considered on the search.
/// </remarks>
/// <param name="baseType">Base type.</param>
/// <returns>The types derived of.</returns>
public static Type[] GetTypesDerivedOf(Type baseType) {
var types = new List<Type>();
//Looks for assignable types in all available assemblies.
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
for (int assemblyIndex = 0; assemblyIndex < assemblies.Length; assemblyIndex++) {
var assembly = assemblies[assemblyIndex];
if (assembly.FullName.StartsWith("Unity") ||
assembly.FullName.StartsWith("Boo") ||
assembly.FullName.StartsWith("Mono") ||
assembly.FullName.StartsWith("System") ||
assembly.FullName.StartsWith("mscorlib")) {
continue;
}
try {
var allTypes = assemblies[assemblyIndex].GetTypes();
for (int typeIndex = 0; typeIndex < allTypes.Length; typeIndex++) {
var type = allTypes[typeIndex];
if (type.IsSubclassOf(baseType)) {
types.Add(type);
}
}
} catch (ReflectionTypeLoadException) {
//If the assembly can't be read, just continue.
continue;
}
}
return types.ToArray();
}
}
}
|
mit
|
C#
|
b30d4317e66d4177c2589f0ad6928026e449ba78
|
use LoadFrom instead of LoadFile
|
OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn
|
src/OmniSharp.Abstractions/Services/IAssemblyLoader.cs
|
src/OmniSharp.Abstractions/Services/IAssemblyLoader.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace OmniSharp.Services
{
public interface IAssemblyLoader
{
Assembly Load(AssemblyName name);
IReadOnlyList<Assembly> LoadAllFrom(string folderPath);
Assembly LoadFrom(string assemblyPath);
}
public static class IAssemblyLoaderExtensions
{
public static Lazy<Assembly> LazyLoad(this IAssemblyLoader loader, string assemblyName)
{
return new Lazy<Assembly>(() => loader.Load(assemblyName));
}
public static Assembly Load(this IAssemblyLoader loader, string name)
{
var assemblyName = name;
if (name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
assemblyName = name.Substring(0, name.Length - 4);
}
return loader.Load(new AssemblyName(assemblyName));
}
public static IEnumerable<Assembly> Load(this IAssemblyLoader loader, params string[] assemblyNames)
{
foreach (var name in assemblyNames)
{
yield return Load(loader, name);
}
}
public static Assembly LoadByAssemblyNameOrPath(string assemblyName)
{
if (File.Exists(assemblyName))
{
return Assembly.LoadFrom(assemblyName);
}
else
{
return Assembly.Load(assemblyName);
}
}
public static IEnumerable<Assembly> LoadByAssemblyNameOrPath(this IAssemblyLoader loader, IEnumerable<string> assemblyNames)
{
foreach (var assemblyName in assemblyNames)
{
yield return LoadByAssemblyNameOrPath(assemblyName);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace OmniSharp.Services
{
public interface IAssemblyLoader
{
Assembly Load(AssemblyName name);
IReadOnlyList<Assembly> LoadAllFrom(string folderPath);
Assembly LoadFrom(string assemblyPath);
}
public static class IAssemblyLoaderExtensions
{
public static Lazy<Assembly> LazyLoad(this IAssemblyLoader loader, string assemblyName)
{
return new Lazy<Assembly>(() => loader.Load(assemblyName));
}
public static Assembly Load(this IAssemblyLoader loader, string name)
{
var assemblyName = name;
if (name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
{
assemblyName = name.Substring(0, name.Length - 4);
}
return loader.Load(new AssemblyName(assemblyName));
}
public static IEnumerable<Assembly> Load(this IAssemblyLoader loader, params string[] assemblyNames)
{
foreach (var name in assemblyNames)
{
yield return Load(loader, name);
}
}
public static Assembly LoadByAssemblyNameOrPath(string assemblyName)
{
if (File.Exists(assemblyName))
{
return Assembly.LoadFile(assemblyName);
}
else
{
return Assembly.Load(assemblyName);
}
}
public static IEnumerable<Assembly> LoadByAssemblyNameOrPath(this IAssemblyLoader loader, IEnumerable<string> assemblyNames)
{
foreach (var assemblyName in assemblyNames)
{
yield return LoadByAssemblyNameOrPath(assemblyName);
}
}
}
}
|
mit
|
C#
|
73197d9628abc5edd86b6f475d4471ef9c2995eb
|
Fix Triangulator test
|
feliwir/openSage,feliwir/openSage
|
src/OpenSage.Game.Tests/Utilities/TriangulatorTests.cs
|
src/OpenSage.Game.Tests/Utilities/TriangulatorTests.cs
|
using System.Numerics;
using OpenSage.Utilities;
using Xunit;
namespace OpenSage.Tests.Utilities
{
public class TriangulatorTests
{
[Fact]
public void CanTriangulatePolygon()
{
var polygonPoints = new[]
{
new Vector2(-22, 577),
new Vector2(-20, -694),
new Vector2(1513, -696),
new Vector2(1536, 968)
};
Triangulator.Triangulate(
polygonPoints,
WindingOrder.CounterClockwise,
out var trianglePoints,
out var triangleIndices);
Assert.Equal(4, trianglePoints.Length);
Assert.Equal(new Vector2(-22, 577), trianglePoints[0]);
Assert.Equal(new Vector2(-20, -694), trianglePoints[1]);
Assert.Equal(new Vector2(1513, -696), trianglePoints[2]);
Assert.Equal(new Vector2(1536, 968), trianglePoints[3]);
Assert.Equal(6, triangleIndices.Length);
Assert.Equal(0, triangleIndices[0]);
Assert.Equal(1, triangleIndices[1]);
Assert.Equal(3, triangleIndices[2]);
Assert.Equal(1, triangleIndices[3]);
Assert.Equal(2, triangleIndices[4]);
Assert.Equal(3, triangleIndices[5]);
}
}
}
|
using System.Numerics;
using OpenSage.Utilities;
using Xunit;
namespace OpenSage.Tests.Utilities
{
public class TriangulatorTests
{
[Fact]
public void CanTriangulatePolygon()
{
var polygonPoints = new[]
{
new Vector2(-22, 577),
new Vector2(-20, -694),
new Vector2(1513, -696),
new Vector2(1536, 968)
};
Assert.True(Triangulator.Process(polygonPoints, out var trianglePoints));
Assert.Equal(6, trianglePoints.Count);
Assert.Equal(new Vector2(1536, 968), trianglePoints[0]);
Assert.Equal(new Vector2(-22, 577), trianglePoints[1]);
Assert.Equal(new Vector2(-20, -694), trianglePoints[2]);
Assert.Equal(new Vector2(-20, -694), trianglePoints[3]);
Assert.Equal(new Vector2(1513, -696), trianglePoints[4]);
Assert.Equal(new Vector2(1536, 968), trianglePoints[5]);
}
}
}
|
mit
|
C#
|
1dfa35eed46d8dae6d67971143db639cd30bd830
|
Add quadratic solver to MathUtility
|
SaberSnail/GoldenAnvil.Utility
|
GoldenAnvil.Utility/MathUtility.cs
|
GoldenAnvil.Utility/MathUtility.cs
|
using System;
using System.Collections.Generic;
namespace GoldenAnvil.Utility
{
public static class MathUtility
{
public const double Sin30 = 0.5;
public const double Sin60 = 0.8660254038;
public const double Cos30 = 0.8660254038;
public const double Cos60 = 0.5;
public static double DegreesToRadians(double degrees) => degrees * Math.PI / 180.0;
public static double Clamp(double value, double min, double max) => Math.Max(Math.Min(value, max), min);
public static IReadOnlyList<double> SolveQuadratic(double a, double b, double c)
{
var values = new List<double>();
var discriminant = (b * b) - (4 * a * c);
if (discriminant == 0.0)
{
values.Add(-b / (2 * a));
}
else if (discriminant > 0)
{
var sqrtOfDiscriminant = Math.Sqrt(discriminant);
values.Add((-b + sqrtOfDiscriminant) / (2 * a));
values.Add((-b - sqrtOfDiscriminant) / (2 * a));
}
return values;
}
}
}
|
using System;
namespace GoldenAnvil.Utility
{
public static class MathUtility
{
public const double Sin30 = 0.5;
public const double Sin60 = 0.8660254038;
public const double Cos30 = 0.8660254038;
public const double Cos60 = 0.5;
public static double DegreesToRadians(double degrees) => degrees * Math.PI / 180.0;
public static double Clamp(double value, double min, double max) => Math.Max(Math.Min(value, max), min);
}
}
|
mit
|
C#
|
5692708809ff1bb6068b26dd3d9f59c360f53d98
|
remove dispose call
|
gigya/microdot
|
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs
|
tests/Gigya.Microdot.Orleans.Hosting.UnitTests/Microservice/WarmupTestService/WarmupTestServiceHostWithSiloHostFake.cs
|
using System.Threading;
using System.Threading.Tasks;
using Gigya.Microdot.Fakes;
using Gigya.Microdot.Hosting.HttpService;
using Gigya.Microdot.Hosting.Validators;
using Gigya.Microdot.Interfaces;
using Gigya.Microdot.Interfaces.Logging;
using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService;
using Gigya.Microdot.SharedLogic;
using Ninject;
using NSubstitute;
namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService
{
public class WarmupTestServiceHostWithSiloHostFake : CalculatorServiceHost
{
private IDependantClassFake _dependantClassFake = Substitute.For<IDependantClassFake>();
private TaskCompletionSource<bool> _hostDisposedEvent = new TaskCompletionSource<bool>();
protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig)
{
kernel.Rebind<ServiceValidator>().To<MockServiceValidator>().InSingletonScope();
kernel.Rebind<IMetricsInitializer>().To<MetricsInitializerFake>();
kernel.Rebind<GigyaSiloHost>().To<GigyaSiloHostFake>();
kernel.Rebind<IDependantClassFake>().ToConstant(_dependantClassFake);
kernel.Rebind<ILog>().To<NullLog>();
kernel.Rebind<IServiceInterfaceMapper>().To<OrleansServiceInterfaceMapper>();
kernel.Rebind<IAssemblyProvider>().To<AssemblyProvider>();
ServiceArguments args = new ServiceArguments(basePortOverride:9555);
kernel.Rebind<ServiceArguments>().ToConstant(args);
kernel.Rebind<WarmupTestServiceHostWithSiloHostFake>().ToConstant(this);
}
public async Task StopHost()
{
await WaitForServiceStartedAsync();
Stop();
await WaitForServiceGracefullyStoppedAsync();
//Dispose();
_hostDisposedEvent.SetResult(true);
}
public async Task WaitForHostDisposed()
{
await _hostDisposedEvent.Task;
}
}
}
|
using System.Threading;
using System.Threading.Tasks;
using Gigya.Microdot.Fakes;
using Gigya.Microdot.Hosting.HttpService;
using Gigya.Microdot.Hosting.Validators;
using Gigya.Microdot.Interfaces;
using Gigya.Microdot.Interfaces.Logging;
using Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.CalculatorService;
using Gigya.Microdot.SharedLogic;
using Ninject;
using NSubstitute;
namespace Gigya.Microdot.Orleans.Hosting.UnitTests.Microservice.WarmupTestService
{
public class WarmupTestServiceHostWithSiloHostFake : CalculatorServiceHost
{
private IDependantClassFake _dependantClassFake = Substitute.For<IDependantClassFake>();
private TaskCompletionSource<bool> _hostDisposedEvent = new TaskCompletionSource<bool>();
protected override void Configure(IKernel kernel, OrleansCodeConfig commonConfig)
{
kernel.Rebind<ServiceValidator>().To<MockServiceValidator>().InSingletonScope();
kernel.Rebind<IMetricsInitializer>().To<MetricsInitializerFake>();
kernel.Rebind<GigyaSiloHost>().To<GigyaSiloHostFake>();
kernel.Rebind<IDependantClassFake>().ToConstant(_dependantClassFake);
kernel.Rebind<ILog>().To<NullLog>();
kernel.Rebind<IServiceInterfaceMapper>().To<OrleansServiceInterfaceMapper>();
kernel.Rebind<IAssemblyProvider>().To<AssemblyProvider>();
ServiceArguments args = new ServiceArguments(basePortOverride:9555);
kernel.Rebind<ServiceArguments>().ToConstant(args);
kernel.Rebind<WarmupTestServiceHostWithSiloHostFake>().ToConstant(this);
}
public async Task StopHost()
{
await WaitForServiceStartedAsync();
Stop();
await WaitForServiceGracefullyStoppedAsync();
Dispose();
_hostDisposedEvent.SetResult(true);
}
public async Task WaitForHostDisposed()
{
await _hostDisposedEvent.Task;
}
}
}
|
apache-2.0
|
C#
|
cacdfc53417f9e787b4b7e672f20760336b111bc
|
Bump Version number to 0.3
|
RemiGC/RReplay
|
RReplay/Properties/AssemblyInfo.cs
|
RReplay/Properties/AssemblyInfo.cs
|
using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RReplay")]
[assembly: AssemblyDescription("A simple application to see the deck code from other user from a Red Dragon replay file")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("RReplay")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.*")]
[assembly: NeutralResourcesLanguage("en")]
|
using System.Resources;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RReplay")]
[assembly: AssemblyDescription("A simple application to see the deck code from other user from a Red Dragon replay file")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("RReplay")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.*")]
[assembly: NeutralResourcesLanguage("en")]
|
mit
|
C#
|
91c5188281f1bab2d2d1e84a700df3b18b1eac0f
|
Change port for new RabbitMQ-MQTT server
|
GeorgeHahn/SOVND
|
SOVND.Server/ServerMqttSettings.cs
|
SOVND.Server/ServerMqttSettings.cs
|
using SOVND.Lib;
using System.IO;
namespace SOVND.Server
{
public class ServerMqttSettings : IMQTTSettings
{
public string Broker { get { return "104.131.87.42"; } }
public int Port { get { return 2883; } }
public string Username
{
get { return File.ReadAllText("username.key"); }
}
public string Password
{
get { return File.ReadAllText("password.key"); }
}
}
}
|
using SOVND.Lib;
using System.IO;
namespace SOVND.Server
{
public class ServerMqttSettings : IMQTTSettings
{
public string Broker { get { return "104.131.87.42"; } }
public int Port { get { return 8883; } }
public string Username
{
get { return File.ReadAllText("username.key"); }
}
public string Password
{
get { return File.ReadAllText("password.key"); }
}
}
}
|
epl-1.0
|
C#
|
92686edbdf8d81f943ce9366234cf4e65ef96d57
|
address some compile warnings.
|
jwChung/Experimentalism,jwChung/Experimentalism
|
test/Experiment.IdiomsUnitTest/ClassWithTestMembers.cs
|
test/Experiment.IdiomsUnitTest/ClassWithTestMembers.cs
|
using System;
namespace Jwc.Experiment.Idioms
{
public class ClassWithTestMembers
{
public object PublicField;
protected internal object ProtectedInternalField;
protected object ProtectedField;
internal object InternalField = null;
#pragma warning disable 169
private object PrivateField;
#pragma warning restore 169
public ClassWithTestMembers()
{
}
protected internal ClassWithTestMembers(string arg)
{
}
protected ClassWithTestMembers(object arg)
{
}
internal ClassWithTestMembers(int arg)
{
}
private ClassWithTestMembers(double arg)
{
}
public object PublicProperty
{
get;
set;
}
protected internal object ProtectedInternalProperty
{
get;
set;
}
protected object ProtectedProperty
{
get;
set;
}
internal object InternalProperty
{
get;
set;
}
private object PrivateProperty
{
get;
set;
}
public void PublicMethod()
{
}
protected internal void ProtectedInternalMethod()
{
}
protected void ProtectedMethod()
{
}
internal void InternalMethod()
{
}
private void PrivateMethod()
{
}
public static void PublicStaticMethod()
{
}
protected internal static void ProtectedInternalMStaticMethod()
{
}
protected static void ProtectedStaticMethod()
{
}
internal static void InternalStaticMethod()
{
}
private static void PrivateStaticMethod()
{
}
#pragma warning disable 67
public event EventHandler PublicEvent;
protected internal event EventHandler ProtectedInternalEvent;
protected event EventHandler ProtectedEvent;
internal event EventHandler InternalEvent;
private event EventHandler PrivateEvent;
#pragma warning restore 67
}
}
|
using System;
namespace Jwc.Experiment.Idioms
{
public class ClassWithTestMembers
{
public object PublicField;
protected internal object ProtectedInternalField;
protected object ProtectedField;
internal object InternalField;
private object PrivateField;
public ClassWithTestMembers()
{
}
protected internal ClassWithTestMembers(string arg)
{
}
protected ClassWithTestMembers(object arg)
{
}
internal ClassWithTestMembers(int arg)
{
}
private ClassWithTestMembers(double arg)
{
}
public object PublicProperty
{
get;
set;
}
protected internal object ProtectedInternalProperty
{
get;
set;
}
protected object ProtectedProperty
{
get;
set;
}
internal object InternalProperty
{
get;
set;
}
private object PrivateProperty
{
get;
set;
}
public void PublicMethod()
{
}
protected internal void ProtectedInternalMethod()
{
}
protected void ProtectedMethod()
{
}
internal void InternalMethod()
{
}
private void PrivateMethod()
{
}
public static void PublicStaticMethod()
{
}
protected internal static void ProtectedInternalMStaticMethod()
{
}
protected static void ProtectedStaticMethod()
{
}
internal static void InternalStaticMethod()
{
}
private static void PrivateStaticMethod()
{
}
public event EventHandler PublicEvent;
protected internal event EventHandler ProtectedInternalEvent;
protected event EventHandler ProtectedEvent;
internal event EventHandler InternalEvent;
private event EventHandler PrivateEvent;
}
}
|
mit
|
C#
|
c49deb8eb38865eefdcfcf3c03fcf6818240cfb5
|
Update PetEnPlugin.cs
|
krbysh/FFXIV-ACT-OverlayPlugin-Plugins
|
PetEnPlugin.cs
|
PetEnPlugin.cs
|
using Advanced_Combat_Tracker;
using System;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
// Advanced Combat Tracker - mini parse window用Plugin
// NameEn: 日本語クライアント利用時に、キャラクター名(ペット含む)を英語で出力
[assembly: AssemblyTitle("Mini Parse Pets' Name in English")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ACTv3Plugins
{
public class NameEnPlugin : IActPluginV1
{
Label statusLabel;
private string[,] Pet = {
{"フェアリー・エオス","Eos"},{"フェアリー・セレネ","Selene"},{"イフリート・エギ","Ifrit-Egi"},{"ガルーダ・エギ","Garuda-Egi"},{"タイタン・エギ","Titan-Egi"},
{"カーバンクル・エメラルド","Emerald"},{"カーバンクル・トパーズ","Topaz"},
};
private bool isOneByteChar(string str)
{
byte [] byte_data = System.Text.Encoding.GetEncoding(932).GetBytes(str);
if (byte_data.Length == str.Length) {
return true;
}else{
return false;
}
}
public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
{
statusLabel = pluginStatusText;
CombatantData.ExportVariables.Add(
"NameEn",
new CombatantData.TextExportFormatter("NameEn", "Name En", "name in english", (data, extra) => {
string name = data.GetColumnByName("Name");
if(!(isOneByteChar(name))){
for( int i=0;i<Pet.Length-1;i++ ){
if(name.Contains(Pet[i,0])) return name.Replace(Pet[i,0],Pet[i,1]);
}
}
return name;
}));
ActGlobals.oFormActMain.ValidateLists();
statusLabel.Text = "Initialized.";
}
public void DeInitPlugin()
{
CombatantData.ExportVariables.Remove("NameEn");
statusLabel.Text = "Deinitialized";
}
}
}
|
using Advanced_Combat_Tracker;
using System;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
// Advanced Combat Tracker - mini parse window用Plugin
// NameEn:キャラクター名のペットも含めて英語で出力
[assembly: AssemblyTitle("Mini Parse Pets' Name in English")]
[assembly: AssemblyVersion("1.0.0.0")]
namespace ACTv3Plugins
{
public class NameEnPlugin : IActPluginV1
{
Label statusLabel;
private string[,] Pet = {
{"フェアリー・エオス","Eos"},{"フェアリー・セレネ","Selene"},{"イフリート・エギ","Ifrit-Egi"},{"ガルーダ・エギ","Garuda-Egi"},{"タイタン・エギ","Titan-Egi"},
{"カーバンクル・エメラルド","Emerald"},{"カーバンクル・トパーズ","Topaz"},
};
private bool isOneByteChar(string str)
{
byte [] byte_data = System.Text.Encoding.GetEncoding(932).GetBytes(str);
if (byte_data.Length == str.Length) {
return true;
}else{
return false;
}
}
public void InitPlugin(TabPage pluginScreenSpace, Label pluginStatusText)
{
statusLabel = pluginStatusText;
CombatantData.ExportVariables.Add(
"NameEn",
new CombatantData.TextExportFormatter("NameEn", "Name En", "name in english", (data, extra) => {
string name = data.GetColumnByName("Name");
if(!(isOneByteChar(name))){
for( int i=0;i<Pet.Length-1;i++ ){
if(name.Contains(Pet[i,0])) return name.Replace(Pet[i,0],Pet[i,1]);
}
}
return name;
}));
ActGlobals.oFormActMain.ValidateLists();
statusLabel.Text = "Initialized.";
}
public void DeInitPlugin()
{
CombatantData.ExportVariables.Remove("NameEn");
statusLabel.Text = "Deinitialized";
}
}
}
|
mit
|
C#
|
b541b3681bf8d14a4097c3d53f4bb1dfd2fe990c
|
change vesrion to 3.2.2
|
RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk,rpmoore/ds3_net_sdk,SpectraLogic/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk,RachelTucker/ds3_net_sdk,rpmoore/ds3_net_sdk,rpmoore/ds3_net_sdk,shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk
|
VersionInfo.cs
|
VersionInfo.cs
|
/*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// 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("3.2.2.0")]
[assembly: AssemblyFileVersion("3.2.2.0")]
|
/*
* ******************************************************************************
* Copyright 2014 Spectra Logic Corporation. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* ****************************************************************************
*/
using System.Reflection;
// 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("3.2.1.0")]
[assembly: AssemblyFileVersion("3.2.1.0")]
|
apache-2.0
|
C#
|
4efbc0ed0ecdbd18e1e9c89243dc042d2ad2fcc5
|
Refactor to C# 7
|
ulrichb/ReSharperExtensionsShared
|
Src/ReSharperExtensionsShared/Debugging/DebugUtility.cs
|
Src/ReSharperExtensionsShared/Debugging/DebugUtility.cs
|
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using JetBrains.ReSharper.Psi;
namespace ReSharperExtensionsShared.Debugging
{
public static class DebugUtility
{
public static string FormatIncludingContext([CanBeNull] IDeclaredElement element)
{
if (element == null)
return "NULL";
var result = element.GetType().Name + " '" + element.ShortName + "'";
if (element is IClrDeclaredElement clrDeclaredElement)
{
var containingType = clrDeclaredElement.GetContainingType();
var containingTypeName = containingType == null ? "NULL" : containingType.GetClrName().FullName;
result += " in " + containingTypeName;
if (clrDeclaredElement is IParameter) // executing GetContainingTypeMember() on e.g. TypeParameters throws in R# 8.2
{
var containingTypeMember = clrDeclaredElement.GetContainingTypeMember();
if (containingTypeMember != null)
result += "." + containingTypeMember.ShortName + "()";
}
}
return result;
}
public static string FormatWithElapsed([NotNull] string message, [NotNull] Stopwatch stopwatch)
{
return message + " took " + Math.Round(stopwatch.Elapsed.TotalMilliseconds * 1000) + " usec";
}
}
}
|
using System;
using System.Diagnostics;
using JetBrains.Annotations;
using JetBrains.ReSharper.Psi;
namespace ReSharperExtensionsShared.Debugging
{
public static class DebugUtility
{
public static string FormatIncludingContext([CanBeNull] IDeclaredElement element)
{
if (element == null)
return "NULL";
var result = element.GetType().Name + " '" + element.ShortName + "'";
var clrDeclaredElement = element as IClrDeclaredElement;
if (clrDeclaredElement != null)
{
var containingType = clrDeclaredElement.GetContainingType();
var containingTypeName = containingType == null ? "NULL" : containingType.GetClrName().FullName;
result += " in " + containingTypeName;
if (clrDeclaredElement is IParameter) // executing GetContainingTypeMember() on e.g. TypeParameters throws in R# 8.2
{
var containingTypeMember = clrDeclaredElement.GetContainingTypeMember();
if (containingTypeMember != null)
result += "." + containingTypeMember.ShortName + "()";
}
}
return result;
}
public static string FormatWithElapsed([NotNull] string message, [NotNull] Stopwatch stopwatch)
{
return message + " took " + Math.Round(stopwatch.Elapsed.TotalMilliseconds * 1000) + " usec";
}
}
}
|
mit
|
C#
|
5276e3b9036589b5e14fe5fd1d0e3471aa1c8731
|
Resolve #86 - Add registration for usage of the Stage
|
csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay,csf-dev/CSF.Screenplay
|
Tests/CSF.Screenplay.SpecFlow.Tests/ScreenplayConfig.cs
|
Tests/CSF.Screenplay.SpecFlow.Tests/ScreenplayConfig.cs
|
using CSF.Screenplay.Integration;
using CSF.Screenplay.Reporting;
using CSF.Screenplay.SpecFlow;
[assembly: ScreenplayAssembly(typeof(CSF.Screenplay.SpecFlow.Tests.ScreenplayConfig))]
namespace CSF.Screenplay.SpecFlow.Tests
{
public class ScreenplayConfig : IIntegrationConfig
{
public void Configure(IIntegrationConfigBuilder builder)
{
builder.UseCast();
builder.UseStage();
builder.UseReporting(config => {
config
.SubscribeToActorsCreatedInCast()
.WriteReport(report => {
var path = "SpecFlow.report.txt";
TextReportWriter.WriteToFile(report, path);
});
});
}
}
}
|
using CSF.Screenplay.Integration;
using CSF.Screenplay.Reporting;
using CSF.Screenplay.SpecFlow;
[assembly: ScreenplayAssembly(typeof(CSF.Screenplay.SpecFlow.Tests.ScreenplayConfig))]
namespace CSF.Screenplay.SpecFlow.Tests
{
public class ScreenplayConfig : IIntegrationConfig
{
public void Configure(IIntegrationConfigBuilder builder)
{
builder.UseCast();
builder.UseReporting(config => {
config
.SubscribeToActorsCreatedInCast()
.WriteReport(report => {
var path = "SpecFlow.report.txt";
TextReportWriter.WriteToFile(report, path);
});
});
}
}
}
|
mit
|
C#
|
3b608a046aa526d6e5a944786c08ba1458db61b9
|
Remove some unneeded debug spew.
|
mdavid/manos-spdy,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos
|
server/Mango.Server/HttpConnection.cs
|
server/Mango.Server/HttpConnection.cs
|
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using Mono.Unix.Native;
namespace Mango.Server {
public class HttpConnection {
public static void HandleConnection (IOStream stream, Socket socket, HttpConnectionCallback callback)
{
HttpConnection connection = new HttpConnection (stream, socket, callback);
}
private bool connection_finished;
public HttpConnection (IOStream stream, Socket socket, HttpConnectionCallback callback)
{
IOStream = stream;
Socket = socket;
ConnectionCallback = callback;
stream.ReadUntil ("\r\n\r\n", OnHeaders);
}
public IOStream IOStream {
get;
private set;
}
public Socket Socket {
get;
private set;
}
public HttpConnectionCallback ConnectionCallback {
get;
private set;
}
public HttpRequest Request {
get;
private set;
}
public HttpResponse Response {
get;
private set;
}
internal void Write (List<ArraySegment<byte>> data)
{
IOStream.Write (data, OnWriteFinished);
}
internal void SendFile (string file)
{
IOStream.SendFile (file);
}
internal void Finish ()
{
connection_finished = true;
}
private void OnWriteFinished ()
{
if (connection_finished)
FinishResponse ();
}
private void FinishResponse ()
{
IOStream.Close ();
}
private void OnHeaders (IOStream stream, byte [] data)
{
string h = Encoding.ASCII.GetString (data);
StringReader reader = new StringReader (h);
string verb;
string path;
string version;
string line = reader.ReadLine ();
ParseStartLine (line, out verb, out path, out version);
HttpHeaders headers = new HttpHeaders ();
headers.Parse (reader);
if (headers.ContentLength != null) {
stream.ReadBytes ((int) headers.ContentLength, OnBody);
}
Request = new HttpRequest (this, headers, verb, path);
Response = new HttpResponse (this, Encoding.ASCII);
ConnectionCallback (this);
}
private void ParseStartLine (string line, out string verb, out string path, out string version)
{
int s = 0;
int e = line.IndexOf (' ');
verb = line.Substring (s, e);
s = e + 1;
e = line.IndexOf (' ', s);
path = line.Substring (s, e - s);
s = e + 1;
version = line.Substring (s);
if (!version.StartsWith ("HTTP/"))
throw new Exception ("Malformed HTTP request, no version specified.");
}
private void OnBody (IOStream stream, byte [] data)
{
}
}
}
|
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Collections;
using System.Collections.Generic;
using Mono.Unix.Native;
namespace Mango.Server {
public class HttpConnection {
public static void HandleConnection (IOStream stream, Socket socket, HttpConnectionCallback callback)
{
HttpConnection connection = new HttpConnection (stream, socket, callback);
}
private bool connection_finished;
public HttpConnection (IOStream stream, Socket socket, HttpConnectionCallback callback)
{
IOStream = stream;
Socket = socket;
ConnectionCallback = callback;
stream.ReadUntil ("\r\n\r\n", OnHeaders);
}
public IOStream IOStream {
get;
private set;
}
public Socket Socket {
get;
private set;
}
public HttpConnectionCallback ConnectionCallback {
get;
private set;
}
public HttpRequest Request {
get;
private set;
}
public HttpResponse Response {
get;
private set;
}
internal void Write (List<ArraySegment<byte>> data)
{
IOStream.Write (data, OnWriteFinished);
}
internal void SendFile (string file)
{
IOStream.SendFile (file);
}
internal void Finish ()
{
connection_finished = true;
}
private void OnWriteFinished ()
{
if (connection_finished)
FinishResponse ();
}
private void FinishResponse ()
{
IOStream.Close ();
}
private void OnHeaders (IOStream stream, byte [] data)
{
Console.WriteLine ("HEADERS:");
Console.WriteLine ("=========");
Console.WriteLine (Encoding.ASCII.GetString (data));
Console.WriteLine ("=========");
string h = Encoding.ASCII.GetString (data);
StringReader reader = new StringReader (h);
string verb;
string path;
string version;
string line = reader.ReadLine ();
ParseStartLine (line, out verb, out path, out version);
HttpHeaders headers = new HttpHeaders ();
headers.Parse (reader);
if (headers.ContentLength != null) {
stream.ReadBytes ((int) headers.ContentLength, OnBody);
}
Request = new HttpRequest (this, headers, verb, path);
Response = new HttpResponse (this, Encoding.ASCII);
ConnectionCallback (this);
}
private void ParseStartLine (string line, out string verb, out string path, out string version)
{
int s = 0;
int e = line.IndexOf (' ');
verb = line.Substring (s, e);
s = e + 1;
e = line.IndexOf (' ', s);
path = line.Substring (s, e - s);
s = e + 1;
version = line.Substring (s);
Console.WriteLine ("VERB: '{0}' PATH: '{1}' VERSION: '{2}'", verb, path, version);
if (!version.StartsWith ("HTTP/"))
throw new Exception ("Malformed HTTP request, no version specified.");
}
private void OnBody (IOStream stream, byte [] data)
{
}
}
}
|
mit
|
C#
|
92b959d5f081561b50ab88be23a31de44a5c4f14
|
Remove unnecessary comment
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Fluent/ViewModels/SettingsPageViewModel.cs
|
WalletWasabi.Fluent/ViewModels/SettingsPageViewModel.cs
|
using ReactiveUI;
using System.Reactive.Threading.Tasks;
using System.Windows.Input;
using WalletWasabi.Fluent.ViewModels.Dialogs;
namespace WalletWasabi.Fluent.ViewModels
{
public class SettingsPageViewModel : NavBarItemViewModel
{
public SettingsPageViewModel(IScreen screen) : base(screen)
{
Title = "Settings";
NextCommand = ReactiveCommand.Create(() => screen.Router.Navigate.Execute(new HomePageViewModel(screen)));
OpenDialogCommand = ReactiveCommand.CreateFromTask(async () => await ConfirmSetting.Handle("Please confirm the setting:").ToTask());
ConfirmSetting = new Interaction<string, bool>();
ConfirmSetting.RegisterHandler(
async interaction =>
{
var x = new TestDialogViewModel(interaction.Input);
var result = await x.ShowDialogAsync(MainViewModel.Instance);
interaction.SetOutput(result);
});
}
public ICommand NextCommand { get; }
public ICommand OpenDialogCommand { get; }
public Interaction<string, bool> ConfirmSetting { get; }
public override string IconName => "settings_regular";
}
}
|
using ReactiveUI;
using System.Reactive.Threading.Tasks;
using System.Windows.Input;
using WalletWasabi.Fluent.ViewModels.Dialogs;
namespace WalletWasabi.Fluent.ViewModels
{
public class SettingsPageViewModel : NavBarItemViewModel
{
public SettingsPageViewModel(IScreen screen) : base(screen)
{
Title = "Settings";
NextCommand = ReactiveCommand.Create(() => screen.Router.Navigate.Execute(new HomePageViewModel(screen)));
OpenDialogCommand = ReactiveCommand.CreateFromTask(async () => await ConfirmSetting.Handle("Please confirm the setting:").ToTask());
ConfirmSetting = new Interaction<string, bool>();
// NOTE: In ReactiveUI docs this is registered in view ctor.
ConfirmSetting.RegisterHandler(
async interaction =>
{
var x = new TestDialogViewModel(interaction.Input);
var result = await x.ShowDialogAsync(MainViewModel.Instance);
interaction.SetOutput(result);
});
}
public ICommand NextCommand { get; }
public ICommand OpenDialogCommand { get; }
public Interaction<string, bool> ConfirmSetting { get; }
public override string IconName => "settings_regular";
}
}
|
mit
|
C#
|
a002dacdce3bdb66d5f44cdee6a2423e954a1bc4
|
Add test coverage of various `ScoreInfo` mod set operations
|
NeoAdonis/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu
|
osu.Game.Tests/NonVisual/ScoreInfoTest.cs
|
osu.Game.Tests/NonVisual/ScoreInfoTest.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Online.API;
using osu.Game.Rulesets.Mania;
using osu.Game.Rulesets.Mania.Mods;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Osu.Mods;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class ScoreInfoTest
{
[Test]
public void TestDeepClone()
{
var score = new ScoreInfo();
score.Statistics.Add(HitResult.Good, 10);
score.Rank = ScoreRank.B;
var scoreCopy = score.DeepClone();
score.Statistics[HitResult.Good]++;
score.Rank = ScoreRank.X;
Assert.That(scoreCopy.Statistics[HitResult.Good], Is.EqualTo(10));
Assert.That(score.Statistics[HitResult.Good], Is.EqualTo(11));
Assert.That(scoreCopy.Rank, Is.EqualTo(ScoreRank.B));
Assert.That(score.Rank, Is.EqualTo(ScoreRank.X));
}
[Test]
public void TestModsInitiallyEmpty()
{
var score = new ScoreInfo();
Assert.That(score.Mods, Is.Empty);
Assert.That(score.APIMods, Is.Empty);
Assert.That(score.ModsJson, Is.Empty);
}
[Test]
public void TestModsUpdatedCorrectly()
{
var score = new ScoreInfo
{
Mods = new Mod[] { new ManiaModClassic() },
Ruleset = new ManiaRuleset().RulesetInfo,
};
Assert.That(score.Mods, Contains.Item(new ManiaModClassic()));
Assert.That(score.APIMods, Contains.Item(new APIMod(new ManiaModClassic())));
Assert.That(score.ModsJson, Contains.Substring("CL"));
score.APIMods = new[] { new APIMod(new ManiaModDoubleTime()) };
Assert.That(score.Mods, Contains.Item(new ManiaModDoubleTime()));
Assert.That(score.APIMods, Contains.Item(new APIMod(new ManiaModDoubleTime())));
Assert.That(score.ModsJson, Contains.Substring("DT"));
score.Mods = new Mod[] { new ManiaModClassic() };
Assert.That(score.Mods, Contains.Item(new ManiaModClassic()));
Assert.That(score.APIMods, Contains.Item(new APIMod(new ManiaModClassic())));
Assert.That(score.ModsJson, Contains.Substring("CL"));
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Game.Rulesets.Scoring;
using osu.Game.Scoring;
namespace osu.Game.Tests.NonVisual
{
[TestFixture]
public class ScoreInfoTest
{
[Test]
public void TestDeepClone()
{
var score = new ScoreInfo();
score.Statistics.Add(HitResult.Good, 10);
score.Rank = ScoreRank.B;
var scoreCopy = score.DeepClone();
score.Statistics[HitResult.Good]++;
score.Rank = ScoreRank.X;
Assert.That(scoreCopy.Statistics[HitResult.Good], Is.EqualTo(10));
Assert.That(score.Statistics[HitResult.Good], Is.EqualTo(11));
Assert.That(scoreCopy.Rank, Is.EqualTo(ScoreRank.B));
Assert.That(score.Rank, Is.EqualTo(ScoreRank.X));
}
}
}
|
mit
|
C#
|
ce687a9f87bbc9307e0b4261a358b72557cf38df
|
Update IShapeFactory.cs
|
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Model/IShapeFactory.cs
|
src/Core2D/Model/IShapeFactory.cs
|
#nullable enable
using System.Collections.Immutable;
using Core2D.Model.Path;
using Core2D.ViewModels.Path;
using Core2D.ViewModels.Shapes;
namespace Core2D.Model;
public interface IShapeFactory
{
PointShapeViewModel? Point(double x, double y, bool isStandalone);
LineShapeViewModel? Line(double x1, double y1, double x2, double y2, bool isStroked);
LineShapeViewModel? Line(PointShapeViewModel? start, PointShapeViewModel? end, bool isStroked);
ArcShapeViewModel? Arc(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, bool isStroked, bool isFilled);
ArcShapeViewModel? Arc(PointShapeViewModel? point1, PointShapeViewModel? point2, PointShapeViewModel? point3, PointShapeViewModel? point4, bool isStroked, bool isFilled);
CubicBezierShapeViewModel? CubicBezier(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, bool isStroked, bool isFilled);
CubicBezierShapeViewModel? CubicBezier(PointShapeViewModel? point1, PointShapeViewModel? point2, PointShapeViewModel? point3, PointShapeViewModel? point4, bool isStroked, bool isFilled);
QuadraticBezierShapeViewModel? QuadraticBezier(double x1, double y1, double x2, double y2, double x3, double y3, bool isStroked, bool isFilled);
QuadraticBezierShapeViewModel? QuadraticBezier(PointShapeViewModel? point1, PointShapeViewModel? point2, PointShapeViewModel? point3, bool isStroked, bool isFilled);
PathShapeViewModel? Path(ImmutableArray<PathFigureViewModel> figures, FillRule fillRule, bool isStroked, bool isFilled);
RectangleShapeViewModel? Rectangle(double x1, double y1, double x2, double y2, bool isStroked, bool isFilled, string? text);
RectangleShapeViewModel? Rectangle(PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, bool isStroked, bool isFilled, string? text);
EllipseShapeViewModel? Ellipse(double x1, double y1, double x2, double y2, bool isStroked, bool isFilled, string? text);
EllipseShapeViewModel? Ellipse(PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, bool isStroked, bool isFilled, string? text);
TextShapeViewModel? Text(double x1, double y1, double x2, double y2, string? text, bool isStroked);
TextShapeViewModel? Text(PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, string? text, bool isStroked);
ImageShapeViewModel? Image(string? path, double x1, double y1, double x2, double y2, bool isStroked, bool isFilled, string? text);
ImageShapeViewModel? Image(string? path, PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, bool isStroked, bool isFilled, string? text);
}
|
#nullable enable
using System.Collections.Immutable;
using Core2D.Model.Path;
using Core2D.ViewModels.Path;
using Core2D.ViewModels.Shapes;
namespace Core2D.Model;
public interface IShapeFactory
{
PointShapeViewModel Point(double x, double y, bool isStandalone);
LineShapeViewModel Line(double x1, double y1, double x2, double y2, bool isStroked);
LineShapeViewModel Line(PointShapeViewModel? start, PointShapeViewModel? end, bool isStroked);
ArcShapeViewModel Arc(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, bool isStroked, bool isFilled);
ArcShapeViewModel Arc(PointShapeViewModel? point1, PointShapeViewModel? point2, PointShapeViewModel? point3, PointShapeViewModel? point4, bool isStroked, bool isFilled);
CubicBezierShapeViewModel CubicBezier(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4, bool isStroked, bool isFilled);
CubicBezierShapeViewModel CubicBezier(PointShapeViewModel? point1, PointShapeViewModel? point2, PointShapeViewModel? point3, PointShapeViewModel? point4, bool isStroked, bool isFilled);
QuadraticBezierShapeViewModel QuadraticBezier(double x1, double y1, double x2, double y2, double x3, double y3, bool isStroked, bool isFilled);
QuadraticBezierShapeViewModel QuadraticBezier(PointShapeViewModel? point1, PointShapeViewModel? point2, PointShapeViewModel? point3, bool isStroked, bool isFilled);
PathShapeViewModel Path(ImmutableArray<PathFigureViewModel> figures, FillRule fillRule, bool isStroked, bool isFilled);
RectangleShapeViewModel Rectangle(double x1, double y1, double x2, double y2, bool isStroked, bool isFilled, string? text);
RectangleShapeViewModel Rectangle(PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, bool isStroked, bool isFilled, string? text);
EllipseShapeViewModel Ellipse(double x1, double y1, double x2, double y2, bool isStroked, bool isFilled, string? text);
EllipseShapeViewModel Ellipse(PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, bool isStroked, bool isFilled, string? text);
TextShapeViewModel Text(double x1, double y1, double x2, double y2, string? text, bool isStroked);
TextShapeViewModel Text(PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, string? text, bool isStroked);
ImageShapeViewModel? Image(string? path, double x1, double y1, double x2, double y2, bool isStroked, bool isFilled, string? text);
ImageShapeViewModel? Image(string? path, PointShapeViewModel? topLeft, PointShapeViewModel? bottomRight, bool isStroked, bool isFilled, string? text);
}
|
mit
|
C#
|
512ad057ecfaf617540c6b411932b55c2c516a7c
|
Change text
|
Sebazzz/IFS,Sebazzz/IFS,Sebazzz/IFS,Sebazzz/IFS
|
src/IFS.Web/Models/UploadModel.cs
|
src/IFS.Web/Models/UploadModel.cs
|
// ******************************************************************************
// © 2016 Sebastiaan Dammann - damsteen.nl
//
// File: : UploadModel.cs
// Project : IFS.Web
// ******************************************************************************
namespace IFS.Web.Models {
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Core;
using Core.Upload;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
public class UploadModel {
public FileIdentifier FileIdentifier { get; set; }
[Required(ErrorMessage = "Please select a file to upload")]
[FileSizeValidation]
[Display(Name = "Your file")]
public IFormFile File { get; set; }
[Display]
public DateTime Expiration { get; set; }
[Display(Name = "When will the file expiration start?")]
public ExpirationMode ExpirationMode { get; set; }
public long SuggestedFileSize { get; set; }
public IEnumerable<SelectListItem> AvailableExpiration { get; set; }
}
public class UploadFileInProgressModel {
public string FileName { get; set; }
public FileIdentifier FileIdentifier { get; set; }
}
public class UploadProgressModel {
public long Current { get; set; }
public long Total { get; set; }
public string FileName { get; set; }
public string Performance { get; set; }
public int Percent { get; set; }
}
}
|
// ******************************************************************************
// © 2016 Sebastiaan Dammann - damsteen.nl
//
// File: : UploadModel.cs
// Project : IFS.Web
// ******************************************************************************
namespace IFS.Web.Models {
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Core;
using Core.Upload;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Rendering;
public class UploadModel {
public FileIdentifier FileIdentifier { get; set; }
[Required(ErrorMessage = "Please select a file to upload")]
[FileSizeValidation]
[Display(Name = "Your file")]
public IFormFile File { get; set; }
[Display]
public DateTime Expiration { get; set; }
[Display(Name = "When will the file expiration start counting?")]
public ExpirationMode ExpirationMode { get; set; }
public long SuggestedFileSize { get; set; }
public IEnumerable<SelectListItem> AvailableExpiration { get; set; }
}
public class UploadFileInProgressModel {
public string FileName { get; set; }
public FileIdentifier FileIdentifier { get; set; }
}
public class UploadProgressModel {
public long Current { get; set; }
public long Total { get; set; }
public string FileName { get; set; }
public string Performance { get; set; }
public int Percent { get; set; }
}
}
|
mit
|
C#
|
321197a59e79fa29f40d983dd530fad063bf1ff3
|
Update ScriptableBuild.cs
|
dimmpixeye/Unity3dTools
|
Runtime/LibMisc/ScriptableBuild.cs
|
Runtime/LibMisc/ScriptableBuild.cs
|
// Project : ecs
// Contacts : Pix - ask@pixeye.games
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Pixeye.Framework
{
public class ScriptableBuild : ScriptableObject
{
public Dictionary<int, ModelComposer> helpers = new Dictionary<int, ModelComposer>();
internal virtual void Execute(in ent entity, Actor a = null)
{
helpers[GetInstanceID()](entity);
EntityOperations.Set(entity, -1, EntityOperations.Action.Activate);
}
internal virtual void ExecuteOnStart(in ent entity, Actor a)
{
helpers[GetInstanceID()](entity);
if (!a.isActiveAndEnabled) return;
EntityOperations.Set(entity, -1, EntityOperations.Action.Activate);
}
protected virtual void OnEnable()
{
#if UNITY_EDITOR
if (!EditorApplication.isPlayingOrWillChangePlaymode) return;
#endif
Type t = GetType();
var n = name.Substring(5).Replace(" ", string.Empty);
helpers.Add(GetInstanceID(), (ModelComposer) Delegate.CreateDelegate(typeof(ModelComposer), null, t.GetMethod(n, BindingFlags.Public | BindingFlags.Static | BindingFlags.Default)));
}
protected virtual void OnDisable()
{
helpers.Clear();
}
}
public static class HelperScriptableBuild
{
public static ModelComposer GetModelComposer(this ScriptableBuild sb)
{
return sb.helpers[sb.GetHashCode()];
}
}
}
|
// Project : ecs
// Contacts : Pix - ask@pixeye.games
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace Pixeye.Framework
{
public class ScriptableBuild : ScriptableObject
{
public Dictionary<int, ModelComposer> helpers = new Dictionary<int, ModelComposer>();
internal virtual void Execute(in ent entity, Actor a = null)
{
helpers[GetInstanceID()](entity);
EntityOperations.Set(entity, -1, EntityOperations.Action.Activate);
}
internal virtual void ExecuteOnStart(in ent entity, Actor a)
{
helpers[GetInstanceID()](entity);
if (!a.isActiveAndEnabled) return;
EntityOperations.Set(entity, -1, EntityOperations.Action.Activate);
}
protected virtual void OnEnable()
{
#if UNITY_EDITOR
if (!EditorApplication.isPlayingOrWillChangePlaymode) return;
#endif
Type t = GetType();
var n = name.Substring(5).Replace(" ", string.Empty);
helpers.Add(GetInstanceID(), (ModelComposer) Delegate.CreateDelegate(typeof(ModelComposer), null, t.GetMethod(n, BindingFlags.Public | BindingFlags.Static | BindingFlags.Default)));
}
protected virtual void OnDisable()
{
helpers.Clear();
}
}
}
|
mit
|
C#
|
5f3d9b23d2b35437a687a7754f0a3dd682978cd9
|
Improve TaskAction canceled test
|
ermau/WinRT.NET
|
WinRT.NET/Tests/TaskActionTests.cs
|
WinRT.NET/Tests/TaskActionTests.cs
|
//
// TaskActionTests.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Threading;
using NUnit.Framework;
using Windows.Foundation;
namespace WinRTNET.Tests
{
[TestFixture]
internal class TaskActionTests
: IAsyncActionTestsBase<TaskAction>
{
protected override TaskAction GetAsync()
{
return new TaskAction (() => "do nothing".ToString());
}
[Test]
public void AsyncStatus_Completed_Canceled()
{
IAsyncAction action = new TaskAction (() => Thread.Sleep (1000));
bool completed = false;
action.Completed = a =>
{
Assert.AreEqual (AsyncStatus.Canceled, a.Status);
completed = true;
};
action.Start();
action.Cancel();
Assert.IsTrue (SpinWait.SpinUntil(() => completed, 5000));
Assert.AreEqual (AsyncStatus.Canceled, action.Status);
}
}
}
|
//
// TaskActionTests.cs
//
// Author:
// Eric Maupin <me@ermau.com>
//
// Copyright (c) 2011 Eric Maupin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System.Threading;
using NUnit.Framework;
using Windows.Foundation;
namespace WinRTNET.Tests
{
[TestFixture]
internal class TaskActionTests
: IAsyncActionTestsBase<TaskAction>
{
protected override TaskAction GetAsync()
{
return new TaskAction (() => "do nothing".ToString());
}
[Test]
public void AsyncStatus_Completed_Canceled()
{
IAsyncAction action = new TaskAction (() => Thread.Sleep (1000));
bool completed = false;
action.Completed = a => completed = true;
action.Start();
action.Cancel();
Assert.IsTrue (SpinWait.SpinUntil(() => completed, 5000));
Assert.AreEqual (AsyncStatus.Canceled, action.Status);
}
}
}
|
mit
|
C#
|
ddc9284bc28a626c745a70a33a2d0854f1f60d94
|
Add missing vault_token property to PaymentSource
|
PayDockDev/paydock_dotnet_sdk
|
sdk/Models/PaymentSource.cs
|
sdk/Models/PaymentSource.cs
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Paydock_dotnet_sdk.Models
{
public enum PaymentType
{
card,
bank_account,
bsb,
checkout
}
public class PaymentSource
{
public string gateway_id { get; set; }
public string vault_token { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public PaymentType type { get; set; }
public string account_name { get; set; }
public string account_bsb { get; set; }
public string account_number { get; set; }
public string account_routing { get; set; }
public string account_holder_type { get; set; }
public string account_bank_name { get; set; }
public string card_name { get; set; }
public string card_number { get; set; }
public string expire_year { get; set; }
public string expire_month { get; set; }
public string card_ccv { get; set; }
public string address_line1 { get; set; }
public string address_line2 { get; set; }
public string address_state { get; set; }
public string address_country { get; set; }
public string address_city { get; set; }
public string address_postcode { get; set; }
public string checkout_holder { get; set; }
public string checkout_email { get; set; }
}
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace Paydock_dotnet_sdk.Models
{
public enum PaymentType
{
card,
bank_account,
bsb,
checkout
}
public class PaymentSource
{
public string gateway_id { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public PaymentType type { get; set; }
public string account_name { get; set; }
public string account_bsb { get; set; }
public string account_number { get; set; }
public string account_routing { get; set; }
public string account_holder_type { get; set; }
public string account_bank_name { get; set; }
public string card_name { get; set; }
public string card_number { get; set; }
public string expire_year { get; set; }
public string expire_month { get; set; }
public string card_ccv { get; set; }
public string address_line1 { get; set; }
public string address_line2 { get; set; }
public string address_state { get; set; }
public string address_country { get; set; }
public string address_city { get; set; }
public string address_postcode { get; set; }
public string checkout_holder { get; set; }
public string checkout_email { get; set; }
}
}
|
mit
|
C#
|
66b78cc24319acf93aff47915e87420a7693ce1a
|
Build error post refactoring..
|
connellw/Firestorm
|
src/Firestorm.EntityFramework6/EntitiesDataSource.cs
|
src/Firestorm.EntityFramework6/EntitiesDataSource.cs
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;
using Firestorm.Data;
namespace Firestorm.EntityFramework6
{
public class EntitiesDataSource<TDbContext> : IDiscoverableDataSource
where TDbContext : DbContext, new()
{
public IDataTransaction CreateTransaction()
{
return new EntitiesDataTransaction<TDbContext>();
}
public IEngineRepository<TEntity> GetRepository<TEntity>(IDataTransaction transaction)
where TEntity : class, new()
{
if(!(transaction is EntitiesDataTransaction<TDbContext> entitiesTransaction))
throw new ArgumentException("Entity Framework data source was given a transaction for the wrong data source type or context.");
TDbContext database = entitiesTransaction.DbContext;
DbSet<TEntity> repo = database.Set<TEntity>();
return new EntitiesRepository<TEntity>(repo);
}
public IEnumerable<Type> FindRepositoryTypes()
{
using (var context = new TDbContext())
{
return IterateEntityClrTypes(context).ToList();
}
}
/// <remarks>
/// From https://stackoverflow.com/a/18950910
/// </remarks>
private static IEnumerable<Type> IterateEntityClrTypes(TDbContext dbContext)
{
var objectItemCollection = (ObjectItemCollection) ((IObjectContextAdapter) dbContext)
.ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.OSpace);
foreach (var entityType in objectItemCollection.GetItems<EntityType>())
{
yield return objectItemCollection.GetClrType(entityType);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Core.Metadata.Edm;
using System.Data.Entity.Infrastructure;
using System.Linq;
using Firestorm.Data;
namespace Firestorm.EntityFramework6
{
public class EntitiesDataSource<TDbContext> : IDiscoverableDataSource
where TDbContext : DbContext, new()
{
public IDataTransaction CreateTransaction()
{
return new EntitiesDataTransaction<TDbContext>();
}
public IEngineRepository<TEntity> GetRepository<TEntity>(IDataTransaction transaction)
where TEntity : class, new()
{
if(!(transaction is EntitiesDataTransaction<TDbContext> entitiesTransaction))
throw new ArgumentException("Entity Framework data source was given a transaction for the wrong data source type or context.");
TDbContext database = entitiesTransaction.DbContext;
DbSet<TEntity> repo = database.Set<TEntity>();
return new EntitiesRepository<TEntity>(repo);
}
public IEnumerable<Type> FindRespositoryTypes()
{
using (var context = new TDbContext())
{
return IterateEntityClrTypes(context).ToList();
}
}
/// <remarks>
/// From https://stackoverflow.com/a/18950910
/// </remarks>
private static IEnumerable<Type> IterateEntityClrTypes(TDbContext dbContext)
{
var objectItemCollection = (ObjectItemCollection) ((IObjectContextAdapter) dbContext)
.ObjectContext.MetadataWorkspace.GetItemCollection(DataSpace.OSpace);
foreach (var entityType in objectItemCollection.GetItems<EntityType>())
{
yield return objectItemCollection.GetClrType(entityType);
}
}
}
}
|
mit
|
C#
|
1f7cdcbe33ef35aaae549f43117a26cf56e94363
|
upgrade version to 2.0.7
|
Aaron-Liu/equeue,tangxuehua/equeue,geffzhang/equeue,tangxuehua/equeue,geffzhang/equeue,Aaron-Liu/equeue,tangxuehua/equeue
|
src/EQueue/Properties/AssemblyInfo.cs
|
src/EQueue/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.7")]
[assembly: AssemblyFileVersion("2.0.7")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的常规信息通过以下
// 特性集控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("EQueue")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EQueue")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 使此程序集中的类型
// 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型,
// 则将该类型上的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("75468a30-77e7-4b09-813c-51513179c550")]
// 程序集的版本信息由下面四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值,
// 方法是按如下所示使用“*”:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.6")]
[assembly: AssemblyFileVersion("2.0.6")]
|
mit
|
C#
|
1199ed4b2d9e4787d8b987a30a2de5fde627281d
|
remove debug msgs
|
Yetangitu/f-spot,Sanva/f-spot,Sanva/f-spot,GNOME/f-spot,nathansamson/F-Spot-Album-Exporter,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mono/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,mono/f-spot,GNOME/f-spot,mono/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,mans0954/f-spot,Yetangitu/f-spot,NguyenMatthieu/f-spot,Sanva/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,mans0954/f-spot,Yetangitu/f-spot,mono/f-spot,mans0954/f-spot,dkoeb/f-spot,Yetangitu/f-spot,dkoeb/f-spot,GNOME/f-spot,Yetangitu/f-spot,GNOME/f-spot,mono/f-spot,mans0954/f-spot,mans0954/f-spot,GNOME/f-spot,dkoeb/f-spot,Sanva/f-spot,NguyenMatthieu/f-spot,dkoeb/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,mans0954/f-spot
|
src/Extensions/ComplexMenuItemNode.cs
|
src/Extensions/ComplexMenuItemNode.cs
|
/*
* FSpot.Extensions.ComplexMenuItemNode
*
* Author(s)
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details.
*
*/
using Mono.Addins;
using FSpot.Widgets;
using System;
namespace FSpot.Extensions
{
[ExtensionNode ("ComplexMenuItem")]
public class ComplexMenuItemNode : MenuNode
{
[NodeAttribute]
string widget_type;
[NodeAttribute]
string command_type;
public event EventHandler Changed;
ICommand cmd;
public override Gtk.MenuItem GetMenuItem ()
{
ComplexMenuItem item = System.Activator.CreateInstance (Type.GetType (widget_type)) as ComplexMenuItem;
cmd = (ICommand) Addin.CreateInstance (command_type);
if (item != null)
item.Changed += OnChanged;
return item;
}
private void OnChanged (object o, EventArgs e)
{
if (cmd != null)
cmd.Run (o, e);
}
}
}
|
/*
* FSpot.Extensions.ComplexMenuItemNode
*
* Author(s)
* Stephane Delcroix <stephane@delcroix.org>
*
* This is free software. See COPYING for details.
*
*/
using Mono.Addins;
using FSpot.Widgets;
using System;
namespace FSpot.Extensions
{
[ExtensionNode ("ComplexMenuItem")]
public class ComplexMenuItemNode : MenuNode
{
[NodeAttribute]
string widget_type;
[NodeAttribute]
string command_type;
public event EventHandler Changed;
ICommand cmd;
public override Gtk.MenuItem GetMenuItem ()
{
Console.WriteLine ("POOOOOOOOOOONG");
ComplexMenuItem item = System.Activator.CreateInstance (Type.GetType (widget_type)) as ComplexMenuItem;
cmd = (ICommand) Addin.CreateInstance (command_type);
if (item != null)
item.Changed += OnChanged;
return item;
}
private void OnChanged (object o, EventArgs e)
{
if (cmd != null)
cmd.Run (o, e);
}
}
}
|
mit
|
C#
|
7756dc640c5d9de30c955a0f84ce7b1529f98118
|
Bump version
|
ruisebastiao/FluentValidation,deluxetiky/FluentValidation,robv8r/FluentValidation,GDoronin/FluentValidation,mgmoody42/FluentValidation,glorylee/FluentValidation,regisbsb/FluentValidation,IRlyDontKnow/FluentValidation,cecilphillip/FluentValidation,olcayseker/FluentValidation,roend83/FluentValidation,roend83/FluentValidation
|
src/CommonAssemblyInfo.cs
|
src/CommonAssemblyInfo.cs
|
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2014")]
#if !PORTABLE
[assembly : ComVisible(false)]
#endif
[assembly : AssemblyVersion("5.1.0.0")]
[assembly : AssemblyFileVersion("5.1.0.0")]
[assembly: CLSCompliant(true)]
[assembly: System.Resources.NeutralResourcesLanguage("en")]
|
#region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// 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.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2014")]
#if !PORTABLE
[assembly : ComVisible(false)]
#endif
[assembly : AssemblyVersion("5.0.0.1")]
[assembly : AssemblyFileVersion("5.0.0.1")]
[assembly: CLSCompliant(true)]
[assembly: System.Resources.NeutralResourcesLanguage("en")]
|
apache-2.0
|
C#
|
e0e7e474f15c4f0c2e01c2fd66b077bd02250075
|
Truncate stream when writing sidecar XMP files.
|
GNOME/f-spot,dkoeb/f-spot,mono/f-spot,NguyenMatthieu/f-spot,Yetangitu/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot,GNOME/f-spot,GNOME/f-spot,mans0954/f-spot,mono/f-spot,mans0954/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,dkoeb/f-spot,GNOME/f-spot,dkoeb/f-spot,Yetangitu/f-spot,Sanva/f-spot,mono/f-spot,Sanva/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot,mans0954/f-spot,mans0954/f-spot,mono/f-spot,Sanva/f-spot,mans0954/f-spot,nathansamson/F-Spot-Album-Exporter,GNOME/f-spot,NguyenMatthieu/f-spot,mono/f-spot,dkoeb/f-spot,mono/f-spot,Sanva/f-spot,mans0954/f-spot,dkoeb/f-spot,NguyenMatthieu/f-spot
|
src/Utils/SidecarXmpExtensions.cs
|
src/Utils/SidecarXmpExtensions.cs
|
using System;
using System.IO;
using GLib;
using Hyena;
using TagLib.Image;
using TagLib.Xmp;
namespace FSpot.Utils
{
public static class SidecarXmpExtensions
{
/// <summary>
/// Parses the XMP file identified by resource and replaces the XMP
/// tag of file by the parsed data.
/// </summary>
public static void ParseXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource)
{
string xmp;
using (var stream = resource.ReadStream) {
using (var reader = new StreamReader (stream)) {
xmp = reader.ReadToEnd ();
}
}
var tag = new XmpTag (xmp);
var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, true) as XmpTag;
xmp_tag.ReplaceFrom (tag);
}
public static void SaveXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource)
{
var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, false) as XmpTag;
if (xmp_tag == null)
return;
var xmp = xmp_tag.Render ();
using (var stream = resource.WriteStream) {
stream.SetLength (0);
using (var writer = new StreamWriter (stream)) {
writer.Write (xmp);
}
resource.CloseStream (stream);
}
}
}
}
|
using System;
using System.IO;
using GLib;
using Hyena;
using TagLib.Image;
using TagLib.Xmp;
namespace FSpot.Utils
{
public static class SidecarXmpExtensions
{
/// <summary>
/// Parses the XMP file identified by resource and replaces the XMP
/// tag of file by the parsed data.
/// </summary>
public static void ParseXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource)
{
string xmp;
using (var stream = resource.ReadStream) {
using (var reader = new StreamReader (stream)) {
xmp = reader.ReadToEnd ();
}
}
var tag = new XmpTag (xmp);
var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, true) as XmpTag;
xmp_tag.ReplaceFrom (tag);
}
public static void SaveXmpSidecar (this TagLib.Image.File file, TagLib.File.IFileAbstraction resource)
{
var xmp_tag = file.GetTag (TagLib.TagTypes.XMP, false) as XmpTag;
if (xmp_tag == null)
return;
var xmp = xmp_tag.Render ();
using (var stream = resource.WriteStream) {
using (var writer = new StreamWriter (stream)) {
writer.Write (xmp);
}
resource.CloseStream (stream);
}
}
}
}
|
mit
|
C#
|
dac2519d5e3101afd874349ab2f40b55a9549bc1
|
add constructors for value or state
|
Kukkimonsuta/Odachi
|
src/Odachi.Validation/ValueOrState.cs
|
src/Odachi.Validation/ValueOrState.cs
|
namespace Odachi.Validation
{
/// <summary>
/// Either value or validation state.
/// </summary>
public struct ValueOrState<TValue>
{
public ValueOrState(TValue value)
{
Value = value;
State = null;
}
public ValueOrState(ValidationState state)
{
Value = default(TValue);
State = state;
}
public TValue Value { get; private set; }
public ValidationState State { get; private set; }
#region Static members
public static implicit operator ValueOrState<TValue>(Validator validator)
{
return new ValueOrState<TValue>()
{
State = validator.State,
};
}
public static implicit operator ValueOrState<TValue>(ValidationState state)
{
return new ValueOrState<TValue>()
{
State = state,
};
}
public static implicit operator ValueOrState<TValue>(TValue result)
{
return new ValueOrState<TValue>()
{
Value = result,
};
}
#endregion
}
}
|
namespace Odachi.Validation
{
/// <summary>
/// Either value or validation state.
/// </summary>
public struct ValueOrState<TValue>
{
public TValue Value { get; private set; }
public ValidationState State { get; private set; }
#region Static members
public static implicit operator ValueOrState<TValue>(Validator validator)
{
return new ValueOrState<TValue>()
{
State = validator.State,
};
}
public static implicit operator ValueOrState<TValue>(TValue result)
{
return new ValueOrState<TValue>()
{
Value = result,
};
}
#endregion
}
}
|
apache-2.0
|
C#
|
6ed1669803d62f7a02f75d89b0e0ad66b8d5d983
|
set a sensible cache size for skia.. based on what flutter uses.
|
akrisiun/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Perspex,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,grokys/Perspex,grokys/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia
|
src/Skia/Avalonia.Skia/SkiaOptions.cs
|
src/Skia/Avalonia.Skia/SkiaOptions.cs
|
using System;
using Avalonia.Skia;
namespace Avalonia
{
/// <summary>
/// Options for Skia rendering subsystem.
/// </summary>
public class SkiaOptions
{
/// <summary>
/// Custom gpu factory to use. Can be used to customize behavior of Skia renderer.
/// </summary>
public Func<ISkiaGpu> CustomGpuFactory { get; set; }
/// <summary>
/// The maximum number of bytes for video memory to store textures and resources.
/// </summary>
public long? MaxGpuResourceSizeBytes { get; set; } = 1024 * 600 * 4 * 12; // ~28mb 12x 1024 x 600 textures.
}
}
|
using System;
using Avalonia.Skia;
namespace Avalonia
{
/// <summary>
/// Options for Skia rendering subsystem.
/// </summary>
public class SkiaOptions
{
/// <summary>
/// Custom gpu factory to use. Can be used to customize behavior of Skia renderer.
/// </summary>
public Func<ISkiaGpu> CustomGpuFactory { get; set; }
/// <summary>
/// The maximum number of bytes for video memory to store textures and resources.
/// </summary>
public long? MaxGpuResourceSizeBytes { get; set; }
}
}
|
mit
|
C#
|
6c6eec2e59ff80e5726af3bb5050e70cf36fdbf3
|
set dev to v4.0.0
|
ControlzEx/ControlzEx,punker76/Controlz
|
src/GlobalAssemblyInfo.cs
|
src/GlobalAssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("https://github.com/ControlzEx/ControlzEx")]
[assembly: AssemblyProduct("ControlzEx")]
[assembly: AssemblyCopyright("Copyright © 2015 - 2017 Jan Karger, Bastian Schmidt, James Willock")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Only increase AssemblyVersion for major releases.
// Otherwise we get issues with nuget version ranges for dependent projects.
// Especially dependent projects which use strong names get problems with changing version numbers.
[assembly: AssemblyVersion("4.0.0")]
[assembly: AssemblyFileVersion("4.0.0")]
[assembly: AssemblyInformationalVersion("SRC")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
|
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Windows;
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
[assembly: AssemblyCompany("https://github.com/ControlzEx/ControlzEx")]
[assembly: AssemblyProduct("ControlzEx")]
[assembly: AssemblyCopyright("Copyright © 2015 - 2017 Jan Karger, Bastian Schmidt, James Willock")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Only increase AssemblyVersion for major releases.
// Otherwise we get issues with nuget version ranges for dependent projects.
// Especially dependent projects which use strong names get problems with changing version numbers.
[assembly: AssemblyVersion("3.0.1.0")]
[assembly: AssemblyFileVersion("3.0.1.0")]
[assembly: AssemblyInformationalVersion("SRC")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)]
|
mit
|
C#
|
d8751df921175cbfd757e2fc2c024ed54fe4eb04
|
Update EntitySet.cs
|
PowerMogli/Rabbit.Db
|
src/RabbitDB/EntitySet.cs
|
src/RabbitDB/EntitySet.cs
|
using System;
using System.Collections;
using System.Collections.Generic;
using RabbitDB.Query;
namespace RabbitDB.Base
{
public class EntitySet<T> : IEnumerable<T>
{
private List<T> _list = new List<T>();
internal EntitySet<T> Load(IDbSession dbSession, IQuery query)
{
using (EntityReader<T> reader = dbSession.GetEntityReader<T>(query))
{
while (reader.Read())
{
_list.Add(reader.Current);
}
}
return this;
}
internal void ForEach(Action<T> action)
{
_list.ForEach(action);
}
public T this[int index]
{
get { return _list[index]; }
}
public int Count { get { return _list.Count; } }
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using RabbitDB.Query;
namespace RabbitDB.Base
{
public class EntitySet<T> : IEnumerable<T>
{
private List<T> _list = new List<T>();
internal EntitySet<T> Load(IDbSession dbSession, IQuery query)
{
using (EntityReader<T> reader = dbSession.GetEntityReader<T>(query))
{
while (reader.Read())
{
_list.Add(reader.Current);
}
}
return this;
}
public T this[int index]
{
get { return _list[index]; }
}
public int Count { get { return _list.Count; } }
public IEnumerator<T> GetEnumerator()
{
return _list.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
|
apache-2.0
|
C#
|
e9792c80ed1b1ac7da0f02eb5041512ee7fe4bdf
|
Use EntitySystem Dictionary
|
copygirl/EntitySystem
|
src/World/ChunkManager.cs
|
src/World/ChunkManager.cs
|
using EntitySystem.Collections;
using EntitySystem.Components.World;
using EntitySystem.Utility;
namespace EntitySystem.World
{
public class ChunkManager
{
readonly Dictionary<ChunkPos, Entity> _chunks =
new Dictionary<ChunkPos, Entity>();
public EntityManager EntityManager { get; private set; }
public ChunkManager(EntityManager entityManager)
{
EntityManager = ThrowIf.Argument.IsNull(entityManager, nameof(entityManager));
}
public BlockRef Get(BlockPos pos) => new BlockRef(this, pos);
public ChunkRef GetChunkRef(BlockPos pos) => GetChunkRef(GetChunkPos(pos));
public ChunkRef GetChunkRef(ChunkPos pos) => new ChunkRef(this, pos);
public Option<Entity> GetChunk(BlockPos pos) => GetChunk(GetChunkPos(pos));
public Option<Entity> GetChunk(ChunkPos pos) => _chunks[pos];
public Entity GetOrCreateChunk(BlockPos pos) => GetOrCreateChunk(GetChunkPos(pos));
public Entity GetOrCreateChunk(ChunkPos pos) => _chunks.GetOrAdd(pos, (_) =>
EntityManager.New(new Chunk(pos)));
public ChunkPos GetChunkPos(BlockPos pos) =>
new ChunkPos((pos.X >> Chunk.BITS), (pos.Y >> Chunk.BITS), (pos.Z >> Chunk.BITS));
public BlockPos GetChunkRelPos(BlockPos pos) =>
new BlockPos((pos.X & Chunk.FLAG), (pos.Y & Chunk.FLAG), (pos.Z & Chunk.FLAG));
}
}
|
using System.Collections.Generic;
using EntitySystem.Components.World;
using EntitySystem.Utility;
namespace EntitySystem.World
{
public class ChunkManager
{
readonly Dictionary<ChunkPos, Entity> _chunks =
new Dictionary<ChunkPos, Entity>();
public EntityManager EntityManager { get; private set; }
public ChunkManager(EntityManager entityManager)
{
EntityManager = ThrowIf.Argument.IsNull(entityManager, nameof(entityManager));
}
public BlockRef Get(BlockPos pos) => new BlockRef(this, pos);
public ChunkRef GetChunkRef(BlockPos pos) => GetChunkRef(GetChunkPos(pos));
public ChunkRef GetChunkRef(ChunkPos pos) => new ChunkRef(this, pos);
public Option<Entity> GetChunk(BlockPos pos) => GetChunk(GetChunkPos(pos));
public Option<Entity> GetChunk(ChunkPos pos) => _chunks[pos];
public Entity GetOrCreateChunk(BlockPos pos) => GetOrCreateChunk(GetChunkPos(pos));
public Entity GetOrCreateChunk(ChunkPos pos) => _chunks.GetOrAdd(pos, (_) =>
EntityManager.New(new Chunk(pos)));
public ChunkPos GetChunkPos(BlockPos pos) =>
new ChunkPos((pos.X >> Chunk.BITS), (pos.Y >> Chunk.BITS), (pos.Z >> Chunk.BITS));
public BlockPos GetChunkRelPos(BlockPos pos) =>
new BlockPos((pos.X & Chunk.FLAG), (pos.Y & Chunk.FLAG), (pos.Z & Chunk.FLAG));
}
}
|
mit
|
C#
|
d15ac2ebbb67239cf85a1f3ae0abe8ac3e43cd22
|
Update Program.cs
|
relianz/s2i-aspnet-example,relianz/s2i-aspnet-example,relianz/s2i-aspnet-example
|
app/Program.cs
|
app/Program.cs
|
// using System.Collections.Generic;
// using System.Linq;
// using System.Threading.Tasks;
using System;
using System.IO; // Directory.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace WebApplication
{
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables("")
.Build();
var url = config["ASPNETCORE_URLS"] ?? "http://*:8080";
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls(url)
.Build();
host.Run();
}
}
}
|
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Threading.Tasks;
using System.IO; // Directory.
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace WebApplication
{
public class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddEnvironmentVariables("")
.Build();
var url = config["ASPNETCORE_URLS"] ?? "http://*:8080";
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
.UseStartup<Startup>()
.UseUrls(url)
.Build();
host.Run();
}
}
}
|
apache-2.0
|
C#
|
de4d80dafdeaba928c4891eb3a09b9203d2faccb
|
Update template to display CompiledName
|
mktange/FSharp.Formatting,mktange/FSharp.Formatting,mktange/FSharp.Formatting,mktange/FSharp.Formatting,theprash/FSharp.Formatting,theprash/FSharp.Formatting,tpetricek/FSharp.Formatting,theprash/FSharp.Formatting,theprash/FSharp.Formatting,theprash/FSharp.Formatting,tpetricek/FSharp.Formatting,mktange/FSharp.Formatting,theprash/FSharp.Formatting,tpetricek/FSharp.Formatting,mktange/FSharp.Formatting,tpetricek/FSharp.Formatting,tpetricek/FSharp.Formatting,tpetricek/FSharp.Formatting
|
misc/templates/reference/part-members.cshtml
|
misc/templates/reference/part-members.cshtml
|
@if (Enumerable.Count(Model.Members) > 0) {
<h3>@Model.Header</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>@Model.TableHeader</td><td>Description</td></tr>
</thead>
<tbody>
@foreach (var it in Model.Members)
{
<tr>
<td class="member-name">
@{ var id = Html.UniqueID().ToString(); }
<code onmouseout="hideTip(event, '@id', @id)" onmouseover="showTip(event, '@id', @id)">
@Html.Encode(it.Details.FormatUsage(40))
</code>
<div class="tip" id="@id">
<strong>Signature:</strong> @Html.Encode(it.Details.Signature)<br />
@if (!it.Details.Modifiers.IsEmpty) {
<strong>Modifiers:</strong> @it.Details.FormatModifiers<br />
}
@if (!it.Details.TypeArguments.IsEmpty) {
<strong>Type parameters:</strong> @it.Details.FormatTypeArguments
}
</div>
</td>
<td class="xmldoc">
@if (!String.IsNullOrEmpty(it.Details.FormatSourceLocation))
{
<a href="@it.Details.FormatSourceLocation" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
}
@it.Comment.FullText
@if (!String.IsNullOrEmpty(it.Details.FormatCompiledName))
{
@:<p>CompiledName: <strong>@it.Details.FormatCompiledName</strong></p>
}
</td>
</tr>
}
</tbody>
</table>
}
|
@if (Enumerable.Count(Model.Members) > 0) {
<h3>@Model.Header</h3>
<table class="table table-bordered member-list">
<thead>
<tr><td>@Model.TableHeader</td><td>Description</td></tr>
</thead>
<tbody>
@foreach (var it in Model.Members)
{
<tr>
<td class="member-name">
@{ var id = Html.UniqueID().ToString(); }
<code onmouseout="hideTip(event, '@id', @id)" onmouseover="showTip(event, '@id', @id)">
@Html.Encode(it.Details.FormatUsage(40))
</code>
<div class="tip" id="@id">
<strong>Signature:</strong> @Html.Encode(it.Details.Signature)<br />
@if (!it.Details.Modifiers.IsEmpty) {
<strong>Modifiers:</strong> @it.Details.FormatModifiers<br />
}
@if (!it.Details.TypeArguments.IsEmpty) {
<strong>Type parameters:</strong> @it.Details.FormatTypeArguments
}
</div>
</td>
<td class="xmldoc">
@if (!String.IsNullOrEmpty(it.Details.FormatSourceLocation))
{
<a href="@it.Details.FormatSourceLocation" class="github-link">
<img src="../content/img/github.png" class="normal" />
<img src="../content/img/github-blue.png" class="hover" />
</a>
}
@it.Comment.FullText
</td>
</tr>
}
</tbody>
</table>
}
|
apache-2.0
|
C#
|
7a94d819c4ae39f472f7da8b8b15695bd7a82f71
|
Add missing constructors to ApiException
|
auth0/auth0.net,auth0/auth0.net
|
src/Auth0.Core/Exceptions/ApiException.cs
|
src/Auth0.Core/Exceptions/ApiException.cs
|
using System;
using System.Net;
namespace Auth0.Core.Exceptions
{
/// <summary>
/// Represents errors that occur when making API calls.
/// </summary>
public class ApiException : Exception
{
/// <summary>
/// The <see cref="Core.ApiError"/> from the response.
/// </summary>
public ApiError ApiError { get; }
/// <summary>
/// The <see cref="HttpStatusCode"/> code associated with the response.
/// </summary>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
public ApiException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public ApiException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class with a specified error message
/// and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or a null
/// reference if no inner exception is specified.</param>
public ApiException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class with a specified
/// <see cref="HttpStatusCode"/>.
/// </summary>
/// The <see cref="HttpStatusCode"/> code associated with the response.
public ApiException(HttpStatusCode statusCode)
: this(statusCode.ToString())
{
StatusCode = statusCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class with a specified
/// <see cref="HttpStatusCode"/> and <see cref="Core.ApiError"/>.
/// </summary>
/// <param name="statusCode">The status code.</param>
/// <param name="apiError">The API error.</param>
public ApiException(HttpStatusCode statusCode, ApiError apiError)
: this(apiError == null ? statusCode.ToString() : apiError.Message)
{
StatusCode = statusCode;
ApiError = apiError;
}
}
}
|
using System;
using System.Net;
namespace Auth0.Core.Exceptions
{
/// <summary>
/// Represents errors that occur when making API calls.
/// </summary>
public class ApiException : Exception
{
/// <summary>
/// The exception payload from the response
/// </summary>
public ApiError ApiError { get; }
/// <summary>
/// The HTTP status code associated with the response
/// </summary>
public HttpStatusCode StatusCode { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="message">The message.</param>
/// <param name="innerException">The inner exception.</param>
public ApiException(string message, Exception innerException)
: base(message, innerException)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="statusCode">The HTTP status code.</param>
public ApiException(HttpStatusCode statusCode)
: base(statusCode.ToString())
{
StatusCode = statusCode;
}
/// <summary>
/// Initializes a new instance of the <see cref="ApiException"/> class.
/// </summary>
/// <param name="statusCode">The status code.</param>
/// <param name="apiError">The API error.</param>
public ApiException(HttpStatusCode statusCode, ApiError apiError)
: base(apiError == null ? statusCode.ToString() : apiError.Message)
{
StatusCode = statusCode;
ApiError = apiError;
}
}
}
|
mit
|
C#
|
73f25c7eb2c78ef044db595c5f71d374593866cc
|
Revert security after applying transforms.
|
nurunquebec/Habitat,nurunquebec/Habitat,GoranHalvarsson/Habitat,GoranHalvarsson/Habitat
|
src/Foundation/Installer/code/PostStep.cs
|
src/Foundation/Installer/code/PostStep.cs
|
namespace Sitecore.Foundation.Installer
{
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Sitecore.Foundation.Installer.XmlTransform;
using Sitecore.Install;
using Sitecore.Install.Files;
using Sitecore.Install.Framework;
public class PostStep : IPostStep
{
private readonly IXdtTransformEngine xdtTransformEngine;
private readonly IFilePathResolver filePathResolver;
private readonly ITransformsProvider transformProvider;
private readonly List<string> transformsOrder = new List<string>()
{
"Foundation",
"Feature",
"Project"
};
public PostStep() : this(new XdtTransformEngine(),new FilePathResolver(), new TransformProvider())
{
}
public PostStep(IXdtTransformEngine xdtTransformEngine, IFilePathResolver filePathResolver, ITransformsProvider transformsProvider)
{
this.xdtTransformEngine = xdtTransformEngine;
this.filePathResolver = filePathResolver;
this.transformProvider = transformsProvider;
}
public void Run(ITaskOutput output, NameValueCollection metaData)
{
foreach (var transformsLayer in transformsOrder)
{
var transforms = this.transformProvider.GetTransformsByLayer(transformsLayer);
foreach (var transform in transforms)
{
var fileToTransformPath = Regex.Replace(transform, "^.*\\\\code", "~").Replace(".transform", "");
var fileToTransform = this.filePathResolver.MapPath(fileToTransformPath);
this.ApplyTransform(fileToTransform, transform, fileToTransform);
}
}
this.InstallSecurity(metaData);
}
protected void ApplyTransform(string sourceFilePath, string transformFilePath, string targetFilePath)
{
this.xdtTransformEngine.ApplyConfigTransformation(sourceFilePath, transformFilePath, targetFilePath);
}
protected void InstallSecurity(NameValueCollection metaData)
{
if (metaData != null)
{
var packageName = $"{metaData["PackageName"]}.zip";
var installer = new Installer();
var file = Installer.GetFilename(packageName);
installer.InstallSecurity(PathUtils.MapPath(file));
}
}
}
}
|
namespace Sitecore.Foundation.Installer
{
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Sitecore.Foundation.Installer.XmlTransform;
using Sitecore.Install.Framework;
public class PostStep : IPostStep
{
private readonly IXdtTransformEngine xdtTransformEngine;
private readonly IFilePathResolver filePathResolver;
private readonly ITransformsProvider transformProvider;
private readonly List<string> transformsOrder = new List<string>()
{
"Foundation",
"Feature",
"Project"
};
public PostStep() : this(new XdtTransformEngine(),new FilePathResolver(), new TransformProvider())
{
}
public PostStep(IXdtTransformEngine xdtTransformEngine, IFilePathResolver filePathResolver, ITransformsProvider transformsProvider)
{
this.xdtTransformEngine = xdtTransformEngine;
this.filePathResolver = filePathResolver;
this.transformProvider = transformsProvider;
}
public void Run(ITaskOutput output, NameValueCollection metaData)
{
foreach (var transformsLayer in transformsOrder)
{
var transforms = this.transformProvider.GetTransformsByLayer(transformsLayer);
foreach (var transform in transforms)
{
var fileToTransformPath = Regex.Replace(transform, "^.*\\\\code", "~").Replace(".transform", "");
Diagnostics.Log.Warn($"{transform} - {fileToTransformPath}", this);
var fileToTransform = this.filePathResolver.MapPath(fileToTransformPath);
this.ApplyTransform(fileToTransform, transform, fileToTransform);
}
}
}
protected void ApplyTransform(string sourceFilePath, string transformFilePath, string targetFilePath)
{
this.xdtTransformEngine.ApplyConfigTransformation(sourceFilePath, transformFilePath, targetFilePath);
}
}
}
|
apache-2.0
|
C#
|
fc9676c6c2934865b5c7b3ff93817a935473b612
|
Add new line after each question
|
TeamGameFifteen2AtTelerikAcademy/Game-Fifteen
|
src/GameFifteen.Logic/Common/Constants.cs
|
src/GameFifteen.Logic/Common/Constants.cs
|
namespace GameFifteen.Logic.Common
{
using System;
public static class Constants
{
// Validator
public const string ArgumentName = "Argument name";
public const string CannotBeNullFormat = "{0} cannot be null!";
// Matrix
public const string HorizontalBorder = " -------------";
public const string VerticalBorder = "|";
// Scoreboard
public const string Scoreboard = "Scoreboard:";
public const string ScoreboardIsEmpty = "Scoreboard is empty";
public const string ScoreboardFormat = "{0}. {1} --> {2} moves";
public const int ScoreboardMaxCount = 5;
// GameInitializator
public const string TileTypeQuestion = "What type of tiles would you like?\n\rNumber or Letter: ";
public const string PatternTypeQuestion = "What type of pattern would you like?\n\rClassic or Column: ";
public const string MoverTypesQuestion = "How would you like to move the tiles?\n\rClassic or RowCol: ";
public const string RowsQuestion = "How many rows would you like? ";
public const string ColsQuestion = "How many cols would you like? ";
// User messages
public const string EnterCommandMessage = "Enter a number to move: ";
public const string InvalidCommandMessage = "Invalid command!";
public const string InvalidMoveMessage = "Invalid move!";
public const string CongratulationsMessageFormat = "Congratulations! You won the game in {0} moves.";
public const string EnterNameMessage = "Please, enter your name for the top scoreboard: ";
public const string GoodbyeMessage = "Good bye!";
public static readonly string WellcomeMessage =
"Welcome to the game “15”. Please try to arrange the numbers sequentially." + Environment.NewLine +
"Use 'Top' to view the top scoreboard, 'Restart' to start a new game and" + Environment.NewLine +
"'Exit' to quit the game.";
// Convertor
public const int EnglishAlphabetLettersCount = 26;
}
}
|
namespace GameFifteen.Logic.Common
{
using System;
public static class Constants
{
// Validator
public const string ArgumentName = "Argument name";
public const string CannotBeNullFormat = "{0} cannot be null!";
// Matrix
public const string HorizontalBorder = " -------------";
public const string VerticalBorder = "|";
// Scoreboard
public const string Scoreboard = "Scoreboard:";
public const string ScoreboardIsEmpty = "Scoreboard is empty";
public const string ScoreboardFormat = "{0}. {1} --> {2} moves";
public const int ScoreboardMaxCount = 5;
// GameInitializator
public const string TileTypeQuestion = "What type of tiles would you like: Number or Letter: ";
public const string PatternTypeQuestion = "What type of pattern would you like: Classic or Column: ";
public const string MoverTypesQuestion = "How would you like to move the tiles: Classic or RowCol: ";
public const string RowsQuestion = "How many rows would you like: ";
public const string ColsQuestion = "How many cols would you like: ";
// User messages
public const string EnterCommandMessage = "Enter a number to move: ";
public const string InvalidCommandMessage = "Invalid command!";
public const string InvalidMoveMessage = "Invalid move!";
public const string CongratulationsMessageFormat = "Congratulations! You won the game in {0} moves.";
public const string EnterNameMessage = "Please, enter your name for the top scoreboard: ";
public const string GoodbyeMessage = "Good bye!";
public static readonly string WellcomeMessage =
"Welcome to the game “15”. Please try to arrange the numbers sequentially." + Environment.NewLine +
"Use 'Top' to view the top scoreboard, 'Restart' to start a new game and" + Environment.NewLine +
"'Exit' to quit the game.";
// Convertor
public const int EnglishAlphabetLettersCount = 26;
}
}
|
mit
|
C#
|
734d4e553f1989958f7c074cb7820f10ee1f5be1
|
Update Assembly Versions
|
KallynGowdy/LINDI
|
src/LINDI.Core/Properties/AssemblyInfo.cs
|
src/LINDI.Core/Properties/AssemblyInfo.cs
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LINDI.Core")]
[assembly: AssemblyDescription("Language Integrated Dependency Injection")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LINDI.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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("b07602f9-109b-4e41-9c5a-c5e0e4c9b6e8")]
// 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.1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
using System;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("LINDI.Core")]
[assembly: AssemblyDescription("Language Integrated Dependency Injection")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LINDI.Core")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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("b07602f9-109b-4e41-9c5a-c5e0e4c9b6e8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
apache-2.0
|
C#
|
e91e723bbbfdce87afde5a5ce0f7d186dd9babd5
|
Bump version
|
rabbit-link/rabbit-link,rabbit-link/rabbit-link
|
src/RabbitLink/Properties/AssemblyInfo.cs
|
src/RabbitLink/Properties/AssemblyInfo.cs
|
#region Usings
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("RabbitLink")]
[assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RabbitLink")]
[assembly: AssemblyCopyright("Copyright © Artur Kraev 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b2148830-a507-44a5-bc99-efda7f36e21d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.6.0")]
[assembly: AssemblyFileVersion("0.2.6.0")]
|
#region Usings
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("RabbitLink")]
[assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RabbitLink")]
[assembly: AssemblyCopyright("Copyright © Artur Kraev 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("b2148830-a507-44a5-bc99-efda7f36e21d")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.2.5.0")]
[assembly: AssemblyFileVersion("0.2.5.0")]
|
mit
|
C#
|
965e27ffa288c7f756cf5c1a30f3c26736761a6a
|
Fix merge conflict
|
serenabenny/Caliburn.Micro,Caliburn-Micro/Caliburn.Micro
|
samples/setup/Setup.WPF/Properties/Settings.Designer.cs
|
samples/setup/Setup.WPF/Properties/Settings.Designer.cs
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Setup.WPF.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.10.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Setup.WPF.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
|
mit
|
C#
|
30e17a26eebbc5d225963b8320733ab9fc3f3def
|
Fix DeviceFamilyService Bug
|
janabimustafa/waslibs,wasteam/waslibs,janabimustafa/waslibs,pellea/waslibs,wasteam/waslibs,wasteam/waslibs,janabimustafa/waslibs,pellea/waslibs,pellea/waslibs
|
src/AppStudio.Uwp/Services/DeviceFamilyService.cs
|
src/AppStudio.Uwp/Services/DeviceFamilyService.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
namespace AppStudio.Uwp.Services
{
public static class DeviceFamilyService
{
private static IObservableMap<String, String> _qualifierValues;
private static IObservableMap<String, String> QualifierValues
{
get
{
if (_qualifierValues == null)
{
_qualifierValues = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;
}
return _qualifierValues;
}
}
public static bool IsMobile
{
get
{
return QualifierValues.ContainsKey("DeviceFamily") && QualifierValues["DeviceFamily"].ToLowerInvariant() == "Mobile".ToLowerInvariant();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Foundation.Collections;
namespace AppStudio.Uwp.Services
{
public static class DeviceFamilyService
{
private static IObservableMap<String, String> _qualifierValues;
private static IObservableMap<String, String> QualifierValues
{
get
{
return _qualifierValues;
}
}
public static bool IsMobile
{
get
{
return QualifierValues.ContainsKey("DeviceFamily") && QualifierValues["DeviceFamily"].ToLowerInvariant() == "Mobile".ToLowerInvariant();
}
}
}
}
|
mit
|
C#
|
54d71af00dee23f67183d48c01e23ac1cc55fac8
|
Add example for UserLoginInfo's ProviderDisplayName property (#19357)
|
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
|
src/Identity/Extensions.Core/src/UserLoginInfo.cs
|
src/Identity/Extensions.Core/src/UserLoginInfo.cs
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// Represents login information and source for a user record.
/// </summary>
public class UserLoginInfo
{
/// <summary>
/// Creates a new instance of <see cref="UserLoginInfo"/>
/// </summary>
/// <param name="loginProvider">The provider associated with this login information.</param>
/// <param name="providerKey">The unique identifier for this user provided by the login provider.</param>
/// <param name="displayName">The display name for this user provided by the login provider.</param>
public UserLoginInfo(string loginProvider, string providerKey, string displayName)
{
LoginProvider = loginProvider;
ProviderKey = providerKey;
ProviderDisplayName = displayName;
}
/// <summary>
/// Gets or sets the provider for this instance of <see cref="UserLoginInfo"/>.
/// </summary>
/// <value>The provider for the this instance of <see cref="UserLoginInfo"/></value>
/// <remarks>
/// Examples of the provider may be Local, Facebook, Google, etc.
/// </remarks>
public string LoginProvider { get; set; }
/// <summary>
/// Gets or sets the unique identifier for the user identity user provided by the login provider.
/// </summary>
/// <value>
/// The unique identifier for the user identity user provided by the login provider.
/// </value>
/// <remarks>
/// This would be unique per provider, examples may be @microsoft as a Twitter provider key.
/// </remarks>
public string ProviderKey { get; set; }
/// <summary>
/// Gets or sets the display name for the provider.
/// </summary>
/// <value>
/// The display name for the provider.
/// </value>
/// <remarks>
/// Examples of the display name may be local, FACEBOOK, Google, etc.
/// </remarks>
public string ProviderDisplayName { get; set; }
}
}
|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
namespace Microsoft.AspNetCore.Identity
{
/// <summary>
/// Represents login information and source for a user record.
/// </summary>
public class UserLoginInfo
{
/// <summary>
/// Creates a new instance of <see cref="UserLoginInfo"/>
/// </summary>
/// <param name="loginProvider">The provider associated with this login information.</param>
/// <param name="providerKey">The unique identifier for this user provided by the login provider.</param>
/// <param name="displayName">The display name for this user provided by the login provider.</param>
public UserLoginInfo(string loginProvider, string providerKey, string displayName)
{
LoginProvider = loginProvider;
ProviderKey = providerKey;
ProviderDisplayName = displayName;
}
/// <summary>
/// Gets or sets the provider for this instance of <see cref="UserLoginInfo"/>.
/// </summary>
/// <value>The provider for the this instance of <see cref="UserLoginInfo"/></value>
/// <remarks>
/// Examples of the provider may be Local, Facebook, Google, etc.
/// </remarks>
public string LoginProvider { get; set; }
/// <summary>
/// Gets or sets the unique identifier for the user identity user provided by the login provider.
/// </summary>
/// <value>
/// The unique identifier for the user identity user provided by the login provider.
/// </value>
/// <remarks>
/// This would be unique per provider, examples may be @microsoft as a Twitter provider key.
/// </remarks>
public string ProviderKey { get; set; }
/// <summary>
/// Gets or sets the display name for the provider.
/// </summary>
/// <value>
/// The display name for the provider.
/// </value>
public string ProviderDisplayName { get; set; }
}
}
|
apache-2.0
|
C#
|
84eda5877d3376eedd58b7ffc385e00ebc8e6e3d
|
Update StrictTransportSecurityAttribute.
|
ivanra/mvcextras,ivanra/mvcextras
|
src/MvcExtras/StrictTransportSecurityAttribute.cs
|
src/MvcExtras/StrictTransportSecurityAttribute.cs
|
using System;
using System.Web.Mvc;
namespace MvcExtras
{
/// <summary>
/// StrictTransportSecurityAttribute -- render Strict-Transport-Security HTTP header on response (as per RFC 6797: http://tools.ietf.org/html/rfc6797)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class StrictTransportSecurityAttribute : FilterAttribute, IResultFilter
{
private const string StrictTransportPolicyHeader = "Strict-Transport-Security";
private const int DefaultMaxAge = 60;
public StrictTransportSecurityAttribute()
{
MaxAge = DefaultMaxAge;
}
public int MaxAge { get; set; }
public bool IncludeSubdomains { get; set; }
public void OnResultExecuting(ResultExecutingContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");
//if (!filterContext.HttpContext.Request.IsSecureConnection)
// return;
var headerValue = String.Format("max-age={0}{1}", MaxAge,
IncludeSubdomains ? "; includeSubDomains" : String.Empty);
filterContext.HttpContext.Response.AddHeader(StrictTransportPolicyHeader, headerValue);
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
}
|
using System;
using System.Web.Mvc;
namespace MvcExtras
{
/// <summary>
/// StrictTransportSecurityAttribute -- render Strict-Transport-Security HTTP header on response (as per RFC 6797: http://tools.ietf.org/html/rfc6797)
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class StrictTransportSecurityAttribute : FilterAttribute, IResultFilter
{
private const string StrictTransportPolicyHeader = "Strict-Transport-Security";
private const int DefaultMaxAge = 60;
public StrictTransportSecurityAttribute()
{
MaxAge = DefaultMaxAge;
}
public int MaxAge { get; set; }
public bool IncludeSubdomains { get; set; }
public void OnResultExecuting(ResultExecutingContext filterContext)
{
if (filterContext == null)
throw new ArgumentNullException("filterContext");
//if (filterContext.HttpContext.Request.IsSecureConnection)
// return;
var headerValue = String.Format("max-age={0}{1}", MaxAge,
IncludeSubdomains ? "; includeSubDomains" : String.Empty);
filterContext.HttpContext.Response.AddHeader(StrictTransportPolicyHeader, headerValue);
}
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
}
}
|
mit
|
C#
|
38a64a41d589ea5e7f49993b82c0335f4614df78
|
Fix indexed attachments index
|
ravendb/ravendb.contrib
|
src/Raven.Bundles.Contrib.IndexedAttachments/Startup.cs
|
src/Raven.Bundles.Contrib.IndexedAttachments/Startup.cs
|
using System.ComponentModel.Composition;
using Raven.Abstractions.Indexing;
using Raven.Database;
using Raven.Database.Plugins;
namespace Raven.Bundles.IndexedAttachments
{
[InheritedExport(typeof(IStartupTask))]
[ExportMetadata("Bundle", "IndexedAttachments")]
public class Startup : IStartupTask
{
public void Execute(DocumentDatabase database)
{
if (!database.IsBundleActive("IndexedAttachments"))
return;
var index = new IndexDefinition
{
Map = @"from doc in docs
where doc[""@metadata""][""Raven-Attachment-Key""] != null
select new
{
AttachmentKey = doc[""@metadata""][""Raven-Attachment-Key""],
Filename = doc[""@metadata""][""Raven-Attachment-Filename""],
Text = doc.Text
}",
TransformResults = @"from result in results
select new
{
AttachmentKey = result[""@metadata""][""Raven-Attachment-Key""],
Filename = result[""@metadata""][""Raven-Attachment-Filename""]
}"
};
// NOTE: The transform above is specifically there to keep the Text property
// from being returned. The results could get very large otherwise.
index.Indexes.Add("Text", FieldIndexing.Analyzed);
index.Stores.Add("Text", FieldStorage.Yes);
index.TermVectors.Add("Text", FieldTermVector.WithPositionsAndOffsets);
database.PutIndex("Raven/Attachments", index);
}
}
}
|
using System.ComponentModel.Composition;
using Raven.Abstractions.Indexing;
using Raven.Database;
using Raven.Database.Plugins;
namespace Raven.Bundles.IndexedAttachments
{
[InheritedExport(typeof(IStartupTask))]
[ExportMetadata("Bundle", "IndexedAttachments")]
public class Startup : IStartupTask
{
public void Execute(DocumentDatabase database)
{
if (!database.IsBundleActive("IndexedAttachments"))
return;
var index = new IndexDefinition
{
Map = @"from doc in docs
where doc[""@metadata""][""Raven-Attachment-Key""] != null
select new
{
AttachmentKey = doc[""@metadata""][""Raven-Attachment-Key""],
Filename = doc[""@metadata""][""Raven-Attachment-Filename""],
Text = doc.Text
}",
TransformResults = @"from result in results
select new
{
AttachmentKey = result[""@metadata""][""Raven-Attachment-Key""],
Filename = result[""@metadata""][""Raven-Attachment-Filename""]
}"
};
// NOTE: The transform above is specifically there to keep the Text property
// from being returned. The results could get very large otherwise.
index.Indexes.Add("Text", FieldIndexing.Analyzed);
index.Stores.Add("Text", FieldStorage.Yes);
if (database.GetIndexDefinition("Raven/Attachments") == null)
database.PutIndex("Raven/Attachments", index);
}
}
}
|
mit
|
C#
|
9b756b9ce6ed06117ee181fbf3c91935bb82cdc8
|
Fix components
|
marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,lars-erik/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,NikRimington/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,lars-erik/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS
|
src/Umbraco.Core/Components/ManifestWatcherComponent.cs
|
src/Umbraco.Core/Components/ManifestWatcherComponent.cs
|
using System;
using System.IO;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
namespace Umbraco.Core.Components
{
public class ManifestWatcherComponent : IComponent, IDisposable
{
// if configured and in debug mode, a ManifestWatcher watches App_Plugins folders for
// package.manifest chances and restarts the application on any change
private ManifestWatcher _mw;
public ManifestWatcherComponent(IRuntimeState runtimeState, ILogger logger)
{
if (runtimeState.Debug == false) return;
//if (ApplicationContext.Current.IsConfigured == false || GlobalSettings.DebugMode == false)
// return;
var appPlugins = IOHelper.MapPath("~/App_Plugins/");
if (Directory.Exists(appPlugins) == false) return;
_mw = new ManifestWatcher(logger);
_mw.Start(Directory.GetDirectories(appPlugins));
}
public void Dispose()
{
if (_mw == null) return;
_mw.Dispose();
_mw = null;
}
}
}
|
using System.IO;
using Umbraco.Core.IO;
using Umbraco.Core.Logging;
using Umbraco.Core.Manifest;
namespace Umbraco.Core.Components
{
public class ManifestWatcherComponent : IComponent
{
// if configured and in debug mode, a ManifestWatcher watches App_Plugins folders for
// package.manifest chances and restarts the application on any change
private ManifestWatcher _mw;
public ManifestWatcherComponent(IRuntimeState runtimeState, ILogger logger)
{
if (runtimeState.Debug == false) return;
//if (ApplicationContext.Current.IsConfigured == false || GlobalSettings.DebugMode == false)
// return;
var appPlugins = IOHelper.MapPath("~/App_Plugins/");
if (Directory.Exists(appPlugins) == false) return;
_mw = new ManifestWatcher(logger);
_mw.Start(Directory.GetDirectories(appPlugins));
}
public void Terminate()
{
_mw?.Dispose();
_mw = null;
}
}
}
|
mit
|
C#
|
618455f7ba3496591bc8ea2e8859e7ae74de3328
|
Remove exit step (needs login to show properly)
|
2yangk23/osu,ppy/osu,johnneijzen/osu,naoey/osu,smoogipoo/osu,DrabWeb/osu,DrabWeb/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,EVAST9919/osu,peppy/osu-new,naoey/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,peppy/osu,ZLima12/osu,naoey/osu,NeoAdonis/osu,UselessToucan/osu,ZLima12/osu,DrabWeb/osu,ppy/osu
|
osu.Game.Tests/Visual/TestCaseMultiScreen.cs
|
osu.Game.Tests/Visual/TestCaseMultiScreen.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Game.Screens.Multi;
using osu.Game.Screens.Multi.Lounge;
using osu.Game.Screens.Multi.Lounge.Components;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseMultiScreen : ScreenTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(Multiplayer),
typeof(LoungeSubScreen),
typeof(FilterControl)
};
public TestCaseMultiScreen()
{
Multiplayer multi = new Multiplayer();
AddStep(@"show", () => LoadScreen(multi));
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Screens;
using osu.Game.Screens.Multi;
using osu.Game.Screens.Multi.Lounge;
using osu.Game.Screens.Multi.Lounge.Components;
namespace osu.Game.Tests.Visual
{
[TestFixture]
public class TestCaseMultiScreen : ScreenTestCase
{
public override IReadOnlyList<Type> RequiredTypes => new[]
{
typeof(Multiplayer),
typeof(LoungeSubScreen),
typeof(FilterControl)
};
public TestCaseMultiScreen()
{
Multiplayer multi = new Multiplayer();
AddStep(@"show", () => LoadScreen(multi));
AddUntilStep(() => multi.IsCurrentScreen(), "wait until current");
AddStep(@"exit", multi.Exit);
}
}
}
|
mit
|
C#
|
b7e7b0f850766a568e1e08aa985826402f27d1cb
|
Trim whitespace.
|
peppy/osu,NeoAdonis/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu
|
osu.Game/Overlays/Settings/SettingsHeader.cs
|
osu.Game/Overlays/Settings/SettingsHeader.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Settings
{
public class SettingsHeader : Container
{
private readonly LocalisableString heading;
private readonly LocalisableString subheading;
public SettingsHeader(LocalisableString heading, LocalisableString subheading)
{
this.heading = heading;
this.subheading = subheading;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Children = new Drawable[]
{
new OsuTextFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding
{
Left = SettingsPanel.CONTENT_MARGINS,
Top = Toolbar.Toolbar.TOOLTIP_HEIGHT,
Bottom = 30
}
}.With(flow =>
{
flow.AddText(heading, header => header.Font = OsuFont.TorusAlternate.With(size: 40));
flow.NewLine();
flow.AddText(subheading, subheader =>
{
subheader.Colour = colourProvider.Content2;
subheader.Font = OsuFont.GetFont(size: 18);
});
})
};
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
namespace osu.Game.Overlays.Settings
{
public class SettingsHeader : Container
{
private readonly LocalisableString heading;
private readonly LocalisableString subheading;
public SettingsHeader(LocalisableString heading, LocalisableString subheading)
{
this.heading = heading;
this.subheading = subheading;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider)
{
RelativeSizeAxes = Axes.X;
AutoSizeAxes = Axes.Y;
Children = new Drawable[]
{
new OsuTextFlowContainer
{
AutoSizeAxes = Axes.Y,
RelativeSizeAxes = Axes.X,
Margin = new MarginPadding
{
Left = SettingsPanel.CONTENT_MARGINS,
Top = Toolbar.Toolbar.TOOLTIP_HEIGHT,
Bottom = 30
}
}.With(flow =>
{
flow.AddText(heading, header => header.Font = OsuFont.TorusAlternate.With(size: 40));
flow.NewLine();
flow.AddText(subheading, subheader =>
{
subheader.Colour = colourProvider.Content2;
subheader.Font = OsuFont.GetFont(size: 18);
});
})
};
}
}
}
|
mit
|
C#
|
4e600d096c23f27607097856edde9cece9aee454
|
Fix /n strings in Forms demo page
|
jamesmontemagno/ConnectivityPlugin,jamesmontemagno/ConnectivityPlugin
|
tests/app/ConnectivityTest/ConnectivityTestPage.xaml.cs
|
tests/app/ConnectivityTest/ConnectivityTestPage.xaml.cs
|
using Xamarin.Forms;
using Plugin.Connectivity;
using System.Linq;
namespace ConnectivityTest
{
public partial class ConnectivityTestPage : ContentPage
{
public ConnectivityTestPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
await DisplayAlert("Is Connected", CrossConnectivity.Current.IsConnected ? "YES" : "NO", "OK");
}
void HandleStart_Clicked(object sender, System.EventArgs e)
{
//CrossConnectivity.Current.ConnectivityChanged += Current_ConnectivityChanged;
CrossConnectivity.Current.ConnectivityTypeChanged += Current_ConnectivityTypeChanged;
}
void HandleStop_Clicked(object sender, System.EventArgs e)
{
//CrossConnectivity.Current.ConnectivityChanged -= Current_ConnectivityChanged;
CrossConnectivity.Current.ConnectivityTypeChanged -= Current_ConnectivityTypeChanged;
}
async void HandleIsConnected_Clicked(object sender, System.EventArgs e)
{
await DisplayAlert("Is Connected", CrossConnectivity.Current.IsConnected ? "YES" : "NO", "OK");
}
void Current_ConnectivityChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Is Connected", e.IsConnected ? "YES" : "NO", "OK");
});
}
void Current_ConnectivityTypeChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityTypeChangedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
var stuff = string.Empty;
foreach (var i in e.ConnectionTypes)
stuff += "\n" + i.ToString();
await DisplayAlert("Is Connected", (e.IsConnected ? "YES" : "NO") + stuff, "OK");
});
}
async void Types_Clicked(object sender, System.EventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
var stuff = string.Empty;
foreach (var i in CrossConnectivity.Current.ConnectionTypes)
stuff += "\n" + i.ToString();
await DisplayAlert("Is Connected", (CrossConnectivity.Current.IsConnected ? "YES" : "NO") + stuff, "OK");
});
}
}
}
|
using Xamarin.Forms;
using Plugin.Connectivity;
using System.Linq;
namespace ConnectivityTest
{
public partial class ConnectivityTestPage : ContentPage
{
public ConnectivityTestPage()
{
InitializeComponent();
}
protected override async void OnAppearing()
{
base.OnAppearing();
await DisplayAlert("Is Connected", CrossConnectivity.Current.IsConnected ? "YES" : "NO", "OK");
}
void HandleStart_Clicked(object sender, System.EventArgs e)
{
//CrossConnectivity.Current.ConnectivityChanged += Current_ConnectivityChanged;
CrossConnectivity.Current.ConnectivityTypeChanged += Current_ConnectivityTypeChanged;
}
void HandleStop_Clicked(object sender, System.EventArgs e)
{
//CrossConnectivity.Current.ConnectivityChanged -= Current_ConnectivityChanged;
CrossConnectivity.Current.ConnectivityTypeChanged -= Current_ConnectivityTypeChanged;
}
async void HandleIsConnected_Clicked(object sender, System.EventArgs e)
{
await DisplayAlert("Is Connected", CrossConnectivity.Current.IsConnected ? "YES" : "NO", "OK");
}
void Current_ConnectivityChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
await DisplayAlert("Is Connected", e.IsConnected ? "YES" : "NO", "OK");
});
}
void Current_ConnectivityTypeChanged(object sender, Plugin.Connectivity.Abstractions.ConnectivityTypeChangedEventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
var stuff = string.Empty;
foreach (var i in e.ConnectionTypes)
stuff += "/n" + i.ToString();
await DisplayAlert("Is Connected", (e.IsConnected ? "YES" : "NO") + stuff, "OK");
});
}
async void Types_Clicked(object sender, System.EventArgs e)
{
Device.BeginInvokeOnMainThread(async () =>
{
var stuff = string.Empty;
foreach (var i in CrossConnectivity.Current.ConnectionTypes)
stuff += "/n" + i.ToString();
await DisplayAlert("Is Connected", (CrossConnectivity.Current.IsConnected ? "YES" : "NO") + stuff, "OK");
});
}
}
}
|
mit
|
C#
|
275770dc783a9bda2422badbe76bfff244cdee87
|
Remove confined cursor
|
NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare
|
Assets/Scripts/Global/GameController.cs
|
Assets/Scripts/Global/GameController.cs
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;
public class GameController : MonoBehaviour
{
public static GameController instance;
#pragma warning disable 0649
[SerializeField]
private bool disableCursor;
[SerializeField]
private MicrogameCollection _microgameCollection;
[SerializeField]
private SceneShifter _sceneShifter;
[SerializeField]
private Sprite[] controlSprites;
[SerializeField]
private UnityEvent onSceneLoad;
#pragma warning restore 0649
private string startScene;
public MicrogameCollection microgameCollection
{
get { return _microgameCollection; }
}
public SceneShifter sceneShifter
{
get { return _sceneShifter; }
}
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
startScene = gameObject.scene.name;
DontDestroyOnLoad(transform.gameObject);
instance = this;
Cursor.visible = !disableCursor;
//Cursor.lockState = CursorLockMode.Confined;
Application.targetFrameRate = 60;
AudioListener.pause = false;
SceneManager.sceneLoaded += onSceneLoaded;
}
private void Update()
{
//Debug features
if (Debug.isDebugBuild)
{
//Shift+R to reset all prefs
if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.R))
PlayerPrefs.DeleteAll();
}
}
void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (PauseManager.exitedWhilePaused)
{
AudioListener.pause = false;
Time.timeScale = 1f;
PauseManager.exitedWhilePaused = false;
Cursor.visible = true;
}
onSceneLoad.Invoke();
}
public Sprite getControlSprite(MicrogameTraits.ControlScheme controlScheme)
{
return controlSprites[(int)controlScheme];
}
public string getStartScene()
{
return startScene;
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.Events;
using System.Collections;
public class GameController : MonoBehaviour
{
public static GameController instance;
#pragma warning disable 0649
[SerializeField]
private bool disableCursor;
[SerializeField]
private MicrogameCollection _microgameCollection;
[SerializeField]
private SceneShifter _sceneShifter;
[SerializeField]
private Sprite[] controlSprites;
[SerializeField]
private UnityEvent onSceneLoad;
#pragma warning restore 0649
private string startScene;
public MicrogameCollection microgameCollection
{
get { return _microgameCollection; }
}
public SceneShifter sceneShifter
{
get { return _sceneShifter; }
}
void Awake()
{
if (instance != null)
{
Destroy(gameObject);
return;
}
startScene = gameObject.scene.name;
DontDestroyOnLoad(transform.gameObject);
instance = this;
Cursor.visible = !disableCursor;
Cursor.lockState = CursorLockMode.Confined;
Application.targetFrameRate = 60;
AudioListener.pause = false;
SceneManager.sceneLoaded += onSceneLoaded;
}
private void Update()
{
//Debug features
if (Debug.isDebugBuild)
{
//Shift+R to reset all prefs
if ((Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) && Input.GetKeyDown(KeyCode.R))
PlayerPrefs.DeleteAll();
}
}
void onSceneLoaded(Scene scene, LoadSceneMode mode)
{
if (PauseManager.exitedWhilePaused)
{
AudioListener.pause = false;
Time.timeScale = 1f;
PauseManager.exitedWhilePaused = false;
Cursor.visible = true;
}
onSceneLoad.Invoke();
}
public Sprite getControlSprite(MicrogameTraits.ControlScheme controlScheme)
{
return controlSprites[(int)controlScheme];
}
public string getStartScene()
{
return startScene;
}
}
|
mit
|
C#
|
f92e47144ab8b50ce87abfc1231e81255480cc67
|
Fix unable to upload blocks if the world smaller than the area
|
Yonom/BotBits,Tunous/BotBits,EEJesse/BotBits
|
BotBits/Packages/Blocks/BlockAreaEnumerableExtensions.cs
|
BotBits/Packages/Blocks/BlockAreaEnumerableExtensions.cs
|
using System;
namespace BotBits
{
public static class BlockAreaEnumerableExtensions
{
public static BlockAreaEnumerable In(this IBlockAreaEnumerable blockArea, Rectangle area)
{
return new BlockAreaEnumerable(blockArea.Blocks,
Rectangle.Intersect(area, blockArea.Area));
}
public static BlockAreaEnumerable In(this IBlockAreaEnumerable blockArea, Point p1, Point p2)
{
return blockArea.In(new Rectangle(p1, p2));
}
public static BlockAreaEnumerable In(this IBlockAreaEnumerable blockArea, int x, int y, int width, int height)
{
return blockArea.In(new Rectangle(x, y, width, height));
}
public static World CreateCopy(this IBlockAreaEnumerable blockArea)
{
var area = blockArea.Area;
var world = new World(area.Width, area.Height);
for (var x = area.Left; x <= area.Right; x++)
for (var y = area.Top; y <= area.Bottom; y++)
{
world.Foreground[x - area.Left, y - area.Top] = blockArea.Blocks.Foreground[x, y].Block;
world.Background[x - area.Left, y - area.Top] = blockArea.Blocks.Background[x, y].Block;
}
return world;
}
public static void UploadWorld(this IBlockAreaEnumerable blockArea, World world)
{
var area = blockArea.Area;
if (world.Width > area.Width || world.Height > area.Height)
throw new ArgumentException("The world is too big for this area.", "world");
for (var y = area.Top; y < area.Top + world.Height; y++)
for (var x = area.Left; x < area.Left + world.Width; x++)
{
blockArea.Blocks.Place(x, y, world.Foreground[x - area.Left, y - area.Top]);
blockArea.Blocks.Place(x, y, world.Background[x - area.Left, y - area.Top]);
}
}
}
}
|
using System;
namespace BotBits
{
public static class BlockAreaEnumerableExtensions
{
public static BlockAreaEnumerable In(this IBlockAreaEnumerable blockArea, Rectangle area)
{
return new BlockAreaEnumerable(blockArea.Blocks,
Rectangle.Intersect(area, blockArea.Area));
}
public static BlockAreaEnumerable In(this IBlockAreaEnumerable blockArea, Point p1, Point p2)
{
return blockArea.In(new Rectangle(p1, p2));
}
public static BlockAreaEnumerable In(this IBlockAreaEnumerable blockArea, int x, int y, int width, int height)
{
return blockArea.In(new Rectangle(x, y, width, height));
}
public static World CreateCopy(this IBlockAreaEnumerable blockArea)
{
var area = blockArea.Area;
var world = new World(area.Width, area.Height);
for (var x = area.Left; x <= area.Right; x++)
for (var y = area.Top; y <= area.Bottom; y++)
{
world.Foreground[x - area.Left, y - area.Top] = blockArea.Blocks.Foreground[x, y].Block;
world.Background[x - area.Left, y - area.Top] = blockArea.Blocks.Background[x, y].Block;
}
return world;
}
public static void UploadWorld(this IBlockAreaEnumerable blockArea, World world)
{
var area = blockArea.Area;
if (world.Width > area.Width || world.Height > area.Height)
throw new ArgumentException("The world is too big for this area.", "world");
for (var y = area.Top; y <= area.Bottom; y++)
for (var x = area.Left; x <= area.Right; x++)
{
blockArea.Blocks.Place(x, y, world.Foreground[x - area.Left, y - area.Top]);
blockArea.Blocks.Place(x, y, world.Background[x - area.Left, y - area.Top]);
}
}
}
}
|
mit
|
C#
|
83efa19758fa40a478c85ba911e5d954f7d6cb36
|
update at TcpClientNode class, try to directly parse ip address before performing host resolution
|
DarkCaster/DotNetBlocks,DarkCaster/DotNetBlocks
|
CustomBlocks/DataTransfer/Tcp/Client/TcpClientNode.cs
|
CustomBlocks/DataTransfer/Tcp/Client/TcpClientNode.cs
|
// TcpClientNode.cs
//
// The MIT License (MIT)
//
// Copyright (c) 2017 DarkCaster <dark.caster@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using DarkCaster.DataTransfer.Config;
namespace DarkCaster.DataTransfer.Client.Tcp
{
public sealed class TcpClientNode : INode
{
public async Task<ITunnel> OpenTunnelAsync(ITunnelConfig config)
{
var host = config.Get<string>("remote_host");
var port = config.Get<int>("remote_port");
if(string.IsNullOrEmpty(host))
throw new Exception("failed to get remote connection address from \"remote_host\" config parameter");
if(port==0)
throw new Exception("failed to get remote connection port from \"remote_port\" config parameter");
//open tcp connection
if(!IPAddress.TryParse(host, out IPAddress addr))
addr = (await Dns.GetHostEntryAsync(host)).AddressList[0];
var nodelay = config.Get<bool>("tcp_nodelay");
var bufferSize = config.Get<int>("tcp_buffer_size");
var client = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
await Task.Factory.FromAsync(
(callback, state) => client.BeginConnect(new IPEndPoint(addr, port), callback, state),
client.EndConnect, null).ConfigureAwait(false);
//apply some optional settings to socket
client.NoDelay = nodelay;
client.LingerState = new LingerOption(true, 0);
if (bufferSize > 0)
{
client.ReceiveBufferSize = bufferSize;
client.SendBufferSize = bufferSize;
config.Set("buff_size", bufferSize);
}
else
config.Set("buff_size", client.ReceiveBufferSize);
}
catch
{
client.Dispose();
throw;
}
//create and return new itunnel object with this tcp connection
return new TcpClientTunnel(client);
}
}
}
|
// TcpClientNode.cs
//
// The MIT License (MIT)
//
// Copyright (c) 2017 DarkCaster <dark.caster@outlook.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using DarkCaster.DataTransfer.Config;
namespace DarkCaster.DataTransfer.Client.Tcp
{
public sealed class TcpClientNode : INode
{
public async Task<ITunnel> OpenTunnelAsync(ITunnelConfig config)
{
var host = config.Get<string>("remote_host");
var port = config.Get<int>("remote_port");
if(string.IsNullOrEmpty(host))
throw new Exception("failed to get remote connection address from \"remote_host\" config parameter");
if(port==0)
throw new Exception("failed to get remote connection port from \"remote_port\" config parameter");
//open tcp connection
var addr = Dns.GetHostEntry(host).AddressList[0];
var nodelay = config.Get<bool>("tcp_nodelay");
var bufferSize = config.Get<int>("tcp_buffer_size");
var client = new Socket(addr.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
try
{
await Task.Factory.FromAsync(
(callback, state) => client.BeginConnect(new IPEndPoint(addr, port), callback, state),
client.EndConnect, null).ConfigureAwait(false);
//apply some optional settings to socket
client.NoDelay = nodelay;
client.LingerState = new LingerOption(true, 0);
if (bufferSize > 0)
{
client.ReceiveBufferSize = bufferSize;
client.SendBufferSize = bufferSize;
config.Set("buff_size", bufferSize);
}
else
config.Set("buff_size", client.ReceiveBufferSize);
}
catch
{
client.Dispose();
throw;
}
//create and return new itunnel object with this tcp connection
return new TcpClientTunnel(client);
}
}
}
|
mit
|
C#
|
0fcd29bea5012d722305fe3450228f2b874af7f3
|
Modify File userAuth.cpl/UITests/Tests.cs
|
ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate,ARCNanotech/userAuthenticate
|
userAuth.cpl/UITests/Tests.cs
|
userAuth.cpl/UITests/Tests.cs
|
� using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
using Xamarin.UITest.Queries;
namespace userAuth.cpl.UITests
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.StartApp ();
}
[Test]
public void WelcomeTextIsDisplayed ()
{
AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!"));
app.Screenshot ("Welcome screen.");
Assert.IsTrue (results.Any ());
}
}
}
namespace userAuth.cpl.Droid
struct init_struct ()
{
forms = userAuth.Forms.ApplicationException.Android.Config
}
[TestFixtureSetUp]
public class preTest
{
AndroidDevice device;
[SetUpFixture]
public void AlternateBeforeTestParam ()
{
device = IDevice.AndroidConfig.TestDevice ();
}
[TestAction]
public void TestResultsAreDisplayed ()
{
ITestAction[] actions = device.DisplayCurrentElement (c => c.Marked ("Results of the Droid Test are:") + results);
device.ImageCap ("Test Results.");
Math.IsInstance (actions.String ());
}
}
}
namespace userAuth.cpl.Droid
struct command (start)
{
start = internal.interface(cmdLet)
path = scanner("&B", "%6");
[Builtin]
public class start
{
InitUI init;
(stable): from userAuth.FrameAnchor
}
}
|
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
using Xamarin.UITest.Queries;
namespace userAuth.cpl.UITests
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.StartApp ();
}
[Test]
public void WelcomeTextIsDisplayed ()
{
AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!"));
app.Screenshot ("Welcome screen.");
Assert.IsTrue (results.Any ());
}
}
}
namespace userAuth.cpl.Droid
struct init_struct ()
{
forms = userAuth.Forms.ApplicationException.Android.Config
}
[TestFixtureSetUp]
public class preTest
{
AndroidDevice device;
[SetUpFixture]
public void AlternateBeforeTestParam ()
{
device = IDevice.AndroidConfig.TestDevice ();
}
[TestAction]
public void TestResultsAreDisplayed ()
{
ITestAction[] actions = device.DisplayCurrentElement (c => c.Marked ("Results of the Droid Test are:") + results);
device.ImageCap ("Test Results.");
Math.IsInstance (actions.String ());
}
}
}
|
mit
|
C#
|
8b2d4c06a99d1ba93f94eb9ed05ffc36bc3b5a15
|
fix location of file on server
|
m4r71n85/Recipies,m4r71n85/Recipies
|
Recipies/Recipies.Api/Controllers/ImagesController.cs
|
Recipies/Recipies.Api/Controllers/ImagesController.cs
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace Recipies.Api.Controllers
{
public class ImagesController : ApiController
{
public void UploadImage(string sessionKey)
{
HttpContext current = HttpContext.Current;
for (int i = 0; i < current.Request.Files.Count; i++)
{
HttpPostedFile file = current.Request.Files[i];
Stream stream = file.InputStream;
using (var fileStream = File.Create(file.FileName))
{
stream.CopyTo(fileStream);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace Recipies.Api.Controllers
{
public class ImagesController : ApiController
{
public void UploadImage(string sessionKey)
{
HttpContext current = HttpContext.Current;
for (int i = 0; i < current.Request.Files.Count; i++)
{
HttpPostedFile file = current.Request.Files[i];
Stream stream = file.InputStream;
using (var fileStream = File.Create("~/App_Data/" + file.FileName))
{
stream.CopyTo(fileStream);
}
}
}
}
}
|
unlicense
|
C#
|
e3112f29e7856a70a3dd1d9d6c5a77541e050168
|
PATCH and POST on Single object now working. For #12
|
miclip/NJsonApiCore,brainwipe/NJsonApiCore,miclip/NJsonApiCore,brainwipe/NJsonApiCore
|
src/NJsonApi/Serialization/UpdateDocument.cs
|
src/NJsonApi/Serialization/UpdateDocument.cs
|
using System.Collections.Generic;
using Newtonsoft.Json;
using NJsonApi.Serialization.Representations.Resources;
namespace NJsonApi.Serialization
{
internal class UpdateDocument
{
[JsonProperty(PropertyName = "data", Required = Required.Always)]
public SingleResource Data { get; set; }
}
}
|
using System.Collections.Generic;
using Newtonsoft.Json;
using NJsonApi.Serialization.Representations.Resources;
namespace NJsonApi.Serialization
{
internal class UpdateDocument
{
[JsonExtensionData]
public SingleResource Data { get; set; }
}
}
|
mit
|
C#
|
2fc246052086c7fb7c3bbd1a1fc57cd39ea44d67
|
fix LockScreenCommands.
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/Shell/Commands/LockScreenCommands.cs
|
WalletWasabi.Gui/Shell/Commands/LockScreenCommands.cs
|
using Avalonia;
using AvalonStudio.Commands;
using ReactiveUI;
using System;
using System.Composition;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class LockScreenCommands
{
public Global Global { get; }
[ExportCommandDefinition("File.LockScreen")]
public CommandDefinition LockScreenCommand { get; }
[ImportingConstructor]
public LockScreenCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = global.Global;
var lockScreen = ReactiveCommand.Create(OnLockScreen);
lockScreen.ThrownExceptions.Subscribe(ex => Logging.Logger.LogWarning<LockScreenCommands>(ex));
LockScreenCommand = new CommandDefinition(
"Lock Screen",
commandIconService.GetCompletionKindImage("Lock"),
lockScreen);
}
private void OnLockScreen()
{
Global.UiConfig.LockScreenActive = true;
}
}
}
|
using Avalonia;
using AvalonStudio.Commands;
using ReactiveUI;
using System;
using System.Composition;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class LockScreenCommands
{
[ExportCommandDefinition("File.LockScreen")]
public CommandDefinition LockScreenCommand { get; }
[ImportingConstructor]
public LockScreenCommands(CommandIconService commandIconService)
{
var lockScreen = ReactiveCommand.Create(OnLockScreen);
lockScreen.ThrownExceptions.Subscribe(ex => Logging.Logger.LogWarning<LockScreenCommands>(ex));
LockScreenCommand = new CommandDefinition(
"Lock Screen",
commandIconService.GetCompletionKindImage("Lock"),
lockScreen);
}
private void OnLockScreen()
{
}
}
}
|
mit
|
C#
|
00393aec067c4e54dac3be48648463ba8089000b
|
add DI for social media link repo
|
mzrimsek/resume-site-api
|
Web/Configuration/DependencyInjectionConfiguration.cs
|
Web/Configuration/DependencyInjectionConfiguration.cs
|
using Core.Interfaces.RepositoryInterfaces;
using Integration.EntityFramework.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Web.Configuration
{
public static class DependencyInjectionConfiguration
{
public static void Configure(IServiceCollection services)
{
services.AddScoped<IJobRepository, JobRepository>();
services.AddScoped<IJobProjectRepository, JobProjectRepository>();
services.AddScoped<ISchoolRepository, SchoolRepository>();
services.AddScoped<ILanguageRepository, LanguageRepository>();
services.AddScoped<ISkillRepository, SkillRepository>();
services.AddScoped<ISocialMediaLinkRepository, SocialMediaLinkRepository>();
}
}
}
|
using Core.Interfaces.RepositoryInterfaces;
using Integration.EntityFramework.Repositories;
using Microsoft.Extensions.DependencyInjection;
namespace Web.Configuration
{
public static class DependencyInjectionConfiguration
{
public static void Configure(IServiceCollection services)
{
services.AddScoped<IJobRepository, JobRepository>();
services.AddScoped<IJobProjectRepository, JobProjectRepository>();
services.AddScoped<ISchoolRepository, SchoolRepository>();
services.AddScoped<ILanguageRepository, LanguageRepository>();
services.AddScoped<ISkillRepository, SkillRepository>();
}
}
}
|
mit
|
C#
|
31e9b21d3bdbe32f5236e546e56e8c702fbdab1d
|
Replace StackTrace with CallerMemberName attribute
|
OfficeDev/Open-XML-SDK,ThomasBarnekow/Open-XML-SDK,tomjebo/Open-XML-SDK,tarunchopra/Open-XML-SDK,ClareMSYanGit/Open-XML-SDK
|
DocumentFormat.OpenXml.Tests/Common/TestContext.cs
|
DocumentFormat.OpenXml.Tests/Common/TestContext.cs
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace DocumentFormat.OpenXml.Tests
{
public class TestContext
{
public TestContext(string currentTest)
{
this.TestName = currentTest;
this.FullyQualifiedTestClassName = currentTest;
}
public string TestName
{
get;
set;
}
public string FullyQualifiedTestClassName
{
get;
set;
}
public static string GetCurrentMethod([CallerMemberName]string name = null) => name;
}
}
|
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace DocumentFormat.OpenXml.Tests
{
public class TestContext
{
public TestContext(string currentTest)
{
this.TestName = currentTest;
this.FullyQualifiedTestClassName = currentTest;
}
public string TestName
{
get;
set;
}
public string FullyQualifiedTestClassName
{
get;
set;
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static string GetCurrentMethod()
{
StackTrace st = new StackTrace();
StackFrame sf = st.GetFrame(1);
return sf.GetMethod().Name;
}
}
}
|
mit
|
C#
|
42c94a73deacab8417c33b56de43646404030b01
|
Fix potential crash when clicking on header/footer in recent list.
|
masterrr/mobile,ZhangLeiCharles/mobile,masterrr/mobile,eatskolnikov/mobile,peeedge/mobile,peeedge/mobile,eatskolnikov/mobile,eatskolnikov/mobile,ZhangLeiCharles/mobile
|
Joey/UI/Fragments/RecentTimeEntriesListFragment.cs
|
Joey/UI/Fragments/RecentTimeEntriesListFragment.cs
|
using System;
using System.Linq;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
using ListFragment = Android.Support.V4.App.ListFragment;
namespace Toggl.Joey.UI.Fragments
{
public class RecentTimeEntriesListFragment : ListFragment
{
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
var headerView = new View (Activity);
int headerWidth = (int) TypedValue.ApplyDimension (ComplexUnitType.Dip, 6, Resources.DisplayMetrics);
headerView.SetMinimumHeight (headerWidth);
ListView.AddHeaderView (headerView);
ListAdapter = new RecentTimeEntriesAdapter ();
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
RecentTimeEntriesAdapter adapter = null;
if (l.Adapter is HeaderViewListAdapter) {
var headerAdapter = (HeaderViewListAdapter)l.Adapter;
adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter;
// Adjust the position by taking into account the fact that we've got headers
position -= headerAdapter.HeadersCount;
} else if (l.Adapter is RecentTimeEntriesAdapter) {
adapter = (RecentTimeEntriesAdapter)l.Adapter;
}
if (adapter == null || position < 0 || position >= adapter.Count)
return;
var model = adapter.GetModel (position);
if (model == null)
return;
model.Continue ();
}
}
}
|
using System;
using System.Linq;
using Android.OS;
using Android.Util;
using Android.Views;
using Android.Widget;
using Toggl.Joey.UI.Adapters;
using ListFragment = Android.Support.V4.App.ListFragment;
namespace Toggl.Joey.UI.Fragments
{
public class RecentTimeEntriesListFragment : ListFragment
{
public override void OnViewCreated (View view, Bundle savedInstanceState)
{
base.OnViewCreated (view, savedInstanceState);
var headerView = new View (Activity);
int headerWidth = (int) TypedValue.ApplyDimension (ComplexUnitType.Dip, 6, Resources.DisplayMetrics);
headerView.SetMinimumHeight (headerWidth);
ListView.AddHeaderView (headerView);
ListAdapter = new RecentTimeEntriesAdapter ();
}
public override void OnListItemClick (ListView l, View v, int position, long id)
{
RecentTimeEntriesAdapter adapter = null;
if (l.Adapter is HeaderViewListAdapter) {
var headerAdapter = (HeaderViewListAdapter)l.Adapter;
adapter = headerAdapter.WrappedAdapter as RecentTimeEntriesAdapter;
// Adjust the position by taking into account the fact that we've got headers
position -= headerAdapter.HeadersCount;
} else if (l.Adapter is RecentTimeEntriesAdapter) {
adapter = (RecentTimeEntriesAdapter)l.Adapter;
}
if (adapter == null)
return;
var model = adapter.GetModel (position);
if (model == null)
return;
model.Continue ();
}
}
}
|
bsd-3-clause
|
C#
|
cead5d67ac4adc57ac8dae642316f4baea8bec6c
|
update AnimationPartChange DatLoader accessibility for ACViewer clothing (#2995)
|
LtRipley36706/ACE,ACEmulator/ACE,ACEmulator/ACE,LtRipley36706/ACE,LtRipley36706/ACE,ACEmulator/ACE
|
Source/ACE.DatLoader/Entity/AnimationPartChange.cs
|
Source/ACE.DatLoader/Entity/AnimationPartChange.cs
|
using System.IO;
namespace ACE.DatLoader.Entity
{
public class AnimationPartChange : IUnpackable
{
public byte PartIndex { get; set; }
public uint PartID { get; set; }
public void Unpack(BinaryReader reader)
{
PartIndex = reader.ReadByte();
PartID = reader.ReadAsDataIDOfKnownType(0x01000000);
}
public void Unpack(BinaryReader reader, ushort partIndex)
{
PartIndex = (byte)(partIndex & 255);
PartID = reader.ReadAsDataIDOfKnownType(0x01000000);
}
}
}
|
using System.IO;
namespace ACE.DatLoader.Entity
{
public class AnimationPartChange : IUnpackable
{
public byte PartIndex { get; private set; }
public uint PartID { get; private set; }
public void Unpack(BinaryReader reader)
{
PartIndex = reader.ReadByte();
PartID = reader.ReadAsDataIDOfKnownType(0x01000000);
}
public void Unpack(BinaryReader reader, ushort partIndex)
{
PartIndex = (byte)(partIndex & 255);
PartID = reader.ReadAsDataIDOfKnownType(0x01000000);
}
}
}
|
agpl-3.0
|
C#
|
95d6802995b85a2c4e69fb30ecd07098d8e450c2
|
Update AudibleTelemeter.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Core/Analytics/Telemetry/AudibleTelemeter.cs
|
TIKSN.Core/Analytics/Telemetry/AudibleTelemeter.cs
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TIKSN.Speech;
namespace TIKSN.Analytics.Telemetry
{
public class AudibleTelemeter : IEventTelemeter, IExceptionTelemeter, IMetricTelemeter, ITraceTelemeter
{
private readonly ITextToSpeechService _textToSpeechService;
public AudibleTelemeter(ITextToSpeechService textToSpeechService) => this._textToSpeechService =
textToSpeechService ?? throw new ArgumentNullException(nameof(textToSpeechService));
public Task TrackEventAsync(string name) => this._textToSpeechService.SpeakAsync($"Event {name} occurred.");
public Task TrackEventAsync(string name, IDictionary<string, string> properties) =>
this._textToSpeechService.SpeakAsync($"Event {name} occurred.");
public Task TrackExceptionAsync(Exception exception) => this._textToSpeechService.SpeakAsync(exception.Message);
public Task TrackExceptionAsync(Exception exception, TelemetrySeverityLevel severityLevel) =>
this._textToSpeechService.SpeakAsync($"{severityLevel}. {exception.Message}");
public Task TrackMetricAsync(string metricName, decimal metricValue) =>
this._textToSpeechService.SpeakAsync($"Metric {metricName} is {metricValue}.");
public Task TrackTraceAsync(string message) => this._textToSpeechService.SpeakAsync(message);
public Task TrackTraceAsync(string message, TelemetrySeverityLevel severityLevel) =>
this._textToSpeechService.SpeakAsync($"{severityLevel} {message}");
}
}
|
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TIKSN.Speech;
namespace TIKSN.Analytics.Telemetry
{
public class AudibleTelemeter : IEventTelemeter, IExceptionTelemeter, IMetricTelemeter, ITraceTelemeter
{
private readonly ITextToSpeechService _textToSpeechService;
public AudibleTelemeter(ITextToSpeechService textToSpeechService) => this._textToSpeechService =
textToSpeechService ?? throw new ArgumentNullException(nameof(textToSpeechService));
public Task TrackEvent(string name) => this._textToSpeechService.SpeakAsync($"Event {name} occurred.");
public Task TrackEvent(string name, IDictionary<string, string> properties) =>
this._textToSpeechService.SpeakAsync($"Event {name} occurred.");
public Task TrackException(Exception exception) => this._textToSpeechService.SpeakAsync(exception.Message);
public Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel) =>
this._textToSpeechService.SpeakAsync($"{severityLevel}. {exception.Message}");
public Task TrackMetric(string metricName, decimal metricValue) =>
this._textToSpeechService.SpeakAsync($"Metric {metricName} is {metricValue}.");
public Task TrackTrace(string message) => this._textToSpeechService.SpeakAsync(message);
public Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) =>
this._textToSpeechService.SpeakAsync($"{severityLevel} {message}");
}
}
|
mit
|
C#
|
93064b4bfa97e52046cc55eab4a2d950d10b2d9e
|
Implement the ListStates method in EfStateRepository.
|
RichardVSaasbook/Widget
|
Widget/Widget.Domain/Concrete/EfStateRepository.cs
|
Widget/Widget.Domain/Concrete/EfStateRepository.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Widget.Domain.Abstract;
using Widget.Domain.Models;
namespace Widget.Domain.Concrete {
public class EfStateRepository : IStateRepository {
private WidgetDbContext db;
/// <summary>
/// Create a StateRepository with the database connected WidgetDbContext.
/// </summary>
public EfStateRepository() {
db = new WidgetDbContext();
}
/// <summary>
/// Create a StateRepository with the provided WidgetDbContext.
/// </summary>
/// <param name="db">The WidgetDbContext to get data from.</param>
public EfStateRepository(WidgetDbContext db) {
this.db = db;
}
/// <summary>
/// Calculate the TaxAmount for a sub total based on the given state.
/// </summary>
/// <param name="subTotal">The sub total amount.</param>
/// <param name="stateId">The ID of the State to calculate from.</param>
/// <returns>
/// The calculated tax amount or 0.00 if subTotal is negative or
/// the State cannot be found.
/// </returns>
public decimal CalculateTaxAmount(decimal subTotal, int stateId) {
if (subTotal < 0) {
return 0M;
}
State state = db.States.FirstOrDefault(s => s.Id == stateId);
if (state == null) {
return 0M;
}
return subTotal * Math.Round(state.TaxRate, 2);
}
/// <summary>
/// List all of the States.
/// </summary>
/// <returns>The List of States.</returns>
public List<State> ListStates() {
return db.States.ToList();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Widget.Domain.Abstract;
using Widget.Domain.Models;
namespace Widget.Domain.Concrete {
public class EfStateRepository : IStateRepository {
private WidgetDbContext db;
/// <summary>
/// Create a StateRepository with the database connected WidgetDbContext.
/// </summary>
public EfStateRepository() {
db = new WidgetDbContext();
}
/// <summary>
/// Create a StateRepository with the provided WidgetDbContext.
/// </summary>
/// <param name="db">The WidgetDbContext to get data from.</param>
public EfStateRepository(WidgetDbContext db) {
this.db = db;
}
/// <summary>
/// Calculate the TaxAmount for a sub total based on the given state.
/// </summary>
/// <param name="subTotal">The sub total amount.</param>
/// <param name="stateId">The ID of the State to calculate from.</param>
/// <returns>
/// The calculated tax amount or 0.00 if subTotal is negative or
/// the State cannot be found.
/// </returns>
public decimal CalculateTaxAmount(decimal subTotal, int stateId) {
if (subTotal < 0) {
return 0M;
}
State state = db.States.FirstOrDefault(s => s.Id == stateId);
if (state == null) {
return 0M;
}
return subTotal * Math.Round(state.TaxRate, 2);
}
}
}
|
mit
|
C#
|
0670ac5a64fa017001be8da4093413ea80c06bd8
|
Patch array - Hate this problem. Medium my ass. Stupid fucking thing sucks
|
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
|
LeetCode/remote/patch_array.cs
|
LeetCode/remote/patch_array.cs
|
// https://leetcode.com/problems/patching-array/
//
// Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
//
// Example 1:
// nums = [1, 3], n = 6
// Return 1.
//
// Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
// Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
// Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
// So we only need 1 patch.
using System;
using System.Collections.Generic;
public class Solution {
public int MinPatches(int[] nums, int n)
{
var sum = 0;
var i = 0;
var patches = 0;
while (i < nums.Length)
{
while (sum + 1 < nums[i] && sum < n)
{
sum += sum + 1;
patches++;
}
sum += nums[i++];
}
while (sum < n)
{
sum += sum + 1;
patches++;
}
return patches;
}
static void Main()
{
var s = new Solution();
foreach (var x in new [] {
Tuple.Create(new [] { 1, 3 }, 6),
Tuple.Create(new [] { 1, 5, 10 }, 20),
Tuple.Create(new [] { 1, 2, 2 }, 5),
Tuple.Create(new [] { 1, 2, 3 }, 2147483647)
})
{
Console.WriteLine(
"[{0} -- {1}] - [{2}]",
String.Join(", ", x.Item1),
x.Item2,
s.MinPatches(x.Item1, x.Item2));
}
}
}
|
// https://leetcode.com/problems/patching-array/
//
// Given a sorted positive integer array nums and an integer n, add/patch elements to the array such that any number in range [1, n] inclusive can be formed by the sum of some elements in the array. Return the minimum number of patches required.
//
// Example 1:
// nums = [1, 3], n = 6
// Return 1.
//
// Combinations of nums are [1], [3], [1,3], which form possible sums of: 1, 3, 4.
// Now if we add/patch 2 to nums, the combinations are: [1], [2], [3], [1,3], [2,3], [1,2,3].
// Possible sums are 1, 2, 3, 4, 5, 6, which now covers the range [1, 6].
// So we only need 1 patch.
using System;
using System.Collections.Generic;
public class Solution {
public int MinPatches(int[] nums, int n)
{
return Patches(nums, n).Count;
}
public List<int> Patches(int[] nums, int n)
{
var sum = 0;
var i = 0;
var patches = new List<int>();
while (i < nums.Length)
{
while (sum + 1 < nums[i] && i < n)
{
sum += sum + 1;
patches.Add(sum);
}
sum += nums[i++];
}
while (sum < n)
{
sum++;
patches.Add(sum);
}
return patches;
}
static void Main()
{
var s = new Solution();
foreach (var x in new [] {
Tuple.Create(new [] { 1, 3 }, 6),
Tuple.Create(new [] { 1, 5, 10 }, 20),
Tuple.Create(new [] { 1, 2, 2 }, 5)
})
{
Console.WriteLine(
"[{0} -- {1}] - [{2}]",
String.Join(", ", x.Item1),
x.Item2,
String.Join(", ", s.Patches(x.Item1, x.Item2)));
}
}
}
|
mit
|
C#
|
79bf67051eeb1e85d3ef8ca6584d786e324520c7
|
Change cast to Convert.ToBoolean in PlcBool
|
proemmer/papper
|
Papper/src/Papper/Types/PlcBool.cs
|
Papper/src/Papper/Types/PlcBool.cs
|
using System.Linq;
using Papper.Helper;
using System;
namespace Papper.Types
{
internal class PlcBool : PlcObject
{
public PlcBool(string name) :
base(name)
{
Size = new PlcSize { Bits = 1 };
}
public override object ConvertFromRaw(PlcObjectBinding plcObjectBinding)
{
if (plcObjectBinding.Data == null || !plcObjectBinding.Data.Any())
return default(bool);
var baseOffset = plcObjectBinding.Offset + (plcObjectBinding.MetaData.Offset.Bits) / 8;
var bit = plcObjectBinding.Offset + plcObjectBinding.MetaData.Offset.Bits - baseOffset;
return plcObjectBinding.Data[baseOffset].GetBit(bit);
}
public override void ConvertToRaw(object value, PlcObjectBinding plcObjectBinding)
{
var baseOffset = plcObjectBinding.Offset + (plcObjectBinding.MetaData.Offset.Bits) / 8;
var bit = plcObjectBinding.Offset + plcObjectBinding.MetaData.Offset.Bits - baseOffset;
plcObjectBinding.Data[baseOffset] = plcObjectBinding.Data[baseOffset].SetBit(bit, Convert.ToBoolean(value));
}
}
}
|
using System.Linq;
using Papper.Helper;
namespace Papper.Types
{
internal class PlcBool : PlcObject
{
public PlcBool(string name) :
base(name)
{
Size = new PlcSize { Bits = 1 };
}
public override object ConvertFromRaw(PlcObjectBinding plcObjectBinding)
{
if (plcObjectBinding.Data == null || !plcObjectBinding.Data.Any())
return default(bool);
var baseOffset = plcObjectBinding.Offset + (plcObjectBinding.MetaData.Offset.Bits) / 8;
var bit = plcObjectBinding.Offset + plcObjectBinding.MetaData.Offset.Bits - baseOffset;
return plcObjectBinding.Data[baseOffset].GetBit(bit);
}
public override void ConvertToRaw(object value, PlcObjectBinding plcObjectBinding)
{
var baseOffset = plcObjectBinding.Offset + (plcObjectBinding.MetaData.Offset.Bits) / 8;
var bit = plcObjectBinding.Offset + plcObjectBinding.MetaData.Offset.Bits - baseOffset;
plcObjectBinding.Data[baseOffset] = plcObjectBinding.Data[baseOffset].SetBit(bit, (bool)value);
}
}
}
|
apache-2.0
|
C#
|
cad371175b4913e45f36c2e2299635c1cf5146b2
|
Add test for Firebird
|
sqlkata/querybuilder
|
QueryBuilder.Tests/CompilerTest.cs
|
QueryBuilder.Tests/CompilerTest.cs
|
using SqlKata;
using SqlKata.Compilers;
using Xunit;
namespace QueryBuilder.Tests
{
public class CompilerTest
{
private readonly Compiler pgsql;
private readonly MySqlCompiler mysql;
private readonly FirebirdCompiler fbsql;
private SqlServerCompiler mssql { get; }
public CompilerTest()
{
mssql = new SqlServerCompiler();
mysql = new MySqlCompiler();
pgsql = new PostgresCompiler();
fbsql = new FirebirdCompiler();
}
private string[] Compile(Query q)
{
return new[]{
mssql.Compile(q.Clone()).ToString(),
mysql.Compile(q.Clone()).ToString(),
pgsql.Compile(q.Clone()).ToString(),
fbsql.Compile(q.Clone()).ToString(),
};
}
}
}
|
using SqlKata;
using SqlKata.Compilers;
using Xunit;
namespace QueryBuilder.Tests
{
public class CompilerTest
{
private readonly Compiler pgsql;
private readonly MySqlCompiler mysql;
private SqlServerCompiler mssql { get; }
public CompilerTest()
{
mssql = new SqlServerCompiler();
mysql = new MySqlCompiler();
pgsql = new PostgresCompiler();
}
private string[] Compile(Query q)
{
return new[]{
mssql.Compile(q.Clone()).ToString(),
mysql.Compile(q.Clone()).ToString(),
pgsql.Compile(q.Clone()).ToString(),
};
}
}
}
|
mit
|
C#
|
68cb7d1f185abe80d4d46e812a1e49413697a403
|
Make properties writes block by default
|
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
|
NET/API/Treehopper/Settings.cs
|
NET/API/Treehopper/Settings.cs
|
using System;
namespace Treehopper
{
/// <summary>
/// This class represents global settings used by the Treehopper API
/// </summary>
public class Settings
{
/// <summary>
/// Get or sets whether exceptions should be thrown.
/// </summary>
/// <remarks>
/// <para>
/// If true, any exceptions received will be thrown to user code, as well as printed. If false, exceptions will
/// only be printed.
/// </para>
/// </remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// The VID to search for
/// </summary>
public uint Vid { get; set; } = 0x10c4;
/// <summary>
/// The PID to search for
/// </summary>
public uint Pid { get; set; } = 0x8a7e;
/// <summary>
/// The WinUSB GUID used by the librarh
/// </summary>
public Guid Guid { get; set; } = new Guid("{5B34B38B-F4CD-49C3-B2BB-60E47A43E12D}");
/// <summary>
/// Whether or not writing to properties should return immediately, or only upon successfully sending to the board.
/// </summary>
/// <remarks>
/// <para>
/// Properties provide a useful abstraction for the state of peripherals (i.e., <see cref="Pin.DigitalValue" />),
/// but they are inherently synchronous. This setting allows you to control how writes to properties behave; when
/// true, a write to one of these properties will queue up a request to the board but will return immediately ---
/// setting this property to false will synchronously wait for the message to be sent to the board.
/// </para>
/// </remarks>
public bool PropertyWritesReturnImmediately { get; set; } = false;
}
}
|
using System;
namespace Treehopper
{
/// <summary>
/// This class represents global settings used by the Treehopper API
/// </summary>
public class Settings
{
/// <summary>
/// Get or sets whether exceptions should be thrown.
/// </summary>
/// <remarks>
/// <para>
/// If true, any exceptions received will be thrown to user code, as well as printed. If false, exceptions will
/// only be printed.
/// </para>
/// </remarks>
public bool ThrowExceptions { get; set; }
/// <summary>
/// The VID to search for
/// </summary>
public uint Vid { get; set; } = 0x10c4;
/// <summary>
/// The PID to search for
/// </summary>
public uint Pid { get; set; } = 0x8a7e;
/// <summary>
/// The WinUSB GUID used by the librarh
/// </summary>
public Guid Guid { get; set; } = new Guid("{5B34B38B-F4CD-49C3-B2BB-60E47A43E12D}");
/// <summary>
/// Whether or not writing to properties should return immediately, or only upon successfully sending to the board.
/// </summary>
/// <remarks>
/// <para>
/// Properties provide a useful abstraction for the state of peripherals (i.e., <see cref="Pin.DigitalValue" />),
/// but they are inherently synchronous. This setting allows you to control how writes to properties behave; when
/// true, a write to one of these properties will queue up a request to the board but will return immediately ---
/// setting this property to false will synchronously wait for the message to be sent to the board.
/// </para>
/// </remarks>
public bool PropertyWritesReturnImmediately { get; set; } = true;
}
}
|
mit
|
C#
|
f67ce94049cd56393a6e271a18c35f536ced452e
|
Change switch statement in Version task to use ToLower on argument
|
frozenskys/generator-tribble,frozenskys/generator-tribble
|
generators/cakeplus/templates/build.cake
|
generators/cakeplus/templates/build.cake
|
///////////////////////////////////////////////////////////////////////////////
// Tools and Addins
///////////////////////////////////////////////////////////////////////////////
#tool "GitVersion.CommandLine"
#addin nuget:?package=Cake.Git
#addin nuget:?package=Cake.Figlet
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var versionType = Argument("VersionType", "Patch");
var artifacts = MakeAbsolute(Directory(Argument("artifactPath", "./artifacts")));
GitVersion versionInfo = null;
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(ctx =>
{
// Executed BEFORE the first task.
Information(Figlet("Tribble Cake"));
});
Teardown(ctx =>
{
// Executed AFTER the last task.
Information("Finished running tasks.");
});
///////////////////////////////////////////////////////////////////////////////
// SYSTEM TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Version")
.Does(() =>
{
var semVersion = "";
int major = 0;
int minor = 1;
int patch = 0;
GitVersion assertedVersions = GitVersion(new GitVersionSettings
{
OutputType = GitVersionOutput.Json,
});
major = assertedVersions.Major;
minor = assertedVersions.Minor;
patch = assertedVersions.Patch;
switch (versionType.ToLower())
{
case "patch":
patch += 1; break;
case "minor":
minor += 1; patch = 0; break;
case "major":
major += 1; minor = 0; patch = 0; break;
};
semVersion = string.Format("{0}.{1}.{2}", major, minor, patch);
GitTag(".", semVersion);
Information("Changing version: {0} to {1}", assertedVersions.LegacySemVerPadded, semVersion);
});
///////////////////////////////////////////////////////////////////////////////
// USER TASKS
// PUT ALL YOUR BUILD GOODNESS IN HERE
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(artifacts);
});
Task("Default")
.IsDependentOn("Clean")
.Does(() =>
{
Information("Hello Cake!");
});
Task("Build")
.Does(() =>
{
Information("Running Build...");
// Add your build tasks here
// this task can depend on others :)
});
Task("Test")
.Does(() =>
{
Information("Running Tests...");
// Add your test tasks here
// this task can depend on others :)
});
Task("Package")
.Does(() =>
{
Information("Running Packaging...");
// Add your packaging tasks here
// this task can depend on others :)
});
RunTarget(target);
|
///////////////////////////////////////////////////////////////////////////////
// Tools and Addins
///////////////////////////////////////////////////////////////////////////////
#tool "GitVersion.CommandLine"
#addin nuget:?package=Cake.Git
#addin nuget:?package=Cake.Figlet
///////////////////////////////////////////////////////////////////////////////
// ARGUMENTS
///////////////////////////////////////////////////////////////////////////////
var target = Argument("target", "Default");
var configuration = Argument("configuration", "Release");
var versionType = Argument("VersionType", "Patch");
var artifacts = MakeAbsolute(Directory(Argument("artifactPath", "./artifacts")));
GitVersion versionInfo = null;
///////////////////////////////////////////////////////////////////////////////
// SETUP / TEARDOWN
///////////////////////////////////////////////////////////////////////////////
Setup(ctx =>
{
// Executed BEFORE the first task.
Information(Figlet("Tribble Cake"));
});
Teardown(ctx =>
{
// Executed AFTER the last task.
Information("Finished running tasks.");
});
///////////////////////////////////////////////////////////////////////////////
// SYSTEM TASKS
///////////////////////////////////////////////////////////////////////////////
Task("Version")
.Does(() =>
{
var semVersion = "";
int major = 0;
int minor = 1;
int patch = 0;
GitVersion assertedVersions = GitVersion(new GitVersionSettings
{
OutputType = GitVersionOutput.Json,
});
major = assertedVersions.Major;
minor = assertedVersions.Minor;
patch = assertedVersions.Patch;
switch (versionType)
{
case "patch":
patch += 1; break;
case "minor":
minor += 1; patch = 0; break;
case "major":
major += 1; minor = 0; patch = 0; break;
};
semVersion = string.Format("{0}.{1}.{2}", major, minor, patch);
GitTag(".", semVersion);
Information("Changing version: {0} to {1}", assertedVersions.LegacySemVerPadded, semVersion);
});
///////////////////////////////////////////////////////////////////////////////
// USER TASKS
// PUT ALL YOUR BUILD GOODNESS IN HERE
///////////////////////////////////////////////////////////////////////////////
Task("Clean")
.Does(() =>
{
CleanDirectory(artifacts);
});
Task("Default")
.IsDependentOn("Clean")
.Does(() =>
{
Information("Hello Cake!");
});
Task("Build")
.Does(() =>
{
Information("Running Build...");
// Add your build tasks here
// this task can depend on others :)
});
Task("Test")
.Does(() =>
{
Information("Running Tests...");
// Add your test tasks here
// this task can depend on others :)
});
Task("Package")
.Does(() =>
{
Information("Running Packaging...");
// Add your packaging tasks here
// this task can depend on others :)
});
RunTarget(target);
|
mit
|
C#
|
6009876182fb1c3fc96573829ac8a3d80ae45671
|
Edit it
|
sta/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,jogibear9988/websocket-sharp,2Toad/websocket-sharp,2Toad/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp,sta/websocket-sharp,jogibear9988/websocket-sharp
|
websocket-sharp/ErrorEventArgs.cs
|
websocket-sharp/ErrorEventArgs.cs
|
#region License
/*
* ErrorEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* 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.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Frank Razenberg <frank@zzattack.org>
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Represents the event data for the <see cref="WebSocket.OnError"/> event.
/// </summary>
/// <remarks>
/// <para>
/// That event occurs when the <see cref="WebSocket"/> gets an error.
/// </para>
/// <para>
/// If you would like to get the error message, you should access
/// the <see cref="ErrorEventArgs.Message"/> property.
/// </para>
/// <para>
/// And if the error is due to an exception, you can get it by accessing
/// the <see cref="ErrorEventArgs.Exception"/> property.
/// </para>
/// </remarks>
public class ErrorEventArgs : EventArgs
{
#region Private Fields
private Exception _exception;
private string _message;
#endregion
#region Internal Constructors
internal ErrorEventArgs (string message)
: this (message, null)
{
}
internal ErrorEventArgs (string message, Exception exception)
{
_message = message;
_exception = exception;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the exception that caused the error.
/// </summary>
/// <value>
/// An <see cref="System.Exception"/> instance that represents the cause of
/// the error, or <see langword="null"/> if it is not due to an exception.
/// </value>
public Exception Exception {
get {
return _exception;
}
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the error message.
/// </value>
public string Message {
get {
return _message;
}
}
#endregion
}
}
|
#region License
/*
* ErrorEventArgs.cs
*
* The MIT License
*
* Copyright (c) 2012-2015 sta.blockhead
*
* 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.
*/
#endregion
#region Contributors
/*
* Contributors:
* - Frank Razenberg <frank@zzattack.org>
*/
#endregion
using System;
namespace WebSocketSharp
{
/// <summary>
/// Represents the event data for the <see cref="WebSocket.OnError"/> event.
/// </summary>
/// <remarks>
/// <para>
/// A <see cref="WebSocket.OnError"/> event occurs when the <see cref="WebSocket"/> gets
/// an error.
/// </para>
/// <para>
/// If you would like to get the error message, you should access
/// the <see cref="ErrorEventArgs.Message"/> property.
/// </para>
/// <para>
/// And if the error is due to an exception, you can get the exception by accessing
/// the <see cref="ErrorEventArgs.Exception"/> property.
/// </para>
/// </remarks>
public class ErrorEventArgs : EventArgs
{
#region Private Fields
private Exception _exception;
private string _message;
#endregion
#region Internal Constructors
internal ErrorEventArgs (string message)
: this (message, null)
{
}
internal ErrorEventArgs (string message, Exception exception)
{
_message = message;
_exception = exception;
}
#endregion
#region Public Properties
/// <summary>
/// Gets the exception that caused the error.
/// </summary>
/// <value>
/// An <see cref="System.Exception"/> instance that represents the cause of the error,
/// or <see langword="null"/> if the error isn't due to an exception.
/// </value>
public Exception Exception {
get {
return _exception;
}
}
/// <summary>
/// Gets the error message.
/// </summary>
/// <value>
/// A <see cref="string"/> that represents the error message.
/// </value>
public string Message {
get {
return _message;
}
}
#endregion
}
}
|
mit
|
C#
|
ebee9393f1e011d25cdffb36345005a90af74864
|
Stop double call of Directory.GetCurrentDirectory on startup, as 20% slower on linux
|
jtkech/Orchard2,alexbocharov/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,GVX111/Orchard2,petedavis/Orchard2,petedavis/Orchard2,yiji/Orchard2,stevetayloruk/Orchard2,lukaskabrt/Orchard2,xkproject/Orchard2,jtkech/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,yiji/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,jtkech/Orchard2,lukaskabrt/Orchard2,petedavis/Orchard2,xkproject/Orchard2,GVX111/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,lukaskabrt/Orchard2,jtkech/Orchard2,yiji/Orchard2,stevetayloruk/Orchard2,lukaskabrt/Orchard2,alexbocharov/Orchard2,stevetayloruk/Orchard2,GVX111/Orchard2,alexbocharov/Orchard2,stevetayloruk/Orchard2
|
src/Orchard.Web/Program.cs
|
src/Orchard.Web/Program.cs
|
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var currentDirectory = Directory.GetCurrentDirectory();
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(currentDirectory)
.UseWebRoot(currentDirectory)
.UseStartup<Startup>()
.Build();
using (host)
{
host.Run();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
}
|
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Orchard.Hosting;
using Orchard.Web;
namespace Orchard.Console
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseIISIntegration()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseWebRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
using (host)
{
host.Run();
var orchardHost = new OrchardHost(host.Services, System.Console.In, System.Console.Out, args);
orchardHost.Run();
}
}
}
}
|
bsd-3-clause
|
C#
|
4875687e65609b0c13edf8d236a7e88d351d39ca
|
disable retries in tests
|
SimonCropp/NServiceBus.Serilog
|
src/Tests/ConfigBuilder.cs
|
src/Tests/ConfigBuilder.cs
|
using NServiceBus;
public static class ConfigBuilder
{
public static EndpointConfiguration BuildDefaultConfig(string endpointName)
{
var configuration = new EndpointConfiguration(endpointName);
configuration.SendFailedMessagesTo("error");
configuration.UsePersistence<InMemoryPersistence>();
configuration.UseTransport<LearningTransport>();
configuration.PurgeOnStartup(true);
var recoverability = configuration.Recoverability();
recoverability.Delayed(
customizations: settings =>
{
settings.NumberOfRetries(0);
});
recoverability.Immediate(
customizations: settings =>
{
settings.NumberOfRetries(0);
});
return configuration;
}
}
|
using NServiceBus;
public static class ConfigBuilder
{
public static EndpointConfiguration BuildDefaultConfig(string endpointName)
{
var configuration = new EndpointConfiguration(endpointName);
configuration.SendFailedMessagesTo("error");
configuration.UsePersistence<InMemoryPersistence>();
configuration.UseTransport<LearningTransport>();
configuration.PurgeOnStartup(true);
return configuration;
}
}
|
mit
|
C#
|
b15fb65c1a1c8e2ed691cbaf5134d1daddf6b2dd
|
Fix NSwag upgrade
|
amweiss/WeatherLink
|
src/WeatherLink/Startup.cs
|
src/WeatherLink/Startup.cs
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NSwag.AspNetCore;
using WeatherLink.Models;
using WeatherLink.Services;
namespace WeatherLink
{
internal class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwagger();
app.UseSwaggerUi3();
app.UseStaticFiles();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOptions();
// Get config
services.Configure<WeatherLinkSettings>(Configuration);
// Setup token db
services.AddDbContext<SlackWorkspaceAppContext>();
// Add custom services
services.AddTransient<ITrafficAdviceService, WeatherBasedTrafficAdviceService>();
services.AddTransient<IGeocodeService, GoogleMapsGeocodeService>();
services.AddTransient<IDistanceToDurationService, GoogleMapsDistanceToDurationService>();
services.AddTransient<IDarkSkyService, HourlyAndMinutelyDarkSkyService>();
// Configure swagger
services.AddSwaggerDocument(c =>
{
c.Title = "WeatherLink";
c.Description = "An API to get weather based advice.";
});
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using NSwag.AspNetCore;
using WeatherLink.Models;
using WeatherLink.Services;
namespace WeatherLink
{
internal class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseMvc();
app.UseSwaggerUi3WithApiExplorer(c =>
{
c.SwaggerRoute = "/swagger/v1/swagger.json";
c.SwaggerUiRoute = "/swagger";
c.GeneratorSettings.Title = "WeatherLink";
c.GeneratorSettings.Description = "An API to get weather based advice.";
});
app.UseStaticFiles();
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add framework services
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddOptions();
// Get config
services.Configure<WeatherLinkSettings>(Configuration);
// Setup token db
services.AddDbContext<SlackWorkspaceAppContext>();
// Add custom services
services.AddTransient<ITrafficAdviceService, WeatherBasedTrafficAdviceService>();
services.AddTransient<IGeocodeService, GoogleMapsGeocodeService>();
services.AddTransient<IDistanceToDurationService, GoogleMapsDistanceToDurationService>();
services.AddTransient<IDarkSkyService, HourlyAndMinutelyDarkSkyService>();
// Configure swagger
services.AddSwagger();
}
}
}
|
mit
|
C#
|
205b89c680d3abf5b20fb2a5c907111f779ecb8d
|
remove c# 6 syntax
|
lust4life/WebApiProxy
|
WebApiProxy.Tasks/Models/GenerateConfig.cs
|
WebApiProxy.Tasks/Models/GenerateConfig.cs
|
using System.Collections.Generic;
using System.Linq;
namespace WebApiProxy.Tasks.Models
{
public class GenerateConfig
{
public bool GenerateOnBuild { get; set; }
public bool GenerateAsyncReturnTypes { get; set; }
public IEnumerable<ServiceConfig> Services { get; set; }
public class ServiceConfig
{
public ServiceConfig()
{
ClientSuffix = "Client";
}
public string ProxyEndpoint { get; set; }
public string Namespace { get; set; }
public string Name { get; set; }
public string ClientSuffix { get; set; }
public bool IncludeValidation { get; set; }
public bool EnsureSuccess { get; set; }
}
public IEnumerable<Configuration> TransformToOldConfig()
{
return Services.Select(service => new Configuration
{
GenerateOnBuild = GenerateOnBuild,
GenerateAsyncReturnTypes = GenerateAsyncReturnTypes,
Endpoint = service.ProxyEndpoint,
ClientSuffix = service.ClientSuffix,
Namespace = service.Namespace,
Name = service.Name
});
}
}
}
|
using System.Collections.Generic;
using System.Linq;
namespace WebApiProxy.Tasks.Models
{
public class GenerateConfig
{
public bool GenerateOnBuild { get; set; }
public bool GenerateAsyncReturnTypes { get; set; }
public IEnumerable<ServiceConfig> Services { get; set; }
public class ServiceConfig
{
public string ProxyEndpoint { get; set; }
public string Namespace { get; set; }
public string Name { get; set; }
public string ClientSuffix { get; set; } = "Client";
public bool IncludeValidation { get; set; }
public bool EnsureSuccess { get; set; }
}
public IEnumerable<Configuration> TransformToOldConfig()
{
return Services.Select(service => new Configuration
{
GenerateOnBuild = GenerateOnBuild,
GenerateAsyncReturnTypes = GenerateAsyncReturnTypes,
Endpoint = service.ProxyEndpoint,
ClientSuffix = service.ClientSuffix,
Namespace = service.Namespace,
Name = service.Name
});
}
}
}
|
mit
|
C#
|
0b5ffcbdcc5ff2c78d564f3a37cacbb662a0705a
|
Move to next version
|
aloisdg/Doccou,saidmarouf/Doccou,aloisdg/CountPages
|
Counter/Properties/AssemblyInfo.cs
|
Counter/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Resources;
// 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("Counter")]
[assembly: AssemblyDescription("Counter is a PCL to count the page's number of a document.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("aloisdg")]
[assembly: AssemblyProduct("Counter")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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.1.1.0")]
[assembly: AssemblyFileVersion("1.1.1.0")]
|
using System.Reflection;
using System.Resources;
// 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("Counter")]
[assembly: AssemblyDescription("Counter is a PCL to count the page's number of a document.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("aloisdg")]
[assembly: AssemblyProduct("Counter")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.