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 |
|---|---|---|---|---|---|---|---|---|
56f4ed46274e59205c4ab156a3336593f6083774 | Remove dependency to render the fixed path | BlythMeister/Ensconce,BlythMeister/Ensconce,15below/Ensconce,15below/Ensconce | src/Ensconce/TextRendering.cs | src/Ensconce/TextRendering.cs | using System;
using System.Collections.Generic;
using System.IO;
using FifteenBelow.Deployment.Update;
namespace Ensconce
{
internal static class TextRendering
{
private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(() => Retry.Do(BuildTagDictionary, TimeSpan.FromSeconds(5)));
public static IDictionary<string, object> TagDictionary => LazyTags.Value;
internal static string Render(this string s)
{
return s.RenderTemplate(TagDictionary);
}
private static TagDictionary BuildTagDictionary()
{
var instanceName = Environment.GetEnvironmentVariable("InstanceName");
var fixedPath = Arguments.FixedPath;
//If file doesn't exist, try rendering the path as a template string
if (!File.Exists(fixedPath))
{
//Create a tag dictionary from environments to render
var tags = BuildTagDictionary(instanceName);
fixedPath = fixedPath.RenderTemplate(tags);
//build from that path, giving environment dictonary as a fallback
return BuildTagDictionary(instanceName, fixedPath, tags);
}
//Build using fixed path, do not provide a fall back
return BuildTagDictionary(instanceName, fixedPath, null);
}
private static TagDictionary BuildTagDictionary(string instanceName)
{
Logging.Log("Building Tag Dictionary {0}", instanceName);
var tags = new TagDictionary(instanceName);
Logging.Log("Built Tag Dictionary {0}", instanceName);
return tags;
}
private static TagDictionary BuildTagDictionary(string instanceName, string fixedPath, TagDictionary fallbackDictionary)
{
TagDictionary tags;
if (File.Exists(fixedPath))
{
Logging.Log("Loading xml config from file {0}", Path.GetFullPath(fixedPath));
var configXml = Retry.Do(() => File.ReadAllText(fixedPath), TimeSpan.FromSeconds(5));
Logging.Log("Re-Building Tag Dictionary (Using Config File)");
tags = new TagDictionary(instanceName, configXml);
Logging.Log("Built Tag Dictionary (Using Config File)");
}
else
{
Logging.Log("No structure file found at: {0}", Path.GetFullPath(fixedPath));
tags = fallbackDictionary ?? BuildTagDictionary();
}
return tags;
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using FifteenBelow.Deployment.Update;
namespace Ensconce
{
internal static class TextRendering
{
private static readonly Lazy<TagDictionary> LazyTags = new Lazy<TagDictionary>(() => Retry.Do(BuildTagDictionary, TimeSpan.FromSeconds(5)));
public static IDictionary<string, object> TagDictionary { get { return LazyTags.Value; } }
internal static string Render(this string s)
{
return s.RenderTemplate(TagDictionary);
}
private static TagDictionary BuildTagDictionary()
{
var instanceName = Environment.GetEnvironmentVariable("InstanceName");
Logging.Log("Building Tag Dictionary {0}", instanceName);
var tags = new TagDictionary(instanceName);
Logging.Log("Built Tag Dictionary {0}", instanceName);
var renderedFixedPath = Arguments.FixedPath.RenderTemplate(tags);
if (File.Exists(renderedFixedPath))
{
Logging.Log("Loading xml config from file {0}", Path.GetFullPath(renderedFixedPath));
var configXml = Retry.Do(() => File.ReadAllText(renderedFixedPath), TimeSpan.FromSeconds(5));
Logging.Log("Re-Building Tag Dictionary (Using Config File)");
tags = new TagDictionary(instanceName, configXml);
Logging.Log("Built Tag Dictionary (Using Config File)");
}
else
{
Logging.Log("No structure file found at: {0}", Path.GetFullPath(renderedFixedPath));
}
return tags;
}
}
}
| mit | C# |
429de3f1d757510ca738382b2b4ac172f26d8f55 | Add docs. | jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos | src/Manos/Manos/IManosPipe.cs | src/Manos/Manos/IManosPipe.cs | //
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using Manos.Http;
using Manos.Routing;
namespace Manos
{
/// <summary>
/// ManosPipe provides a mechanism to intercept calls before or after the standard Manos Routing has taking place.
/// (For example, Gzip compression module could compress content post process)
/// </summary>
/// <remarks>
/// This is similar in concept to the HttpModule in the ASP.Net stack.</remarks>
public interface IManosPipe
{
/// <summarY>
/// Called as a request is coming in, before any actions at all have been taken on the
/// request. There is not a valid Response object on the transaction yet and the
/// routing information has not been looked up.
/// </summary>
void OnPreProcessRequest (ManosApp app, IHttpTransaction transaction, Action complete);
/// <summary>
/// Called after the response object has been created but before any routing has been done
/// if you would like to override the default routing you can do it here, by changing the
/// IManosTarget returned in the complete Action.
/// </summary>
void OnPreProcessTarget (IManosContext ctx, Action<IManosTarget> complete);
/// <summary>
/// The default routing information has been looked up, but the actual action execution
/// has not occurred yet.
/// </summary>
void OnPostProcessTarget (IManosContext ctx, IManosTarget target, Action complete);
/// <summary>
/// The action has been invoked and has had its End method called. This is the final
/// step in the pipeline.
/// </summary>
void OnPostProcessRequest (ManosApp app, IHttpTransaction transaction, Action complete);
/// <summary>
/// An error has been raised by Manos. (Currently unimplemented).
/// </summary>
void OnError (IManosContext ctx, Action complete);
}
}
| //
// Copyright (C) 2010 Jackson Harper (jackson@manosdemono.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//
using System;
using Manos.Http;
using Manos.Routing;
namespace Manos
{
/// <summary>
/// ManosPipe provides a mechanism to intercept calls before or after the standard Manos Routing has taking place.
/// (For example, Gzip compression module could compress content post process)
/// </summary>
/// <remarks>
/// This is similar in concept to the HttpModule in the ASP.Net stack.</remarks>
public interface IManosPipe
{
void OnPreProcessRequest (ManosApp app, IHttpTransaction transaction, Action complete);
void OnPreProcessTarget (IManosContext ctx, Action<IManosTarget> complete);
void OnPostProcessTarget (IManosContext ctx, IManosTarget target, Action complete);
void OnPostProcessRequest (ManosApp app, IHttpTransaction transaction, Action complete);
void OnError (IManosContext ctx, Action complete);
}
}
| mit | C# |
b76e5757e17100c171df813235dc43d104e52c04 | Fix `InSelectedCollection` not being applied to newly imported beatmaps | ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,peppy/osu | osu.Game/Overlays/Music/Playlist.cs | osu.Game/Overlays/Music/Playlist.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.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Overlays.Music
{
public class Playlist : OsuRearrangeableListContainer<Live<BeatmapSetInfo>>
{
public Action<Live<BeatmapSetInfo>>? RequestSelection;
public readonly Bindable<Live<BeatmapSetInfo>> SelectedSet = new Bindable<Live<BeatmapSetInfo>>();
private FilterCriteria currentCriteria = new FilterCriteria();
public new MarginPadding Padding
{
get => base.Padding;
set => base.Padding = value;
}
public void Filter(FilterCriteria criteria)
{
var items = (SearchContainer<RearrangeableListItem<Live<BeatmapSetInfo>>>)ListContainer;
string[]? currentCollectionHashes = criteria.Collection?.PerformRead(c => c.BeatmapMD5Hashes.ToArray());
foreach (var item in items.OfType<PlaylistItem>())
{
item.InSelectedCollection = currentCollectionHashes == null || item.Model.Value.Beatmaps.Select(b => b.MD5Hash).Any(currentCollectionHashes.Contains);
}
items.SearchTerm = criteria.SearchText;
currentCriteria = criteria;
}
public Live<BeatmapSetInfo>? FirstVisibleSet => Items.FirstOrDefault(i => ((PlaylistItem)ItemMap[i]).MatchingFilter);
protected override OsuRearrangeableListItem<Live<BeatmapSetInfo>> CreateOsuDrawable(Live<BeatmapSetInfo> item) => new PlaylistItem(item)
{
InSelectedCollection = currentCriteria.Collection?.PerformRead(c => item.Value.Beatmaps.Select(b => b.MD5Hash).Any(c.BeatmapMD5Hashes.Contains)) != false,
SelectedSet = { BindTarget = SelectedSet },
RequestSelection = set => RequestSelection?.Invoke(set)
};
protected override FillFlowContainer<RearrangeableListItem<Live<BeatmapSetInfo>>> CreateListFillFlowContainer() => new SearchContainer<RearrangeableListItem<Live<BeatmapSetInfo>>>
{
Spacing = new Vector2(0, 3),
LayoutDuration = 200,
LayoutEasing = Easing.OutQuint,
};
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
#nullable disable
using System;
using System.Linq;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Beatmaps;
using osu.Game.Database;
using osu.Game.Graphics.Containers;
using osuTK;
namespace osu.Game.Overlays.Music
{
public class Playlist : OsuRearrangeableListContainer<Live<BeatmapSetInfo>>
{
public Action<Live<BeatmapSetInfo>> RequestSelection;
public readonly Bindable<Live<BeatmapSetInfo>> SelectedSet = new Bindable<Live<BeatmapSetInfo>>();
public new MarginPadding Padding
{
get => base.Padding;
set => base.Padding = value;
}
public void Filter(FilterCriteria criteria)
{
var items = (SearchContainer<RearrangeableListItem<Live<BeatmapSetInfo>>>)ListContainer;
string[] currentCollectionHashes = criteria.Collection?.PerformRead(c => c.BeatmapMD5Hashes.ToArray());
foreach (var item in items.OfType<PlaylistItem>())
{
if (currentCollectionHashes == null)
item.InSelectedCollection = true;
else
{
item.InSelectedCollection = item.Model.Value.Beatmaps.Select(b => b.MD5Hash)
.Any(currentCollectionHashes.Contains);
}
}
items.SearchTerm = criteria.SearchText;
}
public Live<BeatmapSetInfo> FirstVisibleSet => Items.FirstOrDefault(i => ((PlaylistItem)ItemMap[i]).MatchingFilter);
protected override OsuRearrangeableListItem<Live<BeatmapSetInfo>> CreateOsuDrawable(Live<BeatmapSetInfo> item) => new PlaylistItem(item)
{
SelectedSet = { BindTarget = SelectedSet },
RequestSelection = set => RequestSelection?.Invoke(set)
};
protected override FillFlowContainer<RearrangeableListItem<Live<BeatmapSetInfo>>> CreateListFillFlowContainer() => new SearchContainer<RearrangeableListItem<Live<BeatmapSetInfo>>>
{
Spacing = new Vector2(0, 3),
LayoutDuration = 200,
LayoutEasing = Easing.OutQuint,
};
}
}
| mit | C# |
824699d0dfa124bad457b3389e28f823c465ce4d | Update StaticCoroutine.cs | proyecto26/RestClient | src/Proyecto26.RestClient/Utils/StaticCoroutine.cs | src/Proyecto26.RestClient/Utils/StaticCoroutine.cs | using UnityEngine;
using System.Collections;
namespace Proyecto26
{
public static class StaticCoroutine
{
private class CoroutineHolder : MonoBehaviour { }
private static CoroutineHolder _runner;
private static CoroutineHolder runner
{
get
{
if (_runner == null)
{
_runner = new GameObject("Static Coroutine RestClient").AddComponent<CoroutineHolder>();
Object.DontDestroyOnLoad(_runner);
}
return _runner;
}
}
public static void StartCoroutine(IEnumerator coroutine)
{
runner.StartCoroutine(coroutine);
}
}
}
| using UnityEngine;
using System.Collections;
namespace Proyecto26
{
public static class StaticCoroutine
{
private class CoroutineHolder : MonoBehaviour { }
private static CoroutineHolder _runner;
private static CoroutineHolder runner
{
get
{
if (_runner == null)
{
_runner = new GameObject("Static Corotuine RestClient").AddComponent<CoroutineHolder>();
Object.DontDestroyOnLoad(_runner);
}
return _runner;
}
}
public static void StartCoroutine(IEnumerator corotuine)
{
runner.StartCoroutine(corotuine);
}
}
}
| mit | C# |
bdc46b2c370cc823c218c1ac7d35aa5d703dfa09 | Revert "unit test bug fix" | OBeautifulCode/OBeautifulCode.Serialization | OBeautifulCode.Serialization.Test/SerializationDummyFactory.cs | OBeautifulCode.Serialization.Test/SerializationDummyFactory.cs | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializationDummyFactory.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
// Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Serialization.Test source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.Serialization.Test
{
using OBeautifulCode.AutoFakeItEasy;
using OBeautifulCode.Serialization;
/// <summary>
/// A Dummy Factory for types in <see cref="OBeautifulCode.Serialization"/>.
/// </summary>
#if !OBeautifulCodeSerializationSolution
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Test", "See package version number")]
internal
#else
public
#endif
class SerializationDummyFactory : DefaultSerializationDummyFactory
{
public SerializationDummyFactory()
{
AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationKind.Invalid, SerializationKind.Proprietary);
AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationFormat.Invalid, SerializationFormat.Null);
#if OBeautifulCodeSerializationSolution
AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<KeyOrValueObjectHierarchyBase>();
AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<TestBase>();
#endif
}
}
} | // --------------------------------------------------------------------------------------------------------------------
// <copyright file="SerializationDummyFactory.cs" company="OBeautifulCode">
// Copyright (c) OBeautifulCode 2018. All rights reserved.
// </copyright>
// <auto-generated>
// Sourced from NuGet package. Will be overwritten with package update except in OBeautifulCode.Serialization.Test source.
// </auto-generated>
// --------------------------------------------------------------------------------------------------------------------
namespace OBeautifulCode.Serialization.Test
{
using FakeItEasy;
using OBeautifulCode.AutoFakeItEasy;
using OBeautifulCode.Serialization;
/// <summary>
/// A Dummy Factory for types in <see cref="OBeautifulCode.Serialization"/>.
/// </summary>
#if !OBeautifulCodeSerializationSolution
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
[System.CodeDom.Compiler.GeneratedCode("OBeautifulCode.Serialization.Test", "See package version number")]
internal
#else
public
#endif
class SerializationDummyFactory : DefaultSerializationDummyFactory
{
public SerializationDummyFactory()
{
AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationKind.Invalid, SerializationKind.Proprietary);
AutoFixtureBackedDummyFactory.ConstrainDummyToExclude(SerializationFormat.Invalid, SerializationFormat.Null);
#if OBeautifulCodeSerializationSolution
AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<KeyOrValueObjectHierarchyBase>();
AutoFixtureBackedDummyFactory.UseRandomConcreteSubclassForDummy<TestBase>();
#endif
AutoFixtureBackedDummyFactory.AddDummyCreator(()=> new TestEvent1(A.Dummy<short>(), A.Dummy<UtcDateTime>()));
AutoFixtureBackedDummyFactory.AddDummyCreator(()=> new TestEvent2(A.Dummy<short>(), A.Dummy<UtcDateTime>()));
}
}
} | mit | C# |
1217a44bc3c477d96657e6a6850c5c1833ad106a | use StringTokenizer to parse PointsList | SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,akrisiun/Perspex,grokys/Perspex,grokys/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia | src/Markup/Avalonia.Markup.Xaml/Converters/PointsListTypeConverter.cs | src/Markup/Avalonia.Markup.Xaml/Converters/PointsListTypeConverter.cs | using System;
using System.Collections.Generic;
using System.Globalization;
namespace Avalonia.Markup.Xaml.Converters
{
using System.ComponentModel;
using Avalonia.Utilities;
public class PointsListTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
var points = new List<Point>();
using (var tokenizer = new StringTokenizer((string)value, CultureInfo.InvariantCulture, exceptionMessage: "Invalid PointsList."))
{
while (tokenizer.TryReadDouble(out double x))
{
points.Add(new Point(x, tokenizer.ReadDouble()));
}
}
return points;
}
}
}
| using System;
using System.Collections.Generic;
using System.Globalization;
namespace Avalonia.Markup.Xaml.Converters
{
using System.ComponentModel;
public class PointsListTypeConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
string strValue = (string)value;
string[] pointStrs = strValue.Split(new[] { ' ', '\t', '\r', '\n', ',' }, StringSplitOptions.RemoveEmptyEntries);
var result = new List<Point>(pointStrs.Length / 2);
for (int i = 0; i < pointStrs.Length; i += 2)
{
result.Add(Point.Parse($"{pointStrs[i]} {pointStrs[i + 1]}"));
}
return result;
}
}
}
| mit | C# |
596c59b42ad5a1f9ff60d776310921a6f490e8d4 | Fix TitlePart hints and improve wording. (#7610) | stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2 | src/OrchardCore.Modules/OrchardCore.Title/Views/TitlePart.Edit.cshtml | src/OrchardCore.Modules/OrchardCore.Title/Views/TitlePart.Edit.cshtml | @model TitlePartViewModel
@using OrchardCore.ContentLocalization
@using OrchardCore.Localization
@using OrchardCore.Title.Models
@using OrchardCore.Title.ViewModels;
@{
var culture = await Orchard.GetContentCultureAsync(Model.TitlePart.ContentItem);
}
@if (Model.Settings?.Options != TitlePartOptions.GeneratedHidden)
{
<div class="form-group" asp-validation-class-for="Title">
<label asp-for="Title">@T["Title"]</label>
<input asp-for="Title" class="form-control content-preview-text content-caption-text" disabled="@(Model.Settings?.Options == TitlePartOptions.GeneratedDisabled)" autofocus="autofocus" dir="@culture.GetLanguageDirection()" />
<span asp-validation-for="Title"></span>
@if (!String.IsNullOrWhiteSpace(Model.Settings?.Pattern))
{
switch (Model.Settings?.Options)
{
case TitlePartOptions.Editable:
<span class="hint">@T["Leave empty to auto-generate the title using the pattern."]</span>
break;
case TitlePartOptions.GeneratedDisabled:
<span class="hint">@T["The title will be auto-generated using the pattern."]</span>
break;
}
}
</div>
}
| @model TitlePartViewModel
@using OrchardCore.ContentLocalization
@using OrchardCore.Localization
@using OrchardCore.Title.Models
@using OrchardCore.Title.ViewModels;
@{
var culture = await Orchard.GetContentCultureAsync(Model.TitlePart.ContentItem);
}
@if (Model.Settings?.Options != TitlePartOptions.GeneratedHidden)
{
<div class="form-group" asp-validation-class-for="Title">
<label asp-for="Title">@T["Title"]</label>
<input asp-for="Title" class="form-control content-preview-text content-caption-text" disabled="@(Model.Settings?.Options == TitlePartOptions.GeneratedDisabled)" autofocus="autofocus" dir="@culture.GetLanguageDirection()" />
<span asp-validation-for="Title"></span>
@if (String.IsNullOrWhiteSpace(Model.Settings?.Pattern) && Model.Settings?.Options == TitlePartOptions.Editable)
{
<span class="hint">@T["The title of the content item. Set empty to generate it using the pattern."]</span>
}
else
{
<span class="hint">@T["The title of the content item. It will be automatically generated."]</span>
}
</div>
}
| bsd-3-clause | C# |
646ddb2134f118877e486c523cf6fd76b55f0fe2 | Remove method that has moved to AppConfig. | mysql-net/MySqlConnector,mysql-net/MySqlConnector | tests/SideBySide/TestUtilities.cs | tests/SideBySide/TestUtilities.cs | using System.Diagnostics;
using Xunit;
namespace SideBySide
{
public class TestUtilities
{
/// <summary>
/// Asserts that two byte arrays are equal. This method is much faster than xUnit's <code>Assert.Equal</code>.
/// </summary>
/// <param name="expected">The expected byte array.</param>
/// <param name="actual">The actual byte array.</param>
public static void AssertEqual(byte[] expected, byte[] actual)
{
Assert.Equal(expected.Length, actual.Length);
for (var i = 0; i < expected.Length; i++)
{
if (expected[i] != actual[i])
Assert.Equal(expected[i], actual[i]);
}
}
/// <summary>
/// Asserts that <paramref name="stopwatch"/> is in the range [minimumMilliseconds, minimumMilliseconds + lengthMilliseconds].
/// </summary>
/// <remarks>This method applies a scaling factor for delays encountered under Continuous Integration environments.</remarks>
public static void AssertDuration(Stopwatch stopwatch, int minimumMilliseconds, int lengthMilliseconds)
{
var elapsed = stopwatch.ElapsedMilliseconds;
Assert.InRange(elapsed, minimumMilliseconds, minimumMilliseconds + lengthMilliseconds * AppConfig.TimeoutDelayFactor);
}
}
}
| using System;
using System.Diagnostics;
using System.Globalization;
using Xunit;
namespace SideBySide
{
public class TestUtilities
{
/// <summary>
/// Asserts that two byte arrays are equal. This method is much faster than xUnit's <code>Assert.Equal</code>.
/// </summary>
/// <param name="expected">The expected byte array.</param>
/// <param name="actual">The actual byte array.</param>
public static void AssertEqual(byte[] expected, byte[] actual)
{
Assert.Equal(expected.Length, actual.Length);
for (var i = 0; i < expected.Length; i++)
{
if (expected[i] != actual[i])
Assert.Equal(expected[i], actual[i]);
}
}
/// <summary>
/// Asserts that <paramref name="stopwatch"/> is in the range [minimumMilliseconds, minimumMilliseconds + lengthMilliseconds].
/// </summary>
/// <remarks>This method applies a scaling factor for delays encountered under Continuous Integration environments.</remarks>
public static void AssertDuration(Stopwatch stopwatch, int minimumMilliseconds, int lengthMilliseconds)
{
var elapsed = stopwatch.ElapsedMilliseconds;
Assert.InRange(elapsed, minimumMilliseconds, minimumMilliseconds + lengthMilliseconds * AppConfig.TimeoutDelayFactor);
}
public static Version ParseServerVersion(string serverVersion)
{
// copied from MySql.Data.MySqlClient.ServerVersion
var last = 0;
var index = serverVersion.IndexOf('.', last);
var major = int.Parse(serverVersion.Substring(last, index - last), CultureInfo.InvariantCulture);
last = index + 1;
index = serverVersion.IndexOf('.', last);
var minor = int.Parse(serverVersion.Substring(last, index - last), CultureInfo.InvariantCulture);
last = index + 1;
do
{
index++;
} while (index < serverVersion.Length && serverVersion[index] >= '0' && serverVersion[index] <= '9');
var build = int.Parse(serverVersion.Substring(last, index - last), CultureInfo.InvariantCulture);
return new Version(major, minor, build);
}
public static bool SupportsJson(string serverVersion) =>
ParseServerVersion(serverVersion).CompareTo(new Version(5, 7)) >= 0;
}
}
| mit | C# |
cd087e86d4c62f10ca6375cf1a820ef7c80113ce | Add empty constructor for files that don't have a comment yet. | archrival/taglib-sharp,punker76/taglib-sharp,hwahrmann/taglib-sharp,Clancey/taglib-sharp,CamargoR/taglib-sharp,mono/taglib-sharp,punker76/taglib-sharp,Clancey/taglib-sharp,archrival/taglib-sharp,CamargoR/taglib-sharp,hwahrmann/taglib-sharp,Clancey/taglib-sharp | tests/fixtures/TagLib.Tests.Images/Validators/CommentModificationValidator.cs | tests/fixtures/TagLib.Tests.Images/Validators/CommentModificationValidator.cs | using System;
using NUnit.Framework;
namespace TagLib.Tests.Images.Validators
{
/// <summary>
/// This class tests the modification of the Comment field,
/// regardless of which metadata format is used.
/// </summary>
public class CommentModificationValidator : IMetadataModificationValidator
{
string orig_comment;
readonly string test_comment = "This is a TagLib# &Test?Comment%$@_ ";
public CommentModificationValidator () : this (String.Empty) { }
public CommentModificationValidator (string orig_comment)
{
this.orig_comment = orig_comment;
}
/// <summary>
/// Check if the original comment is found.
/// </summary>
public virtual void ValidatePreModification (Image.File file) {
Assert.AreEqual (orig_comment, GetTag (file).Comment);
}
/// <summary>
/// Changes the comment.
/// </summary>
public virtual void ModifyMetadata (Image.File file) {
GetTag (file).Comment = test_comment;
}
/// <summary>
/// Validates if changes survived a write.
/// </summary>
public void ValidatePostModification (Image.File file) {
Assert.AreEqual (test_comment, GetTag (file).Comment);
}
/// <summary>
/// Returns the tag that should be tested. Default
/// behavior is no specific tag.
/// </summary>
public virtual Image.ImageTag GetTag (Image.File file) {
return file.ImageTag;
}
}
}
| using NUnit.Framework;
namespace TagLib.Tests.Images.Validators
{
/// <summary>
/// This class tests the modification of the Comment field,
/// regardless of which metadata format is used.
/// </summary>
public class CommentModificationValidator : IMetadataModificationValidator
{
string orig_comment;
readonly string test_comment = "This is a TagLib# &Test?Comment%$@_ ";
public CommentModificationValidator (string orig_comment)
{
this.orig_comment = orig_comment;
}
/// <summary>
/// Check if the original comment is found.
/// </summary>
public virtual void ValidatePreModification (Image.File file) {
Assert.AreEqual (orig_comment, GetTag (file).Comment);
}
/// <summary>
/// Changes the comment.
/// </summary>
public virtual void ModifyMetadata (Image.File file) {
GetTag (file).Comment = test_comment;
}
/// <summary>
/// Validates if changes survived a write.
/// </summary>
public void ValidatePostModification (Image.File file) {
Assert.AreEqual (test_comment, GetTag (file).Comment);
}
/// <summary>
/// Returns the tag that should be tested. Default
/// behavior is no specific tag.
/// </summary>
public virtual Image.ImageTag GetTag (Image.File file) {
return file.ImageTag;
}
}
}
| lgpl-2.1 | C# |
6325b2d185e9e9b7ca0ad0950057d466dbfab18b | Update AssemblyInfo.cs | ogaudefroy/Microsoft.AnalysisServices.AdomdClient.Abstractions | Microsoft.AnalysisServices.AdomdClient.Abstractions/Properties/AssemblyInfo.cs | Microsoft.AnalysisServices.AdomdClient.Abstractions/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.AnalysisServices.AdomdClient.Abstractions")]
[assembly: AssemblyDescription("Set of abstraction classes for AdomdClient")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Olivier GAUDEFROY, Arnaud DUFRANNE")]
[assembly: AssemblyProduct("Microsoft.AnalysisServices.AdomdClient.Abstractions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: Guid("de4917a5-a3f4-4514-bacf-f5ddc96a1918")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.AnalysisServices.AdomdClient.Abstractions")]
[assembly: AssemblyDescription("Set of abstraction classes for AdomdClient")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Olivier GAUDEFROY, Arnaud DUFRANNE")]
[assembly: AssemblyProduct("Microsoft.AnalysisServices.AdomdClient.Abstractions")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("de4917a5-a3f4-4514-bacf-f5ddc96a1918")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
ba1884aacb313393ea6eb48c6700b2c4582da599 | Make wait service not timeout without yelling, and making the timeout longer | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/WebSites/RazorWebSite/Services/WaitService.cs | test/WebSites/RazorWebSite/Services/WaitService.cs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
namespace RazorWebSite
{
public class WaitService
{
private static readonly TimeSpan _waitTime = TimeSpan.FromSeconds(60);
private readonly ManualResetEventSlim _serverResetEvent = new ManualResetEventSlim();
private readonly ManualResetEventSlim _clientResetEvent = new ManualResetEventSlim();
public void NotifyClient()
{
_clientResetEvent.Set();
}
public void WaitForClient()
{
_clientResetEvent.Set();
if (!_serverResetEvent.Wait(_waitTime))
{
throw new InvalidOperationException("Timeout exceeded");
}
_serverResetEvent.Reset();
}
public void WaitForServer()
{
_serverResetEvent.Set();
if (!_clientResetEvent.Wait(_waitTime))
{
throw new InvalidOperationException("Timeout exceeded");
}
_clientResetEvent.Reset();
}
}
} | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Threading;
namespace RazorWebSite
{
public class WaitService
{
private static readonly TimeSpan _waitTime = TimeSpan.FromSeconds(10);
private readonly ManualResetEventSlim _serverResetEvent = new ManualResetEventSlim();
private readonly ManualResetEventSlim _clientResetEvent = new ManualResetEventSlim();
public void NotifyClient()
{
_clientResetEvent.Set();
}
public void WaitForClient()
{
_clientResetEvent.Set();
_serverResetEvent.Wait(_waitTime);
_serverResetEvent.Reset();
}
public void WaitForServer()
{
_serverResetEvent.Set();
_clientResetEvent.Wait(_waitTime);
_clientResetEvent.Reset();
}
}
} | apache-2.0 | C# |
a69ad2cb53b6c099e8baca375e76157a55417e2f | Fix sim.exe url | Brad-Christie/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager,dsolovay/Sitecore-Instance-Manager | src/SIM.Tool.Windows/MainWindowComponents/CommandLineButton.cs | src/SIM.Tool.Windows/MainWindowComponents/CommandLineButton.cs | namespace SIM.Tool.Windows.MainWindowComponents
{
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using SIM.Tool.Base;
using Sitecore.Diagnostics.Base.Annotations;
using SIM.Core.Common;
using SIM.Instances;
using SIM.Tool.Base.Plugins;
[UsedImplicitly]
public class CommandLineButton : AbstractDownloadAndRunButton, IMainWindowButton
{
protected override string BaseUrl
{
get
{
var qaFolder = ApplicationManager.IsQA
? "qa/"
: string.Empty;
return "http://dl.sitecore.net/updater/1.1/simcmd/" + qaFolder;
}
}
protected override string AppName
{
get
{
return "SIMCMD";
}
}
protected override string ExecutableName
{
get
{
return "sim.exe";
}
}
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
Analytics.TrackEvent("OpenCommandLine");
if (instance != null)
{
string dataFolderPath = instance.DataFolderPath;
FileSystem.FileSystem.Local.Directory.AssertExists(dataFolderPath, "The data folder ({0}) of the {1} instance doesn't exist".FormatWith(dataFolderPath, instance.Name));
var logs = Path.Combine(dataFolderPath, "logs");
RunApp(mainWindow, logs);
return;
}
RunApp(mainWindow);
}
#endregion
protected override void RunApp(string path, string param)
{
var start = new ProcessStartInfo("cmd.exe")
{
WorkingDirectory = AppFolder,
Arguments = "/K echo %cd%^>sim & sim", // exectute two commands: print fake cmd output C:\somefolder>sim (bacause it is absent), and then do run sim;
UseShellExecute = true
};
WindowHelper.RunApp(start);
}
}
}
| namespace SIM.Tool.Windows.MainWindowComponents
{
using System;
using System.Diagnostics;
using System.IO;
using System.Windows;
using SIM.Tool.Base;
using Sitecore.Diagnostics.Base.Annotations;
using SIM.Core.Common;
using SIM.Instances;
using SIM.Tool.Base.Plugins;
[UsedImplicitly]
public class CommandLineButton : AbstractDownloadAndRunButton, IMainWindowButton
{
protected override string BaseUrl
{
get
{
var qaFolder = ApplicationManager.IsQA
? "qa/"
: string.Empty;
return "http://dl.sitecore.net/updater/" + qaFolder + "simcmd";
}
}
protected override string AppName
{
get
{
return "SIMCMD";
}
}
protected override string ExecutableName
{
get
{
return "sim.exe";
}
}
#region Public methods
public bool IsEnabled(Window mainWindow, Instance instance)
{
return true;
}
public void OnClick(Window mainWindow, Instance instance)
{
Analytics.TrackEvent("OpenCommandLine");
if (instance != null)
{
string dataFolderPath = instance.DataFolderPath;
FileSystem.FileSystem.Local.Directory.AssertExists(dataFolderPath, "The data folder ({0}) of the {1} instance doesn't exist".FormatWith(dataFolderPath, instance.Name));
var logs = Path.Combine(dataFolderPath, "logs");
RunApp(mainWindow, logs);
return;
}
RunApp(mainWindow);
}
#endregion
protected override void RunApp(string path, string param)
{
var start = new ProcessStartInfo("cmd.exe")
{
WorkingDirectory = AppFolder,
Arguments = "/K echo %cd%^>sim & sim", // exectute two commands: print fake cmd output C:\somefolder>sim (bacause it is absent), and then do run sim;
UseShellExecute = true
};
WindowHelper.RunApp(start);
}
}
}
| mit | C# |
6814e5cce328866a3cb6e3ed427b2e37b1798c0a | Enable TLS 1.2 support | datalust/seq-forwarder | src/Seq.Forwarder/ServiceProcess/SeqForwarderWindowsService.cs | src/Seq.Forwarder/ServiceProcess/SeqForwarderWindowsService.cs | // Copyright 2016-2017 Datalust Pty Ltd
//
// 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;
using System.Net;
using System.ServiceProcess;
namespace Seq.Forwarder.ServiceProcess
{
class SeqForwarderWindowsService : ServiceBase
{
readonly ServerService _serverService;
readonly IDisposable _disposeOnStop;
public static string WindowsServiceName { get; } = "Seq Forwarder";
public SeqForwarderWindowsService(ServerService serverService, IDisposable disposeOnStop)
{
// Enable TLS 1.2 Support.
// .NET Framework 4.5.2 does not have it enabled by default
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
_serverService = serverService;
_disposeOnStop = disposeOnStop;
ServiceName = WindowsServiceName;
}
protected override void OnStart(string[] args)
{
_serverService.Start();
}
protected override void OnStop()
{
_serverService.Stop();
_disposeOnStop.Dispose();
}
}
} | // Copyright 2016-2017 Datalust Pty Ltd
//
// 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;
using System.ServiceProcess;
namespace Seq.Forwarder.ServiceProcess
{
class SeqForwarderWindowsService : ServiceBase
{
readonly ServerService _serverService;
readonly IDisposable _disposeOnStop;
public static string WindowsServiceName { get; } = "Seq Forwarder";
public SeqForwarderWindowsService(ServerService serverService, IDisposable disposeOnStop)
{
_serverService = serverService;
_disposeOnStop = disposeOnStop;
ServiceName = WindowsServiceName;
}
protected override void OnStart(string[] args)
{
_serverService.Start();
}
protected override void OnStop()
{
_serverService.Stop();
_disposeOnStop.Dispose();
}
}
} | apache-2.0 | C# |
3e5b1f2da78b4b1ef92ad170cae50a35759a7183 | Update Parse for ReadOnly FileAccess (#876) | cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber,cucumber/cucumber | gherkin/dotnet/Gherkin/Parser.Extensions.cs | gherkin/dotnet/Gherkin/Parser.Extensions.cs | using System.IO;
using Gherkin.Ast;
namespace Gherkin
{
public class Parser : Parser<GherkinDocument>
{
public Parser()
{
}
public Parser(IAstBuilder<GherkinDocument> astBuilder)
: base(astBuilder)
{
}
public GherkinDocument Parse(TextReader reader)
{
return Parse(new TokenScanner(reader));
}
public GherkinDocument Parse(string sourceFile)
{
using (var stream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
{
using (var reader = new StreamReader(stream))
{
return Parse(new TokenScanner(reader));
}
}
}
}
}
| using System.IO;
using Gherkin.Ast;
namespace Gherkin
{
public class Parser : Parser<GherkinDocument>
{
public Parser()
{
}
public Parser(IAstBuilder<GherkinDocument> astBuilder)
: base(astBuilder)
{
}
public GherkinDocument Parse(TextReader reader)
{
return Parse(new TokenScanner(reader));
}
public GherkinDocument Parse(string sourceFile)
{
using (var stream = new FileStream(sourceFile, FileMode.Open))
{
using (var reader = new StreamReader(stream))
{
return Parse(new TokenScanner(reader));
}
}
}
}
}
| mit | C# |
2dfb9258adffe6e655078a5c43b5084616aab76f | add missing initialiser for Errors property in UnauthorizedException | seekasia-oss/jobstreet-ad-posting-api-client | src/SEEK.AdPostingApi.Client/UnauthorizedException.cs | src/SEEK.AdPostingApi.Client/UnauthorizedException.cs | using System;
using System.Runtime.Serialization;
using SEEK.AdPostingApi.Client.Models;
namespace SEEK.AdPostingApi.Client
{
[Serializable]
public class UnauthorizedException : RequestException
{
public UnauthorizedException(string requestId, int httpStatusCode, string message) : base(requestId, httpStatusCode, message)
{
this.Errors = new AdvertisementError[0];
}
public UnauthorizedException(string requestId, int httpStatusCode, AdvertisementErrorResponse errorResponse) : base(requestId, httpStatusCode, errorResponse?.Message)
{
this.Errors = errorResponse?.Errors ?? new AdvertisementError[0];
}
protected UnauthorizedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
this.Errors = (AdvertisementError[])info.GetValue(nameof(this.Errors), typeof(AdvertisementError[]));
}
public AdvertisementError[] Errors { get; }
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(this.Errors), this.Errors);
base.GetObjectData(info, context);
}
}
} | using System;
using System.Runtime.Serialization;
using SEEK.AdPostingApi.Client.Models;
namespace SEEK.AdPostingApi.Client
{
[Serializable]
public class UnauthorizedException : RequestException
{
public UnauthorizedException(string requestId, int httpStatusCode, string message) : base(requestId, httpStatusCode, message)
{
}
public UnauthorizedException(string requestId, int httpStatusCode, AdvertisementErrorResponse errorResponse) : base(requestId, httpStatusCode, errorResponse?.Message)
{
this.Errors = errorResponse?.Errors ?? new AdvertisementError[0];
}
protected UnauthorizedException(SerializationInfo info, StreamingContext context) : base(info, context)
{
this.Errors = (AdvertisementError[])info.GetValue(nameof(this.Errors), typeof(AdvertisementError[]));
}
public AdvertisementError[] Errors { get; }
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(nameof(this.Errors), this.Errors);
base.GetObjectData(info, context);
}
}
} | mit | C# |
2157e076548f2e0de26df0233ad662f1da73b30a | Support for special characters and new line in C# comments. | frhagn/Typewriter | src/Typewriter/CodeModel/Implementation/DocComment.cs | src/Typewriter/CodeModel/Implementation/DocComment.cs | using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Typewriter.CodeModel.Collections;
namespace Typewriter.CodeModel.Implementation
{
public class DocCommentImpl : DocComment
{
private readonly XElement _root;
private DocCommentImpl(XElement root, Item parent)
{
_root = root;
Parent = parent;
}
public override Item Parent { get; }
private string _summary;
public override string Summary => _summary ?? (_summary = FormatValue(_root.Element("summary") == null ? string.Empty : string.Concat(_root.Element("summary").Nodes())));
private string _returns;
public override string Returns => _returns ?? (_returns = FormatValue(_root.Element("returns") == null ? string.Empty : string.Concat(_root.Element("returns").Nodes())));
private ParameterCommentCollection _parameters;
public override ParameterCommentCollection Parameters => _parameters ?? (_parameters = ParameterCommentImpl.FromXElements(_root.Elements("param"), this));
public override string ToString()
{
return Summary;
}
public static string FormatValue(string value)
{
if (string.IsNullOrEmpty(value)) return value;
var lines = value.Split('\r', '\n');
return string.Join(" ", lines.Select(l => l.Trim())).Trim();
}
public static DocComment FromXml(string xml, Item parent)
{
if (string.IsNullOrEmpty(xml)) return null;
var root = XDocument.Parse(xml).Root;
return root != null ? new DocCommentImpl(root, parent) : null;
}
}
public class ParameterCommentImpl : ParameterComment
{
private ParameterCommentImpl(XElement element, Item parent)
{
Parent = parent;
Name = element.Attribute("name")?.Value.Trim();
Description = DocCommentImpl.FormatValue(element.Value);
}
public override Item Parent { get; }
public override string Name { get; }
public override string Description { get; }
public override string ToString()
{
return Name;
}
public static ParameterCommentCollection FromXElements(IEnumerable<XElement> elements, Item parent)
{
return new ParameterCommentCollectionImpl(elements.Select(e => new ParameterCommentImpl(e, parent)));
}
}
} | using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using Typewriter.CodeModel.Collections;
namespace Typewriter.CodeModel.Implementation
{
public class DocCommentImpl : DocComment
{
private readonly XElement _root;
private DocCommentImpl(XElement root, Item parent)
{
_root = root;
Parent = parent;
}
public override Item Parent { get; }
private string _summary;
public override string Summary => _summary ?? (_summary = FormatValue(_root.Element("summary")?.Value));
private string _returns;
public override string Returns => _returns ?? (_returns = FormatValue(_root.Element("returns")?.Value));
private ParameterCommentCollection _parameters;
public override ParameterCommentCollection Parameters => _parameters ?? (_parameters = ParameterCommentImpl.FromXElements(_root.Elements("param"), this));
public override string ToString()
{
return Summary;
}
public static string FormatValue(string value)
{
if (string.IsNullOrEmpty(value)) return value;
var lines = value.Split('\r', '\n');
return string.Join(" ", lines.Select(l => l.Trim())).Trim();
}
public static DocComment FromXml(string xml, Item parent)
{
if (string.IsNullOrEmpty(xml)) return null;
var root = XDocument.Parse(xml).Root;
return root != null ? new DocCommentImpl(root, parent) : null;
}
}
public class ParameterCommentImpl : ParameterComment
{
private ParameterCommentImpl(XElement element, Item parent)
{
Parent = parent;
Name = element.Attribute("name")?.Value.Trim();
Description = DocCommentImpl.FormatValue(element.Value);
}
public override Item Parent { get; }
public override string Name { get; }
public override string Description { get; }
public override string ToString()
{
return Name;
}
public static ParameterCommentCollection FromXElements(IEnumerable<XElement> elements, Item parent)
{
return new ParameterCommentCollectionImpl(elements.Select(e => new ParameterCommentImpl(e, parent)));
}
}
} | apache-2.0 | C# |
acad1fefc18948dd7fb267a1d1b62b83f64395f5 | Fix typo | drussilla/HomeMetrics | HomeMetrics.Collector/src/HomeMetrics.Collector.API/Controllers/SensorController.cs | HomeMetrics.Collector/src/HomeMetrics.Collector.API/Controllers/SensorController.cs | using HomeMetrics.Collector.DAL.Models;
using HomeMetrics.Collector.DAL.Repositories;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
namespace HomeMetrics.Collector.API.Controllers
{
[Route("api/sensor")]
public class SensorController : APIController
{
private readonly ILogger<SensorController> _log;
private readonly ISensorRepository _sensors;
public SensorController(ILogger<SensorController> log, ISensorRepository sensors)
{
_log = log;
_sensors = sensors;
}
[HttpPost]
public IActionResult Add([FromBody]dynamic sensor)
{
var name = (string) sensor.Name;
_log.LogInformation(name);
var newSensor = new Sensor
{
Name = (string)sensor.Name
};
_log.LogInformation(newSensor.Id.ToString());
_sensors.Add(newSensor);
return Created("api/reading/" + newSensor.Id);
}
}
} | using HomeMetrics.Collector.DAL.Models;
using HomeMetrics.Collector.DAL.Repositories;
using Microsoft.AspNet.Mvc;
using Microsoft.Extensions.Logging;
namespace HomeMetrics.Collector.API.Controllers
{
[Route("api/sensor")]
public class SensorController : APIController
{
private readonly ILogger<ReadingController> _log;
private readonly ISensorRepository _sensors;
public SensorController(ILogger<ReadingController> log, ISensorRepository sensors)
{
_log = log;
_sensors = sensors;
}
[HttpPost]
public IActionResult Add([FromBody]dynamic sensor)
{
var name = (string) sensor.Name;
_log.LogInformation(name);
var newSensor = new Sensor
{
Name = (string)sensor.Name
};
_log.LogInformation(newSensor.Id.ToString());
_sensors.Add(newSensor);
return Created("api/reading/" + newSensor.Id);
}
}
} | mit | C# |
77791f606e571ebe112ca891d3d8ac69c1d0c238 | Fix caption of Python Environments window. | fjxhkj/PTVS,crwilcox/PTVS,fivejjs/PTVS,int19h/PTVS,mlorbetske/PTVS,msunardi/PTVS,modulexcite/PTVS,MetSystem/PTVS,Habatchii/PTVS,gomiero/PTVS,jkorell/PTVS,Microsoft/PTVS,Habatchii/PTVS,huguesv/PTVS,DEVSENSE/PTVS,alanch-ms/PTVS,denfromufa/PTVS,jkorell/PTVS,alanch-ms/PTVS,gilbertw/PTVS,modulexcite/PTVS,juanyaw/PTVS,Microsoft/PTVS,mlorbetske/PTVS,MetSystem/PTVS,zooba/PTVS,christer155/PTVS,fivejjs/PTVS,DinoV/PTVS,fjxhkj/PTVS,modulexcite/PTVS,modulexcite/PTVS,jkorell/PTVS,dut3062796s/PTVS,dut3062796s/PTVS,fjxhkj/PTVS,Microsoft/PTVS,MetSystem/PTVS,modulexcite/PTVS,dut3062796s/PTVS,christer155/PTVS,msunardi/PTVS,huguesv/PTVS,denfromufa/PTVS,mlorbetske/PTVS,zooba/PTVS,denfromufa/PTVS,christer155/PTVS,int19h/PTVS,Microsoft/PTVS,crwilcox/PTVS,DinoV/PTVS,huguesv/PTVS,DEVSENSE/PTVS,crwilcox/PTVS,mlorbetske/PTVS,Habatchii/PTVS,alanch-ms/PTVS,christer155/PTVS,denfromufa/PTVS,DinoV/PTVS,gomiero/PTVS,DEVSENSE/PTVS,denfromufa/PTVS,MetSystem/PTVS,christer155/PTVS,bolabola/PTVS,DinoV/PTVS,alanch-ms/PTVS,ChinaQuants/PTVS,Habatchii/PTVS,Microsoft/PTVS,zooba/PTVS,xNUTs/PTVS,int19h/PTVS,zooba/PTVS,dut3062796s/PTVS,huguesv/PTVS,ChinaQuants/PTVS,DinoV/PTVS,DEVSENSE/PTVS,ChinaQuants/PTVS,bolabola/PTVS,Habatchii/PTVS,juanyaw/PTVS,DEVSENSE/PTVS,jkorell/PTVS,DinoV/PTVS,xNUTs/PTVS,MetSystem/PTVS,juanyaw/PTVS,denfromufa/PTVS,gilbertw/PTVS,crwilcox/PTVS,gilbertw/PTVS,dut3062796s/PTVS,huguesv/PTVS,crwilcox/PTVS,gomiero/PTVS,Habatchii/PTVS,int19h/PTVS,gomiero/PTVS,fjxhkj/PTVS,fivejjs/PTVS,xNUTs/PTVS,int19h/PTVS,bolabola/PTVS,DEVSENSE/PTVS,fjxhkj/PTVS,huguesv/PTVS,alanch-ms/PTVS,fjxhkj/PTVS,fivejjs/PTVS,bolabola/PTVS,mlorbetske/PTVS,dut3062796s/PTVS,zooba/PTVS,ChinaQuants/PTVS,alanch-ms/PTVS,MetSystem/PTVS,ChinaQuants/PTVS,mlorbetske/PTVS,xNUTs/PTVS,jkorell/PTVS,Microsoft/PTVS,bolabola/PTVS,juanyaw/PTVS,modulexcite/PTVS,fivejjs/PTVS,msunardi/PTVS,msunardi/PTVS,msunardi/PTVS,msunardi/PTVS,zooba/PTVS,gomiero/PTVS,ChinaQuants/PTVS,int19h/PTVS,juanyaw/PTVS,gilbertw/PTVS,bolabola/PTVS,gilbertw/PTVS,xNUTs/PTVS,crwilcox/PTVS,juanyaw/PTVS,jkorell/PTVS,xNUTs/PTVS,gomiero/PTVS,fivejjs/PTVS,christer155/PTVS,gilbertw/PTVS | Python/Product/PythonTools/PythonTools/InterpreterList/InterpreterListToolWindow.cs | Python/Product/PythonTools/PythonTools/InterpreterList/InterpreterListToolWindow.cs | /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools.InterpreterList {
[Guid(PythonConstants.InterpreterListToolWindowGuid)]
class InterpreterListToolWindow : ToolWindowPane {
public InterpreterListToolWindow() {
Caption = SR.GetString(SR.Interpreters);
Content = new InterpreterList(
PythonToolsPackage.ComponentModel.GetService<IInterpreterOptionsService>(),
PythonToolsPackage.Instance);
}
}
}
| /* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Runtime.InteropServices;
using Microsoft.PythonTools.Interpreter;
using Microsoft.VisualStudio.Shell;
namespace Microsoft.PythonTools.InterpreterList {
[Guid(PythonConstants.InterpreterListToolWindowGuid)]
class InterpreterListToolWindow : ToolWindowPane {
const string Title = "Python Interpreters";
public InterpreterListToolWindow() {
Caption = Title;
Content = new InterpreterList(
PythonToolsPackage.ComponentModel.GetService<IInterpreterOptionsService>(),
PythonToolsPackage.Instance);
}
}
}
| apache-2.0 | C# |
5c1c5d1d71814f0abe533e705592b7ec36788b59 | fix for upsate-database in VS | sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp,sachatrauwaen/OpenApp | src/Satrabel.Starter.Web.Spa/EntityFramework/WebContentFolderHelper.cs | src/Satrabel.Starter.Web.Spa/EntityFramework/WebContentFolderHelper.cs | using System;
using System.IO;
using System.Linq;
using Abp.Reflection.Extensions;
using Satrabel.OpenApp;
using Satrabel.Starter.Web.Startup;
namespace Satrabel.Starter.Web
{
/// <summary>
/// This class is used to find root path of the web project in;
/// unit tests (to find views) and entity framework core command line commands (to find conn string).
/// </summary>
public static class WebContentDirectoryFinder
{
public static string CalculateContentRootFolder()
{
var coreAssemblyDirectoryPath = Path.GetDirectoryName(typeof(WebMvcModule).GetAssembly().Location);
if (coreAssemblyDirectoryPath == null)
{
throw new Exception("Could not find location of Satrabel.OpenApp.Core assembly!");
}
var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "web.config"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
return directoryInfo.FullName;
//var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "Satrabel.OpenApp.Web.Mvc");
//if (Directory.Exists(webMvcFolder))
//{
// return webMvcFolder;
//}
//var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "Satrabel.OpenApp.Web.Host");
//if (Directory.Exists(webHostFolder))
//{
// return webHostFolder;
//}
throw new Exception("Could not find root folder of the web project!");
}
private static bool DirectoryContains(string directory, string fileName)
{
return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
}
}
}
| using System;
using System.IO;
using System.Linq;
using Abp.Reflection.Extensions;
using Satrabel.OpenApp;
namespace Satrabel.Starter.Web
{
/// <summary>
/// This class is used to find root path of the web project in;
/// unit tests (to find views) and entity framework core command line commands (to find conn string).
/// </summary>
public static class WebContentDirectoryFinder
{
public static string CalculateContentRootFolder()
{
var coreAssemblyDirectoryPath = Path.GetDirectoryName(typeof(OpenAppCoreModule).GetAssembly().Location);
if (coreAssemblyDirectoryPath == null)
{
throw new Exception("Could not find location of Satrabel.OpenApp.Core assembly!");
}
var directoryInfo = new DirectoryInfo(coreAssemblyDirectoryPath);
while (!DirectoryContains(directoryInfo.FullName, "web.config"))
{
if (directoryInfo.Parent == null)
{
throw new Exception("Could not find content root folder!");
}
directoryInfo = directoryInfo.Parent;
}
return directoryInfo.FullName;
//var webMvcFolder = Path.Combine(directoryInfo.FullName, "src", "Satrabel.OpenApp.Web.Mvc");
//if (Directory.Exists(webMvcFolder))
//{
// return webMvcFolder;
//}
//var webHostFolder = Path.Combine(directoryInfo.FullName, "src", "Satrabel.OpenApp.Web.Host");
//if (Directory.Exists(webHostFolder))
//{
// return webHostFolder;
//}
throw new Exception("Could not find root folder of the web project!");
}
private static bool DirectoryContains(string directory, string fileName)
{
return Directory.GetFiles(directory).Any(filePath => string.Equals(Path.GetFileName(filePath), fileName));
}
}
}
| mit | C# |
62150e9b539a48fcc0d5e2055d8cdb11f297e6eb | Unwind some Linq in a relatively hot path | robinsedlaczek/roslyn,zooba/roslyn,jeffanders/roslyn,OmarTawfik/roslyn,ljw1004/roslyn,heejaechang/roslyn,mattscheffer/roslyn,KevinH-MS/roslyn,MattWindsor91/roslyn,DustinCampbell/roslyn,CaptainHayashi/roslyn,CaptainHayashi/roslyn,TyOverby/roslyn,davkean/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,xasx/roslyn,tmeschter/roslyn,pdelvo/roslyn,nguerrera/roslyn,diryboy/roslyn,bartdesmet/roslyn,weltkante/roslyn,ljw1004/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,KiloBravoLima/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mattscheffer/roslyn,brettfo/roslyn,mattscheffer/roslyn,robinsedlaczek/roslyn,xoofx/roslyn,gafter/roslyn,tmeschter/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,Pvlerick/roslyn,MattWindsor91/roslyn,tmat/roslyn,budcribar/roslyn,drognanar/roslyn,jcouv/roslyn,natidea/roslyn,genlu/roslyn,lorcanmooney/roslyn,MichalStrehovsky/roslyn,sharwell/roslyn,nguerrera/roslyn,AmadeusW/roslyn,KirillOsenkov/roslyn,srivatsn/roslyn,zooba/roslyn,Shiney/roslyn,reaction1989/roslyn,MattWindsor91/roslyn,mmitche/roslyn,jasonmalinowski/roslyn,Giftednewt/roslyn,abock/roslyn,AlekseyTs/roslyn,budcribar/roslyn,jkotas/roslyn,paulvanbrenk/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,CyrusNajmabadi/roslyn,drognanar/roslyn,bbarry/roslyn,khyperia/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,agocke/roslyn,mavasani/roslyn,AnthonyDGreen/roslyn,AnthonyDGreen/roslyn,amcasey/roslyn,sharwell/roslyn,aelij/roslyn,Pvlerick/roslyn,jhendrixMSFT/roslyn,MatthieuMEZIL/roslyn,srivatsn/roslyn,mmitche/roslyn,agocke/roslyn,dotnet/roslyn,KiloBravoLima/roslyn,MatthieuMEZIL/roslyn,wvdd007/roslyn,akrisiun/roslyn,KevinH-MS/roslyn,a-ctor/roslyn,stephentoub/roslyn,gafter/roslyn,mattwar/roslyn,orthoxerox/roslyn,jasonmalinowski/roslyn,bkoelman/roslyn,tmat/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,pdelvo/roslyn,tannergooding/roslyn,amcasey/roslyn,jhendrixMSFT/roslyn,eriawan/roslyn,ErikSchierboom/roslyn,MattWindsor91/roslyn,jkotas/roslyn,balajikris/roslyn,CyrusNajmabadi/roslyn,Giftednewt/roslyn,AmadeusW/roslyn,dotnet/roslyn,diryboy/roslyn,physhi/roslyn,a-ctor/roslyn,MichalStrehovsky/roslyn,ErikSchierboom/roslyn,OmarTawfik/roslyn,kelltrick/roslyn,srivatsn/roslyn,kelltrick/roslyn,davkean/roslyn,nguerrera/roslyn,weltkante/roslyn,brettfo/roslyn,lorcanmooney/roslyn,mattwar/roslyn,ljw1004/roslyn,vslsnap/roslyn,jkotas/roslyn,VSadov/roslyn,jeffanders/roslyn,tvand7093/roslyn,wvdd007/roslyn,tmeschter/roslyn,physhi/roslyn,cston/roslyn,sharwell/roslyn,robinsedlaczek/roslyn,DustinCampbell/roslyn,jeffanders/roslyn,brettfo/roslyn,Pvlerick/roslyn,orthoxerox/roslyn,vslsnap/roslyn,eriawan/roslyn,jcouv/roslyn,budcribar/roslyn,mgoertz-msft/roslyn,bbarry/roslyn,VSadov/roslyn,zooba/roslyn,bkoelman/roslyn,xoofx/roslyn,tvand7093/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,VSadov/roslyn,natidea/roslyn,genlu/roslyn,mmitche/roslyn,lorcanmooney/roslyn,mattwar/roslyn,genlu/roslyn,panopticoncentral/roslyn,dpoeschl/roslyn,balajikris/roslyn,xasx/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jmarolf/roslyn,pdelvo/roslyn,kelltrick/roslyn,khyperia/roslyn,Shiney/roslyn,amcasey/roslyn,orthoxerox/roslyn,reaction1989/roslyn,drognanar/roslyn,AArnott/roslyn,tmat/roslyn,vslsnap/roslyn,AnthonyDGreen/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,abock/roslyn,agocke/roslyn,Giftednewt/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,Hosch250/roslyn,Hosch250/roslyn,physhi/roslyn,aelij/roslyn,bartdesmet/roslyn,bkoelman/roslyn,dpoeschl/roslyn,KevinRansom/roslyn,AArnott/roslyn,bbarry/roslyn,dpoeschl/roslyn,xasx/roslyn,yeaicc/roslyn,KevinH-MS/roslyn,TyOverby/roslyn,paulvanbrenk/roslyn,tvand7093/roslyn,jcouv/roslyn,akrisiun/roslyn,weltkante/roslyn,AlekseyTs/roslyn,natidea/roslyn,MatthieuMEZIL/roslyn,aelij/roslyn,TyOverby/roslyn,OmarTawfik/roslyn,mavasani/roslyn,jamesqo/roslyn,reaction1989/roslyn,heejaechang/roslyn,tannergooding/roslyn,gafter/roslyn,diryboy/roslyn,stephentoub/roslyn,DustinCampbell/roslyn,cston/roslyn,KiloBravoLima/roslyn,ErikSchierboom/roslyn,MichalStrehovsky/roslyn,KevinRansom/roslyn,Hosch250/roslyn,AArnott/roslyn,panopticoncentral/roslyn,balajikris/roslyn,jmarolf/roslyn,Shiney/roslyn,akrisiun/roslyn,mgoertz-msft/roslyn,jhendrixMSFT/roslyn,yeaicc/roslyn,yeaicc/roslyn,khyperia/roslyn,mavasani/roslyn,CaptainHayashi/roslyn,KirillOsenkov/roslyn,a-ctor/roslyn,abock/roslyn,paulvanbrenk/roslyn,bartdesmet/roslyn,xoofx/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,cston/roslyn,tannergooding/roslyn | src/Workspaces/Core/Portable/Shared/Extensions/SymbolInfoExtensions.cs | src/Workspaces/Core/Portable/Shared/Extensions/SymbolInfoExtensions.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SymbolInfoExtensions
{
public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info)
{
return info.Symbol == null && info.CandidateSymbols.Length == 0
? SpecializedCollections.EmptyEnumerable<ISymbol>()
: GetAllSymbolsWorker(info).Distinct();
}
private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
{
if (info.Symbol != null)
{
yield return info.Symbol;
}
foreach (var symbol in info.CandidateSymbols)
{
yield return symbol;
}
}
public static ISymbol GetAnySymbol(this SymbolInfo info)
{
return info.Symbol != null
? info.Symbol
: info.CandidateSymbols.FirstOrDefault();
}
public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
{
if (info.Symbol != null)
{
return SpecializedCollections.SingletonEnumerable(info.Symbol);
}
else if (info.CandidateSymbols.Length > 0)
{
return info.CandidateSymbols;
}
return SpecializedCollections.EmptyEnumerable<ISymbol>();
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.Shared.Extensions
{
internal static class SymbolInfoExtensions
{
public static IEnumerable<ISymbol> GetAllSymbols(this SymbolInfo info)
{
return info.Symbol == null && info.CandidateSymbols.Length == 0
? SpecializedCollections.EmptyEnumerable<ISymbol>()
: GetAllSymbolsWorker(info).Distinct();
}
private static IEnumerable<ISymbol> GetAllSymbolsWorker(this SymbolInfo info)
{
if (info.Symbol != null)
{
yield return info.Symbol;
}
foreach (var symbol in info.CandidateSymbols)
{
yield return symbol;
}
}
public static ISymbol GetAnySymbol(this SymbolInfo info)
{
return info.GetAllSymbols().FirstOrDefault();
}
public static IEnumerable<ISymbol> GetBestOrAllSymbols(this SymbolInfo info)
{
if (info.Symbol != null)
{
return SpecializedCollections.SingletonEnumerable(info.Symbol);
}
else if (info.CandidateSymbols.Length > 0)
{
return info.CandidateSymbols;
}
return SpecializedCollections.EmptyEnumerable<ISymbol>();
}
}
}
| apache-2.0 | C# |
d21eccf405481710b17638764f062cfe8117d278 | Use GetFileFromApplicationUriAsync to convert from a Uri to a system file path. | phongcao/image-pipeline-windows,phongcao/image-pipeline-windows,phongcao/image-pipeline-windows,phongcao/image-pipeline-windows | ImagePipeline/ImagePipeline/Producers/LocalFileFetchProducer.cs | ImagePipeline/ImagePipeline/Producers/LocalFileFetchProducer.cs | using FBCore.Concurrency;
using ImagePipeline.Image;
using ImagePipeline.Memory;
using ImagePipeline.Request;
using System;
using System.IO;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage;
namespace ImagePipeline.Producers
{
/// <summary>
/// Represents a local file fetch producer.
/// </summary>
public class LocalFileFetchProducer : LocalFetchProducer
{
internal const string PRODUCER_NAME = "LocalFileFetchProducer";
/// <summary>
/// Instantiates the <see cref="LocalFileFetchProducer"/>.
/// </summary>
public LocalFileFetchProducer(
IExecutorService executor,
IPooledByteBufferFactory pooledByteBufferFactory) : base(
executor,
pooledByteBufferFactory)
{
}
/// <summary>
/// Gets the encoded image.
/// </summary>
protected override Task<EncodedImage> GetEncodedImage(ImageRequest imageRequest)
{
Task<StorageFile> uriToFilePathTask = StorageFile.GetFileFromApplicationUriAsync(imageRequest.SourceUri).AsTask();
return uriToFilePathTask.ContinueWith<EncodedImage>((filepathTask) => {
FileInfo file = new FileInfo(filepathTask.Result.Path);
return GetEncodedImage(file.OpenRead(), (int)(file.Length));
});
}
/// <summary>
/// The name of the Producer.
/// </summary>
protected override string ProducerName
{
get
{
return PRODUCER_NAME;
}
}
}
}
| using FBCore.Concurrency;
using ImagePipeline.Image;
using ImagePipeline.Memory;
using ImagePipeline.Request;
using System.IO;
using System.Threading.Tasks;
namespace ImagePipeline.Producers
{
/// <summary>
/// Represents a local file fetch producer.
/// </summary>
public class LocalFileFetchProducer : LocalFetchProducer
{
internal const string PRODUCER_NAME = "LocalFileFetchProducer";
/// <summary>
/// Instantiates the <see cref="LocalFileFetchProducer"/>.
/// </summary>
public LocalFileFetchProducer(
IExecutorService executor,
IPooledByteBufferFactory pooledByteBufferFactory) : base(
executor,
pooledByteBufferFactory)
{
}
/// <summary>
/// Gets the encoded image.
/// </summary>
protected override Task<EncodedImage> GetEncodedImage(ImageRequest imageRequest)
{
FileInfo file = (FileInfo)imageRequest.SourceFile;
return Task.FromResult(GetEncodedImage(file.OpenRead(), (int)(file.Length)));
}
/// <summary>
/// The name of the Producer.
/// </summary>
protected override string ProducerName
{
get
{
return PRODUCER_NAME;
}
}
}
}
| mit | C# |
bf85907167fee1191755c110a7207e467b070fbc | Remove whitespace | pikkpoiss/ld36,pikkpoiss/ld36,pikkpoiss/ld36 | Assets/Scripts/Dialogue.cs | Assets/Scripts/Dialogue.cs | using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Yarn.Unity;
public class Dialogue : MonoBehaviour {
public DialogueStorage storage;
public DialogueUI ui;
private Dictionary<string, BitmaskPuzzle> puzzles_;
private void Awake() {
puzzles_ = new Dictionary<string, BitmaskPuzzle>() {
{ "intro", BitmaskPuzzle.Get(BitmaskPuzzle.Difficulty.Easy, BitmaskOperation.shiftLeft) }
};
}
[YarnCommand("enable")]
public void Enable(string name) {
storage.EnableOperation(name);
}
[YarnCommand("clearpuzzle")]
public void ClearPuzzle() {
ui.ClearPuzzle();
storage.SetValue("$puzzle_target", Yarn.Value.NULL);
storage.SetValue("$puzzle_active", Yarn.Value.NULL);
}
[YarnCommand("setpuzzle")]
public void SetPuzzle(string key) {
BitmaskPuzzle puzzle;
if (!puzzles_.TryGetValue(key, out puzzle)) {
Debug.LogErrorFormat("Could not find puzzle with key {0}", key);
return;
}
storage.SetValue("$puzzle_target", GetPuzzleValue(puzzle.targetValue));
storage.SetValue("$puzzle_active", GetPuzzleValue(puzzle.currentValue));
ui.SetPuzzle(ref puzzle);
}
private string GetPuzzleValue(int value) {
return value.ToString("X4");
}
}
| using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Yarn.Unity;
public class Dialogue : MonoBehaviour {
public DialogueStorage storage;
public DialogueUI ui;
private Dictionary<string, BitmaskPuzzle> puzzles_;
private void Awake() {
puzzles_ = new Dictionary<string, BitmaskPuzzle>() {
{ "intro", BitmaskPuzzle.Get(BitmaskPuzzle.Difficulty.Easy, BitmaskOperation.shiftLeft) }
};
}
[YarnCommand("enable")]
public void Enable(string name) {
storage.EnableOperation(name);
}
[YarnCommand("clearpuzzle")]
public void ClearPuzzle() {
ui.ClearPuzzle();
storage.SetValue("$puzzle_target", Yarn.Value.NULL);
storage.SetValue("$puzzle_active", Yarn.Value.NULL);
}
[YarnCommand("setpuzzle")]
public void SetPuzzle(string key) {
BitmaskPuzzle puzzle;
if (!puzzles_.TryGetValue(key, out puzzle)) {
Debug.LogErrorFormat("Could not find puzzle with key {0}", key);
return;
}
storage.SetValue("$puzzle_target", GetPuzzleValue(puzzle.targetValue));
storage.SetValue("$puzzle_active", GetPuzzleValue(puzzle.currentValue));
ui.SetPuzzle(ref puzzle);
}
private string GetPuzzleValue(int value) {
return value.ToString("X4");
}
}
| apache-2.0 | C# |
b60a2d70fc03a7c11d0b86391c6980588708f943 | Move event outside of lock | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Blockchain/Analysis/FeesEstimation/FeeProviders.cs | WalletWasabi/Blockchain/Analysis/FeesEstimation/FeeProviders.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace WalletWasabi.Blockchain.Analysis.FeesEstimation
{
public class FeeProviders : IFeeProvider, IDisposable
{
public FeeProviders(IEnumerable<IFeeProvider> feeProviders)
{
Providers = feeProviders;
Lock = new object();
SetAllFeeEstimate();
foreach (var provider in Providers)
{
provider.AllFeeEstimateChanged += Provider_AllFeeEstimateChanged;
}
}
public event EventHandler<AllFeeEstimate> AllFeeEstimateChanged;
public AllFeeEstimate AllFeeEstimate { get; private set; }
private IEnumerable<IFeeProvider> Providers { get; }
private object Lock { get; }
private void Provider_AllFeeEstimateChanged(object sender, AllFeeEstimate e)
{
SetAllFeeEstimate();
}
private void SetAllFeeEstimate()
{
lock (Lock)
{
AllFeeEstimate? feeEstimateToSet = null;
IFeeProvider[] providerArray = Providers.ToArray();
for (int i = 0; i < providerArray.Length - 1; i++)
{
IFeeProvider provider = providerArray[i];
var af = provider.AllFeeEstimate;
if (af is { } && af.IsAccurate)
{
feeEstimateToSet = af;
break;
}
}
AllFeeEstimate = feeEstimateToSet ?? providerArray[^1].AllFeeEstimate;
AllFeeEstimateChanged?.Invoke(this, AllFeeEstimate);
}
}
#region IDisposable Support
private volatile bool _disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (var provider in Providers)
{
provider.AllFeeEstimateChanged -= Provider_AllFeeEstimateChanged;
}
}
_disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion IDisposable Support
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace WalletWasabi.Blockchain.Analysis.FeesEstimation
{
public class FeeProviders : IFeeProvider, IDisposable
{
private AllFeeEstimate _allFeeEstimate;
public FeeProviders(IEnumerable<IFeeProvider> feeProviders)
{
Providers = feeProviders;
Lock = new object();
SetAllFeeEstimate();
foreach (var provider in Providers)
{
provider.AllFeeEstimateChanged += Provider_AllFeeEstimateChanged;
}
}
public event EventHandler<AllFeeEstimate> AllFeeEstimateChanged;
public AllFeeEstimate AllFeeEstimate
{
get => _allFeeEstimate;
private set
{
if (value != _allFeeEstimate)
{
_allFeeEstimate = value;
AllFeeEstimateChanged?.Invoke(this, value);
}
}
}
private IEnumerable<IFeeProvider> Providers { get; }
private object Lock { get; }
private void Provider_AllFeeEstimateChanged(object sender, AllFeeEstimate e)
{
SetAllFeeEstimate();
}
private void SetAllFeeEstimate()
{
lock (Lock)
{
IFeeProvider[] providerArray = Providers.ToArray();
for (int i = 0; i < providerArray.Length - 1; i++)
{
IFeeProvider provider = providerArray[i];
var af = provider.AllFeeEstimate;
if (af is { } && af.IsAccurate)
{
AllFeeEstimate = af;
return;
}
}
AllFeeEstimate = providerArray[^1].AllFeeEstimate;
}
}
#region IDisposable Support
private volatile bool _disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!_disposedValue)
{
if (disposing)
{
foreach (var provider in Providers)
{
provider.AllFeeEstimateChanged -= Provider_AllFeeEstimateChanged;
}
}
_disposedValue = true;
}
}
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
}
#endregion IDisposable Support
}
}
| mit | C# |
31d75a9b3ccc7285aea39c4d1d1814358e7ae532 | Fix intermittent tests | Ampla/Ampla-Log-Reader | src/Ampla.LogReader.Tests/EventLogs/EventLogReaderUnitTests.cs | src/Ampla.LogReader.Tests/EventLogs/EventLogReaderUnitTests.cs | using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
namespace Ampla.LogReader.EventLogs
{
[TestFixture]
public class EventLogReaderUnitTests : TestFixture
{
[Test]
public void ReadEntries()
{
ILocalEventLogSystem eventLogSystem = new LocalEventLogSystem();
EventLog eventLog = eventLogSystem.GetEventLogs().FirstOrDefault(ev => ev.Entries.Count > 0);
Assert.That(eventLog, Is.Not.Null, "Unable to find an Event Log with something in it.");
EventLogReader reader = new EventLogReader(eventLog);
Assert.That(reader.Entries, Is.Empty);
int count = eventLog != null ? eventLog.Entries.Count : -1;
Assert.That(count, Is.GreaterThan(0), "No entries in the EventLog");
reader.Read();
Assert.That(reader.Entries, Is.Not.Empty);
Assert.That(reader.Entries.Count, Is.EqualTo(count).Or.EqualTo(count + 2));
reader.Read();
Assert.That(reader.Entries, Is.Not.Empty);
Assert.That(reader.Entries.Count, Is.EqualTo(count).Or.EqualTo(count + 2));
}
}
} | using System.Diagnostics;
using System.Linq;
using NUnit.Framework;
namespace Ampla.LogReader.EventLogs
{
[TestFixture]
public class EventLogReaderUnitTests : TestFixture
{
[Test]
public void ReadEntries()
{
ILocalEventLogSystem eventLogSystem = new LocalEventLogSystem();
EventLog eventLog = eventLogSystem.GetEventLogs().FirstOrDefault(ev => ev.Entries.Count > 0);
Assert.That(eventLog, Is.Not.Null, "Unable to find an Event Log with something in it.");
EventLogReader reader = new EventLogReader(eventLog);
Assert.That(reader.Entries, Is.Empty);
int count = eventLog != null ? eventLog.Entries.Count : -1;
Assert.That(count, Is.GreaterThan(0), "No entries in the EventLog");
reader.Read();
Assert.That(reader.Entries, Is.Not.Empty);
Assert.That(reader.Entries.Count, Is.EqualTo(count).Or.EqualTo(count + 1));
reader.Read();
Assert.That(reader.Entries, Is.Not.Empty);
Assert.That(reader.Entries.Count, Is.EqualTo(count).Or.EqualTo(count + 1));
}
}
} | mit | C# |
9b62b50c2f09a36335eb4a431d2bcf9a112b338f | Update AlphaStreamsSlippageModel.cs | StefanoRaggi/Lean,QuantConnect/Lean,AlexCatarino/Lean,AlexCatarino/Lean,JKarathiya/Lean,QuantConnect/Lean,JKarathiya/Lean,StefanoRaggi/Lean,JKarathiya/Lean,StefanoRaggi/Lean,JKarathiya/Lean,jameschch/Lean,QuantConnect/Lean,QuantConnect/Lean,jameschch/Lean,jameschch/Lean,jameschch/Lean,StefanoRaggi/Lean,AlexCatarino/Lean,StefanoRaggi/Lean,jameschch/Lean,AlexCatarino/Lean | Common/Orders/Slippage/AlphaStreamsSlippageModel.cs | Common/Orders/Slippage/AlphaStreamsSlippageModel.cs | /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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 QuantConnect.Securities;
using System.Collections.Generic;
namespace QuantConnect.Orders.Slippage
{
/// <summary>
/// Represents a slippage model that uses a constant percentage of slip
/// </summary>
public class AlphaStreamsSlippageModel : ISlippageModel
{
private const decimal _slippagePercent = 0.0001m;
/// <summary>
/// Unfortunate dictionary of ETFs and their spread on 10/10 so that we can better approximate
/// slippage for the competition
/// </summary>
private readonly IDictionary<string, decimal> _spreads = new Dictionary<string, decimal>
{
{"PPLT", 0.13m}, {"DGAZ", 0.135m}, {"EDV", 0.085m}, {"SOXL", 0.1m}
};
/// <summary>
/// Initializes a new instance of the <see cref="AlphaStreamsSlippageModel"/> class
/// </summary>
public AlphaStreamsSlippageModel() { }
/// <summary>
/// Return a decimal cash slippage approximation on the order.
/// </summary>
public decimal GetSlippageApproximation(Security asset, Order order)
{
if (asset.Type != SecurityType.Equity)
{
return 0;
}
decimal slippageValue;
if (!_spreads.TryGetValue(asset.Symbol.Value, out slippageValue))
{
return _slippagePercent * asset.GetLastData()?.Value ?? 0;
}
return slippageValue;
}
}
} | /*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* 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 QuantConnect.Securities;
using System.Collections.Generic;
namespace QuantConnect.Orders.Slippage
{
/// <summary>
/// Represents a slippage model that uses a constant percentage of slip
/// </summary>
public class AlphaStreamsSlippageModel : ISlippageModel
{
private const decimal _slippagePercent = 0.0001m;
/// <summary>
/// Unfortunate dictionary of ETFs and their spread on 10/10 so that we can better approximate
/// slippage for the competition
/// </summary>
private readonly IDictionary<string, decimal> _spreads = new Dictionary<string, decimal>
{
{"PPLT", 0.13m}, {"DGAZ", 0.135m}, {"EDV", 0.085m}, {"SOXL", 0.1m}
};
/// <summary>
/// Initializes a new instance of the <see cref="AlphaStreamsSlippageModel"/> class
/// </summary>
public AlphaStreamsSlippageModel() { }
/// <summary>
/// Return a decimal cash slippage approximation on the order.
/// </summary>
public decimal GetSlippageApproximation(Security asset, Order order)
{
if (asset.Type != SecurityType.Equity)
{
return 0;
}
decimal slippagePercent;
if (!_spreads.TryGetValue(asset.Symbol.Value, out slippagePercent))
{
return _slippagePercent * asset.GetLastData()?.Value ?? 0;
}
return slippagePercent * asset.GetLastData()?.Value ?? 0;
}
}
} | apache-2.0 | C# |
8c64d6d0d85bf69c1ae479a9b2bce4bc28d5c3d3 | Change comment. | AeonLucid/CHIP-8_Emulator | CHIP-8_Emulator/Program.cs | CHIP-8_Emulator/Program.cs | using CHIP_8_Emulator.Chip;
namespace CHIP_8_Emulator
{
internal static class Program
{
private static void Main(string[] args)
{
using (var game = new ChipWindow())
{
game.Run(60); // 60 Hz
}
}
}
}
| using CHIP_8_Emulator.Chip;
namespace CHIP_8_Emulator
{
internal static class Program
{
private static void Main(string[] args)
{
using (var game = new ChipWindow())
{
game.Run(60); // 30 Hz
}
}
}
}
| mit | C# |
6d7a44c3621de6244822bfa915867979b77c8398 | Fix a bug taht causes the GetChildNode method to return null references. | nohros/must,nohros/must,nohros/must | src/base/common/configuration/common/provider/ProvidersNode.cs | src/base/common/configuration/common/provider/ProvidersNode.cs | using System;
using System.Collections;
using System.Collections.Generic;
namespace Nohros.Configuration
{
/// <summary>
/// A <see cref="ProvidersNode"/> is a collection of
/// <see cref="ProviderNode"/> objects.
/// </summary>
public partial class ProvidersNode : AbstractHierarchicalConfigurationNode,
IProvidersNode
{
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="ProvidersNode"/> class.
/// </summary>
public ProvidersNode() : base(Strings.kProvidersNodeName) {
}
#endregion
#region IProvidersNode Members
/// <inheritdoc/>
public bool GetProviderNode(string simple_provider_name,
out IProviderNode simple_provider) {
return GetProviderNode(simple_provider_name, string.Empty,
out simple_provider);
}
/// <inheritdoc/>
public bool GetProviderNode(string simple_provider_name,
string simple_provider_group, out IProviderNode simple_provider) {
return
GetChildNode(
ProviderKey(simple_provider_name, simple_provider_group),
out simple_provider);
}
/// <inheritdoc/>
public IProviderNode GetProviderNode(string simple_provider_name) {
return GetProviderNode(simple_provider_name, string.Empty);
}
/// <inheritdoc/>
public IProviderNode GetProviderNode(
string simple_provider_name, string simple_provider_group) {
return
GetChildNode<IProviderNode>(ProviderKey(simple_provider_name,
simple_provider_group));
}
/// <inheritdoc/>
IProviderNode IProvidersNode.this[string provider_name] {
get { return GetProviderNode(provider_name); }
}
/// <inheritdoc/>
IProviderNode IProvidersNode.this[string provider_name, string provider_group] {
get { return GetProviderNode(provider_name, provider_group); }
}
#endregion
static string ProviderKey(string simple_provider_name,
string simple_provider_group) {
return "group:" + simple_provider_group + ",name:" + simple_provider_name;
}
public IEnumerator<IProviderNode> GetEnumerator() {
foreach(IConfigurationNode node in ChildNodes) {
yield return (IProviderNode) node;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
namespace Nohros.Configuration
{
/// <summary>
/// A <see cref="ProvidersNode"/> is a collection of
/// <see cref="ProviderNode"/> objects.
/// </summary>
public partial class ProvidersNode : AbstractHierarchicalConfigurationNode,
IProvidersNode
{
#region .ctor
/// <summary>
/// Initializes a new instance of the <see cref="ProvidersNode"/> class.
/// </summary>
public ProvidersNode() : base(Strings.kProvidersNodeName) {
}
#endregion
#region IProvidersNode Members
/// <inheritdoc/>
public bool GetProviderNode(string simple_provider_name,
out IProviderNode simple_provider) {
return GetProviderNode(simple_provider_name, string.Empty,
out simple_provider);
}
/// <inheritdoc/>
public bool GetProviderNode(string simple_provider_name,
string simple_provider_group, out IProviderNode simple_provider) {
return
GetChildNode(
ProviderKey(simple_provider_name, simple_provider_group),
out simple_provider);
}
/// <inheritdoc/>
public IProviderNode GetProviderNode(string simple_provider_name) {
return GetProviderNode(simple_provider_name, string.Empty);
}
/// <inheritdoc/>
public IProviderNode GetProviderNode(
string simple_provider_name, string simple_provider_group) {
return
base[ProviderKey(simple_provider_name, simple_provider_group)] as
IProviderNode;
}
/// <inheritdoc/>
IProviderNode IProvidersNode.this[string provider_name] {
get { return GetProviderNode(provider_name); }
}
/// <inheritdoc/>
IProviderNode IProvidersNode.this[string provider_name, string provider_group] {
get { return GetProviderNode(provider_name, provider_group); }
}
#endregion
static string ProviderKey(string simple_provider_name,
string simple_provider_group) {
return "group:" + simple_provider_group + ",name:" + simple_provider_name;
}
public IEnumerator<IProviderNode> GetEnumerator() {
foreach(IConfigurationNode node in ChildNodes) {
yield return (IProviderNode) node;
}
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
}
}
| mit | C# |
45e0e9e7890f68c864c6b54511265d3754c46605 | Correct title | damianh/Cedar.EventStore,SQLStreamStore/SQLStreamStore,damianh/SqlStreamStore,SQLStreamStore/SQLStreamStore | src/SqlStreamStore/Properties/AssemblyInfo.cs | src/SqlStreamStore/Properties/AssemblyInfo.cs | using System.Reflection;
[assembly: AssemblyTitle("SqlStreamStore")]
[assembly: AssemblyDescription("")]
| using System.Reflection;
[assembly: AssemblyTitle("StreamStore")]
[assembly: AssemblyDescription("")] | mit | C# |
98b25f126f1a0a10df3aa6556e1c24ff05402926 | fix mono build | rob-somerville/riak-dotnet-client,basho/riak-dotnet-client,rob-somerville/riak-dotnet-client,basho/riak-dotnet-client | src/Test/Integration/KV/FetchPreflistTests.cs | src/Test/Integration/KV/FetchPreflistTests.cs | // <copyright file="FetchPreflistTests.cs" company="Basho Technologies, Inc.">
// Copyright 2015 - Basho Technologies, Inc.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
namespace Test.Integration.CRDT
{
using System;
using System.Linq;
using Common.Logging;
using NUnit.Framework;
using RiakClient;
using RiakClient.Commands;
using RiakClient.Commands.KV;
public class FetchPreflistTests : TestBase
{
protected override RiakString BucketType
{
get { return new RiakString("plain"); }
}
protected override RiakString Bucket
{
get { return new RiakString("fetch_preflists"); }
}
[Test]
public void Can_Fetch_Preflist()
{
RiakMinVersion(2, 1, 0);
var fetch = new FetchPreflist.Builder()
.WithBucketType(BucketType)
.WithBucket(Bucket)
.WithKey("key_1")
.Build();
RiakResult rslt = client.Execute(fetch);
Assert.IsTrue(rslt.IsSuccess, rslt.ErrorMessage);
PreflistResponse response = fetch.Response;
Assert.IsNotNull(response);
Assert.AreEqual(3, response.Value.Count());
}
}
}
| // <copyright file="FetchPreflistTests.cs" company="Basho Technologies, Inc.">
// Copyright 2015 - Basho Technologies, Inc.
//
// This file is provided to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain
// a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
// </copyright>
namespace Test.Integration.CRDT
{
using System;
using System.Linq;
using Common.Logging;
using NUnit.Framework;
using RiakClient;
using RiakClient.Commands;
using RiakClient.Commands.KV;
public class FetchPreflistTests : TestBase
{
private static readonly ILog Log = Logging.GetLogger(typeof(FetchPreflistTests));
protected override RiakString BucketType
{
get { return new RiakString("plain"); }
}
protected override RiakString Bucket
{
get { return new RiakString("fetch_preflists"); }
}
[Test]
public void Can_Fetch_Preflist()
{
RiakMinVersion(2, 1, 0);
var fetch = new FetchPreflist.Builder()
.WithBucketType(BucketType)
.WithBucket(Bucket)
.WithKey("key_1")
.Build();
RiakResult rslt = client.Execute(fetch);
Assert.IsTrue(rslt.IsSuccess, rslt.ErrorMessage);
PreflistResponse response = fetch.Response;
Assert.IsNotNull(response);
Assert.AreEqual(3, response.Value.Count());
}
}
} | apache-2.0 | C# |
26f9b88b1292e64e0bc09e3f2f14809c93b05132 | Refactor validator | mikemajesty/coolvalidator | CoolValidator/Validator.cs | CoolValidator/Validator.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
namespace CoolValidator
{
public static class formValidator
{
public static List<TextBox> GetTextBoxInComponent<T>(this Form form, Func<TextBox, bool> predicate = null)
where T : Control
{
var txtList = new List<TextBox>();
var txtInPanel = GetTextBoxInContainer<T>(form);
var txtInManyPanel = GetTextBoxHierarchicalContainer<T>(form);
var txtInForm = GetTextBoxInForm(form);
txtList.AddRange(txtInPanel);
txtList.AddRange(txtInManyPanel);
txtList.AddRange(txtInForm);
return predicate == null ? txtList : txtList.Where(predicate).ToList();
}
private static List<TextBox> GetTextBoxInForm(Form form)
{
return form.Controls.OfType<TextBox>().Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxHierarchicalContainer<T>(Form form) where T : Control
{
return form.Controls.OfType<T>().SelectMany(groupBox => groupBox.Controls.OfType<T>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).OrderBy(t => t.TabIndex).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
private static List<TextBox> GetTextBoxInContainer<T>(Form form) where T : Control
{
return form.Controls.OfType<T>().SelectMany(groupBox => groupBox.Controls.OfType<TextBox>()).OrderBy(t => t.TabIndex).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
}
}
}
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
namespace CoolValidator
{
public static class formValidator
{
public static List<TextBox> GetTextBoxInComponent<T>(this Form form, Func<TextBox, bool> predicate = null)
where T : Control
{
var txtList = new List<TextBox>();
var txtInPanel = form.Controls.OfType<T>().SelectMany(groupBox => groupBox.Controls.OfType<TextBox>()).OrderBy(t => t.TabIndex).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
var txtInManyPanel = form.Controls.OfType<T>().SelectMany(groupBox => groupBox.Controls.OfType<T>()).SelectMany(textBox => textBox.Controls.OfType<TextBox>()).OrderBy(t => t.TabIndex).Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
var txtInForm = form.Controls.OfType<TextBox>().Where(c => string.IsNullOrEmpty(c.Text.Trim())).ToList();
txtList.AddRange(txtInPanel);
txtList.AddRange(txtInManyPanel);
txtList.AddRange(txtInForm);
return predicate == null ? txtList : txtList.Where(predicate).ToList();
}
}
}
| mit | C# |
cec143044d2626439569e9aad583515556114616 | Update NumberFormatting.cs | keith-hall/Extensions,keith-hall/Extensions | src/NumberFormatting.cs | src/NumberFormatting.cs | namespace HallLibrary.Extensions
{
public static class NumberFormatting
{
private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture
private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture
private const char _defaultThousandsSeparator = ',';
private const string _defaultDecimalSeparatorForRegex = @"\.";
public static string AddThousandsSeparators (string number, string thousandsSeparator = null) {
if (_number.IsMatch(number)) {
return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString()); // TODO: replace comma with thousands separator from current culture
} else {
return number;
}
}
/*
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X"); // doesn't add 0x prefix
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix
*/
}
}
| namespace HallLibrary.Extensions
{
public static class NumberFormatting
{
private static readonly Regex _number = new Regex(@"^-?\d+(?:" + _defaultDecimalSeparatorForRegex + @"\d+)?$"); // TODO: replace dot with decimal separator from current culture
private static readonly Regex _thousands = new Regex(@"(?<=\d)(?<!" + _defaultDecimalSeparatorForRegex + @"\d*)(?=(?:\d{3})+($|" + _defaultDecimalSeparatorForRegex + @"))"); // TODO: replace dot with decimal separator from current culture
private const char _defaultThousandsSeparator = ',';
private const string _defaultDecimalSeparatorForRegex = @"\.";
public static string AddThousandsSeparators (string number, string thousandsSeparator = null) {
if (_number.IsMatch(number)) {
return _thousands.Replace(number, thousandsSeparator ?? _defaultThousandsSeparator.ToString());
} else {
return number;
}
}
/*
// Store integer 182
int decValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = decValue.ToString("X"); // doesn't add 0x prefix
// Convert the hex string back to the number
int decAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); // doesn't cope with 0x prefix
*/
}
}
| apache-2.0 | C# |
e7cee3c63a97f7c1055040114b6b3faca1481bcf | Increment version | R-Smith/vmPing | vmPing/Properties/AssemblyInfo.cs | vmPing/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("vmPing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("vmPing")]
[assembly: AssemblyCopyright("Copyright © 2021 Ryan Smith")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.16.0")]
[assembly: AssemblyFileVersion("1.3.16.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("vmPing")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("vmPing")]
[assembly: AssemblyCopyright("Copyright © 2021 Ryan Smith")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.15.0")]
[assembly: AssemblyFileVersion("1.3.15.0")]
| mit | C# |
458255e7176b0bb6094703314fdd5a60b4ac04bc | Add comment, why check was removed | JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity | resharper/resharper-unity/src/Rider/CodeInsights/AbstractUnityCodeInsightProvider.cs | resharper/resharper-unity/src/Rider/CodeInsights/AbstractUnityCodeInsightProvider.cs | using System.Collections.Generic;
using JetBrains.Application.UI.Controls.GotoByName;
using JetBrains.Application.UI.PopupLayout;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon.CodeInsights;
using JetBrains.ReSharper.Host.Features.TextControls;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.Rider.Model;
using JetBrains.TextControl.TextControlsManagement;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights
{
public abstract class AbstractUnityCodeInsightProvider : ICodeInsightsProvider
{
public static string StartUnityActionId => "startUnity";
private readonly UnitySolutionTracker myUnitySolutionTracker;
private readonly UnityHost myHost;
private readonly BulbMenuComponent myBulbMenu;
protected AbstractUnityCodeInsightProvider(UnitySolutionTracker unitySolutionTracker, UnityHost host, BulbMenuComponent bulbMenu)
{
myUnitySolutionTracker = unitySolutionTracker;
myHost = host;
myBulbMenu = bulbMenu;
}
public void OnClick(CodeInsightsHighlighting highlighting, ISolution solution)
{
var windowContextSource = new PopupWindowContextSource(
lt => new HostTextControlPopupWindowContext(lt,
highlighting.DeclaredElement.GetSolution().GetComponent<TextControlManager>().LastFocusedTextControl
.Value).MarkAsOriginatedFromDataContext());
if (highlighting is UnityCodeInsightsHighlighting unityCodeInsightsHighlighting)
{
if (unityCodeInsightsHighlighting.MenuItems.Count > 0)
myBulbMenu.ShowBulbMenu(unityCodeInsightsHighlighting.MenuItems, windowContextSource);
}
}
public void OnExtraActionClick(CodeInsightsHighlighting highlighting, string actionId, ISolution solution)
{
if (actionId.Equals(StartUnityActionId))
{
myHost.PerformModelAction(model => model.StartUnity());
}
}
// TODO: Fix sdk and add correct check
// We could not check that our provider is available while solution is loading, because user could add Unity Engine
// reference later. wait sdk update
public bool IsAvailableIn(ISolution solution) => true;
public abstract string ProviderId { get; }
public abstract string DisplayName { get; }
public abstract CodeLensAnchorKind DefaultAnchor { get; }
public abstract ICollection<CodeLensRelativeOrdering> RelativeOrderings { get; }
}
} | using System.Collections.Generic;
using JetBrains.Application.UI.Controls.GotoByName;
using JetBrains.Application.UI.PopupLayout;
using JetBrains.Collections.Viewable;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Daemon.CodeInsights;
using JetBrains.ReSharper.Host.Features.TextControls;
using JetBrains.ReSharper.Plugins.Unity.ProjectModel;
using JetBrains.ReSharper.Psi;
using JetBrains.Rider.Model;
using JetBrains.TextControl.TextControlsManagement;
namespace JetBrains.ReSharper.Plugins.Unity.Rider.CodeInsights
{
public abstract class AbstractUnityCodeInsightProvider : ICodeInsightsProvider
{
public static string StartUnityActionId => "startUnity";
private readonly UnitySolutionTracker myUnitySolutionTracker;
private readonly UnityHost myHost;
private readonly BulbMenuComponent myBulbMenu;
protected AbstractUnityCodeInsightProvider(UnitySolutionTracker unitySolutionTracker, UnityHost host, BulbMenuComponent bulbMenu)
{
myUnitySolutionTracker = unitySolutionTracker;
myHost = host;
myBulbMenu = bulbMenu;
}
public void OnClick(CodeInsightsHighlighting highlighting, ISolution solution)
{
var windowContextSource = new PopupWindowContextSource(
lt => new HostTextControlPopupWindowContext(lt,
highlighting.DeclaredElement.GetSolution().GetComponent<TextControlManager>().LastFocusedTextControl
.Value).MarkAsOriginatedFromDataContext());
if (highlighting is UnityCodeInsightsHighlighting unityCodeInsightsHighlighting)
{
if (unityCodeInsightsHighlighting.MenuItems.Count > 0)
myBulbMenu.ShowBulbMenu(unityCodeInsightsHighlighting.MenuItems, windowContextSource);
}
}
public void OnExtraActionClick(CodeInsightsHighlighting highlighting, string actionId, ISolution solution)
{
if (actionId.Equals(StartUnityActionId))
{
myHost.PerformModelAction(model => model.StartUnity());
}
}
public bool IsAvailableIn(ISolution solution) => true;
public abstract string ProviderId { get; }
public abstract string DisplayName { get; }
public abstract CodeLensAnchorKind DefaultAnchor { get; }
public abstract ICollection<CodeLensRelativeOrdering> RelativeOrderings { get; }
}
} | apache-2.0 | C# |
84b2874e8c22bbf4bd944fa5d76408b8ecdda461 | Use RunClassConstructor to initialize templates | sebastienros/fluid | Fluid/BaseFluidTemplate.cs | Fluid/BaseFluidTemplate.cs | using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid.Ast;
namespace Fluid
{
public class BaseFluidTemplate<T> : IFluidTemplate where T : IFluidTemplate, new()
{
static BaseFluidTemplate()
{
// Necessary to force the custom template class static constructor
// as the only member accessed is defined on this class
System.Runtime.CompilerServices.RuntimeHelpers.RunClassConstructor(typeof(T).TypeHandle);
}
public static FluidParserFactory Factory { get; } = new FluidParserFactory();
public IList<Statement> Statements { get; set; } = new List<Statement>();
public static bool TryParse(string template, out T result, out IEnumerable<string> errors)
{
if (Factory.CreateParser().TryParse(template, out var statements, out errors))
{
result = new T();
result.Statements = statements;
return true;
}
else
{
result = default(T);
return false;
}
}
public static bool TryParse(string template, out T result)
{
return TryParse(template, out result, out var errors);
}
public async Task RenderAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
{
foreach (var statement in Statements)
{
await statement.WriteToAsync(writer, encoder, context);
}
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Text.Encodings.Web;
using System.Threading.Tasks;
using Fluid.Ast;
namespace Fluid
{
public class BaseFluidTemplate<T> : IFluidTemplate where T : IFluidTemplate, new()
{
static BaseFluidTemplate()
{
// Necessary to force the custom template class static constructor
// c.f. https://github.com/sebastienros/fluid/issues/19
new T();
}
public static FluidParserFactory Factory { get; } = new FluidParserFactory();
public IList<Statement> Statements { get; set; } = new List<Statement>();
public static bool TryParse(string template, out T result, out IEnumerable<string> errors)
{
if (Factory.CreateParser().TryParse(template, out var statements, out errors))
{
result = new T();
result.Statements = statements;
return true;
}
else
{
result = default(T);
return false;
}
}
public static bool TryParse(string template, out T result)
{
return TryParse(template, out result, out var errors);
}
public async Task RenderAsync(TextWriter writer, TextEncoder encoder, TemplateContext context)
{
foreach (var statement in Statements)
{
await statement.WriteToAsync(writer, encoder, context);
}
}
}
}
| mit | C# |
eba668d14acb981156312c62f5beafe796f0409f | Make Greeter sample calls more obvious (#208) | grpc/grpc-dotnet,grpc/grpc-dotnet,grpc/grpc-dotnet,grpc/grpc-dotnet | examples/Clients/Greeter/Program.cs | examples/Clients/Greeter/Program.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;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Greet;
using Grpc.Core;
namespace Sample.Clients
{
class Program
{
static async Task Main(string[] args)
{
// Server will only support Https on Windows and Linux
var credentials = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ChannelCredentials.Insecure : ClientResources.SslCredentials;
var channel = new Channel("localhost:50051", credentials);
var client = new Greeter.GreeterClient(channel);
await UnaryCallExample(client);
await ServerStreamingCallExample(client);
Console.WriteLine("Shutting down");
await channel.ShutdownAsync();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
private static async Task UnaryCallExample(Greeter.GreeterClient client)
{
var reply = await client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + reply.Message);
}
private static async Task ServerStreamingCallExample(Greeter.GreeterClient client)
{
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(3.5));
var replies = client.SayHellos(new HelloRequest { Name = "GreeterClient" }, cancellationToken: cts.Token);
try
{
while (await replies.ResponseStream.MoveNext(cts.Token))
{
Console.WriteLine("Greeting: " + replies.ResponseStream.Current.Message);
}
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
Console.WriteLine("Stream cancelled.");
}
}
}
}
| #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;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using Common;
using Greet;
using Grpc.Core;
namespace Sample.Clients
{
class Program
{
static async Task Main(string[] args)
{
// Server will only support Https on Windows and Linux
var credentials = RuntimeInformation.IsOSPlatform(OSPlatform.OSX) ? ChannelCredentials.Insecure : ClientResources.SslCredentials;
var channel = new Channel("localhost:50051", credentials);
var client = new Greeter.GreeterClient(channel);
var reply = client.SayHelloAsync(new HelloRequest { Name = "GreeterClient" });
Console.WriteLine("Greeting: " + (await reply.ResponseAsync).Message);
var cts = new CancellationTokenSource();
cts.CancelAfter(TimeSpan.FromSeconds(3.5));
var replies = client.SayHellos(new HelloRequest { Name = "GreeterClient" }, cancellationToken: cts.Token);
try
{
while (await replies.ResponseStream.MoveNext(cts.Token))
{
Console.WriteLine("Greeting: " + replies.ResponseStream.Current.Message);
}
}
catch (RpcException ex) when (ex.StatusCode == StatusCode.Cancelled)
{
Console.WriteLine("Stream cancelled.");
}
Console.WriteLine("Shutting down");
await channel.ShutdownAsync();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
| apache-2.0 | C# |
ee974c25411677a20a78fb0e617a9a3dc84c31d9 | Improve git manipulator. | exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests,exKAZUu/ParserTests | ParserTests/Git.cs | ParserTests/Git.cs | #region License
// Copyright (C) 2011-2014 Kazunori Sakamoto
//
// 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;
using System.IO;
using System.Linq;
using LibGit2Sharp;
namespace ParserTests {
public static class Git {
public static void CloneAndCheckout(string repoPath, string url, string commitPointer) {
Directory.CreateDirectory(repoPath);
if (Directory.GetDirectories(repoPath).Length + Directory.GetFiles(repoPath).Length <= 1) {
Directory.Delete(repoPath, true);
Directory.CreateDirectory(repoPath);
Clone(repoPath, url, commitPointer);
}
Checkout(repoPath, commitPointer);
}
public static void Clone(string repoPath, string url, string commitPointer) {
Console.Write("Cloning ...");
Repository.Clone(url, repoPath);
Console.WriteLine(" done");
Checkout(repoPath, commitPointer);
}
public static string Checkout(string repoPath, string commitPointer) {
using (var repo = new Repository(repoPath)) {
if (!repo.Commits.Any() || !repo.Commits.First().Sha.StartsWith(commitPointer)) {
repo.RemoveUntrackedFiles();
repo.Reset(ResetMode.Hard);
repo.Checkout(commitPointer);
}
}
return repoPath;
}
}
} | #region License
// Copyright (C) 2011-2014 Kazunori Sakamoto
//
// 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;
using System.IO;
using System.Linq;
using LibGit2Sharp;
namespace ParserTests {
public static class Git {
public static void CloneAndCheckout(string repoPath, string url, string commitPointer) {
if (!Directory.GetDirectories(repoPath).Any()) {
Clone(repoPath, url, commitPointer);
}
Checkout(repoPath, commitPointer);
}
public static void Clone(string repoPath, string url, string commitPointer) {
Console.Write("Cloning ...");
Repository.Clone(url, repoPath);
Console.WriteLine(" done");
Checkout(repoPath, commitPointer);
}
public static string Checkout(string repoPath, string commitPointer) {
using (var repo = new Repository(repoPath)) {
if (!repo.Commits.Any() || !repo.Commits.First().Sha.StartsWith(commitPointer)) {
repo.RemoveUntrackedFiles();
repo.Reset(ResetMode.Hard);
repo.Checkout(commitPointer);
}
}
return repoPath;
}
}
} | apache-2.0 | C# |
1c80e1db711b767c28c8a0a3a4ca636372b16324 | update client so that it can return unit-based leave categories | KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet | src/keypay-dotnet/Enums/LeaveAllowanceUnit.cs | src/keypay-dotnet/Enums/LeaveAllowanceUnit.cs | namespace KeyPay.Enums
{
public enum LeaveAllowanceUnit
{
Days = 1,
Weeks = 2,
HoursPerHourWorked = 3,
HoursPerPayRun = 4,
StandardDays = 5,
StandardWeeks = 6,
}
} | namespace KeyPay.Enums
{
public enum LeaveAllowanceUnit
{
Days = 1,
Weeks = 2,
HoursPerHourWorked = 3,
HoursPerPayRun = 4
}
} | mit | C# |
c92759f3ae2436a62986b2847e0e5907733d94cc | Update flags | killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity | Assets/MRTK/SDK/Experimental/Dialog/Scripts/DialogButtonType.cs | Assets/MRTK/SDK/Experimental/Dialog/Scripts/DialogButtonType.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.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Experimental.Dialog
{
/// <summary>
/// Enum describing the style (caption) of button on a Dialog.
/// </summary>
[Flags]
public enum DialogButtonType
{
None = 0 << 0,
Close = 1 << 0,
Confirm = 1 << 1,
Cancel = 1 << 2,
Accept = 1 << 3,
Yes = 1 << 4,
No = 1 << 5,
OK = 1 << 6
}
} | //
// 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.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Experimental.Dialog
{
/// <summary>
/// Enum describing the style (caption) of button on a Dialog.
/// </summary>
[Flags]
public enum DialogButtonType
{
None = 0,
Close = 1,
Confirm = 2,
Cancel = 4,
Accept = 8,
Yes = 16,
No = 32,
OK = 64
}
} | mit | C# |
e6e600ab4181ed6a78aa444de5cfafa8fc67eaa5 | Add optimizations to problem 10 | PlamenNeshkov/Advanced-CSharp | BasicDataStructures/10.PythagoreanNumbers/PythagoreanNumbers.cs | BasicDataStructures/10.PythagoreanNumbers/PythagoreanNumbers.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10.PythagoreanNumbers
{
class PythagoreanNumbers
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] nums = new int[n];
for (int i = 0; i < n; i++)
{
nums[i] = int.Parse(Console.ReadLine());
}
Array.Sort(nums);
bool any = false;
for (int a = 0; a < n; a++)
{
for (int b = a; b < n; b++)
{
for (int c = b; c < n; c++)
{
if (a <= b && (nums[a] * nums[a] + nums[b] * nums[b] == nums[c] * nums[c]))
{
Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", nums[a], nums[b], nums[c]);
any = true;
}
}
}
}
if (!any)
{
Console.WriteLine("No");
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _10.PythagoreanNumbers
{
class PythagoreanNumbers
{
static void Main(string[] args)
{
int n = int.Parse(Console.ReadLine());
int[] nums = new int[n];
for (int i = 0; i < n; i++)
{
nums[i] = int.Parse(Console.ReadLine());
}
Array.Sort(nums);
bool any = false;
for (int a = 0; a < n; a++)
{
for (int b = 0; b < n; b++)
{
for (int c = 0; c < n; c++)
{
if (a < b && (nums[a] * nums[a] + nums[b] * nums[b] == nums[c] * nums[c]))
{
Console.WriteLine("{0}*{0} + {1}*{1} = {2}*{2}", nums[a], nums[b], nums[c]);
any = true;
}
}
}
}
if (!any)
{
Console.WriteLine("No");
}
}
}
}
| mit | C# |
6124aa232f587f5a0129b032c3b73da89b40b109 | Modify default TimestampPolicy. | ilya-chumakov/LoggingAdvanced | Bodrocode.LoggingAdvanced.Console/Timestamps/TimestampPolicy.cs | Bodrocode.LoggingAdvanced.Console/Timestamps/TimestampPolicy.cs | namespace Bodrocode.LoggingAdvanced.Console.Timestamps
{
public class TimestampPolicy
{
public TimestampPolicy()
{
Format = "yyyy.MM.dd HH:mm:ss";
TimeZone = "Local";
}
/// <summary>
/// Custom output format https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
/// </summary>
public string Format { get; set; }
/// <summary>
/// Support for "Local" value and timezones from https://msdn.microsoft.com/en-us/library/gg154758.aspx
/// </summary>
public string TimeZone { get; set; }
}
} | namespace Bodrocode.LoggingAdvanced.Console.Timestamps
{
public class TimestampPolicy
{
public TimestampPolicy()
{
Format = null;
TimeZone = "Local";
}
/// <summary>
/// Custom output format https://docs.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings
/// </summary>
public string Format { get; set; }
/// <summary>
/// Support for "Local" value and timezones from https://msdn.microsoft.com/en-us/library/gg154758.aspx
/// </summary>
public string TimeZone { get; set; }
}
} | apache-2.0 | C# |
4d306ef837884ea75337a5ea80e68e50e8e1a6be | Add comments and clean up code. | peppy/osu,smoogipoo/osu,ppy/osu,naoey/osu,peppy/osu-new,johnneijzen/osu,peppy/osu,ppy/osu,naoey/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,naoey/osu,ZLima12/osu,smoogipooo/osu,NeoAdonis/osu,ZLima12/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,DrabWeb/osu,DrabWeb/osu,DrabWeb/osu,NeoAdonis/osu | osu.Game.Rulesets.Osu/Mods/OsuModArrange.cs | osu.Game.Rulesets.Osu/Mods/OsuModArrange.cs | using System;
using System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModArrange : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Arrange";
public override string ShortenedName => "Arrange";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.DifficultyIncrease;
public override string Description => "Everything rotates. EVERYTHING";
public override bool Ranked => true;
public override double ScoreMultiplier => 1.05;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable => drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState);
}
private float theta = 0;
private void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
var hitObject = (OsuHitObject) drawable.HitObject;
// repeat points get their position data from the slider.
if (hitObject is RepeatPoint)
return;
Vector2 originalPosition = drawable.Position;
// avoiding that the player can see the abroupt move.
const int pre_time_offset = 1000;
using (drawable.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimeFadeIn - pre_time_offset, true))
{
drawable
.MoveToOffset(new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * 250)
.MoveTo(originalPosition, hitObject.TimeFadeIn + pre_time_offset, Easing.InOutSine);
}
// That way slider ticks come all from the same direction.
if (hitObject is HitCircle || hitObject is Slider)
theta += 0.4f;
}
}
}
| using System;
using System.Collections.Generic;
using osu.Framework.Extensions.IEnumerableExtensions;
using osu.Framework.Graphics;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects;
using OpenTK;
namespace osu.Game.Rulesets.Osu.Mods
{
internal class OsuModArrange : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Arrange";
public override string ShortenedName => "Arrange";
public override FontAwesome Icon => FontAwesome.fa_arrows;
public override ModType Type => ModType.DifficultyIncrease;
public override string Description => "Everything rotates. EVERYTHING";
public override bool Ranked => true;
public override double ScoreMultiplier => 1.05;
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
drawables.ForEach(drawable => drawable.ApplyCustomUpdateState += drawableOnApplyCustomUpdateState);
}
private float theta = 0;
private void drawableOnApplyCustomUpdateState(DrawableHitObject drawable, ArmedState state)
{
var hitObject = (OsuHitObject) drawable.HitObject;
Vector2 origPos;
if (hitObject is RepeatPoint rp)
{
return;
}
else
{
origPos = drawable.Position;
}
using (drawable.BeginAbsoluteSequence(hitObject.StartTime - hitObject.TimeFadeIn - 1000, true))
{
drawable
.MoveToOffset(new Vector2((float)Math.Cos(theta), (float)Math.Sin(theta)) * 250)
.MoveTo(origPos, hitObject.TimeFadeIn + 1000, Easing.InOutSine);
}
if (hitObject is HitCircle || hitObject is Slider)
theta += 0.4f;
}
}
}
| mit | C# |
cfefea75ac9988771214be1ab18eeaf5589dac49 | Support Base64 (1) | codetuner/Arebis.Common | Arebis.Common/Arebis/Numerics/SymbolicNumeralSystem.cs | Arebis.Common/Arebis/Numerics/SymbolicNumeralSystem.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Arebis.Numerics
{
/// <summary>
/// Base class for numeral systems that have symbols to represent unitary values.
/// </summary>
[DataContract]
[Serializable]
public abstract class SymbolicNumeralSystem : NumeralSystem
{
/// <summary>
/// Creates a numeral system using given symbols.
/// </summary>
protected SymbolicNumeralSystem(string symbols)
: this(symbols.Length, symbols)
{ }
/// <summary>
/// Creates a numeral system for a base up to 64 with symbolic representation.
/// </summary>
/// <param name="base">Base of the numeral system, max 64.</param>
protected SymbolicNumeralSystem(int @base)
: this(@base, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/")
{ }
private SymbolicNumeralSystem(int @base, string symbols)
: base(@base)
{
if (@base > symbols.Length)
throw new ArgumentException("SymbolicNumeralSystem with base x requires a symbols string with at least x symbols.");
this.Symbols = symbols.Substring(0, @base);
}
/// <summary>
/// The symbols of the numeral system.
/// </summary>
[DataMember]
public string Symbols { get; private set; }
public override char GetSymbolFor(int value)
{
return this.Symbols[value % this.Base];
}
public override int GetValueForSymbol(char symbol)
{
return this.Symbols.IndexOf(symbol);
}
/// <summary>
/// Returns a string representation of the given value expressed in this numeral system.
/// </summary>
public override string ValueToString(string value)
{
return value;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace Arebis.Numerics
{
/// <summary>
/// Base class for numeral systems that have symbols to represent unitary values.
/// </summary>
[DataContract]
[Serializable]
public abstract class SymbolicNumeralSystem : NumeralSystem
{
/// <summary>
/// Creates a numeral system using given symbols.
/// </summary>
protected SymbolicNumeralSystem(string symbols)
: this(symbols.Length, symbols)
{ }
/// <summary>
/// Creates a numeral system for a base up to 62 with symbolic representation.
/// </summary>
/// <param name="base">Base of the numeral system, max 62.</param>
protected SymbolicNumeralSystem(int @base)
: this(@base, "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz")
{ }
private SymbolicNumeralSystem(int @base, string symbols)
: base(@base)
{
if (@base > symbols.Length)
throw new ArgumentException("SymbolicNumeralSystem with base x requires a symbols string with at least x symbols.");
this.Symbols = symbols.Substring(0, @base);
}
/// <summary>
/// The symbols of the numeral system.
/// </summary>
[DataMember]
public string Symbols { get; private set; }
public override char GetSymbolFor(int value)
{
return this.Symbols[value % this.Base];
}
public override int GetValueForSymbol(char symbol)
{
return this.Symbols.IndexOf(symbol);
}
/// <summary>
/// Returns a string representation of the given value expressed in this numeral system.
/// </summary>
public override string ValueToString(string value)
{
return value;
}
}
}
| mit | C# |
aefbbad423132dfa26c0264c4491acbd79c61a70 | Add missed paren in comment. | ViktorHofer/corefx,n1ghtmare/corefx,KrisLee/corefx,larsbj1988/corefx,rjxby/corefx,vidhya-bv/corefx-sorting,CherryCxldn/corefx,tijoytom/corefx,Frank125/corefx,cydhaselton/corefx,huanjie/corefx,DnlHarvey/corefx,parjong/corefx,PatrickMcDonald/corefx,fernando-rodriguez/corefx,n1ghtmare/corefx,benpye/corefx,the-dwyer/corefx,erpframework/corefx,popolan1986/corefx,rubo/corefx,shahid-pk/corefx,MaggieTsang/corefx,ptoonen/corefx,twsouthwick/corefx,SGuyGe/corefx,Jiayili1/corefx,MaggieTsang/corefx,uhaciogullari/corefx,YoupHulsebos/corefx,janhenke/corefx,comdiv/corefx,VPashkov/corefx,tijoytom/corefx,manu-silicon/corefx,tstringer/corefx,nchikanov/corefx,billwert/corefx,alphonsekurian/corefx,marksmeltzer/corefx,krk/corefx,axelheer/corefx,viniciustaveira/corefx,scott156/corefx,mmitche/corefx,mellinoe/corefx,dotnet-bot/corefx,Petermarcu/corefx,PatrickMcDonald/corefx,stormleoxia/corefx,DnlHarvey/corefx,Jiayili1/corefx,Ermiar/corefx,SGuyGe/corefx,shimingsg/corefx,fgreinacher/corefx,krk/corefx,khdang/corefx,vijaykota/corefx,vidhya-bv/corefx-sorting,fgreinacher/corefx,dsplaisted/corefx,zmaruo/corefx,mellinoe/corefx,manu-silicon/corefx,zmaruo/corefx,jlin177/corefx,lydonchandra/corefx,matthubin/corefx,ravimeda/corefx,rahku/corefx,dotnet-bot/corefx,wtgodbe/corefx,jhendrixMSFT/corefx,ViktorHofer/corefx,mmitche/corefx,manu-silicon/corefx,CherryCxldn/corefx,billwert/corefx,rubo/corefx,pallavit/corefx,marksmeltzer/corefx,dotnet-bot/corefx,axelheer/corefx,ravimeda/corefx,stephenmichaelf/corefx,richlander/corefx,marksmeltzer/corefx,rahku/corefx,mellinoe/corefx,alexperovich/corefx,krk/corefx,nelsonsar/corefx,manu-silicon/corefx,Frank125/corefx,akivafr123/corefx,lggomez/corefx,nchikanov/corefx,iamjasonp/corefx,uhaciogullari/corefx,khdang/corefx,mazong1123/corefx,zhangwenquan/corefx,twsouthwick/corefx,claudelee/corefx,bitcrazed/corefx,mmitche/corefx,zhenlan/corefx,shimingsg/corefx,dtrebbien/corefx,zhenlan/corefx,mokchhya/corefx,ptoonen/corefx,kkurni/corefx,ericstj/corefx,fgreinacher/corefx,alexperovich/corefx,shahid-pk/corefx,dsplaisted/corefx,jhendrixMSFT/corefx,n1ghtmare/corefx,jcme/corefx,jmhardison/corefx,iamjasonp/corefx,jlin177/corefx,richlander/corefx,arronei/corefx,pallavit/corefx,kyulee1/corefx,dotnet-bot/corefx,gkhanna79/corefx,dotnet-bot/corefx,tijoytom/corefx,elijah6/corefx,Priya91/corefx-1,zhangwenquan/corefx,oceanho/corefx,kkurni/corefx,yizhang82/corefx,Yanjing123/corefx,weltkante/corefx,benjamin-bader/corefx,pallavit/corefx,jeremymeng/corefx,tijoytom/corefx,cartermp/corefx,rjxby/corefx,wtgodbe/corefx,oceanho/corefx,lggomez/corefx,stone-li/corefx,benjamin-bader/corefx,chenxizhang/corefx,brett25/corefx,chaitrakeshav/corefx,tstringer/corefx,Alcaro/corefx,richlander/corefx,weltkante/corefx,pgavlin/corefx,seanshpark/corefx,zhangwenquan/corefx,Priya91/corefx-1,s0ne0me/corefx,pgavlin/corefx,chaitrakeshav/corefx,tstringer/corefx,uhaciogullari/corefx,shmao/corefx,VPashkov/corefx,chenkennt/corefx,krk/corefx,lydonchandra/corefx,dtrebbien/corefx,gkhanna79/corefx,jeremymeng/corefx,mafiya69/corefx,fgreinacher/corefx,s0ne0me/corefx,Chrisboh/corefx,billwert/corefx,lydonchandra/corefx,brett25/corefx,Petermarcu/corefx,JosephTremoulet/corefx,elijah6/corefx,shiftkey-tester/corefx,shrutigarg/corefx,marksmeltzer/corefx,mazong1123/corefx,vijaykota/corefx,SGuyGe/corefx,BrennanConroy/corefx,twsouthwick/corefx,nbarbettini/corefx,dtrebbien/corefx,rahku/corefx,stone-li/corefx,shahid-pk/corefx,cnbin/corefx,tstringer/corefx,josguil/corefx,ravimeda/corefx,gkhanna79/corefx,vidhya-bv/corefx-sorting,VPashkov/corefx,spoiledsport/corefx,FiveTimesTheFun/corefx,vs-team/corefx,Petermarcu/corefx,Jiayili1/corefx,benjamin-bader/corefx,EverlessDrop41/corefx,ericstj/corefx,erpframework/corefx,destinyclown/corefx,nbarbettini/corefx,shmao/corefx,bpschoch/corefx,ViktorHofer/corefx,marksmeltzer/corefx,shimingsg/corefx,iamjasonp/corefx,BrennanConroy/corefx,690486439/corefx,kkurni/corefx,lydonchandra/corefx,elijah6/corefx,KrisLee/corefx,janhenke/corefx,popolan1986/corefx,nbarbettini/corefx,mafiya69/corefx,DnlHarvey/corefx,janhenke/corefx,dkorolev/corefx,mokchhya/corefx,ellismg/corefx,jhendrixMSFT/corefx,nchikanov/corefx,khdang/corefx,chaitrakeshav/corefx,the-dwyer/corefx,yizhang82/corefx,ViktorHofer/corefx,MaggieTsang/corefx,JosephTremoulet/corefx,heXelium/corefx,690486439/corefx,stephenmichaelf/corefx,oceanho/corefx,rajansingh10/corefx,dkorolev/corefx,yizhang82/corefx,vrassouli/corefx,alphonsekurian/corefx,uhaciogullari/corefx,alexandrnikitin/corefx,krytarowski/corefx,yizhang82/corefx,dhoehna/corefx,manu-silicon/corefx,benpye/corefx,alexandrnikitin/corefx,jlin177/corefx,Petermarcu/corefx,tstringer/corefx,jmhardison/corefx,huanjie/corefx,Petermarcu/corefx,mazong1123/corefx,claudelee/corefx,ptoonen/corefx,EverlessDrop41/corefx,alphonsekurian/corefx,KrisLee/corefx,manu-silicon/corefx,the-dwyer/corefx,rahku/corefx,shana/corefx,parjong/corefx,larsbj1988/corefx,dhoehna/corefx,gkhanna79/corefx,iamjasonp/corefx,SGuyGe/corefx,adamralph/corefx,stephenmichaelf/corefx,janhenke/corefx,gkhanna79/corefx,huanjie/corefx,zhenlan/corefx,manu-silicon/corefx,viniciustaveira/corefx,benpye/corefx,zhenlan/corefx,chenkennt/corefx,shmao/corefx,fffej/corefx,twsouthwick/corefx,shahid-pk/corefx,dotnet-bot/corefx,jlin177/corefx,Ermiar/corefx,stephenmichaelf/corefx,ptoonen/corefx,dsplaisted/corefx,benjamin-bader/corefx,Winsto/corefx,jmhardison/corefx,Priya91/corefx-1,axelheer/corefx,ericstj/corefx,nelsonsar/corefx,wtgodbe/corefx,viniciustaveira/corefx,cydhaselton/corefx,Frank125/corefx,krytarowski/corefx,shmao/corefx,shiftkey-tester/corefx,matthubin/corefx,alexandrnikitin/corefx,parjong/corefx,shmao/corefx,tstringer/corefx,Chrisboh/corefx,iamjasonp/corefx,Priya91/corefx-1,MaggieTsang/corefx,DnlHarvey/corefx,alphonsekurian/corefx,rahku/corefx,YoupHulsebos/corefx,YoupHulsebos/corefx,seanshpark/corefx,cartermp/corefx,huanjie/corefx,alphonsekurian/corefx,ericstj/corefx,stone-li/corefx,axelheer/corefx,brett25/corefx,vidhya-bv/corefx-sorting,mellinoe/corefx,stormleoxia/corefx,vrassouli/corefx,misterzik/corefx,billwert/corefx,arronei/corefx,gabrielPeart/corefx,PatrickMcDonald/corefx,zhenlan/corefx,rjxby/corefx,anjumrizwi/corefx,josguil/corefx,PatrickMcDonald/corefx,alexperovich/corefx,gregg-miskelly/corefx,yizhang82/corefx,EverlessDrop41/corefx,Chrisboh/corefx,mmitche/corefx,parjong/corefx,dhoehna/corefx,richlander/corefx,mmitche/corefx,nelsonsar/corefx,mmitche/corefx,alphonsekurian/corefx,Winsto/corefx,bpschoch/corefx,weltkante/corefx,DnlHarvey/corefx,krk/corefx,mazong1123/corefx,janhenke/corefx,s0ne0me/corefx,krytarowski/corefx,vs-team/corefx,n1ghtmare/corefx,cartermp/corefx,jcme/corefx,pgavlin/corefx,lggomez/corefx,cnbin/corefx,lggomez/corefx,krytarowski/corefx,xuweixuwei/corefx,Winsto/corefx,seanshpark/corefx,yizhang82/corefx,andyhebear/corefx,stone-li/corefx,destinyclown/corefx,Alcaro/corefx,benpye/corefx,comdiv/corefx,akivafr123/corefx,VPashkov/corefx,cartermp/corefx,matthubin/corefx,stormleoxia/corefx,jhendrixMSFT/corefx,cydhaselton/corefx,zmaruo/corefx,tijoytom/corefx,mellinoe/corefx,ptoonen/corefx,chenkennt/corefx,axelheer/corefx,xuweixuwei/corefx,ericstj/corefx,jeremymeng/corefx,Jiayili1/corefx,scott156/corefx,thiagodin/corefx,MaggieTsang/corefx,shimingsg/corefx,FiveTimesTheFun/corefx,scott156/corefx,Yanjing123/corefx,seanshpark/corefx,Jiayili1/corefx,mokchhya/corefx,pallavit/corefx,mellinoe/corefx,shiftkey-tester/corefx,kyulee1/corefx,rajansingh10/corefx,shiftkey-tester/corefx,axelheer/corefx,chenxizhang/corefx,the-dwyer/corefx,ellismg/corefx,dkorolev/corefx,Chrisboh/corefx,josguil/corefx,cartermp/corefx,Chrisboh/corefx,shrutigarg/corefx,fernando-rodriguez/corefx,Jiayili1/corefx,nchikanov/corefx,heXelium/corefx,oceanho/corefx,elijah6/corefx,jeremymeng/corefx,MaggieTsang/corefx,Frank125/corefx,zhenlan/corefx,heXelium/corefx,rjxby/corefx,marksmeltzer/corefx,weltkante/corefx,stephenmichaelf/corefx,bitcrazed/corefx,heXelium/corefx,nbarbettini/corefx,ViktorHofer/corefx,shrutigarg/corefx,weltkante/corefx,kkurni/corefx,shrutigarg/corefx,ptoonen/corefx,nelsonsar/corefx,vs-team/corefx,parjong/corefx,nchikanov/corefx,s0ne0me/corefx,jlin177/corefx,elijah6/corefx,nbarbettini/corefx,pallavit/corefx,cydhaselton/corefx,CherryCxldn/corefx,stephenmichaelf/corefx,gabrielPeart/corefx,jhendrixMSFT/corefx,zhenlan/corefx,the-dwyer/corefx,janhenke/corefx,erpframework/corefx,ravimeda/corefx,claudelee/corefx,YoupHulsebos/corefx,billwert/corefx,lggomez/corefx,Priya91/corefx-1,jmhardison/corefx,thiagodin/corefx,stone-li/corefx,Ermiar/corefx,dkorolev/corefx,chaitrakeshav/corefx,rubo/corefx,weltkante/corefx,iamjasonp/corefx,richlander/corefx,josguil/corefx,ericstj/corefx,ravimeda/corefx,YoupHulsebos/corefx,gkhanna79/corefx,Alcaro/corefx,JosephTremoulet/corefx,vijaykota/corefx,mazong1123/corefx,mafiya69/corefx,cydhaselton/corefx,mazong1123/corefx,mokchhya/corefx,pgavlin/corefx,shmao/corefx,rajansingh10/corefx,mokchhya/corefx,stephenmichaelf/corefx,comdiv/corefx,Alcaro/corefx,FiveTimesTheFun/corefx,mmitche/corefx,krytarowski/corefx,ericstj/corefx,josguil/corefx,shimingsg/corefx,khdang/corefx,elijah6/corefx,YoupHulsebos/corefx,krk/corefx,brett25/corefx,gregg-miskelly/corefx,rajansingh10/corefx,matthubin/corefx,ellismg/corefx,ellismg/corefx,billwert/corefx,erpframework/corefx,cnbin/corefx,alexperovich/corefx,bpschoch/corefx,krytarowski/corefx,rahku/corefx,thiagodin/corefx,anjumrizwi/corefx,shahid-pk/corefx,andyhebear/corefx,fernando-rodriguez/corefx,jcme/corefx,shimingsg/corefx,benjamin-bader/corefx,CloudLens/corefx,zmaruo/corefx,zhangwenquan/corefx,andyhebear/corefx,larsbj1988/corefx,nchikanov/corefx,ravimeda/corefx,billwert/corefx,gabrielPeart/corefx,misterzik/corefx,popolan1986/corefx,scott156/corefx,seanshpark/corefx,akivafr123/corefx,anjumrizwi/corefx,akivafr123/corefx,richlander/corefx,wtgodbe/corefx,andyhebear/corefx,destinyclown/corefx,ravimeda/corefx,rjxby/corefx,Ermiar/corefx,seanshpark/corefx,gkhanna79/corefx,twsouthwick/corefx,CloudLens/corefx,PatrickMcDonald/corefx,nbarbettini/corefx,bitcrazed/corefx,Ermiar/corefx,tijoytom/corefx,wtgodbe/corefx,cydhaselton/corefx,Jiayili1/corefx,cnbin/corefx,Ermiar/corefx,rahku/corefx,seanshpark/corefx,ellismg/corefx,akivafr123/corefx,spoiledsport/corefx,Yanjing123/corefx,nchikanov/corefx,rubo/corefx,BrennanConroy/corefx,mafiya69/corefx,shmao/corefx,mazong1123/corefx,shana/corefx,shahid-pk/corefx,gregg-miskelly/corefx,KrisLee/corefx,JosephTremoulet/corefx,vs-team/corefx,xuweixuwei/corefx,bpschoch/corefx,Priya91/corefx-1,stone-li/corefx,MaggieTsang/corefx,jhendrixMSFT/corefx,mokchhya/corefx,vrassouli/corefx,elijah6/corefx,cydhaselton/corefx,ViktorHofer/corefx,JosephTremoulet/corefx,richlander/corefx,vidhya-bv/corefx-sorting,the-dwyer/corefx,benjamin-bader/corefx,DnlHarvey/corefx,khdang/corefx,mafiya69/corefx,wtgodbe/corefx,bitcrazed/corefx,weltkante/corefx,rjxby/corefx,spoiledsport/corefx,JosephTremoulet/corefx,n1ghtmare/corefx,misterzik/corefx,690486439/corefx,stormleoxia/corefx,larsbj1988/corefx,the-dwyer/corefx,krk/corefx,rubo/corefx,jcme/corefx,thiagodin/corefx,benpye/corefx,jlin177/corefx,dhoehna/corefx,CloudLens/corefx,shimingsg/corefx,SGuyGe/corefx,jcme/corefx,gabrielPeart/corefx,jlin177/corefx,CloudLens/corefx,Ermiar/corefx,fffej/corefx,marksmeltzer/corefx,twsouthwick/corefx,kyulee1/corefx,cartermp/corefx,jeremymeng/corefx,pallavit/corefx,mafiya69/corefx,690486439/corefx,alexandrnikitin/corefx,yizhang82/corefx,parjong/corefx,alphonsekurian/corefx,Yanjing123/corefx,dotnet-bot/corefx,dhoehna/corefx,alexperovich/corefx,iamjasonp/corefx,jcme/corefx,claudelee/corefx,Petermarcu/corefx,josguil/corefx,dhoehna/corefx,rjxby/corefx,bitcrazed/corefx,comdiv/corefx,adamralph/corefx,arronei/corefx,kyulee1/corefx,benpye/corefx,lggomez/corefx,anjumrizwi/corefx,lggomez/corefx,nbarbettini/corefx,shana/corefx,ellismg/corefx,alexperovich/corefx,chenxizhang/corefx,YoupHulsebos/corefx,stone-li/corefx,JosephTremoulet/corefx,shana/corefx,Yanjing123/corefx,DnlHarvey/corefx,vrassouli/corefx,krytarowski/corefx,fffej/corefx,dhoehna/corefx,viniciustaveira/corefx,CherryCxldn/corefx,kkurni/corefx,Chrisboh/corefx,gregg-miskelly/corefx,Petermarcu/corefx,alexandrnikitin/corefx,690486439/corefx,ptoonen/corefx,SGuyGe/corefx,twsouthwick/corefx,parjong/corefx,alexperovich/corefx,khdang/corefx,jhendrixMSFT/corefx,ViktorHofer/corefx,adamralph/corefx,fffej/corefx,wtgodbe/corefx,tijoytom/corefx,dtrebbien/corefx,kkurni/corefx | src/System.Diagnostics.Process/tests/ProcessTest_ConsoleApp/ProcessTest_ConsoleApp.cs | src/System.Diagnostics.Process/tests/ProcessTest_ConsoleApp/ProcessTest_ConsoleApp.cs | using System;
using System.Threading;
namespace ProcessTest_ConsoleApp
{
class Program
{
static int Main(string[] args)
{
try
{
if (args.Length > 0)
{
if (args[0].Equals("infinite"))
{
// To avoid potential issues with orphaned processes (say, the test exits before
// exiting the process), we'll say "infinite" is actually 30 seconds.
Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop");
Thread.Sleep(30 * 1000);
}
if (args[0].Equals("error"))
{
Exception ex = new Exception("Intentional Exception thrown");
throw ex;
}
if (args[0].Equals("input"))
{
string str = Console.ReadLine();
}
}
else
{
Console.WriteLine("ProcessTest_ConsoleApp.exe started");
Console.WriteLine("ProcessTest_ConsoleApp.exe closed");
}
return 100;
}
catch (Exception toLog)
{
// We're testing STDERR streams, not the JIT debugger.
// This makes the process behave just like a crashing .NET app, but without the WER invocation
// nor the blocking dialog that comes with it, or the need to suppress that.
Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString()));
return 1;
}
}
}
}
| using System;
using System.Threading;
namespace ProcessTest_ConsoleApp
{
class Program
{
static int Main(string[] args)
{
try
{
if (args.Length > 0)
{
if (args[0].Equals("infinite"))
{
// To avoid potential issues with orphaned processes (say, the test exits before
// exiting the process, we'll say "infinite" is actually 30 seconds.
Console.WriteLine("ProcessTest_ConsoleApp.exe started with an endless loop");
Thread.Sleep(30 * 1000);
}
if (args[0].Equals("error"))
{
Exception ex = new Exception("Intentional Exception thrown");
throw ex;
}
if (args[0].Equals("input"))
{
string str = Console.ReadLine();
}
}
else
{
Console.WriteLine("ProcessTest_ConsoleApp.exe started");
Console.WriteLine("ProcessTest_ConsoleApp.exe closed");
}
return 100;
}
catch (Exception toLog)
{
// We're testing STDERR streams, not the JIT debugger.
// This makes the process behave just like a crashing .NET app, but without the WER invocation
// nor the blocking dialog that comes with it, or the need to suppress that.
Console.Error.WriteLine(string.Format("Unhandled Exception: {0}", toLog.ToString()));
return 1;
}
}
}
}
| mit | C# |
507e3182b011bf8ffded0e0d7d9546bff8cad4cf | Update the interfaces for authentication. | IvionSauce/MeidoBot | MeidoCommon/MeidoCommon.cs | MeidoCommon/MeidoCommon.cs | using System;
using System.Collections.Generic;
namespace MeidoCommon
{
public interface IMeidoHook
{
// Things the plugin provides us with.
string Name { get; }
string Version { get; }
Dictionary<string, string> Help { get; }
// Things we provide to the plugin.
string Prefix { set; }
// Method to signal to the plugins they need to stop whatever seperate threads they have running.
// As well as to save/deserialize whatever it needs to.
void Stop();
}
public interface IIrcMessage
{
string Message { get; }
string[] MessageArray { get; }
string Channel { get; }
string Nick { get; }
string Ident { get; }
string Host { get; }
string Trigger { get; }
string ReturnTo { get; }
void Reply(string message);
void Reply(string message, params object[] args);
}
public interface IMeidoComm
{
string ConfDir { get; }
string DataDir { get; }
bool Auth(string nick, string pass);
int AuthLevel(string nick);
}
public interface IIrcComm
{
string Nickname { get; }
void AddChannelMessageHandler(Action<IIrcMessage> handler);
void AddChannelActionHandler(Action<IIrcMessage> handler);
void AddQueryMessageHandler(Action<IIrcMessage> handler);
void AddQueryActionHandler(Action<IIrcMessage> handler);
void AddTriggerHandler(Action<IIrcMessage> handler);
void SendMessage(string target, string message);
void SendMessage(string target, string message, params object[] args);
void DoAction(string target, string action);
void DoAction(string target, string action, params object[] args);
void SendNotice(string target, string message);
void SendNotice(string target, string message, params object[] args);
string[] GetChannels();
bool IsMe(string nick);
}
} | using System;
using System.Collections.Generic;
namespace MeidoCommon
{
public interface IMeidoHook
{
// Things the plugin provides us with.
string Name { get; }
string Version { get; }
Dictionary<string, string> Help { get; }
// Things we provide to the plugin.
string Prefix { set; }
// Method to signal to the plugins they need to stop whatever seperate threads they have running.
// As well as to save/deserialize whatever it needs to.
void Stop();
}
public interface IIrcMessage
{
string Message { get; }
string[] MessageArray { get; }
string Channel { get; }
string Nick { get; }
string Ident { get; }
string Host { get; }
string Trigger { get; }
string ReturnTo { get; }
void Reply(string message);
void Reply(string message, params object[] args);
}
public interface IMeidoComm
{
string ConfDir { get; }
}
public interface IIrcComm
{
string Nickname { get; }
void AddChannelMessageHandler(Action<IIrcMessage> handler);
void AddChannelActionHandler(Action<IIrcMessage> handler);
void AddQueryMessageHandler(Action<IIrcMessage> handler);
void AddQueryActionHandler(Action<IIrcMessage> handler);
void AddTriggerHandler(Action<IIrcMessage> handler);
void SendMessage(string target, string message);
void SendMessage(string target, string message, params object[] args);
void DoAction(string target, string action);
void DoAction(string target, string action, params object[] args);
void SendNotice(string target, string message);
void SendNotice(string target, string message, params object[] args);
string[] GetChannels();
bool IsMe(string nick);
}
} | bsd-2-clause | C# |
6c6da8f11f5df72c22c844c224845db1d8970d57 | Remove whitespace | EightBitBoy/EcoRealms | Assets/Scripts/Map/GridRenderer.cs | Assets/Scripts/Map/GridRenderer.cs | using UnityEngine;
using System.Collections;
namespace ecorealms.map {
public class GridRenderer : MonoBehaviour {
private const float WIDTH = 0.05f;
private const float HEIGHT = 0.05f;
private int linesX;
private int linesY;
private Material material;
public void Setup(int chunksX, int chunksY, int tilesX, int tilesY) {
this.linesX = chunksX * tilesX;
this.linesY = chunksY * tilesY;
Initialize();
}
private void Initialize() {
material = new Material((Shader.Find("Diffuse")));
material.SetColor(0, Color.black);
for(int x = 0; x < linesX; x++){
AddLine("Line" + x, x, 0, x, linesY);
}
for(int y = 0; y < linesY; y++){
AddLine("Line" + y, 0, y, linesX, y);
}
}
private void AddLine(string name, float startX, float startY, float endX, float endY){
Vector3 start = new Vector3(startX, HEIGHT, startY);
Vector3 end = new Vector3(endX, HEIGHT, endY);
GameObject line = new GameObject(name);
LineRenderer renderer = line.AddComponent<LineRenderer>();
line.transform.SetParent(gameObject.transform);
renderer.material = material;
renderer.SetWidth(WIDTH, WIDTH);
renderer.SetPosition(0, start);
renderer.SetPosition(1, end);
}
}
}
| using UnityEngine;
using System.Collections;
namespace ecorealms.map {
public class GridRenderer : MonoBehaviour {
private const float WIDTH = 0.05f;
private const float HEIGHT = 0.05f;
private int linesX;
private int linesY;
private Material material;
public void Setup(int chunksX, int chunksY, int tilesX, int tilesY) {
this.linesX = chunksX * tilesX;
this.linesY = chunksY * tilesY;
Initialize();
}
private void Initialize() {
material = new Material((Shader.Find(" Diffuse")));
material.SetColor(0, Color.black);
for(int x = 0; x < linesX; x++){
AddLine("Line" + x, x, 0, x, linesY);
}
for(int y = 0; y < linesY; y++){
AddLine("Line" + y, 0, y, linesX, y);
}
}
private void AddLine(string name, float startX, float startY, float endX, float endY){
Vector3 start = new Vector3(startX, HEIGHT, startY);
Vector3 end = new Vector3(endX, HEIGHT, endY);
GameObject line = new GameObject(name);
LineRenderer renderer = line.AddComponent<LineRenderer>();
line.transform.SetParent(gameObject.transform);
renderer.material = material;
renderer.SetWidth(WIDTH, WIDTH);
renderer.SetPosition(0, start);
renderer.SetPosition(1, end);
}
}
}
| apache-2.0 | C# |
5f2f1b6a9a1c3c15d57e78591a4aa66c42a07fee | Use UpdateScheduler in MethodCommand | michaellperry/Assisticant | Assisticant/Metas/MethodCommand.cs | Assisticant/Metas/MethodCommand.cs | using Assisticant.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Assisticant.Metas
{
public class MethodCommand : ICommand
{
public readonly object Instance;
public readonly CommandMeta Meta;
readonly Computed<bool> _computedCan;
bool? _lastCan;
public event EventHandler CanExecuteChanged;
public MethodCommand(object instance, CommandMeta meta)
{
Instance = instance;
Meta = meta;
if (meta.Condition != null)
{
_computedCan = new Computed<bool>(() => (bool)meta.Condition.GetValue(Instance));
_computedCan.Invalidated += () => UpdateScheduler.ScheduleUpdate(UpdateNow);
}
}
public bool CanExecute(object parameter)
{
if (_computedCan == null)
return true;
return BindingInterceptor.Current.CanExecute(this, parameter);
}
internal bool ContinueCanExecute(object parameter)
{
_lastCan = _computedCan.Value;
return _lastCan.Value;
}
public void Execute(object parameter)
{
var scheduler = UpdateScheduler.Begin();
try
{
BindingInterceptor.Current.Execute(this, parameter);
}
finally
{
if (scheduler != null)
{
foreach (var updatable in scheduler.End())
updatable();
}
}
}
internal void ContinueExecute(object parameter)
{
if (Meta.HasParameter)
Meta.Method.Invoke(Instance, new object[] { parameter });
else
Meta.Method.Invoke(Instance, new object[0]);
}
private void UpdateNow()
{
var can = _computedCan.Value;
if (_lastCan != can && CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
| using Assisticant.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Assisticant.Metas
{
public class MethodCommand : ICommand
{
public readonly object Instance;
public readonly CommandMeta Meta;
readonly Computed<bool> _computedCan;
bool? _lastCan;
public event EventHandler CanExecuteChanged;
public MethodCommand(object instance, CommandMeta meta)
{
Instance = instance;
Meta = meta;
if (meta.Condition != null)
{
_computedCan = new Computed<bool>(() => (bool)meta.Condition.GetValue(Instance));
_computedCan.Invalidated += () => UpdateScheduler.ScheduleUpdate(UpdateNow);
}
}
public bool CanExecute(object parameter)
{
if (_computedCan == null)
return true;
return BindingInterceptor.Current.CanExecute(this, parameter);
}
internal bool ContinueCanExecute(object parameter)
{
_lastCan = _computedCan.Value;
return _lastCan.Value;
}
public void Execute(object parameter)
{
BindingInterceptor.Current.Execute(this, parameter);
}
internal void ContinueExecute(object parameter)
{
if (Meta.HasParameter)
Meta.Method.Invoke(Instance, new object[] { parameter });
else
Meta.Method.Invoke(Instance, new object[0]);
}
private void UpdateNow()
{
var can = _computedCan.Value;
if (_lastCan != can && CanExecuteChanged != null)
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
| mit | C# |
2df0a19ad4a79e3da1c151ad702ca844b05e1cd5 | Update Version | AyrA/BinSend | BinSend/Properties/AssemblyInfo.cs | BinSend/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BinSend")]
[assembly: AssemblyDescription("Send and Decode Binary Bitmessage Messages")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AyrA")]
[assembly: AssemblyProduct("BinSend")]
[assembly: AssemblyCopyright("Copyright © AyrA 2018")]
[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("cd1e6013-442a-496a-9b15-3c576fbac5b4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.3.0.0")]
[assembly: AssemblyFileVersion("1.3.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BinSend")]
[assembly: AssemblyDescription("Send and Decode Binary Bitmessage Messages")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("AyrA")]
[assembly: AssemblyProduct("BinSend")]
[assembly: AssemblyCopyright("Copyright © AyrA 2018")]
[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("cd1e6013-442a-496a-9b15-3c576fbac5b4")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| unlicense | C# |
09c25267add44dd31d6c04cd006044529021d95b | update solution version | gigya/microdot | SolutionVersion.cs | SolutionVersion.cs | #region Copyright
// Copyright 2017 Gigya 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("2.0.5.0")]
[assembly: AssemblyFileVersion("2.0.5.0")]
[assembly: AssemblyInformationalVersion("2.0.5.0")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| #region Copyright
// Copyright 2017 Gigya 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
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#endregion
using System;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Gigya Inc.")]
[assembly: AssemblyCopyright("© 2018 Gigya Inc.")]
[assembly: AssemblyDescription("Microdot Framework")]
[assembly: AssemblyVersion("2.0.4.0")]
[assembly: AssemblyFileVersion("2.0.4.0")]
[assembly: AssemblyInformationalVersion("2.0.4.0")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
| apache-2.0 | C# |
22bfb7c262ea123f491b936e005df4f0bc114402 | Increase min version (#232) | dgarage/NBXplorer,dgarage/NBXplorer | NBXplorer.Client/NBXplorerNetworkProvider.Chaincoin.cs | NBXplorer.Client/NBXplorerNetworkProvider.Chaincoin.cs | using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBXplorer
{
public partial class NBXplorerNetworkProvider
{
private void InitChaincoin(NetworkType networkType)
{
Add(new NBXplorerNetwork(NBitcoin.Altcoins.Chaincoin.Instance, networkType)
{
MinRPCVersion = 160400,
CoinType = networkType == NetworkType.Mainnet ? new KeyPath("711'") : new KeyPath("1'")
});
}
public NBXplorerNetwork GetCHC()
{
return GetFromCryptoCode(NBitcoin.Altcoins.Chaincoin.Instance.CryptoCode);
}
}
}
| using NBitcoin;
using System;
using System.Collections.Generic;
using System.Text;
namespace NBXplorer
{
public partial class NBXplorerNetworkProvider
{
private void InitChaincoin(NetworkType networkType)
{
Add(new NBXplorerNetwork(NBitcoin.Altcoins.Chaincoin.Instance, networkType)
{
MinRPCVersion = 140200
});
}
public NBXplorerNetwork GetCHC()
{
return GetFromCryptoCode(NBitcoin.Altcoins.Chaincoin.Instance.CryptoCode);
}
}
}
| mit | C# |
4dbebc4cda6ebda30432d00f180e2e396c30162e | Use array instead of switch statement | CaitSith2/KtaneTwitchPlays,samfun123/KtaneTwitchPlays | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/AlphabetNumbersComponentSolver.cs | TwitchPlaysAssembly/Src/ComponentSolvers/Modded/Misc/AlphabetNumbersComponentSolver.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class AlphabetNumbersComponentSolver : ComponentSolver
{
public AlphabetNumbersComponentSolver(BombCommander bombCommander, BombComponent bombComponent)
: base (bombCommander, bombComponent)
{
_alphabetNumberComponent = bombComponent.GetComponent(_componentType);
buttons = _alphabetNumberComponent.GetComponent<KMSelectable>().Children;
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press the buttons with !{0} press 1 2 3 4 5 6. The buttons are numbered 1 to 6 in clockwise order.");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
string[] split = inputCommand.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (split[0] != "press" || split.Length == 1) yield break;
List<int> correct = new List<int> { };
foreach (string number in split.Skip(1))
{
if (!int.TryParse(number, out int result)) yield break;
if (result > buttons.Length || result == 0) yield break;
correct.Add(result);
}
foreach (int number in correct)
{
yield return null;
yield return DoInteractionClick(buttons[_buttonMap[number - 1]]);
}
}
static AlphabetNumbersComponentSolver()
{
_componentType = ReflectionHelper.FindType("alphabeticalOrderScript");
}
private static Type _componentType = null;
private readonly int[] _buttonMap = { 0, 2, 4, 5, 3, 1 };
private readonly Component _alphabetNumberComponent = null;
private readonly KMSelectable[] buttons;
} | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class AlphabetNumbersComponentSolver : ComponentSolver
{
public AlphabetNumbersComponentSolver(BombCommander bombCommander, BombComponent bombComponent)
: base (bombCommander, bombComponent)
{
_alphabetNumberComponent = bombComponent.GetComponent(_componentType);
buttons = _alphabetNumberComponent.GetComponent<KMSelectable>().Children;
modInfo = ComponentSolverFactory.GetModuleInfo(GetModuleType(), "Press the buttons with !{0} press 1 2 3 4 5 6. The buttons are numbered 1 to 6 in clockwise order.");
}
protected internal override IEnumerator RespondToCommandInternal(string inputCommand)
{
string[] split = inputCommand.ToLowerInvariant().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (split[0] != "press" || split.Length == 1) yield break;
List<int> correct = new List<int> { };
foreach (string number in split.Skip(1))
{
if (!int.TryParse(number, out int result)) yield break;
if (result > buttons.Length || result == 0) yield break;
correct.Add(result);
}
foreach (int number in correct)
{
yield return null;
switch (number)
{
case 1:
yield return DoInteractionClick(buttons[0]);
break;
case 2:
yield return DoInteractionClick(buttons[2]);
break;
case 3:
yield return DoInteractionClick(buttons[4]);
break;
case 4:
yield return DoInteractionClick(buttons[5]);
break;
case 5:
yield return DoInteractionClick(buttons[3]);
break;
case 6:
yield return DoInteractionClick(buttons[1]);
break;
}
}
}
static AlphabetNumbersComponentSolver()
{
_componentType = ReflectionHelper.FindType("alphabeticalOrderScript");
}
private static Type _componentType = null;
private readonly Component _alphabetNumberComponent = null;
private readonly KMSelectable[] buttons;
} | mit | C# |
79405209985af59f0a9ac06e1284e3a7e26c7346 | fix #257 - writewitoutresponse shouldn't be swapping to write when unavailable. Stub comment IsReadyToWrite implementation for later date | aritchie/bluetoothle,aritchie/bluetoothle | Plugin.BluetoothLE/Platforms/iOS/GattCharacteristic.cs | Plugin.BluetoothLE/Platforms/iOS/GattCharacteristic.cs | using System;
using System.Reactive.Linq;
using CoreBluetooth;
using Foundation;
namespace Plugin.BluetoothLE
{
public partial class GattCharacteristic : AbstractGattCharacteristic
{
public override IObservable<CharacteristicGattResult> WriteWithoutResponse(byte[] value)
{
var data = NSData.FromArray(value);
this.Peripheral.WriteValue(data, this.NativeCharacteristic, CBCharacteristicWriteType.WithoutResponse);
return Observable.Return(new CharacteristicGattResult(this, value));
}
//public override IObservable<CharacteristicGattResult> WriteWithoutResponse(byte[] value)
//{
// if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
// return this.NewInternalWrite(value);
// return Observable.Return(this.InternalWrite(value));
//}
//IObservable<CharacteristicGattResult> NewInternalWrite(byte[] value) => Observable.Create<CharacteristicGattResult>(ob =>
//{
// EventHandler handler = null;
// if (this.Peripheral.CanSendWriteWithoutResponse)
// {
// ob.Respond(this.InternalWrite(value));
// }
// else
// {
// handler = new EventHandler((sender, args) => ob.Respond(this.InternalWrite(value)));
// this.Peripheral.IsReadyToSendWriteWithoutResponse += handler;
// }
// return () =>
// {
// if (handler != null)
// this.Peripheral.IsReadyToSendWriteWithoutResponse -= handler;
// };
//});
//CharacteristicGattResult InternalWrite(byte[] value)
//{
// var data = NSData.FromArray(value);
// this.Peripheral.WriteValue(data, this.NativeCharacteristic, CBCharacteristicWriteType.WithoutResponse);
// return new CharacteristicGattResult(this, value);
//}
}
} | using System;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using Acr.Reactive;
using CoreBluetooth;
using Foundation;
using UIKit;
namespace Plugin.BluetoothLE
{
public partial class GattCharacteristic : AbstractGattCharacteristic
{
public override IObservable<CharacteristicGattResult> WriteWithoutResponse(byte[] value) => Observable.Create<CharacteristicGattResult>(ob =>
{
this.AssertWrite(false);
if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
{
var type = this.Peripheral.CanSendWriteWithoutResponse
? CBCharacteristicWriteType.WithoutResponse
: CBCharacteristicWriteType.WithResponse;
this.Write(ob, type, value);
}
else
{
this.Write(ob, CBCharacteristicWriteType.WithoutResponse, value);
}
return Disposable.Empty;
});
void Write(IObserver<CharacteristicGattResult> ob, CBCharacteristicWriteType type, byte[] value)
{
var data = NSData.FromArray(value);
this.Peripheral.WriteValue(data, this.NativeCharacteristic, type);
ob.Respond(new CharacteristicGattResult(this, value));
}
}
} | mit | C# |
dccea72e30c4a719d0f7dd3705a4103e79a5cabd | Bump version to 0.3.4 | FatturaElettronicaPA/FatturaElettronicaPA | Properties/AssemblyInfo.cs | Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FatturaElettronica.NET")]
[assembly: AssemblyDescription("Fattura Elettronica per le aziende e la Pubblica Amministrazione Italiana")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nicola Iarocci, CIR2000")]
[assembly: AssemblyProduct("FatturaElettronica.NET")]
[assembly: AssemblyCopyright("Copyright © CIR2000 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.4.0")]
[assembly: AssemblyFileVersion("0.3.4.0")]
| using System.Reflection;
using System.Resources;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("FatturaElettronica.NET")]
[assembly: AssemblyDescription("Fattura Elettronica per le aziende e la Pubblica Amministrazione Italiana")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nicola Iarocci, CIR2000")]
[assembly: AssemblyProduct("FatturaElettronica.NET")]
[assembly: AssemblyCopyright("Copyright © CIR2000 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.3.0")]
[assembly: AssemblyFileVersion("0.3.3.0")]
| bsd-3-clause | C# |
541c66e2023d50dda5c8b6bfce391a9e68f5b6e2 | bump version to v1.2 | micdenny/PRTG-Redis-Sensor,cdemi/PRTG-Redis-Sensor | Properties/AssemblyInfo.cs | 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("PRTG Redis Sensor")]
[assembly: AssemblyDescription("https://github.com/cdemi/PRTG-Redis-Sensor")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PRTG Redis Sensor")]
[assembly: AssemblyCopyright("MIT License (MIT)")]
[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("df6bf3bb-1835-4f6e-92c3-0b3926129f73")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.0.0")]
[assembly: AssemblyFileVersion("1.2.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("PRTG Redis Sensor")]
[assembly: AssemblyDescription("https://github.com/cdemi/PRTG-Redis-Sensor")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("PRTG Redis Sensor")]
[assembly: AssemblyCopyright("MIT License (MIT)")]
[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("df6bf3bb-1835-4f6e-92c3-0b3926129f73")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
| mit | C# |
00860fe1a64f58b7fd56babcad0fd3f18ea82dad | update copyright | jordanbtucker/NS84.Syndication.Atom,ArsenShnurkov/NS84.Syndication.Atom | Properties/AssemblyInfo.cs | 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("NerdSince1984.Syndication.Atom")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nerd since 1984")]
[assembly: AssemblyProduct("NerdSince1984.Syndication.Atom")]
[assembly: AssemblyCopyright("© 1984-2015 Jordan Tucker")]
[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("ef82d95a-8226-4990-9b88-d3cfdb29194f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.5.0.0")]
[assembly: AssemblyFileVersion("3.5.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("NerdSince1984.Syndication.Atom")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Nerd since 1984")]
[assembly: AssemblyProduct("NerdSince1984.Syndication.Atom")]
[assembly: AssemblyCopyright("© 1984-2010 Jordan Tucker")]
[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("ef82d95a-8226-4990-9b88-d3cfdb29194f")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.5.0.0")]
[assembly: AssemblyFileVersion("3.5.0.0")]
| mit | C# |
629ecdb9e770f55f6d5a1e81d4b41f191f96ddfa | improve RabbitEventSource to use single deserializing sequence | svtz/homeControl,svtz/homeControl,livingLegend/homeControl | src/homeControl.Interop.Rabbit/RabbitEventSource.cs | src/homeControl.Interop.Rabbit/RabbitEventSource.cs | using System;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using homeControl.Domain.Events;
using JetBrains.Annotations;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Serilog;
namespace homeControl.Interop.Rabbit
{
[UsedImplicitly]
internal sealed class RabbitEventSource : IEventSource, IDisposable
{
private readonly IConnectableObservable<IEvent> _deserializedEvents;
private readonly IDisposable _eventsConnection;
public RabbitEventSource(
IModel channel,
IEventSerializer eventSerializer,
ILogger log,
string exchangeName,
string exchangeType,
string routingKey)
{
Guard.DebugAssertArgumentNotNull(routingKey, nameof(routingKey));
Guard.DebugAssertArgumentNotNull(exchangeName, nameof(exchangeName));
Guard.DebugAssertArgumentNotNull(exchangeType, nameof(exchangeType));
Guard.DebugAssertArgumentNotNull(eventSerializer, nameof(eventSerializer));
Guard.DebugAssertArgumentNotNull(channel, nameof(channel));
Guard.DebugAssertArgumentNotNull(log, nameof(log));
channel.ExchangeDeclare(exchangeName, exchangeType);
var queueName = $"{exchangeName}-{Guid.NewGuid()}";
var queue = channel.QueueDeclare(queueName);
channel.QueueBind(queue.QueueName, exchangeName, routingKey);
var consumer = new EventingBasicConsumer(channel);
var messageSource = Observable.FromEventPattern<BasicDeliverEventArgs>(
e => consumer.Received += e,
e => consumer.Received -= e);
_deserializedEvents = messageSource
.Select(e => e.EventArgs.Body)
.Select(eventSerializer.Deserialize)
.Do(msg => log.Verbose("{ExchangeName}>>>{Event}", exchangeName, msg))
.Publish();
_eventsConnection = _deserializedEvents.Connect();
channel.BasicConsume(queue.QueueName, true, consumer);
}
public IObservable<TEvent> ReceiveEvents<TEvent>() where TEvent : IEvent
{
return _deserializedEvents.OfType<TEvent>();
}
public void Dispose()
{
_eventsConnection.Dispose();
}
}
} | using System;
using System.Reactive.Linq;
using homeControl.Domain.Events;
using JetBrains.Annotations;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using Serilog;
namespace homeControl.Interop.Rabbit
{
[UsedImplicitly]
internal sealed class RabbitEventSource : IEventSource
{
private readonly IEventSerializer _eventSerializer;
private readonly ILogger _log;
private readonly string _exchangeName;
private readonly EventingBasicConsumer _consumer;
public RabbitEventSource(
IModel channel,
IEventSerializer eventSerializer,
ILogger log,
string exchangeName,
string exchangeType,
string routingKey)
{
Guard.DebugAssertArgumentNotNull(routingKey, nameof(routingKey));
Guard.DebugAssertArgumentNotNull(exchangeName, nameof(exchangeName));
Guard.DebugAssertArgumentNotNull(exchangeType, nameof(exchangeType));
Guard.DebugAssertArgumentNotNull(eventSerializer, nameof(eventSerializer));
Guard.DebugAssertArgumentNotNull(channel, nameof(channel));
Guard.DebugAssertArgumentNotNull(log, nameof(log));
_eventSerializer = eventSerializer;
_log = log;
_exchangeName = exchangeName;
channel.ExchangeDeclare(exchangeName, exchangeType);
var queueName = $"{exchangeName}-{Guid.NewGuid()}";
var queue = channel.QueueDeclare(queueName);
channel.QueueBind(queue.QueueName, exchangeName, routingKey);
_consumer = new EventingBasicConsumer(channel);
channel.BasicConsume(queue.QueueName, true, _consumer);
}
public IObservable<TEvent> ReceiveEvents<TEvent>() where TEvent : IEvent
{
var messageSource = Observable.FromEventPattern<BasicDeliverEventArgs>(
e => _consumer.Received += e,
e => _consumer.Received -= e);
return messageSource
.Select(e => e.EventArgs.Body)
.Select(_eventSerializer.Deserialize)
.Do(msg => _log.Verbose("{ExchangeName}>>>{Event}", _exchangeName, msg))
.OfType<TEvent>();
}
}
} | mit | C# |
feb52c0a6988cdc2426f2ea30ea078bc9b1ce85f | Implement client | SLdragon1989/octokit.net,eriawan/octokit.net,shana/octokit.net,gdziadkiewicz/octokit.net,octokit-net-test-org/octokit.net,shiftkey-tester/octokit.net,shiftkey/octokit.net,magoswiat/octokit.net,dampir/octokit.net,editor-tools/octokit.net,geek0r/octokit.net,rlugojr/octokit.net,M-Zuber/octokit.net,daukantas/octokit.net,shiftkey/octokit.net,ChrisMissal/octokit.net,hahmed/octokit.net,kolbasov/octokit.net,dampir/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,octokit/octokit.net,gabrielweyer/octokit.net,eriawan/octokit.net,SamTheDev/octokit.net,M-Zuber/octokit.net,darrelmiller/octokit.net,gabrielweyer/octokit.net,mminns/octokit.net,adamralph/octokit.net,fake-organization/octokit.net,Sarmad93/octokit.net,gdziadkiewicz/octokit.net,shiftkey-tester/octokit.net,brramos/octokit.net,naveensrinivasan/octokit.net,shana/octokit.net,ivandrofly/octokit.net,editor-tools/octokit.net,dlsteuer/octokit.net,TattsGroup/octokit.net,nsnnnnrn/octokit.net,devkhan/octokit.net,chunkychode/octokit.net,hitesh97/octokit.net,octokit-net-test-org/octokit.net,forki/octokit.net,michaKFromParis/octokit.net,bslliw/octokit.net,SmithAndr/octokit.net,thedillonb/octokit.net,fffej/octokit.net,khellang/octokit.net,octokit/octokit.net,devkhan/octokit.net,nsrnnnnn/octokit.net,SmithAndr/octokit.net,khellang/octokit.net,alfhenrik/octokit.net,SamTheDev/octokit.net,rlugojr/octokit.net,cH40z-Lord/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,thedillonb/octokit.net,mminns/octokit.net,takumikub/octokit.net,hahmed/octokit.net,kdolan/octokit.net,alfhenrik/octokit.net,ivandrofly/octokit.net,chunkychode/octokit.net,octokit-net-test/octokit.net,Sarmad93/octokit.net,Red-Folder/octokit.net,TattsGroup/octokit.net | Octokit/Clients/StatisticsClient.cs | Octokit/Clients/StatisticsClient.cs | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Octokit
{
public class StatisticsClient : ApiClient, IStatisticsClient
{
/// <summary>
/// Instantiates a new GitHub Statistics API client.
/// </summary>
/// <param name="apiConnection">An API connection</param>
public StatisticsClient(IApiConnection apiConnection) : base(apiConnection)
{
}
/// <summary>
/// Returns a list of <see cref="Contributor"/> for the given repository
/// </summary>
/// <param name="owner">The owner of the repository</param>
/// <param name="repositoryName">The name of the repository</param>
/// <returns>A list of <see cref="Contributor"/></returns>
public Task<IEnumerable<Contributor>> Contributors(string owner, string repositoryName)
{
Ensure.ArgumentNotNullOrEmptyString(owner, "owner");
Ensure.ArgumentNotNullOrEmptyString(repositoryName, "repositoryName");
var endpoint = "/repos/{0}/{1}/stats/contributors".FormatUri(owner,repositoryName);
return ApiConnection.Get<IEnumerable<Contributor>>(endpoint);
}
}
} | using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Octokit
{
public class StatisticsClient : ApiClient, IStatisticsClient
{
/// <summary>
/// Instantiates a new GitHub Statistics API client.
/// </summary>
/// <param name="apiConnection">An API connection</param>
public StatisticsClient(IApiConnection apiConnection) : base(apiConnection)
{
}
/// <summary>
/// Returns a list of <see cref="Contributor"/> for the given repo
/// </summary>
/// <param name="owner">The owner of the repository</param>
/// <param name="repositoryName">The name of the repository</param>
/// <returns>A list of <see cref="Contributor"/></returns>
public Task<IEnumerable<Contributor>> Contributors(string owner, string repositoryName)
{
throw new NotImplementedException();
}
}
} | mit | C# |
b8dd43f5a6df93eaacecad6b05d7285b5db7ae51 | Tweak min samples. | electricessence/Solve,electricessence/Solve,electricessence/Solve,electricessence/Solve | Problems/BlackBoxFunction/Runner.cs | Problems/BlackBoxFunction/Runner.cs | using Solve.Evaluation;
using Solve.Experiment.Console;
using Solve.ProcessingSchemes;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace BlackBoxFunction
{
[SuppressMessage("ReSharper", "UnusedMember.Local")]
internal class Runner : RunnerBase<EvalGenome>
{
static double AB(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return a * b;
}
static double A2B2(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return a * a + b * b;
}
static double SqrtA2B2(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return Math.Sqrt(a * a + b * b);
}
static double SqrtA2B2C2(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
var c = p[2];
return Math.Sqrt(a * a + b * b + c * c);
}
static double SqrtA2B2A2B1(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return Math.Sqrt(a * a + b * b + a + 2) + b + 1;
}
readonly ushort _minSamples;
protected Runner(ushort minSamples, ushort minConvSamples = 20) : base(minSamples > minConvSamples ? minSamples : minConvSamples)
{
_minSamples = minSamples;
}
public void Init()
{
var factory = new EvalGenomeFactory<EvalGenome>(/*"(({0} * {0}) + ({1} * {1}))"*/);
var emitter = new EvalConsoleEmitter(factory, _minSamples);
var scheme = new TowerProcessingScheme<EvalGenome>(factory, (400, 40, 2));
scheme.AddProblem(Problem.Create(A2B2, 100));
Init(scheme, emitter, factory.Metrics);
}
static Task Main()
{
var runner = new Runner(10);
runner.Init();
var message = string.Format(
"Solving Black-Box Problem... (minimum {0:n0} samples before displaying)",
runner._minSamples);
return runner.Start(message);
}
}
}
| using Solve.Evaluation;
using Solve.Experiment.Console;
using Solve.ProcessingSchemes;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Threading.Tasks;
namespace BlackBoxFunction
{
[SuppressMessage("ReSharper", "UnusedMember.Local")]
internal class Runner : RunnerBase<EvalGenome>
{
static double AB(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return a * b;
}
static double A2B2(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return a * a + b * b;
}
static double SqrtA2B2(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return Math.Sqrt(a * a + b * b);
}
static double SqrtA2B2C2(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
var c = p[2];
return Math.Sqrt(a * a + b * b + c * c);
}
static double SqrtA2B2A2B1(IReadOnlyList<double> p)
{
var a = p[0];
var b = p[1];
return Math.Sqrt(a * a + b * b + a + 2) + b + 1;
}
readonly ushort _minSamples;
protected Runner(ushort minSamples, ushort minConvSamples = 20) : base(minSamples > minConvSamples ? minSamples : minConvSamples)
{
_minSamples = minSamples;
}
public void Init()
{
var factory = new EvalGenomeFactory<EvalGenome>(/*"(({0} * {0}) + ({1} * {1}))"*/);
var emitter = new EvalConsoleEmitter(factory, _minSamples);
var scheme = new TowerProcessingScheme<EvalGenome>(factory, (400, 40, 2));
scheme.AddProblem(Problem.Create(A2B2, 100));
Init(scheme, emitter, factory.Metrics);
}
static Task Main()
{
var runner = new Runner(20);
runner.Init();
var message = string.Format(
"Solving Black-Box Problem... (minimum {0:n0} samples before displaying)",
runner._minSamples);
return runner.Start(message);
}
}
}
| apache-2.0 | C# |
e28c26bca436c8bf19baad5e4493666f393c89c0 | Update PBU-Main-Future.cs | win120a/ACClassRoomUtil,win120a/ACClassRoomUtil | ProcessBlockUtil/PBU-Main-Future.cs | ProcessBlockUtil/PBU-Main-Future.cs | /*
THIS IS ONLY TO EASY CHANGE, NOT THE PROJECT CODE AT NOW. (I will use in the future.)
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
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;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Collections;
namespace ACProcessBlockUtil
{
class Run:ServiceBase
{
SteamReader sr;
ArrayList<String> al;
String[] list;
public static void kill()
{
while (true)
{
Process[] ieProcArray = Process.GetProcessesByName("iexplore");
//Console.WriteLine(ieProcArray.Length);
if (ieProcArray.Length == 0)
{
continue;
}
foreach(Process p in ieProcArray){
p.Kill();
}
Thread.Sleep(2000);
}
}
public static void Main(String[] a)
{
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
if(File.Exists(userProfile + "\\ACRules.txt")){
ar = new ArrayList<String>();
sr = new SteamReader(userProfile + "\\ACRules.txt");
while(true){
String tempLine = sr.ReadLine();
if(tempLine == null){
break;
}
else{
ar.Add(tempLine);
}
}
list = (String) ar.ToArray();
}
else{
list = {"iexplore", "360se", "qqbrowser"}
}
ServiceBase.Run(new Run());
}
protected override void OnStart(String[] a){
Thread t = new Thread(new ThreadStart(kill));
t.IsBackground = true;
t.Start();
}
}
}
| /*
THIS IS ONLY TO EASY CHANGE, NOT THE PROJECT CODE AT NOW. (I will use in the future.)
Copyright (C) 2011-2014 AC Inc. (Andy Cheung)
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;
using System.IO;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
using System.Collections;
namespace ACProcessBlockUtil
{
class Run:ServiceBase
{
SteamReader sr;
ArrayList al;
String[] list;
public static void kill()
{
while (true)
{
Process[] ieProcArray = Process.GetProcessesByName("iexplore");
//Console.WriteLine(ieProcArray.Length);
if (ieProcArray.Length == 0)
{
continue;
}
foreach(Process p in ieProcArray){
p.Kill();
}
Thread.Sleep(2000);
}
}
public static void Main(String[] a)
{
String userProfile = Environment.GetEnvironmentVariable("UserProfile");
String systemRoot = Environment.GetEnvironmentVariable("SystemRoot");
if(File.Exists(userProfile + "\\ACRules.txt")){
ar = new ArrayList();
sr = new SteamReader(userProfile + "\\ACRules.txt");
while(true){
String tempLine = sr.ReadLine();
if(tempLine == null){
break;
}
else{
ar.Add(tempLine);
}
}
list = (String) ar.ToArray();
}
else{
list = {"iexplore", "360se", "qqbrowser"}
}
ServiceBase.Run(new Run());
}
protected override void OnStart(String[] a){
Thread t = new Thread(new ThreadStart(kill));
t.IsBackground = true;
t.Start();
}
}
}
| apache-2.0 | C# |
c264a9cc74ad9b64026793a2c7ab9a7f1726ed84 | Fix mods not being populated | 2yangk23/osu,ZLima12/osu,EVAST9919/osu,naoey/osu,NeoAdonis/osu,ppy/osu,naoey/osu,EVAST9919/osu,johnneijzen/osu,peppy/osu-new,peppy/osu,ZLima12/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,johnneijzen/osu,DrabWeb/osu,ppy/osu,peppy/osu,UselessToucan/osu,DrabWeb/osu,DrabWeb/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,naoey/osu,smoogipoo/osu | osu.Game.Rulesets.Taiko/Difficulty/TaikoDifficultyCalculator.cs | osu.Game.Rulesets.Taiko/Difficulty/TaikoDifficultyCalculator.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Skills;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Rulesets.Taiko.Objects;
namespace osu.Game.Rulesets.Taiko.Difficulty
{
public class TaikoDifficultyCalculator : DifficultyCalculator
{
private const double star_scaling_factor = 0.04125;
public TaikoDifficultyCalculator(Ruleset ruleset, WorkingBeatmap beatmap)
: base(ruleset, beatmap)
{
}
protected override DifficultyAttributes CreateDifficultyAttributes(IBeatmap beatmap, Mod[] mods, Skill[] skills, double clockRate)
{
if (beatmap.HitObjects.Count == 0)
return new TaikoDifficultyAttributes { Mods = mods };
return new TaikoDifficultyAttributes
{
StarRating = skills.Single().DifficultyValue() * star_scaling_factor,
Mods = mods,
// Todo: This int cast is temporary to achieve 1:1 results with osu!stable, and should be removed in the future
GreatHitWindow = (int)(beatmap.HitObjects.First().HitWindows.Great / 2) / clockRate,
MaxCombo = beatmap.HitObjects.Count(h => h is Hit),
};
}
protected override IEnumerable<DifficultyHitObject> CreateDifficultyHitObjects(IBeatmap beatmap, double clockRate)
{
for (int i = 1; i < beatmap.HitObjects.Count; i++)
yield return new TaikoDifficultyHitObject(beatmap.HitObjects[i], beatmap.HitObjects[i - 1], clockRate);
}
protected override Skill[] CreateSkills() => new Skill[] { new Strain() };
protected override Mod[] DifficultyAdjustmentMods => new Mod[]
{
new TaikoModDoubleTime(),
new TaikoModHalfTime(),
new TaikoModEasy(),
new TaikoModHardRock(),
};
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Linq;
using osu.Game.Beatmaps;
using osu.Game.Rulesets.Difficulty;
using osu.Game.Rulesets.Difficulty.Preprocessing;
using osu.Game.Rulesets.Difficulty.Skills;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Taiko.Difficulty.Preprocessing;
using osu.Game.Rulesets.Taiko.Difficulty.Skills;
using osu.Game.Rulesets.Taiko.Mods;
using osu.Game.Rulesets.Taiko.Objects;
namespace osu.Game.Rulesets.Taiko.Difficulty
{
public class TaikoDifficultyCalculator : DifficultyCalculator
{
private const double star_scaling_factor = 0.04125;
public TaikoDifficultyCalculator(Ruleset ruleset, WorkingBeatmap beatmap)
: base(ruleset, beatmap)
{
}
protected override DifficultyAttributes CreateDifficultyAttributes(IBeatmap beatmap, Mod[] mods, Skill[] skills, double clockRate)
{
if (beatmap.HitObjects.Count == 0)
return new TaikoDifficultyAttributes();
return new TaikoDifficultyAttributes
{
StarRating = skills.Single().DifficultyValue() * star_scaling_factor,
Mods = mods,
// Todo: This int cast is temporary to achieve 1:1 results with osu!stable, and should be removed in the future
GreatHitWindow = (int)(beatmap.HitObjects.First().HitWindows.Great / 2) / clockRate,
MaxCombo = beatmap.HitObjects.Count(h => h is Hit),
};
}
protected override IEnumerable<DifficultyHitObject> CreateDifficultyHitObjects(IBeatmap beatmap, double clockRate)
{
for (int i = 1; i < beatmap.HitObjects.Count; i++)
yield return new TaikoDifficultyHitObject(beatmap.HitObjects[i], beatmap.HitObjects[i - 1], clockRate);
}
protected override Skill[] CreateSkills() => new Skill[] { new Strain() };
protected override Mod[] DifficultyAdjustmentMods => new Mod[]
{
new TaikoModDoubleTime(),
new TaikoModHalfTime(),
new TaikoModEasy(),
new TaikoModHardRock(),
};
}
}
| mit | C# |
c4ebc66b1836fd8aba31f87dad01510f46da94a8 | reduce default limit and order by event time | CityofSantaMonica/Orchard.ParkingData,RaghavAbboy/Orchard.ParkingData | Controllers/SensorEventsController.cs | Controllers/SensorEventsController.cs | using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using CSM.ParkingData.Services;
using CSM.ParkingData.ViewModels;
using CSM.Security.Filters.Http;
using Orchard.Logging;
namespace CSM.ParkingData.Controllers
{
[EnableCors("*", null, "GET")]
public class SensorEventsController : ApiController
{
private readonly ISensorEventsService _sensorEventsService;
public ILogger Logger { get; set; }
public SensorEventsController(ISensorEventsService sensorEventsService)
{
_sensorEventsService = sensorEventsService;
Logger = NullLogger.Instance;
}
public IHttpActionResult Get(int limit = 1000)
{
var events = _sensorEventsService.QueryViewModels()
.OrderByDescending(s => s.EventTime)
.Take(limit);
return Ok(events);
}
[RequireBasicAuthentication]
[RequirePermissions("ApiWriter")]
public IHttpActionResult Post([FromBody]SensorEventPOST postedSensorEvent)
{
if (postedSensorEvent == null || !ModelState.IsValid)
{
Logger.Warning("POST with invalid model{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result);
return BadRequest();
}
try
{
_sensorEventsService.AddOrUpdate(postedSensorEvent);
}
catch (Exception ex)
{
Logger.Error(ex, String.Format("Server error saving POSTed model{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result));
return InternalServerError();
}
return Ok();
}
}
}
| using System;
using System.Linq;
using System.Web.Http;
using System.Web.Http.Cors;
using CSM.ParkingData.Services;
using CSM.ParkingData.ViewModels;
using CSM.Security.Filters.Http;
using Orchard.Logging;
namespace CSM.ParkingData.Controllers
{
[EnableCors("*", null, "GET")]
public class SensorEventsController : ApiController
{
private readonly ISensorEventsService _sensorEventsService;
public ILogger Logger { get; set; }
public SensorEventsController(ISensorEventsService sensorEventsService)
{
_sensorEventsService = sensorEventsService;
Logger = NullLogger.Instance;
}
public IHttpActionResult Get(int limit = int.MaxValue)
{
var events = _sensorEventsService.QueryViewModels()
.Take(limit)
.ToList();
return Ok(events);
}
[RequireBasicAuthentication]
[RequirePermissions("ApiWriter")]
public IHttpActionResult Post([FromBody]SensorEventPOST postedSensorEvent)
{
if (postedSensorEvent == null || !ModelState.IsValid)
{
Logger.Warning("POST with invalid model{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result);
return BadRequest();
}
try
{
_sensorEventsService.AddOrUpdate(postedSensorEvent);
}
catch (Exception ex)
{
Logger.Error(ex, String.Format("Server error saving POSTed model{0}{1}", Environment.NewLine, Request.Content.ReadAsStringAsync().Result));
return InternalServerError();
}
return Ok();
}
}
}
| mit | C# |
6f8e03a61495b81924601e427bb3a189910a26ce | Optimize Gas Mint (#2038) | AntShares/AntShares | src/neo/SmartContract/Native/Tokens/GasToken.cs | src/neo/SmartContract/Native/Tokens/GasToken.cs | using Neo.Cryptography.ECC;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
namespace Neo.SmartContract.Native.Tokens
{
public sealed class GasToken : Nep5Token<AccountState>
{
public override int Id => -2;
public override string Name => "GAS";
public override string Symbol => "gas";
public override byte Decimals => 8;
internal GasToken()
{
}
internal override void Initialize(ApplicationEngine engine)
{
UInt160 account = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators);
Mint(engine, account, 30_000_000 * Factor);
}
protected override void OnPersist(ApplicationEngine engine)
{
base.OnPersist(engine);
long totalNetworkFee = 0;
foreach (Transaction tx in engine.Snapshot.PersistingBlock.Transactions)
{
Burn(engine, tx.Sender, tx.SystemFee + tx.NetworkFee);
totalNetworkFee += tx.NetworkFee;
}
ECPoint[] validators = NEO.GetNextBlockValidators(engine.Snapshot);
UInt160 primary = Contract.CreateSignatureRedeemScript(validators[engine.Snapshot.PersistingBlock.ConsensusData.PrimaryIndex]).ToScriptHash();
Mint(engine, primary, totalNetworkFee);
}
}
}
| using Neo.Cryptography.ECC;
using Neo.Ledger;
using Neo.Network.P2P.Payloads;
using System.Linq;
namespace Neo.SmartContract.Native.Tokens
{
public sealed class GasToken : Nep5Token<AccountState>
{
public override int Id => -2;
public override string Name => "GAS";
public override string Symbol => "gas";
public override byte Decimals => 8;
internal GasToken()
{
}
internal override void Initialize(ApplicationEngine engine)
{
UInt160 account = Blockchain.GetConsensusAddress(Blockchain.StandbyValidators);
Mint(engine, account, 30_000_000 * Factor);
}
protected override void OnPersist(ApplicationEngine engine)
{
base.OnPersist(engine);
foreach (Transaction tx in engine.Snapshot.PersistingBlock.Transactions)
Burn(engine, tx.Sender, tx.SystemFee + tx.NetworkFee);
ECPoint[] validators = NEO.GetNextBlockValidators(engine.Snapshot);
UInt160 primary = Contract.CreateSignatureRedeemScript(validators[engine.Snapshot.PersistingBlock.ConsensusData.PrimaryIndex]).ToScriptHash();
Mint(engine, primary, engine.Snapshot.PersistingBlock.Transactions.Sum(p => p.NetworkFee));
}
}
}
| mit | C# |
1b71760d2a6302aa1f33f204a6a39ecc5daaa873 | Update version number for next release | florinszilagyi/PnP-PowerShell,pschaeflein/PnP-PowerShell,PieterVeenstra/PnP-PowerShell,Segelfeldt/PnP-PowerShell,OfficeDev/PnP-PowerShell,comblox/PnP-PowerShell,kilasuit/PnP-PowerShell,Oaden/PnP-PowerShell,sps130/PnP-PowerShell,artokai/PnP-PowerShell,larray/PowerShell,iiunknown/PnP-PowerShell | Commands/Properties/AssemblyInfo.cs | Commands/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OfficeDevPnP.PowerShell.Commands")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OfficeDevPnP.PowerShell.Commands")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2eebc303-84d4-4dbb-96de-8aaa75248120")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.1115.0")]
[assembly: AssemblyFileVersion("1.8.1115.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("OfficeDevPnP.PowerShell.Commands")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("OfficeDevPnP.PowerShell.Commands")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2eebc303-84d4-4dbb-96de-8aaa75248120")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.7.1015.0")]
[assembly: AssemblyFileVersion("1.7.1015.0")]
| mit | C# |
b0a50208cab7c65d1bf1e562f57d1aabc1915a10 | Fix documentation | wrightg42/enigma-simulator,It423/enigma-simulator | Enigma/Enigma/MachineSetup.xaml.cs | Enigma/Enigma/MachineSetup.xaml.cs | // MachineSetup.xaml.cs
// <copyright file="MachineSetup.xaml.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EnigmaUtilities;
using EnigmaUtilities.Components;
namespace Enigma
{
/// <summary>
/// Interaction logic for MachineSetup.xaml
/// </summary>
public partial class MachineSetup : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="MachineSetup" /> class.
/// </summary>
public MachineSetup()
{
this.InitializeComponent();
}
/// <summary>
/// Begins encryption using the current enigma settings.
/// </summary>
/// <param name="sender"> The origin of the event. </param>
/// <param name="e"> The event arguments. </param>
private void Begin_Click(object sender, RoutedEventArgs e)
{
// Use settings to create enigma machine instance
////EnigmaMachine em = new EnigmaMachine(...);
// Create encryption window
////EnigmaWriter ew = new EnigmaWriter(em);
// Show encryptor, hide settings
////ew.Show();
this.Close();
}
}
}
| // MachineSetup.xaml.cs
// <copyright file="MachineSetup.xaml.cs"> This code is protected under the MIT License. </copyright>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using EnigmaUtilities;
using EnigmaUtilities.Components;
namespace Enigma
{
/// <summary>
/// Interaction logic for MachineSetup.xaml
/// </summary>
public partial class MachineSetup : Window
{
/// <summary>
/// Initializes a new instance of the <see cref="MachineSetup" /> class.
/// </summary>
public MachineSetup()
{
this.InitializeComponent();
}
/// <summary>
/// Beigns encryption using the current enigma settings.
/// </summary>
/// <param name="sender"> The origin of the event. </param>
/// <param name="e"> The event arguments. </param>
private void Begin_Click(object sender, RoutedEventArgs e)
{
// Use settings to create enigma machine instance
////EnigmaMachine em = new EnigmaMachine(...);
// Create encryption window
////EnigmaWriter ew = new EnigmaWriter(em);
// Show encryptor, hide settings
////ew.Show();
this.Close();
}
}
}
| mit | C# |
48e85e5284f5a852c7ad2c95a42a181a83c20c1c | Comment fix | vvolkgang/XUTSample.Twitter | Evolve2016Twitter/TwitterUiTest.cs | Evolve2016Twitter/TwitterUiTest.cs | using NUnit.Framework;
using System;
using Xamarin.UITest.Android;
using System.Reflection;
using System.IO;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
using System.Linq;
using Evolve2016Twitter;
namespace Evolve2016Twitter.UITest
{
[TestFixture]
public class TwitterUiTest : BaseTestFixture
{
private const string _username = "CHAMGE_ME";
private const string _password = "CHANGE_ME";
private readonly string _tweet = $"@XamarinHQ #TweetCeption from device {DeviceId} in #TestCloud. Check #DementedVice and @vvolkgang for results!";
private static string DeviceId => Environment.GetEnvironmentVariable("XTC_DEVICE_INDEX") ?? "1";
[Test]
public void Login_and_tweet()
{
//LOGIN
_app.WaitTapWait(_queries.LoginInFirstViewButton, "Given I'm in the initial view",
_queries.Username, "When I tap Login button, I'm presented with the Login view");
_app.WaitAndEnterText(_queries.Username, _username, "After I insert my Username, I can see the username field filled");
_app.WaitAndEnterText(_queries.Password, _password, "After I insert my Password, I can see the password field filled");
_app.TapAndWait(_queries.LoginButton, _queries.OkButton, "When I tap the Login button, I can see the Logged in view");
_app.Tap(_queries.OkButton); //NOTE(vvolkgang) this is the "Twitter would like to use your location" dialog
_app.Screenshot("After I login, I can see the twitter timeline");
//TWEET
_app.TapAndWait(_queries.CreateNewTweet, _queries.TweetBox, "After I tap the Whats Happening box, I can see the tweet composer");
_app.EnterText(_queries.TweetBox, _tweet );
_app.Screenshot("After I insert my tweet, I can see the composer view filled");
_app.TapAndWait(_queries.SendTweetButton, _queries.CreateNewTweet, "When I tap Tweet button, I'm back to the timeline");
}
}
}
| using NUnit.Framework;
using System;
using Xamarin.UITest.Android;
using System.Reflection;
using System.IO;
using Xamarin.UITest;
using Xamarin.UITest.Queries;
using System.Linq;
using Evolve2016Twitter;
namespace Evolve2016Twitter.UITest
{
[TestFixture]
public class TwitterUiTest : BaseTestFixture
{
private const string _username = "CHAMGE_ME";
private const string _password = "CHANGE_ME";
private readonly string _tweet = $"@XamarinHQ #TweetCeption from device {DeviceId} in #TestCloud. Check #DementedVice and @vvolkgang for results!";
private static string DeviceId => Environment.GetEnvironmentVariable("XTC_DEVICE_INDEX") ?? "1";
[Test]
public void Login_and_tweet()
{
//LOGIN
_app.WaitTapWait(_queries.LoginInFirstViewButton, "Given I'm in the initial view",
_queries.Username, "When I tap Login button, I'm presented with the Login view");
_app.WaitAndEnterText(_queries.Username, _username, "After I insert my Username, I can see the username field filled");
_app.WaitAndEnterText(_queries.Password, _password, "After I insert my Password, I can see the password field filled");
_app.TapAndWait(_queries.LoginButton, _queries.OkButton, "When I tap the Login button, I can see the Logged in view");
_app.Tap(_queries.OkButton); //NOTE(avfe) this is the "Twitter would like to use your location" dialog
_app.Screenshot("After I login, I can see the twitter timeline");
//TWEET
_app.TapAndWait(_queries.CreateNewTweet, _queries.TweetBox, "After I tap the Whats Happening box, I can see the tweet composer");
_app.EnterText(_queries.TweetBox, _tweet );
_app.Screenshot("After I insert my tweet, I can see the composer view filled");
_app.TapAndWait(_queries.SendTweetButton, _queries.CreateNewTweet, "When I tap Tweet button, I'm back to the timeline");
}
}
}
| mit | C# |
1fdeb21012c8f474e83ded00001ac754c0c88c04 | Bump version to 1.5 | hudl/Mjolnir,courtneyklatt/Mjolnir | Hudl.Mjolnir/Properties/AssemblyInfo.cs | Hudl.Mjolnir/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("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Isolation library for protecting against cascading failure.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyInformationalVersion("1.5.0.0")]
[assembly: AssemblyFileVersion("1.5.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Hudl.Mjolnir")]
[assembly: AssemblyDescription("Isolation library for protecting against cascading failure.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Hudl")]
[assembly: AssemblyProduct("Hudl.Mjolnir")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
[assembly: InternalsVisibleTo("Hudl.Mjolnir.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("97b23684-6c4a-4749-b307-5867cbce2dff")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyInformationalVersion("1.4.0.0")]
[assembly: AssemblyFileVersion("1.4.0.0")]
[assembly: AssemblyVersion("1.0.0.0")]
| apache-2.0 | C# |
167e225dda6cfc4251f5541238686b294cd2e159 | Increase version number | pratoservices/extjswebdriver,pratoservices/extjswebdriver,pratoservices/extjswebdriver | ExtjsWd/Properties/AssemblyInfo.cs | ExtjsWd/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ExtjsWd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ExtjsWd")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efc31b18-7c2f-44f2-a1f3-4c49b28f409c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.3")]
[assembly: AssemblyFileVersion("1.0.0.3")] | 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("ExtjsWd")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("ExtjsWd")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("efc31b18-7c2f-44f2-a1f3-4c49b28f409c")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.2")]
[assembly: AssemblyFileVersion("1.0.0.2")]
| mit | C# |
a4c550fb05d1df8c3def51514169183f771461bb | add additional encoding providers through reflection | Scandit/barcodescanner-sdk-xamarin-samples,Scandit/barcodescanner-sdk-xamarin-samples | Unified/SimpleSample/SimpleSample/UWP/MainPage.xaml.cs | Unified/SimpleSample/SimpleSample/UWP/MainPage.xaml.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace SimpleSample.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
// required if you are scanning codes with more "exotic" encodings such as Kanji.
// Without this call, the data can't be converted to UTF-8.
this.SetupAdditionalEncodingProviders();
LoadApplication(new SimpleSample.App());
}
// setup additional encoding providers using reflection. In your own application, it's typically sufficient to just
// call Encoding.RegisterProvider(CodePagesEncodingProvider.Instance). We use reflection to make this also work with
// older .NET versions that don't yet have the functionality.
private void SetupAdditionalEncodingProviders()
{
var encodingType = Type.GetType("System.Text.Encoding, Windows, ContentType=WindowsRuntime");
var codePagesEncodingProviderType = Type.GetType("System.Text.CodePagesEncodingProvider, Windows, ContentType=WindowsRuntime");
if (encodingType == null || codePagesEncodingProviderType == null)
{
return;
}
var registerProviderMethod = encodingType.GetRuntimeMethod("RegisterProvider", new Type[] { codePagesEncodingProviderType });
var instanceProperty = codePagesEncodingProviderType.GetRuntimeProperty("Instance");
if (registerProviderMethod == null || instanceProperty == null)
{
return;
}
try
{
var theInstance = instanceProperty.GetValue(null);
if (theInstance == null)
{
return;
}
registerProviderMethod.Invoke(null, new object[] { theInstance });
}
catch (TargetInvocationException)
{
return;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
namespace SimpleSample.UWP
{
public sealed partial class MainPage
{
public MainPage()
{
this.InitializeComponent();
// required if you are scanning codes with more "exotic" encodings such as Kanji.
// Without this call, the data can't be converted to UTF-8.
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
LoadApplication(new SimpleSample.App());
}
}
}
| apache-2.0 | C# |
02cc38f957e94973afe0c64f6e40a64bd2ccc624 | Add SetMethod & GetMethod Property | AspectCore/AspectCore-Framework,AspectCore/Abstractions,AspectCore/Lite,AspectCore/AspectCore-Framework | src/AspectCore.Lite.Abstractions.Generator/PropertyGenerator.cs | src/AspectCore.Lite.Abstractions.Generator/PropertyGenerator.cs | using System;
using System.Reflection;
using System.Reflection.Emit;
namespace AspectCore.Lite.Abstractions.Generator
{
public abstract class PropertyGenerator : AbstractGenerator<TypeBuilder, PropertyBuilder>
{
public abstract string PropertyName { get; }
public abstract PropertyAttributes PropertyAttributes { get; }
public abstract CallingConventions CallingConventions { get; }
public abstract Type ReturnType { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
public abstract MethodInfo GetMethod { get; }
public abstract MethodInfo SetMethod { get; }
public virtual Type[] ParameterTypes
{
get
{
return Type.EmptyTypes;
}
}
public PropertyGenerator(TypeBuilder declaringMember) : base(declaringMember)
{
}
protected override PropertyBuilder ExecuteBuild()
{
var propertyBuilder = DeclaringMember.DefineProperty(PropertyName, PropertyAttributes, CallingConventions, ReturnType, ParameterTypes);
if (CanRead)
{
var readMethodGenerator = GetReadMethodGenerator(DeclaringMember);
propertyBuilder.SetGetMethod(readMethodGenerator.Build());
}
if (CanWrite)
{
var writeMethodGenerator = GetWriteMethodGenerator(DeclaringMember);
propertyBuilder.SetSetMethod(writeMethodGenerator.Build());
}
return propertyBuilder;
}
protected abstract MethodGenerator GetReadMethodGenerator(TypeBuilder declaringType);
protected abstract MethodGenerator GetWriteMethodGenerator(TypeBuilder declaringType);
}
}
| using System;
using System.Reflection;
using System.Reflection.Emit;
namespace AspectCore.Lite.Abstractions.Generator
{
public abstract class PropertyGenerator : AbstractGenerator<TypeBuilder, PropertyBuilder>
{
public abstract string PropertyName { get; }
public abstract PropertyAttributes PropertyAttributes { get; }
public abstract CallingConventions CallingConventions { get; }
public abstract Type ReturnType { get; }
public abstract bool CanRead { get; }
public abstract bool CanWrite { get; }
public virtual Type[] ParameterTypes
{
get
{
return Type.EmptyTypes;
}
}
public PropertyGenerator(TypeBuilder declaringMember) : base(declaringMember)
{
}
protected override PropertyBuilder ExecuteBuild()
{
var propertyBuilder = DeclaringMember.DefineProperty(PropertyName, PropertyAttributes, CallingConventions, ReturnType, ParameterTypes);
if (CanRead)
{
var readMethodGenerator = GetReadMethodGenerator(DeclaringMember);
propertyBuilder.SetGetMethod(readMethodGenerator.Build());
}
if (CanWrite)
{
var writeMethodGenerator = GetWriteMethodGenerator(DeclaringMember);
propertyBuilder.SetSetMethod(writeMethodGenerator.Build());
}
return propertyBuilder;
}
protected abstract MethodGenerator GetReadMethodGenerator(TypeBuilder declaringType);
protected abstract MethodGenerator GetWriteMethodGenerator(TypeBuilder declaringType);
}
}
| mit | C# |
8add79af05b86f9907b0d58273a4dccd0619e2d7 | increase version to match home | fredatgithub/DeleteLine | DeleteLine/Properties/AssemblyInfo.cs | DeleteLine/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("DeleteLine")]
[assembly: AssemblyDescription("Delete lines in a csv file")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeleteLine")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("ff050d32-0509-4a4c-8894-2ccddd36414c")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.14.0.0")]
[assembly: AssemblyFileVersion("1.14.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("DeleteLine")]
[assembly: AssemblyDescription("Delete lines in a csv file")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DeleteLine")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("ff050d32-0509-4a4c-8894-2ccddd36414c")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.8.0.0")]
[assembly: AssemblyFileVersion("1.8.0.0")]
| mit | C# |
b7ced1ff8db50b3a69ecf4e9ebe4e2508c7a9cd6 | Add PKIX key blob formats | ektrah/nsec | src/Cryptography/KeyBlobFormat.cs | src/Cryptography/KeyBlobFormat.cs | namespace NSec.Cryptography
{
public enum KeyBlobFormat
{
None = 0,
// --- Secret Key Formats ---
RawSymmetricKey = -1,
RawPrivateKey = -2,
NSecSymmetricKey = -101,
NSecPrivateKey = -102,
PkixPrivateKey = -202,
PkixPrivateKeyText = -203,
// --- Public Key Formats ---
RawPublicKey = 1,
NSecPublicKey = 101,
PkixPublicKey = 201,
PkixPublicKeyText = 202,
}
}
| namespace NSec.Cryptography
{
public enum KeyBlobFormat
{
None = 0,
// --- Secret Key Formats ---
RawSymmetricKey = -1,
RawPrivateKey = -2,
NSecSymmetricKey = -101,
NSecPrivateKey = -102,
// --- Public Key Formats ---
RawPublicKey = 1,
NSecPublicKey = 101,
}
}
| mit | C# |
8b770b3e41f45d8d7ebc00e3994fcaf93d3be25d | Fix for randomBase64, it was filling a full internal array unnecessarily. | louthy/language-ext,StefanBertels/language-ext,StanJav/language-ext | LanguageExt.Core/Prelude_Random.cs | LanguageExt.Core/Prelude_Random.cs | using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace LanguageExt
{
public static partial class Prelude
{
readonly static RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
readonly static byte[] inttarget = new byte[4];
/// <summary>
/// Thread-safe cryptographically strong random number generator
/// </summary>
/// <param name="max">Maximum value to return + 1</param>
/// <returns>A non-negative random number, less than the value specified.</returns>
public static int random(int max)
{
lock (rnd)
{
rnd.GetBytes(inttarget);
return Math.Abs(BitConverter.ToInt32(inttarget, 0)) % max;
}
}
/// <summary>
/// Thread-safe cryptographically strong random base-64 string generator
/// </summary>
/// <param name="count">bytesCount - number of bytes generated that are then
/// returned Base64 encoded</param>
/// <returns>Base64 encoded random string</returns>
public static string randomBase64(int bytesCount)
{
if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1");
var bytes = new byte[bytesCount];
rnd.GetBytes(bytes);
return Convert.ToBase64String(bytes);
}
}
} | using System;
using System.Collections.Generic;
using System.Security.Cryptography;
namespace LanguageExt
{
public static partial class Prelude
{
readonly static RNGCryptoServiceProvider rnd = new RNGCryptoServiceProvider();
readonly static byte[] target = new byte[4096];
/// <summary>
/// Thread-safe cryptographically strong random number generator
/// </summary>
/// <param name="max">Maximum value to return + 1</param>
/// <returns>A non-negative random number, less than the value specified.</returns>
public static int random(int max)
{
lock (rnd)
{
rnd.GetBytes(target);
return Math.Abs(BitConverter.ToInt32(target, 0)) % max;
}
}
/// <summary>
/// Thread-safe cryptographically strong random base-64 string generator
/// </summary>
/// <param name="count">bytesCount - number of bytes generated that are then
/// returned Base64 encoded</param>
/// <returns>Base64 encoded random string</returns>
public static string randomBase64(int bytesCount)
{
if (bytesCount < 1) throw new ArgumentException($"The minimum value for {nameof(bytesCount)} is 1");
if (bytesCount > 4096) throw new ArgumentException($"The maximum value for {nameof(bytesCount)} is 4096");
lock (rnd)
{
rnd.GetBytes(target);
return Convert.ToBase64String(target);
}
}
}
} | mit | C# |
1529de75d1af00fc5c57f8f08faff3361c6b8c3c | Bump version to 1.3.0 | mwilliamson/dotnet-mammoth | Mammoth/Properties/AssemblyInfo.cs | Mammoth/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Mammoth")]
[assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Williamson")]
[assembly: AssemblyProduct("Mammoth")]
[assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.3.0.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("Mammoth")]
[assembly: AssemblyDescription("Convert Word documents from docx to simple HTML")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Michael Williamson")]
[assembly: AssemblyProduct("Mammoth")]
[assembly: AssemblyCopyright("Copyright © Michael Williamson 2015 - 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("0.0.2.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| bsd-2-clause | C# |
6f9181230b9ae86923f96d2cbcdc2896638f7ad3 | Use of IsDefaultCollapsed | JetBrains/Nitra,rsdn/nitra,rsdn/nitra,JetBrains/Nitra | N2.Visualizer/N2FoldingStrategy.cs | N2.Visualizer/N2FoldingStrategy.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Document;
namespace N2.Visualizer
{
public sealed class N2FoldingStrategy : AbstractFoldingStrategy
{
public override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
{
var parseResult = ParseResult;
if (parseResult == null)
{
firstErrorOffset = 0;
return Enumerable.Empty<NewFolding>();
}
var outlining = new List<OutliningInfo>();
parseResult.GetOutlining(outlining);
var result = new List<NewFolding>();
foreach (var o in outlining)
{
var newFolding = new NewFolding
{
DefaultClosed = o.IsDefaultCollapsed,
StartOffset = o.Span.StartPos,
EndOffset = o.Span.EndPos
};
result.Add(newFolding);
}
result.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
firstErrorOffset = 0;
return result;
}
public ParseResult ParseResult { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.AvalonEdit.Folding;
using ICSharpCode.AvalonEdit.Document;
namespace N2.Visualizer
{
public sealed class N2FoldingStrategy : AbstractFoldingStrategy
{
public override IEnumerable<NewFolding> CreateNewFoldings(TextDocument document, out int firstErrorOffset)
{
var parseResult = ParseResult;
if (parseResult == null)
{
firstErrorOffset = 0;
return Enumerable.Empty<NewFolding>();
}
var outlining = new List<OutliningInfo>();
parseResult.GetOutlining(outlining);
var result = new List<NewFolding>();
foreach (var o in outlining)
{
var newFolding = new NewFolding
{
DefaultClosed = false,
StartOffset = o.Span.StartPos,
EndOffset = o.Span.EndPos
};
result.Add(newFolding);
}
result.Sort((a, b) => a.StartOffset.CompareTo(b.StartOffset));
firstErrorOffset = 0;
return result;
}
public ParseResult ParseResult { get; set; }
}
}
| apache-2.0 | C# |
29be4a8e16cc985f1d0f7cb9d094066378f1f580 | Update fix | dimmpixeye/Unity3dTools | Editor/Helpers/HelperReturnClick.cs | Editor/Helpers/HelperReturnClick.cs | /*===============================================================
Product: Cryoshock
Developer: Dimitry Pixeye - pixeye@hbrew.store
Company: Homebrew - http://hbrew.store
Date: 2/5/2018 2:42 PM
================================================================*/
using UnityEditor;
using UnityEngine;
namespace Pixeye.Framework
{
[InitializeOnLoad]
public class HelperReturnClick
{
static HelperReturnClick()
{
#if UNITY_2019_1_OR_NEWER
SceneView.duringSceneGui += SceneGUI;
#else
SceneView.onSceneGUIDelegate += SceneGUI;
#endif
}
static void SceneGUI(SceneView sceneView)
{
if (!Event.current.alt) return;
if (Event.current.button != 1) return;
var pos = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(Event.current.mousePosition);
Debug.Log("Click position is: <b>" + pos + "</b>");
}
}
} | /*===============================================================
Product: Cryoshock
Developer: Dimitry Pixeye - pixeye@hbrew.store
Company: Homebrew - http://hbrew.store
Date: 2/5/2018 2:42 PM
================================================================*/
using UnityEditor;
using UnityEngine;
namespace Pixeye.Framework
{
[InitializeOnLoad]
public class HelperReturnClick
{
static HelperReturnClick()
{
SceneView.duringSceneGui += SceneGUI;
}
static void SceneGUI(SceneView sceneView)
{
if (!Event.current.alt) return;
if (Event.current.button!=1) return;
var pos = SceneView.currentDrawingSceneView.camera.ScreenToWorldPoint(Event.current.mousePosition);
Debug.Log("Click position is: <b>" + pos + "</b>");
}
}
} | mit | C# |
208ab9784651a4208b5f2c4e003363c0fe427431 | implement calcintegratedwatts | Surigoma/PVDataProcessor | PVDataProcessor/Tool/Processing.cs | PVDataProcessor/Tool/Processing.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PVDataProcessor.Tool
{
class Processing
{
public double CalcIntegratedWatts(PH[] PHdata, int interval)
{
double result=0.0;
for (int i = 0; i < PHdata.Length; i++)
{
result += (interval / 3600) * PHdata[i].Watts;
}
return result;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace PVDataProcessor.Tool
{
class Processing
{
public double CalcIntegratedWatts(PH[] PHdata, )
{
return 0.0;
}
}
}
| apache-2.0 | C# |
5de623dfb98410ae21e011484ed1488ddff95786 | Add test Notes.UpdateTest.WithTag | orodriguez/FTF,orodriguez/FTF,orodriguez/FTF | FTF.Tests.XUnit/Notes/UpdateTest.cs | FTF.Tests.XUnit/Notes/UpdateTest.cs | using System;
using System.Linq;
using FTF.Api.Exceptions;
using Xunit;
namespace FTF.Tests.XUnit.Notes
{
public class UpdateTest : UserAuthenticatedTest
{
[Fact]
public void SimpleTextUpdate()
{
CurrentTime = new DateTime(2016, 2, 20);
var noteId = App.Notes.Create("Buy cheese");
App.Notes.Update(noteId, "Buy american cheese");
var note = App.Notes.Retrieve(noteId);
Assert.Equal("Buy american cheese", note.Text);
Assert.Equal(new DateTime(2016,2,20), note.CreationDate);
Assert.Equal("orodriguez", note.UserName);
}
[Fact]
public void WithTags()
{
var noteId = App.Notes.Create("Note without tag");
App.Notes.Update(noteId, "A Note with #some #tags");
var note = App.Notes.Retrieve(noteId);
Assert.Equal(new[] { "some", "tags" }, note.Tags.Select(n => n.Name));
}
[Fact]
public void EmptyText()
{
var noteId = App.Notes.Create("Buy cheese");
var error = Assert.Throws<ValidationException>(() => App.Notes.Update(noteId, ""));
Assert.Equal("Note can not be empty", error.Message);
}
}
}
| using System;
using FTF.Api.Exceptions;
using Xunit;
namespace FTF.Tests.XUnit.Notes
{
public class UpdateTest : UserAuthenticatedTest
{
[Fact]
public void SimpleTextUpdate()
{
CurrentTime = new DateTime(2016, 2, 20);
var noteId = App.Notes.Create("Buy cheese");
App.Notes.Update(noteId, "Buy american cheese");
var note = App.Notes.Retrieve(noteId);
Assert.Equal("Buy american cheese", note.Text);
Assert.Equal(new DateTime(2016,2,20), note.CreationDate);
Assert.Equal("orodriguez", note.UserName);
}
[Fact]
public void EmptyText()
{
var noteId = App.Notes.Create("Buy cheese");
var error = Assert.Throws<ValidationException>(() => App.Notes.Update(noteId, ""));
Assert.Equal("Note can not be empty", error.Message);
}
}
}
| mit | C# |
853ec5f823b50db3b63c314d22ea6bc007e0071a | Fix compile errors | mmkiwi/KwMusicTools,mmkiwi/KwMusicTools | SpotifyImporter/MainWindow.xaml.cs | SpotifyImporter/MainWindow.xaml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace SpotifyImporter
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Do_Things_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("Oi m8");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SpotifyWebAPI;
namespace SpotifyImporter
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Do_Things_Click(object sender, RoutedEventArgs e)
{
Console.WriteLine("Oi m8");
SpotifyWebAPI.
}
}
}
| apache-2.0 | C# |
995e9de5a183a748bd0ab63ec465a2c750a249c2 | implement additional properties in FileAttributesTag | Alexx999/SwfSharp | SwfSharp/Tags/FileAttributesTag.cs | SwfSharp/Tags/FileAttributesTag.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SwfSharp.Utils;
namespace SwfSharp.Tags
{
public class FileAttributesTag : SwfTag
{
public FileAttributesTag(int size)
: base(TagType.FileAttributes, size)
{
}
public bool UseDirectBlit { get; set; }
public bool UseGPU { get; set; }
public bool HasMetadata { get; set; }
public bool ActionScript3 { get; set; }
public bool SuppressCrossDomainCaching { get; set; }
public bool SwfRelativeUrls { get; set; }
public bool UseNetwork { get; set; }
internal override void FromStream(BitReader reader, byte swfVersion)
{
reader.ReadBits(1);
UseDirectBlit = reader.ReadBoolBit();
UseGPU = reader.ReadBoolBit();
HasMetadata = reader.ReadBoolBit();
ActionScript3 = reader.ReadBoolBit();
SuppressCrossDomainCaching = reader.ReadBoolBit();
SwfRelativeUrls = reader.ReadBoolBit();
UseNetwork = reader.ReadBoolBit();
reader.ReadUI24();
}
internal override void ToStream(BitWriter writer, byte swfVersion)
{
writer.WriteBits(1, 0);
writer.WriteBoolBit(UseDirectBlit);
writer.WriteBoolBit(UseGPU);
writer.WriteBoolBit(HasMetadata);
writer.WriteBoolBit(ActionScript3);
writer.WriteBoolBit(SuppressCrossDomainCaching);
writer.WriteBoolBit(SwfRelativeUrls);
writer.WriteBoolBit(UseNetwork);
writer.WriteUI24(0);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SwfSharp.Utils;
namespace SwfSharp.Tags
{
public class FileAttributesTag : SwfTag
{
public FileAttributesTag(int size)
: base(TagType.FileAttributes, size)
{
}
public bool UseDirectBlit { get; set; }
public bool UseGPU { get; set; }
public bool HasMetadata { get; set; }
public bool ActionScript3 { get; set; }
public bool UseNetwork { get; set; }
internal override void FromStream(BitReader reader, byte swfVersion)
{
reader.ReadBits(1);
UseDirectBlit = reader.ReadBoolBit();
UseGPU = reader.ReadBoolBit();
HasMetadata = reader.ReadBoolBit();
ActionScript3 = reader.ReadBoolBit();
reader.ReadBits(2);
UseNetwork = reader.ReadBoolBit();
reader.ReadUI24();
}
internal override void ToStream(BitWriter writer, byte swfVersion)
{
writer.WriteBits(1, 0);
writer.WriteBoolBit(UseDirectBlit);
writer.WriteBoolBit(UseGPU);
writer.WriteBoolBit(HasMetadata);
writer.WriteBoolBit(ActionScript3);
writer.WriteBits(2, 0);
writer.WriteBoolBit(UseNetwork);
writer.WriteUI24(0);
}
}
}
| mit | C# |
1e57c679e648134f16bf1ef9d5efcc7539d3fbc3 | Make tests of converters possible | LordMike/TMDbLib | TMDbLib/Properties/AssemblyInfo.cs | TMDbLib/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: AssemblyConfiguration("")]
// 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("c8cd805d-f17a-4919-9adb-b5f50d72f32a")]
[assembly: InternalsVisibleTo("TMDbLibTests")] | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
// 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("c8cd805d-f17a-4919-9adb-b5f50d72f32a")] | mit | C# |
83b919ff370254173550ff53c7107acc9be43f72 | Add a way to measure how long it took to read a binlog file. | KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog | src/StructuredLogger/BinaryLog.cs | src/StructuredLogger/BinaryLog.cs | using System.Diagnostics;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.SourceArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
| namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.SourceArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
eventSource.Replay(filePath);
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
build.SourceFilesArchive = sourceArchive;
return build;
}
}
}
| mit | C# |
8e30d300aaf59a4ff318aaa50fe56b6107f386e8 | Use ICustomAttributeProvider.IsDefined in `HasAttribute` to avoid allocations. | IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce,IntelliTect/Coalesce | src/IntelliTect.Coalesce/TypeDefinition/Helpers/ReflectionExtensions.cs | src/IntelliTect.Coalesce/TypeDefinition/Helpers/ReflectionExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace IntelliTect.Coalesce.TypeDefinition
{
public static class ReflectionExtensions
{
/// <summary>
/// Returns the attributed requested if it exists or null if it does not.
/// </summary>
/// <typeparam name="TAttribute"></typeparam>
/// <returns></returns>
public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
{
var attributes = member.GetCustomAttributes(typeof(TAttribute), true);
return attributes.FirstOrDefault() as TAttribute;
}
/// <summary>
/// Returns true if the attribute exists.
/// </summary>
/// <typeparam name="TAttribute"></typeparam>
/// <returns></returns>
public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
{
return member.IsDefined(typeof(TAttribute), true);
}
public static Object GetAttributeValue<TAttribute>(this ICustomAttributeProvider member, string valueName) where TAttribute : Attribute
{
var attr = member.GetAttribute<TAttribute>();
if (attr != null)
{
var property = attr.GetType().GetProperty(valueName);
if (property == null) return null;
// TODO: Some properties throw an exception here. DisplayAttribute.Order. Not sure why.
try
{
return property.GetValue(attr, null);
}
catch (Exception)
{
return null;
}
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace IntelliTect.Coalesce.TypeDefinition
{
public static class ReflectionExtensions
{
/// <summary>
/// Returns the attributed requested if it exists or null if it does not.
/// </summary>
/// <typeparam name="TAttribute"></typeparam>
/// <returns></returns>
public static TAttribute GetAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
{
var attributes = member.GetCustomAttributes(typeof(TAttribute), true);
return attributes.FirstOrDefault() as TAttribute;
}
/// <summary>
/// Returns true if the attribute exists.
/// </summary>
/// <typeparam name="TAttribute"></typeparam>
/// <returns></returns>
public static bool HasAttribute<TAttribute>(this ICustomAttributeProvider member) where TAttribute : Attribute
{
return member.GetAttribute<TAttribute>() != null;
}
public static Object GetAttributeValue<TAttribute>(this ICustomAttributeProvider member, string valueName) where TAttribute : Attribute
{
var attr = member.GetAttribute<TAttribute>();
if (attr != null)
{
var property = attr.GetType().GetProperty(valueName);
if (property == null) return null;
// TODO: Some properties throw an exception here. DisplayAttribute.Order. Not sure why.
try {
return property.GetValue(attr, null);
}
catch (Exception)
{
return null;
}
}
return null;
}
}
}
| apache-2.0 | C# |
c7bc6caf37063ed3c437d1cea650a1818c862f05 | Fix the build | tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server | tests/Tgstation.Server.Host.Tests/System/TestProcessFeatures.cs | tests/Tgstation.Server.Host.Tests/System/TestProcessFeatures.cs | using Castle.Core.Logging;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Threading.Tasks;
using Tgstation.Server.Host.IO;
namespace Tgstation.Server.Host.System.Tests
{
/// <summary>
/// Tests for <see cref="IProcessFeatures"/>.
/// </summary>
[TestClass]
public sealed class TestProcessFeatures
{
IProcessFeatures features;
[TestInitialize]
public void Init()
{
features = new PlatformIdentifier().IsWindows
? (IProcessFeatures)new WindowsProcessFeatures(Mock.Of<ILogger<WindowsProcessFeatures>>())
: new PosixProcessFeatures(new Lazy<IProcessExecutor>(() => null), new DefaultIOManager(), Mock.Of<ILogger<PosixProcessFeatures>>());
}
[TestMethod]
public async Task TestGetUsername()
{
if (!String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TRAVIS")))
Assert.Inconclusive("This test doesn't work on TRAVIS CI!");
var username = await features.GetExecutingUsername(global::System.Diagnostics.Process.GetCurrentProcess(), default);
Assert.IsTrue(username.Contains(Environment.UserName), $"Exepcted a string containing \"{Environment.UserName}\", got \"{username}\"");
}
}
}
| using Castle.Core.Logging;
using Microsoft.Extensions.Logging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System;
using System.Threading.Tasks;
using Tgstation.Server.Host.IO;
namespace Tgstation.Server.Host.System.Tests
{
/// <summary>
/// Tests for <see cref="IProcessFeatures"/>.
/// </summary>
[TestClass]
public sealed class TestProcessFeatures
{
IProcessFeatures features;
[TestInitialize]
public void Init()
{
features = new PlatformIdentifier().IsWindows
? (IProcessFeatures)new WindowsProcessFeatures(Mock.Of<ILogger<WindowsProcessFeatures>>())
: new PosixProcessFeatures(new DefaultIOManager(), Mock.Of<ILogger<PosixProcessFeatures>>());
}
[TestMethod]
public async Task TestGetUsername()
{
if (!String.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("TRAVIS")))
Assert.Inconclusive("This test doesn't work on TRAVIS CI!");
var username = await features.GetExecutingUsername(global::System.Diagnostics.Process.GetCurrentProcess(), default);
Assert.IsTrue(username.Contains(Environment.UserName), $"Exepcted a string containing \"{Environment.UserName}\", got \"{username}\"");
}
}
}
| agpl-3.0 | C# |
c9b6e5be80c671637e1e4efb2394547a903d55ca | Add new Methods | MarinPetrov/CSharpGame2048-OnlineTeamRain,MarinPetrov/CSharpGame2048-OnlineTeamRain | GameTeamRain/GameTeamRain/GameCore.cs | GameTeamRain/GameTeamRain/GameCore.cs | namespace GameTeamRain
{
using System;
using System.Collections.Generic;
class GameCore
{
private ushort[,] coreMatrix;
private Random randomNumber = new Random();
public GameCore()
{
this.coreMatrix = new ushort[4, 4];
InitCoreMatrix();
}
public void InitCoreMatrix()
{
}
public bool IsGameWon()
{
}
public bool IsGameLost()
{
}
public void addNewNumber()
{
}
public void PrintMatrix()
{
}
public bool ReCalculateMatrix(string direction)
{
}
public bool CalculateRightDirection()
{
}
public bool CalculateLeftDirection()
{
}
public bool CalculateUpDirection()
{
}
public bool CalculateDownDirection()
{
}
}
}
| namespace GameTeamRain
{
using System;
using System.Collections.Generic;
class GameCore
{
private ushort[,] coreMatrix;
private Random randomNumber = new Random();
public GameCore()
{
this.coreMatrix = new ushort[4, 4];
InitCoreMatrix();
}
public void InitCoreMatrix()
{
}
public bool IsGameWon()
{
}
public bool IsGameLost()
{
}
public void addNewNumber()
{
}
public void PrintMatrix()
{
}
}
}
| mit | C# |
f9a32427325901ed97cd13dd5ed360cf2bdee9e1 | Correct unit test namespace. | imazen/libwebp-net,imazen/libwebp-net,imazen/libwebp-net | Imazen.Test.Webp/TestSimpleEncoder.cs | Imazen.Test.Webp/TestSimpleEncoder.cs | using System;
using Xunit;
using Imazen.WebP;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using Imazen.WebP.Extern;
namespace Imazen.Test.WebP
{
public class TestSimpleEncoder
{
[Fact]
public void TestVersion(){
Imazen.WebP.Extern.LoadLibrary.LoadWebPOrFail();
Assert.Equal("0.4.0",SimpleEncoder.GetEncoderVersion());
}
[Fact]
public void TestEncSimple()
{
Imazen.WebP.Extern.LoadLibrary.LoadWebPOrFail();
var encoder = new SimpleEncoder();
var fileName = "testimage.jpg";
var outFileName = "testimageout.webp";
File.Delete(outFileName);
Bitmap mBitmap;
FileStream outStream = new FileStream(outFileName, FileMode.Create);
using (Stream BitmapStream = System.IO.File.Open(fileName, System.IO.FileMode.Open))
{
Image img = Image.FromStream(BitmapStream);
mBitmap = new Bitmap(img);
encoder.Encode(mBitmap, outStream, 100, false);
}
FileInfo finfo = new FileInfo(outFileName);
Assert.True(finfo.Exists);
}
}
}
| using System;
using Xunit;
using Imazen.WebP;
using System.IO;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
using Imazen.WebP.Extern;
namespace UnitTestProject1
{
public class TestSimpleEncoder
{
[Fact]
public void TestVersion(){
Imazen.WebP.Extern.LoadLibrary.LoadWebPOrFail();
Assert.Equal("0.4.0",SimpleEncoder.GetEncoderVersion());
}
[Fact]
public void TestEncSimple()
{
Imazen.WebP.Extern.LoadLibrary.LoadWebPOrFail();
var encoder = new SimpleEncoder();
var fileName = "testimage.jpg";
var outFileName = "testimageout.webp";
File.Delete(outFileName);
Bitmap mBitmap;
FileStream outStream = new FileStream(outFileName, FileMode.Create);
using (Stream BitmapStream = System.IO.File.Open(fileName, System.IO.FileMode.Open))
{
Image img = Image.FromStream(BitmapStream);
mBitmap = new Bitmap(img);
encoder.Encode(mBitmap, outStream, 100, false);
}
FileInfo finfo = new FileInfo(outFileName);
Assert.True(finfo.Exists);
}
}
}
| mit | C# |
3d139c24e769856fc3f6f851e0fdac741928507f | Update ArrayRingBuffer.cs | efruchter/UnityUtilities | MiscDataStructures/ArrayRingBuffer.cs | MiscDataStructures/ArrayRingBuffer.cs | using System.Collections.Generic;
/// <summary>
/// An array-based ring buffer. Faster random access than .NET Queue.
/// </summary>
public class ArrayRingBuffer<T> : IEnumerable<T>{
public readonly T[] array;
private int startingIndex = 0;
private int count;
public ArrayRingBuffer(int size, T defaultValue) {
array = new T[size];
for (int i = 0; i < array.Length; i++) {
array[i] = defaultValue;
}
}
public ArrayRingBuffer(int size) : this(size, default(T)) {
;
}
private int nextWriteIndex {
get {
return (startingIndex + count) % Capacity;
}
}
public void Enqueue(T t) {
array [nextWriteIndex] = t;
count++;
if (count > Capacity) {
startingIndex = CalculateIndex (1);
count = Capacity;
}
}
public T Last{
get{
return this [count - 1];
}
}
private int CalculateIndex(int relativeIndex) {
if (relativeIndex < 0 || relativeIndex >= Count) {
throw new System.ArgumentOutOfRangeException ("Index is out of range: " + relativeIndex);
}
return (startingIndex + relativeIndex) % Capacity;
}
public T this [int index] {
set {
array [CalculateIndex (index)] = value;
}
get {
return array [CalculateIndex (index)];
}
}
public int Capacity { get { return array.Length; } }
public int Count { get { return count; } }
#region IEnumerable implementation
public IEnumerator<T> GetEnumerator () {
for (int i = 0; i < Count; i++) {
yield return this [i];
}
}
#endregion
#region IEnumerable implementation
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {
return GetEnumerator ();
}
#endregion
public override string ToString() {
System.Text.StringBuilder str = new System.Text.StringBuilder ();
str.Append ("{");
foreach (var t in this) {
str.Append (" ");
str.Append (t);
str.Append (" ");
}
str.Append ("}");
return str.ToString ();
}
}
| /// <summary>
/// An array-based ring buffer. The internal array can be accessed directly if needed.
/// </summary>
public class ArrayRingBuffer<T> : IEnumerable<T> {
public readonly T[] array;
private int startingIndex = 0;
private int count;
public ArrayRingBuffer(int size, T defaultValue) {
array = new T[size];
for (int i = 0; i < array.Length; i++) {
array[i] = defaultValue;
}
}
public ArrayRingBuffer(int size) : this(size, default(T)) {
;
}
private int nextWriteIndex {
get {
return (startingIndex + count) % Capacity;
}
}
public void Enqueue(T t) {
array [nextWriteIndex] = t;
count++;
if (count > Capacity) {
startingIndex = CalculateIndex (1);
count = Capacity;
}
}
private int CalculateIndex(int relativeIndex) {
if (relativeIndex < 0 || relativeIndex >= Count) {
throw new System.ArgumentOutOfRangeException ("Index is out of range: " + relativeIndex);
}
return (startingIndex + relativeIndex) % Capacity;
}
public T this [int index] {
set {
array [CalculateIndex (index)] = value;
}
get {
return array [CalculateIndex (index)];
}
}
public int Capacity { get { return array.Length; } }
public int Count { get { return count; } }
#region IEnumerable implementation
public IEnumerator<T> GetEnumerator () {
for (int i = 0; i < Count; i++) {
yield return this [i];
}
}
#endregion
#region IEnumerable implementation
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator () {
return GetEnumerator ();
}
#endregion
public override string ToString() {
System.Text.StringBuilder str = new System.Text.StringBuilder ();
str.Append ("{");
foreach (var t in this) {
str.Append (" ");
str.Append (t);
str.Append (" ");
}
str.Append ("}");
return str.ToString ();
}
}
| mit | C# |
f1a2fd484e91284a0ed0e0a3ddafa031a7df6695 | fix shareddata 2 | NaamloosDT/ModCore,NaamloosDT/ModCore | ModCore/Listeners/UnbanTimerRemove.cs | ModCore/Listeners/UnbanTimerRemove.cs | using DSharpPlus.EventArgs;
using ModCore.Entities;
using ModCore.Logic;
using System.Threading.Tasks;
namespace ModCore.Listeners
{
public class UnbanTimerRemove
{
[AsyncListener(EventTypes.GuildBanRemoved)]
public static async Task CommandError(ModCoreShard bot, GuildBanRemoveEventArgs e)
{
var t = Timers.FindNearestTimer(TimerActionType.Unban, e.Member.Id, 0, e.Guild.Id, bot.Database);
if (t != null)
await Timers.UnscheduleTimerAsync(t, bot.Client, bot.Database, bot.SharedData);
}
}
}
| using DSharpPlus.EventArgs;
using ModCore.Entities;
using ModCore.Logic;
using System.Threading.Tasks;
namespace ModCore.Listeners
{
public class UnbanTimerRemove
{
[AsyncListener(EventTypes.GuildBanRemoved)]
public static async Task CommandError(ModCoreShard bot, GuildBanRemoveEventArgs e)
{
var t = Timers.FindNearestTimer(TimerActionType.Unban, e.Member.Id, 0, e.Guild.Id, bot.Database);
if (t != null)
await Timers.UnscheduleTimerAsync(t, bot.Client, bot.Database, bot.ShardData);
}
}
}
| mit | C# |
1e515f9d1becd654c8436c4ee8cf3d707d0214c7 | Add more examples to Implicit test #453 | mbdavid/LiteDB,RytisLT/LiteDB,RytisLT/LiteDB,89sos98/LiteDB,falahati/LiteDB,falahati/LiteDB,masterdidoo/LiteDB,masterdidoo/LiteDB,89sos98/LiteDB | LiteDB.Tests/Document/ImplicitTest.cs | LiteDB.Tests/Document/ImplicitTest.cs | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace LiteDB.Tests
{
[TestClass]
public class ImplicitTest
{
[TestMethod]
public void Implicit_Test()
{
int i = int.MaxValue;
long l = long.MaxValue;
ulong u = ulong.MaxValue;
BsonValue bi = i;
BsonValue bl = l;
BsonValue bu = u;
Assert.IsTrue(bi.IsInt32);
Assert.IsTrue(bl.IsInt64);
Assert.IsTrue(bu.IsDouble);
Assert.AreEqual(i, bi.AsInt32);
Assert.AreEqual(l, bl.AsInt64);
Assert.AreEqual(u, bu.AsDouble);
}
}
} | using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;
using System.Text;
namespace LiteDB.Tests
{
[TestClass]
public class ImplicitTest
{
[TestMethod]
public void Implicit_Test()
{
int i = 10;
long l = 20;
ulong ul = 99;
BsonValue bi = i;
BsonValue bl = l;
BsonValue bu = ul;
Assert.IsTrue(bi.IsInt32);
Assert.IsTrue(bl.IsInt64);
Assert.IsTrue(bu.IsDouble);
}
}
} | mit | C# |
5c8aa9437034819be1903dfffdfcdbb358b9ca00 | optimize version nummer | tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date | Nager.Date/Properties/AssemblyInfo.cs | Nager.Date/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("Nager.Date")]
[assembly: AssemblyDescription("Calculate Public Holiday for any Year")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nager.at")]
[assembly: AssemblyProduct("Nager.Date")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("13bd121f-1af4-429b-a596-1247d3f3f090")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.13")]
[assembly: AssemblyFileVersion("1.0.13")]
| 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("Nager.Date")]
[assembly: AssemblyDescription("Calculate Public Holiday for any Year")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("nager.at")]
[assembly: AssemblyProduct("Nager.Date")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("13bd121f-1af4-429b-a596-1247d3f3f090")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.13")]
[assembly: AssemblyFileVersion("1.0.0.13")]
| mit | C# |
204dcb636fb0b0a660c7e92767ba44f5b8a203bb | Add test TestMicrosoftNCSIAsync | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | MagicalCryptoWallet.Tests/TorTests.cs | MagicalCryptoWallet.Tests/TorTests.cs | using MagicalCryptoWallet.TorSocks5;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;
namespace MagicalCryptoWallet.Tests
{
// Tor must be running
public class TorTests : IClassFixture<SharedFixture>
{
private SharedFixture SharedFixture { get; }
public TorTests(SharedFixture fixture)
{
SharedFixture = fixture;
}
[Fact]
public async Task CanGetTwiceAsync()
{
using (var client = new TorHttpClient(new Uri("https://icanhazip.com/")))
{
await client.SendAsync(HttpMethod.Get, "");
await client.SendAsync(HttpMethod.Get, "");
}
}
[Fact]
public async Task CanDoRequest1Async()
{
using (var client = new TorHttpClient(new Uri("http://api.qbit.ninja")))
{
var contents = await QBitTestAsync(client, 1);
foreach (var content in contents)
{
Assert.Equal("\"Good question Holmes !\"", content);
}
}
}
[Fact]
public async Task CanRequestChunkEncodedAsync()
{
using (var client = new TorHttpClient(new Uri("https://jigsaw.w3.org/")))
{
var response = await client.SendAsync(HttpMethod.Get, "/HTTP/ChunkedScript");
var content = await response.Content.ReadAsStringAsync();
Assert.Equal(1000, Regex.Matches(content, "01234567890123456789012345678901234567890123456789012345678901234567890").Count);
}
}
[Fact]
public async Task TestMicrosoftNCSIAsync()
{
using (var client = new TorHttpClient(new Uri("http://www.msftncsi.com/")))
{
var response = await client.SendAsync(HttpMethod.Get, "ncsi.txt");
var content = await response.Content.ReadAsStringAsync();
Assert.Equal("Microsoft NCSI", content);
}
}
private static async Task<List<string>> QBitTestAsync(TorHttpClient client, int times, bool alterRequests = false)
{
var relativetUri = "/whatisit/what%20is%20my%20future";
var tasks = new List<Task<HttpResponseMessage>>();
for (var i = 0; i < times; i++)
{
var task = client.SendAsync(HttpMethod.Get, relativetUri);
if (alterRequests)
{
using (var ipClient = new TorHttpClient(new Uri("https://api.ipify.org/")))
{
var task2 = ipClient.SendAsync(HttpMethod.Get, "/");
tasks.Add(task2);
}
}
tasks.Add(task);
}
await Task.WhenAll(tasks);
var contents = new List<string>();
foreach (var task in tasks)
{
contents.Add(await (await task).Content.ReadAsStringAsync());
}
return contents;
}
}
}
| using MagicalCryptoWallet.TorSocks5;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Xunit;
namespace MagicalCryptoWallet.Tests
{
// Tor must be running
public class TorTests : IClassFixture<SharedFixture>
{
private SharedFixture SharedFixture { get; }
public TorTests(SharedFixture fixture)
{
SharedFixture = fixture;
}
[Fact]
public async Task CanGetTwiceAsync()
{
using (var client = new TorHttpClient(new Uri("https://icanhazip.com/")))
{
await client.SendAsync(HttpMethod.Get, "");
await client.SendAsync(HttpMethod.Get, "");
}
}
[Fact]
public async Task CanDoRequest1Async()
{
using (var client = new TorHttpClient(new Uri("http://api.qbit.ninja")))
{
var contents = await QBitTestAsync(client, 1);
foreach (var content in contents)
{
Assert.Equal("\"Good question Holmes !\"", content);
}
}
}
[Fact]
public async Task CanRequestChunkEncodedAsync()
{
using (var client = new TorHttpClient(new Uri("https://jigsaw.w3.org/")))
{
var response = await client.SendAsync(HttpMethod.Get, "/HTTP/ChunkedScript");
var content = await response.Content.ReadAsStringAsync();
Assert.Equal(1000, Regex.Matches(content, "01234567890123456789012345678901234567890123456789012345678901234567890").Count);
}
}
private static async Task<List<string>> QBitTestAsync(TorHttpClient client, int times, bool alterRequests = false)
{
var relativetUri = "/whatisit/what%20is%20my%20future";
var tasks = new List<Task<HttpResponseMessage>>();
for (var i = 0; i < times; i++)
{
var task = client.SendAsync(HttpMethod.Get, relativetUri);
if (alterRequests)
{
using (var ipClient = new TorHttpClient(new Uri("https://api.ipify.org/")))
{
var task2 = ipClient.SendAsync(HttpMethod.Get, "/");
tasks.Add(task2);
}
}
tasks.Add(task);
}
await Task.WhenAll(tasks);
var contents = new List<string>();
foreach (var task in tasks)
{
contents.Add(await (await task).Content.ReadAsStringAsync());
}
return contents;
}
}
}
| mit | C# |
4ed3b86793fd1a00736d5c50bf8bbdbfdca7af44 | Bump for v0.4.0 (#166) | jrick/Paymetheus,decred/Paymetheus | Paymetheus/Properties/AssemblyInfo.cs | Paymetheus/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Paymetheus Decred Wallet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Paymetheus")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("Organization", "Decred")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.4.0.0")]
[assembly: AssemblyFileVersion("0.4.0.0")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Paymetheus Decred Wallet")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Paymetheus")]
[assembly: AssemblyCopyright("Copyright © 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyMetadata("Organization", "Decred")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.0.0")]
[assembly: AssemblyFileVersion("0.3.0.0")]
| isc | C# |
1a85d495451d356f6b5ae0ff186e39986b732409 | Move to cake-contrib | Redth/Cake.Yaml | setup.cake | setup.cake | #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Yaml",
repositoryOwner: "cake-contrib",
repositoryName: "Cake.Yaml",
appVeyorAccountName: "cakecontrib",
shouldRunDotNetCorePack: true,
shouldRunDupFinder: false,
shouldRunInspectCode: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context,
dupFinderExcludePattern: new string[] {
BuildParameters.RootDirectoryPath + "/Cake.Yaml.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| #load nuget:https://www.myget.org/F/cake-contrib/api/v2?package=Cake.Recipe&prerelease
Environment.SetVariableNames();
BuildParameters.SetParameters(context: Context,
buildSystem: BuildSystem,
sourceDirectoryPath: "./src",
title: "Cake.Yaml",
repositoryOwner: "redth",
repositoryName: "Cake.Yaml",
appVeyorAccountName: "redth",
shouldRunDotNetCorePack: true,
shouldRunDupFinder: false,
shouldRunInspectCode: false);
BuildParameters.PrintParameters(Context);
ToolSettings.SetToolSettings(context: Context,
dupFinderExcludePattern: new string[] {
BuildParameters.RootDirectoryPath + "/Cake.Yaml.Tests/*.cs" },
testCoverageFilter: "+[*]* -[xunit.*]* -[Cake.Core]* -[Cake.Testing]* -[*.Tests]* -[FakeItEasy]*",
testCoverageExcludeByAttribute: "*.ExcludeFromCodeCoverage*",
testCoverageExcludeByFile: "*/*Designer.cs;*/*.g.cs;*/*.g.i.cs");
Build.RunDotNetCore();
| apache-2.0 | C# |
34e00d6e5a86386a97b6d6031ca836eceb583719 | Fix PaintBucketTool. | jakeclawson/Pinta,PintaProject/Pinta,PintaProject/Pinta,Fenex/Pinta,jakeclawson/Pinta,Mailaender/Pinta,Fenex/Pinta,Mailaender/Pinta,PintaProject/Pinta | Pinta.Core/Tools/PaintBucketTool.cs | Pinta.Core/Tools/PaintBucketTool.cs | //
// PaintBucketTool.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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 Cairo;
namespace Pinta.Core
{
public class PaintBucketTool : FloodTool
{
private Color fill_color;
public override string Name {
get { return "Paint Bucket"; }
}
public override string Icon {
get { return "Tools.PaintBucket.png"; }
}
public override string StatusBarText {
get { return "Left click to fill a region with the primary color, right click to fill with the secondary color."; }
}
protected override void OnMouseDown (Gtk.DrawingArea canvas, Gtk.ButtonPressEventArgs args, PointD point)
{
if (args.Event.Button == 1)
fill_color = PintaCore.Palette.PrimaryColor;
else
fill_color = PintaCore.Palette.SecondaryColor;
base.OnMouseDown (canvas, args, point);
}
protected unsafe override void OnFillRegionComputed (Point[][] polygonSet)
{
SimpleHistoryItem hist = new SimpleHistoryItem (Icon, Name);
hist.TakeSnapshotOfLayer (PintaCore.Layers.CurrentLayer);
using (Context g = new Context (PintaCore.Layers.CurrentLayer.Surface)) {
g.AppendPath (g.CreatePolygonPath (polygonSet));
g.Antialias = Antialias.Subpixel;
g.Color = fill_color;
g.Fill ();
}
PintaCore.History.PushNewItem (hist);
PintaCore.Workspace.Invalidate ();
}
}
}
| //
// PaintBucketTool.cs
//
// Author:
// Jonathan Pobst <monkey@jpobst.com>
//
// Copyright (c) 2010 Jonathan Pobst
//
// 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 Cairo;
namespace Pinta.Core
{
public class PaintBucketTool : FloodTool
{
private Color fill_color;
public override string Name {
get { return "Paint Bucket"; }
}
public override string Icon {
get { return "Tools.PaintBucket.png"; }
}
public override string StatusBarText {
get { return "Left click to fill a region with the primary color, right click to fill with the secondary color."; }
}
protected override void OnMouseDown (Gtk.DrawingArea canvas, Gtk.ButtonPressEventArgs args, PointD point)
{
if (args.Event.Button == 1)
fill_color = PintaCore.Palette.PrimaryColor;
else
fill_color = PintaCore.Palette.SecondaryColor;
base.OnMouseDown (canvas, args, point);
}
protected unsafe override void OnFillRegionComputed (Point[][] polygonSet)
{
SimpleHistoryItem hist = new SimpleHistoryItem (Icon, Name);
hist.TakeSnapshotOfLayer (PintaCore.Layers.CurrentLayer);
PintaCore.Layers.ToolLayer.Clear ();
ImageSurface surface = PintaCore.Layers.ToolLayer.Surface;
ColorBgra* surf_data_ptr = (ColorBgra*)surface.DataPtr;
int surf_width = surface.Width;
for (int x = 0; x < stencil.Width; x++)
for (int y = 0; y < stencil.Height; y++)
if (stencil.GetUnchecked (x, y))
surface.SetPixel (surf_data_ptr, surf_width, x, y, fill_color);
using (Context g = new Context (PintaCore.Layers.CurrentLayer.Surface)) {
g.AppendPath (PintaCore.Layers.SelectionPath);
g.FillRule = FillRule.EvenOdd;
g.Clip ();
g.Antialias = Antialias.Subpixel;
g.SetSource (surface);
g.Paint ();
}
PintaCore.History.PushNewItem (hist);
PintaCore.Workspace.Invalidate ();
}
}
}
| mit | C# |
a3c2f3425af90601f3c3f881c50d00761e2aae1c | Update AdProviders.cs | tiksn/TIKSN-Framework | TIKSN.Core/Advertising/AdProviders.cs | TIKSN.Core/Advertising/AdProviders.cs | namespace TIKSN.Advertising
{
public static class AdProviders
{
public const string AdDuplex = "AdDuplex";
public const string Microsoft = "Microsoft";
}
}
| namespace TIKSN.Advertising
{
public static class AdProviders
{
public const string AdDuplex = "AdDuplex";
public const string Microsoft = "Microsoft";
}
} | mit | C# |
d2e0b7f3132f22744d28e2fd90d4f50616955b7a | Add test case for 69c97371 | yufeih/Nine.Storage,studio-nine/Nine.Storage | test/Client/PersistedStorageTest.cs | test/Client/PersistedStorageTest.cs | namespace Nine.Storage
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading.Tasks;
using Xunit;
public class PersistedStorageTest : StorageSpec<PersistedStorageTest>
{
public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData()
{
return new[]
{
new TestFactory<IStorage<TestStorageObject>>(typeof(PersistedStorage<>), () => new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString())),
};
}
[Fact]
public async Task persisted_storage_put_and_get()
{
var storage = new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString());
await storage.Put(new TestStorageObject("a"));
Assert.NotNull(await storage.Get("a"));
var gets = new ConcurrentBag<TestStorageObject>();
Parallel.For(0, 100, i =>
{
if (i % 2 == 0)
{
storage.Put(new TestStorageObject("a")).Wait();
}
else
{
gets.Add(storage.Get("a").Result);
}
});
Assert.All(gets, got => Assert.NotNull(got));
}
}
}
| namespace Nine.Storage
{
using System;
using System.Collections.Generic;
using Xunit;
public class PersistedStorageTest : StorageSpec<PersistedStorageTest>
{
public override IEnumerable<ITestFactory<IStorage<TestStorageObject>>> GetData()
{
return new[]
{
new TestFactory<IStorage<TestStorageObject>>(typeof(PersistedStorage<>), () => new PersistedStorage<TestStorageObject>(Guid.NewGuid().ToString())),
};
}
}
}
| mit | C# |
6d5227248a8ffd54446f02db528b1a3551c9cb0b | Change to view all link | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | BatteryCommander.Web/Views/Soldier/List.cshtml | BatteryCommander.Web/Views/Soldier/List.cshtml | @model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "Soldiers";
}
<h2>@ViewBag.Title</h2>
<div class="btn-group" role="group">
@Html.ActionLink("Add a Soldier", "New", null, new { @class = "btn btn-primary" })
@Html.ActionLink("Bulk Add/Edit Soldiers", "Bulk", null, new { @class = "btn btn-default" })
@Html.ActionLink("View All", "List", new { activeOnly = false }, new { @class = "btn btn-default" })
</div>
<table class="table table-striped">
<tr>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Group)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Position)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().MOS)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Notes)</th>
<th></th>
</tr>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank, new { UseShortName = true })</td>
<td>@Html.ActionLink(soldier.LastName, "View", new { soldierId = soldier.Id })</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Group)</td>
<td>@Html.DisplayFor(s => soldier.Position)</td>
<td>@Html.DisplayFor(s => soldier.MOS, new { UseShortName = true })</td>
<td>@Html.DisplayFor(s => soldier.Notes)</td>
<td>
@Html.ActionLink("View", "View", new { soldierId = soldier.Id }, new { @class = "btn btn-default" })
@Html.ActionLink("Edit", "Edit", new { soldierId = soldier.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</table> | @model IEnumerable<BatteryCommander.Common.Models.Soldier>
@{
ViewBag.Title = "Soldiers";
}
<h2>@ViewBag.Title</h2>
<div class="btn-group" role="group">
@Html.ActionLink("Add a Soldier", "New", null, new { @class = "btn btn-primary" })
@Html.ActionLink("Bulk Add/Edit Soldiers", "Bulk", null, new { @class = "btn btn-default" })
@Html.ActionLink("Include Inactive Soldiers", "List", new { activeOnly = false }, new { @class = "btn btn-default" })
</div>
<table class="table table-striped">
<tr>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Rank)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().LastName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().FirstName)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Group)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Position)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().MOS)</th>
<th>@Html.DisplayNameFor(s => s.FirstOrDefault().Notes)</th>
<th></th>
</tr>
@foreach (var soldier in Model)
{
<tr>
<td>@Html.DisplayFor(s => soldier.Rank, new { UseShortName = true })</td>
<td>@Html.ActionLink(soldier.LastName, "View", new { soldierId = soldier.Id })</td>
<td>@Html.DisplayFor(s => soldier.FirstName)</td>
<td>@Html.DisplayFor(s => soldier.Group)</td>
<td>@Html.DisplayFor(s => soldier.Position)</td>
<td>@Html.DisplayFor(s => soldier.MOS, new { UseShortName = true })</td>
<td>@Html.DisplayFor(s => soldier.Notes)</td>
<td>
@Html.ActionLink("View", "View", new { soldierId = soldier.Id }, new { @class = "btn btn-default" })
@Html.ActionLink("Edit", "Edit", new { soldierId = soldier.Id }, new { @class = "btn btn-default" })
</td>
</tr>
}
</table> | mit | C# |
07e5775ee4cb06fe26609a7f31a1e464c4d74032 | Remove filter inheritance, just move properties to the filter itself | nozzlegear/ShopifySharp,clement911/ShopifySharp | ShopifySharp/Filters/ArticleFilter.cs | ShopifySharp/Filters/ArticleFilter.cs | using System;
using System.Collections.Generic;
using Newtonsoft.Json;
namespace ShopifySharp.Filters
{
/// <summary>
/// Options for filtering the results of <see cref="ArticleService.ListAsync(long, ArticleFilter)"/>.
/// </summary>
public class ArticleFilter : Parameterizable
{
/// <summary>
/// Filter the results to this article handle.
/// </summary>
[JsonProperty("handle")]
public string Handle { get; set; }
/// <summary>
/// Restricts results to those created after date (format: 2008-12-31 03:00).
/// </summary>
[JsonProperty("created_at_min")]
public DateTimeOffset? CreatedAtMin { get; set; }
/// <summary>
/// Restricts results to those created before date (format: 2008-12-31 03:00).
/// </summary>
[JsonProperty("created_at_max")]
public DateTimeOffset? CreatedAtMax { get; set; }
/// <summary>
/// Restricts results to those last updated after date (format: 2008-12-31 03:00).
/// </summary>
[JsonProperty("updated_at_min")]
public DateTimeOffset? UpdatedAtMin { get; set; }
/// <summary>
/// Restricts results to those last updated before date (format: 2008-12-31 03:00).
/// </summary>
[JsonProperty("updated_at_max")]
public DateTimeOffset? UpdatedAtMax { get; set; }
/// <summary>
/// Restrict results to after the specified ID. Note: this field may not have an effect on certain resources.
/// </summary>
[JsonProperty("since_id")]
public long? SinceId { get; set; }
/// <summary>
/// An optional array of order ids to retrieve.
/// </summary>
[JsonProperty("ids")]
public IEnumerable<long> Ids { get; set; }
/// <summary>
/// Limit the amount of results. Default is 50, max is 250.
/// </summary>
[JsonProperty("limit")]
public int? Limit { get; set; }
/// <summary>
/// Page of results to be returned. Default is 1.
/// </summary>
[JsonProperty("page")]
public int? Page { get; set; }
/// <summary>
/// An optional, comma-separated list of fields to include in the response.
/// </summary>
[JsonProperty("fields")]
public string Fields { get; set; }
/// <summary>
/// An optional field name to order by, followed by either ' asc' or ' desc'.
/// For example, 'created_at asc'
/// Not all fields are supported...
/// </summary>
[JsonProperty("order")]
public string Order { get; set; }
/// <summary>
/// Show objects published after date (format: 2008-12-31 03:00).
/// </summary>
[JsonProperty("published_at_min")]
public DateTimeOffset? PublishedAtMin { get; set; } = null;
/// <summary>
/// Show objects published before date (format: 2008-12-31 03:00).
/// </summary>
[JsonProperty("published_at_max")]
public DateTimeOffset? PublishedAtMax { get; set; } = null;
/// <summary>
/// Published Status.
/// published - Show only published objects, unpublished - Show only unpublished objects, any - Show all objects(default)
/// </summary>
[JsonProperty("published_status")]
public string PublishedStatus { get; set; } = null;
}
}
| using Newtonsoft.Json;
namespace ShopifySharp.Filters
{
/// <summary>
/// Options for filtering the results of <see cref="ArticleService.ListAsync(long, ArticleFilter)"/>.
/// </summary>
public class ArticleFilter : PublishableListFilter
{
/// <summary>
/// Filter the results to this article handle.
/// </summary>
[JsonProperty("handle")]
public string Handle { get; set; }
}
}
| mit | C# |
1c78ff9668f2716e607065cdc353e8d0fd27fafc | Revert "test public class" | CanadianBeaver/DataViewExtenders | Source/Forms/BitMaskCheckedListBox.cs | Source/Forms/BitMaskCheckedListBox.cs | using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace CBComponents.Forms
{
[ToolboxBitmap(typeof(CheckedListBox))]
internal sealed class BitMaskCheckedListBox : CheckedListBox
{
public BitMaskCheckedListBox()
{
this.CheckOnClick = true;
this.ItemCheck += (sender, e) => { if (this.ValueChanged != null) this.ValueChanged(sender, EventArgs.Empty); };
}
[BrowsableAttribute(false)]
public event EventHandler ValueChanged;
[DefaultValue(0)]
[Bindable(true), Browsable(true)]
public long Value
{
get
{
int result = 0;
for (int i = 0; i < this.Items.Count; i++)
if (this.GetItemChecked(i)) result |= 1 << i;
return result;
}
set
{
this.BeginUpdate();
for (int i = 0; i < this.Items.Count; i++)
{
int j = 1 << i;
bool nch = (value & j) == j;
bool och = this.GetItemChecked(i);
if (nch != och) this.SetItemChecked(i, nch);
}
this.EndUpdate();
}
}
}
}
| using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
namespace CBComponents.Forms
{
[ToolboxBitmap(typeof(CheckedListBox))]
public sealed class BitMaskCheckedListBox : CheckedListBox
{
public BitMaskCheckedListBox()
{
this.CheckOnClick = true;
this.ItemCheck += (sender, e) => { if (this.ValueChanged != null) this.ValueChanged(sender, EventArgs.Empty); };
}
[BrowsableAttribute(false)]
public event EventHandler ValueChanged;
[DefaultValue(0)]
[Bindable(true), Browsable(true)]
public long Value
{
get
{
int result = 0;
for (int i = 0; i < this.Items.Count; i++)
if (this.GetItemChecked(i)) result |= 1 << i;
return result;
}
set
{
this.BeginUpdate();
for (int i = 0; i < this.Items.Count; i++)
{
int j = 1 << i;
bool nch = (value & j) == j;
bool och = this.GetItemChecked(i);
if (nch != och) this.SetItemChecked(i, nch);
}
this.EndUpdate();
}
}
}
}
| mit | C# |
c1b2034e231127fdccc7840892a0123ec259db5d | Fix of documentation of `VersionToleranceLevel`. | rogeralsing/Migrant,antmicro/Migrant,modulexcite/Migrant,rogeralsing/Migrant,antmicro/Migrant,modulexcite/Migrant | Migrant/Customization/VersionToleranceLevel.cs | Migrant/Customization/VersionToleranceLevel.cs | /*
Copyright (c) 2013-2015 Antmicro <www.antmicro.com>
Authors:
* Konrad Kruczynski (kkruczynski@antmicro.com)
* Mateusz Holenko (mholenko@antmicro.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Antmicro.Migrant.Customization
{
/// <summary>
/// Level of the version tolerance, that is how much layout of the deserialized type can differ
/// from the (original) layout of the serialized type.
/// </summary>
[Flags]
public enum VersionToleranceLevel
{
/// <summary>
/// Difference in guid is allowed which means that classes may be from different compilation of the same library.
/// </summary>
AllowGuidChange = 0x1,
/// <summary>
/// The new layout can have more fields that the old one. They are initialized to their default values.
/// </summary>
AllowFieldAddition = 0x2,
/// <summary>
/// The new layout can have less fields that the old one. Values of the missing one are ignored.
/// </summary>
AllowFieldRemoval = 0x4,
/// <summary>
/// Classes inheritance hirarchy can vary between new and old layout, e.g., base class can be removed.
/// </summary>
AllowInheritanceChainChange = 0x80,
/// <summary>
/// Assemblies version can very between new and old layout.
/// </summary>
AllowAssemblyVersionChange = 0x10
}
}
| /*
Copyright (c) 2013-2015 Antmicro <www.antmicro.com>
Authors:
* Konrad Kruczynski (kkruczynski@antmicro.com)
* Mateusz Holenko (mholenko@antmicro.com)
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
using System;
namespace Antmicro.Migrant.Customization
{
/// <summary>
/// Level of the version tolerance, that is how much layout of the deserialized type can differ
/// from the (original) layout of the serialized type.
/// </summary>
[Flags]
public enum VersionToleranceLevel
{
/// <summary>
/// Both serialized and serialized classes must have identical module ID (which is GUID). In other words
/// that means these assemblies are from one and the same compilation.
/// </summary>
AllowGuidChange = 0x1,
/// <summary>
/// The new layout can have more fields that the old one. They are initialized to their default values.
/// </summary>
AllowFieldAddition = 0x2,
/// <summary>
/// The new layout can have less fields that the old one. Values of the missing one are ignored.
/// </summary>
AllowFieldRemoval = 0x4,
/// <summary>
/// Classes inheritance hirarchy can vary between new and old layout, e.g., base class can be removed.
/// </summary>
AllowInheritanceChainChange = 0x80,
/// <summary>
/// Assemblies version can very between new and old layout.
/// </summary>
AllowAssemblyVersionChange = 0x10
}
}
| mit | C# |
39f8d5cb2ede4377e1f2c4b118e80499c8b2de3b | Stop loading dynamic modules from disk | jagrem/slang,jagrem/slang,jagrem/slang | tests/Compiler/Clr.Tests/Compilation/IL/AssemblyDefinitionExtensions.cs | tests/Compiler/Clr.Tests/Compilation/IL/AssemblyDefinitionExtensions.cs | using System;
using System.Reflection;
using slang.Compiler.Clr.Compilation.Definitions;
namespace slang.Tests.IL
{
static class AssemblyDefinitionExtensions
{
public static Type [] GetTypes (this AssemblyDefinition assemblyDefinition)
{
return assemblyDefinition.LoadAssembly ().GetTypes ();
}
public static Assembly LoadAssembly (this AssemblyDefinition assemblyDefinition)
{
throw new InvalidOperationException("We will no longer be loading dynamic assemblies for disk so this operation is no longer possible.");
}
}
}
| using System;
using System.Reflection;
using slang.Compiler.Clr.Compilation.Definitions;
namespace slang.Tests.IL
{
static class AssemblyDefinitionExtensions
{
public static Type [] GetTypes (this AssemblyDefinition assemblyDefinition)
{
return assemblyDefinition.LoadAssembly ().GetTypes ();
}
public static Assembly LoadAssembly (this AssemblyDefinition assemblyDefinition)
{
return AppDomain.CurrentDomain.Load (new AssemblyName (assemblyDefinition.Name));
}
}
}
| mit | C# |
56907ff51bfac13e6508e783a091208a58a55458 | Remove stray import | ProtoTest/ProtoTest.Golem,ProtoTest/ProtoTest.Golem | ProtoTest.Golem/Tests/TestWebDriverTestBase.cs | ProtoTest.Golem/Tests/TestWebDriverTestBase.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MbUnit.Framework;
using OpenQA.Selenium.Firefox;
using ProtoTest.Golem.Tests.PageObjects.Google;
using ProtoTest.Golem.WebDriver;
namespace ProtoTest.Golem.Tests
{
class TestWebDriverTestBase : WebDriverTestBase
{
[Test]
public void TestPageObjectCreater()
{
var page = OpenPage<GoogleHomePage>("http://www.google.com");
Assert.IsInstanceOfType<GoogleHomePage>(page);
}
[Test]
public void TestDriverNotNull()
{
Assert.IsNotNull(driver);
}
[Test]
public void TestDefaultBrowser()
{
Assert.AreEqual(browser, WebDriverBrowser.Browser.Chrome);
}
[Test]
public void TestEventFiringDriverLaunches()
{
Assert.IsInstanceOfType<EventFiringWebDriver>(driver);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MbUnit.Framework;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.Events;
using ProtoTest.Golem.Tests.PageObjects.Google;
using ProtoTest.Golem.WebDriver;
namespace ProtoTest.Golem.Tests
{
class TestWebDriverTestBase : WebDriverTestBase
{
[Test]
public void TestPageObjectCreater()
{
var page = OpenPage<GoogleHomePage>("http://www.google.com");
Assert.IsInstanceOfType<GoogleHomePage>(page);
}
[Test]
public void TestDriverNotNull()
{
Assert.IsNotNull(driver);
}
[Test]
public void TestDefaultBrowser()
{
Assert.AreEqual(browser, WebDriverBrowser.Browser.Chrome);
}
[Test]
public void TestEventFiringDriverLaunches()
{
Assert.IsInstanceOfType<EventFiringWebDriver>(driver);
}
}
}
| apache-2.0 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.