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
869136b2fb25277c28ba6919ed4878db1a85da72
Fix possible cross-thread config cache access (#4730)
smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ZLima12/osu,ppy/osu,EVAST9919/osu,johnneijzen/osu,EVAST9919/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,peppy/osu,ZLima12/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,johnneijzen/osu,smoogipoo/osu,2yangk23/osu,ppy/osu
osu.Game/Rulesets/RulesetConfigCache.cs
osu.Game/Rulesets/RulesetConfigCache.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Concurrent; using osu.Framework.Graphics; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; namespace osu.Game.Rulesets { /// <summary> /// A cache that provides a single <see cref="IRulesetConfigManager"/> per-ruleset. /// This is done to support referring to and updating ruleset configs from multiple locations in the absence of inter-config bindings. /// </summary> public class RulesetConfigCache : Component { private readonly ConcurrentDictionary<int, IRulesetConfigManager> configCache = new ConcurrentDictionary<int, IRulesetConfigManager>(); private readonly SettingsStore settingsStore; public RulesetConfigCache(SettingsStore settingsStore) { this.settingsStore = settingsStore; } /// <summary> /// Retrieves the <see cref="IRulesetConfigManager"/> for a <see cref="Ruleset"/>. /// </summary> /// <param name="ruleset">The <see cref="Ruleset"/> to retrieve the <see cref="IRulesetConfigManager"/> for.</param> /// <returns>The <see cref="IRulesetConfigManager"/> defined by <paramref name="ruleset"/>, null if <paramref name="ruleset"/> doesn't define one.</returns> /// <exception cref="InvalidOperationException">If <paramref name="ruleset"/> doesn't have a valid <see cref="RulesetInfo.ID"/>.</exception> public IRulesetConfigManager GetConfigFor(Ruleset ruleset) { if (ruleset.RulesetInfo.ID == null) throw new InvalidOperationException("The provided ruleset doesn't have a valid id."); return configCache.GetOrAdd(ruleset.RulesetInfo.ID.Value, _ => ruleset.CreateConfig(settingsStore)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; namespace osu.Game.Rulesets { /// <summary> /// A cache that provides a single <see cref="IRulesetConfigManager"/> per-ruleset. /// This is done to support referring to and updating ruleset configs from multiple locations in the absence of inter-config bindings. /// </summary> public class RulesetConfigCache : Component { private readonly Dictionary<int, IRulesetConfigManager> configCache = new Dictionary<int, IRulesetConfigManager>(); private readonly SettingsStore settingsStore; public RulesetConfigCache(SettingsStore settingsStore) { this.settingsStore = settingsStore; } /// <summary> /// Retrieves the <see cref="IRulesetConfigManager"/> for a <see cref="Ruleset"/>. /// </summary> /// <param name="ruleset">The <see cref="Ruleset"/> to retrieve the <see cref="IRulesetConfigManager"/> for.</param> /// <returns>The <see cref="IRulesetConfigManager"/> defined by <paramref name="ruleset"/>, null if <paramref name="ruleset"/> doesn't define one.</returns> /// <exception cref="InvalidOperationException">If <paramref name="ruleset"/> doesn't have a valid <see cref="RulesetInfo.ID"/>.</exception> public IRulesetConfigManager GetConfigFor(Ruleset ruleset) { if (ruleset.RulesetInfo.ID == null) throw new InvalidOperationException("The provided ruleset doesn't have a valid id."); if (configCache.TryGetValue(ruleset.RulesetInfo.ID.Value, out var existing)) return existing; return configCache[ruleset.RulesetInfo.ID.Value] = ruleset.CreateConfig(settingsStore); } } }
mit
C#
b447880f40c9f9a26b53c6e0e49316a7fd79f0f4
Install using the "LocalService" user account by default.
highlyunavailable/ncron,schourode/ncron
load/ProjectInstaller.cs
load/ProjectInstaller.cs
// Copyright (c) 2007-2008, Joern Schou-Rode <jsr@malamute.dk> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the NCron nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. using System; using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; namespace NCron.Loader { [RunInstaller(true)] public class ProjectInstaller : Installer { public ProjectInstaller() { ServiceProcessInstaller procInst = new ServiceProcessInstaller(); procInst.Account = ServiceAccount.LocalService; base.Installers.Add(procInst); ServiceInstaller svcInst = new ServiceInstaller(); svcInst.ServiceName = "ncron"; svcInst.DisplayName = "NCron task scheduling"; svcInst.Description = "Executes task according to the configured NCron schedule."; svcInst.StartType = ServiceStartMode.Automatic; base.Installers.Add(svcInst); } } }
// Copyright (c) 2007-2008, Joern Schou-Rode <jsr@malamute.dk> // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of the NCron nor the names of its contributors may // be used to endorse or promote products derived from this software // without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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. using System; using System.ComponentModel; using System.Configuration.Install; using System.ServiceProcess; namespace NCron.Loader { [RunInstaller(true)] public class ProjectInstaller : Installer { public ProjectInstaller() { ServiceProcessInstaller procInst = new ServiceProcessInstaller(); procInst.Account = ServiceAccount.NetworkService; base.Installers.Add(procInst); ServiceInstaller svcInst = new ServiceInstaller(); svcInst.ServiceName = "ncron"; svcInst.DisplayName = "NCron task scheduling"; svcInst.Description = "Executes task according to the configured NCron schedule."; svcInst.StartType = ServiceStartMode.Automatic; base.Installers.Add(svcInst); } } }
apache-2.0
C#
44a156f18c593908277c9b6f7426c3ef0c6e2349
Bump 3.4.0
criteo/RabbitMQHare
RabbitMQHare/Properties/AssemblyInfo.cs
RabbitMQHare/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RabbitMQHare")] [assembly: AssemblyDescription("Simple wrapper around rabbit official client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Criteo")] [assembly: AssemblyProduct("RabbitMQHare")] [assembly: AssemblyCopyright("Copyright © Criteo 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("058763b1-7003-4abe-86f7-e7f58334b2c7")] // 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(Info.Version)] [assembly: AssemblyFileVersion(Info.Version)] [assembly: AssemblyInformationalVersion(Info.Version)] public static class Info { public const string Version = "3.4.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("RabbitMQHare")] [assembly: AssemblyDescription("Simple wrapper around rabbit official client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Criteo")] [assembly: AssemblyProduct("RabbitMQHare")] [assembly: AssemblyCopyright("Copyright © Criteo 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("058763b1-7003-4abe-86f7-e7f58334b2c7")] // 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(Info.Version)] [assembly: AssemblyFileVersion(Info.Version)] [assembly: AssemblyInformationalVersion(Info.Version)] public static class Info { public const string Version = "3.3.0"; }
apache-2.0
C#
d330b39db492a8b85b79a93e5ed1d6018db0b1bb
Remove max
smoogipooo/osu,ZLima12/osu,DrabWeb/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,johnneijzen/osu,Nabile-Rahmani/osu,naoey/osu,ppy/osu,Frontear/osuKyzer,NeoAdonis/osu,2yangk23/osu,Drezi126/osu,ppy/osu,EVAST9919/osu,2yangk23/osu,naoey/osu,smoogipoo/osu,DrabWeb/osu,naoey/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,johnneijzen/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu
osu.Game/Screens/Play/SongProgressGraph.cs
osu.Game/Screens/Play/SongProgressGraph.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 System.Linq; using System.Collections.Generic; using System.Diagnostics; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Screens.Play { public class SongProgressGraph : SquareGraph { private IEnumerable<HitObject> objects; public IEnumerable<HitObject> Objects { set { objects = value; const int granularity = 200; Values = new int[granularity]; if (!objects.Any()) return; var firstHit = objects.First().StartTime; var lastHit = objects.Max(o => (o as IHasEndTime)?.EndTime ?? o.StartTime); if (lastHit == 0) lastHit = objects.Last().StartTime; var interval = (lastHit - firstHit + 1) / granularity; foreach (var h in objects) { var endTime = (h as IHasEndTime)?.EndTime ?? h.StartTime; Debug.Assert(endTime >= h.StartTime); int startRange = (int)((h.StartTime - firstHit) / interval); int endRange = (int)((endTime - firstHit) / interval); for (int i = startRange; i <= endRange; i++) Values[i]++; } } } } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Objects; namespace osu.Game.Screens.Play { public class SongProgressGraph : SquareGraph { private IEnumerable<HitObject> objects; public IEnumerable<HitObject> Objects { set { objects = value; const int granularity = 200; Values = new int[granularity]; if (!objects.Any()) return; var firstHit = objects.First().StartTime; var lastHit = objects.Max(o => (o as IHasEndTime)?.EndTime ?? o.StartTime); if (lastHit == 0) lastHit = objects.Last().StartTime; var interval = (lastHit - firstHit + 1) / granularity; foreach (var h in objects) { var endTime = Math.Max((h as IHasEndTime)?.EndTime ?? h.StartTime, h.StartTime); Debug.Assert(endTime >= h.StartTime); int startRange = (int)((h.StartTime - firstHit) / interval); int endRange = (int)((endTime - firstHit) / interval); for (int i = startRange; i <= endRange; i++) Values[i]++; } } } } }
mit
C#
b76dc8150d63547991802da35dd7ed5698c7e8f9
Use non-aggressive comparison for J2N collections
jeme/lucenenet,jeme/lucenenet,apache/lucenenet,sisve/lucenenet,NightOwl888/lucenenet,apache/lucenenet,apache/lucenenet,jeme/lucenenet,NightOwl888/lucenenet,apache/lucenenet,NightOwl888/lucenenet,jeme/lucenenet,NightOwl888/lucenenet,sisve/lucenenet
src/Lucene.Net.Tests/Util/TestIdentityHashSet.cs
src/Lucene.Net.Tests/Util/TestIdentityHashSet.cs
using J2N.Runtime.CompilerServices; using NUnit.Framework; using System; using System.Collections.Generic; using JCG = J2N.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; using System.Diagnostics.CodeAnalysis; namespace Lucene.Net.Util { /* * 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. */ [TestFixture] public class TestIdentityHashSet : LuceneTestCase { [Test] public virtual void TestCheck() { Random rnd = Random; ISet<object> jdk = new JCG.HashSet<object>(IdentityEqualityComparer<object>.Default); RamUsageEstimator.IdentityHashSet<object> us = new RamUsageEstimator.IdentityHashSet<object>(); int max = 100000; int threshold = 256; for (int i = 0; i < max; i++) { // some of these will be interned and some will not so there will be collisions. int v = rnd.Next(threshold); bool e1 = jdk.Contains(v); bool e2 = us.Contains(v); Assert.AreEqual(e1, e2); e1 = jdk.Add(v); e2 = us.Add(v); Assert.AreEqual(e1, e2); } ISet<object> collected = new JCG.HashSet<object>(IdentityEqualityComparer<object>.Default); foreach (var o in us) { collected.Add(o); } // LUCENENET: We have 2 J2N hashsets, so no need to use aggressive mode assertEquals(collected, jdk, aggressive: false); } } }
using J2N.Runtime.CompilerServices; using NUnit.Framework; using System; using System.Collections.Generic; using JCG = J2N.Collections.Generic; using Assert = Lucene.Net.TestFramework.Assert; namespace Lucene.Net.Util { /* * 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. */ [TestFixture] public class TestIdentityHashSet : LuceneTestCase { [Test] public virtual void TestCheck() { Random rnd = Random; ISet<object> jdk = new JCG.HashSet<object>(IdentityEqualityComparer<object>.Default); RamUsageEstimator.IdentityHashSet<object> us = new RamUsageEstimator.IdentityHashSet<object>(); int max = 100000; int threshold = 256; for (int i = 0; i < max; i++) { // some of these will be interned and some will not so there will be collisions. int? v = rnd.Next(threshold); bool e1 = jdk.Contains(v); bool e2 = us.Contains(v); Assert.AreEqual(e1, e2); e1 = jdk.Add(v); e2 = us.Add(v); Assert.AreEqual(e1, e2); } ISet<object> collected = new JCG.HashSet<object>(IdentityEqualityComparer<object>.Default); foreach (object o in us) { collected.Add(o); } assertEquals(collected, jdk); } } }
apache-2.0
C#
13dcb74d6732b99adc5b7bcb0b7c964490c5e7a5
tidy only
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.PAS.ContractAgreements.WebJob/Program.cs
src/SFA.DAS.PAS.ContractAgreements.WebJob/Program.cs
using System; using System.Diagnostics; using SFA.DAS.NLog.Logger; using SFA.DAS.PAS.ContractAgreements.WebJob.DependencyResolution; namespace SFA.DAS.PAS.ContractAgreements.WebJob { // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976 class Program { static void Main() { try { var container = IoC.Initialize(); var logger = container.GetInstance<ILog>(); logger.Info("ContractAgreements job started"); var timer = Stopwatch.StartNew(); var service = container.GetInstance<ProviderAgreementStatusService>(); service.UpdateProviderAgreementStatuses().Wait(); timer.Stop(); logger.Info($"ContractAgreements job done, Took: {timer.ElapsedMilliseconds} milliseconds"); } catch (Exception ex) { ILog exLogger = new NLogLogger(); exLogger.Error(ex, "Error running ContractAgreements WebJob"); } } } }
using System; using System.Diagnostics; using SFA.DAS.NLog.Logger; using SFA.DAS.PAS.ContractAgreements.WebJob.DependencyResolution; namespace SFA.DAS.PAS.ContractAgreements.WebJob { // To learn more about Microsoft Azure WebJobs SDK, please see http://go.microsoft.com/fwlink/?LinkID=320976 class Program { // Please set the following connection strings in app.config for this WebJob to run: // AzureWebJobsDashboard and AzureWebJobsStorage static void Main() { // The following code ensures that the WebJob will be running continuously //var host = new JobHost(); //host.RunAndBlock(); try { var container = IoC.Initialize(); var logger = container.GetInstance<ILog>(); logger.Info("ContractAgreements job started"); var timer = Stopwatch.StartNew(); var service = container.GetInstance<ProviderAgreementStatusService>(); service.UpdateProviderAgreementStatuses().Wait(); timer.Stop(); logger.Info($"ContractAgreements job done, Took: {timer.ElapsedMilliseconds} milliseconds"); } catch (Exception ex) { ILog exLogger = new NLogLogger(); exLogger.Error(ex, "Error running ContractAgreements WebJob"); } } } }
mit
C#
79b19b879fa88612d5cd15db9a75b7f01afc759a
fix #335
AerysBat/slimCat,WreckedAvent/slimCat
slimCat/Commands/Character/LogInCommand.cs
slimCat/Commands/Character/LogInCommand.cs
#region Copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="LogInCommand.cs"> // Copyright (c) 2013, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace slimCat.Models { #region Usings using Services; using Utilities; #endregion /// <summary> /// The login state changed event args. /// </summary> public class LoginStateChangedEventArgs : CharacterUpdateEventArgs { public bool IsLogIn { get; set; } public override string ToString() { return "has logged " + (IsLogIn ? "in." : "out."); } public override void DisplayNewToast(IChatState chatState, IManageToasts toastsManager) { if (!ApplicationSettings.ShowLoginToasts || !chatState.IsInteresting(Model.TargetCharacter.Name) || chatState.CharacterManager.IsOnList(Model.TargetCharacter.Name, ListKind.IgnoreUpdates, false)) { return; } DoNormalToast(toastsManager); } } } namespace slimCat.Services { #region Usings using System.Collections.Generic; using Models; using Utilities; #endregion public partial class ServerCommandService { private void UserLoggedInCommand(IDictionary<string, object> command) { var character = command.Get(Constants.Arguments.Identity); var temp = new CharacterModel { Name = character, Gender = ParseGender(command.Get(Constants.Arguments.Gender)), Status = command.Get(Constants.Arguments.Status).ToEnum<StatusType>() }; CharacterManager.SignOn(temp); Events.GetEvent<NewUpdateEvent>() .Publish( new CharacterUpdateModel( temp, new LoginStateChangedEventArgs {IsLogIn = true})); } } }
#region Copyright // -------------------------------------------------------------------------------------------------------------------- // <copyright file="LogInCommand.cs"> // Copyright (c) 2013, Justin Kadrovach, All rights reserved. // // This source is subject to the Simplified BSD License. // Please see the License.txt file for more information. // All other rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #endregion namespace slimCat.Models { #region Usings using Services; using Utilities; #endregion /// <summary> /// The login state changed event args. /// </summary> public class LoginStateChangedEventArgs : CharacterUpdateEventArgs { public bool IsLogIn { get; set; } public override string ToString() { return "has logged " + (IsLogIn ? "in." : "out."); } public override void DisplayNewToast(IChatState chatState, IManageToasts toastsManager) { if (!ApplicationSettings.ShowLoginToasts || !chatState.IsInteresting(Model.TargetCharacter.Name)) { return; } DoNormalToast(toastsManager); } } } namespace slimCat.Services { #region Usings using System.Collections.Generic; using Models; using Utilities; #endregion public partial class ServerCommandService { private void UserLoggedInCommand(IDictionary<string, object> command) { var character = command.Get(Constants.Arguments.Identity); var temp = new CharacterModel { Name = character, Gender = ParseGender(command.Get(Constants.Arguments.Gender)), Status = command.Get(Constants.Arguments.Status).ToEnum<StatusType>() }; CharacterManager.SignOn(temp); Events.GetEvent<NewUpdateEvent>() .Publish( new CharacterUpdateModel( temp, new LoginStateChangedEventArgs {IsLogIn = true})); } } }
bsd-2-clause
C#
9626e562b3ce9ce5fcd6f57dbbfdc4f066413ee2
Cut down 4 loc
akashkrishnan/CERN-Application-2014
CERN-Application-2014/Program.cs
CERN-Application-2014/Program.cs
using System; using System.Linq; using System.Numerics; namespace CERN_Application_2014 { class Program { static void Main(string[] args) { Console.WriteLine(SumOfPrimes(4000000, 5000000)); Console.WriteLine(SumOfDigits(BigInteger.Pow(2, 3502))); Console.ReadKey(false); } private static BigInteger SumOfPrimes(int min, int max) { BigInteger sum = 0; for (int n = min; n < max; n++) if (IsPrime(n)) sum += n; return sum; } private static bool IsPrime(int n) { if (n == 1 || (n > 2 && n % 2 == 0)) return false; for (int i = 3; i * i <= n; i += 2) if (n % i == 0) return false; return true; } private static int SumOfDigits(BigInteger n) { int sum = 0; for (; n > 0; sum += (int)(n % 10), n /= 10) ; return sum; } } }
using System; using System.Linq; using System.Numerics; namespace CERN_Application_2014 { class Program { static void Main(string[] args) { Console.WriteLine(SumOfPrimes(4000000, 5000000)); Console.WriteLine(SumOfDigits(BigInteger.Pow(2, 3502))); Console.ReadKey(false); } private static BigInteger SumOfPrimes(int min, int max) { BigInteger sum = 0; for (int n = min; n < max; n++) if (IsPrime(n)) sum += n; return sum; } private static bool IsPrime(int n) { if (n == 1 || (n > 2 && n % 2 == 0)) return false; for (int i = 3; i * i <= n; i += 2) if (n % i == 0) return false; return true; } private static int SumOfDigits(BigInteger n) { int sum = 0; while (n > 0) { sum += (int)(n % 10); n /= 10; } return sum; } } }
mit
C#
32f56c8ca8c3f4d472aba252ecbdba1d41d48a54
refactor Main to follow core 2.0 recommended pattern
alimon808/contoso-university,alimon808/contoso-university,alimon808/contoso-university
ContosoUniversity.Web/Program.cs
ContosoUniversity.Web/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; namespace ContosoUniversity { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace ContosoUniversity { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() //.UseApplicationInsights() .Build(); host.Run(); } } }
mit
C#
4143d70e41bf6c04304bf7adf4a39752b05686f1
Remove unresolvable seealso reference
BenJenkinson/nodatime,BenJenkinson/nodatime,nodatime/nodatime,nodatime/nodatime
src/NodaTime/IClock.cs
src/NodaTime/IClock.cs
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime { /// <summary> /// Represents a clock which can return the current time as an <see cref="Instant" />. /// </summary> /// <remarks> /// <see cref="IClock"/> is intended for use anywhere you need to have access to the current time. /// Although it's not strictly incorrect to call <c>SystemClock.Instance.GetCurrentInstant()</c> directly, /// in the same way as you might call <see cref="DateTime.UtcNow"/>, it's strongly discouraged /// as a matter of style for production code. We recommend providing an instance of <see cref="IClock"/> /// to anything that needs it, which allows you to write tests using the fake clock in the NodaTime.Testing /// assembly (or your own implementation). /// </remarks> /// <seealso cref="SystemClock"/> /// <threadsafety>All implementations in Noda Time are thread-safe; custom implementations /// should be thread-safe too. See the thread safety section of the user guide for more information. /// </threadsafety> public interface IClock { /// <summary> /// Gets the current <see cref="Instant"/> on the time line according to this clock. /// </summary> /// <returns>The current instant on the time line according to this clock.</returns> Instant GetCurrentInstant(); } }
// Copyright 2011 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using System; namespace NodaTime { /// <summary> /// Represents a clock which can return the current time as an <see cref="Instant" />. /// </summary> /// <remarks> /// <see cref="IClock"/> is intended for use anywhere you need to have access to the current time. /// Although it's not strictly incorrect to call <c>SystemClock.Instance.GetCurrentInstant()</c> directly, /// in the same way as you might call <see cref="DateTime.UtcNow"/>, it's strongly discouraged /// as a matter of style for production code. We recommend providing an instance of <see cref="IClock"/> /// to anything that needs it, which allows you to write tests using the fake clock in the NodaTime.Testing /// assembly (or your own implementation). /// </remarks> /// <seealso cref="SystemClock"/> /// <seealso cref="NodaTime.Testing.FakeClock"/> /// <threadsafety>All implementations in Noda Time are thread-safe; custom implementations /// should be thread-safe too. See the thread safety section of the user guide for more information. /// </threadsafety> public interface IClock { /// <summary> /// Gets the current <see cref="Instant"/> on the time line according to this clock. /// </summary> /// <returns>The current instant on the time line according to this clock.</returns> Instant GetCurrentInstant(); } }
apache-2.0
C#
57526ed4ff676a378cda31a20c9cd02d3601ea4f
Fix missing ErrorText
StevenLiekens/Txt,StevenLiekens/TextFx
src/TextFx/ReadResult.cs
src/TextFx/ReadResult.cs
namespace TextFx { using System; using JetBrains.Annotations; public sealed class ReadResult<T> where T : Element { private ReadResult([NotNull] SyntaxError error) { if (error == null) { throw new ArgumentNullException(nameof(error)); } Error = error; Text = string.Empty; ErrorText = error.ErrorText; EndOfInput = error.EndOfInput; Success = false; Text = error.Text; } private ReadResult([NotNull] T element) { if (element == null) { throw new ArgumentNullException(nameof(element)); } Success = true; Text = element.Text; ErrorText = string.Empty; Element = element; } public T Element { get; } public bool EndOfInput { get; } public SyntaxError Error { get; } [NotNull] public string ErrorText { get; } public bool Success { get; } [NotNull] public string Text { get; } public static ReadResult<T> FromResult([NotNull] T result) { return new ReadResult<T>(result); } public static ReadResult<T> FromSyntaxError([NotNull] SyntaxError error) { return new ReadResult<T>(error); } } }
namespace TextFx { using System; using JetBrains.Annotations; public sealed class ReadResult<T> where T : Element { private ReadResult([NotNull] SyntaxError error) { if (error == null) { throw new ArgumentNullException(nameof(error)); } Error = error; Text = string.Empty; ErrorText = error.Text; EndOfInput = error.EndOfInput; Success = false; Text = error.Text; } private ReadResult([NotNull] T element) { if (element == null) { throw new ArgumentNullException(nameof(element)); } Success = true; Text = element.Text; ErrorText = string.Empty; Element = element; } public T Element { get; } public bool EndOfInput { get; } public SyntaxError Error { get; } [NotNull] public string ErrorText { get; } public bool Success { get; } [NotNull] public string Text { get; } public static ReadResult<T> FromResult([NotNull] T result) { return new ReadResult<T>(result); } public static ReadResult<T> FromSyntaxError([NotNull] SyntaxError error) { return new ReadResult<T>(error); } } }
mit
C#
41a552f62c8c84937df3f38da410bce974c2a87d
Introduce variable for new count
rubberduck203/GitNStats,rubberduck203/GitNStats
src/gitnstats.core/Analysis.cs
src/gitnstats.core/Analysis.cs
using System; using System.Collections.Generic; using System.Linq; using LibGit2Sharp; namespace GitNStats.Core { public delegate bool DiffFilterPredicate((Commit Commit, TreeEntryChanges TreeEntryChanges) diff); public static class Analysis { public static IEnumerable<PathCount> CountFileChanges(IEnumerable<(Commit, TreeEntryChanges)> diffs) { return diffs.Aggregate<(Commit Commit, TreeEntryChanges Diff), Dictionary<string, int>>( new Dictionary<string, int>(), (acc, x) => { int newCount; if (x.Diff.Status == ChangeKind.Renamed) { newCount = acc[x.Diff.OldPath] + 1; acc.Remove(x.Diff.OldPath); } else { newCount = acc.GetOrDefault(x.Diff.Path, 0) + 1; } acc[x.Diff.Path] = newCount; return acc; } ) .Select(x => new PathCount(x.Key, x.Value)) .OrderByDescending(s => s.Count); } /// <summary> /// Predicate for filtering by date /// </summary> /// <param name="onOrAfter">Local DateTime</param> /// <returns>True if Commit was on or after <paramref name="onOrAfter"/>, otherwise false.</returns> public static DiffFilterPredicate OnOrAfter(DateTime onOrAfter) { return change => change.Commit.Author.When.ToUniversalTime() >= onOrAfter.ToUniversalTime(); } } static class DictionaryExtensions { public static V GetOrDefault<K,V>(this Dictionary<K,V> dictionary, K key, V defaultValue) { return dictionary.TryGetValue(key, out V value) ? value : defaultValue; } } }
using System; using System.Collections.Generic; using System.Linq; using LibGit2Sharp; namespace GitNStats.Core { public delegate bool DiffFilterPredicate((Commit Commit, TreeEntryChanges TreeEntryChanges) diff); public static class Analysis { public static IEnumerable<PathCount> CountFileChanges(IEnumerable<(Commit, TreeEntryChanges)> diffs) { return diffs.Aggregate<(Commit Commit, TreeEntryChanges Diff), Dictionary<string, int>>( new Dictionary<string, int>(), (acc, x) => { if (x.Diff.Status == ChangeKind.Renamed) { acc[x.Diff.Path] = acc[x.Diff.OldPath] + 1; acc.Remove(x.Diff.OldPath); } else { acc[x.Diff.Path] = acc.GetOrDefault(x.Diff.Path, 0) + 1; } return acc; } ) .Select(x => new PathCount(x.Key, x.Value)) .OrderByDescending(s => s.Count); } /// <summary> /// Predicate for filtering by date /// </summary> /// <param name="onOrAfter">Local DateTime</param> /// <returns>True if Commit was on or after <paramref name="onOrAfter"/>, otherwise false.</returns> public static DiffFilterPredicate OnOrAfter(DateTime onOrAfter) { return change => change.Commit.Author.When.ToUniversalTime() >= onOrAfter.ToUniversalTime(); } } static class DictionaryExtensions { public static V GetOrDefault<K,V>(this Dictionary<K,V> dictionary, K key, V defaultValue) { return dictionary.TryGetValue(key, out V value) ? value : defaultValue; } } }
mit
C#
63bee72b92a529e9c2a22852b8183565bde039d6
Update AssemblyInfo
airbreather/StepperUpper
StepperUpper/Properties/AssemblyInfo.cs
StepperUpper/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("StepperUpper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StepperUpper")] [assembly: AssemblyCopyright("Copyright (C) Joe Amenta 2016-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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6acbe635-a903-4f00-8ced-6b2da8f23c82")] // 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")]
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("StepperUpper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("StepperUpper")] [assembly: AssemblyCopyright("Copyright (C) Joe Amenta 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6acbe635-a903-4f00-8ced-6b2da8f23c82")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")]
mit
C#
d95b547d5a0736020ded198e87cb4cf877c482db
Simplify UnitTestStopwatch
MiniProfiler/dotnet,MiniProfiler/dotnet
tests/MiniProfiler.Tests/UnitTestStopwatch.cs
tests/MiniProfiler.Tests/UnitTestStopwatch.cs
using StackExchange.Profiling.Helpers; using System; namespace Tests { /// <summary> /// The unit test stopwatch. /// </summary> public class UnitTestStopwatch : IStopwatch { private bool _isRunning = true; /// <summary> /// The ticks per second. /// </summary> public static readonly long TicksPerSecond = TimeSpan.TicksPerSecond; /// <summary> /// The ticks per millisecond. /// </summary> public static readonly long TicksPerMillisecond = TimeSpan.TicksPerMillisecond; /// <summary> /// Gets or sets the elapsed ticks. /// </summary> public long ElapsedTicks { get; set; } /// <summary> /// Gets the frequency, <see cref="MiniProfiler.GetRoundedMilliseconds"/> method will use this to determine how many ticks actually elapsed, so make it simple. /// </summary> public long Frequency => TicksPerSecond; /// <summary> /// Gets a value indicating whether is running. /// </summary> public bool IsRunning => _isRunning; /// <summary> /// Stop the profiler. /// </summary> public void Stop() => _isRunning = false; } }
using StackExchange.Profiling.Helpers; using System; namespace Tests { /// <summary> /// The unit test stopwatch. /// </summary> public class UnitTestStopwatch : IStopwatch { private bool _isRunning = true; /// <summary> /// The ticks per second. /// </summary> public static readonly long TicksPerSecond = TimeSpan.FromSeconds(1).Ticks; /// <summary> /// The ticks per millisecond. /// </summary> public static readonly long TicksPerMillisecond = TimeSpan.FromMilliseconds(1).Ticks; /// <summary> /// Gets or sets the elapsed ticks. /// </summary> public long ElapsedTicks { get; set; } /// <summary> /// Gets the frequency, <see cref="MiniProfiler.GetRoundedMilliseconds"/> method will use this to determine how many ticks actually elapsed, so make it simple. /// </summary> public long Frequency => TicksPerSecond; /// <summary> /// Gets a value indicating whether is running. /// </summary> public bool IsRunning => _isRunning; /// <summary> /// Stop the profiler. /// </summary> public void Stop() => _isRunning = false; } }
mit
C#
0531a8dfefd54c545cb8659a2f4cd356285f1d70
initialize datarepository and previewgenerator
bradwestness/SecretSanta,bradwestness/SecretSanta
SecretSanta/Startup.cs
SecretSanta/Startup.cs
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SecretSanta.Utilities; using System; namespace SecretSanta { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; AppSettings.Initialize(configuration); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDistributedMemoryCache(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => { o.LoginPath = AppSettings.LoginPath; o.LogoutPath = AppSettings.LogoutPath; o.ExpireTimeSpan = TimeSpan.FromMinutes(60); o.SlidingExpiration = true; }); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { DataRepository.Initialize(env.ContentRootPath); PreviewGenerator.Initialize(env.WebRootPath); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SecretSanta.Utilities; using System; namespace SecretSanta { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; AppSettings.Initialize(configuration); } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDistributedMemoryCache(); services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => { o.LoginPath = AppSettings.LoginPath; o.LogoutPath = AppSettings.LogoutPath; o.ExpireTimeSpan = TimeSpan.FromMinutes(60); o.SlidingExpiration = true; }); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromMinutes(60); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseSession(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
apache-2.0
C#
4737adb6e8d22c3773c77aa894f67898747e6d2d
Refactor Config class
atata-framework/atata-sample-app-tests
src/Atata.SampleApp.AutoTests/Config.cs
src/Atata.SampleApp.AutoTests/Config.cs
using System.Configuration; namespace Atata.SampleApp.AutoTests { public static class Config { public static string Url { get; } = ConfigurationManager.AppSettings[nameof(Url)]; public static class Account { public static string Email { get; } = ConfigurationManager.AppSettings[nameof(Email)]; public static string Password { get; } = ConfigurationManager.AppSettings[nameof(Password)]; } } }
using System.Configuration; namespace Atata.SampleApp.AutoTests { public static class Config { public static string Url { get; } = ConfigurationManager.AppSettings["Url"]; public static class Account { public static string Email { get; } = ConfigurationManager.AppSettings["Email"]; public static string Password { get; } = ConfigurationManager.AppSettings["Password"]; } } }
apache-2.0
C#
512c15fd6f96f52e12ddecd901d671b20371077e
add comment
luguandao/SSystem.Processors
implementation/src/SSystem.Processors/PerTimerType.cs
implementation/src/SSystem.Processors/PerTimerType.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SSystem.Processors { /// <summary> /// type of timer /// </summary> public enum PerTimerType { Once, Second, Minitus, Hour, Day, Week, Month, Year } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SSystem.Processors { public enum PerTimerType { Once, Second, Minitus, Hour, Day, Week, Month, Year } }
mpl-2.0
C#
0c8dab99d96d9286ae0ee88e5cfe0e3f37369815
remove unnessary ref
lukeschafer/HtmlCleanser
src/HtmlCleanser/Rules/StylesAttributesShouldHaveValue.cs
src/HtmlCleanser/Rules/StylesAttributesShouldHaveValue.cs
using System.Collections.Generic; using HtmlAgilityPack; namespace HtmlCleanser.Rules { /// <summary> /// Remove all styles attributtes that don`t have a value. For ex. style="font-family:Calibri,Arial,Helvetica,sans-serif; font-size:; margin: 0" /// => style="font-family:Calibri,Arial,Helvetica,sans-serif;margin: 0" /// </summary> public class StylesAttributesShouldHaveValue : IHtmlCleanserRule { public void Perform(HtmlDocument doc) { var nodes = doc.DocumentNode.Descendants(); if (nodes == null) return; var cssParser = GetCssParser(); foreach (var n in nodes) { var styleAttribute = n.Attributes["style"]; if (styleAttribute != null) { var parsedStyles = new StyleClass(cssParser.ParseStyleClass("styleTag", styleAttribute.Value)); var parsedStyleToDelete = new Dictionary<string, string>(); foreach (var a in parsedStyles.Attributes) { if (string.IsNullOrWhiteSpace(a.Value)) parsedStyleToDelete.Add(a.Key, a.Value); } if (parsedStyleToDelete.Count > 0) { foreach (var s in parsedStyleToDelete) parsedStyles.Attributes.Remove(s.Key); styleAttribute.Value = parsedStyles.ToString(); } } } } protected virtual CssParser GetCssParser() { return new CssParser(); } } }
using System; using System.Collections.Generic; using HtmlAgilityPack; namespace HtmlCleanser.Rules { /// <summary> /// Remove all styles attributtes that don`t have a value. For ex. style="font-family:Calibri,Arial,Helvetica,sans-serif; font-size:; margin: 0" /// => style="font-family:Calibri,Arial,Helvetica,sans-serif;margin: 0" /// </summary> public class StylesAttributesShouldHaveValue : IHtmlCleanserRule { public void Perform(HtmlDocument doc) { var nodes = doc.DocumentNode.Descendants(); if (nodes == null) return; var cssParser = GetCssParser(); foreach (var n in nodes) { var styleAttribute = n.Attributes["style"]; if (styleAttribute != null) { var parsedStyles = new StyleClass(cssParser.ParseStyleClass("styleTag", styleAttribute.Value)); var parsedStyleToDelete = new Dictionary<string, string>(); foreach (var a in parsedStyles.Attributes) { if (string.IsNullOrWhiteSpace(a.Value)) parsedStyleToDelete.Add(a.Key, a.Value); } if (parsedStyleToDelete.Count > 0) { foreach (var s in parsedStyleToDelete) parsedStyles.Attributes.Remove(s.Key); styleAttribute.Value = parsedStyles.ToString(); } } } } protected virtual CssParser GetCssParser() { return new CssParser(); } } }
mit
C#
288231d025ca4ac207979e3ea907535c7ca75e22
Use ArgumentNullException.ThrowIfNull()
martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site,martincostello/alexa-london-travel-site
src/LondonTravel.Site/Extensions/IHtmlHelperExtensions.cs
src/LondonTravel.Site/Extensions/IHtmlHelperExtensions.cs
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Mvc.Rendering; namespace MartinCostello.LondonTravel.Site.Extensions; /// <summary> /// A class containing extension methods for the <see cref="IHtmlHelper"/> interface. This class cannot be inherited. /// </summary> public static class IHtmlHelperExtensions { /// <summary> /// A mapping of authentication schemes to icon classes. This field is read-only. /// </summary> private static readonly IDictionary<string, string> _iconImageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["Amazon"] = "amazon", ["Apple"] = "apple", ["Facebook"] = "facebook", ["GitHub"] = "github", ["Google"] = "google", ["Microsoft"] = "windows", ["Twitter"] = "twitter", }; /// <summary> /// Gets the CSS class to use for a social login button. /// </summary> /// <param name="html">The <see cref="IHtmlHelper"/> to use.</param> /// <param name="authenticationScheme">The Id/name of the authentication scheme.</param> /// <returns> /// The CSS class to use for a button for the authentication scheme. /// </returns> public static string GetSocialLoginButtonCss(this IHtmlHelper html, string authenticationScheme) { ArgumentNullException.ThrowIfNull(html); return $"btn-{authenticationScheme?.ToLowerInvariant()}"; } /// <summary> /// Gets the CSS class to use for a social login icon. /// </summary> /// <param name="html">The <see cref="IHtmlHelper"/> to use.</param> /// <param name="authenticationScheme">The Id/name of the authentication scheme.</param> /// <returns> /// The CSS class to use for an icon for the authentication scheme. /// </returns> public static string GetSocialLoginIconCss(this IHtmlHelper html, string authenticationScheme) { ArgumentNullException.ThrowIfNull(html); if (string.IsNullOrEmpty(authenticationScheme)) { return string.Empty; } string iconClass = string.Empty; if (_iconImageMap.TryGetValue(authenticationScheme, out string? modifier)) { iconClass = $"fa-{modifier}"; } return iconClass; } }
// Copyright (c) Martin Costello, 2017. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. using Microsoft.AspNetCore.Mvc.Rendering; namespace MartinCostello.LondonTravel.Site.Extensions; /// <summary> /// A class containing extension methods for the <see cref="IHtmlHelper"/> interface. This class cannot be inherited. /// </summary> public static class IHtmlHelperExtensions { /// <summary> /// A mapping of authentication schemes to icon classes. This field is read-only. /// </summary> private static readonly IDictionary<string, string> _iconImageMap = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { ["Amazon"] = "amazon", ["Apple"] = "apple", ["Facebook"] = "facebook", ["GitHub"] = "github", ["Google"] = "google", ["Microsoft"] = "windows", ["Twitter"] = "twitter", }; /// <summary> /// Gets the CSS class to use for a social login button. /// </summary> /// <param name="html">The <see cref="IHtmlHelper"/> to use.</param> /// <param name="authenticationScheme">The Id/name of the authentication scheme.</param> /// <returns> /// The CSS class to use for a button for the authentication scheme. /// </returns> #pragma warning disable CA1801 public static string GetSocialLoginButtonCss(this IHtmlHelper html, string authenticationScheme) #pragma warning restore CA1801 { return $"btn-{authenticationScheme?.ToLowerInvariant()}"; } /// <summary> /// Gets the CSS class to use for a social login icon. /// </summary> /// <param name="html">The <see cref="IHtmlHelper"/> to use.</param> /// <param name="authenticationScheme">The Id/name of the authentication scheme.</param> /// <returns> /// The CSS class to use for an icon for the authentication scheme. /// </returns> #pragma warning disable CA1801 public static string GetSocialLoginIconCss(this IHtmlHelper html, string authenticationScheme) #pragma warning restore CA1801 { if (string.IsNullOrEmpty(authenticationScheme)) { return string.Empty; } string iconClass = string.Empty; if (_iconImageMap.TryGetValue(authenticationScheme, out string? modifier)) { iconClass = $"fa-{modifier}"; } return iconClass; } }
apache-2.0
C#
71e1eac9ab00b70ee0c86e9c329111a6a7e1de9e
Add UserIDFromDeployedItem and UserIDsFromBuildingPrivilege - Courtesy of @strykes aka Reneb
MSylvia/Oxide,bawNg/Oxide,Nogrod/Oxide-2,Visagalis/Oxide,Nogrod/Oxide-2,MSylvia/Oxide,LaserHydra/Oxide,LaserHydra/Oxide,Visagalis/Oxide,bawNg/Oxide,ApocDev/Oxide,ApocDev/Oxide
Oxide.Ext.Rust/Libraries/Rust.cs
Oxide.Ext.Rust/Libraries/Rust.cs
using System; using System.Collections.Generic; using System.Linq; using Oxide.Core.Libraries; using Oxide.Core.Plugins; namespace Oxide.Rust.Libraries { /// <summary> /// A library containing utility shortcut functions for rust /// </summary> public class Rust : Library { /// <summary> /// Returns if this library should be loaded into the global namespace /// </summary> public override bool IsGlobal { get { return false; } } /// <summary> /// Returns the UserID for the specified connection as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromConnection")] public string UserIDFromConnection(Network.Connection connection) { return connection.userid.ToString(); } /// <summary> /// Returns the UserIDs for the specified building privilege as an array /// </summary> /// <param name="privilege"></param> /// <returns></returns> [LibraryFunction("UserIDsFromBuildingPrivilege")] public Array UserIDsFromBuildingPrivlidge(BuildingPrivlidge buildingpriv) { List<string> list = new List<string>(); foreach (ProtoBuf.PlayerNameID eid in buildingpriv.authorizedPlayers) { list.Add(eid.userid.ToString()); } return list.ToArray(); } /// <summary> /// Returns the UserID for the specified deployed item as a string /// </summary> /// <param name="item"></param> /// <returns></returns> [LibraryFunction("UserIDFromDeployedItem")] public string UserIDFromDeployedItem(DeployedItem DeployedItem) { return DeployedItem.deployerUserID.ToString(); } /// <summary> /// Returns the UserID for the specified player as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromPlayer")] public string UserIDFromPlayer(BasePlayer player) { return player.userID.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using Oxide.Core.Libraries; using Oxide.Core.Plugins; namespace Oxide.Rust.Libraries { /// <summary> /// A library containing utility shortcut functions for rust /// </summary> public class Rust : Library { /// <summary> /// Returns if this library should be loaded into the global namespace /// </summary> public override bool IsGlobal { get { return false; } } /// <summary> /// Returns the UserID for the specified connection as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromConnection")] public string UserIDFromConnection(Network.Connection connection) { return connection.userid.ToString(); } /// <summary> /// Returns the UserID for the specified player as a string /// </summary> /// <param name="connection"></param> /// <returns></returns> [LibraryFunction("UserIDFromPlayer")] public string UserIDFromPlayer(BasePlayer player) { return player.userID.ToString(); } } }
mit
C#
7bf177ad8ff871939906cc93a4737183276bc8f6
Add shortcut of canvas width scaling by up/down arrow key
setchi/NotesEditor,setchi/NoteEditor
Assets/Scripts/UI/CanvasWidthScalePresenter.cs
Assets/Scripts/UI/CanvasWidthScalePresenter.cs
using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class CanvasWidthScalePresenter : MonoBehaviour { [SerializeField] CanvasEvents canvasEvents; [SerializeField] Slider canvasWidthScaleController; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { model.CanvasWidth = canvasEvents.MouseScrollWheelObservable .Where(_ => KeyInput.CtrlKey()) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.1f)) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.1f)) .Select(delta => model.CanvasWidth.Value * (1 + delta)) .Select(x => x / (model.Audio.clip.samples / 100f)) .Select(x => Mathf.Clamp(x, 0.1f, 2f)) .Merge(canvasWidthScaleController.OnValueChangedAsObservable() .DistinctUntilChanged()) .Select(x => model.Audio.clip.samples / 100f * x) .ToReactiveProperty(); } }
using UniRx; using UnityEngine; using UnityEngine.UI; public class CanvasWidthScalePresenter : MonoBehaviour { [SerializeField] CanvasEvents canvasEvents; [SerializeField] Slider canvasWidthScaleController; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { model.CanvasWidth = canvasEvents.MouseScrollWheelObservable .Where(_ => KeyInput.CtrlKey()) .Select(delta => model.CanvasWidth.Value * (1 + delta)) .Select(x => x / (model.Audio.clip.samples / 100f)) .Select(x => Mathf.Clamp(x, 0.1f, 2f)) .Merge(canvasWidthScaleController.OnValueChangedAsObservable() .DistinctUntilChanged()) .Select(x => model.Audio.clip.samples / 100f * x) .ToReactiveProperty(); } }
mit
C#
4b63a2cf1333386fe4fac385db4a550f2b2dcda1
indent down
yurii-litvinov/Biblio2015,yurii-litvinov/Biblio2015,yurii-litvinov/Biblio2015
BibliographicSystem/Views/Account/LogIn.cshtml
BibliographicSystem/Views/Account/LogIn.cshtml
@model BibliographicSystem.Models.LogOnModel @{ ViewBag.Title = "LogIn"; Layout = "~/Views/Shared/_Layout.cshtml"; } <br> <br> <br> <br> <br> <div class="container"> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <form class="form-horizontal" method="post"> <h2 class="form-signin-heading">Вход в систему</h2> <label for="Username" class="sr-only">Username</label> <input type="text" id="Username" name="Username" class="form-control" placeholder="Username" required autofocus> <br /> <label for="Password" class="sr-only">Password</label> <input type="password" id="Password" name="Password" class="form-control" placeholder="Password" required> <div class="checkbox"> <label> <input type="checkbox" value="RememberMe"> Запомнить </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Вход в систему</button> </form> </div> <!-- col --> </div> <!-- row --> </div> <!--container-->
@model BibliographicSystem.Models.LogOnModel @{ ViewBag.Title = "LogIn"; Layout = "~/Views/Shared/_Layout.cshtml"; } <br> <br> <div class="container"> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <form class="form-horizontal" method="post"> <h2 class="form-signin-heading">Вход в систему</h2> <label for="Username" class="sr-only">Username</label> <input type="text" id="Username" name="Username" class="form-control" placeholder="Username" required autofocus> <label for="Password" class="sr-only">Password</label> <input type="password" id="Password" name="Password" class="form-control" placeholder="Password" required> <div class="checkbox"> <label> <input type="checkbox" value="RememberMe"> Запомнить </label> </div> <button class="btn btn-lg btn-primary btn-block" type="submit">Вход в систему</button> </form> </div> <!-- col --> </div> <!-- row --> </div> <!--container-->
apache-2.0
C#
aa1b76fff612cb66e75a3c1013642d1eafc8a4c5
Remove InternalsVisibleTo assembly attribute
discomurray/ZedGraph,ZedGraph/ZedGraph,DHMechatronicAG/ZedGraph
source/ZedGraph/Properties/AssemblyInfo.cs
source/ZedGraph/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Resources; using System; // 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: AssemblyDescription( "ZedGraph Library" )] [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( "a552bf32-72a3-4d27-968c-72e7a90243f2" )] [assembly: NeutralResourcesLanguageAttribute( "" )] [assembly: CLSCompliant( true )]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security; using System.Resources; using System; // 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: AssemblyDescription( "ZedGraph Library" )] [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 )] [assembly: InternalsVisibleTo("ZedGraph.WinForms, PublicKey=" + "00240000048000009400000006020000002400005253413100040000010001002f86fc317ec78e" + "545188db70d915056f5a42bcc59f3e973eea23b771b6e6778c74d5b426a9ff9eb73447edee78fc" + "45ce3801471ae8070b846df0d8e327f2c9f493de3a761f1f6c2cab157cb4e64a7f0df833c95648" + "7dded5cb3fb80e104a0ba17b9cbd23eb3974e1724831f0fdcc431f4c08b7679ad3a1212fbcb173" + "bee104be")] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid( "a552bf32-72a3-4d27-968c-72e7a90243f2" )] [assembly: NeutralResourcesLanguageAttribute( "" )] [assembly: CLSCompliant( true )]
lgpl-2.1
C#
d69e58ae2ce4b874e679f0c5a5574535d5c856d4
Update WhereBuilder.cs
loresoft/FluentCommand
src/FluentCommand/Query/WhereBuilder.cs
src/FluentCommand/Query/WhereBuilder.cs
using FluentCommand.Query.Generators; namespace FluentCommand; public abstract class WhereBuilder<TBuilder> : StatementBuilder<TBuilder> where TBuilder : WhereBuilder<TBuilder> { protected WhereBuilder(IQueryGenerator queryGenerator, List<QueryParameter> parameters, LogicalOperators logicalOperator = LogicalOperators.And) : base(queryGenerator, parameters) { LogicalOperator = logicalOperator; } protected HashSet<string> WhereClause { get; } = new(); protected LogicalOperators LogicalOperator { get; } public TBuilder Where<TValue>( string columnName, TValue parameterValue, FilterOperators filterOperator = FilterOperators.Equal) { var paramterName = NextParameter(); var whereClause = QueryGenerator.WhereClause(columnName, paramterName, filterOperator); WhereClause.Add(whereClause); Parameters.Add(new QueryParameter(paramterName, parameterValue, typeof(TValue))); return (TBuilder)this; } public TBuilder WhereIf<TValue>( string columnName, TValue parameterValue, FilterOperators filterOperator = FilterOperators.Equal, Func<string, TValue, bool> condition = null) { if (condition != null && !condition(columnName, parameterValue)) return (TBuilder)this; return Where(columnName, parameterValue, filterOperator); } public TBuilder Where( string whereClause, IReadOnlyCollection<QueryParameter> parametes = null) { if (string.IsNullOrWhiteSpace(whereClause)) throw new ArgumentException($"'{nameof(whereClause)}' cannot be null or empty.", nameof(whereClause)); WhereClause.Add(whereClause); if (parametes != null) Parameters.AddRange(parametes); return (TBuilder)this; } public TBuilder WhereIf( string whereClause, IReadOnlyCollection<QueryParameter> parametes = null, Func<string, IReadOnlyCollection<QueryParameter>, bool> condition = null) { if (condition != null && !condition(whereClause, parametes)) return (TBuilder)this; return Where(whereClause, parametes); } }
using FluentCommand.Query.Generators; namespace FluentCommand; public abstract class WhereBuilder<TBuilder> : StatementBuilder<TBuilder> where TBuilder : WhereBuilder<TBuilder> { protected WhereBuilder(IQueryGenerator queryGenerator, List<QueryParameter> parameters, LogicalOperators logicalOperator = LogicalOperators.And) : base(queryGenerator, parameters) { LogicalOperator = logicalOperator; } protected HashSet<string> WhereClause { get; } = new(); protected LogicalOperators LogicalOperator { get; } public TBuilder Where<TValue>( string columnName, TValue parameterValue, FilterOperators filterOperator = FilterOperators.Equal) { var paramterName = NextParameter(); var whereClause = QueryGenerator.WhereClause(columnName, paramterName, filterOperator); WhereClause.Add(whereClause); Parameters.Add(new QueryParameter(paramterName, parameterValue, typeof(TValue))); return (TBuilder)this; } public TBuilder WhereIf<TValue>( string columnName, TValue parameterValue, FilterOperators filterOperator = FilterOperators.Equal, Func<string, TValue, bool> condition = null) { if (condition != null && !condition(columnName, parameterValue)) return (TBuilder)this; return Where(columnName, parameterValue, filterOperator); } public TBuilder Where( string whereClause, IList<QueryParameter> parametes = null) { if (string.IsNullOrWhiteSpace(whereClause)) throw new ArgumentException($"'{nameof(whereClause)}' cannot be null or empty.", nameof(whereClause)); WhereClause.Add(whereClause); if (parametes != null) Parameters.AddRange(parametes); return (TBuilder)this; } }
mit
C#
0e9ae93af1e528635294dcf5353c0854fb214431
Fix unit tests
famoser/FexCompiler
Famoser.FexCompiler.Test/Helpers/TestHelper.cs
Famoser.FexCompiler.Test/Helpers/TestHelper.cs
using System.Collections.Generic; using System.IO; using System.Reflection; using Famoser.FexCompiler.Models; namespace Famoser.FexCompiler.Test.Helpers { class TestHelper { public static string GetInputFolderPath() { var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); return Path.Combine(basePath, "Input\\"); } public static string[] GetInputFile(string fileName) { return File.ReadAllLines(GetInputFilePath(fileName)); } public static string GetInputFilePath(string fileName) { return Path.Combine(GetInputFolderPath(), fileName); } public static ConfigModel GetConfigModel() { return new ConfigModel() { Author = "famoser", CompilePaths = new List<string> {GetInputFolderPath()} }; } } }
using System.IO; using System.Reflection; using Famoser.FexCompiler.Models; namespace Famoser.FexCompiler.Test.Helpers { class TestHelper { public static string GetInputFolderPath() { var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); return Path.Combine(basePath, "Input\\"); } public static string[] GetInputFile(string fileName) { return File.ReadAllLines(GetInputFilePath(fileName)); } public static string GetInputFilePath(string fileName) { return Path.Combine(GetInputFolderPath(), fileName); } public static ConfigModel GetConfigModel() { return new ConfigModel() { Author = "famoser", CompilePaths = GetInputFolderPath() }; } } }
mit
C#
77e07e9b091448ce7540471f27a15d6b3af718de
Add IsSolid property for block
lupidan/Tetris
Assets/Scripts/Block.cs
Assets/Scripts/Block.cs
using UnityEngine; namespace Tetris { public class Block : MonoBehaviour { public bool IsSolid = true; public Color Color { get { return _spriteRenderer.color; } set { _spriteRenderer.color = value; } } private SpriteRenderer _spriteRenderer; private void Awake() { _spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); } } }
using UnityEngine; namespace Tetris { public class Block : MonoBehaviour { public Color Color { get { return _spriteRenderer.color; } set { _spriteRenderer.color = value; } } private SpriteRenderer _spriteRenderer; private void Awake() { _spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); } } }
mit
C#
cae1a3780239eeece87d858ce150431395abca5c
call feed url without params
jgraber/atom_exchange,jgraber/atom_exchange,jgraber/atom_exchange
AtomConsumer/Program.cs
AtomConsumer/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Text; using System.Threading.Tasks; using System.Xml; namespace AtomConsumer { class Program { static void Main(string[] args) { var feedUrl = "http://localhost:7646/Home/Feed/false"; //var feedUrl = "http://improveandrepeat.com/feed/atom/"; Atom10FeedFormatter formatter = new Atom10FeedFormatter(); using (XmlReader reader = XmlReader.Create(feedUrl)) { formatter.ReadFrom(reader); } foreach (SyndicationItem item in formatter.Feed.Items) { Console.WriteLine("[{0}][{1}] {2}", item.PublishDate, item.Title.Text, item.Links.First().Uri); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Text; using System.Threading.Tasks; using System.Xml; namespace AtomConsumer { class Program { static void Main(string[] args) { var feedUrl = "http://localhost:7646/Home/Feed"; //var feedUrl = "http://improveandrepeat.com/feed/atom/"; Atom10FeedFormatter formatter = new Atom10FeedFormatter(); using (XmlReader reader = XmlReader.Create(feedUrl)) { formatter.ReadFrom(reader); } foreach (SyndicationItem item in formatter.Feed.Items) { Console.WriteLine("[{0}][{1}] {2}", item.PublishDate, item.Title.Text, item.Links.First().Uri); } Console.ReadLine(); } } }
apache-2.0
C#
eba54cc40b242404a2c380dd9105922139f1b912
Fix LSP client dispose bug in tests (#1212)
PowerShell/PowerShellEditorServices
test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs
test/PowerShellEditorServices.Test.E2E/LSPTestsFixures.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Client.Processes; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace PowerShellEditorServices.Test.E2E { public class LSPTestsFixture : TestsFixture { public override bool IsDebugAdapterTests => false; public LanguageClient LanguageClient { get; private set; } public List<Diagnostic> Diagnostics { get; set; } public async override Task CustomInitializeAsync( ILoggerFactory factory, StdioServerProcess process) { LanguageClient = new LanguageClient(factory, process); DirectoryInfo testdir = Directory.CreateDirectory(Path.Combine(s_binDir, Path.GetRandomFileName())); await LanguageClient.Initialize(testdir.FullName); // Make sure Script Analysis is enabled because we'll need it in the tests. LanguageClient.Workspace.DidChangeConfiguration(JObject.Parse(@" { ""PowerShell"": { ""ScriptAnalysis"": { ""Enable"": true } } } ")); Diagnostics = new List<Diagnostic>(); LanguageClient.TextDocument.OnPublishDiagnostics((uri, diagnostics) => { Diagnostics.AddRange(diagnostics.Where(d => d != null)); }); } public override async Task DisposeAsync() { try { await LanguageClient.Shutdown(); await _psesProcess.Stop(); LanguageClient?.Dispose(); } catch (ObjectDisposedException) { // Language client has a disposal bug in it } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Client; using OmniSharp.Extensions.LanguageServer.Client.Processes; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace PowerShellEditorServices.Test.E2E { public class LSPTestsFixture : TestsFixture { public override bool IsDebugAdapterTests => false; public LanguageClient LanguageClient { get; private set; } public List<Diagnostic> Diagnostics { get; set; } public async override Task CustomInitializeAsync( ILoggerFactory factory, StdioServerProcess process) { LanguageClient = new LanguageClient(factory, process); DirectoryInfo testdir = Directory.CreateDirectory(Path.Combine(s_binDir, Path.GetRandomFileName())); await LanguageClient.Initialize(testdir.FullName); // Make sure Script Analysis is enabled because we'll need it in the tests. LanguageClient.Workspace.DidChangeConfiguration(JObject.Parse(@" { ""PowerShell"": { ""ScriptAnalysis"": { ""Enable"": true } } } ")); Diagnostics = new List<Diagnostic>(); LanguageClient.TextDocument.OnPublishDiagnostics((uri, diagnostics) => { Diagnostics.AddRange(diagnostics.Where(d => d != null)); }); } public override async Task DisposeAsync() { await LanguageClient.Shutdown(); await _psesProcess.Stop(); LanguageClient?.Dispose(); } } }
mit
C#
859228a1d15a9cc2b62bab82ea9941ef3fa0a465
Update WebGL AssemblyVersion
e-lefort/Frameworks,bridgedotnet/Frameworks,e-lefort/Frameworks,e-lefort/Frameworks
WebGL/Properties/AssemblyInfo.cs
WebGL/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Bridge.WebGL")] [assembly: AssemblyProduct("Bridge.WebGL")] [assembly: AssemblyDescription("WebGL (Web Graphics Library) version 1.x bindings for Bridge.NET.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Object.NET, Inc.")] [assembly: AssemblyCopyright("Copyright 2008-2015 Object.NET, Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("99243041-ec64-4e8d-8f3a-ad822b81caa9")] [assembly: AssemblyVersion("1.6")] [assembly: AssemblyFileVersion("1.6.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Bridge.WebGL")] [assembly: AssemblyProduct("Bridge.WebGL")] [assembly: AssemblyDescription("WebGL (Web Graphics Library) version 1.x bindings for Bridge.NET.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Object.NET, Inc.")] [assembly: AssemblyCopyright("Copyright 2008-2015 Object.NET, Inc.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("99243041-ec64-4e8d-8f3a-ad822b81caa9")] [assembly: AssemblyVersion("1.5")] [assembly: AssemblyFileVersion("1.5.0")]
apache-2.0
C#
28dfd90ad636a94147bd75559a5d75df0e66f968
Add OldPassword property to the User entity in order to be able to change the password.
devicehive/devicehive-.net,devicehive/devicehive-.net,devicehive/devicehive-.net
src/Client/DeviceHive.Client/Model/User.cs
src/Client/DeviceHive.Client/Model/User.cs
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace DeviceHive.Client { /// <summary> /// Represents enumeration of user roles. /// </summary> public enum UserRole { /// <summary> /// Administrator role. /// </summary> Administrator = 0, /// <summary> /// Client role. /// </summary> Client = 1, } /// <summary> /// Represents a DeviceHive user. /// </summary> public class User { #region Public Properties /// <summary> /// Gets or sets user identifier. /// </summary> public int? Id { get; set; } /// <summary> /// Gets or sets user login. /// </summary> public string Login { get; set; } /// <summary> /// Gets or sets old user password (required when setting a new password). /// </summary> public string OldPassword { get; set; } /// <summary> /// Gets or sets new user password. /// </summary> public string Password { get; set; } /// <summary> /// Gets or sets user role. /// </summary> public UserRole Role { get; set; } /// <summary> /// Gets or sets the list of associated networks. /// </summary> public List<UserNetwork> Networks { get; set; } #endregion } }
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace DeviceHive.Client { /// <summary> /// Represents enumeration of user roles. /// </summary> public enum UserRole { /// <summary> /// Administrator role. /// </summary> Administrator = 0, /// <summary> /// Client role. /// </summary> Client = 1, } /// <summary> /// Represents a DeviceHive user. /// </summary> public class User { #region Public Properties /// <summary> /// Gets or sets user identifier. /// </summary> public int? Id { get; set; } /// <summary> /// Gets or sets user login. /// </summary> public string Login { get; set; } /// <summary> /// Gets or sets user password. /// </summary> public string Password { get; set; } /// <summary> /// Gets or sets user role. /// </summary> public UserRole Role { get; set; } /// <summary> /// Gets or sets the list of associated networks. /// </summary> public List<UserNetwork> Networks { get; set; } #endregion } }
mit
C#
3e16f0b92d20bb979cdfb59865e3ac929aff8e79
Update Program.cs
AlonAmsalem/NLoad
src/Examples/NLoad.Examples.ConsoleApplication/Program.cs
src/Examples/NLoad.Examples.ConsoleApplication/Program.cs
using System; using System.Threading; namespace NLoad.Examples.ConsoleApplication { class Program { static void Main() { var loadTest = NLoad.Test<MyTest>() .WithNumberOfThreads(10) .WithDurationOf(TimeSpan.FromSeconds(10)) .OnHeartbeat((s, e) => Console.WriteLine(e.Throughput)) .Build(); var result = loadTest.Run(); Console.WriteLine("\nTotal Iterations: {0}", result.TotalIterations); Console.WriteLine("Total Runtime: {0}", result.TotalRuntime); Console.WriteLine("Average Throughput: {0}", result.AverageThroughput); Console.WriteLine("Average Response Time: {0}", result.AverageResponseTime); Console.WriteLine("\nPress <Enter> to terminate."); Console.ReadLine(); } } /// Test Implementation class MyTest : ITest { public void Initialize() { } public TestResult Execute() { Thread.Sleep(1000); return TestResult.Success; } } }
using System; using System.Threading; namespace NLoad.Examples.ConsoleApplication { class Program { static void Main() { var loadTest = NLoad.Test<MyTest>() .WithNumberOfThreads(10) .WithDurationOf(TimeSpan.FromSeconds(10)) .OnHeartbeat((s, e) => Console.WriteLine(e.Throughput)) .Build(); var result = loadTest.Run(); Console.WriteLine("Total Iterations: {0}", result.TotalIterations); Console.WriteLine("\nTotal Runtime: {0}", result.TotalRuntime); Console.WriteLine("Average Throughput: {0}", result.AverageThroughput); Console.WriteLine("Average Response Time: {0}", result.AverageResponseTime); Console.WriteLine("\nPress <Enter> to terminate."); Console.ReadLine(); } } /// Test Implementation class MyTest : ITest { public void Initialize() { } public TestResult Execute() { Thread.Sleep(1000); return TestResult.Success; } } }
apache-2.0
C#
19bc458f43e1dba93461193b02adeec1045c0660
Change DownloadDataFlow to support Files only.
ComputerWorkware/TeamCityApi
src/TeamCityConsole/DownloadDataFlow.cs
src/TeamCityConsole/DownloadDataFlow.cs
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using NLog; using TeamCityConsole.Commands; using TeamCityConsole.Utils; using File = TeamCityApi.Domain.File; namespace TeamCityConsole { public interface IDownloadDataFlow { Task Completion { get; } void Complete(); void Download(PathFilePair pair); } public class DownloadDataFlow : IDownloadDataFlow { private static readonly Logger Log = LogManager.GetCurrentClassLogger(); private readonly IFileDownloader _downloader; ActionBlock<PathFilePair> _initialBroadcast; public Task Completion { get { return _initialBroadcast.Completion; } } public DownloadDataFlow(IFileDownloader downloader) { _downloader = downloader; SetupDataFlow(); } public void Complete() { _initialBroadcast.Complete(); } public void Download(PathFilePair pair) { _initialBroadcast.Post(pair); } private void SetupDataFlow() { var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8 }; _initialBroadcast = new ActionBlock<PathFilePair>(pair => HandleFileDownload(pair), options); } private void HandleFileDownload(PathFilePair pair) { Log.Debug("Downloading {0} to {1}", pair.File.Name, pair.Path); _downloader.Download(pair.Path, pair.File); } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using NLog; using TeamCityConsole.Commands; using TeamCityConsole.Utils; using File = TeamCityApi.Domain.File; namespace TeamCityConsole { public interface IDownloadDataFlow { Task Completion { get; } void Complete(); void Download(PathFilePair pair); } public class DownloadDataFlow : IDownloadDataFlow { private static readonly Logger Log = LogManager.GetCurrentClassLogger(); private readonly IFileDownloader _downloader; BroadcastBlock<PathFilePair> _initialBroadcast; public Task Completion { get { return _initialBroadcast.Completion; } } public DownloadDataFlow(IFileDownloader downloader) { _downloader = downloader; SetupDataFlow(); } public void Complete() { _initialBroadcast.Complete(); } public void Download(PathFilePair pair) { _initialBroadcast.Post(pair); } private void SetupDataFlow() { var options = new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 8 }; _initialBroadcast = new BroadcastBlock<PathFilePair>(pair => pair, options); var directoryTransformation = new TransformManyBlock<PathFilePair, PathFilePair>(pair => HandleDirectory(pair), options); var downloadActionBlock = new ActionBlock<PathFilePair>(pair => HandleFileDownload(pair), options); _initialBroadcast.LinkTo(directoryTransformation, pair => pair.File.HasChildren); directoryTransformation.LinkTo(_initialBroadcast); _initialBroadcast.LinkTo(downloadActionBlock, pair => pair.File.HasContent); } private IEnumerable<PathFilePair> HandleDirectory(PathFilePair pair) { List<File> children = pair.File.GetChildren().Result; IEnumerable<PathFilePair> childPairs = children.Select(x => new PathFilePair { File = x, Path = Path.Combine(pair.Path, x.Name) }); return childPairs; } private void HandleFileDownload(PathFilePair pair) { Log.Debug("Downloading {0} to {1}", pair.File.Name, pair.Path); _downloader.Download(pair.Path, pair.File); } } }
mit
C#
6d8826dcc143c73d1d9cbb38c480a8b163b94e6b
Make MartenIgnore public
mysticmind/marten,mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,mysticmind/marten,ericgreenmix/marten,mysticmind/marten
src/Marten/Events/CodeGeneration/MartenIgnoreAttribute.cs
src/Marten/Events/CodeGeneration/MartenIgnoreAttribute.cs
using System; namespace Marten.Events.CodeGeneration { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] public class MartenIgnoreAttribute: Attribute { } }
using System; namespace Marten.Events.CodeGeneration { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property)] internal class MartenIgnoreAttribute: Attribute { } }
mit
C#
d2d3be78b614427c7c80f1426c5fceb8772025a5
remove call out of collector ctor
mdsol/Medidata.ZipkinTracerModule
src/Medidata.ZipkinTracer.Core.Collector/SpanCollector.cs
src/Medidata.ZipkinTracer.Core.Collector/SpanCollector.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thrift; namespace Medidata.ZipkinTracer.Core.Collector { public class SpanCollector { private const int MAX_QUEUE_SIZE = 100; internal static BlockingCollection<Span> spanQueue; internal SpanProcessor spanProcessor; internal IClientProvider clientProvider; public SpanCollector(IClientProvider clientProvider, int maxProcessorBatchSize) { if ( spanQueue == null) { spanQueue = new BlockingCollection<Span>(MAX_QUEUE_SIZE); } this.clientProvider = clientProvider; spanProcessor = new SpanProcessor(spanQueue, clientProvider, maxProcessorBatchSize); } public virtual void Collect(Span span) { spanQueue.Add(span); } public virtual void Start() { spanProcessor.Start(); } public virtual void Stop() { spanProcessor.Stop(); clientProvider.Close(); } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Thrift; namespace Medidata.ZipkinTracer.Core.Collector { public class SpanCollector { private const int MAX_QUEUE_SIZE = 100; internal static BlockingCollection<Span> spanQueue; internal SpanProcessor spanProcessor; internal IClientProvider clientProvider; public SpanCollector(IClientProvider clientProvider, int maxProcessorBatchSize) { if ( spanQueue == null) { spanQueue = new BlockingCollection<Span>(MAX_QUEUE_SIZE); } this.clientProvider = clientProvider; try { clientProvider.Setup(); } catch (TException tEx) { clientProvider.Close(); throw tEx; } spanProcessor = new SpanProcessor(spanQueue, clientProvider, maxProcessorBatchSize); } public virtual void Collect(Span span) { spanQueue.Add(span); } public virtual void Start() { spanProcessor.Start(); } public virtual void Stop() { spanProcessor.Stop(); clientProvider.Close(); } } }
mit
C#
0f08fd3e728591edf3e1b248145366aefaf93515
Make ApplicationNavigatorForm working.
maraf/Money,maraf/Money,maraf/Money
src/Money.UI/Views/Navigation/ApplicationNavigatorForm.cs
src/Money.UI/Views/Navigation/ApplicationNavigatorForm.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; namespace Money.Views.Navigation { internal class ApplicationNavigatorForm : PageNavigatorForm { private readonly Template template; public ApplicationNavigatorForm(Template template, Type pageType, object parameter) : base(template.ContentFrame, pageType, parameter) { this.template = template; } public override void Show() { base.Show(); template.ShowLoading(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; namespace Money.Views.Navigation { internal class ApplicationNavigatorForm : PageNavigatorForm { private readonly Template template; public ApplicationNavigatorForm(Template template, Type pageType, object parameter) : base(template.ContentFrame, pageType, parameter) { } public override void Show() { base.Show(); template.ShowLoading(); } } }
apache-2.0
C#
636fb96d013861c0cdc2e272f18b7467877e7cc9
Add space for readability in the exception messages.
SQLStreamStore/SQLStreamStore,damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore
src/SqlStreamStore/Infrastructure/EnsureThatExtensions.cs
src/SqlStreamStore/Infrastructure/EnsureThatExtensions.cs
namespace SqlStreamStore.Infrastructure { using SqlStreamStore.Imports.Ensure.That; internal static class EnsureThatExtensions { internal static Param<string> DoesNotStartWith(this Param<string> param, string s) { if (!Ensure.IsActive) { return param; } if (param.Value.StartsWith(s)) { throw ExceptionFactory.CreateForParamValidation(param, $"Must not start with {s}"); } return param; } } }
namespace SqlStreamStore.Infrastructure { using SqlStreamStore.Imports.Ensure.That; internal static class EnsureThatExtensions { internal static Param<string> DoesNotStartWith(this Param<string> param, string s) { if (!Ensure.IsActive) { return param; } if (param.Value.StartsWith(s)) { throw ExceptionFactory.CreateForParamValidation(param, $"Must not start with{s}"); } return param; } } }
mit
C#
44ddf7acef2a13d47b282f32a59b8a44d17eae13
Add extra check (#12075)
robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS
src/Umbraco.Web.Common/Extensions/ControllerExtensions.cs
src/Umbraco.Web.Common/Extensions/ControllerExtensions.cs
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace Umbraco.Extensions { public static class ControllerExtensions { /// <summary> /// Runs the authentication process /// </summary> /// <param name="controller"></param> /// <returns></returns> public static async Task<AuthenticateResult> AuthenticateBackOfficeAsync(this ControllerBase controller) { return await controller.HttpContext.AuthenticateBackOfficeAsync(); } /// <summary> /// Return the controller name from the controller type /// </summary> /// <param name="controllerType"></param> /// <returns></returns> public static string GetControllerName(Type controllerType) { if (!controllerType.Name.EndsWith("Controller") && !controllerType.Name.EndsWith("Controller`1")) { throw new InvalidOperationException("The controller type " + controllerType + " does not follow conventions, MVC Controller class names must be suffixed with the term 'Controller'"); } return controllerType.Name.Substring(0, controllerType.Name.LastIndexOf("Controller")); } /// <summary> /// Return the controller name from the controller instance /// </summary> /// <param name="controllerInstance"></param> /// <returns></returns> public static string GetControllerName(this Controller controllerInstance) { return GetControllerName(controllerInstance.GetType()); } /// <summary> /// Return the controller name from the controller type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <remarks></remarks> public static string GetControllerName<T>() { return GetControllerName(typeof(T)); } } }
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace Umbraco.Extensions { public static class ControllerExtensions { /// <summary> /// Runs the authentication process /// </summary> /// <param name="controller"></param> /// <returns></returns> public static async Task<AuthenticateResult> AuthenticateBackOfficeAsync(this ControllerBase controller) { return await controller.HttpContext.AuthenticateBackOfficeAsync(); } /// <summary> /// Return the controller name from the controller type /// </summary> /// <param name="controllerType"></param> /// <returns></returns> public static string GetControllerName(Type controllerType) { if (!controllerType.Name.EndsWith("Controller")) { throw new InvalidOperationException("The controller type " + controllerType + " does not follow conventions, MVC Controller class names must be suffixed with the term 'Controller'"); } return controllerType.Name.Substring(0, controllerType.Name.LastIndexOf("Controller")); } /// <summary> /// Return the controller name from the controller instance /// </summary> /// <param name="controllerInstance"></param> /// <returns></returns> public static string GetControllerName(this Controller controllerInstance) { return GetControllerName(controllerInstance.GetType()); } /// <summary> /// Return the controller name from the controller type /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <remarks></remarks> public static string GetControllerName<T>() { return GetControllerName(typeof(T)); } } }
mit
C#
7acdba4975f61b4cd82286da623fbf9b6b1a00ce
fix conventions
AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp
src/AngleSharp/Dom/Events/ErrorEvent.cs
src/AngleSharp/Dom/Events/ErrorEvent.cs
namespace AngleSharp.Dom.Events { using AngleSharp.Attributes; using System; /// <summary> /// Represents the error event arguments. /// </summary> [DomName("ErrorEvent")] public class ErrorEvent : Event { /// <summary> /// Gets the message describing the error. /// </summary> [DomName("message")] public String Message { get { return Error.Message; } } /// <summary> /// Gets the filename where the error occurred. /// </summary> [DomName("filename")] public String FileName { get; private set; } /// <summary> /// Gets the line number of the error. /// </summary> [DomName("lineno")] public Int32 Line { get; private set; } /// <summary> /// Gets the column number of the error. /// </summary> [DomName("colno")] public Int32 Column { get; private set; } /// <summary> /// Gets the exception describing the error. /// </summary> [DomName("error")] public Exception Error { get; private set; } public void Init(String filename, Int32 line, Int32 column, Exception error) { FileName = filename; Line = line; Column = column; Error = error; } } }
namespace AngleSharp.Dom.Events { using AngleSharp.Attributes; using System; /// <summary> /// Represents the error event arguments. /// </summary> [DomName("ErrorEvent")] public class ErrorEvent : Event { /// <summary> /// Gets the message describing the error. /// </summary> [DomName("message")] public String Message { get { return Error.Message; } } /// <summary> /// Gets the filename where the error occurred. /// </summary> [DomName("filename")] public String FileName { get; private set; } /// <summary> /// Gets the line number of the error. /// </summary> [DomName("lineno")] public Int32 Line { get; private set; } /// <summary> /// Gets the column number of the error. /// </summary> [DomName("colno")] public Int32 Column { get; private set; } /// <summary> /// Gets the exception describing the error. /// </summary> [DomName("error")] public Exception Error { get; private set; } public void Init(string filename, int line, int column, Exception error) { FileName = filename; Line = line; Column = column; Error = error; } } }
mit
C#
7301a31737cc89ad7fb1cc5f7002d228c52459f6
Handle null content
civicsource/http,civicsource/webapi-utils
http/GZipCompressingHandler.cs
http/GZipCompressingHandler.cs
using System; using System.Collections.Immutable; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Archon.Http { /// <summary> /// GZip-compresses requests to save bytes over the wire. /// </summary> public sealed class GZipCompressingHandler : DelegatingHandler { private readonly ImmutableHashSet<HttpMethod> verbs; /// <inheritdoc cref="DelegatingHandler"/> /// <param name="verbsToCompress">A list of HTTP verbs to compress. Generally, only <see cref="HttpMethod.Post"/> and <see cref="HttpMethod.Put"/> are particularly useful.</param> public GZipCompressingHandler(HttpMessageHandler innerHandler, params HttpMethod[] verbsToCompress) : base(innerHandler) { if (verbsToCompress.Length == 0) throw new ArgumentException("Must specify at least one HTTP verb to compress", nameof(verbsToCompress)); verbs = verbsToCompress.ToImmutableHashSet(); } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (verbs.Contains(request.Method) && request.Content != null) request.Content = new GZipHttpContent(request.Content); return base.SendAsync(request, cancellationToken); } } public sealed class GZipHttpContent : HttpContent { private readonly HttpContent originalContent; public GZipHttpContent(HttpContent content) { originalContent = content; foreach (var header in originalContent.Headers) { Headers.TryAddWithoutValidation(header.Key, header.Value); } Headers.ContentEncoding.Add("gzip"); } protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { using (var gzip = new GZipStream(stream, CompressionLevel.Fastest, true)) { await originalContent.CopyToAsync(gzip); } } protected override bool TryComputeLength(out long length) { length = -1; return false; } } }
using System; using System.Collections.Immutable; using System.IO; using System.IO.Compression; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace Archon.Http { /// <summary> /// GZip-compresses requests to save bytes over the wire. /// </summary> public sealed class GZipCompressingHandler : DelegatingHandler { private readonly ImmutableHashSet<HttpMethod> verbs; /// <inheritdoc cref="DelegatingHandler"/> /// <param name="verbsToCompress">A list of HTTP verbs to compress. Generally, only <see cref="HttpMethod.Post"/> and <see cref="HttpMethod.Put"/> are particularly useful.</param> public GZipCompressingHandler(HttpMessageHandler innerHandler, params HttpMethod[] verbsToCompress) : base(innerHandler) { if (verbsToCompress.Length == 0) throw new ArgumentException("Must specify at least one HTTP verb to compress", nameof(verbsToCompress)); verbs = verbsToCompress.ToImmutableHashSet(); } protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (verbs.Contains(request.Method)) request.Content = new GZipHttpContent(request.Content); return base.SendAsync(request, cancellationToken); } } public sealed class GZipHttpContent : HttpContent { private readonly HttpContent originalContent; public GZipHttpContent(HttpContent content) { originalContent = content; foreach (var header in originalContent.Headers) { Headers.TryAddWithoutValidation(header.Key, header.Value); } Headers.ContentEncoding.Add("gzip"); } protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) { using (var gzip = new GZipStream(stream, CompressionLevel.Fastest, true)) { await originalContent.CopyToAsync(gzip); } } protected override bool TryComputeLength(out long length) { length = -1; return false; } } }
mit
C#
f6290f0b8acc14b3cc1fb2e5a3f0bef7b98d16a1
Update assembly version
ironfede/openmcdf
sources/OpenMcdf/Properties/AssemblyInfo.cs
sources/OpenMcdf/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("OpenMcdf")] [assembly: AssemblyDescription("MS Compound File Storage .NET Implementation")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Federico Blaseotto")] [assembly: AssemblyProduct("OpenMcdf 2.1")] [assembly: AssemblyCopyright("Copyright © 2010-2018, Federico Blaseotto")] [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("ffc13791-ddf0-4d14-bd64-575aba119190")] // 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("2.1.4.23498")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Test,PublicKey=002400000480000094000000060200000024000052534131000400000100010085b50cbc1e40df696f8c30eaafc59a01e22303cb038fc832289b2c393f908a65c9aaa0d28026a47c6e5f85cc236f0735bea17236dbaaf91fea0003ddc1bb9c4cd318c5b855e7ef5877df5a7fc8394ee747d3573b69622e045837d546befb2fc13257e984db53a73dd59254a9a1d3c99a8ca6876c91304ea96899ac06a88d7bc6")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Extensions,PublicKey=002400000480000094000000060200000024000052534131000400000100010085b50cbc1e40df696f8c30eaafc59a01e22303cb038fc832289b2c393f908a65c9aaa0d28026a47c6e5f85cc236f0735bea17236dbaaf91fea0003ddc1bb9c4cd318c5b855e7ef5877df5a7fc8394ee747d3573b69622e045837d546befb2fc13257e984db53a73dd59254a9a1d3c99a8ca6876c91304ea96899ac06a88d7bc6")]
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("OpenMcdf")] [assembly: AssemblyDescription("MS Compound File Storage .NET Implementation")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Federico Blaseotto")] [assembly: AssemblyProduct("OpenMcdf 2.1")] [assembly: AssemblyCopyright("Copyright © 2010-2016, Federico Blaseotto")] [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("ffc13791-ddf0-4d14-bd64-575aba119190")] // 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("2.1.3.34730")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Test,PublicKey=002400000480000094000000060200000024000052534131000400000100010085b50cbc1e40df696f8c30eaafc59a01e22303cb038fc832289b2c393f908a65c9aaa0d28026a47c6e5f85cc236f0735bea17236dbaaf91fea0003ddc1bb9c4cd318c5b855e7ef5877df5a7fc8394ee747d3573b69622e045837d546befb2fc13257e984db53a73dd59254a9a1d3c99a8ca6876c91304ea96899ac06a88d7bc6")] [assembly: System.Runtime.CompilerServices.InternalsVisibleTo("OpenMcdf.Extensions,PublicKey=002400000480000094000000060200000024000052534131000400000100010085b50cbc1e40df696f8c30eaafc59a01e22303cb038fc832289b2c393f908a65c9aaa0d28026a47c6e5f85cc236f0735bea17236dbaaf91fea0003ddc1bb9c4cd318c5b855e7ef5877df5a7fc8394ee747d3573b69622e045837d546befb2fc13257e984db53a73dd59254a9a1d3c99a8ca6876c91304ea96899ac06a88d7bc6")]
mpl-2.0
C#
2c04a2e0267c49c3d24c601c2064d036c9b30ed8
Declare Parser as a delegate instead of an interface, temporarily causing many build errors.
plioi/parsley
src/Parsley/Parser.cs
src/Parsley/Parser.cs
namespace Parsley; public delegate Reply<T> Parser<out T>(Text input);
namespace Parsley; public interface Parser<out T> { Reply<T> Parse(Text input); }
mit
C#
e4d03eed39bcdf9b071ffaafba11e081be090548
build fix
ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET,ElectronNET/Electron.NET
ElectronNET.WebApp/Controllers/ShortcutsController.cs
ElectronNET.WebApp/Controllers/ShortcutsController.cs
using ElectronNET.API; using ElectronNET.API.Entities; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ElectronNET.WebApp.Controllers { public class ShortcutsController : Controller { public IActionResult Index() { if (HybridSupport.IsElectronActive) { Electron.GlobalShortcut.Register("CommandOrControl+Alt+K", async () => { var options = new MessageBoxOptions("You pressed the registered global shortcut keybinding.") { Type = MessageBoxType.info, Title = "Success!" }; await Electron.Dialog.ShowMessageBoxAsync(options); }); Electron.App.WillQuit += arg => Task.Run(() => Electron.GlobalShortcut.UnregisterAll()); } return View(); } } }
using ElectronNET.API; using ElectronNET.API.Entities; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace ElectronNET.WebApp.Controllers { public class ShortcutsController : Controller { public IActionResult Index() { if (HybridSupport.IsElectronActive) { Electron.GlobalShortcut.Register("CommandOrControl+Alt+K", async () => { var options = new MessageBoxOptions("You pressed the registered global shortcut keybinding.") { Type = MessageBoxType.info, Title = "Success!" }; await Electron.Dialog.ShowMessageBoxAsync(options); }); Electron.App.WillQuit += () => Task.Run(() => Electron.GlobalShortcut.UnregisterAll()); } return View(); } } }
mit
C#
6253b5529f2f0e60a4c6c3eb97b6b8ba770dc410
Update API version response
archrival/Resonance
src/Resonance.Subsonic/SubsonicConstants.cs
src/Resonance.Subsonic/SubsonicConstants.cs
namespace Resonance.SubsonicCompat { public static class SubsonicConstants { public const string AlbumNotFound = "Album not found."; public const string ArtistNotFound = "Artist not found."; public const string AuthenticationContext = "AuthenticationContext"; public const string DirectoryNotFound = "Directory not found"; public const string MediaFileNotFound = "Media file not found."; public const string PlaylistNotFound = "Playlist not found."; public const string RequiredParameterIsMissing = "Required parameter is missing."; public const string ServerVersion = "1.16.0"; public const string SongNotFound = "Song not found."; public const string SubsonicQueryParameters = "SubsonicQueryParameters"; public const string UserAlreadyExists = "User already exists."; public const string UserDoesNotExist = "User does not exist."; public const string UserIsNotAuthorizedForTheGivenOperation = "User is not authorized for the given operation."; public const string VideoNotFound = "Video not found."; public const string WrongUsernameOrPassword = "Wrong username or password."; } }
namespace Resonance.SubsonicCompat { public static class SubsonicConstants { public const string AlbumNotFound = "Album not found."; public const string ArtistNotFound = "Artist not found."; public const string AuthenticationContext = "AuthenticationContext"; public const string DirectoryNotFound = "Directory not found"; public const string MediaFileNotFound = "Media file not found."; public const string PlaylistNotFound = "Playlist not found."; public const string RequiredParameterIsMissing = "Required parameter is missing."; public const string ServerVersion = "1.15.0"; public const string SongNotFound = "Song not found."; public const string SubsonicQueryParameters = "SubsonicQueryParameters"; public const string UserAlreadyExists = "User already exists."; public const string UserDoesNotExist = "User does not exist."; public const string UserIsNotAuthorizedForTheGivenOperation = "User is not authorized for the given operation."; public const string VideoNotFound = "Video not found."; public const string WrongUsernameOrPassword = "Wrong username or password."; } }
apache-2.0
C#
039592a9e146f2f21b6f81cb27a2d6bf4362ad74
Initialize AppCommand with an IAppHarborClient
appharbor/appharbor-cli
src/AppHarbor/Commands/AppCommand.cs
src/AppHarbor/Commands/AppCommand.cs
using System; namespace AppHarbor.Commands { public class AppCommand : ICommand { private readonly IAppHarborClient _client; public AppCommand(IAppHarborClient appharborClient) { _client = appharborClient; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
using System; namespace AppHarbor.Commands { public class AppCommand : ICommand { public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
mit
C#
b8cfbde619949d71f48eb4c7a2942ed6a2881259
Make IStatefulJob compilee time error with Obsolete tag as it really isn't used anymore
AlonAmsalem/quartznet,quartznet/quartznet,sean-gilliam/quartznet,quartznet/quartznet,quartznet/quartznet,zhangjunhao/quartznet,quartznet/quartznet,xlgwr/quartznet,RafalSladek/quartznet,huoxudong125/quartznet,sean-gilliam/quartznet,AndreGleichner/quartznet,quartznet/quartznet,andyshao/quartznet,sean-gilliam/quartznet,sean-gilliam/quartznet,sean-gilliam/quartznet,neuronesb/quartznet
src/Quartz/IStatefulJob.cs
src/Quartz/IStatefulJob.cs
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; namespace Quartz { /// <summary> /// A marker interface for <see cref="IJobDetail" /> s that /// wish to have their state maintained between executions. /// </summary> /// <remarks> /// <see cref="IStatefulJob" /> instances follow slightly different rules from /// regular <see cref="IJob" /> instances. The key difference is that their /// associated <see cref="JobDataMap" /> is re-persisted after every /// execution of the job, thus preserving state for the next execution. The /// other difference is that stateful jobs are not allowed to Execute /// concurrently, which means new triggers that occur before the completion of /// the <see cref="IJob.Execute" /> method will be delayed. /// </remarks> /// <seealso cref="DisallowConcurrentExecutionAttribute" /> /// <seealso cref="PersistJobDataAfterExecutionAttribute" /> /// <seealso cref="IJob" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="JobDataMap" /> /// <seealso cref="IScheduler" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Obsolete("Use DisallowConcurrentExecutionAttribute and/or PersistJobDataAfterExecutionAttribute annotations instead.", true)] public interface IStatefulJob : IJob { } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; namespace Quartz { /// <summary> /// A marker interface for <see cref="IJobDetail" /> s that /// wish to have their state maintained between executions. /// </summary> /// <remarks> /// <see cref="IStatefulJob" /> instances follow slightly different rules from /// regular <see cref="IJob" /> instances. The key difference is that their /// associated <see cref="JobDataMap" /> is re-persisted after every /// execution of the job, thus preserving state for the next execution. The /// other difference is that stateful jobs are not allowed to Execute /// concurrently, which means new triggers that occur before the completion of /// the <see cref="IJob.Execute" /> method will be delayed. /// </remarks> /// <seealso cref="DisallowConcurrentExecutionAttribute" /> /// <seealso cref="PersistJobDataAfterExecutionAttribute" /> /// <seealso cref="IJob" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="JobDataMap" /> /// <seealso cref="IScheduler" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> [Obsolete("Use DisallowConcurrentExecutionAttribute and/or PersistJobDataAfterExecutionAttribute annotations instead.")] public interface IStatefulJob : IJob { } }
apache-2.0
C#
b14f2de281a208bf0b6d787fab4d9e12238fa96f
Enable logging
boumenot/Grobid.NET
test/Grobid.Test/GrobidTest.cs
test/Grobid.Test/GrobidTest.cs
using System; using System.IO; using ApprovalTests; using ApprovalTests.Reporters; using FluentAssertions; using Xunit; using Grobid.NET; using org.apache.log4j; using org.grobid.core; namespace Grobid.Test { [UseReporter(typeof(DiffReporter))] public class GrobidTest { static GrobidTest() { BasicConfigurator.configure(); org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR); } [Fact] [Trait("Test", "EndToEnd")] public void ExtractTest() { var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE"); var factory = new GrobidFactory( "grobid.zip", binPath, Directory.GetCurrentDirectory()); var grobid = factory.Create(); var result = grobid.Extract(@"essence-linq.pdf"); result.Should().NotBeEmpty(); Approvals.Verify(result); } [Fact] public void Test() { var x = GrobidModels.NAMES_HEADER; x.name().Should().Be("NAMES_HEADER"); x.toString().Should().Be("name/header"); } } }
using System; using System.IO; using ApprovalTests; using ApprovalTests.Reporters; using FluentAssertions; using Xunit; using Grobid.NET; using org.apache.log4j; using org.grobid.core; namespace Grobid.Test { [UseReporter(typeof(DiffReporter))] public class GrobidTest { static GrobidTest() { // BasicConfigurator.configure(); org.apache.log4j.Logger.getRootLogger().setLevel(Level.ERROR); } [Fact] [Trait("Test", "EndToEnd")] public void ExtractTest() { var binPath = Environment.GetEnvironmentVariable("PDFTOXMLEXE"); var factory = new GrobidFactory( "grobid.zip", binPath, Directory.GetCurrentDirectory()); var grobid = factory.Create(); var result = grobid.Extract(@"essence-linq.pdf"); result.Should().NotBeEmpty(); Approvals.Verify(result); } [Fact] public void Test() { var x = GrobidModels.NAMES_HEADER; x.name().Should().Be("NAMES_HEADER"); x.toString().Should().Be("name/header"); } } }
apache-2.0
C#
425b8d5ba1e308da2714c133893d9433f42f1700
Update test
sakapon/Samples-2017
DrawingSample/BitmapScaleConsole/Program.cs
DrawingSample/BitmapScaleConsole/Program.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.IO; using System.Linq; namespace BitmapScaleConsole { class Program { static void Main(string[] args) { Console.WriteLine("Press [Enter] key to start."); Console.ReadLine(); var dirName = $"{DateTime.Now:yyyyMMdd-HHmmss}"; Directory.CreateDirectory(dirName); using (var bitmap = BitmapHelper.GetScreenBitmap(200, 100, 1920, 1080)) { BitmapHelper.SaveImage($@"{dirName}\{dirName}.png", bitmap); BitmapHelper.SaveImage($@"{dirName}\{dirName}.jpg", bitmap); ResizeImageTest_Drawing(dirName, bitmap); ResizeImageTest_Windows(dirName, bitmap); } } static void ResizeImageTest_Drawing(string dirName, Bitmap bitmap) { var modes = Enum.GetValues(typeof(InterpolationMode)) .Cast<InterpolationMode>() .Where(m => m != InterpolationMode.Invalid); foreach (var mode in modes) { using (var resized = BitmapHelper.ResizeImage(bitmap, bitmap.Width / 2, bitmap.Height / 2, mode)) { BitmapHelper.SaveImage($@"{dirName}\{mode}.jpg", resized); } } } static void ResizeImageTest_Windows(string dirName, Bitmap bitmap) { using (var memory = BitmapHelper.ToStream(bitmap)) { var source = System.Windows.Media.Imaging.BitmapFrame.Create(memory); var resized = BitmapHelper2.ResizeImage(source, bitmap.Width / 2, bitmap.Height / 2); BitmapHelper2.SaveImage($@"{dirName}\WPF.png", resized); BitmapHelper2.SaveImage($@"{dirName}\WPF.jpg", resized); } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; using System.Linq; namespace BitmapScaleConsole { class Program { static void Main(string[] args) { Console.WriteLine("Press [Enter] key to start."); Console.ReadLine(); var dirName = $"{DateTime.Now:yyyyMMdd-HHmmss}"; Directory.CreateDirectory(dirName); using (var bitmap = BitmapHelper.GetScreenBitmap(200, 100, 1080, 720)) { bitmap.Save($@"{dirName}\Original.png", ImageFormat.Png); bitmap.Save($@"{dirName}\Original.jpg", ImageFormat.Jpeg); ResizeImageTest_Drawing(dirName, bitmap); ResizeImageTest_Windows(dirName, bitmap); } } static void ResizeImageTest_Drawing(string dirName, Bitmap bitmap) { var modes = Enum.GetValues(typeof(InterpolationMode)) .Cast<InterpolationMode>() .Where(m => m != InterpolationMode.Invalid); foreach (var mode in modes) { using (var resized = BitmapHelper.ResizeImage(bitmap, bitmap.Width / 2, bitmap.Height / 2, mode)) { resized.Save($@"{dirName}\{mode}.jpg", ImageFormat.Jpeg); } } } static void ResizeImageTest_Windows(string dirName, Bitmap bitmap) { using (var memory = BitmapHelper.ToStream(bitmap)) { var source = System.Windows.Media.Imaging.BitmapFrame.Create(memory); var resized = BitmapHelper2.ResizeImage(source, bitmap.Width / 2, bitmap.Height / 2); BitmapHelper2.SaveImage($@"{dirName}\WPF.png", resized); BitmapHelper2.SaveImage($@"{dirName}\WPF.jpg", resized); } } } }
mit
C#
87bc7d0a7a15cbd9808a35bebff1ffb494db1cbe
Reorder enum values
bartlomiejwolk/ActionTrigger
Enums/Mode.cs
Enums/Mode.cs
namespace ActionTrigger { /// <summary> /// A multi-purpose script which causes an action to occur on trigger enter. /// </summary> public enum Mode { UnityEvent, // Invoke UnityAction Message, // Just broadcast the action on to the target Enable, // Enable a component Activate, // Activate the target GameObject Deactivate, // Decativate target GameObject Replace, // replace target with source Animate // Start animation on target } }
namespace ActionTrigger { /// <summary> /// A multi-purpose script which causes an action to occur on trigger enter. /// </summary> public enum Mode { UnityEvent, // Invoke UnityAction Replace, // replace target with source Activate, // Activate the target GameObject Enable, // Enable a component Animate, // Start animation on target Deactivate, // Decativate target GameObject Message // Just broadcast the action on to the target } }
mit
C#
469b13441b70b408e03f8c372e9888794d436525
Fix mistake
UselessToucan/osu,naoey/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu-new,johnneijzen/osu,DrabWeb/osu,DrabWeb/osu,smoogipoo/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,Nabile-Rahmani/osu,Frontear/osuKyzer,ZLima12/osu,ppy/osu,peppy/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,2yangk23/osu,ppy/osu,DrabWeb/osu,UselessToucan/osu,NeoAdonis/osu,naoey/osu,NeoAdonis/osu,naoey/osu,ZLima12/osu,smoogipoo/osu,peppy/osu,peppy/osu,2yangk23/osu
osu.Game/Beatmaps/DifficultyCalculator.cs
osu.Game/Beatmaps/DifficultyCalculator.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Objects; using System.Collections.Generic; using osu.Game.Rulesets.Mods; using osu.Framework.Timing; using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Game.Beatmaps { public abstract class DifficultyCalculator { protected double TimeRate = 1; public abstract double Calculate(Dictionary<string, double> categoryDifficulty = null); } public abstract class DifficultyCalculator<T> : DifficultyCalculator where T : HitObject { protected readonly Beatmap<T> Beatmap; protected readonly Mod[] Mods; protected DifficultyCalculator(Beatmap beatmap, Mod[] mods = null) { Beatmap = CreateBeatmapConverter(beatmap).Convert(beatmap); Mods = mods ?? new Mod[0]; ApplyMods(Mods); PreprocessHitObjects(); } protected virtual void ApplyMods(Mod[] mods) { var clock = new StopwatchClock(); mods.OfType<IApplicableToClock>().ForEach(m => m.ApplyToClock(clock)); TimeRate = clock.Rate; foreach (var mod in Mods.OfType<IApplicableToDifficulty>()) mod.ApplyToDifficulty(Beatmap.BeatmapInfo.BaseDifficulty); foreach (var mod in mods.OfType<IApplicableToHitObject<T>>()) foreach (var obj in Beatmap.HitObjects) mod.ApplyToHitObject(obj); foreach (var h in Beatmap.HitObjects) h.ApplyDefaults(Beatmap.ControlPointInfo, Beatmap.BeatmapInfo.BaseDifficulty); } protected virtual void PreprocessHitObjects() { } protected abstract BeatmapConverter<T> CreateBeatmapConverter(Beatmap beatmap); } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Game.Rulesets.Objects; using System.Collections.Generic; using osu.Game.Rulesets.Mods; using osu.Framework.Timing; using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; namespace osu.Game.Beatmaps { public abstract class DifficultyCalculator { protected double TimeRate = 1; public abstract double Calculate(Dictionary<string, double> categoryDifficulty = null); } public abstract class DifficultyCalculator<T> : DifficultyCalculator where T : HitObject { protected Beatmap<T> Beatmap; protected readonly Mod[] Mods; protected DifficultyCalculator(Beatmap beatmap, Mod[] mods = null) { Beatmap = CreateBeatmapConverter(beatmap).Convert(beatmap); Mods = mods ?? new Mod[0]; ApplyMods(Mods); PreprocessHitObjects(); } protected virtual void ApplyMods(Mod[] mods) { var clock = new StopwatchClock(); mods.OfType<IApplicableToClock>().ForEach(m => m.ApplyToClock(clock)); TimeRate = clock.Rate; foreach (var mod in Mods.OfType<IApplicableToDifficulty>()) mod.ApplyToDifficulty(Beatmap.BeatmapInfo.BaseDifficulty); foreach (var mod in mods.OfType<IApplicableToHitObject<T>>()) foreach (var obj in Beatmap.HitObjects) mod.ApplyToHitObject(obj); foreach (var h in Beatmap.HitObjects) h.ApplyDefaults(Beatmap.ControlPointInfo, Beatmap.BeatmapInfo.BaseDifficulty); } protected virtual void PreprocessHitObjects() { } protected abstract BeatmapConverter<T> CreateBeatmapConverter(Beatmap beatmap); } }
mit
C#
ca08fce5b7438401f42623da86acae90c0ee09ea
Work around problem in casting int to double.
SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,OronDF343/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,jkoritzinsky/Avalonia,kekekeks/Perspex,wieslawsoltes/Perspex,bbqchickenrobot/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,tshcherban/Perspex,DavidKarlas/Perspex,jkoritzinsky/Avalonia,MrDaedra/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,susloparovdenis/Perspex,SuperJMN/Avalonia,wieslawsoltes/Perspex,MrDaedra/Avalonia,danwalmsley/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,sagamors/Perspex,SuperJMN/Avalonia,susloparovdenis/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,kekekeks/Perspex,SuperJMN/Avalonia,ncarrillo/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,akrisiun/Perspex,punker76/Perspex,susloparovdenis/Avalonia,jazzay/Perspex
Perspex.Themes.Default/GridSplitterStyle.cs
Perspex.Themes.Default/GridSplitterStyle.cs
// ----------------------------------------------------------------------- // <copyright file="GridSplitterStyle.cs" company="Steven Kirk"> // Copyright 2014 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Themes.Default { using Perspex.Controls; using Perspex.Styling; using System.Linq; public class GridSplitterStyle : Styles { public GridSplitterStyle() { this.AddRange(new[] { new Style(x => x.OfType<GridSplitter>()) { Setters = new[] { new Setter(GridSplitter.TemplateProperty, ControlTemplate.Create<GridSplitter>(this.Template)), new Setter(GridSplitter.WidthProperty, 4.0), }, }, }); } private Control Template(GridSplitter control) { Border border = new Border { [~Border.BackgroundProperty] = control[~GridSplitter.BackgroundProperty], }; return border; } } }
// ----------------------------------------------------------------------- // <copyright file="GridSplitterStyle.cs" company="Steven Kirk"> // Copyright 2014 MIT Licence. See licence.md for more information. // </copyright> // ----------------------------------------------------------------------- namespace Perspex.Themes.Default { using System.Linq; using Perspex.Controls; using Perspex.Controls.Presenters; using Perspex.Media; using Perspex.Styling; public class GridSplitterStyle : Styles { public GridSplitterStyle() { this.AddRange(new[] { new Style(x => x.OfType<GridSplitter>()) { Setters = new[] { new Setter(GridSplitter.TemplateProperty, ControlTemplate.Create<GridSplitter>(this.Template)), new Setter(GridSplitter.WidthProperty, 4), }, }, }); } private Control Template(GridSplitter control) { Border border = new Border { [~Border.BackgroundProperty] = control[~GridSplitter.BackgroundProperty], }; return border; } } }
mit
C#
2b6caf9b650fd5cfc5af4e168d1d794322ceb4a8
Fix duplicate code in setting default logic
ppy/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipoo/osu,UselessToucan/osu
osu.Game/Configuration/SessionStatics.cs
osu.Game/Configuration/SessionStatics.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Bindables; using osu.Game.Graphics.UserInterface; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays; namespace osu.Game.Configuration { /// <summary> /// Stores global per-session statics. These will not be stored after exiting the game. /// </summary> public class SessionStatics : InMemoryConfigManager<Static> { protected override void InitialiseDefaults() => ResetValues(); public void ResetValues() { ensureDefault(SetDefault(Static.LoginOverlayDisplayed, false)); ensureDefault(SetDefault(Static.MutedAudioNotificationShownOnce, false)); ensureDefault(SetDefault(Static.LowBatteryNotificationShownOnce, false)); ensureDefault(SetDefault(Static.LastHoverSoundPlaybackTime, (double?)null)); ensureDefault(SetDefault<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null)); } private void ensureDefault<T>(Bindable<T> bindable) => bindable.SetDefault(); } public enum Static { LoginOverlayDisplayed, MutedAudioNotificationShownOnce, LowBatteryNotificationShownOnce, /// <summary> /// Info about seasonal backgrounds available fetched from API - see <see cref="APISeasonalBackgrounds"/>. /// Value under this lookup can be <c>null</c> if there are no backgrounds available (or API is not reachable). /// </summary> SeasonalBackgrounds, /// <summary> /// The last playback time in milliseconds of a hover sample (from <see cref="HoverSounds"/>). /// Used to debounce hover sounds game-wide to avoid volume saturation, especially in scrolling views with many UI controls like <see cref="SettingsOverlay"/>. /// </summary> LastHoverSoundPlaybackTime } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Graphics.UserInterface; using osu.Game.Online.API.Requests.Responses; using osu.Game.Overlays; namespace osu.Game.Configuration { /// <summary> /// Stores global per-session statics. These will not be stored after exiting the game. /// </summary> public class SessionStatics : InMemoryConfigManager<Static> { protected override void InitialiseDefaults() { SetDefault(Static.LoginOverlayDisplayed, false); SetDefault(Static.MutedAudioNotificationShownOnce, false); SetDefault(Static.LowBatteryNotificationShownOnce, false); SetDefault(Static.LastHoverSoundPlaybackTime, (double?)null); SetDefault<APISeasonalBackgrounds>(Static.SeasonalBackgrounds, null); } public void ResetValues() { GetOriginalBindable<bool>(Static.LoginOverlayDisplayed).SetDefault(); GetOriginalBindable<bool>(Static.MutedAudioNotificationShownOnce).SetDefault(); GetOriginalBindable<bool>(Static.LowBatteryNotificationShownOnce).SetDefault(); GetOriginalBindable<double?>(Static.LastHoverSoundPlaybackTime).SetDefault(); GetOriginalBindable<APISeasonalBackgrounds>(Static.SeasonalBackgrounds).SetDefault(); } } public enum Static { LoginOverlayDisplayed, MutedAudioNotificationShownOnce, LowBatteryNotificationShownOnce, /// <summary> /// Info about seasonal backgrounds available fetched from API - see <see cref="APISeasonalBackgrounds"/>. /// Value under this lookup can be <c>null</c> if there are no backgrounds available (or API is not reachable). /// </summary> SeasonalBackgrounds, /// <summary> /// The last playback time in milliseconds of a hover sample (from <see cref="HoverSounds"/>). /// Used to debounce hover sounds game-wide to avoid volume saturation, especially in scrolling views with many UI controls like <see cref="SettingsOverlay"/>. /// </summary> LastHoverSoundPlaybackTime } }
mit
C#
b6b050d5e9662155924c3dfa5c41a22a7fbeb1cd
Add sample path to the lookup names
ZLima12/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,johnneijzen/osu,ppy/osu,peppy/osu,2yangk23/osu,smoogipoo/osu,UselessToucan/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,EVAST9919/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,peppy/osu-new,EVAST9919/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu
osu.Game/Storyboards/StoryboardSample.cs
osu.Game/Storyboards/StoryboardSample.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Storyboards.Drawables; namespace osu.Game.Storyboards { public class StoryboardSampleInfo : IStoryboardElement, ISampleInfo { public string Path { get; } public bool IsDrawable => true; public double StartTime { get; } public int Volume { get; } public IEnumerable<string> LookupNames => new[] { // Try first with the full name, then attempt with no path Path, System.IO.Path.ChangeExtension(Path, null), }; public StoryboardSampleInfo(string path, double time, int volume) { Path = path; StartTime = time; Volume = volume; } public Drawable CreateDrawable() => new DrawableStoryboardSample(this); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Audio; using osu.Game.Storyboards.Drawables; namespace osu.Game.Storyboards { public class StoryboardSampleInfo : IStoryboardElement, ISampleInfo { public string Path { get; } public bool IsDrawable => true; public double StartTime { get; } public int Volume { get; } public StoryboardSampleInfo(string path, double time, int volume) { Path = path; StartTime = time; Volume = volume; } public Drawable CreateDrawable() => new DrawableStoryboardSample(this); } }
mit
C#
834e316f7a51971b87880a0b148c2f54f11f9706
Correct the spelling of 'EnableEndpointRouting' (#13655)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.cs
src/Analyzers/Analyzers/src/StartupAnalyzer.Diagnostics.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.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.AspNetCore.Analyzers { public partial class StartupAnalyzer : DiagnosticAnalyzer { internal static class Diagnostics { public static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics; static Diagnostics() { SupportedDiagnostics = ImmutableArray.Create<DiagnosticDescriptor>(new[] { // ASP BuildServiceProviderShouldNotCalledInConfigureServicesMethod, // MVC UnsupportedUseMvcWithEndpointRouting, }); } internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor( "ASP0000", "Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'", "Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.", "Design", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/AA5k895"); internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor( "MVC1005", "Cannot use UseMvc with Endpoint Routing.", "Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRouting = false' inside '{1}'.", "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/YJggeFn"); } } }
// 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.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.AspNetCore.Analyzers { public partial class StartupAnalyzer : DiagnosticAnalyzer { internal static class Diagnostics { public static readonly ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics; static Diagnostics() { SupportedDiagnostics = ImmutableArray.Create<DiagnosticDescriptor>(new[] { // ASP BuildServiceProviderShouldNotCalledInConfigureServicesMethod, // MVC UnsupportedUseMvcWithEndpointRouting, }); } internal readonly static DiagnosticDescriptor BuildServiceProviderShouldNotCalledInConfigureServicesMethod = new DiagnosticDescriptor( "ASP0000", "Do not call 'IServiceCollection.BuildServiceProvider' in 'ConfigureServices'", "Calling 'BuildServiceProvider' from application code results in an additional copy of singleton services being created. Consider alternatives such as dependency injecting services as parameters to 'Configure'.", "Design", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/AA5k895"); internal readonly static DiagnosticDescriptor UnsupportedUseMvcWithEndpointRouting = new DiagnosticDescriptor( "MVC1005", "Cannot use UseMvc with Endpoint Routing.", "Using '{0}' to configure MVC is not supported while using Endpoint Routing. To continue using '{0}', please set 'MvcOptions.EnableEndpointRounting = false' inside '{1}'.", "Usage", DiagnosticSeverity.Warning, isEnabledByDefault: true, helpLinkUri: "https://aka.ms/YJggeFn"); } } }
apache-2.0
C#
d60e2ae5d84ea8004e1adcd9a6dfc6d7008a2b46
Update UaxEmailUrlTokenizer.cs
LeoYao/elasticsearch-net,mac2000/elasticsearch-net,junlapong/elasticsearch-net,KodrAus/elasticsearch-net,jonyadamit/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,mac2000/elasticsearch-net,adam-mccoy/elasticsearch-net,abibell/elasticsearch-net,TheFireCookie/elasticsearch-net,Grastveit/NEST,robrich/elasticsearch-net,wawrzyn/elasticsearch-net,ststeiger/elasticsearch-net,UdiBen/elasticsearch-net,alanprot/elasticsearch-net,geofeedia/elasticsearch-net,DavidSSL/elasticsearch-net,faisal00813/elasticsearch-net,robrich/elasticsearch-net,joehmchan/elasticsearch-net,LeoYao/elasticsearch-net,gayancc/elasticsearch-net,tkirill/elasticsearch-net,RossLieberman/NEST,alanprot/elasticsearch-net,SeanKilleen/elasticsearch-net,faisal00813/elasticsearch-net,gayancc/elasticsearch-net,cstlaurent/elasticsearch-net,amyzheng424/elasticsearch-net,jonyadamit/elasticsearch-net,DavidSSL/elasticsearch-net,TheFireCookie/elasticsearch-net,geofeedia/elasticsearch-net,tkirill/elasticsearch-net,joehmchan/elasticsearch-net,wawrzyn/elasticsearch-net,joehmchan/elasticsearch-net,amyzheng424/elasticsearch-net,abibell/elasticsearch-net,alanprot/elasticsearch-net,azubanov/elasticsearch-net,SeanKilleen/elasticsearch-net,adam-mccoy/elasticsearch-net,starckgates/elasticsearch-net,LeoYao/elasticsearch-net,tkirill/elasticsearch-net,wawrzyn/elasticsearch-net,azubanov/elasticsearch-net,SeanKilleen/elasticsearch-net,elastic/elasticsearch-net,Grastveit/NEST,geofeedia/elasticsearch-net,UdiBen/elasticsearch-net,junlapong/elasticsearch-net,robertlyson/elasticsearch-net,robrich/elasticsearch-net,RossLieberman/NEST,KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,amyzheng424/elasticsearch-net,elastic/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,cstlaurent/elasticsearch-net,TheFireCookie/elasticsearch-net,robertlyson/elasticsearch-net,CSGOpenSource/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,gayancc/elasticsearch-net,ststeiger/elasticsearch-net,DavidSSL/elasticsearch-net,ststeiger/elasticsearch-net,abibell/elasticsearch-net,Grastveit/NEST,robertlyson/elasticsearch-net,starckgates/elasticsearch-net,alanprot/elasticsearch-net,mac2000/elasticsearch-net,jonyadamit/elasticsearch-net,azubanov/elasticsearch-net,junlapong/elasticsearch-net,faisal00813/elasticsearch-net,starckgates/elasticsearch-net
src/Nest/Domain/Analysis/Tokenizer/UaxEmailUrlTokenizer.cs
src/Nest/Domain/Analysis/Tokenizer/UaxEmailUrlTokenizer.cs
using System.Collections.Generic; using Newtonsoft.Json; namespace Nest { /// <summary> /// A tokenizer of type uax_url_email which works exactly like the standard tokenizer, but tokenizes emails and urls as single tokens /// </summary> public class UaxEmailUrlTokenizer : TokenizerBase { public UaxEmailUrlTokenizer() { Type = "uax_url_email"; } /// <summary> /// The maximum token length. If a token is seen that exceeds this length then it is discarded. Defaults to 255. /// </summary> [JsonProperty("max_token_length")] public int? MaximumTokenLength { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace Nest { /// <summary> /// A tokenizer of type uax_url_email which works exactly like the standard tokenizer, but tokenizes emails and urls as single tokens /// </summary> public class UaxEmailUrlTokenizer : TokenizerBase { public UaxEmailUrlTokenizer() { Type = "uax_url_email "; } /// <summary> /// The maximum token length. If a token is seen that exceeds this length then it is discarded. Defaults to 255. /// </summary> [JsonProperty("max_token_length")] public int? MaximumTokenLength { get; set; } } }
apache-2.0
C#
c3499d7faa75a5c266373a1f3290473d005e1acb
Remove irrelevant comment.
bardoloi/fixie,JakeGinnivan/fixie,EliotJones/fixie,bardoloi/fixie,Duohong/fixie,KevM/fixie,fixie/fixie
src/Fixie/Behaviors/CaseBehavior.cs
src/Fixie/Behaviors/CaseBehavior.cs
namespace Fixie.Behaviors { public interface CaseBehavior { void Execute(Case @case, object instance); } }
namespace Fixie.Behaviors { public interface CaseBehavior { void Execute(Case @case, object instance); //comment to demo teamcity } }
mit
C#
0ddc0a7adb67db88a3fc3e978998f0dcf2f18619
edit megacli cs
lesovsky/uber-scripts,lesovsky/uber-scripts,lesovsky/uber-scripts
cheatsheets/megacli.cs
cheatsheets/megacli.cs
MegaCli is a RAID utility For LSI MegaRAID Controllers LD - LogicalDrive PD - PhysicalDrive BBU - Backup Battery Unit # Get Info megacli adpcount # get controllers count megacli adpallinfo aall # get information about all adapters megacli adpbbucmd aall # get BBU information megacli ldinfo lall aall # get LogicalDrives information from all adapters magacli pdlist aall # get PhysicalDrives information from all adapters # Get/Set Logical Drives Properties megacli ldgetprop cache lall aall # get LogicalDrives cache information megacli ldgetprop dskcache lall aall # get PhysicalDrive cache status MegaCli ldinfo lall aall |grep -E '(Virtual Drive|RAID Level|Cache Policy|Access Policy)' # get LD cache and PD cache information megacli ldsetprop WB RA DisDskCache NoCachedBadBBU lall aall # set WriteBack, Adaptive ReadAhead, disable Disk Cache, Disable Cache when bad BBU # Misc megacli adpfwflash -f filename aN # flash adapter firmware from image megacli phyerrorcounters aN # get error counters for physical media # EventLog MegaCli -AdpEventLog -GetEventLogInfo -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetEvents {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetSinceShutdown {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetSinceReboot {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -IncludeDeleted {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetLatest n {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetCCIncon -f <fileName> -LX|-L0,2,5...|-LALL -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -Clear -aN|-a0,1,2|-aALL # Disgnose megacli fwtermlogdsply aall > /tmp/out.log
MegaCli is a RAID utility For LSI MegaRAID Controllers LD - LogicalDrive PD - PhysicalDrive BBU - Backup Battery Unit megacli adpcount # get controllers count megacli adpallinfo aall # get information about all adapters megacli adpbbucmd aall # get BBU information megacli ldinfo lall aall # get LogicalDrives information from all adapters magacli pdlist aall # get PhysicalDrives information from all adapters megacli ldgetprop cache lall aall # get LogicalDrives cache information megacli ldgetprop dskcache lall aall # get PhysicalDrive cache status MegaCli ldinfo lall aall |grep -E '(Virtual Drive|RAID Level|Cache Policy|Access Policy)' # get LD cache and PD cache information megacli ldsetprop WB RA DisDskCache NoCachedBadBBU lall aall # set WriteBack, Adaptive ReadAhead, disable Disk Cache, Disable Cache when bad BBU megacli adpfwflash -f filename aN # flash adapter firmware from image megacli phyerrorcounters aN # get error counters for physical media MegaCli -AdpEventLog -GetEventLogInfo -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetEvents {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetSinceShutdown {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetSinceReboot {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -IncludeDeleted {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetLatest n {-info -warning -critical -fatal} {-f <fileName>} -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -GetCCIncon -f <fileName> -LX|-L0,2,5...|-LALL -aN|-a0,1,2|-aALL MegaCli -AdpEventLog -Clear -aN|-a0,1,2|-aALL
mit
C#
047eb76d43ffa0c9da45a1c66251b926ba97fa80
convert datetime field values to utf
kreeben/resin,kreeben/resin
src/ResinCore/Field.cs
src/ResinCore/Field.cs
using System; using System.Diagnostics; namespace Resin { [DebuggerDisplay("{Value}")] public struct Field { private readonly string _value; public string Value { get { return _value; } } public string Key { get; private set; } public bool Store { get; private set; } public bool Analyze { get; private set; } public bool Index { get; private set; } public Field(string key, object value, bool store = true, bool analyze = true, bool index = true) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("key"); if (value == null) throw new ArgumentNullException("value"); Key = key; Store = store; Analyze = analyze; Index = index; object obj = value; if (value is DateTime) { obj = ((DateTime)value).ToUniversalTime().Ticks.ToString(); } if (obj is string) { _value = obj.ToString(); } else { // Assumes all values that are not DateTime or string must be Int64. // TODO: implement native number indexes var len = long.MaxValue.ToString().Length; _value = obj.ToString().PadLeft(len, '0'); } } } }
using System; using System.Diagnostics; namespace Resin { [DebuggerDisplay("{Value}")] public struct Field { private readonly string _value; public string Value { get { return _value; } } public string Key { get; private set; } public bool Store { get; private set; } public bool Analyze { get; private set; } public bool Index { get; private set; } public Field(string key, object value, bool store = true, bool analyze = true, bool index = true) { if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("key"); if (value == null) throw new ArgumentNullException("value"); Key = key; Store = store; Analyze = analyze; Index = index; if (value is DateTime) { _value = ((DateTime)value).Ticks.ToString(); } else if (value is string) { _value = value.ToString(); } else { // Assumes all values that are not DateTime or string must be Int32. // TODO: implement native number indexes var len = int.MaxValue.ToString().Length; _value = value.ToString().PadLeft(len, '0'); } } } }
mit
C#
75be2e0c9a19a1e7042c377391dfdae29863f6c0
Add clear on mvbaction
markjackmilian/MVB
Mvb/Mvb/Mvb.Core/Components/BinderActions/IBinderActions.cs
Mvb/Mvb/Mvb.Core/Components/BinderActions/IBinderActions.cs
using System; namespace Mvb.Core.Components.BinderActions { public interface IBinderActions { /// <summary> /// Add Action /// </summary> /// <param name="subscriber"></param> /// <param name="action"></param> void AddAction(object subscriber,Action action); /// <summary> /// Remove All Action /// </summary> void Clear(); /// <summary> /// Remove all action for a subscriber /// </summary> /// <param name="subscriber"></param> void Clear(object subscriber); /// <summary> /// Invoke all actions /// </summary> void Invoke(); } public interface IBinderActions<T> { /// <summary> /// Add Action /// </summary> /// <param name="subscriber"></param> /// <param name="action"></param> void AddAction(object subscriber,Action<T> action); /// <summary> /// Remove All Action /// </summary> void Clear(); /// <summary> /// Remove all action for a subscriber /// </summary> /// <param name="subscriber"></param> void Clear(object subscriber); /// <summary> /// Invoke all actions /// </summary> void Invoke(T arg); } }
using System; namespace Mvb.Core.Components.BinderActions { public interface IBinderActions { /// <summary> /// Add Action /// </summary> /// <param name="subscriber"></param> /// <param name="action"></param> void AddAction(object subscriber,Action action); /// <summary> /// Invoke all actions /// </summary> void Invoke(); } public interface IBinderActions<T> { /// <summary> /// Add Action /// </summary> /// <param name="subscriber"></param> /// <param name="action"></param> void AddAction(object subscriber,Action<T> action); /// <summary> /// Invoke all actions /// </summary> void Invoke(T arg); } }
apache-2.0
C#
22147347b2751868660d5c95a6b5eec956283b9f
Use available ToString method
FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,FlorianRappl/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,zedr0n/AngleSharp.Local,FlorianRappl/AngleSharp,zedr0n/AngleSharp.Local,Livven/AngleSharp,Livven/AngleSharp,zedr0n/AngleSharp.Local,AngleSharp/AngleSharp,Livven/AngleSharp
AngleSharp/Parser/ParseErrorEventArgs.cs
AngleSharp/Parser/ParseErrorEventArgs.cs
namespace AngleSharp.Parser { using System; using System.Diagnostics; /// <summary> /// The ParseErrorEventArgs package. /// </summary> [DebuggerStepThrough] public sealed class ParseErrorEventArgs : EventArgs { #region ctor /// <summary> /// Creates a new ErrorEventArgs package. /// </summary> /// <param name="code">The provided error code.</param> /// <param name="msg">The associated error message.</param> /// <param name="position">The position in the source.</param> public ParseErrorEventArgs(Int32 code, String msg, TextPosition position) { ErrorMessage = msg; ErrorCode = code; Position = position; } #endregion #region Properties /// <summary> /// Gets the position of the error. /// </summary> public TextPosition Position { get; private set; } /// <summary> /// Gets the provided error code. /// </summary> public Int32 ErrorCode { get; private set; } /// <summary> /// Gets the associated error message. /// </summary> public String ErrorMessage { get; private set; } #endregion #region Methods /// <summary> /// Creates a string containing the relevant information. /// </summary> /// <returns>The string containing the error message, error /// code as well as line and column.</returns> public override String ToString() { return String.Format("{0}: ERR{1} ({2}).", Position.ToString(), ErrorCode.ToString(), ErrorMessage); } #endregion } }
namespace AngleSharp.Parser { using System; using System.Diagnostics; /// <summary> /// The ParseErrorEventArgs package. /// </summary> [DebuggerStepThrough] public sealed class ParseErrorEventArgs : EventArgs { #region ctor /// <summary> /// Creates a new ErrorEventArgs package. /// </summary> /// <param name="code">The provided error code.</param> /// <param name="msg">The associated error message.</param> /// <param name="position">The position in the source.</param> public ParseErrorEventArgs(Int32 code, String msg, TextPosition position) { ErrorMessage = msg; ErrorCode = code; Position = position; } #endregion #region Properties /// <summary> /// Gets the position of the error. /// </summary> public TextPosition Position { get; private set; } /// <summary> /// Gets the provided error code. /// </summary> public Int32 ErrorCode { get; private set; } /// <summary> /// Gets the associated error message. /// </summary> public String ErrorMessage { get; private set; } #endregion #region Methods /// <summary> /// Creates a string containing the relevant information. /// </summary> /// <returns>The string containing the error message, error /// code as well as line and column.</returns> public override String ToString() { return String.Format("Ln {0}, Col {1}: ERR{2} ({3}).", Position.Line.ToString(), Position.Column.ToString(), ErrorCode.ToString(), ErrorMessage); } #endregion } }
mit
C#
b2f2c5b0272b1ba9779a8ff32cdd869422579f7b
Revert "Only test that the program compiles until we can parse top-level arrays"
quicktype/quicktype,quicktype/quicktype,quicktype/quicktype,quicktype/quicktype,quicktype/quicktype
test/csharp/Program.cs
test/csharp/Program.cs
using System; using System.IO; namespace test { class Program { static void Main(string[] args) { var path = args[0]; var json = File.ReadAllText(path); var qt = QuickType.TopLevel.FromJson(json); } } }
using System; using System.IO; namespace test { class Program { static void Main(string[] args) { var path = args[0]; // var json = File.ReadAllText(path); // var qt = QuickType.TopLevel.FromJson(json); } } }
apache-2.0
C#
b7dda3ab96e92175b4a304c528a18232aefa9ee7
Remove typo
AArnott/pinvoke,vbfox/pinvoke,jmelosegui/pinvoke
src/User32.Tests/User32Facts.cs
src/User32.Tests/User32Facts.cs
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using PInvoke; using Xunit; using static PInvoke.User32; public partial class User32Facts { [Fact] public void MessageBeep_Asterisk() { Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK)); } [Fact] public void INPUT_Union() { INPUT i = default(INPUT); i.type = InputType.INPUT_HARDWARE; // Assert that the first field (type) has its own memory space. Assert.Equal(0u, i.Inputs.hi.uMsg); Assert.Equal(0, (int)i.Inputs.ki.wScan); Assert.Equal(0, i.Inputs.mi.dx); // Assert that these three fields (hi, ki, mi) share memory space. i.Inputs.hi.uMsg = 1; Assert.Equal(1, (int)i.Inputs.ki.wVk); Assert.Equal(1, i.Inputs.mi.dx); } /// <summary> /// Validates that the union fields are all exactly 4 bytes (or 8 bytes on x64) /// after the start of the struct. /// </summary> /// <devremarks> /// From http://www.pinvoke.net/default.aspx/Structures/INPUT.html: /// The last 3 fields are a union, which is why they are all at the same memory offset. /// On 64-Bit systems, the offset of the <see cref="mi"/>, <see cref="ki"/> and <see cref="hi"/> fields is 8, /// because the nested struct uses the alignment of its biggest member, which is 8 /// (due to the 64-bit pointer in <see cref="KEYBDINPUT.dwExtraInfo"/>). /// By separating the union into its own structure, rather than placing the /// <see cref="mi"/>, <see cref="ki"/> and <see cref="hi"/> fields directly in the INPUT structure, /// we assure that the .NET structure will have the correct alignment on both 32 and 64 bit. /// </devremarks> [Fact] public unsafe void INPUT_UnionMemoryAlignment() { INPUT input; Assert.Equal(IntPtr.Size, (long)&input.Inputs.hi - (long)&input); Assert.Equal(IntPtr.Size, (long)&input.Inputs.mi - (long)&input); Assert.Equal(IntPtr.Size, (long)&input.Inputs.ki - (long)&input); } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using PInvoke; using Xunit; using static PInvoke.User32; public partial class User32Facts { [Fact] public void MessageBeep_Asterisk() { Assert.True(MessageBeep(MessageBeepType.MB_ICONASTERISK)); } [Fact] public void INPUT_Union() { INPUT i = default(INPUT); i.type = InputType.INPUT_HARDWARE; // Assert that the first field (type) has its own memory space. Assert.Equal(0u, i.Inputs.hi.uMsg); Assert.Equal(0, (int)i.Inputs.ki.wScan); Assert.Equal(0, i.Inputs.mi.dx); // Assert that these three fields (hi, ki, mi) share memory space. i.Inputs.hi.uMsg = 1; Assert.Equal(1, (int)i.Inputs.ki.wVk); Assert.Equal(1, i.Inputs.mi.dx); } /// <summary> /// Validates that the union fields are all exactly 4 bytes (or 8 bytes on x64) /// after the start of the struct.i /// </summary> /// <devremarks> /// From http://www.pinvoke.net/default.aspx/Structures/INPUT.html: /// The last 3 fields are a union, which is why they are all at the same memory offset. /// On 64-Bit systems, the offset of the <see cref="mi"/>, <see cref="ki"/> and <see cref="hi"/> fields is 8, /// because the nested struct uses the alignment of its biggest member, which is 8 /// (due to the 64-bit pointer in <see cref="KEYBDINPUT.dwExtraInfo"/>). /// By separating the union into its own structure, rather than placing the /// <see cref="mi"/>, <see cref="ki"/> and <see cref="hi"/> fields directly in the INPUT structure, /// we assure that the .NET structure will have the correct alignment on both 32 and 64 bit. /// </devremarks> [Fact] public unsafe void INPUT_UnionMemoryAlignment() { INPUT input; Assert.Equal(IntPtr.Size, (long)&input.Inputs.hi - (long)&input); Assert.Equal(IntPtr.Size, (long)&input.Inputs.mi - (long)&input); Assert.Equal(IntPtr.Size, (long)&input.Inputs.ki - (long)&input); } }
mit
C#
9478394bc69936ec12ddd7d71c1dc4e5543f1a76
Change setup cameras config temporarily
intel-cornellcup/mini-modbot-simulation,intel-cornellcup/mini-modbot-simulation,intel-cornellcup/mini-modbot-simulation
ModbotSim/Assets/Scripts/SetupCameras.cs
ModbotSim/Assets/Scripts/SetupCameras.cs
using UnityEngine; using System.Collections; public class SetupCameras : MonoBehaviour { public int numPlayers = 2; // Use this for initialization void Start () { GameObject[] cameraObjects = GameObject.FindGameObjectsWithTag ("Camera"); GameObject[] karts = GameObject.FindGameObjectsWithTag ("kart"); Camera[] cameras = new Camera[4]; for (int i = 0; i < 4; i++) { cameras [i] = karts [i].GetComponentInChildren<Camera> (); } if (numPlayers == 1) { cameras [0].rect = new Rect (0f, 0f, 1f, 1f); } else if (numPlayers == 2) { cameras [0].rect = new Rect (0f, .5f, .7f, .5f); cameras [1].rect = new Rect (.3f, 0f, .7f, .5f); karts [2].SetActive (false); karts [3].SetActive (false); } else if (numPlayers == 3) { cameras [0].rect = new Rect (0f, .5f, 1f, .5f); cameras [1].rect = new Rect (0f, 0f, .5f, .5f); cameras [2].rect = new Rect (.5f, 0f, .5f, .5f); } else if (numPlayers == 4) { cameras [0].rect = new Rect (0f, 0f, .5f, .5f); cameras [1].rect = new Rect (.5f, 0f, .5f, .5f); cameras [2].rect = new Rect (0f, .5f, .5f, .5f); cameras [3].rect = new Rect (.5f, .5f, .5f, .5f); } //for (int i = numPlayers; i < 4; i++) { // karts [i].SetActive(false); //} } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; public class SetupCameras : MonoBehaviour { public int numPlayers = 2; // Use this for initialization void Start () { GameObject[] cameraObjects = GameObject.FindGameObjectsWithTag ("Camera"); GameObject[] karts = GameObject.FindGameObjectsWithTag ("kart"); Camera[] cameras = new Camera[4]; for (int i = 0; i < 4; i++) { cameras [i] = karts [i].GetComponentInChildren<Camera> (); } if (numPlayers == 1) { cameras [0].rect = new Rect (0f, 0f, 1f, 1f); } else if (numPlayers == 2) { cameras [0].rect = new Rect (0f, .5f, .7f, .5f); cameras [2].rect = new Rect (.3f, 0f, .7f, .5f); karts [1].SetActive (false); karts [3].SetActive (false); } else if (numPlayers == 3) { cameras [0].rect = new Rect (0f, .5f, 1f, .5f); cameras [1].rect = new Rect (0f, 0f, .5f, .5f); cameras [2].rect = new Rect (.5f, 0f, .5f, .5f); } else if (numPlayers == 4) { cameras [0].rect = new Rect (0f, 0f, .5f, .5f); cameras [1].rect = new Rect (.5f, 0f, .5f, .5f); cameras [2].rect = new Rect (0f, .5f, .5f, .5f); cameras [3].rect = new Rect (.5f, .5f, .5f, .5f); } //for (int i = numPlayers; i < 4; i++) { // karts [i].SetActive(false); //} } // Update is called once per frame void Update () { } }
mit
C#
231e70163299e0b043e501e5a693a2f26a57ef55
simplify the testapp
memleaks/SuperSocket,kerryjiang/SuperSocket,kerryjiang/SuperSocket
test/TestApp/Program.cs
test/TestApp/Program.cs
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; namespace TestApp { class Program { static IHostBuilder CreateSocketServerBuilder() { return SuperSocketHostBuilder.Create<TextPackageInfo, LinePipelineFilter>() .ConfigurePackageHandler(async (s, p) => { await s.Channel.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n")); }) .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary<string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureServices((hostCtx, services) => { services.AddOptions(); services.Configure<ServerOptions>(hostCtx.Configuration.GetSection("serverOptions")); }); } static async Task Main(string[] args) { var host = CreateSocketServerBuilder().Build(); await host.RunAsync(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using SuperSocket; using SuperSocket.ProtoBase; using SuperSocket.Server; namespace TestApp { class Program { static IHostBuilder CreateSocketServerBuilder<TPackageInfo, TPipelineFilter>(Dictionary<string, string> configDict = null, Func<IAppSession, TPackageInfo, Task> packageHandler = null) where TPackageInfo : class where TPipelineFilter : IPipelineFilter<TPackageInfo>, new() { var hostBuilder = new HostBuilder() .ConfigureAppConfiguration((hostCtx, configApp) => { configApp.AddInMemoryCollection(new Dictionary<string, string> { { "serverOptions:name", "TestServer" }, { "serverOptions:listeners:0:ip", "Any" }, { "serverOptions:listeners:0:port", "4040" } }); }) .ConfigureLogging((hostCtx, loggingBuilder) => { loggingBuilder.AddConsole(); }) .ConfigureServices((hostCtx, services) => { services.AddOptions(); services.Configure<ServerOptions>(hostCtx.Configuration.GetSection("serverOptions")); }) .UseSuperSocket<TPackageInfo, TPipelineFilter>(); return hostBuilder; } static async Task Main(string[] args) { await RunAsync(); } static async Task RunAsync() { var host = CreateSocketServerBuilder<TextPackageInfo, LinePipelineFilter>() .ConfigurePackageHandler(async (IAppSession s, TextPackageInfo p) => { await s.Channel.SendAsync(Encoding.UTF8.GetBytes(p.Text + "\r\n")); }).Build(); await host.RunAsync(); } } }
apache-2.0
C#
7343b5b4c200c7f4e9cdbcbed38323132ffc3c2c
Rename <T> with <TValue>
tainicom/XNALibrary
Source/DataStructures/Collections/Set.cs
Source/DataStructures/Collections/Set.cs
#region License // Copyright 2015 Kastellanos Nikolaos // // 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 using System.Collections.Generic; namespace tainicom.DataStructures.Collections { public class Set<TValue> : ICollection<TValue> { private Dictionary<TValue, short> _dictionary; public Set() { _dictionary = new Dictionary<TValue,short>(); } public void Add(TValue item) { _dictionary.Add(item,0); } public void Clear() { _dictionary.Clear(); } public bool Contains(TValue item) { return _dictionary.ContainsKey(item); } public void CopyTo(TValue[] array, int arrayIndex) { _dictionary.Keys.CopyTo(array,arrayIndex); } public int Count { get { return _dictionary.Keys.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(TValue item) { return _dictionary.Remove(item); } public IEnumerator<TValue> GetEnumerator() { return _dictionary.Keys.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _dictionary.Keys.GetEnumerator(); } } }
#region License // Copyright 2015 Kastellanos Nikolaos // // 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 using System.Collections.Generic; namespace tainicom.DataStructures.Collections { public class Set<T>:ICollection<T> { private Dictionary<T, short> _dictionary; public Set() { _dictionary = new Dictionary<T,short>(); } public void Add(T item) { _dictionary.Add(item,0); } public void Clear() { _dictionary.Clear(); } public bool Contains(T item) { return _dictionary.ContainsKey(item); } public void CopyTo(T[] array, int arrayIndex) { _dictionary.Keys.CopyTo(array,arrayIndex); } public int Count { get { return _dictionary.Keys.Count; } } public bool IsReadOnly { get { return false; } } public bool Remove(T item) { return _dictionary.Remove(item); } public IEnumerator<T> GetEnumerator() { return _dictionary.Keys.GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return _dictionary.Keys.GetEnumerator(); } } }
apache-2.0
C#
a4877382ca62b09d421836f123955567c73f6988
Change AssemblyCopyright from ACAXLabs to ACAExpress
acaxlabs/LibSlyBroadcast
LibSlyBroadcast/Properties/AssemblyInfo.cs
LibSlyBroadcast/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("LibSlyBroadcast")] [assembly: AssemblyProduct("LibSlyBroadcast")] [assembly: AssemblyCopyright("Copyright © ACAExpress.com, Inc 2016")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("LibSlyBroadcast")] [assembly: AssemblyProduct("LibSlyBroadcast")] [assembly: AssemblyCopyright("Copyright © ACAXLabs 2016")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
10cde01e4342a6e4666ba843d3d2dfae4d587bda
Update LinkedListDictionary.cs
efruchter/UnityUtilities
MiscDataStructures/LinkedListDictionary.cs
MiscDataStructures/LinkedListDictionary.cs
using System.Collections; using System.Collections.Generic; /// <summary> /// LinkedList/Dictionary combo for constant time add/remove/contains. Memory usage is higher as expected. /// -kazoo /// </summary> /// <typeparam name="TK">key value type. It is recomended that this be "int", for speed purposes.</typeparam> /// <typeparam name="TV">The value type. Can be anything you like.</typeparam> public class LinkedListDictionary<TK, TV> { private readonly Dictionary<TK, LLEntry> dictionary = new Dictionary<TK, LLEntry>(); private readonly LinkedList<TV> list = new LinkedList<TV>(); /// <summary> /// Get The count. /// </summary> /// <returns></returns> public int Count { get { return list.Count; } } /// <summary> /// Is the key in the dictionary? /// </summary> /// <param name="k">key</param> /// <returns>true if key is present, false otherwise.</returns> public bool ContainsKey(TK k) { return dictionary.ContainsKey(k); } /// <summary> /// Remove a key/value from the dictionary if present. /// </summary> /// <param name="k">key</param> /// <returns>True if removal worked. False if removal is not possible.</returns> public bool Remove(TK k) { if (!ContainsKey(k)) { return false; } LLEntry entry = dictionary[k]; list.Remove(entry.vNode); return dictionary.Remove(k); } /// <summary> /// Add an item. Replacement is allowed. /// </summary> /// <param name="k">key</param> /// <param name="v">value</param> public void Add(TK k, TV v) { Remove(k); dictionary[k] = new LLEntry(v, list.AddLast(v)); } /// <summary> /// Retrieve an element by key. /// </summary> /// <param name="k">key</param> /// <returns>Value. If element is not present, default(V) will be returned.</returns> public TV GetValue(TK k) { if (ContainsKey(k)) { return dictionary[k].v; } return default(TV); } public TV this[TK k] { get { return GetValue(k); } set { Add(k, value); } } /// <summary> /// Raw list of Values for garbage-free iteration. Do not modify. /// </summary> /// <value>The values</value> public LinkedList<TV> Values { get { return list; } } private struct LLEntry { public readonly TV v; public readonly LinkedListNode<TV> vNode; public LLEntry(TV v, LinkedListNode<TV> vNode) { this.v = v; this.vNode = vNode; } } }
using System.Collections; using System.Collections.Generic; namespace System.Collections.Generic { /// <summary> /// LinkedList/Dictionary combo for constant time add/remove/contains. Memory usage is higher as expected. /// -kazoo /// </summary> /// <typeparam name="TK">key value type. It is recomended that this be "int", for speed purposes.</typeparam> /// <typeparam name="TV">The value type. Can be anything you like.</typeparam> public class LinkedListDictionary<TK, TV> : IEnumerable<TV> { private readonly Dictionary<TK, LLEntry> dictionary = new Dictionary<TK, LLEntry>(); private readonly LinkedList<TV> list = new LinkedList<TV>(); /// <summary> /// Get The count. /// </summary> /// <returns></returns> public int Count { get { return list.Count; } } /// <summary> /// Is the key in the dictionary? /// </summary> /// <param name="k">key</param> /// <returns>true if key is present, false otherwise.</returns> public bool ContainsKey(TK k) { return dictionary.ContainsKey(k); } /// <summary> /// Remove a key/value from the dictionary if present. /// </summary> /// <param name="k">key</param> /// <returns>True if removal worked. False if removal is not possible.</returns> public bool Remove(TK k) { if (!ContainsKey(k)) { return false; } LLEntry entry = dictionary[k]; list.Remove(entry.vNode); return dictionary.Remove(k); } /// <summary> /// Add an item. Replacement is allowed. /// </summary> /// <param name="k">key</param> /// <param name="v">value</param> public void Add(TK k, TV v) { Remove(k); dictionary[k] = new LLEntry(v, list.AddLast(v)); } /// <summary> /// Retrieve an element by key. /// </summary> /// <param name="k">key</param> /// <returns>Value. If element is not present, default(V) will be returned.</returns> public TV GetValue(TK k) { if (ContainsKey(k)) { return dictionary[k].v; } return default(TV); } public TV this[TK k] { get { return GetValue(k); } set { Add(k, value); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public IEnumerator<TV> GetEnumerator() { return list.GetEnumerator(); } public void Clear() { dictionary.Clear(); list.Clear(); } private struct LLEntry { public readonly TV v; public readonly LinkedListNode<TV> vNode; public LLEntry(TV v, LinkedListNode<TV> vNode) { this.v = v; this.vNode = vNode; } } } }
mit
C#
cbeff2ad673c638c30571fdc137c3554aab2249c
Add hit count on Index page
KuduApps/Dev14_Net46_Mvc5,KuduApps/Dev14_Net46_Mvc5,KuduApps/Dev14_Net46_Mvc5
Dev14_Net46_Mvc5/Views/Home/Index.cshtml
Dev14_Net46_Mvc5/Views/Home/Index.cshtml
@functions { static int count; } @{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started! @(++count)</h2> <p> ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development. </p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div>
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>ASP.NET</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p> <p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p> ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development. </p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div>
apache-2.0
C#
57cdbaee7cf2c1cf23a10cb8094400a8de56d02a
Fix for script ordering being bust
mcintyre321/Noodles,mcintyre321/Noodles
Noodles.AspMvc/Helpers/IncludesHelper.cs
Noodles.AspMvc/Helpers/IncludesHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Noodles.AspMvc.Models.Layout; namespace Noodles.AspMvc.Helpers { public static class IncludesHelper { public static void RegisterScripts(this LayoutVm layout) { layout.HeadBundle.ScriptIncludes.Add("/Scripts/modernizr-2.6.2.js"); var styles = layout.HeadBundle.StyleIncludes; styles.Add("/Content/bootstrap.min.css"); styles.Add("/Content/bootstrap-overrides.css"); styles.Add("/Content/font-awesome.min.css"); styles.Add("/Content/themes/base/jquery-ui.css"); styles.Add("/Content/Noodles.AspMvc.css"); var scripts = layout.HeadBundle.ScriptIncludes; scripts.Add("/Scripts/jquery-1.9.1.min.js"); scripts.Add("/Scripts/jquery-migrate-1.1.1.js"); scripts.Add("/Scripts/jquery-ui-1.10.2.min.js"); scripts.Add("/Scripts/bootstrap.js"); scripts.Add("/Scripts/jquery.validate.js"); scripts.Add("/Scripts/jquery.validate.unobtrusive.js"); scripts.Add("/Scripts/jquery.unobtrusive-ajax.js"); scripts.Add("/Scripts/formfactory/formfactory.js"); scripts.Add("/Scripts/jquery.validate.unobtrusive.dynamic.js"); scripts.Add("/Scripts/jquery.signalR-1.0.0-rc2.js"); scripts.Add("/Scripts/Noodles/Noodles.js"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Noodles.AspMvc.Models.Layout; namespace Noodles.AspMvc.Helpers { public static class IncludesHelper { public static void RegisterScripts(this LayoutVm layout) { layout.HeadBundle.ScriptIncludes.Add("/Scripts/modernizr-2.6.2.js"); var styles = layout.HeadBundle.StyleIncludes; styles.Add("/Content/bootstrap.min.css"); styles.Add("/Content/bootstrap-overrides.css"); styles.Add("/Content/font-awesome.min.css"); styles.Add("/Content/themes/base/jquery-ui.css"); styles.Add("/Content/Noodles.AspMvc.css"); var scripts = layout.HeadBundle.ScriptIncludes; scripts.Add("/Scripts/jquery-1.9.1.min.js"); scripts.Add("/Scripts/jquery-migrate-1.1.1.js"); scripts.Add("/Scripts/jquery-ui-1.10.2.min.js"); scripts.Add("/Scripts/bootstrap.js"); scripts.Add("/Scripts/Noodles/Noodles.js"); scripts.Add("/Scripts/jquery.validate.js"); scripts.Add("/Scripts/jquery.validate.unobtrusive.js"); scripts.Add("/Scripts/jquery.unobtrusive-ajax.js"); scripts.Add("/Scripts/formfactory/formfactory.js"); scripts.Add("/Scripts/jquery.validate.unobtrusive.dynamic.js"); scripts.Add("/Scripts/jquery.signalR-1.0.0-rc2.js"); } } }
mit
C#
4c79750a8fa805a73027fbe0cb0bdb7e621a8ca6
Update to v0.1.1.0
WatcherWhale/Netflix-Shakti.net
NetflixShakti/Properties/AssemblyInfo.cs
NetflixShakti/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Netflix Shakti.net")] [assembly: AssemblyDescription("A .net wrapper for the netflix not so public shakti api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mathias Maes")] [assembly: AssemblyProduct("Netflix Shakti.net")] [assembly: AssemblyCopyright("Copyright ©Mathias Maes 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4324c982-8c17-4274-9e11-b2c234d8e3c3")] // 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.1.1.0")] [assembly: AssemblyFileVersion("0.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("Netflix Shakti.net")] [assembly: AssemblyDescription("A .net wrapper for the netflix not so public shakti api")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Mathias Maes")] [assembly: AssemblyProduct("Netflix Shakti.net")] [assembly: AssemblyCopyright("Copyright ©Mathias Maes 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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4324c982-8c17-4274-9e11-b2c234d8e3c3")] // 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.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
mit
C#
04be8a80dcfc394e44d3ea7eff2ec156642448e8
Build and publish prerelease package
RockFramework/Rock.Encryption
Rock.Encryption/Properties/AssemblyInfo.cs
Rock.Encryption/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Rock.Encryption")] [assembly: AssemblyDescription("An easy-to-use crypto API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("Rock.Encryption")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a4476f1b-671a-43d1-8bdb-5a275ef62995")] // 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.9.0.0")] [assembly: AssemblyFileVersion("0.9.0")] [assembly: AssemblyInformationalVersion("0.9.0-beta02")]
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("Rock.Encryption")] [assembly: AssemblyDescription("An easy-to-use crypto API.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Quicken Loans")] [assembly: AssemblyProduct("Rock.Encryption")] [assembly: AssemblyCopyright("Copyright © Quicken Loans 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a4476f1b-671a-43d1-8bdb-5a275ef62995")] // 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.9.0.0")] [assembly: AssemblyFileVersion("0.9.0")] [assembly: AssemblyInformationalVersion("0.9.0-beta01")]
mit
C#
b135bc94325d223bf717de3a7a5e008b32802b9d
Return the values of variables in the program as well as variables in the query
Logicalshift/Reason
LogicalShift.Reason/BasicUnification.cs
LogicalShift.Reason/BasicUnification.cs
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null) { var simpleUnifier = new SimpleUnifier(); var freeVariables = new HashSet<ILiteral>(); // Run the unifier try { var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings); simpleUnifier.PrepareToRunProgram(); var programFreeVars = simpleUnifier.ProgramUnifier.Compile(program, bindings); freeVariables.UnionWith(queryFreeVars); freeVariables.UnionWith(programFreeVars); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way return null; } // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { var variableBindings = freeVariables.ToDictionary(variable => variable, variable => simpleUnifier.UnifiedValue(variable)); return new BasicBinding(result, variableBindings); } else { return null; } } } }
using LogicalShift.Reason.Api; using LogicalShift.Reason.Unification; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason { /// <summary> /// Helper methods for performing unification /// </summary> public static class BasicUnification { /// <summary> /// Returns the possible ways that a query term can unify with a program term /// </summary> public static IBindings Unify(this ILiteral query, ILiteral program, IBindings bindings = null) { var simpleUnifier = new SimpleUnifier(); var freeVariables = new HashSet<ILiteral>(); // Run the unifier try { var queryFreeVars = simpleUnifier.QueryUnifier.Compile(query, bindings); simpleUnifier.PrepareToRunProgram(); simpleUnifier.ProgramUnifier.Compile(program, bindings); freeVariables.UnionWith(queryFreeVars); } catch (InvalidOperationException) { // No results // TODO: really should report failure in a better way return null; } // Retrieve the unified value for the program var result = simpleUnifier.UnifiedValue(query.UnificationKey ?? query); // If the result was valid, return as the one value from this function if (result != null) { var variableBindings = freeVariables.ToDictionary(variable => variable, variable => simpleUnifier.UnifiedValue(variable)); return new BasicBinding(result, variableBindings); } else { return null; } } } }
apache-2.0
C#
de8961567afcbdf3254608edc9e3f50942e4036a
Order change
xonaki/NetCoreCMS,OnnoRokomSoftware/NetCoreCMS,xonaki/NetCoreCMS,xonaki/NetCoreCMS,xonaki/NetCoreCMS,OnnoRokomSoftware/NetCoreCMS,xonaki/NetCoreCMS,xonaki/NetCoreCMS,OnnoRokomSoftware/NetCoreCMS,OnnoRokomSoftware/NetCoreCMS,OnnoRokomSoftware/NetCoreCMS
NetCoreCMS.Web/Themes/Default/Shared/_ViewImports.cshtml
NetCoreCMS.Web/Themes/Default/Shared/_ViewImports.cshtml
@inherits NccRazorPage<TModel> @using NetCoreCMS.Framework.Core @using NetCoreCMS.Framework.Core.Models @using NetCoreCMS.Framework.Core.Mvc.Views @using NetCoreCMS.Framework.Core.Mvc.Views.Extensions @using NetCoreCMS.Framework.Utility @using NetCoreCMS.Framework.Modules @using NetCoreCMS.Framework.Modules.Widgets @using NetCoreCMS.Framework.Themes @using NetCoreCMS.Themes.Default.Lib @using Microsoft.AspNetCore.Identity @using Microsoft.Extensions.Localization @using NetCoreCMS.Framework.i18n @addTagHelper *, NetCoreCMS.Framework @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet @inject SignInManager<NccUser> SignInManager @inject UserManager<NccUser> UserManager @inject NccLanguageDetector LanguageDetector @inject IStringLocalizer _T
@inherits NccRazorPage<TModel> @using NetCoreCMS.Framework.Themes @using NetCoreCMS.Framework.Core @using Microsoft.AspNetCore.Identity @using NetCoreCMS.Framework.Utility @using NetCoreCMS.Framework.Modules @using NetCoreCMS.Framework.Modules.Widgets @using NetCoreCMS.Framework.Core.Models @using NetCoreCMS.Framework.Core.Mvc.Views @using NetCoreCMS.Framework.Core.Mvc.Views.Extensions @using NetCoreCMS.Themes.Default.Lib @using Microsoft.Extensions.Localization @using NetCoreCMS.Framework.i18n @addTagHelper *, NetCoreCMS.Framework @addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers @inject Microsoft.ApplicationInsights.AspNetCore.JavaScriptSnippet JavaScriptSnippet @inject SignInManager<NccUser> SignInManager @inject UserManager<NccUser> UserManager @inject NccLanguageDetector LanguageDetector @inject IStringLocalizer _T
bsd-3-clause
C#
eab466695fcaa52c59e2c1750b18a5ae787f4bb4
Use JsonSerializer.SerializeToDocument
carbon/Amazon
src/Amazon.Sts/Helpers/RequestHelper.cs
src/Amazon.Sts/Helpers/RequestHelper.cs
using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace Amazon.Sts; internal static class StsRequestHelper { private static readonly JsonSerializerOptions jso = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; public static Dictionary<string, string> ToParams<T>(T instance) where T : IStsRequest { using var doc = JsonSerializer.SerializeToDocument(instance, jso); var parameters = new Dictionary<string, string>(2); foreach (var member in doc.RootElement.EnumerateObject()) { parameters.Add(member.Name, member.Value.ToString()!); } return parameters; } }
using System.Collections.Generic; using System.Text.Json; using System.Text.Json.Serialization; namespace Amazon.Sts; internal static class StsRequestHelper { private static readonly JsonSerializerOptions jso = new() { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull }; public static Dictionary<string, string> ToParams<T>(T instance) where T : IStsRequest { using var doc = JsonDocument.Parse(JsonSerializer.SerializeToUtf8Bytes(instance, jso)); var parameters = new Dictionary<string, string>(2); foreach (var member in doc.RootElement.EnumerateObject()) { parameters.Add(member.Name, member.Value.ToString()!); } return parameters; } }
mit
C#
021c988e6008b1fca3cd828c4a2d9dac8c505d13
fix RdnRmnSd Handler
PipatPosawad/nChronic
src/Chronic/Handlers/RdnRmnSdHandler.cs
src/Chronic/Handlers/RdnRmnSdHandler.cs
using System; using System.Collections.Generic; using Chronic.Tags.Repeaters; using System.Linq; namespace Chronic.Handlers { public class RdnRmnSdHandler : IHandler { public Span Handle(IList<Token> tokens, Options options) { var month = tokens[1].GetTag<RepeaterMonthName>(); var day = tokens[2].GetTag<ScalarDay>().Value; var time_tokens = tokens.Skip(3).ToList(); var year = options.Clock().Year; if (Time.IsMonthOverflow(year, (int) month.Value, day)) { return null; } try { if (time_tokens == null || time_tokens.Count == 0) { var start = Time.New(year, (int)month.Value, day); var end = start.AddDays(1); return new Span(start, end); } else { var dayStart = Time.New(year, (int)month.Value, day); return Utils.DayOrTime(dayStart, time_tokens, options); } } catch (ArgumentException) { return null; } } } }
using System; using System.Collections.Generic; using Chronic.Tags.Repeaters; namespace Chronic.Handlers { public class RdnRmnSdHandler : IHandler { public Span Handle(IList<Token> tokens, Options options) { var month = tokens[1].GetTag<RepeaterMonthName>(); var day = tokens[2].GetTag<ScalarDay>().Value; var year = options.Clock().Year; if (Time.IsMonthOverflow(year, (int) month.Value, day)) { return null; } try { var start = Time.New(year, (int) month.Value, day); var end = start.AddDays(1); return new Span(start, end); } catch (ArgumentException) { return null; } } } }
mit
C#
1498f2ddc57ea3546a370e7d26b06f5b9fe43328
Fix warning
ermau/Gablarski,ermau/Gablarski
src/Gablarski.Tests/AudioFormatTests.cs
src/Gablarski.Tests/AudioFormatTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Gablarski.Audio; using NUnit.Framework; namespace Gablarski.Tests { [TestFixture] public class AudioFormatTests { [Test] public void Equals() { var one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.IsTrue (one.Equals (two)); } [Test] public void DoesNotEqual() { var one = new AudioFormat (WaveFormatEncoding.Unknown, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.IsFalse (one.Equals (two)); one = new AudioFormat (WaveFormatEncoding.LPCM, 1, 16, 48000); Assert.IsFalse (one.Equals (two)); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 8, 48000); Assert.IsFalse (one.Equals (two)); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 44100); Assert.IsFalse (one.Equals (two)); } [Test] public void GetHashCodeTest() { var one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.AreEqual (one.GetHashCode(), two.GetHashCode()); } [Test] public void GetHashCodeNotMatching() { var one = new AudioFormat (WaveFormatEncoding.Unknown, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); one = new AudioFormat (WaveFormatEncoding.LPCM, 1, 16, 48000); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 8, 48000); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 44100); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Gablarski.Audio; using NUnit.Framework; namespace Gablarski.Tests { [TestFixture] public class AudioFormatTests { [Test] public void Equals() { var one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.IsTrue (one.Equals (two)); } [Test] public void DoesNotEqual() { var one = new AudioFormat (WaveFormatEncoding.Unknown, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.IsFalse (one.Equals (two)); one = new AudioFormat (WaveFormatEncoding.LPCM, 1, 16, 48000); Assert.IsFalse (one.Equals (two)); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 8, 48000); Assert.IsFalse (one.Equals (two)); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 44100); Assert.IsFalse (one.Equals (two)); } [Test] public void GetHashCode() { var one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.AreEqual (one.GetHashCode(), two.GetHashCode()); } [Test] public void GetHashCodeNotMatching() { var one = new AudioFormat (WaveFormatEncoding.Unknown, 2, 16, 48000); var two = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 48000); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); one = new AudioFormat (WaveFormatEncoding.LPCM, 1, 16, 48000); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 8, 48000); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); one = new AudioFormat (WaveFormatEncoding.LPCM, 2, 16, 44100); Assert.AreNotEqual (one.GetHashCode(), two.GetHashCode()); } } }
bsd-3-clause
C#
d2015b2a0df537ca2731b5e680e0a2d51ec8ce48
Rename Float to FloatField
laicasaane/VFW
Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Floats.cs
Assets/Plugins/Editor/Vexe/GUIs/BaseGUI/Controls/Floats.cs
using UnityEngine; namespace Vexe.Editor.GUIs { public abstract partial class BaseGUI { public float FloatField(float value) { return FloatField(string.Empty, value); } public float FloatField(string label, float value) { return FloatField(label, value, null); } public float FloatField(string label, string tooltip, float value) { return FloatField(label, tooltip, value, null); } public float FloatField(string label, float value, Layout option) { return FloatField(label, string.Empty, value, option); } public float FloatField(string label, string tooltip, float value, Layout option) { return FloatField(GetContent(label, tooltip), value, option); } public abstract float FloatField(GUIContent content, float value, Layout option); } }
using UnityEngine; namespace Vexe.Editor.GUIs { public abstract partial class BaseGUI { public float Float(float value) { return Float(string.Empty, value); } public float Float(string label, float value) { return Float(label, value, null); } public float Float(string label, string tooltip, float value) { return Float(label, tooltip, value, null); } public float Float(string label, float value, Layout option) { return Float(label, string.Empty, value, option); } public float Float(string label, string tooltip, float value, Layout option) { return Float(GetContent(label, tooltip), value, option); } public abstract float Float(GUIContent content, float value, Layout option); } }
mit
C#
feba8fe9b391668bbc5b4002877a6bb320b8d9ad
Remove type limit from ReflectionViewModel
evandixon/SkyEditor.Core
SkyEditor.Core/UI/ReflectionViewModel.cs
SkyEditor.Core/UI/ReflectionViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SkyEditor.Core.UI { /// <summary> /// A view model that can read all public properties /// </summary> public class ReflectionViewModel : GenericViewModel { public ReflectionViewModel() { } public ReflectionViewModel(object model, ApplicationViewModel appViewModel) : base(model, appViewModel) { } public override IEnumerable<TypeInfo> GetSupportedTypes() { return new[] { typeof(object).GetTypeInfo() }; } protected bool IsPropertyTypeSupported(TypeInfo type) { return true; //var supportedTypes = new[] { typeof(string).GetTypeInfo(), typeof(int).GetTypeInfo() }; //return supportedTypes.Contains(type); //Todo: add check for custom interface } public IEnumerable<PropertyInfo> GetProperties() { var allProperties = Model.GetType().GetTypeInfo().DeclaredProperties; return allProperties.Where(x => IsPropertyTypeSupported(x.PropertyType.GetTypeInfo())); } public Dictionary<string, string> GetPropertyValues() { Dictionary<string, string> output = new Dictionary<string, string>(); foreach (var item in GetProperties()) { output.Add(item.Name, item.GetValue(Model).ToString()); } return output; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SkyEditor.Core.UI { /// <summary> /// A view model that can read all public properties /// </summary> public class ReflectionViewModel : GenericViewModel { public ReflectionViewModel() { } public ReflectionViewModel(object model, ApplicationViewModel appViewModel) : base(model, appViewModel) { } public override IEnumerable<TypeInfo> GetSupportedTypes() { return new[] { typeof(object).GetTypeInfo() }; } protected bool IsPropertyTypeSupported(TypeInfo type) { var supportedTypes = new[] { typeof(string).GetTypeInfo(), typeof(int).GetTypeInfo() }; return supportedTypes.Contains(type); //Todo: add check for custom interface } public IEnumerable<PropertyInfo> GetProperties() { var allProperties = Model.GetType().GetTypeInfo().DeclaredProperties; return allProperties.Where(x => IsPropertyTypeSupported(x.PropertyType.GetTypeInfo())); } public Dictionary<string, string> GetPropertyValues() { Dictionary<string, string> output = new Dictionary<string, string>(); foreach (var item in GetProperties()) { output.Add(item.Name, item.GetValue(Model).ToString()); } return output; } } }
mit
C#
85b8981f9dbc7dc85126a7644bc90a3d5c6657eb
Rename the variable in SetActiveAction to something cleaner
mikelovesrobots/unity3d-trigger-action-pattern
TriggerAction/Actions/SetActiveAction.cs
TriggerAction/Actions/SetActiveAction.cs
using UnityEngine; using System.Collections; public class SetActiveAction : ActionBase { public GameObject target; public bool setToActive; public override void Action() { target.SetActive(setToActive); } }
using UnityEngine; using System.Collections; public class SetActiveAction : ActionBase { public GameObject target; public bool isActive; public override void Action() { target.SetActive(isActive); } }
mit
C#
48ce88fe471b024be684e64f7be42b0c735c8307
Add more visualisations
ruarai/Trigrad,ruarai/Trigrad
Trigrad/DataTypes/TrigradDecompressed.cs
Trigrad/DataTypes/TrigradDecompressed.cs
using System.Drawing; using TriangleNet; namespace Trigrad.DataTypes { /// <summary> The results of a TrigradDecompression, containing both the output and debug bitmaps. </summary> public class TrigradDecompressed { /// <summary> Constructor for a TrigradDecompressed object, defining the width and height of output bitmaps. </summary> public TrigradDecompressed(int width, int height) { Output = new Bitmap(width, height); DebugOutput = new Bitmap(width, height); } /// <summary> The decompressed output bitmap. </summary> public Bitmap Output; /// <summary> The debug output bitmap, showing calculated barycentric coordinates. </summary> public Bitmap DebugOutput; internal Mesh Mesh; public Bitmap MeshOutput { get { return Mesh.ToBitmap(Output.Width,Output.Height); } } } }
using System.Drawing; namespace Trigrad.DataTypes { /// <summary> The results of a TrigradDecompression, containing both the output and debug bitmaps. </summary> public class TrigradDecompressed { /// <summary> Constructor for a TrigradDecompressed object, defining the width and height of output bitmaps. </summary> public TrigradDecompressed(int width, int height) { Output = new Bitmap(width, height); DebugOutput = new Bitmap(width, height); } /// <summary> The decompressed output bitmap. </summary> public Bitmap Output; /// <summary> The debug output bitmap, showing calculated barycentric coordinates. </summary> public Bitmap DebugOutput; } }
mit
C#
5870f04312c5ddf3a60403c3164b73e5fd1b1da5
Fix silly mistake (improper ability granting)
csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil
Tests/Agiil.BDD/ScreenplayExtensions.cs
Tests/Agiil.BDD/ScreenplayExtensions.cs
using System; using Agiil.BDD.Abilities; using Agiil.BDD.Personas; using CSF.Screenplay; using CSF.Screenplay.Actors; namespace Agiil.BDD { public static class ScreenplayExtensions { public static IActor GetApril(this IScreenplayScenario screenplay) { if(screenplay == null) throw new ArgumentNullException(nameof(screenplay)); var cast = screenplay.GetCast(); return cast.Get(April.Name, CustomiseApril); } public static IActor GetJoe(this IScreenplayScenario screenplay) { if(screenplay == null) throw new ArgumentNullException(nameof(screenplay)); var cast = screenplay.GetCast(); return cast.Get(Joe.Name, CustomiseJoe, screenplay); } public static IActor GetYoussef(this IScreenplayScenario screenplay) { if(screenplay == null) throw new ArgumentNullException(nameof(screenplay)); var cast = screenplay.GetCast(); return cast.Get(Youssef.Name, CustomiseYoussef, screenplay); } static void CustomiseApril(IActor april) { april.IsAbleTo<ActAsTheApplication>(); } static void CustomiseJoe(IActor joe, IScreenplayScenario scenario) { var browseTheWeb = scenario.GetWebBrowser(); joe.IsAbleTo(browseTheWeb); } static void CustomiseYoussef(IActor youssef, IScreenplayScenario scenario) { var browseTheWeb = scenario.GetWebBrowser(); youssef.IsAbleTo(browseTheWeb); youssef.IsAbleTo(LogInWithAUserAccount.WithTheUsername(Youssef.Name).AndThePassword(Youssef.Password)); } } }
using System; using Agiil.BDD.Abilities; using Agiil.BDD.Personas; using CSF.Screenplay; using CSF.Screenplay.Actors; namespace Agiil.BDD { public static class ScreenplayExtensions { public static IActor GetApril(this IScreenplayScenario screenplay) { if(screenplay == null) throw new ArgumentNullException(nameof(screenplay)); var cast = screenplay.GetCast(); return cast.Get(April.Name, CustomiseApril); } public static IActor GetJoe(this IScreenplayScenario screenplay) { if(screenplay == null) throw new ArgumentNullException(nameof(screenplay)); var cast = screenplay.GetCast(); return cast.Get(Joe.Name, CustomiseJoe, screenplay); } public static IActor GetYoussef(this IScreenplayScenario screenplay) { if(screenplay == null) throw new ArgumentNullException(nameof(screenplay)); var cast = screenplay.GetCast(); return cast.Get(Youssef.Name, CustomiseYoussef, screenplay); } static void CustomiseApril(IActor april) { april.HasAbility<ActAsTheApplication>(); } static void CustomiseJoe(IActor joe, IScreenplayScenario scenario) { var browseTheWeb = scenario.GetWebBrowser(); joe.IsAbleTo(browseTheWeb); } static void CustomiseYoussef(IActor youssef, IScreenplayScenario scenario) { var browseTheWeb = scenario.GetWebBrowser(); youssef.IsAbleTo(browseTheWeb); youssef.IsAbleTo(LogInWithAUserAccount.WithTheUsername(Youssef.Name).AndThePassword(Youssef.Password)); } } }
mit
C#
427e726eeb55f6f433b0e1e7f71418ed84f9a390
fix datetime conversion for logs
ceee/UptimeSharp
UptimeSharp/Utilities/JsonExtensions.cs
UptimeSharp/Utilities/JsonExtensions.cs
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; using System.Globalization; namespace UptimeSharp { public class BoolConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((bool)value) ? 1 : 0); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value.ToString() == "1"; } public override bool CanConvert(Type objectType) { return objectType == typeof(bool); } } public class UnixDateTimeConverter : DateTimeConverterBase { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { DateTime epoc = new DateTime(1970, 1, 1); var delta = (DateTime)value - epoc; writer.WriteValue((long)delta.TotalSeconds); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value.ToString() == "0") { return null; } return DateTime.Parse(reader.Value.ToString(), CultureInfo.InvariantCulture).ToLocalTime(); } } public class UriConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.String && Uri.IsWellFormedUriString(reader.Value.ToString(), UriKind.Absolute)) { return new Uri(reader.Value.ToString()); } return null; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else if (value is Uri) { writer.WriteValue(((Uri)value).OriginalString); } } public override bool CanConvert(Type objectType) { return objectType.Equals(typeof(Uri)); } } public class EnumConverter : StringEnumConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { string value = reader.Value.ToString(); if (String.IsNullOrEmpty(value)) { return Enum.ToObject(objectType, 0); } return base.ReadJson(reader, objectType, existingValue, serializer); } } }
using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System; namespace UptimeSharp { public class BoolConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { writer.WriteValue(((bool)value) ? 1 : 0); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return reader.Value.ToString() == "1"; } public override bool CanConvert(Type objectType) { return objectType == typeof(bool); } } public class UnixDateTimeConverter : DateTimeConverterBase { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { DateTime epoc = new DateTime(1970, 1, 1); var delta = (DateTime)value - epoc; writer.WriteValue((long)delta.TotalSeconds); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.Value.ToString() == "0") { return null; } return new DateTime(1970, 1, 1, 0, 0, 0, 0).AddSeconds(Convert.ToDouble(reader.Value)).ToLocalTime(); } } public class UriConverter : JsonConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.String && Uri.IsWellFormedUriString(reader.Value.ToString(), UriKind.Absolute)) { return new Uri(reader.Value.ToString()); } return null; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { writer.WriteNull(); } else if (value is Uri) { writer.WriteValue(((Uri)value).OriginalString); } } public override bool CanConvert(Type objectType) { return objectType.Equals(typeof(Uri)); } } public class EnumConverter : StringEnumConverter { public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { string value = reader.Value.ToString(); if (String.IsNullOrEmpty(value)) { return Enum.ToObject(objectType, 0); } return base.ReadJson(reader, objectType, existingValue, serializer); } } }
mit
C#
bb64705698b127c882725849ebf6d246ce37e5e3
add MultipartMediaTypeFormatter
IvanZheng/IFramework,IvanZheng/IFramework,IvanZheng/IFramework
Src/Sample/Sample.CommandService/App_Start/WebApiConfig.cs
Src/Sample/Sample.CommandService/App_Start/WebApiConfig.cs
using IFramework.Infrastructure.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; namespace Sample.CommandService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Formatters.JsonFormatter .MediaTypeMappings .Add(new QueryStringMapping("json", "true", "application/json")); config.Formatters.XmlFormatter .MediaTypeMappings .Add(new QueryStringMapping("xml", "true", "application/xml")); config.Formatters.Insert(0, new MultipartMediaTypeFormatter()); config.Formatters.Insert(0, new CommandMediaTypeFormatter()); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{command}", defaults: new { command = RouteParameter.Optional } ); // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712. //config.EnableQuerySupport(); // To disable tracing in your application, please comment out or remove the following line of code // For more information, refer to: http://www.asp.net/web-api config.EnableSystemDiagnosticsTracing(); } } }
using IFramework.Infrastructure.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Formatting; using System.Web.Http; namespace Sample.CommandService { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Formatters.JsonFormatter .MediaTypeMappings .Add(new QueryStringMapping("json", "true", "application/json")); config.Formatters.XmlFormatter .MediaTypeMappings .Add(new QueryStringMapping("xml", "true", "application/xml")); config.Formatters.Insert(0, new CommandMediaTypeFormatter()); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{command}", defaults: new { command = RouteParameter.Optional } ); // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712. //config.EnableQuerySupport(); // To disable tracing in your application, please comment out or remove the following line of code // For more information, refer to: http://www.asp.net/web-api config.EnableSystemDiagnosticsTracing(); } } }
mit
C#
60ff1008d2d7517608fbb70279456e7715299054
Add tests for different kinds of numbers.
izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp,izrik/FbxSharp
FbxSharpTests/NumberTest.cs
FbxSharpTests/NumberTest.cs
using System; using NUnit.Framework; using FbxSharp; namespace FbxSharpTests { [TestFixture] public class NumberTest : TestBase { [Test] public void Create_ValuesAreNull() { // when: var n = new Number(); // then: Assert.IsNull(n.AsDouble); Assert.IsNull(n.AsLong); Assert.IsNull(n.StringRepresentation); // Assert.AreEqual("null", n.ToString()); } [Test] public void CreateWithLong_HasLongAndDoubleValue() { // when var n = new Number("123"); // then Assert.IsTrue(n.AsDouble.HasValue); Assert.AreEqual(123d, n.AsDouble.Value); Assert.IsTrue(n.AsLong.HasValue); Assert.AreEqual(123, n.AsLong.Value); Assert.AreEqual("123", n.ToString()); Assert.AreEqual("123", n.StringRepresentation); // when n = new Number("12345678900"); // then Assert.IsTrue(n.AsDouble.HasValue); Assert.AreEqual(12345678900d, n.AsDouble.Value); Assert.IsTrue(n.AsLong.HasValue); Assert.AreEqual(12345678900, n.AsLong.Value); Assert.AreEqual("12345678900", n.ToString()); Assert.AreEqual("12345678900", n.StringRepresentation); // when n = new Number("0"); // then Assert.IsTrue(n.AsDouble.HasValue); Assert.AreEqual(0d, n.AsDouble.Value); Assert.IsTrue(n.AsLong.HasValue); Assert.AreEqual(0L, n.AsLong.Value); Assert.AreEqual("0", n.ToString()); Assert.AreEqual("0", n.StringRepresentation); } [Test] public void CreateWithDouble_HasOnlyDoubleValue() { // when var n = new Number("0.0"); // then Assert.IsTrue(n.AsDouble.HasValue); Assert.AreEqual(0d, n.AsDouble.Value); Assert.IsFalse(n.AsLong.HasValue); Assert.AreEqual("0", n.ToString()); Assert.AreEqual("0.0", n.StringRepresentation); // when n = new Number("0.000000000000000"); // then Assert.IsTrue(n.AsDouble.HasValue); Assert.AreEqual(0d, n.AsDouble.Value); Assert.IsFalse(n.AsLong.HasValue); Assert.AreEqual("0", n.ToString()); Assert.AreEqual("0.000000000000000", n.StringRepresentation); } } }
using System; using NUnit.Framework; using FbxSharp; namespace FbxSharpTests { [TestFixture] public class NumberTest : TestBase { [Test] public void Create_ValuesAreNull() { // when: var n = new Number(); // then: Assert.IsNull(n.AsDouble); Assert.IsNull(n.AsLong); Assert.IsNull(n.StringRepresentation); // Assert.AreEqual("null", n.ToString()); } } }
lgpl-2.1
C#
a95123a4fe00bf9e7e0b735af02de4178e3aa010
Add isArchivized to class Request
BartoszBaczek/WorkshopRequestsManager
Project/WorkshopManager/WorkshopManager/Models/Request.cs
Project/WorkshopManager/WorkshopManager/Models/Request.cs
using System.Collections.Generic; using System.Linq; using WorkshopManager.Models.IRequest; namespace WorkshopManager { public class Request : IRequestWithIdAcces { public int ID { get; private set; } public string Model { get; set; } public string Mark { get; set; } public string Owner { get; set; } public string Description { get; set; } public List<Part> ListOfParts { get; set; } public bool isArchivized { get; set; } public Request(string model, string owner,string mark, string description, List<Part> listOfParts) { Mark = mark; Model = model; Owner = owner; Description = description; ListOfParts = listOfParts; } public void SetId(int id) { ID = id; } public bool Equals(Request request) { if (Model != request.Model) return false; if (Owner != request.Owner) return false; if (Description != request.Description) return false; var firstNotSecond = ListOfParts.Except(request.ListOfParts).ToList(); var secondNotFirst = request.ListOfParts.Except(ListOfParts).ToList(); return (firstNotSecond.Count == 0 && secondNotFirst.Count == 0); } public void AddPartToRequest(Part part) { ListOfParts.Add(part); } public void DeletePartFromRequest(Part part) { ListOfParts.Remove(part); } public double GetTotalPrize() { double TotalPrize = 0; foreach (var part in ListOfParts) { TotalPrize += part.Prize * part.Amount; } return TotalPrize; } } }
using System.Collections.Generic; using System.Linq; using WorkshopManager.Models.IRequest; namespace WorkshopManager { public class Request : IRequestWithIdAcces { public int ID { get; private set; } public string Model { get; set; } public string Mark { get; set; } public string Owner { get; set; } public string Description { get; set; } public List<Part> ListOfParts { get; set; } public Request(string model, string owner,string mark, string description, List<Part> listOfParts) { Mark = mark; Model = model; Owner = owner; Description = description; ListOfParts = listOfParts; } public void SetId(int id) { ID = id; } public bool Equals(Request request) { if (Model != request.Model) return false; if (Owner != request.Owner) return false; if (Description != request.Description) return false; var firstNotSecond = ListOfParts.Except(request.ListOfParts).ToList(); var secondNotFirst = request.ListOfParts.Except(ListOfParts).ToList(); return (firstNotSecond.Count == 0 && secondNotFirst.Count == 0); } public void AddPartToRequest(Part part) { ListOfParts.Add(part); } public void DeletePartFromRequest(Part part) { ListOfParts.Remove(part); } public double GetTotalPrize() { double TotalPrize = 0; foreach (var part in ListOfParts) { TotalPrize += part.Prize * part.Amount; } return TotalPrize; } } }
mit
C#
13d8e8e15604701b32c4dac368c502c40f734e23
Update CompositeTraceTelemeter.cs
tiksn/TIKSN-Framework
TIKSN.Core/Analytics/Telemetry/CompositeTraceTelemeter.cs
TIKSN.Core/Analytics/Telemetry/CompositeTraceTelemeter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using TIKSN.Configuration; namespace TIKSN.Analytics.Telemetry { public class CompositeTraceTelemeter : ITraceTelemeter { private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration; private readonly IEnumerable<ITraceTelemeter> traceTelemeters; public CompositeTraceTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration, IEnumerable<ITraceTelemeter> traceTelemeters) { this.commonConfiguration = commonConfiguration; this.traceTelemeters = traceTelemeters; } public async Task TrackTrace(string message) { if (this.commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in this.traceTelemeters) { try { await traceTelemeter.TrackTrace(message); } catch (Exception ex) { Debug.WriteLine(ex); } } } } public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) { if (this.commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in this.traceTelemeters) { try { await traceTelemeter.TrackTrace(message, severityLevel); } catch (Exception ex) { Debug.WriteLine(ex); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; using TIKSN.Configuration; namespace TIKSN.Analytics.Telemetry { public class CompositeTraceTelemeter : ITraceTelemeter { private readonly IPartialConfiguration<CommonTelemetryOptions> commonConfiguration; private readonly IEnumerable<ITraceTelemeter> traceTelemeters; public CompositeTraceTelemeter(IPartialConfiguration<CommonTelemetryOptions> commonConfiguration, IEnumerable<ITraceTelemeter> traceTelemeters) { this.commonConfiguration = commonConfiguration; this.traceTelemeters = traceTelemeters; } public async Task TrackTrace(string message) { if (commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in traceTelemeters) { try { await traceTelemeter.TrackTrace(message); } catch (Exception ex) { Debug.WriteLine(ex); } } } } public async Task TrackTrace(string message, TelemetrySeverityLevel severityLevel) { if (commonConfiguration.GetConfiguration().IsTraceTrackingEnabled) { foreach (var traceTelemeter in traceTelemeters) { try { await traceTelemeter.TrackTrace(message, severityLevel); } catch (Exception ex) { Debug.WriteLine(ex); } } } } } }
mit
C#
02fd4bf452f13a929bbe81301ae8f0cdd5c801ef
Make the login button more noticeable
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Shared/_LoginPartial.cshtml
Anlab.Mvc/Views/Shared/_LoginPartial.cshtml
@using Anlab.Core.Domain @using Microsoft.AspNetCore.Http @inject SignInManager<User> SignInManager @inject UserManager<User> UserManager @if (User.Identity.IsAuthenticated) { var user = await UserManager.GetUserAsync(User); <form class="flexer" asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <p><a asp-area="" asp-controller="Profile" asp-action="Index" title="Manage">Hello @user.Name!</a></p> <button type="submit" class="btn-hollow">Log out</button> </form> } else { <p><a class="btn btn-primary" asp-area="" asp-controller="Account" asp-action="Login">Log in</a></p> }
@using Anlab.Core.Domain @using Microsoft.AspNetCore.Http @inject SignInManager<User> SignInManager @inject UserManager<User> UserManager @if (User.Identity.IsAuthenticated) { var user = await UserManager.GetUserAsync(User); <form class="flexer" asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <p><a asp-area="" asp-controller="Profile" asp-action="Index" title="Manage">Hello @user.Name!</a></p> <button type="submit" class="btn-hollow">Log out</button> </form> } else { <p><a asp-area="" asp-controller="Account" asp-action="Login">Log in</a></p> }
mit
C#
db241a8b1ccc5c2e6417d0750e4437950d00c8cb
add byte[] extension ToDosString()
martinlindhe/Punku
punku/Extensions/ByteArrayExtensions.cs
punku/Extensions/ByteArrayExtensions.cs
using System; using System.Text; // TODO: use this in metaemu & hexview. move their hex printing to helper extensions // TODO: like ToCString but for $-terminated DOS strings public static class ByteArrayExtensions { /** * Returns a hex string representation of the content */ public static string ToHexString (this byte[] bytes) { byte b; int cx = 0; char[] c = new char[bytes.Length * 2]; for (int bx = 0; bx < bytes.Length; ++bx) { b = (byte)(bytes [bx] >> 4); c [cx++] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30); b = (byte)(bytes [bx] & 0x0F); c [cx++] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30); } return new string (c); } /** * Decodes byte array to a C-string (each letter is 1 byte, 0 = end of text) */ public static string ToCString (this byte[] bytes) { var res = new StringBuilder (); foreach (byte x in bytes) { if (x == 0) break; res.Append ((char)x); } return res.ToString (); } /** * Decodes byte array to a DOS $-terminated string (each letter is 1 byte, $ = end of text) */ public static string ToDosString (this byte[] bytes) { var res = new StringBuilder (); foreach (byte x in bytes) { if (x == (byte)'$') break; res.Append ((char)x); } return res.ToString (); } }
using System; // TODO: use this in metaemu & hexview. move their hex printing to helper extensions public static class ByteArrayExtensions { public static string ToHexString (this byte[] bytes) { byte b; int cx = 0; char[] c = new char[bytes.Length * 2]; for (int bx = 0; bx < bytes.Length; ++bx) { b = (byte)(bytes [bx] >> 4); c [cx++] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30); b = (byte)(bytes [bx] & 0x0F); c [cx++] = (char)(b > 9 ? b + 0x37 + 0x20 : b + 0x30); } return new string (c); } public static string ToCString (this byte[] bytes) { int len; for (len = 0; len < bytes.Length; len++) if (bytes [len] == 0) break; char[] c = new char[len]; for (int i = 0; i < bytes.Length; i++) { // stop on NUL if (bytes [i] == 0) break; c [i] = (char)bytes [i]; } return new string (c); } }
mit
C#
7ee835358485b78cab17606f91be8479526aadb4
add patch to RestSharp proxy
dkackman/DynamicRestProxy,jamesholcomb/DynamicRestProxy,jamesholcomb/DynamicRestProxy,dkackman/DynamicRestProxy
DynamicRestProxy.RestSharp/RestInvocation.cs
DynamicRestProxy.RestSharp/RestInvocation.cs
using System; using System.Threading.Tasks; using System.Diagnostics; using RestSharp; namespace DynamicRestProxy { class RestInvocation { private readonly IRestClient _client; public RestInvocation(IRestClient client, string verb) { Debug.Assert(client != null); _client = client; Verb = verb; } public string Verb { get; private set; } public async Task<dynamic> InvokeAsync(IRestRequest request) { // set the result to the async task that will execute the request and create the dynamic object // based on the supplied verb if (Verb == "post") { return await _client.ExecuteDynamicTaskAsync(request, Method.POST); } else if (Verb == "get") { return await _client.ExecuteDynamicTaskAsync(request, Method.GET); } else if (Verb == "delete") { return await _client.ExecuteDynamicTaskAsync(request, Method.DELETE); } else if (Verb == "put") { return await _client.ExecuteDynamicTaskAsync(request, Method.PUT); } else if (Verb == "patch") { return await _client.ExecuteDynamicTaskAsync(request, Method.PATCH); } Debug.Assert(false, "unsupported verb"); throw new InvalidOperationException("unsupported verb: " + Verb); } } }
using System; using System.Threading.Tasks; using System.Diagnostics; using RestSharp; namespace DynamicRestProxy { class RestInvocation { private IRestClient _client; public RestInvocation(IRestClient client, string verb) { Debug.Assert(client != null); _client = client; Verb = verb; } public string Verb { get; private set; } public async Task<dynamic> InvokeAsync(IRestRequest request) { // set the result to the async task that will execute the request and create the dynamic object // based on the supplied verb if (Verb == "post") { return await _client.ExecuteDynamicTaskAsync(request, Method.POST); } else if (Verb == "get") { return await _client.ExecuteDynamicTaskAsync(request, Method.GET); } else if (Verb == "delete") { return await _client.ExecuteDynamicTaskAsync(request, Method.DELETE); } else if (Verb == "put") { return await _client.ExecuteDynamicTaskAsync(request, Method.PUT); } Debug.Assert(false, "unsupported verb"); throw new InvalidOperationException("unsupported verb: " + Verb); } } }
apache-2.0
C#
ec488572f888d60edc22e2424f8206d2d96ec77c
Update to 2.0.1
kamsar/Kamsar.WebConsole,kamsar/Kamsar.WebConsole
Kamsar.WebConsole/Properties/AssemblyInfo.cs
Kamsar.WebConsole/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Web.UI; [assembly: AssemblyTitle("Kamsar.WebConsole")] [assembly: AssemblyProduct("Kamsar.WebConsole")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.1")] [assembly: AssemblyFileVersion("2.0.1")] [assembly: AssemblyInformationalVersion("2.0.0")] [assembly: WebResource("Kamsar.WebConsole.Resources.console.css", "text/css")] [assembly: WebResource("Kamsar.WebConsole.Resources.console.js", "text/javascript")]
using System.Reflection; using System.Runtime.InteropServices; using System.Web.UI; [assembly: AssemblyTitle("Kamsar.WebConsole")] [assembly: AssemblyProduct("Kamsar.WebConsole")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.0")] [assembly: AssemblyFileVersion("2.0.0")] [assembly: AssemblyInformationalVersion("2.0.0")] [assembly: WebResource("Kamsar.WebConsole.Resources.console.css", "text/css")] [assembly: WebResource("Kamsar.WebConsole.Resources.console.js", "text/javascript")]
mit
C#
f7552075934e21f7b8b334ae0e4dc878f327383a
Fix minor matching issue
portaljacker/portalbot
src/portalbot/Commands/WeatherModule.cs
src/portalbot/Commands/WeatherModule.cs
using System; using DarkSky.Services; using Discord.Commands; using GoogleGeoCoderCore; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace portalbot.Commands { public class WeatherModule : ModuleBase { private static readonly Regex ValidCityState = new Regex(@"^[\p{L}\p{Mn}]+(?:[\s-][\p{L}\p{Mn}]+)*(?:(\,|(\,\s))?[\p{L}\p{Mn}]{2,})$", RegexOptions.IgnoreCase); private readonly GoogleGeocodeService _geocoder; private readonly DarkSkyService _darkSky; public WeatherModule(GoogleGeocodeService geocoder, DarkSkyService darkSky) { _geocoder = geocoder; _darkSky = darkSky; } [Command("weather")] [Summary("Echos a message.")] [Alias("woppy")] public async Task Weather([Remainder, Summary("City (State optional")] string city) { if (!ValidCityState.IsMatch(city)) { await ReplyAsync("Invalid city format, please try again. (eg. Montreal, QC)"); return; } var location = GetLocation(city); const double tolerance = 0.001f; if (Math.Abs(location.Result.Latitude) < tolerance && Math.Abs(location.Result.Longitude) < tolerance) { await ReplyAsync("City not found, please try again."); return; } var forecast = _darkSky.GetForecast(location.Result.Latitude, location.Result.Longitude); var currently = forecast.Result.Response.Currently; if (currently.ApparentTemperature != null && currently.WindSpeed != null) await ReplyAsync($"Weather in ***{city}*** is currently ***{(int)currently.ApparentTemperature}°F***, with wind speed of ***{(int)currently.WindSpeed}mph***."); } private async Task<Location> GetLocation(string address) { var result = await _geocoder.GeocodeLocation(address); return result; } } }
using System; using DarkSky.Services; using Discord.Commands; using GoogleGeoCoderCore; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace portalbot.Commands { public class WeatherModule : ModuleBase { private static readonly Regex ValidCityState = new Regex(@"^[\p{L}\p{Mn}]+(?:[\s-][a-zA-Z]+)*(?:(\,|(\,\s))?[\p{L}\p{Mn}]{2,})$", RegexOptions.IgnoreCase); private readonly GoogleGeocodeService _geocoder; private readonly DarkSkyService _darkSky; public WeatherModule(GoogleGeocodeService geocoder, DarkSkyService darkSky) { _geocoder = geocoder; _darkSky = darkSky; } [Command("weather")] [Summary("Echos a message.")] [Alias("woppy")] public async Task Weather([Remainder, Summary("City (State optional")] string city) { if (!ValidCityState.IsMatch(city)) { await ReplyAsync("Invalid city format, please try again. (eg. Montreal, QC)"); return; } var location = GetLocation(city); const double tolerance = 0.001f; if (Math.Abs(location.Result.Latitude) < tolerance && Math.Abs(location.Result.Longitude) < tolerance) { await ReplyAsync("City not found, please try again."); return; } var forecast = _darkSky.GetForecast(location.Result.Latitude, location.Result.Longitude); var currently = forecast.Result.Response.Currently; if (currently.ApparentTemperature != null && currently.WindSpeed != null) await ReplyAsync($"Weather in ***{city}*** is currently ***{(int)currently.ApparentTemperature}°F***, with wind speed of ***{(int)currently.WindSpeed}mph***."); } private async Task<Location> GetLocation(string address) { var result = await _geocoder.GeocodeLocation(address); return result; } } }
mit
C#
db498ee56213ebf3671310503dfe1393637032d1
Remove some using statements
cdhunt/NewRelicApiPoshProvider
NewRelicAPIPoshProvider/Items/Application.cs
NewRelicAPIPoshProvider/Items/Application.cs
using System; using System.Collections.Generic; namespace NewRelicAPIPoshProvider.Items { public class ListApplications { public List<Application> Applications { get; set; } } public class Application { public int Id { get; set; } public string Name { get; set; } public string Language { get; set; } public string Health_Status { get; set; } public bool Reporting { get; set; } public DateTime Last_Reported_At { get; set; } public ApplicationSummary Application_Summary { get; set; } public EndUserSummary End_User_Summary { get; set; } public Setting Settings { get; set; } public Link Links { get; set; } public List<Int32> Application_Hosts { get; set; } public List<Int32> Application_Instances { get; set; } public class ApplicationSummary { public float Response_Time { get; set; } public float Throughput { get; set; } public float Apdex_Target { get; set; } public float Apdex_Score { get; set; } } public class EndUserSummary { public float Response_Time { get; set; } public float Throughput { get; set; } public float Apdex_Target { get; set; } public float Apdex_Score { get; set; } } public class Setting { public float App_Apdex_Threshold { get; set; } public float End_User_Apdex_Threshold { get; set; } public bool Enable_Real_User_Monitoring { get; set; } public bool Use_Server_Side_Config { get; set; } } public class Link { public List<Int32> Servers { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; namespace NewRelicAPIPoshProvider.Items { public class ListApplications { public List<Application> Applications { get; set; } } public class Application { public int Id { get; set; } public string Name { get; set; } public string Language { get; set; } public string Health_Status { get; set; } public bool Reporting { get; set; } public DateTime Last_Reported_At { get; set; } public ApplicationSummary Application_Summary { get; set; } public EndUserSummary End_User_Summary { get; set; } public Setting Settings { get; set; } public Link Links { get; set; } public List<Int32> Application_Hosts { get; set; } public List<Int32> Application_Instances { get; set; } public class ApplicationSummary { public float Response_Time { get; set; } public float Throughput { get; set; } public float Apdex_Target { get; set; } public float Apdex_Score { get; set; } } public class EndUserSummary { public float Response_Time { get; set; } public float Throughput { get; set; } public float Apdex_Target { get; set; } public float Apdex_Score { get; set; } } public class Setting { public float App_Apdex_Threshold { get; set; } public float End_User_Apdex_Threshold { get; set; } public bool Enable_Real_User_Monitoring { get; set; } public bool Use_Server_Side_Config { get; set; } } public class Link { public List<Int32> Servers { get; set; } } } }
mit
C#
9404096a28c49a2c9370d6dd2d07a893d86f82df
Update tests to match new constructor
NeoAdonis/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu
osu.Game.Tests/Visual/Ranking/TestSceneStarRatingDisplay.cs
osu.Game.Tests/Visual/Ranking/TestSceneStarRatingDisplay.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { public TestSceneStarRatingDisplay() { Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new StarDifficulty(1.23, 0)), new StarRatingDisplay(new StarDifficulty(2.34, 0)), new StarRatingDisplay(new StarDifficulty(3.45, 0)), new StarRatingDisplay(new StarDifficulty(4.56, 0)), new StarRatingDisplay(new StarDifficulty(5.67, 0)), new StarRatingDisplay(new StarDifficulty(6.78, 0)), new StarRatingDisplay(new StarDifficulty(10.11, 0)), } }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Beatmaps; using osu.Game.Screens.Ranking.Expanded; namespace osu.Game.Tests.Visual.Ranking { public class TestSceneStarRatingDisplay : OsuTestScene { public TestSceneStarRatingDisplay() { Child = new FillFlowContainer { Anchor = Anchor.Centre, Origin = Anchor.Centre, Children = new Drawable[] { new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 1.23 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 2.34 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 3.45 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 4.56 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 5.67 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 6.78 }), new StarRatingDisplay(new BeatmapInfo { StarDifficulty = 10.11 }), } }; } } }
mit
C#
0f382590e6caa7e58f85ac30840289ea9c4b93f2
Remove unnecessary `#nullable disable`
peppy/osu,peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game/Rulesets/UI/Scrolling/IDrawableScrollingRuleset.cs
osu.Game/Rulesets/UI/Scrolling/IDrawableScrollingRuleset.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Game.Configuration; namespace osu.Game.Rulesets.UI.Scrolling { /// <summary> /// An interface for scrolling-based <see cref="DrawableRuleset{TObject}"/>s. /// </summary> public interface IDrawableScrollingRuleset { ScrollVisualisationMethod VisualisationMethod { get; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Game.Configuration; namespace osu.Game.Rulesets.UI.Scrolling { /// <summary> /// An interface for scrolling-based <see cref="DrawableRuleset{TObject}"/>s. /// </summary> public interface IDrawableScrollingRuleset { ScrollVisualisationMethod VisualisationMethod { get; } } }
mit
C#
e503407d2b2c2defd52a4c93637b28b7f883f8b0
Remove ctor
khellang/Middleware,khellang/Middleware
src/SpaFallback/SpaFallbackException.cs
src/SpaFallback/SpaFallbackException.cs
using System; using System.Text; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.SpaFallback { public class SpaFallbackException : Exception { private const string Fallback = nameof(SpaFallbackExtensions.UseSpaFallback); private const string StaticFiles = "UseStaticFiles"; private const string Mvc = "UseMvc"; public SpaFallbackException(PathString path) : base(GetMessage(path)) { } private static string GetMessage(PathString path) => new StringBuilder() .AppendLine($"The {Fallback} middleware failed to provide a fallback response for path '{path}' because no middleware could handle it.") .AppendLine($"Make sure {Fallback} is placed before any middleware that is supposed to provide the fallback response. This is typically {StaticFiles} or {Mvc}.") .AppendLine($"If you're using {StaticFiles}, make sure the file exists on disk and that the middleware is configured correctly.") .AppendLine($"If you're using {Mvc}, make sure you have a controller and action method that can handle '{path}'.") .ToString(); } }
using System; using System.Text; using Microsoft.AspNetCore.Http; namespace Hellang.Middleware.SpaFallback { public class SpaFallbackException : Exception { private const string Fallback = nameof(SpaFallbackExtensions.UseSpaFallback); private const string StaticFiles = "UseStaticFiles"; private const string Mvc = "UseMvc"; public SpaFallbackException(PathString path) : this(GetMessage(path)) { } public SpaFallbackException(string message) : base(message) { } private static string GetMessage(PathString path) => new StringBuilder() .AppendLine($"The {Fallback} middleware failed to provide a fallback response for path '{path}' because no middleware could handle it.") .AppendLine($"Make sure {Fallback} is placed before any middleware that is supposed to provide the fallback response. This is typically {StaticFiles} or {Mvc}.") .AppendLine($"If you're using {StaticFiles}, make sure the file exists on disk and that the middleware is configured correctly.") .AppendLine($"If you're using {Mvc}, make sure you have a controller and action method that can handle '{path}'.") .ToString(); } }
mit
C#
e0b921952848e87cabe2bdd55b05b7a8bb709891
Update MacroContent.cs to use `is` operator for comparison to null
abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,abjerner/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS
src/Umbraco.Core/Macros/MacroContent.cs
src/Umbraco.Core/Macros/MacroContent.cs
using System; namespace Umbraco.Web.Macros { // represents the content of a macro public class MacroContent { // gets or sets the text content public string Text { get; set; } // gets or sets the date the content was generated public DateTime Date { get; set; } = DateTime.Now; // a value indicating whether the content is empty public bool IsEmpty => Text is null; // gets an empty macro content public static MacroContent Empty { get; } = new MacroContent(); } }
using System; namespace Umbraco.Web.Macros { // represents the content of a macro public class MacroContent { // gets or sets the text content public string Text { get; set; } // gets or sets the date the content was generated public DateTime Date { get; set; } = DateTime.Now; // a value indicating whether the content is empty public bool IsEmpty => Text == null; // gets an empty macro content public static MacroContent Empty { get; } = new MacroContent(); } }
mit
C#
0ac7672b0a4ec4467972c5939208585420159020
Add binom command
ForNeVeR/wpf-math
src/WpfMath/Parsers/StandardCommands.cs
src/WpfMath/Parsers/StandardCommands.cs
using System.Collections.Generic; using WpfMath.Atoms; using WpfMath.Parsers.Matrices; namespace WpfMath.Parsers { internal static class StandardCommands { private class UnderlineCommand : ICommandParser { public CommandProcessingResult ProcessCommand(CommandContext context) { var source = context.CommandSource; var position = context.ArgumentsStartPosition; var underlineFormula = context.Parser.Parse( TexFormulaParser.ReadElement(source, ref position), context.Formula.TextStyle, context.Environment); var start = context.CommandNameStartPosition; var atomSource = source.Segment(start, position - start); var atom = new UnderlinedAtom(atomSource, underlineFormula.RootAtom); return new CommandProcessingResult(atom, position); } } private class BinomCommand : ICommandParser { public CommandProcessingResult ProcessCommand(CommandContext context) { //binom{2}{5} var source = context.CommandSource; var position = context.ArgumentsStartPosition; var top = context.Parser.Parse( TexFormulaParser.ReadElement(source, ref position), context.Formula.TextStyle, context.Environment); var bottom = context.Parser.Parse( TexFormulaParser.ReadElement(source, ref position), context.Formula.TextStyle, context.Environment); var start = context.CommandNameStartPosition; var atomSource = source.Segment(start, position - start); var atoms1 = new List<Atom> {top.RootAtom}; var atoms2 = new List<Atom> { bottom.RootAtom }; var atoms = new List<List<Atom>> { atoms1 , atoms2}; var matrixAtom = new MatrixAtom(atomSource, atoms, MatrixCellAlignment.Center); var left = new SymbolAtom(source, "(", TexAtomType.Opening, true); var right = new SymbolAtom(source, ")", TexAtomType.Closing, true); var fencedAtom = new FencedAtom(atomSource, matrixAtom, left, right); return new CommandProcessingResult(fencedAtom, position); } } public static IReadOnlyDictionary<string, ICommandParser> Dictionary = new Dictionary<string, ICommandParser> { ["cases"] = new MatrixCommandParser("lbrace", null, MatrixCellAlignment.Left), ["matrix"] = new MatrixCommandParser(null, null, MatrixCellAlignment.Center), ["pmatrix"] = new MatrixCommandParser("lbrack", "rbrack", MatrixCellAlignment.Center), ["underline"] = new UnderlineCommand(), ["binom"] = new BinomCommand() }; } }
using System.Collections.Generic; using WpfMath.Atoms; using WpfMath.Parsers.Matrices; namespace WpfMath.Parsers { internal static class StandardCommands { private class UnderlineCommand : ICommandParser { public CommandProcessingResult ProcessCommand(CommandContext context) { var source = context.CommandSource; var position = context.ArgumentsStartPosition; var underlineFormula = context.Parser.Parse( TexFormulaParser.ReadElement(source, ref position), context.Formula.TextStyle, context.Environment); var start = context.CommandNameStartPosition; var atomSource = source.Segment(start, position - start); var atom = new UnderlinedAtom(atomSource, underlineFormula.RootAtom); return new CommandProcessingResult(atom, position); } } public static IReadOnlyDictionary<string, ICommandParser> Dictionary = new Dictionary<string, ICommandParser> { ["cases"] = new MatrixCommandParser("lbrace", null, MatrixCellAlignment.Left), ["matrix"] = new MatrixCommandParser(null, null, MatrixCellAlignment.Center), ["pmatrix"] = new MatrixCommandParser("lbrack", "rbrack", MatrixCellAlignment.Center), ["underline"] = new UnderlineCommand() }; } }
mit
C#
9e03f78d472dba54e257aed8564a00581a1ca3c9
update assembly info
hylasoft-usa/h-dependency,hylasoft-usa/h-dependency
h-dependency/Properties/AssemblyInfo.cs
h-dependency/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("h-dependency")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("hylasoft")] [assembly: AssemblyProduct("h-dependency")] [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("76751769-0ec7-4eb0-a508-162a956c58a5")] // 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("0.0.1")] [assembly: AssemblyVersion("0.0.1")] [assembly: AssemblyFileVersion("0.0.1")]
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("h-dependency")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("h-dependency")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("76751769-0ec7-4eb0-a508-162a956c58a5")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
c25c626caeee72bf43823e7eff35ad457dab0435
Make open file also work at runtime
accu-rate/SumoVizUnity,accu-rate/SumoVizUnity
Assets/FileChooser.cs
Assets/FileChooser.cs
using UnityEngine; using System.Collections; public class FileChooser : MonoBehaviour { FileBrowser fb = new FileBrowser(); FileLoaderXML fl = new FileLoaderXML(); // Use this for initialization void Start () { fb.searchPattern = "*.xml"; } void OnGUI(){ if (fb.draw()) { if (fb.outputFile == null){ Debug.Log("Cancel hit"); Application.Quit(); } else { Debug.Log("Ouput File = \""+fb.outputFile.ToString()+"\""); /*the outputFile variable is of type FileInfo from the .NET library "http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx"*/ fl.loadXMLFile(fb.outputFile.FullName); Destroy (this); } } } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; public class FileChooser : MonoBehaviour { FileBrowser fb = new FileBrowser(); void OnGUI(){ fb.searchPattern = "*.xml"; FileLoaderXML fl = new FileLoaderXML(); if(fb.draw()){ if(fb.outputFile == null){ Debug.Log("Cancel hit"); }else{ Debug.Log("Ouput File = \""+fb.outputFile.ToString()+"\""); /*the outputFile variable is of type FileInfo from the .NET library "http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx"*/ fl.loadXMLFile(fb.outputFile.ToString()); } } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
92d4aa0d8b5f17e41b2bdf594da6f6d28f22d28d
Fix typo in TransactionManager
Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum,Nethereum/Nethereum
src/Nethereum.RPC/TransactionManagers/TransactionManager.cs
src/Nethereum.RPC/TransactionManagers/TransactionManager.cs
using System; using System.Threading.Tasks; using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.Transactions; using Nethereum.RPC.Eth.DTOs; using System.Numerics; namespace Nethereum.RPC.TransactionManagers { public class TransactionManager : TransactionManagerBase { public override BigInteger DefaultGasPrice { get; set; } public override BigInteger DefaultGas { get; set; } public override Task<string> SignTransactionAsync(TransactionInput transaction) { throw new InvalidOperationException("Default transaction manager cannot sign offline transactions"); } public override Task<string> SignTransactionRetrievingNextNonceAsync(TransactionInput transaction) { throw new InvalidOperationException("Default transaction manager cannot sign offline transactions"); } public TransactionManager(IClient client) { this.Client = client; } public override Task<string> SendTransactionAsync(TransactionInput transactionInput) { if (Client == null) throw new NullReferenceException("Client not configured"); if (transactionInput == null) throw new ArgumentNullException(nameof(transactionInput)); SetDefaultGasPriceAndCostIfNotSet(transactionInput); return new EthSendTransaction(Client).SendRequestAsync(transactionInput); } } }
using System; using System.Threading.Tasks; using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.Transactions; using Nethereum.RPC.Eth.DTOs; using System.Numerics; namespace Nethereum.RPC.TransactionManagers { public class TransactionManager : TransactionManagerBase { public override BigInteger DefaultGasPrice { get; set; } public override BigInteger DefaultGas { get; set; } public override Task<string> SignTransactionAsync(TransactionInput transaction) { throw new InvalidOperationException("Default transaction manager cannot sign offline transactions"); } public override Task<string> SignTransactionRetrievingNextNonceAsync(TransactionInput transaction) { throw new InvalidOperationException("Default transaction manager sign offline transactions"); } public TransactionManager(IClient client) { this.Client = client; } public override Task<string> SendTransactionAsync(TransactionInput transactionInput) { if (Client == null) throw new NullReferenceException("Client not configured"); if (transactionInput == null) throw new ArgumentNullException(nameof(transactionInput)); SetDefaultGasPriceAndCostIfNotSet(transactionInput); return new EthSendTransaction(Client).SendRequestAsync(transactionInput); } } }
mit
C#
04974714bc392db74873a2711a376159bc98d5db
Divide weapon arc by half
iridinite/shiftdrive
Client/WeaponMount.cs
Client/WeaponMount.cs
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// Represents the maximum weapon size that a mount can hold. /// </summary> internal enum MountSize { Small = 1, Medium = 2, Large = 3 } /// <summary> /// Represents an attachment point for a weapon. /// </summary> internal sealed class WeaponMount { public Vector2 Offset; public Vector2 Position; public float Bearing; public float Arc; public float OffsetMag; public MountSize Size; public static WeaponMount FromLua(IntPtr L, int tableidx) { LuaAPI.luaL_checktype(L, tableidx, LuaAPI.LUA_TTABLE); WeaponMount ret = new WeaponMount(); LuaAPI.lua_getfield(L, tableidx, "position"); LuaAPI.lua_checkfieldtype(L, tableidx, "position", -1, LuaAPI.LUA_TTABLE); ret.Offset = LuaAPI.lua_tovec2(L, -1); ret.OffsetMag = -ret.Offset.Length(); LuaAPI.lua_pop(L, 1); ret.Bearing = LuaAPI.luaH_gettablefloat(L, tableidx, "bearing"); ret.Arc = LuaAPI.luaH_gettablefloat(L, tableidx, "arc") / 2f; ret.Size = (MountSize)LuaAPI.luaH_gettableint(L, tableidx, "size"); return ret; } } }
/* ** Project ShiftDrive ** (C) Mika Molenkamp, 2016. */ using System; using Microsoft.Xna.Framework; namespace ShiftDrive { /// <summary> /// Represents the maximum weapon size that a mount can hold. /// </summary> internal enum MountSize { Small = 1, Medium = 2, Large = 3 } /// <summary> /// Represents an attachment point for a weapon. /// </summary> internal sealed class WeaponMount { public Vector2 Offset; public Vector2 Position; public float Bearing; public float Arc; public float OffsetMag; public MountSize Size; public static WeaponMount FromLua(IntPtr L, int tableidx) { LuaAPI.luaL_checktype(L, tableidx, LuaAPI.LUA_TTABLE); WeaponMount ret = new WeaponMount(); LuaAPI.lua_getfield(L, tableidx, "position"); LuaAPI.lua_checkfieldtype(L, tableidx, "position", -1, LuaAPI.LUA_TTABLE); ret.Offset = LuaAPI.lua_tovec2(L, -1); ret.OffsetMag = -ret.Offset.Length(); LuaAPI.lua_pop(L, 1); ret.Bearing = LuaAPI.luaH_gettablefloat(L, tableidx, "bearing"); ret.Arc = LuaAPI.luaH_gettablefloat(L, tableidx, "arc"); ret.Size = (MountSize)LuaAPI.luaH_gettableint(L, tableidx, "size"); return ret; } } }
bsd-3-clause
C#