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
da1aeb816695414c669ebb0993ea62a2384ce7f5
Add support for invert condition (unless) to ScriptIfStatement
lunet-io/scriban,textamina/scriban
src/Scriban/Syntax/ScriptIfStatement.cs
src/Scriban/Syntax/ScriptIfStatement.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. namespace Scriban.Syntax { public abstract class ScriptConditionStatement : ScriptStatement { public ScriptConditionStatement Else { get; set; } public override object Evaluate(TemplateContext context) { return context.Evaluate(Else); } } [ScriptSyntax("if statement", "if <expression> ... end|else|else if")] public class ScriptIfStatement : ScriptConditionStatement { /// <summary> /// Get or sets the condition of this if statement. /// </summary> public ScriptExpression Condition { get; set; } /// <summary> /// Gets or sets a boolean indicating that the result of the condition is inverted /// </summary> public bool InvertCondition { get; set; } public ScriptBlockStatement Then { get; set; } public override object Evaluate(TemplateContext context) { var conditionValue = context.ToBool(context.Evaluate(Condition)); if (InvertCondition) { conditionValue = !conditionValue; } if (conditionValue) { return context.Evaluate(Then); } else { return base.Evaluate(context); } } public override string ToString() { return $"if {Condition}"; } } [ScriptSyntax("else statement", "else | else if <expression> ... end|else|else if")] public class ScriptElseStatement : ScriptConditionStatement { public ScriptBlockStatement Body { get; set; } public override object Evaluate(TemplateContext context) { context.Evaluate(Body); return base.Evaluate(context); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. namespace Scriban.Syntax { public abstract class ScriptConditionStatement : ScriptStatement { public ScriptConditionStatement Else { get; set; } public override object Evaluate(TemplateContext context) { return context.Evaluate(Else); } } [ScriptSyntax("if statement", "if <expression> ... end|else|else if")] public class ScriptIfStatement : ScriptConditionStatement { /// <summary> /// Get or sets the condition of this if statement. /// </summary> public ScriptExpression Condition { get; set; } public ScriptBlockStatement Then { get; set; } public override object Evaluate(TemplateContext context) { var conditionValue = context.ToBool(context.Evaluate(Condition)); if (conditionValue) { return context.Evaluate(Then); } else { return base.Evaluate(context); } } public override string ToString() { return $"if {Condition}"; } } [ScriptSyntax("else statement", "else | else if <expression> ... end|else|else if")] public class ScriptElseStatement : ScriptConditionStatement { public ScriptBlockStatement Body { get; set; } public override object Evaluate(TemplateContext context) { context.Evaluate(Body); return base.Evaluate(context); } } }
bsd-2-clause
C#
f7ae856b9d8de51edc393035b1c30b6563f53068
Build doesn't like new C# featurs.
mwhelan/Specify
src/Specify/Configuration/TestRunner.cs
src/Specify/Configuration/TestRunner.cs
using System.Linq; namespace Specify.Configuration { internal class TestRunner { private readonly ITestEngine _testEngine; public TestRunner(SpecifyBootstrapper configuration, IApplicationContainer applicationContainer, ITestEngine testEngine) { Configuration = configuration; ApplicationContainer = applicationContainer; _testEngine = testEngine; } public void Execute(IScenario testObject, string scenarioTitle = null) { using (var container = ApplicationContainer.CreateChildContainer()) { foreach (var action in Configuration.PerScenarioActions) { action.Before(container); } var scenario = (IScenario)container.Resolve(testObject.GetType()); scenario.SetContainer(container); _testEngine.Execute(scenario); foreach (var action in Configuration.PerScenarioActions.AsEnumerable().Reverse()) { action.After(); } } } internal IApplicationContainer ApplicationContainer { get; set; } internal SpecifyBootstrapper Configuration { get; set; } } }
using System.Linq; namespace Specify.Configuration { internal class TestRunner { private readonly ITestEngine _testEngine; public TestRunner(SpecifyBootstrapper configuration, IApplicationContainer applicationContainer, ITestEngine testEngine) { Configuration = configuration; ApplicationContainer = applicationContainer; _testEngine = testEngine; } public void Execute(IScenario testObject, string scenarioTitle = null) { using (var container = ApplicationContainer.CreateChildContainer()) { foreach (var action in Configuration.PerScenarioActions) { action.Before(container); } var scenario = (IScenario)container.Resolve(testObject.GetType()); scenario.SetContainer(container); _testEngine.Execute(scenario); foreach (var action in Configuration.PerScenarioActions.AsEnumerable().Reverse()) { action.After(); } } } internal IApplicationContainer ApplicationContainer { get; } internal SpecifyBootstrapper Configuration { get; } } }
mit
C#
be0ec0f84cdf4a0a04d302cb52af60810927f3ad
add .Are() overload for ienumerable
Pondidum/Finite,Pondidum/Finite
Finite/States.cs
Finite/States.cs
using System; using System.Collections.Generic; using System.Linq; using Finite.Configurations; using Finite.Infrastructure; namespace Finite { public class States<TSwitches> { private readonly List<Type> _types; private readonly IDictionary<Type, State<TSwitches>> _states; public States() { _types = new List<Type>(); _states = new Dictionary<Type, State<TSwitches>>(); } public IEnumerable<Type> KnownTypes { get { return _types; } } public States<TSwitches> Are(params Type[] states) { _types.AddRange(states); return this; } public States<TSwitches> Are(IEnumerable<Type> states) { _types.AddRange(states); return this; } public void InitialiseStates(IInstanceCreator instanceCreator) { _states.AddRange(_types .Where(t => typeof(State<TSwitches>).IsAssignableFrom(t)) .ToDictionary(t => t, instanceCreator.Create<TSwitches>)); _states.ForEach(i => i.Value.Configure(this)); } public State<TSwitches> GetStateFor<TState>() { var stateType = typeof(TState); if (_states.ContainsKey(stateType) == false) { throw new UnknownStateException(stateType); } return _states[stateType]; } } }
using System; using System.Collections.Generic; using System.Linq; using Finite.Configurations; using Finite.Infrastructure; namespace Finite { public class States<TSwitches> { private readonly List<Type> _types; private readonly IDictionary<Type, State<TSwitches>> _states; public States() { _types = new List<Type>(); _states = new Dictionary<Type, State<TSwitches>>(); } public IEnumerable<Type> KnownTypes { get { return _types; } } public States<TSwitches> Are(params Type[] states) { _types.AddRange(states); return this; } public void InitialiseStates(IInstanceCreator instanceCreator) { _states.AddRange(_types .Where(t => typeof(State<TSwitches>).IsAssignableFrom(t)) .ToDictionary(t => t, instanceCreator.Create<TSwitches>)); _states.ForEach(i => i.Value.Configure(this)); } public State<TSwitches> GetStateFor<TState>() { var stateType = typeof(TState); if (_states.ContainsKey(stateType) == false) { throw new UnknownStateException(stateType); } return _states[stateType]; } } }
lgpl-2.1
C#
b5faca60738ec0f5e1f69605d23e1b05825acc78
Support responses for collectors, and commonise
bcemmett/SurveyMonkeyApi-v3,davek17/SurveyMonkeyApi-v3
SurveyMonkey/SurveyMonkeyApi.Responses.cs
SurveyMonkey/SurveyMonkeyApi.Responses.cs
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; using SurveyMonkey.Containers; using SurveyMonkey.RequestSettings; namespace SurveyMonkey { public partial class SurveyMonkeyApi { private enum SurveyOrCollector { Survey, Collector } public List<Response> GetSurveyResponseOverviews(int id) { return GetResponsesRequest(id, false, SurveyOrCollector.Survey); } public List<Response> GetSurveyResponseDetails(int id) { return GetResponsesRequest(id, true, SurveyOrCollector.Survey); } public List<Response> GetCollectorResponseOverviews(int id) { return GetResponsesRequest(id, false, SurveyOrCollector.Collector); } public List<Response> GetCollectorResponseDetails(int id) { return GetResponsesRequest(id, true, SurveyOrCollector.Collector); } private List<Response> GetResponsesRequest(int id, bool details, SurveyOrCollector source) { var bulk = details ? "/bulk" : String.Empty; string endPoint = String.Format("https://api.surveymonkey.net/v3/{0}s/{1}/responses{2}", source.ToString().ToLower(), id, bulk); var verb = Verb.GET; JToken result = MakeApiRequest(endPoint, verb, new RequestData()); var responses = result["data"].ToObject<List<Response>>(); return responses; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; using SurveyMonkey.Containers; using SurveyMonkey.RequestSettings; namespace SurveyMonkey { public partial class SurveyMonkeyApi { public List<Response> GetResponseOverviews(int id) { string endPoint = String.Format("https://api.surveymonkey.net/v3/surveys/{0}/responses", id); var verb = Verb.GET; JToken result = MakeApiRequest(endPoint, verb, new RequestData()); var responses = result["data"].ToObject<List<Response>>(); return responses; } public List<Response> GetResponseDetails(int id) { string endPoint = String.Format("https://api.surveymonkey.net/v3/surveys/{0}/responses/bulk", id); var verb = Verb.GET; JToken result = MakeApiRequest(endPoint, verb, new RequestData()); var responses = result["data"].ToObject<List<Response>>(); return responses; } } }
mit
C#
2e56571dbca02f837f3be06a81c3c28344f934f7
Bump to 0.2.1.
aldentea/SweetMutus
SweetMutusData/Properties/AssemblyInfo.cs
SweetMutusData/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("SweetMutusData")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SweetMutusData")] [assembly: AssemblyCopyright("Copyright © aldentea 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("106e8563-1dc8-4f4c-9b44-73f44d659382")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.1.0")] [assembly: AssemblyFileVersion("0.2.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("SweetMutusData")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SweetMutusData")] [assembly: AssemblyCopyright("Copyright © aldentea 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("106e8563-1dc8-4f4c-9b44-73f44d659382")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
mit
C#
4b50b40583ab6aba26c5c86443312d25a68b8fe0
Add a failing test for the MultipleDatabase issue originally reported by ANT1.
castleproject/Castle.Facilities.Wcf-READONLY,castleproject/Castle.Transactions,castleproject/Castle.Transactions,castleproject/Castle.Facilities.Wcf-READONLY,carcer/Castle.Components.Validator,codereflection/Castle.Components.Scheduler,castleproject/castle-READONLY-SVN-dump,castleproject/castle-READONLY-SVN-dump,castleproject/Castle.Transactions,castleproject/castle-READONLY-SVN-dump
ActiveRecord/Castle.ActiveRecord.Tests/MultipleDatabasesTestCase.cs
ActiveRecord/Castle.ActiveRecord.Tests/MultipleDatabasesTestCase.cs
// Copyright 2004-2007 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.ActiveRecord.Tests { using Castle.ActiveRecord.Framework; using Castle.ActiveRecord.Tests.Model; using NUnit.Framework; [TestFixture] public class MultipleDatabasesTestCase : AbstractActiveRecordTest { [SetUp] public void Setup() { base.Init(); ActiveRecordStarter.Initialize( GetConfigSource(), typeof(Blog), typeof(Post), typeof(Hand), typeof(Test2ARBase) ); Recreate(); } [Test] public void OperateOne() { Blog[] blogs = Blog.FindAll(); Assert.AreEqual(0, blogs.Length); CreateBlog(); blogs = Blog.FindAll(); Assert.AreEqual(1, blogs.Length); } private static void CreateBlog() { Blog blog = new Blog(); blog.Author = "Henry"; blog.Name = "Senseless"; blog.Save(); } [Test] public void OperateTheOtherOne() { Hand[] hands = Hand.FindAll(); Assert.AreEqual(0, hands.Length); CreateHand(); hands = Hand.FindAll(); Assert.AreEqual(1, hands.Length); } private static void CreateHand() { Hand hand = new Hand(); hand.Side = "Right"; hand.Save(); } [Test] public void OperateBoth() { Blog[] blogs = Blog.FindAll(); Hand[] hands = Hand.FindAll(); Assert.AreEqual(0, blogs.Length); Assert.AreEqual(0, hands.Length); CreateBlog(); CreateHand(); blogs = Blog.FindAll(); hands = Hand.FindAll(); Assert.AreEqual(1, blogs.Length); Assert.AreEqual(1, hands.Length); } [Test] [Ignore] [ExpectedException(typeof(ActiveRecordInitializationException))] public void MultipleDatabaseInvalidConfigWhenNotRegisterBaseClass() { base.Init(); //Not registering the base class should not cause AR to silently ignore the configuration //for the type meaning all classes would use a single database. //if there is a type in the config which is not registered - but a subclass is then we should throw. ActiveRecordStarter.Initialize(GetConfigSource(), typeof(Blog), typeof(Post), typeof(Hand)); Recreate(); } } }
// Copyright 2004-2007 Castle Project - http://www.castleproject.org/ // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Castle.ActiveRecord.Tests { using Castle.ActiveRecord.Tests.Model; using NUnit.Framework; [TestFixture] public class MultipleDatabasesTestCase : AbstractActiveRecordTest { [SetUp] public void Setup() { base.Init(); ActiveRecordStarter.Initialize( GetConfigSource(), typeof(Blog), typeof(Post), typeof(Hand), typeof(Test2ARBase) ); Recreate(); } [Test] public void OperateOne() { Blog[] blogs = Blog.FindAll(); Assert.AreEqual(0, blogs.Length); CreateBlog(); blogs = Blog.FindAll(); Assert.AreEqual(1, blogs.Length); } private static void CreateBlog() { Blog blog = new Blog(); blog.Author = "Henry"; blog.Name = "Senseless"; blog.Save(); } [Test] public void OperateTheOtherOne() { Hand[] hands = Hand.FindAll(); Assert.AreEqual(0, hands.Length); CreateHand(); hands = Hand.FindAll(); Assert.AreEqual(1, hands.Length); } private static void CreateHand() { Hand hand = new Hand(); hand.Side = "Right"; hand.Save(); } [Test] public void OperateBoth() { Blog[] blogs = Blog.FindAll(); Hand[] hands = Hand.FindAll(); Assert.AreEqual(0, blogs.Length); Assert.AreEqual(0, hands.Length); CreateBlog(); CreateHand(); blogs = Blog.FindAll(); hands = Hand.FindAll(); Assert.AreEqual(1, blogs.Length); Assert.AreEqual(1, hands.Length); } } }
apache-2.0
C#
384d5c110eb8268ade4f18fd910eb03dcc5bcd48
Move AudioSource to observable also and add field attributes
jnissin/Air-Hockey,jnissin/Air-Hockey
Assets/Scripts/PuckController.cs
Assets/Scripts/PuckController.cs
using UnityEngine; using System.Collections; using UniRx; using UniRx.Triggers; public class PuckController : MonoBehaviour { [SerializeField] private GameObject _trail = null; [SerializeField] private AudioSource _audioSource = null; [SerializeField] private Rigidbody2D _rigidbody = null; public AudioSource AudioSource { get { return _audioSource; } protected set { _audioSource = value; } } public Rigidbody2D Rigidbody { get { return _rigidbody; } protected set { _rigidbody = value; } } public GameObject Trail { get { return _trail; } protected set { _trail = value; } } // Use this for initialization void Start () { AudioSource = GetComponent<AudioSource> (); Rigidbody = GetComponent<Rigidbody2D> (); this.UpdateAsObservable () .Select (_ => GetPositionVector ()) .DistinctUntilChanged () .Subscribe (position => Trail.transform.localPosition = position); this.OnCollisionEnter2DAsObservable () .Subscribe (_ => AudioSource.Play ()); } Vector3 GetPositionVector () { if (Rigidbody.velocity.magnitude > 0.0f) { Vector2 posXY = Rigidbody.velocity.normalized * -0.2f; return new Vector3 (posXY.x, posXY.y, 0.0f); } else { return Vector3.zero; } } }
using UnityEngine; using System.Collections; using UniRx; using UniRx.Triggers; public class PuckController : MonoBehaviour { [SerializeField] private GameObject _trail = null; private AudioSource _audioSource = null; private Rigidbody2D _rigidbody = null; public AudioSource AudioSource { get { return _audioSource; } protected set { _audioSource = value; } } public Rigidbody2D Rigidbody { get { return _rigidbody; } protected set { _rigidbody = value; } } public GameObject Trail { get { return _trail; } protected set { _trail = value; } } // Use this for initialization void Start () { AudioSource = GetComponent<AudioSource> (); Rigidbody = GetComponent<Rigidbody2D> (); this.UpdateAsObservable () .Select (_ => GetPositionVector ()) .DistinctUntilChanged () .Subscribe (position => Trail.transform.localPosition = position); } Vector3 GetPositionVector () { if (Rigidbody.velocity.magnitude > 0.0f) { Vector2 posXY = Rigidbody.velocity.normalized * -0.2f; return new Vector3 (posXY.x, posXY.y, 0.0f); } else { return Vector3.zero; } } void OnCollisionEnter2D (Collision2D collision) { AudioSource.Play (); } }
mit
C#
916a9be3469d51c98c296bd04d81b42144f8e739
Add connection pruning test (currently just fails)
madelson/DistributedLock
DistributedLock.Tests/Tests/Postgres/PostgresDistributedLockTest.cs
DistributedLock.Tests/Tests/Postgres/PostgresDistributedLockTest.cs
using Medallion.Threading.Postgres; using Microsoft.Data.SqlClient; using Npgsql; using NUnit.Framework; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Medallion.Threading.Tests.Tests.Postgres { public class PostgresDistributedLockTest { [Test] public async Task TestInt64AndInt32PairKeyNamespacesAreDifferent() { var connectionString = TestingPostgresDistributedLockEngine.GetConnectionString(); var key1 = new PostgresAdvisoryLockKey(0); var key2 = new PostgresAdvisoryLockKey(0, 0); var @lock1 = new PostgresDistributedLock(key1, connectionString); var @lock2 = new PostgresDistributedLock(key2, connectionString); using var handle1 = await lock1.TryAcquireAsync(); Assert.IsNotNull(handle1); using var handle2 = await lock2.TryAcquireAsync(); Assert.IsNotNull(handle2); } // todo probably just always needs keepalive [Test] public async Task TestIdleConnectionPruning() { var connectionString = new NpgsqlConnectionStringBuilder(TestingPostgresDistributedLockEngine.GetConnectionString()) { ConnectionIdleLifetime = 1, ConnectionPruningInterval = 1, MaxPoolSize = 1, Timeout = 2, }.ConnectionString; var @lock = new PostgresDistributedLock(new PostgresAdvisoryLockKey("IdeConPru"), connectionString); using var handle1 = await @lock.AcquireAsync(); await Task.Delay(TimeSpan.FromSeconds(.5)); using var handle2 = await @lock.TryAcquireAsync(TimeSpan.FromSeconds(5)); Assert.IsNotNull(handle2); } // todo idle pruning interval? } }
using Medallion.Threading.Postgres; using Microsoft.Data.SqlClient; using Npgsql; using NUnit.Framework; using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Medallion.Threading.Tests.Tests.Postgres { public class PostgresDistributedLockTest { [Test] public async Task TestInt64AndInt32PairKeyNamespacesAreDifferent() { var connectionString = TestingPostgresDistributedLockEngine.GetConnectionString(); var key1 = new PostgresAdvisoryLockKey(0); var key2 = new PostgresAdvisoryLockKey(0, 0); var @lock1 = new PostgresDistributedLock(key1, connectionString); var @lock2 = new PostgresDistributedLock(key2, connectionString); using var handle1 = await lock1.TryAcquireAsync(); Assert.IsNotNull(handle1); using var handle2 = await lock2.TryAcquireAsync(); Assert.IsNotNull(handle2); } // todo idle pruning interval? } }
mit
C#
3b208e88b1ca744360736dcd2a407d5751a890e4
Fix DisableEvent in GTK Expander Backend
TheBrainTech/xwt,hamekoz/xwt,cra0zy/xwt,residuum/xwt,mono/xwt,akrisiun/xwt,antmicro/xwt,mminns/xwt,iainx/xwt,steffenWi/xwt,lytico/xwt,sevoku/xwt,hwthomas/xwt,mminns/xwt,directhex/xwt
Xwt.Gtk/Xwt.GtkBackend/ExpanderBackend.cs
Xwt.Gtk/Xwt.GtkBackend/ExpanderBackend.cs
using System; using Xwt; using Xwt.Backends; namespace Xwt.GtkBackend { public class ExpanderBackend : WidgetBackend, IExpanderBackend { public ExpanderBackend () { Widget = new Gtk.Expander (string.Empty); Widget.Show (); } protected new Gtk.Expander Widget { get { return (Gtk.Expander)base.Widget; } set { base.Widget = value; } } protected new IExpandEventSink EventSink { get { return (IExpandEventSink)base.EventSink; } } public string Label { get { return Widget.Label; } set { Widget.Label = value; } } public bool Expanded { get { return Widget.Expanded; } set { Widget.Expanded = value; } } public void SetContent (IWidgetBackend child) { Widget.Child = GetWidget (child); } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is ExpandEvent) { if ((ExpandEvent)eventId == ExpandEvent.ExpandChanged) Widget.Activated += HandleExpandedChanged; } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is ExpandEvent) { if ((ExpandEvent)eventId == ExpandEvent.ExpandChanged) Widget.Activated -= HandleExpandedChanged; } } void HandleExpandedChanged (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.ExpandChanged (); }); } } }
using System; using Xwt; using Xwt.Backends; namespace Xwt.GtkBackend { public class ExpanderBackend : WidgetBackend, IExpanderBackend { public ExpanderBackend () { Widget = new Gtk.Expander (string.Empty); Widget.Show (); } protected new Gtk.Expander Widget { get { return (Gtk.Expander)base.Widget; } set { base.Widget = value; } } protected new IExpandEventSink EventSink { get { return (IExpandEventSink)base.EventSink; } } public string Label { get { return Widget.Label; } set { Widget.Label = value; } } public bool Expanded { get { return Widget.Expanded; } set { Widget.Expanded = value; } } public void SetContent (IWidgetBackend child) { Widget.Child = GetWidget (child); } public override void EnableEvent (object eventId) { base.EnableEvent (eventId); if (eventId is ExpandEvent) { if ((ExpandEvent)eventId == ExpandEvent.ExpandChanged) Widget.Activated += HandleExpandedChanged; } } public override void DisableEvent (object eventId) { base.DisableEvent (eventId); if (eventId is ExpandEvent) { if ((ExpandEvent)eventId == ExpandEvent.ExpandChanged) Widget.Activated += HandleExpandedChanged; } } void HandleExpandedChanged (object sender, EventArgs e) { ApplicationContext.InvokeUserCode (delegate { EventSink.ExpandChanged (); }); } } }
mit
C#
d082031864be01b9dfa1777f7573daa6b9643c73
Fix encodig DataProviderInfoStub to UTF-8
InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform
InfinniPlatform.Reporting.Tests/DataSources/DataProviderInfoStub.cs
InfinniPlatform.Reporting.Tests/DataSources/DataProviderInfoStub.cs
using InfinniPlatform.FastReport.Templates.Data; namespace InfinniPlatform.Reporting.Tests.DataSources { internal sealed class DataProviderInfoStub : IDataProviderInfo { } }
using InfinniPlatform.FastReport.Templates.Data; namespace InfinniPlatform.Reporting.Tests.DataSources { internal sealed class DataProviderInfoStub : IDataProviderInfo { } }
agpl-3.0
C#
2f3dd81b37cc1c8397f70d08651439344c2b480f
test update
Ar3sDevelopment/UnitOfWork.NET.EntityFramework
UnitOfWork.NET.EntityFramework.NUnit/Repositories/UserRepository.cs
UnitOfWork.NET.EntityFramework.NUnit/Repositories/UserRepository.cs
using System; using System.Linq; using System.Collections.Generic; using UnitOfWork.NET.EntityFramework.Classes; using UnitOfWork.NET.EntityFramework.NUnit.Data.Models; using UnitOfWork.NET.EntityFramework.NUnit.DTO; using UnitOfWork.NET.Interfaces; using System.Linq.Dynamic; namespace UnitOfWork.NET.EntityFramework.NUnit.Repositories { public class UserRepository : EntityRepository<User, UserDTO> { public UserRepository(IUnitOfWork manager) : base(manager) { } public IEnumerable<UserDTO> NewList() { Console.WriteLine("NewList"); return List(); } public override void OnSaveChanges(IDictionary<System.Data.Entity.EntityState, IEnumerable<User>> entities) { base.OnSaveChanges(entities); Console.WriteLine("On User Save Changes"); Console.WriteLine("Users saving: " + string.Join(", ", entities.SelectMany(t => t.Value.Select(u => u.Login)))); } } }
using System; using System.Collections.Generic; using UnitOfWork.NET.EntityFramework.Classes; using UnitOfWork.NET.EntityFramework.NUnit.Data.Models; using UnitOfWork.NET.EntityFramework.NUnit.DTO; using UnitOfWork.NET.Interfaces; namespace UnitOfWork.NET.EntityFramework.NUnit.Repositories { public class UserRepository : EntityRepository<User, UserDTO> { public UserRepository(IUnitOfWork manager) : base(manager) { } public IEnumerable<UserDTO> NewList() { Console.WriteLine("NewList"); return List(); } } }
mit
C#
ad10bcb5c05a90b2ee5496a478bf17b434c4ee94
Replace Courier New dependency
GetTabster/Tabster
Plugins/FileTypes/PdfFile/PdfFileExporter.cs
Plugins/FileTypes/PdfFile/PdfFileExporter.cs
#region using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using Tabster.Core.Types; using Tabster.Data; using Tabster.Data.Processing; using Version = System.Version; #endregion namespace PdfFile { public class PdfFileExporter : ITablatureFileExporter { public PdfFileExporter() { FileType = new FileType("PDF File", ".pdf"); } #region Implementation of ITablatureFileExporter public FileType FileType { get; private set; } public Version Version { get { return new Version("1.0"); } } public void Export(ITablatureFile file, string fileName, TablatureFileExportArguments args) { var plugin = new PdfFilePlugin(); var font = new Font(Font.FontFamily.COURIER, 9F); using (var fs = new FileStream(fileName, FileMode.Create)) { var pdfdoc = new Document(); using (var writer = PdfWriter.GetInstance(pdfdoc, fs)) { pdfdoc.AddCreator(string.Format("{0} {1}", plugin.DisplayName, plugin.Version)); pdfdoc.AddTitle(file.ToFriendlyString()); pdfdoc.Open(); pdfdoc.Add(new Paragraph(file.Contents, font)); pdfdoc.Close(); } } } #endregion } }
#region using System; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using Tabster.Core.Types; using Tabster.Data; using Tabster.Data.Processing; using Version = System.Version; #endregion namespace PdfFile { public class PdfFileExporter : ITablatureFileExporter { private readonly Font _font; public PdfFileExporter() { FileType = new FileType("PDF File", ".pdf"); //register system fonts directory before loading fonts var fontsDirectory = Path.Combine(Directory.GetParent(Environment.GetFolderPath(Environment.SpecialFolder.System)).FullName, "Fonts"); FontFactory.RegisterDirectory(fontsDirectory); _font = FontFactory.GetFont("Courier New", 9F, BaseColor.BLACK); } #region Implementation of ITablatureFileExporter public FileType FileType { get; private set; } public Version Version { get { return new Version("1.0"); } } public void Export(ITablatureFile file, string fileName) { var plugin = new PdfFilePlugin(); using (var fs = new FileStream(fileName, FileMode.Create)) { var pdfdoc = new Document(); using (var writer = PdfWriter.GetInstance(pdfdoc, fs)) { pdfdoc.AddCreator(string.Format("{0} {1}", plugin.DisplayName, plugin.Version)); pdfdoc.AddTitle(file.ToFriendlyString()); pdfdoc.Open(); pdfdoc.Add(new Paragraph(file.Contents, _font)); pdfdoc.Close(); } } } #endregion } }
apache-2.0
C#
ba20e689f46c311cac2a6b93581772fa6ee8b1cc
Fix DateTimeFormatInfoGetInstance.GetInstance test
wtgodbe/corefx,parjong/corefx,alexperovich/corefx,Petermarcu/corefx,parjong/corefx,zhenlan/corefx,DnlHarvey/corefx,mazong1123/corefx,axelheer/corefx,rjxby/corefx,Jiayili1/corefx,shimingsg/corefx,dhoehna/corefx,shimingsg/corefx,dhoehna/corefx,ptoonen/corefx,dotnet-bot/corefx,zhenlan/corefx,alexperovich/corefx,weltkante/corefx,fgreinacher/corefx,gkhanna79/corefx,axelheer/corefx,twsouthwick/corefx,krk/corefx,dotnet-bot/corefx,billwert/corefx,mazong1123/corefx,MaggieTsang/corefx,nchikanov/corefx,axelheer/corefx,Jiayili1/corefx,ravimeda/corefx,wtgodbe/corefx,dotnet-bot/corefx,tijoytom/corefx,mmitche/corefx,axelheer/corefx,Ermiar/corefx,richlander/corefx,ViktorHofer/corefx,Jiayili1/corefx,BrennanConroy/corefx,seanshpark/corefx,yizhang82/corefx,tijoytom/corefx,jlin177/corefx,rahku/corefx,dotnet-bot/corefx,seanshpark/corefx,fgreinacher/corefx,yizhang82/corefx,alexperovich/corefx,dhoehna/corefx,Petermarcu/corefx,parjong/corefx,parjong/corefx,weltkante/corefx,mazong1123/corefx,nbarbettini/corefx,nbarbettini/corefx,krytarowski/corefx,Petermarcu/corefx,Petermarcu/corefx,tijoytom/corefx,nchikanov/corefx,YoupHulsebos/corefx,stephenmichaelf/corefx,nbarbettini/corefx,ViktorHofer/corefx,twsouthwick/corefx,nchikanov/corefx,ravimeda/corefx,krytarowski/corefx,the-dwyer/corefx,stone-li/corefx,shimingsg/corefx,billwert/corefx,stephenmichaelf/corefx,DnlHarvey/corefx,weltkante/corefx,zhenlan/corefx,rubo/corefx,twsouthwick/corefx,dhoehna/corefx,MaggieTsang/corefx,marksmeltzer/corefx,Ermiar/corefx,marksmeltzer/corefx,yizhang82/corefx,Ermiar/corefx,parjong/corefx,dotnet-bot/corefx,DnlHarvey/corefx,Ermiar/corefx,elijah6/corefx,fgreinacher/corefx,rjxby/corefx,gkhanna79/corefx,lggomez/corefx,the-dwyer/corefx,Jiayili1/corefx,wtgodbe/corefx,seanshpark/corefx,nchikanov/corefx,richlander/corefx,wtgodbe/corefx,Ermiar/corefx,rubo/corefx,dhoehna/corefx,ptoonen/corefx,cydhaselton/corefx,rahku/corefx,marksmeltzer/corefx,marksmeltzer/corefx,elijah6/corefx,rubo/corefx,twsouthwick/corefx,stephenmichaelf/corefx,lggomez/corefx,nbarbettini/corefx,elijah6/corefx,richlander/corefx,dotnet-bot/corefx,stone-li/corefx,weltkante/corefx,marksmeltzer/corefx,DnlHarvey/corefx,the-dwyer/corefx,nbarbettini/corefx,ericstj/corefx,rjxby/corefx,richlander/corefx,billwert/corefx,mmitche/corefx,mazong1123/corefx,Petermarcu/corefx,cydhaselton/corefx,lggomez/corefx,nchikanov/corefx,cydhaselton/corefx,jlin177/corefx,ericstj/corefx,cydhaselton/corefx,the-dwyer/corefx,stone-li/corefx,Ermiar/corefx,yizhang82/corefx,ericstj/corefx,zhenlan/corefx,cydhaselton/corefx,ViktorHofer/corefx,twsouthwick/corefx,JosephTremoulet/corefx,tijoytom/corefx,JosephTremoulet/corefx,Petermarcu/corefx,ravimeda/corefx,jlin177/corefx,lggomez/corefx,rjxby/corefx,yizhang82/corefx,mazong1123/corefx,zhenlan/corefx,seanshpark/corefx,MaggieTsang/corefx,ViktorHofer/corefx,nbarbettini/corefx,nbarbettini/corefx,rjxby/corefx,seanshpark/corefx,stone-li/corefx,cydhaselton/corefx,parjong/corefx,ptoonen/corefx,stone-li/corefx,stephenmichaelf/corefx,weltkante/corefx,ptoonen/corefx,stone-li/corefx,mmitche/corefx,rahku/corefx,dotnet-bot/corefx,cydhaselton/corefx,ptoonen/corefx,nchikanov/corefx,elijah6/corefx,shimingsg/corefx,seanshpark/corefx,Petermarcu/corefx,seanshpark/corefx,JosephTremoulet/corefx,jlin177/corefx,BrennanConroy/corefx,nchikanov/corefx,jlin177/corefx,ravimeda/corefx,tijoytom/corefx,krk/corefx,twsouthwick/corefx,tijoytom/corefx,krytarowski/corefx,wtgodbe/corefx,billwert/corefx,YoupHulsebos/corefx,the-dwyer/corefx,billwert/corefx,JosephTremoulet/corefx,yizhang82/corefx,krytarowski/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,weltkante/corefx,krk/corefx,parjong/corefx,Jiayili1/corefx,Jiayili1/corefx,gkhanna79/corefx,ericstj/corefx,billwert/corefx,krk/corefx,MaggieTsang/corefx,fgreinacher/corefx,shimingsg/corefx,axelheer/corefx,wtgodbe/corefx,krk/corefx,krk/corefx,DnlHarvey/corefx,rahku/corefx,YoupHulsebos/corefx,rjxby/corefx,ericstj/corefx,the-dwyer/corefx,gkhanna79/corefx,ravimeda/corefx,gkhanna79/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,gkhanna79/corefx,yizhang82/corefx,stone-li/corefx,richlander/corefx,alexperovich/corefx,marksmeltzer/corefx,tijoytom/corefx,JosephTremoulet/corefx,MaggieTsang/corefx,marksmeltzer/corefx,krytarowski/corefx,DnlHarvey/corefx,ViktorHofer/corefx,wtgodbe/corefx,elijah6/corefx,lggomez/corefx,gkhanna79/corefx,lggomez/corefx,rahku/corefx,rubo/corefx,ravimeda/corefx,alexperovich/corefx,mmitche/corefx,twsouthwick/corefx,mazong1123/corefx,BrennanConroy/corefx,alexperovich/corefx,richlander/corefx,ViktorHofer/corefx,weltkante/corefx,Jiayili1/corefx,mazong1123/corefx,DnlHarvey/corefx,stephenmichaelf/corefx,ptoonen/corefx,elijah6/corefx,jlin177/corefx,rjxby/corefx,alexperovich/corefx,mmitche/corefx,mmitche/corefx,richlander/corefx,rahku/corefx,krytarowski/corefx,shimingsg/corefx,krytarowski/corefx,dhoehna/corefx,stephenmichaelf/corefx,elijah6/corefx,ravimeda/corefx,ptoonen/corefx,lggomez/corefx,ericstj/corefx,Ermiar/corefx,stephenmichaelf/corefx,axelheer/corefx,ericstj/corefx,mmitche/corefx,dhoehna/corefx,krk/corefx,YoupHulsebos/corefx,jlin177/corefx,MaggieTsang/corefx,zhenlan/corefx,rubo/corefx,YoupHulsebos/corefx,billwert/corefx,shimingsg/corefx,rahku/corefx,zhenlan/corefx,JosephTremoulet/corefx,the-dwyer/corefx,YoupHulsebos/corefx
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoGetInstance.cs
src/System.Globalization/tests/DateTimeFormatInfo/DateTimeFormatInfoGetInstance.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class TestIFormatProviderClass : IFormatProvider { public object GetFormat(Type formatType) { return this; } } public class TestIFormatProviderClass2 : IFormatProvider { public object GetFormat(Type formatType) { return new DateTimeFormatInfo(); } } public class DateTimeFormatInfoGetInstance { public static IEnumerable<object[]> GetInstance_NotNull_TestData() { yield return new object[] { new DateTimeFormatInfo() }; yield return new object[] { new CultureInfo("en-US") }; yield return new object[] { new TestIFormatProviderClass2() }; } [Theory] [MemberData(nameof(GetInstance_NotNull_TestData))] public void GetInstance_NotNull(IFormatProvider provider) { Assert.NotNull(DateTimeFormatInfo.GetInstance(provider)); } [Fact] public void GetInstance_ExpectedCurrent() { Assert.Same(DateTimeFormatInfo.CurrentInfo, DateTimeFormatInfo.GetInstance(null)); Assert.Same(DateTimeFormatInfo.CurrentInfo, DateTimeFormatInfo.GetInstance(new TestIFormatProviderClass())); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Globalization.Tests { public class TestIFormatProviderClass : IFormatProvider { public object GetFormat(Type formatType) { return this; } } public class TestIFormatProviderClass2 : IFormatProvider { public object GetFormat(Type formatType) { return new DateTimeFormatInfo(); } } public class DateTimeFormatInfoGetInstance { public static IEnumerable<object[]> GetInstance_NotNull_TestData() { yield return new object[] { new DateTimeFormatInfo() }; yield return new object[] { new CultureInfo("en-US") }; yield return new object[] { new TestIFormatProviderClass2() }; } [Theory] [MemberData(nameof(GetInstance_NotNull_TestData))] public void GetInstance(IFormatProvider provider) { Assert.NotNull(DateTimeFormatInfo.GetInstance(provider)); } public static IEnumerable<object[]> GetInstance_Specific_TestData() { yield return new object[] { null, DateTimeFormatInfo.CurrentInfo }; yield return new object[] { new TestIFormatProviderClass(), DateTimeFormatInfo.CurrentInfo }; } [Theory] [MemberData(nameof(GetInstance_Specific_TestData))] public void GetInstance(IFormatProvider provider, DateTimeFormatInfo expected) { Assert.Equal(expected, DateTimeFormatInfo.GetInstance(provider)); } } }
mit
C#
ec01e79cab725b6dcabf107b0df051a1be849051
Fix NLogConsumer
YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata/Logging/NLogConsumer.cs
src/Atata/Logging/NLogConsumer.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Atata { public class NLogConsumer : ILogConsumer { private readonly dynamic logger; private readonly Type logEventInfoType; private readonly Dictionary<LogLevel, dynamic> logLevelsMap = new Dictionary<LogLevel, dynamic>(); public NLogConsumer(string loggerName = null) { Type logManagerType = Type.GetType("NLog.LogManager,NLog", true); logger = loggerName != null ? logManagerType.GetMethodWithThrowOnError("GetLogger", typeof(string)).Invoke(null, new[] { loggerName }) : logManagerType.GetMethodWithThrowOnError("GetCurrentClassLogger").Invoke(null, new object[0]); if (logger == null) throw new InvalidOperationException("Failed to create NLog logger."); logEventInfoType = Type.GetType("NLog.LogEventInfo,NLog", true); InitLogLevelsMap(); } private void InitLogLevelsMap() { Type logLevelType = Type.GetType("NLog.LogLevel,NLog", true); PropertyInfo allLevelsProperty = logLevelType.GetPropertyWithThrowOnError("AllLoggingLevels"); IEnumerable allLevels = (IEnumerable)allLevelsProperty.GetValue(null, new object[0]); foreach (LogLevel level in Enum.GetValues(typeof(LogLevel))) { logLevelsMap[level] = allLevels. Cast<dynamic>(). First(x => x.Name == Enum.GetName(typeof(LogLevel), level)); } } public void Log(LogEventInfo eventInfo) { dynamic otherEventInfo = ActivatorEx.CreateInstance(logEventInfoType); otherEventInfo.TimeStamp = eventInfo.Timestamp; otherEventInfo.Level = logLevelsMap[eventInfo.Level]; otherEventInfo.Message = eventInfo.Message; otherEventInfo.Exception = eventInfo.Exception; logger.Log(otherEventInfo); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace Atata { public class NLogConsumer : ILogConsumer { private readonly dynamic logger; private readonly Type logEventInfoType; private readonly Dictionary<LogLevel, dynamic> logLevelsMap = new Dictionary<LogLevel, dynamic>(); public NLogConsumer(string loggerName = null) { Type logManagerType = Type.GetType("NLog.LogManager,NLog", true); logger = loggerName != null ? logManagerType.GetMethodWithThrowOnError("GetLogger", typeof(string)).Invoke(null, new[] { loggerName }) : logManagerType.GetMethodWithThrowOnError("GetCurrentClassLogger").Invoke(null, new object[0]); if (logger == null) throw new InvalidOperationException("Failed to create NLog logger."); logEventInfoType = Type.GetType("NLog.NLog,LogEventInfo", true); InitLogLevelsMap(); } private void InitLogLevelsMap() { Type logLevelType = Type.GetType("NLog.LogLevel,NLog", true); PropertyInfo allLevelsProperty = logLevelType.GetPropertyWithThrowOnError("AllLoggingLevels"); IEnumerable allLevels = (IEnumerable)allLevelsProperty.GetValue(null, new object[0]); foreach (LogLevel level in Enum.GetValues(typeof(LogLevel))) { logLevelsMap[level] = allLevels. Cast<dynamic>(). First(x => x.Name == Enum.GetName(typeof(LogLevel), level)); } } public void Log(LogEventInfo eventInfo) { dynamic otherEventInfo = ActivatorEx.CreateInstance(logEventInfoType); otherEventInfo.TimeStamp = eventInfo.Timestamp; otherEventInfo.Level = logLevelsMap[eventInfo.Level]; otherEventInfo.Message = eventInfo.Message; otherEventInfo.Exception = eventInfo.Exception; logger.Log(otherEventInfo); } } }
apache-2.0
C#
ead15df3bb3a47f1dda24e975bc649b8b0ba8675
Add comments for XBox360Gamepad struct
mina-asham/XBox360ControllerManager
XBox360ControllerManager/XBox360Gamepad.cs
XBox360ControllerManager/XBox360Gamepad.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace XBox360ControllerManager { /// <summary> /// Struct that represents an XBox360 gamepad /// </summary> [StructLayout(LayoutKind.Sequential)] public struct XBox360Gamepad { /// <summary> /// Event count for gamepad /// </summary> public uint EventCount; /// <summary> /// Bitmask of the device digital buttons, as follows. A set bit indicates that the corresponding button is pressed. /// </summary> public XBox360GamepadButton WButtons; /// <summary> /// The current value of the left trigger analog control. The value is between 0 and 255. /// </summary> public byte BLeftTrigger; /// <summary> /// The current value of the right trigger analog control. The value is between 0 and 255. /// </summary> public byte BRightTrigger; /// <summary> /// Left thumbstick x-axis value. The value is between -32768 and 32767. /// </summary> public short SThumbLX; /// <summary> /// Left thumbstick y-axis value. The value is between -32768 and 32767. /// </summary> public short SThumbLY; /// <summary> /// Right thumbstick x-axis value. The value is between -32768 and 32767. /// </summary> public short SThumbRX; /// <summary> /// Right thumbstick y-axis value. The value is between -32768 and 32767. /// </summary> public short SThumbRY; /// <summary> /// Checks if a specific button is pressed /// </summary> /// <param name="button">Button to check</param> /// <returns>True if button is pressed, false otherwise</returns> private bool IsPressed(XBox360GamepadButton button) { return (ushort)(button & WButtons) != 0; } /// <summary> /// Get list of pressed buttons /// </summary> /// <returns>List of pressed button</returns> public List<XBox360GamepadButton> GetButtons() { return Enum.GetValues(typeof(XBox360GamepadButton)) .Cast<XBox360GamepadButton>() .Where(IsPressed) .ToList(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; namespace XBox360ControllerManager { [StructLayout(LayoutKind.Sequential)] public struct XBox360Gamepad { public uint EventCount; public XBox360GamepadButton WButtons; public byte BLeftTrigger; public byte BRightTrigger; public short SThumbLX; public short SThumbLY; public short SThumbRX; public short SThumbRY; private bool IsPressed(XBox360GamepadButton button) { return (ushort)(button & WButtons) != 0; } public List<XBox360GamepadButton> GetButtons() { return Enum.GetValues(typeof(XBox360GamepadButton)) .Cast<XBox360GamepadButton>() .Where(IsPressed) .ToList(); } } }
mit
C#
cfb8db619b3d64162c56c8de0d8d2382f0311648
optimize GetMemberInfo()
huoxudong125/Weakly,tibel/Weakly
src/Weakly/Expressions/ExpressionHelper.cs
src/Weakly/Expressions/ExpressionHelper.cs
using System.Linq.Expressions; using System.Reflection; namespace Weakly { /// <summary> /// Common extensions for <see cref="Expression"/>. /// </summary> public static class ExpressionHelper { /// <summary> /// Converts an expression into a <see cref="MemberInfo"/>. /// </summary> /// <param name="expression">The expression to convert.</param> /// <returns>The member info.</returns> public static MemberInfo GetMemberInfo(Expression expression) { expression = ((LambdaExpression)expression).Body; if (expression.NodeType == ExpressionType.Convert) { expression = ((UnaryExpression)expression).Operand; } var memberExpression = (MemberExpression) expression; return memberExpression.Member; } } }
using System.Linq.Expressions; using System.Reflection; namespace Weakly { /// <summary> /// Common extensions for <see cref="Expression"/>. /// </summary> public static class ExpressionHelper { /// <summary> /// Converts an expression into a <see cref="MemberInfo"/>. /// </summary> /// <param name="expression">The expression to convert.</param> /// <returns>The member info.</returns> public static MemberInfo GetMemberInfo(Expression expression) { var lambda = (LambdaExpression)expression; MemberExpression memberExpression; var unaryExpression = lambda.Body as UnaryExpression; if (unaryExpression != null) { memberExpression = (MemberExpression)unaryExpression.Operand; } else { memberExpression = (MemberExpression)lambda.Body; } return memberExpression.Member; } } }
mit
C#
cbccae7fecf79aba8de4f67bd5876ea99ec9bdb7
Fix merge issue
MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS
src/Host/Client/Impl/Extensions/AboutHostExtensions.cs
src/Host/Client/Impl/Extensions/AboutHostExtensions.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static readonly Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { if (_localVersion.MajorRevision != 0 || _localVersion.MinorRevision != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Reflection; using Microsoft.Common.Core; using Microsoft.R.Host.Protocol; namespace Microsoft.R.Host.Client { public static class AboutHostExtensions { private static readonly Version _localVersion; static AboutHostExtensions() { _localVersion = typeof(AboutHost).GetTypeInfo().Assembly.GetName().Version; } public static string IsHostVersionCompatible(this AboutHost aboutHost) { if (_localVersion.MajorRevision != 0 || _localVersion.MinorRevision != 0) { // Filter out debug builds var serverVersion = new Version(aboutHost.Version.Major, aboutHost.Version.Minor); var clientVersion = new Version(_localVersion.Major, _localVersion.Minor); if (serverVersion > clientVersion) { return Resources.Error_RemoteVersionHigher.FormatInvariant(aboutHost.Version, _localVersion); } if (serverVersion < clientVersion) { return Resources.Error_RemoteVersionLower.FormatInvariant(aboutHost.Version, _localVersion); } } #endif return null; } } }
mit
C#
fea5d5cfdc8fc9413ba7816cc108f4d893ac16e1
Truncate SystemClock to Seconds Precision (#1110)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Authentication/SystemClock.cs
src/Microsoft.AspNetCore.Authentication/SystemClock.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. using System; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Provides access to the normal system clock with precision in seconds. /// </summary> public class SystemClock : ISystemClock { /// <summary> /// Retrieves the current system time in UTC. /// </summary> public DateTimeOffset UtcNow { get { // the clock measures whole seconds only, to have integral expires_in results, and // because milliseconds do not round-trip serialization formats var utcNowPrecisionSeconds = new DateTime((DateTime.UtcNow.Ticks / TimeSpan.TicksPerSecond) * TimeSpan.TicksPerSecond, DateTimeKind.Utc); return new DateTimeOffset(utcNowPrecisionSeconds); } } } }
// 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. using System; namespace Microsoft.AspNetCore.Authentication { /// <summary> /// Provides access to the normal system clock. /// </summary> public class SystemClock : ISystemClock { /// <summary> /// Retrieves the current system time in UTC. /// </summary> public DateTimeOffset UtcNow { get { // the clock measures whole seconds only, to have integral expires_in results, and // because milliseconds do not round-trip serialization formats DateTimeOffset utcNow = DateTimeOffset.UtcNow; return utcNow.AddMilliseconds(-utcNow.Millisecond); } } } }
apache-2.0
C#
d17201f89f9f0b3cc1375e5fce48cc0a273c5425
Write the top-level function for checking for updates
rzhw/Squirrel.Windows,rzhw/Squirrel.Windows
src/NSync.Client/UpdateManager.cs
src/NSync.Client/UpdateManager.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using NSync.Core; namespace NSync.Client { public class UpdateManager { Func<string, Stream> openPath; Func<string, IObservable<string>> downloadUrl; string updateUrl; public UpdateManager(string url, Func<string, Stream> openPathMock = null, Func<string, IObservable<string>> downloadUrlMock = null) { updateUrl = url; openPath = openPathMock; downloadUrl = downloadUrlMock; } public IObservable<UpdateInfo> CheckForUpdate() { IEnumerable<ReleaseEntry> localReleases; using (var sr = new StreamReader(openPath(Path.Combine("packages", "RELEASES")))) { localReleases = ReleaseEntry.ParseReleaseFile(sr.ReadToEnd()); } var ret = downloadUrl(updateUrl) .Select(ReleaseEntry.ParseReleaseFile) .Select(releases => determineUpdateInfo(localReleases, releases)) .Multicast(new AsyncSubject<UpdateInfo>()); ret.Connect(); return ret; } UpdateInfo determineUpdateInfo(IEnumerable<ReleaseEntry> localReleases, IEnumerable<ReleaseEntry> remoteReleases) { if (localReleases.Count() == remoteReleases.Count()) { return null; } } } public class UpdateInfo { public string Version { get; protected set; } } }
using System; using System.IO; namespace NSync.Client { public class UpdateManager { Func<string, Stream> openPath; Func<string, IObservable<string>> downloadUrl; public UpdateManager(string url, Func<string, Stream> openPathMock = null, Func<string, IObservable<string>> downloadUrlMock = null) { openPath = openPathMock; downloadUrl = downloadUrlMock; } public IObservable<UpdateInfo> CheckForUpdate() { throw new NotImplementedException(); } } public class UpdateInfo { public string Version { get; protected set; } } }
mit
C#
10e41a4d5052bc6ccb2a72c1c8252fc40775e862
Add extension method to convert `IExceptional` to `Option`
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/OptionExtensions.cs
SolidworksAddinFramework/OptionExtensions.cs
using System; using System.Collections.Generic; using System.Collections.Immutable; using LanguageExt; using Weingartner.Exceptional; using static LanguageExt.Prelude; namespace SolidworksAddinFramework { public static class OptionExtensions { /// <summary> /// Get the value from an option. If it is none /// then a null reference exception will be raised. /// Don't use this in production please. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="option"></param> /// <returns></returns> public static T __Value__<T>(this Option<T> option) { return option.Match (v => v , () => { throw new NullReferenceException(); }); } public static Option<ImmutableList<T>> Sequence<T>(this IEnumerable<Option<T>> p) { return p.Fold( Prelude.Optional(ImmutableList<T>.Empty), (state, itemOpt) => from item in itemOpt from list in state select list.Add(item)); } /// <summary> /// Invokes the action if it is there. /// </summary> /// <param name="a"></param> public static void Invoke(this Option<Action> a) { a.IfSome(fn => fn()); } /// <summary> /// Fluent version Optional /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static Option<T> ToOption<T>(this T obj) { return Optional(obj); } public static Option<T> ToOption<T>(this IExceptional<T> obj) { return obj.Match(Some, _ => None); } } }
using System; using System.Collections.Generic; using System.Collections.Immutable; using LanguageExt; using static LanguageExt.Prelude; namespace SolidworksAddinFramework { public static class OptionExtensions { /// <summary> /// Get the value from an option. If it is none /// then a null reference exception will be raised. /// Don't use this in production please. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="option"></param> /// <returns></returns> public static T __Value__<T>(this Option<T> option) { return option.Match (v => v , () => { throw new NullReferenceException(); }); } public static Option<ImmutableList<T>> Sequence<T>(this IEnumerable<Option<T>> p) { return p.Fold( Prelude.Optional(ImmutableList<T>.Empty), (state, itemOpt) => from item in itemOpt from list in state select list.Add(item)); } /// <summary> /// Invokes the action if it is there. /// </summary> /// <param name="a"></param> public static void Invoke(this Option<Action> a) { a.IfSome(fn => fn()); } /// <summary> /// Fluent version Optional /// </summary> /// <typeparam name="T"></typeparam> /// <param name="obj"></param> /// <returns></returns> public static Option<T> ToOption<T>(this T obj) { return Optional(obj); } } }
mit
C#
86a8603b20b7ecb6e3fb8ed68a612a343ef1297c
make sure we can show a wizard outside of the staged wizard
larsbrubaker/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,jlewin/MatterControl,jlewin/MatterControl
MatterControlLib/ConfigurationPage/PrintLeveling/SetupWizards/PrinterSetupWizard.cs
MatterControlLib/ConfigurationPage/PrintLeveling/SetupWizards/PrinterSetupWizard.cs
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System.Collections; using System.Collections.Generic; using MatterHackers.VectorMath; namespace MatterHackers.MatterControl { public abstract class PrinterSetupWizard : ISetupWizard { private IEnumerator<WizardPage> pages; protected PrinterConfig printer; public PrinterSetupWizard(PrinterConfig printer) { this.printer = printer; } protected abstract IEnumerator<WizardPage> GetPages(); public abstract bool SetupRequired { get; } public abstract bool Visible { get; } public abstract bool Enabled { get; } public string Title { get; protected set; } public PrinterConfig Printer => printer; public WizardPage Current { get { if (pages == null) { // Reset enumerator, move to first item this.Reset(); this.MoveNext(); } return pages.Current; } } object IEnumerator.Current => pages.Current; public Vector2 WindowSize { get; protected set; } public bool MoveNext() { // Shutdown active page pages.Current?.Close(); // Advance return pages.MoveNext(); } public void Reset() { pages = this.GetPages(); } public virtual void Dispose() { } } }
/* Copyright (c) 2019, Lars Brubaker, John Lewin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. */ using System.Collections; using System.Collections.Generic; using MatterHackers.VectorMath; namespace MatterHackers.MatterControl { public abstract class PrinterSetupWizard : ISetupWizard { private IEnumerator<WizardPage> pages; protected PrinterConfig printer; public PrinterSetupWizard(PrinterConfig printer) { this.printer = printer; } protected abstract IEnumerator<WizardPage> GetPages(); public abstract bool SetupRequired { get; } public abstract bool Visible { get; } public abstract bool Enabled { get; } public string Title { get; protected set; } public PrinterConfig Printer => printer; public WizardPage Current => pages.Current; object IEnumerator.Current => pages.Current; public Vector2 WindowSize { get; protected set; } public bool MoveNext() { // Shutdown active page pages.Current?.Close(); // Advance return pages.MoveNext(); } public void Reset() { pages = this.GetPages(); } public virtual void Dispose() { } } }
bsd-2-clause
C#
9222a191cb4dad559601b77c5da959f88be8623f
make it easier to grasp.
bozoweed/Sanderling,Arcitectus/Sanderling,exodus444/Sanderling
src/Sanderling/Sanderling.Exe/sample/script/default.cs
src/Sanderling/Sanderling.Exe/sample/script/default.cs
// Welcome to Sanderling, the botting framework that makes eve online easily scriptable. // Got questions or a feature request? Leave a message at http://forum.botengine.de/cat/eve-online/ // The script below is a Warp to 0 Auto-Pilot, making your travels faster and thus safer. // this pattern matches strings containing "dock" or "jump". const string MenuEntryRegexPattern = "dock|jump"; while(true) { var Measurement = HostSanderling?.MemoryMeasurement?.Wert; // from the set of route element markers in the Info Panel pick the one that represents the next Waypoint/System. // We assume this is the one which is nearest to the topleft corner of the Screen which is at (0,0) var RouteElementMarkerNext = Measurement?.InfoPanelRoute?.RouteElementMarker ?.OrderByCenterDistanceToPoint(new Vektor2DInt(0, 0))?.FirstOrDefault(); if(null == RouteElementMarkerNext) { Host.Log("no route found in info panel."); goto loop; } // righclick the marker to open the contextmenu. HostSanderling.MouseClickRight(RouteElementMarkerNext); // retrieve a new measurement because we issued an Measurement = HostSanderling?.MemoryMeasurement?.Wert; // from the first menu, pick the first matching entry. var MenuEntry = Measurement?.Menu?.FirstOrDefault() ?.Entry?.FirstOrDefault(candidate => candidate.Text.RegexMatchSuccessIgnoreCase(MenuEntryRegexPattern)); if(null == MenuEntry) { Host.Log("no suitable menu entry found."); goto loop; } // click on the "dock"/"jump" menu entry to initiate warp to at 0km. HostSanderling.MouseClickLeft(MenuEntry); loop: // wait for four seconds before repeating. Host.Delay(4000); }
// Welcome to Sanderling, the botting framework that makes eve online easily scriptable. // Got questions or a feature request? Leave a message at http://forum.botengine.de/cat/eve-online/ // The script below is a 0km Autopilot. // this pattern matches strings containing "dock" or "jump". const string MenuEntryRegexPattern = "dock|jump"; while(true) { var Measurement = HostSanderling?.MemoryMeasurement?.Wert; var Menu = Measurement?.Menu?.FirstOrDefault(); // from the first menu, pick the first matching entry. var MenuEntry = Menu?.Entry?.FirstOrDefault(candidateEntry => candidateEntry.Text.RegexMatchSuccessIgnoreCase(MenuEntryRegexPattern)); if(null != MenuEntry) { HostSanderling.MouseClickLeft(MenuEntry); // wait for four seconds before repeating. Host.Delay(4000); continue; } Host.Log("no suitable menu entry found."); var InfoPanelRoute = Measurement?.InfoPanelRoute; // from the set of Waypoint markers in the Info Panel pick the one that represents the next Waypoint/System. // We assume this is the one which is nearest to the topleft corner of the Screen which is at (0,0) var RouteElementMarkerNext = InfoPanelRoute?.RouteElementMarker ?.OrderByCenterDistanceToPoint(new Vektor2DInt(0, 0))?.FirstOrDefault(); if(null != RouteElementMarkerNext) { // righclick the marker to open the contextmenu. HostSanderling.MouseClickRight(RouteElementMarkerNext); continue; } Host.Log("no route in info panel found."); // wait for four seconds before repeating. Host.Delay(4000); }
apache-2.0
C#
a29e83e7080b9396d6fd2ea34400868f8493e742
Fix lesson 5 workshop
suvroc/selenium-mail-course,Bartty9/selenium-mail-course,ronlouw/selenium-mail-course
EndToEndMailCourse/EndToEndMailCourse/05/Workshop05Tests.cs
EndToEndMailCourse/EndToEndMailCourse/05/Workshop05Tests.cs
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System.Linq; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Interactions; namespace EndToEndMailCourse._05 { [TestFixture] public class Workshop05Tests { private string testUrl = "https://suvroc.github.io/selenium-mail-course/05/workshop.html"; [Test] public void ShouldSelectAnswers() { var driver = new ChromeDriver(); driver.Navigate().GoToUrl(testUrl); var qualityElement = driver.FindElement(By.Id("procuctQualityElement")); var supportElement = driver.FindElement(By.Id("supportQualityElement")); #region TEST //var qualitySelect = new SelectElement(qualityElement); //qualitySelect.SelectByText("Good"); //var supportSelect = new SelectElement(supportElement); //supportSelect.SelectByText("Poor"); #endregion Assert.AreEqual(qualityElement.GetAttribute("value"), "good"); Assert.AreEqual(supportElement.GetAttribute("value"), "poor"); driver.Quit(); } } }
using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using System.Linq; using OpenQA.Selenium.Support.UI; using OpenQA.Selenium.Interactions; namespace EndToEndMailCourse._05 { [TestFixture] public class Workshop05Tests { private string testUrl = "https://suvroc.github.io/selenium-mail-course/05/example.html"; [Test] public void ShouldSelectAnswers() { var driver = new ChromeDriver(); driver.Navigate().GoToUrl(testUrl); var qualityElement = driver.FindElement(By.Id("procuctQualityElement")); var supportElement = driver.FindElement(By.Id("supportQualityElement")); #region TEST //var qualitySelect = new SelectElement(qualityElement); //qualitySelect.SelectByText("Good"); //var supportSelect = new SelectElement(supportElement); //supportSelect.SelectByText("Poor"); #endregion Assert.AreEqual(qualityElement.GetAttribute("value"), "good"); Assert.AreEqual(supportElement.GetAttribute("value"), "poor"); driver.Quit(); } } }
mit
C#
db2f3e21f15d061bf4905adf83ce8d36cdddd5f4
Fix LayoutMode flags
SixLabors/Fonts
src/SixLabors.Fonts/LayoutMode.cs
src/SixLabors.Fonts/LayoutMode.cs
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; namespace SixLabors.Fonts { /// <summary> /// Defines modes to determine the layout direction of text. /// </summary> [Flags] public enum LayoutMode { /// <summary> /// Text is laid out horizontally from top to bottom. /// </summary> HorizontalTopBottom = 0, /// <summary> /// Text is laid out horizontally from bottom to top. /// </summary> HorizontalBottomTop = 1 << 0, /// <summary> /// Text is laid out vertically from left to right. Currently unsupported. /// </summary> VerticalLeftRight = 1 << 1, /// <summary> /// Text is laid out vertically from right to left. Currently unsupported. /// </summary> VerticalRightLeft = 1 << 2 } }
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; namespace SixLabors.Fonts { /// <summary> /// Defines modes to determine the layout direction of text. /// </summary> [Flags] public enum LayoutMode { /// <summary> /// Text is laid out horizontally from top to bottom. /// </summary> HorizontalTopBottom = 1 << 0, /// <summary> /// Text is laid out horizontally from bottom to top. /// </summary> HorizontalBottomTop = 1 << 1, /// <summary> /// Text is laid out vertically from left to right. Currently unsupported. /// </summary> VerticalLeftRight = 1 << 2, /// <summary> /// Text is laid out vertically from right to left. Currently unsupported. /// </summary> VerticalRightLeft = 1 << 3 } }
apache-2.0
C#
1d749bfd2a0b63ab40cc3c41baaabd96514f7742
Remove potential for NullReferenceException
terrajobst/xsddoc
src/XsdDocumentation.Build/Zip.cs
src/XsdDocumentation.Build/Zip.cs
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace XsdDocumentation.Build { public sealed class Zip : Task { public string WorkingDirectory { get; set; } [Required] public string ZipFileName { get; set; } [Required] public string[] Files { get; set; } public override bool Execute() { try { CreateZipArchive(WorkingDirectory, ZipFileName, Files); } catch (Exception ex) { Log.LogErrorFromException(ex); } return !Log.HasLoggedErrors; } private static void CreateZipArchive(string workingDirectory, string zipFileName, IEnumerable<string> fileNames) { using (var fileStream = File.Create(zipFileName)) using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create)) { foreach (var fileName in fileNames) { var relativePath = GetRelativePath(fileName, workingDirectory); zipArchive.CreateEntryFromFile(fileName, relativePath, CompressionLevel.Optimal); } } } private static string GetRelativePath(string fileName, string workingDirectory) { if (!fileName.StartsWith(workingDirectory, StringComparison.OrdinalIgnoreCase)) return Path.GetFileName(fileName); var backslashCompensation = workingDirectory.EndsWith("\\") ? 1 : 0; return fileName.Substring(workingDirectory.Length + backslashCompensation); } } }
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; namespace XsdDocumentation.Build { public sealed class Zip : Task { public ITaskItem WorkingDirectory { get; set; } [Required] public ITaskItem ZipFileName { get; set; } [Required] public ITaskItem[] Files { get; set; } public override bool Execute() { try { var workingDirectory = WorkingDirectory.ItemSpec; var zipFileName = ZipFileName.ItemSpec; var fileNames = Files.Select(f => f.ItemSpec); CreateZipArchive(workingDirectory, zipFileName, fileNames); } catch (Exception ex) { Log.LogErrorFromException(ex); } return !Log.HasLoggedErrors; } private static void CreateZipArchive(string workingDirectory, string zipFileName, IEnumerable<string> fileNames) { using (var fileStream = File.Create(zipFileName)) using (var zipArchive = new ZipArchive(fileStream, ZipArchiveMode.Create)) { foreach (var fileName in fileNames) { var relativePath = GetRelativePath(fileName, workingDirectory); zipArchive.CreateEntryFromFile(fileName, relativePath, CompressionLevel.Optimal); } } } private static string GetRelativePath(string fileName, string workingDirectory) { if (!fileName.StartsWith(workingDirectory, StringComparison.OrdinalIgnoreCase)) return Path.GetFileName(fileName); var backslashCompensation = workingDirectory.EndsWith("\\") ? 1 : 0; return fileName.Substring(workingDirectory.Length + backslashCompensation); } } }
mit
C#
59e0d213ceac2fcb181855fc7e4eea43d389b308
Fix ambiguous reference
nied/ZXing.Net.Mobile,r2d2rigo/ZXing.Net.Mobile,Redth/ZXing.Net.Mobile,benyao1201/Xamarin,sephirothwzc/ZXing.Net.Mobile,syphe/ZXing.Net.Mobile
src/ZXing.Net/common/BigInteger/BigIntegerException.cs
src/ZXing.Net/common/BigInteger/BigIntegerException.cs
using System; using ZXing; namespace BigIntegerLibrary { /// <summary> /// BigInteger-related exception class. /// </summary> [System.Serializable] public sealed class BigIntegerException : Exception { /// <summary> /// BigIntegerException constructor. /// </summary> /// <param name="message">The exception message</param> /// <param name="innerException">The inner exception</param> public BigIntegerException(string message, Exception innerException) : base(message, innerException) { } } }
using System; using ZXing; namespace BigIntegerLibrary { /// <summary> /// BigInteger-related exception class. /// </summary> [Serializable] public sealed class BigIntegerException : Exception { /// <summary> /// BigIntegerException constructor. /// </summary> /// <param name="message">The exception message</param> /// <param name="innerException">The inner exception</param> public BigIntegerException(string message, Exception innerException) : base(message, innerException) { } } }
apache-2.0
C#
e4a7b43d5c2ebdafee11552678fbc7060fc22c0b
Fix jenkins test fixture
Genesis2001/Lantea
Tests/Lantea.UnitTests/JenkinsTestFixture.cs
Tests/Lantea.UnitTests/JenkinsTestFixture.cs
#if DEBUG // ----------------------------------------------------------------------------- // <copyright file="JenkinsTestFixture.cs" company="Zack Loveless"> // Copyright (c) Zack Loveless. All rights reserved. // </copyright> // ----------------------------------------------------------------------------- namespace Lantea.UnitTests { using NUnit.Framework; // ReSharper disable InconsistentNaming // ReSharper disable PossibleNullReferenceException [TestFixture] public class JenkinsTestFixture { [Test] [ExpectedException(typeof (AssertionException))] public void Jenkins_TestShouldFail() { Assert.Fail(); } [Test] [ExpectedException(typeof (InconclusiveException))] public void Jenkins_TestShouldBeInconclusive() { Assert.Inconclusive(); } [Test] public void Jenkins_TestShouldPass() { Assert.Pass(); } [Test] [ExpectedException(typeof(IgnoreException))] public void Jenkins_TestShouldBeIgnored() { Assert.Ignore(); } } // ReSharper enable InconsistentNaming // ReSharper enable PossibleNullReferenceException } #endif
#if DEBUG // ----------------------------------------------------------------------------- // <copyright file="JenkinsTestFixture.cs" company="Zack Loveless"> // Copyright (c) Zack Loveless. All rights reserved. // </copyright> // ----------------------------------------------------------------------------- namespace Lantea.UnitTests { using NUnit.Framework; // ReSharper disable InconsistentNaming // ReSharper disable PossibleNullReferenceException [TestFixture] public class JenkinsTestFixture { [Test] //[ExpectedException(typeof (AssertionException))] public void Jenkins_TestShouldFail() { Assert.Fail(); } [Test] // [ExpectedException(typeof (InconclusiveException))] public void Jenkins_TestShouldBeInconclusive() { Assert.Inconclusive(); } [Test] public void Jenkins_TestShouldPass() { Assert.Pass(); } [Test] // [ExpectedException(typeof(IgnoreException))] public void Jenkins_TestShouldBeIgnored() { Assert.Ignore(); } } // ReSharper enable InconsistentNaming // ReSharper enable PossibleNullReferenceException } #endif
mit
C#
a11b3abdc75fb0cf9e0e0d0c658a1890026eb0bd
Add comments about BDD
pawelec/todo-list,pawelec/todo-list,pawelec/todo-list,pawelec/todo-list
Tests/TodoServices.Tests/TodoServiceTests.cs
Tests/TodoServices.Tests/TodoServiceTests.cs
using Shouldly; using System; using TodoList.Services; using Xunit; namespace TodoServices.Tests { public class TodoServiceTests : IClassFixture<TodoService> { private readonly IToDoService todoService; public TodoServiceTests(TodoService todoService) { this.todoService = todoService; } [Fact] // TODO: It violates the BDD internal void Get_ByIdThatDoNotExist_ShouldReturnNull() { // Arrange int todoId = 5; // Act var item = todoService.Get(todoId); // Assert item.ShouldBeNull(); } [Fact] // TODO: It violates the BDD internal void Get_ByIdThatExist_ShouldReturnObject() { // Arrange int todoId = 1; // Act var item = todoService.Get(todoId); // Assert item.ShouldNotBeNull(); item.Id.ShouldBe(todoId); } [Fact] internal void Add_NullAsName_ShouldThrowArgumentNullException() { // Arrange string newItemName = null; // Act & Assert Action action = () => todoService.Add(newItemName); action.ShouldThrow<ArgumentNullException>(); } [Theory] [InlineData("")] [InlineData(" ")] internal void Add_NameIsEmptyOrWhitespace_ShouldThrowArgumentException(string newItemName) { // Act & Assert Action action = () => todoService.Add(newItemName); action.ShouldThrow<ArgumentException>(); } } }
using Shouldly; using System; using TodoList.Services; using Xunit; namespace TodoServices.Tests { public class TodoServiceTests : IClassFixture<TodoService> { private readonly IToDoService todoService; public TodoServiceTests(TodoService todoService) { this.todoService = todoService; } [Fact] internal void Get_ByIdThatDoNotExist_ShouldReturnNull() { // Arrange int todoId = 5; // Act var item = todoService.Get(todoId); // Assert item.ShouldBeNull(); } [Fact] internal void Get_ByIdThatExist_ShouldReturnObject() { // Arrange int todoId = 1; // Act var item = todoService.Get(todoId); // Assert item.ShouldNotBeNull(); item.Id.ShouldBe(todoId); } [Fact] internal void Add_NullAsName_ShouldThrowArgumentNullException() { // Arrange string newItemName = null; // Act & Assert Action action = () => todoService.Add(newItemName); action.ShouldThrow<ArgumentNullException>(); } [Theory] [InlineData("")] [InlineData(" ")] internal void Add_NameIsEmptyOrWhitespace_ShouldThrowArgumentException(string newItemName) { // Act & Assert Action action = () => todoService.Add(newItemName); action.ShouldThrow<ArgumentException>(); } } }
mit
C#
1b79bd8498f8e59aa2fb9fb9c67a70e2fcb8a6aa
Update LineCommentTokenScanner.cs
Zebrina/PapyrusScriptEditorVSIX,Zebrina/PapyrusScriptEditorVSIX
PapyrusScriptEditorVSIX/Language/LineCommentTokenScanner.cs
PapyrusScriptEditorVSIX/Language/LineCommentTokenScanner.cs
using Microsoft.VisualStudio.Text; using Papyrus.Common.Extensions; using Papyrus.Language.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Papyrus.Language { public class LineCommentTokenScanner : TokenScannerModule { public override bool Scan(SnapshotSpan sourceSnapshotSpan, int offset, ref TokenScannerState state, out Token token) { if (state == TokenScannerState.Text) { string text ? sourceSnapshotSpan.GetText(); if (text[offset] == (char)Delimiter.SemiColon) { token = new Token(new Comment(text.Substring(offset), false), sourceSnapshotSpan.Subspan(offset)); return true; } } token = null; return false; } } }
using Microsoft.VisualStudio.Text; using Papyrus.Common.Extensions; using Papyrus.Language.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Papyrus.Language { public class LineCommentTokenScanner : TokenScannerModule { public override bool Scan(SnapshotSpan sourceSnapshotSpan, int offset, ref TokenScannerState state, out Token token) { string text = sourceSnapshotSpan.GetText(); if (state == TokenScannerState.Text) { if (text[offset] == (char)Delimiter.SemiColon) { token = new Token(new Comment(text.Substring(offset), false), sourceSnapshotSpan.Subspan(offset)); return true; } } token = null; return false; } } }
mit
C#
2613062f66bbbdbff308d50f6688116ae2bcd252
Make props non-virtual
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University.Controls/ViewModels/AgplSignatureViewModel.cs
R7.University.Controls/ViewModels/AgplSignatureViewModel.cs
using System; using System.Reflection; using R7.University.Components; namespace R7.University.Controls.ViewModels { public class AgplSignatureViewModel { public bool ShowRule { get; set; } = true; public Assembly BaseAssembly => UniversityAssembly.GetCoreAssembly (); public string Name => BaseAssembly.GetName ().Name; public Version Version => BaseAssembly.GetName ().Version; public string InformationalVersion => BaseAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute> ()?.InformationalVersion; public string Product => BaseAssembly.GetCustomAttribute<AssemblyProductAttribute> ()?.Product ?? Name; } }
using System; using System.Reflection; using R7.University.Components; namespace R7.University.Controls.ViewModels { public class AgplSignatureViewModel { public bool ShowRule { get; set; } = true; public virtual Assembly BaseAssembly => UniversityAssembly.GetCoreAssembly (); public virtual string Name => BaseAssembly.GetName ().Name; public virtual Version Version => BaseAssembly.GetName ().Version; public virtual string InformationalVersion => BaseAssembly.GetCustomAttribute<AssemblyInformationalVersionAttribute> ()?.InformationalVersion; public virtual string Product => BaseAssembly.GetCustomAttribute<AssemblyProductAttribute> ()?.Product ?? Name; } }
agpl-3.0
C#
c906a4d1df81d167999721d5d91b2ba0b109cc51
use helper to convert image for a list item
l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto
Source/Eto.Platform.Wpf/Forms/Controls/WpfListItemHelper.cs
Source/Eto.Platform.Wpf/Forms/Controls/WpfListItemHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using sw = System.Windows; using swc = System.Windows.Controls; using swd = System.Windows.Data; using Eto.Forms; using Eto.Platform.Wpf.Drawing; namespace Eto.Platform.Wpf.Forms.Controls { public static class WpfListItemHelper { public static sw.FrameworkElementFactory ItemTemplate () { var factory = new sw.FrameworkElementFactory (typeof (swc.StackPanel)); factory.SetValue (swc.StackPanel.OrientationProperty, swc.Orientation.Horizontal); factory.AppendChild (ImageBlock ()); factory.AppendChild (TextBlock ()); return factory; } class TextConverter : swd.IValueConverter { public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var item = value as IListItem; return (item != null) ? item.Text : null; } public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException (); } } public static sw.FrameworkElementFactory TextBlock () { var factory = new sw.FrameworkElementFactory (typeof (swc.TextBlock)); factory.SetBinding (swc.TextBlock.TextProperty, new sw.Data.Binding { Converter = new TextConverter () }); return factory; } class ImageConverter : swd.IValueConverter { public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var item = value as IImageListItem; if (item == null || item.Image == null) return null; return item.Image.ToWpf (16); } public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException (); } } public static sw.FrameworkElementFactory ImageBlock () { var factory = new sw.FrameworkElementFactory (typeof (swc.Image)); factory.SetValue (swc.Image.MaxHeightProperty, 16.0); factory.SetValue (swc.Image.MaxWidthProperty, 16.0); factory.SetValue (swc.Image.StretchDirectionProperty, swc.StretchDirection.DownOnly); factory.SetValue (swc.Image.MarginProperty, new sw.Thickness (0, 2, 2, 2)); factory.SetBinding (swc.Image.SourceProperty, new sw.Data.Binding { Converter = new ImageConverter () }); return factory; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using sw = System.Windows; using swc = System.Windows.Controls; using swd = System.Windows.Data; using Eto.Forms; using Eto.Platform.Wpf.Drawing; namespace Eto.Platform.Wpf.Forms.Controls { public static class WpfListItemHelper { public static sw.FrameworkElementFactory ItemTemplate () { var factory = new sw.FrameworkElementFactory (typeof (swc.StackPanel)); factory.SetValue (swc.StackPanel.OrientationProperty, swc.Orientation.Horizontal); factory.AppendChild (ImageBlock ()); factory.AppendChild (TextBlock ()); return factory; } class TextConverter : swd.IValueConverter { public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var item = value as IListItem; return (item != null) ? item.Text : null; } public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException (); } } public static sw.FrameworkElementFactory TextBlock () { var factory = new sw.FrameworkElementFactory (typeof (swc.TextBlock)); factory.SetBinding (swc.TextBlock.TextProperty, new sw.Data.Binding { Converter = new TextConverter () }); return factory; } class ImageConverter : swd.IValueConverter { public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { var item = value as IImageListItem; if (item == null || item.Image == null) return null; return ((IWpfImage)item.Image.Handler).GetImageClosestToSize (16); } public object ConvertBack (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException (); } } public static sw.FrameworkElementFactory ImageBlock () { var factory = new sw.FrameworkElementFactory (typeof (swc.Image)); factory.SetValue (swc.Image.MaxHeightProperty, 16.0); factory.SetValue (swc.Image.MaxWidthProperty, 16.0); factory.SetValue (swc.Image.StretchDirectionProperty, swc.StretchDirection.DownOnly); factory.SetValue (swc.Image.MarginProperty, new sw.Thickness (0, 2, 2, 2)); factory.SetBinding (swc.Image.SourceProperty, new sw.Data.Binding { Converter = new ImageConverter () }); return factory; } } }
bsd-3-clause
C#
584be644c72d00a1e21eeaff214ab3a481431dfc
Add hidden fields.
EdBlankenship/typeform-dotnet
Typeform-dotnet/Typeform.Dotnet.Client/Data/FormResponse.cs
Typeform-dotnet/Typeform.Dotnet.Client/Data/FormResponse.cs
using System.Collections.Generic; using Newtonsoft.Json; using Typeform.Dotnet.Core; namespace Typeform.Dotnet.Data { public class FormResponse { [JsonConverter(typeof(BooleanConverter))] [JsonProperty("completed")] public bool Completed { get; set; } [JsonProperty("token")] public string ResponseId { get; set; } [JsonProperty("metadata")] public FormResponseMetadata Metadata { get; set; } // TODO: Handle collection [JsonProperty("hidden")] public Dictionary<string, string> Hidden { get; set; } // TODO: Handle collection [JsonProperty("answers")] public Dictionary<string, string> Answers { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; using Typeform.Dotnet.Core; namespace Typeform.Dotnet.Data { public class FormResponse { [JsonConverter(typeof(BooleanConverter))] [JsonProperty("completed")] public bool Completed { get; set; } [JsonProperty("token")] public string ResponseId { get; set; } [JsonProperty("metadata")] public FormResponseMetadata Metadata { get; set; } // TODO: Hidden // TODO: Handle Answers collection [JsonProperty("answers")] public Dictionary<string, string> Answers { get; set; } } }
apache-2.0
C#
75e3b1ddd3e62fba069b5a321caa209e1feaad18
Move abstract methods to top.
greghoover/gluon,greghoover/gluon,greghoover/gluon
hase/hase.DevLib/Framework/Relay/RelayDispatcherClientBase.cs
hase/hase.DevLib/Framework/Relay/RelayDispatcherClientBase.cs
using hase.DevLib.Framework.Contract; using System; namespace hase.DevLib.Framework.Relay { public abstract class RelayDispatcherClientBase<TService, TRequest, TResponse> : IRelayDispatcherClient<TService, TRequest, TResponse> where TService : IService<TRequest, TResponse> where TRequest : class where TResponse : class { public static readonly string ChannelName = typeof(TService).Name; public abstract string Abbr { get; } public abstract void Connect(int timeoutMs); public abstract TRequest DeserializeRequest(); public abstract void SerializeResponse(TResponse response); public virtual void Run() { Console.WriteLine($"{this.Abbr}:{ChannelName} connecting... to relay."); this.Connect(timeoutMs: 5000); Console.WriteLine($"{this.Abbr}:{ChannelName} connected to relay."); while (true) { ProcessRequest(); } } protected virtual void ProcessRequest() { //Console.WriteLine($"{this.Abbr}:Waiting to receive {ChannelName} request."); var request = this.DeserializeRequest(); Console.WriteLine($"{this.Abbr}:Received {ChannelName} request: {request}."); var response = DispatchRequest(request); Console.WriteLine($"{this.Abbr}:Sending {ChannelName} response: {response}."); this.SerializeResponse(response); //Console.WriteLine($"{this.Abbr}:Sent {ChannelName} response."); } protected virtual TResponse DispatchRequest(TRequest request) { var service = ServiceFactory<TService, TRequest, TResponse>.CreateLocalInstance(); TResponse response = default(TResponse); try { response = service.Execute(request); } catch (Exception ex) { } return response; } } }
using hase.DevLib.Framework.Contract; using System; namespace hase.DevLib.Framework.Relay { public abstract class RelayDispatcherClientBase<TService, TRequest, TResponse> : IRelayDispatcherClient<TService, TRequest, TResponse> where TService : IService<TRequest, TResponse> where TRequest : class where TResponse : class { public static readonly string ChannelName = typeof(TService).Name; public abstract string Abbr { get; } public virtual void Run() { Console.WriteLine($"{this.Abbr}:{ChannelName} connecting... to relay."); this.Connect(timeoutMs: 5000); Console.WriteLine($"{this.Abbr}:{ChannelName} connected to relay."); while (true) { ProcessRequest(); } } public abstract void Connect(int timeoutMs); public abstract TRequest DeserializeRequest(); public abstract void SerializeResponse(TResponse response); protected virtual void ProcessRequest() { //Console.WriteLine($"{this.Abbr}:Waiting to receive {ChannelName} request."); var request = this.DeserializeRequest(); Console.WriteLine($"{this.Abbr}:Received {ChannelName} request: {request}."); var response = DispatchRequest(request); Console.WriteLine($"{this.Abbr}:Sending {ChannelName} response: {response}."); this.SerializeResponse(response); //Console.WriteLine($"{this.Abbr}:Sent {ChannelName} response."); } protected virtual TResponse DispatchRequest(TRequest request) { var service = ServiceFactory<TService, TRequest, TResponse>.CreateLocalInstance(); TResponse response = default(TResponse); try { response = service.Execute(request); } catch (Exception ex) { } return response; } } }
mit
C#
1a00e4d1d3048a00dc58cd49c529e6dae41c52b5
Update namespace reference in unit comments
247Entertainment/E247.Fun
E247.Fun/Unit.cs
E247.Fun/Unit.cs
using System; #pragma warning disable 1591 namespace E247.Fun { public struct Unit : IEquatable<Unit> { public static readonly Unit Value = new Unit(); public override int GetHashCode() => 0; public override bool Equals(object obj) => obj is Unit; public override string ToString() => "()"; public bool Equals(Unit other) => true; public static bool operator ==(Unit lhs, Unit rhs) => true; public static bool operator !=(Unit lhs, Unit rhs) => false; // with using static E247.Fun.Unit, allows using unit instead of the ugly Unit.Value // ReSharper disable once InconsistentNaming public static Unit unit => Value; // with using static E247.Fun.Unit, allows using ignore(anything) to have anything return unit // ReSharper disable once InconsistentNaming public static Unit ignore<T>(T anything) => unit; } }
using System; #pragma warning disable 1591 namespace E247.Fun { public struct Unit : IEquatable<Unit> { public static readonly Unit Value = new Unit(); public override int GetHashCode() => 0; public override bool Equals(object obj) => obj is Unit; public override string ToString() => "()"; public bool Equals(Unit other) => true; public static bool operator ==(Unit lhs, Unit rhs) => true; public static bool operator !=(Unit lhs, Unit rhs) => false; // with using static E247.Juke.Model.Entities.Unit, allows using unit instead of the ugly Unit.Value // ReSharper disable once InconsistentNaming public static Unit unit => Value; // with using static E247.Juke.Model.Entities.Unit, allows using ignore(anything) to have anything return unit // ReSharper disable once InconsistentNaming public static Unit ignore<T>(T anything) => unit; } }
mit
C#
e1dc3ee1e656ba8ce5b11226672b1057fac789c0
Update ANDGate.cs
irtezasyed007/CSC523-Game-Project
Gates/ANDGate.cs
Gates/ANDGate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSC_523_Game { class ANDGate : Gate { public ANDGate(Variable[] vars) : base(vars) { } public override bool getResult() { return gateOperation(); } public override bool gateOperation() { bool assignedValue = false; bool result = false; foreach (Variable v in vars) { //Assigning a base value to the result if (!assignedValue) { result = v.getTruthValue(); assignedValue = true; } else result = result && v.getTruthValue(); } return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSC_523_Game { class ANDGate : Gate { public ANDGate(Variable [] vars) : base(vars) { } public override bool getResult() { bool assignedValue = false; bool result = false; foreach (Variable v in Variables) { if (!assignedValue) { result = v.getTruthValue(); assignedValue = true; } else result = result && v.getTruthValue(); } return result; } } }
mit
C#
62d7456804b2fff5f39f1409f4c5eeeab3fe2f0f
Change AsNonNull to NotNull return
smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework
osu.Framework/Extensions/ObjectExtensions/ObjectExtensions.cs
osu.Framework/Extensions/ObjectExtensions/ObjectExtensions.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.Diagnostics.CodeAnalysis; namespace osu.Framework.Extensions.ObjectExtensions { /// <summary> /// Extensions that apply to all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>". /// </summary> /// <remarks> /// This should only be used when an assertion or other handling is not a reasonable alternative. /// </remarks> /// <param name="obj">The nullable object.</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns> [return: NotNull] public static T AsNonNull<T>(this T? obj) => obj!; /// <summary> /// If the given object is null. /// </summary> public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null); /// <summary> /// <c>true</c> if the given object is not null, <c>false</c> otherwise. /// </summary> public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null); } }
// 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.Diagnostics.CodeAnalysis; namespace osu.Framework.Extensions.ObjectExtensions { /// <summary> /// Extensions that apply to all objects. /// </summary> public static class ObjectExtensions { /// <summary> /// Coerces a nullable object as non-nullable. This is an alternative to the C# 8 null-forgiving operator "<c>!</c>". /// </summary> /// <remarks> /// This should only be used when an assertion or other handling is not a reasonable alternative. /// </remarks> /// <param name="obj">The nullable object.</param> /// <typeparam name="T">The type of the object.</typeparam> /// <returns>The non-nullable object corresponding to <paramref name="obj"/>.</returns> [return: NotNullIfNotNull("obj")] public static T AsNonNull<T>(this T? obj) => obj!; /// <summary> /// If the given object is null. /// </summary> public static bool IsNull<T>([NotNullWhen(false)] this T obj) => ReferenceEquals(obj, null); /// <summary> /// <c>true</c> if the given object is not null, <c>false</c> otherwise. /// </summary> public static bool IsNotNull<T>([NotNullWhen(true)] this T obj) => !ReferenceEquals(obj, null); } }
mit
C#
3f42c550049bbc3ab15a79e84bb6960016670c42
Update Cities view.
SoftUni-NoSharpers/Project-X,SoftUni-NoSharpers/Project-X
Eventis/Views/Home/Cities.cshtml
Eventis/Views/Home/Cities.cshtml
<!DOCTYPE html> @model ICollection<Eventis.Models.Eventis.City> @{ ViewBag.Title = "Cities"; } <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> <div class="row, text-center" style="margin:50px"> <h1>CITIES</h1> </div> <div class="row" style="margin:50px"> <div class="col-md-1"></div> @foreach (var city in Model) { <div class="col-md-2"> <h2>@city.Name</h2> </div> } </div> <div class="row" style="margin:50px"> <div class="col-md-1"></div> @foreach (var city in Model) { <div class="col-md-2"> @foreach (var hall in city.Halls) { @hall.Name <br /> } </div> } </div> </body> </html>
<!DOCTYPE html> @model ICollection<Eventis.Models.Eventis.City> @{ ViewBag.Title = "Cities"; } <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> <div class="row" style="margin:50px"> <div class="col-md-1"></div> @foreach (var city in Model) { <div class="col-md-2"> <h2>@city.Name</h2> </div> } </div> <div class="row" style="margin:50px"> <div class="col-md-1"></div> @foreach (var city in Model) { <div class="col-md-2"> @foreach (var hall in city.Halls) { @hall.Name <br /> } </div> } </div> </body> </html>
mit
C#
081aadaa2b7a939393fab6682148780ea6a1550e
Add source documentation for playback progress item.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Objects/Get/Syncs/Playback/TraktSyncPlaybackProgressItem.cs
Source/Lib/TraktApiSharp/Objects/Get/Syncs/Playback/TraktSyncPlaybackProgressItem.cs
namespace TraktApiSharp.Objects.Get.Syncs.Playback { using Attributes; using Enums; using Movies; using Newtonsoft.Json; using Shows; using Shows.Episodes; using System; /// <summary>Contains information about a Trakt playback progress, including the corresponding movie or episode.</summary> public class TraktSyncPlaybackProgressItem { /// <summary>Gets or sets the id of this progress item.</summary> [JsonProperty(PropertyName = "id")] public int Id { get; set; } /// <summary> /// Gets or sets a value between 0 and 100 representing the watched progress percentage /// of the movie or episode. /// </summary> [JsonProperty(PropertyName = "progress")] public float? Progress { get; set; } /// <summary>Gets or sets the UTC datetime, when the watched movie or episode was paused.</summary> [JsonProperty(PropertyName = "paused_at")] public DateTime? PausedAt { get; set; } /// <summary> /// Gets or sets the object type, which this progress item contains. /// See also <seealso cref="TraktSyncType" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "type")] [JsonConverter(typeof(TraktEnumerationConverter<TraktSyncType>))] [Nullable] public TraktSyncType Type { get; set; } /// <summary> /// Gets or sets the movie, if <see cref="Type" /> is <see cref="TraktSyncType.Movie" />. /// See also <seealso cref="TraktMovie" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "movie")] [Nullable] public TraktMovie Movie { get; set; } /// <summary> /// Gets or sets the episode, if <see cref="Type" /> is <see cref="TraktSyncType.Episode" />. /// See also <seealso cref="TraktEpisode" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "episode")] [Nullable] public TraktEpisode Episode { get; set; } /// <summary> /// Gets or sets the show, if <see cref="Type" /> is <see cref="TraktSyncType.Episode" />. /// See also <seealso cref="TraktShow" />. /// <para>Nullable</para> /// </summary> [JsonProperty(PropertyName = "show")] [Nullable] public TraktShow Show { get; set; } } }
namespace TraktApiSharp.Objects.Get.Syncs.Playback { using Attributes; using Enums; using Movies; using Newtonsoft.Json; using Shows; using Shows.Episodes; using System; public class TraktSyncPlaybackProgressItem { [JsonProperty(PropertyName = "progress")] public float? Progress { get; set; } [JsonProperty(PropertyName = "paused_at")] public DateTime? PausedAt { get; set; } [JsonProperty(PropertyName = "id")] public int Id { get; set; } [JsonProperty(PropertyName = "type")] [JsonConverter(typeof(TraktEnumerationConverter<TraktSyncType>))] [Nullable] public TraktSyncType Type { get; set; } [JsonProperty(PropertyName = "movie")] [Nullable] public TraktMovie Movie { get; set; } [JsonProperty(PropertyName = "episode")] [Nullable] public TraktEpisode Episode { get; set; } [JsonProperty(PropertyName = "show")] [Nullable] public TraktShow Show { get; set; } } }
mit
C#
cd56f1c338d32055fe68a31a1d838bc3bc55813d
Enable Codecov
bbtsoftware/TfsUrlParser
setup.cake
setup.cake
#load nuget:?package=Cake.Recipe&version=1.0.0 Environment.SetVariableNames(); BuildParameters.SetParameters( context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "TfsUrlParser", repositoryOwner: "bbtsoftware", repositoryName: "TfsUrlParser", appVeyorAccountName: "BBTSoftwareAG", shouldPublishMyGet: false, shouldRunCodecov: true, shouldDeployGraphDocumentation: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings( context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
#load nuget:?package=Cake.Recipe&version=1.0.0 Environment.SetVariableNames(); BuildParameters.SetParameters( context: Context, buildSystem: BuildSystem, sourceDirectoryPath: "./src", title: "TfsUrlParser", repositoryOwner: "bbtsoftware", repositoryName: "TfsUrlParser", appVeyorAccountName: "BBTSoftwareAG", shouldPublishMyGet: false, shouldRunCodecov: false, shouldDeployGraphDocumentation: false); BuildParameters.PrintParameters(Context); ToolSettings.SetToolSettings( context: Context, dupFinderExcludePattern: new string[] { BuildParameters.RootDirectoryPath + "/src/TfsUrlParser.Tests/*.cs" }, testCoverageFilter: "+[*]* -[xunit.*]* -[*.Tests]* -[Shouldly]*", testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*", testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs"); Build.RunDotNetCore();
mit
C#
3b2face9367a59186193d1a019bfea84538ecef9
Simplify status convention based on conversation with Mr David Goodyear
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Api/Controllers/StatusController.cs
src/SFA.DAS.EmployerUsers.Api/Controllers/StatusController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SFA.DAS.EmployerUsers.Api.Controllers { [RoutePrefix("api/status")] public class StatusController : ApiController { [Route("")] public IHttpActionResult Index() { // Do some Infrastructre work here to smoke out any issues. return Ok(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SFA.DAS.EmployerUsers.Api.Controllers { [RoutePrefix("api/status")] public class StatusController : ApiController { [HttpGet, Route("")] public IHttpActionResult Index() { return Ok(); } [Route("{random}"), HttpGet] public IHttpActionResult Show(string random) { return Ok(random); } } }
mit
C#
2b4b3b0655c75d1ee63b32a2da5ff811be4ea5a1
Verify route
dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan
SnittListan/RouteConfigurator.cs
SnittListan/RouteConfigurator.cs
using System.Web.Mvc; using System.Web.Routing; using SnittListan.Helpers; namespace SnittListan { public class RouteConfigurator { private readonly RouteCollection routes; public RouteConfigurator(RouteCollection routes) { this.routes = routes; } public void Configure() { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("admin/elmah.axd/{*pathInfo}"); ConfigureAccount(); ConfigureHome(); // default route routes.MapRouteLowerCase( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults } private void ConfigureAccount() { routes.MapRouteLowerCase( "AccountController-Action", "{action}", new { controller = "Account" }, new { action = "LogOn|Register|Verify" }); } private void ConfigureHome() { routes.MapRouteLowerCase( "HomeController-Action", "{action}", new { controller = "Home" }, new { action = "About" }); } } }
using System.Web.Mvc; using System.Web.Routing; using SnittListan.Helpers; namespace SnittListan { public class RouteConfigurator { private readonly RouteCollection routes; public RouteConfigurator(RouteCollection routes) { this.routes = routes; } public void Configure() { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.IgnoreRoute("admin/elmah.axd/{*pathInfo}"); ConfigureAccount(); ConfigureHome(); // default route routes.MapRouteLowerCase( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional }); // Parameter defaults } private void ConfigureAccount() { routes.MapRouteLowerCase( "AccountController-Action", "{action}", new { controller = "Account" }, new { action = "LogOn|Register" }); } private void ConfigureHome() { routes.MapRouteLowerCase( "HomeController-Action", "{action}", new { controller = "Home" }, new { action = "About" }); } } }
mit
C#
4b1dd046e432fc7fe9e507863111a70004bae832
Change Update method in Repository.cs file.
razsilev/Sv_Naum,razsilev/Sv_Naum,razsilev/Sv_Naum
Source/SvNaum.Data/Repository.cs
Source/SvNaum.Data/Repository.cs
namespace SvNaum.Data { using System; using MongoDB.Driver; using MongoDB.Bson; using MongoDB.Driver.Builders; public class Repository { public T FindOneById<T>(MongoCollection<T> collection, string id) where T : class { T result = null; try { result = collection.FindOneById(ObjectId.Parse(id)); } catch (Exception) { } return result; } public MongoCursor<T> FindAll<T>(MongoCollection<T> collection) { MongoCursor<T> result = null; try { result = collection.FindAll(); } catch (Exception) { } return result; } public void Insert<T>(MongoCollection<T> collection, T data) { collection.Insert(data); } public void Update<T>(MongoCollection<T> collection, T data, string idUpdatedEntry) { //collection.Insert(data); //this.Delete(collection, idUpdatedEntry); var bsonData = data.ToBsonDocument(); bsonData.Remove("_id"); var update = new UpdateDocument("$set", bsonData); var query = this.CreateQueryById(idUpdatedEntry); collection.Update(query, update); } public void Delete(MongoCollection collection, string id) { IMongoQuery query = this.CreateQueryById(id); collection.Remove(query); } private IMongoQuery CreateQueryById(string id) { MongoDB.Driver.IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id)); return query; } } }
namespace SvNaum.Data { using System; using MongoDB.Driver; using MongoDB.Bson; using MongoDB.Driver.Builders; public class Repository { public T FindOneById<T>(MongoCollection<T> collection, string id) where T : class { T result = null; try { result = collection.FindOneById(ObjectId.Parse(id)); } catch (Exception) { } return result; } public MongoCursor<T> FindAll<T>(MongoCollection<T> collection) { MongoCursor<T> result = null; try { result = collection.FindAll(); } catch (Exception) { } return result; } public void Insert<T>(MongoCollection<T> collection, T data) { collection.Insert(data); } public void Update<T>(MongoCollection<T> collection, T data, string idUpdatedEntry) { collection.Insert(data); this.Delete(collection, idUpdatedEntry); } public void Delete(MongoCollection collection, string id) { IMongoQuery query = this.CreateQueryById(id); collection.Remove(query); } private IMongoQuery CreateQueryById(string id) { MongoDB.Driver.IMongoQuery query = Query.EQ("_id", ObjectId.Parse(id)); return query; } } }
mit
C#
b7077a3b43295c74e1545533a1970b6fc26d3162
bump version
Fody/Caseless
CommonAssemblyInfo.cs
CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Caseless")] [assembly: AssemblyProduct("Caseless")] [assembly: AssemblyVersion("1.4.0")] [assembly: AssemblyFileVersion("1.4.0")]
using System.Reflection; [assembly: AssemblyTitle("Caseless")] [assembly: AssemblyProduct("Caseless")] [assembly: AssemblyVersion("1.3.7")] [assembly: AssemblyFileVersion("1.3.7")]
mit
C#
a6b03672ed858e7ab638c4a6af684612ace6ed1f
use thumbnail channel for system spam
RPCS3/discord-bot
CompatBot/Watchdog.cs
CompatBot/Watchdog.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using CompatBot.Commands; using DSharpPlus; namespace CompatBot { internal static class Watchdog { private static readonly TimeSpan CheckInterval = TimeSpan.FromSeconds(10); public static readonly ConcurrentQueue<DateTime> DisconnectTimestamps = new ConcurrentQueue<DateTime>(); public static async Task Watch(DiscordClient client) { do { await Task.Delay(CheckInterval, Config.Cts.Token).ConfigureAwait(false); if (DisconnectTimestamps.IsEmpty) continue; try { var ch = await client.GetChannelAsync(Config.ThumbnailSpamId).ConfigureAwait(false); await client.SendMessageAsync(ch, "Potential socket deadlock detected, restarting...").ConfigureAwait(false); Sudo.Bot.Restart(Program.InvalidChannelId); } catch (Exception e) { Config.Log.Error(e); } } while (!Config.Cts.IsCancellationRequested); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using CompatBot.Commands; using DSharpPlus; namespace CompatBot { internal static class Watchdog { private static readonly TimeSpan CheckInterval = TimeSpan.FromSeconds(10); public static readonly ConcurrentQueue<DateTime> DisconnectTimestamps = new ConcurrentQueue<DateTime>(); public static async Task Watch(DiscordClient client) { do { await Task.Delay(CheckInterval, Config.Cts.Token).ConfigureAwait(false); if (DisconnectTimestamps.IsEmpty) continue; try { var ch = await client.GetChannelAsync(Config.BotSpamId).ConfigureAwait(false); await client.SendMessageAsync(ch, "Potential socket deadlock detected, restarting...").ConfigureAwait(false); Sudo.Bot.Restart(Program.InvalidChannelId); } catch (Exception e) { Config.Log.Error(e); } } while (!Config.Cts.IsCancellationRequested); } } }
lgpl-2.1
C#
80b8ad2c413ed941d9619f1e09e23a3e4bc01370
Revert "fix for fakeiteasy issue"
wikibus/Argolis
src/Lernaean.Hydra.Tests/ApiDocumentation/DefaultPropertyRangeRetrievalPolicyTests.cs
src/Lernaean.Hydra.Tests/ApiDocumentation/DefaultPropertyRangeRetrievalPolicyTests.cs
using System; using System.Collections.Generic; using System.Reflection; using FakeItEasy; using FluentAssertions; using Hydra.Discovery.SupportedProperties; using JsonLD.Entities; using TestHydraApi; using Vocab; using Xunit; namespace Lernaean.Hydra.Tests.ApiDocumentation { public class DefaultPropertyRangeRetrievalPolicyTests { private readonly DefaultPropertyRangeRetrievalPolicy _rangePolicy; private readonly IPropertyRangeMappingPolicy _propertyType; public DefaultPropertyRangeRetrievalPolicyTests() { _propertyType = A.Fake<IPropertyRangeMappingPolicy>(); var mappings = new[] { _propertyType }; _rangePolicy = new DefaultPropertyRangeRetrievalPolicy(mappings); } [Fact] public void Should_use_RangAttribute_if_present() { // when var iriRef = _rangePolicy.GetRange(typeof (Issue).GetProperty("ProjectId"), new Dictionary<Type, Uri>()); // then iriRef.Should().Be((IriRef)"http://example.api/o#project"); } [Fact] public void Should_map_property_range_to_RDF_type() { // given var mappedPredicate = new Uri(Xsd.@string); var classIds = new Dictionary<Type, Uri> { { typeof(Issue), new Uri("http://example.com/issue") } }; A.CallTo(() => _propertyType.MapType(A<PropertyInfo>._, A<IReadOnlyDictionary<Type, Uri>>._)).Returns(mappedPredicate); // when var range = _rangePolicy.GetRange(typeof(Issue).GetProperty("Content"), classIds); // then range.Should().Be((IriRef)mappedPredicate); } } }
using System; using System.Collections.Generic; using FakeItEasy; using FluentAssertions; using Hydra.Discovery.SupportedProperties; using JsonLD.Entities; using TestHydraApi; using Vocab; using Xunit; namespace Lernaean.Hydra.Tests.ApiDocumentation { public class DefaultPropertyRangeRetrievalPolicyTests { private readonly DefaultPropertyRangeRetrievalPolicy _rangePolicy; private readonly IPropertyRangeMappingPolicy _propertyType; public DefaultPropertyRangeRetrievalPolicyTests() { _propertyType = A.Fake<IPropertyRangeMappingPolicy>(); var mappings = new[] { _propertyType }; _rangePolicy = new DefaultPropertyRangeRetrievalPolicy(mappings); } [Fact] public void Should_use_RangAttribute_if_present() { // when var iriRef = _rangePolicy.GetRange(typeof (Issue).GetProperty("ProjectId"), new Dictionary<Type, Uri>()); // then iriRef.Should().Be((IriRef)"http://example.api/o#project"); } [Fact] public void Should_map_property_range_to_RDF_type() { // given var propertyInfo = typeof(Issue).GetProperty("Content"); var mappedPredicate = new Uri(Xsd.@string); var classIds = new Dictionary<Type, Uri> { { typeof(Issue), new Uri("http://example.com/issue") } }; A.CallTo(() => _propertyType.MapType(propertyInfo, classIds)).Returns(mappedPredicate); // when var range = _rangePolicy.GetRange(propertyInfo, classIds); // then range.Should().Be((IriRef)mappedPredicate); } } }
mit
C#
570072d4b8921ad19a9ead468909b1e0812e57bf
Fix for null reference exceptions thrown when certain exceptions occur in the getstream.io API requests - #15
shawnspeak/stream-net,GetStream/stream-net,GetStream/stream-net,GetStream/stream-net
src/stream-net/StreamException.cs
src/stream-net/StreamException.cs
using Newtonsoft.Json; using RestSharp; using System; namespace Stream { [Serializable] public class StreamException : Exception { internal StreamException(ExceptionState state) : base(message: state.Detail) { } internal class ExceptionState { public int? Code { get; set; } public string Detail { get; set; } public string Exception { get; set; } [Newtonsoft.Json.JsonProperty("status_code")] public int HttpStatusCode { get; set; } } internal static StreamException FromResponse(IRestResponse response) { //If we get an error response from getstream.io with the following structure then use it to populate the exception details, //otherwise fill in the properties from the response, the most likely case being when we get a timeout. //{"code": 6, "detail": "The following feeds are not configured: 'secret'", "duration": "4ms", "exception": "FeedConfigException", "status_code": 400} ExceptionState state = null; if (!string.IsNullOrWhiteSpace(response.Content)) { state = JsonConvert.DeserializeObject<ExceptionState>(response.Content); } if (state == null) { state = new ExceptionState() { Code = null, Detail = response.ErrorMessage, @Exception = response.ErrorException.ToString(), HttpStatusCode = (int)response.StatusCode }; } throw new StreamException(state); } } }
using Newtonsoft.Json; using RestSharp; using System; namespace Stream { [Serializable] public class StreamException : Exception { internal StreamException(ExceptionState state) : base(message: state.Detail) { } internal class ExceptionState { public int? Code { get; set; } public string Detail { get; set; } public string Exception { get; set; } [Newtonsoft.Json.JsonProperty("status_code")] public int HttpStatusCode { get; set; } } internal static StreamException FromResponse(IRestResponse response) { //{"code": 6, "detail": "The following feeds are not configured: 'secret'", "duration": "4ms", "exception": "FeedConfigException", "status_code": 400} var state = JsonConvert.DeserializeObject<ExceptionState>(response.Content); throw new StreamException(state); } } }
bsd-3-clause
C#
ac0a9e865bb2b212db136bb5811ae810db960595
comment log
Anatolij-Grigorjev/Unity5TankArena,Anatolij-Grigorjev/Unity5TankArena,Anatolij-Grigorjev/Unity5TankArena
Assets/Scripts/Controllers/Tank/TankTurretController.cs
Assets/Scripts/Controllers/Tank/TankTurretController.cs
using UnityEngine; using System.Collections; using TankArena.Models.Tank; using System; using TankArena.Utils; namespace TankArena.Controllers { public class TankTurretController : BaseTankPartController<TankTurret> { public Transform Rotator; private float turnCoef = 0.0f; private const float TURN_BASE_COEF = 0.69314718055994530941723212145818f; // Use this for initialization public void Start() { TankChassis chassis = parentObject.GetComponent<TankController>().chassisController.Model; var rotatorGO = new GameObject("Rotator"); rotatorGO.transform.parent = parentObject.transform; chassis.TurretPivot.CopyToTransform(rotatorGO.transform); transform.parent = rotatorGO.transform; Rotator = rotatorGO.transform; } ///<summary> ///Turn coefficient to which spin speed should be applied ///Indicates turret spinniness ///</summary> public float TurnCoef { set { turnCoef = value * TURN_BASE_COEF; } } // Update is called once per frame void Update() { } /// <summary> /// Issued command for tank to fire from selected groups /// </summary> /// <param name="weaponGroups">selected weapon groups</param> public void Fire(WeaponGroups weaponGroups) { Model.Fire(weaponGroups, transform); } public void Reload() { Model.Reload(); } public void TurnTurret(float intensity) { var wantedEuler = Rotator.localRotation.eulerAngles; wantedEuler.z += (intensity * turnCoef); // DBG.Log("Wanted Rotation: {0}", wantedEuler); var wantedRotation = Quaternion.Euler(wantedEuler); Rotator.localRotation = Quaternion.Lerp(Rotator.localRotation, wantedRotation, Time.fixedDeltaTime); } } }
using UnityEngine; using System.Collections; using TankArena.Models.Tank; using System; using TankArena.Utils; namespace TankArena.Controllers { public class TankTurretController : BaseTankPartController<TankTurret> { public Transform Rotator; private float turnCoef = 0.0f; private const float TURN_BASE_COEF = 0.69314718055994530941723212145818f; // Use this for initialization public void Start() { TankChassis chassis = parentObject.GetComponent<TankController>().chassisController.Model; var rotatorGO = new GameObject("Rotator"); rotatorGO.transform.parent = parentObject.transform; chassis.TurretPivot.CopyToTransform(rotatorGO.transform); transform.parent = rotatorGO.transform; Rotator = rotatorGO.transform; } ///<summary> ///Turn coefficient to which spin speed should be applied ///Indicates turret spinniness ///</summary> public float TurnCoef { set { turnCoef = value * TURN_BASE_COEF; } } // Update is called once per frame void Update() { } /// <summary> /// Issued command for tank to fire from selected groups /// </summary> /// <param name="weaponGroups">selected weapon groups</param> public void Fire(WeaponGroups weaponGroups) { Model.Fire(weaponGroups, transform); } public void Reload() { Model.Reload(); } public void TurnTurret(float intensity) { var wantedEuler = Rotator.localRotation.eulerAngles; wantedEuler.z += (intensity * turnCoef); DBG.Log("Wanted Rotation: {0}", wantedEuler); var wantedRotation = Quaternion.Euler(wantedEuler); Rotator.localRotation = Quaternion.Lerp(Rotator.localRotation, wantedRotation, Time.fixedDeltaTime); } } }
mit
C#
d37df6afeca4e2a1fff47a521dec9d7ab6997adc
Fix test failing after BDL -> `[Test]` change
peppy/osu-new,NeoAdonis/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipoo/osu
osu.Game.Tournament.Tests/Screens/TestSceneTeamWinScreen.cs
osu.Game.Tournament.Tests/Screens/TestSceneTeamWinScreen.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.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Tournament.Screens.TeamWin; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneTeamWinScreen : TournamentTestScene { [Test] public void TestBasic() { AddStep("set up match", () => { var match = Ladder.CurrentMatch.Value; match.Round.Value = Ladder.Rounds.FirstOrDefault(g => g.Name.Value == "Finals"); match.Completed.Value = true; }); AddStep("create screen", () => Add(new TeamWinScreen { FillMode = FillMode.Fit, FillAspectRatio = 16 / 9f })); } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Tournament.Screens.TeamWin; namespace osu.Game.Tournament.Tests.Screens { public class TestSceneTeamWinScreen : TournamentTestScene { [Test] public void TestBasic() { var match = Ladder.CurrentMatch.Value; match.Round.Value = Ladder.Rounds.FirstOrDefault(g => g.Name.Value == "Finals"); match.Completed.Value = true; Add(new TeamWinScreen { FillMode = FillMode.Fit, FillAspectRatio = 16 / 9f }); } } }
mit
C#
e220d7ce57debf7f0a2847ae85883bbf49d82fcd
Fix a comment
madsbangh/EasyButtons
Assets/EasyButtons/Editor/ButtonEditor.cs
Assets/EasyButtons/Editor/ButtonEditor.cs
using System; using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(UnityEngine.Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with no parameters foreach (var method in target.GetType().GetMethods() .Where(m => m.GetParameters().Length == 0)) { // Get the ButtonAttribute on the method (if any) var ba = (ButtonAttribute)Attribute.GetCustomAttribute(method, typeof(ButtonAttribute)); if (ba != null) { // Determine whether the button should be enabled based on its mode GUI.enabled = ba.mode == ButtonMode.AlwaysEnabled || (EditorApplication.isPlaying ? ba.mode == ButtonMode.EnabledInPlayMode : ba.mode == ButtonMode.DisabledInPlayMode); // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { foreach (var target in targets) { method.Invoke(target, null); } } GUI.enabled = true; } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
using System; using System.Linq; using UnityEngine; using UnityEditor; namespace EasyButtons { /// <summary> /// Custom inspector for Object including derived classes. /// </summary> [CanEditMultipleObjects] [CustomEditor(typeof(UnityEngine.Object), true)] public class ObjectEditor : Editor { public override void OnInspectorGUI() { // Loop through all methods with the Button attribute and no arguments foreach (var method in target.GetType().GetMethods() .Where(m => m.GetParameters().Length == 0)) { // Get the ButtonAttribute on the method (if any) var ba = (ButtonAttribute)Attribute.GetCustomAttribute(method, typeof(ButtonAttribute)); if (ba != null) { // Determine whether the button should be enabled based on its mode GUI.enabled = ba.mode == ButtonMode.AlwaysEnabled || (EditorApplication.isPlaying ? ba.mode == ButtonMode.EnabledInPlayMode : ba.mode == ButtonMode.DisabledInPlayMode); // Draw a button which invokes the method if (GUILayout.Button(ObjectNames.NicifyVariableName(method.Name))) { foreach (var target in targets) { method.Invoke(target, null); } } GUI.enabled = true; } } // Draw the rest of the inspector as usual DrawDefaultInspector(); } } }
mit
C#
c7aa14596f155e886b383aedf879d7200831ca4d
Add auto select device
tobyclh/UnityCNTK,tobyclh/UnityCNTK
Assets/UnityCNTK/Scripts/CNTKManager.cs
Assets/UnityCNTK/Scripts/CNTKManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using CNTK; namespace UnityCNTK{ public class CNTKManager : MonoBehaviour { public static CNTKManager instance; public List<Model> managedModels = new List<Model>(); public static DeviceDescriptor device; public enum HardwareOptions { Auto, CPU, GPU, Default } [Tooltip("Avoid Default unless you are familiar with the usage")] public HardwareOptions hardwareOption = HardwareOptions.Auto; void Start () { MakeSingleton(); switch (hardwareOption) { case HardwareOptions.Auto: { SelectBestDevice(); break; } case HardwareOptions.CPU: { device = DeviceDescriptor.CPUDevice; break; } case HardwareOptions.GPU: { device = DeviceDescriptor.GPUDevice(0); break; } case HardwareOptions.Default: { device = DeviceDescriptor.UseDefaultDevice(); break; } } foreach(var model in managedModels) { if(model.LoadOnStart) { model.LoadModel(); } } } // Update is called once per frame void Update () { } private void MakeSingleton() { if (instance != null && instance != this ) { Debug.LogError("Only 1 CNTK manager allowed in a scene, destroying"); Destroy(this); } else { instance = this; } } private void SelectBestDevice() { var gpu = DeviceDescriptor.GPUDevice(0); if(gpu != null) { device = gpu; } else { device = DeviceDescriptor.CPUDevice; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace UnityCNTK{ public class CNTKManager : MonoBehaviour { public static CNTKManager instance; public List<Model> managedModels = new List<Model>(); void Start () { MakeSingleton(); } // Update is called once per frame void Update () { } private void MakeSingleton() { if (instance != null && instance != this ) { Debug.LogError("Only 1 CNTK manager allowed in a scene, destroying"); Destroy(this); } else { instance = this; } } } }
mit
C#
bde25bee98f1627435ef46dcf4de0087fde2a99f
Update AssemblyInfo.cs
cyotek/Cyotek.Windows.Forms.TabList
Cyotek.Windows.Forms.TabList/Properties/AssemblyInfo.cs
Cyotek.Windows.Forms.TabList/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Cyotek TabList // Copyright (c) 2012-2017 Cyotek Ltd. // https://www.cyotek.com // https://www.cyotek.com/blog/tag/tablist // Licensed under the MIT License. See LICENSE.txt for the full text. // If you use this control in your applications, attribution, donations or contributions are welcome. [assembly: AssemblyTitle("Cyotek TabList Control")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cyotek Ltd")] [assembly: AssemblyProduct("Cyotek TabList Control")] [assembly: AssemblyCopyright("Copyright © 2012-2020 Cyotek Ltd. All Rights Reserved")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f22e6f0f-2f81-4db8-a3c9-4ae0a1e15a74")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")] [assembly: AssemblyInformationalVersion("2.1.0")] [assembly: InternalsVisibleTo("Cyotek.Windows.Forms.TabList.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100f711fe95c698a0533975dc0eabc40db1876c95e7a4b03ef65765b7f10d81b71c0f64d4d2ae7c1026d6426fa2d09c2dc16766acfa397141c1496dad3ee8be06749fb655edd7e4c902ad5a87074f56c0a452bc181a5fa8e3e4a441ecd747921e13d239737f4fdffdeabeb09e5386bbb865d41b560b787dbc9b9d29e3aa0b4b1ac4")]
using System; using System.Reflection; using System.Runtime.InteropServices; // Cyotek TabList // Copyright (c) 2012-2017 Cyotek Ltd. // https://www.cyotek.com // https://www.cyotek.com/blog/tag/tablist // Licensed under the MIT License. See LICENSE.txt for the full text. // If you use this control in your applications, attribution, donations or contributions are welcome. [assembly: AssemblyTitle("Cyotek TabList Control")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Cyotek Ltd")] [assembly: AssemblyProduct("Cyotek TabList Control")] [assembly: AssemblyCopyright("Copyright © 2012-2020 Cyotek Ltd. All Rights Reserved")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("f22e6f0f-2f81-4db8-a3c9-4ae0a1e15a74")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.2.0")] [assembly: AssemblyInformationalVersion("2.0.2")]
mit
C#
0ca8a61353156779c7efc7f0d134bc4b6c09240f
Test close connection
pleonex/NitroDebugger,pleonex/NitroDebugger,pleonex/NitroDebugger
NitroDebugger.UnitTests/SessionTests.cs
NitroDebugger.UnitTests/SessionTests.cs
// // Test.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2014 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using NUnit.Framework; using System; using NitroDebugger.RSP; using System.Net.Sockets; using System.Net; using System.Runtime.Serialization.Formatters; namespace UnitTests { [TestFixture] public class SessionTests { private const int DefaultPort = 10101; private TcpListener server; [TestFixtureSetUp] public void CreateServer() { server = new TcpListener(IPAddress.Loopback, DefaultPort); server.Start(); } [TestFixtureTearDown] public void StopServer() { server.Stop(); } [TearDown] public void ResetServer() { while (server.Pending()) server.AcceptTcpClient().Close(); } [Test] public void ConnectLocalhostDefaultPort() { Assert.DoesNotThrow(() => new Session("localhost", DefaultPort)); } [Test] public void ConnectCloseLocalhostDefaultPort() { Assert.DoesNotThrow(() => new Session("localhost", DefaultPort).Close()); } } }
// // Test.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2014 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using NUnit.Framework; using System; using NitroDebugger.RSP; using System.Net.Sockets; using System.Net; namespace UnitTests { [TestFixture()] public class Test { private const int DefaultPort = 10101; [Test()] public void ConnectLocalhostDefaultPort() { TcpListener server = new TcpListener(IPAddress.Loopback, DefaultPort); server.Start(); Assert.DoesNotThrow(() => new Session("localhost", DefaultPort)); server.Stop(); } } }
mit
C#
f119318572b9dd1e076c542bf8ef0898edf35511
Add onHealthChange event
SnpM/Lockstep-Framework,erebuswolf/LockstepFramework,yanyiyun/LockstepFramework
Core/Game/Abilities/Essential/Health.cs
Core/Game/Abilities/Essential/Health.cs
using System; using Lockstep.UI; using UnityEngine; namespace Lockstep { public class Health : Ability { [SerializeField, FixedNumber] private long _maxHealth = FixedMath.One * 100; public long MaxHealth { get { return _maxHealth; } set { _maxHealth = value; } } public event Action onHealthChange; private long _healthAmount; public long HealthAmount { get { return _healthAmount; } set { _healthAmount = value; onHealthChange (); } } protected override void OnSetup() { } protected override void OnInitialize() { HealthAmount = MaxHealth; OnTakeProjectile = null; } public void TakeProjectile(LSProjectile projectile) { if (Agent.IsActive && HealthAmount >= 0) { if (OnTakeProjectile .IsNotNull ()) { OnTakeProjectile (projectile); } TakeRawDamage (projectile.CheckExclusiveDamage (Agent.Tag)); } } public void TakeRawDamage (long damage) { HealthAmount -= damage; // don't let the health go below zero if (HealthAmount <= 0) { HealthAmount = 0; if (HealthAmount <= 0) { Die (); return; } } if (Agent.StatsBarer != null) Agent.StatsBarer.SetFill (StatBarType.Health, (float)(HealthAmount / (double)MaxHealth)); } public void Die () { AgentController.DestroyAgent(Agent); if (Agent.Animator.IsNotNull ()) { Agent.SetState(AnimState.Dying); Agent.Animator.Visualize(); } } protected override void OnDeactivate() { OnTakeProjectile = null; } public event Action<LSProjectile> OnTakeProjectile; public int shieldIndex {get; set;} public bool Protected { get {return CoveringShield .IsNotNull () && CoveringShield.IsShielding;} } public Shield CoveringShield {get; private set;} public void Protect (Shield shield) { CoveringShield = shield; } public void Unprotect (Shield shield) { CoveringShield = null; } } }
using System; using Lockstep.UI; using UnityEngine; namespace Lockstep { public class Health : Ability { [SerializeField, FixedNumber] private long _maxHealth = FixedMath.One * 100; public long MaxHealth { get { return _maxHealth; } set { _maxHealth = value; } } public long HealthAmount { get; set; } protected override void OnSetup() { } protected override void OnInitialize() { HealthAmount = MaxHealth; OnTakeProjectile = null; } public void TakeProjectile(LSProjectile projectile) { if (Agent.IsActive && HealthAmount >= 0) { if (OnTakeProjectile .IsNotNull ()) { OnTakeProjectile (projectile); } TakeRawDamage (projectile.CheckExclusiveDamage (Agent.Tag)); } } public void TakeRawDamage (long damage) { HealthAmount -= damage; // don't let the health go below zero if (HealthAmount <= 0) { HealthAmount = 0; if (HealthAmount <= 0) { Die (); return; } } if (Agent.StatsBarer != null) Agent.StatsBarer.SetFill (StatBarType.Health, (float)(HealthAmount / (double)MaxHealth)); } public void Die () { AgentController.DestroyAgent(Agent); if (Agent.Animator.IsNotNull ()) { Agent.SetState(AnimState.Dying); Agent.Animator.Visualize(); } } protected override void OnDeactivate() { OnTakeProjectile = null; } public event Action<LSProjectile> OnTakeProjectile; public int shieldIndex {get; set;} public bool Protected { get {return CoveringShield .IsNotNull () && CoveringShield.IsShielding;} } public Shield CoveringShield {get; private set;} public void Protect (Shield shield) { CoveringShield = shield; } public void Unprotect (Shield shield) { CoveringShield = null; } } }
mit
C#
eda42c0f1788486a97c36015e44322422dbd7d07
Update AssemblyInfo.cs
idormenco/PolyBool.Net
Polybool.Net/Properties/AssemblyInfo.cs
Polybool.Net/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Polybool.Net")] [assembly: AssemblyDescription("Boolean operations on polygons (union, intersection, difference, xor) (this library is a port for .net of polybooljs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Polybool.Net")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5fb7c719-ba44-48da-8384-1796a5cf3ff6")] // 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.5.0.0")] [assembly: AssemblyFileVersion("1.5.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Polybool.Net")] [assembly: AssemblyDescription("Boolean operations on polygons (union, intersection, difference, xor) (this library is a port for .net of polybooljs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Polybool.Net")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5fb7c719-ba44-48da-8384-1796a5cf3ff6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
mit
C#
6652f97025f7750bd00240daabaeb78bab560873
remove old drawing logic of component
NicoVIII/QuizPresentator,NicoVIII/QuizPresentator,NicoVIII/QuizPresenter
QuizPresentator/QuestionComponentBox.cs
QuizPresentator/QuestionComponentBox.cs
using Xwt; using Xwt.Drawing; namespace QuizPresentation { /// <summary> /// Box, which is used to display the question or an answer /// </summary> public class QuestionComponentBox : Canvas { string text; public QuestionComponentBox() { } protected override void OnDraw(Context ctx, Rectangle dirtyRect) { ctx.Rectangle(new Rectangle(0, 0, dirtyRect.Height, dirtyRect.Height)); } public void SetBorder(int border) { } public void SetText(string text) { this.text = text; } } }
using Xwt; using Xwt.Drawing; namespace QuizPresentation { /// <summary> /// Box, which is used to display the question or an answer /// </summary> public class QuestionComponentBox : HBox { private Label label = new Label(); private HBox hBox = new HBox(); public QuestionComponentBox() { this.BackgroundColor = Parameter.BoxBorderColor; hBox.BackgroundColor = Parameter.BoxBackgroundColor; hBox.Margin = new WidgetSpacing(3, 3, 3, 3); // Init Label label.Margin = new WidgetSpacing(12, 12, 12, 12); label.Font = label.Font.WithSize(Parameter.FontSize); label.Wrap = WrapMode.Word; this.PackStart(hBox, true); hBox.PackStart(label, true); } public void SetBorder(int border) { int margin = 15; hBox.Margin = new WidgetSpacing(border, border, border, border); label.Margin = new WidgetSpacing(margin - border, margin - border, margin - border, margin - border); } public void SetText(string text) { label.Text = text; } } }
mit
C#
0fb6b151038158ca0cab48c7333b6b1acb2a8f81
Add Email Setting Seed Items
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
Portal.CMS.Entities/Seed/SettingSeed.cs
Portal.CMS.Entities/Seed/SettingSeed.cs
using Portal.CMS.Entities.Entities.Settings; using System.Collections.Generic; using System.Linq; namespace Portal.CMS.Entities.Seed { public static class SettingSeed { public static void Seed(PortalEntityModel context) { var settingList = context.Settings.ToList(); var newSettings = new List<Setting>(); if (!settingList.Any(x => x.SettingName == "Website Name")) newSettings.Add(new Setting { SettingName = "Website Name", SettingValue = "Portal CMS" }); if (!settingList.Any(x => x.SettingName == "Description Meta Tag")) newSettings.Add(new Setting { SettingName = "Description Meta Tag", SettingValue = "Portal CMS is a fully featured content management system with a powerful integrated page builder." }); if (!settingList.Any(x => x.SettingName == "Google Analytics Tracking ID")) newSettings.Add(new Setting { SettingName = "Google Analytics Tracking ID", SettingValue = "" }); if (!settingList.Any(x => x.SettingName == "Email From Address")) newSettings.Add(new Setting { SettingName = "Email From Address", SettingValue = "" }); if (!settingList.Any(x => x.SettingName == "SendGrid UserName")) newSettings.Add(new Setting { SettingName = "SendGrid UserName", SettingValue = "" }); if (!settingList.Any(x => x.SettingName == "SendGrid Password")) newSettings.Add(new Setting { SettingName = "SendGrid Password", SettingValue = "" }); if (newSettings.Any()) context.Settings.AddRange(newSettings); } } }
using Portal.CMS.Entities.Entities.Settings; using System.Collections.Generic; using System.Linq; namespace Portal.CMS.Entities.Seed { public static class SettingSeed { public static void Seed(PortalEntityModel context) { var settingList = context.Settings.ToList(); var newSettings = new List<Setting>(); if (!settingList.Any(x => x.SettingName == "Website Name")) newSettings.Add(new Setting { SettingName = "Website Name", SettingValue = "Portal CMS" }); if (!settingList.Any(x => x.SettingName == "Description Meta Tag")) newSettings.Add(new Setting { SettingName = "Description Meta Tag", SettingValue = "Portal CMS is a fully featured content management system with a powerful integrated page builder." }); if (!settingList.Any(x => x.SettingName == "Google Analytics Tracking ID")) newSettings.Add(new Setting { SettingName = "Google Analytics Tracking ID", SettingValue = "" }); if (newSettings.Any()) context.Settings.AddRange(newSettings); } } }
mit
C#
459f7b53f8e2ed0200d09c15e63a59e86821b04d
Add references to 4 subclass singletons to GreenPgnGameResultSyntax.
PenguinF/sandra-three
Sandra.Chess/Pgn/PgnGameResultSyntax.cs
Sandra.Chess/Pgn/PgnGameResultSyntax.cs
#region License /********************************************************************************* * PgnGameResultSyntax.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion namespace Sandra.Chess.Pgn { /// <summary> /// Represents any of four types of game termination markers in PGN. /// These are <see cref="GreenPgnAsteriskSyntax"/>, <see cref="GreenPgnBlackWinMarkerSyntax"/>, /// <see cref="GreenPgnDrawMarkerSyntax"/> and <see cref="GreenPgnWhiteWinMarkerSyntax"/>. /// </summary> public abstract class GreenPgnGameResultSyntax { /// <summary> /// Gets the <see cref="GreenPgnGameResultSyntax"/> which represents the undetermined result. /// </summary> public static GreenPgnGameResultSyntax UndeterminedResultSyntax => GreenPgnAsteriskSyntax.Value; /// <summary> /// Gets the <see cref="GreenPgnGameResultSyntax"/> which represents a black win. /// </summary> public static GreenPgnGameResultSyntax BlackWinsResultSyntax => GreenPgnBlackWinMarkerSyntax.Value; /// <summary> /// Gets the <see cref="GreenPgnGameResultSyntax"/> which represents a draw. /// </summary> public static GreenPgnGameResultSyntax DrawResultSyntax => GreenPgnDrawMarkerSyntax.Value; /// <summary> /// Gets the <see cref="GreenPgnGameResultSyntax"/> which represents a white win. /// </summary> public static GreenPgnGameResultSyntax WhiteWinsResultSyntax => GreenPgnWhiteWinMarkerSyntax.Value; /// <summary> /// Gets the type of game termination marker. /// </summary> public abstract PgnGameResult GameResult { get; } internal GreenPgnGameResultSyntax() { } } }
#region License /********************************************************************************* * PgnGameResultSyntax.cs * * Copyright (c) 2004-2020 Henk Nicolai * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ #endregion namespace Sandra.Chess.Pgn { /// <summary> /// Represents any of four types of game termination markers in PGN. /// These are <see cref="GreenPgnAsteriskSyntax"/>, <see cref="GreenPgnBlackWinMarkerSyntax"/>, /// <see cref="GreenPgnDrawMarkerSyntax"/> and <see cref="GreenPgnWhiteWinMarkerSyntax"/>. /// </summary> public abstract class GreenPgnGameResultSyntax { /// <summary> /// Gets the type of game termination marker. /// </summary> public abstract PgnGameResult GameResult { get; } internal GreenPgnGameResultSyntax() { } } }
apache-2.0
C#
36df54cc6125103795f730255adf00736e36dd70
fix missed spaces
ccellar/Nancy,VQComms/Nancy,danbarua/Nancy,jchannon/Nancy,VQComms/Nancy,VQComms/Nancy,thecodejunkie/Nancy,jchannon/Nancy,phillip-haydon/Nancy,xt0rted/Nancy,blairconrad/Nancy,danbarua/Nancy,damianh/Nancy,davidallyoung/Nancy,khellang/Nancy,ccellar/Nancy,charleypeng/Nancy,jchannon/Nancy,asbjornu/Nancy,jeff-pang/Nancy,felipeleusin/Nancy,anton-gogolev/Nancy,phillip-haydon/Nancy,blairconrad/Nancy,thecodejunkie/Nancy,damianh/Nancy,NancyFx/Nancy,asbjornu/Nancy,NancyFx/Nancy,felipeleusin/Nancy,davidallyoung/Nancy,khellang/Nancy,NancyFx/Nancy,khellang/Nancy,NancyFx/Nancy,ccellar/Nancy,sadiqhirani/Nancy,asbjornu/Nancy,phillip-haydon/Nancy,ccellar/Nancy,charleypeng/Nancy,sadiqhirani/Nancy,blairconrad/Nancy,sloncho/Nancy,davidallyoung/Nancy,anton-gogolev/Nancy,JoeStead/Nancy,asbjornu/Nancy,khellang/Nancy,felipeleusin/Nancy,sadiqhirani/Nancy,JoeStead/Nancy,damianh/Nancy,phillip-haydon/Nancy,VQComms/Nancy,xt0rted/Nancy,VQComms/Nancy,jchannon/Nancy,anton-gogolev/Nancy,sloncho/Nancy,sloncho/Nancy,thecodejunkie/Nancy,davidallyoung/Nancy,charleypeng/Nancy,blairconrad/Nancy,jchannon/Nancy,davidallyoung/Nancy,danbarua/Nancy,JoeStead/Nancy,thecodejunkie/Nancy,danbarua/Nancy,xt0rted/Nancy,anton-gogolev/Nancy,sadiqhirani/Nancy,jeff-pang/Nancy,jeff-pang/Nancy,sloncho/Nancy,xt0rted/Nancy,felipeleusin/Nancy,JoeStead/Nancy,asbjornu/Nancy,jeff-pang/Nancy,charleypeng/Nancy,charleypeng/Nancy
samples/Nancy.Demo.Authentication.Stateless/SecureModule.cs
samples/Nancy.Demo.Authentication.Stateless/SecureModule.cs
namespace Nancy.Demo.Authentication.Stateless { using System; using Nancy.Demo.Authentication.Stateless.Models; using Nancy.Security; public class SecureModule : LegacyNancyModule { //by this time, the api key should have already been pulled out of our querystring //and, using the api key, an identity assigned to our NancyContext public SecureModule() { this.RequiresAuthentication(); Get["secure"] = x => { //Context.CurrentUser was set by StatelessAuthentication earlier in the pipeline var identity = this.Context.CurrentUser; //return the secure information in a json response var userModel = new UserModel(identity.Identity.Name); return this.Response.AsJson(new { SecureContent = "here's some secure content that you can only see if you provide a correct apiKey", User = userModel }); }; Post["secure/create_user"] = x => { Tuple<string, string> user = UserDatabase.CreateUser(this.Context.Request.Form["username"], this.Context.Request.Form["password"]); return this.Response.AsJson(new { username = user.Item1 }); }; } } }
namespace Nancy.Demo.Authentication.Stateless { using System; using Nancy.Demo.Authentication.Stateless.Models; using Nancy.Security; public class SecureModule : LegacyNancyModule { //by this time, the api key should have already been pulled out of our querystring //and, using the api key, an identity assigned to our NancyContext public SecureModule() { this.RequiresAuthentication(); Get["secure"] = x => { //Context.CurrentUser was set by StatelessAuthentication earlier in the pipeline var identity = this.Context.CurrentUser; //return the secure information in a json response var userModel = new UserModel(identity.Identity.Name); return this.Response.AsJson(new { SecureContent = "here's some secure content that you can only see if you provide a correct apiKey", User = userModel }); }; Post["secure/create_user"] = x => { Tuple<string, string> user = UserDatabase.CreateUser(this.Context.Request.Form["username"], this.Context.Request.Form["password"]); return this.Response.AsJson(new { username = user.Item1 }); }; } } }
mit
C#
dbb2333eed8c9cd635e6d3476d13a76109599c26
Add CurrencyPair new attributes
Gatecoin/api-gatecoin-dotnet,Gatecoin/api-gatecoin-dotnet,Gatecoin/API_client_csharp
Model/CurrencyPair.cs
Model/CurrencyPair.cs
using ServiceStack.ServiceInterface.ServiceModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GatecoinServiceInterface.Model; namespace GatecoinServiceInterface.Model{ [Serializable] public class CurrencyPair { public System.String Name {get; set; } public System.String TradingCode {get; set; } public System.String BaseCurrency {get; set; } public System.String QuoteCurrency {get; set; } public System.String DisplayName {get; set; } public System.Int64 PriceDecimalPlaces {get; set; } } }
using ServiceStack.ServiceInterface.ServiceModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GatecoinServiceInterface.Model; namespace GatecoinServiceInterface.Model{ [Serializable] public class CurrencyPair { public System.String Name {get; set; } public System.String TradingCode {get; set; } } }
mit
C#
337ca73e30d32459c2377100e98a57b3b7743d7c
Fix drop file
michael-reichenauer/Dependinator
Dependinator/Common/ModelMetadataFolders/Private/OpenModelService.cs
Dependinator/Common/ModelMetadataFolders/Private/OpenModelService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using Dependinator.MainWindowViews; using Dependinator.ModelViewing.Private; using Dependinator.Utils; namespace Dependinator.Common.ModelMetadataFolders.Private { internal class OpenModelService : IOpenModelService { private readonly IModelMetadataService modelMetadataService; private readonly IModelViewService modelViewService; private readonly IOpenFileDialogService openFileDialogService; private readonly IExistingInstanceService existingInstanceService; private readonly Lazy<MainWindow> mainWindow; public OpenModelService( IModelViewService modelViewService, IModelMetadataService modelMetadataService, IOpenFileDialogService openFileDialogService, IExistingInstanceService existingInstanceService, Lazy<MainWindow> mainWindow) { this.modelViewService = modelViewService; this.modelMetadataService = modelMetadataService; this.openFileDialogService = openFileDialogService; this.existingInstanceService = existingInstanceService; this.mainWindow = mainWindow; } public async Task OpenModelAsync() { if (!openFileDialogService.TryShowOpenFileDialog(out string modelFilePath)) { return; } await TryModelAsync(modelFilePath); } public async Task TryModelAsync(string modelFilePath) { if (modelMetadataService.ModelFilePath.IsSameIgnoreCase(modelFilePath)) { Log.Debug("User tries to open same model that is already open"); return; } await OpenOtherModelAsync(modelFilePath); } public async Task OpenOtherModelAsync(string modelFilePath) { modelMetadataService.SetModelFilePath(modelFilePath); string metadataFolderPath = modelMetadataService.MetadataFolderPath; if (existingInstanceService.TryActivateExistingInstance(metadataFolderPath, null)) { // Another instance for this working folder is already running and it received the // command line from this instance, lets exit this instance, while other instance continuous Application.Current.Shutdown(0); return; } existingInstanceService.RegisterPath(metadataFolderPath); mainWindow.Value.RestoreWindowSettings(); await modelViewService.LoadAsync(); } public async Task OpenModelAsync(IReadOnlyList<string> modelFilePaths) { // Currently only support one dropped file string modelFilePath = modelFilePaths.First(); await TryModelAsync(modelFilePath); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using Dependinator.MainWindowViews; using Dependinator.ModelViewing.Private; using Dependinator.Utils; namespace Dependinator.Common.ModelMetadataFolders.Private { internal class OpenModelService : IOpenModelService { private readonly IModelMetadataService modelMetadataService; private readonly IModelViewService modelViewService; private readonly IOpenFileDialogService openFileDialogService; private readonly IExistingInstanceService existingInstanceService; private readonly Lazy<MainWindow> mainWindow; public OpenModelService( IModelViewService modelViewService, IModelMetadataService modelMetadataService, IOpenFileDialogService openFileDialogService, IExistingInstanceService existingInstanceService, Lazy<MainWindow> mainWindow) { this.modelViewService = modelViewService; this.modelMetadataService = modelMetadataService; this.openFileDialogService = openFileDialogService; this.existingInstanceService = existingInstanceService; this.mainWindow = mainWindow; } public async Task OpenModelAsync() { if (!openFileDialogService.TryShowOpenFileDialog(out string modelFilePath)) { return; } await TryModelAsync(modelFilePath); } public async Task TryModelAsync(string modelFilePath) { if (modelMetadataService.ModelFilePath.IsSameIgnoreCase(modelFilePath)) { Log.Debug("User tries to open same model that is already open"); return; } await OpenOtherModelAsync(modelFilePath); } public async Task OpenOtherModelAsync(string modelFilePath) { modelMetadataService.SetModelFilePath(modelFilePath); string metadataFolderPath = modelMetadataService.MetadataFolderPath; if (existingInstanceService.TryActivateExistingInstance(metadataFolderPath, null)) { // Another instance for this working folder is already running and it received the // command line from this instance, lets exit this instance, while other instance continuous Application.Current.Shutdown(0); return; } existingInstanceService.RegisterPath(metadataFolderPath); mainWindow.Value.RestoreWindowSettings(); await modelViewService.LoadAsync(); } public async Task OpenModelAsync(IReadOnlyList<string> modelFilePaths) { // Currently only support one dropped file string modelFilePath = modelFilePaths.First(); await OpenOtherModelAsync(modelFilePath); } } }
mit
C#
d032b26d139184952907598e02b78f9465fe0a5d
update samples.
ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP
samples/Sample.RabbitMQ.MySql/Startup.cs
samples/Sample.RabbitMQ.MySql/Startup.cs
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Sample.RabbitMQ.MySql { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(); services.AddCap(x => { x.UseEntityFramework<AppDbContext>(); x.UseRabbitMQ("localhost"); x.UseDashboard(); x.FailedRetryCount = 5; x.FailedThresholdCallback = (type, name, content) => { Console.WriteLine($@"A message of type {type} failed after executing {x.FailedRetryCount} several times, requiring manual troubleshooting. Message name: {name}, message body: {content}"); }; }); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvc(); app.UseCap(); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Sample.RabbitMQ.MySql { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddDbContext<AppDbContext>(); services.AddCap(x => { x.UseEntityFramework<AppDbContext>(); x.UseRabbitMQ("localhost"); x.UseDashboard(); }); services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { app.UseMvc(); app.UseCap(); } } }
mit
C#
3f741c2ae157bf08c073ed9cf258d86c46b44def
Update IRestAuthenticationTokenProvider.cs
tiksn/TIKSN-Framework
TIKSN.Core/Web/Rest/IRestAuthenticationTokenProvider.cs
TIKSN.Core/Web/Rest/IRestAuthenticationTokenProvider.cs
using System.Threading.Tasks; namespace TIKSN.Web.Rest { public interface IRestAuthenticationTokenProvider { Task<string> GetAuthenticationTokenAsync(string apiKey); } }
using System.Threading.Tasks; namespace TIKSN.Web.Rest { public interface IRestAuthenticationTokenProvider { Task<string> GetAuthenticationToken(string apiKey); } }
mit
C#
59fb45258483efba5415fd0247dc90defe4193eb
Prepare 0.2.1 release
LouisTakePILLz/ArgumentParser
ArgumentParser/Properties/AssemblyInfo.cs
ArgumentParser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Security; // 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("ArgumentParser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 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("a67b27e2-8841-4951-a6f0-a00d93f59560")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.1.0")] [assembly: AssemblyFileVersion("0.2.1.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Security; // 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("ArgumentParser")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 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("a67b27e2-8841-4951-a6f0-a00d93f59560")] // 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.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")]
apache-2.0
C#
de0452010479db6b62f0ecb208d912a5ebb4577e
Use conventional camel-casing for parameters (#81)
amis92/RecordGenerator
src/Amadevus.RecordGenerator.Generators/RecordDescriptor.cs
src/Amadevus.RecordGenerator.Generators/RecordDescriptor.cs
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Amadevus.RecordGenerator.Generators { internal class RecordDescriptor { public RecordDescriptor(TypeSyntax typeSyntax, SyntaxToken typeIdentifier, ImmutableArray<Entry> entries, Location typeDeclarationLocation, bool isTypeSealed) { TypeSyntax = typeSyntax; TypeIdentifier = typeIdentifier; Entries = entries; TypeDeclarationLocation = typeDeclarationLocation; IsTypeSealed = isTypeSealed; } public TypeSyntax TypeSyntax { get; } public SyntaxToken TypeIdentifier { get; } public ImmutableArray<Entry> Entries { get; } public Location TypeDeclarationLocation { get; } public bool IsTypeSealed { get; } internal class Entry { public Entry(SyntaxToken identifier, SyntaxToken identifierInCamelCase, TypeSyntax typeSyntax, string qualifiedTypeName) { Identifier = identifier; TypeSyntax = typeSyntax; IdentifierInCamelCase = identifierInCamelCase; QualifiedTypeName = qualifiedTypeName; } public SyntaxToken Identifier { get; } public SyntaxToken IdentifierInCamelCase { get; } public TypeSyntax TypeSyntax { get; } public string QualifiedTypeName { get; } } } }
using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Amadevus.RecordGenerator.Generators { internal class RecordDescriptor { public RecordDescriptor(TypeSyntax TypeSyntax, SyntaxToken TypeIdentifier, ImmutableArray<Entry> Entries, Location TypeDeclarationLocation, bool IsTypeSealed) { this.TypeSyntax = TypeSyntax; this.TypeIdentifier = TypeIdentifier; this.Entries = Entries; this.TypeDeclarationLocation = TypeDeclarationLocation; this.IsTypeSealed = IsTypeSealed; } public TypeSyntax TypeSyntax { get; } public SyntaxToken TypeIdentifier { get; } public ImmutableArray<Entry> Entries { get; } public Location TypeDeclarationLocation { get; } public bool IsTypeSealed { get; } internal class Entry { public Entry(SyntaxToken Identifier, SyntaxToken IdentifierInCamelCase, TypeSyntax TypeSyntax, string QualifiedTypeName) { this.Identifier = Identifier; this.TypeSyntax = TypeSyntax; this.IdentifierInCamelCase = IdentifierInCamelCase; this.QualifiedTypeName = QualifiedTypeName; } public SyntaxToken Identifier { get; } public SyntaxToken IdentifierInCamelCase { get; } public TypeSyntax TypeSyntax { get; } public string QualifiedTypeName { get; } } } }
mit
C#
e26f479013d9cf0e1e5b6f4d01090d5e2c4af65e
Update DragPositionBehavior.cs
XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors,XamlBehaviors/XamlBehaviors,wieslawsoltes/AvaloniaBehaviors
src/Avalonia.Xaml.Interactions/Core/DragPositionBehavior.cs
src/Avalonia.Xaml.Interactions/Core/DragPositionBehavior.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Core { /// <summary> /// A behavior that allows controls to be moved around the canvas using RenderTransform of AssociatedObject. /// </summary> public sealed class DragPositionBehavior : Behavior<Control> { private IControl _parent = null; private Point _previous; /// <summary> /// Called after the behavior is attached to the <see cref="Behavior.AssociatedObject"/>. /// </summary> protected override void OnAttached() { base.OnAttached(); AssociatedObject.PointerPressed += AssociatedObject_PointerPressed; } /// <summary> /// Called when the behavior is being detached from its <see cref="Behavior.AssociatedObject"/>. /// </summary> protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PointerPressed -= AssociatedObject_PointerPressed; _parent = null; } private void AssociatedObject_PointerPressed(object sender, PointerPressedEventArgs e) { _parent = AssociatedObject.Parent; if (!(AssociatedObject.RenderTransform is TranslateTransform)) { AssociatedObject.RenderTransform = new TranslateTransform(); } _previous = e.GetPosition(_parent); _parent.PointerMoved += Parent_PointerMoved; _parent.PointerReleased += Parent_PointerReleased; } private void Parent_PointerMoved(object sender, PointerEventArgs args) { var pos = args.GetPosition(_parent); var tr = (TranslateTransform)AssociatedObject.RenderTransform; tr.X += pos.X - _previous.X; tr.Y += pos.Y - _previous.Y; _previous = pos; } private void Parent_PointerReleased(object sender, PointerReleasedEventArgs e) { _parent.PointerMoved -= Parent_PointerMoved; _parent.PointerReleased -= Parent_PointerReleased; _parent = null; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Media; using Avalonia.Xaml.Interactivity; namespace Avalonia.Xaml.Interactions.Core { public sealed class DragPositionBehavior : Behavior<Control> { private IControl parent = null; private Point prevPoint; protected override void OnAttached() { base.OnAttached(); AssociatedObject.PointerPressed += AssociatedObject_PointerPressed; } protected override void OnDetaching() { base.OnDetaching(); AssociatedObject.PointerPressed -= AssociatedObject_PointerPressed; parent = null; } private void AssociatedObject_PointerPressed(object sender, PointerPressedEventArgs e) { parent = AssociatedObject.Parent; if (!(AssociatedObject.RenderTransform is TranslateTransform)) { AssociatedObject.RenderTransform = new TranslateTransform(); } prevPoint = e.GetPosition(parent); parent.PointerMoved += Parent_PointerMoved; parent.PointerReleased += Parent_PointerReleased; } private void Parent_PointerMoved(object sender, PointerEventArgs args) { var pos = args.GetPosition(parent); var tr = (TranslateTransform)AssociatedObject.RenderTransform; tr.X += pos.X - prevPoint.X; tr.Y += pos.Y - prevPoint.Y; prevPoint = pos; } private void Parent_PointerReleased(object sender, PointerReleasedEventArgs e) { parent.PointerMoved -= Parent_PointerMoved; parent.PointerReleased -= Parent_PointerReleased; parent = null; } } }
mit
C#
175e6fe63042e8b5d5f4003080ec692aa18f50e6
Bump version to 0.6.0 because of pit crew color editing
codemeyer/ArgData
Source/ArgData/Properties/AssemblyInfo.cs
Source/ArgData/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ArgData")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Manicomio Software")] [assembly: AssemblyProduct("ArgData")] [assembly: AssemblyCopyright("Copyright © 2014-2015 Fredrik Meyer")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("30dad107-2eae-43cf-a8fe-5e658a3b5e7c")] [assembly: AssemblyVersion("0.6.0.0")] [assembly: AssemblyFileVersion("0.6.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("ArgData")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Manicomio Software")] [assembly: AssemblyProduct("ArgData")] [assembly: AssemblyCopyright("Copyright © 2014-2015 Fredrik Meyer")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("30dad107-2eae-43cf-a8fe-5e658a3b5e7c")] [assembly: AssemblyVersion("0.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
mit
C#
1b9f28200f076af8f587796b1e4c139550c05371
Remove window debug thing that was left in
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.Client/Window/WindowVisualizer.cs
Content.Client/Window/WindowVisualizer.cs
using System; using Content.Shared.Rounding; using Content.Shared.Window; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; namespace Content.Client.Window { [UsedImplicitly] public sealed class WindowVisualizer : AppearanceVisualizer { [DataField("crackRsi")] public ResourcePath CrackRsi { get; } = new ("/Textures/Structures/Windows/cracks.rsi"); public override void InitializeEntity(IEntity entity) { if (!entity.TryGetComponent(out ISpriteComponent? sprite)) return; sprite.LayerMapReserveBlank(WindowDamageLayers.Layer); sprite.LayerSetVisible(WindowDamageLayers.Layer, false); sprite.LayerSetRSI(WindowDamageLayers.Layer, CrackRsi); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; if (component.TryGetData(WindowVisuals.Damage, out float fraction)) { var level = Math.Min(ContentHelpers.RoundToLevels(fraction, 1, 5), 3); if (level == 0) { sprite.LayerSetVisible(WindowDamageLayers.Layer, false); return; } sprite.LayerSetVisible(WindowDamageLayers.Layer, true); sprite.LayerSetState(WindowDamageLayers.Layer, $"{level}"); } } public enum WindowDamageLayers : byte { Layer, } } }
using System; using Content.Shared.Rounding; using Content.Shared.Window; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Shared.GameObjects; using Robust.Shared.Log; using Robust.Shared.Serialization.Manager.Attributes; using Robust.Shared.Utility; namespace Content.Client.Window { [UsedImplicitly] public sealed class WindowVisualizer : AppearanceVisualizer { [DataField("crackRsi")] public ResourcePath CrackRsi { get; } = new ("/Textures/Structures/Windows/cracks.rsi"); public override void InitializeEntity(IEntity entity) { if (!entity.TryGetComponent(out ISpriteComponent? sprite)) return; sprite.LayerMapReserveBlank(WindowDamageLayers.Layer); sprite.LayerSetVisible(WindowDamageLayers.Layer, false); sprite.LayerSetRSI(WindowDamageLayers.Layer, CrackRsi); } public override void OnChangeData(AppearanceComponent component) { base.OnChangeData(component); if (!component.Owner.TryGetComponent(out ISpriteComponent? sprite)) return; if (component.TryGetData(WindowVisuals.Damage, out float fraction)) { var level = Math.Min(ContentHelpers.RoundToLevels(fraction, 1, 5), 3); if (level == 0) { sprite.LayerSetVisible(WindowDamageLayers.Layer, false); return; } Logger.Info($"LEVEL: {level} DMG: {fraction}"); sprite.LayerSetVisible(WindowDamageLayers.Layer, true); sprite.LayerSetState(WindowDamageLayers.Layer, $"{level}"); } } public enum WindowDamageLayers : byte { Layer, } } }
mit
C#
0b470541e7cae083854877c27ee661b1f60fc97e
Fix driver update error
devworx-au/Devworx.CodePrettify,devworx-au/Devworx.CodePrettify
Drivers/CodePrettifySettingsPartDriver.cs
Drivers/CodePrettifySettingsPartDriver.cs
using System.Collections.Generic; using Devworx.CodePrettify.Models; using Devworx.CodePrettify.ViewModels; using JetBrains.Annotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Localization; namespace Devworx.CodePrettify.Drivers { [UsedImplicitly] public class CodePrettifySettingsPartDriver : ContentPartDriver<CodePrettifySettingsPart> { private const string TemplateName = "Parts/CodePrettifySettings"; public CodePrettifySettingsPartDriver() { T = NullLocalizer.Instance; } public Localizer T { get; set; } protected override string Prefix { get { return "CodePrettifySettings"; } } protected override DriverResult Editor(CodePrettifySettingsPart part, dynamic shapeHelper) { return ContentShape("Parts_CodePrettifySettings_Edit", () => { var themes = GetThemes(); var viewModel = new CodePrettifySettingsViewModel { PrettifySettingsPart = part, Themes = themes }; return shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: viewModel, Prefix: Prefix); }).OnGroup("code-prettify"); } protected override DriverResult Editor(CodePrettifySettingsPart part, IUpdateModel updater, dynamic shapeHelper) { updater.TryUpdateModel(part, Prefix, null, null); return Editor(part, shapeHelper); } private IEnumerable<string> GetThemes() { return new[] { "default" , "desert" , "github" , "hemisu-dark" , "hemisu-light" , "son-of-obsidian" , "sunburst" , "tomorrow-night-blue" , "tomorrow-night-bright" , "tomorrow-night-eighties" , "tomorrow-night" , "tomorrow" , "vibrant-ink" }; } } }
using System.Collections.Generic; using Devworx.CodePrettify.Models; using Devworx.CodePrettify.ViewModels; using JetBrains.Annotations; using Orchard.ContentManagement; using Orchard.ContentManagement.Drivers; using Orchard.Localization; namespace Devworx.CodePrettify.Drivers { [UsedImplicitly] public class CodePrettifySettingsPartDriver : ContentPartDriver<CodePrettifySettingsPart> { private const string TemplateName = "Parts/CodePrettifySettings"; public CodePrettifySettingsPartDriver() { T = NullLocalizer.Instance; } public Localizer T { get; set; } protected override string Prefix { get { return "CodePrettifySettings"; } } protected override DriverResult Editor(CodePrettifySettingsPart part, dynamic shapeHelper) { return ContentShape("Parts_CodePrettifySettings_Edit", () => { var themes = GetThemes(); var viewModel = new CodePrettifySettingsViewModel { PrettifySettingsPart = part, Themes = themes }; return shapeHelper.EditorTemplate(TemplateName: TemplateName, Model: viewModel, Prefix: Prefix); }).OnGroup("code-prettify"); } protected override DriverResult Editor(CodePrettifySettingsPart part, IUpdateModel updater, dynamic shapeHelper) { var viewModel = new CodePrettifySettingsViewModel { PrettifySettingsPart = part }; updater.TryUpdateModel(viewModel, Prefix, null, null); return Editor(part, shapeHelper); } private IEnumerable<string> GetThemes() { return new[] { "default" , "desert" , "github" , "hemisu-dark" , "hemisu-light" , "son-of-obsidian" , "sunburst" , "tomorrow-night-blue" , "tomorrow-night-bright" , "tomorrow-night-eighties" , "tomorrow-night" , "tomorrow" , "vibrant-ink" }; } } }
mit
C#
9b6f850ad2f68fdff50267f68e5e930523768526
add utility function to search through a statement container
toontown-archive/Krypton.LibProtocol
Krypton.LibProtocol/Src/Member/Statement/IStatementContainer.cs
Krypton.LibProtocol/Src/Member/Statement/IStatementContainer.cs
using System; using System.Collections.Generic; namespace Krypton.LibProtocol.Member.Statement { public interface IStatementContainer { IEnumerable<IStatement> Statements { get; } void AddStatement(IStatement statement); } public class StatementContainerUtils { public static IStatement FindStatement(IStatementContainer container, Func<IStatement, bool> filter) { foreach (var s in container.Statements) { if (filter(s)) { return s; } // Search the statement if its an inner container if (!(s is IStatementContainer x)) continue; var res = FindStatement(x, filter); if (res != null) { return res; } } return null; } } }
using System.Collections.Generic; namespace Krypton.LibProtocol.Member.Statement { public interface IStatementContainer { IEnumerable<IStatement> Statements { get; } void AddStatement(IStatement statement); } }
mit
C#
09bfa510acbef0f144ae14e8f610cbb089b11399
Update MainPage.xaml.cs
gavronek/L2PAccess-Win
L2PAccess-Windows/L2PAccess-Windows.Windows/MainPage.xaml.cs
L2PAccess-Windows/L2PAccess-Windows.Windows/MainPage.xaml.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using L2PAccess.API; using L2PAccess.API.Model; using L2PAccess.Authentication; using L2PAccess.Authentication.Config; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace L2PAccess_Windows { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private async void Button_Click(object sender, RoutedEventArgs e) { var config = RwthConfig.Create("YOUR CLIENT ID"); var task1 = Task.Factory.StartNew(async () => { var l2PClient = new L2PClient(config); return await l2PClient.ViewAllCourseInfo(); }).Result; var task2 = Task.Factory.StartNew(async () => { var l2PClient = new L2PClient(config); return await l2PClient.ViewAllCourseInfo(); }).Result; var l2PResponses = await Task.WhenAll(task1, task2); ResuListView.ItemsSource = l2PResponses[0].dataSet.Select(course => course.courseTitle); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using L2PAccess.API; using L2PAccess.API.Model; using L2PAccess.Authentication; using L2PAccess.Authentication.Config; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace L2PAccess_Windows { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Page { public MainPage() { this.InitializeComponent(); } private async void Button_Click(object sender, RoutedEventArgs e) { var config = RwthConfig.Create("yJV0yVoAPZ3ykvnhZImWg61TBbMUBv7ZYI3zSo7XCaPlJKsMVOHBqBbbx7Ko5SXi.apps.rwth-aachen.de"); var task1 = Task.Factory.StartNew(async () => { var l2PClient = new L2PClient(config); return await l2PClient.ViewAllCourseInfo(); }).Result; var task2 = Task.Factory.StartNew(async () => { var l2PClient = new L2PClient(config); return await l2PClient.ViewAllCourseInfo(); }).Result; var l2PResponses = await Task.WhenAll(task1, task2); ResuListView.ItemsSource = l2PResponses[0].dataSet.Select(course => course.courseTitle); } } }
apache-2.0
C#
6e1e74b443af9c02fa8b68216a8aecc7a7f78a78
Disable CS1591 for TimeUnit,
CodeFromJordan/Humanizer,HalidCisse/Humanizer,preetksingh80/Humanizer,kikoanis/Humanizer,mrchief/Humanizer,micdenny/Humanizer,thunsaker/Humanizer,Flatlineato/Humanizer,CodeFromJordan/Humanizer,micdenny/Humanizer,schalpat/Humanizer,preetksingh80/Humanizer,mrchief/Humanizer,HalidCisse/Humanizer,llehouerou/Humanizer,ErikSchierboom/Humanizer,schalpat/Humanizer,ErikSchierboom/Humanizer,Flatlineato/Humanizer,aloisdg/Humanizer,thunsaker/Humanizer,CodeFromJordan/Humanizer,llehouerou/Humanizer,thunsaker/Humanizer,hazzik/Humanizer,jaxx-rep/Humanizer,mrchief/Humanizer,MehdiK/Humanizer,preetksingh80/Humanizer,llehouerou/Humanizer,HalidCisse/Humanizer,kikoanis/Humanizer
src/Humanizer/Localisation/TimeUnit.cs
src/Humanizer/Localisation/TimeUnit.cs
namespace Humanizer.Localisation { #pragma warning disable 1591 /// <summary> /// Units of time. /// </summary> public enum TimeUnit { Millisecond, Second, Minute, Hour, Day, Week, Month, Year } #pragma warning restore 1591 }
namespace Humanizer.Localisation { /// <summary> /// Units of time. /// </summary> public enum TimeUnit { Millisecond, Second, Minute, Hour, Day, Week, Month, Year } }
mit
C#
281d2077cfa54015074e637e09e68a929c78fa1d
remove unused code.
Terpla/A-Bot,scahyono/A-Bot
src/Sanderling.ABot/Bot/Task/Combat.cs
src/Sanderling.ABot/Bot/Task/Combat.cs
using BotEngine.Common; using System.Collections.Generic; using System.Linq; using Sanderling.Motor; using Sanderling.Parse; namespace Sanderling.ABot.Bot.Task { public class CombatTask : IBotTask { public Bot bot; public IEnumerable<IBotTask> Component { get { var memoryMeasurementAtTime = bot?.MemoryMeasurementAtTime; var memoryMeasurementAccu = bot?.MemoryMeasurementAccu; var memoryMeasurement = memoryMeasurementAtTime?.Value; var currentManeuverType = memoryMeasurement?.ShipUi?.Indication?.ManeuverType; if (ShipManeuverTypeEnum.Warp == currentManeuverType || ShipManeuverTypeEnum.Jump == currentManeuverType) yield break; var listOverviewEntryToAttack = memoryMeasurement?.WindowOverview?.FirstOrDefault()?.ListView?.Entry?.Where(entry => entry?.MainIcon?.Color?.IsRed() ?? false) ?.OrderBy(entry => entry?.DistanceMax ?? int.MaxValue) ?.ToArray(); var targetSelected = memoryMeasurement?.Target?.FirstOrDefault(target => target?.IsSelected ?? false); var shouldAttackTarget = listOverviewEntryToAttack?.Any(entry => entry?.MeActiveTarget ?? false) ?? false; var setModuleWeapon = memoryMeasurementAccu?.ShipUiModule?.Where(module => module?.TooltipLast?.Value?.IsWeapon ?? false); if (null != targetSelected) if (shouldAttackTarget) yield return bot.EnsureIsActive(setModuleWeapon); else yield return new MenuEntryInMenuRootTask { Bot = bot, MenuEntryRegexPattern = "unlock", RootUIElement = targetSelected }; var overviewEntryLockTarget = listOverviewEntryToAttack?.FirstOrDefault(entry => !((entry?.MeTargeted ?? false) || (entry?.MeTargeting ?? false))); if (null == overviewEntryLockTarget) yield break; yield return new MenuEntryInMenuRootTask { Bot = bot, RootUIElement = overviewEntryLockTarget, MenuEntryRegexPattern = @"^lock\s*target", }; } } public MotionParam Motion => null; } }
using BotEngine.Common; using System.Collections.Generic; using System.Linq; using Sanderling.Motor; using Sanderling.Parse; namespace Sanderling.ABot.Bot.Task { public class CombatTask : IBotTask { public Bot bot; public IEnumerable<IBotTask> Component { get { var memoryMeasurementAtTime = bot?.MemoryMeasurementAtTime; var memoryMeasurementAccu = bot?.MemoryMeasurementAccu; var memoryMeasurement = memoryMeasurementAtTime?.Value; var currentManeuverType = memoryMeasurement?.ShipUi?.Indication?.ManeuverType; if (ShipManeuverTypeEnum.Warp == currentManeuverType || ShipManeuverTypeEnum.Jump == currentManeuverType) yield break; var listOverviewEntryToAttack = memoryMeasurement?.WindowOverview?.FirstOrDefault()?.ListView?.Entry?.Where(entry => entry?.MainIcon?.Color?.IsRed() ?? false) ?.OrderBy(entry => entry?.DistanceMax ?? int.MaxValue) ?.ToArray(); var targetSelected = memoryMeasurement?.Target?.FirstOrDefault(target => target?.IsSelected ?? false); var shouldAttackTarget = listOverviewEntryToAttack?.Any(entry => entry?.MeActiveTarget ?? false) ?? false; var setModuleWeapon = memoryMeasurementAccu?.ShipUiModule?.Where(module => module?.TooltipLast?.Value?.IsWeapon ?? false); if (null != targetSelected) if (shouldAttackTarget) yield return bot.EnsureIsActive(setModuleWeapon); else yield return new MenuEntryInMenuRootTask { Bot = bot, MenuEntryRegexPattern = "unlock", RootUIElement = targetSelected }; var overviewEntryLockTarget = listOverviewEntryToAttack?.FirstOrDefault(entry => !((entry?.MeTargeted ?? false) || (entry?.MeTargeting ?? false))); if (null == overviewEntryLockTarget) yield break; var menu = memoryMeasurement?.Menu?.FirstOrDefault(); var menuIsOpenedForOverviewEntry = bot?.MouseClickLastAgeStepCountFromUIElement(overviewEntryLockTarget) <= 1 && (menu?.Entry?.Any(menuEntry => menuEntry?.Text?.RegexMatchSuccessIgnoreCase(@"remove.*overview") ?? false) ?? false); yield return new MenuEntryInMenuRootTask { Bot = bot, RootUIElement = overviewEntryLockTarget, MenuEntryRegexPattern = @"^lock\s*target", }; } } public MotionParam Motion => null; } }
apache-2.0
C#
7c90d77ecabc237e17e4a9e6413a5a74952115ce
Bump to 0.8.0.0 version
modulexcite/Nowin,Bobris/Nowin,et1975/Nowin,Bobris/Nowin,lstefano71/Nowin,pysco68/Nowin,lstefano71/Nowin,modulexcite/Nowin,Bobris/Nowin,et1975/Nowin,pysco68/Nowin,modulexcite/Nowin,pysco68/Nowin,lstefano71/Nowin,et1975/Nowin
NowinWebServer/Properties/AssemblyInfo.cs
NowinWebServer/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NowinWebServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("NowinWebServer")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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.8.0.0")] [assembly: AssemblyFileVersion("0.8.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("NowinWebServer")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Boris Letocha")] [assembly: AssemblyProduct("NowinWebServer")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fd085b68-3766-42af-ab6d-351b7741c685")] // 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.7.1.0")] [assembly: AssemblyFileVersion("0.7.1.0")]
mit
C#
a2c8cbcfa316e5975ccfee71a1088cef7e871b27
Add logging capability to serviceaware
greymind/WebApiToTypeScript,greymind/WebApiToTypeScript,greymind/WebApiToTypeScript
src/WebApiToTypeScript/ServiceAware.cs
src/WebApiToTypeScript/ServiceAware.cs
using WebApiToTypeScript.Enums; using WebApiToTypeScript.Interfaces; using WebApiToTypeScript.Types; namespace WebApiToTypeScript { public abstract class ServiceAware { protected string IHaveQueryParams = WebApiToTypeScript.IHaveQueryParams; protected string IEndpoint = WebApiToTypeScript.IEndpoint; protected TypeService TypeService => WebApiToTypeScript.TypeService; protected EnumsService EnumsService => WebApiToTypeScript.EnumsService; protected InterfaceService InterfaceService => WebApiToTypeScript.InterfaceService; public Config.Config Config => WebApiToTypeScript.Config; public void LogMessage(string message) => WebApiToTypeScript.LogMessages.Add(message); } }
using WebApiToTypeScript.Enums; using WebApiToTypeScript.Interfaces; using WebApiToTypeScript.Types; namespace WebApiToTypeScript { public abstract class ServiceAware { protected string IHaveQueryParams = WebApiToTypeScript.IHaveQueryParams; protected string IEndpoint = WebApiToTypeScript.IEndpoint; protected TypeService TypeService => WebApiToTypeScript.TypeService; protected EnumsService EnumsService => WebApiToTypeScript.EnumsService; protected InterfaceService InterfaceService => WebApiToTypeScript.InterfaceService; public Config.Config Config => WebApiToTypeScript.Config; } }
mit
C#
63536c2ed0f36a0cd4d1fd3d3104e94b680ed64d
Update WireMock.Net.StandAlone
StefH/WireMock.Net,StefH/WireMock.Net,WireMock-Net/WireMock.Net
src/WireMock.Net.StandAlone/Program.cs
src/WireMock.Net.StandAlone/Program.cs
using System; using System.Collections.Generic; using System.Linq; using CommandLineParser.Arguments; using CommandLineParser.Exceptions; using WireMock.Server; namespace WireMock.Net.StandAlone { public class Program { private class Options { [ValueArgument(typeof(string), 'u', "Urls", Description = "URL(s) to listen on.", Optional = true, AllowMultiple = true)] public List<string> Urls { get; set; } [SwitchArgument('p', "AllowPartialMapping", true, Description = "Allow Partial Mapping (default set to true).", Optional = true)] public bool AllowPartialMapping { get; set; } } static void Main(params string[] args) { var options = new Options(); var parser = new CommandLineParser.CommandLineParser(); parser.ExtractArgumentAttributes(options); try { parser.ParseCommandLine(args); if (!options.Urls.Any()) options.Urls.Add("http://localhost:9090/"); var server = FluentMockServer.StartWithAdminInterface(options.Urls.ToArray()); if (options.AllowPartialMapping) server.AllowPartialMapping(); Console.WriteLine("WireMock.Net server listening at {0}", string.Join(" and ", server.Urls)); } catch (CommandLineException e) { Console.WriteLine(e.Message); parser.ShowUsage(); } Console.WriteLine("Press any key to stop the server"); Console.ReadKey(); } } }
using System; using CommandLineParser.Arguments; using CommandLineParser.Exceptions; using WireMock.Server; namespace WireMock.Net.StandAlone { public class Program { private class Options { [ValueArgument(typeof(string), 'u', "Urls", Description = "URL(s) to listen on", Optional = false, AllowMultiple = true)] public string[] Urls; [SwitchArgument('p', "AllowPartialMapping", true, Description = "Allow Partial Mapping (default set to true)", Optional = true)] public bool AllowPartialMapping; } static void Main(params string[] args) { var options = new Options(); var parser = new CommandLineParser.CommandLineParser(); parser.ExtractArgumentAttributes(options); parser.ParseCommandLine(args); try { parser.ParseCommandLine(args); var server = FluentMockServer.StartWithAdminInterface(options.Urls); if (options.AllowPartialMapping) server.AllowPartialMapping(); Console.WriteLine("WireMock.Net server listening at {0}", string.Join(" and ", server.Urls)); } catch (CommandLineException e) { Console.WriteLine(e.Message); parser.ShowUsage(); } Console.WriteLine("Press any key to stop the server"); Console.ReadKey(); } } }
apache-2.0
C#
d4a986b4977b40358f036ea4a360ca40df741ba9
Write more INDI data
fire-eggs/YAGP,fire-eggs/YAGP,fire-eggs/YAGP
SharpGEDParse/SharpGEDWriter/WriteINDI.cs
SharpGEDParse/SharpGEDWriter/WriteINDI.cs
using System.Reflection; using SharpGEDParser.Model; using System; using System.Collections.Generic; using System.IO; // TODO can record ident be generalized? namespace SharpGEDWriter { class WriteINDI { internal static void WriteINDIs(StreamWriter file, List<GEDCommon> records) { foreach (var gedCommon in records) { if (gedCommon is IndiRecord) WriteOneIndi(file, gedCommon as IndiRecord); } } private static void WriteOneIndi(StreamWriter file, IndiRecord indiRecord) { file.WriteLine("0 @{0}@ INDI", indiRecord.Ident); WriteCommon.writeIfNotEmpty(file, "RESN", indiRecord.Restriction, 1); // TODO original text or corrected? WriteCommon.writeIfNotEmpty(file, "SEX", indiRecord.FullSex, 1); // TODO NAME // FAMC/FAMS foreach (var indiLink in indiRecord.Links) { // TODO extra text WriteCommon.writeXrefIfNotEmpty(file, indiLink.Tag, indiLink.Xref, 2); WriteCommon.writeIfNotEmpty(file, "PEDI", indiLink.Pedi, 3); WriteCommon.writeIfNotEmpty(file, "STAT", indiLink.Stat, 3); WriteCommon.writeSubNotes(file, indiLink, 3); } WriteEvent.writeEvents(file, indiRecord.Events, 1); WriteEvent.writeEvents(file, indiRecord.Attribs, 1); // TODO LDS events foreach (var aliasLink in indiRecord.AliasLinks) { WriteCommon.writeXrefIfNotEmpty(file, "ALIA", aliasLink, 1); } foreach (var assoRec in indiRecord.Assocs) { WriteCommon.writeXrefIfNotEmpty(file, "ASSO", assoRec.Ident, 1); WriteCommon.writeIfNotEmpty(file, "RELA", assoRec.Relation, 2); WriteCommon.writeSubNotes(file, assoRec, 2); WriteCommon.writeSourCit(file, assoRec, 2); } // TODO why are INDI and FAM submitters treated different? foreach (var submitter in indiRecord.Submitters) { file.WriteLine("1 SUBM @{0}@", submitter.Xref); } WriteCommon.writeRecordTrailer(file, indiRecord, 1); } } }
using SharpGEDParser.Model; using System; using System.Collections.Generic; using System.IO; // TODO can record ident be generalized? namespace SharpGEDWriter { class WriteINDI { internal static void WriteINDIs(StreamWriter file, List<GEDCommon> records) { foreach (var gedCommon in records) { if (gedCommon is IndiRecord) WriteOneIndi(file, gedCommon as IndiRecord); } } private static void WriteOneIndi(StreamWriter file, IndiRecord indiRecord) { file.WriteLine("0 @{0}@ INDI", indiRecord.Ident); WriteEvent.writeEvents(file, indiRecord.Events, 1); WriteEvent.writeEvents(file, indiRecord.Attribs, 1); // TODO LDS events // TODO why are INDI and FAM submitters treated different? foreach (var submitter in indiRecord.Submitters) { file.WriteLine("1 SUBM @{0}@", submitter.Xref); } WriteCommon.writeRecordTrailer(file, indiRecord, 1); } } }
apache-2.0
C#
dbfbcdddc4b7bcbc78a167d0b677aa2da09ea9ac
delete code dupe
MartinRL/SlackTurnus,MartinRL/SlackTurnus
SlackTurnus/Controllers/HomeController.cs
SlackTurnus/Controllers/HomeController.cs
using System; using System.Collections; using System.Linq; using System.Web.Mvc; using System.Web.UI.WebControls; using SlackTurnus.DomainModel; using SlackTurnus.ViewModel; namespace SlackTurnus.Controllers { public class HomeController : Controller { private const string PRIMARY_SLACKER_TURNUS = "primarySlackerTurnus"; private const string SECONDARY_SLACKER_TURNUS = "secondarySlackerTurnus"; private readonly IGetSlackTurnus _getSlackTurnus; private readonly IUpdateSlackTurnus _updateSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus, IUpdateSlackTurnus updateSlackTurnus) { _getSlackTurnus = getSlackTurnus; _updateSlackTurnus = updateSlackTurnus; } public ActionResult Index() { var primarySlackerTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var secondarySlackerTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var slackerNamePairs = primarySlackerTurnus.Zip(secondarySlackerTurnus, (primaryDictionaryEntry, secondaryDictionaryEntry) => new Tuple<string, string>((string)primaryDictionaryEntry.Key, (string)secondaryDictionaryEntry.Key)); return View(new HomeViewModel(slackerNamePairs.Reverse())); } private ActionResult Next(string turnus) { var slackTurnus = _getSlackTurnus.Execute(turnus); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, turnus); return RedirectToAction("Index"); } public ActionResult NextPrimary() { return Next(PRIMARY_SLACKER_TURNUS); } public ActionResult NextSecondary() { return Next(SECONDARY_SLACKER_TURNUS); } private ActionResult Skip(string turnus) { var slackTurnus = _getSlackTurnus.Execute(turnus); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, turnus); return RedirectToAction("Index"); } public ActionResult SkipPrimary() { return Skip(PRIMARY_SLACKER_TURNUS); } public ActionResult SkipSecondary() { return Skip(SECONDARY_SLACKER_TURNUS); } } }
using System; using System.Collections; using System.Linq; using System.Web.Mvc; using System.Web.UI.WebControls; using SlackTurnus.DomainModel; using SlackTurnus.ViewModel; namespace SlackTurnus.Controllers { public class HomeController : Controller { private const string PRIMARY_SLACKER_TURNUS = "primarySlackerTurnus"; private const string SECONDARY_SLACKER_TURNUS = "secondarySlackerTurnus"; private readonly IGetSlackTurnus _getSlackTurnus; private readonly IUpdateSlackTurnus _updateSlackTurnus; public HomeController(IGetSlackTurnus getSlackTurnus, IUpdateSlackTurnus updateSlackTurnus) { _getSlackTurnus = getSlackTurnus; _updateSlackTurnus = updateSlackTurnus; } public ActionResult Index() { var primarySlackerTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var secondarySlackerTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS).Cast<DictionaryEntry>(); var slackerNamePairs = primarySlackerTurnus.Zip(secondarySlackerTurnus, (primaryDictionaryEntry, secondaryDictionaryEntry) => new Tuple<string, string>((string)primaryDictionaryEntry.Key, (string)secondaryDictionaryEntry.Key)); return View(new HomeViewModel(slackerNamePairs.Reverse())); } private ActionResult Next(string turnus) { var slackTurnus = _getSlackTurnus.Execute(turnus); slackTurnus.Next(); _updateSlackTurnus.Execute(slackTurnus, turnus); return RedirectToAction("Index"); } public ActionResult NextPrimary() { return Next(PRIMARY_SLACKER_TURNUS); } public ActionResult NextSecondary() { return Next(SECONDARY_SLACKER_TURNUS); } public ActionResult SkipPrimary() { var slackTurnus = _getSlackTurnus.Execute(PRIMARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, PRIMARY_SLACKER_TURNUS); return RedirectToAction("Index"); } public ActionResult SkipSecondary() { var slackTurnus = _getSlackTurnus.Execute(SECONDARY_SLACKER_TURNUS); slackTurnus.Skip(); _updateSlackTurnus.Execute(slackTurnus, SECONDARY_SLACKER_TURNUS); return RedirectToAction("Index"); } } }
mit
C#
cf5e987851c42fb536d165c03be63b2a454e3099
Bump version to 1.1.0
matthid/Yaaf.DependencyInjection,matthid/Yaaf.DependencyInjection
src/SharedAssemblyInfo.SimpleInjector.cs
src/SharedAssemblyInfo.SimpleInjector.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyCompanyAttribute("Yaaf.DependencyInjection.SimpleInjector")] [assembly: AssemblyProductAttribute("Yaaf.DependencyInjection.SimpleInjector")] [assembly: AssemblyCopyrightAttribute("Yaaf.DependencyInjection Copyright © Matthias Dittrich 2015")] [assembly: AssemblyVersionAttribute("1.1.3")] [assembly: AssemblyFileVersionAttribute("1.1.3")] [assembly: AssemblyInformationalVersionAttribute("1.1.3")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "1.1.3"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyCompanyAttribute("Yaaf.DependencyInjection.SimpleInjector")] [assembly: AssemblyProductAttribute("Yaaf.DependencyInjection.SimpleInjector")] [assembly: AssemblyCopyrightAttribute("Yaaf.DependencyInjection Copyright © Matthias Dittrich 2015")] [assembly: AssemblyVersionAttribute("1.1.2")] [assembly: AssemblyFileVersionAttribute("1.1.2")] [assembly: AssemblyInformationalVersionAttribute("1.1.2")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "1.1.2"; } }
apache-2.0
C#
68bbaa373a4b3ff125df81f3c7d7acda05f8715a
fix namespace
huoxudong125/Weakly,tibel/Weakly
src/Weakly/Delegates/ActionDisposable.cs
src/Weakly/Delegates/ActionDisposable.cs
using System; namespace Weakly { /// <summary> /// Executes an action when disposed. /// </summary> public sealed class DisposableAction : IDisposable { private Action _action; /// <summary> /// Initializes a new instance of the <see cref="DisposableAction"/> class. /// </summary> /// <param name="action">The action to execute on dispose.</param> public DisposableAction(Action action) { if (action == null) throw new ArgumentNullException("action"); _action = action; } /// <summary> /// Executes the supplied action. /// </summary> public void Dispose() { if (_action == null) return; _action(); _action = null; } } }
using System; namespace Weakly.MVVM { /// <summary> /// Executes an action when disposed. /// </summary> public sealed class DisposableAction : IDisposable { private Action _action; /// <summary> /// Initializes a new instance of the <see cref="DisposableAction"/> class. /// </summary> /// <param name="action">The action to execute on dispose.</param> public DisposableAction(Action action) { if (action == null) throw new ArgumentNullException("action"); _action = action; } /// <summary> /// Executes the supplied action. /// </summary> public void Dispose() { if (_action == null) return; _action(); _action = null; } } }
mit
C#
527f4e5d5c2f482f259db7d2fc09bc9a5a4acbf7
Update ListExtensions.cs
djfdat/UnityUtilities
Assets/Scripts/Extensions/ListExtensions.cs
Assets/Scripts/Extensions/ListExtensions.cs
using UnityEngine; using System.Collections.Generic; public static class ListExtensions { public static T RandomEntry<T>(this List<T> list) { return list[Random.Range(0, list.Count)]; } public static int RandomIndex<T>(this List<T> list, int excludedIndex = -1) { if (excludedIndex == -1) { return Random.Range(0, list.Count); } return (excludedIndex + Random.Range(1, list.Count)) % list.Count; } public static List<T> ExtractComponent<T>(this List<GameObject> GameObjects) { List<T> returnList = new List<T>(); foreach (GameObject go in GameObjects) { T tempC = go.GetComponent<T>(); if (tempC != null) { returnList.Add(tempC); } } return returnList; } }
using UnityEngine; using System.Collections.Generic; public static class ListExtensions { public static T RandomEntry<T>(this List<T> list) { return list[Random.Range(0, list.Count)]; } public static int RandomIndex<T>(this List<T> list, int excludedIndex = -1) { if (excludedIndex == -1) { return Random.Range(0, list.Count); } return (excludedIndex + Random.Range(1, list.Count)) % list.Count; } }
mit
C#
a42230af7330e89ada8faf17a7c52dfa7b7a7614
Add groups to the serialization
InWorldz/chrysalis
src/Controllers/GeometryController.cs
src/Controllers/GeometryController.cs
using System.Net; using System.Threading.Tasks; using FlatBuffers; using InWorldz.Arbiter.Serialization; using InWorldz.Chrysalis.Util; namespace InWorldz.Chrysalis.Controllers { /// <summary> /// Handles incoming requests related to geometry /// </summary> internal class GeometryController { public GeometryController(HttpFrontend frontEnd) { frontEnd.AddHandler("POST", "/geometry/hp2b", ConvertHalcyonPrimToBabylon); frontEnd.AddHandler("POST", "/geometry/hg2b", ConvertHalcyonGroupToBabylon); } private async Task ConvertHalcyonPrimToBabylon(HttpListenerContext context, HttpListenerRequest request) { //halcyon gemoetry is coming in as a primitive flatbuffer object //as binary in the body. deserialize and convert using the prim exporter ByteBuffer body = await StreamUtil.ReadStreamFullyAsync(request.InputStream); var prim = HalcyonPrimitive.GetRootAsHalcyonPrimitive(body); } private async Task ConvertHalcyonGroupToBabylon(HttpListenerContext context, HttpListenerRequest request) { //halcyon gemoetry is coming in as a primitive flatbuffer object //as binary in the body. deserialize and convert using the prim exporter ByteBuffer body = await StreamUtil.ReadStreamFullyAsync(request.InputStream); var prim = HalcyonPrimitive.GetRootAsHalcyonPrimitive(body); } } }
using System.Net; using System.Threading.Tasks; using FlatBuffers; using InWorldz.Arbiter.Serialization; using InWorldz.Chrysalis.Util; namespace InWorldz.Chrysalis.Controllers { /// <summary> /// Handles incoming requests related to geometry /// </summary> internal class GeometryController { public GeometryController(HttpFrontend frontEnd) { frontEnd.AddHandler("POST", "/geometry/h2b", ConvertHalcyonGeomToBabylon); } private async Task ConvertHalcyonGeomToBabylon(HttpListenerContext context, HttpListenerRequest request) { //halcyon gemoetry is coming in as a primitive flatbuffer object //as binary in the body. deserialize and convert using the prim exporter ByteBuffer body = await StreamUtil.ReadStreamFullyAsync(request.InputStream); var prim = HalcyonPrimitive.GetRootAsHalcyonPrimitive(body); } } }
apache-2.0
C#
218c899441f7e3ac6b41cb58dd30be4cb9b0f886
Reset Handle when Dispose.
zhongzf/Xamarin.Forms.Platform.LibUI
Xamarin.Forms.Platform.LibUI/Control.cs
Xamarin.Forms.Platform.LibUI/Control.cs
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms.Platform.LibUI.Interop; using static Xamarin.Forms.Platform.LibUI.Interop.NativeMethods; namespace Xamarin.Forms.Platform.LibUI { public abstract class Control: IDisposable { protected internal IntPtr Handle { get; protected set; } public void Dispose() { if (Handle != IntPtr.Zero) { uiControlDestroy(Handle); Handle = IntPtr.Zero; } GC.SuppressFinalize(this); } private Control _parent; public Control Parent { get { return _parent; } set { _parent = value; uiControlSetParent(Handle, _parent.Handle); } } public bool TopLevel => uiControlToplevel(Handle); public bool Visible => uiControlVisible(Handle); public void Show() => uiControlShow(Handle); public void Hide() => uiControlHide(Handle); public bool Enabled => uiControlEnabled(Handle); public void Enable() => uiControlEnable(Handle); public void Disable() => uiControlDisable(Handle); } }
using System; using System.Collections.Generic; using System.Text; using Xamarin.Forms.Platform.LibUI.Interop; using static Xamarin.Forms.Platform.LibUI.Interop.NativeMethods; namespace Xamarin.Forms.Platform.LibUI { public abstract class Control: IDisposable { protected internal IntPtr Handle { get; protected set; } public void Dispose() { if (Handle != IntPtr.Zero) { uiControlDestroy(Handle); } GC.SuppressFinalize(this); } private Control _parent; public Control Parent { get { return _parent; } set { _parent = value; uiControlSetParent(Handle, _parent.Handle); } } public bool TopLevel => uiControlToplevel(Handle); public bool Visible => uiControlVisible(Handle); public void Show() => uiControlShow(Handle); public void Hide() => uiControlHide(Handle); public bool Enabled => uiControlEnabled(Handle); public void Enable() => uiControlEnable(Handle); public void Disable() => uiControlDisable(Handle); } }
mit
C#
245dcf4be2d7ed8d19b5a896ad02151927a00528
Add an ErrorMessage
ucdavis/CRP,ucdavis/CRP,ucdavis/CRP
CRP.Mvc/Controllers/ApplicatonController.cs
CRP.Mvc/Controllers/ApplicatonController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CRP.Controllers.Helpers; using UCDArch.Web.Controller; namespace CRP.Controllers { //[LocServiceMessage("ConferenceRegistrationAndPayments", ViewDataKey = "ServiceMessages", MessageServiceAppSettingsKey = "MessageServer")] public class ApplicationController : SuperController { private const string TempDataErrorMessageKey = "ErrorMessage"; public string ErrorMessage { get => TempData[TempDataErrorMessageKey] as string; set => TempData[TempDataErrorMessageKey] = value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CRP.Controllers.Helpers; using UCDArch.Web.Controller; namespace CRP.Controllers { //[LocServiceMessage("ConferenceRegistrationAndPayments", ViewDataKey = "ServiceMessages", MessageServiceAppSettingsKey = "MessageServer")] public class ApplicationController : SuperController { } }
mit
C#
aaecb45c13e669ad5203d6374ea36e9bc5690953
replace old parameter names with new key parameter names
tropo/tropo-webapi-csharp,tropo/tropo-webapi-csharp
TropoOutboundSMS/Program.cs
TropoOutboundSMS/Program.cs
using System; using System.Collections.Generic; using System.Web; using System.Xml; using TropoCSharp.Structs; using TropoCSharp.Tropo; namespace OutboundTest { /// <summary> /// A simple console appplication used to launch a Tropo Session and send an outbound SMS. /// Note - use in conjnction withe the OutboundSMS.aspx example in the TropoSamples project. /// For further information, see http://blog.tropo.com/2011/04/14/sending-outbound-sms-with-c/ /// </summary> class Program { static void Main(string[] args) { // The voice and messaging tokens provisioned when your Tropo application is set up. string voiceToken = "your-voice-token-here"; string messagingToken = "your-messaging-token-here"; // A collection to hold the parameters we want to send to the Tropo Session API. IDictionary<string, string> parameters = new Dictionary<String, String>(); // Enter a phone number to send a call or SMS message to here. parameters.Add("numberToDial", "15551112222"); // Enter a phone number to use as the caller ID. parameters.Add("sendFromNumber", "15551113333"); // Select the channel you want to use via the Channel struct. string channel = Channel.Text; parameters.Add("channel", channel); string network = Network.SMS; parameters.Add("network", network); // Message is sent as a query string parameter, make sure it is properly encoded. parameters.Add("textMessageBody", HttpUtility.UrlEncode("This is a test message from C#.")); // Instantiate a new instance of the Tropo object. Tropo tropo = new Tropo(); // Create an XML doc to hold the response from the Tropo Session API. XmlDocument doc = new XmlDocument(); // Set the token to use. string token = channel == Channel.Text ? messagingToken : voiceToken; // Load the XML document with the return value of the CreateSession() method call. doc.Load(tropo.CreateSession(token, parameters)); // Display the results in the console. Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper()); Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText); Console.Read(); } } }
using System; using System.Collections.Generic; using System.Web; using System.Xml; using TropoCSharp.Structs; using TropoCSharp.Tropo; namespace OutboundTest { /// <summary> /// A simple console appplication used to launch a Tropo Session and send an outbound SMS. /// Note - use in conjnction withe the OutboundSMS.aspx example in the TropoSamples project. /// For further information, see http://blog.tropo.com/2011/04/14/sending-outbound-sms-with-c/ /// </summary> class Program { static void Main(string[] args) { // The voice and messaging tokens provisioned when your Tropo application is set up. string voiceToken = "your-voice-token-here"; string messagingToken = "your-messaging-token-here"; // A collection to hold the parameters we want to send to the Tropo Session API. IDictionary<string, string> parameters = new Dictionary<String, String>(); // Enter a phone number to send a call or SMS message to here. parameters.Add("sendToNumber", "15551112222"); // Enter a phone number to use as the caller ID. parameters.Add("sendFromNumber", "15551113333"); // Select the channel you want to use via the Channel struct. string channel = Channel.Text; parameters.Add("channel", channel); string network = Network.SMS; parameters.Add("network", network); // Message is sent as a query string parameter, make sure it is properly encoded. parameters.Add("msg", HttpUtility.UrlEncode("This is a test message from C#.")); // Instantiate a new instance of the Tropo object. Tropo tropo = new Tropo(); // Create an XML doc to hold the response from the Tropo Session API. XmlDocument doc = new XmlDocument(); // Set the token to use. string token = channel == Channel.Text ? messagingToken : voiceToken; // Load the XML document with the return value of the CreateSession() method call. doc.Load(tropo.CreateSession(token, parameters)); // Display the results in the console. Console.WriteLine("Result: " + doc.SelectSingleNode("session/success").InnerText.ToUpper()); Console.WriteLine("Token: " + doc.SelectSingleNode("session/token").InnerText); Console.Read(); } } }
mit
C#
3c526de640bc4f45d67a4bb59e7a01be5431e4d6
update annotation
60071jimmy/UartOscilloscope,60071jimmy/UartOscilloscope
UartOscilloscope/Program.cs
UartOscilloscope/Program.cs
using System; // 使用System函式庫 using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; // 使用System.Windows.Forms函式庫 namespace UartOscilloscope // 命名空間為本程式 { static class Program // Program類別 { // 進入Program類別 /// <summary> /// 應用程式的主要進入點。 /// </summary> [STAThread] static void Main() // Main(主程式) { // 進入Main(主程式) Application.EnableVisualStyles(); // 為應用程式啟用視覺化樣式 Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } // 結束Main(主程式) } // 結束Program類別 }
using System; // 使用System函式庫 using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; // 使用System.Windows.Forms函式庫 namespace UartOscilloscope // 命名空間為本程式 { static class Program // Program類別 { // 進入Program類別 /// <summary> /// 應用程式的主要進入點。 /// </summary> [STAThread] static void Main() // Main(主程式) { // 進入Main(主程式) Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } // 結束Main(主程式) } // 結束Program類別 }
apache-2.0
C#
7f480dae1a64c47f0052475c77442b916a26daea
Correct face away logic
DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit.SDK/Features/Input/Handlers/Constraints/FaceUserConstraint.cs
Assets/MixedRealityToolkit.SDK/Features/Input/Handlers/Constraints/FaceUserConstraint.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI { /// <summary> /// Component for fixing the rotation of a manipulated object such that /// it always faces or faces away from the user /// </summary> public class FaceUserConstraint : TransformConstraint { #region Properties [SerializeField] [Tooltip("Option to use this constraint to face away from the user")] private bool faceAway = false; /// <summary> /// If true, this will constrain rotation to face away from the user /// </summary> public bool FaceAway { get => faceAway; set => faceAway = value; } public override TransformFlags ConstraintType => TransformFlags.Rotate; #endregion Properties #region Public Methods /// <summary> /// Updates an rotation so that its facing the camera /// </summary> public override void ApplyConstraint(ref MixedRealityTransform transform) { Vector3 directionToTarget = transform.Position - CameraCache.Main.transform.position; transform.Rotation = Quaternion.LookRotation(faceAway ? directionToTarget : -directionToTarget); } #endregion Public Methods } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.UI { /// <summary> /// Component for fixing the rotation of a manipulated object such that /// it always faces or faces away from the user /// </summary> public class FaceUserConstraint : TransformConstraint { #region Properties [SerializeField] [Tooltip("Option to use this constraint to face away from the user")] private bool faceAway = false; /// <summary> /// If true, this will constrain rotation to face away from the user /// </summary> public bool FaceAway { get => faceAway; set => faceAway = value; } public override TransformFlags ConstraintType => TransformFlags.Rotate; #endregion Properties #region Public Methods /// <summary> /// Updates an rotation so that its facing the camera /// </summary> public override void ApplyConstraint(ref MixedRealityTransform transform) { Vector3 directionToTarget = transform.Position - CameraCache.Main.transform.position; transform.Rotation = Quaternion.LookRotation(faceAway ? -directionToTarget : directionToTarget); } #endregion Public Methods } }
mit
C#
e4c100e8ad8e30a75cd42a878e030f3c3bcbb3e9
add back selenium assertions
alindgren/Fundraise,alindgren/Fundraise,alindgren/Fundraise
Fundraise.MvcExample.Tests/AdminTests.cs
Fundraise.MvcExample.Tests/AdminTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium.Firefox; using Fundraise.MvcExample.Tests.Config; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace Fundraise.MvcExample.Tests { [TestClass] public class AdminTests { public static IisExpressWebServer WebServer; public static FirefoxDriver Browser; [ClassInitialize] public static void Init(TestContext context) { var app = new WebApplication(ProjectLocation.FromFolder("Fundraise.MvcExample"), 12365); WebServer = new IisExpressWebServer(app); WebServer.Start(); Browser = new FirefoxDriver(); } [ClassCleanup] public static void Cleanup() { Browser.Quit(); WebServer.Stop(); // todo: reset LocalDB } [TestMethod] public void CreateNewAccount() { Browser.Manage().Window.Maximize(); Browser.Navigate().GoToUrl("http://localhost:12365/Account/Register"); var emailBox = Browser.FindElementById("Email"); emailBox.SendKeys("test@alexlindgren.com"); var passwordBox = Browser.FindElementById("Password"); passwordBox.SendKeys("test1234"); var confirmPasswordBox = Browser.FindElementById("ConfirmPassword"); confirmPasswordBox.SendKeys("test1234"); var submitButton = Browser.FindElementById("RegisterSubmit"); submitButton.Submit(); try { var wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(10)); var element = wait.Until(driver => driver.FindElement(By.Id("manage"))); } catch (Exception ex) { Console.WriteLine("Exception while waiting for 'manage': " + ex.Message); var screenshot = Browser.GetScreenshot(); screenshot.SaveAsFile("error.png"); } Assert.IsTrue(Browser.Url == "http://localhost:12365/", "The browser should redirect to 'http://localhost:12365/'"); Assert.IsTrue(Browser.PageSource.Contains(""), "After registering, browser should display 'Hello test@alexlindgren.com!'"); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium.Firefox; using Fundraise.MvcExample.Tests.Config; using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; namespace Fundraise.MvcExample.Tests { [TestClass] public class AdminTests { public static IisExpressWebServer WebServer; public static FirefoxDriver Browser; [ClassInitialize] public static void Init(TestContext context) { var app = new WebApplication(ProjectLocation.FromFolder("Fundraise.MvcExample"), 12365); WebServer = new IisExpressWebServer(app); WebServer.Start(); Browser = new FirefoxDriver(); } [ClassCleanup] public static void Cleanup() { Browser.Quit(); WebServer.Stop(); // todo: reset LocalDB } [TestMethod] public void CreateNewAccount() { Browser.Manage().Window.Maximize(); Browser.Navigate().GoToUrl("http://localhost:12365/Account/Register"); var emailBox = Browser.FindElementById("Email"); emailBox.SendKeys("test@alexlindgren.com"); var passwordBox = Browser.FindElementById("Password"); passwordBox.SendKeys("test1234"); var confirmPasswordBox = Browser.FindElementById("ConfirmPassword"); confirmPasswordBox.SendKeys("test1234"); var submitButton = Browser.FindElementById("RegisterSubmit"); submitButton.Submit(); try { var wait = new WebDriverWait(Browser, TimeSpan.FromSeconds(10)); var element = wait.Until(driver => driver.FindElement(By.Id("manage"))); } catch (Exception ex) { Console.WriteLine("Exception while waiting for 'manage': " + ex.Message); var screenshot = Browser.GetScreenshot(); screenshot.SaveAsFile("error.png"); } //Assert.IsTrue(Browser.Url == "http://localhost:12365/", "The browser should redirect to 'http://localhost:12365/'"); //Assert.IsTrue(Browser.PageSource.Contains(""), "After registering, browser should display 'Hello test@alexlindgren.com!'"); } } }
mit
C#
bbb55a0c60b98fddfa45e80d4dbf19889d970aba
Correct Version Number.
krs43/ib-csharp,sebfia/ib-csharp,qusma/ib-csharp
Krs.Ats.IBNet/Properties/AssemblyInfo.cs
Krs.Ats.IBNet/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly : AssemblyTitle("Krs.Ats.IBNet")] [assembly : AssemblyDescription("Interactive Brokers C# Client")] [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("Dinosaurtech")] [assembly : AssemblyProduct("Krs.Ats.IBNet")] [assembly : AssemblyCopyright("Copyright © 2010")] [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("099cdbe6-c63a-4c1d-9d1e-de9942e56388")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly : AssemblyVersion("9.6.4.16")] [assembly : AssemblyFileVersion("9.6.4.16")] //CLS Compliant [assembly : CLSCompliant(true)]
using System; using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly : AssemblyTitle("Krs.Ats.IBNet")] [assembly : AssemblyDescription("Interactive Brokers C# Client")] [assembly : AssemblyConfiguration("")] [assembly : AssemblyCompany("Dinosaurtech")] [assembly : AssemblyProduct("Krs.Ats.IBNet")] [assembly : AssemblyCopyright("Copyright © 2009")] [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("099cdbe6-c63a-4c1d-9d1e-de9942e56388")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly : AssemblyVersion("9.6.3.15")] [assembly : AssemblyFileVersion("9.6.3.15")] //CLS Compliant [assembly : CLSCompliant(true)]
mit
C#
8cdfd6230ec1b223add50fae61a03b3bfd277211
Implement Icompareable in class.cs
JunaidSarfraz/SchoolSystem
SchoolSystem/Class.cs
SchoolSystem/Class.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SchoolSystem { using System; using System.Collections.Generic; public partial class Class : IComparable { public Class() { this.Courses = new HashSet<Course>(); this.Sections = new HashSet<Section>(); } public decimal Id { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<Course> Courses { get; set; } public virtual ICollection<Section> Sections { get; set; } public int CompareTo(object obj) { return this.Name.CompareTo(((Class)obj).Name); } } }
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SchoolSystem { using System; using System.Collections.Generic; public partial class Class { public Class() { this.Courses = new HashSet<Course>(); this.Sections = new HashSet<Section>(); } public decimal Id { get; set; } public string Name { get; set; } public string Description { get; set; } public virtual ICollection<Course> Courses { get; set; } public virtual ICollection<Section> Sections { get; set; } } }
apache-2.0
C#
b51bc7a856454e65533765de38c43488a2880c3d
update SharedAssemblyInfo.cs for 1.1 release
Pavuucek/ArachNGIN,Pavuucek/ArachNGIN
SharedAssemblyInfo.cs
SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. //[assembly: AssemblyTitle("ArachNGIN.Files")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("X-C Soft ltd.")] [assembly: AssemblyProduct("ArachNGIN")] [assembly: AssemblyCopyright("Copyright © X-C Soft ltd. 2007 - 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // 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.1.0.0")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: AssemblyInformationalVersion("master:1.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. //[assembly: AssemblyTitle("ArachNGIN.Files")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("X-C Soft ltd.")] [assembly: AssemblyProduct("ArachNGIN")] [assembly: AssemblyCopyright("Copyright © X-C Soft ltd. 2007 - 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // 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.1.146")] [assembly: AssemblyVersion("1.0.1.146")] [assembly: AssemblyFileVersion("1.0.1.146")] [assembly: AssemblyInformationalVersion("Optimization:1.0.1-146-g86a8cf2")]
mit
C#
ec700e91427549ff29a36ba9300a8e1aa94d2410
Remove unused using statement
ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu
osu.Game.Tests/Visual/Navigation/TestSceneEditDefaultSkin.cs
osu.Game.Tests/Visual/Navigation/TestSceneEditDefaultSkin.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.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Overlays.Settings.Sections; using osu.Game.Skinning; using osu.Game.Skinning.Editor; namespace osu.Game.Tests.Visual.Navigation { public class TestSceneEditDefaultSkin : OsuGameTestScene { private SkinManager skinManager => Game.Dependencies.Get<SkinManager>(); private SkinEditorOverlay skinEditor => Game.Dependencies.Get<SkinEditorOverlay>(); [Test] public void TestEditDefaultSkin() { AddAssert("is default skin", () => skinManager.CurrentSkinInfo.Value.ID == SkinInfo.DEFAULT_SKIN); AddStep("open settings", () => { Game.Settings.Show(); }); // Until step requires as settings has a delayed load. AddUntilStep("export button disabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == false); // Will create a mutable skin. AddStep("open skin editor", () => skinEditor.Show()); // Until step required as the skin editor may take time to load (and an extra scheduled frame for the mutable part). AddUntilStep("is modified default skin", () => skinManager.CurrentSkinInfo.Value.ID != SkinInfo.DEFAULT_SKIN); AddAssert("is not protected", () => skinManager.CurrentSkinInfo.Value.PerformRead(s => !s.Protected)); AddUntilStep("export button enabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == true); } } }
// 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.IO; using System.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Testing; using osu.Game.Overlays.Settings.Sections; using osu.Game.Skinning; using osu.Game.Skinning.Editor; namespace osu.Game.Tests.Visual.Navigation { public class TestSceneEditDefaultSkin : OsuGameTestScene { private SkinManager skinManager => Game.Dependencies.Get<SkinManager>(); private SkinEditorOverlay skinEditor => Game.Dependencies.Get<SkinEditorOverlay>(); [Test] public void TestEditDefaultSkin() { AddAssert("is default skin", () => skinManager.CurrentSkinInfo.Value.ID == SkinInfo.DEFAULT_SKIN); AddStep("open settings", () => { Game.Settings.Show(); }); // Until step requires as settings has a delayed load. AddUntilStep("export button disabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == false); // Will create a mutable skin. AddStep("open skin editor", () => skinEditor.Show()); // Until step required as the skin editor may take time to load (and an extra scheduled frame for the mutable part). AddUntilStep("is modified default skin", () => skinManager.CurrentSkinInfo.Value.ID != SkinInfo.DEFAULT_SKIN); AddAssert("is not protected", () => skinManager.CurrentSkinInfo.Value.PerformRead(s => !s.Protected)); AddUntilStep("export button enabled", () => Game.Settings.ChildrenOfType<SkinSection.ExportSkinButton>().SingleOrDefault()?.Enabled.Value == true); } } }
mit
C#
400ed7081447d7f5566a3acd8b28446c62487c4e
Bump copyright year
Dagwaging/log4net,amtkmrsmn/log4net,Dagwaging/log4net,StevenJiang2015/log4net,harold4/log4net,drunkirishcoder/monotouch-log4net,drunkirishcoder/monotouch-log4net,modulexcite/log4net,modulexcite/log4net,harold4/log4net,amtkmrsmn/log4net,amtkmrsmn/log4net,StevenJiang2015/log4net,harold4/log4net,Dagwaging/log4net,drunkirishcoder/monotouch-log4net,StevenJiang2015/log4net,drunkirishcoder/monotouch-log4net,modulexcite/log4net
src/AssemblyVersionInfo.cs
src/AssemblyVersionInfo.cs
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: System.Reflection.AssemblyVersion("1.2.11.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.2")] #if !NETCF #if !SSCLI [assembly: System.Reflection.AssemblyFileVersion("1.2.11.0")] #endif #endif // // Shared assembly settings // [assembly: System.Reflection.AssemblyCompany("The Apache Software Foundation")] [assembly: System.Reflection.AssemblyCopyright("Copyright 2004-2013 The Apache Software Foundation.")] [assembly: System.Reflection.AssemblyTrademark("Apache and Apache log4net are trademarks of The Apache Software Foundation")]
#region Apache License // // Licensed to the Apache Software Foundation (ASF) under one or more // contributor license agreements. See the NOTICE file distributed with // this work for additional information regarding copyright ownership. // The ASF licenses this file to you under the Apache License, Version 2.0 // (the "License"); you may not use this file except in compliance with // the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion // // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: System.Reflection.AssemblyVersion("1.2.11.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.2")] #if !NETCF #if !SSCLI [assembly: System.Reflection.AssemblyFileVersion("1.2.11.0")] #endif #endif // // Shared assembly settings // [assembly: System.Reflection.AssemblyCompany("The Apache Software Foundation")] [assembly: System.Reflection.AssemblyCopyright("Copyright 2004-2011 The Apache Software Foundation.")] [assembly: System.Reflection.AssemblyTrademark("Apache and Apache log4net are trademarks of The Apache Software Foundation")]
apache-2.0
C#
e4ed477acbb62b3d7591ec0f069d8b83339d9ef3
Fix off by one error in DFSStateScheduler.GetNumberOfStates()
symbooglix/symbooglix,symbooglix/symbooglix,symbooglix/symbooglix
src/Symbooglix/Executor/StateSchedulers/DFSStateScheduler.cs
src/Symbooglix/Executor/StateSchedulers/DFSStateScheduler.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace Symbooglix { public class DFSStateScheduler : IStateScheduler { private List<ExecutionState> States; private ExecutionState Popped; public DFSStateScheduler() { States = new List<ExecutionState>(); Popped = null; } public ExecutionState GetNextState() { if (Popped != null) return Popped; if (States.Count == 0) return null; if (Popped == null) { Popped = States[States.Count - 1]; States.RemoveAt(States.Count - 1); } return Popped; } public int GetNumberOfStates() { return States.Count + ((Popped != null)?1:0) ;} public void AddState(ExecutionState toAdd) { Debug.Assert(!States.Contains(toAdd), "ExecutionStates already in the scheduler should not be added again"); States.Add(toAdd); } public void RemoveState(ExecutionState toRemove) { // Fast path: Remove state that was being Executed if (toRemove == Popped) { Popped = null; return; } Debug.Assert(States.Contains(toRemove), "Cannot remove state not stored in the state scheduler"); States.Remove(toRemove); } public void RemoveAll(Predicate<ExecutionState> p) { States.RemoveAll(p); } public void ReceiveExecutor(Executor executor) { // Not needed } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Symbooglix { public class DFSStateScheduler : IStateScheduler { private List<ExecutionState> States; private ExecutionState Popped; public DFSStateScheduler() { States = new List<ExecutionState>(); Popped = null; } public ExecutionState GetNextState() { if (Popped != null) return Popped; if (States.Count == 0) return null; if (Popped == null) { Popped = States[States.Count - 1]; States.RemoveAt(States.Count - 1); } return Popped; } public int GetNumberOfStates() { return States.Count;} public void AddState(ExecutionState toAdd) { Debug.Assert(!States.Contains(toAdd), "ExecutionStates already in the scheduler should not be added again"); States.Add(toAdd); } public void RemoveState(ExecutionState toRemove) { // Fast path: Remove state that was being Executed if (toRemove == Popped) { Popped = null; return; } Debug.Assert(States.Contains(toRemove), "Cannot remove state not stored in the state scheduler"); States.Remove(toRemove); } public void RemoveAll(Predicate<ExecutionState> p) { States.RemoveAll(p); } public void ReceiveExecutor(Executor executor) { // Not needed } } }
bsd-2-clause
C#
3bbe6893be2ffa6ff19839eadfbbc74ad9b95203
Fix assert hit during OnInstantiated validation
modesttree/Zenject,modesttree/Zenject,modesttree/Zenject
UnityProject/Assets/Plugins/Zenject/Source/Binding/Binders/InstantiateCallbackConditionCopyNonLazyBinder.cs
UnityProject/Assets/Plugins/Zenject/Source/Binding/Binders/InstantiateCallbackConditionCopyNonLazyBinder.cs
using System; using ModestTree; namespace Zenject { [NoReflectionBaking] public class InstantiateCallbackConditionCopyNonLazyBinder : ConditionCopyNonLazyBinder { public InstantiateCallbackConditionCopyNonLazyBinder(BindInfo bindInfo) : base(bindInfo) { } public ConditionCopyNonLazyBinder OnInstantiated( Action<InjectContext, object> callback) { BindInfo.InstantiatedCallback = callback; return this; } public ConditionCopyNonLazyBinder OnInstantiated<T>( Action<InjectContext, T> callback) { // Can't do this here because of factory bindings //Assert.That(BindInfo.ContractTypes.All(x => x.DerivesFromOrEqual<T>())); BindInfo.InstantiatedCallback = (ctx, obj) => { if (obj is ValidationMarker) { Assert.That(ctx.Container.IsValidating); ValidationMarker marker = obj as ValidationMarker; Assert.That(marker.MarkedType.DerivesFromOrEqual<T>(), "Invalid generic argument to OnInstantiated! {0} must be type {1}", marker.MarkedType, typeof(T)); } else { Assert.That(obj == null || obj is T, "Invalid generic argument to OnInstantiated! {0} must be type {1}", obj.GetType(), typeof(T)); callback(ctx, (T)obj); } }; return this; } } }
using System; using ModestTree; namespace Zenject { [NoReflectionBaking] public class InstantiateCallbackConditionCopyNonLazyBinder : ConditionCopyNonLazyBinder { public InstantiateCallbackConditionCopyNonLazyBinder(BindInfo bindInfo) : base(bindInfo) { } public ConditionCopyNonLazyBinder OnInstantiated( Action<InjectContext, object> callback) { BindInfo.InstantiatedCallback = callback; return this; } public ConditionCopyNonLazyBinder OnInstantiated<T>( Action<InjectContext, T> callback) { // Can't do this here because of factory bindings //Assert.That(BindInfo.ContractTypes.All(x => x.DerivesFromOrEqual<T>())); BindInfo.InstantiatedCallback = (ctx, obj) => { Assert.That(obj == null || obj is T, "Invalid generic argument to OnInstantiated! {0} must be type {1}", obj.GetType(), typeof(T)); callback(ctx, (T)obj); }; return this; } } }
mit
C#
97367448432b48058ae74baf21776555d0e389d1
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.9.6")] [assembly: AssemblyInformationalVersion("0.9.6")] /* * Version 0.9.6 * * Excludes Experiment.AutoFixture.dll from the nuget package, but instead, * the features were implemented directly in the published source codes. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.9.5")] [assembly: AssemblyInformationalVersion("0.9.5")] /* * Version 0.9.5 * * Changes the accessibility of CreateTestFixture from public to protected. * * BREAKING CHANGE * - the member of BaseTheoremAttribute, * BaseFirstClassTheoremAttribute, * AutoFixtureTheoremAttribute, * AutoFixtureFirstClassTheoremAttribute * * public ITestFixture CreateTestFixture(MethodInfo) -> * protected ITestFixture CreateTestFixture(MethodInfo) */
mit
C#
c56d69be7da45c38362d2dc58de552f868f9e20c
Add comments.
miyabi/unity-replay-kit-bridge
Example/Assets/UIController.cs
Example/Assets/UIController.cs
using UnityEngine; using System.Collections; public class UIController : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnPressStartRecordingButton() { if (!ReplayKitBridge.IsScreenRecorderAvailable || ReplayKitBridge.IsRecording) { return; } ReplayKitBridge.onStartRecordingCallback = OnStartRecording; ReplayKitBridge.onDiscardRecordingCallback = OnDiscardRecording; ReplayKitBridge.onStopRecordingCallback = OnStopRecording; ReplayKitBridge.onFinishPreviewCallback = OnFinishPreview; // Enable camera and microphone ReplayKitBridge.IsCameraEnabled = true; ReplayKitBridge.IsMicrophoneEnabled = true; // And then start recording ReplayKitBridge.StartRecording(); } public void OnPressDiscardRecordingButton() { if (!ReplayKitBridge.IsRecording) { return; } // Disable camera and microphone ReplayKitBridge.IsCameraEnabled = false; ReplayKitBridge.IsMicrophoneEnabled = false; // Discard recording ReplayKitBridge.DiscardRecording(); } public void OnPressStopRecordingButton() { if (!ReplayKitBridge.IsRecording) { return; } // Disable camera and microphone ReplayKitBridge.IsCameraEnabled = false; ReplayKitBridge.IsMicrophoneEnabled = false; // Stop recording ReplayKitBridge.StopRecording(); } public void OnStartRecording() { Debug.Log("OnStartRecording"); } public void OnDiscardRecording() { Debug.Log("OnDiscardRecording"); } public void OnStopRecording() { Debug.Log("OnStopRecording"); Time.timeScale = 0; ReplayKitBridge.PresentPreviewViewController(); } public void OnFinishPreview(string activityType) { Debug.Log("OnFinishPreview activityType=" + activityType); ReplayKitBridge.DismissPreviewViewController(); Time.timeScale = 1; } }
using UnityEngine; using System.Collections; public class UIController : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnPressStartRecordingButton() { if (!ReplayKitBridge.IsScreenRecorderAvailable || ReplayKitBridge.IsRecording) { return; } ReplayKitBridge.onStartRecordingCallback = OnStartRecording; ReplayKitBridge.onDiscardRecordingCallback = OnDiscardRecording; ReplayKitBridge.onStopRecordingCallback = OnStopRecording; ReplayKitBridge.onFinishPreviewCallback = OnFinishPreview; ReplayKitBridge.IsCameraEnabled = true; ReplayKitBridge.IsMicrophoneEnabled = true; ReplayKitBridge.StartRecording(); } public void OnPressDiscardRecordingButton() { if (!ReplayKitBridge.IsRecording) { return; } ReplayKitBridge.IsCameraEnabled = false; ReplayKitBridge.IsMicrophoneEnabled = false; ReplayKitBridge.DiscardRecording(); } public void OnPressStopRecordingButton() { if (!ReplayKitBridge.IsRecording) { return; } ReplayKitBridge.IsCameraEnabled = false; ReplayKitBridge.IsMicrophoneEnabled = false; ReplayKitBridge.StopRecording(); } public void OnStartRecording() { Debug.Log("OnStartRecording"); } public void OnDiscardRecording() { Debug.Log("OnDiscardRecording"); } public void OnStopRecording() { Debug.Log("OnStopRecording"); Time.timeScale = 0; ReplayKitBridge.PresentPreviewViewController(); } public void OnFinishPreview(string activityType) { Debug.Log("OnFinishPreview activityType=" + activityType); ReplayKitBridge.DismissPreviewViewController(); Time.timeScale = 1; } }
mit
C#
cbdba401df5864644a6f2c70a82f7cf6930ce31a
change assembly version to 1.1
yixiangling/toxy,yixiangling/toxy,tonyqus/toxy
ToxyFramework/Properties/AssemblyInfo.cs
ToxyFramework/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("Toxy Framework")] [assembly: AssemblyDescription(".Net Data/Text Extraction Framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Neuzilla")] [assembly: AssemblyProduct("Toxy")] [assembly: AssemblyCopyright("Apache 2.0")] [assembly: AssemblyTrademark("Neuzilla")] [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("3c5f41de-9f62-45cc-b89e-8e377a2e036e")] // 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")] [assembly: AssemblyInformationalVersion("Toxy 1.0")] [assembly: AllowPartiallyTrustedCallers]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; // 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("Toxy Framework")] [assembly: AssemblyDescription(".Net Data/Text Extraction Framework")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Neuzilla")] [assembly: AssemblyProduct("Toxy")] [assembly: AssemblyCopyright("Apache 2.0")] [assembly: AssemblyTrademark("Neuzilla")] [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("3c5f41de-9f62-45cc-b89e-8e377a2e036e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("Toxy 1.0")] [assembly: AllowPartiallyTrustedCallers]
apache-2.0
C#
a0c91000b26b0c21eeb54fb4e28175bfae910740
Update BinanceTransferHistory.cs (#644)
JKorf/Binance.Net
Binance.Net/Objects/Spot/MarginData/BinanceTransferHistory.cs
Binance.Net/Objects/Spot/MarginData/BinanceTransferHistory.cs
using System; using Binance.Net.Converters; using Binance.Net.Enums; using CryptoExchange.Net.Converters; using Newtonsoft.Json; namespace Binance.Net.Objects.Spot.MarginData { /// <summary> /// Transfer history entry /// </summary> public class BinanceTransferHistory { /// <summary> /// Amount of the transfer /// </summary> public decimal Amount { get; set; } /// <summary> /// Asset of the transfer /// </summary> public string Asset { get; set; } = ""; /// <summary> /// Status of the transfer /// </summary> public string Status { get; set; } = ""; /// <summary> /// Timestamp of the transaction /// </summary> [JsonConverter(typeof(TimestampConverter))] public DateTime Timestamp { get; set; } /// <summary> /// Transaction id /// </summary> [JsonProperty("txId")] public decimal TransactionId { get; set; } /// <summary> /// Direction of the transfer /// </summary> [JsonProperty("type"), JsonConverter(typeof(TransferDirectionConverter))] public TransferDirection Direction { get; set; } } }
using System; using Binance.Net.Converters; using Binance.Net.Enums; using CryptoExchange.Net.Converters; using Newtonsoft.Json; namespace Binance.Net.Objects.Spot.MarginData { /// <summary> /// Transfer history entry /// </summary> public class BinanceTransferHistory { /// <summary> /// Amount of the transfer /// </summary> public decimal Amount { get; set; } /// <summary> /// Asset of the transfer /// </summary> public decimal Asset { get; set; } /// <summary> /// Status of the transfer /// </summary> public string Status { get; set; } = ""; /// <summary> /// Timestamp of the transaction /// </summary> [JsonConverter(typeof(TimestampConverter))] public DateTime Timestamp { get; set; } /// <summary> /// Transaction id /// </summary> [JsonProperty("txId")] public decimal TransactionId { get; set; } /// <summary> /// Direction of the transfer /// </summary> [JsonProperty("type"), JsonConverter(typeof(TransferDirectionConverter))] public TransferDirection Direction { get; set; } } }
mit
C#
d6e49b94ececed3b176f312ef98f55b0f44c277f
Add comment.
NeoAdonis/osu,naoey/osu,EVAST9919/osu,DrabWeb/osu,UselessToucan/osu,EVAST9919/osu,Frontear/osuKyzer,peppy/osu,2yangk23/osu,DrabWeb/osu,2yangk23/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu,ZLima12/osu,naoey/osu,osu-RP/osu-RP,Nabile-Rahmani/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,DrabWeb/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,Damnae/osu,peppy/osu-new,Drezi126/osu,naoey/osu
osu.Game.Rulesets.Mania/Timing/Drawables/DrawableManiaTimingChange.cs
osu.Game.Rulesets.Mania/Timing/Drawables/DrawableManiaTimingChange.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; namespace osu.Game.Rulesets.Mania.Timing.Drawables { public class DrawableManiaTimingChange : DrawableTimingChange { public DrawableManiaTimingChange(TimingChange timingChange) : base(timingChange, Axes.Y) { } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); var parent = Parent as IHasTimeSpan; if (parent == null) return; // This is very naive and can be improved, but is adequate for now LifetimeStart = TimingChange.Time - parent.TimeSpan.Y; LifetimeEnd = TimingChange.Time + Content.RelativeCoordinateSpace.Y * 2; } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; namespace osu.Game.Rulesets.Mania.Timing.Drawables { public class DrawableManiaTimingChange : DrawableTimingChange { public DrawableManiaTimingChange(TimingChange timingChange) : base(timingChange, Axes.Y) { } protected override void UpdateAfterChildren() { base.UpdateAfterChildren(); var parent = Parent as IHasTimeSpan; if (parent == null) return; LifetimeStart = TimingChange.Time - parent.TimeSpan.Y; LifetimeEnd = TimingChange.Time + Content.RelativeCoordinateSpace.Y * 2; } } }
mit
C#
ce01a593d30a2e69301d3fd63492a3d5804f25a5
Remove a redundant UpdateLayout invocation
DotNetKit/DotNetKit.Wpf.Printing
DotNetKit.Wpf.Printing/Windows/Documents/FixedDocumentCreator.cs
DotNetKit.Wpf.Printing/Windows/Documents/FixedDocumentCreator.cs
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace DotNetKit.Windows.Documents { /// <summary> /// Provides functions. /// </summary> public struct FixedDocumentCreator { /// <summary> /// Converts data contexts to a <see cref="FixedDocument"/>. /// </summary> public FixedDocument FromDataContexts(IEnumerable contents, Size pageSize) { var isLandscape = pageSize.Width > pageSize.Height; var mediaSize = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize; var document = new FixedDocument(); foreach (var content in contents) { var presenter = new ContentPresenter() { Content = content, Width = pageSize.Width, Height = pageSize.Height, }; if (isLandscape) { presenter.LayoutTransform = new RotateTransform(90.0); } var page = new FixedPage() { Width = mediaSize.Width, Height = mediaSize.Height, }; page.Children.Add(presenter); var pageContent = new PageContent() { Child = page }; document.Pages.Add(pageContent); } return document; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace DotNetKit.Windows.Documents { /// <summary> /// Provides functions. /// </summary> public struct FixedDocumentCreator { /// <summary> /// Converts data contexts to a <see cref="FixedDocument"/>. /// </summary> public FixedDocument FromDataContexts(IEnumerable contents, Size pageSize) { var isLandscape = pageSize.Width > pageSize.Height; var mediaSize = isLandscape ? new Size(pageSize.Height, pageSize.Width) : pageSize; var document = new FixedDocument(); foreach (var content in contents) { var presenter = new ContentPresenter() { Content = content, Width = pageSize.Width, Height = pageSize.Height, }; if (isLandscape) { presenter.LayoutTransform = new RotateTransform(90.0); } var page = new FixedPage() { Width = mediaSize.Width, Height = mediaSize.Height, }; page.Children.Add(presenter); page.Measure(mediaSize); page.Arrange(new Rect(new Point(0, 0), mediaSize)); page.UpdateLayout(); var pageContent = new PageContent() { Child = page }; document.Pages.Add(pageContent); } return document; } } }
mit
C#