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 |
|---|---|---|---|---|---|---|---|---|
adc9cdc30d653b041155847123efb15e4d869a50 | Create CrowdSSOAPICall.cs | ryanmcdonough/CrowdSSO | CrowdSSOAPICall.cs | CrowdSSOAPICall.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public sealed class CrowdSSOAPICall
{
private readonly String name;
private readonly int value;
public static readonly CrowdSSOAPICall Authenticate = new CrowdSSOAPICall(1, "authentication?username=");
public static readonly CrowdSSOAPICall ChangePassword = new CrowdSSOAPICall(2, "user/password?username=");
public static readonly CrowdSSOAPICall RequestPasswordReset = new CrowdSSOAPICall(3, "user/mail/password?username=");
public static readonly CrowdSSOAPICall UsersInGroup = new CrowdSSOAPICall(4, "group/user/nested?groupname=");
public static readonly CrowdSSOAPICall UserDetail = new CrowdSSOAPICall(5, "user/attribute?username=");
private CrowdSSOAPICall(int value, String name)
{
this.name = name;
this.value = value;
}
public override String ToString()
{
return name;
}
}
| mit | C# | |
95f808e17f6827f8f9e8b9b0b52c77fb451e2194 | Add calls to AssertIsOnMainThread. | AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS | src/Package/Impl/ProjectSystem/IVsHierarchyExtensions.cs | src/Package/Impl/ProjectSystem/IVsHierarchyExtensions.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.R.Components.Extensions;
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem.Designers;
using Microsoft.VisualStudio.R.Package.Shell;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.R.Package.ProjectSystem {
internal static class IVsHierarchyExtensions {
/// <summary>
/// Returns EnvDTE.Project object for the hierarchy
/// </summary>
public static EnvDTE.Project GetDTEProject(this IVsHierarchy hierarchy) {
VsAppShell.Current.AssertIsOnMainThread();
object extObject;
if (ErrorHandler.Succeeded(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out extObject))) {
return extObject as EnvDTE.Project;
}
return null;
}
/// <summary>
/// Convenient way to get to the UnconfiguredProject from the hierarchy
/// </summary>
public static UnconfiguredProject GetUnconfiguredProject(this IVsHierarchy hierarchy) {
VsAppShell.Current.AssertIsOnMainThread();
IVsBrowseObjectContext context = hierarchy as IVsBrowseObjectContext;
if (context == null) {
EnvDTE.Project dteProject = hierarchy.GetDTEProject();
if (dteProject != null) {
context = dteProject.Object as IVsBrowseObjectContext;
}
}
return context?.UnconfiguredProject;
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.VisualStudio.ProjectSystem;
using Microsoft.VisualStudio.ProjectSystem.Designers;
using Microsoft.VisualStudio.Shell.Interop;
namespace Microsoft.VisualStudio.R.Package.ProjectSystem {
internal static class IVsHierarchyExtensions {
/// <summary>
/// Returns EnvDTE.Project object for the hierarchy
/// </summary>
public static EnvDTE.Project GetDTEProject(this IVsHierarchy hierarchy) {
//UIThreadHelper.VerifyOnUIThread();
object extObject;
if (ErrorHandler.Succeeded(hierarchy.GetProperty(VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ExtObject, out extObject))) {
return extObject as EnvDTE.Project;
}
return null;
}
/// <summary>
/// Convenient way to get to the UnconfiguredProject from the hierarchy
/// </summary>
public static UnconfiguredProject GetUnconfiguredProject(this IVsHierarchy hierarchy) {
//UIThreadHelper.VerifyOnUIThread();
IVsBrowseObjectContext context = hierarchy as IVsBrowseObjectContext;
if (context == null) {
EnvDTE.Project dteProject = hierarchy.GetDTEProject();
if (dteProject != null) {
context = dteProject.Object as IVsBrowseObjectContext;
}
}
return context?.UnconfiguredProject;
}
}
}
| mit | C# |
abfbadbaf4a40654c429ef165e437fd218192401 | Copy FileSystemGlobbing and HashCodeCombiner sources | schellap/core-setup,ravimeda/core-setup,vivmishra/core-setup,cakine/core-setup,weshaggard/core-setup,rakeshsinghranchi/core-setup,cakine/core-setup,joperezr/core-setup,chcosta/core-setup,rakeshsinghranchi/core-setup,ravimeda/core-setup,cakine/core-setup,joperezr/core-setup,janvorli/core-setup,joperezr/core-setup,schellap/core-setup,wtgodbe/core-setup,steveharter/core-setup,chcosta/core-setup,janvorli/core-setup,ramarag/core-setup,MichaelSimons/core-setup,zamont/core-setup,schellap/core-setup,gkhanna79/core-setup,MichaelSimons/core-setup,ericstj/core-setup,ramarag/core-setup,crummel/dotnet_core-setup,ramarag/core-setup,ravimeda/core-setup,ravimeda/core-setup,joperezr/core-setup,MichaelSimons/core-setup,ramarag/core-setup,MichaelSimons/core-setup,ravimeda/core-setup,ericstj/core-setup,weshaggard/core-setup,janvorli/core-setup,rakeshsinghranchi/core-setup,crummel/dotnet_core-setup,crummel/dotnet_core-setup,gkhanna79/core-setup,weshaggard/core-setup,wtgodbe/core-setup,karajas/core-setup,janvorli/core-setup,steveharter/core-setup,gkhanna79/core-setup,ellismg/core-setup,zamont/core-setup,rakeshsinghranchi/core-setup,steveharter/core-setup,schellap/core-setup,vivmishra/core-setup,wtgodbe/core-setup,chcosta/core-setup,janvorli/core-setup,ellismg/core-setup,karajas/core-setup,karajas/core-setup,zamont/core-setup,MichaelSimons/core-setup,ericstj/core-setup,gkhanna79/core-setup,ravimeda/core-setup,rakeshsinghranchi/core-setup,ericstj/core-setup,vivmishra/core-setup,joperezr/core-setup,weshaggard/core-setup,weshaggard/core-setup,wtgodbe/core-setup,vivmishra/core-setup,crummel/dotnet_core-setup,vivmishra/core-setup,karajas/core-setup,ellismg/core-setup,cakine/core-setup,zamont/core-setup,ramarag/core-setup,ramarag/core-setup,wtgodbe/core-setup,crummel/dotnet_core-setup,gkhanna79/core-setup,steveharter/core-setup,weshaggard/core-setup,wtgodbe/core-setup,karajas/core-setup,vivmishra/core-setup,ellismg/core-setup,ellismg/core-setup,chcosta/core-setup,crummel/dotnet_core-setup,joperezr/core-setup,zamont/core-setup,zamont/core-setup,MichaelSimons/core-setup,ericstj/core-setup,schellap/core-setup,steveharter/core-setup,chcosta/core-setup,ericstj/core-setup,ellismg/core-setup,rakeshsinghranchi/core-setup,gkhanna79/core-setup,cakine/core-setup,schellap/core-setup,karajas/core-setup,chcosta/core-setup,steveharter/core-setup,cakine/core-setup,janvorli/core-setup | HashCodeCombiner.cs | HashCodeCombiner.cs | // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System.Collections.Generic;
using System.Runtime.CompilerServices;
namespace Microsoft.DotNet.InternalAbstractions
{
public struct HashCodeCombiner
{
private long _combinedHash64;
public int CombinedHash
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return _combinedHash64.GetHashCode(); }
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private HashCodeCombiner(long seed)
{
_combinedHash64 = seed;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(int i)
{
_combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(string s)
{
var hashCode = (s != null) ? s.GetHashCode() : 0;
Add(hashCode);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add(object o)
{
var hashCode = (o != null) ? o.GetHashCode() : 0;
Add(hashCode);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Add<TValue>(TValue value, IEqualityComparer<TValue> comparer)
{
var hashCode = value != null ? comparer.GetHashCode(value) : 0;
Add(hashCode);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static HashCodeCombiner Start()
{
return new HashCodeCombiner(0x1505L);
}
}
} | mit | C# | |
515b169f13582ae0083fcc6245b6dca7ffe7c62a | Add generic WebAgentPool | CrustyJew/RedditSharp,justcool393/RedditSharp-1,pimanac/RedditSharp | RedditSharp/WebAgentPool.cs | RedditSharp/WebAgentPool.cs | using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Reactive.Subjects;
using System.Text;
using System.Threading.Tasks;
namespace RedditSharp
{
/// <summary>
/// Generic memory cache wrapper for storing and retrieving <see cref="IWebAgent"/>s. Items are stored in memory until explicitly removed.
/// </summary>
/// <typeparam name="TKey">Key type to store agents</typeparam>
/// <typeparam name="TAgent">Web Agent type. Must inherit from <see cref="IWebAgent"/></typeparam>
public class WebAgentPool<TKey, TAgent>
where TAgent : IWebAgent
{
private MemoryCache activeAgentsCache = new MemoryCache(new MemoryCacheOptions() { CompactOnMemoryPressure = false });
/// <summary>
/// Returns the <typeparamref name="TAgent"/> corresponding to the <paramref name="key"/>
/// </summary>
/// <param name="key">Key of Web Agent to return</param>
/// <returns><typeparamref name="TAgent"/></returns>
public TAgent GetAgent(TKey key) {
return activeAgentsCache.Get<TAgent>(key);
}
/// <summary>
/// Gets or Creates the <typeparamref name="TAgent"/> with the given key.
/// </summary>
/// <param name="key">Key of Web Agent to return or create</param>
/// <param name="create">Function that returns the <typeparamref name="TAgent" /> corresponding to the <paramref name="key"/></param>
/// <returns></returns>
public Task<TAgent> GetOrCreateAgentAsync(TKey key, Func<Task<TAgent>> create)
{
return activeAgentsCache.GetOrCreateAsync<TAgent>(key, (c) =>
{
c.AbsoluteExpiration = null;
c.SlidingExpiration = null;
return create();
});
}
/// <summary>
/// Sets the web agent at the given key to be equal to the given value.
/// </summary>
/// <param name="key"></param>
/// <param name="agent"></param>
public void SetAgent(TKey key, TAgent agent)
{
activeAgentsCache.Set(key, agent);
}
/// <summary>
/// Removes the web agent at the given key from the cache
/// </summary>
/// <param name="key"></param>
public void RemoveAgent(TKey key)
{
activeAgentsCache.Remove(key);
}
}
}
| mit | C# | |
80adc2102019acf2211461f149dd0da472b45cec | Add Factory5 with PresentAllowTearing feature check. | sharpdx/SharpDX,sharpdx/SharpDX,sharpdx/SharpDX | Source/SharpDX.DXGI/Factory5.cs | Source/SharpDX.DXGI/Factory5.cs | // Copyright (c) 2010-2014 SharpDX - Alexandre Mutel
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using SharpDX.Mathematics.Interop;
namespace SharpDX.DXGI
{
public partial class Factory5
{
/// <summary>
/// Gets if tearing is allowed during present.
/// </summary>
public unsafe bool PresentAllowTearing
{
get
{
RawBool allowTearing;
CheckFeatureSupport(Feature.PresentAllowTearing, new IntPtr(&allowTearing), sizeof(RawBool));
return allowTearing;
}
}
}
} | mit | C# | |
c8dda5bbb1bc56787c8c0baf0bd96bc72e2c37c6 | Add ProductBuilderFromScratch. | tdpreece/TestObjectBuilderCsharp | Examples/ProductBuilderFromScratch.cs | Examples/ProductBuilderFromScratch.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Examples
{
class ProductBuilderFromScratch
{
Product Build()
{
return new Product(this.X);
}
ProductBuilderFromScratch With(int x)
{
this.X = x;
return this;
}
ProductBuilderFromScratch With(List<int> y)
{
this.Y = y;
return this;
}
ProductBuilderFromScratch But()
{
return (ProductBuilderFromScratch)this.MemberwiseClone();
}
public int X { get; set; }
public List<int> Y { get; set; }
}
}
| mit | C# | |
0ca73bfb52f9e40e5c6d56bb78e4791b22d96113 | Update core | sunkaixuan/SqlSugar | Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/Compatible.cs | Src/Asp.NetCore2/SqlSeverTest/SqlSugar/OnlyCore/Compatible.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SqlSugar
{
public class SugarCompatible
{
public const bool IsFramework = false;
}
}
| apache-2.0 | C# | |
884079fd8b2e3ba1dc3991e8939ad1025bd0e1e2 | Create EditorWindowExtension.cs | kinifi/framework-unity | EditorExtensions/Template/Editor/EditorWindowExtension.cs | EditorExtensions/Template/Editor/EditorWindowExtension.cs | /*
* Must be located in a folder called "Editor"
* Note: the %l is the shortcut for opening this window in unity. % = Alt/CMD button
*/
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine.Assertions;
public class EditorWindowExtension : EditorWindow
{
[MenuItem("Window/Language Editor %l")]
public static void ShowEditor()
{
//create the editor window
EditorWindowExtension editor = EditorWindow.GetWindow<EditorWindowExtension>();
//the editor window must have a min size
editor.titleContent = new GUIContent("Editor");
editor.minSize = new Vector2 (600, 400);
//call the init method after we create our window
editor.Init();
}
private void Init()
{
}
private void OnGUI()
{
}
//UNITY EVENTS START
public void PlaymodeChanged()
{
Repaint();
}
public void OnLostFocus ()
{
Repaint();
}
public void OnFocus()
{
Repaint();
}
public void OnProjectChange ()
{
Repaint();
}
public void OnSelectionChange ()
{
Repaint();
}
//UNITY EVENTS END
}
| mit | C# | |
af039ef132047ee4f1dd8139b05f3bfb1c70ff6b | Create RowParseTest.cs | bytefish/TinyCsvParser | TinyCsvParser/TinyCsvParser.Test/Examples/RowParseTest.cs | TinyCsvParser/TinyCsvParser.Test/Examples/RowParseTest.cs | using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using TinyCsvParser.Mapping;
using TinyCsvParser.Model;
namespace TinyCsvParser.Test.Examples
{
public static class EnumerableExtensions
{
public static IEnumerable<IEnumerable<T>> Batch<T>(this IEnumerable<T> source, int size)
{
T[] bucket = null;
var count = 0;
foreach (var item in source)
{
if (bucket == null)
{
bucket = new T[size];
}
bucket[count++] = item;
if (count != size)
{
continue;
}
yield return bucket.Select(x => x);
bucket = null;
count = 0;
}
if (bucket != null && count > 0)
{
yield return bucket.Take(count);
}
}
}
public class RowBasedCsvParser<TEntity>
{
private readonly CsvParserOptions options;
private readonly ICsvMapping<TEntity> mapping;
public RowBasedCsvParser(CsvParserOptions options, ICsvMapping<TEntity> mapping)
{
this.options = options;
this.mapping = mapping;
}
public IEnumerable<CsvMappingResult<TEntity>> Parse(string rowData, int numberOfProperties)
{
if (rowData == null)
{
throw new ArgumentNullException(nameof(rowData));
}
// This could be too huge for In-Memory. Maybe optimize it, so you
// are using IEnumerable:
var tokens = options.Tokenizer.Tokenize(rowData);
return tokens
// Now we Batch the Columns into smaller groups, so they resemble a Row:
.Batch(numberOfProperties)
.Select((x, i) => new TokenizedRow(i * numberOfProperties, x.ToArray()))
.Select(x => mapping.Map(x));
}
public override string ToString()
{
return $"CsvParser (Options = {options})";
}
}
// Test Entities
public class TestEntityForRow
{
public string A { get; set; }
public string B { get; set; }
}
public class TestEntityForRowMapper : CsvMapping<TestEntityForRow>
{
public TestEntityForRowMapper()
{
MapProperty(0, x => x.A);
MapProperty(1, x => x.B);
}
}
[TestFixture]
public class RowParseTest
{
[Test]
public void TestCustomRowParser()
{
string csvRowTestData = "1,2,3,4,5,6,7,8";
var csvParserOptions = new CsvParserOptions(true, ',');
var csvReaderOptions = new CsvReaderOptions(new[] { Environment.NewLine });
var csvMapper = new TestEntityForRowMapper();
var csvParser = new RowBasedCsvParser<TestEntityForRow>(csvParserOptions, csvMapper);
var res = csvParser
.Parse(csvRowTestData, 2)
.Where(x => x.IsValid)
.ToList();
Assert.AreEqual(4, res.Count);
Assert.AreEqual("1", res[0].Result.A);
Assert.AreEqual("2", res[0].Result.B);
}
}
}
| mit | C# | |
97229c7e19ba065381dd96c24a4be086bdda15a3 | Bump version to 3.1 | deluxetiky/FluentValidation,cecilphillip/FluentValidation,glorylee/FluentValidation,roend83/FluentValidation,regisbsb/FluentValidation,roend83/FluentValidation,IRlyDontKnow/FluentValidation,olcayseker/FluentValidation,robv8r/FluentValidation,ruisebastiao/FluentValidation,mgmoody42/FluentValidation,pacificIT/FluentValidation,GDoronin/FluentValidation | src/CommonAssemblyInfo.cs | src/CommonAssemblyInfo.cs | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2011")]
[assembly : ComVisible(false)]
[assembly : AssemblyVersion("3.1.0.0")]
[assembly : AssemblyFileVersion("3.1.0.0")]
[assembly: CLSCompliant(true)]
#if !SILVERLIGHT
[assembly: AllowPartiallyTrustedCallers]
#endif | #region License
// Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// The latest version of this file can be found at http://www.codeplex.com/FluentValidation
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly : AssemblyTitle("FluentValidation")]
[assembly : AssemblyDescription("FluentValidation")]
[assembly : AssemblyProduct("FluentValidation")]
[assembly : AssemblyCopyright("Copyright (c) Jeremy Skinner 2008-2011")]
[assembly : ComVisible(false)]
[assembly : AssemblyVersion("3.0.0.1")]
[assembly : AssemblyFileVersion("3.0.0.1")]
[assembly: CLSCompliant(true)]
#if !SILVERLIGHT
[assembly: AllowPartiallyTrustedCallers]
#endif | apache-2.0 | C# |
34dfa06b4b4898799016e12c9c5b77abb800c475 | add unary call overhead benchmark | stanley-cheung/grpc,nicolasnoble/grpc,ctiller/grpc,nicolasnoble/grpc,ejona86/grpc,firebase/grpc,ejona86/grpc,vjpai/grpc,donnadionne/grpc,muxi/grpc,donnadionne/grpc,nicolasnoble/grpc,ctiller/grpc,muxi/grpc,firebase/grpc,pszemus/grpc,pszemus/grpc,jtattermusch/grpc,pszemus/grpc,firebase/grpc,ejona86/grpc,donnadionne/grpc,jtattermusch/grpc,muxi/grpc,vjpai/grpc,nicolasnoble/grpc,nicolasnoble/grpc,vjpai/grpc,nicolasnoble/grpc,grpc/grpc,muxi/grpc,firebase/grpc,nicolasnoble/grpc,grpc/grpc,vjpai/grpc,ejona86/grpc,jtattermusch/grpc,ejona86/grpc,ctiller/grpc,pszemus/grpc,jtattermusch/grpc,grpc/grpc,jboeuf/grpc,firebase/grpc,grpc/grpc,jboeuf/grpc,jtattermusch/grpc,ctiller/grpc,nicolasnoble/grpc,nicolasnoble/grpc,grpc/grpc,pszemus/grpc,vjpai/grpc,ctiller/grpc,jboeuf/grpc,donnadionne/grpc,ctiller/grpc,jtattermusch/grpc,nicolasnoble/grpc,donnadionne/grpc,jboeuf/grpc,jboeuf/grpc,jtattermusch/grpc,jtattermusch/grpc,grpc/grpc,muxi/grpc,muxi/grpc,nicolasnoble/grpc,nicolasnoble/grpc,stanley-cheung/grpc,ctiller/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,jboeuf/grpc,jboeuf/grpc,donnadionne/grpc,jboeuf/grpc,pszemus/grpc,ctiller/grpc,firebase/grpc,stanley-cheung/grpc,ejona86/grpc,firebase/grpc,stanley-cheung/grpc,grpc/grpc,pszemus/grpc,firebase/grpc,pszemus/grpc,jtattermusch/grpc,ejona86/grpc,muxi/grpc,jboeuf/grpc,ejona86/grpc,pszemus/grpc,grpc/grpc,muxi/grpc,donnadionne/grpc,muxi/grpc,stanley-cheung/grpc,stanley-cheung/grpc,donnadionne/grpc,firebase/grpc,muxi/grpc,ejona86/grpc,vjpai/grpc,ctiller/grpc,ctiller/grpc,vjpai/grpc,ejona86/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,grpc/grpc,vjpai/grpc,stanley-cheung/grpc,stanley-cheung/grpc,stanley-cheung/grpc,donnadionne/grpc,donnadionne/grpc,vjpai/grpc,ctiller/grpc,grpc/grpc,firebase/grpc,grpc/grpc,donnadionne/grpc,jtattermusch/grpc,pszemus/grpc,muxi/grpc,firebase/grpc,jboeuf/grpc,firebase/grpc,jtattermusch/grpc,jtattermusch/grpc,vjpai/grpc,muxi/grpc,jboeuf/grpc,vjpai/grpc,vjpai/grpc,pszemus/grpc,donnadionne/grpc,pszemus/grpc,jboeuf/grpc,ejona86/grpc | src/csharp/Grpc.Microbenchmarks/UnaryCallOverheadBenchmark.cs | src/csharp/Grpc.Microbenchmarks/UnaryCallOverheadBenchmark.cs | #region Copyright notice and license
// Copyright 2019 The gRPC Authors
//
// 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.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using Grpc.Core;
using Grpc.Core.Internal;
using System;
namespace Grpc.Microbenchmarks
{
// this test creates a real server and client, measuring the inherent inbuilt
// platform overheads; the marshallers **DO NOT ALLOCATE**, so any allocations
// are from the framework, not the messages themselves
// important: allocs are not reliable on .NET Core until .NET Core 3, since
// this test involves multiple threads
[ClrJob, CoreJob] // test .NET Core and .NET Framework
[MemoryDiagnoser] // allocations
public class UnaryCallOverheadBenchmark
{
private static readonly Task<string> CompletedString = Task.FromResult("");
private static readonly byte[] EmptyBlob = new byte[0];
private static readonly Marshaller<string> EmptyMarshaller = new Marshaller<string>(_ => EmptyBlob, _ => "");
private static readonly Method<string, string> PingMethod = new Method<string, string>(MethodType.Unary, nameof(PingBenchmark), "Ping", EmptyMarshaller, EmptyMarshaller);
[Benchmark]
public string Ping()
{
return client.Ping("", new CallOptions());
}
Channel channel;
PingClient client;
[GlobalSetup]
public void Setup()
{
// create client
channel = new Channel("localhost", 10042, ChannelCredentials.Insecure);
client = new PingClient(new DefaultCallInvoker(channel));
var native = NativeMethods.Get();
// replace the implementation of a native method with a fake
NativeMethods.Delegates.grpcsharp_call_start_unary_delegate fakeCallStartUnary = (CallSafeHandle call, BatchContextSafeHandle ctx, byte[] sendBuffer, UIntPtr sendBufferLen, WriteFlags writeFlags, MetadataArraySafeHandle metadataArray, CallFlags metadataFlags) => {
return native.grpcsharp_test_call_start_unary_echo(call, ctx, sendBuffer, sendBufferLen, writeFlags, metadataArray, metadataFlags);
};
native.GetType().GetField(nameof(native.grpcsharp_call_start_unary)).SetValue(native, fakeCallStartUnary);
NativeMethods.Delegates.grpcsharp_completion_queue_pluck_delegate fakeCqPluck = (CompletionQueueSafeHandle cq, IntPtr tag) => {
return new CompletionQueueEvent {
type = CompletionQueueEvent.CompletionType.OpComplete,
success = 1,
tag = tag
};
};
native.GetType().GetField(nameof(native.grpcsharp_completion_queue_pluck)).SetValue(native, fakeCqPluck);
}
[GlobalCleanup]
public async Task Cleanup()
{
await channel.ShutdownAsync();
}
class PingClient : LiteClientBase
{
public PingClient(CallInvoker callInvoker) : base(callInvoker) { }
public string Ping(string request, CallOptions options)
{
return CallInvoker.BlockingUnaryCall(PingMethod, null, options, request);
}
}
}
}
| apache-2.0 | C# | |
bde26a8282cf7d3e173413a49a88f25a6bee0db1 | Add missing file | EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,RavenB/opensim,TomDataworks/opensim,RavenB/opensim,RavenB/opensim,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC | OpenSim/Framework/Capabilities/LLSDTaskScriptUploadComplete.cs | OpenSim/Framework/Capabilities/LLSDTaskScriptUploadComplete.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
using System;
using System.Collections;
namespace OpenSim.Framework.Capabilities
{
[OSDMap]
public class LLSDTaskScriptUploadComplete
{
/// <summary>
/// The task inventory item that was updated
/// </summary>
public UUID new_asset;
/// <summary>
/// Was it compiled?
/// </summary>
public bool compiled;
/// <summary>
/// State of the upload. So far have only even seen this set to "complete"
/// </summary>
public string state;
public OSDArray errors;
}
}
| bsd-3-clause | C# | |
eec7996b3713dce42b456d53a39258662d5f3075 | Test for code creation from generating polynomial was added | litichevskiydv/GfPolynoms,litichevskiydv/GfPolynoms | test/WaveletCodesTools.Tests/StandardCodesFactoryTests.cs | test/WaveletCodesTools.Tests/StandardCodesFactoryTests.cs | namespace AppliedAlgebra.WaveletCodesTools.Tests
{
using CodesResearchTools.NoiseGenerator;
using Decoding.ListDecoderForFixedDistanceCodes;
using Decoding.StandartDecoderForFixedDistanceCodes;
using FixedDistanceCodesFactory;
using GeneratingPolynomialsBuilder;
using GfAlgorithms.CombinationsCountCalculator;
using GfAlgorithms.ComplementaryFilterBuilder;
using GfAlgorithms.LinearSystemSolver;
using GfAlgorithms.PolynomialsGcdFinder;
using GfPolynoms;
using GfPolynoms.GaloisFields;
using RsCodesTools.Decoding.ListDecoder;
using RsCodesTools.Decoding.ListDecoder.GsDecoderDependencies.InterpolationPolynomialBuilder;
using RsCodesTools.Decoding.ListDecoder.GsDecoderDependencies.InterpolationPolynomialFactorisator;
using RsCodesTools.Decoding.StandartDecoder;
using Xunit;
public class StandardCodesFactoryTests
{
private static readonly StandardCodesFactory CodesFactory;
static StandardCodesFactoryTests()
{
var gaussSolver = new GaussSolver();
CodesFactory
= new StandardCodesFactory(
new LiftingSchemeBasedBuilder(new GcdBasedBuilder(new RecursiveGcdFinder()), gaussSolver),
new RsBasedDecoder(new BerlekampWelchDecoder(gaussSolver), gaussSolver),
new GsBasedDecoder(
new GsDecoder(new KotterAlgorithmBasedBuilder(new PascalsTriangleBasedCalcualtor()), new RrFactorizator()),
gaussSolver
)
);
}
[Fact]
public void ShouldCreateCodeFromGeneratingPolynomial()
{
// Given
var generationPolynomial = new Polynomial(
new PrimePowerOrderField(8, new Polynomial(new PrimeOrderField(2), 1, 1, 0, 1)),
0, 0, 2, 5, 6, 0, 1
);
// When
var code = CodesFactory.Create(generationPolynomial);
// Then
Assert.Equal(7, code.CodewordLength);
Assert.Equal(3, code.InformationWordLength);
Assert.Equal(4, code.CodeDistance);
}
}
} | mit | C# | |
2b980cd972492660beb80aedd219ef08cbd05364 | Update LibraryApp | gdm-201516-prodev3/wdad3,gdm-201516-prodev3/wdad3,gdm-201516-prodev3/wdad3 | LibraryApp/App.API/Controllers/LibraryItemsController.cs | LibraryApp/App.API/Controllers/LibraryItemsController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc;
using App.Data;
using App.Models;
using App.Services;
using App.Services.Ahs;
namespace App.API.Controllers
{
[Route("api/[controller]")]
public class LibraryItemsController : Controller
{
[FromServices]
public IMediatheekService _mediatheekService { get; set; }
// GET: api/values
[HttpGet(Name = "GetLibraryItems")]
public IEnumerable<LibraryItem> GetLibraryItems()
{
var search = new MediatheekSimpleSearch()
{
LibraryCode = "MAR",
SearchField = "JavaScript",
ItemsPerPage = 30,
Offset = 0,
SortOrder = MediatheekSortOrder.Title
};
return _mediatheekService.GetLibraryItemsBySimpleSearch(search);
}
}
}
| apache-2.0 | C# | |
09768cd74054e6cb806f0858bb5732bc9b27fd61 | Add test coverage | peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu | osu.Game.Rulesets.Taiko.Tests/Mods/TestSceneTaikoModClassic.cs | osu.Game.Rulesets.Taiko.Tests/Mods/TestSceneTaikoModClassic.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 NUnit.Framework;
using osu.Game.Rulesets.Replays;
using osu.Game.Rulesets.Taiko.Beatmaps;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Rulesets.Taiko.Objects;
using osu.Game.Rulesets.Taiko.Replays;
namespace osu.Game.Rulesets.Taiko.Tests.Mods
{
public class TestSceneTaikoModClassic : TaikoModTestScene
{
[Test]
public void TestHittingDrumRollsIsOptional() => CreateModTest(new ModTestData
{
Mod = new TaikoModClassic(),
Autoplay = false,
Beatmap = new TaikoBeatmap
{
BeatmapInfo = { Ruleset = CreatePlayerRuleset().RulesetInfo },
HitObjects = new List<TaikoHitObject>
{
new Hit
{
StartTime = 1000,
Type = HitType.Centre
},
new DrumRoll
{
StartTime = 3000,
EndTime = 6000
}
}
},
ReplayFrames = new List<ReplayFrame>
{
new TaikoReplayFrame(1000, TaikoAction.LeftCentre),
new TaikoReplayFrame(1001)
},
PassCondition = () => Player.ScoreProcessor.HasCompleted.Value
&& Player.ScoreProcessor.Combo.Value == 1
&& Player.ScoreProcessor.Accuracy.Value == 1
});
[Test]
public void TestHittingSwellsIsOptional() => CreateModTest(new ModTestData
{
Mod = new TaikoModClassic(),
Autoplay = false,
Beatmap = new TaikoBeatmap
{
BeatmapInfo = { Ruleset = CreatePlayerRuleset().RulesetInfo },
HitObjects = new List<TaikoHitObject>
{
new Hit
{
StartTime = 1000,
Type = HitType.Centre
},
new Swell
{
StartTime = 3000,
EndTime = 6000
}
}
},
ReplayFrames = new List<ReplayFrame>
{
new TaikoReplayFrame(1000, TaikoAction.LeftCentre),
new TaikoReplayFrame(1001)
},
PassCondition = () => Player.ScoreProcessor.HasCompleted.Value
&& Player.ScoreProcessor.Combo.Value == 1
&& Player.ScoreProcessor.Accuracy.Value == 1
});
}
}
| mit | C# | |
ae2c90e8c697a24a921ec58368971a0c2766ad93 | Add tests for Generator | tunnelvisionlabs/dotnet-trees | Tvl.Collections.Trees.Test/GeneratorTest.cs | Tvl.Collections.Trees.Test/GeneratorTest.cs | // Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
namespace Tvl.Collections.Trees.Test
{
using System.Reflection;
using Xunit;
public class GeneratorTest
{
[Fact]
public void TestSeed()
{
ResetSeed(null);
Assert.Null(Generator.Seed);
Generator.Seed = null;
Assert.Null(Generator.Seed);
Generator.Seed = 50;
Assert.Equal(50, Generator.Seed);
Generator.Seed = 64;
Assert.Equal(50, Generator.Seed);
void ResetSeed(int? seed)
{
FieldInfo seedField = typeof(Generator).GetField("_seed", BindingFlags.Static | BindingFlags.NonPublic);
seedField.SetValue(null, seed);
}
}
[Fact]
public void TestGetInt32SingleElement()
{
Assert.Equal(13, Generator.GetInt32(13, 13));
Assert.Equal(20, Generator.GetInt32(20, 20));
}
[Fact]
public void TestGetInt32NegativeRange()
{
Assert.Equal(13, Generator.GetInt32(13, 10));
Assert.Equal(-2, Generator.GetInt32(-2, -5));
}
}
}
| mit | C# | |
79100f7c42d595c42e54d3ec234bb43012169982 | Add TypeData abstract class | kcotugno/OpenARLog | OpenARLog.Data/TypeData.cs | OpenARLog.Data/TypeData.cs | /*
* Copyright (C) 2015-2016 kcotugno
* All rights reserved
*
* Distributed under the terms of the BSD 2 Clause software license. See the
* accompanying LICENSE file or http://www.opensource.org/licenses/BSD-2-Clause.
*
* Author: kcotugno
* Date: 4/6/2016
*/
using System.Data;
namespace OpenARLog.Data
{
public abstract class TypeData
{
protected dataTable;
protected typeDataDb;
protected Constants.TYPES type;
public Load()
{
dataTable = typeDataDb.GetTable(type);
}
public DataTable GetTypeData()
{
return dataTable;
}
}
}
| mit | C# | |
6fb0d9c51c939b59e6249c6caac8d488721b9e45 | Add converter for old storable objects | TheEadie/LazyLibrary,TheEadie/LazyStorage,TheEadie/LazyStorage | src/LazyStorage/StorableConverter.cs | src/LazyStorage/StorableConverter.cs | using System;
using LazyStorage.Interfaces;
namespace LazyStorage.Xml
{
internal class StorableConverter<T> : IConverter<T> where T : IStorable<T>, IEquatable<T>, new()
{
public StorableObject GetStorableObject(T item)
{
return new StorableObject(item.GetStorageInfo());
}
public T GetOriginalObject(StorableObject info)
{
var item = new T();
item.InitialiseWithStorageInfo(info.Info);
return item;
}
public bool IsEqual(StorableObject storageObject, T realObject)
{
return GetOriginalObject(storageObject).Equals(realObject);
}
}
} | mit | C# | |
5d8aacdc9d89b975b555606e352b2cad6f551f43 | Create SameAsConstraintTests.cs | blairconrad/FakeItEasy,wenyanw/FakeItEasy,wenyanw/FakeItEasy,robvanschelven/FakeItEasy,FakeItEasy/FakeItEasy,thomaslevesque/FakeItEasy,adamralph/FakeItEasy,jamiehumphries/FakeItEasy,CedarLogic/FakeItEasy,robvanschelven/FakeItEasy,adamralph/FakeItEasy,FakeItEasy/FakeItEasy,CedarLogic/FakeItEasy,khellang/FakeItEasy,jamiehumphries/FakeItEasy,thomaslevesque/FakeItEasy,khellang/FakeItEasy,blairconrad/FakeItEasy | Source/FakeItEasy.Tests/ArgumentConstraintExtensions/SameAsConstraintTests.cs | Source/FakeItEasy.Tests/ArgumentConstraintExtensions/SameAsConstraintTests.cs | namespace FakeItEasy.Tests.ArgumentValidationExtensions
{
using System.Collections.Generic;
using NUnit.Framework;
[TestFixture]
internal class SameAsConstraintTests
: ArgumentConstraintTestBase<object>
{
protected override IEnumerable<object> InvalidValues
{
get
{
yield return new Foo { Bar = "1" };
yield return new Foo { Bar = "2" };
}
}
class Foo
{
public string Bar { get; set; }
}
protected override IEnumerable<object> ValidValues
{
get { yield return new Foo { Bar = "1" } };
}
protected override string ExpectedDescription
{
get { return "same as Foo with Bar of 1"; }
}
protected override void CreateConstraint(IArgumentConstraintManager<object> scope)
{
// huh?
scope.IsEqualTo(10);
}
}
}
| mit | C# | |
c57a388621e8cabaf17b1f5fc349f8ce5d9d4b5d | Handle cases where IThreadingContext does not provide a main thread | tannergooding/roslyn,gafter/roslyn,dotnet/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,panopticoncentral/roslyn,eriawan/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,gafter/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,eriawan/roslyn,stephentoub/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,tmat/roslyn,stephentoub/roslyn,tmat/roslyn,KirillOsenkov/roslyn,jasonmalinowski/roslyn,gafter/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,weltkante/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,AmadeusW/roslyn,bartdesmet/roslyn,mavasani/roslyn,tannergooding/roslyn,physhi/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,stephentoub/roslyn,sharwell/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,diryboy/roslyn,physhi/roslyn,wvdd007/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,weltkante/roslyn,physhi/roslyn,dotnet/roslyn,AmadeusW/roslyn,tmat/roslyn | src/EditorFeatures/Core/Shared/Utilities/VisualStudioTaskSchedulerProvider.cs | src/EditorFeatures/Core/Shared/Utilities/VisualStudioTaskSchedulerProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class VisualStudioTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioTaskSchedulerProvider(IThreadingContext threadingContext)
{
CurrentContextScheduler = threadingContext.HasMainThread
? new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory)
: TaskScheduler.Default;
}
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
return false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Composition;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.VisualStudio.Threading;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Editor.Shared.Utilities
{
[ExportWorkspaceService(typeof(ITaskSchedulerProvider), ServiceLayer.Editor), Shared]
internal sealed class VisualStudioTaskSchedulerProvider : ITaskSchedulerProvider
{
public TaskScheduler CurrentContextScheduler { get; }
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public VisualStudioTaskSchedulerProvider(IThreadingContext threadingContext)
=> CurrentContextScheduler = new JoinableTaskFactoryTaskScheduler(threadingContext.JoinableTaskFactory);
private sealed class JoinableTaskFactoryTaskScheduler : TaskScheduler
{
private readonly JoinableTaskFactory _joinableTaskFactory;
public JoinableTaskFactoryTaskScheduler(JoinableTaskFactory joinableTaskFactory)
=> _joinableTaskFactory = joinableTaskFactory;
public override int MaximumConcurrencyLevel => 1;
protected override IEnumerable<Task> GetScheduledTasks()
=> SpecializedCollections.EmptyEnumerable<Task>();
protected override void QueueTask(Task task)
{
_joinableTaskFactory.RunAsync(async () =>
{
await _joinableTaskFactory.SwitchToMainThreadAsync(alwaysYield: true);
TryExecuteTask(task);
});
}
protected override bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued)
{
if (_joinableTaskFactory.Context.IsOnMainThread)
{
return TryExecuteTask(task);
}
return false;
}
}
}
}
| mit | C# |
3ba8c2d3f0d2d4859586d4d14a1b064ef70c750c | Add ListenHandleTests (#1923) | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/Microsoft.AspNetCore.Server.Kestrel.FunctionalTests/ListenHandleTests.cs | test/Microsoft.AspNetCore.Server.Kestrel.FunctionalTests/ListenHandleTests.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.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Server.Kestrel.Core;
using Microsoft.AspNetCore.Testing;
using Microsoft.AspNetCore.Testing.xunit;
namespace Microsoft.AspNetCore.Server.Kestrel.FunctionalTests
{
[OSSkipCondition(OperatingSystems.Windows, SkipReason = "Listening to open TCP socket and/or pipe handles is not supported on Windows.")]
public class ListenHandleTests
{
[ConditionalFact]
public async Task CanListenToOpenTcpSocketHandle()
{
using (var listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
listenSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
using (var server = new TestServer(_ => Task.CompletedTask, new TestServiceContext(), new ListenOptions((ulong)listenSocket.Handle)))
{
using (var connection = new TestConnection(((IPEndPoint)listenSocket.LocalEndPoint).Port))
{
await connection.SendEmptyGet();
await connection.Receive(
"HTTP/1.1 200 OK",
$"Date: {server.Context.DateHeaderValue}",
"Content-Length: 0",
"",
"");
}
}
}
}
}
}
| apache-2.0 | C# | |
6e42a4db2bf063cc7f18bdf30fa2239d2700e027 | Add benchmark coverage of logger | smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework | osu.Framework.Benchmarks/BenchmarkLogger.cs | osu.Framework.Benchmarks/BenchmarkLogger.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 BenchmarkDotNet.Attributes;
using osu.Framework.Logging;
using osu.Framework.Testing;
namespace osu.Framework.Benchmarks
{
[MemoryDiagnoser]
public class BenchmarkLogger
{
private const int line_count = 10000;
[GlobalSetup]
public void GlobalSetup()
{
Logger.Storage = new TemporaryNativeStorage(Guid.NewGuid().ToString());
}
[Benchmark]
public void LogManyLinesDebug()
{
for (int i = 0; i < line_count; i++)
{
Logger.Log("This is a test log line.", level: LogLevel.Debug);
}
Logger.Flush();
}
[Benchmark]
public void LogManyMultiLineLines()
{
for (int i = 0; i < line_count; i++)
{
Logger.Log("This\nis\na\ntest\nlog\nline.");
}
Logger.Flush();
}
[Benchmark]
public void LogManyLines()
{
for (int i = 0; i < line_count; i++)
{
Logger.Log("This is a test log line.");
}
Logger.Flush();
}
}
}
| mit | C# | |
97be3f445fbd155b8e3246a992e7fbfb74511177 | Create gisttyleoverride.cs | ShibumiWare/Blog | gisttyleoverride.cs | gisttyleoverride.cs |
.gist {
color: #000000;
direction: ltr;
font-size: 14px;
text-align: left;
}
.gist-meta a {
color: #000000 !important;
text-decoration: none;
}
.gist .gist .blob-wrapper table {
border-collapse: collapse;
}
.gist .highlight {
background: #fff;
border: 0;
color: #333;
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
font-size: 12px;
font-weight: normal;
line-height: 1.4;
margin: 0;
padding: 0;
}
.gist .gist-file {
border: 1px solid #ddd;
border-bottom: 1px solid #ccc;
border-radius: 3px;
font-family: Consolas, "Liberation Mono", Menlo, Courier, monospace;
margin-bottom: 1em;
}
.gist .gist-data {
background-color: pink;
border-bottom: 1px solid #ddd;
border-radius: 2px 2px 0 0;
overflow: auto;
word-wrap: normal;
}
.gist .blob-code {
background: #d3d3d3;
padding: 1px 10px !important;
text-align: left;
}
.gist .blob-num {
background: #dcdcdc;
min-width: inherit;
padding: 1px 10px !important;
}
.gist .gist-meta {
background-color: #767676;
border-radius: 0 0 2px 2px;
color: #f5f5f5;
font: 12px -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
overflow: hidden;
padding: 10px;
}
.gist .gist-data {
background-color: #fff;
border-bottom: 1px solid #ddd;
border-radius: 2px 2px 0 0;
overflow: auto;
word-wrap: normal;
}
| mit | C# | |
6c80742b14f928b0b56420198adbe082ea09d7e8 | Fix #64 : REPL intellisense, up/down arrow naviates history, not the intellisense | MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS | src/Package/Impl/Repl/Commands/HistoryNavigationCommand.cs | src/Package/Impl/Repl/Commands/HistoryNavigationCommand.cs | using System;
using System.ComponentModel.Composition;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller.Command;
using Microsoft.Languages.Editor.Shell;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Language.Intellisense;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.R.Package.Repl.Commands
{
public sealed class HistoryNavigationCommand : ViewCommand
{
[Import]
private ICompletionBroker _completionBroker { get; set; }
public HistoryNavigationCommand(ITextView textView) :
base(textView, new CommandId[] {
new CommandId(VSConstants.VSStd2K, (int)VSConstants.VSStd2KCmdID.UP),
new CommandId(VSConstants.VSStd2K, (int)VSConstants.VSStd2KCmdID.DOWN)
}, false)
{
EditorShell.Current.CompositionService.SatisfyImportsOnce(this);
}
public override CommandStatus Status(Guid group, int id)
{
if(_completionBroker.IsCompletionActive(TextView))
{
return CommandStatus.NotSupported;
}
return CommandStatus.SupportedAndEnabled;
}
public override CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg)
{
if (_completionBroker.IsCompletionActive(TextView))
{
return CommandResult.NotSupported;
}
if (id == (int)VSConstants.VSStd2KCmdID.UP)
{
IVsInteractiveWindow interactive = ReplWindow.Current.GetInteractiveWindow();
interactive.InteractiveWindow.Operations.HistoryPrevious();
}
else if (id == (int)VSConstants.VSStd2KCmdID.DOWN)
{
IVsInteractiveWindow interactive = ReplWindow.Current.GetInteractiveWindow();
interactive.InteractiveWindow.Operations.HistoryNext();
}
return CommandResult.Executed;
}
}
}
| using System;
using Microsoft.Languages.Editor;
using Microsoft.Languages.Editor.Controller.Command;
using Microsoft.VisualStudio.InteractiveWindow.Shell;
using Microsoft.VisualStudio.Text.Editor;
namespace Microsoft.VisualStudio.R.Package.Repl.Commands
{
public sealed class HistoryNavigationCommand : ViewCommand
{
public HistoryNavigationCommand(ITextView textView) :
base(textView, new CommandId[] {
new CommandId(VSConstants.VSStd2K, (int)VSConstants.VSStd2KCmdID.UP),
new CommandId(VSConstants.VSStd2K, (int)VSConstants.VSStd2KCmdID.DOWN)
}, false)
{
}
public override CommandStatus Status(Guid group, int id)
{
return CommandStatus.SupportedAndEnabled;
}
public override CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg)
{
if (id == (int)VSConstants.VSStd2KCmdID.UP)
{
IVsInteractiveWindow interactive = ReplWindow.Current.GetInteractiveWindow();
interactive.InteractiveWindow.Operations.HistoryPrevious();
}
else if (id == (int)VSConstants.VSStd2KCmdID.DOWN)
{
IVsInteractiveWindow interactive = ReplWindow.Current.GetInteractiveWindow();
interactive.InteractiveWindow.Operations.HistoryNext();
}
return CommandResult.Executed;
}
}
}
| mit | C# |
9e2a7d548fa5c742aa3def030122db20dd2c6c4b | Remove unneeded suppression | gafter/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,tmat/roslyn,diryboy/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,gafter/roslyn,mavasani/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,dotnet/roslyn,wvdd007/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,panopticoncentral/roslyn,panopticoncentral/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,diryboy/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,wvdd007/roslyn,physhi/roslyn,tmat/roslyn,AmadeusW/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,KevinRansom/roslyn,tannergooding/roslyn,sharwell/roslyn,stephentoub/roslyn,gafter/roslyn,physhi/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,tmat/roslyn,AmadeusW/roslyn,eriawan/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,sharwell/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,AlekseyTs/roslyn,diryboy/roslyn,wvdd007/roslyn | src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopSpinLock.cs | src/Scripting/CoreTestUtilities/ObjectFormatterFixtures/MockDesktopSpinLock.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading;
namespace ObjectFormatterFixtures
{
/// <summary>
/// Follows the shape of the Desktop version of <see cref="SpinLock"/> relevant for debugger display.
/// </summary>
[DebuggerTypeProxy(typeof(SpinLockDebugView))]
[DebuggerDisplay("IsHeld = {IsHeld}")]
internal struct MockDesktopSpinLock
{
private volatile int m_owner;
public MockDesktopSpinLock(bool enableThreadOwnerTracking)
{
m_owner = enableThreadOwnerTracking ? 0 : int.MinValue;
}
public bool IsHeld
=> false;
public bool IsHeldByCurrentThread
=> IsThreadOwnerTrackingEnabled ? true : throw new InvalidOperationException("Error");
public bool IsThreadOwnerTrackingEnabled
=> (m_owner & int.MinValue) == 0;
internal class SpinLockDebugView
{
private MockDesktopSpinLock m_spinLock;
public bool? IsHeldByCurrentThread
=> m_spinLock.IsHeldByCurrentThread;
public int? OwnerThreadID
=> m_spinLock.IsThreadOwnerTrackingEnabled ? m_spinLock.m_owner : (int?)null;
public bool IsHeld => m_spinLock.IsHeld;
public SpinLockDebugView(MockDesktopSpinLock spinLock)
{
m_spinLock = spinLock;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#nullable disable
using System;
using System.Diagnostics;
using System.Threading;
namespace ObjectFormatterFixtures
{
/// <summary>
/// Follows the shape of the Desktop version of <see cref="SpinLock"/> relevant for debugger display.
/// </summary>
[DebuggerTypeProxy(typeof(SpinLockDebugView))]
[DebuggerDisplay("IsHeld = {IsHeld}")]
internal struct MockDesktopSpinLock
{
#pragma warning disable IDE0044 // Add readonly modifier - See https://github.com/dotnet/roslyn/issues/47225
private volatile int m_owner;
#pragma warning restore IDE0044 // Add readonly modifier
public MockDesktopSpinLock(bool enableThreadOwnerTracking)
{
m_owner = enableThreadOwnerTracking ? 0 : int.MinValue;
}
public bool IsHeld
=> false;
public bool IsHeldByCurrentThread
=> IsThreadOwnerTrackingEnabled ? true : throw new InvalidOperationException("Error");
public bool IsThreadOwnerTrackingEnabled
=> (m_owner & int.MinValue) == 0;
internal class SpinLockDebugView
{
private MockDesktopSpinLock m_spinLock;
public bool? IsHeldByCurrentThread
=> m_spinLock.IsHeldByCurrentThread;
public int? OwnerThreadID
=> m_spinLock.IsThreadOwnerTrackingEnabled ? m_spinLock.m_owner : (int?)null;
public bool IsHeld => m_spinLock.IsHeld;
public SpinLockDebugView(MockDesktopSpinLock spinLock)
{
m_spinLock = spinLock;
}
}
}
}
| mit | C# |
b07d42d416bf27ec12d711e71882474634e62b48 | Add XML DOM constants | iolevel/peachpie,peachpiecompiler/peachpie,iolevel/peachpie-concept,peachpiecompiler/peachpie,peachpiecompiler/peachpie,iolevel/peachpie,iolevel/peachpie,iolevel/peachpie-concept,iolevel/peachpie-concept | src/Peachpie.Library.XmlDom/XmlDom.cs | src/Peachpie.Library.XmlDom/XmlDom.cs | using System;
using System.Collections.Generic;
using System.Text;
namespace Peachpie.Library.XmlDom
{
#region Constants
/// <summary>
/// Enumerates possible DOM node types.
/// </summary>
public enum NodeType
{
Element = 1,
Attribute = 2,
Text = 3,
CharacterDataSection = 4,
EntityReference = 5,
Entity = 6,
ProcessingInstruction = 7,
Comment = 8,
Document = 9,
DocumentType = 10,
DocumentFragment = 11,
Notation = 12,
HtmlDocument = 13,
Dtd = 14,
ElementDecl = 15,
AttributeDecl = 16,
EntityDecl = 17,
NamespaceDecl = 18,
LocalNamespace = 18
}
/// <summary>
/// Enumerates who-knows-what.
/// </summary>
public enum AttributeType
{
CharacterData = 1,
Id = 2,
IdReference = 3,
IdReferences = 4,
Entity = 5,
Token = 7,
Tokens = 8,
Enumeration = 9,
Notation = 10
}
#endregion
/// <summary>
/// Implements constants and functions.
/// </summary>
public static class XmlDom
{
public const int XML_ELEMENT_NODE = (int)NodeType.Element;
public const int XML_ATTRIBUTE_NODE = (int)NodeType.Attribute;
public const int XML_TEXT_NODE = (int)NodeType.Text;
public const int XML_CDATA_SECTION_NODE = (int)NodeType.CharacterDataSection;
public const int XML_ENTITY_REF_NODE = (int)NodeType.EntityReference;
public const int XML_ENTITY_NODE = (int)NodeType.Entity;
public const int XML_PI_NODE = (int)NodeType.ProcessingInstruction;
public const int XML_COMMENT_NODE = (int)NodeType.Comment;
public const int XML_DOCUMENT_NODE = (int)NodeType.Document;
public const int XML_DOCUMENT_TYPE_NODE = (int)NodeType.DocumentType;
public const int XML_DOCUMENT_FRAG_NODE = (int)NodeType.DocumentFragment;
public const int XML_NOTATION_NODE = (int)NodeType.Notation;
public const int XML_HTML_DOCUMENT_NODE = (int)NodeType.HtmlDocument;
public const int XML_DTD_NODE = (int)NodeType.Dtd;
public const int XML_ELEMENT_DECL_NODE = (int)NodeType.ElementDecl;
public const int XML_ATTRIBUTE_DECL_NODE = (int)NodeType.AttributeDecl;
public const int XML_ENTITY_DECL_NODE = (int)NodeType.EntityDecl;
public const int XML_NAMESPACE_DECL_NODE = (int)NodeType.NamespaceDecl;
public const int XML_LOCAL_NAMESPACE = (int)NodeType.LocalNamespace;
public const int XML_ATTRIBUTE_CDATA = (int)AttributeType.CharacterData;
public const int XML_ATTRIBUTE_ID = (int)AttributeType.Id;
public const int XML_ATTRIBUTE_IDREF = (int)AttributeType.IdReference;
public const int XML_ATTRIBUTE_IDREFS = (int)AttributeType.IdReferences;
public const int XML_ATTRIBUTE_ENTITY = (int)AttributeType.Entity;
public const int XML_ATTRIBUTE_NMTOKEN = (int)AttributeType.Token;
public const int XML_ATTRIBUTE_NMTOKENS = (int)AttributeType.Tokens;
public const int XML_ATTRIBUTE_ENUMERATION = (int)AttributeType.Enumeration;
public const int XML_ATTRIBUTE_NOTATION = (int)AttributeType.Notation;
/// <summary>
/// Converts a <see cref="SimpleXMLElement"/> object to a <see cref="DOMElement"/>.
/// </summary>
//public static DOMElement dom_import_simplexml(SimpleXMLElement node) => DOMNode.Create(node.XmlElement);
}
}
| apache-2.0 | C# | |
03847cbc61f0bae618664e9108e7060b4969f9b9 | Fix tests | MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS | src/Markdown/Editor/Test/ContainedLanguage/RLanguageHandlerTest.cs | src/Markdown/Editor/Test/ContainedLanguage/RLanguageHandlerTest.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.Common.Core.Services;
using Microsoft.Common.Core.Shell;
using Microsoft.Languages.Editor.Projection;
using Microsoft.Markdown.Editor.ContainedLanguage;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.UnitTests.Core.XUnit;
using Microsoft.VisualStudio.Editor.Mocks;
using Microsoft.VisualStudio.Text.Projection;
using Microsoft.VisualStudio.Utilities;
using NSubstitute;
using Xunit;
namespace Microsoft.Markdown.Editor.Test.ContainedLanguage {
[ExcludeFromCodeCoverage]
public class RLanguageHandlerTest {
private readonly ICoreShell _coreShell;
public RLanguageHandlerTest(IServiceContainer services) {
_coreShell = services.GetService<ICoreShell>();
}
[CompositeTest]
[Category.Md.RCode]
[InlineData("```{r}\n\n```")]
[InlineData("```{r x=1}\nplot()\n```")]
[InlineData("```{r x=1,\ny=2}\nx <- 1\n```")]
[InlineData("```{r x=function() {\n}}\nx <- 1\n```")]
[InlineData("```{r}\nparams$a = 3\nx <- 1\n```")]
public void RCodeGen(string markdown) {
var tb = new TextBufferMock(markdown, MdContentTypeDefinition.ContentType);
var pbm = Substitute.For<IProjectionBufferManager>();
string secondaryBuffer = null;
ProjectionMapping[] mappings = null;
pbm.When(x => x.SetProjectionMappings(Arg.Any<string>(), Arg.Any<ProjectionMapping[]>())).Do(x => {
secondaryBuffer = ((string)x[0]);
mappings = (ProjectionMapping[])x[1];
});
var expectedSecondaryBuffer = markdown.Replace("```", string.Empty) + Environment.NewLine;
var handler = new RLanguageHandler(tb, pbm, _coreShell);
secondaryBuffer.Should().Be(expectedSecondaryBuffer);
mappings.Should().HaveCount(1);
mappings[0].SourceStart.Should().Be(3);
mappings[0].ProjectionRange.Start.Should().Be(0);
mappings[0].Length.Should().Be(expectedSecondaryBuffer.Length - Environment.NewLine.Length);
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using System.Diagnostics.CodeAnalysis;
using FluentAssertions;
using Microsoft.Languages.Editor.Projection;
using Microsoft.Markdown.Editor.ContentTypes;
using Microsoft.UnitTests.Core.XUnit;
using Microsoft.VisualStudio.Editor.Mocks;
using NSubstitute;
using Xunit;
namespace Microsoft.Markdown.Editor.Test.ContainedLanguage {
[ExcludeFromCodeCoverage]
public class RLanguageHandlerTest {
[CompositeTest]
[Category.Md.RCode]
[InlineData("```{r}\n\n```")]
[InlineData("```{r x=1}\nplot()\n```")]
[InlineData("```{r x=1,\ny=2}\nx <- 1\n```")]
[InlineData("```{r x=function() {\n}}\nx <- 1\n```")]
[InlineData("```{r}\nparams$a = 3\nx <- 1\n```")]
public void RCodeGen(string markdown) {
var tb = new TextBufferMock(markdown, MdContentTypeDefinition.ContentType);
var pbm = Substitute.For<IProjectionBufferManager>();
string secondaryBuffer = null;
ProjectionMapping[] mappings = null;
pbm.When(x => x.SetProjectionMappings(Arg.Any<string>(), Arg.Any<ProjectionMapping[]>())).Do(x => {
secondaryBuffer = ((string)x[0]);
mappings = (ProjectionMapping[])x[1];
});
var expectedSecondaryBuffer = markdown.Replace("```", string.Empty) + Environment.NewLine;
secondaryBuffer.Should().Be(expectedSecondaryBuffer);
mappings.Should().HaveCount(1);
mappings[0].SourceStart.Should().Be(3);
mappings[0].ProjectionRange.Start.Should().Be(0);
mappings[0].Length.Should().Be(expectedSecondaryBuffer.Length - Environment.NewLine.Length);
}
}
}
| mit | C# |
4b6c0770765beb67d89c9a7b4269023042bfe7a5 | Create FibonacciNumbers.cs | DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges,DuckBoss/Programming-Challenges | Fibonacci_Numbers/FibonacciNumbers.cs | Fibonacci_Numbers/FibonacciNumbers.cs | using System;
namespace EvenFibonacciNumbers
{
class MainClass
{
public static void Main(string[] args)
{
if (args.Length != 3)
{
Console.WriteLine("This program requires 2 starting integers, and the max terms to count!\n");
Environment.Exit(0);
}
int start1 = Convert.ToInt32(args[0]);
int start2 = Convert.ToInt32(args[1]);
int maxCount = Convert.ToInt32(args[2]);
if (maxCount < 2)
maxCount = 2;
int[] fullList = new int[maxCount];
fullList[0] = start1;
fullList[1] = start2;
for (int i = 2; i < maxCount; i++)
fullList[i] = fullList[i - 1] + fullList[i-2];
Console.Write("Result - {");
foreach (int fib in fullList)
{
Console.Write($" {fib}");
}
Console.Write(" }");
Console.WriteLine();
Console.ReadKey();
}
}
}
| unlicense | C# | |
b03acd6fc530c22a2cd6cac062aaedbb14bd1992 | Create CartItem.cs | daniela1991/hack4europecontest | CartItem.cs | CartItem.cs | namespace Cdiscount.OpenApi.ProxyClient.Contract.GetCart
{
/// <summary>
/// Cart item detail
/// </summary>
public class CartItem
{
/// <summary>
/// Product condition (new or used)
/// </summary>
public string Condition { get; set; }
/// <summary>
/// Offer identifier
/// </summary>
public string OfferId { get; set; }
/// <summary>
/// Product unit price (in euros)
/// </summary>
public decimal Price { get; set; }
/// <summary>
/// Product identifier
/// </summary>
public string ProductId { get; set; }
/// <summary>
/// Product quantity
/// </summary>
public int Quantity { get; set; }
/// <summary>
/// Seller identifier
/// </summary>
public int? SellerId { get; set; }
/// <summary>
/// Size identifier
/// </summary>
public int? SizeId { get; set; }
}
}
| mit | C# | |
541a093e6d55ead5906a07e2e31d7af8758e9622 | Add serviceable attribute to projects. | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.StaticFiles/Properties/AssemblyInfo.cs | src/Microsoft.AspNet.StaticFiles/Properties/AssemblyInfo.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Reflection;
[assembly: AssemblyMetadata("Serviceable", "True")] | apache-2.0 | C# | |
acc676376bb50cce2fd630f181ba4370594602d0 | Add ITranslatorFactory | kotorihq/kotori-core | KotoriCore/Translators/ITranslatorFactory.cs | KotoriCore/Translators/ITranslatorFactory.cs | using KotoriCore.Database.DocumentDb;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Documents.OData.Core.Sql;
namespace KotoriCore.Translators
{
public interface ITranslatorFactory<T> where T:IEntity
{
ITranslator<T> CreateTranslator();
}
} | mit | C# | |
ab87c93ebe1a6b5f4a7be50b4b4f746e80788b25 | Add tests for ConfigQueryResult | Choc13/Winton.Extensions.Configuration.Consul,Choc13/Winton.Extensions.Configuration.Consul | test/AspNetCore.Configuration.Consul.Test/ConfigQueryResultTests.cs | test/AspNetCore.Configuration.Consul.Test/ConfigQueryResultTests.cs | using System.Net;
using Consul;
using NUnit.Framework;
namespace Chocolate.AspNetCore.Configuration.Consul
{
[TestFixture]
internal sealed class ConfigQueryResultTests
{
[Test]
public void ShouldSetExistsToFalseWhenConstructedFromNullResult()
{
var configQueryResult = new ConfigQueryResult(null);
Assert.That(configQueryResult.Exists, Is.False);
}
[Test]
public void ShouldSetExistsToFalseWhenConstructedFromResultWithNullResponse()
{
QueryResult<KVPair> kvPairResult = new QueryResult<KVPair>
{
Response = null,
StatusCode = HttpStatusCode.OK
};
var configQueryResult = new ConfigQueryResult(kvPairResult);
Assert.That(configQueryResult.Exists, Is.False);
}
[Test]
public void ShouldSetExistsToFalseWhenConstructedFromResultWithNullValue()
{
QueryResult<KVPair> kvPairResult = new QueryResult<KVPair>
{
Response = new KVPair("Key")
{
Value = null
},
StatusCode = HttpStatusCode.OK
};
var configQueryResult = new ConfigQueryResult(kvPairResult);
Assert.That(configQueryResult.Exists, Is.False);
}
[Test]
public void ShouldSetExistsToFalseWhenConstructedFromResultWithEmptyValue()
{
QueryResult<KVPair> kvPairResult = new QueryResult<KVPair>
{
Response = new KVPair("Key")
{
Value = new byte[]{}
},
StatusCode = HttpStatusCode.OK
};
var configQueryResult = new ConfigQueryResult(kvPairResult);
Assert.That(configQueryResult.Exists, Is.False);
}
[Test]
public void ShouldSetExistsToFalseWhenConstructedFromResultWithNotFoundStatus()
{
QueryResult<KVPair> kvPairResult = new QueryResult<KVPair>
{
StatusCode = HttpStatusCode.NotFound
};
var configQueryResult = new ConfigQueryResult(kvPairResult);
Assert.That(configQueryResult.Exists, Is.False);
}
[Test]
public void ShouldSetValueToResultValue()
{
var actualValue = new byte[]{1};
QueryResult<KVPair> kvPairResult = new QueryResult<KVPair>
{
Response = new KVPair("Key")
{
Value = actualValue
},
StatusCode = HttpStatusCode.OK
};
var configQueryResult = new ConfigQueryResult(kvPairResult);
Assert.That(configQueryResult.Value, Is.SameAs(actualValue));
}
}
} | apache-2.0 | C# | |
de9e8e2fb2c344d3a81cf94dc08b7079179605e4 | Add IServiceResolver | AspectCore/Abstractions,AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/AspectCore-Framework | src/IoC/src/AspectCore.Extensions.IoC/IServiceResolver.cs | src/IoC/src/AspectCore.Extensions.IoC/IServiceResolver.cs | using System;
namespace AspectCore.Extensions.IoC
{
public interface IServiceResolver : IServiceProvider
{
object Resolve(Type serviceType, object key);
}
}
| mit | C# | |
0259790f72dde84705ab81425008e8815b6709a6 | Update InactiveSite.cs | LANDIS-II-Foundation/Landis-Spatial-Modeling-Library | src/api/InactiveSite.cs | src/api/InactiveSite.cs | // Copyright 2004-2006 University of Wisconsin
// All rights reserved.
//
// Contributors:
// James Domingo, UW-Madison, Forest Landscape Ecology Lab
namespace Landis.SpatialModeling
{
/// <summary>
/// Provides information about inactive sites on a landscape.
/// </summary>
public static class InactiveSite
{
/// <summary>
/// The data index assigned to inactive sites.
/// </summary>
public const uint DataIndex = 0;
//---------------------------------------------------------------------
/// <summary>
/// Creates a new inactive site on a landscape.
/// </summary>
/// <param name="landscape">
/// The landscape where the site is located.
/// </param>
/// <param name="location">
/// The location of the site.
/// </param>
internal static Site Create(ILandscape landscape,
Location location)
{
return new Site(landscape, location, DataIndex);
}
}
}
| // Copyright 2004-2006 University of Wisconsin
// All rights reserved.
//
// The copyright holders license this file under the New (3-clause) BSD
// License (the "License"). You may not use this file except in
// compliance with the License. A copy of the License is available at
//
// http://www.opensource.org/licenses/BSD-3-Clause
//
// and is included in the NOTICE.txt file distributed with this work.
//
// Contributors:
// James Domingo, UW-Madison, Forest Landscape Ecology Lab
namespace Landis.SpatialModeling
{
/// <summary>
/// Provides information about inactive sites on a landscape.
/// </summary>
public static class InactiveSite
{
/// <summary>
/// The data index assigned to inactive sites.
/// </summary>
public const uint DataIndex = 0;
//---------------------------------------------------------------------
/// <summary>
/// Creates a new inactive site on a landscape.
/// </summary>
/// <param name="landscape">
/// The landscape where the site is located.
/// </param>
/// <param name="location">
/// The location of the site.
/// </param>
internal static Site Create(ILandscape landscape,
Location location)
{
return new Site(landscape, location, DataIndex);
}
}
}
| apache-2.0 | C# |
991723a3ec700197a9b99ed4c9af3c3d3b1c4ae8 | add reports to auth | ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab | Anlab.Mvc/Controllers/ReviewerController.cs | Anlab.Mvc/Controllers/ReviewerController.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Anlab.Core.Data;
using Microsoft.EntityFrameworkCore;
using Anlab.Core.Models;
using Microsoft.AspNetCore.Authorization;
using AnlabMvc.Models.Roles;
namespace AnlabMvc.Controllers
{
[Authorize(Roles = RoleCodes.Admin + "," + RoleCodes.Reports)]
public class ReviewerController : ApplicationController
{
private readonly ApplicationDbContext _context;
public ReviewerController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var model = await _context.Orders.Where(a => a.Status == OrderStatusCodes.Finalized).ToArrayAsync();
return View(model);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Anlab.Core.Data;
using Microsoft.EntityFrameworkCore;
using Anlab.Core.Models;
using Microsoft.AspNetCore.Authorization;
using AnlabMvc.Models.Roles;
namespace AnlabMvc.Controllers
{
[Authorize(Roles = RoleCodes.Admin)]
public class ReviewerController : ApplicationController
{
private readonly ApplicationDbContext _context;
public ReviewerController(ApplicationDbContext context)
{
_context = context;
}
public async Task<IActionResult> Index()
{
var model = await _context.Orders.Where(a => a.Status == OrderStatusCodes.Finalized).ToArrayAsync();
return View(model);
}
}
}
| mit | C# |
eb85f0e432d17db321ff95609960adade4664c66 | add version 3 databus doco | yuxuac/docs.particular.net,WojcikMike/docs.particular.net,pedroreys/docs.particular.net,eclaus/docs.particular.net | Snippets/Snippets_3/DataBus/DataBus.cs | Snippets/Snippets_3/DataBus/DataBus.cs | using NServiceBus;
public class DataBus
{
public void FileShareDataBus()
{
string databusPath = null;
#region FileShareDataBus
Configure configure = Configure.With()
.FileShareDataBus(databusPath);
#endregion
}
}
namespace DataBusProperties
{
#region MessageWithLargePayload
public class MessageWithLargePayload
{
public string SomeProperty { get; set; }
public DataBusProperty<byte[]> LargeBlob { get; set; }
}
#endregion
#region MessageWithLargePayloadUsingConvention
public class MessageWithLargePayloadUsingConvention
{
public string SomeProperty { get; set; }
public byte[] LargeBlobDataBus { get; set; }
}
#endregion
public static class MessageConventions
{
public static void DefineDataBusPropertiesConvention(Configure configuration)
{
#region DefineMessageWithLargePayloadUsingConvention
configuration.DefiningDataBusPropertiesAs(p => p.Name.EndsWith("DataBus"));
#endregion
}
}
} | apache-2.0 | C# | |
ffee3cddfd510b499b7c6f44b1993c21c7654df9 | Add a partial view with form to reply to comments. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Views/Project/CommentReplyFormPartial.cshtml | src/CompetitionPlatform/Views/Project/CommentReplyFormPartial.cshtml | @using System.Threading.Tasks
@using CompetitionPlatform.Helpers
@model CompetitionPlatform.Models.ProjectViewModels.ProjectCommentPartialViewModel
<form asp-controller="ProjectDetails" asp-action="AddComment" enctype="multipart/form-data">
@if (ClaimsHelper.GetUser(User.Identity).Email != null)
{
<div class="form-group">
@Html.Hidden("projectId", Model.ProjectId)
@Html.Hidden("ParentId", Model.ParentId)
<input asp-for="@Model.ProjectId" type="hidden" />
<textarea asp-for="@Model.Comment" rows="5" class="form-control" placeholder="Enter your comment here..."></textarea>
</div>
<input type="submit" value="Post Comment" class="btn btn-primary pull-right" />
}
</form> | mit | C# | |
6d93031860d13302a5c41cf114407823cf7dc641 | Fix #28 | lucasdavid/Gamedalf,lucasdavid/Gamedalf | Gamedalf/Controllers/PlayingController.cs | Gamedalf/Controllers/PlayingController.cs | using Gamedalf.Core.Models;
using Gamedalf.Services;
using Gamedalf.ViewModels;
using Microsoft.AspNet.Identity;
using PagedList;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Gamedalf.Controllers
{
[Authorize(Roles = "player")]
public class PlayingController : Controller
{
private readonly PlayingService _playings;
public PlayingController(PlayingService playings)
{
_playings = playings;
}
// GET: Playing
public async Task<ActionResult> Index(string q = null, int page = 1, int size = 10)
{
ViewBag.q = q;
var list = (await _playings.MyPlayings(User.Identity.GetUserId(), q))
.ToPagedList(page, size);
if (Request.IsAjaxRequest())
{
return PartialView("_List", list);
}
return View(list);
}
// GET: Playing/Evalute
public async Task<ActionResult> Evaluate(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var playing = await _playings.Find(id);
if (playing == null)
{
return HttpNotFound();
}
var model = new EvaluationViewModel
{
Id = playing.Id,
GameTitle = playing.Game.Title,
PlayerEmail = playing.Player.Email,
Review = playing.Review
};
if (playing.IsEvaluated)
{
model.Score = (short)playing.Score;
}
return View(model);
}
// POST: Playing/Evaluate
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Evaluate(EvaluationViewModel model)
{
if (ModelState.IsValid)
{
var playing = new Playing
{
Id = model.Id,
Review = model.Review,
Score = model.Score
};
playing = await _playings.Evaluate(playing);
return RedirectToAction("Index");
}
return View(model);
}
}
}
| mit | C# | |
69afe90571f1ab7c98564c091fb35987de0854af | add helper extension to get ef sql output | Research-Institute/json-api-dotnet-core,Research-Institute/json-api-dotnet-core,json-api-dotnet/JsonApiDotNetCore | test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/IQueryableExtensions.cs | test/JsonApiDotNetCoreExampleTests/Helpers/Extensions/IQueryableExtensions.cs | using System;
using System.Linq;
using System.Reflection;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Remotion.Linq.Parsing.Structure;
using Database = Microsoft.EntityFrameworkCore.Storage.Database;
namespace JsonApiDotNetCoreExampleTests.Helpers.Extensions
{
public static class IQueryableExtensions
{
private static readonly TypeInfo QueryCompilerTypeInfo = typeof(QueryCompiler).GetTypeInfo();
private static readonly FieldInfo QueryCompilerField = typeof(EntityQueryProvider).GetTypeInfo().DeclaredFields.First(x => x.Name == "_queryCompiler");
private static readonly PropertyInfo NodeTypeProviderField = QueryCompilerTypeInfo.DeclaredProperties.Single(x => x.Name == "NodeTypeProvider");
private static readonly MethodInfo CreateQueryParserMethod = QueryCompilerTypeInfo.DeclaredMethods.First(x => x.Name == "CreateQueryParser");
private static readonly FieldInfo DataBaseField = QueryCompilerTypeInfo.DeclaredFields.Single(x => x.Name == "_database");
private static readonly FieldInfo QueryCompilationContextFactoryField = typeof(Database).GetTypeInfo().DeclaredFields.Single(x => x.Name == "_queryCompilationContextFactory");
public static string ToSql<TEntity>(this IQueryable<TEntity> query) where TEntity : class
{
if (!(query is EntityQueryable<TEntity>) && !(query is InternalDbSet<TEntity>))
throw new ArgumentException("Invalid query");
var queryCompiler = (IQueryCompiler)QueryCompilerField.GetValue(query.Provider);
var nodeTypeProvider = (INodeTypeProvider)NodeTypeProviderField.GetValue(queryCompiler);
var parser = (IQueryParser)CreateQueryParserMethod.Invoke(queryCompiler, new object[] { nodeTypeProvider });
var queryModel = parser.GetParsedQuery(query.Expression);
var database = DataBaseField.GetValue(queryCompiler);
var queryCompilationContextFactory = (IQueryCompilationContextFactory)QueryCompilationContextFactoryField.GetValue(database);
var queryCompilationContext = queryCompilationContextFactory.Create(false);
var modelVisitor = (RelationalQueryModelVisitor)queryCompilationContext.CreateQueryModelVisitor();
modelVisitor.CreateQueryExecutor<TEntity>(queryModel);
var sql = modelVisitor.Queries.First().ToString();
return sql;
}
}
} | mit | C# | |
4e72109803d93e8423954e699f36bc2e58d9e6df | Create Problem59.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Problems/Problem59.cs | Problems/Problem59.cs | using System;
using System.Collections.Generic;
using System.IO;
namespace ProjectEuler.Problems
{
class Problem59
{
private Dictionary<byte, char> ByteToChar = new Dictionary<byte, char>();
private Dictionary<char, byte> CharToByte = new Dictionary<char, byte>();
public Problem59()
{
}
private List<string> GenerateKeys()
{
string lower = "abcdefghijklmnopqrstuvwxyz";
List<string> res = new List<string>();
foreach (char x in lower)
{
foreach (char y in lower)
{
foreach (char z in lower)
{
res.Add(x.ToString() + y + z);
}
}
}
return res;
}
private int SumASCII(string text)
{
int sum = 0;
foreach (char t in text)
{
sum += (byte)t;
}
return sum;
}
public void Run()
{
string[] str_input;
byte[] byte_input;
using (StreamReader sr = new StreamReader("Input/p059_cipher.txt"))
{
str_input = sr.ReadLine().Split(',');
}
byte_input = new byte[str_input.Length];
for (int i = 0; i < str_input.Length; i++)
{
byte_input[i] = byte.Parse(str_input[i]);
}
List<string> keys = GenerateKeys();
foreach (string key in keys)
{
string str_output = "";
for (int ix = 0; ix < byte_input.Length; ix++)
{
str_output += (char)(byte_input[ix] ^ (byte)key[ix % 3]);
}
string[] commonWords = new string[] { "the", "and", "of" };
bool passTest = true;
string str_lower = str_output.ToLower();
foreach (string word in commonWords)
{
passTest &= str_lower.Contains(word);
}
if (passTest)
{
Console.WriteLine(key + " = " + SumASCII(str_output));
Console.WriteLine(str_output.Substring(0, 100));
}
}
Console.WriteLine("End");
Console.ReadLine();
}
}
}
| mit | C# | |
8e33ca8515f1c328d920e4daa6c40e0948ecd68b | Create Excercise_08.cs | jesushilarioh/Questions-and-Exercises-in-C-Sharp | Excercise_08.cs | Excercise_08.cs | using System;
public class Exercise_08
{
public static void Main()
{
/********************************************************************
*
* 8. Write a program that takes a number as input and
* print its multiplication table.
*
*
* By: Jesus Hilario Hernandez
* Last Updated: October 4th 2017
*
********************************************************************/
Console.WriteLine("Enter the number: 5");
var number = Convert.ToInt32(Console.ReadLine());
var ten = 10;
for(var i = 0; i <= ten; i++)
{
Console.WriteLine("{1} * {2} = {3}", number, i, number * i);
}
}
}
| mit | C# | |
d0f1969322a62d949d9610fd5118d851c6758a74 | Drop cassette config in for less integration | Mike737377/Exceptional,Mike737377/Exceptional,Mike737377/Exceptional,Mike737377/Exceptional | src/Exceptional.Web/CassetteConfiguration.cs | src/Exceptional.Web/CassetteConfiguration.cs | using Cassette;
using Cassette.Scripts;
using Cassette.Stylesheets;
namespace Exceptional.Web
{
/// <summary>
/// Configures the Cassette asset bundles for the web application.
/// </summary>
public class CassetteBundleConfiguration : IConfiguration<BundleCollection>
{
public void Configure(BundleCollection bundles)
{
// TODO: Configure your bundles here...
// Please read http://getcassette.net/documentation/configuration
// This default configuration treats each file as a separate 'bundle'.
// In production the content will be minified, but the files are not combined.
// So you probably want to tweak these defaults!
bundles.AddPerIndividualFile<StylesheetBundle>("Content");
bundles.AddPerIndividualFile<ScriptBundle>("Scripts");
// To combine files, try something like this instead:
// bundles.Add<StylesheetBundle>("Content");
// In production mode, all of ~/Content will be combined into a single bundle.
// If you want a bundle per folder, try this:
// bundles.AddPerSubDirectory<ScriptBundle>("Scripts");
// Each immediate sub-directory of ~/Scripts will be combined into its own bundle.
// This is useful when there are lots of scripts for different areas of the website.
}
}
} | mit | C# | |
7ed226ea97579b3399c64668b963a9a44fdd101f | fix signature | xamarin/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,xamarin/monotouch-samples,xamarin/monotouch-samples,iFreedive/monotouch-samples,kingyond/monotouch-samples,markradacz/monotouch-samples,albertoms/monotouch-samples,markradacz/monotouch-samples,W3SS/monotouch-samples,W3SS/monotouch-samples,albertoms/monotouch-samples,kingyond/monotouch-samples,iFreedive/monotouch-samples,markradacz/monotouch-samples,albertoms/monotouch-samples,W3SS/monotouch-samples | ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/GameViewController.cs | ios9/MetalPerformanceShadersHelloWorld/MetalPerformanceShadersHelloWorld/GameViewController.cs | using CoreAnimation;
using Foundation;
using Metal;
using MetalKit;
using MetalPerformanceShaders;
using UIKit;
using CoreGraphics;
namespace MetalPerformanceShadersHelloWorld {
public partial class GameViewController : UIViewController, IMTKViewDelegate, INSCoding {
MTKView metalView;
IMTLCommandQueue commandQueue;
IMTLTexture sourceTexture;
[Export ("initWithCoder:")]
public GameViewController (NSCoder coder) : base (coder)
{
}
public override void ViewDidLoad ()
{
metalView = (MTKView)View;
// Make sure the current device supports MetalPerformanceShaders.
bool? deviceSupportsPerformanceShaders = null;
deviceSupportsPerformanceShaders = metalView.Device?.SupportsFeatureSet (MTLFeatureSet.iOS_GPUFamily2_v1);
if (!deviceSupportsPerformanceShaders.HasValue || !deviceSupportsPerformanceShaders.Value)
return;
MetalPerformanceShadersDisabledLabel.Hidden = true;
SetupView ();
SetupMetal ();
LoadAssets ();
}
void SetupMetal ()
{
// Set the view to use the default device.
metalView.Device = MTLDevice.SystemDefault;
// Create a new command queue.
commandQueue = metalView.Device.CreateCommandQueue ();
}
void SetupView ()
{
metalView.Delegate = this;
// Setup the render target, choose values based on your app.
metalView.DepthStencilPixelFormat = MTLPixelFormat.Stencil8 | MTLPixelFormat.Depth32Float;
// Set up pixel format as your input/output texture.
metalView.ColorPixelFormat = MTLPixelFormat.BGRA8Unorm;
// Allow to access to currentDrawable.texture write mode.
metalView.FramebufferOnly = false;
}
void LoadAssets ()
{
var textureLoader = new MTKTextureLoader (metalView.Device);
NSUrl url = NSBundle.MainBundle.GetUrlForResource ("AnimalImage", "png");
NSError error;
sourceTexture = textureLoader.FromUrl(url, null, out error);
}
void Render ()
{
// Create a new command buffer for each renderpass to the current drawable.
IMTLCommandBuffer commandBuffer = commandQueue.CommandBuffer ();
// Initialize MetalPerformanceShaders gaussianBlur with Sigma = 10.0f.
var gaussianblur = new MPSImageGaussianBlur (metalView.Device, 10f);
var drawable = ((CAMetalLayer)metalView.Layer).NextDrawable ();
// Run MetalPerformanceShader gaussianblur.
gaussianblur.EncodeToCommandBuffer (commandBuffer, sourceTexture, drawable.Texture);
// Schedule a present using the current drawable.
commandBuffer.PresentDrawable (drawable);
// Finalize command buffer.
commandBuffer.Commit ();
commandBuffer.WaitUntilCompleted ();
// To reuse a CAMetalDrawable object’s texture, you must deallocate the drawable after presenting it.
drawable.Dispose ();
}
public void Draw (MTKView view)
{
Render ();
}
public void DrawableSizeWillChange (MTKView view, CGSize size)
{
// Called whenever view changes orientation or layout is changed
}
}
} | using CoreAnimation;
using Foundation;
using Metal;
using MetalKit;
using MetalPerformanceShaders;
using UIKit;
namespace MetalPerformanceShadersHelloWorld {
public partial class GameViewController : UIViewController, IMTKViewDelegate, INSCoding {
MTKView metalView;
IMTLCommandQueue commandQueue;
IMTLTexture sourceTexture;
[Export ("initWithCoder:")]
public GameViewController (NSCoder coder) : base (coder)
{
}
public override void ViewDidLoad ()
{
metalView = (MTKView)View;
// Make sure the current device supports MetalPerformanceShaders.
bool? deviceSupportsPerformanceShaders = null;
deviceSupportsPerformanceShaders = metalView.Device?.SupportsFeatureSet (MTLFeatureSet.iOS_GPUFamily2_v1);
if (!deviceSupportsPerformanceShaders.HasValue || !deviceSupportsPerformanceShaders.Value)
return;
MetalPerformanceShadersDisabledLabel.Hidden = true;
SetupView ();
SetupMetal ();
LoadAssets ();
}
void SetupMetal ()
{
// Set the view to use the default device.
metalView.Device = MTLDevice.SystemDefault;
// Create a new command queue.
commandQueue = metalView.Device.CreateCommandQueue ();
}
void SetupView ()
{
metalView.Delegate = this;
// Setup the render target, choose values based on your app.
metalView.DepthStencilPixelFormat = MTLPixelFormat.Stencil8 | MTLPixelFormat.Depth32Float;
// Set up pixel format as your input/output texture.
metalView.ColorPixelFormat = MTLPixelFormat.BGRA8Unorm;
// Allow to access to currentDrawable.texture write mode.
metalView.FramebufferOnly = false;
}
void LoadAssets ()
{
var textureLoader = new MTKTextureLoader (metalView.Device);
NSUrl url = NSBundle.MainBundle.GetUrlForResource ("AnimalImage", "png");
NSError error;
sourceTexture = textureLoader.TextureWithContentsOfUrl (url, null, out error);
}
void Render ()
{
// Create a new command buffer for each renderpass to the current drawable.
IMTLCommandBuffer commandBuffer = commandQueue.CommandBuffer ();
// Initialize MetalPerformanceShaders gaussianBlur with Sigma = 10.0f.
var gaussianblur = new MPSImageGaussianBlur (metalView.Device, 10f);
var drawable = ((CAMetalLayer)metalView.Layer).NextDrawable ();
// Run MetalPerformanceShader gaussianblur.
gaussianblur.EncodeToCommandBuffer (commandBuffer, sourceTexture, drawable.Texture);
// Schedule a present using the current drawable.
commandBuffer.PresentDrawable (drawable);
// Finalize command buffer.
commandBuffer.Commit ();
commandBuffer.WaitUntilCompleted ();
// To reuse a CAMetalDrawable object’s texture, you must deallocate the drawable after presenting it.
drawable.Dispose ();
}
public void WillLayout (MTKView view, CoreGraphics.CGSize size)
{
// Called whenever view changes orientation or layout is changed
}
public void Draw (MTKView view)
{
Render ();
}
}
} | mit | C# |
d03ecb96bd77e5d2c3f4120301a19a7009de7210 | Create CandiesDP.cs | denivy/CSharpCode,denivy/CSharpCode | CandiesDP.cs | CandiesDP.cs | using System;
using System.IO;
class CandiesDP
{
static void Main(String[] args)
{
System.IO.StreamReader file = new System.IO.StreamReader(@"file_path.txt");
Console.SetIn(file);
int numKids, next, answer, j;
numKids = int.Parse(Console.ReadLine());
int[] ratings = new int[numKids];
int[] candy = new int[numKids];
answer = 0;
candy[0] = 1;
for (int i = 0; i < numKids; i++)
ratings[i] = int.Parse(Console.ReadLine());
for (int i = 1; i < ratings.Length; i++)
{//look at each childs ranking
next = 0;
j = i;
while (j < ratings.Length - 1 && ratings[j] > ratings[j + 1])
{
next++;
j++;
}
if (ratings[i] > ratings[i - 1]) //if current child has a better rating than previous child
candy[i] = candy[i - 1] + 1; //add one to previous
else if (ratings[i] == ratings[i - 1]) candy[i] = 1;
else
{
candy[i - 1] = Math.Max(candy[i - 1], next + 2);
candy[i] = 1;
}
}//end for
for (int i = 0; i < ratings.Length; i++)
{
//Console.Write(candy[i] + " + ");
answer += candy[i];
}//end for
Console.WriteLine(answer);
file.Close();
throw new Exception(); //pause for debug
}//end main
}//end class Candies DP
| mit | C# | |
b917c422adcba76c7d06e2393c3fccbd0217f2c6 | Create Factorial.cs | fireheadmx/ProjectEuler,fireheadmx/ProjectEuler | Factorial.cs | Factorial.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace ProjectEuler
{
class Factorial
{
private List<BigInteger> value;
public Factorial() {
value = new List<BigInteger>();
value.Add(1);
value.Add(1);
}
public Factorial(int value) {
new Factorial();
//val(value);
}
public BigInteger val(int ix)
{
while (value.Count <= ix)
{
value.Add(value[value.Count - 1] * value.Count);
}
return value[ix];
}
}
}
| mit | C# | |
1b1303c8c2df60520eee8ffffca3cb37bc89750e | Add file missed in build | yizhang82/corert,krytarowski/corert,shrah/corert,botaberg/corert,shrah/corert,yizhang82/corert,gregkalapos/corert,gregkalapos/corert,tijoytom/corert,shrah/corert,botaberg/corert,krytarowski/corert,tijoytom/corert,krytarowski/corert,tijoytom/corert,shrah/corert,yizhang82/corert,botaberg/corert,yizhang82/corert,tijoytom/corert,gregkalapos/corert,gregkalapos/corert,botaberg/corert,krytarowski/corert | src/ILCompiler.Compiler/src/Compiler/INonEmittableType.cs | src/ILCompiler.Compiler/src/Compiler/INonEmittableType.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace ILCompiler
{
/// <summary>
/// Used to mark TypeDesc types that are not part of the core type system
/// that should never be turned into an EEType.
/// </summary>
public interface INonEmittableType
{ }
}
| mit | C# | |
e4a843f1fbbd6bd916f712806386f5f31dbd85a3 | Add NeutralResourcesLanguageAttribute to Channels lib | adamsitnik/corefxlab,tarekgh/corefxlab,whoisj/corefxlab,Vedin/corefxlab,dotnet/corefxlab,joshfree/corefxlab,VSadov/corefxlab,VSadov/corefxlab,dotnet/corefxlab,KrzysztofCwalina/corefxlab,benaadams/corefxlab,Vedin/corefxlab,benaadams/corefxlab,VSadov/corefxlab,whoisj/corefxlab,ericstj/corefxlab,ahsonkhan/corefxlab,ahsonkhan/corefxlab,adamsitnik/corefxlab,Vedin/corefxlab,tarekgh/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,Vedin/corefxlab,Vedin/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,stephentoub/corefxlab,VSadov/corefxlab,ericstj/corefxlab,Vedin/corefxlab,joshfree/corefxlab,ericstj/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,VSadov/corefxlab,KrzysztofCwalina/corefxlab,stephentoub/corefxlab,VSadov/corefxlab | src/System.Threading.Tasks.Channels/AssemblyAttributes.cs | src/System.Threading.Tasks.Channels/AssemblyAttributes.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Resources;
[assembly:NeutralResourcesLanguage("en")]
| mit | C# | |
936bedb70a6ef52811b1dbe1aaa9b6984d329e7d | Create res.Designer.cs | Kivitoe/Web-Status | src/res.Designer.cs | src/res.Designer.cs | //------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Web_Stats {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class res {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal res() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Web_Stats.res", typeof(res).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Icon similar to (Icon).
/// </summary>
internal static System.Drawing.Icon _1484722682_08_Web_Development {
get {
object obj = ResourceManager.GetObject("1484722682_08_Web_Development", resourceCulture);
return ((System.Drawing.Icon)(obj));
}
}
}
| mit | C# | |
66bbc09fb958f7b41b73dc04991ad7330e59d8d2 | Create MainView.xaml.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/Draw2D.NetCore/MainView.xaml.cs | src/Draw2D.NetCore/MainView.xaml.cs | // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace Draw2D.NetCore
{
public class MainView : UserControl
{
public MainView()
{
this.InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| mit | C# | |
4476bd20637e4c16f3dd62601682061b1551a246 | Add code for creating challenge from IdentityModel | ZEISS-PiWeb/PiWeb-Api | src/Common/Utilities/ProtocolHelperExtensions.cs | src/Common/Utilities/ProtocolHelperExtensions.cs | #region Copyright
/* * * * * * * * * * * * * * * * * * * * * * * * * */
/* Carl Zeiss IMT (IZfM Dresden) */
/* Softwaresystem PiWeb */
/* (c) Carl Zeiss 2020 */
/* * * * * * * * * * * * * * * * * * * * * * * * * */
#endregion
namespace Zeiss.IMT.PiWeb.Api.Common.Utilities
{
using System;
using System.Security.Cryptography;
using System.Text;
using IdentityModel;
/// <remarks>
/// The following code is originated from an earlier version of the IdentityModel nuget package.
/// </remarks>
internal static class ProtocolHelperExtensions
{
private enum HashStringEncoding
{
Base64,
Base64Url,
}
public static string ToCodeChallenge(this string input)
{
return input.ToSha256(HashStringEncoding.Base64Url);
}
private static string ToSha256(this string input, HashStringEncoding encoding = HashStringEncoding.Base64)
{
if (string.IsNullOrWhiteSpace(input))
{
return string.Empty;
}
using (var sha256 = SHA256.Create())
{
var bytes = Encoding.ASCII.GetBytes(input);
return Encode(sha256.ComputeHash(bytes), encoding);
}
}
private static string Encode(byte[] hash, HashStringEncoding encoding)
{
switch (encoding)
{
case HashStringEncoding.Base64:
return Convert.ToBase64String(hash);
case HashStringEncoding.Base64Url:
return Base64Url.Encode(hash);
default:
throw new ArgumentException("Invalid encoding");
}
}
}
} | bsd-3-clause | C# | |
e3c205ce3f879da09b3395dd178d445b8993c59f | Create Update.cs | zelbo/Number-Guessing | Update.cs | Update.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace NumberGuessing
{
partial class Program
{
static void Update()
{
// --------------------
// Non-State-Specific Processes (quit, help)
//if(KeyState[(int)MyKeys.Escape]) Environment.Exit(0);
if (KeyState[(int)MyKeys.Escape]) exitProgram = true;
// --------------------
// State Specific Processes
switch (gameState)
{
case GameState.Initialize:
Initialize();
gameState = GameState.Guess;
break;
// breaking the input/update/render theme here
// need to implement a custom readline method?
// maybe input/update/render is a little much for a console app.
case GameState.Guess:
string inputString = Console.ReadLine();
int inputNumber;
if (int.TryParse(inputString, out inputNumber))
{
myResult = Guess(inputNumber);
if (myResult.isCorrect) gameState = GameState.Win;
else
{
// three chances
guessesRemaining--;
if (guessesRemaining <= 0) gameState = GameState.Lose;
}
}
else { if (inputString.ToLower() == "q") exitProgram = true; }
break;
case GameState.Win:
// player score++
// play again?
if (GameOver(true)) gameState = GameState.Initialize;
else gameState = GameState.Exit;
break;
case GameState.Lose:
// play again?
if (GameOver(false)) gameState = GameState.Initialize;
else gameState = GameState.Exit;
break;
case GameState.Exit:
// do cleanup stuff here?
// save high score...
// display thank you screen
Console.WriteLine(errorMessage);
Console.WriteLine("");
Console.WriteLine("brought to you by:");
Console.WriteLine("sleep deprived games");
Console.WriteLine("and");
Console.WriteLine("egalitarian but gansta productions");
Console.WriteLine("");
Console.WriteLine("Thank you for playing!");
Console.WriteLine("Press the any key to continue...");
Console.ReadKey();
exitProgram = true;
break;
default:
errorMessage = "Invalid game state during update.";
break;
}
}
}
}
| mit | C# | |
c6287f92fc965132fde7494aff2e04f21c6f6bb9 | Add C# 7.0 Pattern variable with switch-statement example | devlights/try-csharp | TryCSharp.Samples/CSharp7/PatternVariableWithSwitchStatement.cs | TryCSharp.Samples/CSharp7/PatternVariableWithSwitchStatement.cs | using TryCSharp.Common;
namespace TryCSharp.Samples.CSharp7
{
[Sample]
public class PatternVariableWithSwitchStatement : IExecutable
{
public void Execute()
{
// C# 7.0 から Pattern Variables の概念が導入された
// switch 文でもパターンが利用できるようになった
this.SwitchWithPattern(100);
this.SwitchWithPattern("hello");
this.SwitchWithPattern(true);
this.SwitchWithPattern(null);
}
private void SwitchWithPattern(object x)
{
// 型で振り分け
switch (x)
{
case int i:
Output.WriteLine($"x is int: {i}");
break;
case string s:
Output.WriteLine($"x is string: {s}");
break;
case bool b:
Output.WriteLine($"x is bool: {b}");
break;
case null:
Output.WriteLine($"x is null");
break;
}
// case に when で条件を付けることが可能
switch (x)
{
case int i when i == 10:
Output.WriteLine($"x is int, value is 10");
break;
case int i when i == 100:
Output.WriteLine($"x is int, value is 100");
break;
case string s when s == "hello":
Output.WriteLine($"x is string, value is hello");
break;
case string s when s == "world":
Output.WriteLine($"x is string, value is world");
break;
case bool b when b == true:
Output.WriteLine($"x is bool, value is true");
break;
case bool b when b == false:
Output.WriteLine($"x is bool, value is false");
break;
}
}
}
} | mit | C# | |
fc85f37eb606d44f101bf5fef3b3e89460f1b410 | Add IGameRepository interface | Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training,Chess-Variants-Training/Chess-Variants-Training | src/ChessVariantsTraining/DbRepositories/Variant960/IGameRepository.cs | src/ChessVariantsTraining/DbRepositories/Variant960/IGameRepository.cs | using ChessVariantsTraining.Models.Variant960;
namespace ChessVariantsTraining.DbRepositories.Variant960
{
public interface IGameRepository
{
void Add(Game game);
void Get(string id);
void Update(Game game);
}
}
| agpl-3.0 | C# | |
abd8bbd74fc33ee9f57897d0c62e8755523653f8 | fix crash when saving weld command | Rynchodon/ARMS,Rynchodon/Autopilot,Rynchodon/Autopilot,Souper07/Autopilot,Souper07/Autopilot,Rynchodon/ARMS | Scripts/Autopilot/Instruction/Command/Weld.cs | Scripts/Autopilot/Instruction/Command/Weld.cs | using System;
using System.Collections.Generic;
using System.Text;
using Rynchodon.Autopilot.Navigator;
using Sandbox.Game.Entities;
using Sandbox.Game.Gui;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Utils;
namespace Rynchodon.Autopilot.Instruction.Command
{
public class Weld : ACommand
{
private StringBuilder m_target = new StringBuilder();
private bool m_fetch;
public override ACommand Clone()
{
return new Weld() { m_target = m_target, m_fetch = m_fetch };
}
public override string Identifier
{
get { return "weld"; }
}
public override string AddName
{
get { return "Weld"; }
}
public override string AddDescription
{
get { return "Weld a friendly ship"; }
}
public override string Description
{
get { return "Weld the ship: " + m_target + (m_fetch ? ", fetching components" : string.Empty); }
}
public override void AddControls(List<Sandbox.ModAPI.Interfaces.Terminal.IMyTerminalControl> controls)
{
MyTerminalControlTextbox<MyShipController> gridName = new MyTerminalControlTextbox<MyShipController>("GridName", MyStringId.GetOrCompute("Grid"), MyStringId.GetOrCompute("Weld the specified grid"));
gridName.Getter = block => m_target;
gridName.Setter = (block, value) => m_target = value;
controls.Add(gridName);
IMyTerminalControlCheckbox fetch = new MyTerminalControlCheckbox<MyShipController>("FetchComponents", MyStringId.GetOrCompute("Fetch components"), MyStringId.GetOrCompute("Fetch components the next time the ship lands"));
fetch.Getter = block => m_fetch;
fetch.Setter = (block, value) => m_fetch = value;
controls.Add(fetch);
}
protected override Action<Movement.Mover> Parse(VRage.Game.ModAPI.IMyCubeBlock autopilot, string command, out string message)
{
if (string.IsNullOrWhiteSpace(command))
{
message = "No target";
return null;
}
string[] split = command.Split(',');
if (split.Length == 1)
m_fetch = false;
else if (split.Length == 2)
{
if (split[1].TrimStart().StartsWith("f", StringComparison.InvariantCultureIgnoreCase))
m_fetch = true;
else
{
message = "Invalid argument: " + split[1];
return null;
}
}
else
{
message = "Too many arguments: " + split.Length;
return null;
}
m_target = new StringBuilder(split[0]);
message = null;
return mover => new WeldGrid(mover, split[0], m_fetch);
}
protected override string TermToString()
{
return Identifier + ' ' + m_target + (m_fetch ? ",f" : string.Empty);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Rynchodon.Autopilot.Navigator;
using Sandbox.Game.Entities;
using Sandbox.Game.Gui;
using Sandbox.ModAPI.Interfaces.Terminal;
using VRage.Utils;
namespace Rynchodon.Autopilot.Instruction.Command
{
public class Weld : ACommand
{
private StringBuilder m_target = new StringBuilder();
private bool m_fetch;
public override ACommand Clone()
{
return new Weld() { m_target = m_target, m_fetch = m_fetch };
}
public override string Identifier
{
get { return "weld"; }
}
public override string AddName
{
get { return "Weld"; }
}
public override string AddDescription
{
get { return "Weld a friendly ship"; }
}
public override string Description
{
get { return "Weld the ship: " + m_target + (m_fetch ? ", fetching components" : string.Empty); }
}
public override void AddControls(List<Sandbox.ModAPI.Interfaces.Terminal.IMyTerminalControl> controls)
{
MyTerminalControlTextbox<MyShipController> gridName = new MyTerminalControlTextbox<MyShipController>("GridName", MyStringId.GetOrCompute("Grid"), MyStringId.GetOrCompute("Weld the specified grid"));
gridName.Getter = block => m_target;
gridName.Setter = (block, value) => m_target = value;
controls.Add(gridName);
IMyTerminalControlCheckbox fetch = new MyTerminalControlCheckbox<MyShipController>("FetchComponents", MyStringId.GetOrCompute("Fetch components"), MyStringId.GetOrCompute("Fetch components the next time the ship lands"));
fetch.Getter = block => m_fetch;
fetch.Setter = (block, value) => m_fetch = value;
controls.Add(fetch);
}
protected override Action<Movement.Mover> Parse(VRage.Game.ModAPI.IMyCubeBlock autopilot, string command, out string message)
{
if (string.IsNullOrWhiteSpace(command))
{
message = "No target";
return null;
}
string[] split = command.Split(',');
if (split.Length == 1)
m_fetch = false;
else if (split.Length == 2)
{
if (split[1].Trim().Equals("fetch", StringComparison.InvariantCultureIgnoreCase))
m_fetch = true;
else
{
message = "Invalid argument: " + split[1];
return null;
}
}
else
{
message = "Too many arguments: " + split.Length;
return null;
}
m_target = new StringBuilder(split[1]);
message = null;
return mover => new WeldGrid(mover, split[1], m_fetch);
}
protected override string TermToString()
{
return Identifier + ' ' + m_target + (m_fetch ? ", fetch" : string.Empty);
}
}
}
| cc0-1.0 | C# |
b504b0c9fefb3398834a36d0e524e40329d91078 | Add a missing file | rubyu/CreviceApp,rubyu/CreviceApp | CreviceApp/Core.AppGlobal.cs | CreviceApp/Core.AppGlobal.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace CreviceApp
{
public class AppGlobal
{
public readonly Core.Config.UserConfig UserConfig;
public readonly MainForm MainForm;
public AppGlobal()
{
this.UserConfig = new Core.Config.UserConfig();
this.MainForm = new MainForm(this);
}
}
}
| mit | C# | |
2a28ef0e0e787b17e1d0226f9f98b85b8a8c7109 | Add debug printing to the TAPCfgTest class about packet headers | zhanleewo/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,zhanleewo/tapcfg,zhanleewo/tapcfg,eyecreate/tapcfg,zhanleewo/tapcfg,juhovh/tapcfg,eyecreate/tapcfg,eyecreate/tapcfg,juhovh/tapcfg,eyecreate/tapcfg,juhovh/tapcfg | src/bindings/TAPCfgTest.cs | src/bindings/TAPCfgTest.cs |
using TAP;
using System;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start();
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
while (true) {
EthernetFrame frame = dev.Read();
Console.WriteLine("Read Ethernet frame of type {0}",
frame.EtherType);
Console.WriteLine("Source address: {0}",
BitConverter.ToString(frame.SourceAddress));
Console.WriteLine("Destination address: {0}",
BitConverter.ToString(frame.DestinationAddress));
}
}
}
|
using TAP;
using System.Net;
public class TAPCfgTest {
private static void Main(string[] args) {
EthernetDevice dev = new EthernetDevice();
dev.Start();
dev.SetAddress(IPAddress.Parse("192.168.1.1"), 16);
dev.SetAddress(IPAddress.Parse("fc00::1"), 64);
dev.Enabled = true;
System.Threading.Thread.Sleep(100000);
}
}
| lgpl-2.1 | C# |
ba26ec513ddcbd054e924517f73089e1d16395ba | enhance AutoGrab script | thestonefox/VRTK,mbbmbbmm/SteamVR_Unity_Toolkit,virror/VRTK,Innoactive/IA-unity-VR-toolkit-VRTK,red-horizon/VRTK,phr00t/SteamVR_Unity_Toolkit,nmccarty/htvr,jcrombez/SteamVR_Unity_Toolkit,gpvigano/SteamVR_Unity_Toolkit,Blueteak/SteamVR_Unity_Toolkit,adamjweaver/VRTK,Fulby/VRTK,pargee/SteamVR_Unity_Toolkit,gomez-addams/SteamVR_Unity_Toolkit,TMaloteaux/SteamVR_Unity_Toolkit,gpvigano/VRTK,mattboy64/SteamVR_Unity_Toolkit,thestonefox/SteamVR_Unity_Toolkit | Assets/SteamVR_Unity_Toolkit/Scripts/VRTK_ObjectAutoGrab.cs | Assets/SteamVR_Unity_Toolkit/Scripts/VRTK_ObjectAutoGrab.cs | namespace VRTK
{
using UnityEngine;
using System.Collections;
public class VRTK_ObjectAutoGrab : MonoBehaviour
{
public VRTK_InteractableObject objectToGrab;
public bool cloneGrabbedObject;
private VRTK_InteractGrab controller;
private IEnumerator Start()
{
controller = GetComponent<VRTK_InteractGrab>();
if (!controller)
{
Debug.LogError("The VRTK_InteractGrab script is required to be attached to the controller along with this script.");
yield break;
}
if (!objectToGrab)
{
Debug.LogError("You have to assign an object that should be grabbed.");
yield break;
}
while (controller.controllerAttachPoint == null)
{
yield return true;
}
VRTK_InteractableObject grabbableObject = objectToGrab;
if (cloneGrabbedObject)
{
grabbableObject = Instantiate(objectToGrab);
}
controller.GetComponent<VRTK_InteractTouch>().ForceStopTouching();
controller.GetComponent<VRTK_InteractTouch>().ForceTouch(grabbableObject.gameObject);
controller.AttemptGrab();
}
}
} | namespace VRTK
{
using UnityEngine;
using System.Collections;
public class VRTK_ObjectAutoGrab : MonoBehaviour
{
public GameObject objectToGrab;
public bool cloneGrabbedObject;
private VRTK_InteractGrab controller;
private IEnumerator Start()
{
controller = GetComponent<VRTK_InteractGrab>();
if (!controller)
{
Debug.LogError("The VRTK_InteractGrab script is required to be attached to the controller along with this script.");
}
if (!objectToGrab || !objectToGrab.GetComponent<VRTK_InteractableObject>())
{
Debug.LogError("The objectToGrab Game Object must have the VRTK_InteractableObject script applied to it.");
}
while (controller.controllerAttachPoint == null)
{
yield return true;
}
var grabbableObject = objectToGrab;
if (cloneGrabbedObject)
{
grabbableObject = Instantiate(objectToGrab);
}
controller.GetComponent<VRTK_InteractTouch>().ForceTouch(grabbableObject);
controller.AttemptGrab();
}
}
} | mit | C# |
8998322f932c6f6afe322d6f4eb4a82f623c5151 | Add assembly info. | hymerman/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,svn2github/nvidia-texture-tools,svn2github/nvidia-texture-tools,hymerman/nvidia-texture-tools,hymerman/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,casseveritt/nvidia-texture-tools,hymerman/nvidia-texture-tools,casseveritt/nvidia-texture-tools,svn2github/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,svn2github/nvidia-texture-tools,salamanderrake/nvidia-texture-tools,casseveritt/nvidia-texture-tools | project/vc8/Nvidia.TextureTools/Properties/AssemblyInfo.cs | project/vc8/Nvidia.TextureTools/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("Nvidia.TextureTools")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("NVIDIA Corporation")]
[assembly: AssemblyProduct("Nvidia.TextureTools")]
[assembly: AssemblyCopyright("Copyright © NVIDIA 2008")]
[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("5fa03fb3-b7a3-4ba8-90e7-545929731356")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# | |
423a836bad0454a226895533e894f98b56a995d7 | Add new class to facilitate multi-threaded onion generation | printerpam/purpleonion,printerpam/purpleonion,neoeinstein/purpleonion | src/Xpdm.PurpleOnion/OnionGenerator.cs | src/Xpdm.PurpleOnion/OnionGenerator.cs | using System;
using System.ComponentModel;
namespace Xpdm.PurpleOnion
{
class OnionGenerator
{
private readonly BackgroundWorker worker = new BackgroundWorker();
public OnionGenerator()
{
worker.DoWork += GenerateOnion;
worker.RunWorkerCompleted += RunWorkerCompleted;
}
public event EventHandler<OnionGeneratedEventArgs> OnionGenerated;
public void StartGenerating()
{
worker.RunWorkerAsync();
}
protected virtual void GenerateOnion(object sender, DoWorkEventArgs e)
{
e.Result = OnionAddress.Create();
}
protected virtual void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
OnionGeneratedEventArgs args = new OnionGeneratedEventArgs {
Result = (OnionAddress) e.Result,
};
OnOnionGenerated(args);
if (!args.Cancel)
{
worker.RunWorkerAsync();
}
}
protected virtual void OnOnionGenerated(OnionGeneratedEventArgs e)
{
EventHandler<OnionGeneratedEventArgs> handler = OnionGenerated;
if (handler != null)
{
handler(this, e);
}
}
public class OnionGeneratedEventArgs : EventArgs {
new internal static readonly OnionGeneratedEventArgs Empty = new OnionGeneratedEventArgs();
public bool Cancel { get; set; }
public OnionAddress Result { get; set; }
}
}
}
| bsd-3-clause | C# | |
29206d321129910331493317c0a1ecb88771a605 | Remove test classes | InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform,InfinniPlatform/InfinniPlatform | InfinniPlatform.ServiceHost/ContainerModule.cs | InfinniPlatform.ServiceHost/ContainerModule.cs | using InfinniPlatform.IoC;
namespace InfinniPlatform.ServiceHost
{
public class ContainerModule : IContainerModule
{
public void Load(IContainerBuilder builder)
{
// Register dependencies
}
}
} | using System;
using System.Reflection;
using System.Threading.Tasks;
using InfinniPlatform.Cache;
using InfinniPlatform.Http;
using InfinniPlatform.IoC;
namespace InfinniPlatform.ServiceHost
{
public class ContainerModule : IContainerModule
{
public void Load(IContainerBuilder builder)
{
// Register dependencies
builder.RegisterHttpServices(GetType().GetTypeInfo().Assembly);
}
}
public class HttpService: IHttpService
{
private readonly ISharedCache _sharedCache;
public HttpService(ISharedCache sharedCache)
{
_sharedCache = sharedCache;
}
public void Load(IHttpServiceBuilder builder)
{
builder.Get["/cache"]=Func;
}
private Task<object> Func(IHttpRequest httpRequest)
{
_sharedCache.Set("123", "123");
return Task.FromResult<object>(true);
}
}
} | agpl-3.0 | C# |
f518696f6e2adf57c6c06a02988775a998d0591f | add courses controller | alimon808/contoso-university,alimon808/contoso-university,alimon808/contoso-university | ContosoUniversity.Spa.React/Controllers/CoursesController.cs | ContosoUniversity.Spa.React/Controllers/CoursesController.cs | using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using ContosoUniversity.Common.Interfaces;
using ContosoUniversity.Data.Entities;
using System.Linq;
using ContosoUniversity.Common;
using ContosoUniversity.Data.DbContexts;
using ContosoUniversity.Common.DTO;
using AutoMapper;
namespace ContosoUniversity_Spa_React.Controllers
{
[Route("api/[controller]")]
public class CoursesController : Controller
{
private readonly IRepository<Course> _coursesRepo;
private readonly IMapper _mapper;
public CoursesController(UnitOfWork<ApiContext> unitOfWork, IMapper mapper)
{
_coursesRepo = unitOfWork.CourseRepository;
_mapper = mapper;
}
public IEnumerable<Course> Get()
{
return _coursesRepo.GetAll().ToArray();
}
}
} | mit | C# | |
b13736500d26464b730426d9589b757d0b1f4bd0 | Add unit of work interface | Branimir123/ZobShop,Branimir123/ZobShop,Branimir123/ZobShop | src/ZobShop.Data/Contracts/IUnitOfWork.cs | src/ZobShop.Data/Contracts/IUnitOfWork.cs | using System;
namespace ZobShop.Data.Contracts
{
public interface IUnitOfWork : IDisposable
{
void Commit();
}
}
| mit | C# | |
f7cf56f130e7a3f1965f8ba2a0277ed073cc69dc | test value handling | ElderByte-/Archimedes.Framework | Archimedes.Framework.Test/ConfigurationTest/Values/TestValueService.cs | Archimedes.Framework.Test/ConfigurationTest/Values/TestValueService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Archimedes.Framework.DI.Attribute;
using Archimedes.Framework.Stereotype;
namespace Archimedes.Framework.Test.ConfigurationTest.Values
{
[Service]
public class TestValueService
{
[Value("${test.simpleBool}")]
private bool _simpleBool;
[Value("${test.simpleBool2}")]
private bool _simpleBool2;
[Value("${test.simpleBoolNegative}")]
private bool simpleBoolNegative;
[Value("${test.simpleBoolNegative2}")]
private bool simpleBoolNegative2;
[Value("${test.simpleBoolOpt}")]
private bool? simpleBoolOpt;
[Value("${test.simpleBoolNegativeOpt}")]
private bool? simpleBoolNegativeOpt;
[Value("${unset}")]
private bool _simpleBoolUnset;
[Value("${unset2}")]
private bool? _simpleBoolUnsetOpt;
public bool SimpleBool
{
get { return _simpleBool; }
}
public bool SimpleBool2
{
get { return _simpleBool2; }
}
public bool SimpleBoolNegative
{
get { return simpleBoolNegative; }
}
public bool SimpleBoolNegative2
{
get { return simpleBoolNegative2; }
}
public bool? SimpleBoolOpt
{
get { return simpleBoolOpt; }
}
public bool? SimpleBoolNegativeOpt
{
get { return simpleBoolNegativeOpt; }
}
public bool BoolUnset
{
get { return _simpleBoolUnset; }
}
public bool? BoolUnsetOpt {
get { return _simpleBoolUnsetOpt; }
}
}
}
| mit | C# | |
020ef160a2eb77e7369f4f78b7dd75a220d0ac9d | Create Day_2.cs | leocabrallce/HackerRank,leocabrallce/HackerRank | Day_2.cs | Day_2.cs | using System;
class Solution
{
static void Main(String[] args)
{
var mealCost = double.Parse(Console.ReadLine());
var tipPercent = int.Parse(Console.ReadLine());
var taxPercent = int.Parse(Console.ReadLine());
var tip = tipPercent * mealCost / 100;
var tax = taxPercent * mealCost / 100;
var totalCost = Math.Round(tip + tax + mealCost);
Console.WriteLine($"The total meal cost is {totalCost} dollars.");
}
}
| mit | C# | |
d7936f98d44fe4aa83948a00e0dd4b84adbf18bd | fix #11 - uwp scheduled notifications message ID was incorrect | aritchie/notifications | Acr.Notifications.Uwp/NotificationsImpl.cs | Acr.Notifications.Uwp/NotificationsImpl.cs | using System;
using System.Linq;
using Windows.Data.Xml.Dom;
using Windows.Storage;
using Windows.UI.Notifications;
namespace Acr.Notifications
{
public class NotificationsImpl : AbstractNotificationsImpl
{
const string TOAST_TEMPLATE = @"
<toast>
{0}
<visual>
<binding template=""ToastText02"">
<text id=""1"">{1}</text>
<text id=""2"">{2}</text>
</binding>
</visual>
</toast>";
readonly BadgeUpdater badgeUpdater;
readonly ToastNotifier toastNotifier;
readonly XmlDocument badgeXml;
readonly XmlElement badgeEl;
public NotificationsImpl()
{
this.badgeUpdater = BadgeUpdateManager.CreateBadgeUpdaterForApplication();
this.toastNotifier = ToastNotificationManager.CreateToastNotifier();
this.badgeXml = BadgeUpdateManager.GetTemplateContent(BadgeTemplateType.BadgeNumber);
this.badgeEl = (XmlElement)this.badgeXml.SelectSingleNode("/badge");
}
const string CFG_KEY = "acr.notifications";
string GetMessageId()
{
var id = 1;
var s = ApplicationData.Current.LocalSettings.Values;
if (s.ContainsKey(CFG_KEY))
{
id = Int32.Parse((string)s[CFG_KEY]);
}
s[CFG_KEY] = id.ToString();
return id.ToString();
}
public override string Send(Notification notification)
{
var id = this.GetMessageId();
var soundXml = notification.Sound == null
? String.Empty
: $"<audio src=\"ms-appx:///Assets/{notification.Sound}.wav\"/>";
var xmlData = String.Format(TOAST_TEMPLATE, soundXml, notification.Title, notification.Message);
var xml = new XmlDocument();
xml.LoadXml(xmlData);
if (notification.Date == null && notification.When == null)
{
var toast = new ToastNotification(xml);
this.toastNotifier.Show(toast);
}
else
{
var schedule = new ScheduledToastNotification(xml, notification.SendTime)
{
Id = id
};
this.toastNotifier.AddToSchedule(schedule);
}
return id;
}
public override int Badge
{
get { return 0; }
set
{
if (value == 0)
{
this.badgeUpdater.Clear();
}
else
{
this.badgeEl.SetAttribute("value", value.ToString());
this.badgeUpdater.Update(new BadgeNotification(this.badgeXml));
}
}
}
public override bool Cancel(string id)
{
var notification = this.toastNotifier
.GetScheduledToastNotifications()
.FirstOrDefault(x => x.Id.Equals(id, StringComparison.OrdinalIgnoreCase));
if (notification == null)
return false;
this.toastNotifier.RemoveFromSchedule(notification);
return true;
}
public override void CancelAll()
{
this.Badge = 0;
var list = this.toastNotifier
.GetScheduledToastNotifications()
.ToList();
foreach (var item in list)
this.toastNotifier.RemoveFromSchedule(item);
}
public override void Vibrate(int ms) => Windows
.Phone
.Devices
.Notification
.VibrationDevice
.GetDefault()
.Vibrate(TimeSpan.FromMilliseconds(ms));
}
} | mit | C# | |
bb79f9a309033d6cfa1514f6959861b767367508 | Create CertificateMixed.cs | OfficeDev/PnP-Sites-Core,phillipharding/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,OfficeDev/PnP-Sites-Core,phillipharding/PnP-Sites-Core | Core/OfficeDevPnP.Core/IdentityModel/TokenProviders/ADFS/CertificateMixed.cs | Core/OfficeDevPnP.Core/IdentityModel/TokenProviders/ADFS/CertificateMixed.cs | mit | C# | ||
64609ae9366c624e930ba79b6c6edd0ac28eebb0 | Add DriverStandings tests. | lewishenson/FluentErgast | FluentErgast.Tests/F1/DriverStandingsTests.cs | FluentErgast.Tests/F1/DriverStandingsTests.cs | using System;
using System.Threading.Tasks;
using FluentAssertions;
using FluentErgast.F1.Mappers;
using FluentErgast.Http;
using NSubstitute;
using Xunit;
using Dtos = FluentErgast.F1.Dtos;
using DriverStandingsInstance = FluentErgast.F1.DriverStandings;
using InternalDtos = FluentErgast.F1.InternalDtos;
namespace FluentErgast.Tests.F1
{
public class DriverStandingsTests
{
[Fact]
public async Task ForYearAsyncGetsExpectedDataAndReturnsMappedInstance()
{
// Arrange
var httpClient = Substitute.For<IHttpClient>();
var driverStandingsResponse = new InternalDtos.DriverStandings.Response
{
MRData = new InternalDtos.DriverStandings.MRData
{
StandingsTable = new InternalDtos.DriverStandings.StandingsTable()
}
};
httpClient.GetAsync<InternalDtos.DriverStandings.Response>("http://ergast.com/api/f1/2017/driverStandings.json")
.Returns(Task.FromResult(driverStandingsResponse));
var standingsTableMapper = Substitute.For<IMapper<InternalDtos.DriverStandings.StandingsTable, Dtos.DriverStandings.StandingsTable>>();
var standingsTable = new Dtos.DriverStandings.StandingsTable();
standingsTableMapper.Map(driverStandingsResponse.MRData.StandingsTable)
.Returns(standingsTable);
var subjectUnderTest = new DriverStandingsInstance(httpClient, standingsTableMapper);
// Act
var output = await subjectUnderTest.ForYearAsync(2017);
// Assert
output.Should().Be(standingsTable);
}
[Fact]
public async Task ForCurrentYearAsyncGetsExpectedDataAndReturnsMappedInstance()
{
// Arrange
var httpClient = Substitute.For<IHttpClient>();
var driverStandingsResponse = new InternalDtos.DriverStandings.Response
{
MRData = new InternalDtos.DriverStandings.MRData
{
StandingsTable = new InternalDtos.DriverStandings.StandingsTable()
}
};
httpClient.GetAsync<InternalDtos.DriverStandings.Response>($"http://ergast.com/api/f1/{DateTime.Now.Year}/driverStandings.json")
.Returns(Task.FromResult(driverStandingsResponse));
var standingsTableMapper = Substitute.For<IMapper<InternalDtos.DriverStandings.StandingsTable, Dtos.DriverStandings.StandingsTable>>();
var standingsTable = new Dtos.DriverStandings.StandingsTable();
standingsTableMapper.Map(driverStandingsResponse.MRData.StandingsTable)
.Returns(standingsTable);
var subjectUnderTest = new DriverStandingsInstance(httpClient, standingsTableMapper);
// Act
var output = await subjectUnderTest.ForCurrentYearAsync();
// Assert
output.Should().Be(standingsTable);
}
[Fact]
public async Task ForRoundGetsExpectedDataAndReturnsMappedInstance()
{
// Arrange
var httpClient = Substitute.For<IHttpClient>();
var driverStandingsResponse = new InternalDtos.DriverStandings.Response
{
MRData = new InternalDtos.DriverStandings.MRData
{
StandingsTable = new InternalDtos.DriverStandings.StandingsTable()
}
};
httpClient.GetAsync<InternalDtos.DriverStandings.Response>("http://ergast.com/api/f1/2017/3/driverStandings.json")
.Returns(Task.FromResult(driverStandingsResponse));
var standingsTableMapper = Substitute.For<IMapper<InternalDtos.DriverStandings.StandingsTable, Dtos.DriverStandings.StandingsTable>>();
var standingsTable = new Dtos.DriverStandings.StandingsTable();
standingsTableMapper.Map(driverStandingsResponse.MRData.StandingsTable)
.Returns(standingsTable);
var subjectUnderTest = new DriverStandingsInstance(httpClient, standingsTableMapper);
// Act
var output = await subjectUnderTest.ForRound(3).ForYearAsync(2017);
// Assert
output.Should().Be(standingsTable);
}
}
} | mit | C# | |
94a737891650685023e88a9143d842a54b012682 | Fix MessageBox behaviour | zlphoenix/Wox,EmuxEvans/Wox,kayone/Wox,renzhn/Wox,danisein/Wox,kdar/Wox,JohnTheGr8/Wox,jondaniels/Wox,18098924759/Wox,gnowxilef/Wox,shangvven/Wox,kdar/Wox,yozora-hitagi/Saber,Megasware128/Wox,dstiert/Wox,apprentice3d/Wox,Launchify/Launchify,vebin/Wox,gnowxilef/Wox,18098924759/Wox,jondaniels/Wox,vebin/Wox,mika76/Wox,sanbinabu/Wox,dstiert/Wox,AlexCaranha/Wox,JohnTheGr8/Wox,dstiert/Wox,kdar/Wox,mika76/Wox,apprentice3d/Wox,medoni/Wox,derekforeman/Wox,danisein/Wox,vebin/Wox,yozora-hitagi/Saber,EmuxEvans/Wox,Megasware128/Wox,sanbinabu/Wox,derekforeman/Wox,renzhn/Wox,EmuxEvans/Wox,shangvven/Wox,sanbinabu/Wox,AlexCaranha/Wox,gnowxilef/Wox,shangvven/Wox,mika76/Wox,derekforeman/Wox,AlexCaranha/Wox,18098924759/Wox,zlphoenix/Wox,medoni/Wox,apprentice3d/Wox,kayone/Wox,Launchify/Launchify,kayone/Wox | Wox.Plugin.SystemPlugins/Program/ProgramSetting.xaml.cs | Wox.Plugin.SystemPlugins/Program/ProgramSetting.xaml.cs | using System.Windows;
using System.Windows.Controls;
using Wox.Infrastructure.Storage.UserSettings;
namespace Wox.Plugin.SystemPlugins.Program
{
/// <summary>
/// Interaction logic for ProgramSetting.xaml
/// </summary>
public partial class ProgramSetting : UserControl
{
public ProgramSetting()
{
InitializeComponent();
Loaded += Setting_Loaded;
}
private void Setting_Loaded(object sender, RoutedEventArgs e)
{
programSourceView.ItemsSource = UserSettingStorage.Instance.ProgramSources;
}
public void ReloadProgramSourceView()
{
programSourceView.Items.Refresh();
}
private void btnAddProgramSource_OnClick(object sender, RoutedEventArgs e)
{
ProgramSourceSetting programSource = new ProgramSourceSetting(this);
programSource.ShowDialog();
}
private void btnDeleteProgramSource_OnClick(object sender, RoutedEventArgs e)
{
ProgramSource seletedProgramSource = programSourceView.SelectedItem as ProgramSource;
if (seletedProgramSource != null)
{
if (MessageBox.Show("Are your sure to delete " + seletedProgramSource.ToString(), "Delete ProgramSource",
MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
UserSettingStorage.Instance.ProgramSources.Remove(seletedProgramSource);
programSourceView.Items.Refresh();
}
}
else
{
MessageBox.Show("Please select a program source");
}
}
private void btnEditProgramSource_OnClick(object sender, RoutedEventArgs e)
{
ProgramSource seletedProgramSource = programSourceView.SelectedItem as ProgramSource;
if (seletedProgramSource != null)
{
ProgramSourceSetting programSource = new ProgramSourceSetting(this);
programSource.UpdateItem(seletedProgramSource);
programSource.ShowDialog();
}
else
{
MessageBox.Show("Please select a program source");
}
}
}
}
| using System.Windows;
using System.Windows.Controls;
using Wox.Infrastructure.Storage.UserSettings;
namespace Wox.Plugin.SystemPlugins.Program
{
/// <summary>
/// Interaction logic for ProgramSetting.xaml
/// </summary>
public partial class ProgramSetting : UserControl
{
public ProgramSetting()
{
InitializeComponent();
Loaded += Setting_Loaded;
}
private void Setting_Loaded(object sender, RoutedEventArgs e)
{
programSourceView.ItemsSource = UserSettingStorage.Instance.ProgramSources;
}
public void ReloadProgramSourceView()
{
programSourceView.Items.Refresh();
}
private void btnAddProgramSource_OnClick(object sender, RoutedEventArgs e)
{
ProgramSourceSetting programSource = new ProgramSourceSetting(this);
programSource.ShowDialog();
}
private void btnDeleteProgramSource_OnClick(object sender, RoutedEventArgs e)
{
ProgramSource seletedProgramSource = programSourceView.SelectedItem as ProgramSource;
if (seletedProgramSource != null &&
MessageBox.Show("Are your sure to delete " + seletedProgramSource.ToString(), "Delete ProgramSource",
MessageBoxButton.YesNo) == MessageBoxResult.Yes)
{
UserSettingStorage.Instance.ProgramSources.Remove(seletedProgramSource);
programSourceView.Items.Refresh();
}
else
{
MessageBox.Show("Please select a program source");
}
}
private void btnEditProgramSource_OnClick(object sender, RoutedEventArgs e)
{
ProgramSource seletedProgramSource = programSourceView.SelectedItem as ProgramSource;
if (seletedProgramSource != null)
{
ProgramSourceSetting programSource = new ProgramSourceSetting(this);
programSource.UpdateItem(seletedProgramSource);
programSource.ShowDialog();
}
else
{
MessageBox.Show("Please select a program source");
}
}
}
}
| mit | C# |
9277b38426ac865715e5da382d8e995af45d7de7 | Add PublicAccessPrevention integration test | jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet | apis/Google.Cloud.Storage.V1/Google.Cloud.Storage.V1.IntegrationTests/PublicAccessPreventionTest.cs | apis/Google.Cloud.Storage.V1/Google.Cloud.Storage.V1.IntegrationTests/PublicAccessPreventionTest.cs | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using Google.Apis.Storage.v1.Data;
using Xunit;
namespace Google.Cloud.Storage.V1.IntegrationTests
{
[Collection(nameof(StorageFixture))]
public class PublicAccessPreventionTest
{
private const string EnforcedValue = "enforced";
private const string UnspecifiedValue = "unspecified";
private static readonly Policy.BindingsData AllUsersViewer = new Policy.BindingsData
{
Members = new[] { "allUsers" },
Role = "roles/storage.objectViewer"
};
private readonly StorageFixture _fixture;
public PublicAccessPreventionTest(StorageFixture fixture) => _fixture = fixture;
[Fact]
public void PreventAccessOnExistingBucket()
{
var client = _fixture.Client;
string bucketName = _fixture.GenerateBucketName();
Bucket bucket = _fixture.CreateBucket(bucketName, false);
Assert.Null(bucket.IamConfiguration.PublicAccessPrevention);
// Enforce PAP
client.PatchBucket(CreateBucketRepresentation(bucketName, EnforcedValue));
// We shouldn't be able to allow all users to view objects.
var policy = client.GetBucketIamPolicy(bucketName);
policy.Bindings.Add(AllUsersViewer);
Assert.Throws<GoogleApiException>(() => client.SetBucketIamPolicy(bucketName, policy));
}
[Fact]
public void PreventAccessOnNewBucket()
{
var client = _fixture.Client;
string bucketName = _fixture.GenerateBucketName();
StorageFixture.SleepAfterBucketCreateDelete();
Bucket created = client.CreateBucket(_fixture.ProjectId, CreateBucketRepresentation(bucketName, EnforcedValue));
_fixture.RegisterBucketToDelete(bucketName);
StorageFixture.SleepAfterBucketCreateDelete();
Assert.Equal(EnforcedValue, created.IamConfiguration.PublicAccessPrevention);
// We shouldn't be able to allow all users to view objects.
var policy = client.GetBucketIamPolicy(bucketName);
policy.Bindings.Add(AllUsersViewer);
Assert.Throws<GoogleApiException>(() => client.SetBucketIamPolicy(bucketName, policy));
}
[Fact]
public void RestoreAccess()
{
var client = _fixture.Client;
string bucketName = _fixture.GenerateBucketName();
Bucket bucket = _fixture.CreateBucket(bucketName, false);
Assert.Null(bucket.IamConfiguration.PublicAccessPrevention);
// Enforce PAP, then unenforce it
client.PatchBucket(CreateBucketRepresentation(bucketName, EnforcedValue));
client.PatchBucket(CreateBucketRepresentation(bucketName, UnspecifiedValue));
// Now we should be able to allow all users to view objects.
var policy = client.GetBucketIamPolicy(bucketName);
policy.Bindings.Add(AllUsersViewer);
client.SetBucketIamPolicy(bucketName, policy);
}
private static Bucket CreateBucketRepresentation(string bucketName, string papValue) =>
new Bucket
{
Name = bucketName,
IamConfiguration = new Bucket.IamConfigurationData { PublicAccessPrevention = papValue }
};
}
}
| apache-2.0 | C# | |
55327c16e3828c52496fa3c2bfe29f5859c5cc60 | Create HelloWorld.cs | m181190/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,DakRomo/2017Challenges,m181190/2017Challenges,m181190/2017Challenges,DakRomo/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,m181190/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,DakRomo/2017Challenges,m181190/2017Challenges,popcornanachronism/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,popcornanachronism/2017Challenges,popcornanachronism/2017Challenges,m181190/2017Challenges,mindm/2017Challenges,popcornanachronism/2017Challenges,popcornanachronism/2017Challenges,m181190/2017Challenges,m181190/2017Challenges,DakRomo/2017Challenges,DakRomo/2017Challenges,DakRomo/2017Challenges,popcornanachronism/2017Challenges,DakRomo/2017Challenges,popcornanachronism/2017Challenges,popcornanachronism/2017Challenges,DakRomo/2017Challenges,mindm/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,mindm/2017Challenges,popcornanachronism/2017Challenges,popcornanachronism/2017Challenges,DakRomo/2017Challenges,DakRomo/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,mindm/2017Challenges,erocs/2017Challenges,erocs/2017Challenges,mindm/2017Challenges,popcornanachronism/2017Challenges,DakRomo/2017Challenges,erocs/2017Challenges,popcornanachronism/2017Challenges,DakRomo/2017Challenges,m181190/2017Challenges,DakRomo/2017Challenges,erocs/2017Challenges,popcornanachronism/2017Challenges,m181190/2017Challenges,DakRomo/2017Challenges,m181190/2017Challenges,erocs/2017Challenges,popcornanachronism/2017Challenges,mindm/2017Challenges | challenge_0/CSharp/badoomtch/HelloWorld.cs | challenge_0/CSharp/badoomtch/HelloWorld.cs | using System;
namespace ProgrammingPlayground
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}
}
| mit | C# | |
5dc910c8808479430a2ba90687e5583788ae801d | Add utility class. | ShooShoSha/SEUtility | Utility.cs | Utility.cs | /*
Copyright (c) 2015 Kevin O'Brien
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
namespace SE
{
/// <summary>
/// Utility methods for various common operations in Space Engineers.
/// </summary>
/// <seealso href="http://www.spaceengineersgame.com/"/>
/// <seealso href="http://www.spaceengineerswiki.com/Programming"/>
class Utility
{
/// <summary>
/// Returns list of blocks of a group.
/// </summary>
/// <param name="groupName">Name of block group.</param>
/// <returns>List of blocks of <paramref name="groupName"/> or <see langword="null"/> if group not found.</returns>
List<IMyTerminalBlock> GetBlockGroup(string groupName)
{
var groups = new List<IMyBlockGroup>();
GridTerminalSystem.GetBlockGroups(groups);
for(int i = 0; i < groups.Count; i++)
{
if(groups[i].Name.Equals(groupName))
{
return groups[i].Blocks;
}
}
return null;
}
}
}
| mit | C# | |
991517d647d7f72ff066c61ff162af92aaa266c8 | Add simple test case | smoogipooo/osu-framework,Tom94/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework | osu.Framework.Tests/Visual/TestCaseCircularContainerSizing.cs | osu.Framework.Tests/Visual/TestCaseCircularContainerSizing.cs | // Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using NUnit.Framework;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Testing;
using OpenTK;
namespace osu.Framework.Tests.Visual
{
public class TestCaseCircularContainerSizing : TestCase
{
[Test]
public void TestLateSizing()
{
HookedContainer container;
CircularContainer circular;
Child = container = new HookedContainer
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Child = circular = new CircularContainer
{
RelativeSizeAxes = Axes.Both,
Masking = true,
Child = new Box { RelativeSizeAxes = Axes.Both }
}
};
container.OnUpdate = () => onUpdate(container);
container.OnUpdateAfterChildren = () => onUpdateAfterChildren(container, circular);
bool hasCorrectCornerRadius = false;
AddAssert("has correct corner radius", () => hasCorrectCornerRadius);
void onUpdate(Container parent)
{
// Suppose the parent has some arbitrary size prior to the child being updated...
parent.Size = Vector2.One;
}
void onUpdateAfterChildren(Container parent, CircularContainer nested)
{
// ... and the size of the parent is changed to the desired value after the child has been updated
// This could happen just by ordering of events in the hierarchy, regardless of auto or relative size
parent.Size = new Vector2(200);
hasCorrectCornerRadius = nested.CornerRadius == 100;
}
}
private class HookedContainer : Container
{
public new Action OnUpdate;
public Action OnUpdateAfterChildren;
protected override void Update()
{
base.Update();
OnUpdate?.Invoke();
}
protected override void UpdateAfterChildren()
{
OnUpdateAfterChildren?.Invoke();
base.UpdateAfterChildren();
}
}
}
}
| mit | C# | |
c14fe94699e79fdedc4f68e3237dd863534a966e | Add test class 'FindInfoCarrierTest' | azabluda/InfoCarrier.Core | test/InfoCarrier.Core.EFCore.FunctionalTests/FindInfoCarrierTest.cs | test/InfoCarrier.Core.EFCore.FunctionalTests/FindInfoCarrierTest.cs | namespace InfoCarrier.Core.EFCore.FunctionalTests
{
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Specification.Tests;
public abstract class FindInfoCarrierTest
: FindTestBase<TestStore, FindInfoCarrierTest.FindInfoCarrierFixture>
{
protected FindInfoCarrierTest(FindInfoCarrierFixture fixture)
: base(fixture)
{
}
public class FindInfoCarrierTestSet : FindInfoCarrierTest
{
public FindInfoCarrierTestSet(FindInfoCarrierFixture fixture)
: base(fixture)
{
}
protected override TEntity Find<TEntity>(DbContext context, params object[] keyValues)
=> context.Set<TEntity>().Find(keyValues);
protected override Task<TEntity> FindAsync<TEntity>(DbContext context, params object[] keyValues)
=> context.Set<TEntity>().FindAsync(keyValues);
}
public class FindInfoCarrierTestContext : FindInfoCarrierTest
{
public FindInfoCarrierTestContext(FindInfoCarrierFixture fixture)
: base(fixture)
{
}
protected override TEntity Find<TEntity>(DbContext context, params object[] keyValues)
=> context.Find<TEntity>(keyValues);
protected override Task<TEntity> FindAsync<TEntity>(DbContext context, params object[] keyValues)
=> context.FindAsync<TEntity>(keyValues);
}
public class FindInfoCarrierTestNonGeneric : FindInfoCarrierTest
{
public FindInfoCarrierTestNonGeneric(FindInfoCarrierFixture fixture)
: base(fixture)
{
}
protected override TEntity Find<TEntity>(DbContext context, params object[] keyValues)
=> (TEntity)context.Find(typeof(TEntity), keyValues);
protected override async Task<TEntity> FindAsync<TEntity>(DbContext context, params object[] keyValues)
=> (TEntity)await context.FindAsync(typeof(TEntity), keyValues);
}
public class FindInfoCarrierFixture : FindFixtureBase
{
private readonly InfoCarrierInMemoryTestHelper<FindContext> helper;
public FindInfoCarrierFixture()
{
this.helper = InfoCarrierInMemoryTestHelper.Create(
this.OnModelCreating,
(opt, _) => new FindContext(opt));
}
public override DbContext CreateContext(TestStore testStore)
=> this.helper.CreateInfoCarrierContext();
public override TestStore CreateTestStore()
=> this.helper.CreateTestStore(this.Seed);
}
}
}
| mit | C# | |
98b2b746ef63a2c9a8ea5f6463a838a43871c34c | Create DeleteSkillCommandHandler.cs | NinjaVault/NinjaHive,NinjaVault/NinjaHive | NinjaHive.BusinessLayer/CommandHandlers/DeleteSkillCommandHandler.cs | NinjaHive.BusinessLayer/CommandHandlers/DeleteSkillCommandHandler.cs | using NinjaHive.Contract.Commands;
using NinjaHive.Core;
using NinjaHive.Domain;
namespace NinjaHive.BusinessLayer.CommandHandlers
{
public class DeleteSkillCommandHandler
: ICommandHandler<DeleteSkillCommand>
{
private readonly IRepository<SkillEntity> skillEntityRepository;
public DeleteSkillCommandHandler(IRepository<SkillEntity> skillEntityRepository)
{
this.skillEntityRepository = skillEntityRepository;
}
public void Handle(DeleteSkillCommand command)
{
var skillItem = this.skillEntityRepository.GetById(command.Skill.Id);
this.skillEntityRepository.Remove(skillItem);
}
}
}
| apache-2.0 | C# | |
0cf1157c8d6242d7c18532aab521a9987481f68d | Implement AbstractRemoveRedundantEqualityWithTrueCodeFixProvider | eriawan/roslyn,stephentoub/roslyn,eriawan/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,aelij/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,aelij/roslyn,physhi/roslyn,diryboy/roslyn,wvdd007/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,AmadeusW/roslyn,eriawan/roslyn,gafter/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,brettfo/roslyn,stephentoub/roslyn,weltkante/roslyn,mavasani/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,tannergooding/roslyn,AmadeusW/roslyn,gafter/roslyn,heejaechang/roslyn,mavasani/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,tmat/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,tmat/roslyn,panopticoncentral/roslyn,weltkante/roslyn,tannergooding/roslyn,stephentoub/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,gafter/roslyn,bartdesmet/roslyn,diryboy/roslyn,diryboy/roslyn,mavasani/roslyn,tmat/roslyn,dotnet/roslyn,KevinRansom/roslyn,dotnet/roslyn,wvdd007/roslyn,sharwell/roslyn,physhi/roslyn,aelij/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,heejaechang/roslyn,tannergooding/roslyn,AmadeusW/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,shyamnamboodiripad/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn | src/Analyzers/Core/CodeFixes/RemoveRedundantEqualityWithTrue/AbstractRemoveRedundantEqualityWithTrueCodeFixProvider.cs | src/Analyzers/Core/CodeFixes/RemoveRedundantEqualityWithTrue/AbstractRemoveRedundantEqualityWithTrueCodeFixProvider.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editing;
namespace Microsoft.CodeAnalysis.RemoveRedundantEqualityWithTrue
{
internal abstract class AbstractRemoveRedundantEqualityWithTrueCodeFixProvider
: SyntaxEditorBasedCodeFixProvider
{
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(IDEDiagnosticIds.RemoveRedundantEqualityWithTrueDiagnosticId);
internal override CodeFixCategory CodeFixCategory => CodeFixCategory.CodeStyle;
public override Task RegisterCodeFixesAsync(CodeFixContext context)
{
foreach (var diagnostic in context.Diagnostics)
{
context.RegisterCodeFix(new MyCodeAction(
AnalyzersResources.Remove_redundant_equality_with_true,
(ct) => FixAsync(context.Document, diagnostic, ct)),
diagnostic);
}
return Task.CompletedTask;
}
protected override async Task FixAllAsync(Document document, ImmutableArray<Diagnostic> diagnostics, SyntaxEditor editor, CancellationToken cancellationToken)
{
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
foreach (var diagnostic in diagnostics)
{
var node = root.FindNode(diagnostic.Location.SourceSpan);
if (TryGetReplacementNode(node, out var replacement))
{
editor.ReplaceNode(node, replacement);
}
}
}
protected abstract bool TryGetReplacementNode(SyntaxNode node, out SyntaxNode replacement);
private class MyCodeAction : CustomCodeActions.DocumentChangeAction
{
public MyCodeAction(string title, Func<CancellationToken, Task<Document>> createChangedDocument)
: base(title, createChangedDocument, title)
{
}
}
}
}
| mit | C# | |
402c2308a4b7c6d4eb8febedd874d52eb1f41249 | Add test to ensure ClaimsPrincipal serializes via MobileFormatter | MarimerLLC/csla,JasonBock/csla,MarimerLLC/csla,MarimerLLC/csla,rockfordlhotka/csla,JasonBock/csla,rockfordlhotka/csla,JasonBock/csla,rockfordlhotka/csla | Source/csla.netcore.test/Serialization/ClaimsPrincipalTests.cs | Source/csla.netcore.test/Serialization/ClaimsPrincipalTests.cs | //-----------------------------------------------------------------------
// <copyright file="ClaimsPrincipalTests.cs" company="Marimer LLC">
// Copyright (c) Marimer LLC. All rights reserved.
// Website: https://cslanet.com
// </copyright>
// <summary>no summary</summary>
//-----------------------------------------------------------------------
using System.Linq;
using System.Security.Claims;
#if !NUNIT
using Microsoft.VisualStudio.TestTools.UnitTesting;
#else
using NUnit.Framework;
using TestClass = NUnit.Framework.TestFixtureAttribute;
using TestInitialize = NUnit.Framework.SetUpAttribute;
using TestCleanup = NUnit.Framework.TearDownAttribute;
using TestMethod = NUnit.Framework.TestAttribute;
#endif
namespace Csla.Test.Serialization
{
[TestClass]
public class ClaimsPrincipalTests
{
[TestMethod]
public void CloneClaimsPrincipal()
{
Configuration.ConfigurationManager.AppSettings["CslaSerializationFormatter"] = "MobileFormatter";
var i = new ClaimsIdentity();
i.AddClaim(new Claim("name", "Franklin"));
var p = new ClaimsPrincipal(i);
var p1 = (ClaimsPrincipal)Core.ObjectCloner.Clone(p);
Assert.AreNotSame(p, p1, "Should be different instances");
Assert.AreEqual(p.Claims.Count(), p1.Claims.Count(), "Should have same number of claims");
var c = p1.Claims.Where(r => r.Type == "name").First();
Assert.AreEqual("Franklin", c.Value, "Claim value should match");
}
}
}
| mit | C# | |
0ed077fc2559ad60d6d3fea9156137164ead1749 | Create CountFactorielZeros.cs | emilisa/CountFactorielZeros | CountFactorielZeros.cs | CountFactorielZeros.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Numerics;
namespace CountFactorielZeros
{
class CountFactorielZeros
{
/// <Exercise>
/// Write a program that calculates for given N how many trailing zeros present at the end of the number N!.
/// Examples:
/// N = 10 - N! = 3628800 - 2 zeros
/// N = 20 - N! = 2432902008176640000 - 4 zeros
/// Your program should work for N up to 50 000.
/// Three variants of decision are included
/// </Exercise>
static void Main(string[] args)
{
int number = int.Parse(Console.ReadLine());
int count = 1;
BigInteger result = 1;
do
{
result = result * count;
count++;
} while (count <= number);
Console.WriteLine("Factoriel of {0}, is: ", number);
Console.WriteLine(result);
//Decision variant 1: Devison to 5 dependence is used
//5! = 120 so 5/5 = 1 and 1/5 = 0,2 sum 1 + 0 = 1 zero at the end
//10! = 3628800 devide 10/5 = 2 and 2/5 = 0,4 sum 2 + 0 = 2 zeros at the end
//15! = 1307674368000 devide 15/5 = 3 and 3/5 = 0,6 sum 3 + 0 = 3 zeros at the end
//25! = 15511210043330985984000000 devide 25/5 = 5 and 5/5 = 1,0 sum 5 + 1 = 6 zeros at the end
# region Variant 1
// works only for numbers up to 124!
if (number <= 124)
{
int devidor = number / 5;
int plusVlaue = devidor / 5;
int countOfZerosVar1 = devidor + plusVlaue;
Console.WriteLine("At the end of the result there is {0} zeros /.var1/", countOfZerosVar1);
}
else
{
Console.WriteLine("This variant works only with numbers <= 124! /.var1/");
}
# endregion
//Decision variant 2: Here is used more rough, method - simply counting zeros at the end of the result
//Using result string as array of chars and counting how many chars zero are at the end.
# region Variant 2
//Decision variant 2a: with for loop
string resultString = Convert.ToString(result);
int countOfZerosVar2A = 0;
for (int i = resultString.Length - 1; i > 0; i--)
{
if (resultString[i] != '0')
{
break;
}
else if (resultString[i] == '0')
{
countOfZerosVar2A++;
}
}
Console.WriteLine("At the end of the result there is {0} zeros /.var2a/", countOfZerosVar2A);
//Decision variant 2b: with do-while loop
int countOfZerosVar2B = 0;
int j = resultString.Length - 1;
do
{
countOfZerosVar2B++;
j--;
} while (resultString[j] == '0');
Console.WriteLine("At the end of the result there is {0} zeros /.var2b/", countOfZerosVar2B);
# endregion
//Decision variant 3: A variant of Devison to 5 dependence is used but with do while loop
//to ensure counting of zeros of numbers bigger than 124!
# region Variant 3
int countOfZerosVar3 = 0;
do
{
countOfZerosVar3 = countOfZerosVar3 + number / 5;
number = number / 5;
} while (number / 5 != 0);
Console.WriteLine("At the end of the result there is {0} zeros /.var3/", countOfZerosVar3);
#endregion
}
}
}
| mit | C# | |
ed92f53c50959e9273305d400d8d0895da1f5480 | Create RecordDeclarationOrganizer.cs | sharwell/roslyn,ErikSchierboom/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,eriawan/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,tannergooding/roslyn,dotnet/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,diryboy/roslyn,physhi/roslyn,sharwell/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,tmat/roslyn,weltkante/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,AlekseyTs/roslyn,tmat/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,mgoertz-msft/roslyn,sharwell/roslyn,wvdd007/roslyn,tmat/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,physhi/roslyn,tannergooding/roslyn,KevinRansom/roslyn,wvdd007/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,KevinRansom/roslyn,weltkante/roslyn,weltkante/roslyn,AmadeusW/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,mavasani/roslyn,AmadeusW/roslyn,physhi/roslyn,mavasani/roslyn,AlekseyTs/roslyn,mavasani/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn | src/Features/CSharp/Portable/Organizing/Organizers/RecordDeclarationOrganizer.cs | src/Features/CSharp/Portable/Organizing/Organizers/RecordDeclarationOrganizer.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using System.Threading;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Organizing.Organizers;
namespace Microsoft.CodeAnalysis.CSharp.Organizing.Organizers
{
[ExportSyntaxNodeOrganizer(LanguageNames.CSharp), Shared]
internal class RecordDeclarationOrganizer : AbstractSyntaxNodeOrganizer<RecordDeclarationSyntax>
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public RecordDeclarationOrganizer()
{
}
protected override RecordDeclarationSyntax Organize(
RecordDeclarationSyntax syntax,
CancellationToken cancellationToken)
{
return syntax.Update(
syntax.AttributeLists,
ModifiersOrganizer.Organize(syntax.Modifiers),
syntax.Keyword,
syntax.Identifier,
syntax.TypeParameterList,
syntax.BaseList,
syntax.ConstraintClauses,
syntax.OpenBraceToken,
MemberDeclarationsOrganizer.Organize(syntax.Members, cancellationToken),
syntax.CloseBraceToken,
syntax.SemicolonToken);
}
}
}
| mit | C# | |
faf87cb0d00d3830393608090590b28f50e99654 | add concat | m5knt/ThunderEgg.Extensions | src/Collections/Concat.cs | src/Collections/Concat.cs | /**
* @file
* @brief Repeat操作
*/
using System;
using System.Collections;
using System.Collections.Generic;
namespace ThunderEgg.Extentions {
public static partial class A {
/// <summary>IEnumerator を連結します</summary>
public static IEnumerator //
Concat(this IEnumerator @this, IEnumerator follow) //
{
while (@this.MoveNext()) yield return @this.Current;
while (follow.MoveNext()) yield return follow.Current;
}
/// <summary>IEnumerator<T> を連結します</summary>
public static IEnumerator<T> //
Concat<T>(this IEnumerator<T> @this, IEnumerator<T> follow) //
{
while (@this.MoveNext()) yield return @this.Current;
while (follow.MoveNext()) yield return follow.Current;
}
}
}
| mit | C# | |
2c990e5474aeac92d354c1441063de5db401b7bd | add http request reason provider test | carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,verdentk/aspnetboilerplate,verdentk/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,luchaoshuai/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,luchaoshuai/aspnetboilerplate,carldai0106/aspnetboilerplate,ryancyq/aspnetboilerplate,verdentk/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,ilyhacker/aspnetboilerplate,ryancyq/aspnetboilerplate,carldai0106/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,ilyhacker/aspnetboilerplate | test/Abp.Web.Tests/EntityHistory/EntityHistory_Reason_Tests.cs | test/Abp.Web.Tests/EntityHistory/EntityHistory_Reason_Tests.cs | using System.Threading.Tasks;
using Abp.Dependency;
using Abp.EntityHistory;
using Abp.TestBase;
using Abp.Web.EntityHistory;
using Shouldly;
using Xunit;
namespace Abp.Web.Tests
{
public class EntityHistory_Reason_Tests : AbpIntegratedTestBase<AbpWebModule>
{
private readonly MyNonUseCaseMarkedClass _nonUseCaseMarkedClass;
private readonly MyUseCaseMarkedClass _useCaseMarkedClass;
public EntityHistory_Reason_Tests()
{
_nonUseCaseMarkedClass = Resolve<MyNonUseCaseMarkedClass>();
_useCaseMarkedClass = Resolve<MyUseCaseMarkedClass>();
}
[Fact]
public void HttpRequestEntityChangeSetReasonProvider_Can_Be_Constructor_Injected()
{
_useCaseMarkedClass.ReasonProvider.ShouldBeOfType<HttpRequestEntityChangeSetReasonProvider>();
}
[Fact]
public void HttpRequestEntityChangeSetReasonProvider_Should_Be_Property_Injected()
{
_nonUseCaseMarkedClass.ReasonProvider.ShouldBeOfType<HttpRequestEntityChangeSetReasonProvider>();
}
[Fact]
public void Should_Intercept_UseCase_Marked_Classes()
{
_useCaseMarkedClass.NonUseCaseMarkedMethod();
}
[Fact]
public void Should_Intercept_UseCase_Marked_Methods()
{
_nonUseCaseMarkedClass.UseCaseMarkedMethod();
}
[Fact]
public async Task Should_Intercept_UseCase_Marked_Async_Methods()
{
await _nonUseCaseMarkedClass.UseCaseMarkedAsyncMethod();
}
[Fact]
public async Task Should_Intercept_UseCase_Marked_Async_Methods_WithResult()
{
await _nonUseCaseMarkedClass.UseCaseMarkedAsyncMethodWithResult();
}
[Fact]
public void Should_Not_Intercept_No_UseCase_Marked_Method()
{
_nonUseCaseMarkedClass.AnotherMethod();
}
}
public static class Consts
{
public const string UseCaseDescription = "UseCaseDescription";
}
public class MyNonUseCaseMarkedClass : ITransientDependency
{
public IEntityChangeSetReasonProvider ReasonProvider { get; set; }
public MyNonUseCaseMarkedClass()
{
ReasonProvider = NullEntityChangeSetReasonProvider.Instance;
}
[UseCase(Description = Consts.UseCaseDescription)]
public virtual void UseCaseMarkedMethod()
{
ReasonProvider.Reason.ShouldBe(Consts.UseCaseDescription);
}
[UseCase(Description = Consts.UseCaseDescription)]
public virtual async Task UseCaseMarkedAsyncMethod()
{
ReasonProvider.Reason.ShouldBe(Consts.UseCaseDescription);
await Task.CompletedTask;
}
[UseCase(Description = Consts.UseCaseDescription)]
public virtual async Task<string> UseCaseMarkedAsyncMethodWithResult()
{
ReasonProvider.Reason.ShouldBe(Consts.UseCaseDescription);
return await Task.FromResult("");
}
public virtual void AnotherMethod()
{
ReasonProvider.Reason.ShouldBeNull();
}
}
[UseCase(Description = Consts.UseCaseDescription)]
public class MyUseCaseMarkedClass : ITransientDependency
{
public readonly IEntityChangeSetReasonProvider ReasonProvider;
public MyUseCaseMarkedClass(IEntityChangeSetReasonProvider reasonProvider)
{
ReasonProvider = reasonProvider;
}
public virtual void NonUseCaseMarkedMethod()
{
ReasonProvider.Reason.ShouldBe(Consts.UseCaseDescription);
}
}
}
| mit | C# | |
765bd3b35e286c910eb83b0e4ffa1ed6a33828b5 | add OnTestChecker | BigBabay/AsyncConverter,BigBabay/AsyncConverter | AsyncConverter/AsyncHelpers/ConfigureAwaitCheckers/CustomCheckers/OnTestChecker.cs | AsyncConverter/AsyncHelpers/ConfigureAwaitCheckers/CustomCheckers/OnTestChecker.cs | using AsyncConverter.Checkers;
using AsyncConverter.Settings;
using JetBrains.Application.Settings;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Psi.CSharp.Tree;
using JetBrains.ReSharper.Psi.Tree;
namespace AsyncConverter.AsyncHelpers.ConfigureAwaitCheckers.CustomCheckers
{
[SolutionComponent]
internal class OnTestChecker : IConfigureAwaitCustomChecker
{
private readonly IUnderTestChecker underTestChecker;
public OnTestChecker(IUnderTestChecker underTestChecker)
{
this.underTestChecker = underTestChecker;
}
public bool CanBeAdded(IAwaitExpression element)
{
var excludeTestMethods = element.GetSettingsStore().GetValue(AsyncConverterSettingsAccessor.ExcludeTestMethodsFromConfigureAwait);
var methodDeclaration =
element.GetContainingTypeMemberDeclarationIgnoringClosures() as IMethodDeclaration;
if (methodDeclaration == null)
return true;
return !excludeTestMethods || !underTestChecker.IsUnder(methodDeclaration);
}
}
} | mit | C# | |
24b2b06ea019f1d6a39ad7af58f54dccd5624996 | Disable concurrent test execution | jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet,jskeet/gcloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet | apis/Google.Cloud.Translation.V2/Google.Cloud.Translation.V2.Tests/AssemblyInfo.cs | apis/Google.Cloud.Translation.V2/Google.Cloud.Translation.V2.Tests/AssemblyInfo.cs | // Copyright 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.CompilerServices;
using Xunit;
// Because of the Stackdriver limits on reading and writing entries.
// This reduces the chances of exceeding the limits.
[assembly: CollectionBehavior(DisableTestParallelization = true)] | apache-2.0 | C# | |
a39d5c01e1693576e48f50d02d3a0033f1cd2003 | Create SamplePacket.cs | cfairchi/MulticastUDP | packets/SamplePacket.cs | packets/SamplePacket.cs | namespace MulticastUDP.packets {
public class SamplePacket : Packet {
public double DoubleValue {get;set;}
public string StringValue {get;set;}
public DateTime DateTimeValue {get;set}
public override PACKETTYPE PacketType {get { return PACKETTYPE.SAMPLE; }}
public SamplePacket() : base() {}
public SamplePacket(bool isHeartBeat) : base(isHeartBeat) {}
public SamplePacket(byte[] theBytes) : base(theBytes){}
public SamplePackdet(SamplePacket thePacket) : base(thePacket) {
DoubleValue
}
}
}
| mit | C# | |
8faecc20eb4337b6a47fba7117005b7cc099f2e7 | Create KelvinTegelaar.cs | planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell | src/Firehose.Web/Authors/KelvinTegelaar.cs | src/Firehose.Web/Authors/KelvinTegelaar.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class KelvinTegelaar : IAmACommunityMember
{
public string FirstName => "Kelvin";
public string LastName => "Tegelaar";
public string ShortBioOrTagLine => "For every monitoring automation there is an equal PowerShell remediation.";
public string StateOrRegion => "Rotterdam, Netherlands";
public string EmailAddress => "ktegelaar@cyberdrain.com";
public string TwitterHandle => "KelvinTegelaar";
public string GitHubHandle => "KelvinTegelaar";
public string GravatarHash => "4dc012d6848c8403805130f2fefcf64b";
public GeoPosition Position => new GeoPosition(51.921638,4.528056);
public Uri WebSite => new Uri("https://www.cyberdrain.com");
public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.cyberdrain.com/feed/"); } }
public string FeedLanguageCode => "en";
}
}
| mit | C# | |
b44db9f5e5036fd59cb4e62f2b2a40df56aaff14 | Add test scene for thumbnail component | peppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,peppy/osu,ppy/osu | osu.Game.Tests/Visual/Beatmaps/TestSceneBeatmapCardThumbnail.cs | osu.Game.Tests/Visual/Beatmaps/TestSceneBeatmapCardThumbnail.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.Drawables.Cards;
using osu.Game.Overlays;
using osuTK;
namespace osu.Game.Tests.Visual.Beatmaps
{
public class TestSceneBeatmapCardThumbnail : OsuTestScene
{
[Cached]
private OverlayColourProvider colourProvider = new OverlayColourProvider(OverlayColourScheme.Blue);
[Test]
public void TestThumbnailPreview()
{
BeatmapCardThumbnail thumbnail = null;
AddStep("create thumbnail", () => Child = thumbnail = new BeatmapCardThumbnail(CreateAPIBeatmapSet(Ruleset.Value))
{
Anchor = Anchor.Centre,
Origin = Anchor.Centre,
Size = new Vector2(200)
});
AddToggleStep("toggle dim", dimmed => thumbnail.Dimmed.Value = dimmed);
}
}
}
| mit | C# | |
b8824e64c45ef9cc2a38869a745877b43b691f00 | Add near-empty Row class | 12joan/hangman | row.cs | row.cs | using System;
namespace Hangman {
public class Row {
public Row() {
}
}
}
| unlicense | C# | |
fec7c44606cacd645ac8e4d37520d653c4d85e0a | Create program.cs | nathanrosspowell/presentations,nathanrosspowell/presentations,nathanrosspowell/presentations,nathanrosspowell/presentations | src/beginner_guides/programmer_talk/program.cs | src/beginner_guides/programmer_talk/program.cs | // Lesson 1 CPP examples.
#include "stdafx.h" // This is what a basic 'Console Application' gets set up with in Visual Studio
#include <stdio.h> // Includes the function like printf
#include <vector> // Includes std::vector, which means standard resizable array -or- a list
#include <string> // Includes std::string
// In C++ if you want to call a before it is defined (when reading from top to bottom), then you have to do this:
void Example1();
void Example2();
void Example3();
void UserExercise1();
void UserExercise2();
void UserExercise3();
// This is called a forward decleration and the compiler needs it to know that the function WILL exsist at some point.
template<class T> class GenericType
{
private:
T _privateData;
public:
void SetData( T setValue )
{
_privateData = setValue;
}
T GetData()
{
return _privateData;
}
};
class CallStackExample
{
private:
int _mathsQuestions = 10;
int _scienceQuestions = 15;
int _bonusQuestions = 3;
public:
void Run()
{
float score = (float)GetScore(); // This is how to 'cast' (change the type) from int to a float.
float total = (float)GetTotal();
float average = (score / total ) * 100;
printf("Score: %d/%d Average: %f\n", GetScore(), GetTotalTheHardWay(), average );
}
int GetScore()
{
return 16;
}
int GetTotal()
{
return _mathsQuestions + _scienceQuestions + _bonusQuestions;
}
int GetTotalTheHardWay()
{
return The();
}
int The()
{
return Hard();
}
int Hard()
{
return Way();
}
int Way()
{
return GetTotal();
}
};
class Exercise3
{
public:
void StackOverflow()
{
}
};
// This is called the 'entry point' of the program.
// The function parameters are the number of arguments and an array of pointers to strings.
// This is how command line arguments are injected into the program.
int _tmain(int argc, _TCHAR* argv[])
{
Example1();
Example2();
Example3();
UserExercise1();
UserExercise2();
UserExercise3();
// The progam will exit when it's finished.
// Put a breakpoint (F9) on this line of code to keep the console window open.
printf("The program is going to finish!");
return 0;
}
void Example1()
{
// These are some basic variable types.
int age = 27; // int is a whole number
char middleInitial = 'R'; // use ' for chars
std::string firstName = "Nathan"; // use " for strings
float hateForOlives = 97.3f; // a number with a decimal point, the 'f' is manditory
// Here are some arrays.
char favoriteAnimal[] = { 'C', 'u', 't', 't', 'l', 'e', 'f', 'i', 's', 'h' }; // https://www.youtube.com/watch?v=GDwOi7HpHtQ
float coolNumbers[] = { 99.66f, 88.88f, 66.99f };
// Here are some generic (templated) types.
std::vector<int> testScores = { 7, 9, 8, 10, 6 };
std::vector<char> lastName = { 'P', 'o', 'w', 'e', 'l', 'l' };
std::vector<std::string> catchphrase = { "That's", "a", "bingo!" };
// A way to use a list of chars
std::string bestAnimal = "";
for( char i : favoriteAnimal )
{
bestAnimal += i;
}
// A way to use a list of numbers.
int sum = 0;
for( int i : testScores )
{
sum += i;
}
int average = sum / testScores.size(); // what is the bug here?
// Some standard library wizardy to make a list of chars in to a string
std::string familyName(lastName.begin(), lastName.end());
// Output to the screen.
// printf uses escape codes;
// %s = string
// %c = char
// %d = int
// %f = float
// \n = new line (return)
// %% = %
// \a = ???? try it!
printf("Name: %s %c %s Age: %d\n", firstName.c_str(), middleInitial, familyName.c_str(), age);
printf("Average test score: %d\n", average );
printf("Hate for Olives: %f%% Fave Animal: %s\n", hateForOlives, bestAnimal.c_str());
}
void Example2()
{
// Generic (template) example.
GenericType<std::string> myName;
myName.SetData("Nathan");
GenericType<int> myAge;
myAge.SetData(27);
printf( "%s is %u\n", myName.GetData().c_str(), myAge.GetData() );
}
void Example3()
{
// Call Stack example.
// Go put a breakpoint inside the function GetTotal.
// When the breakpoint hits, look at the call stack.
// Continue the program (F5).
// Look at the next callstack.
CallStackExample example;
example.Run();
}
void UserExercise1()
{
// Following Example1, print out your name and gamer tag.
// Store each part in a variable.
// Do not use the 'string' class.
printf("Print out UserExercise1 here...\n");
}
void UserExercise2()
{
// Following Example2, make a your own template class.
// The class must have a function called 'GetDoubled', which uses the '+' operation
// Print out the results for int, float and string.
printf("Print out UserExercise2 here...\n");
}
void UserExercise3()
{
// Make this function call create a stack overflow.
Exercise3 uhoh;
uhoh.StackOverflow();
printf("This won't get printed out if UserExercise3 is completed!\n");
}
| mit | C# | |
9176a8b50f627f25d624138309c5df3166c47257 | Create BaseService.cs | ioab/.NET-EF6-GenericRepository,CypressNorth/.NET-EF6-GenericRepository | BaseService.cs | BaseService.cs | using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
namespace com.youapp.data.services
{
public class BaseService<TObject> where TObject : class
{
protected RecipeContext _context;
public BaseService(RecipeContext context)
{
_context = context;
}
public ICollection<TObject> GetAll()
{
return _context.Set<TObject>().ToList();
}
public async Task<ICollection<TObject>> GetAllAsync()
{
return await _context.Set<TObject>().ToListAsync();
}
public TObject Get(int id)
{
return _context.Set<TObject>().Find(id);
}
public async Task<TObject> GetAsync(int id)
{
return await _context.Set<TObject>().FindAsync(id);
}
public TObject Find(Expression<Func<TObject, bool>> match)
{
return _context.Set<TObject>().SingleOrDefault(match);
}
public async Task<TObject> FindAsync(Expression<Func<TObject, bool>> match)
{
return await _context.Set<TObject>().SingleOrDefaultAsync(match);
}
public ICollection<TObject> FindAll(Expression<Func<TObject, bool>> match)
{
return _context.Set<TObject>().Where(match).ToList();
}
public async Task<ICollection<TObject>> FindAllAsync(Expression<Func<TObject, bool>> match)
{
return await _context.Set<TObject>().Where(match).ToListAsync();
}
public TObject Add(TObject t)
{
_context.Set<TObject>().Add(t);
_context.SaveChanges();
return t;
}
public async Task<TObject> AddAsync(TObject t)
{
_context.Set<TObject>().Add(t);
await _context.SaveChangesAsync();
return t;
}
public TObject Update(TObject updated,int key)
{
if (updated == null)
return null;
TObject existing = _context.Set<TObject>().Find(key);
if (existing != null)
{
_context.Entry(existing).CurrentValues.SetValues(updated);
_context.SaveChanges();
}
return existing;
}
public async Task<TObject> UpdateAsync(TObject updated, int key)
{
if (updated == null)
return null;
TObject existing = await _context.Set<TObject>().FindAsync(key);
if (existing != null)
{
_context.Entry(existing).CurrentValues.SetValues(updated);
await _context.SaveChangesAsync();
}
return existing;
}
public void Delete(TObject t)
{
_context.Set<TObject>().Remove(t);
_context.SaveChanges();
}
public async void DeleteAsync(TObject t)
{
_context.Set<TObject>().Remove(t);
await _context.SaveChangesAsync();
}
public int Count()
{
return _context.Set<TObject>().Count();
}
public async Task<int> CountAsync()
{
return await _context.Set<TObject>().CountAsync();
}
}
}
| mit | C# | |
9796bb82fa99f40def19326346364aaa97ba0cf1 | Create ProductSize.cs | daniela1991/hack4europecontest | ProductSize.cs | ProductSize.cs | namespace Cdiscount.OpenApi.ProxyClient.Contract.Common
{
/// <summary>
/// product size entity
/// </summary>
public class ProductSize
{
/// <summary>
/// Size identifier
/// </summary>
public string Id { get; set; }
/// <summary>
/// Size name
/// </summary>
public string Name { get; set; }
/// <summary>
/// Sale price (in euros)
/// </summary>
public decimal SalePrice { get; set; }
/// <summary>
/// True if the size is available
/// </summary>
public bool IsAvailable { get; set; }
}
}
| mit | C# | |
53db9f7f9dbcdc87a566f4865f3227103ea2fea4 | Insert new files, Alura, C# e seus Fundamentos, Aula 1 | fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs,fabriciofmsilva/labs | alura/c-sharp/Form1.cs | alura/c-sharp/Form1.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace OiMundo
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(Object sender, EventArgs e)
{
MessageBox.Show("Hello World");
}
}
}
| mit | C# | |
c0c8167b8981859b3caee3068c3674beedb8a5aa | Add AddAspectScope extensions | AspectCore/AspectCore-Framework,AspectCore/Lite,AspectCore/AspectCore-Framework,AspectCore/Abstractions | extras/src/AspectCore.Extensions.AspNetCore/Extensions/ServiceCollectionExtensions.cs | extras/src/AspectCore.Extensions.AspNetCore/Extensions/ServiceCollectionExtensions.cs | using System;
using System.Collections.Generic;
using System.Text;
using AspectCore.DynamicProxy;
using AspectCore.Extensions.AspectScope;
using Microsoft.Extensions.DependencyInjection;
namespace AspectCore.Extensions.AspNetCore
{
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddAspectScope(this IServiceCollection services)
{
if (services == null)
{
throw new ArgumentNullException(nameof(services));
}
services.AddScoped<IAspectScheduler, ScopeAspectScheduler>();
services.AddScoped<IAspectContextFactory, ScopeAspectContextFactory>();
services.AddScoped<IAspectBuilderFactory, ScopeAspectBuilderFactory>();
return services;
}
}
} | mit | C# | |
347eeec65fcbefea577cd2de488b6f1b0fafb7a4 | Add shader disposal test coverage | ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework | osu.Framework.Tests/Shaders/TestSceneShaderDisposal.cs | osu.Framework.Tests/Shaders/TestSceneShaderDisposal.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using NUnit.Framework;
using osu.Framework.Graphics.Shaders;
using osu.Framework.IO.Stores;
using osu.Framework.Testing;
using osu.Framework.Tests.Visual;
namespace osu.Framework.Tests.Shaders
{
public class TestSceneShaderDisposal : FrameworkTestScene
{
private ShaderManager manager;
private Shader shader;
private WeakReference<IShader> shaderRef;
[SetUpSteps]
public void SetUpSteps()
{
AddStep("setup manager", () =>
{
manager = new TestShaderManager(new NamespacedResourceStore<byte[]>(new DllResourceStore(typeof(Game).Assembly), @"Resources/Shaders"));
shader = (Shader)manager.Load(VertexShaderDescriptor.TEXTURE_2, FragmentShaderDescriptor.TEXTURE);
shaderRef = new WeakReference<IShader>(shader);
shader.Compile();
});
AddUntilStep("wait for load", () => shader.IsLoaded);
}
[Test]
public void TestShadersLoseReferencesOnManagerDisposal()
{
AddStep("remove local reference", () => shader = null);
AddStep("dispose manager", () =>
{
manager.Dispose();
manager = null;
});
AddUntilStep("reference lost", () =>
{
GC.Collect();
GC.WaitForPendingFinalizers();
return !shaderRef.TryGetTarget(out _);
});
}
private class TestShaderManager : ShaderManager
{
public TestShaderManager(IResourceStore<byte[]> store)
: base(store)
{
}
internal override Shader CreateShader(string name, List<ShaderPart> parts) => new TestShader(name, parts);
private class TestShader : Shader
{
internal TestShader(string name, List<ShaderPart> parts)
: base(name, parts)
{
}
protected override int CreateProgram() => 1337;
protected override bool CompileInternal() => true;
protected override void SetupUniforms()
{
Uniforms.Add("test", new Uniform<int>(this, "test", 1));
}
protected override string GetProgramLog() => string.Empty;
protected override void DeleteProgram(int id)
{
}
}
}
}
}
| mit | C# | |
6e797ddcac59f939f7fed68a9f0a91c1bf9a5143 | Add test coverage of creating, saving and loading a new beatmap | NeoAdonis/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu | osu.Game.Tests/Visual/Editing/TestSceneEditorSaving.cs | osu.Game.Tests/Visual/Editing/TestSceneEditorSaving.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Linq;
using NUnit.Framework;
using osu.Framework.Input;
using osu.Framework.Testing;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Rulesets.Edit;
using osu.Game.Screens.Edit;
using osu.Game.Screens.Menu;
using osu.Game.Screens.Select;
using osuTK.Input;
namespace osu.Game.Tests.Visual.Editing
{
public class TestSceneEditorSaving : OsuGameTestScene
{
private Editor editor => Game.ChildrenOfType<Editor>().FirstOrDefault();
private EditorBeatmap editorBeatmap => (EditorBeatmap)editor.Dependencies.Get(typeof(EditorBeatmap));
/// <summary>
/// Tests the general expected flow of creating a new beatmap, saving it, then loading it back from song select.
/// </summary>
[Test]
public void TestNewBeatmapSaveThenLoad()
{
AddStep("set default beatmap", () => Game.Beatmap.SetDefault());
PushAndConfirm(() => new EditorLoader());
AddUntilStep("wait for editor load", () => editor != null);
AddStep("Add timing point", () => editorBeatmap.ControlPointInfo.Add(0, new TimingControlPoint()));
AddStep("Enter compose mode", () => InputManager.Key(Key.F1));
AddUntilStep("Wait for compose mode load", () => editor.ChildrenOfType<HitObjectComposer>().FirstOrDefault()?.IsLoaded == true);
AddStep("Change to placement mode", () => InputManager.Key(Key.Number2));
AddStep("Move to playfield", () => InputManager.MoveMouseTo(Game.ScreenSpaceDrawQuad.Centre));
AddStep("Place single hitcircle", () => InputManager.Click(MouseButton.Left));
AddStep("Save and exit", () =>
{
InputManager.Keys(PlatformAction.Save);
InputManager.Key(Key.Escape);
});
AddUntilStep("Wait for main menu", () => Game.ScreenStack.CurrentScreen is MainMenu);
PushAndConfirm(() => new PlaySongSelect());
AddUntilStep("Wait for beatmap selected", () => !Game.Beatmap.IsDefault);
AddStep("Open options", () => InputManager.Key(Key.F3));
AddStep("Enter editor", () => InputManager.Key(Key.Number5));
AddUntilStep("Wait for editor load", () => editor != null);
AddAssert("Beatmap contains single hitcircle", () => editorBeatmap.HitObjects.Count == 1);
}
}
}
| mit | C# | |
b9ce54f3cabdede8f7d2092787ca55f7a7fefd43 | Make sure changelist timer is enabled in watchdog, because Steamkit can get stuck between being connected and logging in | agarbuno/SteamDatabaseBackend,SGColdSun/SteamDatabaseBackend,SteamDatabase/SteamDatabaseBackend,GoeGaming/SteamDatabaseBackend,GoeGaming/SteamDatabaseBackend,SteamDatabase/SteamDatabaseBackend,thecocce/SteamDatabaseBackend,thecocce/SteamDatabaseBackend,SGColdSun/SteamDatabaseBackend | Managers/Watchdog.cs | Managers/Watchdog.cs | /*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.Threading;
namespace SteamDatabaseBackend
{
class Watchdog
{
public Watchdog()
{
new Timer(OnTimer, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(20));
}
private void OnTimer(object state)
{
if (Steam.Instance.Client.IsConnected && Application.ChangelistTimer.Enabled)
{
AccountInfo.Sync();
}
else if (DateTime.Now.Subtract(Connection.LastSuccessfulLogin).TotalMinutes >= 5.0)
{
Connection.Reconnect(null, null);
}
}
}
}
| /*
* Copyright (c) 2013-2015, SteamDB. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
using System;
using System.Threading;
namespace SteamDatabaseBackend
{
public class Watchdog
{
public Watchdog()
{
new Timer(OnTimer, null, TimeSpan.FromMinutes(5), TimeSpan.FromMinutes(20));
}
private void OnTimer(object state)
{
if (Steam.Instance.Client.IsConnected)
{
AccountInfo.Sync();
}
else if (DateTime.Now.Subtract(Connection.LastSuccessfulLogin).TotalMinutes >= 5.0)
{
Connection.Reconnect(null, null);
}
}
}
}
| bsd-3-clause | C# |
21e20056adf05009833d39631dcb72480fda96ae | Make Activity Serializable on NET 4.5 since it's stored in CallContext | YoupHulsebos/corefx,JosephTremoulet/corefx,alexperovich/corefx,rjxby/corefx,axelheer/corefx,seanshpark/corefx,wtgodbe/corefx,YoupHulsebos/corefx,Ermiar/corefx,JosephTremoulet/corefx,dhoehna/corefx,fgreinacher/corefx,stephenmichaelf/corefx,rubo/corefx,ravimeda/corefx,DnlHarvey/corefx,parjong/corefx,BrennanConroy/corefx,the-dwyer/corefx,rahku/corefx,MaggieTsang/corefx,rjxby/corefx,rahku/corefx,elijah6/corefx,rubo/corefx,alexperovich/corefx,tijoytom/corefx,gkhanna79/corefx,krk/corefx,cydhaselton/corefx,seanshpark/corefx,weltkante/corefx,DnlHarvey/corefx,zhenlan/corefx,parjong/corefx,gkhanna79/corefx,dhoehna/corefx,mazong1123/corefx,dhoehna/corefx,stephenmichaelf/corefx,axelheer/corefx,nbarbettini/corefx,twsouthwick/corefx,seanshpark/corefx,mazong1123/corefx,twsouthwick/corefx,mmitche/corefx,gkhanna79/corefx,nchikanov/corefx,dhoehna/corefx,stone-li/corefx,DnlHarvey/corefx,BrennanConroy/corefx,yizhang82/corefx,krk/corefx,tijoytom/corefx,ViktorHofer/corefx,BrennanConroy/corefx,weltkante/corefx,stephenmichaelf/corefx,dotnet-bot/corefx,mazong1123/corefx,stone-li/corefx,DnlHarvey/corefx,nbarbettini/corefx,tijoytom/corefx,wtgodbe/corefx,Jiayili1/corefx,dotnet-bot/corefx,billwert/corefx,the-dwyer/corefx,stone-li/corefx,dotnet-bot/corefx,Jiayili1/corefx,elijah6/corefx,rahku/corefx,jlin177/corefx,zhenlan/corefx,parjong/corefx,Petermarcu/corefx,mazong1123/corefx,yizhang82/corefx,MaggieTsang/corefx,MaggieTsang/corefx,ptoonen/corefx,ravimeda/corefx,mmitche/corefx,fgreinacher/corefx,wtgodbe/corefx,krytarowski/corefx,Ermiar/corefx,Ermiar/corefx,tijoytom/corefx,YoupHulsebos/corefx,nchikanov/corefx,krk/corefx,alexperovich/corefx,YoupHulsebos/corefx,zhenlan/corefx,zhenlan/corefx,JosephTremoulet/corefx,stone-li/corefx,cydhaselton/corefx,yizhang82/corefx,weltkante/corefx,parjong/corefx,krytarowski/corefx,richlander/corefx,yizhang82/corefx,weltkante/corefx,twsouthwick/corefx,shimingsg/corefx,nchikanov/corefx,ravimeda/corefx,Petermarcu/corefx,gkhanna79/corefx,dhoehna/corefx,seanshpark/corefx,stephenmichaelf/corefx,fgreinacher/corefx,shimingsg/corefx,shimingsg/corefx,JosephTremoulet/corefx,twsouthwick/corefx,alexperovich/corefx,Jiayili1/corefx,ViktorHofer/corefx,the-dwyer/corefx,fgreinacher/corefx,stephenmichaelf/corefx,rjxby/corefx,seanshpark/corefx,YoupHulsebos/corefx,krk/corefx,rjxby/corefx,ViktorHofer/corefx,DnlHarvey/corefx,axelheer/corefx,cydhaselton/corefx,ravimeda/corefx,Petermarcu/corefx,gkhanna79/corefx,jlin177/corefx,billwert/corefx,cydhaselton/corefx,MaggieTsang/corefx,Jiayili1/corefx,nbarbettini/corefx,nbarbettini/corefx,tijoytom/corefx,seanshpark/corefx,mazong1123/corefx,Petermarcu/corefx,zhenlan/corefx,the-dwyer/corefx,richlander/corefx,nbarbettini/corefx,weltkante/corefx,elijah6/corefx,JosephTremoulet/corefx,axelheer/corefx,twsouthwick/corefx,mmitche/corefx,axelheer/corefx,billwert/corefx,richlander/corefx,stephenmichaelf/corefx,richlander/corefx,ptoonen/corefx,gkhanna79/corefx,MaggieTsang/corefx,Jiayili1/corefx,nchikanov/corefx,wtgodbe/corefx,mazong1123/corefx,rubo/corefx,shimingsg/corefx,Ermiar/corefx,rjxby/corefx,ericstj/corefx,DnlHarvey/corefx,JosephTremoulet/corefx,parjong/corefx,nbarbettini/corefx,billwert/corefx,seanshpark/corefx,twsouthwick/corefx,rubo/corefx,dhoehna/corefx,wtgodbe/corefx,MaggieTsang/corefx,gkhanna79/corefx,alexperovich/corefx,krk/corefx,krytarowski/corefx,ViktorHofer/corefx,ericstj/corefx,elijah6/corefx,richlander/corefx,axelheer/corefx,MaggieTsang/corefx,tijoytom/corefx,Jiayili1/corefx,ericstj/corefx,krk/corefx,rahku/corefx,stone-li/corefx,jlin177/corefx,ptoonen/corefx,krytarowski/corefx,richlander/corefx,stone-li/corefx,shimingsg/corefx,billwert/corefx,Petermarcu/corefx,yizhang82/corefx,dhoehna/corefx,nchikanov/corefx,Ermiar/corefx,krk/corefx,rjxby/corefx,alexperovich/corefx,dotnet-bot/corefx,twsouthwick/corefx,ptoonen/corefx,rahku/corefx,jlin177/corefx,mmitche/corefx,ptoonen/corefx,zhenlan/corefx,ravimeda/corefx,the-dwyer/corefx,yizhang82/corefx,ViktorHofer/corefx,billwert/corefx,wtgodbe/corefx,Jiayili1/corefx,parjong/corefx,krytarowski/corefx,ptoonen/corefx,mazong1123/corefx,the-dwyer/corefx,YoupHulsebos/corefx,zhenlan/corefx,DnlHarvey/corefx,rubo/corefx,elijah6/corefx,rahku/corefx,elijah6/corefx,wtgodbe/corefx,stone-li/corefx,ericstj/corefx,nchikanov/corefx,jlin177/corefx,mmitche/corefx,cydhaselton/corefx,rjxby/corefx,tijoytom/corefx,ViktorHofer/corefx,elijah6/corefx,shimingsg/corefx,jlin177/corefx,alexperovich/corefx,krytarowski/corefx,cydhaselton/corefx,dotnet-bot/corefx,dotnet-bot/corefx,jlin177/corefx,parjong/corefx,yizhang82/corefx,Petermarcu/corefx,nchikanov/corefx,Petermarcu/corefx,the-dwyer/corefx,ViktorHofer/corefx,Ermiar/corefx,ericstj/corefx,weltkante/corefx,rahku/corefx,stephenmichaelf/corefx,krytarowski/corefx,ptoonen/corefx,weltkante/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,ericstj/corefx,ericstj/corefx,ravimeda/corefx,billwert/corefx,mmitche/corefx,shimingsg/corefx,richlander/corefx,Ermiar/corefx,mmitche/corefx,cydhaselton/corefx,YoupHulsebos/corefx,nbarbettini/corefx,ravimeda/corefx | src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs | src/System.Diagnostics.DiagnosticSource/src/System/Diagnostics/Activity.Current.net45.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Threading;
namespace System.Diagnostics
{
[Serializable]
public partial class Activity
{
/// <summary>
/// Returns the current operation (Activity) for the current thread. This flows
/// across async calls.
/// </summary>
public static Activity Current
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
return (Activity)CallContext.LogicalGetData(FieldKey);
}
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
private set
{
CallContext.LogicalSetData(FieldKey, value);
}
}
#region private
private static readonly string FieldKey = $"{typeof(Activity).FullName}.Value.{AppDomain.CurrentDomain.Id}";
#endregion
}
} | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Runtime.Remoting.Messaging;
using System.Security;
using System.Threading;
namespace System.Diagnostics
{
public partial class Activity
{
/// <summary>
/// Returns the current operation (Activity) for the current thread. This flows
/// across async calls.
/// </summary>
public static Activity Current
{
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
get
{
return (Activity)CallContext.LogicalGetData(FieldKey);
}
#if ALLOW_PARTIALLY_TRUSTED_CALLERS
[System.Security.SecuritySafeCriticalAttribute]
#endif
private set
{
CallContext.LogicalSetData(FieldKey, value);
}
}
#region private
private static readonly string FieldKey = $"{typeof(Activity).FullName}.Value.{AppDomain.CurrentDomain.Id}";
#endregion
}
} | mit | C# |
6eec78211044fa0ec5047304bebd8fca24ab133c | Add basic Dispatcher class | Vtek/Bartender | src/Bartender/Dispatcher.cs | src/Bartender/Dispatcher.cs | namespace Bartender
{
/// <summary>
/// Dispatcher.
/// </summary>
public class Dispatcher
{
/// <summary>
/// Dependency container.
/// </summary>
private IDependencyContainer Container { get; }
/// <summary>
/// Initializes a new instance of the Dispatcher class.
/// </summary>
/// <param name="container">Dependency container.</param>
public Dispatcher(IDependencyContainer container)
{
Container = container;
}
}
} | mit | C# | |
49abe00fb7e9e35bf775e0b5c0d98f8e6676acf1 | Add credentials template to fix ci build errors | InfiniteSoul/Azuria | Azuria.Test/Credentials.cs | Azuria.Test/Credentials.cs | namespace Azuria.Test
{
internal static class Credentials
{
public const string ApiKey = "";
public const string Password = "";
public const string Username = "";
}
} | mit | C# | |
3cd6dcaed2e8a77e7ba372c7f8dc0d0509ae2268 | add ParseException | rit-sse-mycroft/core | Mycroft.Messages/ParseException.cs | Mycroft.Messages/ParseException.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mycroft.Messages
{
public class ParseException : Exception
{
public string Received { get; private set; }
public string Message { get; private set; }
public void ParseException(string received, string message)
{
Received = received;
Message = message;
}
/// <summary>
/// Serialize this to exception to json as defined in Mycroft.Msg.MsgGeneralFailure.Serialize
/// </summary>
/// <returns>The JSON</returns>
public string Serialize()
{
var msgFail = new Msg.MsgGeneralFailure();
msgFail.Message = Message;
msgFail.Received = Received;
return msgFail.Serialize();
}
}
}
| bsd-3-clause | C# | |
77c293e067a8b2263a51a541c7744a584746d60e | Comment code. | tannergooding/roslyn,robinsedlaczek/roslyn,davkean/roslyn,brettfo/roslyn,stephentoub/roslyn,jkotas/roslyn,genlu/roslyn,sharadagrawal/Roslyn,yeaicc/roslyn,wvdd007/roslyn,aelij/roslyn,AlekseyTs/roslyn,AArnott/roslyn,jamesqo/roslyn,KiloBravoLima/roslyn,MattWindsor91/roslyn,ericfe-ms/roslyn,ErikSchierboom/roslyn,mattwar/roslyn,amcasey/roslyn,pdelvo/roslyn,diryboy/roslyn,amcasey/roslyn,abock/roslyn,bbarry/roslyn,stephentoub/roslyn,jhendrixMSFT/roslyn,dpoeschl/roslyn,ljw1004/roslyn,Pvlerick/roslyn,AmadeusW/roslyn,sharwell/roslyn,paulvanbrenk/roslyn,Giftednewt/roslyn,akrisiun/roslyn,weltkante/roslyn,tvand7093/roslyn,wvdd007/roslyn,panopticoncentral/roslyn,cston/roslyn,Shiney/roslyn,physhi/roslyn,akrisiun/roslyn,drognanar/roslyn,reaction1989/roslyn,KevinRansom/roslyn,heejaechang/roslyn,natidea/roslyn,VSadov/roslyn,leppie/roslyn,ErikSchierboom/roslyn,leppie/roslyn,paulvanbrenk/roslyn,rgani/roslyn,bartdesmet/roslyn,aelij/roslyn,natidea/roslyn,zooba/roslyn,jamesqo/roslyn,bkoelman/roslyn,sharwell/roslyn,Shiney/roslyn,abock/roslyn,balajikris/roslyn,gafter/roslyn,srivatsn/roslyn,CaptainHayashi/roslyn,robinsedlaczek/roslyn,heejaechang/roslyn,VSadov/roslyn,AArnott/roslyn,jcouv/roslyn,tmat/roslyn,jmarolf/roslyn,dotnet/roslyn,OmarTawfik/roslyn,KiloBravoLima/roslyn,xasx/roslyn,KevinH-MS/roslyn,mavasani/roslyn,khyperia/roslyn,weltkante/roslyn,michalhosala/roslyn,davkean/roslyn,Pvlerick/roslyn,KirillOsenkov/roslyn,natidea/roslyn,nguerrera/roslyn,xoofx/roslyn,a-ctor/roslyn,yeaicc/roslyn,lorcanmooney/roslyn,jasonmalinowski/roslyn,AArnott/roslyn,eriawan/roslyn,robinsedlaczek/roslyn,cston/roslyn,jmarolf/roslyn,Giftednewt/roslyn,tmat/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,mattscheffer/roslyn,sharadagrawal/Roslyn,bartdesmet/roslyn,xasx/roslyn,rgani/roslyn,kelltrick/roslyn,AlekseyTs/roslyn,zooba/roslyn,paulvanbrenk/roslyn,TyOverby/roslyn,TyOverby/roslyn,Hosch250/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,DustinCampbell/roslyn,agocke/roslyn,diryboy/roslyn,Giftednewt/roslyn,KiloBravoLima/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,kelltrick/roslyn,KirillOsenkov/roslyn,mavasani/roslyn,MichalStrehovsky/roslyn,agocke/roslyn,Pvlerick/roslyn,abock/roslyn,davkean/roslyn,michalhosala/roslyn,mattwar/roslyn,KirillOsenkov/roslyn,MichalStrehovsky/roslyn,akrisiun/roslyn,mattwar/roslyn,ericfe-ms/roslyn,zooba/roslyn,orthoxerox/roslyn,weltkante/roslyn,swaroop-sridhar/roslyn,a-ctor/roslyn,genlu/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jasonmalinowski/roslyn,Shiney/roslyn,balajikris/roslyn,yeaicc/roslyn,jkotas/roslyn,budcribar/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,ljw1004/roslyn,bbarry/roslyn,dotnet/roslyn,orthoxerox/roslyn,jeffanders/roslyn,budcribar/roslyn,xasx/roslyn,bkoelman/roslyn,khyperia/roslyn,srivatsn/roslyn,jeffanders/roslyn,AlekseyTs/roslyn,orthoxerox/roslyn,reaction1989/roslyn,jkotas/roslyn,lorcanmooney/roslyn,TyOverby/roslyn,eriawan/roslyn,khyperia/roslyn,kelltrick/roslyn,jhendrixMSFT/roslyn,drognanar/roslyn,OmarTawfik/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,ericfe-ms/roslyn,swaroop-sridhar/roslyn,heejaechang/roslyn,sharadagrawal/Roslyn,MatthieuMEZIL/roslyn,mmitche/roslyn,bkoelman/roslyn,michalhosala/roslyn,vslsnap/roslyn,nguerrera/roslyn,MattWindsor91/roslyn,KevinRansom/roslyn,tmat/roslyn,jaredpar/roslyn,jcouv/roslyn,mattscheffer/roslyn,ErikSchierboom/roslyn,OmarTawfik/roslyn,mmitche/roslyn,bbarry/roslyn,tannergooding/roslyn,tmeschter/roslyn,jmarolf/roslyn,CaptainHayashi/roslyn,dpoeschl/roslyn,panopticoncentral/roslyn,AmadeusW/roslyn,pdelvo/roslyn,panopticoncentral/roslyn,Hosch250/roslyn,KevinH-MS/roslyn,mgoertz-msft/roslyn,eriawan/roslyn,AnthonyDGreen/roslyn,swaroop-sridhar/roslyn,Hosch250/roslyn,dpoeschl/roslyn,leppie/roslyn,MattWindsor91/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,xoofx/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,budcribar/roslyn,jaredpar/roslyn,jeffanders/roslyn,tvand7093/roslyn,CaptainHayashi/roslyn,drognanar/roslyn,agocke/roslyn,pdelvo/roslyn,MatthieuMEZIL/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,amcasey/roslyn,MichalStrehovsky/roslyn,wvdd007/roslyn,cston/roslyn,KevinRansom/roslyn,tmeschter/roslyn,nguerrera/roslyn,a-ctor/roslyn,jamesqo/roslyn,vslsnap/roslyn,xoofx/roslyn,MatthieuMEZIL/roslyn,DustinCampbell/roslyn,brettfo/roslyn,stephentoub/roslyn,srivatsn/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,physhi/roslyn,balajikris/roslyn,tvand7093/roslyn,vslsnap/roslyn,physhi/roslyn,AnthonyDGreen/roslyn,jcouv/roslyn,CyrusNajmabadi/roslyn,jaredpar/roslyn,rgani/roslyn,DustinCampbell/roslyn,AnthonyDGreen/roslyn,bartdesmet/roslyn,gafter/roslyn,genlu/roslyn,ljw1004/roslyn,lorcanmooney/roslyn,VSadov/roslyn,brettfo/roslyn,reaction1989/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jhendrixMSFT/roslyn,mmitche/roslyn,aelij/roslyn,gafter/roslyn,KevinH-MS/roslyn | src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/IDeclarationInfo.cs | src/Workspaces/Core/Portable/FindSymbols/SyntaxTree/IDeclarationInfo.cs | using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.FindSymbols
{
/// <summary>
/// Information about all the declarations defined within a document. Each declaration in the
/// document get a single item in <see cref="IDeclarationInfo.DeclaredSymbolInfos"/>.
/// </summary>
internal interface IDeclarationInfo
{
IReadOnlyList<DeclaredSymbolInfo> DeclaredSymbolInfos { get; }
}
} | using System.Collections.Generic;
namespace Microsoft.CodeAnalysis.FindSymbols
{
internal interface IDeclarationInfo
{
IReadOnlyList<DeclaredSymbolInfo> DeclaredSymbolInfos { get; }
}
} | apache-2.0 | C# |
7d8cec63e7f5ea08c1a1c2cc3caa508e0c012ca7 | Revert "try threaded" | Fody/EmptyConstructor | Tests/TestConfig.cs | Tests/TestConfig.cs | using Xunit;
[assembly: CollectionBehavior(CollectionBehavior.CollectionPerAssembly, DisableTestParallelization = true)] | mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.