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
484ad116f0a5f62a4e28a02adf623d72e94cc05a
Remove dependency on admin url mapper
ronnieholm/Bugfree.Spo.Cqrs
src/Bugfree.Spo.Cqrs.Core/Queries/GetTenantSiteCollections.cs
src/Bugfree.Spo.Cqrs.Core/Queries/GetTenantSiteCollections.cs
using Bugfree.Spo.Cqrs.Core.Utilities; using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using System.Collections.Generic; using System.Linq; namespace Bugfree.Spo.Cqrs.Core.Queries { public class GetTenantSiteCollections : Query { public GetTenantSiteCollections(ILogger l) : base(l) { } private List<SiteProperties> GetTenantSiteCollectionsRecursive(Tenant tenant, List<SiteProperties> siteProperties, int startPosition) { Logger.Verbose($"Fetching tenant site collections starting from position {startPosition}"); var tenantSiteCollections = tenant.GetSiteProperties(startPosition, true); tenant.Context.Load(tenantSiteCollections); tenant.Context.ExecuteQuery(); var newSiteProperties = siteProperties.Concat(tenantSiteCollections).ToList(); return tenantSiteCollections.NextStartIndex == -1 ? newSiteProperties : GetTenantSiteCollectionsRecursive(tenant, newSiteProperties, tenantSiteCollections.NextStartIndex); } public List<SiteProperties> Execute(ClientContext tenantAdminCtx) { Logger.Verbose($"About to execute {nameof(GetTenantSiteCollections)}"); var tenant = new Tenant(tenantAdminCtx); tenantAdminCtx.Load(tenant); tenantAdminCtx.ExecuteQuery(); return GetTenantSiteCollectionsRecursive(tenant, new List<SiteProperties>(), 0); } } }
using Bugfree.Spo.Cqrs.Core.Utilities; using Microsoft.Online.SharePoint.TenantAdministration; using Microsoft.SharePoint.Client; using System; using System.Collections.Generic; using System.Linq; namespace Bugfree.Spo.Cqrs.Core.Queries { public class GetTenantSiteCollections : Query { public GetTenantSiteCollections(ILogger l) : base(l) { } private List<SiteProperties> GetTenantSiteCollectionsRecursive(Tenant tenant, List<SiteProperties> siteProperties, int startPosition) { Logger.Verbose($"Fetching tenant site collections starting from position {startPosition}"); var tenantSiteCollections = tenant.GetSiteProperties(startPosition, true); tenant.Context.Load(tenantSiteCollections); tenant.Context.ExecuteQuery(); var newSiteProperties = siteProperties.Concat(tenantSiteCollections).ToList(); return tenantSiteCollections.NextStartIndex == -1 ? newSiteProperties : GetTenantSiteCollectionsRecursive(tenant, newSiteProperties, tenantSiteCollections.NextStartIndex); } public List<SiteProperties> Execute(ClientContext ctx) { Logger.Verbose($"About to execute {nameof(GetTenantSiteCollections)}"); var url = ctx.Url; var tenantAdminUrl = new AdminUrlInferrer().InferAdminFromTenant(new Uri(url.Replace(new Uri(url).AbsolutePath, ""))); var tenantAdminCtx = new ClientContext(tenantAdminUrl) { Credentials = ctx.Credentials }; var tenant = new Tenant(tenantAdminCtx); tenantAdminCtx.Load(tenant); tenantAdminCtx.ExecuteQuery(); return GetTenantSiteCollectionsRecursive(tenant, new List<SiteProperties>(), 0); } } }
bsd-2-clause
C#
f8d97791fbad8995154bc294b05b18f4a45f83f4
Handle unknown user/group IDs
FubarDevelopment/FtpServer
src/FubarDev.FtpServer.FileSystem.Unix/UnixFileSystemEntry.cs
src/FubarDev.FtpServer.FileSystem.Unix/UnixFileSystemEntry.cs
// <copyright file="UnixFileSystemEntry.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using System.Globalization; using JetBrains.Annotations; using Mono.Unix; namespace FubarDev.FtpServer.FileSystem.Unix { internal abstract class UnixFileSystemEntry : IUnixFileSystemEntry { [NotNull] private readonly UnixFileSystemInfo _info; protected UnixFileSystemEntry( [NotNull] UnixFileSystemInfo info) { GenericInfo = _info = info; Permissions = new UnixPermissions(info); Owner = GetNameOrId(() => info.OwnerUser.UserName, () => info.OwnerUserId); Group = GetNameOrId(() => info.OwnerGroup.GroupName, () => info.OwnerGroupId); } /// <summary> /// Gets generic unix file system entry information. /// </summary> [NotNull] public UnixFileSystemInfo GenericInfo { get; } /// <inheritdoc /> public string Owner { get; } /// <inheritdoc /> public string Group { get; } /// <inheritdoc /> public string Name => _info.Name; /// <inheritdoc /> public IUnixPermissions Permissions { get; } /// <inheritdoc /> public DateTimeOffset? LastWriteTime => _info.LastWriteTimeUtc; /// <inheritdoc /> public DateTimeOffset? CreatedTime => _info.LastStatusChangeTimeUtc; /// <inheritdoc /> public long NumberOfLinks => _info.LinkCount; private static string GetNameOrId(Func<string> getName, Func<long> getId) { try { return getName(); } catch { return getId().ToString(CultureInfo.InvariantCulture); } } } }
// <copyright file="UnixFileSystemEntry.cs" company="Fubar Development Junker"> // Copyright (c) Fubar Development Junker. All rights reserved. // </copyright> using System; using JetBrains.Annotations; using Mono.Unix; namespace FubarDev.FtpServer.FileSystem.Unix { internal abstract class UnixFileSystemEntry : IUnixFileSystemEntry { [NotNull] private readonly UnixFileSystemInfo _info; protected UnixFileSystemEntry( [NotNull] UnixFileSystemInfo info) { GenericInfo = _info = info; Permissions = new UnixPermissions(info); } /// <summary> /// Gets generic unix file system entry information. /// </summary> [NotNull] public UnixFileSystemInfo GenericInfo { get; } /// <inheritdoc /> public string Owner => _info.OwnerUser.UserName; /// <inheritdoc /> public string Group => _info.OwnerGroup.GroupName; /// <inheritdoc /> public string Name => _info.Name; /// <inheritdoc /> public IUnixPermissions Permissions { get; } /// <inheritdoc /> public DateTimeOffset? LastWriteTime => _info.LastWriteTimeUtc; /// <inheritdoc /> public DateTimeOffset? CreatedTime => _info.LastStatusChangeTimeUtc; /// <inheritdoc /> public long NumberOfLinks => _info.LinkCount; } }
mit
C#
2ce0bd81975e91cd7e18d1c44d3aad90e2b99c92
remove unfinished comment
ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework
osu.Framework.Tests/Audio/AudioCollectionManagerTest.cs
osu.Framework.Tests/Audio/AudioCollectionManagerTest.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 System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { private class TestingAdjustableAudioComponent : AdjustableAudioComponent {} [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to be added in the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); Assert.DoesNotThrow(() => manager.Dispose()); } } }
// 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 System.Threading; using NUnit.Framework; using osu.Framework.Audio; namespace osu.Framework.Tests.Audio { [TestFixture] public class AudioCollectionManagerTest { private class TestingAdjustableAudioComponent : AdjustableAudioComponent {} [Test] public void TestDisposalWhileItemsAreAddedDoesNotThrowInvalidOperationException() { var manager = new AudioCollectionManager<AdjustableAudioComponent>(); // add a huge amount of items to be added in the queue for (int i = 0; i < 10000; i++) manager.AddItem(new TestingAdjustableAudioComponent()); // in a seperate thread start processing the queue new Thread(() => manager.Update()).Start(); // wait a little for beginning of the update to start Thread.Sleep(4); // the Assert.DoesNotThrow(() => manager.Dispose()); } } }
mit
C#
658aa526f382a8e7cd3f9c84450ab6ffd30284de
Improve orientation tests + add quad test
EVAST9919/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework
osu.Framework.Tests/Primitives/Vector2ExtensionsTest.cs
osu.Framework.Tests/Primitives/Vector2ExtensionsTest.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 NUnit.Framework; using osu.Framework.Graphics; using osu.Framework.Graphics.Primitives; using osuTK; namespace osu.Framework.Tests.Primitives { [TestFixture] public class Vector2ExtensionsTest { [TestCase(true)] [TestCase(false)] public void TestArrayOrientation(bool clockwise) { var vertices = new[] { new Vector2(0, 1), Vector2.One, new Vector2(1, 0), Vector2.Zero }; if (!clockwise) Array.Reverse(vertices); float orientation = Vector2Extensions.GetOrientation(vertices); Assert.That(orientation, Is.EqualTo(clockwise ? 2 : -2).Within(0.001)); } [TestCase(true)] [TestCase(false)] public void TestQuadOrientation(bool clockwise) { Quad quad = clockwise ? new Quad(new Vector2(0, 1), Vector2.One, Vector2.Zero, new Vector2(1, 0)) : new Quad(Vector2.Zero, new Vector2(1, 0), new Vector2(0, 1), Vector2.One); float orientation = Vector2Extensions.GetOrientation(quad.GetVertices()); Assert.That(orientation, Is.EqualTo(clockwise ? 2 : -2).Within(0.001)); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Graphics; using osuTK; namespace osu.Framework.Tests.Primitives { [TestFixture] public class Vector2ExtensionsTest { [Test] public void TestClockwiseOrientation() { var vertices = new[] { new Vector2(0, 1), Vector2.One, new Vector2(1, 0), Vector2.Zero }; float orientation = Vector2Extensions.GetOrientation(vertices); Assert.That(orientation, Is.EqualTo(2).Within(0.001)); } [Test] public void TestCounterClockwiseOrientation() { var vertices = new[] { Vector2.Zero, new Vector2(1, 0), Vector2.One, new Vector2(0, 1), }; float orientation = Vector2Extensions.GetOrientation(vertices); Assert.That(orientation, Is.EqualTo(-2).Within(0.001)); } } }
mit
C#
5ac8ba8f71f5d74eaa21bd3a9e7d7ec73e0e8b67
add AsyncController
zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning
my_aspnetmvc_learning/Controllers/AsyncController.cs
my_aspnetmvc_learning/Controllers/AsyncController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace my_aspnetmvc_learning.Controllers { public class AsyncController : Controller { // GET: Async [AsyncTimeout(1000)] public async Task<ActionResult> Index() { var data = await GetPageTaskAsync("http://163.com"); string otherData = "Irving"; return data; } /// <summary> /// 处理异步请求 /// </summary> /// <param name="url"></param> /// <returns></returns> public async Task<ActionResult> GetPageTaskAsync(string url) { try { using (var client = new HttpClient()) { await Task.Delay(3000); var fetchTextTask = client.GetStringAsync(url); return Json(new { fetchText = await fetchTextTask, error = "NO" }, JsonRequestBehavior.AllowGet); } } catch (WebException exception) { throw exception; // TODO: Logging, update statistics etc. } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace my_aspnetmvc_learning.Controllers { public class AsyncController : Controller { // GET: Async public ActionResult Index() { return View(); } } }
mit
C#
d8aa5a8042a73b0c19b9c32cef38782cd9074983
Fix bug where loader fade would not stop
cemrich/From-Outer-Space
Assets/Scripts/Loader.cs
Assets/Scripts/Loader.cs
using UnityEngine; using System.Collections; using System; [RequireComponent (typeof(CanvasGroup))] public class Loader : MonoBehaviour { [Tooltip ("Time in seconds to fade in/out the loader.")] public float fadeSpeed = 1f; private CanvasGroup canvasGroup; private IEnumerator currentFade; public void Show () { Debug.Log ("[Loader] Show"); StopCurrentFade (); currentFade = Fade (1, fadeSpeed); StartCoroutine (currentFade); } public void Hide () { Debug.Log ("[Loader] Hide"); StopCurrentFade (); currentFade = Fade (0, fadeSpeed); StartCoroutine (currentFade); } void Start () { canvasGroup = GetComponent<CanvasGroup> (); } void StopCurrentFade () { if (currentFade != null) { StopCoroutine (currentFade); } } IEnumerator Fade (float alpha, float speed) { float speedForAlphaChange = (alpha - canvasGroup.alpha) / speed; while (!Mathf.Approximately (canvasGroup.alpha, alpha)) { canvasGroup.alpha += (speedForAlphaChange * Time.deltaTime); yield return null; } } }
using UnityEngine; using System.Collections; using System; [RequireComponent (typeof(CanvasGroup))] public class Loader : MonoBehaviour { [Tooltip ("Time in seconds to fade in/out the loader.")] public float fadeSpeed = 1f; private CanvasGroup canvasGroup; public void Show () { Debug.Log ("[Loader] Show"); StopCoroutine ("Fade"); StartCoroutine (Fade (1, fadeSpeed)); } public void Hide () { Debug.Log ("[Loader] Hide"); StopCoroutine ("Fade"); StartCoroutine (Fade (0, fadeSpeed)); } void Start () { canvasGroup = GetComponent<CanvasGroup> (); } IEnumerator Fade (float alpha, float speed) { float speedForAlphaChange = (alpha - canvasGroup.alpha) / speed; while (!Mathf.Approximately (canvasGroup.alpha, alpha)) { canvasGroup.alpha += (speedForAlphaChange * Time.deltaTime); yield return null; } } }
mit
C#
a695b3d9d65a4d759dc5ef56f05658f67e245b77
Remove deprecated use of GtkTreeView.RulesHint.
PintaProject/Pinta,PintaProject/Pinta,PintaProject/Pinta
Pinta/Dialogs/VersionInformationTabPage.cs
Pinta/Dialogs/VersionInformationTabPage.cs
// VersionInformationTabPage.cs // // Author: // Viktoria Dudka (viktoriad@remobjects.com) // // Copyright (c) 2009 RemObjects Software // // 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 Gtk; using System.Reflection; using Pinta.Core; namespace Pinta { internal class VersionInformationTabPage : VBox { private ListStore? data = null; private CellRenderer cellRenderer = new CellRendererText (); public VersionInformationTabPage () { TreeView treeView = new TreeView (); TreeViewColumn treeViewColumnTitle = new TreeViewColumn (Translations.GetString ("Title"), cellRenderer, "text", 0); treeViewColumnTitle.FixedWidth = 200; treeViewColumnTitle.Sizing = TreeViewColumnSizing.Fixed; treeViewColumnTitle.Resizable = true; treeView.AppendColumn (treeViewColumnTitle); TreeViewColumn treeViewColumnVersion = new TreeViewColumn (Translations.GetString ("Version"), cellRenderer, "text", 1); treeView.AppendColumn (treeViewColumnVersion); TreeViewColumn treeViewColumnPath = new TreeViewColumn (Translations.GetString ("Path"), cellRenderer, "text", 2); treeView.AppendColumn (treeViewColumnPath); data = new ListStore (typeof (string), typeof (string), typeof (string)); treeView.Model = data; ScrolledWindow scrolledWindow = new ScrolledWindow (); scrolledWindow.Add (treeView); scrolledWindow.ShadowType = ShadowType.In; BorderWidth = 6; PackStart (scrolledWindow, true, true, 0); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies ()) { try { AssemblyName assemblyName = assembly.GetName (); data.AppendValues (assemblyName.Name, assemblyName.Version?.ToString (), System.IO.Path.GetFullPath (assembly.Location)); } catch { } } data.SetSortColumnId (0, SortType.Ascending); } protected override void OnDestroyed () { if (data != null) { data.Dispose (); data = null; } base.OnDestroyed (); } } }
// VersionInformationTabPage.cs // // Author: // Viktoria Dudka (viktoriad@remobjects.com) // // Copyright (c) 2009 RemObjects Software // // 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 Gtk; using System.Reflection; using Pinta.Core; namespace Pinta { internal class VersionInformationTabPage : VBox { private ListStore? data = null; private CellRenderer cellRenderer = new CellRendererText (); public VersionInformationTabPage () { TreeView treeView = new TreeView (); TreeViewColumn treeViewColumnTitle = new TreeViewColumn (Translations.GetString ("Title"), cellRenderer, "text", 0); treeViewColumnTitle.FixedWidth = 200; treeViewColumnTitle.Sizing = TreeViewColumnSizing.Fixed; treeViewColumnTitle.Resizable = true; treeView.AppendColumn (treeViewColumnTitle); TreeViewColumn treeViewColumnVersion = new TreeViewColumn (Translations.GetString ("Version"), cellRenderer, "text", 1); treeView.AppendColumn (treeViewColumnVersion); TreeViewColumn treeViewColumnPath = new TreeViewColumn (Translations.GetString ("Path"), cellRenderer, "text", 2); treeView.AppendColumn (treeViewColumnPath); treeView.RulesHint = true; data = new ListStore (typeof (string), typeof (string), typeof (string)); treeView.Model = data; ScrolledWindow scrolledWindow = new ScrolledWindow (); scrolledWindow.Add (treeView); scrolledWindow.ShadowType = ShadowType.In; BorderWidth = 6; PackStart (scrolledWindow, true, true, 0); foreach (Assembly assembly in AppDomain.CurrentDomain.GetAssemblies ()) { try { AssemblyName assemblyName = assembly.GetName (); data.AppendValues (assemblyName.Name, assemblyName.Version?.ToString (), System.IO.Path.GetFullPath (assembly.Location)); } catch { } } data.SetSortColumnId (0, SortType.Ascending); } protected override void OnDestroyed () { if (data != null) { data.Dispose (); data = null; } base.OnDestroyed (); } } }
mit
C#
e7a80a43f1eb27b00004a671d65341d54d969a8a
Handle exceptions in isolated storage
Teleopti/signalr-signalr-messagebus,Teleopti/signalr-signalr-messagebus
Contrib.SignalR.SignalRMessageBus/Contrib.SignalR.SignalRMessageBus.Backend/IdStorage.cs
Contrib.SignalR.SignalRMessageBus/Contrib.SignalR.SignalRMessageBus.Backend/IdStorage.cs
using System; using System.IO; using System.IO.IsolatedStorage; using System.Security; using System.Threading; namespace Contrib.SignalR.SignalRMessageBus.Backend { public class IdStorage { private const string FileName = "LastKnownId.key"; public void OnStart() { if (attemptIsolatedStorageOperation(tryLoadLastId)) return; _nextId = long.MinValue; } private static bool tryLoadLastId() { var store = IsolatedStorageFile.GetUserStoreForAssembly(); if (store.FileExists(FileName)) { using (var stream = store.OpenFile(FileName, FileMode.OpenOrCreate, FileAccess.Read)) using (var streamReader = new StreamReader(stream)) { var result = streamReader.ReadToEnd(); long value; if (long.TryParse(result, out value)) { _nextId = value; return true; } } } return false; } public void OnStop() { attemptIsolatedStorageOperation(trySaveLastId); } private static bool attemptIsolatedStorageOperation(Func<bool> isolatedStorageOperation) { try { return isolatedStorageOperation(); } catch (SecurityException) { } catch (IsolatedStorageException) { } return false; } private static bool trySaveLastId() { var store = IsolatedStorageFile.GetUserStoreForAssembly(); using (var stream = store.OpenFile(FileName, FileMode.OpenOrCreate, FileAccess.Write)) using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(_nextId); } return true; } private static long _nextId; public static long NextId() { return Interlocked.Increment(ref _nextId); } } }
using System.IO; using System.IO.IsolatedStorage; using System.Threading; namespace Contrib.SignalR.SignalRMessageBus.Backend { public class IdStorage { private const string FileName = "LastKnownId.key"; public void OnStart() { var store = IsolatedStorageFile.GetUserStoreForAssembly(); if (store.FileExists(FileName)) { using (var stream = store.OpenFile(FileName, FileMode.OpenOrCreate, FileAccess.Read)) using (var streamReader = new StreamReader(stream)) { var result = streamReader.ReadToEnd(); long value; if (long.TryParse(result, out value)) { _nextId = value; return; } } } _nextId = long.MinValue; } public void OnStop() { var store = IsolatedStorageFile.GetUserStoreForAssembly(); using (var stream = store.OpenFile(FileName, FileMode.OpenOrCreate, FileAccess.Write)) using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(_nextId); } } private static long _nextId; public static long NextId() { return Interlocked.Increment(ref _nextId); } } }
mit
C#
2404f5ee3005a47d4e0bd49f827802ce61761626
Fix TableListPage
atata-framework/atata-samples
Performance.ControlList/AtataSamples.Performance.ControlList/Components/TableListPage.cs
Performance.ControlList/AtataSamples.Performance.ControlList/Components/TableListPage.cs
using System.Collections.Generic; using Atata; namespace AtataSamples.Performance.ControlList { using _ = TableListPage; [Url("table-list")] public class TableListPage : Page<_> { public ItemsContainer Items { get; set; } [ControlDefinition("div", ContainingClass = "table-list", ComponentTypeName = "list")] public class ItemsContainer : Control<_> { public ControlList<ItemRow, _> Rows { get; private set; } public DataProvider<IEnumerable<int>, _> Ids => Rows.SelectContentsByExtraXPath<int>($"/{ItemRow.XPathTo.Id}", "Ids"); public DataProvider<IEnumerable<string>, _> Names => Rows.SelectContentsByExtraXPath($"/{ItemRow.XPathTo.Name}", "Names"); public ItemRow FindRowById(int id) { return Rows.GetByXPathCondition($"Id={id}", $"{ItemRow.XPathTo.Id}[.='{id}']"); } public ItemRow FindRowByIdAndName(int id, string name) { return Rows.GetByXPathCondition($"Id={id} & Name={name}", $"{ItemRow.XPathTo.Id}[.='{id}'] and {ItemRow.XPathTo.Name}[.='{name}']"); } } public class ItemRow : TableRow<_> { [FindByXPath(XPathTo.Id)] public Number<_> Id { get; private set; } [FindByXPath(XPathTo.Name)] public Text<_> Name { get; private set; } [FindByClass] public Text<_> Description { get; private set; } public static class XPathTo { public const string Id = "td[contains(concat(' ', normalize-space(@class), ' '), ' id ')]"; public const string Name = "td[contains(concat(' ', normalize-space(@class), ' '), ' name ')]"; } } } }
using System.Collections.Generic; using Atata; namespace AtataSamples.Performance.ControlList { using _ = TableListPage; [Url("table-list")] public class TableListPage : Page<_> { public ItemsContainer Items { get; set; } [ControlDefinition("div", ContainingClass = "table-list", ComponentTypeName = "list")] public class ItemsContainer : Control<_> { public ControlList<ItemRow, _> Rows { get; private set; } public DataProvider<IEnumerable<int>, _> Ids => Rows.SelectContentsByExtraXPath<int>(ItemRow.XPathTo.Id, "Ids"); public DataProvider<IEnumerable<string>, _> Names => Rows.SelectContentsByExtraXPath(ItemRow.XPathTo.Name, "Names"); public ItemRow FindRowById(int id) { return Rows.GetByXPathCondition($"Id={id}", $"{ItemRow.XPathTo.Id}[.='{id}']"); } public ItemRow FindRowByIdAndName(int id, string name) { return Rows.GetByXPathCondition($"Id={id} & Name={name}", $"{ItemRow.XPathTo.Id}[.='{id}'] and {ItemRow.XPathTo.Name}[.='{name}']"); } } public class ItemRow : TableRow<_> { [FindByXPath(XPathTo.Id)] public Number<_> Id { get; private set; } [FindByXPath(XPathTo.Name)] public Text<_> Name { get; private set; } [FindByClass] public Text<_> Description { get; private set; } public static class XPathTo { public const string Id = "/td[contains(concat(' ', normalize-space(@class), ' '), ' id ')]"; public const string Name = "/td[contains(concat(' ', normalize-space(@class), ' '), ' name ')]"; } } } }
apache-2.0
C#
75ed0b6dd13bd30a18f52ec4edf521488e9ed65b
Update version numbers in CommonAssemblyInfo.cs to 4.1 and 3.1 to match nuget package versions.
yonglehou/WebApi,abkmr/WebApi,LianwMS/WebApi,chimpinano/WebApi,chimpinano/WebApi,abkmr/WebApi,lungisam/WebApi,lewischeng-ms/WebApi,scz2011/WebApi,scz2011/WebApi,congysu/WebApi,lungisam/WebApi,yonglehou/WebApi,LianwMS/WebApi,congysu/WebApi,lewischeng-ms/WebApi
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")] [assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETMVC && ASPNETWEBPAGES #error Runtime projects cannot define both ASPNETMVC and ASPNETWEBPAGES #elif ASPNETMVC [assembly: AssemblyVersion("4.1.0.0")] // ASPNETMVC [assembly: AssemblyFileVersion("4.1.0.0")] // ASPNETMVC [assembly: AssemblyProduct("Microsoft ASP.NET MVC")] #elif ASPNETWEBPAGES [assembly: AssemblyVersion("2.1.0.0")] // ASPNETWEBPAGES [assembly: AssemblyFileVersion("2.1.0.0")] // ASPNETWEBPAGES [assembly: AssemblyProduct("Microsoft ASP.NET Web Pages")] #else #error Runtime projects must define either ASPNETMVC or ASPNETWEBPAGES #endif
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Microsoft Open Technologies, Inc.")] [assembly: AssemblyCopyright("© Microsoft Open Technologies, Inc. All rights reserved.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: NeutralResourcesLanguage("en-US")] // =========================================================================== // DO NOT EDIT OR REMOVE ANYTHING BELOW THIS COMMENT. // Version numbers are automatically generated based on regular expressions. // =========================================================================== #if ASPNETMVC && ASPNETWEBPAGES #error Runtime projects cannot define both ASPNETMVC and ASPNETWEBPAGES #elif ASPNETMVC [assembly: AssemblyVersion("5.0.0.0")] // ASPNETMVC [assembly: AssemblyFileVersion("5.0.0.0")] // ASPNETMVC [assembly: AssemblyProduct("Microsoft ASP.NET MVC")] #elif ASPNETWEBPAGES [assembly: AssemblyVersion("3.0.0.0")] // ASPNETWEBPAGES [assembly: AssemblyFileVersion("3.0.0.0")] // ASPNETWEBPAGES [assembly: AssemblyProduct("Microsoft ASP.NET Web Pages")] #else #error Runtime projects must define either ASPNETMVC or ASPNETWEBPAGES #endif
mit
C#
a10e59ea9b5a3e11da3e5280b92b97ca4ae7d334
Update the import image type contract
DimensionDataCBUSydney/Compute.Api.Client
ComputeClient/Compute.Contracts/Image/ImportImageType.cs
ComputeClient/Compute.Contracts/Image/ImportImageType.cs
namespace DD.CBU.Compute.Api.Contracts.Image { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types")] [System.Xml.Serialization.XmlRootAttribute("importImage", Namespace = "urn:didata.com:api:cloud:types", IsNullable = false)] public partial class ImportImageType { private string ovfPackageField; private string nameField; private string descriptionField; private bool guestOsCustomizationField; private bool guestOsCustomizationSpecifiedField; private string ItemField; private ItemChoiceType ItemElementNameField; /// <remarks/> public string ovfPackage { get { return this.ovfPackageField; } set { this.ovfPackageField = value; } } /// <remarks/> public string name { get { return this.nameField; } set { this.nameField = value; } } /// <remarks/> public string description { get { return this.descriptionField; } set { this.descriptionField = value; } } /// <remarks/> public bool guestOsCustomization { get { return this.guestOsCustomizationField; } set { this.guestOsCustomizationField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool guestOsCustomizationSpecified { get { return this.guestOsCustomizationSpecifiedField; } set { this.guestOsCustomizationSpecifiedField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("clusterId", typeof(string))] [System.Xml.Serialization.XmlElementAttribute("datacenterId", typeof(string))] [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")] public string Item { get { return this.ItemField; } set { this.ItemField = value; } } /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public ItemChoiceType ItemElementName { get { return this.ItemElementNameField; } set { this.ItemElementNameField = value; } } } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types", IncludeInSchema = false)] public enum ItemChoiceType { /// <remarks/> clusterId, /// <remarks/> datacenterId, } }
namespace DD.CBU.Compute.Api.Contracts.Image { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types")] [System.Xml.Serialization.XmlRootAttribute("importImage", Namespace = "urn:didata.com:api:cloud:types", IsNullable = false)] public partial class ImportImageType { /// <remarks/> public string ovfPackage; /// <remarks/> public string name; /// <remarks/> public string description; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("clusterId", typeof(string))] [System.Xml.Serialization.XmlElementAttribute("datacenterId", typeof(string))] [System.Xml.Serialization.XmlChoiceIdentifierAttribute("ItemElementName")] public string Item; /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public ItemChoiceType ItemElementName; /// <remarks/> public bool guestOsCustomization; /// <remarks/> [System.Xml.Serialization.XmlIgnoreAttribute()] public bool guestOsCustomizationSpecified; } /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.6.81.0")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(Namespace = "urn:didata.com:api:cloud:types", IncludeInSchema = false)] public enum ItemChoiceType { /// <remarks/> clusterId, /// <remarks/> datacenterId, } }
mit
C#
0f8bef1041334ddd5d03eafcb495e4d4403109d2
Fix system menu position for CaptionIcon.
Grabacr07/MetroRadiance
source/MetroRadiance/UI/Controls/CaptionIcon.cs
source/MetroRadiance/UI/Controls/CaptionIcon.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using MetroRadiance.Interop; using MetroRadiance.Interop.Win32; namespace MetroRadiance.UI.Controls { public class CaptionIcon : Button { static CaptionIcon() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CaptionIcon), new FrameworkPropertyMetadata(typeof(CaptionIcon))); } private bool isSystemMenuOpened; protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); var window = Window.GetWindow(this); if (window == null) return; window.SourceInitialized += this.Initialize; } private void Initialize(object sender, EventArgs e) { var window = (Window)sender; window.SourceInitialized -= this.Initialize; var source = PresentationSource.FromVisual(window) as HwndSource; if (source != null) { source.AddHook(this.WndProc); window.Closed += (o, args) => source.RemoveHook(this.WndProc); } } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == (int)WindowsMessages.WM_NCLBUTTONDOWN) { this.isSystemMenuOpened = false; } return IntPtr.Zero; } protected override void OnMouseDown(MouseButtonEventArgs e) { if (e.ChangedButton == MouseButton.Left) { var window = Window.GetWindow(this); if (e.ClickCount == 1) { if (!this.isSystemMenuOpened) { this.isSystemMenuOpened = true; var point = this.PointToScreen(new Point(0, this.ActualHeight)); var dpi = Dpi.FromVisual(window); SystemCommands.ShowSystemMenu(window, dpi.PhysicalToLogical(point)); } else { this.isSystemMenuOpened = false; } } else if (e.ClickCount == 2) { window.Close(); } } else { base.OnMouseDown(e); } } protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) { var window = Window.GetWindow(this); var point = this.PointToScreen(e.GetPosition(this)); var dpi = Dpi.FromVisual(window); SystemCommands.ShowSystemMenu(window, dpi.PhysicalToLogical(point)); } protected override void OnMouseLeave(MouseEventArgs e) { this.isSystemMenuOpened = false; base.OnMouseLeave(e); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Interop; using MetroRadiance.Interop.Win32; namespace MetroRadiance.UI.Controls { public class CaptionIcon : Button { static CaptionIcon() { DefaultStyleKeyProperty.OverrideMetadata(typeof(CaptionIcon), new FrameworkPropertyMetadata(typeof(CaptionIcon))); } private bool isSystemMenuOpened; protected override void OnInitialized(EventArgs e) { base.OnInitialized(e); var window = Window.GetWindow(this); if (window == null) return; window.SourceInitialized += this.Initialize; } private void Initialize(object sender, EventArgs e) { var window = (Window)sender; window.SourceInitialized -= this.Initialize; var source = PresentationSource.FromVisual(window) as HwndSource; if (source != null) { source.AddHook(this.WndProc); window.Closed += (o, args) => source.RemoveHook(this.WndProc); } } private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled) { if (msg == (int)WindowsMessages.WM_NCLBUTTONDOWN) { this.isSystemMenuOpened = false; } return IntPtr.Zero; } protected override void OnMouseDown(MouseButtonEventArgs e) { var window = Window.GetWindow(this) as MetroWindow; if (window == null) { base.OnMouseDown(e); return; } if (e.ChangedButton == MouseButton.Left) { if (e.ClickCount == 1) { if (!this.isSystemMenuOpened) { this.isSystemMenuOpened = true; var point = this.PointToScreen(new Point(0, this.ActualHeight)); SystemCommands.ShowSystemMenu(window, new Point(point.X / window.CurrentDpi.ScaleX, point.Y / window.CurrentDpi.ScaleY)); } else { this.isSystemMenuOpened = false; } } else if (e.ClickCount == 2) { window.Close(); } } } protected override void OnMouseRightButtonUp(MouseButtonEventArgs e) { var window = Window.GetWindow(this) as MetroWindow; if (window == null) { base.OnMouseRightButtonUp(e); return; } var point = this.PointToScreen(e.GetPosition(this)); SystemCommands.ShowSystemMenu(window, new Point(point.X / window.CurrentDpi.ScaleX, point.Y / window.CurrentDpi.ScaleY)); } protected override void OnMouseLeave(MouseEventArgs e) { this.isSystemMenuOpened = false; base.OnMouseLeave(e); } } }
mit
C#
b66e6748ccbefd514e4866cb23e46daec4e41f83
exit if app already started
ZaWertun/ImapTray
Program.cs
Program.cs
using System; using System.Threading; using System.Windows.Forms; namespace ImapTray { static class Program { [STAThread] static void Main() { bool result; var mutex = new Mutex(true, "ImapTray", out result); if (!result) { return; } Log.Info("Application starting up..."); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ImapTrayApplicationContext()); GC.KeepAlive(mutex); } } }
using System; using System.Windows.Forms; namespace ImapTray { static class Program { [STAThread] static void Main() { Log.Info("Application starting up..."); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ImapTrayApplicationContext()); } } }
mit
C#
7b277392d4983afeaa06cd398255f46ff661039c
Add debug mode
mitchfizz05/DangerousPanel,mitchfizz05/DangerousPanel,mitchfizz05/DangerousPanel
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DangerousPanel_Server { class Program { static bool Debug = true; static void Log(string text, ConsoleColor color = ConsoleColor.White, bool debug = false) { if (Debug || !debug) { ConsoleColor oldColor = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(text); Console.ForegroundColor = oldColor; } } static void Main(string[] args) { Console.Title = "Dangerous Panel Server"; Log("Dangerous Panel Server (by Mitchfizz05)", ConsoleColor.Cyan); Log("Debug mode active.", ConsoleColor.Green, true); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DangerousPanel_Server { class Program { static void Log(string text, ConsoleColor color) { ConsoleColor oldColor = Console.ForegroundColor; Console.ForegroundColor = color; Console.WriteLine(text); Console.ForegroundColor = oldColor; } static void Main(string[] args) { Console.Title = "Dangerous Panel Server"; Log("Dangerous Panel Server (by Mitchfizz05)", ConsoleColor.Cyan); Console.ReadKey(); } } }
mit
C#
8a1c0322fdbc15bc1fe6bf14308e142218085c96
convert TestDescriptionAndNoDueDate
jgraber/ForgetTheMilk,jgraber/ForgetTheMilk,jgraber/ForgetTheMilk
ForgetTheMilk/ConsoleVerification/CreateTaskTests.cs
ForgetTheMilk/ConsoleVerification/CreateTaskTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ForgetTheMilk.Controllers; using NUnit.Framework; namespace ConsoleVerification { public class CreateTaskTests : AssertionHelper { [Test] public void TestDescriptionAndNoDueDate() { var input = "Pickup the groceries"; var task = new Task(input, default(DateTime)); Expect(task.Description, Is.EqualTo(input)); Assert.AreEqual(null, task.DueDate); } [Test] public void TestMayDueDateDoesWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-31"; var today = new DateTime(2015, 5, 31); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(2016, 5, 5))); } [Test] public void TestMayDueDateDoesNotWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-04"; var today = new DateTime(2015, 5, 4); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(DateTime.Today.Year, 5, 5))); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ForgetTheMilk.Controllers; using NUnit.Framework; namespace ConsoleVerification { public class CreateTaskTests : AssertionHelper { [Test] public void TestDescriptionAndNoDueDate() { var input = "Pickup the groceries"; var task = new Task(input, default(DateTime)); Expect(task.Description, Is.EqualTo(input)); Assert.AreEqual(null, task.DueDate); } [Test] public void TestMayDueDateDoesWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-31"; var today = new DateTime(2015, 5, 31); var task = new Task(input, today); Expect(task.DueDate, Is.EqualTo(new DateTime(2016, 5, 5))); } private static void TestMayDueDateDoesNotWrapYear() { var input = "Pickup the groceries may 5 - as of 2015-05-04"; Console.WriteLine("Scenario: " + input); var today = new DateTime(2015, 5, 4); var task = new Task(input, today); var dueDateShouldBe = new DateTime(DateTime.Today.Year, 5, 5); var success = dueDateShouldBe == task.DueDate; var failureMessage = "Due date: " + task.DueDate + " should be " + dueDateShouldBe; Program.PrintOutcome(success, failureMessage); } } }
apache-2.0
C#
3bfe47619ff025aab350e6a4f4236c95c6890f8b
teste d
Thiago-Caramelo/patchsearch
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PatchSearch { // teste teste class Program { static void Main(string[] args) { if (args == null || args.Length == 0) { return; } // obter todos os arquivos da pasta string[] files = Directory.GetFiles(Directory.GetCurrentDirectory()); foreach (var item in files) //teste { using (StreamReader reader = new StreamReader(item)) { string fileContent = reader.ReadToEnd(); int qt = 0;//teste 7 foreach (var term in args) { if (fileContent.Contains(term)) { qt++; } } if (qt == args.Length) { Console.WriteLine(Path.GetFileName(item)); } } } } } } //teste c //teste d
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PatchSearch { // teste teste class Program { static void Main(string[] args) { if (args == null || args.Length == 0) { return; } // obter todos os arquivos da pasta string[] files = Directory.GetFiles(Directory.GetCurrentDirectory()); foreach (var item in files) //teste { using (StreamReader reader = new StreamReader(item)) { string fileContent = reader.ReadToEnd(); int qt = 0;//teste 7 foreach (var term in args) { if (fileContent.Contains(term)) { qt++; } } if (qt == args.Length) { Console.WriteLine(Path.GetFileName(item)); } } } } } } //teste c
mit
C#
0cd77d4a845a3b2f07dac024b9d6655bc3c30000
Fix help message
teelahti/AzureServiceBusSharedAccessSignatureGenerator
Program.cs
Program.cs
using System; using System.IO; using System.Reflection; using Microsoft.ServiceBus; namespace AzureServiceBusSharedAccessSignatureGenerator { class Program { static void Main(string[] args) { if (args.Length != 3) { PrintHelps(); return; } string resource = args[0]; string keyName = args[1]; string primaryKey = args[2]; string signature = SharedAccessSignatureTokenProvider.GetSharedAccessSignature( keyName, primaryKey, resource, TimeSpan.FromDays(500)); Console.WriteLine("Complete HTTP header format signature:"); Console.WriteLine(signature); } private static void PrintHelps() { var exe = Path.GetFileName(Assembly.GetExecutingAssembly().Location); Console.WriteLine("Usage: {0} resourceUri keyName primaryKey", exe); Console.WriteLine("e.g. {0} http://foo-ns.servicebus.windows.net/foo WriteEvents cia1mGdvhkD/XDXZD+vChY+fqVsGJr7N21fwHuABbMs=", exe); } } }
using System; using System.IO; using System.Reflection; using Microsoft.ServiceBus; namespace AzureServiceBusSharedAccessSignatureGenerator { class Program { static void Main(string[] args) { if (args.Length != 3) { PrintHelps(); return; } string resource = args[0]; string keyName = args[1]; string primaryKey = args[2]; string signature = SharedAccessSignatureTokenProvider.GetSharedAccessSignature( keyName, primaryKey, resource, TimeSpan.FromDays(500)); Console.WriteLine("Complete HTTP header format signature:"); Console.WriteLine(signature); } private static void PrintHelps() { var exe = Path.GetFileName(Assembly.GetExecutingAssembly().Location); Console.WriteLine("Usage: {0} resourceUri keyName primaryKey", exe); Console.WriteLine("e.g. {0} http://foo-ns.servicebus.windows.net/foo WriteEvents cia1mGdvhkD/XDXZD+vChY+fqVsGJr7N21fwHuABbMs="); } } }
mit
C#
8b36a13cad66f42783c860a29c532658571fc032
Test for deploy
Quilt4/Quilt4.Service,Quilt4/Quilt4.Service,Quilt4/Quilt4.Service
src/Quilt4.Api/Startup.cs
src/Quilt4.Api/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Quilt4.Api.Business; using Quilt4.Api.Interfaces; using Quilt4.Api.Repositories; namespace Quilt4.Api { public class Startup { public Startup(IHostingEnvironment env) { } // This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()); }); services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()); }); // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. // services.AddWebApiConventions(); services.AddTransient<IRepository, MemoryRepository>(); services.AddTransient<IUserBusiness, UserBusiness>(); services.AddTransient<IProjectBusiness, ProjectBusiness>(); services.AddTransient<ISettingBusiness, SettingBusiness>(); } // Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //// Configure the HTTP request pipeline. //app.UseStaticFiles(); //// Add MVC to the request pipeline. //app.UseMvc(); //// Add the following route for porting Web API 2 controllers. //// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.Framework.DependencyInjection; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; using Quilt4.Api.Business; using Quilt4.Api.Interfaces; using Quilt4.Api.Repositories; namespace Quilt4.Api { public class Startup { public Startup(IHostingEnvironment env) { } // This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); options.SerializerSettings.Converters.Add(new IsoDateTimeConverter()); }); services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => builder.AllowAnyOrigin()); }); // Uncomment the following line to add Web API services which makes it easier to port Web API 2 controllers. // You will also need to add the Microsoft.AspNet.Mvc.WebApiCompatShim package to the 'dependencies' section of project.json. // services.AddWebApiConventions(); services.AddTransient<IRepository, MemoryRepository>(); services.AddTransient<IUserBusiness, UserBusiness>(); services.AddTransient<IProjectBusiness, ProjectBusiness>(); services.AddTransient<ISettingBusiness, SettingBusiness>(); } // Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { // Configure the HTTP request pipeline. app.UseStaticFiles(); // Add MVC to the request pipeline. app.UseMvc(); // Add the following route for porting Web API 2 controllers. // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}"); } } }
mit
C#
ff1f87f3664535f523ee5fdff5c8b1c007dbed30
Remove invalid Scripts call
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
SupportManager.Web/Views/PhoneNumber/Create.cshtml
SupportManager.Web/Views/PhoneNumber/Create.cshtml
@using SupportManager.Web.Infrastructure @model SupportManager.Web.Features.PhoneNumber.PhoneNumberCreateCommand @{ ViewBag.Title = "Add phone number"; } <h2>Add phone number</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <fieldset> <legend>Phone number details</legend> @Html.ValidationDiv() @Html.FormBlock(m => m.Label) @Html.FormBlock(m => m.PhoneNumber) <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-primary"/> </div> </div> </fieldset> </div> } <div> @Html.ActionLink("Back to list", "Index") </div>
@using SupportManager.Web.Infrastructure @model SupportManager.Web.Features.PhoneNumber.PhoneNumberCreateCommand @{ ViewBag.Title = "Add phone number"; } <h2>Add phone number</h2> @using (Html.BeginForm()) { @Html.AntiForgeryToken() <div class="form-horizontal"> <fieldset> <legend>Phone number details</legend> @Html.ValidationDiv() @Html.FormBlock(m => m.Label) @Html.FormBlock(m => m.PhoneNumber) <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Create" class="btn btn-primary"/> </div> </div> </fieldset> </div> } <div> @Html.ActionLink("Back to list", "Index") </div> @Scripts.Render("~/bundles/jqueryval")
mit
C#
5c165aab03bd784850120c6bf0f917e01b6acd03
Clean some unnecessary event
afisd/jovice,afisd/jovice
Test/Test.cs
Test/Test.cs
using Aphysoft.Share; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Aphysoft.Test { public class Test : Node { #region Constructors public Test() : base("TEST") { } #endregion protected override void OnEvent(string message) { if (IsConsole) Console.WriteLine(message); } protected override void OnStart() { while (IsRunning) { Thread.Sleep(1000); } } protected override void OnStop() { } } }
using Aphysoft.Share; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Aphysoft.Test { public class Test : Node { #region Constructors public Test() : base("TEST") { } #endregion protected override void OnEvent(string message) { if (IsConsole) Console.WriteLine(message); } protected override void OnStart() { Event("Test Starting"); while (IsRunning) { Thread.Sleep(1000); } } protected override void OnStop() { } } }
mit
C#
71a6b222ae85ed6e26c84f5b68a76b4287e816fd
Add IfTrue for fluent composition of bool
Weingartner/SolidworksAddinFramework
SolidworksAddinFramework/BoolExtensions.cs
SolidworksAddinFramework/BoolExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LanguageExt; using static LanguageExt.Prelude; namespace SolidworksAddinFramework { public static class BoolExtensions { public static Option<T> IfTrue<T>(this bool v, Func<T> fn) => v ? Some(fn()) : None; public static bool IfTrue(this bool v, Action fn) { if (v) fn(); return true; } public static Option<T> IfTrue<T>(this bool v, T t) => v.IfTrue(() => t); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LanguageExt; using static LanguageExt.Prelude; namespace SolidworksAddinFramework { public static class BoolExtensions { public static Option<T> IfTrue<T>(this bool v, Func<T> fn) => v ? Some(fn()) : None; public static Option<T> IfTrue<T>(this bool v, T t) => v.IfTrue(() => t); } }
mit
C#
63a3a5e0d88f3f5bdf76d992c96d902528a9880f
Set current HTTP request when sending Status Code exceptions from WebApi
nelsonsar/raygun4net,nelsonsar/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,MindscapeHQ/raygun4net,tdiehl/raygun4net,articulate/raygun4net,tdiehl/raygun4net,ddunkin/raygun4net,articulate/raygun4net,ddunkin/raygun4net
Mindscape.Raygun4Net45/WebApi/RaygunWebApiFilters.cs
Mindscape.Raygun4Net45/WebApi/RaygunWebApiFilters.cs
using System; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Filters; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiExceptionFilter : ExceptionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiExceptionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnException(HttpActionExecutedContext context) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception); } public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken) { return Task.Factory.StartNew(() => _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception), cancellationToken); } } public class RaygunWebApiActionFilter : ActionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiActionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnActionExecuted(HttpActionExecutedContext context) { base.OnActionExecuted(context); if (context != null && context.Response != null && (int)context.Response.StatusCode >= 400) { try { throw new RaygunWebApiHttpException( context.Response.StatusCode, string.Format("HTTP {0} returned while handling Request {2} {1}", (int)context.Response.StatusCode, context.Request.RequestUri, context.Request.Method)); } catch (Exception e) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(e); } } } } public class RaygunWebApiHttpException : Exception { public HttpStatusCode StatusCode { get; set; } public RaygunWebApiHttpException(HttpStatusCode statusCode, string message) : base(message) { StatusCode = statusCode; } } }
using System; using System.Net; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Filters; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiExceptionFilter : ExceptionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiExceptionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnException(HttpActionExecutedContext context) { _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception); } public override Task OnExceptionAsync(HttpActionExecutedContext context, CancellationToken cancellationToken) { return Task.Factory.StartNew(() => _clientCreator.GenerateRaygunWebApiClient().CurrentHttpRequest(context.Request).Send(context.Exception), cancellationToken); } } public class RaygunWebApiActionFilter : ActionFilterAttribute { private readonly IRaygunWebApiClientProvider _clientCreator; internal RaygunWebApiActionFilter(IRaygunWebApiClientProvider clientCreator) { _clientCreator = clientCreator; } public override void OnActionExecuted(HttpActionExecutedContext context) { base.OnActionExecuted(context); if (context != null && context.Response != null && (int)context.Response.StatusCode >= 400) { try { throw new RaygunWebApiHttpException( context.Response.StatusCode, string.Format("HTTP {0} returned while handling Request {2} {1}", (int)context.Response.StatusCode, context.Request.RequestUri, context.Request.Method)); } catch (Exception e) { _clientCreator.GenerateRaygunWebApiClient().Send(e); } } } } public class RaygunWebApiHttpException : Exception { public HttpStatusCode StatusCode { get; set; } public RaygunWebApiHttpException(HttpStatusCode statusCode, string message) : base(message) { StatusCode = statusCode; } } }
mit
C#
2045188f455701780d23e801f3cfea1399874011
Add FromHexString tests.
BluewireTechnologies/cassette,honestegg/cassette,damiensawyer/cassette,damiensawyer/cassette,andrewdavey/cassette,andrewdavey/cassette,honestegg/cassette,andrewdavey/cassette,honestegg/cassette,BluewireTechnologies/cassette,damiensawyer/cassette
src/Cassette.UnitTests/Utilities/ByteArrayExtensions.cs
src/Cassette.UnitTests/Utilities/ByteArrayExtensions.cs
using Should; using Xunit; namespace Cassette.Utilities { public class ByteArrayExtensions_ToHexString_Tests { [Fact] public void Empty_array_returns_empty_string() { new byte[] { }.ToHexString().ShouldEqual(""); } [Fact] public void _1_returns_01_as_string() { new byte[] { 1 }.ToHexString().ShouldEqual("01"); } [Fact] public void _10_returns_0a_as_string() { new byte[] { 10 }.ToHexString().ShouldEqual("0a"); } [Fact] public void _255_returns_ff_as_string() { new byte[] { 255 }.ToHexString().ShouldEqual("ff"); } } public class ByteArrayExtensions_FromHexString_Tests { [Fact] public void _01_returns_1() { ByteArrayExtensions.FromHexString("01").ShouldEqual(new byte[] { 1 }); } [Fact] public void _01ff_returns_1_255() { ByteArrayExtensions.FromHexString("01ff").ShouldEqual(new byte[] { 1, 255 }); } [Fact] public void _01FF_returns_1_255() { ByteArrayExtensions.FromHexString("01FF").ShouldEqual(new byte[] { 1, 255 }); } } }
using Should; using Xunit; namespace Cassette.Utilities { public class ByteArrayExtensions_ToHexString_tests { [Fact] public void Empty_array_returns_empty_string() { new byte[] { }.ToHexString().ShouldEqual(""); } [Fact] public void _1_returns_01_as_string() { new byte[] { 1 }.ToHexString().ShouldEqual("01"); } [Fact] public void _10_returns_0a_as_string() { new byte[] { 10 }.ToHexString().ShouldEqual("0a"); } [Fact] public void _255_returns_ff_as_string() { new byte[] { 255 }.ToHexString().ShouldEqual("ff"); } } }
mit
C#
e127e01c4754d2f8c6cb7f90dac2f5f9885f9db7
Update RequiresStatelessAuth.cs
jchannon/Owin.StatelessAuth,jchannon/Owin.StatelessAuth,jchannon/Owin.StatelessAuth
src/Owin.StatelessAuth/RequiresStatelessAuth.cs
src/Owin.StatelessAuth/RequiresStatelessAuth.cs
namespace Owin.RequiresStatelessAuth { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public class RequiresStatelessAuth { private readonly ITokenValidator tokenValidator; private readonly Func<IDictionary<string, object>, Task> nextFunc; private const string ServerUser = "server.User"; public RequiresStatelessAuth(Func<IDictionary<string, object>, Task> nextFunc, ITokenValidator tokenValidator) { this.nextFunc = nextFunc; this.tokenValidator = tokenValidator; } public Task Invoke(IDictionary<string, object> environment) { var requestHeaders = (IDictionary<string, string[]>)environment["owin.RequestHeaders"]; if (!requestHeaders.ContainsKey("Authorization")) { environment["owin.ResponseStatusCode"] = 401; return ReturnCompletedTask(); } var token = requestHeaders["Authorization"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(token)) { environment["owin.ResponseStatusCode"] = 401; return ReturnCompletedTask(); } var validatedUser = tokenValidator.ValidateUser(token); if (validatedUser == null) { environment["owin.ResponseStatusCode"] = 401; return ReturnCompletedTask(); } if (environment.ContainsKey(ServerUser)) { environment[ServerUser] = validatedUser; } else { environment.Add(ServerUser, validatedUser); } return nextFunc(environment); } private Task ReturnCompletedTask() { return Task.FromResult(0); } } }
namespace Owin.RequiresStatelessAuth { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public class RequiresStatelessAuth { private readonly ITokenValidator tokenValidator; private readonly Func<IDictionary<string, object>, Task> nextFunc; public RequiresStatelessAuth(Func<IDictionary<string, object>, Task> nextFunc, ITokenValidator tokenValidator) { this.nextFunc = nextFunc; this.tokenValidator = tokenValidator; } public Task Invoke(IDictionary<string, object> environment) { var requestHeaders = (IDictionary<string, string[]>)environment["owin.RequestHeaders"]; if (!requestHeaders.ContainsKey("Authorization")) { environment["owin.ResponseStatusCode"] = 401; return ReturnCompletedTask(); } var token = requestHeaders["Authorization"].FirstOrDefault(); if (string.IsNullOrWhiteSpace(token)) { environment["owin.ResponseStatusCode"] = 401; return ReturnCompletedTask(); } var validated = tokenValidator.ValidateUser(token); if (!validated) { environment["owin.ResponseStatusCode"] = 401; return ReturnCompletedTask(); } return nextFunc(environment); } private Task ReturnCompletedTask() { return Task.FromResult(0); } } }
mit
C#
50c6485eefa466d205a2b23b446bc3fc723cb01d
Correct the name of this test
Benrnz/BudgetAnalyser
Rees.TangyFruitMapper.UnitTest/Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix.cs
Rees.TangyFruitMapper.UnitTest/Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix.cs
using Rees.TangyFruitMapper.UnitTest.TestData; using Xunit; using Xunit.Abstractions; namespace Rees.TangyFruitMapper.UnitTest { public class Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix : MappingGeneratorScenarios<DtoType4, ModelType4_UnderscoreBackingField> { public Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix(ITestOutputHelper output) : base(output) { } [Fact] public void Generate_ShouldOutputCode() { Assert.NotEmpty(this.GeneratedCode); } [Fact] public void Generate_ShouldSuccessfullyMapToDto() { var mapper = CreateMapperFromGeneratedCode(); var result = mapper.ToDto(new ModelType4_UnderscoreBackingField(410, 3.1415M, "Pie Constant")); Assert.Equal(410, result.Age); Assert.Equal(3.1415M, result.MyNumber); Assert.Equal("Pie Constant", result.Name); } [Fact] public void Generate_ShouldNOTMapToModel() { // This is not supported. Properties must be writable at least with private setters. Assert.True(this.GeneratedCode.Contains("// TODO No properties found to map")); } } }
using Rees.TangyFruitMapper.UnitTest.TestData; using Xunit; using Xunit.Abstractions; namespace Rees.TangyFruitMapper.UnitTest { public class Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix : MappingGeneratorScenarios<DtoType4, ModelType4_UnderscoreBackingField> { public Scenario4_PropertiesWithBackingFieldAndUnderscorePrefix(ITestOutputHelper output) : base(output) { } [Fact] public void Generate_ShouldOutputCode() { Assert.NotEmpty(this.GeneratedCode); } [Fact] public void Generate_ShouldSuccessfullyMapToDto() { var mapper = CreateMapperFromGeneratedCode(); var result = mapper.ToDto(new ModelType4_UnderscoreBackingField(410, 3.1415M, "Pie Constant")); Assert.Equal(410, result.Age); Assert.Equal(3.1415M, result.MyNumber); Assert.Equal("Pie Constant", result.Name); } [Fact] public void Generate_ShouldSuccessfullyMapToModel() { // This is not supported. Properties must be writable at least with private setters. Assert.True(this.GeneratedCode.Contains("// TODO No properties found to map")); } } }
mit
C#
6d57b0b93657c773f5ceaa429a9326b395a577fd
Update version to 1.1.1-beta3
bungeemonkee/Transformerizer
Transformerizer/Properties/AssemblyInfo.cs
Transformerizer/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("Transformerizer")] [assembly: AssemblyDescription("Transformerizer: Parallel transform library for .NET")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Transformerizer")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.1.1.3")] [assembly: AssemblyFileVersion("1.1.1.3")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.1.1-beta3")]
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("Transformerizer")] [assembly: AssemblyDescription("Transformerizer: Parallel transform library for .NET")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("David Love")] [assembly: AssemblyProduct("Transformerizer")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values. // We will increase these values in the following way: // Major Version : Increased when there is a release that breaks a public api // Minor Version : Increased for each non-api-breaking release // Build Number : 0 for alpha versions, 1 for beta versions, 2 for release candidates, 3 for releases // Revision : Always 0 for release versions, always 1+ for alpha, beta, rc versions to indicate the alpha/beta/rc number [assembly: AssemblyVersion("1.1.1.2")] [assembly: AssemblyFileVersion("1.1.1.2")] // This version number will roughly follow semantic versioning : http://semver.org // The first three numbers will always match the first the numbers of the version above. [assembly: AssemblyInformationalVersion("1.1.1-beta2")]
mit
C#
75c6dd0c0ae2d5e9d2415480f6ab0e11cb66dba0
Add AchivementType enum
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University/entities/EmployeeAchivementInfo.cs
R7.University/entities/EmployeeAchivementInfo.cs
using System; using System.Text.RegularExpressions; using DotNetNuke.Data; using DotNetNuke.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; namespace R7.University { public enum AchivementType { Achivement = 'A', Education = 'E', Training = 'T' } // More attributes for class: // Set caching for table: [Cacheable("R7.University_Divisions", CacheItemPriority.Default, 20)] // Explicit mapping declaration: [DeclareColumns] // More attributes for class properties: // Custom column name: [ColumnName("DivisionID")] // Explicit include column: [IncludeColumn] // Note: DAL 2 have no AutoJoin analogs from PetaPOCO at this time [TableName ("University_EmployeeAchivements")] [PrimaryKey ("EmployeeAchivementID", AutoIncrement = true)] public class EmployeeAchivementInfo : IReferenceEntity { #region Fields #endregion /// <summary> /// Empty default cstor /// </summary> public EmployeeAchivementInfo () { } #region IReferenceEntity implementation public string Title { get; set; } public string ShortTitle { get; set; } #endregion #region Properties public int EmployeeAchivementID { get; set; } public int EmployeeID { get; set; } public string Description { get; set; } public int? YearBegin { get; set; } public int? YearEnd { get; set; } public bool IsTitle { get; set; } public string DocumentURL { get; set; } [ColumnName ("AchivementType")] public string AchivementTypeString { get; set; } #endregion [IgnoreColumn] public AchivementType AchivementType { get { return (AchivementType)AchivementTypeString[0]; } set { AchivementTypeString = ((char)value).ToString(); } } } }
using System; using System.Text.RegularExpressions; using DotNetNuke.Data; using DotNetNuke.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; namespace R7.University { // More attributes for class: // Set caching for table: [Cacheable("R7.University_Divisions", CacheItemPriority.Default, 20)] // Explicit mapping declaration: [DeclareColumns] // More attributes for class properties: // Custom column name: [ColumnName("DivisionID")] // Explicit include column: [IncludeColumn] // Note: DAL 2 have no AutoJoin analogs from PetaPOCO at this time [TableName ("University_EmployeeAchivements")] [PrimaryKey ("EmployeeAchivementID", AutoIncrement = true)] public class EmployeeAchivementInfo : IReferenceEntity { #region Fields #endregion /// <summary> /// Empty default cstor /// </summary> public EmployeeAchivementInfo () { } #region IReferenceEntity implementation public string Title { get; set; } public string ShortTitle { get; set; } #endregion #region Properties public int EmployeeAchivementID { get; set; } public int EmployeeID { get; set; } public string Description { get; set; } public int? YearBegin { get; set; } public int? YearEnd { get; set; } public bool IsTitle { get; set; } public string DocumentURL { get; set; } [ColumnName ("AchivementType")] public string AchivementTypeString { get; set; } #endregion [IgnoreColumn] public char AchivementType { get { return AchivementTypeString [0]; } set { AchivementTypeString = value.ToString (); } } } }
agpl-3.0
C#
b33fbd46f057ee4b1e0e62ca1dfab09ed0cdb76c
update version and copyright
daviddumas/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina,MutonUfoAI/pgina,daviddumas/pgina,daviddumas/pgina
Plugins/Kerberos/Kerberos/Properties/AssemblyInfo.cs
Plugins/Kerberos/Kerberos/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("Kerberos")] [assembly: AssemblyDescription("Seth Walsh")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("University of Utah")] [assembly: AssemblyProduct("Kerberos")] [assembly: AssemblyCopyright("Copyright © University of Utah 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("594fae6c-c648-419f-8412-6ba2a67a3fbf")] // 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.9.9.0")] [assembly: AssemblyFileVersion("3.9.9.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("Kerberos")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Kerberos")] [assembly: AssemblyCopyright("Copyright © 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("594fae6c-c648-419f-8412-6ba2a67a3fbf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.2.5.0")] [assembly: AssemblyFileVersion("3.2.5.0")]
bsd-3-clause
C#
f48cc01d27a1f3e1d18e03c2bfe90da68d902b2e
Fix a bug or two
kjac/FormEditor,kjac/FormEditor,kjac/FormEditor
Source/Solution/FormEditor/Fields/MemberInfoField.cs
Source/Solution/FormEditor/Fields/MemberInfoField.cs
using System; using System.Collections.Generic; using Umbraco.Core.Models; using Umbraco.Web; namespace FormEditor.Fields { public class MemberInfoField : FieldWithValue, IEmailField { public override string Type { get { return "core.memberinfo"; } } public override string PrettyName { get { return "Member info"; } } protected internal override void CollectSubmittedValue(Dictionary<string, string> allSubmittedValues, IPublishedContent content) { // get the logged in member (if any) var user = UmbracoContext.Current.HttpContext.User; var identity = user != null ? user.Identity : null; var member = identity != null && string.IsNullOrWhiteSpace(identity.Name) == false ? UmbracoContext.Current.Application.Services.MemberService.GetByUsername(identity.Name) : null; if (member == null) { // no member logged in base.CollectSubmittedValue(allSubmittedValues, content); return; } // gather member data for index SubmittedValue = string.Format("{0}|{1}|{2}", member.Name, member.Email, member.Id); } protected internal override string FormatValueForDataView(string value, IContent content, Guid rowId) { return FormatValue(value) ?? base.FormatValueForDataView(value, content, rowId); } protected internal override string FormatValueForCsvExport(string value, IContent content, Guid rowId) { return FormatValue(value) ?? base.FormatValueForCsvExport(value, content, rowId); } protected internal override string FormatValueForFrontend(string value, IPublishedContent content, Guid rowId) { return FormatValue(value) ?? base.FormatValueForFrontend(value, content, rowId); } #region IEmailField members // this field implements IEmailField so receipt emails can be sent to the member email public IEnumerable<string> EmailAddresses { get { if (string.IsNullOrEmpty(SubmittedValue)) { return null; } var parts = SubmittedValue.Split(new[] {'|'}, StringSplitOptions.None); return parts.Length < 2 ? null : new[] {parts[1]}; } } #endregion private string FormatValue(string value) { if (string.IsNullOrEmpty(value)) { return null; } var parts = value.Split(new[] {'|'}, StringSplitOptions.None); return parts.Length < 2 ? null : string.Format("{0} ({1})", parts[0], parts[1]); } } }
using System; using System.Collections.Generic; using Umbraco.Core.Models; using Umbraco.Web; namespace FormEditor.Fields { public class MemberInfoField : FieldWithValue, IEmailField { public override string Type { get { return "core.memberinfo"; } } public override string PrettyName { get { return "Member info"; } } protected internal override void CollectSubmittedValue(Dictionary<string, string> allSubmittedValues, IPublishedContent content) { var currentUser = UmbracoContext.Current.Security.CurrentUser; if (currentUser == null) { base.CollectSubmittedValue(allSubmittedValues, content); return; } SubmittedValue = string.Format("{0}|{1}|{2}", currentUser.Name, currentUser.Email, currentUser.Id); } protected internal override string FormatValueForDataView(string value, IContent content, Guid rowId) { return FormatValue(value) ?? base.FormatValueForDataView(value, content, rowId); } protected internal override string FormatValueForCsvExport(string value, IContent content, Guid rowId) { return FormatValue(value) ?? base.FormatValueForCsvExport(value, content, rowId); } protected internal override string FormatValueForFrontend(string value, IPublishedContent content, Guid rowId) { return FormatValue(value) ?? base.FormatValueForFrontend(value, content, rowId); } public IEnumerable<string> EmailAddresses { get { if (string.IsNullOrEmpty(SubmittedValue)) { return null; } var parts = SubmittedValue.Split(new[] {'|'}, StringSplitOptions.None); return parts.Length < 2 ? null : new[] {parts[1]}; } } private string FormatValue(string value) { if (string.IsNullOrEmpty(value)) { return null; } var parts = SubmittedValue.Split(new[] {'|'}, StringSplitOptions.None); return parts.Length < 2 ? null : string.Format("{0} ({1})", parts[0], parts[1]); } } }
mit
C#
feb0546f1fab4510516dce3a121a762af4c328e6
Update ICommand.cs
DarkIrata/WinCommandPalette
WinCommandPalette/PluginSystem/ICommand.cs
WinCommandPalette/PluginSystem/ICommand.cs
using System.Windows.Controls; namespace WinCommandPalette.PluginSystem { public interface ICommand { string Name { get; } string Description { get; } bool RunInUIThread { get; } void Execute(); } }
using System.Windows.Controls; namespace WinCommandPalette.PluginSystem { public interface ICommand { string Name { get; } string Description { get; } bool RunInUIThread { get; } bool RunAsAdmin { get; } void Execute(); } }
mit
C#
1d39a2a0c8046983e7c4d287ae866814231963b0
Add CamelCasePropertyNamesContractResolver to serializer
huysentruitw/simple-json-api
src/SimpleJsonApi/Configuration/JsonApiConfiguration.cs
src/SimpleJsonApi/Configuration/JsonApiConfiguration.cs
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace SimpleJsonApi.Configuration { public sealed class JsonApiConfiguration { public const string JsonApiMediaType = "application/vnd.api+json"; public JsonApiConfiguration() { SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); SerializerSettings.Converters.Add(new IsoDateTimeConverter()); SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); } public string MediaType { get; set; } = JsonApiMediaType; public ResourceConfiguration ResourceConfiguration { get; set; } public JsonSerializerSettings SerializerSettings { get; } = new JsonSerializerSettings(); internal void Validate() { if (string.IsNullOrEmpty(MediaType)) throw new ArgumentNullException(nameof(MediaType)); if (ResourceConfiguration == null) throw new ArgumentNullException(nameof(ResourceConfiguration)); } } }
using System; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace SimpleJsonApi.Configuration { public sealed class JsonApiConfiguration { public const string JsonApiMediaType = "application/vnd.api+json"; public JsonApiConfiguration() { SerializerSettings.Converters.Add(new IsoDateTimeConverter()); SerializerSettings.Converters.Add(new StringEnumConverter { CamelCaseText = true }); } public string MediaType { get; set; } = JsonApiMediaType; public ResourceConfiguration ResourceConfiguration { get; set; } public JsonSerializerSettings SerializerSettings { get; } = new JsonSerializerSettings(); internal void Validate() { if (string.IsNullOrEmpty(MediaType)) throw new ArgumentNullException(nameof(MediaType)); if (ResourceConfiguration == null) throw new ArgumentNullException(nameof(ResourceConfiguration)); } } }
apache-2.0
C#
6e910babd10d1492a5c25a5211548b06944b775c
Simplify startup class
stuartleeks/tinyaspnet5
Startup.cs
Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; namespace EmptyWeb { public class Startup { public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseWelcomePage(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; namespace EmptyWeb { public class Startup { public Startup(IHostingEnvironment env) { } // This method gets called by a runtime. // Use this method to add services to the container public void ConfigureServices(IServiceCollection services) { } // Configure is called after ConfigureServices is called. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseWelcomePage(); } } }
mit
C#
a0d245f9ecd995226118db8389499f1ce0d2b383
fix test outputHelper exception
WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common
test/WeihanLi.Common.Test/AspectTest/TestOutputInterceptor.cs
test/WeihanLi.Common.Test/AspectTest/TestOutputInterceptor.cs
using System; using System.Diagnostics; using System.Threading.Tasks; using WeihanLi.Common.Aspect; using WeihanLi.Extensions; using Xunit.Abstractions; namespace WeihanLi.Common.Test.AspectTest { public class TestOutputInterceptor : IInterceptor { private readonly ITestOutputHelper _output; public TestOutputInterceptor(ITestOutputHelper output) { _output = output; } public async Task Invoke(IInvocation invocation, Func<Task> next) { Debug.WriteLine($"Method[{invocation.ProxyMethod.Name}({invocation.Arguments.StringJoin(",")})] is invoking..."); await next(); Debug.WriteLine($"Method[{invocation.ProxyMethod.Name}({invocation.Arguments.StringJoin(",")})] invoked..."); } } }
using System; using System.Threading.Tasks; using WeihanLi.Common.Aspect; using WeihanLi.Extensions; using Xunit.Abstractions; namespace WeihanLi.Common.Test.AspectTest { public class TestOutputInterceptor : IInterceptor { private readonly ITestOutputHelper _output; public TestOutputInterceptor(ITestOutputHelper output) { _output = output; } public async Task Invoke(IInvocation invocation, Func<Task> next) { _output.WriteLine($"Method[{invocation.ProxyMethod.Name}({invocation.Arguments.StringJoin(",")})] is invoking..."); await next(); _output.WriteLine($"Method[{invocation.ProxyMethod.Name}({invocation.Arguments.StringJoin(",")})] invoked..."); } } }
mit
C#
4f980de4b7a02649580da4d2ec56ecd97eb18489
Add view for displaying event details
samaritanevent/Samaritans,samaritanevent/Samaritans
Samaritans/Samaritans/Views/Event/Details.cshtml
Samaritans/Samaritans/Views/Event/Details.cshtml
@model Samaritans.Models.EventViewModel @{ ViewBag.Title = Model.Name; } <article class="event"> <form> <h2>@M<input type="type" name="name" value="odel.Name</h2> <div>@Model.EventTime</div> <div>@Model.Attendance</div> <p>@Model.Purpose</p> <h3>Bring:</h3> @for (var i = 0; i < Model.Resources.Length; i++) { var resources = Model.Resources[i]; <div> <span>resource.Description</span> <input type="hidden" name="resources[i].description" /> <input type="number" name="resources[i].quantity" /> </div> } " /> type="submit" value="Join" /> </form> </article>
@model Samaritans.Models.EventViewModel @{ ViewBag.Title = Model.Name; } <h2>@Model.Name</h2>
mit
C#
483bdc5a358383a2cbdf7635aef01cd2d7c0b9e1
Fix a bug in VirtualButtonsFromCode
mfep/Duality.InputPlugin
Source/Code/CorePlugin/Example/VirtualButtonsFromCode.cs
Source/Code/CorePlugin/Example/VirtualButtonsFromCode.cs
using Duality; using Duality.Editor; using Duality.Input; namespace MFEP.Duality.Plugins.InputPlugin.Example { [EditorHintCategory (ResNames.EditorCategory)] public class VirtualButtonsFromCode : Component, ICmpUpdatable { public void OnUpdate () { if (DualityApp.Keyboard.KeyHit (Key.Number1)) AddButtons (); if (DualityApp.Keyboard.KeyHit (Key.Number2)) RemoveButton (); if (DualityApp.Keyboard.KeyHit (Key.Number3)) RenameButton (); if (DualityApp.Keyboard.KeyHit (Key.Number4)) AddKeys (); if (DualityApp.Keyboard.KeyHit (Key.Number5)) RemoveKeys (); } private void RemoveKeys () { InputManager.RemoveFromButton ("Rave", Key.Space); } private void AddKeys () { InputManager.AddToButton ("Rave", Key.Space); } private void RenameButton () { InputManager.RenameButton ("Sleep", "Rave"); } private void RemoveButton () { InputManager.RemoveButton ("Eat"); } private void AddButtons () { InputManager.RegisterButton (new ButtonTuple ("Eat", Key.ControlLeft)); InputManager.AddToButton ("Eat", Key.ControlRight); InputManager.RegisterButton (new ButtonTuple ("Sleep", Key.AltLeft)); InputManager.AddToButton ("Sleep", Key.AltRight); } } }
using Duality; using Duality.Editor; using Duality.Input; namespace MFEP.Duality.Plugins.InputPlugin.Example { [EditorHintCategory (ResNames.EditorCategory)] public class VirtualButtonsFromCode : Component, ICmpUpdatable { public void OnUpdate () { if (DualityApp.Keyboard[Key.Number1]) AddButtons (); if (DualityApp.Keyboard[Key.Number2]) RemoveButton (); if (DualityApp.Keyboard[Key.Number3]) RenameButton (); if (DualityApp.Keyboard[Key.Number4]) AddKeys (); if (DualityApp.Keyboard[Key.Number5]) RemoveKeys (); } private void RemoveKeys () { InputManager.RemoveFromButton ("Rave", Key.Space); } private void AddKeys () { InputManager.AddToButton ("Rave", Key.Space); } private void RenameButton () { InputManager.RenameButton ("Sleep", "Rave"); } private void RemoveButton () { InputManager.RemoveButton ("Eat"); } private void AddButtons () { InputManager.RegisterButton (new ButtonTuple ("Eat", Key.ControlLeft)); InputManager.AddToButton ("Eat", Key.ControlRight); InputManager.RegisterButton (new ButtonTuple ("Sleep", Key.AltLeft)); InputManager.AddToButton ("Sleep", Key.AltRight); } } }
mit
C#
3607568ec5165ce05e709c233306ed93fbeaf48f
Add constructor that accepts DbConnection and bool contextOwnsConnection
abdllhbyrktr/module-zero-core-template,abdllhbyrktr/module-zero-core-template,abdllhbyrktr/module-zero-core-template,abdllhbyrktr/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,abdllhbyrktr/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template,aspnetboilerplate/module-zero-core-template
src/AbpCompanyName.AbpProjectName.EntityFramework/EntityFramework/AbpProjectNameDbContext.cs
src/AbpCompanyName.AbpProjectName.EntityFramework/EntityFramework/AbpProjectNameDbContext.cs
using System.Data.Common; using System.Data.Entity; using Abp.Zero.EntityFramework; using Microsoft.Extensions.Configuration; using AbpCompanyName.AbpProjectName.Authorization.Roles; using AbpCompanyName.AbpProjectName.Configuration; using AbpCompanyName.AbpProjectName.MultiTenancy; using AbpCompanyName.AbpProjectName.Users; using AbpCompanyName.AbpProjectName.Web; namespace AbpCompanyName.AbpProjectName.EntityFramework { [DbConfigurationType(typeof(AbpProjectNameDbConfiguration))] public class AbpProjectNameDbContext : AbpZeroDbContext<Tenant, Role, User> { /* Define an IDbSet for each entity of the application */ /* Default constructor is needed for EF command line tool. */ public AbpProjectNameDbContext() : base(GetConnectionString()) { } private static string GetConnectionString() { var configuration = AppConfigurations.Get( WebContentDirectoryFinder.CalculateContentRootFolder() ); return configuration.GetConnectionString( AbpProjectNameConsts.ConnectionStringName ); } /* This constructor is used by ABP to pass connection string. * Notice that, actually you will not directly create an instance of AbpProjectNameDbContext since ABP automatically handles it. */ public AbpProjectNameDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } /* This constructor is used in tests to pass a fake/mock connection. */ public AbpProjectNameDbContext(DbConnection dbConnection) : base(dbConnection, true) { } public AbpProjectNameDbContext(DbConnection dbConnection, bool contextOwnsConnection) : base(dbConnection, contextOwnsConnection) { } } public class AbpProjectNameDbConfiguration : DbConfiguration { public AbpProjectNameDbConfiguration() { SetProviderServices( "System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance ); } } }
using System.Data.Common; using System.Data.Entity; using Abp.Zero.EntityFramework; using Microsoft.Extensions.Configuration; using AbpCompanyName.AbpProjectName.Authorization.Roles; using AbpCompanyName.AbpProjectName.Configuration; using AbpCompanyName.AbpProjectName.MultiTenancy; using AbpCompanyName.AbpProjectName.Users; using AbpCompanyName.AbpProjectName.Web; namespace AbpCompanyName.AbpProjectName.EntityFramework { [DbConfigurationType(typeof(AbpProjectNameDbConfiguration))] public class AbpProjectNameDbContext : AbpZeroDbContext<Tenant, Role, User> { /* Define an IDbSet for each entity of the application */ /* Default constructor is needed for EF command line tool. */ public AbpProjectNameDbContext() : base(GetConnectionString()) { } private static string GetConnectionString() { var configuration = AppConfigurations.Get( WebContentDirectoryFinder.CalculateContentRootFolder() ); return configuration.GetConnectionString( AbpProjectNameConsts.ConnectionStringName ); } /* This constructor is used by ABP to pass connection string. * Notice that, actually you will not directly create an instance of AbpProjectNameDbContext since ABP automatically handles it. */ public AbpProjectNameDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { } /* This constructor is used in tests to pass a fake/mock connection. */ public AbpProjectNameDbContext(DbConnection dbConnection) : base(dbConnection, true) { } } public class AbpProjectNameDbConfiguration : DbConfiguration { public AbpProjectNameDbConfiguration() { SetProviderServices( "System.Data.SqlClient", System.Data.Entity.SqlServer.SqlProviderServices.Instance ); } } }
mit
C#
aabb85744ea7b1a04f8cb1c51a74a964ad4df7ca
Update assembly version of sharpmake to the one from the *next* intended release, 0.7.3, that way I might not forget to update it...
ubisoftinc/Sharpmake,ubisoftinc/Sharpmake,ubisoftinc/Sharpmake
Sharpmake.Application/Properties/AssemblyInfo.cs
Sharpmake.Application/Properties/AssemblyInfo.cs
// Copyright (c) 2017 Ubisoft Entertainment // // 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.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("Sharpmake.Application")] [assembly: AssemblyDescription(".NET-based project generator for C#, C++ and more.")] // Probably write a better description. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ubisoft")] [assembly: AssemblyProduct("Sharpmake.Application")] [assembly: AssemblyCopyright("Copyright \u00A9 Ubisoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6c9d3ac9-bd39-4a6a-aac1-2f87aba6d941")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.3.0")] [assembly: AssemblyFileVersion("0.7.3.0")]
// Copyright (c) 2017 Ubisoft Entertainment // // 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.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("Sharpmake.Application")] [assembly: AssemblyDescription(".NET-based project generator for C#, C++ and more.")] // Probably write a better description. [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Ubisoft")] [assembly: AssemblyProduct("Sharpmake.Application")] [assembly: AssemblyCopyright("Copyright \u00A9 Ubisoft 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6c9d3ac9-bd39-4a6a-aac1-2f87aba6d941")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.7.1.0")] [assembly: AssemblyFileVersion("0.7.1.0")]
apache-2.0
C#
9a4bea51dcb2f4020125b690c2d3a0f13fb1bcb4
update reduce tests
amiralles/abacus,amiralles/abacus
src/test/ReduceFixture.cs
src/test/ReduceFixture.cs
#pragma warning disable 414, 219 namespace Abacus.Test { using System; using System.Collections.Generic; using System.Data; using System.Reflection; using System.Linq.Expressions; using static Abacus.Utils; using static Abacus.Error; using static System.Linq.Expressions.Expression; using static Interpreter; using static System.Console; using static System.Convert; using static System.DateTime; using _ = System.Action<Contest.Core.Runner>; class ReduceFixture { //TODO: Add hook for client func calls. _ reduce_data_table = assert => { var tbl = new DataTable(); tbl.Columns.Add("Price", typeof(double)); tbl.Columns.Add("Date", typeof(DateTime)); tbl.Columns.Add("User", typeof(string)); var startDate = new DateTime(2012, 05, 14); for (int i = 0; i < 10; ++i) { var row = tbl.NewRow(); row["Price"] = i; row["Date"] = startDate.AddDays(i); row["User"] = i % 2 == 0 ? "amiralles" : "pipex"; tbl.Rows.Add(row); } var red = tbl.Reduce("Price >= 5"); assert.Equal(5, red.Rows.Count); red = tbl.Reduce("Price >= 5 or Price = 2"); assert.Equal(6, red.Rows.Count); red = tbl.Reduce("Date = dat('15/05/2012')"); assert.Equal(1, red.Rows.Count); // Mix table values with local vars. var names = new [] { "usr" }; var locals = new object[] { "pipex" }; var fx = "User = usr and Date = dat('15/05/2012')"; red = tbl.Reduce(fx, names, locals); assert.Equal(1, red.Rows.Count); // Date Add red = tbl.Reduce("Date = dat('15/05/2012') + 1"); assert.Equal(1, red.Rows.Count); // Date Sub red = tbl.Reduce("Date = dat('15/05/2012') - 1"); assert.Equal(1, red.Rows.Count); }; } }
#pragma warning disable 414, 219 namespace Abacus.Test { using System; using System.Collections.Generic; using System.Data; using System.Reflection; using System.Linq.Expressions; using static Abacus.Utils; using static Abacus.Error; using static System.Linq.Expressions.Expression; using static Interpreter; using static System.Console; using static System.Convert; using static System.DateTime; using _ = System.Action<Contest.Core.Runner>; class ReduceFixture { //TODO: Add hook for client func calls. _ reduce_data_table = assert => { var tbl = new DataTable(); tbl.Columns.Add("Precio", typeof(double)); tbl.Columns.Add("Fecha", typeof(DateTime)); tbl.Columns.Add("Usuario", typeof(string)); var startDate = new DateTime(2012, 05, 14); for (int i = 0; i < 10; ++i) { var row = tbl.NewRow(); row["Precio"] = i; row["Fecha"] = startDate.AddDays(i); row["Usuario"] = i % 2 == 0 ? "amiralles" : "pipex"; tbl.Rows.Add(row); } var red = tbl.Reduce("Precio >= 5"); assert.Equal(5, red.Rows.Count); red = tbl.Reduce("Precio >= 5 or Precio = 2"); assert.Equal(6, red.Rows.Count); red = tbl.Reduce("Fecha = dat('15/05/2012')"); assert.Equal(1, red.Rows.Count); // Mix table values with local vars. var names = new [] {"usr"}; var locals = new object[] {"pipex"}; var fx = "Usuario = usr and Fecha = dat('15/05/2012')"; red = tbl.Reduce(fx, names, locals); assert.Equal(1, red.Rows.Count); // Date Add red = tbl.Reduce("Fecha = dat('15/05/2012') + 1"); assert.Equal(1, red.Rows.Count); // Date Sub red = tbl.Reduce("Fecha = dat('15/05/2012') - 1"); assert.Equal(1, red.Rows.Count); }; } }
mit
C#
bcac5548f07e02685855d8ea2d5e17b0882ed75f
add alternative influxdb config method
MetaG8/Metrics.NET,ntent-ad/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,etishor/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,Liwoj/Metrics.NET,huoxudong125/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,DeonHeyns/Metrics.NET,DeonHeyns/Metrics.NET,huoxudong125/Metrics.NET,mnadel/Metrics.NET,cvent/Metrics.NET,ntent-ad/Metrics.NET
Src/Metrics/Influxdb/InfluxdbConfigExtensions.cs
Src/Metrics/Influxdb/InfluxdbConfigExtensions.cs
using System; using Metrics.Influxdb; using Metrics.Reports; namespace Metrics { public static class InfluxdbConfigExtensions { public static MetricsReports WithInfluxDb(this MetricsReports reports, string host, int port, string user, string pass, string database, TimeSpan interval) { return reports.WithInfluxDb(new Uri(string.Format(@"http://{0}:{1}/db/{2}/series?u={3}&p={4}&time_precision=s", host, port, user, pass, database)), interval); } public static MetricsReports WithInfluxDb(this MetricsReports reports, Uri influxdbUri, TimeSpan interval) { return reports.WithReport(new InfluxdbReport(influxdbUri), interval); } } }
using System; using Metrics.Influxdb; using Metrics.Reports; namespace Metrics { public static class InfluxdbConfigExtensions { public static MetricsReports WithInfluxDb(this MetricsReports reports, Uri influxdbUri, TimeSpan interval) { return reports.WithReport(new InfluxdbReport(influxdbUri), interval); } } }
apache-2.0
C#
82c761b819ce2396180875d17c6f2e1e7be55c98
update S_PARTY_MEMBER_INFO
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TeraPacketParser/Messages/S_PARTY_MEMBER_INFO.cs
TeraPacketParser/Messages/S_PARTY_MEMBER_INFO.cs
using System; using System.Collections.Generic; using TeraDataLite; namespace TeraPacketParser.Messages { public class S_PARTY_MEMBER_INFO : ParsedMessage { public uint Id { get; } public List<GroupMemberData> Members { get; } public S_PARTY_MEMBER_INFO(TeraMessageReader reader) : base(reader) { var count = reader.ReadUInt16(); var offset = reader.ReadUInt16(); reader.Skip(2); reader.BaseStream.Position = offset - 4; Members = new List<GroupMemberData>(); for (var i = 0; i < count; i++) { var u = new GroupMemberData(); reader.Skip(2); var next = reader.ReadUInt16(); var nameOffset = reader.ReadUInt16(); u.PlayerId = reader.ReadUInt32(); u.Class = (Class)reader.ReadUInt16(); reader.Skip(4); u.Level = Convert.ToUInt32(reader.ReadUInt16()); reader.Skip(4); u.GuardId = reader.ReadUInt32(); u.SectionId = reader.ReadUInt32(); u.Order = Convert.ToInt32(reader.ReadInt16()); reader.Skip(2); u.IsLeader = reader.ReadBoolean(); if (u.IsLeader) Id = u.PlayerId; u.Online = reader.ReadBoolean(); reader.BaseStream.Position = nameOffset - 4; u.Name = reader.ReadTeraString(); Members.Add(u); if (next != 0) reader.BaseStream.Position = next - 4; } } } }
using System; using System.Collections.Generic; using TeraDataLite; namespace TeraPacketParser.Messages { public class S_PARTY_MEMBER_INFO : ParsedMessage { public uint Id { get; } public List<GroupMemberData> Members { get; } public S_PARTY_MEMBER_INFO(TeraMessageReader reader) : base(reader) { var count = reader.ReadUInt16(); var offset = reader.ReadUInt16(); reader.Skip(8); Id = reader.ReadUInt32(); reader.BaseStream.Position = offset - 4; Members = new List<GroupMemberData>(); for (var i = 0; i < count; i++) { var u = new GroupMemberData(); reader.Skip(2); // var current = reader.ReadUInt16(); var next = reader.ReadUInt16(); var nameOffset = reader.ReadUInt16(); u.PlayerId = reader.ReadUInt32(); u.Class = (Class)reader.ReadUInt16(); reader.Skip(2 + 2); u.Level = Convert.ToUInt32(reader.ReadUInt16()); reader.ReadBoolean(); reader.Skip(1); u.Order = Convert.ToInt32(reader.ReadInt16()); u.GuardId = reader.ReadUInt32(); u.SectionId = reader.ReadUInt32(); //u.Location = SessionManager.DB.GetSectionName(gId, aId); u.IsLeader = reader.ReadBoolean(); //u.Laurel = (Laurel)reader.ReadUInt32(); //Console.WriteLine("---"); u.Online = reader.ReadBoolean(); //Console.WriteLine(reader.ReadByte()); //Console.WriteLine(reader.ReadByte()); reader.BaseStream.Position = nameOffset - 4; u.Name = reader.ReadTeraString(); //u.IsLeader = u.PlayerId == Id; Members.Add(u); if (next != 0) reader.BaseStream.Position = next - 4; } } } }
mit
C#
6b7007e6b716bf0cf3a16a9242ac1a0945630360
Change app description.
da2x/EdgeDeflector
EdgeDeflector/Properties/AssemblyInfo.cs
EdgeDeflector/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("EdgeDeflector")] [assembly: AssemblyDescription("Open MICROSOFT-EDGE:// links in your default web browser.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EdgeDeflector")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("64e191bc-e8ce-4190-939e-c77a75aa0e28")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Maintenance Number // Build Number // // 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.3.0")] [assembly: AssemblyFileVersion("1.1.3.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("EdgeDeflector")] [assembly: AssemblyDescription("Rewrites microsoft-edge URI addresses into standard http URI addresses.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EdgeDeflector")] [assembly: AssemblyCopyright("Copyright © 2021")] [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("64e191bc-e8ce-4190-939e-c77a75aa0e28")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Maintenance Number // Build Number // // 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.3.0")] [assembly: AssemblyFileVersion("1.1.3.0")]
mit
C#
ab2c969122e78f4a9f3d2c87d4463fff89f88c83
Add private channel types
UselessToucan/osu,DrabWeb/osu,naoey/osu,peppy/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu,ZLima12/osu,smoogipoo/osu,2yangk23/osu,NeoAdonis/osu,EVAST9919/osu,ppy/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,naoey/osu,johnneijzen/osu,peppy/osu-new,2yangk23/osu,naoey/osu,UselessToucan/osu,ZLima12/osu,peppy/osu,NeoAdonis/osu,EVAST9919/osu,UselessToucan/osu,smoogipooo/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu
osu.Game/Online/Chat/ChannelType.cs
osu.Game/Online/Chat/ChannelType.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Online.Chat { public enum ChannelType { Public, Private, Multiplayer, Spectator, Temporary, PM, Group, } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE namespace osu.Game.Online.Chat { public enum ChannelType { Public, Multiplayer, Spectator, Temporary, PM, Group, } }
mit
C#
1b2b42bb8a7cc2d3b510ef9d45ef075187b832c0
Update `CountryStatistics` to use `code` for country enum
peppy/osu,ppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game/Users/CountryStatistics.cs
osu.Game/Users/CountryStatistics.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. #nullable disable using Newtonsoft.Json; namespace osu.Game.Users { public class CountryStatistics { [JsonProperty(@"code")] public Country Country; [JsonProperty(@"active_users")] public long ActiveUsers; [JsonProperty(@"play_count")] public long PlayCount; [JsonProperty(@"ranked_score")] public long RankedScore; [JsonProperty(@"performance")] public long Performance; } }
// 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 Newtonsoft.Json; namespace osu.Game.Users { public class CountryStatistics { [JsonProperty] public Country Country; [JsonProperty(@"code")] public string FlagName; [JsonProperty(@"active_users")] public long ActiveUsers; [JsonProperty(@"play_count")] public long PlayCount; [JsonProperty(@"ranked_score")] public long RankedScore; [JsonProperty(@"performance")] public long Performance; } }
mit
C#
303620e8d85f35df58b08b0048a3d5a8a49cc53d
Add more registrations for what uris should be ignored out of the box
pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype
src/Glimpse.Agent.Web/GlimpseAgentWebOptionsSetup.cs
src/Glimpse.Agent.Web/GlimpseAgentWebOptionsSetup.cs
using System; using Glimpse.Agent.Web.Options; using Microsoft.Framework.OptionsModel; namespace Glimpse.Agent.Web { public class GlimpseAgentWebOptionsSetup : ConfigureOptions<GlimpseAgentWebOptions> { public GlimpseAgentWebOptionsSetup() : base(ConfigureGlimpseAgentWebOptions) { Order = -1000; } public static void ConfigureGlimpseAgentWebOptions(GlimpseAgentWebOptions options) { // Set up IgnoredUris options.IgnoredUris.Add("^__browserLink//requestData"); options.IgnoredUris.Add("^//Glimpse"); options.IgnoredUris.Add("^favicon.ico"); } } }
using System; using Glimpse.Agent.Web.Options; using Microsoft.Framework.OptionsModel; namespace Glimpse.Agent.Web { public class GlimpseAgentWebOptionsSetup : ConfigureOptions<GlimpseAgentWebOptions> { public GlimpseAgentWebOptionsSetup() : base(ConfigureGlimpseAgentWebOptions) { Order = -1000; } public static void ConfigureGlimpseAgentWebOptions(GlimpseAgentWebOptions options) { // Set up IgnoredUris options.IgnoredUris.Add("__browserLink/requestData"); } } }
mit
C#
e8180ab153901844621d0877918dd918a43c9c73
Add ToString() method to message for better debugging
peppy/osu,peppy/osu,peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,ppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,smoogipooo/osu,ppy/osu,smoogipoo/osu
osu.Game/Online/Chat/Message.cs
osu.Game/Online/Chat/Message.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Users; namespace osu.Game.Online.Chat { public class Message : IComparable<Message>, IEquatable<Message> { [JsonProperty(@"message_id")] public readonly long? Id; [JsonProperty(@"channel_id")] public long ChannelId; [JsonProperty(@"is_action")] public bool IsAction; [JsonProperty(@"timestamp")] public DateTimeOffset Timestamp; [JsonProperty(@"content")] public string Content; [JsonProperty(@"sender")] public User Sender; [JsonConstructor] public Message() { } /// <summary> /// The text that is displayed in chat. /// </summary> public string DisplayContent { get; set; } /// <summary> /// The links found in this message. /// </summary> /// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks> public List<Link> Links; public Message(long? id) { Id = id; } public int CompareTo(Message other) { if (!Id.HasValue) return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp); if (!other.Id.HasValue) return -1; return Id.Value.CompareTo(other.Id.Value); } public virtual bool Equals(Message other) => Id == other?.Id; // ReSharper disable once ImpureMethodCallOnReadonlyValueField public override int GetHashCode() => Id.GetHashCode(); public override string ToString() => $"[{ChannelId}] ({Id}) {Sender}: {Content}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Users; namespace osu.Game.Online.Chat { public class Message : IComparable<Message>, IEquatable<Message> { [JsonProperty(@"message_id")] public readonly long? Id; [JsonProperty(@"channel_id")] public long ChannelId; [JsonProperty(@"is_action")] public bool IsAction; [JsonProperty(@"timestamp")] public DateTimeOffset Timestamp; [JsonProperty(@"content")] public string Content; [JsonProperty(@"sender")] public User Sender; [JsonConstructor] public Message() { } /// <summary> /// The text that is displayed in chat. /// </summary> public string DisplayContent { get; set; } /// <summary> /// The links found in this message. /// </summary> /// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks> public List<Link> Links; public Message(long? id) { Id = id; } public int CompareTo(Message other) { if (!Id.HasValue) return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp); if (!other.Id.HasValue) return -1; return Id.Value.CompareTo(other.Id.Value); } public virtual bool Equals(Message other) => Id == other?.Id; // ReSharper disable once ImpureMethodCallOnReadonlyValueField public override int GetHashCode() => Id.GetHashCode(); } }
mit
C#
5874e71e043e8b8b4600aea4881657aac71d775a
Update IPointToString converter to use display Coordinate Type
Esri/visibility-addin-dotnet
source/ArcMapAddinVisibility/ArcMapAddinVisibility/ValueConverters/IPointToStringConverter.cs
source/ArcMapAddinVisibility/ArcMapAddinVisibility/ValueConverters/IPointToStringConverter.cs
// Copyright 2016 Esri // // 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.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using ESRI.ArcGIS.Geometry; namespace ArcMapAddinVisibility { [ValueConversion(typeof(IPoint), typeof(String))] public class IPointToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return "NA"; var point = value as IPoint; if (point == null) return "NA"; var result = string.Format("{0:0.0} {1:0.0}", point.Y, point.X); if (point.SpatialReference == null) return result; var cn = point as IConversionNotation; if (cn != null) { switch (ArcMapAddinVisibility.ViewModels.TabBaseViewModel.AddInConfig.DisplayCoordinateType) { case CoordinateTypes.DD: result = cn.GetDDFromCoords(6); break; case CoordinateTypes.DDM: result = cn.GetDDMFromCoords(4); break; case CoordinateTypes.DMS: result = cn.GetDMSFromCoords(2); break; case CoordinateTypes.GARS: result = cn.GetGARSFromCoords(); break; case CoordinateTypes.MGRS: result = cn.CreateMGRS(5, true, esriMGRSModeEnum.esriMGRSMode_Automatic); break; case CoordinateTypes.USNG: result = cn.GetUSNGFromCoords(5, true, true); break; case CoordinateTypes.UTM: result = cn.GetUTMFromCoords(esriUTMConversionOptionsEnum.esriUTMAddSpaces | esriUTMConversionOptionsEnum.esriUTMUseNS); break; default: break; } } return result; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
// Copyright 2016 Esri // // 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.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using ESRI.ArcGIS.Geometry; namespace ArcMapAddinVisibility { [ValueConversion(typeof(IPoint), typeof(String))] public class IPointToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) return "NA"; //TODO update with IConversionNotation var point = value as IPoint; return string.Format("{0:0.0#####} {1:0.0#####}", point.Y, point.X); } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
apache-2.0
C#
f53350a90d20ebace9bc7b86cba5b7db930f202f
Fix stuck locks
DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer
LmpClient/Harmony/KscVesselMarkers_SpawnVesselMarkers.cs
LmpClient/Harmony/KscVesselMarkers_SpawnVesselMarkers.cs
using Harmony; using KSP.UI.Screens; using LmpClient.Systems.Lock; using LmpClient.Systems.VesselRemoveSys; using LmpCommon.Enums; using System.Collections.Generic; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to hide the vessel markers from other controlled vessels in the KSC. /// This way we avoid that ppl click on the marker of a vessel that is being controlled by another person. /// </summary> [HarmonyPatch(typeof(KSCVesselMarkers))] [HarmonyPatch("SpawnVesselMarkers")] public class KscVesselMarkers_SpawnVesselMarkers { private static readonly List<KSCVesselMarker> MarkersToRemove = new List<KSCVesselMarker>(); [HarmonyPostfix] private static void PostfixVesselMarkers() { if (MainSystem.NetworkState < ClientState.Connected) return; MarkersToRemove.Clear(); var markers = Traverse.Create(KSCVesselMarkers.fetch).Field("markers").GetValue<List<KSCVesselMarker>>(); foreach (var marker in markers) { var vessel = Traverse.Create(marker).Field("v").GetValue<Vessel>(); if (LockSystem.LockQuery.ControlLockExists(vessel.id) || VesselRemoveSystem.Singleton.VesselWillBeKilled(vessel.id)) MarkersToRemove.Add(marker); } foreach (var marker in MarkersToRemove) { markers.Remove(marker); marker.Terminate(); } //HACK: Sometimes you can get a lock when holding the mouse over a marker. Here we clear them InputLockManager.ClearControlLocks(); } } }
using System.Collections.Generic; using Harmony; using KSP.UI.Screens; using LmpClient.Systems.Lock; using LmpClient.Systems.VesselRemoveSys; using LmpCommon.Enums; // ReSharper disable All namespace LmpClient.Harmony { /// <summary> /// This harmony patch is intended to hide the vessel markers from other controlled vessels in the KSC. /// This way we avoid that ppl click on the marker of a vessel that is being controlled by another person. /// </summary> [HarmonyPatch(typeof(KSCVesselMarkers))] [HarmonyPatch("SpawnVesselMarkers")] public class KscVesselMarkers_SpawnVesselMarkers { private static readonly List<KSCVesselMarker> MarkersToRemove = new List<KSCVesselMarker>(); [HarmonyPostfix] private static void PostfixVesselMarkers() { if (MainSystem.NetworkState < ClientState.Connected) return; MarkersToRemove.Clear(); var markers = Traverse.Create(KSCVesselMarkers.fetch).Field("markers").GetValue<List<KSCVesselMarker>>(); foreach (var marker in markers) { var vessel = Traverse.Create(marker).Field("v").GetValue<Vessel>(); if (LockSystem.LockQuery.ControlLockExists(vessel.id) || VesselRemoveSystem.Singleton.VesselWillBeKilled(vessel.id)) MarkersToRemove.Add(marker); } foreach (var marker in MarkersToRemove) { markers.Remove(marker); marker.Terminate(); } } } }
mit
C#
fadd76cc159d70c019e7337eb4d22fae3bcad826
Fix negative hue values
treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk,treehopper-electronics/treehopper-sdk
NET/API/Treehopper.Libraries/Utilities/ColorConverter.cs
NET/API/Treehopper.Libraries/Utilities/ColorConverter.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace Treehopper.Libraries.Utilities { public static class ColorConverter { /// <summary> /// Construct a color from HSL values /// </summary> /// <param name="hue">The hue, in degrees (0-360 mod)</param> /// <param name="saturation">The saturation percentage, from 0 to 100</param> /// <param name="luminance">The luminance percentage, from 0 to 100</param> /// <returns></returns> public static Color FromHsl(float hue, float saturation, float luminance) { while (hue < 0) hue += 360; var h = Math.Max((hue % 360) / 360.0f, 0); var s = saturation / 100.0f; var l = luminance / 100.0f; float r, g, b; if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1f / 3f); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1f / 3f); } return Color.FromArgb((int)Math.Round(r * 255), (int)Math.Round(g * 255), (int)Math.Round(b * 255)); } private static float hue2rgb(float p, float q, float t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1d / 6) return p + (q - p) * 6f * t; if (t < 1d / 2) return q; if (t < 2d / 3) return p + (q - p) * (2f / 3f - t) * 6f; return p; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace Treehopper.Libraries.Utilities { public static class ColorConverter { /// <summary> /// Construct a color from HSL values /// </summary> /// <param name="hue">The hue, in degrees (0-360 mod)</param> /// <param name="saturation">The saturation percentage, from 0 to 100</param> /// <param name="luminance">The luminance percentage, from 0 to 100</param> /// <returns></returns> public static Color FromHsl(float hue, float saturation, float luminance) { var h = Math.Max((hue % 360) / 360.0f, 0); var s = saturation / 100.0f; var l = luminance / 100.0f; float r, g, b; if (s == 0) { r = g = b = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; r = hue2rgb(p, q, h + 1f / 3f); g = hue2rgb(p, q, h); b = hue2rgb(p, q, h - 1f / 3f); } return Color.FromArgb((int)Math.Round(r * 255), (int)Math.Round(g * 255), (int)Math.Round(b * 255)); } private static float hue2rgb(float p, float q, float t) { if (t < 0) t += 1; if (t > 1) t -= 1; if (t < 1d / 6) return p + (q - p) * 6f * t; if (t < 1d / 2) return q; if (t < 2d / 3) return p + (q - p) * (2f / 3f - t) * 6f; return p; } } }
mit
C#
925747322283226f86fc4da28d3d7930fb9324ec
Enable multi-viewports by default
zwcloud/ImGui,zwcloud/ImGui,zwcloud/ImGui
src/ImGui/GUIConfiguration.cs
src/ImGui/GUIConfiguration.cs
namespace ImGui { internal class GUIConfiguration { // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. public ImGuiConfigFlags ConfigFlags = ImGuiConfigFlags.ViewportsEnable;// = 0 public ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. public bool ConfigWindowsMoveFromTitleBarOnly { get; set; } = false; } }
namespace ImGui { internal class GUIConfiguration { // See ImGuiConfigFlags_ enum. Set by user/application. Gamepad/keyboard navigation options, etc. public ImGuiConfigFlags ConfigFlags;// = 0 public ImGuiBackendFlags BackendFlags; // = 0 // See ImGuiBackendFlags_ enum. Set by backend (imgui_impl_xxx files or custom backend) to communicate features supported by the backend. public bool ConfigWindowsMoveFromTitleBarOnly { get; set; } = false; } }
agpl-3.0
C#
1ba7ea958073b8c90cb8bf9643926ebaa8bae233
Remove obsolete code (deserialization of generics via dynamics)
ctrlpprint/PivotSharp
src/PivotSharp/PivotConfig.cs
src/PivotSharp/PivotConfig.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; using PivotSharp.Aggregators; using PivotSharp.Filters; namespace PivotSharp { [JsonObject(MemberSerialization.OptIn)] public class PivotConfig { [JsonProperty] public IList<string> Rows { get; set; } [JsonProperty] public IList<string> Cols { get; set; } public Func<IAggregator> Aggregator { get; set; } [JsonProperty] protected string[] AggregatorName { get { if (Aggregator == null) return new string[]{}; var aggregator = Aggregator(); return new []{aggregator.SqlFunctionName, aggregator.ColumnName}; } set { if(value.Length < 2) throw new ArgumentException("Require at least one element"); Aggregator = FromString(value[0], value.Length > 1 ? value[1] : null); } } private Func<IAggregator> FromString(string name, string columnName) { switch (name) { case "Count": return () => new Count(); case "Sum": return () => new Sum(columnName); case "Ave": case "Avg": return () => new Ave(columnName); case "Min": return () => new Min(columnName); case "Max": return () => new Max(columnName); } throw new NotImplementedException(); } [JsonProperty] public bool FillTable { get; set; } [JsonProperty()] public IList<Filter> Filters { get; set; } public PivotConfig() { Rows = new List<string>(); Cols = new List<string>(); Filters = new List<Filter>(); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using PivotSharp.Aggregators; using PivotSharp.Filters; namespace PivotSharp { [JsonObject(MemberSerialization.OptIn)] public class PivotConfig { [JsonProperty] public IList<string> Rows { get; set; } [JsonProperty] public IList<string> Cols { get; set; } public Func<IAggregator> Aggregator { get; set; } [JsonProperty] protected string[] AggregatorName { get { if (Aggregator == null) return new string[]{}; var aggregator = Aggregator(); return new []{aggregator.SqlFunctionName, aggregator.ColumnName}; } set { if(value.Length < 2) throw new ArgumentException("Require at least one element"); Aggregator = FromString(value[0], value.Length > 1 ? value[1] : null); } } //protected dynamic[] FilterNames { // get { // var ret = new dynamic[Filters.Count]; // foreach (var filter in Filters) { // ret[Filters.IndexOf(filter)] = new { // Op = filter.Op, // Value = filter.ParameterValue, // FieldName = filter.FieldName // }; // } // return ret; // } // set { // Filters = new List<Filter>(); // foreach (var details in value) { // ((List<Filter>)Filters).Add(FromString(details)); // Cast to List to fix a dynamic binding issue: http://stackoverflow.com/questions/15920844/system-collections-generic-ilistobject-does-not-contain-a-definition-for-ad // } // } //} //private Filter FromString(dynamic details) { // return new Filter( // fieldName: details.FieldName.Value, // op: details. // ); // var type = details.ParameterValue.Value.GetType(); // if (details.Name == "Equals") { // var constructedClass = typeof (Equals<>).MakeGenericType(type); // return (Filter)Activator.CreateInstance(constructedClass, new object[]{ details.FieldName.Value, details.ParameterValue.Value}); // } // if (details.Name == "GreaterThan") { // var constructedClass = typeof(GreaterThan<>).MakeGenericType(type); // return (Filter)Activator.CreateInstance(constructedClass, new object[] { details.FieldName.Value, details.ParameterValue.Value }); // } // throw new NotImplementedException(); //} private Func<IAggregator> FromString(string name, string columnName) { switch (name) { case "Count": return () => new Count(); case "Sum": return () => new Sum(columnName); } throw new NotImplementedException(); } [JsonProperty] public bool FillTable { get; set; } [JsonProperty()] public IList<Filter> Filters { get; set; } public PivotConfig() { Rows = new List<string>(); Cols = new List<string>(); Filters = new List<Filter>(); } } }
mit
C#
047ae487d5e62783e6f0856b2939f1d45638d377
Increase thread pool min threads.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
tests/SideBySide/DatabaseFixture.cs
tests/SideBySide/DatabaseFixture.cs
using System; #if NETCOREAPP1_1_2 using System.Reflection; #endif using System.Threading; using MySql.Data.MySqlClient; namespace SideBySide { public class DatabaseFixture : IDisposable { public DatabaseFixture() { // increase the number of worker threads to reduce number of spurious failures from threadpool starvation #if NETCOREAPP1_1_2 // from https://stackoverflow.com/a/42982698 typeof(ThreadPool).GetMethod("SetMinThreads", BindingFlags.Public | BindingFlags.Static).Invoke(null, new object[] { 64, 64 }); #else ThreadPool.SetMinThreads(64, 64); #endif var csb = AppConfig.CreateConnectionStringBuilder(); var connectionString = csb.ConnectionString; var database = csb.Database; csb.Database = ""; using (var db = new MySqlConnection(csb.ConnectionString)) { db.Open(); using (var cmd = db.CreateCommand()) { cmd.CommandText = $"create schema if not exists {database};"; cmd.ExecuteNonQuery(); if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase)) { cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};"; cmd.ExecuteNonQuery(); } } db.Close(); } Connection = new MySqlConnection(connectionString); } public MySqlConnection Connection { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Connection.Dispose(); } } } }
using System; using MySql.Data.MySqlClient; namespace SideBySide { public class DatabaseFixture : IDisposable { public DatabaseFixture() { var csb = AppConfig.CreateConnectionStringBuilder(); var connectionString = csb.ConnectionString; var database = csb.Database; csb.Database = ""; using (var db = new MySqlConnection(csb.ConnectionString)) { db.Open(); using (var cmd = db.CreateCommand()) { cmd.CommandText = $"create schema if not exists {database};"; cmd.ExecuteNonQuery(); if (!string.IsNullOrEmpty(AppConfig.SecondaryDatabase)) { cmd.CommandText = $"create schema if not exists {AppConfig.SecondaryDatabase};"; cmd.ExecuteNonQuery(); } } db.Close(); } Connection = new MySqlConnection(connectionString); } public MySqlConnection Connection { get; } public void Dispose() { Dispose(true); } protected virtual void Dispose(bool disposing) { if (disposing) { Connection.Dispose(); } } } }
mit
C#
f0efa2806e6d7fda25c29c14c903009e28812684
Make test base class abstract
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
resharper/resharper-unity/test/src/CSharp/Daemon/Stages/Analysis/CSharpHighlightingTestBase.cs
resharper/resharper-unity/test/src/CSharp/Daemon/Stages/Analysis/CSharpHighlightingTestBase.cs
using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.FeaturesTestFramework.Daemon; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.Analysis { public abstract class CSharpHighlightingTestBase<T> : CSharpHighlightingTestBase { protected sealed override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile, IContextBoundSettingsStore settingsStore) { return highlighting is T; } } }
using JetBrains.Application.Settings; using JetBrains.ReSharper.Feature.Services.Daemon; using JetBrains.ReSharper.FeaturesTestFramework.Daemon; using JetBrains.ReSharper.Psi; namespace JetBrains.ReSharper.Plugins.Unity.Tests.CSharp.Daemon.Stages.Analysis { public class CSharpHighlightingTestBase<T> : CSharpHighlightingTestBase { protected sealed override bool HighlightingPredicate(IHighlighting highlighting, IPsiSourceFile sourceFile, IContextBoundSettingsStore settingsStore) { return highlighting is T; } } }
apache-2.0
C#
d729c0008923d827ae959b2767f12d3e9610640f
fix dokan version parsing
fedorg/win-sshfs,fedorg/win-sshfs
Sshfs/Sshfs/AboutForm.cs
Sshfs/Sshfs/AboutForm.cs
using System; using System.Diagnostics; using System.Drawing; using System.Reflection; using System.Windows.Forms; using Renci.SshNet; namespace Sshfs { public partial class AboutForm : Form { private static readonly string _sshfsText = String.Format("Sshfs {0}", Assembly.GetEntryAssembly().GetName().Version); private static readonly string _dokanText = (DokanNet.Dokan.Version < 600) ? String.Format("Dokan {0}.{1}.{2}", DokanNet.Dokan.Version / 100, (DokanNet.Dokan.Version % 100) / 10, DokanNet.Dokan.Version % 10) : String.Format("Dokan {0}.{1}.{2}.{3}", DokanNet.Dokan.Version / 1000, (DokanNet.Dokan.Version % 1000) / 100, (DokanNet.Dokan.Version % 100) / 10, DokanNet.Dokan.Version % 10); private static readonly string _sshnetText = String.Format("SSH.NET {0}", Assembly.GetAssembly(typeof (SshClient)).GetName().Version); public AboutForm() { InitializeComponent(); label1.Text = _sshfsText; label2.Text = _dokanText; label3.Text = _sshnetText; } private void ok_Click(object sender, EventArgs e) { this.Close(); } private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(String.Format("http:\\{0}", (sender as LinkLabel).Text)); } private void panel1_Paint(object sender, PaintEventArgs e) { // ControlPaint.DrawBorder3D(e.Graphics,0,0,panel1.Width,panel1.Height,Border3DStyle.); e.Graphics.DrawLine(new Pen(SystemColors.ActiveBorder,3), 0, panel1.Height, panel1.Width, panel1.Height); // ControlPaint.DrawBorder(e.Graphics, new Rectangle(0, panel1.Height-1, panel1.Width, panel1.Height-1), SystemColors.ActiveBorder, ButtonBorderStyle.Dashed); } } }
using System; using System.Diagnostics; using System.Drawing; using System.Reflection; using System.Windows.Forms; using Renci.SshNet; namespace Sshfs { public partial class AboutForm : Form { private static readonly string _sshfsText = String.Format("Sshfs {0}", Assembly.GetEntryAssembly().GetName().Version); private static readonly string _dokanText = String.Format("Dokan {0}.{1}.{2}.{3}",DokanNet.Dokan.Version / 1000, (DokanNet.Dokan.Version%1000) / 100, (DokanNet.Dokan.Version%100) / 10, DokanNet.Dokan.Version % 10); private static readonly string _sshnetText = String.Format("SSH.NET {0}", Assembly.GetAssembly(typeof (SshClient)).GetName().Version); public AboutForm() { InitializeComponent(); label1.Text = _sshfsText; label2.Text = _dokanText; label3.Text = _sshnetText; } private void ok_Click(object sender, EventArgs e) { this.Close(); } private void linkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { Process.Start(String.Format("http:\\{0}", (sender as LinkLabel).Text)); } private void panel1_Paint(object sender, PaintEventArgs e) { // ControlPaint.DrawBorder3D(e.Graphics,0,0,panel1.Width,panel1.Height,Border3DStyle.); e.Graphics.DrawLine(new Pen(SystemColors.ActiveBorder,3), 0, panel1.Height, panel1.Width, panel1.Height); // ControlPaint.DrawBorder(e.Graphics, new Rectangle(0, panel1.Height-1, panel1.Width, panel1.Height-1), SystemColors.ActiveBorder, ButtonBorderStyle.Dashed); } } }
bsd-3-clause
C#
6988d71bbb28696cb2e251a15de4c01be4021ef1
fix errors
taka-oyama/UniHttp
Assets/UniHttp/Support/Debug/Logger.cs
Assets/UniHttp/Support/Debug/Logger.cs
using UnityEngine; namespace UniHttp { public class Logger { public enum Level { Debug, Info, Warning, Error, Exception } public static Level LogLevel = Level.Info; public static ILogger logger = UnityEngine.Debug.logger; static string kTAG = "UniHttp"; #region Debug public static void Debug(object message) { logger.Log(kTAG, message); } public static void Debug(object message, Object context) { logger.Log(kTAG, message, context); } public static void DebugFormat(string format, params object[] objects) { logger.Log(kTAG, string.Format(format, objects)); } public static void DebugFormat(Object context, string format, params object[] objects) { logger.Log(kTAG, string.Format(format, objects), context); } #endregion #region Info public static void Info(object message) { logger.Log(kTAG, message); } public static void Info(object message, Object context) { logger.Log(kTAG, message, context); } public static void InfoFormat(string format, params object[] objects) { logger.Log(kTAG, string.Format(format, objects)); } public static void InfoFormat(Object context, string format, params object[] objects) { logger.Log(kTAG, string.Format(format, objects), context); } #endregion #region Warning public static void Warning(object message) { logger.LogWarning(kTAG, message); } public static void Warning(object message, Object context) { logger.LogWarning(kTAG, message, context); } public static void WarningFormat(string format, params object[] objects) { logger.LogWarning(kTAG, string.Format(format, objects)); } public static void WarningFormat(Object context, string format, params object[] objects) { logger.LogWarning(kTAG, string.Format(format, objects), context); } #endregion #region Error public static void Error(object message) { logger.LogError(kTAG, message); } public static void Error(object message, Object context) { logger.LogError(kTAG, message, context); } public static void ErrorFormat(string format, params object[] objects) { logger.LogError(kTAG, string.Format(format, objects)); } public static void ErrorFormat(Object context, string format, params object[] objects) { logger.LogError(kTAG, string.Format(format, objects), context); } #endregion #region Exception public static void Exception(System.Exception exception) { logger.LogException(exception); } public static void Exception(System.Exception exception, Object context) { logger.LogException(exception, context); } #endregion } }
using UnityEngine; namespace UniHttp { public class Logger { public enum Level { Debug, Info, Warning, Error, Exception } public static Level LogLevel = LogLevel.Info; public static UnityEngine.Logger logger = UnityEngine.Debug.logger; static string kTAG = "UniHttp"; #region Debug public static void Debug(object message) { logger.Log(kTAG, message); } public static void Debug(object message, Object context) { logger.Log(kTAG, message, context); } public static void DebugFormat(string format, params object objects) { logger.Log(kTAG, string.Format(format, objects)); } public static void DebugFormat(Object context, string format, params object objects) { logger.Log(kTAG, string.Format(format, objects), context); } #endregion #region Info public static void Info(object message) { logger.Log(kTAG, message); } public static void Info(object message, Object context) { logger.Log(kTAG, message, context); } public static void InfoFormat(string format, params object objects) { logger.Log(kTAG, string.Format(format, objects)); } public static void InfoFormat(Object context, string format, params object objects) { logger.Log(kTAG, string.Format(format, objects), context); } #endregion #region Warning public static void Warning(object message) { logger.LogWarning(kTAG, message); } public static void Warning(object message, Object context) { logger.LogWarning(kTAG, message, context); } public static void WarningFormat(string format, params object objects) { logger.LogWarning(kTAG, string.Format(format, objects)); } public static void WarningFormat(Object context, string format, params object objects) { logger.LogWarning(kTAG, string.Format(format, objects), context); } #endregion #region Error public static void Error(object message) { logger.LogError(kTAG, message); } public static void Error(object message, Object context) { logger.LogError(kTAG, message, context); } public static void ErrorFormat(string format, params object objects) { logger.LogError(kTAG, string.Format(format, objects)); } public static void ErrorFormat(Object context, string format, params object objects) { logger.LogError(kTAG, string.Format(format, objects), context); } #endregion #region Exception public static void Exception(object message) { logger.LogException(kTAG, message); } public static void Exception(object message, Object context) { logger.LogException(kTAG, message, context); } public static void ExceptionFormat(string format, params object objects) { logger.LogException(kTAG, string.Format(format, objects)); } public static void ExceptionFormat(Object context, string format, params object objects) { logger.LogException(kTAG, string.Format(format, objects), context); } #endregion } }
mit
C#
6224213e887fe83855f0b25ce026ab9822aa3b2d
Add Serializable attribute
ashfordl/cards
CardGames/TooManyPlayersException.cs
CardGames/TooManyPlayersException.cs
// TooManyPlayersException.cs // <copyright file="TooManyPlayersException.cs"> This code is protected under the MIT License. </copyright> using System; namespace CardGames { /// <summary> /// An exception raised when TooManyPlayers are added to a game. /// </summary> [Serializable] public class TooManyPlayersException : Exception { /// <summary> /// Initializes a new instance of the <see cref="TooManyPlayersException" /> class. /// </summary> public TooManyPlayersException() { } /// <summary> /// Initializes a new instance of the <see cref="TooManyPlayersException" /> class. /// </summary> /// <param name="message"> The message to explain the exception. </param> public TooManyPlayersException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="TooManyPlayersException" /> class. /// </summary> /// <param name="message"> The message to explain the exception. </param> /// <param name="inner"> The exception that caused the TooManyPlayersException. </param> public TooManyPlayersException(string message, Exception inner) : base(message, inner) { } } }
// TooManyPlayersException.cs // <copyright file="TooManyPlayersException.cs"> This code is protected under the MIT License. </copyright> using System; namespace CardGames { /// <summary> /// An exception raised when TooManyPlayers are added to a game. /// </summary> public class TooManyPlayersException : Exception { /// <summary> /// Initializes a new instance of the <see cref="TooManyPlayersException" /> class. /// </summary> public TooManyPlayersException() { } /// <summary> /// Initializes a new instance of the <see cref="TooManyPlayersException" /> class. /// </summary> /// <param name="message"> The message to explain the exception. </param> public TooManyPlayersException(string message) : base(message) { } /// <summary> /// Initializes a new instance of the <see cref="TooManyPlayersException" /> class. /// </summary> /// <param name="message"> The message to explain the exception. </param> /// <param name="inner"> The exception that caused the TooManyPlayersException. </param> public TooManyPlayersException(string message, Exception inner) : base(message, inner) { } } }
mit
C#
d1011d27bab4ddffc63513b2d87cf776042d4f04
Add actual winnitron mappings.
thinkrad/WinnitronLauncher
Assets/Scripts/View/PlaylistNavigationManager.cs
Assets/Scripts/View/PlaylistNavigationManager.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlaylistNavigationManager : Singleton<PlaylistNavigationManager> { float GRID_Y_OFFSET = 60; List<Game> playlist; int currentGameIndex = 0; public UILabel gameLabelPrefab; Coroutine<_> moveThroughList; UIGrid titleGrid; void Start() { playlist = GameRepository.Instance.games; titleGrid = GetComponentInChildren<UIGrid>(); CreateLabels(); } void CreateLabels() { foreach (var game in playlist) { var label = Instantiate(gameLabelPrefab) as UILabel; label.text = game.name; label.transform.parent = titleGrid.transform; label.transform.localScale = new Vector3(1,1,1); } } void Update() { if(Input.GetKeyDown(KeyCode.UpArrow) || Input.GetKeyDown (KeyCode.I)) Move(-1); else if(Input.GetKeyDown(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.K)) Move(1); if (Input.GetKeyDown(KeyCode.Z) || Input.GetKeyDown(KeyCode.X) || Input.GetKeyDown(KeyCode.N) || Input.GetKeyDown(KeyCode.M)) { Runner.Instance.Run(playlist[currentGameIndex]); } } void Move(int direction) { if (moveThroughList == null && (currentGameIndex + direction >= 0) && (currentGameIndex + direction < playlist.Count)) { int nextGameIndex = Maths.Mod((currentGameIndex + direction), playlist.Count); ScreenshotDisplayManager.Instance.LoadScreenshot(playlist[nextGameIndex].screenshot); var startY = titleGrid.transform.localPosition.y; moveThroughList = StartCoroutine<_>(Coroutines.OverTime(ScreenshotDisplayManager.Instance.CROSSFADE_TIME, Funcs.Identity, t => { var lp = titleGrid.transform.localPosition; titleGrid.transform.localPosition = new Vector3(lp.x, Mathf.SmoothStep(startY, startY + direction * GRID_Y_OFFSET, t), lp.z); if (t == 1) { currentGameIndex = Maths.Mod(currentGameIndex + direction, playlist.Count); moveThroughList = null; } })); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class PlaylistNavigationManager : Singleton<PlaylistNavigationManager> { float GRID_Y_OFFSET = 60; List<Game> playlist; int currentGameIndex = 0; public UILabel gameLabelPrefab; Coroutine<_> moveThroughList; UIGrid titleGrid; void Start() { playlist = GameRepository.Instance.games; titleGrid = GetComponentInChildren<UIGrid>(); CreateLabels(); } void CreateLabels() { foreach (var game in playlist) { var label = Instantiate(gameLabelPrefab) as UILabel; label.text = game.name; label.transform.parent = titleGrid.transform; label.transform.localScale = new Vector3(1,1,1); } } void Update() { if(Input.GetKeyDown(KeyCode.UpArrow)) Move(-1); else if(Input.GetKeyDown(KeyCode.DownArrow)) Move(1); if (Input.GetKeyDown(KeyCode.Return)) { Runner.Instance.Run(playlist[currentGameIndex]); } } void Move(int direction) { if (moveThroughList == null && (currentGameIndex + direction >= 0) && (currentGameIndex + direction < playlist.Count)) { int nextGameIndex = Maths.Mod((currentGameIndex + direction), playlist.Count); ScreenshotDisplayManager.Instance.LoadScreenshot(playlist[nextGameIndex].screenshot); var startY = titleGrid.transform.localPosition.y; moveThroughList = StartCoroutine<_>(Coroutines.OverTime(ScreenshotDisplayManager.Instance.CROSSFADE_TIME, Funcs.Identity, t => { var lp = titleGrid.transform.localPosition; titleGrid.transform.localPosition = new Vector3(lp.x, Mathf.SmoothStep(startY, startY + direction * GRID_Y_OFFSET, t), lp.z); if (t == 1) { currentGameIndex = Maths.Mod(currentGameIndex + direction, playlist.Count); moveThroughList = null; } })); } } }
mit
C#
1edc11c10ec72e16fcff2a0e5ef9a958ef20ecde
use GLKeyPressEventHandler instead.
bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL
CSharpGL/GLCanvas/IGLCanvas.cs
CSharpGL/GLCanvas/IGLCanvas.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CSharpGL { /// <summary> /// /// </summary> public interface IGLCanvas { /// <summary> /// /// </summary> int Width { get; set; } /// <summary> /// /// </summary> int Height { get; set; } /// <summary> /// /// </summary> Rectangle ClientRectangle { get; } /// <summary> /// /// </summary> void Repaint(); /// <summary> /// /// </summary> GLRenderContext RenderContext { get; } // TODO: use GLKeyPressEventHandler instead. /// <summary> /// /// </summary> event KeyPressEventHandler KeyPress; /// <summary> /// /// </summary> event MouseEventHandler MouseDown; /// <summary> /// /// </summary> event MouseEventHandler MouseMove; /// <summary> /// /// </summary> event MouseEventHandler MouseUp; /// <summary> /// /// </summary> event MouseEventHandler MouseWheel; /// <summary> /// /// </summary> event KeyEventHandler KeyDown; /// <summary> /// /// </summary> event KeyEventHandler KeyUp; /// <summary> /// /// </summary> event EventHandler Resize; /// <summary> /// /// </summary> bool IsDisposed { get; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace CSharpGL { /// <summary> /// /// </summary> public interface IGLCanvas { /// <summary> /// /// </summary> int Width { get; set; } /// <summary> /// /// </summary> int Height { get; set; } /// <summary> /// /// </summary> Rectangle ClientRectangle { get; } /// <summary> /// /// </summary> void Repaint(); /// <summary> /// /// </summary> GLRenderContext RenderContext { get; } /// <summary> /// /// </summary> event KeyPressEventHandler KeyPress; /// <summary> /// /// </summary> event MouseEventHandler MouseDown; /// <summary> /// /// </summary> event MouseEventHandler MouseMove; /// <summary> /// /// </summary> event MouseEventHandler MouseUp; /// <summary> /// /// </summary> event MouseEventHandler MouseWheel; /// <summary> /// /// </summary> event KeyEventHandler KeyDown; /// <summary> /// /// </summary> event KeyEventHandler KeyUp; /// <summary> /// /// </summary> event EventHandler Resize; /// <summary> /// /// </summary> bool IsDisposed { get; } } }
mit
C#
f2b8a57f0252edba4fa3344d1e81625bea198cac
Define Persona at client start
ermau/Tempest.Social
Desktop/Tempest.Social/SocialClient.cs
Desktop/Tempest.Social/SocialClient.cs
// // SocialClient.cs // // Author: // Eric Maupin <me@ermau.com> // // Copyright (c) 2012 Eric Maupin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Net; using System.Threading.Tasks; namespace Tempest.Social { public class SocialClient : LocalClient { public SocialClient (IClientConnection connection, Person persona) : base (connection, MessageTypes.Reliable) { if (persona == null) throw new ArgumentNullException ("persona"); this.watchList = new WatchList (this); this.RegisterMessageHandler<RequestBuddyListMessage> (OnRequestBuddyListMessage); this.persona = persona; } /// <summary> /// The server has requested that you send your buddy list in full. /// </summary> /// <remarks> /// <para>For simple match making servers that do not have a storage mechanism, /// it is necessary for the client to persist its own buddy list and resend /// it to the server on each connection.</para> /// <para>This event is also an indication that you should record your buddy list /// locally.</para> /// </remarks> public event EventHandler BuddyListRequested; public Person Persona { get { return this.persona; } } public WatchList WatchList { get { return this.watchList; } } public Task<EndPoint> RequestEndPointAsync (string identity) { if (identity == null) throw new ArgumentNullException ("identity"); return Connection.SendFor<EndPointResultMessage> (new EndPointRequestMessage { Identity = identity }) .ContinueWith (t => t.Result.EndPoint); } private readonly WatchList watchList; private readonly Person persona; private void OnRequestBuddyListMessage (MessageEventArgs<RequestBuddyListMessage> e) { OnBuddyListRequested(); } private void OnBuddyListRequested () { var handler = BuddyListRequested; if (handler != null) handler (this, EventArgs.Empty); } } }
// // SocialClient.cs // // Author: // Eric Maupin <me@ermau.com> // // Copyright (c) 2012 Eric Maupin // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Net; using System.Threading.Tasks; namespace Tempest.Social { public class SocialClient : LocalClient { public SocialClient (IClientConnection connection) : base (connection, MessageTypes.Reliable) { this.watchList = new WatchList (this); this.RegisterMessageHandler<RequestBuddyListMessage> (OnRequestBuddyListMessage); } /// <summary> /// The server has requested that you send your buddy list in full. /// </summary> /// <remarks> /// For simple match making servers that do not have a storage mechanism, /// it is necessary for the client to persist its own buddy list and resend /// it to the server on each connection. /// </remarks> public event EventHandler BuddyListRequested; public WatchList WatchList { get { return this.watchList; } } public Task<EndPoint> RequestEndPointAsync (string identity) { if (identity == null) throw new ArgumentNullException ("identity"); return Connection.SendFor<EndPointResultMessage> (new EndPointRequestMessage { Identity = identity }) .ContinueWith (t => t.Result.EndPoint); } private readonly WatchList watchList; private void OnRequestBuddyListMessage (MessageEventArgs<RequestBuddyListMessage> e) { OnBuddyListRequested(); } private void OnBuddyListRequested () { var handler = BuddyListRequested; if (handler != null) handler (this, EventArgs.Empty); } } }
mit
C#
f63f48b443abfed2319371cee17ce638451627a9
Update Program.cs
chemadvisor/chemapi_csharp_example
ConsoleClient/Program.cs
ConsoleClient/Program.cs
/* * Copyright (c) 2017 ChemADVISOR, Inc. All rights reserved. * Licensed under The MIT License (MIT) * https://opensource.org/licenses/MIT */ using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace ConsoleClient { internal class Program { public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult(); private static async Task MainAsync() { // set base address var baseAddress = "https://sandbox.chemadvisor.io/chem/rest/v2/"; // set app_key header var appKey = "your_app_key"; // set app_id header var appId = "your_app_id"; // set accept header: "application/xml", "application/json" var acceptHeader = "application/json"; // set resource var resource = "regulatory_lists"; // set query parameters: q, limit, offset var q = Uri.EscapeUriString("{\"tags.tag.name\":\"Government Inventory Lists\"}"); var limit = 10; var offset = 0; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); client.DefaultRequestHeaders.Add("app_key", appKey); client.DefaultRequestHeaders.Add("app_id", appId); var response = await client.GetAsync(string.Format("{0}?q={1}&limit={2}&offset={3}", resource, q, limit, offset)); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } else { Console.WriteLine(response.StatusCode); } Console.ReadLine(); } } }
/* * Copyright (c) 2017 ChemADVISOR, Inc. All rights reserved. * Licensed under The MIT License (MIT) * https://opensource.org/licenses/MIT */ using System; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace ConsoleClient { internal class Program { public static void Main(string[] args) => MainAsync().GetAwaiter().GetResult(); private static async Task MainAsync() { // set base address var baseAddress = "https://sandbox.chemadvisor.io/chem/rest/v2/"; // set user_key header var userKey = "your_user_key"; // set accept header: "application/xml", "application/json" var acceptHeader = "application/json"; // set api var resource = "regulatory_lists"; // set query parameters: q, limit, offset var q = Uri.EscapeUriString("{\"tags.tag.name\":\"Government Inventory Lists\"}"); var limit = 10; var offset = 0; HttpClient client = new HttpClient(); client.BaseAddress = new Uri(baseAddress); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptHeader)); client.DefaultRequestHeaders.Add("user_key", userKey); var response = await client.GetAsync(string.Format("{0}?q={1}&limit={2}&offset={3}", resource, q, limit, offset)); if (response.IsSuccessStatusCode) { Console.WriteLine(await response.Content.ReadAsStringAsync()); } else { Console.WriteLine(response.StatusCode); } Console.ReadLine(); } } }
mit
C#
e9a52637d5614c6ba6453cc5afec4360d408a2c2
Remove "Folder Watcher" widget "Replace Existing File" option
danielchalmers/DesktopWidgets
DesktopWidgets/Widgets/FolderWatcher/Settings.cs
DesktopWidgets/Widgets/FolderWatcher/Settings.cs
using System; using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.FolderWatcher { public class Settings : WidgetSettingsBase, IEventWidget { [Category("General")] [DisplayName("Folder Check Interval")] public TimeSpan FolderCheckInterval { get; set; } = TimeSpan.FromMilliseconds(500); [Category("General")] [DisplayName("Folder To Watch")] public string WatchFolder { get; set; } = ""; [Category("General")] [DisplayName("Include Filter")] public string IncludeFilter { get; set; } = "*.*"; [Category("General")] [DisplayName("Exclude Filter")] public string ExcludeFilter { get; set; } = ""; [Category("Style")] [DisplayName("Show File Name")] public bool ShowFileName { get; set; } = true; [Category("Style")] [DisplayName("Show Mute")] public bool ShowMute { get; set; } = true; [Category("Style")] [DisplayName("Show Dismiss")] public bool ShowDismiss { get; set; } = true; [DisplayName("Mute End Time")] public DateTime MuteEndTime { get; set; } = DateTime.Now; [DisplayName("Mute Duration")] public TimeSpan MuteDuration { get; set; } = TimeSpan.FromHours(1); [Category("General")] [DisplayName("Timeout Duration")] public TimeSpan TimeoutDuration { get; set; } = TimeSpan.FromMinutes(1); [DisplayName("Last File Check")] public DateTime LastCheck { get; set; } = DateTime.Now; [Category("General")] [DisplayName("Enable Timeout")] public bool EnableTimeout { get; set; } = false; [Category("Behavior (Hideable)")] [DisplayName("Open On Event")] public bool OpenOnEvent { get; set; } = true; [Category("Behavior (Hideable)")] [DisplayName("Stay Open On Event")] public bool OpenOnEventStay { get; set; } = false; [Category("Behavior (Hideable)")] [DisplayName("Open On Event Duration")] public TimeSpan OpenOnEventDuration { get; set; } = TimeSpan.FromSeconds(10); } }
using System; using System.ComponentModel; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.FolderWatcher { public class Settings : WidgetSettingsBase, IEventWidget { [Category("General")] [DisplayName("Folder Check Interval")] public TimeSpan FolderCheckInterval { get; set; } = TimeSpan.FromMilliseconds(500); [Category("General")] [DisplayName("Folder To Watch")] public string WatchFolder { get; set; } = ""; [Category("General")] [DisplayName("Include Filter")] public string IncludeFilter { get; set; } = "*.*"; [Category("General")] [DisplayName("Exclude Filter")] public string ExcludeFilter { get; set; } = ""; [Category("Style")] [DisplayName("Show File Name")] public bool ShowFileName { get; set; } = true; [Category("Style")] [DisplayName("Show Mute")] public bool ShowMute { get; set; } = true; [Category("Style")] [DisplayName("Show Dismiss")] public bool ShowDismiss { get; set; } = true; [Category("Style")] [DisplayName("Replace Existing File")] public bool NotificationReplaceExisting { get; set; } = false; [DisplayName("Mute End Time")] public DateTime MuteEndTime { get; set; } = DateTime.Now; [DisplayName("Mute Duration")] public TimeSpan MuteDuration { get; set; } = TimeSpan.FromHours(1); [Category("General")] [DisplayName("Timeout Duration")] public TimeSpan TimeoutDuration { get; set; } = TimeSpan.FromMinutes(1); [DisplayName("Last File Check")] public DateTime LastCheck { get; set; } = DateTime.Now; [Category("General")] [DisplayName("Enable Timeout")] public bool EnableTimeout { get; set; } = false; [Category("Behavior (Hideable)")] [DisplayName("Open On Event")] public bool OpenOnEvent { get; set; } = true; [Category("Behavior (Hideable)")] [DisplayName("Stay Open On Event")] public bool OpenOnEventStay { get; set; } = false; [Category("Behavior (Hideable)")] [DisplayName("Open On Event Duration")] public TimeSpan OpenOnEventDuration { get; set; } = TimeSpan.FromSeconds(10); } }
apache-2.0
C#
9bc24b769fe4a7657389c2b069bc51580b86a66c
Update GoogleAuthenticationSettings.Edit.cshtml
xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,petedavis/Orchard2,petedavis/Orchard2,xkproject/Orchard2
src/OrchardCore.Modules/OrchardCore.Google/Views/GoogleAuthenticationSettings.Edit.cshtml
src/OrchardCore.Modules/OrchardCore.Google/Views/GoogleAuthenticationSettings.Edit.cshtml
@using OrchardCore.Google.Authentication.ViewModels; @model GoogleAuthenticationSettingsViewModel; <p class="alert alert-warning">@T["The current tenant will be reloaded when the settings are saved."]</p> <h3>@T["Google Authentication Settings"]</h3> <div class="form-group row" asp-validation-class-for="ClientID"> <div class="col-lg"> <label asp-for="ClientID">@T["Client ID"]</label> <input asp-for="ClientID" class="form-control" autocomplete="off" /> <span asp-validation-for="ClientID"></span> <span class="hint">@T["The client id defined in Google API console for the application."]</span> </div> </div> <div class="form-group row" asp-validation-class-for="ClientSecret"> <div class="col-lg"> <label asp-for="ClientSecret">@T["API secret key"]</label> <input asp-for="ClientSecret" class="form-control" type="password" value="@Model.ClientSecret" autocomplete="off" /> <span asp-validation-for="ClientSecret"></span> <span class="hint">@T["The client secret defined in Google API console for the application."]</span> </div> </div> <div class="form-group row" asp-validation-class-for="CallbackPath"> <div class="col-lg"> <label asp-for="CallbackPath">@T["CallbackPath"]</label> <input asp-for="CallbackPath" class="form-control" placeholder="/signin-google" /> <span asp-validation-for="CallbackPath"></span> <span class="hint">@T["The request path within the application's base path where the user-agent will be returned. The middleware will process this request when it arrives."]</span> </div> </div>
@using OrchardCore.Google.Authentication.ViewModels; @model GoogleAuthenticationSettingsViewModel; <p class="alert alert-warning">@T["The current tenant will be reloaded when the settings are saved."]</p> <h3>@T["Google Authentication Settings"]</h3> <div class="form-group row" asp-validation-class-for="ClientID"> <div class="col-lg"> <label asp-for="ClientID">@T["Client ID"]</label> <input asp-for="ClientID" class="form-control" autocomplete="off" /> <span asp-validation-for="ClientSecret"></span> <span class="hint">@T["The client id defined in Google API console for the application."]</span> </div> </div> <div class="form-group row" asp-validation-class-for="ClientSecret"> <div class="col-lg"> <label asp-for="ClientSecret">@T["API secret key"]</label> <input asp-for="ClientSecret" class="form-control" type="password" value="@Model.ClientSecret" autocomplete="off" /> <span asp-validation-for="ClientSecret"></span> <span class="hint">@T["The client secret defined in Google API console for the application."]</span> </div> </div> <div class="form-group row" asp-validation-class-for="CallbackPath"> <div class="col-lg"> <label asp-for="CallbackPath">@T["CallbackPath"]</label> <input asp-for="CallbackPath" class="form-control" placeholder="/signin-google" /> <span asp-validation-for="CallbackPath"></span> <span class="hint">@T["The request path within the application's base path where the user-agent will be returned. The middleware will process this request when it arrives."]</span> </div> </div>
bsd-3-clause
C#
842b1cdb28805a1cfc7589b1cf5df6d4aadd94b6
Update AssemblyInfo.cs
managed-commons/managed-commons-crypto-phelix
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
// Commons.Crypto.Phelix Assembly Information // // Copyright ©2014 Rafael 'Monoman' Teixeira, Managed Commons Team // // 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.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Managed Commons Crypto Phelix")] [assembly: AssemblyDescription("Managed implementation of Phelix Cipher/MAC")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Managed Commons Team")] [assembly: AssemblyProduct("Managed.Commons.Crypto.Phelix")] [assembly: AssemblyCopyright("Copyright © Managed Commons Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("6d353780-6f73-44ef-9a1d-7bbe98725c61")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Managed.Commons.Crypto.Phelix")] [assembly: AssemblyDescription("Phelix Cipher/MAC")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Managed Commons Team")] [assembly: AssemblyProduct("Managed.Commons.Crypto.Phelix")] [assembly: AssemblyCopyright("Copyright © Managed Commons Team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("6d353780-6f73-44ef-9a1d-7bbe98725c61")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")]
bsd-2-clause
C#
807f2d3639d4ea7b66332f11826e4d2af13ee95b
Fix delayed timestamp fetching
REPLDigital/Sharp.Xmpp
Extensions/XEP-0203/DelayedDelivery.cs
Extensions/XEP-0203/DelayedDelivery.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Sharp.Xmpp.Extensions { /// <summary> /// Helper class for extracting delayed delivery timestamps as specified in XEP-0203 /// </summary> public static class DelayedDelivery { /// <summary> /// Try to get a timestamp from a delay node. If this fails, return the current UTC time. /// </summary> /// <param name="xml">The xml node that contains a delay node</param> public static DateTimeOffset GetDelayedTimestampOrNow(XmlElement xml) { DateTimeOffset timestamp = DateTimeOffset.UtcNow; // Refer to XEP-0203. var delay = xml["delay"]; if (delay != null && delay.NamespaceURI == "urn:xmpp:delay") { var stampAttribute = delay.GetAttribute("stamp"); if (stampAttribute != null) { timestamp = DateTimeProfiles.FromXmppString(stampAttribute); } } return timestamp; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace Sharp.Xmpp.Extensions { /// <summary> /// Helper class for extracting delayed delivery timestamps as specified in XEP-0203 /// </summary> public static class DelayedDelivery { /// <summary> /// Try to get a timestamp from a delay node. If this fails, return the current UTC time. /// </summary> /// <param name="xml">The xml node that contains a delay node</param> public static DateTimeOffset GetDelayedTimestampOrNow(XmlElement xml) { DateTimeOffset timestamp = DateTimeOffset.UtcNow; // Refer to XEP-0203. var delay = xml["delay"]; if (delay != null && delay.NamespaceURI == "urn:xmpp:delay") { var stampAttribute = delay["stamp"]; if (stampAttribute != null) { timestamp = DateTimeProfiles.FromXmppString(stampAttribute.InnerText); } } return timestamp; } } }
mit
C#
b3d12a29ab0d14bc07e145be425222ccaecac985
Add Screenshot tests
tablesmit/FluentAutomation,jorik041/FluentAutomation,tablesmit/FluentAutomation,jorik041/FluentAutomation,stirno/FluentAutomation,stirno/FluentAutomation,tablesmit/FluentAutomation,stirno/FluentAutomation,mirabeau-nl/WbTstr.Net,mirabeau-nl/WbTstr.Net,jorik041/FluentAutomation
FluentAutomation.Tests/Actions/TakeScreenshotTests.cs
FluentAutomation.Tests/Actions/TakeScreenshotTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Xunit; using System.Globalization; using FluentAutomation.Exceptions; namespace FluentAutomation.Tests.Actions { public class TakeScreenshotTests : BaseTest { private string tempPath = null; public TakeScreenshotTests() : base() { tempPath = Path.GetTempPath(); Config.ScreenshotPath(tempPath); TextPage.Go(); } [Fact] public void TakeScreenshot() { var screenshotName = string.Format(CultureInfo.CurrentCulture, "TakeScreenshot_{0}", DateTimeOffset.Now.Date.ToFileTime()); var filepath = this.tempPath + screenshotName + ".png"; I.Assert.False(() => File.Exists(filepath)); I.TakeScreenshot(screenshotName) .Assert .True(() => File.Exists(filepath)) .True(() => new FileInfo(filepath).Length > 0); File.Delete(filepath); } [Fact] public void ScreenshotOnFailedAction() { var c = Config.Settings.ScreenshotOnFailedAction; Config.ScreenshotOnFailedAction(true); Assert.Throws<FluentException>(() => I.Click("#nope")); var screenshotName = string.Format(CultureInfo.CurrentCulture, "ActionFailed_{0}", DateTimeOffset.Now.Date.ToFileTime()); var filepath = this.tempPath + screenshotName + ".png"; I.Assert .True(() => File.Exists(filepath)) .True(() => new FileInfo(filepath).Length > 0); File.Delete(filepath); Config.ScreenshotOnFailedAction(c); } [Fact] public void ScreenshotOnFailedAssert() { var c = Config.Settings.ScreenshotOnFailedAssert; Config.ScreenshotOnFailedAssert(true); Assert.Throws<FluentException>(() => I.Assert.True(() => false)); var screenshotName = string.Format(CultureInfo.CurrentCulture, "AssertFailed_{0}", DateTimeOffset.Now.Date.ToFileTime()); var filepath = this.tempPath + screenshotName + ".png"; I.Assert .True(() => File.Exists(filepath)) .True(() => new FileInfo(filepath).Length > 0); File.Delete(filepath); Config.ScreenshotOnFailedAssert(c); } /* [Fact] public void ScreenshotOnFailedExpect() { var c = Config.Settings.ScreenshotOnFailedExpect; Config.ScreenshotOnFailedExpect(true); I.Expect.True(() => false); var screenshotName = string.Format(CultureInfo.CurrentCulture, "ExpectFailed_{0}", DateTimeOffset.Now.Date.ToFileTime()); var filepath = this.tempPath + screenshotName + ".png"; I.Assert .True(() => File.Exists(filepath)) .True(() => new FileInfo(filepath).Length > 0); File.Delete(filepath); Config.ScreenshotOnFailedExpect(c); } */ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FluentAutomation.Tests.Actions { class TakeScreenshotTests { } }
mit
C#
4799b17fe0f05958c413fd2f3fa9568d5bf7e235
Update Program.cs
dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua
src/WebSite/Program.cs
src/WebSite/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace WebSite { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true) .AddEnvironmentVariables(); }) .UseStartup<Startup>() .Build(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace WebSite { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { var env = hostingContext.HostingEnvironment; config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true); }) .UseStartup<Startup>() .Build(); } }
mit
C#
a7e55ca60f8695cff3d3cb106edeb8af9f092ccf
fix to actuall check password
kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
Joinrpg/App_Start/ApiSignInProvider.cs
Joinrpg/App_Start/ApiSignInProvider.cs
using System.Data.Entity; using System.Threading.Tasks; using JoinRpg.Web.Helpers; using Microsoft.Owin.Security.OAuth; namespace JoinRpg.Web { internal class ApiSignInProvider : OAuthAuthorizationServerProvider { private ApplicationUserManager Manager { get; } public ApiSignInProvider(ApplicationUserManager manager) { Manager = manager; } /// <inheritdoc /> public override Task ValidateClientAuthentication( OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult(0); } public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"}); var user = await Manager.FindByEmailAsync(context.UserName); if (!await Manager.CheckPasswordAsync(user, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var x = await user.GenerateUserIdentityAsync(Manager, context.Options.AuthenticationType); context.Validated(x); } } }
using System.Data.Entity; using System.Threading.Tasks; using JoinRpg.Web.Helpers; using Microsoft.Owin.Security.OAuth; namespace JoinRpg.Web { internal class ApiSignInProvider : OAuthAuthorizationServerProvider { private ApplicationUserManager Manager { get; } public ApiSignInProvider(ApplicationUserManager manager) { Manager = manager; } /// <inheritdoc /> public override Task ValidateClientAuthentication( OAuthValidateClientAuthenticationContext context) { context.Validated(); return Task.FromResult(0); } public override async Task GrantResourceOwnerCredentials( OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] {"*"}); var user = await Manager.FindByEmailAsync(context.UserName); if (await Manager.CheckPasswordAsync(user, context.Password)) { context.SetError("invalid_grant", "The user name or password is incorrect."); return; } var x = await user.GenerateUserIdentityAsync(Manager, context.Options.AuthenticationType); context.Validated(x); } } }
mit
C#
1b6de475cbcf4c848452e95f9c8538cb4916ed8b
Check for uniqueness for the classes that come back.
gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT,gordonwatts/LINQtoROOT
LINQToTTree/TTreeParser.Tests/Utils.cs
LINQToTTree/TTreeParser.Tests/Utils.cs
using System.Collections.Generic; using System.Linq; using TTreeDataModel; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace TTreeParser.Tests { public static class TUtils { /// <summary> /// Find a class in the list, return null if we can't find it. /// </summary> /// <param name="classes"></param> /// <param name="name"></param> /// <returns></returns> public static ROOTClassShell FindClass(this IEnumerable<ROOTClassShell> classes, string name) { Assert.AreEqual(1, classes.Where(c => c.Name == name).Count(), string.Format("# of classes called {0}", name)); return classes.Where(c => c.Name == name).FirstOrDefault(); } /// <summary> /// Find the class item for a particular item. /// </summary> /// <param name="cls"></param> /// <param name="itemName"></param> /// <returns></returns> public static IClassItem FindItem(this ROOTClassShell cls, string itemName) { return cls.Items.Where(i => i.Name == itemName).FirstOrDefault(); } } }
using System.Collections.Generic; using System.Linq; using TTreeDataModel; namespace TTreeParser.Tests { public static class TUtils { /// <summary> /// Find a class in the list, return null if we can't find it. /// </summary> /// <param name="classes"></param> /// <param name="name"></param> /// <returns></returns> public static ROOTClassShell FindClass(this IEnumerable<ROOTClassShell> classes, string name) { return classes.Where(c => c.Name == name).FirstOrDefault(); } /// <summary> /// Find the class item for a particular item. /// </summary> /// <param name="cls"></param> /// <param name="itemName"></param> /// <returns></returns> public static IClassItem FindItem(this ROOTClassShell cls, string itemName) { return cls.Items.Where(i => i.Name == itemName).FirstOrDefault(); } } }
lgpl-2.1
C#
1a9bd7747d30f9d6a6c10a1042ed6397a15d5000
add virtual keys and key-name mapper
hemincong/PostageStampTransactionHelper
PostageStampTransactionHelper/VirtualKeyCodes.cs
PostageStampTransactionHelper/VirtualKeyCodes.cs
using System.Collections.Generic; namespace PostageStampTransactionHelper { public class VirtualKeyCodes { public const int WM_HOTKEY = 0x0312; public const int HOTKEY_ID = 9000; //Modifiers: public const uint MOD_NONE = 0x0000; //(none) public const uint MOD_ALT = 0x0001; //ALT public const uint MOD_CONTROL = 0x0002; //CTRL public const uint MOD_SHIFT = 0x0004; //SHIFT public const uint MOD_WIN = 0x0008; //WINDOWS public const uint VK_CAPITAL = 0x14; public const uint VK_TAB = 0x09; public const uint VK_RETURN = 0x0D; public const uint A_KEY = 0x41; public const uint B_KEY = 0x42; public const uint I_KEY = 0x49; public const uint J_KEY = 0x4A; public const uint K_KEY = 0x4B; public const uint X_KEY = 0x58; public const uint Y_KEY = 0x59; public const uint Z_KEY = 0x5A; static private Dictionary<uint, string> key_name_mapper = new Dictionary<uint, string> { { A_KEY, "A" }, { B_KEY, "B" }, { I_KEY, "I" }, { J_KEY, "J" }, { K_KEY, "K" }, { X_KEY, "X" }, { Y_KEY, "Y" }, { Z_KEY, "Z" }, }; static public string GetKeyName(uint virtualKey) { string name; key_name_mapper.TryGetValue(virtualKey, out name); return name; } } }
// ReSharper disable InconsistentNaming namespace PostageStampTransactionHelper { public class VirtualKeyCodes { public const int WM_HOTKEY = 0x0312; public const int HOTKEY_ID = 9000; //Modifiers: public const uint MOD_NONE = 0x0000; //(none) public const uint MOD_ALT = 0x0001; //ALT public const uint MOD_CONTROL = 0x0002; //CTRL public const uint MOD_SHIFT = 0x0004; //SHIFT public const uint MOD_WIN = 0x0008; //WINDOWS public const uint VK_CAPITAL = 0x14; public const uint VK_TAB = 0x09; public const uint VK_RETURN = 0x0D; } }
apache-2.0
C#
d8fc6cbd41c83b2882b1c002372d69dc030ed6ce
Fix StyleCop issues
NilesDavis/oxyplot,as-zhuravlev/oxyplot_wpf_fork,GeertvanHorrik/oxyplot,GeertvanHorrik/oxyplot,HermanEldering/oxyplot,objorke/oxyplot,Isolocis/oxyplot,as-zhuravlev/oxyplot_wpf_fork,DotNetDoctor/oxyplot,Jonarw/oxyplot,objorke/oxyplot,jeremyiverson/oxyplot,ze-pequeno/oxyplot,Sbosanquet/oxyplot,shoelzer/oxyplot,HermanEldering/oxyplot,as-zhuravlev/oxyplot_wpf_fork,Jofta/oxyplot,shoelzer/oxyplot,Kaplas80/oxyplot,shoelzer/oxyplot,olegtarasov/oxyplot,olegtarasov/oxyplot,objorke/oxyplot,jeremyiverson/oxyplot,oxyplot/oxyplot,GeertvanHorrik/oxyplot,Rustemt/oxyplot,zur003/oxyplot,DotNetDoctor/oxyplot,jeremyiverson/oxyplot,Sbosanquet/oxyplot,Kaplas80/oxyplot,Rustemt/oxyplot,Sbosanquet/oxyplot,Rustemt/oxyplot
Source/OxyPlot.Tests/Utilities/ComparerHelperTests.cs
Source/OxyPlot.Tests/Utilities/ComparerHelperTests.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ComparerHelperTests.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Tests { using System.Collections.Generic; using System.Linq; using NUnit.Framework; /// <summary> /// Unit tests for the <see cref="ComparerHelper"/>. /// </summary> [TestFixture] public class ComparerHelperTests { /// <summary> /// Creates a comparer from a delegate. /// </summary> [Test] public void CreateComparerFromDelegate() { var source = new List<int> { 1, 2, 3, 0, 4, 5, 6, 7 }; var comparer = ComparerHelper.CreateComparer<int>( (x, y) => { if (x == 0) { return y == 0 ? 0 : -1; } if (y == 0) { return 1; } return y.CompareTo(x); }); var sorted = source.OrderBy(x => x, comparer).ToList(); var expected = new List<int> { 0, 7, 6, 5, 4, 3, 2, 1 }; CollectionAssert.AreEqual(expected, sorted); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ComparerHelperTests.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot.Tests { using System.Collections.Generic; using System.Linq; using NUnit.Framework; [TestFixture] public class ComparerHelperTests { [Test] public void CreateComparerFromDelegate() { var source = new List<int> { 1, 2, 3, 0, 4, 5, 6, 7 }; var comparer = ComparerHelper.CreateComparer<int>( (x, y) => { if (x == 0) return y == 0 ? 0 : -1; if (y == 0) return 1; return y.CompareTo(x); }); var sorted = source.OrderBy(x => x, comparer).ToList(); var expected = new List<int> { 0, 7, 6, 5, 4, 3, 2, 1 }; CollectionAssert.AreEqual(expected, sorted); } } }
mit
C#
cb60462f991940f5de39a6e1c9f5f7b98c6ebfed
Update Exention
Nanabell/NoAdsHere
NoAdsHere/Common/Extentions.cs
NoAdsHere/Common/Extentions.cs
using System.Collections.Generic; using System.Linq; using Discord; using NoAdsHere.Database.Models.GuildSettings; namespace NoAdsHere.Common { public static class Extentions { public static bool CheckChannelPermission(this IMessageChannel channel, ChannelPermission permission, IGuildUser guildUser) { var guildchannel = channel as IGuildChannel; ChannelPermissions perms; perms = guildchannel != null ? guildUser.GetPermissions(guildchannel) : ChannelPermissions.All(null); return perms.Has(permission); } public static IEnumerable<Ignore> GetIgnoreType(this IEnumerable<Ignore> ignores, IgnoreType type) => ignores.Where(i => i.IgnoreType == type || i.IgnoreType == IgnoreType.All); } }
using System.Collections.Generic; using System.Linq; using Discord; using NoAdsHere.Database.Models.GuildSettings; namespace NoAdsHere.Common { public static class Extentions { public static bool CheckChannelPermission(this IMessageChannel channel, ChannelPermission permission, IGuildUser guildUser) { var guildchannel = channel as IGuildChannel; ChannelPermissions perms; perms = guildchannel != null ? guildUser.GetPermissions(guildchannel) : ChannelPermissions.All(null); return perms.Has(permission); } public static IEnumerable<Ignore> GetIgnoreType(this IEnumerable<Ignore> ignores, IgnoreTypes type) => ignores.Where(i => i.IgnoreType == type || i.IgnoreType == IgnoreTypes.All); } }
mit
C#
de6f3844b410a8d8307268a6e43a7c602d810020
Add a default ToString to TryWebsitesIdentity
fashaikh/SimpleWAWS,fashaikh/SimpleWAWS,davidebbo/SimpleWAWS,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,projectkudu/TryAppService,projectkudu/SimpleWAWS,projectkudu/TryAppService,davidebbo/SimpleWAWS,projectkudu/SimpleWAWS,fashaikh/SimpleWAWS,projectkudu/TryAppService,projectkudu/TryAppService,projectkudu/SimpleWAWS,davidebbo/SimpleWAWS,fashaikh/SimpleWAWS
SimpleWAWS/Authentication/TryWebsitesIdentity.cs
SimpleWAWS/Authentication/TryWebsitesIdentity.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Principal; using System.Web; namespace SimpleWAWS.Authentication { public class TryWebsitesIdentity : IIdentity { public TryWebsitesIdentity(string email, string puid, string issure) { this.Name = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", issure, email); this.Email = email; this.Puid = puid; this.Issuer = issure; this.AuthenticationType = issure; this.IsAuthenticated = true; } public string Name { get; private set; } public string AuthenticationType { get; private set; } public bool IsAuthenticated { get; private set; } public string UniqueName { get { return string.Format(CultureInfo.InvariantCulture, "{0};{1}", Issuer, Email); } } public string Puid { get; private set; } public string Email { get; private set; } public string Issuer { get; private set; } public override string ToString() { return Name; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Security.Principal; using System.Web; namespace SimpleWAWS.Authentication { public class TryWebsitesIdentity : IIdentity { public TryWebsitesIdentity(string email, string puid, string issure) { this.Name = string.Format(CultureInfo.InvariantCulture, "{0}#{1}", issure, email); this.Email = email; this.Puid = puid; this.Issuer = issure; this.AuthenticationType = issure; this.IsAuthenticated = true; } public string Name { get; private set; } public string AuthenticationType { get; private set; } public bool IsAuthenticated { get; private set; } public string UniqueName { get { return string.Format(CultureInfo.InvariantCulture, "{0};{1}", Issuer, Email); } } public string Puid { get; private set; } public string Email { get; private set; } public string Issuer { get; private set; } } }
apache-2.0
C#
571b9614eac57c6cca99e64d525194d3aa8d775d
Remove .NET limit on env var name and value length
Ermiar/corefx,ptoonen/corefx,ViktorHofer/corefx,shimingsg/corefx,ptoonen/corefx,Ermiar/corefx,ericstj/corefx,ericstj/corefx,BrennanConroy/corefx,Jiayili1/corefx,mmitche/corefx,zhenlan/corefx,ptoonen/corefx,mmitche/corefx,shimingsg/corefx,ViktorHofer/corefx,Jiayili1/corefx,ptoonen/corefx,ravimeda/corefx,ptoonen/corefx,mmitche/corefx,Ermiar/corefx,Ermiar/corefx,ericstj/corefx,ericstj/corefx,Ermiar/corefx,ravimeda/corefx,zhenlan/corefx,wtgodbe/corefx,zhenlan/corefx,mmitche/corefx,zhenlan/corefx,ericstj/corefx,shimingsg/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,mmitche/corefx,wtgodbe/corefx,Ermiar/corefx,ViktorHofer/corefx,ViktorHofer/corefx,Jiayili1/corefx,Jiayili1/corefx,ViktorHofer/corefx,zhenlan/corefx,Ermiar/corefx,mmitche/corefx,BrennanConroy/corefx,ravimeda/corefx,ravimeda/corefx,ptoonen/corefx,mmitche/corefx,Jiayili1/corefx,ravimeda/corefx,BrennanConroy/corefx,shimingsg/corefx,ericstj/corefx,Jiayili1/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,ravimeda/corefx,wtgodbe/corefx,zhenlan/corefx,wtgodbe/corefx,ptoonen/corefx,wtgodbe/corefx,ericstj/corefx,zhenlan/corefx,ravimeda/corefx,wtgodbe/corefx,Jiayili1/corefx
src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs
src/Common/src/CoreLib/Interop/Windows/Interop.Errors.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. internal partial class Interop { // As defined in winerror.h and https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx internal partial class Errors { internal const int ERROR_SUCCESS = 0x0; internal const int ERROR_FILE_NOT_FOUND = 0x2; internal const int ERROR_PATH_NOT_FOUND = 0x3; internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_INVALID_HANDLE = 0x6; internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; internal const int ERROR_INVALID_DRIVE = 0xF; internal const int ERROR_NO_MORE_FILES = 0x12; internal const int ERROR_NOT_READY = 0x15; internal const int ERROR_SHARING_VIOLATION = 0x20; internal const int ERROR_HANDLE_EOF = 0x26; internal const int ERROR_FILE_EXISTS = 0x50; internal const int ERROR_INVALID_PARAMETER = 0x57; internal const int ERROR_BROKEN_PIPE = 0x6D; internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; internal const int ERROR_INVALID_NAME = 0x7B; internal const int ERROR_BAD_PATHNAME = 0xA1; internal const int ERROR_ALREADY_EXISTS = 0xB7; internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; internal const int ERROR_NO_DATA = 0xE8; internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_NO_MORE_ITEMS = 0x103; internal const int ERROR_NOT_OWNER = 0x120; internal const int ERROR_TOO_MANY_POSTS = 0x12A; internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 0x24B; internal const int ERROR_OPERATION_ABORTED = 0x3E3; internal const int ERROR_IO_PENDING = 0x3E5; internal const int ERROR_NO_UNICODE_TRANSLATION = 0x459; internal const int ERROR_NOT_FOUND = 0x490; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542; internal const int ERROR_NO_SYSTEM_RESOURCES = 0x5AA; internal const int E_FILENOTFOUND = unchecked((int)0x80070002); internal const int ERROR_TIMEOUT = 0x000005B4; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. internal partial class Interop { // As defined in winerror.h and https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382.aspx internal partial class Errors { internal const int ERROR_SUCCESS = 0x0; internal const int ERROR_FILE_NOT_FOUND = 0x2; internal const int ERROR_PATH_NOT_FOUND = 0x3; internal const int ERROR_ACCESS_DENIED = 0x5; internal const int ERROR_INVALID_HANDLE = 0x6; internal const int ERROR_NOT_ENOUGH_MEMORY = 0x8; internal const int ERROR_INVALID_DRIVE = 0xF; internal const int ERROR_NO_MORE_FILES = 0x12; internal const int ERROR_NOT_READY = 0x15; internal const int ERROR_SHARING_VIOLATION = 0x20; internal const int ERROR_HANDLE_EOF = 0x26; internal const int ERROR_FILE_EXISTS = 0x50; internal const int ERROR_INVALID_PARAMETER = 0x57; internal const int ERROR_BROKEN_PIPE = 0x6D; internal const int ERROR_INSUFFICIENT_BUFFER = 0x7A; internal const int ERROR_INVALID_NAME = 0x7B; internal const int ERROR_BAD_PATHNAME = 0xA1; internal const int ERROR_ALREADY_EXISTS = 0xB7; internal const int ERROR_ENVVAR_NOT_FOUND = 0xCB; internal const int ERROR_FILENAME_EXCED_RANGE = 0xCE; internal const int ERROR_NO_DATA = 0xE8; internal const int ERROR_MORE_DATA = 0xEA; internal const int ERROR_NO_MORE_ITEMS = 0x103; internal const int ERROR_NOT_OWNER = 0x120; internal const int ERROR_TOO_MANY_POSTS = 0x12A; internal const int ERROR_ARITHMETIC_OVERFLOW = 0x216; internal const int ERROR_MUTANT_LIMIT_EXCEEDED = 0x24B; internal const int ERROR_OPERATION_ABORTED = 0x3E3; internal const int ERROR_IO_PENDING = 0x3E5; internal const int ERROR_NO_UNICODE_TRANSLATION = 0x459; internal const int ERROR_NOT_FOUND = 0x490; internal const int ERROR_BAD_IMPERSONATION_LEVEL = 0x542; internal const int E_FILENOTFOUND = unchecked((int)0x80070002); internal const int ERROR_TIMEOUT = 0x000005B4; } }
mit
C#
f6c2be93895094c5dc11260f2c4b4741052bbe6b
clear the message when the panel is closed
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio.UI/UI/Controls/InfoPanel.xaml.cs
src/GitHub.VisualStudio.UI/UI/Controls/InfoPanel.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 GitHub.VisualStudio.UI.Controls { /// <summary> /// Interaction logic for InfoPanel.xaml /// </summary> public partial class InfoPanel : UserControl { public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(nameof(Message), typeof(string), typeof(InfoPanel), new PropertyMetadata(null, UpdateVisibility)); public string Message { get { return (string)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); } } public InfoPanel() { InitializeComponent(); this.DataContext = this; } static void UpdateVisibility(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (InfoPanel)d; control.Visibility = string.IsNullOrEmpty(control.Message) ? Visibility.Collapsed : Visibility.Visible; } void Button_Click(object sender, RoutedEventArgs e) { this.Visibility = Visibility.Collapsed; this.Message = string.Empty; } } }
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 GitHub.VisualStudio.UI.Controls { /// <summary> /// Interaction logic for InfoPanel.xaml /// </summary> public partial class InfoPanel : UserControl { public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(nameof(Message), typeof(string), typeof(InfoPanel), new PropertyMetadata(null, UpdateVisibility)); public string Message { get { return (string)GetValue(MessageProperty); } set { SetValue(MessageProperty, value); } } public InfoPanel() { InitializeComponent(); this.DataContext = this; } static void UpdateVisibility(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = (InfoPanel)d; control.Visibility = string.IsNullOrEmpty(control.Message) ? Visibility.Collapsed : Visibility.Visible; } void Button_Click(object sender, RoutedEventArgs e) { this.Visibility = Visibility.Collapsed; } } }
mit
C#
2b0da295f9bb7a6d88ac0d637abf767192d10e17
use lock.
Cologler/jasily.cologler
Jasily.Core/Singleton.cs
Jasily.Core/Singleton.cs
using JetBrains.Annotations; namespace System { public static class Singleton { public static T Instance<T>() where T : class, new() { if (Shared<T>.instance == null) { lock (typeof(Shared<T>)) { if (Shared<T>.instance == null) { Shared<T>.instance = new T(); } } } return Shared<T>.instance; } public static T Instance<T>([NotNull] Func<T> creator) where T : class { if (creator == null) throw new ArgumentNullException(nameof(creator)); if (Shared<T>.instance == null) { lock (typeof(Shared<T>)) { if (Shared<T>.instance == null) { Shared<T>.instance = creator(); } } } return Shared<T>.instance; } private static class Shared<T> where T : class { // ReSharper disable once InconsistentNaming public static T instance; } #region thread static public static T ThreadStaticInstance<T>() where T : class, new() => ThreadStatic<T>.instance ?? (ThreadStatic<T>.instance = new T()); private static class ThreadStatic<T> where T : class { [ThreadStatic] // ReSharper disable once InconsistentNaming public static T instance; } #endregion } }
using System.Threading; namespace System { public static class Singleton { public static T Instance<T>() where T : class, new() { if (Shared<T>.instance == null) { Interlocked.CompareExchange(ref Shared<T>.instance, new T(), null); } return Shared<T>.instance; } public static T InstanceSafe<T>() where T : class, new() { if (Shared<T>.instance == null) { lock (typeof(Shared<T>)) { return Instance<T>(); } } return Shared<T>.instance; } private static class Shared<T> { // ReSharper disable once InconsistentNaming public static T instance; } #region thread static public static T ThreadStaticInstance<T>() where T : class, new() => ThreadStatic<T>.instance ?? (ThreadStatic<T>.instance = new T()); private static class ThreadStatic<T> { [ThreadStatic] // ReSharper disable once InconsistentNaming public static T instance; } #endregion } }
mit
C#
1d2b5e83d3743ce3db9c1eafbb5c8e66952be4de
Fix ClientCertificateThumbprint whitespace issue
SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers,SkillsFundingAgency/das-employerusers
src/SFA.DAS.EmployerUsers.Api.Client/SecureHttpClient.cs
src/SFA.DAS.EmployerUsers.Api.Client/SecureHttpClient.cs
using System.Net.Http; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace SFA.DAS.EmployerUsers.Api.Client { internal class SecureHttpClient : ISecureHttpClient { private readonly IEmployerUsersApiConfiguration _configuration; internal SecureHttpClient(IEmployerUsersApiConfiguration configuration) { _configuration = configuration; } private async Task<AuthenticationResult> GetAuthenticationResult(string clientId, string appKey, string resourceId, string tenant) { var authority = $"https://login.microsoftonline.com/{tenant}"; var clientCredential = new ClientCredential(clientId, appKey); var context = new AuthenticationContext(authority, true); var result = await context.AcquireTokenAsync(resourceId, clientCredential); return result; } public virtual async Task<string> GetAsync(string url) { var authenticationResult = await GetAuthenticationResult(_configuration.ClientId, _configuration.ClientSecret, _configuration.IdentifierUri, _configuration.Tenant); using (var store = new ClientCertificateStore(new X509Store(StoreLocation.LocalMachine))) using (var handler = new WebRequestHandler()) using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); if (!string.IsNullOrWhiteSpace(_configuration.ClientCertificateThumbprint)) { var certificate = store.FindCertificateByThumbprint(_configuration.ClientCertificateThumbprint); if (certificate != null) { handler.ClientCertificates.Add(certificate); } } var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } } }
using System.Net.Http; using System.Security.Cryptography.X509Certificates; using System.Threading.Tasks; using Microsoft.IdentityModel.Clients.ActiveDirectory; namespace SFA.DAS.EmployerUsers.Api.Client { internal class SecureHttpClient : ISecureHttpClient { private readonly IEmployerUsersApiConfiguration _configuration; internal SecureHttpClient(IEmployerUsersApiConfiguration configuration) { _configuration = configuration; } private async Task<AuthenticationResult> GetAuthenticationResult(string clientId, string appKey, string resourceId, string tenant) { var authority = $"https://login.microsoftonline.com/{tenant}"; var clientCredential = new ClientCredential(clientId, appKey); var context = new AuthenticationContext(authority, true); var result = await context.AcquireTokenAsync(resourceId, clientCredential); return result; } public virtual async Task<string> GetAsync(string url) { var authenticationResult = await GetAuthenticationResult(_configuration.ClientId, _configuration.ClientSecret, _configuration.IdentifierUri, _configuration.Tenant); using (var store = new ClientCertificateStore(new X509Store(StoreLocation.LocalMachine))) using (var handler = new WebRequestHandler()) using (var client = new HttpClient(handler)) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authenticationResult.AccessToken); if (!string.IsNullOrEmpty(_configuration.ClientCertificateThumbprint)) { var certificate = store.FindCertificateByThumbprint(_configuration.ClientCertificateThumbprint); if (certificate != null) { handler.ClientCertificates.Add(certificate); } } var response = await client.GetAsync(url); response.EnsureSuccessStatusCode(); return await response.Content.ReadAsStringAsync(); } } } }
mit
C#
08429cb1448ef8fa052c215182f965dc4127cc1c
Change paths in tests
MortenHoustonLudvigsen/KarmaTestAdapter,MortenHoustonLudvigsen/KarmaTestAdapter,MortenHoustonLudvigsen/KarmaTestAdapter,MortenHoustonLudvigsen/KarmaTestAdapter,MortenHoustonLudvigsen/KarmaTestAdapter
KarmaTestAdapterTests/Globals.cs
KarmaTestAdapterTests/Globals.cs
using NUnit.Framework; using NUnit.Framework.Constraints; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KarmaTestAdapterTests.GlobalsTests { public class Globals : BaseFixture { public class IsTest : BaseFixture { [Test] public void ShouldBeTrue() { Assert.That(KarmaTestAdapter.Globals.IsTest, Is.True); } } public class AssemblyDirectory : BaseFixture { [Test] public void ShouldBeTestDirectory() { Assert.That(KarmaTestAdapter.Globals.AssemblyDirectory, IsTestPath(TestDir)); } } public class RootDirectory : BaseFixture { [Test] public void ShouldBeKarmaDirectoryIfTest() { Assert.That(KarmaTestAdapter.Globals.RootDirectory, IsTestPath(SolutionDir, @"KarmaServer")); } [Test] public void ShouldBeTestDirectoryIfNotTest() { KarmaTestAdapter.Globals.IsTest = false; Assert.That(KarmaTestAdapter.Globals.RootDirectory, IsTestPath(TestDir)); } } public class LibDirectory : BaseFixture { [Test] public void ShouldBeInKarmaDirectoryIfTest() { Assert.That(KarmaTestAdapter.Globals.LibDirectory, IsTestPath(SolutionDir, @"KarmaServer\lib")); } [Test] public void ShouldBeInTestDirectoryIfNotTest() { KarmaTestAdapter.Globals.IsTest = false; Assert.That(KarmaTestAdapter.Globals.LibDirectory, IsTestPath(TestDir, "lib")); } } } }
using NUnit.Framework; using NUnit.Framework.Constraints; using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KarmaTestAdapterTests.GlobalsTests { public class Globals : BaseFixture { public class IsTest : BaseFixture { [Test] public void ShouldBeTrue() { Assert.That(KarmaTestAdapter.Globals.IsTest, Is.True); } } public class AssemblyDirectory : BaseFixture { [Test] public void ShouldBeTestDirectory() { Assert.That(KarmaTestAdapter.Globals.AssemblyDirectory, IsTestPath(TestDir)); } } public class RootDirectory : BaseFixture { [Test] public void ShouldBeKarmaDirectoryIfTest() { Assert.That(KarmaTestAdapter.Globals.RootDirectory, IsTestPath(SolutionDir, @"KarmaTestAdapter")); } [Test] public void ShouldBeTestDirectoryIfNotTest() { KarmaTestAdapter.Globals.IsTest = false; Assert.That(KarmaTestAdapter.Globals.RootDirectory, IsTestPath(TestDir)); } } public class LibDirectory : BaseFixture { [Test] public void ShouldBeInKarmaDirectoryIfTest() { Assert.That(KarmaTestAdapter.Globals.LibDirectory, IsTestPath(SolutionDir, @"KarmaTestAdapter\lib")); } [Test] public void ShouldBeInTestDirectoryIfNotTest() { KarmaTestAdapter.Globals.IsTest = false; Assert.That(KarmaTestAdapter.Globals.LibDirectory, IsTestPath(TestDir, "lib")); } } } }
mit
C#
ded9b02d72c162eb5718238cc21be3f8702352e3
Fix Monitoring snippet
googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/gcloud-dotnet,googleapis/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,jskeet/google-cloud-dotnet,googleapis/google-cloud-dotnet
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.Snippets/MetricServiceClientSnippets.cs
apis/Google.Cloud.Monitoring.V3/Google.Cloud.Monitoring.V3.Snippets/MetricServiceClientSnippets.cs
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api; using Google.Api.Gax; using Google.Cloud.ClientTesting; using System; using System.Linq; using Xunit; namespace Google.Cloud.Monitoring.V3 { [SnippetOutputCollector] [Collection(nameof(MonitoringFixture))] public class MetricServiceClientSnippets { private readonly MonitoringFixture _fixture; public MetricServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListMetricDescriptors() { string projectId = _fixture.ProjectId; // Sample: ListMetricDescriptors // Additional: ListMetricDescriptors(ProjectName,*,*,*) MetricServiceClient client = MetricServiceClient.Create(); ProjectName projectName = new ProjectName(projectId); PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName); foreach (MetricDescriptor metric in metrics.Take(10)) { Console.WriteLine($"{metric.Name}: {metric.DisplayName}"); } // End sample } } }
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api; using Google.Api.Gax; using Google.Cloud.ClientTesting; using System; using System.Linq; using Xunit; namespace Google.Cloud.Monitoring.V3 { [SnippetOutputCollector] [Collection(nameof(MonitoringFixture))] public class MetricServiceClientSnippets { private readonly MonitoringFixture _fixture; public MetricServiceClientSnippets(MonitoringFixture fixture) { _fixture = fixture; } [Fact] public void ListMetricDescriptors() { string projectId = _fixture.ProjectId; // Sample: ListMetricDescriptors // Additional: ListMetricDescriptors(*,*,*,*) MetricServiceClient client = MetricServiceClient.Create(); ProjectName projectName = new ProjectName(projectId); PagedEnumerable<ListMetricDescriptorsResponse, MetricDescriptor> metrics = client.ListMetricDescriptors(projectName); foreach (MetricDescriptor metric in metrics.Take(10)) { Console.WriteLine($"{metric.Name}: {metric.DisplayName}"); } // End sample } } }
apache-2.0
C#
4bd3d09d72178156228a077b3a8679d58b8c5645
Support sending an empty body
rackerlabs/RackspaceCloudOfficeApiClient
Rackspace.CloudOffice/BodyEncoder.cs
Rackspace.CloudOffice/BodyEncoder.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Newtonsoft.Json; namespace Rackspace.CloudOffice { internal static class BodyEncoder { public static string Encode(object data, string contentType) { if (data == null) return string.Empty; switch (contentType) { case ApiClient.ContentType.UrlEncoded: return FormUrlEncode(GetObjectAsDictionary(data)); case ApiClient.ContentType.Json: return JsonConvert.SerializeObject(data); default: throw new ArgumentException("Unsupported contentType: " + contentType); } } static string FormUrlEncode(IDictionary<string, string> data) { var pairs = data.Select(pair => string.Format("{0}={1}", WebUtility.UrlEncode(pair.Key), WebUtility.UrlEncode(pair.Value))); return string.Join("&", pairs); } static IDictionary<string, string> GetObjectAsDictionary(object obj) { var dict = new Dictionary<string, string>(); var properties = obj.GetType() .GetMembers(BindingFlags.Public | BindingFlags.Instance) .OfType<PropertyInfo>(); foreach (var prop in properties) dict[prop.Name] = Convert.ToString(prop.GetValue(obj)); return dict; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Reflection; using Newtonsoft.Json; namespace Rackspace.CloudOffice { internal static class BodyEncoder { public static string Encode(object data, string contentType) { switch (contentType) { case ApiClient.ContentType.UrlEncoded: return FormUrlEncode(GetObjectAsDictionary(data)); case ApiClient.ContentType.Json: return JsonConvert.SerializeObject(data); default: throw new ArgumentException("Unsupported contentType: " + contentType); } } static string FormUrlEncode(IDictionary<string, string> data) { var pairs = data.Select(pair => string.Format("{0}={1}", WebUtility.UrlEncode(pair.Key), WebUtility.UrlEncode(pair.Value))); return string.Join("&", pairs); } static IDictionary<string, string> GetObjectAsDictionary(object obj) { var dict = new Dictionary<string, string>(); var properties = obj.GetType() .GetMembers(BindingFlags.Public | BindingFlags.Instance) .OfType<PropertyInfo>(); foreach (var prop in properties) dict[prop.Name] = Convert.ToString(prop.GetValue(obj)); return dict; } } }
mit
C#
95f72a99dd6d2013952daa9a027a2f8e7afda905
update version
ceee/ReadSharp,alexeib/ReadSharp
ReadSharp/Properties/AssemblyInfo.cs
ReadSharp/Properties/AssemblyInfo.cs
using System.Reflection; // 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("ReadSharp")] [assembly: AssemblyDescription("Extract meaningful website contents using a port of NReadability")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("cee")] [assembly: AssemblyProduct("ReadSharp")] [assembly: AssemblyCopyright("Copyright © cee 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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("5.0.0")] [assembly: AssemblyFileVersion("5.0.0")]
using System.Reflection; // 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("ReadSharp")] [assembly: AssemblyDescription("Extract meaningful website contents using a port of NReadability")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("cee")] [assembly: AssemblyProduct("ReadSharp")] [assembly: AssemblyCopyright("Copyright © cee 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 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("4.2.3")] [assembly: AssemblyFileVersion("4.2.3")]
mit
C#
c6da1dd38d7976d9e7d6c549ca09c31d5e9aa8c0
test method
ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins,ignatandrei/stankins
StankinsTests/TestSenderAzureIoTHub.cs
StankinsTests/TestSenderAzureIoTHub.cs
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using SenderAzureIoTHub; using System.Threading.Tasks; using Moq; using StankinsInterfaces; namespace StankinsTests { [TestClass] public class TestSenderAzureIoTHub { [TestMethod] [TestCategory("ExternalProgramsToBeRun")] public async Task TestSenderAzureIoTHubSimple() { #region arrange //Sender string iotHubUri = "a"; string deviceId = "b"; string deviceKey = "c"; string dataType = "UnitTest"; var snd = new SenderToAzureIoTHub(iotHubUri, deviceId, deviceKey, dataType); //Data to be sent var m = new Mock<IRow>(); var rows = new List<IRow>(); int nrRows = 2; for (int i = 0; i < nrRows; i++) { var row = new Mock<IRow>(); row.SetupProperty ( obj => obj.Values, new Dictionary<string, object>() { ["PersonID"] = i, ["FirstName"] = "John " + i, ["LastName"] = "Doe " + i } ); rows.Add(row.Object); } #endregion #region act snd.valuesToBeSent = rows.ToArray(); await snd.Send(); #endregion #region assert //No special assert here. If above code doesn't throw an exception then it's fine. #endregion } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using SenderAzureIoTHub; using System.Threading.Tasks; using Moq; using StankinsInterfaces; namespace StankinsTests { [TestClass] public class TestSenderAzureIoTHub { [TestMethod] public async Task TestSenderAzureIoTHubSimple() { #region arrange //Sender string iotHubUri = "a"; string deviceId = "b"; string deviceKey = "c"; string dataType = "UnitTest"; var snd = new SenderToAzureIoTHub(iotHubUri, deviceId, deviceKey, dataType); //Data to be sent var m = new Mock<IRow>(); var rows = new List<IRow>(); int nrRows = 2; for (int i = 0; i < nrRows; i++) { var row = new Mock<IRow>(); row.SetupProperty ( obj => obj.Values, new Dictionary<string, object>() { ["PersonID"] = i, ["FirstName"] = "John " + i, ["LastName"] = "Doe " + i } ); rows.Add(row.Object); } #endregion #region act snd.valuesToBeSent = rows.ToArray(); await snd.Send(); #endregion #region assert //No special assert here. If above code doesn't throw an exception then it's fine. #endregion } } }
mit
C#
d9bf0994b39fe3dde4f74443b170de0b94a83091
change to use long instead of double
feedhenry-templates/sync-xamarin-app,feedhenry-templates/sync-xamarin-app
sync-model/ShoppingItem.cs
sync-model/ShoppingItem.cs
/** * Copyright Red Hat, Inc, and individual contributors. * * 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 FHSDK.Sync; using Newtonsoft.Json; using System.Text.RegularExpressions; namespace sync.model { public class ShoppingItem: IFHSyncModel { public ShoppingItem(string name) { Name = name; Created = "" + ((long)(DateTime.Now - GetEpoch()).TotalMilliseconds); } [JsonProperty("name")] public string Name { set; get; } [JsonProperty("created")] public string Created { set; get; } [JsonIgnore] public string UID { set; get; } public override string ToString() { return $"[ShoppingItem: UID={UID}, Name={Name}, Created={Created}]"; } private static DateTime GetEpoch() { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); } public string GetCreatedTime() { if (Regex.IsMatch (Created, @"^\d*$")) { return GetEpoch().AddMilliseconds(long.Parse(Created)).ToString ("MMM dd, yyyy, H:mm:ss tt"); } return "no date"; } private bool Equals(IFHSyncModel other) { return string.Equals(UID, other.UID); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((ShoppingItem) obj); } public override int GetHashCode() { return UID?.GetHashCode() ?? 0; } } }
/** * Copyright Red Hat, Inc, and individual contributors. * * 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 FHSDK.Sync; using Newtonsoft.Json; using System.Text.RegularExpressions; namespace sync.model { public class ShoppingItem: IFHSyncModel { public ShoppingItem(string name) { Name = name; Created = "" + (DateTime.Now - GetEpoch()).TotalMilliseconds; } [JsonProperty("name")] public string Name { set; get; } [JsonProperty("created")] public string Created { set; get; } [JsonIgnore] public string UID { set; get; } public override string ToString() { return $"[ShoppingItem: UID={UID}, Name={Name}, Created={Created}]"; } private static DateTime GetEpoch() { return new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); } public string GetCreatedTime() { if (Regex.IsMatch (Created, @"^\d*$")) { return GetEpoch().AddMilliseconds(double.Parse(Created)).ToString ("MMM dd, yyyy, H:mm:ss tt"); } return "no date"; } private bool Equals(IFHSyncModel other) { return string.Equals(UID, other.UID); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj.GetType() == GetType() && Equals((ShoppingItem) obj); } public override int GetHashCode() { return UID?.GetHashCode() ?? 0; } } }
apache-2.0
C#
88b21504e4850d56a1dbd24a49f265e5f83b8295
Make ByteBufferWriter faster (now really).
klesta490/BTDB,yonglehou/BTDB,Bobris/BTDB,karasek/BTDB
BTDB/StreamLayer/ByteBufferWriter.cs
BTDB/StreamLayer/ByteBufferWriter.cs
using System; using BTDB.Buffer; namespace BTDB.StreamLayer { public sealed class ByteBufferWriter : AbstractBufferedWriter { ByteBuffer _result; public ByteBufferWriter() { Buf = new byte[4096]; End = Buf.Length; } public ByteBuffer Data { get { FinalFlushIfNeeded(); return _result; } } public override void FlushBuffer() { JustFlushWithoutAllocNewBuffer(); if (Buf == null) Buf = new byte[4096]; End = Buf.Length; Pos = 0; } void FinalFlushIfNeeded() { if (Pos != 0) { JustFlushWithoutAllocNewBuffer(); Pos = 0; Buf = null; End = 1; } } void JustFlushWithoutAllocNewBuffer() { if (_result.Buffer == null || _result.Length == 0) { _result = ByteBuffer.NewAsync(Buf, 0, Pos); Buf = null; } else { var origLength = _result.Length; var newLength = origLength + Pos; var b = _result.Buffer; if (newLength > b.Length) { _result = new ByteBuffer(); Array.Resize(ref b, Math.Max(origLength*2, newLength)); } Array.Copy(Buf, 0, b, origLength, Pos); _result = ByteBuffer.NewAsync(b, 0, newLength); } } } }
using System; using BTDB.Buffer; namespace BTDB.StreamLayer { public sealed class ByteBufferWriter : AbstractBufferedWriter { ByteBuffer _result; public ByteBufferWriter() { Buf = new byte[4096]; End = Buf.Length; } public ByteBuffer Data { get { FinalFlushIfNeeded(); return _result; } } public override void FlushBuffer() { JustFlushWithoutAllocNewBuffer(); if (Buf == null) Buf = new byte[4096]; End = Buf.Length; Pos = 0; } void FinalFlushIfNeeded() { if (Pos != 0) { JustFlushWithoutAllocNewBuffer(); Pos = 0; Buf = null; End = 1; } } void JustFlushWithoutAllocNewBuffer() { if (_result.Buffer == null || _result.Length == 0) { _result = ByteBuffer.NewAsync(Buf, 0, Pos); Buf = null; } else { var origLength = _result.Length; var newLength = origLength + Pos; var b = _result.Buffer; _result = new ByteBuffer(); Array.Resize(ref b, Math.Max(origLength * 2, newLength)); Array.Copy(Buf, 0, b, origLength, Pos); _result = ByteBuffer.NewAsync(b, 0, newLength); } } } }
mit
C#
222b78c51f742f8d4fb5e65918c88dcebc1e0ce8
Fix TcpClientExtension throws exception in Linux
Code-Artist/CodeArtEng.Tcp
CodeArtEng.Tcp/TcpClientExtension.cs
CodeArtEng.Tcp/TcpClientExtension.cs
using System.Linq; using System.Net.NetworkInformation; namespace System.Net.Sockets { /// <summary> /// TCP Client Helper Class. /// </summary> public static class TcpClientExtension { /// <summary> /// Extension method to check if TCP client is connected. /// </summary> /// <param name="sender"></param> /// <returns></returns> public static bool IsConnected(this TcpClient sender) { return GetState(sender) == TcpState.Established; } private static TcpState GetState(TcpClient sender) { if (sender == null) return TcpState.Unknown; if (sender.Client == null) return TcpState.Closed; try { //In .NET 5.0, sender.Client.LocalEndPoint in IPV6 format. IPEndPoint clientEndPoint = sender.Client.LocalEndPoint as IPEndPoint; if (clientEndPoint == null) return TcpState.Closed; IPAddress senderIPV4 = clientEndPoint.Address; if (OSIsWindow()) { //Check and convert to IPV4 if client end point address is IPV6 (Windows Only) if (clientEndPoint.Address.IsIPv4MappedToIPv6) senderIPV4 = clientEndPoint.Address.MapToIPv4(); } int port = (sender.Client.LocalEndPoint as IPEndPoint).Port; var prop = IPGlobalProperties.GetIPGlobalProperties() .GetActiveTcpConnections() //Return TCP connection in IPV4 format .SingleOrDefault(x => (x.LocalEndPoint as IPEndPoint)?.Port == port && (x.LocalEndPoint as IPEndPoint).Address.Equals(senderIPV4)); return prop != null ? prop.State : TcpState.Unknown; } catch { return TcpState.Unknown; } } private static bool OSIsWindow() { switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32Windows: case PlatformID.WinCE: case PlatformID.Win32S: return true; case PlatformID.Unix: case PlatformID.Xbox: case PlatformID.MacOSX: default: return false; } } } }
using System.Linq; using System.Net.NetworkInformation; namespace System.Net.Sockets { /// <summary> /// TCP Client Helper Class. /// </summary> public static class TcpClientExtension { /// <summary> /// Extension method to check if TCP client is connected. /// </summary> /// <param name="sender"></param> /// <returns></returns> public static bool IsConnected(this TcpClient sender) { return GetState(sender) == TcpState.Established; } private static TcpState GetState(TcpClient sender) { if (sender == null) return TcpState.Unknown; if (sender.Client == null) return TcpState.Closed; try { //In .NET 5.0, sender.Client.LocalEndPoint in IPV6 format. IPEndPoint clientEndPoint = sender.Client.LocalEndPoint as IPEndPoint; if (clientEndPoint == null) return TcpState.Closed; //Check and convert to IPV4 if client end point address is IPV6 IPAddress senderIPV4 = clientEndPoint.Address.IsIPv4MappedToIPv6 ? clientEndPoint.Address.MapToIPv4() : clientEndPoint.Address; int port = (sender.Client.LocalEndPoint as IPEndPoint).Port; var prop = IPGlobalProperties.GetIPGlobalProperties() .GetActiveTcpConnections() //Return TCP connection in IPV4 format .SingleOrDefault(x => (x.LocalEndPoint as IPEndPoint)?.Port == port && (x.LocalEndPoint as IPEndPoint).Address.Equals(senderIPV4)); return prop != null ? prop.State : TcpState.Unknown; } catch { return TcpState.Unknown; } } } }
mit
C#
4990fe171e243589c8f195ded2a4f02120f63b2c
Delete line
physhi/roslyn,KevinRansom/roslyn,bartdesmet/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,eriawan/roslyn,tannergooding/roslyn,genlu/roslyn,gafter/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,gafter/roslyn,jmarolf/roslyn,jmarolf/roslyn,panopticoncentral/roslyn,diryboy/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,sharwell/roslyn,reaction1989/roslyn,weltkante/roslyn,stephentoub/roslyn,aelij/roslyn,davkean/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,diryboy/roslyn,ErikSchierboom/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,dotnet/roslyn,sharwell/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,tmat/roslyn,jasonmalinowski/roslyn,genlu/roslyn,gafter/roslyn,diryboy/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,aelij/roslyn,jasonmalinowski/roslyn,CyrusNajmabadi/roslyn,aelij/roslyn,tmat/roslyn,mavasani/roslyn,eriawan/roslyn,eriawan/roslyn,dotnet/roslyn,davkean/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,heejaechang/roslyn,AmadeusW/roslyn,physhi/roslyn,brettfo/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,wvdd007/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,davkean/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,wvdd007/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,reaction1989/roslyn,panopticoncentral/roslyn,bartdesmet/roslyn,mavasani/roslyn,stephentoub/roslyn,bartdesmet/roslyn,tannergooding/roslyn,tmat/roslyn,weltkante/roslyn
src/Features/Core/Portable/TodoComments/ITodoCommentService.cs
src/Features/Core/Portable/TodoComments/ITodoCommentService.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// A TODO comment that has been found within the user's code. /// </summary> internal readonly struct TodoComment { public TodoCommentDescriptor Descriptor { get; } public string Message { get; } public int Position { get; } public TodoComment(TodoCommentDescriptor descriptor, string message, int position) : this() { Descriptor = descriptor; Message = message; Position = position; } internal TodoCommentData CreateSerializableData( Document document, SourceText text, SyntaxTree tree) { // make sure given position is within valid text range. var textSpan = new TextSpan(Math.Min(text.Length, Math.Max(0, this.Position)), 0); var location = tree.GetLocation(textSpan); var originalLineInfo = location.GetLineSpan(); var mappedLineInfo = location.GetMappedLineSpan(); return new TodoCommentData { Priority = this.Descriptor.Priority, Message = this.Message, DocumentId = document.Id, OriginalLine = originalLineInfo.StartLinePosition.Line, OriginalColumn = originalLineInfo.StartLinePosition.Character, OriginalFilePath = document.FilePath, MappedLine = mappedLineInfo.StartLinePosition.Line, MappedColumn = mappedLineInfo.StartLinePosition.Character, MappedFilePath = mappedLineInfo.GetMappedFilePathIfExist(), }; } } internal interface ITodoCommentService : ILanguageService { Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync(Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.TodoComments { /// <summary> /// A TODO comment that has been found within the user's code. /// </summary> internal readonly struct TodoComment { public TodoCommentDescriptor Descriptor { get; } public string Message { get; } public int Position { get; } public TodoComment(TodoCommentDescriptor descriptor, string message, int position) : this() { Descriptor = descriptor; Message = message; Position = position; } internal TodoCommentData CreateSerializableData( Document document, SourceText text, SyntaxTree tree) { // make sure given position is within valid text range. var textSpan = new TextSpan(Math.Min(text.Length, Math.Max(0, this.Position)), 0); var location = tree.GetLocation(textSpan); // var location = tree == null ? Location.Create(document.FilePath, textSpan, text.Lines.GetLinePositionSpan(textSpan)) : tree.GetLocation(textSpan); var originalLineInfo = location.GetLineSpan(); var mappedLineInfo = location.GetMappedLineSpan(); return new TodoCommentData { Priority = this.Descriptor.Priority, Message = this.Message, DocumentId = document.Id, OriginalLine = originalLineInfo.StartLinePosition.Line, OriginalColumn = originalLineInfo.StartLinePosition.Character, OriginalFilePath = document.FilePath, MappedLine = mappedLineInfo.StartLinePosition.Line, MappedColumn = mappedLineInfo.StartLinePosition.Character, MappedFilePath = mappedLineInfo.GetMappedFilePathIfExist(), }; } } internal interface ITodoCommentService : ILanguageService { Task<ImmutableArray<TodoComment>> GetTodoCommentsAsync(Document document, ImmutableArray<TodoCommentDescriptor> commentDescriptors, CancellationToken cancellationToken); } }
mit
C#
944fadfd31d9ee9856923c2058d9e851547c63c9
remove unnecessary comment
kjnilsson/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2
src/OnPremise/WebSite/Areas/Admin/ViewModels/UsersViewModel.cs
src/OnPremise/WebSite/Areas/Admin/ViewModels/UsersViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Thinktecture.IdentityServer.Web.Areas.Admin.ViewModels { public class UsersViewModel { private Repositories.IUserManagementRepository UserManagementRepository; public UsersViewModel(Repositories.IUserManagementRepository UserManagementRepository, string filter) { this.UserManagementRepository = UserManagementRepository; this.Filter = filter; if (String.IsNullOrEmpty(filter)) { Users = UserManagementRepository.GetUsers(); Total = Showing; } else { Users = UserManagementRepository.GetUsers(filter); Total = UserManagementRepository.GetUsers().Count(); } } public IEnumerable<string> Users { get; set; } public UserDeleteModel[] UsersDeleteList { get { return Users.Select(x => new UserDeleteModel { Username = x }).ToArray(); } } public string Filter { get; set; } public int Total { get; set; } public int Showing { get { return Users.Count(); } } } public class UserDeleteModel { public string Username { get; set; } public bool Delete { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Thinktecture.IdentityServer.Web.Areas.Admin.ViewModels { public class UsersViewModel { private Repositories.IUserManagementRepository UserManagementRepository; public UsersViewModel(Repositories.IUserManagementRepository UserManagementRepository, string filter) { // TODO: Complete member initialization this.UserManagementRepository = UserManagementRepository; this.Filter = filter; if (String.IsNullOrEmpty(filter)) { Users = UserManagementRepository.GetUsers(); Total = Showing; } else { Users = UserManagementRepository.GetUsers(filter); Total = UserManagementRepository.GetUsers().Count(); } } public IEnumerable<string> Users { get; set; } public UserDeleteModel[] UsersDeleteList { get { return Users.Select(x => new UserDeleteModel { Username = x }).ToArray(); } } public string Filter { get; set; } public int Total { get; set; } public int Showing { get { return Users.Count(); } } } public class UserDeleteModel { public string Username { get; set; } public bool Delete { get; set; } } }
bsd-3-clause
C#
6df1b60053f5ef54ce2b4a99f1a358f31c5414ec
Fix tests: version parsing failed against ES 1.4.0.Beta1
amyzheng424/elasticsearch-net,tkirill/elasticsearch-net,azubanov/elasticsearch-net,gayancc/elasticsearch-net,wawrzyn/elasticsearch-net,TheFireCookie/elasticsearch-net,starckgates/elasticsearch-net,KodrAus/elasticsearch-net,geofeedia/elasticsearch-net,robrich/elasticsearch-net,SeanKilleen/elasticsearch-net,abibell/elasticsearch-net,faisal00813/elasticsearch-net,junlapong/elasticsearch-net,wawrzyn/elasticsearch-net,KodrAus/elasticsearch-net,abibell/elasticsearch-net,jonyadamit/elasticsearch-net,UdiBen/elasticsearch-net,LeoYao/elasticsearch-net,DavidSSL/elasticsearch-net,junlapong/elasticsearch-net,adam-mccoy/elasticsearch-net,gayancc/elasticsearch-net,amyzheng424/elasticsearch-net,robertlyson/elasticsearch-net,geofeedia/elasticsearch-net,tkirill/elasticsearch-net,CSGOpenSource/elasticsearch-net,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,robertlyson/elasticsearch-net,abibell/elasticsearch-net,KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net,robertlyson/elasticsearch-net,robrich/elasticsearch-net,elastic/elasticsearch-net,SeanKilleen/elasticsearch-net,mac2000/elasticsearch-net,wawrzyn/elasticsearch-net,SeanKilleen/elasticsearch-net,azubanov/elasticsearch-net,robrich/elasticsearch-net,azubanov/elasticsearch-net,mac2000/elasticsearch-net,joehmchan/elasticsearch-net,adam-mccoy/elasticsearch-net,jonyadamit/elasticsearch-net,ststeiger/elasticsearch-net,gayancc/elasticsearch-net,joehmchan/elasticsearch-net,amyzheng424/elasticsearch-net,jonyadamit/elasticsearch-net,CSGOpenSource/elasticsearch-net,starckgates/elasticsearch-net,LeoYao/elasticsearch-net,geofeedia/elasticsearch-net,RossLieberman/NEST,joehmchan/elasticsearch-net,DavidSSL/elasticsearch-net,CSGOpenSource/elasticsearch-net,junlapong/elasticsearch-net,starckgates/elasticsearch-net,LeoYao/elasticsearch-net,cstlaurent/elasticsearch-net,elastic/elasticsearch-net,tkirill/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,mac2000/elasticsearch-net,ststeiger/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,ststeiger/elasticsearch-net,DavidSSL/elasticsearch-net,faisal00813/elasticsearch-net,UdiBen/elasticsearch-net
src/Tests/Nest.Tests.Integration/ElasticsearchConfiguration.cs
src/Tests/Nest.Tests.Integration/ElasticsearchConfiguration.cs
using System; using System.Diagnostics; using System.Linq; using Elasticsearch.Net.Connection.Thrift; using Elasticsearch.Net; namespace Nest.Tests.Integration { public static class ElasticsearchConfiguration { public static readonly string DefaultIndexPrefix = "nest_test_data-"; public static readonly string Host = "localhost"; public static readonly int MaxConnections = 20; public static readonly int NumberOfShards = 2; public static readonly int NumberOfReplicas = 1; public static readonly string DefaultIndex = DefaultIndexPrefix + Process.GetCurrentProcess().Id; private static Version _currentVersion; public static Version CurrentVersion { get { if (_currentVersion == null) _currentVersion = GetCurrentVersion(); return _currentVersion; } } public static Uri CreateBaseUri(int? port = null) { var host = Host; if (port != 9500 && Process.GetProcessesByName("fiddler").HasAny()) host = "ipv4.fiddler"; var uri = new UriBuilder("http", host, port.GetValueOrDefault(9200)).Uri; return uri; } public static ConnectionSettings Settings(int? port = null, Uri hostOverride = null) { return new ConnectionSettings(hostOverride ?? CreateBaseUri(port), ElasticsearchConfiguration.DefaultIndex) .SetMaximumAsyncConnections(MaxConnections) .DisableAutomaticProxyDetection(false) .UsePrettyResponses() .ExposeRawResponse(); } public static readonly Lazy<ElasticClient> Client = new Lazy<ElasticClient>(()=> new ElasticClient(Settings())); public static readonly Lazy<ElasticClient> ClientNoRawResponse = new Lazy<ElasticClient>(()=> new ElasticClient(Settings().ExposeRawResponse(false))); public static readonly Lazy<ElasticClient> ClientThatThrows = new Lazy<ElasticClient>(()=> new ElasticClient(Settings().ThrowOnElasticsearchServerExceptions())); public static readonly Lazy<ElasticClient> ThriftClient = new Lazy<ElasticClient>(()=> new ElasticClient(Settings(9500), new ThriftConnection(Settings(9500)))); public static string NewUniqueIndexName() { return DefaultIndex + "_" + Guid.NewGuid().ToString(); } public static Version GetCurrentVersion() { dynamic info = Client.Value.Raw.Info().Response; var versionString = (string)info.version.number; if (versionString.Contains("Beta")) versionString = string.Join(".", versionString.Split('.').Where(s => !s.StartsWith("Beta", StringComparison.OrdinalIgnoreCase))); var version = Version.Parse(versionString); return version; } } }
using System; using System.Diagnostics; using Elasticsearch.Net.Connection.Thrift; using Elasticsearch.Net; namespace Nest.Tests.Integration { public static class ElasticsearchConfiguration { public static readonly string DefaultIndexPrefix = "nest_test_data-"; public static readonly string Host = "localhost"; public static readonly int MaxConnections = 20; public static readonly int NumberOfShards = 2; public static readonly int NumberOfReplicas = 1; public static readonly string DefaultIndex = DefaultIndexPrefix + Process.GetCurrentProcess().Id; private static Version _currentVersion; public static Version CurrentVersion { get { if (_currentVersion == null) _currentVersion = GetCurrentVersion(); return _currentVersion; } } public static Uri CreateBaseUri(int? port = null) { var host = Host; if (port != 9500 && Process.GetProcessesByName("fiddler").HasAny()) host = "ipv4.fiddler"; var uri = new UriBuilder("http", host, port.GetValueOrDefault(9200)).Uri; return uri; } public static ConnectionSettings Settings(int? port = null, Uri hostOverride = null) { return new ConnectionSettings(hostOverride ?? CreateBaseUri(port), ElasticsearchConfiguration.DefaultIndex) .SetMaximumAsyncConnections(MaxConnections) .DisableAutomaticProxyDetection(false) .UsePrettyResponses() .ExposeRawResponse(); } public static readonly Lazy<ElasticClient> Client = new Lazy<ElasticClient>(()=> new ElasticClient(Settings())); public static readonly Lazy<ElasticClient> ClientNoRawResponse = new Lazy<ElasticClient>(()=> new ElasticClient(Settings().ExposeRawResponse(false))); public static readonly Lazy<ElasticClient> ClientThatThrows = new Lazy<ElasticClient>(()=> new ElasticClient(Settings().ThrowOnElasticsearchServerExceptions())); public static readonly Lazy<ElasticClient> ThriftClient = new Lazy<ElasticClient>(()=> new ElasticClient(Settings(9500), new ThriftConnection(Settings(9500)))); public static string NewUniqueIndexName() { return DefaultIndex + "_" + Guid.NewGuid().ToString(); } public static Version GetCurrentVersion() { dynamic info = Client.Value.Raw.Info().Response; var version = Version.Parse(info.version.number); return version; } } }
apache-2.0
C#
377f578c9c2cbfc65b4c561a46c12ef4ceac30bf
Revert "Make cookie valid for 30 days."
gyrosworkshop/Wukong,gyrosworkshop/Wukong
Wukong/Controllers/AuthController.cs
Wukong/Controllers/AuthController.cs
using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authentication; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Wukong.Models; namespace Wukong.Controllers { [Route("oauth")] public class AuthController : Controller { [HttpGet("all")] public IEnumerable<OAuthMethod> AllSchemes() { return new List<OAuthMethod>{ new OAuthMethod() { Scheme = "Microsoft", DisplayName = "Microsoft", Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}" }}; } [HttpGet("go/{any}")] public async Task SignIn(string any, string redirectUri = "/") { await HttpContext.ChallengeAsync( OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = redirectUri, IsPersistent = true }); } [HttpGet("signout")] public SignOutResult SignOut(string redirectUrl = "/") { return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authentication; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Wukong.Models; namespace Wukong.Controllers { [Route("oauth")] public class AuthController : Controller { [HttpGet("all")] public IEnumerable<OAuthMethod> AllSchemes() { return new List<OAuthMethod>{ new OAuthMethod() { Scheme = "Microsoft", DisplayName = "Microsoft", Url = $"/oauth/go/{OpenIdConnectDefaults.AuthenticationScheme}" }}; } [HttpGet("go/{any}")] public async Task SignIn(string any, string redirectUri = "/") { await HttpContext.ChallengeAsync( OpenIdConnectDefaults.AuthenticationScheme, new AuthenticationProperties { RedirectUri = redirectUri, IsPersistent = true, ExpiresUtc = System.DateTime.UtcNow.AddDays(30) }); } [HttpGet("signout")] public SignOutResult SignOut(string redirectUrl = "/") { return SignOut(new AuthenticationProperties { RedirectUri = redirectUrl }, CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme); } } }
mit
C#
522f6c127c6773cb5e7efc6fd6e5a8d8f9d34c5f
Add method to update specific layer only
isurakka/ecs
ECS/EntityComponentSystem.cs
ECS/EntityComponentSystem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private readonly EntityManager entityManager; private readonly SystemManager systemManager; private static readonly bool running64Bit; static EntityComponentSystem() { running64Bit = Environment.Is64BitProcess; } public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager { context = this }; } public Entity CreateEntity() => entityManager.CreateEntity(); public void AddSystem(System system, int layer = 0) => systemManager.AddSystem(system, layer); public void RemoveSystem(System system, int layer) => systemManager.RemoveSystem(system, layer); // TODO: Is this needed and is this right place for this method? public IEnumerable<Entity> FindEntities(Aspect aspect) => entityManager.GetEntitiesForAspect(aspect); public void Update(float deltaTime) { FlushChanges(); // 256 MB var noGc = GC.TryStartNoGCRegion(running64Bit ? 256000000L : 16000000L); foreach (var systems in systemManager.GetSystemsInLayerOrder()) { foreach (var system in systems) { system.Update(deltaTime); } FlushChanges(); } if (noGc) GC.EndNoGCRegion(); } public void UpdateSpecific(float deltaTime, int layer) { FlushChanges(); foreach (var system in systemManager.GetSystems(layer)) { system.Update(deltaTime); } FlushChanges(); } public void FlushChanges() { entityManager.FlushPending(); systemManager.FlushPendingChanges(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ECS { public class EntityComponentSystem { private readonly EntityManager entityManager; private readonly SystemManager systemManager; private static readonly bool running64Bit; static EntityComponentSystem() { running64Bit = Environment.Is64BitProcess; } public EntityComponentSystem() { entityManager = new EntityManager(); systemManager = new SystemManager { context = this }; } public Entity CreateEntity() => entityManager.CreateEntity(); public void AddSystem(System system, int layer = 0) => systemManager.AddSystem(system, layer); public void RemoveSystem(System system, int layer) => systemManager.RemoveSystem(system, layer); // TODO: Is this needed and is this right place for this method? public IEnumerable<Entity> FindEntities(Aspect aspect) => entityManager.GetEntitiesForAspect(aspect); public void Update(float deltaTime) { entityManager.FlushPending(); systemManager.FlushPendingChanges(); // 256 MB var noGc = GC.TryStartNoGCRegion(running64Bit ? 256000000L : 16000000L); foreach (var systems in systemManager.GetSystemsInLayerOrder()) { foreach (var system in systems) { system.Update(deltaTime); } systemManager.FlushPendingChanges(); // Add and remove entities before each system layer entityManager.FlushPending(); } if (noGc) GC.EndNoGCRegion(); } public void FlushChanges() { entityManager.FlushPending(); systemManager.FlushPendingChanges(); } } }
apache-2.0
C#
2167d6ae23482df5f5e09ec4b9a9f8d231352769
Remove ConsoleApplication used for quick testing
richardschris/EchoNestNET
EchoNestNET/GenreModel.cs
EchoNestNET/GenreModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace EchoNestNET { [JsonObject] public class Genre { [JsonProperty(PropertyName = "name")] public string name { get; set; } [JsonProperty(PropertyName = "description")] public string description { get; set; } [JsonProperty(PropertyName = "similarity")] public float similarity { get; set; } [JsonObject] public class Urls { [JsonProperty(PropertyName = "wikipedia_url")] public string wikipediaUrl { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace EchoNestNET { [JsonObject] public class Genre { [JsonProperty(PropertyName = "name")] public string name { get; set; } [JsonProperty(PropertyName = "description")] public string description { get; set; } [JsonProperty(PropertyName = "similarity")] public float similarity { get; set; } [JsonObject] public class Urls { [JsonProperty(PropertyName = "wikipedia_url")] public string wikipediaUrl { get; set; } } } }
apache-2.0
C#
f92b5a35a0fef96043b192bc853b4ec68ff203e0
Undo irrelevant change - original code worked as expected
JasonBock/csla,rockfordlhotka/csla,rockfordlhotka/csla,rockfordlhotka/csla,JasonBock/csla,MarimerLLC/csla,MarimerLLC/csla,JasonBock/csla,MarimerLLC/csla
Source/Csla.Blazor/CslaPolicy.cs
Source/Csla.Blazor/CslaPolicy.cs
//----------------------------------------------------------------------- // <copyright file="CslaPolicy.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Contains methods to manage CSLA permission policy information</summary> //----------------------------------------------------------------------- using System; namespace Csla.Blazor { /// <summary> /// Contains methods to manage CSLA permission policy information. /// </summary> public static class CslaPolicy { private static string PolicyPrefix = "Csla:"; /// <summary> /// Gets a string representing a CSLA permissions policy /// </summary> /// <param name="action">Authorization action</param> /// <param name="objectType">Business object type</param> /// <returns></returns> public static string GetPolicy(Rules.AuthorizationActions action, Type objectType) { var actionName = action.ToString(); var typeName = objectType.AssemblyQualifiedName; return $"{PolicyPrefix}{actionName}|{typeName}"; } /// <summary> /// Gets a permission requirement object representing /// a CSLA permissions policy /// </summary> /// <param name="policy">Permissions policy string</param> /// <param name="requirement">Permission requirement object</param> /// <returns>True if a requirement object was created</returns> public static bool TryGetPermissionRequirement(string policy, out CslaPermissionRequirement requirement) { if (policy.StartsWith(PolicyPrefix)) { var parts = policy.Substring(PolicyPrefix.Length).Split('|'); var action = (Rules.AuthorizationActions)Enum.Parse(typeof(Rules.AuthorizationActions), parts[0]); var type = Type.GetType(parts[1]); requirement = new CslaPermissionRequirement(action, type); return true; } else { requirement = null; return false; } } } }
//----------------------------------------------------------------------- // <copyright file="CslaPolicy.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. // Website: https://cslanet.com // </copyright> // <summary>Contains methods to manage CSLA permission policy information</summary> //----------------------------------------------------------------------- using System; namespace Csla.Blazor { /// <summary> /// Contains methods to manage CSLA permission policy information. /// </summary> public static class CslaPolicy { private static string PolicyPrefix = "Csla:"; /// <summary> /// Gets a string representing a CSLA permissions policy /// </summary> /// <param name="action">Authorization action</param> /// <param name="objectType">Business object type</param> /// <returns></returns> public static string GetPolicy(Rules.AuthorizationActions action, Type objectType) { var actionName = action.ToString(); var typeName = objectType.AssemblyQualifiedName; return $"{PolicyPrefix}{actionName}|{typeName}"; } /// <summary> /// Gets a permission requirement object representing /// a CSLA permissions policy /// </summary> /// <param name="policy">Permissions policy string</param> /// <param name="requirement">Permission requirement object</param> /// <returns>True if a requirement object was created</returns> public static bool TryGetPermissionRequirement(string policy, out CslaPermissionRequirement requirement) { if (policy.StartsWith(PolicyPrefix)) { policy = policy.Substring(PolicyPrefix.Length); var actionName = policy.Substring(0, policy.IndexOf('|')); var typeName = policy.Substring(policy.IndexOf('|') + 1); var action = (Rules.AuthorizationActions)Enum.Parse(typeof(Rules.AuthorizationActions), actionName); var type = Type.GetType(typeName); requirement = new CslaPermissionRequirement(action, type); return true; } else { requirement = null; return false; } } } }
mit
C#
0dfe02e6d0c4b763e7b78a0fecd4827ca40d4fef
Normalize line endings in ExceptionFactory
YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata
src/Atata.WebDriverExtras/Exceptions/ExceptionFactory.cs
src/Atata.WebDriverExtras/Exceptions/ExceptionFactory.cs
using OpenQA.Selenium; using System; using System.Text; namespace Atata { public static class ExceptionFactory { public static ArgumentException CreateForArgumentEmptyCollection(string parameterName) { return new ArgumentException("Collection should contain at least one element.", parameterName); } public static NoSuchElementException CreateForNoSuchElement(string elementName = null, By by = null) { string message = BuildElementErrorMessage("Unable to locate element", elementName, by); return new NoSuchElementException(message); } public static NotMissingElementException CreateForNotMissingElement(string elementName = null, By by = null) { string message = BuildElementErrorMessage("Able to locate element that should be missing", elementName, by); return new NotMissingElementException(message); } public static ArgumentException CreateForUnsupportedEnumValue<T>(T value, string paramName) where T : struct { string message = string.Format("Unsupported {0} enum value: {1}.", typeof(T).FullName, value); return new ArgumentException(message, paramName); } public static string BuildElementErrorMessage(string message, string elementName, By by) { StringBuilder builder = new StringBuilder(message); bool hasName = !string.IsNullOrWhiteSpace(elementName); bool hasBy = by != null; if (hasName || hasBy) { builder.Append(": "); if (hasName && hasBy) builder.AppendFormat("{0}. {1}", elementName, by); else if (!string.IsNullOrWhiteSpace(elementName)) builder.Append(elementName); else if (by != null) builder.Append(by); } return builder.ToString(); } } }
using OpenQA.Selenium; using System; using System.Text; namespace Atata { public static class ExceptionFactory { public static ArgumentException CreateForArgumentEmptyCollection(string parameterName) { return new ArgumentException("Collection should contain at least one element.", parameterName); } public static NoSuchElementException CreateForNoSuchElement(string elementName = null, By by = null) { string message = BuildElementErrorMessage("Unable to locate element", elementName, by); return new NoSuchElementException(message); } public static NotMissingElementException CreateForNotMissingElement(string elementName = null, By by = null) { string message = BuildElementErrorMessage("Able to locate element that should be missing", elementName, by); return new NotMissingElementException(message); } public static ArgumentException CreateForUnsupportedEnumValue<T>(T value, string paramName) where T : struct { string message = string.Format("Unsupported {0} enum value: {1}.", typeof(T).FullName, value); return new ArgumentException(message, paramName); } public static string BuildElementErrorMessage(string message, string elementName, By by) { StringBuilder builder = new StringBuilder(message); bool hasName = !string.IsNullOrWhiteSpace(elementName); bool hasBy = by != null; if (hasName || hasBy) { builder.Append(": "); if (hasName && hasBy) builder.AppendFormat("{0}. {1}", elementName, by); else if (!string.IsNullOrWhiteSpace(elementName)) builder.Append(elementName); else if (by != null) builder.Append(by); } return builder.ToString(); } } }
apache-2.0
C#
c2c9443cf677d4e34f20b95a93cd304bd453464d
Update AdUnit.cs
tiksn/TIKSN-Framework
TIKSN.Core/Advertising/AdUnit.cs
TIKSN.Core/Advertising/AdUnit.cs
namespace TIKSN.Advertising { public class AdUnit { public AdUnit(string provider, string applicationId, string adUnitId, bool isTest = false) { this.Provider = provider; this.ApplicationId = applicationId; this.AdUnitId = adUnitId; this.IsTest = isTest; } public string AdUnitId { get; } public string ApplicationId { get; } public bool IsTest { get; } public string Provider { get; } } }
namespace TIKSN.Advertising { public class AdUnit { public AdUnit(string provider, string applicationId, string adUnitId, bool isTest = false) { Provider = provider; ApplicationId = applicationId; AdUnitId = adUnitId; IsTest = isTest; } public string AdUnitId { get; } public string ApplicationId { get; } public bool IsTest { get; } public string Provider { get; } } }
mit
C#
05f06459e557ae136ac32a84afe37bf6a03c11be
simplify GitLink tasks
MahApps/MahApps.Metro.IconPacks
src/build/build.cake
src/build/build.cake
#tool "nuget:?package=gitlink" // Arguments var target = Argument("target", "Default"); var version = "1.0.0.0"; var configGitLink = new GitLinkSettings { RepositoryUrl = "https://github.com/MahApps/MahApps.Metro.IconPacks", Branch = "master", Configuration = "Release" }; // Tasks Task("GitLink") .Does(() => { GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET45"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET451"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET452"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET46"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET461"; GitLink("../../", configGitLink); }); Task("GitLink_dev") .Does(() => { configGitLink.Branch = "dev"; }); Task("UpdateAssemblyInfo") .Does(() => { var assemblyInfo = ParseAssemblyInfo("../GlobalAssemblyInfo.cs"); var newAssemblyInfoSettings = new AssemblyInfoSettings { Product = string.Format("MahApps.Metro.IconPacks {0}", version), Version = version, FileVersion = version, InformationalVersion = version, Copyright = string.Format("Copyright © MahApps.Metro 2011 - {0}", DateTime.Now.Year) }; CreateAssemblyInfo("../GlobalAssemblyInfo.cs", newAssemblyInfoSettings); }); Task("Build") .Does(() => { MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET45").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET451").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET452").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET46").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET461").UseToolVersion(MSBuildToolVersion.VS2015)); }); // Task Targets Task("Default").IsDependentOn("UpdateAssemblyInfo").IsDependentOn("Build").IsDependentOn("GitLink"); Task("dev").IsDependentOn("UpdateAssemblyInfo").IsDependentOn("Build").IsDependentOn("GitLink_dev").IsDependentOn("GitLink"); // Execution RunTarget(target);
#tool "nuget:?package=gitlink" // Arguments var target = Argument("target", "Default"); var version = "1.0.0.0"; var configGitLink = new GitLinkSettings { RepositoryUrl = "https://github.com/MahApps/MahApps.Metro.IconPacks", Branch = "master", Configuration = "Release" }; // Tasks Task("GitLink_master") .Does(() => { GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET45"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET451"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET452"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET46"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET461"; GitLink("../../", configGitLink); }); Task("GitLink_dev") .Does(() => { configGitLink.Branch = "dev"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET45"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET451"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET452"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET46"; GitLink("../../", configGitLink); configGitLink.Configuration = "Release_NET461"; GitLink("../../", configGitLink); }); Task("UpdateAssemblyInfo") .Does(() => { var assemblyInfo = ParseAssemblyInfo("../GlobalAssemblyInfo.cs"); var newAssemblyInfoSettings = new AssemblyInfoSettings { Product = string.Format("MahApps.Metro.IconPacks {0}", version), Version = version, FileVersion = version, InformationalVersion = version, Copyright = string.Format("Copyright © MahApps.Metro 2011 - {0}", DateTime.Now.Year) }; CreateAssemblyInfo("../GlobalAssemblyInfo.cs", newAssemblyInfoSettings); }); Task("Build") .Does(() => { MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET45").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET451").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET452").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET46").UseToolVersion(MSBuildToolVersion.VS2015)); MSBuild("../MahApps.Metro.IconPacks.sln", settings => settings.SetConfiguration("Release_NET461").UseToolVersion(MSBuildToolVersion.VS2015)); }); // Task Targets Task("Default").IsDependentOn("UpdateAssemblyInfo").IsDependentOn("Build").IsDependentOn("GitLink_master"); Task("dev").IsDependentOn("UpdateAssemblyInfo").IsDependentOn("Build").IsDependentOn("GitLink_dev"); // Execution RunTarget(target);
mit
C#
c00d247feff5573b93333db0cf5baa2dfda45e60
fix build 65 error
acolono/opentrigger-distributor,acolono/opentrigger-distributor
com.opentrigger.distributor/tests/PluginTests.cs
com.opentrigger.distributor/tests/PluginTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using com.opentrigger.distributord.Plugins; using NUnit.Core; using NUnit.Framework; namespace com.opentrigger.tests { [TestFixture] public class PluginTests { [Test] public void BuiltinDummy() { var dummy = typeof(DummyPlugin); Plugins.StartPlugins(new []{"--dummy"}); Console.WriteLine(string.Join(", ", Plugins.ActivatedPlugins.Keys.Select(k => k.FullName))); var activeDummy = Plugins.ActivatedPlugins[dummy] as DummyPlugin; Assert.IsNotNull(activeDummy); } private class FailingPlugin : IPlugin { public void Start(string[] cmdlineArgs) { if(cmdlineArgs.Contains("--failing")) throw new Exception("die"); } } [Test] public void Failing() { var name = typeof(FailingPlugin).FullName; var cnt = 0; try { Plugins.StartPlugins(new [] {"--failing"}); } catch (Exception e) { if (e.Message.Contains(name)) { Assert.AreEqual(e.InnerException?.Message,"die"); cnt++; } else { throw; } } Assert.AreEqual(cnt,1); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using com.opentrigger.distributord.Plugins; using NUnit.Core; using NUnit.Framework; namespace com.opentrigger.tests { [TestFixture] public class PluginTests { [Test] public void BuiltinDummy() { var dummy = typeof(DummyPlugin); Plugins.StartPlugins(new []{"--dummy"}); Console.WriteLine(string.Join(", ", Plugins.ActivatedPlugins.Keys.Select(k => k.FullName))); var activeDummy = Plugins.ActivatedPlugins[dummy] as DummyPlugin; Assert.IsNotNull(activeDummy); } private class FailingPlugin : IPlugin { public void Start(string[] cmdlineArgs) { throw new Exception("die"); } } [Test] public void Failing() { var name = typeof(FailingPlugin).FullName; var cnt = 0; try { Plugins.StartPlugins(new string[] { }); } catch (Exception e) { if (e.Message.Contains(name)) { Assert.AreEqual(e.InnerException?.Message,"die"); cnt++; } else { throw; } } Assert.AreEqual(cnt,1); } } }
mit
C#
32d15c58db1be0670d739e0d4da1f6098d224aba
Send Account model back for validation
SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice
src/SFA.DAS.EmployerApprenticeshipsService.Web/Orchestrators/EmployerAccountTransactionsOrchestrator.cs
src/SFA.DAS.EmployerApprenticeshipsService.Web/Orchestrators/EmployerAccountTransactionsOrchestrator.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using MediatR; using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccount; using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccountTransactions; using SFA.DAS.EmployerApprenticeshipsService.Domain; namespace SFA.DAS.EmployerApprenticeshipsService.Web.Orchestrators { public class EmployerAccountTransactionsOrchestrator { private readonly IMediator _mediator; public EmployerAccountTransactionsOrchestrator(IMediator mediator) { if (mediator == null) throw new ArgumentNullException(nameof(mediator)); _mediator = mediator; } public async Task<TransactionViewResult> GetAccountTransactions(int accountId) { var employerAccountResult = await _mediator.SendAsync(new GetEmployerAccountQuery { Id = accountId }); if (employerAccountResult == null) { return new TransactionViewResult(); } var data = await _mediator.SendAsync(new GetEmployerAccountTransactionsQuery {AccountId = accountId}); return new TransactionViewResult { Account = employerAccountResult.Account, Model = new TransactionViewModel { Data = data.Data } }; } } public class TransactionViewResult { public Account Account { get; set; } public TransactionViewModel Model { get; set; } } public class TransactionViewModel { public AggregationData Data { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using MediatR; using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccount; using SFA.DAS.EmployerApprenticeshipsService.Application.Queries.GetEmployerAccountTransactions; using SFA.DAS.EmployerApprenticeshipsService.Domain; namespace SFA.DAS.EmployerApprenticeshipsService.Web.Orchestrators { public class EmployerAccountTransactionsOrchestrator { private readonly IMediator _mediator; public EmployerAccountTransactionsOrchestrator(IMediator mediator) { if (mediator == null) throw new ArgumentNullException(nameof(mediator)); _mediator = mediator; } public async Task<TransactionViewResult> GetAccountTransactions(int accountId) { var employerAccountResult = await _mediator.SendAsync(new GetEmployerAccountQuery { Id = accountId }); if (employerAccountResult == null) { return new TransactionViewResult(); } var data = await _mediator.SendAsync(new GetEmployerAccountTransactionsQuery {AccountId = accountId}); return new TransactionViewResult { Account = null, Model = new TransactionViewModel { Data = data.Data } }; } } public class TransactionViewResult { public Account Account { get; set; } public TransactionViewModel Model { get; set; } } public class TransactionViewModel { public AggregationData Data { get; set; } } }
mit
C#
f8943c06701bc795e9ea7954a56f53e73bb05be8
make test pass.
fffej/codekatas,fffej/codekatas,fffej/codekatas
MineField/MineSweeperTest.cs
MineField/MineSweeperTest.cs
using NUnit.Framework; using FluentAssertions; namespace Fatvat.Katas.MineSweeper { [TestFixture] public class MineSweeperTest { [Test] public void TestSimplestMineField() { var mineField = new MineField("."); Assert.That(mineField.Show(), Is.EqualTo("0")); } [Test] public void OneMine() { var mineField = new MineField("*"); Assert.That(mineField.Show(), Is.EqualTo("*")); } } public class MineField { private readonly string m_MineField; public MineField(string mineField) { m_MineField = mineField; } public string Show() { return m_MineField[0] == '*' ? "*" : "0"; } } }
using NUnit.Framework; using FluentAssertions; namespace Fatvat.Katas.MineSweeper { [TestFixture] public class MineSweeperTest { [Test] public void TestSimplestMineField() { var mineField = new MineField("."); Assert.That(mineField.Show(), Is.EqualTo("0")); } [Test] public void OneMine() { var mineField = new MineField("*"); Assert.That(mineField.Show(), Is.EqualTo("*")); } } public class MineField { public MineField(string s) { } public string Show() { return "0"; } } }
mit
C#
6cce26d7bdf6a71594abcbe039bc47556f81c495
Fix highlight deserialization
synhershko/NElasticsearch,khalidabuhakmeh/NElasticsearch
NElasticsearch/Models/Hit.cs
NElasticsearch/Models/Hit.cs
using System.Collections.Generic; using System.Diagnostics; namespace NElasticsearch.Models { /// <summary> /// Individual hit response from ElasticSearch. /// </summary> [DebuggerDisplay("{_type} in {_index} id {_id}")] public class Hit<T> { public string _index { get; set; } public string _type { get; set; } public string _id { get; set; } public double? _score { get; set; } public T _source { get; set; } public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>(); public Dictionary<string, List<string>> highlight { get; set; } } }
using System.Collections.Generic; using System.Diagnostics; namespace NElasticsearch.Models { /// <summary> /// Individual hit response from ElasticSearch. /// </summary> [DebuggerDisplay("{_type} in {_index} id {_id}")] public class Hit<T> { public string _index { get; set; } public string _type { get; set; } public string _id { get; set; } public double? _score { get; set; } public T _source { get; set; } public Dictionary<string, IEnumerable<object>> fields = new Dictionary<string, IEnumerable<object>>(); public Dictionary<string, IEnumerable<string>> highlight; } }
apache-2.0
C#
93f9fb57c3e3444a044f3bd79394927b16990cb4
Sort input files and directories in subentries by path
DvdKhl/AVDump3,DvdKhl/AVDump3,DvdKhl/AVDump3
AVDump3Lib/Misc/FileTraversal.cs
AVDump3Lib/Misc/FileTraversal.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AVDump3Lib.Misc { public class FileTraversal { public static void Traverse(string path, bool includeSubFolders, Action<string> onFile, Action<Exception> onError) { try { if(File.Exists(path)) { onFile(path); return; } else if(Directory.Exists(path)) { TraverseDirectories(new[] { path }, includeSubFolders, onFile, onError); } } catch(Exception ex) { onError?.Invoke(ex); } } public static void Traverse(IEnumerable<string> fileSystemEntries, bool includeSubFolders, Action<string> onFile, Action<Exception> onError) { foreach(var path in fileSystemEntries.Where(path => !Directory.Exists(path) && !File.Exists(path))) { onError?.Invoke(new Exception("Path not found: " + path)); } foreach(var filePath in fileSystemEntries.Where(path => File.Exists(path))) { try { onFile(filePath); } catch(Exception ex) { onError?.Invoke(ex); } } TraverseDirectories(fileSystemEntries.Where(path => Directory.Exists(path)), includeSubFolders, onFile, onError); } public static void TraverseDirectories(IEnumerable<string> directoryPaths, bool includeSubFolders, Action<string> onFile, Action<Exception> onError) { foreach(var directoryPath in directoryPaths) { try { foreach(var filePath in Directory.EnumerateFiles(directoryPath).OrderBy(x => x)) { try { onFile(filePath); } catch(Exception ex) { onError?.Invoke(ex); } } if(includeSubFolders) TraverseDirectories(Directory.EnumerateDirectories(directoryPath).OrderBy(x => x), includeSubFolders, onFile, onError); } catch(UnauthorizedAccessException ex) { if(!Directory.Exists("Error")) Directory.CreateDirectory("Error"); File.AppendAllText( Path.Combine("Error", "UnauthorizedAccessExceptions.txt"), string.Format("{0} {1} \"{2}\"", Environment.Version.Build, DateTime.Now.ToString("s"), ex.Message) + Environment.NewLine ); } catch(Exception ex) { onError?.Invoke(ex); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace AVDump3Lib.Misc { public class FileTraversal { public static void Traverse(string path, bool includeSubFolders, Action<string> onFile, Action<Exception> onError) { try { if(File.Exists(path)) { onFile(path); return; } else if(Directory.Exists(path)) { TraverseDirectories(new[] { path }, includeSubFolders, onFile, onError); } } catch(Exception ex) { onError?.Invoke(ex); } } public static void Traverse(IEnumerable<string> fileSystemEntries, bool includeSubFolders, Action<string> onFile, Action<Exception> onError) { foreach(var path in fileSystemEntries.Where(path => !Directory.Exists(path) && !File.Exists(path))) { onError?.Invoke(new Exception("Path not found: " + path)); } foreach(var filePath in fileSystemEntries.Where(path => File.Exists(path))) { try { onFile(filePath); } catch(Exception ex) { onError?.Invoke(ex); } } TraverseDirectories(fileSystemEntries.Where(path => Directory.Exists(path)), includeSubFolders, onFile, onError); } public static void TraverseDirectories(IEnumerable<string> directoryPaths, bool includeSubFolders, Action<string> onFile, Action<Exception> onError) { foreach(var directoryPath in directoryPaths) { try { foreach(var filePath in Directory.EnumerateFiles(directoryPath)) { try { onFile(filePath); } catch(Exception ex) { onError?.Invoke(ex); } } if(includeSubFolders) TraverseDirectories(Directory.EnumerateDirectories(directoryPath), includeSubFolders, onFile, onError); } catch(UnauthorizedAccessException ex) { if(!Directory.Exists("Error")) Directory.CreateDirectory("Error"); File.AppendAllText( Path.Combine("Error", "UnauthorizedAccessExceptions.txt"), string.Format("{0} {1} \"{2}\"", Environment.Version.Build, DateTime.Now.ToString("s"), ex.Message) + Environment.NewLine ); } catch(Exception ex) { onError?.Invoke(ex); } } } } }
mit
C#
afb262323c3b26f21d5589c830b93cfdba1cdeda
improve performance
ruarai/Trigrad,ruarai/Trigrad
Trigrad/DataTypes/Barycentric.cs
Trigrad/DataTypes/Barycentric.cs
using System.Drawing; namespace Trigrad.DataTypes { public static class Barycentric { public static BarycentricCoordinates GetCoordinates(Point Pp, Point Pa, Point Pb, Point Pc) { double[] v0 = { Pb.X - Pa.X, Pb.Y - Pa.Y }; double[] v1 = { Pc.X - Pa.X, Pc.Y - Pa.Y }; double[] v2 = { Pp.X - Pa.X, Pp.Y - Pa.Y }; double d00 = dotProduct(v0, v0); double d01 = dotProduct(v0, v1); double d11 = dotProduct(v1, v1); double d20 = dotProduct(v2, v0); double d21 = dotProduct(v2, v1); double denom = d00 * d11 - d01 * d01; double v = ((d11 * d20 - d01 * d21) / denom); double w = ((d00 * d21 - d01 * d20) / denom); double u = (1.0f - v - w); return new BarycentricCoordinates(u, v, w); } public static bool ValidCoords(BarycentricCoordinates coords) { return coords.U >= 0 && coords.V >= 0 && coords.W >= 0; } private static double dotProduct(double[] vec1, double[] vec2) { return vec1[0]*vec2[0] + vec1[1]*vec2[1]; } } public struct BarycentricCoordinates { public BarycentricCoordinates(double u, double v, double w) { U = u; V = v; W = w; } public double U; public double V; public double W; } }
using System.Drawing; namespace Trigrad.DataTypes { public static class Barycentric { public static BarycentricCoordinates GetCoordinates(Point Pp, Point Pa, Point Pb, Point Pc) { double[] p = { Pp.X, Pp.Y }; double[] a = { Pa.X, Pa.Y }; double[] b = { Pb.X, Pb.Y }; double[] c = { Pc.X, Pc.Y }; double[] v0 = { b[0] - a[0], b[1] - a[1] }; double[] v1 = { c[0] - a[0], c[1] - a[1] }; double[] v2 = { p[0] - a[0], p[1] - a[1] }; double d00 = dotProduct(v0, v0); double d01 = dotProduct(v0, v1); double d11 = dotProduct(v1, v1); double d20 = dotProduct(v2, v0); double d21 = dotProduct(v2, v1); double denom = d00 * d11 - d01 * d01; double v = ((d11 * d20 - d01 * d21) / denom); double w = ((d00 * d21 - d01 * d20) / denom); double u = (1.0f - v - w); return new BarycentricCoordinates(u, v, w); } public static bool ValidCoords(BarycentricCoordinates coords) { return coords.U >= 0 && coords.V >= 0 && coords.W >= 0; } private static double dotProduct(double[] vec1, double[] vec2) { return vec1[0]*vec2[0] + vec1[1]*vec2[1]; } } public struct BarycentricCoordinates { public BarycentricCoordinates(double u, double v, double w) { U = u; V = v; W = w; } public double U; public double V; public double W; } }
mit
C#
2639b197e2394b6aea1d3dfc8435dd7c0cd0acc6
Support for custom watch expressions
openmedicus/dbus-sharp,arfbtwn/dbus-sharp,arfbtwn/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,Tragetaschen/dbus-sharp,mono/dbus-sharp,openmedicus/dbus-sharp
src/Monitor.cs
src/Monitor.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr = Address.SessionBus; if (args.Length == 1) { string arg = args[0]; switch (arg) { case "--system": addr = Address.SystemBus; break; case "--session": addr = Address.SessionBus; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--system | --session] [watch expressions]"); return; } } Connection conn = new Connection (false); conn.Open (addr); conn.Authenticate (); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; Bus bus = conn.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; bus.Hello (); //hack to process the NameAcquired signal synchronously conn.HandleSignal (conn.ReadMessage ()); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); //custom match rules if (args.Length > 1) for (int i = 1 ; i != args.Length ; i++) bus.AddMatch (args[i]); while (true) { Message msg = conn.ReadMessage (); Console.WriteLine ("Message:"); Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine ("\t" + hf.Code + ": " + hf.Value); foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields) Console.WriteLine ("\t" + field.Key + ": " + field.Value); if (msg.Body != null) { Console.WriteLine ("\tBody:"); MessageReader reader = new MessageReader (msg); //TODO: this needs to be done more intelligently try { foreach (DType dtype in msg.Signature.Data) { if (dtype == DType.Invalid) continue; object arg; reader.GetValue (dtype, out arg); Console.WriteLine ("\t\t" + dtype + ": " + arg); } } catch { Console.WriteLine ("\t\tmonitor is too dumb to decode message body"); } } Console.WriteLine (); } } }
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System; using System.Collections.Generic; using NDesk.DBus; using org.freedesktop.DBus; public class ManagedDBusTest { public static void Main (string[] args) { string addr = Address.SessionBus; if (args.Length == 1) { string arg = args[0]; switch (arg) { case "--system": addr = Address.SystemBus; break; case "--session": addr = Address.SessionBus; break; default: Console.Error.WriteLine ("Usage: monitor.exe [--system | --session]"); return; } } Connection conn = new Connection (false); conn.Open (addr); conn.Authenticate (); ObjectPath opath = new ObjectPath ("/org/freedesktop/DBus"); string name = "org.freedesktop.DBus"; Bus bus = conn.GetObject<Bus> (name, opath); bus.NameAcquired += delegate (string acquired_name) { Console.WriteLine ("NameAcquired: " + acquired_name); }; bus.Hello (); //hack to process the NameAcquired signal synchronously conn.HandleSignal (conn.ReadMessage ()); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Signal)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodCall)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.MethodReturn)); bus.AddMatch (MessageFilter.CreateMatchRule (MessageType.Error)); while (true) { Message msg = conn.ReadMessage (); Console.WriteLine ("Message:"); Console.WriteLine ("\t" + "Type: " + msg.Header.MessageType); //foreach (HeaderField hf in msg.HeaderFields) // Console.WriteLine ("\t" + hf.Code + ": " + hf.Value); foreach (KeyValuePair<FieldCode,object> field in msg.Header.Fields) Console.WriteLine ("\t" + field.Key + ": " + field.Value); if (msg.Body != null) { Console.WriteLine ("\tBody:"); MessageReader reader = new MessageReader (msg); //TODO: this needs to be done more intelligently try { foreach (DType dtype in msg.Signature.Data) { if (dtype == DType.Invalid) continue; object arg; reader.GetValue (dtype, out arg); Console.WriteLine ("\t\t" + dtype + ": " + arg); } } catch { Console.WriteLine ("\t\tmonitor is too dumb to decode message body"); } } Console.WriteLine (); } } }
mit
C#