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
193d6683ecc44068b679ec2d85f3147b636c6ea9
Implement disposable pattern to satisfy Sonar.
ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog,ivanpointer/NuLog
Take2/NuLog/Targets/SmtpClientShim.cs
Take2/NuLog/Targets/SmtpClientShim.cs
/* © 2017 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using System.Net; using System.Net.Mail; namespace NuLog.Targets { /// <summary> /// A shim to the real SmtpClient. /// </summary> public class SmtpClientShim : ISmtpClient { /// <summary> /// The SMTP client this shim wraps. /// </summary> private readonly SmtpClient smtpClient; public SmtpClientShim() { this.smtpClient = new SmtpClient(); } public void Send(MailMessage mailMessage) { this.smtpClient.Send(mailMessage); } public void SetCredentials(string userName, string password) { this.smtpClient.Credentials = new NetworkCredential(userName, password); } public void SetEnableSsl(bool enableSsl) { this.smtpClient.EnableSsl = enableSsl; } public void SetPickupDirectoryLocation(string pickupDirectoryLocation) { this.smtpClient.PickupDirectoryLocation = pickupDirectoryLocation; } public void SetSmtpDeliveryMethod(SmtpDeliveryMethod smtpDeliveryMethod) { this.smtpClient.DeliveryMethod = smtpDeliveryMethod; } public void SetSmtpPort(int port) { this.smtpClient.Port = port; } public void SetSmtpServer(string smtpServer) { this.smtpClient.Host = smtpServer; } public void SetTimeout(int timeout) { this.smtpClient.Timeout = timeout; } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { #if !PRENET4 this.smtpClient.Dispose(); #endif } disposedValue = true; } } // This code added to correctly implement the disposable pattern. public void Dispose() { // Do not change this code. Put cleanup code in Dispose(bool disposing) above. Dispose(true); } #endregion IDisposable Support } }
/* © 2017 Ivan Pointer MIT License: https://github.com/ivanpointer/NuLog/blob/master/LICENSE Source on GitHub: https://github.com/ivanpointer/NuLog */ using System.Net; using System.Net.Mail; namespace NuLog.Targets { /// <summary> /// A shim to the real SmtpClient. /// </summary> public class SmtpClientShim : ISmtpClient { /// <summary> /// The SMTP client this shim wraps. /// </summary> private readonly SmtpClient smtpClient; public SmtpClientShim() { this.smtpClient = new SmtpClient(); } public void Dispose() { #if !PRENET4 this.smtpClient.Dispose(); #endif } public void Send(MailMessage mailMessage) { this.smtpClient.Send(mailMessage); } public void SetCredentials(string userName, string password) { this.smtpClient.Credentials = new NetworkCredential(userName, password); } public void SetEnableSsl(bool enableSsl) { this.smtpClient.EnableSsl = enableSsl; } public void SetPickupDirectoryLocation(string pickupDirectoryLocation) { this.smtpClient.PickupDirectoryLocation = pickupDirectoryLocation; } public void SetSmtpDeliveryMethod(SmtpDeliveryMethod smtpDeliveryMethod) { this.smtpClient.DeliveryMethod = smtpDeliveryMethod; } public void SetSmtpPort(int port) { this.smtpClient.Port = port; } public void SetSmtpServer(string smtpServer) { this.smtpClient.Host = smtpServer; } public void SetTimeout(int timeout) { this.smtpClient.Timeout = timeout; } } }
mit
C#
c1a12413848b6cc6181f87d8bf18cef5246c7ee2
Change Order of Loading Styles
tommcclean/PortalCMS,tommcclean/PortalCMS,tommcclean/PortalCMS
Portal.CMS.Web/Views/Shared/_Layout.cshtml
Portal.CMS.Web/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en-gb"> <head> <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <meta name="description" content="@SettingHelper.Get("Description Meta Tag")"> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Administration/Framework") @Styles.Render("~/Resources/CSS/PageBuilder/Framework") @Styles.Render("~/Resources/CSS/Framework") @if (UserHelper.IsAdmin) { @Styles.Render("~/Resources/CSS/Bootstrap/Tour") @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration") } <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" /> @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body> @Html.Partial("_NavBar") @Html.Partial("_Administration") @RenderBody() @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>
<!DOCTYPE html> <html lang="en-gb"> <head> <title>@SettingHelper.Get("Website Name"): @ViewBag.Title</title> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0" /> <meta name="description" content="@SettingHelper.Get("Description Meta Tag")"> @RenderSection("Styles", false) @Styles.Render("~/Resources/CSS/Bootstrap") @Styles.Render("~/Resources/CSS/FontAwesome") @Styles.Render("~/Resources/CSS/Administration/Framework") @Styles.Render("~/Resources/CSS/PageBuilder/Framework") @Styles.Render("~/Resources/CSS/Framework") @Scripts.Render("~/Resources/JavaScript/JQuery") @Scripts.Render("~/Resources/JavaScript/JQueryUI") @RenderSection("HEADScripts", false) @Html.Partial("_Analytics") </head> <body> @Html.Partial("_NavBar") @Html.Partial("_Administration") @RenderBody() @if (UserHelper.IsAdmin) { @Styles.Render("~/Resources/CSS/Bootstrap/Tour") @Styles.Render("~/Resources/CSS/PageBuilder/Framework/Administration") } <link href="@Url.Action("Render", "Theme", new { area = "Builder" })" rel="stylesheet" type="text/css" /> @Html.Partial("_DOMScripts") @RenderSection("DOMScripts", false) </body> </html>
mit
C#
e39f219acb7e55683f1dd009f75f351216038fbf
Update UserController.cs
barld/project5_6,barld/project5_6,barld/project5_6
Webshop/Controllers/UserController.cs
Webshop/Controllers/UserController.cs
using MVC.View; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webshop.Models; using DataModels; using MVC; namespace Webshop.Controllers { public class UserController : MVC.Controller.Controller { private AuthModule Auth; private readonly Context context; public UserController() { context = new Context(); } public override void AfterConstruct() { Auth = new AuthModule(Session, context); } public ViewObject PostLogin() { var data = GetBodyFromJson<User>(); return Json(Auth.Login(data)); } public bool PutLogout() { return Auth.Logout(); } public ViewObject PostRegister() { var user = GetBodyFromJson<User>(); return Json(Auth.Register(user)); } public ViewObject GetStatus() { return Json(this.Auth.LoginStatus()); } public ViewObject GetOrders() { if (Auth.LoggedIn) { User user = Auth.CurrentUser; return Json(context.Orders.GetAllByEmail(user.Email).Result); } else { return Json("user not logged in"); } } public ViewObject PostUser() { User user = this.GetBodyFromJson<User>(); context.Users.Insert(user).Wait(); return Json(user); } } }
using MVC.View; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Webshop.Models; using DataModels; using MVC; namespace Webshop.Controllers { public class UserController : MVC.Controller.Controller { private AuthModule Auth; private readonly Context context; public UserController() { context = new Context(); } public override void AfterConstruct() { Auth = new AuthModule(Session, context); } public ViewObject PostLogin() { var data = GetBodyFromJson<User>(); return Json(Auth.Login(data)); } public bool PutLogout() { return Auth.Logout(); } public ViewObject PostRegister() { var user = GetBodyFromJson<User>(); return Json(Auth.Register(user)); } public ViewObject GetStatus() { return Json(this.Auth.LoginStatus()); } public ViewObject GetOrders() { if (Auth.LoggedIn) { User user = Auth.CurrentUser; return Json(context.Orders.GetAllByEmail(user.Email).Result); } else { return Json("user not logged in"); } public ViewObject PostUser() { User user = this.GetBodyFromJson<User>(); context.Users.Insert(user).Wait(); return Json(user); } } }
mit
C#
a4d33a69461545c44c536eebd83b63a68c5f85b4
add DoubleSidenize()
TakeAsh/cs-WpfUtility
WpfUtility/Model3DExtensionMethods.cs
WpfUtility/Model3DExtensionMethods.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media.Media3D; namespace WpfUtility { public static class Model3DExtensionMethods { public static object GetTag(this Model3D model) { return model.GetValue(FrameworkElement.TagProperty); } public static void SetTag(this Model3D model, object value) { model.SetValue(FrameworkElement.TagProperty, value); } public static Model3DGroup ToModel3DGroup( this IEnumerable<Model3D> source, Transform3D transform = null ) { if (source == null || source.Count() == 0) { return null; } return new Model3DGroup() { Children = new Model3DCollection(source), Transform = transform, }; } public static ModelVisual3D ToModelVisual3D( this Model3D model, Transform3D transform = null ) { if (model == null) { return null; } return new ModelVisual3D() { Content = model, Transform = transform, }; } public static ModelVisual3D ToModelVisual3D( this IEnumerable<Model3D> source, Transform3D transform = null ) { if (source == null || source.Count() == 0) { return null; } return source.ToModel3DGroup() .ToModelVisual3D(transform); } /// <summary> /// Change BackMaterial automatically when Material is changed. /// </summary> /// <param name="model">Model to be DoubleSidenized</param> public static void DoubleSidenize(this GeometryModel3D model) { model.AddPropertyChanged(GeometryModel3D.MaterialProperty, OnMaterialChanged); model.BackMaterial = model.Material; } private static void OnMaterialChanged(object sender, EventArgs e) { var model = sender as GeometryModel3D; if (model == null) { return; } model.BackMaterial = model.Material; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media.Media3D; namespace WpfUtility { public static class Model3DExtensionMethods { public static object GetTag(this Model3D model) { return model.GetValue(FrameworkElement.TagProperty); } public static void SetTag(this Model3D model, object value) { model.SetValue(FrameworkElement.TagProperty, value); } public static Model3DGroup ToModel3DGroup( this IEnumerable<Model3D> source, Transform3D transform = null ) { if (source == null || source.Count() == 0) { return null; } return new Model3DGroup() { Children = new Model3DCollection(source), Transform = transform, }; } public static ModelVisual3D ToModelVisual3D( this Model3D model, Transform3D transform = null ) { if (model == null) { return null; } return new ModelVisual3D() { Content = model, Transform = transform, }; } public static ModelVisual3D ToModelVisual3D( this IEnumerable<Model3D> source, Transform3D transform = null ) { if (source == null || source.Count() == 0) { return null; } return source.ToModel3DGroup() .ToModelVisual3D(transform); } } }
mit
C#
cb24419d275565b897b724618e31c4484f55bcea
fix link to Players view in navigation.
saxx/Wuzlstats-2014,afuersch/Wuzlstats-2014,afuersch/Wuzlstats-2014,saxx/Wuzlstats-2014
WuzlStats/Views/Shared/_Layout.cshtml
WuzlStats/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <meta http-equiv="refresh" content="3600"> <title>@(ViewBag.Title ?? "Wuzlstats")</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Wuzlstats", "Index", "Home", null, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#" onclick="window.location = '/Players';">Players</a></li> </ul> <ul class="nav navbar-nav pull-right"> <li><a href="http://saxx.github.io/Wuzlstats/">Project Website</a></li> <li><a href="https://github.com/saxx/Wuzlstats">Wuzlstats on GitHub</a></li> </ul> </div> </div> </div> <div class="container"> @RenderBody() </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width" /> <meta http-equiv="refresh" content="3600"> <title>@(ViewBag.Title ?? "Wuzlstats")</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <div class="navbar navbar-inverse navbar-fixed-top"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> @Html.ActionLink("Wuzlstats", "Index", "Home", null, new { @class = "navbar-brand" }) </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#" onclick="window.location = 'Players';">Players</a></li> </ul> <ul class="nav navbar-nav pull-right"> <li><a href="http://saxx.github.io/Wuzlstats/">Project Website</a></li> <li><a href="https://github.com/saxx/Wuzlstats">Wuzlstats on GitHub</a></li> </ul> </div> </div> </div> <div class="container"> @RenderBody() </div> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
apache-2.0
C#
6f0dd4aa39f020b1ac1516fadaad701f2c5f3413
Implement aspect attributes
sakapon/Samples-2017
ProxySample/CrossCuttingConsole/Aspects.cs
ProxySample/CrossCuttingConsole/Aspects.cs
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Transactions; namespace CrossCuttingConsole { public class TraceLogAttribute : AspectAttribute { public override IMethodReturnMessage Invoke(Func<IMethodReturnMessage> baseInvoke, MarshalByRefObject target, IMethodCallMessage methodCall) { var methodLog = $"{methodCall.MethodBase.DeclaringType.Name}.{methodCall.MethodName}({string.Join(", ", methodCall.InArgs)})"; Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: Begin: {methodLog}"); var result = baseInvoke(); if (result.Exception == null) Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: Success: {methodLog}"); else { Console.WriteLine($"{DateTime.Now:HH:mm:ss.fff}: Error: {methodLog}"); Console.WriteLine(result.Exception); } return result; } } public class TransactionScopeAttribute : AspectAttribute { public TransactionScopeOption TransactionScopeOption { get; } public TransactionOptions TransactionOptions { get; } public TransactionScopeAttribute( TransactionScopeOption scopeOption = TransactionScopeOption.Required, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, double timeoutInSeconds = 30) { TransactionScopeOption = scopeOption; TransactionOptions = new TransactionOptions { IsolationLevel = isolationLevel, Timeout = TimeSpan.FromSeconds(timeoutInSeconds), }; } public override IMethodReturnMessage Invoke(Func<IMethodReturnMessage> baseInvoke, MarshalByRefObject target, IMethodCallMessage methodCall) { using (var scope = new TransactionScope(TransactionScopeOption, TransactionOptions)) { var result = baseInvoke(); scope.Complete(); return result; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Transactions; namespace CrossCuttingConsole { public class TraceLogAttribute : AspectAttribute { public override IMethodReturnMessage Invoke(Func<IMethodReturnMessage> baseInvoke, MarshalByRefObject target, IMethodCallMessage methodCall) { throw new NotImplementedException(); } } public class TransactionScopeAttribute : AspectAttribute { public TransactionScopeOption TransactionScopeOption { get; } public TransactionOptions TransactionOptions { get; } public TransactionScopeAttribute( TransactionScopeOption scopeOption = TransactionScopeOption.Required, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, double timeoutInSeconds = 30) { TransactionScopeOption = scopeOption; TransactionOptions = new TransactionOptions { IsolationLevel = isolationLevel, Timeout = TimeSpan.FromSeconds(timeoutInSeconds), }; } public override IMethodReturnMessage Invoke(Func<IMethodReturnMessage> baseInvoke, MarshalByRefObject target, IMethodCallMessage methodCall) { throw new NotImplementedException(); } } }
mit
C#
f1078a447c9832c30f899e3443dc5dbf9d1e3f4c
fix Android BaseUrl
teefresh/xamarin-forms-samples-1,williamsrz/xamarin-forms-samples,williamsrz/xamarin-forms-samples,KiranKumarAlugonda/xamarin-forms-samples,conceptdev/xamarin-forms-samples,JakeShanley/xamarin-forms-samples,fabianwilliams/xamarin-forms-samples,pabloescribanoloza/xamarin-forms-samples-1,reverence12389/xamarin-forms-samples-1,pabloescribanoloza/xamarin-forms-samples-1,reverence12389/xamarin-forms-samples-1,JakeShanley/xamarin-forms-samples,teefresh/xamarin-forms-samples-1,KiranKumarAlugonda/xamarin-forms-samples,biste5/xamarin-forms-samples-1,fabianwilliams/xamarin-forms-samples,biste5/xamarin-forms-samples-1,conceptdev/xamarin-forms-samples
RestaurantGuide/Android/BaseUrl_Android.cs
RestaurantGuide/Android/BaseUrl_Android.cs
using System; using Xamarin.Forms; using RestaurantGuide.Android; [assembly: Dependency (typeof (BaseUrl_Android))] namespace RestaurantGuide.Android { public class BaseUrl_Android : IBaseUrl { #region IBaseUrl implementation public string Get () { throw new NotImplementedException ("Once bug is fixed in Xamarin.Forms, implement this!"); } #endregion } }
using System; using Xamarin.Forms; using RestaurantGuide.Android; [assembly: Dependency (typeof (BaseUrl_Android))] namespace RestaurantGuide.Android { public class BaseUrl_Android : IBaseUrl { #region IBaseUrl implementation public string Get () { return NotImplementedException ("Once bug is fixed in Xamarin.Forms, implement this!"); } #endregion } }
mit
C#
297c25f1ae1e6f0a9abd066e86f00946d9e02a0c
Fix FrameworkActionContainer only accepting a single child
peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,ppy/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Input/FrameworkActionContainer.cs
osu.Framework/Input/FrameworkActionContainer.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input.Bindings; namespace osu.Framework.Input { public class FrameworkActionContainer : KeyBindingContainer<FrameworkAction> { public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(new[] { InputKey.Control, InputKey.F1 }, FrameworkAction.ToggleDrawVisualiser), new KeyBinding(new[] { InputKey.Control, InputKey.F11 }, FrameworkAction.CycleFrameStatistics), new KeyBinding(new[] { InputKey.Control, InputKey.F10 }, FrameworkAction.ToggleLogOverlay), new KeyBinding(new[] { InputKey.Alt, InputKey.Enter }, FrameworkAction.ToggleFullscreen), }; protected override bool Prioritised => true; protected override IEnumerable<Drawable> KeyBindingInputQueue => base.KeyBindingInputQueue.Prepend(Children.First()); } public enum FrameworkAction { CycleFrameStatistics, ToggleDrawVisualiser, ToggleLogOverlay, ToggleFullscreen } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Framework.Graphics; using osu.Framework.Input.Bindings; namespace osu.Framework.Input { public class FrameworkActionContainer : KeyBindingContainer<FrameworkAction> { public override IEnumerable<KeyBinding> DefaultKeyBindings => new[] { new KeyBinding(new[] { InputKey.Control, InputKey.F1 }, FrameworkAction.ToggleDrawVisualiser), new KeyBinding(new[] { InputKey.Control, InputKey.F11 }, FrameworkAction.CycleFrameStatistics), new KeyBinding(new[] { InputKey.Control, InputKey.F10 }, FrameworkAction.ToggleLogOverlay), new KeyBinding(new[] { InputKey.Alt, InputKey.Enter }, FrameworkAction.ToggleFullscreen), }; protected override bool Prioritised => true; protected override IEnumerable<Drawable> KeyBindingInputQueue => base.KeyBindingInputQueue.Prepend(Child); } public enum FrameworkAction { CycleFrameStatistics, ToggleDrawVisualiser, ToggleLogOverlay, ToggleFullscreen } }
mit
C#
dbcabfb6ac14a5940e5d64da57a5d8198ec00eb6
Remove ManiaAction.Specia2
peppy/osu,DrabWeb/osu,naoey/osu,NeoAdonis/osu,naoey/osu,peppy/osu-new,ppy/osu,Nabile-Rahmani/osu,johnneijzen/osu,ZLima12/osu,ppy/osu,DrabWeb/osu,Frontear/osuKyzer,ppy/osu,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,johnneijzen/osu,peppy/osu,NeoAdonis/osu,naoey/osu,EVAST9919/osu,EVAST9919/osu,UselessToucan/osu,2yangk23/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ZLima12/osu,UselessToucan/osu,smoogipooo/osu,peppy/osu,2yangk23/osu
osu.Game.Rulesets.Mania/ManiaInputManager.cs
osu.Game.Rulesets.Mania/ManiaInputManager.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania { public class ManiaInputManager : RulesetInputManager<ManiaAction> { public ManiaInputManager(RulesetInfo ruleset, int variant) : base(ruleset, variant, SimultaneousBindingMode.Unique) { } } public enum ManiaAction { [Description("Special")] Special = 1, [Description("Key 1")] Key1 = 1000, [Description("Key 2")] Key2, [Description("Key 3")] Key3, [Description("Key 4")] Key4, [Description("Key 5")] Key5, [Description("Key 6")] Key6, [Description("Key 7")] Key7, [Description("Key 8")] Key8, [Description("Key 9")] Key9 } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.ComponentModel; using osu.Framework.Input.Bindings; using osu.Game.Rulesets.UI; namespace osu.Game.Rulesets.Mania { public class ManiaInputManager : RulesetInputManager<ManiaAction> { public ManiaInputManager(RulesetInfo ruleset, int variant) : base(ruleset, variant, SimultaneousBindingMode.Unique) { } } public enum ManiaAction { [Description("Special")] Special, [Description("Special")] Specia2, [Description("Key 1")] Key1 = 1000, [Description("Key 2")] Key2, [Description("Key 3")] Key3, [Description("Key 4")] Key4, [Description("Key 5")] Key5, [Description("Key 6")] Key6, [Description("Key 7")] Key7, [Description("Key 8")] Key8, [Description("Key 9")] Key9 } }
mit
C#
cb2d1f3f04ae864b330bd2470e5769bb6839536b
Use horizontally symmetrical padding rather than margin
smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,ppy/osu
osu.Game/Overlays/Settings/SettingsHeader.cs
osu.Game/Overlays/Settings/SettingsHeader.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Localisation; using osu.Game.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Overlays.Settings { public class SettingsHeader : Container { private readonly LocalisableString heading; private readonly LocalisableString subheading; public SettingsHeader(LocalisableString heading, LocalisableString subheading) { this.heading = heading; this.subheading = subheading; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Children = new Drawable[] { new OsuTextFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Padding = new MarginPadding { Horizontal = SettingsPanel.CONTENT_MARGINS, Top = Toolbar.Toolbar.TOOLTIP_HEIGHT, Bottom = 30 } }.With(flow => { flow.AddText(heading, header => header.Font = OsuFont.TorusAlternate.With(size: 40)); flow.NewLine(); flow.AddText(subheading, subheader => { subheader.Colour = colourProvider.Content2; subheader.Font = OsuFont.GetFont(size: 18); }); }) }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Localisation; using osu.Game.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Overlays.Settings { public class SettingsHeader : Container { private readonly LocalisableString heading; private readonly LocalisableString subheading; public SettingsHeader(LocalisableString heading, LocalisableString subheading) { this.heading = heading; this.subheading = subheading; } [BackgroundDependencyLoader] private void load(OverlayColourProvider colourProvider) { RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Children = new Drawable[] { new OsuTextFlowContainer { AutoSizeAxes = Axes.Y, RelativeSizeAxes = Axes.X, Margin = new MarginPadding { Left = SettingsPanel.CONTENT_MARGINS, Top = Toolbar.Toolbar.TOOLTIP_HEIGHT, Bottom = 30 } }.With(flow => { flow.AddText(heading, header => header.Font = OsuFont.TorusAlternate.With(size: 40)); flow.NewLine(); flow.AddText(subheading, subheader => { subheader.Colour = colourProvider.Content2; subheader.Font = OsuFont.GetFont(size: 18); }); }) }; } } }
mit
C#
ecdc89ca0ad41887999b261c3e18d0edbf5b0256
Fix comment
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer
Client/Systems/ExternalSeat/ExternalSeatSystem.cs
Client/Systems/ExternalSeat/ExternalSeatSystem.cs
using LunaClient.Events; namespace LunaClient.Systems.ExternalSeat { /// <summary> /// This system handles the events when a kerbal boards or unboards an external seat /// </summary> public class ExternalSeatSystem : Base.System<ExternalSeatSystem> { #region Fields & properties private ExternalSeatEvents ExternalSeatEvents { get; } = new ExternalSeatEvents(); #endregion #region Base overrides public override string SystemName { get; } = nameof(ExternalSeatSystem); protected override void OnEnabled() { base.OnEnabled(); ExternalSeatEvent.onExternalSeatBoard.Add(ExternalSeatEvents.ExternalSeatBoard); ExternalSeatEvent.onExternalSeatUnboard.Add(ExternalSeatEvents.ExternalSeatUnboard); } protected override void OnDisabled() { base.OnDisabled(); ExternalSeatEvent.onExternalSeatBoard.Remove(ExternalSeatEvents.ExternalSeatBoard); ExternalSeatEvent.onExternalSeatUnboard.Remove(ExternalSeatEvents.ExternalSeatUnboard); } #endregion } }
using LunaClient.Events; namespace LunaClient.Systems.ExternalSeat { /// <summary> /// This system packs applis a custom precalc to all vessels so they don't do the kill check if they are not yours /// </summary> public class ExternalSeatSystem : Base.System<ExternalSeatSystem> { #region Fields & properties private ExternalSeatEvents ExternalSeatEvents { get; } = new ExternalSeatEvents(); #endregion #region Base overrides public override string SystemName { get; } = nameof(ExternalSeatSystem); protected override void OnEnabled() { base.OnEnabled(); ExternalSeatEvent.onExternalSeatBoard.Add(ExternalSeatEvents.ExternalSeatBoard); ExternalSeatEvent.onExternalSeatUnboard.Add(ExternalSeatEvents.ExternalSeatUnboard); } protected override void OnDisabled() { base.OnDisabled(); ExternalSeatEvent.onExternalSeatBoard.Remove(ExternalSeatEvents.ExternalSeatBoard); ExternalSeatEvent.onExternalSeatUnboard.Remove(ExternalSeatEvents.ExternalSeatUnboard); } #endregion } }
mit
C#
f5228a60319defeb24ee98a37933b527b0fb6d9c
Change "Countdown" widget default "TimeFormat"
danielchalmers/DesktopWidgets
DesktopWidgets/Widgets/CountdownClock/Settings.cs
DesktopWidgets/Widgets/CountdownClock/Settings.cs
using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public Settings() { TimeFormat = "dd:hh:mm:ss"; } public DateTime EndDateTime { get; set; } = DateTime.Now; } }
using System; using DesktopWidgets.Classes; namespace DesktopWidgets.Widgets.CountdownClock { public class Settings : WidgetClockSettingsBase { public DateTime EndDateTime { get; set; } = DateTime.Now; } }
apache-2.0
C#
8753bf42693e8715ed052a1fb51de6fa520c67e7
add key 1 and 2 as left and right trigger
kasoki/UniCube,kasoki/UniCube
InControl/Unity/DeviceProfiles/KeyboardProfile.cs
InControl/Unity/DeviceProfiles/KeyboardProfile.cs
using System; using System.Collections; using System.Collections.Generic; namespace InControl { [AutoDiscover] public class KeyboardProfile : UnityInputDeviceProfile { public KeyboardProfile() { Name = "Keyboard"; Meta = ""; SupportedPlatforms = new[] { "Windows", "Mac", "Linux" }; Sensitivity = 1.0f; DeadZone = 0.0f; ButtonMappings = new[] { new InputControlButtonMapping() { Handle = "W Key", Target = InputControlType.Action4, Source = "w" }, new InputControlButtonMapping() { Handle = "A Key", Target = InputControlType.Action3, Source = "a" }, new InputControlButtonMapping() { Handle = "S Key", Target = InputControlType.Action1, Source = "s" }, new InputControlButtonMapping() { Handle = "D Key", Target = InputControlType.Action2, Source = "d" }, new InputControlButtonMapping() { Handle = "Q Key", Target = InputControlType.LeftBumper, Source = "q" }, new InputControlButtonMapping() { Handle = "E Key", Target = InputControlType.RightBumper, Source = "e" }, new InputControlButtonMapping() { Handle = "Button 1 Trigger", Target = InputControlType.LeftTrigger, Source = "1" }, new InputControlButtonMapping() { Handle = "Button 2 Trigger", Target = InputControlType.RightTrigger, Source = "2" } }; AnalogMappings = new InputControlAnalogMapping[] { new InputControlAnalogMapping() { Handle = "Arrow Keys X", Target = InputControlType.LeftStickX, Source = "left right" }, new InputControlAnalogMapping() { Handle = "Arrow Keys Y", Target = InputControlType.LeftStickY, Source = "down up" } }; } } }
using System; using System.Collections; using System.Collections.Generic; namespace InControl { [AutoDiscover] public class KeyboardProfile : UnityInputDeviceProfile { public KeyboardProfile() { Name = "Keyboard"; Meta = ""; SupportedPlatforms = new[] { "Windows", "Mac", "Linux" }; Sensitivity = 1.0f; DeadZone = 0.0f; ButtonMappings = new[] { new InputControlButtonMapping() { Handle = "W Key", Target = InputControlType.Action4, Source = "w" }, new InputControlButtonMapping() { Handle = "A Key", Target = InputControlType.Action3, Source = "a" }, new InputControlButtonMapping() { Handle = "S Key", Target = InputControlType.Action1, Source = "s" }, new InputControlButtonMapping() { Handle = "D Key", Target = InputControlType.Action2, Source = "d" }, new InputControlButtonMapping() { Handle = "Q Key", Target = InputControlType.LeftBumper, Source = "q" }, new InputControlButtonMapping() { Handle = "E Key", Target = InputControlType.RightBumper, Source = "e" } }; AnalogMappings = new InputControlAnalogMapping[] { new InputControlAnalogMapping() { Handle = "Arrow Keys X", Target = InputControlType.LeftStickX, Source = "left right" }, new InputControlAnalogMapping() { Handle = "Arrow Keys Y", Target = InputControlType.LeftStickY, Source = "down up" } }; } } }
mit
C#
e7cdbb5da4ad37699fe7c63a10412d756228bfcb
Bump version to 1.6.0.1
danlister/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder,zpqrtbnk/Zbu.ModelsBuilder
Zbu.ModelsBuilder/Properties/CommonInfo.cs
Zbu.ModelsBuilder/Properties/CommonInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("ZpqrtBnk Umbraco ModelsBuilder")] [assembly: AssemblyCompany("Pilotine - ZpqrtBnk")] [assembly: AssemblyCopyright("Copyright © Pilotine - ZpqrtBnk 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.6.0.1")] [assembly: AssemblyFileVersion("1.6.0.1")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("ZpqrtBnk Umbraco ModelsBuilder")] [assembly: AssemblyCompany("Pilotine - ZpqrtBnk")] [assembly: AssemblyCopyright("Copyright © Pilotine - ZpqrtBnk 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.5.0.4")] [assembly: AssemblyFileVersion("1.5.0.4")]
mit
C#
665b738289251ab3d4829cba6c6c9595083b1a0a
Remove unused
BenPhegan/NuGet.Extensions
NuGet.Extensions/MSBuild/SolutionProjectLoader.cs
NuGet.Extensions/MSBuild/SolutionProjectLoader.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NuGet.Common; namespace NuGet.Extensions.MSBuild { public class SolutionProjectLoader : IDisposable { private readonly FileInfo _solutionFile; private readonly IConsole _console; private readonly CachingProjectLoader _projectLoader; private readonly Lazy<ICollection<IVsProject>> _projectsInSolution; public SolutionProjectLoader(FileInfo solutionFile, IDictionary<string, string> globalMsBuildProperties, IConsole console) { _solutionFile = solutionFile; _console = console; globalMsBuildProperties["SolutionDir"] = solutionFile.Directory.FullName; _projectLoader = new CachingProjectLoader(globalMsBuildProperties, console); _projectsInSolution = new Lazy<ICollection<IVsProject>>(LoadProjectsInSolutionByGuid); } public List<IVsProject> GetProjects() { return new List<IVsProject>(_projectsInSolution.Value); } public void Dispose() { _projectLoader.Dispose(); } private ICollection<IVsProject> LoadProjectsInSolutionByGuid() { var solution = new Solution(_solutionFile.FullName); return solution.Projects.Where(ProjectExists).Select(CreateProjectAdapter).ToList(); } private IVsProject CreateProjectAdapter(SolutionProject p) { string absoluteProjectPath = GetAbsoluteProjectPath(p.RelativePath); return _projectLoader.GetProject(ProjectGuid(p), absoluteProjectPath); } private bool ProjectExists(SolutionProject simpleProject) { var projectPath = GetAbsoluteProjectPath(simpleProject.RelativePath); if (File.Exists(projectPath)) return true; if (!Directory.Exists(projectPath)) _console.WriteWarning("Project: {0} was not found on disk", simpleProject.ProjectName); return false; } private static Guid ProjectGuid(SolutionProject p) { return Guid.Parse(p.ProjectGuid); } private string GetAbsoluteProjectPath(string relativePath) { return Path.Combine(_solutionFile.Directory.FullName, relativePath); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using NuGet.Common; namespace NuGet.Extensions.MSBuild { public class SolutionProjectLoader : IDisposable { private readonly FileInfo _solutionFile; private readonly IConsole _console; private readonly CachingProjectLoader _projectLoader; private readonly Lazy<ICollection<IVsProject>> _projectsInSolution; public SolutionProjectLoader(FileInfo solutionFile, IDictionary<string, string> globalMsBuildProperties, IConsole console) { _solutionFile = solutionFile; _console = console; globalMsBuildProperties["SolutionDir"] = solutionFile.Directory.FullName; _projectLoader = new CachingProjectLoader(globalMsBuildProperties, console); _projectsInSolution = new Lazy<ICollection<IVsProject>>(LoadProjectsInSolutionByGuid); } public CachingProjectLoader ProjectLoader { get { return _projectLoader; } } public List<IVsProject> GetProjects() { return new List<IVsProject>(_projectsInSolution.Value); } public void Dispose() { _projectLoader.Dispose(); } private ICollection<IVsProject> LoadProjectsInSolutionByGuid() { var solution = new Solution(_solutionFile.FullName); return solution.Projects.Where(ProjectExists).Select(CreateProjectAdapter).ToList(); } private IVsProject CreateProjectAdapter(SolutionProject p) { string absoluteProjectPath = GetAbsoluteProjectPath(p.RelativePath); return _projectLoader.GetProject(ProjectGuid(p), absoluteProjectPath); } private bool ProjectExists(SolutionProject simpleProject) { var projectPath = GetAbsoluteProjectPath(simpleProject.RelativePath); if (File.Exists(projectPath)) return true; if (!Directory.Exists(projectPath)) _console.WriteWarning("Project: {0} was not found on disk", simpleProject.ProjectName); return false; } private static Guid ProjectGuid(SolutionProject p) { return Guid.Parse(p.ProjectGuid); } private string GetAbsoluteProjectPath(string relativePath) { return Path.Combine(_solutionFile.Directory.FullName, relativePath); } } }
mit
C#
a0cdcda3f30b5903303cd557557dc6951bf6a261
Fix first completion being submitted instead of selected
Baggykiin/pass-winmenu
pass-winmenu/src/Windows/FileSelectionWindow.cs
pass-winmenu/src/Windows/FileSelectionWindow.cs
using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; namespace PassWinmenu.Windows { internal class FileSelectionWindow : MainWindow { private readonly DirectoryAutocomplete autocomplete; private readonly string baseDirectory; public FileSelectionWindow(string baseDirectory, MainWindowConfiguration configuration) : base(configuration) { this.baseDirectory = baseDirectory; autocomplete = new DirectoryAutocomplete(baseDirectory); var completions = autocomplete.GetCompletionList(""); RedrawLabels(completions); } private void RedrawLabels(IEnumerable<string> options) { ClearLabels(); var first = true; foreach (var option in options) { var label = CreateLabel(option); AddLabel(label); if (first) { first = false; Select(label); } } } protected override void SearchBox_OnTextChanged(object sender, TextChangedEventArgs e) { var completions = autocomplete.GetCompletionList(SearchBox.Text).ToList(); if (!string.IsNullOrWhiteSpace(SearchBox.Text) && !SearchBox.Text.EndsWith("/") && !completions.Contains(SearchBox.Text)) { completions.Insert(0, SearchBox.Text); } RedrawLabels(completions); } protected override void HandleSelect() { // If a suggestion is selected, put that suggestion in the searchbox. if (Options.IndexOf(Selected) > 0 || string.IsNullOrEmpty(SearchBox.Text)) { var selection = GetSelection(); if (selection.EndsWith(".gpg")) { selection = selection.Substring(0, selection.Length - 4); } SetSearchBoxText(selection); } else { if (SearchBox.Text.EndsWith("/")) { return; } var selection = GetSelection(); if (selection.EndsWith(".gpg")) { MessageBox.Show("A .gpg extension will be added automatically and does not need to be entered here."); selection = selection.Substring(0, selection.Length - 4); SetSearchBoxText(selection); return; } if (File.Exists(Path.Combine(baseDirectory, selection + ".gpg"))) { MessageBox.Show($"The password file \"{selection + ".gpg"}\" already exists."); return; } Success = true; Close(); } } } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; namespace PassWinmenu.Windows { internal class FileSelectionWindow : MainWindow { private readonly DirectoryAutocomplete autocomplete; private readonly string baseDirectory; public FileSelectionWindow(string baseDirectory, MainWindowConfiguration configuration) : base(configuration) { this.baseDirectory = baseDirectory; autocomplete = new DirectoryAutocomplete(baseDirectory); var completions = autocomplete.GetCompletionList(""); RedrawLabels(completions); } private void RedrawLabels(IEnumerable<string> options) { ClearLabels(); var first = true; foreach (var option in options) { var label = CreateLabel(option); AddLabel(label); if (first) { first = false; Select(label); } } } protected override void SearchBox_OnTextChanged(object sender, TextChangedEventArgs e) { var completions = autocomplete.GetCompletionList(SearchBox.Text).ToList(); if (!string.IsNullOrWhiteSpace(SearchBox.Text) && !SearchBox.Text.EndsWith("/") && !completions.Contains(SearchBox.Text)) { completions.Insert(0, SearchBox.Text); } RedrawLabels(completions); } protected override void HandleSelect() { // If a suggestion is selected, put that suggestion in the searchbox. if (Options.IndexOf(Selected) > 0) { var selection = GetSelection(); if (selection.EndsWith(".gpg")) { selection = selection.Substring(0, selection.Length - 4); } SetSearchBoxText(selection); } else { if (SearchBox.Text.EndsWith("/")) { return; } var selection = GetSelection(); if (selection.EndsWith(".gpg")) { MessageBox.Show("A .gpg extension will be added automatically and does not need to be entered here."); selection = selection.Substring(0, selection.Length - 4); SetSearchBoxText(selection); return; } if (File.Exists(Path.Combine(baseDirectory, selection + ".gpg"))) { MessageBox.Show($"The password file \"{selection + ".gpg"}\" already exists."); return; } Success = true; Close(); } } } }
mit
C#
e541b36d01e2b0e6c4fce3c39b268fba1d024c24
Change conditional from decorator to a task
marcotmp/BehaviorTree
Assets/Scripts/BehaviorTree/Conditionals/Conditional.cs
Assets/Scripts/BehaviorTree/Conditionals/Conditional.cs
public class Conditional : Task { private ConditionalDelegate conditionalDelegate; public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name) { this.conditionalDelegate = conditionalDelegate; } public override ReturnCode Update() { var value = conditionalDelegate(); if (value) { return ReturnCode.Succeed; } else { return ReturnCode.Fail; } } } public delegate bool ConditionalDelegate();
public class Conditional : DecoratorTask { private ConditionalDelegate conditionalDelegate; public Conditional(string name, ConditionalDelegate conditionalDelegate) : base(name) { this.conditionalDelegate = conditionalDelegate; } public override ReturnCode Update() { var value = conditionalDelegate(); if (value) { return ReturnCode.Succeed; } else { return ReturnCode.Fail; } } } public delegate bool ConditionalDelegate();
unlicense
C#
b51d4d482afc688aa2a1f6001bf453b13de287f1
Add some guards for measuring nulls
Branimir123/FMI-IoT-Teamwork,Branimir123/FMI-IoT-Teamwork
SmartHive/SmartHive.Web/Views/Hive/Details.cshtml
SmartHive/SmartHive.Web/Views/Hive/Details.cshtml
@model IList<SmartHive.Services.JsonModels.JsonHive> @{ ViewBag.Title = "Details"; } <h2>Details</h2> @{ double[] humids = Model.Select(h => Convert.ToDouble(h.Humidity)).ToArray(); double[] temps = Model.Select(h => Convert.ToDouble(h.Temperature)).ToArray(); string[] dates = Model.Select(h => Convert.ToDateTime(h.CreatedAt).ToShortTimeString()).ToArray(); } @{ var tempChart = new Chart(width: 600, height: 400) .AddTitle("Temperature Chart") .AddSeries( name: "Temperature", xValue: dates, yValues: temps ); var humidChart = new Chart(width: 600, height: 400) .AddTitle("Humidity Chart") .AddSeries( name: "Humidity", xValue: dates, yValues: humids ); } <div class="col-md-6"> <img src="data:image/png;base64,@Convert.ToBase64String(tempChart.GetBytes("png"))" alt="Alternate Text" /> </div> <div class="col-md-6"> <img src="data:image/png;base64,@Convert.ToBase64String(humidChart.GetBytes("png"))" alt="Alternate Text" /> </div> <h3>Detailed history: </h3> @foreach (var hive in Model) { <h4><strong>Measured At: @hive.CreatedAt</strong></h4> if (hive.Temperature != null) {<h4>Temperature: @hive.Temperature</h4>} if (hive.Humidity != null) {<h4>Humidity: @hive.Humidity</h4>} <hr/> }
@model IList<SmartHive.Services.JsonModels.JsonHive> @{ ViewBag.Title = "Details"; } <h2>Details</h2> @{ double[] humids = Model.Select(h => Convert.ToDouble(h.Humidity)).ToArray(); double[] temps = Model.Select(h => Convert.ToDouble(h.Temperature)).ToArray(); string[] dates = Model.Select(h => Convert.ToDateTime(h.CreatedAt).ToShortTimeString()).ToArray(); } @{ var tempChart = new Chart(width: 600, height: 400) .AddTitle("Temperature Chart") .AddSeries( name: "Temperature", xValue: dates, yValues: temps ); var humidChart = new Chart(width: 600, height: 400) .AddTitle("Humidity Chart") .AddSeries( name: "Humidity", xValue: dates, yValues: humids ); } <div class="col-md-6"> <img src="data:image/png;base64,@Convert.ToBase64String(tempChart.GetBytes("png"))" alt="Alternate Text" /> </div> <div class="col-md-6"> <img src="data:image/png;base64,@Convert.ToBase64String(humidChart.GetBytes("png"))" alt="Alternate Text" /> </div> <h3>Detailed history: </h3> @foreach (var hive in Model) { <h4>Measured At: @hive.CreatedAt</h4> <h4>Temperature: @hive.Temperature</h4> <h4>Humidity: @hive.Humidity</h4> }
mit
C#
b9dfccadc569ce1d99e7e6e88b2f000561b4aead
Disable of deleting character groups if they have any claims (#53)
kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
JoinRpg.DataModel/CharacterGroup.cs
JoinRpg.DataModel/CharacterGroup.cs
using System.Collections.Generic; using System.Linq; using JoinRpg.Helpers; namespace JoinRpg.DataModel { // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global (virtual methods used by LINQ) public class CharacterGroup : IClaimSource, IDeletableSubEntity { public int CharacterGroupId { get; set; } public int ProjectId { get; set; } int IOrderableEntity.Id => CharacterGroupId; public virtual Project Project { get; set; } public string CharacterGroupName { get; set; } public bool IsRoot { get; set; } public virtual ICollection<CharacterGroup> ParentGroups { get; set; } string IWorldObject.Name => CharacterGroupName; /// <summary> /// /// </summary> /// <remarks>Check may be you need to use ordered groups</remarks> public virtual IEnumerable<CharacterGroup> ChildGroups => Project.CharacterGroups.Where(cg => cg.ParentGroups.Contains(this)); public bool IsPublic { get; set; } public bool IsSpecial { get; set; } public int AvaiableDirectSlots { get; set; } public bool HaveDirectSlots { get; set; } public bool DirectSlotsUnlimited => AvaiableDirectSlots == -1; public IEnumerable<Character> Characters => Project.Characters.Where(cg => cg.Groups.Contains(this)); public bool IsActive { get; set; } public MarkdownString Description { get; set; } = new MarkdownString(); /// <summary> /// Can add claim directly to character group (not individual characters) /// </summary> public bool IsAvailable => HaveDirectSlots && AvaiableDirectSlots != 0 && Project.IsAcceptingClaims; public IEnumerable<Claim> Claims => Project.Claims.Where(c => c.CharacterGroupId == CharacterGroupId); public virtual User ResponsibleMasterUser { get; set; } public int? ResponsibleMasterUserId { get; set; } public string ChildCharactersOrdering { get; set; } public string ChildGroupsOrdering { get; set; } public virtual ICollection<PlotFolder> DirectlyRelatedPlotFolders { get; set; } public virtual ICollection<PlotElement> DirectlyRelatedPlotElements { get; set; } public virtual ICollection<UserSubscription> Subscriptions { get; set; } public bool CanBePermanentlyDeleted => !ChildGroups.Any() && !Characters.Any() && !DirectlyRelatedPlotFolders.Any() && !Claims.Any(); } }
using System.Collections.Generic; using System.Linq; using JoinRpg.Helpers; namespace JoinRpg.DataModel { // ReSharper disable once ClassWithVirtualMembersNeverInherited.Global (virtual methods used by LINQ) public class CharacterGroup : IClaimSource, IDeletableSubEntity { public int CharacterGroupId { get; set; } public int ProjectId { get; set; } int IOrderableEntity.Id => CharacterGroupId; public virtual Project Project { get; set; } public string CharacterGroupName { get; set; } public bool IsRoot { get; set; } public virtual ICollection<CharacterGroup> ParentGroups { get; set; } string IWorldObject.Name => CharacterGroupName; /// <summary> /// /// </summary> /// <remarks>Check may be you need to use ordered groups</remarks> public virtual IEnumerable<CharacterGroup> ChildGroups => Project.CharacterGroups.Where(cg => cg.ParentGroups.Contains(this)); public bool IsPublic { get; set; } public bool IsSpecial { get; set; } public int AvaiableDirectSlots { get; set; } public bool HaveDirectSlots { get; set; } public bool DirectSlotsUnlimited => AvaiableDirectSlots == -1; public IEnumerable<Character> Characters => Project.Characters.Where(cg => cg.Groups.Contains(this)); public bool IsActive { get; set; } public MarkdownString Description { get; set; } = new MarkdownString(); /// <summary> /// Can add claim directly to character group (not individual characters) /// </summary> public bool IsAvailable => HaveDirectSlots && AvaiableDirectSlots != 0 && Project.IsAcceptingClaims; public IEnumerable<Claim> Claims => Project.Claims.Where(c => c.CharacterGroupId == CharacterGroupId); public virtual User ResponsibleMasterUser { get; set; } public int? ResponsibleMasterUserId { get; set; } public string ChildCharactersOrdering { get; set; } public string ChildGroupsOrdering { get; set; } public virtual ICollection<PlotFolder> DirectlyRelatedPlotFolders { get; set; } public virtual ICollection<PlotElement> DirectlyRelatedPlotElements { get; set; } public virtual ICollection<UserSubscription> Subscriptions { get; set; } public IEnumerable<Character> CharactersWithOnlyParent => WithOnlyParent(Characters); public IEnumerable<CharacterGroup> ChildGroupsWithOnlyParent => WithOnlyParent(ChildGroups); public bool CanBePermanentlyDeleted => !ChildGroups.Any() && !Characters.Any() && !DirectlyRelatedPlotFolders.Any(); private IEnumerable<T> WithOnlyParent<T>(IEnumerable<T> worldObjects) where T:IWorldObject { return worldObjects.Where(obj => obj.ParentGroups.All(group => @group.CharacterGroupId == CharacterGroupId)); } } }
mit
C#
f66ffad7aa94cd9560ebabbd2457a13aa203059f
Change assembly description
PolarbearDK/Miracle.FileZilla.Api
Source/Miracle.FileZilla.Api/Properties/AssemblyInfo.cs
Source/Miracle.FileZilla.Api/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("Miracle.FileZilla.Api")] [assembly: AssemblyDescription("Managed api for FileZilla FTP server. Primarily for automated user/group management, but all functionallity in the FileZilla Server interface is supported.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Philip Hoppe")] [assembly: AssemblyProduct("Miracle.FileZilla.Api")] [assembly: AssemblyCopyright("Copyright © Philip Hoppe, Miracle A/S 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1890ad91-115e-4f43-a389-964a6595e9da")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Miracle.FileZilla.Api")] [assembly: AssemblyDescription("Managed api for FileZilla FTP server. Primarily for automated user/group management.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Philip Hoppe")] [assembly: AssemblyProduct("Miracle.FileZilla.Api")] [assembly: AssemblyCopyright("Copyright © Philip Hoppe, Miracle A/S 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1890ad91-115e-4f43-a389-964a6595e9da")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")]
mit
C#
d282bde7cb5037482d759ce69cdb13d9ca926ecf
Read flight file using File.ReadAllLines
dinazil/she-codes-csharp-for-beginners
Module7/AirlineDelays/FlightInfo.cs
Module7/AirlineDelays/FlightInfo.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AirlineDelays { class FlightInfo { public string Airline { get; set; } public string Origin { get; set; } public string Destination { get; set; } public int DepartureDelay { get; set; } public int ArrivalDelay { get; set; } public bool Cancelled { get; set; } public int Distance { get; set; } public FlightInfo(string[] fields) { Airline = fields[0]; Origin = fields[1]; Destination = fields[2]; DepartureDelay = int.Parse(fields[3]); ArrivalDelay = int.Parse(fields[4]); Cancelled = int.Parse(fields[5]) == 1; Distance = int.Parse(fields[6]); } public override string ToString() { return String.Format("{0} flight from {1} to {2} ({3} miles) departure delay {4} arrival delay {5}", Airline, Origin, Destination, Distance, DepartureDelay, ArrivalDelay); } public static List<FlightInfo> ReadFlightsFromFile(string fileName) { List<FlightInfo> flights = new List<FlightInfo>(); string[] lines = File.ReadAllLines(fileName); for (int i = 1; i < lines.Length; ++i) { string line = lines[i]; string[] parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 7) continue; flights.Add(new FlightInfo(parts)); } return flights; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AirlineDelays { class FlightInfo { public string Airline { get; set; } public string Origin { get; set; } public string Destination { get; set; } public int DepartureDelay { get; set; } public int ArrivalDelay { get; set; } public bool Cancelled { get; set; } public int Distance { get; set; } public FlightInfo(string[] fields) { Airline = fields[0]; Origin = fields[1]; Destination = fields[2]; DepartureDelay = int.Parse(fields[3]); ArrivalDelay = int.Parse(fields[4]); Cancelled = int.Parse(fields[5]) == 1; Distance = int.Parse(fields[6]); } public override string ToString() { return String.Format("{0} flight from {1} to {2} ({3} miles) departure delay {4} arrival delay {5}", Airline, Origin, Destination, Distance, DepartureDelay, ArrivalDelay); } public static List<FlightInfo> ReadFlightsFromFile(string fileName) { List<FlightInfo> flights = new List<FlightInfo>(); bool first = true; using (var reader = new StreamReader(fileName)) { string line; while ((line = reader.ReadLine()) != null) { if (first) { first = false; continue; } string[] parts = line.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length != 7) continue; flights.Add(new FlightInfo(parts)); } } return flights; } } }
mit
C#
68da9e8afc42dedfb41a38ffd123917533e4a6f8
Add LessThan and LongerThan attributes to TestRunnerFactory
Hammerstad/Moya
Moya/Factories/TestRunnerFactory.cs
Moya/Factories/TestRunnerFactory.cs
namespace Moya.Factories { using System; using System.Collections.Generic; using Attributes; using Exceptions; using Extensions; using Runners; using Utility; public class TestRunnerFactory : ITestRunnerFactory { private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type> { { typeof(StressAttribute), typeof(StressTestRunner) }, { typeof(WarmupAttribute), typeof(WarmupTestRunner) }, { typeof(LongerThanAttribute), typeof(LongerThanTestRunner) }, { typeof(LessThanAttribute), typeof(LessThanTestRunner) }, }; public IMoyaTestRunner GetTestRunnerForAttribute(Type type) { if (!Reflection.TypeIsMoyaAttribute(type)) { throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type)); } Type typeOfTestRunner = attributeTestRunnerMapping[type]; IMoyaTestRunner instance = (IMoyaTestRunner)Activator.CreateInstance(typeOfTestRunner); IMoyaTestRunner timerDecoratedInstance = new TimerDecorator(instance); return timerDecoratedInstance; } } }
namespace Moya.Factories { using System; using System.Collections.Generic; using Attributes; using Exceptions; using Extensions; using Runners; using Utility; public class TestRunnerFactory : ITestRunnerFactory { private readonly IDictionary<Type, Type> attributeTestRunnerMapping = new Dictionary<Type, Type> { { typeof(StressAttribute), typeof(StressTestRunner) }, { typeof(WarmupAttribute), typeof(WarmupTestRunner) }, }; public IMoyaTestRunner GetTestRunnerForAttribute(Type type) { if (!Reflection.TypeIsMoyaAttribute(type)) { throw new MoyaException("Unable to provide moya test runner for type {0}".FormatWith(type)); } Type typeOfTestRunner = attributeTestRunnerMapping[type]; IMoyaTestRunner instance = (IMoyaTestRunner)Activator.CreateInstance(typeOfTestRunner); IMoyaTestRunner timerDecoratedInstance = new TimerDecorator(instance); return timerDecoratedInstance; } } }
mit
C#
c28c518ae3efd18ead1311bb03473356f650bccd
bump version
SimonCropp/NServiceBus.Serilog
NServiceBus.Serilog/AssemblyInfo.cs
NServiceBus.Serilog/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.6.1")] [assembly: AssemblyFileVersion("1.6.1")] [assembly: AssemblyTitle("NServiceBus.Serilog")] [assembly: AssemblyProduct("NServiceBus.Serilog")]
using System.Reflection; [assembly: AssemblyVersion("1.6.0")] [assembly: AssemblyFileVersion("1.6.0")] [assembly: AssemblyTitle("NServiceBus.Serilog")] [assembly: AssemblyProduct("NServiceBus.Serilog")]
mit
C#
8e5ad58cde1b850bf3b97a0e2c9a0b68c17ed6c1
update Parser.cs
gaulinsoft/fusion,gaulinsoft/fusion,gaulinsoft/fusion
dll/Gaulinsoft.Web.Fusion/Parser.cs
dll/Gaulinsoft.Web.Fusion/Parser.cs
/*! ------------------------------------------------------------------------ // Fusion // ------------------------------------------------------------------------ // // Copyright 2014 Nicholas Gaulin // // 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; namespace Gaulinsoft.Web.Fusion { public class Parser : Lexer, ICloneable, IEquatable<Parser> { public Parser() : this(null, null) { // } public Parser(string source, string language = null) : base(source, language) { // } protected new TParser Clone<TParser>() where TParser : Parser, new() { // Create a clone of the lexer as a parser var parser = base.Clone<TParser>(); // Return the parser return parser; } public override object Clone() { // Return a clone of this parser as an object return this.Clone<Parser>(); } public bool Equals(Parser parser) { // If a parser wasn't provided, return false if (parser == null) return false; // If the parsers don't have matching lexers, return false if (!base.Equals(parser)) return false; // return true; } // ### TEMPORARILY PUBLIC UNTIL PARSER IS READY ### public new string State { get { return this.State; } } public new Token Token { get { return this.Token; } } } }
/*! ------------------------------------------------------------------------ // Fusion // ------------------------------------------------------------------------ // // Copyright 2014 Nicholas Gaulin // // 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; namespace Gaulinsoft.Web.Fusion { public class Parser { // } }
apache-2.0
C#
6c983d4a36afaf985b6cfa760ea745d9abe91117
Add type string converter documentation.
cemdervis/SharpConfig
SharpConfig/ITypeStringConverter.cs
SharpConfig/ITypeStringConverter.cs
using System; using System.Collections.Generic; using System.Text; namespace SharpConfig { /// <summary> /// Defines a type-to-string and string-to-type converter /// that is used for the conversion of setting values. /// </summary> public interface ITypeStringConverter { /// <summary> /// Converts an object to its string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The object's string representation.</returns> string ConvertToString(object value); /// <summary> /// Converts a string value to an object of this converter's type. /// </summary> /// <param name="value"></param> /// <param name="hint"> /// A type hint. This is used rarely, such as in the enum converter. /// The enum converter's official type is Enum, whereas the type hint /// represents the underlying enum type. /// This parameter can be safely ignored for custom converters. /// </param> /// <returns>The converted object.</returns> object ConvertFromString(string value, Type hint); /// <summary> /// The type that this converter is able to convert to and from a string. /// </summary> Type ConvertibleType { get; } } /// <summary> /// Represents a type-to-string and string-to-type converter /// that is used for the conversion of setting values. /// </summary> /// <typeparam name="T">The type that this converter is able to convert.</typeparam> public abstract class TypeStringConverter<T> : ITypeStringConverter { /// <summary> /// Converts an object to its string representation. /// </summary> /// <param name="value">The value to convert.</param> /// <returns>The object's string representation.</returns> public abstract string ConvertToString(object value); /// <summary> /// Converts a string value to an object of this converter's type. /// </summary> /// <param name="value"></param> /// <param name="hint"> /// A type hint. This is used rarely, such as in the enum converter. /// The enum converter's official type is Enum, whereas the type hint /// represents the underlying enum type. /// This parameter can be safely ignored for custom converters. /// </param> /// <returns>The converted object.</returns> public abstract object ConvertFromString(string value, Type hint); /// <summary> /// The type that this converter is able to convert to and from a string. /// </summary> public Type ConvertibleType { get { return typeof(T); } } } }
using System; using System.Collections.Generic; using System.Text; namespace SharpConfig { public interface ITypeStringConverter { string ConvertToString(object value); object ConvertFromString(string value, Type hint); Type ConvertibleType { get; } } public abstract class TypeStringConverter<T> : ITypeStringConverter { public abstract string ConvertToString(object value); public abstract object ConvertFromString(string value, Type hint); public Type ConvertibleType { get { return typeof(T); } } } }
mit
C#
d18f8d9a85a9f2befbb27d1403854354c65b916b
Package Update #CHANGE: Pushed AdamsLair.WinForms 1.0.8
windygu/winforms,AdamsLair/winforms
WinForms/Properties/AssemblyInfo.cs
WinForms/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.8")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("AdamsLair.WinForms")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AdamsLair.WinForms")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("735ee5dc-8c18-4a06-8e64-2f172ddd01cc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // übernehmen, indem Sie "*" eingeben: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.7")]
mit
C#
cc88bd3c972a5b707f5d4118757ef47bf3302bde
Document PoESocketColor
jcmoyer/Yeena
Yeena/PathOfExile/PoESocketColor.cs
Yeena/PathOfExile/PoESocketColor.cs
// Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Yeena.PathOfExile { /// <summary> /// Represents a socket color. /// </summary> enum PoESocketColor { Red, Green, Blue, Unknown, } static class PoESocketColorExtensions { public static string GetShortName(this PoESocketColor color) { switch (color) { case PoESocketColor.Red: return "R"; case PoESocketColor.Green: return "G"; case PoESocketColor.Blue: return "B"; default: return "?"; } } } static class PoESocketColorUtilities { public static PoESocketColor Parse(string s) { switch (s) { case "S": return PoESocketColor.Red; case "D": return PoESocketColor.Green; case "I": return PoESocketColor.Blue; default: return PoESocketColor.Unknown; } } } }
// Copyright 2013 J.C. Moyer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Yeena.PathOfExile { enum PoESocketColor { Red, Green, Blue, Unknown, } static class PoESocketColorExtensions { public static string GetShortName(this PoESocketColor color) { switch (color) { case PoESocketColor.Red: return "R"; case PoESocketColor.Green: return "G"; case PoESocketColor.Blue: return "B"; default: return "?"; } } } static class PoESocketColorUtilities { public static PoESocketColor Parse(string s) { switch (s) { case "S": return PoESocketColor.Red; case "D": return PoESocketColor.Green; case "I": return PoESocketColor.Blue; default: return PoESocketColor.Unknown; } } } }
apache-2.0
C#
4610e37c682ec1195046d6621ac1ba8701306394
Fix isAuthenticated -> authenticated to get it working - Camunda docs error
jlucansky/Camunda.Api.Client
Camunda.Api.Client/Identity/IdentityVerifiedUser.cs
Camunda.Api.Client/Identity/IdentityVerifiedUser.cs
using System; using System.Collections.Generic; using System.Text; namespace Camunda.Api.Client.Identity { public class IdentityVerifiedUser { /// <summary> /// The id of the user /// </summary> public string AuthenticatedUser; /// <summary> /// Verification successful or not /// </summary> public bool Authenticated; } }
using System; using System.Collections.Generic; using System.Text; namespace Camunda.Api.Client.Identity { public class IdentityVerifiedUser { /// <summary> /// The id of the user /// </summary> public string AuthenticatedUser; /// <summary> /// Verification successful or not /// </summary> public bool IsAuthenticated; } }
mit
C#
dd4e563d5eb3cf35db14b593c12b95e3dd53d855
Fix to update invoice
craigmckeachie/stripe.net,chickenham/stripe.net,AvengingSyndrome/stripe.net,duckwaffle/stripe.net,shirley-truong-volusion/stripe.net,hattonpoint/stripe.net,Raganhar/stripe.net,matthewcorven/stripe.net,DemocracyVenturesInc/stripe.net,DemocracyVenturesInc/stripe.net,richardlawley/stripe.net,shirley-truong-volusion/stripe.net,haithemaraissia/stripe.net,agrogan/stripe.net,hattonpoint/stripe.net,sidshetye/stripe.net,matthewcorven/stripe.net,chickenham/stripe.net,mathieukempe/stripe.net,haithemaraissia/stripe.net,Raganhar/stripe.net,mathieukempe/stripe.net,brentdavid2008/stripe.net,sidshetye/stripe.net,agrogan/stripe.net,craigmckeachie/stripe.net,weizensnake/stripe.net,AvengingSyndrome/stripe.net,weizensnake/stripe.net,stripe/stripe-dotnet
src/Stripe.Tests/invoices/when_closing_an_invoice.cs
src/Stripe.Tests/invoices/when_closing_an_invoice.cs
using System.Collections.Generic; using System.Linq; using Machine.Specifications; using System; namespace Stripe.Tests { public class when_closing_an_invoice { private static StripeInvoice _stripeInvoice; private static List<StripeInvoice> _stripeInvoiceList; private static StripeInvoiceService _stripeInvoiceService; Establish context = () => { var stripePlanService = new StripePlanService(); var stripePlan = stripePlanService.Create(test_data.stripe_plan_create_options.Valid()); var stripeCouponService = new StripeCouponService(); var stripeCoupon = stripeCouponService.Create(test_data.stripe_coupon_create_options.Valid()); var stripeCustomerService = new StripeCustomerService(); var stripeCustomerCreateOptions = test_data.stripe_customer_create_options.ValidCard(stripePlan.Id, stripeCoupon.Id); var stripeCustomer = stripeCustomerService.Create(stripeCustomerCreateOptions); var stripeInvoiceItemService = new StripeInvoiceItemService(); stripeInvoiceItemService.Create(test_data.stripe_invoiceitem_create_options.Valid(stripeCustomer.Id)); _stripeInvoiceService = new StripeInvoiceService(); _stripeInvoiceService.Create(stripeCustomer.Id); _stripeInvoiceList = _stripeInvoiceService.List(10, 0, stripeCustomer.Id).ToList(); }; Because of = () => _stripeInvoice = _stripeInvoiceService.Update(_stripeInvoiceList.First().Id, new StripeInvoiceUpdateOptions { Closed = true }); It should_have_the_correct_id = () => _stripeInvoice.Id.ShouldEqual(_stripeInvoiceList.First().Id); It should_be_closed = () => _stripeInvoice.Closed.ShouldEqual(true); } }
using System.Collections.Generic; using System.Linq; using Machine.Specifications; using System; namespace Stripe.Tests { public class when_closing_an_invoice { private static StripeInvoice _stripeInvoice; private static List<StripeInvoice> _stripeInvoiceList; private static StripeInvoiceService _stripeInvoiceService; Establish context = () => { var stripePlanService = new StripePlanService(); var stripePlan = stripePlanService.Create(test_data.stripe_plan_create_options.Valid()); var stripeCouponService = new StripeCouponService(); var stripeCoupon = stripeCouponService.Create(test_data.stripe_coupon_create_options.Valid()); var stripeCustomerService = new StripeCustomerService(); var stripeCustomerCreateOptions = test_data.stripe_customer_create_options.ValidCard(stripePlan.Id, stripeCoupon.Id); var stripeCustomer = stripeCustomerService.Create(stripeCustomerCreateOptions); _stripeInvoiceService = new StripeInvoiceService(); _stripeInvoiceList = _stripeInvoiceService.List(10, 0, stripeCustomer.Id).ToList(); }; Because of = () => _stripeInvoice = _stripeInvoiceService.Update(_stripeInvoiceList.First().Id, new StripeInvoiceUpdateOptions { Closed = true }); It should_have_the_correct_id = () => _stripeInvoice.Id.ShouldEqual(_stripeInvoiceList.First().Id); It should_be_closed = () => _stripeInvoice.Closed.ShouldEqual(true); } }
apache-2.0
C#
b689e75924bfc84375795bcba084148c74c4ddbf
Fix namespace function not using top level types
fretelweb/ConfuserEx,timnboys/ConfuserEx,arpitpanwar/ConfuserEx,modulexcite/ConfuserEx,farmaair/ConfuserEx,yuligang1234/ConfuserEx,yeaicc/ConfuserEx,AgileJoshua/ConfuserEx,manojdjoshi/ConfuserEx,jbeshir/ConfuserEx,JPVenson/ConfuserEx,mirbegtlax/ConfuserEx,Desolath/ConfuserEx3,MetSystem/ConfuserEx,mirbegtlax/ConfuserEx,JPVenson/ConfuserEx,HalidCisse/ConfuserEx,Desolath/Confuserex,HalidCisse/ConfuserEx,KKKas/ConfuserEx,Immortal-/ConfuserEx,engdata/ConfuserEx,apexrichard/ConfuserEx,yuligang1234/ConfuserEx
Confuser.Core/Project/Patterns/NamespaceFunction.cs
Confuser.Core/Project/Patterns/NamespaceFunction.cs
using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the namespace of definition. /// </summary> public class NamespaceFunction : PatternFunction { internal const string FnName = "namespace"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; object ns = Arguments[0].Evaluate(definition); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; while (type.IsNested) type = type.DeclaringType; return type != null && type.Namespace == ns.ToString(); } } }
using dnlib.DotNet; namespace Confuser.Core.Project.Patterns { /// <summary> /// A function that compare the namespace of definition. /// </summary> public class NamespaceFunction : PatternFunction { internal const string FnName = "namespace"; /// <inheritdoc /> public override string Name { get { return FnName; } } /// <inheritdoc /> public override int ArgumentCount { get { return 1; } } /// <inheritdoc /> public override object Evaluate(IDnlibDef definition) { if (!(definition is TypeDef) && !(definition is IMemberDef)) return false; object ns = Arguments[0].Evaluate(definition); var type = definition as TypeDef; if (type == null) type = ((IMemberDef)definition).DeclaringType; return type != null && type.Namespace == ns.ToString(); } } }
mit
C#
6834a28fe35f92da3f2cbac0cb2dffb4d09367b5
Fix Dic2 lexer regexes to work properly on Linux
TheBerkin/Rant,esaul/Rant
Rant/Vocabulary/Dic2Lexer.cs
Rant/Vocabulary/Dic2Lexer.cs
using System.Collections.Generic; using System.Text.RegularExpressions; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Vocabulary { internal static class Dic2Lexer { private const RegexOptions DicRegexOptions = RegexOptions.Compiled; private static readonly LexerRules<DicTokenType> Rules; static Dic2Lexer() { Rules = new LexerRules<DicTokenType> { {new Regex(@"\#\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2}, {new Regex(@"\|\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2}, {new Regex(@"\>\s*(?<value>.*?)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2}, {new Regex(@"\s+"), DicTokenType.Ignore} }; Rules.AddEndToken(DicTokenType.EOF); Rules.IgnoreRules.Add(DicTokenType.Ignore); } public static IEnumerable<Token<DicTokenType>> Tokenize(string data) { Token<DicTokenType> token; var reader = new StringeReader(data); while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF) { yield return token; } } } internal enum DicTokenType { Directive, Entry, Property, Ignore, EOF } }
using System.Collections.Generic; using System.Text.RegularExpressions; using Rant.Stringes; using Rant.Stringes.Tokens; namespace Rant.Vocabulary { internal static class Dic2Lexer { private const RegexOptions DicRegexOptions = RegexOptions.Compiled; private static readonly LexerRules<DicTokenType> Rules; static Dic2Lexer() { Rules = new LexerRules<DicTokenType> { {new Regex(@"\#\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Directive, 2}, {new Regex(@"\|\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Property, 2}, {new Regex(@"\>\s*(?<value>[^\r]*)[\s\r]*(?=\#|\||\>|$)", DicRegexOptions), DicTokenType.Entry, 2}, {new Regex(@"\s+"), DicTokenType.Ignore} }; Rules.AddEndToken(DicTokenType.EOF); Rules.IgnoreRules.Add(DicTokenType.Ignore); } public static IEnumerable<Token<DicTokenType>> Tokenize(string data) { Token<DicTokenType> token; var reader = new StringeReader(data); while ((token = reader.ReadToken(Rules)).Identifier != DicTokenType.EOF) { yield return token; } } } internal enum DicTokenType { Directive, Entry, Property, Ignore, EOF } }
mit
C#
722513cf07bd0ee92fd08725ed441cf2e27d2ece
Fix JUnit test to find running assembly in Mono C#
reportunit/reportunit,reportunit/reportunit,ekirmayer/reportunit,reportunit/reportunit,ekirmayer/reportunit,ekirmayer/reportunit
ReportUnitTest/JUnitTests.cs
ReportUnitTest/JUnitTests.cs
using System; using System.IO; using System.Reflection; using NUnit.Framework; namespace ReportUnitTest { [TestFixture] public class JUnitTests { public static string ExecutableDir; public static string ResourcesDir; [OneTimeSetUp] public static void Setup() { var assemblyDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (assemblyDir == null) { throw new Exception("Failed to get assembly path"); } TestContext.Out.WriteLine("Assembly: " + assemblyDir); ResourcesDir = Path.Combine(assemblyDir, "..", "..", "Resources"); if (!Directory.Exists(ResourcesDir)) { throw new Exception("Can't find Resources folder"); } TestContext.Out.WriteLine("Resources: " + ResourcesDir); ExecutableDir = Path.Combine(assemblyDir, "..", "..", "..", "ReportUnit", "bin"); if (!Directory.Exists(ExecutableDir)) { throw new Exception("Can't find ReportUnit folder"); } TestContext.Out.WriteLine("Executable: " + ExecutableDir); } [Test] public void Test() { var filename = Path.Combine(ExecutableDir, "ReportUnit.exe"); var proc = System.Diagnostics.Process.Start(filename, "test_junit_01.xml"); if (proc == null) { throw new Exception("Failed to start"); } if (!proc.WaitForExit(5000)) { throw new Exception("Timeout"); } if (proc.ExitCode != 0) { throw new Exception("Exit code " + proc.ExitCode); } } } }
using System; using System.IO; using NUnit.Framework; namespace ReportUnitTest { [TestFixture] public class JUnitTests { public static string ExecutableDir; public static string ResourcesDir; [OneTimeSetUp] public static void Setup() { ResourcesDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "Resources"); if (!Directory.Exists(ResourcesDir)) { throw new Exception("Can't find Resources folder"); } ExecutableDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "..", "..", "..", "ReportUnit", "bin"); if (!Directory.Exists(ExecutableDir)) { throw new Exception("Can't find ReportUnit folder"); } } [Test] public void Test() { var filename = Path.Combine(ExecutableDir, "ReportUnit.exe"); var proc = System.Diagnostics.Process.Start(filename, "test_junit_01.xml"); if (proc == null) { throw new Exception("Failed to start"); } if (!proc.WaitForExit(5000)) { throw new Exception("Timeout"); } if (proc.ExitCode != 0) { throw new Exception("Exit code " + proc.ExitCode); } } } }
mit
C#
c7dca4b6631dc519dd0c8953962decfc4213b22a
update responsive meta tag per twbs
AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us,AerisG222/mikeandwan.us
src/mikeandwan.us/Views/Shared/_LayoutMinimal.cshtml
src/mikeandwan.us/Views/Shared/_LayoutMinimal.cshtml
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <title>mikeandwan.us | @ViewBag.Title</title> @await RenderSectionAsync("custom_head", required: false) </head> <body> @RenderBody() </body> </html>
<!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>mikeandwan.us | @ViewBag.Title</title> @await RenderSectionAsync("custom_head", required: false) </head> <body> @RenderBody() </body> </html>
mit
C#
31ae499fffa3c058ff27123a9db870dfb6675775
Change order of operations for selectable menu
PearMed/Pear-Interaction-Engine
Scripts/UI/SelectableMenu.cs
Scripts/UI/SelectableMenu.cs
using Pear.InteractionEngine.Controllers; using Pear.InteractionEngine.EventListeners; using Pear.Models; using System; using UnityEngine; using UnityEngine.UI; namespace Pear.InteractionEngine.UI { /// <summary> /// A menu that opens around a controller /// and uses selectable navigation /// </summary> public class SelectableMenu : MonoBehaviour { [Tooltip("The default selected object")] public Selectable DefaultSelected; [Tooltip("Offset from the controller")] public Vector3 PositionOffset; [Tooltip("Local rotation around the parent controller")] public Vector3 RotationOffset; [Tooltip("The slider selector")] public SelectableNavigation SliderNavigation; [Tooltip("Called when the menu opens")] public ControllerEvent OnOpen = new ControllerEvent(); [Tooltip("Called when the menu closes")] public ControllerEvent OnClose = new ControllerEvent(); // The controller we're currently open around private Controller _activeController; private void Awake() { // When selection changes set the active objects SliderNavigation.SelectedChangedEvent += (selected) => { if (_activeController != null) _activeController.SetActive(gameObject, selected.gameObject); }; } /// <summary> /// Place the menu around the given controller /// </summary> /// <param name="go"></param> public void Open(Controller controller) { gameObject.SetActive(true); _activeController = controller; controller.SetActive(gameObject); // Select the default element SliderNavigation.Select(DefaultSelected); OnOpen.Invoke(_activeController); } /// <summary> /// Close the menu /// </summary> /// <param name="controller"></param> public void Close() { Debug.Log("Closing selectable menu: " + name); gameObject.SetActive(false); if(_activeController != null) _activeController.RemoveActives(gameObject); OnClose.Invoke(_activeController); } } }
using Pear.InteractionEngine.Controllers; using Pear.InteractionEngine.EventListeners; using Pear.Models; using System; using UnityEngine; using UnityEngine.UI; namespace Pear.InteractionEngine.UI { /// <summary> /// A menu that opens around a controller /// and uses selectable navigation /// </summary> public class SelectableMenu : MonoBehaviour { [Tooltip("The default selected object")] public Selectable DefaultSelected; [Tooltip("Offset from the controller")] public Vector3 PositionOffset; [Tooltip("Local rotation around the parent controller")] public Vector3 RotationOffset; [Tooltip("The slider selector")] public SelectableNavigation SliderNavigation; [Tooltip("Called when the menu opens")] public ControllerEvent OnOpen = new ControllerEvent(); [Tooltip("Called when the menu closes")] public ControllerEvent OnClose = new ControllerEvent(); // The controller we're currently open around private Controller _activeController; private void Awake() { // When selection changes set the active objects SliderNavigation.SelectedChangedEvent += (selected) => { if (_activeController != null) _activeController.SetActive(gameObject, selected.gameObject); }; } /// <summary> /// Place the menu around the given controller /// </summary> /// <param name="go"></param> public void Open(Controller controller) { gameObject.SetActive(true); _activeController = controller; controller.SetActive(gameObject); // Select the default element SliderNavigation.Select(DefaultSelected); OnOpen.Invoke(_activeController); } /// <summary> /// Close the menu /// </summary> /// <param name="controller"></param> public void Close() { Debug.Log("Closing selectable menu: " + name); gameObject.SetActive(false); if(_activeController != null) _activeController.RemoveActives(gameObject); OnClose.Invoke(_activeController); } } }
mit
C#
e4463254d7feab088262dfb84826f4ce5a04ba43
Add test coverage for score counter alignment
UselessToucan/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,peppy/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu
osu.Game.Tests/Visual/Gameplay/TestSceneSkinnableScoreCounter.cs
osu.Game.Tests/Visual/Gameplay/TestSceneSkinnableScoreCounter.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 NUnit.Framework; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableScoreCounter : SkinnableTestScene { private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableScoreCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestScoreCounterIncrementing() { AddStep(@"Reset all", delegate { foreach (var s in scoreCounters) s.Current.Value = 0; }); AddStep(@"Hit! :D", delegate { foreach (var s in scoreCounters) s.Current.Value += 300; }); } [Test] public void TestVeryLargeScore() { AddStep("set large score", () => scoreCounters.ForEach(counter => counter.Current.Value = 1_00_000_000)); } } }
// 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 NUnit.Framework; using osu.Framework.Testing; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu; using osu.Game.Screens.Play.HUD; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneSkinnableScoreCounter : SkinnableTestScene { private IEnumerable<SkinnableScoreCounter> scoreCounters => CreatedDrawables.OfType<SkinnableScoreCounter>(); protected override Ruleset CreateRulesetForSkinProvider() => new OsuRuleset(); [SetUpSteps] public void SetUpSteps() { AddStep("Create combo counters", () => SetContents(() => { var comboCounter = new SkinnableScoreCounter(); comboCounter.Current.Value = 1; return comboCounter; })); } [Test] public void TestScoreCounterIncrementing() { AddStep(@"Reset all", delegate { foreach (var s in scoreCounters) s.Current.Value = 0; }); AddStep(@"Hit! :D", delegate { foreach (var s in scoreCounters) s.Current.Value += 300; }); } } }
mit
C#
40ec24c721aed28fdeb82eaa8a35e18ece3c6cd9
Increase line thickness to match design
EVAST9919/osu,2yangk23/osu,peppy/osu,2yangk23/osu,ZLima12/osu,ZLima12/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,johnneijzen/osu,johnneijzen/osu,ppy/osu,smoogipooo/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu
osu.Game.Tournament/Screens/Ladder/Components/ProgressionPath.cs
osu.Game.Tournament/Screens/Ladder/Components/ProgressionPath.cs
using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Lines; using OpenTK; namespace osu.Game.Tournament.Screens.Ladder.Components { public class ProgressionPath : Path { public DrawableMatchPairing Source { get; private set; } public DrawableMatchPairing Destination { get; private set; } public ProgressionPath(DrawableMatchPairing source, DrawableMatchPairing destination) { Source = source; Destination = destination; PathWidth = 3; BypassAutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); Vector2 getCenteredVector(Vector2 top, Vector2 bottom) => new Vector2(top.X, top.Y + (bottom.Y - top.Y) / 2); var q1 = Source.ScreenSpaceDrawQuad; var q2 = Destination.ScreenSpaceDrawQuad; float padding = q1.Width / 20; bool progressionToRight = q2.TopLeft.X > q1.TopLeft.X; if (!progressionToRight) { var temp = q2; q2 = q1; q1 = temp; } var c1 = getCenteredVector(q1.TopRight, q1.BottomRight) + new Vector2(padding, 0); var c2 = getCenteredVector(q2.TopLeft, q2.BottomLeft) - new Vector2(padding, 0); var p1 = c1; var p2 = p1 + new Vector2(padding, 0); if (p2.X > c2.X) { c2 = getCenteredVector(q2.TopRight, q2.BottomRight) + new Vector2(padding, 0); p2.X = c2.X + padding; } var p3 = new Vector2(p2.X, c2.Y); var p4 = new Vector2(c2.X, p3.Y); Positions = new[] { p1, p2, p3, p4 }.Select(ToLocalSpace).ToList(); } } }
using System.Linq; using osu.Framework.Graphics; using osu.Framework.Graphics.Lines; using OpenTK; namespace osu.Game.Tournament.Screens.Ladder.Components { public class ProgressionPath : Path { public DrawableMatchPairing Source { get; private set; } public DrawableMatchPairing Destination { get; private set; } public ProgressionPath(DrawableMatchPairing source, DrawableMatchPairing destination) { Source = source; Destination = destination; PathWidth = 2; BypassAutoSizeAxes = Axes.Both; } protected override void LoadComplete() { base.LoadComplete(); Vector2 getCenteredVector(Vector2 top, Vector2 bottom) => new Vector2(top.X, top.Y + (bottom.Y - top.Y) / 2); var q1 = Source.ScreenSpaceDrawQuad; var q2 = Destination.ScreenSpaceDrawQuad; float padding = q1.Width / 20; bool progressionToRight = q2.TopLeft.X > q1.TopLeft.X; if (!progressionToRight) { var temp = q2; q2 = q1; q1 = temp; } var c1 = getCenteredVector(q1.TopRight, q1.BottomRight) + new Vector2(padding, 0); var c2 = getCenteredVector(q2.TopLeft, q2.BottomLeft) - new Vector2(padding, 0); var p1 = c1; var p2 = p1 + new Vector2(padding, 0); if (p2.X > c2.X) { c2 = getCenteredVector(q2.TopRight, q2.BottomRight) + new Vector2(padding, 0); p2.X = c2.X + padding; } var p3 = new Vector2(p2.X, c2.Y); var p4 = new Vector2(c2.X, p3.Y); Positions = new[] { p1, p2, p3, p4 }.Select(ToLocalSpace).ToList(); } } }
mit
C#
67b6811ca8d18ed7e4063cb712577a260a0de232
add comment to show why test isnt working.
SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia
samples/IntegrationTestApp/ShowWindowTest.axaml.cs
samples/IntegrationTestApp/ShowWindowTest.axaml.cs
using System; using Avalonia.Controls; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Rendering; namespace IntegrationTestApp { public class ShowWindowTest : Window { public ShowWindowTest() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } protected override void OnOpened(EventArgs e) { base.OnOpened(e); this.GetControl<TextBox>("ClientSize").Text = $"{Width}, {Height}"; this.GetControl<TextBox>("FrameSize").Text = $"{FrameSize}"; this.GetControl<TextBox>("Position").Text = $"{Position}"; this.GetControl<TextBox>("ScreenRect").Text = $"{Screens.ScreenFromVisual(this)?.WorkingArea}"; this.GetControl<TextBox>("Scaling").Text = $"{((IRenderRoot)this).RenderScaling}"; // TODO Use DesktopScaling from WindowImpl. if (Owner is not null) { var ownerRect = this.GetControl<TextBox>("OwnerRect"); var owner = (Window)Owner; ownerRect.Text = $"{owner.Position}, {owner.FrameSize}"; } } private void CloseWindow_Click(object sender, RoutedEventArgs e) => Close(); } }
using System; using Avalonia.Controls; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Rendering; namespace IntegrationTestApp { public class ShowWindowTest : Window { public ShowWindowTest() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } protected override void OnOpened(EventArgs e) { base.OnOpened(e); this.GetControl<TextBox>("ClientSize").Text = $"{Width}, {Height}"; this.GetControl<TextBox>("FrameSize").Text = $"{FrameSize}"; this.GetControl<TextBox>("Position").Text = $"{Position}"; this.GetControl<TextBox>("ScreenRect").Text = $"{Screens.ScreenFromVisual(this)?.WorkingArea}"; this.GetControl<TextBox>("Scaling").Text = $"{((IRenderRoot)this).RenderScaling}"; if (Owner is not null) { var ownerRect = this.GetControl<TextBox>("OwnerRect"); var owner = (Window)Owner; ownerRect.Text = $"{owner.Position}, {owner.FrameSize}"; } } private void CloseWindow_Click(object sender, RoutedEventArgs e) => Close(); } }
mit
C#
78528fc49ea840a74b0abfcc9393c902a724ecfc
Add test for day 18 part 2
martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode,martincostello/adventofcode
tests/AdventOfCode.Tests/Puzzles/Y2016/Day18Tests.cs
tests/AdventOfCode.Tests/Puzzles/Y2016/Day18Tests.cs
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles.Y2016 { using Xunit; /// <summary> /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited. /// </summary> public static class Day18Tests { [Theory] [InlineData("..^^.", 3, 6)] [InlineData(".^^.^.^^^^", 10, 38)] public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected) { // Act int actual = Day18.FindSafeTileCount(firstRowTiles, rows); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("40", 1987)] [InlineData("400000", 19984714)] public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected) { // Arrange string[] args = new[] { rows }; // Act var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args); // Assert Assert.Equal(expected, puzzle.SafeTileCount); } } }
// Copyright (c) Martin Costello, 2015. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.AdventOfCode.Puzzles.Y2016 { using Xunit; /// <summary> /// A class containing tests for the <see cref="Day18"/> class. This class cannot be inherited. /// </summary> public static class Day18Tests { [Theory] [InlineData("..^^.", 3, 6)] [InlineData(".^^.^.^^^^", 10, 38)] public static void Y2016_Day18_FindSafeTileCount_Returns_Correct_Solution(string firstRowTiles, int rows, int expected) { // Act int actual = Day18.FindSafeTileCount(firstRowTiles, rows); // Assert Assert.Equal(expected, actual); } [Theory] [InlineData("40", 1987)] public static void Y2016_Day18_Solve_Returns_Correct_Solution(string rows, int expected) { // Arrange string[] args = new[] { rows }; // Act var puzzle = PuzzleTestHelpers.SolvePuzzle<Day18>(args); // Assert Assert.Equal(expected, puzzle.SafeTileCount); } } }
apache-2.0
C#
5a7ebfbb16538746ab816983b779924d1922a54e
Change checkbox to check mark and cross mark characters.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
MitternachtWeb/Areas/Guild/Views/Mutes/Index.cshtml
MitternachtWeb/Areas/Guild/Views/Mutes/Index.cshtml
@model IEnumerable<Mute> <table class="table"> <thead> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.Username) </th> <th> @Html.DisplayNameFor(model => model.UserId) </th> <th> @Html.DisplayNameFor(model => model.Muted) </th> <th> @Html.DisplayNameFor(model => model.UnmuteAt) </th> <th></th> </tr> </thead> <tbody> @foreach(var mute in Model) { <tr> <td> @if(!string.IsNullOrWhiteSpace(mute.AvatarUrl)) { <img class="discord-avatar" src="@mute.AvatarUrl" alt="Avatar" /> } </td> <td> @Html.DisplayFor(modelItem => mute.Username) </td> <td> @Html.DisplayFor(modelItem => mute.UserId) </td> <td> @if(mute.Muted) { @Html.Raw("✅") } else { @Html.Raw("❌") } </td> <td> @Html.DisplayFor(modelItem => mute.MutedUntil) </td> <td> @if(ViewBag.PermissionWriteMutes) { <a asp-area="Guild" asp-controller="Mutes" asp-action="Delete" asp-route-guildId="@ViewBag.GuildId" asp-route-id="@mute.UserId">Löschen</a> } </td> </tr> } </tbody> </table>
@model IEnumerable<Mute> <table class="table"> <thead> <tr> <th></th> <th> @Html.DisplayNameFor(model => model.Username) </th> <th> @Html.DisplayNameFor(model => model.UserId) </th> <th> @Html.DisplayNameFor(model => model.Muted) </th> <th> @Html.DisplayNameFor(model => model.UnmuteAt) </th> <th></th> </tr> </thead> <tbody> @foreach(var mute in Model) { <tr> <td> @if(!string.IsNullOrWhiteSpace(mute.AvatarUrl)) { <img class="discord-avatar" src="@mute.AvatarUrl" alt="Avatar" /> } </td> <td> @Html.DisplayFor(modelItem => mute.Username) </td> <td> @Html.DisplayFor(modelItem => mute.UserId) </td> <td> @Html.DisplayFor(modelItem => mute.Muted) </td> <td> @Html.DisplayFor(modelItem => mute.MutedUntil) </td> <td> @if(ViewBag.PermissionWriteMutes) { <a asp-area="Guild" asp-controller="Mutes" asp-action="Delete" asp-route-guildId="@ViewBag.GuildId" asp-route-id="@mute.UserId">Löschen</a> } </td> </tr> } </tbody> </table>
mit
C#
9778415e7f5e7b7753f2dcbd6586f88b9de2737c
Fix 'ThreadThread' keys
oysteinkrog/thing_libutils,oysteinkrog/thing_libutils
scripts/generator/generator/Threads/ThreadEntry.cs
scripts/generator/generator/Threads/ThreadEntry.cs
using System.Xml.Serialization; using UnitsNet; namespace generator.Threads { public sealed class ThreadEntry : IObjectEntry { public Length Size { get; set; } public string Key { get; set; } public string KeySimple { get; set; } public Length PitchMm { get; set; } // External (bolt thread) public string ExternalBoltClass { get; set; } public Length ExternalMajorDiaMax { get; set; } public Length ExternalMajorDiaMin { get; set; } public Length ExternalPitchMax { get; set; } public Length ExternalPitchMin { get; set; } public Length ExternalMinorDiaMax { get; set; } public Length ExternalMinorDiaMin { get; set; } // Internal (nut thread) public string InternalBoltClass { get; set; } public Length InternalMinorDiaMin { get; set; } public Length InternalMinorDiaMax { get; set; } public Length InternalPitchMin { get; set; } public Length InternalPitchMax { get; set; } public Length InternalMajorDiaMin { get; set; } public Length InternalMajorDiaMax { get; set; } public Length BasicTapDrill { get; set; } public override string ToString() { return $"Thread{KeySimple}"; } [XmlIgnore] public string ExtraPrefix => string.Empty; [XmlIgnore] public string ExtraSuffix { get; } } }
using System.Xml.Serialization; using UnitsNet; namespace generator.Threads { public sealed class ThreadEntry : IObjectEntry { public Length Size { get; set; } public string ThreadKey { get; set; } public string ThreadKeySimple { get; set; } public Length PitchMm { get; set; } // External (bolt thread) public string ExternalBoltClass { get; set; } public Length ExternalMajorDiaMax { get; set; } public Length ExternalMajorDiaMin { get; set; } public Length ExternalPitchMax { get; set; } public Length ExternalPitchMin { get; set; } public Length ExternalMinorDiaMax { get; set; } public Length ExternalMinorDiaMin { get; set; } // Internal (nut thread) public string InternalBoltClass { get; set; } public Length InternalMinorDiaMin { get; set; } public Length InternalMinorDiaMax { get; set; } public Length InternalPitchMin { get; set; } public Length InternalPitchMax { get; set; } public Length InternalMajorDiaMin { get; set; } public Length InternalMajorDiaMax { get; set; } public Length BasicTapDrill { get; set; } public override string ToString() { return $"Thread{ThreadKeySimple}"; } [XmlIgnore] public string ExtraPrefix => string.Empty; [XmlIgnore] public string ExtraSuffix { get; } } }
lgpl-2.1
C#
3aa7bcaf7ae6ec5e6db644fad2fc072bbd3cc299
fix #18 EventAggregator PublishOnBackgroundThread() was not always executed on a background thread
huoxudong125/Caliburn.Micro,BrunoJuchli/Caliburn.Micro,thewindev/Caliburn.Micro,vgrigoriu/Caliburn.Micro,mbruckner/Caliburn.Micro,Billpzoom/Caliburn.Micro,chrisrpatterson/Caliburn.Micro,bitbonk/Caliburn.Micro,TriadTom/Caliburn.Micro,ehigh2014/Caliburn.Micro,dvdvorle/Caliburn.Micro,serenabenny/Caliburn.Micro,mwpowellhtx/Caliburn.Micro,suvjunmd/Caliburn.Micro,taori/Caliburn.Micro,fmarrabal/Caliburn.Micro,dvdvorle/Caliburn.Micro,TriadTom/Caliburn.Micro,bendetat/Caliburn.Micro,ckjohn88/CaliburnMicroCopy,Bobdina/Caliburn.Micro,Caliburn-Micro/Caliburn.Micro
src/Caliburn.Micro/EventAggregatorExtensions.cs
src/Caliburn.Micro/EventAggregatorExtensions.cs
namespace Caliburn.Micro { using System.Threading; using System.Threading.Tasks; /// <summary> /// Extensions for <see cref="IEventAggregator"/>. /// </summary> public static class EventAggregatorExtensions { /// <summary> /// Publishes a message on the current thread (synchrone). /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void PublishOnCurrentThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, action => action()); } /// <summary> /// Publishes a message on a background thread (async). /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void PublishOnBackgroundThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, action => Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default)); } /// <summary> /// Publishes a message on the UI thread. /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void PublishOnUIThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, Execute.OnUIThread); } /// <summary> /// Publishes a message on the UI thread asynchrone. /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void BeginPublishOnUIThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, Execute.BeginOnUIThread); } /// <summary> /// Publishes a message on the UI thread asynchrone. /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name="message">The message instance.</param> public static Task PublishOnUIThreadAsync(this IEventAggregator eventAggregator, object message) { Task task = null; eventAggregator.Publish(message, action => task = action.OnUIThreadAsync()); return task; } } }
namespace Caliburn.Micro { using System.Threading.Tasks; /// <summary> /// Extensions for <see cref="IEventAggregator"/>. /// </summary> public static class EventAggregatorExtensions { /// <summary> /// Publishes a message on the current thread (synchrone). /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void PublishOnCurrentThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, action => action()); } /// <summary> /// Publishes a message on a background thread (async). /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void PublishOnBackgroundThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, action => Task.Factory.StartNew(action)); } /// <summary> /// Publishes a message on the UI thread. /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void PublishOnUIThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, Execute.OnUIThread); } /// <summary> /// Publishes a message on the UI thread asynchrone. /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name = "message">The message instance.</param> public static void BeginPublishOnUIThread(this IEventAggregator eventAggregator, object message) { eventAggregator.Publish(message, Execute.BeginOnUIThread); } /// <summary> /// Publishes a message on the UI thread asynchrone. /// </summary> /// <param name="eventAggregator">The event aggregator.</param> /// <param name="message">The message instance.</param> public static Task PublishOnUIThreadAsync(this IEventAggregator eventAggregator, object message) { Task task = null; eventAggregator.Publish(message, action => task = action.OnUIThreadAsync()); return task; } } }
mit
C#
ac0fce327f1ca45c7909858bbb5796486a770956
refresh for windows
jamesmontemagno/app-coffeecups
CoffeeCups/View/CoffeesPage.xaml.cs
CoffeeCups/View/CoffeesPage.xaml.cs
using System; using System.Collections.Generic; using Xamarin.Forms; using Plugin.Connectivity; namespace CoffeeCups { public partial class CoffeesPage : ContentPage { CoffeesViewModel vm; public CoffeesPage() { InitializeComponent(); BindingContext = vm = new CoffeesViewModel(); ListViewCoffees.ItemTapped += (sender, e) => { if(Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Android) ListViewCoffees.SelectedItem = null; }; if (Device.OS != TargetPlatform.iOS && Device.OS != TargetPlatform.Android) { ToolbarItems.Add(new ToolbarItem { Text ="Refresh", Command=vm.LoadCoffeesCommand }); } } protected override void OnAppearing() { base.OnAppearing(); CrossConnectivity.Current.ConnectivityChanged += ConnecitvityChanged; //OfflineStack.IsVisible = !CrossConnectivity.Current.IsConnected; if (vm.Coffees.Count == 0) vm.LoadCoffeesCommand.Execute(null); } protected override void OnDisappearing() { base.OnDisappearing(); CrossConnectivity.Current.ConnectivityChanged -= ConnecitvityChanged; } void ConnecitvityChanged (object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e) { Device.BeginInvokeOnMainThread(() => { OfflineStack.IsVisible = !e.IsConnected; }); } } }
using System; using System.Collections.Generic; using Xamarin.Forms; using Plugin.Connectivity; namespace CoffeeCups { public partial class CoffeesPage : ContentPage { CoffeesViewModel vm; public CoffeesPage() { InitializeComponent(); BindingContext = vm = new CoffeesViewModel(); ListViewCoffees.ItemTapped += (sender, e) => { if(Device.OS == TargetPlatform.iOS || Device.OS == TargetPlatform.Android) ListViewCoffees.SelectedItem = null; }; if (Device.OS != TargetPlatform.iOS && Device.OS == TargetPlatform.Android) { ToolbarItems.Add(new ToolbarItem { Text ="Refresh", Command=vm.LoadCoffeesCommand }); } } protected override void OnAppearing() { base.OnAppearing(); CrossConnectivity.Current.ConnectivityChanged += ConnecitvityChanged; //OfflineStack.IsVisible = !CrossConnectivity.Current.IsConnected; if (vm.Coffees.Count == 0) vm.LoadCoffeesCommand.Execute(null); } protected override void OnDisappearing() { base.OnDisappearing(); CrossConnectivity.Current.ConnectivityChanged -= ConnecitvityChanged; } void ConnecitvityChanged (object sender, Plugin.Connectivity.Abstractions.ConnectivityChangedEventArgs e) { Device.BeginInvokeOnMainThread(() => { OfflineStack.IsVisible = !e.IsConnected; }); } } }
mit
C#
00c7f37cacc53b361d41321153dd8667eeb64c70
Build v0.4.1
AzarinSergey/umbraco-ditto,leekelleher/umbraco-ditto,Hendy/umbraco-ditto,robertjf/umbraco-ditto,rasmusjp/umbraco-ditto
src/Our.Umbraco.Ditto/Properties/VersionInfo.cs
src/Our.Umbraco.Ditto/Properties/VersionInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18449 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.4.*")] [assembly: AssemblyInformationalVersion("0.4.1")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18449 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("0.4.*")] [assembly: AssemblyInformationalVersion("0.4.0")]
mit
C#
21638033953c54df2995336eac93f1ba6208c1b8
change version of TAlex.Common.Diagnostics
T-Alex/Common
TAlex.Common.Diagnostics/Properties/AssemblyInfo.cs
TAlex.Common.Diagnostics/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("TAlex.Common.Diagnostics")] [assembly: AssemblyDescription("Set of diagnostic tools.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("T-Alex Software")] [assembly: AssemblyProduct("TAlex.Common.Diagnostics")] [assembly: AssemblyCopyright("Copyright © 2015 T-Alex Software")] [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("b32b57c8-a0c6-4ba6-9f28-ac2fd1216d7e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.2.1")] [assembly: AssemblyFileVersion("1.2.2.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("TAlex.Common.Diagnostics")] [assembly: AssemblyDescription("Set of diagnostic tools.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("T-Alex Software")] [assembly: AssemblyProduct("TAlex.Common.Diagnostics")] [assembly: AssemblyCopyright("Copyright © 2015 T-Alex Software")] [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("b32b57c8-a0c6-4ba6-9f28-ac2fd1216d7e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")]
mit
C#
4d67afb5ac913a1862db4573e125ceebdbb7e9e3
Fix IEntityTypeResolver service registration.
quartz-software/kephas,quartz-software/kephas
src/Kephas.Data.Client/Queries/Conversion/IEntityTypeResolver.cs
src/Kephas.Data.Client/Queries/Conversion/IEntityTypeResolver.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IEntityTypeResolver.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Declares the IEntityTypeResolver interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.Client.Queries.Conversion { using System; using Kephas.Reflection; using Kephas.Services; /// <summary> /// Interface for entity type resolver. /// </summary> [SharedAppServiceContract] public interface IEntityTypeResolver { /// <summary> /// Resolves an entity type based on the provided client entity type. /// </summary> /// <param name="clientEntityType">The client entity type.</param> /// <param name="throwOnNotFound">Indicates whether to throw or not when the indicated type is not found.</param> /// <returns> /// A <see cref="ITypeInfo"/>. /// </returns> Type ResolveEntityType(Type clientEntityType, bool throwOnNotFound = true); } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IEntityTypeResolver.cs" company="Quartz Software SRL"> // Copyright (c) Quartz Software SRL. All rights reserved. // </copyright> // <summary> // Declares the IEntityTypeResolver interface. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Kephas.Data.Client.Queries.Conversion { using System; using Kephas.Reflection; /// <summary> /// Interface for entity type resolver. /// </summary> public interface IEntityTypeResolver { /// <summary> /// Resolves an entity type based on the provided client entity type. /// </summary> /// <param name="clientEntityType">The client entity type.</param> /// <param name="throwOnNotFound">Indicates whether to throw or not when the indicated type is not found.</param> /// <returns> /// A <see cref="ITypeInfo"/>. /// </returns> Type ResolveEntityType(Type clientEntityType, bool throwOnNotFound = true); } }
mit
C#
bf9231ef76afef6e5b5434616d29c50a783651dd
Add DocumentId index to dashboard widgets (#8624)
xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2
src/OrchardCore.Modules/OrchardCore.AdminDashboard/Migrations.cs
src/OrchardCore.Modules/OrchardCore.AdminDashboard/Migrations.cs
using OrchardCore.Data.Migration; using OrchardCore.AdminDashboard.Indexes; using YesSql.Sql; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.Recipes.Services; using System.Threading.Tasks; namespace OrchardCore.AdminDashboard { public class Migrations : DataMigration { private IContentDefinitionManager _contentDefinitionManager; private readonly IRecipeMigrator _recipeMigrator; public Migrations(IContentDefinitionManager contentDefinitionManager, IRecipeMigrator recipeMigrator) { _contentDefinitionManager = contentDefinitionManager; _recipeMigrator = recipeMigrator; } public int Create() { SchemaBuilder.CreateMapIndexTable<DashboardPartIndex>(table => table .Column<double>("Position") ); SchemaBuilder.AlterIndexTable<DashboardPartIndex>(table => table .CreateIndex("IDX_DashboardPart_DocumentId", "DocumentId", nameof(DashboardPartIndex.Position)) ); _contentDefinitionManager.AlterPartDefinition("DashboardPart", builder => builder .Attachable() .WithDescription("Provides a way to add widgets to a dashboard.") ); return 1; } public async Task<int> UpdateFrom1Async() { await _recipeMigrator.ExecuteAsync("dashboard-widgets.recipe.json", this); // Shortcut other migration steps on new content definition schemas. return 3; } // This code can be removed in a later version. public int UpdateFrom2() { SchemaBuilder.AlterIndexTable<DashboardPartIndex>(table => table .CreateIndex("IDX_DashboardPart_DocumentId", "DocumentId", nameof(DashboardPartIndex.Position)) ); return 3; } } }
using OrchardCore.Data.Migration; using OrchardCore.AdminDashboard.Indexes; using YesSql.Sql; using OrchardCore.ContentManagement.Metadata; using OrchardCore.ContentManagement.Metadata.Settings; using OrchardCore.Recipes.Services; using System.Threading.Tasks; namespace OrchardCore.AdminDashboard { public class Migrations : DataMigration { private IContentDefinitionManager _contentDefinitionManager; private readonly IRecipeMigrator _recipeMigrator; public Migrations(IContentDefinitionManager contentDefinitionManager, IRecipeMigrator recipeMigrator) { _contentDefinitionManager = contentDefinitionManager; _recipeMigrator = recipeMigrator; } public int Create() { SchemaBuilder.CreateMapIndexTable<DashboardPartIndex>(table => table .Column<double>("Position") ); _contentDefinitionManager.AlterPartDefinition("DashboardPart", builder => builder .Attachable() .WithDescription("Provides a way to add widgets to a dashboard.") ); return 1; } public async Task<int> UpdateFrom1Async() { await _recipeMigrator.ExecuteAsync("dashboard-widgets.recipe.json", this); return 2; } } }
bsd-3-clause
C#
bb120b80f171b80b82688469635df6c1594f70bf
add hacky diagnostic mode.
atsushieno/managed-midi
tools/managed-midi-player-console/managed-midi-player-console.cs
tools/managed-midi-player-console/managed-midi-player-console.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using Commons.Music.Midi; using PortMidiSharp; using Timer = System.Timers.Timer; namespace Commons.Music.Midi.Player { public class Driver { static void ShowHelp () { Console.WriteLine (@" managed-midi-player-console [options] SMF-files(*.mid) Options: --help show this help. --device:x specifies MIDI output device by ID. --diagnose diagnose MIDI message outputs to console. "); Console.WriteLine ("List of MIDI output device IDs: "); foreach (var dev in MidiDeviceManager.AllDevices) if (dev.IsOutput) Console.WriteLine ("\t{0}: {1}", dev.ID, dev.Name); } public static void Main (string [] args) { int outdev = MidiDeviceManager.DefaultOutputDeviceID; var files = new List<string> (); bool diagnostic = false; if (args.Length == 0) { ShowHelp (); return; } foreach (var arg in args) { if (arg == "--help") { ShowHelp (); return; } else if (arg == "--diagnose") diagnostic = true; else if (arg.StartsWith ("--device:")) { if (!int.TryParse (arg.Substring (9), out outdev)) { ShowHelp (); Console.WriteLine (); Console.WriteLine ("Invalid MIDI output device ID."); return; } } else files.Add (arg); } var output = MidiDeviceManager.OpenOutput (outdev); foreach (var arg in files) { var parser = new SmfReader (File.OpenRead (arg)); parser.Parse (); var player = new PortMidiPlayer (output, parser.Music); DateTimeOffset start = DateTimeOffset.Now; if (diagnostic) player.MessageReceived += m => Console.WriteLine ("{0:06} {1:X08}", (DateTimeOffset.Now - start).TotalMilliseconds, m.Value); player.StartLoop (); player.PlayAsync (); Console.WriteLine ("empty line to quit, P to pause and resume"); while (true) { string line = Console.ReadLine (); if (line == "P") { if (player.State == PlayerState.Playing) player.PauseAsync (); else player.PlayAsync (); } else if (line == "") { player.Dispose (); break; } else Console.WriteLine ("what do you mean by '{0}' ?", line); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using Commons.Music.Midi; using PortMidiSharp; using Timer = System.Timers.Timer; namespace Commons.Music.Midi.Player { public class Driver { static void ShowHelp () { Console.WriteLine (@" managed-midi-player-console [options] SMF-files(*.mid) Options: --help show this help. --device:x specifies MIDI output device by ID. "); Console.WriteLine ("List of MIDI output device IDs: "); foreach (var dev in MidiDeviceManager.AllDevices) if (dev.IsOutput) Console.WriteLine ("\t{0}: {1}", dev.ID, dev.Name); } public static void Main (string [] args) { int outdev = MidiDeviceManager.DefaultOutputDeviceID; var files = new List<string> (); if (args.Length == 0) { ShowHelp (); return; } foreach (var arg in args) { if (arg == "--help") { ShowHelp (); return; } if (arg.StartsWith ("--device:")) { if (!int.TryParse (arg.Substring (9), out outdev)) { ShowHelp (); Console.WriteLine (); Console.WriteLine ("Invalid MIDI output device ID."); return; } } else files.Add (arg); } var output = MidiDeviceManager.OpenOutput (outdev); foreach (var arg in files) { var parser = new SmfReader (File.OpenRead (arg)); parser.Parse (); var player = new PortMidiPlayer (output, parser.Music); player.StartLoop (); player.PlayAsync (); Console.WriteLine ("empty line to quit, P to pause and resume"); while (true) { string line = Console.ReadLine (); if (line == "P") { if (player.State == PlayerState.Playing) player.PauseAsync (); else player.PlayAsync (); } else if (line == "") { player.Dispose (); break; } else Console.WriteLine ("what do you mean by '{0}' ?", line); } } } } }
mit
C#
0cb28eac5e794f3aeb5effea1b8aeec587ed5a2c
update endpoint
OfficeDev/O365-AspNetMVC-Unified-API-Connect,OfficeDev/O365-AspNetMVC-Microsoft-Graph-Connect,OfficeDev/O365-AspNetMVC-Unified-API-Connect
UnifiedApiConnect/Helpers/Settings.cs
UnifiedApiConnect/Helpers/Settings.cs
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. using System.Configuration; namespace UnifiedApiConnect.Helpers { public static class Settings { public static string ClientId => ConfigurationManager.AppSettings["ClientID"]; public static string ClientSecret => ConfigurationManager.AppSettings["ClientSecret"]; public static string AzureADAuthority = @"https://login.microsoftonline.com/common"; public static string LogoutAuthority = @"https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri="; public static string O365UnifiedAPIResource = @"https://graph.microsoft.com/"; public static string SendMessageUrl = @"https://graph.microsoft.com/v1.0/me/microsoft.graph.sendmail"; public static string GetMeUrl = @"https://graph.microsoft.com/v1.0/me"; public static string MessageBody => ConfigurationManager.AppSettings["MessageBody"]; public static string MessageSubject => ConfigurationManager.AppSettings["MessageSubject"]; } } //********************************************************* // //O365-AspNetMVC-Unified-API-Connect, https://github.com/OfficeDev/O365-AspNetMVC-Unified-API-Connect // //Copyright (c) Microsoft Corporation //All rights reserved. // // MIT License: // 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. // //*********************************************************
// Copyright (c) Microsoft. All rights reserved. Licensed under the MIT license. See full license at the bottom of this file. using System.Configuration; namespace UnifiedApiConnect.Helpers { public static class Settings { public static string ClientId => ConfigurationManager.AppSettings["ClientID"]; public static string ClientSecret => ConfigurationManager.AppSettings["ClientSecret"]; public static string AzureADAuthority = @"https://login.microsoftonline.com/common"; public static string LogoutAuthority = @"https://login.microsoftonline.com/common/oauth2/logout?post_logout_redirect_uri="; public static string O365UnifiedAPIResource = @"https://graph.microsoft.com/"; public static string SendMessageUrl = @"https://graph.microsoft.com/v1.0/me/sendmail"; public static string GetMeUrl = @"https://graph.microsoft.com/v1.0/me"; public static string MessageBody => ConfigurationManager.AppSettings["MessageBody"]; public static string MessageSubject => ConfigurationManager.AppSettings["MessageSubject"]; } } //********************************************************* // //O365-AspNetMVC-Unified-API-Connect, https://github.com/OfficeDev/O365-AspNetMVC-Unified-API-Connect // //Copyright (c) Microsoft Corporation //All rights reserved. // // MIT License: // 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. // //*********************************************************
mit
C#
749360981c97325820bb830e183f6a48d873e053
Add search box (back) to strings view
feliwir/openSage,feliwir/openSage
src/OpenSage.Game/Diagnostics/StringsView.cs
src/OpenSage.Game/Diagnostics/StringsView.cs
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using ImGuiNET; using OpenSage.Data.Csf; using OpenSage.Diagnostics.Util; namespace OpenSage.Diagnostics { internal sealed class StringsView : DiagnosticView { private readonly List<CsfLabel> _labels; private readonly byte[] _searchTextBuffer; private string _searchText; public override string DisplayName { get; } = "Strings"; public StringsView(DiagnosticViewContext context) : base(context) { _labels = new List<CsfLabel>(); _searchTextBuffer = new byte[32]; } protected override void DrawOverride(ref bool isGameViewFocused) { ImGui.PushItemWidth(-1); ImGuiUtility.InputText("##search", _searchTextBuffer, out var searchText); UpdateSearch(searchText); ImGui.PopItemWidth(); ImGui.BeginChild("strings", Vector2.Zero, false); ImGui.Columns(2, "CSF", true); ImGui.Separator(); ImGui.Text("Name"); ImGui.NextColumn(); ImGui.Text("Value"); ImGui.NextColumn(); ImGui.Separator(); foreach (var label in _labels) { ImGui.Text(label.Name); ImGui.NextColumn(); string value = null; if (label.Strings.Length > 0) { var csfString = label.Strings[0]; value = csfString.Value; } ImGui.Text(CleanText(value)); ImGui.NextColumn(); } ImGui.Columns(1, null, false); ImGui.EndChild(); } private void UpdateSearch(string searchText) { searchText = ImGuiUtility.TrimToNullByte(searchText); if (searchText == _searchText) { return; } _searchText = searchText; _labels.Clear(); foreach (var label in Context.Game.ContentManager.TranslationManager.Labels) { var matchesSearch = label.Name.Contains(searchText, StringComparison.OrdinalIgnoreCase) || label.Strings.Any(x => x.Value.Contains(searchText, StringComparison.OrdinalIgnoreCase)); if (matchesSearch) { _labels.Add(label); } } } private static string CleanText(string text) => (text ?? string.Empty).Replace("%", "%%"); } }
using ImGuiNET; using OpenSage.Content; namespace OpenSage.Diagnostics { internal sealed class StringsView : DiagnosticView { public override string DisplayName { get; } = "Strings"; public StringsView(DiagnosticViewContext context) : base(context) { } protected override void DrawOverride(ref bool isGameViewFocused) { ImGui.Columns(2, "CSF", true); ImGui.Separator(); ImGui.Text("Name"); ImGui.NextColumn(); ImGui.Text("Value"); ImGui.NextColumn(); ImGui.Separator(); foreach (var label in Game.ContentManager.TranslationManager.Labels) { ImGui.Text(label.Name); ImGui.NextColumn(); string value = null; if (label.Strings.Length > 0) { var csfString = label.Strings[0]; value = csfString.Value; } ImGui.Text(CleanText(value)); ImGui.NextColumn(); } ImGui.Columns(1, null, false); } private static string CleanText(string text) => (text ?? string.Empty).Replace("%", "%%"); } }
mit
C#
55ad5df104a4592d5a84a8daf3c7b494ada2bcba
Add some methods to NotesManagingUtilities
melanchall/drymidi,melanchall/drywetmidi,melanchall/drywetmidi
DryWetMidi/Smf/Interaction/NotesManager/NotesManagingUtilities.cs
DryWetMidi/Smf/Interaction/NotesManager/NotesManagingUtilities.cs
using System; using System.Collections.Generic; using System.Linq; namespace Melanchall.DryWetMidi.Smf.Interaction { public static class NotesManagingUtilities { #region Methods public static NotesManager ManageNotes(this EventsCollection eventsCollection, Comparison<MidiEvent> sameTimeEventsComparison = null) { if (eventsCollection == null) throw new ArgumentNullException(nameof(eventsCollection)); return new NotesManager(eventsCollection, sameTimeEventsComparison); } public static NotesManager ManageNotes(this TrackChunk trackChunk, Comparison<MidiEvent> sameTimeEventsComparison = null) { if (trackChunk == null) throw new ArgumentNullException(nameof(trackChunk)); return trackChunk.Events.ManageNotes(sameTimeEventsComparison); } public static IEnumerable<Note> GetNotes(this IEnumerable<TrackChunk> trackChunks) { if (trackChunks == null) throw new ArgumentNullException(nameof(trackChunks)); return trackChunks.SelectMany(c => c.ManageNotes().Notes) .OrderBy(n => n.Time); } public static IEnumerable<Note> GetNotes(this MidiFile file) { if (file == null) throw new ArgumentNullException(nameof(file)); return file.Chunks.OfType<TrackChunk>().GetNotes(); } public static IEnumerable<Note> GetNotesAtTime(this TrackChunk trackChunk, long time, bool exactMatch = true) { if (trackChunk == null) throw new ArgumentNullException(nameof(trackChunk)); if (time < 0) throw new ArgumentOutOfRangeException(nameof(time), time, "Time is negative."); return trackChunk.ManageNotes().GetNotesAtTime(time, exactMatch); } public static IEnumerable<Note> GetNotesAtTime(this IEnumerable<TrackChunk> trackChunks, long time, bool exactMatch = true) { if (trackChunks == null) throw new ArgumentNullException(nameof(trackChunks)); if (time < 0) throw new ArgumentOutOfRangeException(nameof(time), time, "Time is negative."); return trackChunks.SelectMany(c => c.GetNotesAtTime(time, exactMatch)); } public static IEnumerable<Note> GetNotesAtTime(this MidiFile file, long time, bool exactMatch = true) { if (file == null) throw new ArgumentNullException(nameof(file)); if (time < 0) throw new ArgumentOutOfRangeException(nameof(time), time, "Time is negative."); return file.Chunks.OfType<TrackChunk>().GetNotesAtTime(time, exactMatch); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace Melanchall.DryWetMidi.Smf.Interaction { public static class NotesManagingUtilities { #region Methods public static NotesManager ManageNotes(this EventsCollection eventsCollection, Comparison<MidiEvent> sameTimeEventsComparison = null) { if (eventsCollection == null) throw new ArgumentNullException(nameof(eventsCollection)); return new NotesManager(eventsCollection, sameTimeEventsComparison); } public static NotesManager ManageNotes(this TrackChunk trackChunk, Comparison<MidiEvent> sameTimeEventsComparison = null) { if (trackChunk == null) throw new ArgumentNullException(nameof(trackChunk)); return trackChunk.Events.ManageNotes(sameTimeEventsComparison); } public static IEnumerable<Note> GetNotes(this IEnumerable<TrackChunk> trackChunks) { if (trackChunks == null) throw new ArgumentNullException(nameof(trackChunks)); return trackChunks.SelectMany(c => c.ManageNotes().Notes) .OrderBy(n => n.Time); } public static IEnumerable<Note> GetNotes(this MidiFile file) { if (file == null) throw new ArgumentNullException(nameof(file)); return file.Chunks.OfType<TrackChunk>().GetNotes(); } #endregion } }
mit
C#
ea2b552ac91eb2f8ad39201888cfec499a6c8875
Fix an error in JournalEndCrewSession
jgoode/EDDiscovery,jthorpe4/EDDiscovery,mwerle/EDDiscovery,jgoode/EDDiscovery,mwerle/EDDiscovery
EDDiscovery/EliteDangerous/JournalEvents/JournalEndCrewSession.cs
EDDiscovery/EliteDangerous/JournalEvents/JournalEndCrewSession.cs
/* * Copyright © 2017 EDDiscovery development team * * 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. * * EDDiscovery is not affiliated with Frontier Developments plc. */ using Newtonsoft.Json.Linq; using System.Linq; namespace EDDiscovery.EliteDangerous.JournalEvents { // When written: when the captain in multicrew disbands the crew //Parameters: // OnCrime: (bool) true if crew disbanded as a result of a crime in a lawful session // { "timestamp":"2017-04-12T11:32:30Z", "event":"EndCrewSession", "OnCrime":false } [JournalEntryType(JournalTypeEnum.EndCrewSession)] public class JournalEndCrewSession : JournalEntry { public JournalEndCrewSession(JObject evt) : base(evt, JournalTypeEnum.EndCrewSession) { OnCrime = evt["OnCrime"].Bool(); } public bool OnCrime { get; set; } public override System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.crewmemberquits; } } public override void FillInformation(out string summary, out string info, out string detailed) //V { summary = EventTypeStr.SplitCapsWord(); info = Tools.FieldBuilder("; Crime", OnCrime); detailed = ""; } } }
/* * Copyright © 2017 EDDiscovery development team * * 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. * * EDDiscovery is not affiliated with Frontier Developments plc. */ using Newtonsoft.Json.Linq; using System.Linq; namespace EDDiscovery.EliteDangerous.JournalEvents { // When written: when the captain in multicrew disbands the crew //Parameters: // OnCrime: (bool) true if crew disbanded as a result of a crime in a lawful session // { "timestamp":"2017-04-12T11:32:30Z", "event":"EndCrewSession", "OnCrime":false } [JournalEntryType(JournalTypeEnum.EndCrewSession)] public class JournalEndCrewSession : JournalEntry { public JournalEndCrewSession(JObject evt) : base(evt, JournalTypeEnum.EndCrewSession) { OnCrime = evt["Name"].Bool(); } public bool OnCrime { get; set; } public override System.Drawing.Bitmap Icon { get { return EDDiscovery.Properties.Resources.crewmemberquits; } } public override void FillInformation(out string summary, out string info, out string detailed) //V { summary = EventTypeStr.SplitCapsWord(); info = Tools.FieldBuilder("; Crime", OnCrime); detailed = ""; } } }
apache-2.0
C#
f37f33512046707eef69a2cb3944338de819439d
allow alive check on cloud an self host
bitwarden/core,bitwarden/core,bitwarden/core,bitwarden/core
src/Notifications/Controllers/SendController.cs
src/Notifications/Controllers/SendController.cs
using System; using System.IO; using System.Text; using System.Threading.Tasks; using Bit.Core.Utilities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; namespace Bit.Notifications { [Authorize("Internal")] [SelfHosted(SelfHostedOnly = true)] public class SendController : Controller { private readonly IHubContext<NotificationsHub> _hubContext; public SendController(IHubContext<NotificationsHub> hubContext) { _hubContext = hubContext; } [HttpGet("~/alive")] [HttpGet("~/now")] [AllowAnonymous] [SelfHosted(SelfHostedOnly = false, NotSelfHostedOnly = false)] public DateTime GetAlive() { return DateTime.UtcNow; } [HttpPost("~/send")] public async Task PostSend() { using(var reader = new StreamReader(Request.Body, Encoding.UTF8)) { var notificationJson = await reader.ReadToEndAsync(); if(!string.IsNullOrWhiteSpace(notificationJson)) { await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext); } } } } }
using System; using System.IO; using System.Text; using System.Threading.Tasks; using Bit.Core.Utilities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.SignalR; namespace Bit.Notifications { [Authorize("Internal")] [SelfHosted(SelfHostedOnly = true)] public class SendController : Controller { private readonly IHubContext<NotificationsHub> _hubContext; public SendController(IHubContext<NotificationsHub> hubContext) { _hubContext = hubContext; } [HttpGet("~/alive")] [HttpGet("~/now")] [AllowAnonymous] public DateTime GetAlive() { return DateTime.UtcNow; } [HttpPost("~/send")] public async Task PostSend() { using(var reader = new StreamReader(Request.Body, Encoding.UTF8)) { var notificationJson = await reader.ReadToEndAsync(); if(!string.IsNullOrWhiteSpace(notificationJson)) { await HubHelpers.SendNotificationToHubAsync(notificationJson, _hubContext); } } } } }
agpl-3.0
C#
fa17e090f7115cdef7cf0253e5af45d16d7997c0
add some code annotation
Ahoo-Wang/SmartSql
src/SmartSql.DyRepository/StatementAttribute.cs
src/SmartSql.DyRepository/StatementAttribute.cs
using System; using System.Data; namespace SmartSql.DyRepository { /// <summary> /// SqlMap.Statement 映射 /// </summary> [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] public class StatementAttribute : Attribute { /// <summary> /// 定义 SmartSqlMap.Scope 该属性可选,默认使用仓储接口的Scope /// </summary> public string Scope { get; set; } /// <summary> /// 可选,默认使用函数名作为 Statement.Id /// </summary> public string Id { get; set; } /// <summary> /// 可选, 默认 Execute:Auto ,自动判断 执行类型 /// </summary> public ExecuteBehavior Execute { get; set; } = ExecuteBehavior.Auto; /// <summary> /// 可选,当不使用 SmartSqlMap.Statement 时可直接定义 Sql /// </summary> public string Sql { get; set; } } /// <summary> /// 执行行为 /// </summary> public enum ExecuteBehavior { /// <summary> /// 自动判断执行类型 /// </summary> Auto = 0, /// <summary> /// 返回受影响行数 /// </summary> Execute = 1, /// <summary> /// 返回结果的第一行第一列的值,主要用于返回主键 /// </summary> ExecuteScalar = 2, /// <summary> /// 查询枚举对象,List /// </summary> Query = 3, /// <summary> /// 查询单个对象 /// </summary> QuerySingle = 4, /// <summary> /// 返回DataTable /// </summary> GetDataTable = 5, /// <summary> /// 返回DataSet /// </summary> GetDataSet = 6 } }
using System; using System.Data; namespace SmartSql.DyRepository { public class StatementAttribute : Attribute { /// <summary> /// 定义 SmartSqlMap.Scope 该属性可选,默认使用仓储接口的Scope /// </summary> public string Scope { get; set; } /// <summary> /// 可选,默认使用函数名作为 Statement.Id /// </summary> public string Id { get; set; } /// <summary> /// 可选, 默认 Execute:Auto ,自动判断 执行类型 /// </summary> public ExecuteBehavior Execute { get; set; } = ExecuteBehavior.Auto; /// <summary> /// 可选,当不使用 SmartSqlMap.Statement 时可直接定义 Sql /// </summary> public string Sql { get; set; } } /// <summary> /// 执行行为 /// </summary> public enum ExecuteBehavior { /// <summary> /// 自动判断执行类型 /// </summary> Auto = 0, /// <summary> /// 返回受影响行数 /// </summary> Execute = 1, /// <summary> /// 返回结果的第一行第一列的值,主要用于返回主键 /// </summary> ExecuteScalar = 2, /// <summary> /// 查询枚举对象,List /// </summary> Query = 3, /// <summary> /// 查询单个对象 /// </summary> QuerySingle = 4, /// <summary> /// 返回DataTable /// </summary> GetDataTable = 5, /// <summary> /// 返回DataSet /// </summary> GetDataSet = 6 } }
apache-2.0
C#
d5afb429f4c77404e2ecfff69aac63ae074df5a6
Change debug to warn
volak/Aggregates.NET,volak/Aggregates.NET
src/Aggregates.NET/Internal/AsyncronizedInvoke.cs
src/Aggregates.NET/Internal/AsyncronizedInvoke.cs
 using NServiceBus; using NServiceBus.Logging; using NServiceBus.ObjectBuilder; using NServiceBus.Pipeline; using NServiceBus.Pipeline.Contexts; using NServiceBus.Sagas; using NServiceBus.Settings; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aggregates.Internal { public class AsyncronizedInvoke : IBehavior<IncomingContext> { private static ILog Logger = LogManager.GetLogger<AsyncronizedInvoke>(); public IBus Bus { get; set; } public ReadOnlySettings Settings { get; set; } public void Invoke(IncomingContext context, Action next) { var _slowAlert = Settings.Get<Int32>("SlowAlertThreshold"); ActiveSagaInstance saga; if (context.TryGet(out saga) && saga.NotFound && saga.SagaType == context.MessageHandler.Instance.GetType()) { next(); return; } var messageHandler = context.Get<AsyncMessageHandler>(); //var handleContext = new HandleContext { Bus = Bus, Context = context }; //messageHandler.Invocation(messageHandler.Handler, context.IncomingLogicalMessage.Instance, handleContext).Wait(); Task.Run((Func<Task>)(async () => { var s = Stopwatch.StartNew(); var handleContext = new HandleContext { Bus = Bus, Context = context }; await messageHandler.Invocation(messageHandler.Handler, context.IncomingLogicalMessage.Instance, handleContext); if (Logger.IsDebugEnabled) { Logger.DebugFormat("Executing message {0} on handler {1} took {2} ms", context.IncomingLogicalMessage.MessageType.FullName, messageHandler.Handler.GetType().FullName, s.ElapsedMilliseconds); } if(s.ElapsedMilliseconds > _slowAlert) { Logger.WarnFormat(" - SLOW ALERT - Executing message {0} on handler {1} took {2} ms", context.IncomingLogicalMessage.MessageType.FullName, messageHandler.Handler.GetType().FullName, s.ElapsedMilliseconds); } })).Wait(); next(); } } }
 using NServiceBus; using NServiceBus.Logging; using NServiceBus.ObjectBuilder; using NServiceBus.Pipeline; using NServiceBus.Pipeline.Contexts; using NServiceBus.Sagas; using NServiceBus.Settings; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Aggregates.Internal { public class AsyncronizedInvoke : IBehavior<IncomingContext> { private static ILog Logger = LogManager.GetLogger<AsyncronizedInvoke>(); public IBus Bus { get; set; } public ReadOnlySettings Settings { get; set; } public void Invoke(IncomingContext context, Action next) { var _slowAlert = Settings.Get<Int32>("SlowAlertThreshold"); ActiveSagaInstance saga; if (context.TryGet(out saga) && saga.NotFound && saga.SagaType == context.MessageHandler.Instance.GetType()) { next(); return; } var messageHandler = context.Get<AsyncMessageHandler>(); //var handleContext = new HandleContext { Bus = Bus, Context = context }; //messageHandler.Invocation(messageHandler.Handler, context.IncomingLogicalMessage.Instance, handleContext).Wait(); Task.Run((Func<Task>)(async () => { var s = Stopwatch.StartNew(); var handleContext = new HandleContext { Bus = Bus, Context = context }; await messageHandler.Invocation(messageHandler.Handler, context.IncomingLogicalMessage.Instance, handleContext); if (Logger.IsDebugEnabled) { Logger.DebugFormat("Executing message {0} on handler {1} took {2} ms", context.IncomingLogicalMessage.MessageType.FullName, messageHandler.Handler.GetType().FullName, s.ElapsedMilliseconds); } if(s.ElapsedMilliseconds > _slowAlert) { Logger.DebugFormat(" - SLOW ALERT - Executing message {0} on handler {1} took {2} ms", context.IncomingLogicalMessage.MessageType.FullName, messageHandler.Handler.GetType().FullName, s.ElapsedMilliseconds); } })).Wait(); next(); } } }
mit
C#
c646e99f668b7cb0d8ad682c3eb7ed44b40a4648
Add comments identifying the weakly typed enums
AArnott/pinvoke,jmelosegui/pinvoke,vbfox/pinvoke
src/Kernel32.Desktop/Kernel32+KEY_EVENT_RECORD.cs
src/Kernel32.Desktop/Kernel32+KEY_EVENT_RECORD.cs
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="KEY_EVENT_RECORD"/> nested type. /// </content> public partial class Kernel32 { /// <summary> /// Describes a keyboard input event in a console <see cref="INPUT_RECORD"/> structure. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct KEY_EVENT_RECORD { /// <summary> /// If the key is pressed, this member is TRUE. Otherwise, this member is FALSE (the key is released). /// </summary> [MarshalAs(UnmanagedType.Bool)] public bool bKeyDown; /// <summary> /// The repeat count, which indicates that a key is being held down. /// For example, when a key is held down, you might get five events with this member equal to 1, /// one event with this member equal to 5, or multiple events with this member greater than or equal to 1. /// </summary> public ushort wRepeatCount; /// <summary> /// A virtual-key code that identifies the given key in a device-independent manner. /// Possible values are in the User32.VirtualKey enum. /// </summary> public ushort wVirtualKeyCode; /// <summary> /// The virtual scan code of the given key that represents the device-dependent value generated by the keyboard hardware. /// Possible values are in the User32.ScanCode enum. /// </summary> public ushort wVirtualScanCode; /// <summary> /// A union of the Unicode and Ascii encodings. /// </summary> public CHAR_INFO_ENCODING uChar; /// <summary> /// The state of the control keys. /// </summary> public ControlKeyStates dwControlKeyState; } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; using System.Runtime.InteropServices; /// <content> /// Contains the <see cref="KEY_EVENT_RECORD"/> nested type. /// </content> public partial class Kernel32 { /// <summary> /// Describes a keyboard input event in a console <see cref="INPUT_RECORD"/> structure. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct KEY_EVENT_RECORD { /// <summary> /// If the key is pressed, this member is TRUE. Otherwise, this member is FALSE (the key is released). /// </summary> [MarshalAs(UnmanagedType.Bool)] public bool bKeyDown; /// <summary> /// The repeat count, which indicates that a key is being held down. /// For example, when a key is held down, you might get five events with this member equal to 1, /// one event with this member equal to 5, or multiple events with this member greater than or equal to 1. /// </summary> public ushort wRepeatCount; /// <summary> /// A virtual-key code that identifies the given key in a device-independent manner. /// </summary> public ushort wVirtualKeyCode; /// <summary> /// The virtual scan code of the given key that represents the device-dependent value generated by the keyboard hardware. /// </summary> public ushort wVirtualScanCode; /// <summary> /// A union of the Unicode and Ascii encodings. /// </summary> public CHAR_INFO_ENCODING uChar; /// <summary> /// The state of the control keys. /// </summary> public ControlKeyStates dwControlKeyState; } } }
mit
C#
8b1fb2e5e74700cd54c0187085046f151a1ac6a3
Fix GetLineText
KirillOsenkov/MSBuildStructuredLog,KirillOsenkov/MSBuildStructuredLog
src/StructuredLogViewer/SourceFiles/SourceText.cs
src/StructuredLogViewer/SourceFiles/SourceText.cs
using System; using System.Collections.Generic; namespace StructuredLogViewer { public class SourceText { public SourceText(string text) { Text = text; Lines = TextUtilities.GetLineSpans(text); } public string Text { get; } public Span[] Lines { get; } public IReadOnlyList<int> Find(string searchText) { var result = new List<int>(); var searchTextLength = searchText.Length; for (int i = 0; i < Lines.Length; i++) { var line = Lines[i]; if (line.Length >= searchTextLength) { int foundOffset = Text.IndexOf(searchText, line.Start, line.Length, StringComparison.OrdinalIgnoreCase); if (foundOffset >= line.Start && foundOffset < line.End - searchTextLength) { result.Add(i); } } } return result; } public string GetLineText(int lineNumber) { var line = Lines[lineNumber]; if (line.Length == 0) { return ""; } var end = line.End - 1; while (end >= line.Start && TextUtilities.IsLineBreakChar(Text[end])) { end--; } if (end < line.Start) { return ""; } return Text.Substring(line.Start, end - line.Start + 1); } } }
using System; using System.Collections.Generic; namespace StructuredLogViewer { public class SourceText { public SourceText(string text) { Text = text; Lines = TextUtilities.GetLineSpans(text); } public string Text { get; } public Span[] Lines { get; } public IReadOnlyList<int> Find(string searchText) { var result = new List<int>(); var searchTextLength = searchText.Length; for (int i = 0; i < Lines.Length; i++) { var line = Lines[i]; if (line.Length >= searchTextLength) { int foundOffset = Text.IndexOf(searchText, line.Start, line.Length, StringComparison.OrdinalIgnoreCase); if (foundOffset >= line.Start && foundOffset < line.End - searchTextLength) { result.Add(i); } } } return result; } public string GetLineText(int lineNumber) { var line = Lines[lineNumber]; var end = line.End - 1; while (TextUtilities.IsLineBreakChar(Text[end]) && end > line.Start) { end--; } return Text.Substring(line.Start, end - line.Start); } } }
mit
C#
953b2a905c4be7c05608e7b53ee0b277a73240fb
Make ElasticUpMigration public
XPCegeka/ElasticUp
ElasticUp/ElasticUp/Migration/ElasticUpMigration.cs
ElasticUp/ElasticUp/Migration/ElasticUpMigration.cs
using System; using System.Collections.Generic; using System.Linq; using ElasticUp.Operation; using ElasticUp.Migration.Meta; using Nest; namespace ElasticUp.Migration { public abstract class ElasticUpMigration { internal int MigrationNumber { get; } internal List<ElasticUpOperation> Operations { get; } public string IndexAlias { get; protected set; } protected ElasticUpMigration(int migrationNumber) { MigrationNumber = migrationNumber; Operations = new List<ElasticUpOperation>(); } public void Operation(ElasticUpOperation operation) { if(HasDuplicateOperationNumber(operation)) throw new ArgumentException("Duplicate operation number."); Operations.Add(operation); } public sealed override string ToString() { return $"{MigrationNumber:D3}_{this.GetType().Name}"; } public ElasticUpMigration OnIndexAlias(string indexAlias) { IndexAlias = indexAlias; return this; } internal void Execute(IElasticClient elasticClient, VersionedIndexName fromIndex, VersionedIndexName toIndex) { Operations.ForEach(o => o.Execute(elasticClient, fromIndex.ToString(), toIndex.ToString())); } private bool HasDuplicateOperationNumber(ElasticUpOperation operation) { return Operations.Any(o => o.OperationNumber == operation.OperationNumber); } } }
using System; using System.Collections.Generic; using System.Linq; using ElasticUp.Operation; using ElasticUp.Migration.Meta; using Nest; namespace ElasticUp.Migration { public abstract class ElasticUpMigration { internal int MigrationNumber { get; } internal List<ElasticUpOperation> Operations { get; } public string IndexAlias { get; protected set; } internal ElasticUpMigration(int migrationNumber) { MigrationNumber = migrationNumber; Operations = new List<ElasticUpOperation>(); } internal void Operation(ElasticUpOperation operation) { if(HasDuplicateOperationNumber(operation)) throw new ArgumentException("Duplicate operation number."); Operations.Add(operation); } public sealed override string ToString() { return $"{MigrationNumber:D3}_{this.GetType().Name}"; } public ElasticUpMigration OnIndexAlias(string indexAlias) { IndexAlias = indexAlias; return this; } internal void Execute(IElasticClient elasticClient, VersionedIndexName fromIndex, VersionedIndexName toIndex) { Operations.ForEach(o => o.Execute(elasticClient, fromIndex.ToString(), toIndex.ToString())); } private bool HasDuplicateOperationNumber(ElasticUpOperation operation) { return Operations.Any(o => o.OperationNumber == operation.OperationNumber); } } }
mit
C#
a754486689e38929dfbd97601c358ceb60bb11bd
Initialize back button control in intermediate control sets
ethanmoffat/EndlessClient
EndlessClient/ControlSets/IntermediateControlSet.cs
EndlessClient/ControlSets/IntermediateControlSet.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.Controllers; using EndlessClient.GameExecution; using EndlessClient.UIControls; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using XNAControls; namespace EndlessClient.ControlSets { public abstract class IntermediateControlSet : BackButtonControlSet { protected readonly KeyboardDispatcher _dispatcher; private readonly Texture2D[] _personSet2; private readonly Random _randomGen; private XNAButton _btnCreate; private PictureBox _person2Picture; protected IntermediateControlSet(KeyboardDispatcher dispatcher, IMainButtonController mainButtonController) : base(mainButtonController) { _dispatcher = dispatcher; _personSet2 = new Texture2D[8]; _randomGen = new Random(); } public override void InitializeResources(INativeGraphicsManager gfxManager, ContentManager xnaContentManager) { base.InitializeResources(gfxManager, xnaContentManager); for (int i = 0; i < _personSet2.Length; ++i) _personSet2[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 61 + i, true); } protected override void InitializeControlsHelper(IControlSet currentControlSet) { _btnCreate = GetControl(currentControlSet, GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, GetCreateButton); _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); _allComponents.Add(_btnCreate); _allComponents.Add(_person2Picture); base.InitializeControlsHelper(currentControlSet); } public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { switch (control) { case GameControlIdentifier.CreateAccountButton: return GameState == GameStates.CreateAccount ? _btnCreate : null; case GameControlIdentifier.CreateCharacterButton: return GameState == GameStates.LoggedIn ? _btnCreate : null; case GameControlIdentifier.PersonDisplay2: return _person2Picture; default: return base.FindComponentByControlIdentifier(control); } } protected virtual XNAButton GetCreateButton() { var isCreateCharacterButton = GameState == GameStates.LoggedIn; var button = new XNAButton(_secondaryButtonTexture, new Vector2(isCreateCharacterButton ? 334 : 359, 417), new Rectangle(0, 0, 120, 40), new Rectangle(120, 0, 120, 40)); return button; } private PictureBox GetPerson2Picture() { var texture = _personSet2[_randomGen.Next(8)]; return new PictureBox(texture) { DrawLocation = new Vector2(43, 140) }; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using EndlessClient.Controllers; using EndlessClient.GameExecution; using EndlessClient.UIControls; using EOLib.Graphics; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using XNAControls; namespace EndlessClient.ControlSets { public abstract class IntermediateControlSet : BackButtonControlSet { protected readonly KeyboardDispatcher _dispatcher; private readonly Texture2D[] _personSet2; private readonly Random _randomGen; private XNAButton _btnCreate; private PictureBox _person2Picture; protected IntermediateControlSet(KeyboardDispatcher dispatcher, IMainButtonController mainButtonController) : base(mainButtonController) { _dispatcher = dispatcher; _personSet2 = new Texture2D[8]; _randomGen = new Random(); } public override void InitializeResources(INativeGraphicsManager gfxManager, ContentManager xnaContentManager) { base.InitializeResources(gfxManager, xnaContentManager); for (int i = 0; i < _personSet2.Length; ++i) _personSet2[i] = gfxManager.TextureFromResource(GFXTypes.PreLoginUI, 61 + i, true); } protected override void InitializeControlsHelper(IControlSet currentControlSet) { _btnCreate = GetControl(currentControlSet, GameState == GameStates.LoggedIn ? GameControlIdentifier.CreateCharacterButton : GameControlIdentifier.CreateAccountButton, GetCreateButton); _person2Picture = GetControl(currentControlSet, GameControlIdentifier.PersonDisplay2, GetPerson2Picture); _allComponents.Add(_btnCreate); _allComponents.Add(_person2Picture); } public override IGameComponent FindComponentByControlIdentifier(GameControlIdentifier control) { switch (control) { case GameControlIdentifier.CreateAccountButton: return GameState == GameStates.CreateAccount ? _btnCreate : null; case GameControlIdentifier.CreateCharacterButton: return GameState == GameStates.LoggedIn ? _btnCreate : null; case GameControlIdentifier.PersonDisplay2: return _person2Picture; default: return base.FindComponentByControlIdentifier(control); } } protected virtual XNAButton GetCreateButton() { var isCreateCharacterButton = GameState == GameStates.LoggedIn; var button = new XNAButton(_secondaryButtonTexture, new Vector2(isCreateCharacterButton ? 334 : 359, 417), new Rectangle(0, 0, 120, 40), new Rectangle(120, 0, 120, 40)); return button; } private PictureBox GetPerson2Picture() { var texture = _personSet2[_randomGen.Next(8)]; return new PictureBox(texture) { DrawLocation = new Vector2(43, 140) }; } } }
mit
C#
708e44c95ae9b175e46a5efc3df8c9345d1b6163
Update Core.cs
syuilo/Misq
Misq/Core.cs
Misq/Core.cs
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace Misq { public static class Core { static Lazy<HttpClient> _client = new Lazy<HttpClient>(); /// <summary> /// APIにリクエストします。 /// </summary> /// <param name="host">MisskeyインスタンスのURL</param> /// <param name="endpoint">エンドポイント名</param> /// <param name="ps">パラメーター</param> /// <returns>レスポンス</returns> public static async Task<dynamic> Request(string host, string endpoint, Dictionary<string, object> ps) { var client = _client.Value; var ep = $"{host}/api/{endpoint}"; var content = new StringContent(JsonConvert.SerializeObject(ps), Encoding.UTF8, "application/json"); var res = await client.PostAsync(ep, content); var obj = JsonConvert.DeserializeObject<dynamic>( await res.Content.ReadAsStringAsync()); return obj; } /// <summary> /// APIにリクエストします。 /// </summary> /// <param name="host">MisskeyインスタンスのURL</param> /// <param name="endpoint">エンドポイント名</param> /// <param name="ps">パラメーター</param> /// <returns>レスポンス</returns> public static async Task<dynamic> RequestWithBinary(string host, string endpoint, MultipartFormDataContent ps) { var client = _client.Value; var ep = $"{host}/api/{endpoint}"; var res = await client.PostAsync(ep, ps); var obj = JsonConvert.DeserializeObject<dynamic>( await res.Content.ReadAsStringAsync()); return obj; } } }
using Newtonsoft.Json; using System.Collections.Generic; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace Misq { public static class Core { static Lazy<HttpClient> _client = new Lazy<HttpClient>(); /// <summary> /// APIにリクエストします。 /// </summary> /// <param name="host">MisskeyインスタンスのURL</param> /// <param name="endpoint">エンドポイント名</param> /// <param name="ps">パラメーター</param> /// <returns>レスポンス</returns> public static async Task<dynamic> Request(string host, string endpoint, Dictionary<string, object> ps) { var client = _client.Value; var ep = $"{host}/api/{endpoint}"; var content = new StringContent(JsonConvert.SerializeObject(ps), Encoding.UTF8, "application/json"); var res = await client.PostAsync(ep, content); var obj = JsonConvert.DeserializeObject<dynamic>( await res.Content.ReadAsStringAsync()); return obj; } /// <summary> /// APIにリクエストします。 /// </summary> /// <param name="host">MisskeyインスタンスのURL</param> /// <param name="endpoint">エンドポイント名</param> /// <param name="ps">パラメーター</param> /// <returns>レスポンス</returns> public static async Task<dynamic> RequestWithBinary(string host, string endpoint, MultipartFormDataContent ps) { var client = _client.Value; var ep = $"{host}/api/{endpoint}"; var res = await client.PostAsync(ep, ps); var obj = JsonConvert.DeserializeObject<dynamic>( await res.Content.ReadAsStringAsync()); return obj; } } }
mit
C#
8c26ab78bbbc0472ba9877690ad5ca64837e77a6
Remove use of Runtime.GetSystemVersion
jeffanders/roslyn,dotnet/roslyn,marksantos/roslyn,weltkante/roslyn,MihaMarkic/roslyn-prank,yjfxfjch/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,sharwell/roslyn,srivatsn/roslyn,dovzhikova/roslyn,Inverness/roslyn,evilc0des/roslyn,dpoeschl/roslyn,ErikSchierboom/roslyn,davkean/roslyn,budcribar/roslyn,rchande/roslyn,Maxwe11/roslyn,panopticoncentral/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,HellBrick/roslyn,nguerrera/roslyn,khyperia/roslyn,mgoertz-msft/roslyn,jrharmon/roslyn,drognanar/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,srivatsn/roslyn,xoofx/roslyn,droyad/roslyn,poizan42/roslyn,jaredpar/roslyn,bkoelman/roslyn,jasonmalinowski/roslyn,khellang/roslyn,poizan42/roslyn,ilyes14/roslyn,KamalRathnayake/roslyn,Giten2004/roslyn,vcsjones/roslyn,VSadov/roslyn,KevinRansom/roslyn,jrharmon/roslyn,sharwell/roslyn,EricArndt/roslyn,pdelvo/roslyn,KirillOsenkov/roslyn,tvand7093/roslyn,leppie/roslyn,mgoertz-msft/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,dpen2000/roslyn,lisong521/roslyn,supriyantomaftuh/roslyn,stephentoub/roslyn,robinsedlaczek/roslyn,akrisiun/roslyn,HellBrick/roslyn,AnthonyDGreen/roslyn,KirillOsenkov/roslyn,sharadagrawal/TestProject2,mavasani/roslyn,ilyes14/roslyn,grianggrai/roslyn,mirhagk/roslyn,jeremymeng/roslyn,mseamari/Stuff,natidea/roslyn,jcouv/roslyn,ericfe-ms/roslyn,dovzhikova/roslyn,tmeschter/roslyn,AmadeusW/roslyn,eriawan/roslyn,drognanar/roslyn,zooba/roslyn,taylorjonl/roslyn,BugraC/roslyn,dsplaisted/roslyn,vcsjones/roslyn,vcsjones/roslyn,KevinRansom/roslyn,tang7526/roslyn,cston/roslyn,mattscheffer/roslyn,michalhosala/roslyn,mavasani/roslyn,KiloBravoLima/roslyn,OmarTawfik/roslyn,sharwell/roslyn,paladique/roslyn,ahmedshuhel/roslyn,paulvanbrenk/roslyn,tmeschter/roslyn,mmitche/roslyn,jamesqo/roslyn,garryforreg/roslyn,GuilhermeSa/roslyn,enginekit/roslyn,danielcweber/roslyn,genlu/roslyn,abock/roslyn,ahmedshuhel/roslyn,taylorjonl/roslyn,zooba/roslyn,kienct89/roslyn,OmniSharp/roslyn,supriyantomaftuh/roslyn,huoxudong125/roslyn,stebet/roslyn,supriyantomaftuh/roslyn,moozzyk/roslyn,paulvanbrenk/roslyn,VSadov/roslyn,MihaMarkic/roslyn-prank,JakeGinnivan/roslyn,zmaruo/roslyn,diryboy/roslyn,DanielRosenwasser/roslyn,panopticoncentral/roslyn,diryboy/roslyn,ValentinRueda/roslyn,antonssonj/roslyn,FICTURE7/roslyn,basoundr/roslyn,ahmedshuhel/roslyn,BugraC/roslyn,leppie/roslyn,Pvlerick/roslyn,CaptainHayashi/roslyn,aelij/roslyn,tannergooding/roslyn,lorcanmooney/roslyn,Shiney/roslyn,jeremymeng/roslyn,orthoxerox/roslyn,cybernet14/roslyn,managed-commons/roslyn,natgla/roslyn,YOTOV-LIMITED/roslyn,jmarolf/roslyn,balajikris/roslyn,jroggeman/roslyn,REALTOBIZ/roslyn,panopticoncentral/roslyn,lorcanmooney/roslyn,CyrusNajmabadi/roslyn,TyOverby/roslyn,aanshibudhiraja/Roslyn,mattwar/roslyn,mavasani/roslyn,mirhagk/roslyn,khyperia/roslyn,heejaechang/roslyn,heejaechang/roslyn,VShangxiao/roslyn,swaroop-sridhar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,balajikris/roslyn,paladique/roslyn,wvdd007/roslyn,jrharmon/roslyn,MihaMarkic/roslyn-prank,Maxwe11/roslyn,jeremymeng/roslyn,paladique/roslyn,antonssonj/roslyn,mmitche/roslyn,tang7526/roslyn,bbarry/roslyn,oocx/roslyn,MattWindsor91/roslyn,rchande/roslyn,natidea/roslyn,mmitche/roslyn,VPashkov/roslyn,akrisiun/roslyn,tsdl2013/roslyn,oberxon/roslyn,paulvanbrenk/roslyn,Giten2004/roslyn,CyrusNajmabadi/roslyn,tmeschter/roslyn,AmadeusW/roslyn,sharadagrawal/TestProject2,jasonmalinowski/roslyn,gafter/roslyn,DanielRosenwasser/roslyn,GuilhermeSa/roslyn,jkotas/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,huoxudong125/roslyn,v-codeel/roslyn,3F/roslyn,eriawan/roslyn,MattWindsor91/roslyn,zooba/roslyn,oberxon/roslyn,shyamnamboodiripad/roslyn,jamesqo/roslyn,russpowers/roslyn,moozzyk/roslyn,jbhensley/roslyn,physhi/roslyn,yjfxfjch/roslyn,KashishArora/Roslyn,sharadagrawal/TestProject2,mirhagk/roslyn,AnthonyDGreen/roslyn,kelltrick/roslyn,AlexisArce/roslyn,doconnell565/roslyn,bkoelman/roslyn,3F/roslyn,MatthieuMEZIL/roslyn,srivatsn/roslyn,xasx/roslyn,ljw1004/roslyn,MichalStrehovsky/roslyn,kienct89/roslyn,jcouv/roslyn,pjmagee/roslyn,DanielRosenwasser/roslyn,RipCurrent/roslyn,stebet/roslyn,KevinRansom/roslyn,bbarry/roslyn,swaroop-sridhar/roslyn,xoofx/roslyn,hanu412/roslyn,jeffanders/roslyn,stjeong/roslyn,nemec/roslyn,DustinCampbell/roslyn,natgla/roslyn,antiufo/roslyn,jmarolf/roslyn,KamalRathnayake/roslyn,KashishArora/Roslyn,yeaicc/roslyn,thomaslevesque/roslyn,yjfxfjch/roslyn,tsdl2013/roslyn,AArnott/roslyn,swaroop-sridhar/roslyn,v-codeel/roslyn,chenxizhang/roslyn,yeaicc/roslyn,abock/roslyn,aelij/roslyn,a-ctor/roslyn,jbhensley/roslyn,OmniSharp/roslyn,stebet/roslyn,tang7526/roslyn,taylorjonl/roslyn,MichalStrehovsky/roslyn,AmadeusW/roslyn,shyamnamboodiripad/roslyn,reaction1989/roslyn,tmat/roslyn,CaptainHayashi/roslyn,HellBrick/roslyn,sharadagrawal/Roslyn,pjmagee/roslyn,michalhosala/roslyn,wvdd007/roslyn,tmat/roslyn,VShangxiao/roslyn,doconnell565/roslyn,russpowers/roslyn,Giftednewt/roslyn,MattWindsor91/roslyn,shyamnamboodiripad/roslyn,budcribar/roslyn,reaction1989/roslyn,garryforreg/roslyn,genlu/roslyn,mattscheffer/roslyn,jhendrixMSFT/roslyn,tvand7093/roslyn,jonatassaraiva/roslyn,ValentinRueda/roslyn,kelltrick/roslyn,grianggrai/roslyn,marksantos/roslyn,gafter/roslyn,GuilhermeSa/roslyn,RipCurrent/roslyn,diryboy/roslyn,dpen2000/roslyn,KiloBravoLima/roslyn,evilc0des/roslyn,danielcweber/roslyn,aanshibudhiraja/Roslyn,robinsedlaczek/roslyn,MattWindsor91/roslyn,chenxizhang/roslyn,xoofx/roslyn,ValentinRueda/roslyn,lorcanmooney/roslyn,poizan42/roslyn,khellang/roslyn,jeffanders/roslyn,KevinH-MS/roslyn,stephentoub/roslyn,budcribar/roslyn,furesoft/roslyn,nagyistoce/roslyn,tannergooding/roslyn,pjmagee/roslyn,REALTOBIZ/roslyn,VitalyTVA/roslyn,orthoxerox/roslyn,krishnarajbb/roslyn,ilyes14/roslyn,mattscheffer/roslyn,hanu412/roslyn,Giftednewt/roslyn,jhendrixMSFT/roslyn,mseamari/Stuff,khellang/roslyn,devharis/roslyn,MavenRain/roslyn,FICTURE7/roslyn,ljw1004/roslyn,chenxizhang/roslyn,grianggrai/roslyn,jroggeman/roslyn,MichalStrehovsky/roslyn,russpowers/roslyn,tvand7093/roslyn,thomaslevesque/roslyn,managed-commons/roslyn,pdelvo/roslyn,brettfo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,magicbing/roslyn,kuhlenh/roslyn,antiufo/roslyn,jaredpar/roslyn,dsplaisted/roslyn,jmarolf/roslyn,danielcweber/roslyn,bartdesmet/roslyn,mattwar/roslyn,jroggeman/roslyn,REALTOBIZ/roslyn,managed-commons/roslyn,AlexisArce/roslyn,Hosch250/roslyn,akrisiun/roslyn,bkoelman/roslyn,SeriaWei/roslyn,rgani/roslyn,BugraC/roslyn,MavenRain/roslyn,Hosch250/roslyn,VPashkov/roslyn,heejaechang/roslyn,aelij/roslyn,ericfe-ms/roslyn,kelltrick/roslyn,JakeGinnivan/roslyn,xasx/roslyn,enginekit/roslyn,EricArndt/roslyn,VitalyTVA/roslyn,tsdl2013/roslyn,TyOverby/roslyn,DustinCampbell/roslyn,DinoV/roslyn,ErikSchierboom/roslyn,sharadagrawal/Roslyn,EricArndt/roslyn,natgla/roslyn,krishnarajbb/roslyn,gafter/roslyn,nguerrera/roslyn,nguerrera/roslyn,enginekit/roslyn,bartdesmet/roslyn,kienct89/roslyn,Hosch250/roslyn,a-ctor/roslyn,jasonmalinowski/roslyn,basoundr/roslyn,vslsnap/roslyn,eriawan/roslyn,krishnarajbb/roslyn,jhendrixMSFT/roslyn,SeriaWei/roslyn,a-ctor/roslyn,davkean/roslyn,TyOverby/roslyn,xasx/roslyn,droyad/roslyn,Maxwe11/roslyn,amcasey/roslyn,OmarTawfik/roslyn,JakeGinnivan/roslyn,DustinCampbell/roslyn,robinsedlaczek/roslyn,jkotas/roslyn,FICTURE7/roslyn,pdelvo/roslyn,tmat/roslyn,kuhlenh/roslyn,weltkante/roslyn,natidea/roslyn,v-codeel/roslyn,droyad/roslyn,vslsnap/roslyn,KevinH-MS/roslyn,OmniSharp/roslyn,devharis/roslyn,DinoV/roslyn,amcasey/roslyn,KiloBravoLima/roslyn,Pvlerick/roslyn,doconnell565/roslyn,tannergooding/roslyn,ericfe-ms/roslyn,oberxon/roslyn,jaredpar/roslyn,dpoeschl/roslyn,dpoeschl/roslyn,magicbing/roslyn,VShangxiao/roslyn,davkean/roslyn,nagyistoce/roslyn,evilc0des/roslyn,mattwar/roslyn,dsplaisted/roslyn,furesoft/roslyn,antiufo/roslyn,rgani/roslyn,AnthonyDGreen/roslyn,Shiney/roslyn,Giten2004/roslyn,Giftednewt/roslyn,drognanar/roslyn,Pvlerick/roslyn,khyperia/roslyn,VitalyTVA/roslyn,oocx/roslyn,genlu/roslyn,jonatassaraiva/roslyn,AArnott/roslyn,nemec/roslyn,devharis/roslyn,basoundr/roslyn,sharadagrawal/Roslyn,abock/roslyn,AlekseyTs/roslyn,moozzyk/roslyn,KamalRathnayake/roslyn,jonatassaraiva/roslyn,AlexisArce/roslyn,kuhlenh/roslyn,AlekseyTs/roslyn,Shiney/roslyn,ljw1004/roslyn,marksantos/roslyn,jamesqo/roslyn,agocke/roslyn,3F/roslyn,yeaicc/roslyn,aanshibudhiraja/Roslyn,AlekseyTs/roslyn,huoxudong125/roslyn,orthoxerox/roslyn,KashishArora/Roslyn,jbhensley/roslyn,lisong521/roslyn,brettfo/roslyn,Inverness/roslyn,AArnott/roslyn,nagyistoce/roslyn,furesoft/roslyn,brettfo/roslyn,oocx/roslyn,physhi/roslyn,agocke/roslyn,stjeong/roslyn,dotnet/roslyn,CyrusNajmabadi/roslyn,zmaruo/roslyn,cston/roslyn,Inverness/roslyn,wvdd007/roslyn,thomaslevesque/roslyn,VPashkov/roslyn,SeriaWei/roslyn,magicbing/roslyn,antonssonj/roslyn,leppie/roslyn,lisong521/roslyn,physhi/roslyn,rchande/roslyn,cybernet14/roslyn,DinoV/roslyn,amcasey/roslyn,dpen2000/roslyn,agocke/roslyn,MatthieuMEZIL/roslyn,jcouv/roslyn,garryforreg/roslyn,stjeong/roslyn,YOTOV-LIMITED/roslyn,reaction1989/roslyn,stephentoub/roslyn,weltkante/roslyn,mseamari/Stuff,cston/roslyn,MavenRain/roslyn,KevinH-MS/roslyn,hanu412/roslyn,michalhosala/roslyn,balajikris/roslyn,rgani/roslyn,vslsnap/roslyn,YOTOV-LIMITED/roslyn,RipCurrent/roslyn,zmaruo/roslyn,OmarTawfik/roslyn,cybernet14/roslyn,dovzhikova/roslyn,MatthieuMEZIL/roslyn,bbarry/roslyn,nemec/roslyn
src/Compilers/Core/Desktop/Interop/ClrStrongName.cs
src/Compilers/Core/Desktop/Interop/ClrStrongName.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.CodeAnalysis.Interop { internal static class ClrStrongName { [DllImport("mscoree.dll", PreserveSig = false, EntryPoint = "CLRCreateInstance")] [return: MarshalAs(UnmanagedType.Interface)] private static extern object nCreateInterface( [MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid); internal static IClrStrongName GetInstance() { var metaHostClsid = new Guid(0x9280188D, 0xE8E, 0x4867, 0xB3, 0xC, 0x7F, 0xA8, 0x38, 0x84, 0xE8, 0xDE); var metaHostGuid = new Guid(0xD332DB9E, 0xB9B3, 0x4125, 0x82, 0x07, 0xA1, 0x48, 0x84, 0xF5, 0x32, 0x16); var clrStrongNameClsid = new Guid(0xB79B0ACD, 0xF5CD, 0x409b, 0xB5, 0xA5, 0xA1, 0x62, 0x44, 0x61, 0x0B, 0x92); var clrRuntimeInfoGuid = new Guid(0xBD39D1D2, 0xBA2F, 0x486A, 0x89, 0xB0, 0xB4, 0xB0, 0xCB, 0x46, 0x68, 0x91); var clrStrongNameGuid = new Guid(0x9FD93CCF, 0x3280, 0x4391, 0xB3, 0xA9, 0x96, 0xE1, 0xCD, 0xE7, 0x7C, 0x8D); var metaHost = (IClrMetaHost)nCreateInterface(metaHostClsid, metaHostGuid); var runtime = (IClrRuntimeInfo)metaHost.GetRuntime(GetRuntimeVersion(), clrRuntimeInfoGuid); return (IClrStrongName)runtime.GetInterface(clrStrongNameClsid, clrStrongNameGuid); } internal static string GetRuntimeVersion() { // When running in a complus environment we must respect the specified CLR version. This // important to keeping internal builds runnning. if (!string.IsNullOrEmpty(Environment.GetEnvironmentVariable("COMPLUS_InstallRoot"))) { var version = Environment.GetEnvironmentVariable("COMPLUS_Version"); if (!string.IsNullOrEmpty(version)) { return version; } } return "v4.0.30319"; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.CodeAnalysis.Interop { internal static class ClrStrongName { [DllImport("mscoree.dll", PreserveSig = false, EntryPoint = "CLRCreateInstance")] [return: MarshalAs(UnmanagedType.Interface)] private static extern object nCreateInterface( [MarshalAs(UnmanagedType.LPStruct)] Guid clsid, [MarshalAs(UnmanagedType.LPStruct)] Guid riid); internal static IClrStrongName GetInstance() { var metaHostClsid = new Guid(0x9280188D, 0xE8E, 0x4867, 0xB3, 0xC, 0x7F, 0xA8, 0x38, 0x84, 0xE8, 0xDE); var metaHostGuid = new Guid(0xD332DB9E, 0xB9B3, 0x4125, 0x82, 0x07, 0xA1, 0x48, 0x84, 0xF5, 0x32, 0x16); var clrStrongNameClsid = new Guid(0xB79B0ACD, 0xF5CD, 0x409b, 0xB5, 0xA5, 0xA1, 0x62, 0x44, 0x61, 0x0B, 0x92); var clrRuntimeInfoGuid = new Guid(0xBD39D1D2, 0xBA2F, 0x486A, 0x89, 0xB0, 0xB4, 0xB0, 0xCB, 0x46, 0x68, 0x91); var clrStrongNameGuid = new Guid(0x9FD93CCF, 0x3280, 0x4391, 0xB3, 0xA9, 0x96, 0xE1, 0xCD, 0xE7, 0x7C, 0x8D); var metaHost = (IClrMetaHost)nCreateInterface(metaHostClsid, metaHostGuid); var runtime = (IClrRuntimeInfo)metaHost.GetRuntime(RuntimeEnvironment.GetSystemVersion(), clrRuntimeInfoGuid); return (IClrStrongName)runtime.GetInterface(clrStrongNameClsid, clrStrongNameGuid); } } }
mit
C#
a33520fcd90bce20cb398edd82828744343b9da4
Update DocumentTextBindingBehavior.cs
wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D/Behaviors/DocumentTextBindingBehavior.cs
src/Core2D/Behaviors/DocumentTextBindingBehavior.cs
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Xaml.Interactivity; using AvaloniaEdit; namespace Core2D.Behaviors { public class DocumentTextBindingBehavior : Behavior<TextEditor> { private TextEditor _textEditor = null; public static readonly StyledProperty<string> TextProperty = AvaloniaProperty.Register<DocumentTextBindingBehavior, string>(nameof(Text)); public string Text { get => GetValue(TextProperty); set => SetValue(TextProperty, value); } protected override void OnAttached() { base.OnAttached(); if (AssociatedObject is TextEditor textEditor) { _textEditor = textEditor; _textEditor.TextChanged += TextChanged; this.GetObservable(TextProperty).Subscribe(TextPropertyChanged); } } protected override void OnDetaching() { base.OnDetaching(); if (_textEditor != null) { _textEditor.TextChanged -= TextChanged; } } private void TextChanged(object sender, EventArgs eventArgs) { if (_textEditor?.Document != null) { Text = _textEditor.Document.Text; } } private void TextPropertyChanged(string text) { if (_textEditor?.Document != null && text != null) { var caretOffset = _textEditor.CaretOffset; _textEditor.Document.Text = text; _textEditor.CaretOffset = caretOffset; } } } }
using System; using Avalonia; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Xaml.Interactivity; using AvaloniaEdit; namespace Core2D.Behaviors { public class DocumentTextBindingBehavior : Behavior<TextEditor> { private TextEditor _textEditor = null; public static readonly StyledProperty<string> TextProperty = AvaloniaProperty.Register<DocumentTextBindingBehavior, string>(nameof(Text)); public string Text { get => GetValue(TextProperty); set => SetValue(TextProperty, value); } protected override void OnAttached() { base.OnAttached(); if (AssociatedObject is TextEditor textEditor) { _textEditor = textEditor; _textEditor.TextChanged += TextChanged; this.GetObservable(TextProperty).Subscribe(TextPropertyChanged); } } protected override void OnDetaching() { base.OnDetaching(); if (_textEditor != null) { _textEditor.TextChanged -= TextChanged; } } private void TextChanged(object sender, EventArgs eventArgs) { if (_textEditor != null && _textEditor.Document != null) { Text = _textEditor.Document.Text; } } private void TextPropertyChanged(string text) { if (_textEditor != null && _textEditor.Document != null && text != null) { var caretOffset = _textEditor.CaretOffset; _textEditor.Document.Text = text; _textEditor.CaretOffset = caretOffset; } } } }
mit
C#
18f0ea05190c3e12f5b8a4f64a9aa94119d720d5
Remove Editor code from ActionLibrary
mbbarange/hivemind,rev087/hivemind
ActionLibrary.cs
ActionLibrary.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace Hivemind { public enum GUIField { BoundsField, ColorField, CurveField, EnumMaskField, EnumPopup, FloatField, IntField, IntSlider, LayerField, RectField, TagField, TextField, Toggle, ToggleLeft, Vector2Field, Vector3Field, Vector4Field } [System.AttributeUsage(System.AttributeTargets.Method)] public class ActionAttribute : System.Attribute { public ActionAttribute() {} } [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true)] public class ParameterAttribute : System.Attribute { public string name; public System.Type type; public GUIField guiField; public ParameterAttribute(string parameterName, System.Type parameterType) { name = parameterName; type = parameterType; throw new System.NotImplementedException("ParameterAttribute not implemented"); } public ParameterAttribute(string parameterName, System.Type parameterType, GUIField parameterGUIField) { name = parameterName; type = parameterType; guiField = parameterGUIField; throw new System.NotImplementedException("ParameterAttribute not implemented"); } } [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true)] public class ExpectsAttribute : System.Attribute { public string key; public System.Type type; public ExpectsAttribute(string inputKey, System.Type inputType) { key = inputKey; type = inputType; } } [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true)] public class OutputsAttribute : System.Attribute { public string key; public System.Type type; public OutputsAttribute(string outputKey, System.Type outputType) { key = outputKey; type = outputType; } } public abstract class ActionLibrary { public GameObject agent; public Context context; } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; namespace Hivemind { public enum GUIField { BoundsField, ColorField, CurveField, EnumMaskField, EnumPopup, FloatField, IntField, IntSlider, LayerField, RectField, TagField, TextField, Toggle, ToggleLeft, Vector2Field, Vector3Field, Vector4Field } [System.AttributeUsage(System.AttributeTargets.Method)] public class ActionAttribute : System.Attribute { public ActionAttribute() {} } [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true)] public class ParameterAttribute : System.Attribute { public string name; public System.Type type; public GUIField guiField; public ParameterAttribute(string parameterName, System.Type parameterType) { name = parameterName; type = parameterType; throw new System.NotImplementedException("ParameterAttribute not implemented"); } public ParameterAttribute(string parameterName, System.Type parameterType, GUIField parameterGUIField) { name = parameterName; type = parameterType; guiField = parameterGUIField; throw new System.NotImplementedException("ParameterAttribute not implemented"); } } [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true)] public class ExpectsAttribute : System.Attribute { public string key; public System.Type type; public ExpectsAttribute(string inputKey, System.Type inputType) { key = inputKey; type = inputType; } } [System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple=true)] public class OutputsAttribute : System.Attribute { public string key; public System.Type type; public OutputsAttribute(string outputKey, System.Type outputType) { key = outputKey; type = outputType; } } public abstract class ActionLibrary { public GameObject agent; public Context context; } }
mit
C#
4d4e03e20e449102d0bcaeb91911dc15e483a526
fix warning
boformer/BuildingThemes
BuildingThemes/Detour/DistrictWorldInfoPanelDetour.cs
BuildingThemes/Detour/DistrictWorldInfoPanelDetour.cs
using System.Reflection; using ColossalFramework.UI; using UnityEngine; namespace BuildingThemes.Detour { public class DistrictWorldInfoPanelDetour : DistrictWorldInfoPanel { private static bool deployed = false; private static RedirectCallsState _state; private static MethodInfo _original; private static MethodInfo _detour; public static void Deploy() { if (!deployed) { _original = typeof(DistrictWorldInfoPanel).GetMethod("OnPoliciesClick", BindingFlags.Instance | BindingFlags.Public); _detour = typeof(DistrictWorldInfoPanelDetour).GetMethod("OnPoliciesClick", BindingFlags.Instance | BindingFlags.Public); _state = RedirectionHelper.RedirectCalls(_original, _detour); deployed = true; Debugger.Log("Building Themes: DistrictWorldInfoPanel Methods detoured!"); } } public static void Revert() { if (deployed) { RedirectionHelper.RevertRedirect(_original, _state); _original = null; _detour = null; deployed = false; Debugger.Log("Building Themes: DistrictWorldInfoPanel Methods restored!"); } } public new void OnPoliciesClick() { if ((Object)ToolsModifierControl.GetTool<DistrictTool>() != (Object)ToolsModifierControl.GetCurrentTool<DistrictTool>()) ToolsModifierControl.keepThisWorldInfoPanel = true; ToolsModifierControl.mainToolbar.ShowPoliciesPanel(this.m_InstanceID.District); UIView.Find<UIPanel>("PoliciesPanel").Find<UITabstrip>("Tabstrip").selectedIndex = 0; } } }
using System.Reflection; using ColossalFramework.UI; using UnityEngine; namespace BuildingThemes.Detour { public class DistrictWorldInfoPanelDetour : DistrictWorldInfoPanel { private static bool deployed = false; private static RedirectCallsState _state; private static MethodInfo _original; private static MethodInfo _detour; public static void Deploy() { if (!deployed) { _original = typeof(DistrictWorldInfoPanel).GetMethod("OnPoliciesClick", BindingFlags.Instance | BindingFlags.Public); _detour = typeof(DistrictWorldInfoPanelDetour).GetMethod("OnPoliciesClick", BindingFlags.Instance | BindingFlags.Public); _state = RedirectionHelper.RedirectCalls(_original, _detour); deployed = true; Debugger.Log("Building Themes: DistrictWorldInfoPanel Methods detoured!"); } } public static void Revert() { if (deployed) { RedirectionHelper.RevertRedirect(_original, _state); _original = null; _detour = null; deployed = false; Debugger.Log("Building Themes: DistrictWorldInfoPanel Methods restored!"); } } public void OnPoliciesClick() { if ((Object)ToolsModifierControl.GetTool<DistrictTool>() != (Object)ToolsModifierControl.GetCurrentTool<DistrictTool>()) ToolsModifierControl.keepThisWorldInfoPanel = true; ToolsModifierControl.mainToolbar.ShowPoliciesPanel(this.m_InstanceID.District); UIView.Find<UIPanel>("PoliciesPanel").Find<UITabstrip>("Tabstrip").selectedIndex = 0; } } }
mit
C#
b6f1ab58f0ab18d920d626036467d97d925dacd8
Hide invisible letters.
ethankennerly/flash-unity-port-example
Assets/Scripts/View.cs
Assets/Scripts/View.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class View { private Model model; private GameObject main; public View(Model theModel, GameObject theMainScene) { model = theModel; main = theMainScene; } public void Update() { updateLetters(main, model.word); } /** * Find could be cached. * http://gamedev.stackexchange.com/questions/15601/find-all-game-objects-with-an-input-string-name-not-tag/15617#15617 */ private void updateLetters(GameObject parent, ArrayList letters) { int max = model.letterMax; for (int i = 0; i < max; i++) { string name = "Letter_" + i; GameObject letter = GameObject.Find(name); if (null != letter) { bool visible = i < letters.Count; letter.SetActive(visible); if (visible) { GameObject text3d = letter.transform.Find("text3d").gameObject; TextMesh mesh = text3d.GetComponent<TextMesh>(); mesh.text = (string) letters[i]; } } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class View { private Model model; private GameObject main; public View(Model theModel, GameObject theMainScene) { model = theModel; main = theMainScene; } public void Update() { updateLetters(main, model.word); } /** * Find could be cached. * http://gamedev.stackexchange.com/questions/15601/find-all-game-objects-with-an-input-string-name-not-tag/15617#15617 */ private void updateLetters(GameObject parent, ArrayList letters) { int max = model.letterMax; for (int i = 0; i < max; i++) { string name = "Letter_" + i; GameObject letter = GameObject.Find(name); if (null != letter) { Debug.Log("View.updateLetters: <" + letters[i] + ">"); bool visible = i < letters.Count; letter.SetActive(visible); if (visible) { GameObject text3d = letter.transform.Find("text3d").gameObject; TextMesh mesh = text3d.GetComponent<TextMesh>(); mesh.text = (string) letters[i]; } } } } }
mit
C#
0288444ab1f35761138b07db533413fcb1354a51
Increase number of list items in report page.
wsv-accidis/sjoslaget,wsv-accidis/sjoslaget,wsv-accidis/sjoslaget,wsv-accidis/sjoslaget
SjoslagetBackend/Controllers/ReportingController.cs
SjoslagetBackend/Controllers/ReportingController.cs
using System; using System.Threading.Tasks; using System.Web.Hosting; using System.Web.Http; using Accidis.Sjoslaget.WebService.Models; using Accidis.Sjoslaget.WebService.Services; using Accidis.WebServices.Auth; using Accidis.WebServices.Db; using Accidis.WebServices.Web; namespace Accidis.Sjoslaget.WebService.Controllers { public sealed class ReportingController : ApiController { readonly CruiseRepository _cruiseRepository; readonly ReportingService _reportingService; readonly ReportRepository _reportRepository; public ReportingController(CruiseRepository cruiseRepository, ReportingService reportingService, ReportRepository reportRepository) { _cruiseRepository = cruiseRepository; _reportingService = reportingService; _reportRepository = reportRepository; } [Authorize(Roles = Roles.Admin)] [HttpGet] public async Task<IHttpActionResult> Current() { var cruise = await _cruiseRepository.GetActiveAsync(); if(null == cruise) return NotFound(); using(var db = DbUtil.Open()) { return this.OkCacheControl(new { AgeDistribution = await _reportingService.GetAgeDistribution(db, cruise), BookingsByPayment = await _reportingService.GetNumberOfBookingsByPaymentStatus(db, cruise), Genders = await _reportingService.GetGenders(db, cruise), TopContacts = await _reportingService.GetTopContacts(db, cruise, 15), TopGroups = await _reportingService.GetTopGroups(db, cruise, 15) }, WebConfig.DynamicDataMaxAge); } } [Authorize(Roles = Roles.Admin)] [HttpGet] public async Task<IHttpActionResult> Summary() { var cruise = await _cruiseRepository.GetActiveAsync(); if(null == cruise) return NotFound(); Report[] reports = await _reportRepository.GetActiveAsync(cruise); return this.OkCacheControl(ReportSummary.FromReports(reports), WebConfig.DynamicDataMaxAge); } // This is a GET so we can trigger it from a scheduled monitoring task // We also generate reports from BookingsController [HttpGet] public IHttpActionResult Update() { HostingEnvironment.QueueBackgroundWorkItem(ct => _reportingService.GenerateReportsAsync()); return this.OkNoCache(String.Empty); } } }
using System; using System.Threading.Tasks; using System.Web.Hosting; using System.Web.Http; using Accidis.Sjoslaget.WebService.Models; using Accidis.Sjoslaget.WebService.Services; using Accidis.WebServices.Auth; using Accidis.WebServices.Db; using Accidis.WebServices.Web; namespace Accidis.Sjoslaget.WebService.Controllers { public sealed class ReportingController : ApiController { readonly CruiseRepository _cruiseRepository; readonly ReportingService _reportingService; readonly ReportRepository _reportRepository; public ReportingController(CruiseRepository cruiseRepository, ReportingService reportingService, ReportRepository reportRepository) { _cruiseRepository = cruiseRepository; _reportingService = reportingService; _reportRepository = reportRepository; } [Authorize(Roles = Roles.Admin)] [HttpGet] public async Task<IHttpActionResult> Current() { var cruise = await _cruiseRepository.GetActiveAsync(); if(null == cruise) return NotFound(); using(var db = DbUtil.Open()) { return this.OkCacheControl(new { AgeDistribution = await _reportingService.GetAgeDistribution(db, cruise), BookingsByPayment = await _reportingService.GetNumberOfBookingsByPaymentStatus(db, cruise), Genders = await _reportingService.GetGenders(db, cruise), TopContacts = await _reportingService.GetTopContacts(db, cruise, 10), TopGroups = await _reportingService.GetTopGroups(db, cruise, 10) }, WebConfig.DynamicDataMaxAge); } } [Authorize(Roles = Roles.Admin)] [HttpGet] public async Task<IHttpActionResult> Summary() { var cruise = await _cruiseRepository.GetActiveAsync(); if(null == cruise) return NotFound(); Report[] reports = await _reportRepository.GetActiveAsync(cruise); return this.OkCacheControl(ReportSummary.FromReports(reports), WebConfig.DynamicDataMaxAge); } // This is a GET so we can trigger it from a scheduled monitoring task // We also generate reports from BookingsController [HttpGet] public IHttpActionResult Update() { HostingEnvironment.QueueBackgroundWorkItem(ct => _reportingService.GenerateReportsAsync()); return this.OkNoCache(String.Empty); } } }
apache-2.0
C#
b34b6a829f87db1d820828847beed8b9732acab6
Fix saving changes when seeding data
denismaster/dcs,denismaster/dcs,denismaster/dcs,denismaster/dcs
src/Diploms.DataLayer/DiplomContextExtensions.cs
src/Diploms.DataLayer/DiplomContextExtensions.cs
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } context.SaveChanges(); } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
using System; using System.Linq; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Diploms.Core; using System.Collections.Generic; namespace Diploms.DataLayer { public static class DiplomContentSystemExtensions { public static void EnsureSeedData(this DiplomContext context) { if (context.AllMigrationsApplied()) { if (!context.Roles.Any()) { context.Roles.AddRange(Role.Admin, Role.Owner, Role.Student, Role.Teacher); context.SaveChanges(); } if(!context.Users.Any()) { context.Users.Add(new User{ Id = 1, Login = "admin", PasswordHash = @"WgHWgYQpzkpETS0VemCGE15u2LNPjTbtocMdxtqLll8=", Roles = new List<UserRole> { new UserRole { UserId = 1, RoleId = 1 } } }); } } } private static bool AllMigrationsApplied(this DiplomContext context) { var applied = context.GetService<IHistoryRepository>() .GetAppliedMigrations() .Select(m => m.MigrationId); var total = context.GetService<IMigrationsAssembly>() .Migrations .Select(m => m.Key); return !total.Except(applied).Any(); } } }
mit
C#
815e16f5ff4bb031c23c0f5e2204c2fb5270c019
fix the producer connection returned
ouraspnet/cap,dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP
src/DotNetCore.CAP.Kafka/PublishQueueExecutor.cs
src/DotNetCore.CAP.Kafka/PublishQueueExecutor.cs
using System; using System.Text; using System.Threading.Tasks; using DotNetCore.CAP.Processor.States; using Microsoft.Extensions.Logging; namespace DotNetCore.CAP.Kafka { internal class PublishQueueExecutor : BasePublishQueueExecutor { private readonly ConnectionPool _connectionPool; private readonly ILogger _logger; public PublishQueueExecutor( CapOptions options, IStateChanger stateChanger, ConnectionPool connectionPool, ILogger<PublishQueueExecutor> logger) : base(options, stateChanger, logger) { _logger = logger; _connectionPool = connectionPool; } public override async Task<OperateResult> PublishAsync(string keyName, string content) { var producer = _connectionPool.Rent(); try { var contentBytes = Encoding.UTF8.GetBytes(content); var message = await producer.ProduceAsync(keyName, null, contentBytes); if (!message.Error.HasError) { _logger.LogDebug($"kafka topic message [{keyName}] has been published."); return OperateResult.Success; } return OperateResult.Failed(new OperateError { Code = message.Error.Code.ToString(), Description = message.Error.Reason }); } catch (Exception ex) { _logger.LogError(ex, $"An error occurred during sending the topic message to kafka. Topic:[{keyName}], Exception: {ex.Message}"); return OperateResult.Failed(ex); } finally { var returned = _connectionPool.Return(producer); if (!returned) producer.Dispose(); } } } }
using System; using System.Text; using System.Threading.Tasks; using DotNetCore.CAP.Processor.States; using Microsoft.Extensions.Logging; namespace DotNetCore.CAP.Kafka { internal class PublishQueueExecutor : BasePublishQueueExecutor { private readonly ConnectionPool _connectionPool; private readonly ILogger _logger; public PublishQueueExecutor( CapOptions options, IStateChanger stateChanger, ConnectionPool connectionPool, ILogger<PublishQueueExecutor> logger) : base(options, stateChanger, logger) { _logger = logger; _connectionPool = connectionPool; } public override async Task<OperateResult> PublishAsync(string keyName, string content) { var producer = _connectionPool.Rent(); try { var contentBytes = Encoding.UTF8.GetBytes(content); var message = await producer.ProduceAsync(keyName, null, contentBytes); if (!message.Error.HasError) { _logger.LogDebug($"kafka topic message [{keyName}] has been published."); return OperateResult.Success; } return OperateResult.Failed(new OperateError { Code = message.Error.Code.ToString(), Description = message.Error.Reason }); } catch (Exception ex) { _logger.LogError(ex, $"An error occurred during sending the topic message to kafka. Topic:[{keyName}], Exception: {ex.Message}"); return OperateResult.Failed(ex); } finally { _connectionPool.Return(producer); } } } }
mit
C#
c9fe3caf9c9454d1e134174a4ed1ea68abae31b5
Set to 0 if null
Ulterius/server
RemoteTaskServer/TaskServer/Api/Controllers/Impl/GpuController.cs
RemoteTaskServer/TaskServer/Api/Controllers/Impl/GpuController.cs
#region using System.Linq; using System.Management; using UlteriusServer.TaskServer.Api.Models; using UlteriusServer.TaskServer.Api.Serialization; using vtortola.WebSockets; #endregion namespace UlteriusServer.TaskServer.Api.Controllers.Impl { internal class GpuController : ApiController { private readonly WebSocket client; private readonly Packets packet; private readonly ApiSerializator serializator = new ApiSerializator(); public GpuController(WebSocket client, Packets packet) { this.client = client; this.packet = packet; } public void GetGpuInformation() { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"); var gpus = (from ManagementBaseObject mo in searcher.Get() select new GpuInformation { Name = mo["Name"]?.ToString(), ScreenInfo = mo["VideoModeDescription"]?.ToString(), DriverVersion = mo["DriverVersion"]?.ToString(), RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString() ?? "0"), AdapterRam = mo["AdapterRAM"]?.ToString(), VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString() ?? "0"), VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString() ?? "0"), InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','), AdapterCompatibility = mo["AdapterCompatibility"]?.ToString() }).ToList(); var data = new { gpus }; serializator.Serialize(client, packet.endpoint, packet.syncKey, data); } } }
#region using System.Linq; using System.Management; using UlteriusServer.TaskServer.Api.Models; using UlteriusServer.TaskServer.Api.Serialization; using vtortola.WebSockets; #endregion namespace UlteriusServer.TaskServer.Api.Controllers.Impl { internal class GpuController : ApiController { private readonly WebSocket client; private readonly Packets packet; private readonly ApiSerializator serializator = new ApiSerializator(); public GpuController(WebSocket client, Packets packet) { this.client = client; this.packet = packet; } public void GetGpuInformation() { var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_VideoController"); var gpus = (from ManagementBaseObject mo in searcher.Get() select new GpuInformation { Name = mo["Name"]?.ToString(), ScreenInfo = mo["VideoModeDescription"]?.ToString(), DriverVersion = mo["DriverVersion"]?.ToString(), RefreshRate = int.Parse(mo["CurrentRefreshRate"]?.ToString()), AdapterRam = mo["AdapterRAM"]?.ToString(), VideoArchitecture = int.Parse(mo["VideoArchitecture"]?.ToString()), VideoMemoryType = int.Parse(mo["VideoMemoryType"]?.ToString()), InstalledDisplayDrivers = mo["InstalledDisplayDrivers"]?.ToString()?.Split(','), AdapterCompatibility = mo["AdapterCompatibility"]?.ToString() }).ToList(); var data = new { gpus }; serializator.Serialize(client, packet.endpoint, packet.syncKey, data); } } }
mpl-2.0
C#
43cac8ec1cf8d5f24fe32f91640aefd8115edbf0
Update plateformer gravity at fixed update
julesbriquet/PostCredit
Game/Assets/Scripts/plateformer/PlateformerManager.cs
Game/Assets/Scripts/plateformer/PlateformerManager.cs
using UnityEngine; using System.Collections; public class PlateformerManager : MonoBehaviour { public float MoveSpeed; public float JumpForce; public float Gravity; public float TimerForDifficulty; float timeUntilEndGame; public static PlateformerManager Instance; void Awake () { PlateformerManager.Instance = this; } // Use this for initialization void Start () { this.timeUntilEndGame = Time.time + TimerForDifficulty; } // Update is called once per frame void Update () { if(Time.time > this.timeUntilEndGame) { if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove) { GameManager.Instance.LevelEnd(true); } else { GameManager.Instance.LevelEnd(false); } } } void FixedUpdate () { Physics2D.gravity = new Vector2(0f, this.Gravity); } public float GetJumpForce () { return this.JumpForce; } public float GetMoveSpeed () { return this.MoveSpeed; } public float GetGravity () { return this.Gravity; } }
using UnityEngine; using System.Collections; public class PlateformerManager : MonoBehaviour { public float MoveSpeed; public float JumpForce; public float Gravity; public float TimerForDifficulty; float timeUntilEndGame; public static PlateformerManager Instance; void Awake () { PlateformerManager.Instance = this; } // Use this for initialization void Start () { this.timeUntilEndGame = Time.time + TimerForDifficulty; Physics2D.gravity = new Vector2(0f, this.Gravity); } // Update is called once per frame void Update () { if(Time.time > this.timeUntilEndGame) { if(GameObject.FindGameObjectWithTag("Player").GetComponent<PlateformerCharacter>().LockMove) { GameManager.Instance.LevelEnd(true); } else { GameManager.Instance.LevelEnd(false); } } } public float GetJumpForce () { return this.JumpForce; } public float GetMoveSpeed () { return this.MoveSpeed; } public float GetGravity () { return this.Gravity; } }
mit
C#
c1a589f97986577b6a79f5b208ab2de59151bb35
use model.ToFileName() instead of model.OriginalFileName
IUMDPI/IUMediaHelperApps
Packager/Factories/AbstractEmbeddedMetadataFactory.cs
Packager/Factories/AbstractEmbeddedMetadataFactory.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Packager.Exceptions; using Packager.Extensions; using Packager.Models.EmbeddedMetadataModels; using Packager.Models.FileModels; using Packager.Models.PodMetadataModels; namespace Packager.Factories { public abstract class AbstractEmbeddedMetadataFactory<T> : IEmbeddedMetadataFactory<T> where T : AbstractPodMetadata { public AbstractEmbeddedMetadata Generate(IEnumerable<ObjectFileModel> models, ObjectFileModel target, T metadata) { var provenance = GetProvenance(metadata, models, target); return Generate(target, provenance, metadata); } protected abstract AbstractEmbeddedMetadata Generate(ObjectFileModel model, AbstractDigitalFile provenance, T metadata); protected static string GenerateDescription(AbstractPodMetadata metadata, ObjectFileModel model) { return $"{metadata.Unit}. {metadata.CallNumber}. File use: {model.FullFileUse}. {Path.GetFileNameWithoutExtension(model.ToFileName())}"; } protected static string GetDateString(DateTime? date, string format, string defaultValue) { return date.HasValue == false ? defaultValue : date.Value.ToString(format); } private static AbstractDigitalFile GetProvenance(AbstractPodMetadata podMetadata, IEnumerable<ObjectFileModel> instances, ObjectFileModel model) { var sequenceInstances = instances.Where(m => m.SequenceIndicator.Equals(model.SequenceIndicator)); var sequenceMaster = sequenceInstances.GetPreservationOrIntermediateModel(); if (sequenceMaster == null) { throw new EmbeddedMetadataException("No corresponding preservation or preservation-intermediate master present for {0}", model.ToFileName()); } var defaultProvenance = GetProvenance(podMetadata, sequenceMaster); if (defaultProvenance == null) { throw new EmbeddedMetadataException("No digital file provenance in metadata for {0}", sequenceMaster.ToFileName()); } return GetProvenance(podMetadata, model, defaultProvenance); } private static AbstractDigitalFile GetProvenance(AbstractPodMetadata podMetadata, AbstractFileModel model, AbstractDigitalFile defaultValue = null) { var result = podMetadata.FileProvenances.SingleOrDefault(dfp => model.IsSameAs(NormalizeFilename(dfp.Filename, model))); return result ?? defaultValue; } private static string NormalizeFilename(string value, AbstractFileModel model) { return Path.ChangeExtension(value, model.Extension); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Packager.Exceptions; using Packager.Extensions; using Packager.Models.EmbeddedMetadataModels; using Packager.Models.FileModels; using Packager.Models.PodMetadataModels; namespace Packager.Factories { public abstract class AbstractEmbeddedMetadataFactory<T> : IEmbeddedMetadataFactory<T> where T : AbstractPodMetadata { public AbstractEmbeddedMetadata Generate(IEnumerable<ObjectFileModel> models, ObjectFileModel target, T metadata) { var provenance = GetProvenance(metadata, models, target); return Generate(target, provenance, metadata); } protected abstract AbstractEmbeddedMetadata Generate(ObjectFileModel model, AbstractDigitalFile provenance, T metadata); protected static string GenerateDescription(AbstractPodMetadata metadata, ObjectFileModel model) { return $"{metadata.Unit}. {metadata.CallNumber}. File use: {model.FullFileUse}. {Path.GetFileNameWithoutExtension(model.OriginalFileName)}"; } protected static string GetDateString(DateTime? date, string format, string defaultValue) { return date.HasValue == false ? defaultValue : date.Value.ToString(format); } private static AbstractDigitalFile GetProvenance(AbstractPodMetadata podMetadata, IEnumerable<ObjectFileModel> instances, ObjectFileModel model) { var sequenceInstances = instances.Where(m => m.SequenceIndicator.Equals(model.SequenceIndicator)); var sequenceMaster = sequenceInstances.GetPreservationOrIntermediateModel(); if (sequenceMaster == null) { throw new EmbeddedMetadataException("No corresponding preservation or preservation-intermediate master present for {0}", model.ToFileName()); } var defaultProvenance = GetProvenance(podMetadata, sequenceMaster); if (defaultProvenance == null) { throw new EmbeddedMetadataException("No digital file provenance in metadata for {0}", sequenceMaster.ToFileName()); } return GetProvenance(podMetadata, model, defaultProvenance); } private static AbstractDigitalFile GetProvenance(AbstractPodMetadata podMetadata, AbstractFileModel model, AbstractDigitalFile defaultValue = null) { var result = podMetadata.FileProvenances.SingleOrDefault(dfp => model.IsSameAs(NormalizeFilename(dfp.Filename, model))); return result ?? defaultValue; } private static string NormalizeFilename(string value, AbstractFileModel model) { return Path.ChangeExtension(value, model.Extension); } } }
apache-2.0
C#
2d97e2618208d4ec3a196fffbeab37b03f4a17b0
Remove unused code
stranne/BooliLib
Stranne.BooliLib/Converters/ShortDateJsonConverter.cs
Stranne.BooliLib/Converters/ShortDateJsonConverter.cs
using System; using Newtonsoft.Json; namespace Stranne.BooliLib.Converters { internal class ShortDateJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var date = (DateTimeOffset)value; writer.WriteValue(date.ToString("yyyyMMdd")); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanRead => false; public override bool CanConvert(Type objectType) { return objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?); } } }
using System; using Newtonsoft.Json; namespace Stranne.BooliLib.Converters { internal class ShortDateJsonConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value == null) { return; } var date = (DateTimeOffset)value; writer.WriteValue(date.ToString("yyyyMMdd")); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override bool CanRead => false; public override bool CanConvert(Type objectType) { return objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?); } } }
mit
C#
eb16c758e0a3589306cf6cc5eca1976900ca08b6
Add comment for WebHost URLs.
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
cloud-sql/postgres/Program.cs
cloud-sql/postgres/Program.cs
/* * Copyright (c) 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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 CloudSql.Settings; using Google.Cloud.Diagnostics.AspNetCore; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using System; using System.IO; namespace CloudSql { public class Program { public static AppSettings AppSettings { get; private set; } public static void Main(string[] args) { BuildWebHost(args).Build().Run(); } public static IWebHostBuilder BuildWebHost(string[] args) { ReadAppSettings(); string port = Environment.GetEnvironmentVariable("PORT") ?? "8080"; // hostingUrl is for hosting by Cloud Run and App Engine. string hostingUrl = $"http://0.0.0.0:{port}"; // localhostUrl is for running locally and running tests. // localhostUrl port should be different from hostingUrl port // to prevent "Address already in use" error when deploying // to Cloud Run or App Engine. string localhostUrl = "http://localhost:5567"; string urls = $"{localhostUrl};{hostingUrl}"; return WebHost.CreateDefaultBuilder(args) .UseGoogleDiagnostics(AppSettings.GoogleCloudSettings.ProjectId, AppSettings.GoogleCloudSettings.ServiceName, AppSettings.GoogleCloudSettings.Version) .UseStartup<Startup>().UseUrls(urls); } /// <summary> /// Read application settings from appsettings.json. /// </summary> private static void ReadAppSettings() { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false) .Build(); // Read json config into AppSettings. AppSettings = new AppSettings(); config.Bind(AppSettings); } } }
/* * Copyright (c) 2019 Google LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * 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 CloudSql.Settings; using Google.Cloud.Diagnostics.AspNetCore; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using System; using System.IO; namespace CloudSql { public class Program { public static AppSettings AppSettings { get; private set; } public static void Main(string[] args) { BuildWebHost(args).Build().Run(); } public static IWebHostBuilder BuildWebHost(string[] args) { ReadAppSettings(); string port = Environment.GetEnvironmentVariable("PORT") ?? "8080"; string hostingUrl = $"http://0.0.0.0:{port}"; string localhostUrl = "http://localhost:5567"; string urls = $"{localhostUrl};{hostingUrl}"; return WebHost.CreateDefaultBuilder(args) .UseGoogleDiagnostics(AppSettings.GoogleCloudSettings.ProjectId, AppSettings.GoogleCloudSettings.ServiceName, AppSettings.GoogleCloudSettings.Version) .UseStartup<Startup>().UseUrls(urls); } /// <summary> /// Read application settings from appsettings.json. /// </summary> private static void ReadAppSettings() { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false) .Build(); // Read json config into AppSettings. AppSettings = new AppSettings(); config.Bind(AppSettings); } } }
apache-2.0
C#
dc04de617fed1fb9f6c2eb10b4551a02604d0971
Use the correct strong name for dbus-sharp-glib friend assembly
tmds/Tmds.DBus
AssemblyInfo.cs
AssemblyInfo.cs
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("NDesk.DBus.GLib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
// Copyright 2006 Alp Toker <alp@atoker.com> // This software is made available under the MIT License // See COPYING for details using System.Reflection; using System.Runtime.CompilerServices; //[assembly: AssemblyVersion("0.0.0.*")] [assembly: AssemblyTitle ("NDesk.DBus")] [assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")] [assembly: AssemblyCopyright ("Copyright (C) Alp Toker")] [assembly: AssemblyCompany ("NDesk")] [assembly: InternalsVisibleTo ("dbus-sharp-glib")] [assembly: InternalsVisibleTo ("dbus-monitor")] [assembly: InternalsVisibleTo ("dbus-daemon")]
mit
C#
85d6e258cf8186d9b85244976b29c3f3b6b94b52
Update colors of the GridRenderer
rev087/hivemind,mbbarange/hivemind
Editor/GridRenderer.cs
Editor/GridRenderer.cs
using UnityEngine; using UnityEditor; using System.Collections; namespace Hivemind { public class GridRenderer { Texture2D gridTex; public static int width { get { return 120; } } public static int height { get { return 120; } } public static Vector2 step { get { return new Vector2(width / 10, height / 10); } } // Generates a single tile of the grid texture void GenerateGrid() { gridTex = new Texture2D(width, height); gridTex.hideFlags = HideFlags.DontSave; Color bg = new Color(0.64f, 0.64f, 0.64f); Color dark = Color.Lerp(bg, Color.black, 0.15f); Color darkIntersection = Color.Lerp(bg, Color.black, 0.2f); Color light = Color.Lerp(bg, Color.black, 0.05f); Color lightIntersection = Color.Lerp(bg, Color.black, 0.1f); for (int x = 0; x < width; x ++) { for (int y = 0; y < height; y ++) { // Left Top edge, dark intersection color if (x == 0 && y == 0) gridTex.SetPixel(x, y, darkIntersection); // Left and Top edges, dark color else if (x == 0 || y == 0) gridTex.SetPixel(x, y, dark); // Finer grid intersection color else if (x % step.x == 0 && y % step.y == 0) gridTex.SetPixel(x, y, lightIntersection); // Finer grid color else if (x % step.x == 0 || y % step.y == 0) gridTex.SetPixel(x, y, light); // Background else gridTex.SetPixel(x, y, bg); } } gridTex.Apply(); } public void Draw(Vector2 scrollPoint, Rect canvas) { if (!gridTex) GenerateGrid (); float yOffset = scrollPoint.y % gridTex.height; float yStart = scrollPoint.y - yOffset; float yEnd = scrollPoint.y + canvas.height + yOffset; float xOffset = scrollPoint.x % gridTex.width; float xStart = scrollPoint.x - xOffset; float xEnd = scrollPoint.x + canvas.width + xOffset; for (float x = xStart; x < xEnd; x += gridTex.width) { for (float y = yStart; y < yEnd; y += gridTex.height) { GUI.DrawTexture(new Rect(x, y, gridTex.width, gridTex.height), gridTex); } } } } }
using UnityEngine; using UnityEditor; using System.Collections; namespace Hivemind { public class GridRenderer { Texture2D gridTex; public static int width { get { return 120; } } public static int height { get { return 120; } } public static Vector2 step { get { return new Vector2(width / 10, height / 10); } } // Generates a single tile of the grid texture void GenerateGrid() { gridTex = new Texture2D(width, height); gridTex.hideFlags = HideFlags.DontSave; Color bg = new Color(0.365f, 0.365f, 0.4f, 1f); Color dark = new Color(0.278f, 0.278f, 0.278f); Color light = new Color(0.329f, 0.329f, 0.329f); Color darkX = new Color(0.216f, 0.216f, 0.216f); Color lightX = new Color(0.298f, 0.298f, 0.298f); for (int x = 0; x < width; x ++) { for (int y = 0; y < height; y ++) { // Left Top edge, dark intersection color if (x == 0 && y == 0) gridTex.SetPixel(x, y, darkX); // Left and Top edges, dark color else if (x == 0 || y == 0) gridTex.SetPixel(x, y, dark); // Finer grid intersection color else if (x % step.x == 0 && y % step.y == 0) gridTex.SetPixel(x, y, lightX); // Finer grid color else if (x % step.x == 0 || y % step.y == 0) gridTex.SetPixel(x, y, light); // Background else gridTex.SetPixel(x, y, bg); } } gridTex.Apply(); } public void Draw(Vector2 scrollPoint, Rect canvas) { if (!gridTex) GenerateGrid (); float yOffset = scrollPoint.y % gridTex.height; float yStart = scrollPoint.y - yOffset; float yEnd = scrollPoint.y + canvas.height + yOffset; float xOffset = scrollPoint.x % gridTex.width; float xStart = scrollPoint.x - xOffset; float xEnd = scrollPoint.x + canvas.width + xOffset; for (float x = xStart; x < xEnd; x += gridTex.width) { for (float y = yStart; y < yEnd; y += gridTex.height) { GUI.DrawTexture(new Rect(x, y, gridTex.width, gridTex.height), gridTex); } } } } }
mit
C#
660d6a57fca927107d4645b69402fec8311d0ac1
Remove IO dependency; expect contents of private key and not path to key
Nexmo/csharp-client,Nexmo/csharp-client,Nexmo/nexmo-dotnet
Nexmo.Api/Jwt.cs
Nexmo.Api/Jwt.cs
using System; using System.Collections.Generic; using System.Security.Cryptography; using Jose; namespace Nexmo.Api { internal class Jwt { internal static string CreateToken(string appId, string privateKey) { var tokenData = new byte[64]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(tokenData); var jwtTokenId = Convert.ToBase64String(tokenData); var payload = new Dictionary<string, object> { { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }, { "application_id", appId }, { "jti", jwtTokenId } }; var rsa = PemParse.DecodePEMKey(privateKey); return JWT.Encode(payload, rsa, JwsAlgorithm.RS256); } } }
using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using Jose; namespace Nexmo.Api { internal class Jwt { internal static string CreateToken(string appId, string privateKeyFile) { var tokenData = new byte[64]; var rng = RandomNumberGenerator.Create(); rng.GetBytes(tokenData); var jwtTokenId = Convert.ToBase64String(tokenData); var payload = new Dictionary<string, object> { { "iat", (long) (DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds }, { "application_id", appId }, { "jti", jwtTokenId } }; var pemContents = File.ReadAllText(privateKeyFile); var rsa = PemParse.DecodePEMKey(pemContents); return JWT.Encode(payload, rsa, JwsAlgorithm.RS256); } } }
mit
C#
0a02fa84a1b870598baa9b1c70ed3fa253378625
Add support for update property
daveaglick/Buildalyzer,daveaglick/Buildalyzer,daveaglick/Buildalyzer
src/Buildalyzer/Construction/PackageReference.cs
src/Buildalyzer/Construction/PackageReference.cs
using System; using System.Xml.Linq; namespace Buildalyzer.Construction { public class PackageReference : IPackageReference { public string Name { get; } public string Version { get; } internal PackageReference(XElement packageReferenceElement) { this.Name = packageReferenceElement.GetAttributeValue("Include") ?? packageReferenceElement.GetAttributeValue("Update"); this.Version = packageReferenceElement.GetAttributeValue("Version"); } } }
using System; using System.Xml.Linq; namespace Buildalyzer.Construction { public class PackageReference : IPackageReference { public string Name { get; } public string Version { get; } internal PackageReference(XElement packageReferenceElement) { this.Name = packageReferenceElement.GetAttributeValue("Include"); this.Version = packageReferenceElement.GetAttributeValue("Version"); } } }
mit
C#
ecf15f3984d20a1e0c2f4ec89d83ddd6cb85bd2b
Update DesignerModule.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D
src/Core2D.UI.Avalonia/Modules/DesignerModule.cs
src/Core2D.UI.Avalonia/Modules/DesignerModule.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Autofac; using Core2D.Interfaces; using Core2D.Renderer; using Core2D.Renderer.Avalonia; using Core2D.UI.Avalonia.Utilities; namespace Core2D.UI.Avalonia.Modules { /// <summary> /// Designer dependencies components module. /// </summary> public class DesignerModule : Module { /// <inheritdoc/> protected override void Load(ContainerBuilder builder) { builder.RegisterType<AvaloniaRenderer>().As<IShapeRenderer>().InstancePerDependency(); builder.RegisterType<AvaloniaTextClipboard>().As<ITextClipboard>().InstancePerLifetimeScope(); } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Autofac; using Core2D.Interfaces; using Core2D.Renderer; using Core2D.Renderer.Avalonia; using Core2D.UI.Avalonia.Utilities; namespace Core2D.UI.Avalonia.Modules { /// <summary> /// Designer dependencies components module. /// </summary> public class DesignerModule : Module { /// <inheritdoc/> protected override void Load(ContainerBuilder builder) { builder.RegisterType<AvaloniaRenderer>().As<IShapeRenderer>().InstancePerDependency(); builder.RegisterType<AvaloniaTextClipboard>().As<ITextClipboard>().InstancePerLifetimeScope(); } } }
mit
C#
072c7795a7489cb2d35a43771106ca47c5a72e36
Use floor for better file sizes
GGG-KILLER/GUtils.NET
GUtils.IO/FileSizes.cs
GUtils.IO/FileSizes.cs
using System; namespace GUtils.IO { public static class FileSizes { public const UInt64 B = 1024; public const UInt64 KiB = 1024 * B; public const UInt64 MiB = 1024 * KiB; public const UInt64 GiB = 1024 * MiB; public const UInt64 TiB = 1024 * GiB; public const UInt64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( UInt64 Size ) { var i = ( Int32 ) Math.Floor ( Math.Log ( Size, 1024 ) ); return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}"; } } }
using System; namespace GUtils.IO { public static class FileSizes { public const UInt64 B = 1024; public const UInt64 KiB = 1024 * B; public const UInt64 MiB = 1024 * KiB; public const UInt64 GiB = 1024 * MiB; public const UInt64 TiB = 1024 * GiB; public const UInt64 PiB = 1024 * TiB; private static readonly String[] _suffixes = new[] { "B", "KiB", "MiB", "GiB", "TiB", "PiB" }; public static String Format ( UInt64 Size ) { var i = ( Int32 ) Math.Round ( Math.Log ( Size, 1024 ) ); return $"{Size / ( Math.Pow ( B, i ) )} {_suffixes[i]}"; } } }
mit
C#
79878e1a09689699beb8bd45c18fa0c64dc22ddf
Fix tests to catch exceptions from CanCreateSymbolicLinks
twsouthwick/corefx,alexperovich/corefx,richlander/corefx,nbarbettini/corefx,Jiayili1/corefx,mmitche/corefx,MaggieTsang/corefx,billwert/corefx,shimingsg/corefx,Ermiar/corefx,seanshpark/corefx,billwert/corefx,tijoytom/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,ericstj/corefx,jlin177/corefx,ViktorHofer/corefx,Ermiar/corefx,ViktorHofer/corefx,ericstj/corefx,seanshpark/corefx,the-dwyer/corefx,DnlHarvey/corefx,twsouthwick/corefx,tijoytom/corefx,mazong1123/corefx,yizhang82/corefx,billwert/corefx,zhenlan/corefx,zhenlan/corefx,parjong/corefx,krk/corefx,mmitche/corefx,krk/corefx,BrennanConroy/corefx,richlander/corefx,JosephTremoulet/corefx,ericstj/corefx,twsouthwick/corefx,Ermiar/corefx,the-dwyer/corefx,nchikanov/corefx,MaggieTsang/corefx,gkhanna79/corefx,nbarbettini/corefx,wtgodbe/corefx,ericstj/corefx,fgreinacher/corefx,mazong1123/corefx,gkhanna79/corefx,ptoonen/corefx,billwert/corefx,cydhaselton/corefx,mazong1123/corefx,parjong/corefx,mmitche/corefx,shimingsg/corefx,rubo/corefx,nchikanov/corefx,mmitche/corefx,the-dwyer/corefx,Ermiar/corefx,krk/corefx,alexperovich/corefx,tijoytom/corefx,stone-li/corefx,jlin177/corefx,ptoonen/corefx,MaggieTsang/corefx,dotnet-bot/corefx,parjong/corefx,richlander/corefx,ravimeda/corefx,stone-li/corefx,krytarowski/corefx,ravimeda/corefx,billwert/corefx,cydhaselton/corefx,gkhanna79/corefx,JosephTremoulet/corefx,nbarbettini/corefx,ptoonen/corefx,wtgodbe/corefx,tijoytom/corefx,jlin177/corefx,nbarbettini/corefx,krytarowski/corefx,alexperovich/corefx,DnlHarvey/corefx,axelheer/corefx,seanshpark/corefx,fgreinacher/corefx,the-dwyer/corefx,ViktorHofer/corefx,the-dwyer/corefx,ptoonen/corefx,nbarbettini/corefx,parjong/corefx,rubo/corefx,ericstj/corefx,DnlHarvey/corefx,axelheer/corefx,richlander/corefx,fgreinacher/corefx,seanshpark/corefx,yizhang82/corefx,richlander/corefx,zhenlan/corefx,dotnet-bot/corefx,stone-li/corefx,Ermiar/corefx,wtgodbe/corefx,alexperovich/corefx,krytarowski/corefx,billwert/corefx,krytarowski/corefx,shimingsg/corefx,ViktorHofer/corefx,ravimeda/corefx,wtgodbe/corefx,twsouthwick/corefx,BrennanConroy/corefx,krytarowski/corefx,axelheer/corefx,ptoonen/corefx,ViktorHofer/corefx,JosephTremoulet/corefx,axelheer/corefx,mmitche/corefx,gkhanna79/corefx,the-dwyer/corefx,krytarowski/corefx,alexperovich/corefx,dotnet-bot/corefx,ptoonen/corefx,tijoytom/corefx,krk/corefx,tijoytom/corefx,Jiayili1/corefx,shimingsg/corefx,nchikanov/corefx,MaggieTsang/corefx,twsouthwick/corefx,gkhanna79/corefx,alexperovich/corefx,ravimeda/corefx,yizhang82/corefx,jlin177/corefx,shimingsg/corefx,rubo/corefx,Jiayili1/corefx,MaggieTsang/corefx,mazong1123/corefx,Jiayili1/corefx,BrennanConroy/corefx,Ermiar/corefx,ptoonen/corefx,wtgodbe/corefx,parjong/corefx,DnlHarvey/corefx,rubo/corefx,alexperovich/corefx,parjong/corefx,DnlHarvey/corefx,cydhaselton/corefx,shimingsg/corefx,wtgodbe/corefx,krytarowski/corefx,dotnet-bot/corefx,billwert/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,Jiayili1/corefx,Ermiar/corefx,MaggieTsang/corefx,cydhaselton/corefx,nchikanov/corefx,zhenlan/corefx,wtgodbe/corefx,JosephTremoulet/corefx,stone-li/corefx,seanshpark/corefx,dotnet-bot/corefx,ravimeda/corefx,jlin177/corefx,stone-li/corefx,axelheer/corefx,mazong1123/corefx,richlander/corefx,nchikanov/corefx,twsouthwick/corefx,richlander/corefx,twsouthwick/corefx,rubo/corefx,jlin177/corefx,ericstj/corefx,zhenlan/corefx,mazong1123/corefx,Jiayili1/corefx,ViktorHofer/corefx,yizhang82/corefx,mmitche/corefx,DnlHarvey/corefx,axelheer/corefx,stone-li/corefx,shimingsg/corefx,jlin177/corefx,ravimeda/corefx,DnlHarvey/corefx,MaggieTsang/corefx,fgreinacher/corefx,zhenlan/corefx,mazong1123/corefx,cydhaselton/corefx,stone-li/corefx,dotnet-bot/corefx,seanshpark/corefx,gkhanna79/corefx,cydhaselton/corefx,yizhang82/corefx,yizhang82/corefx,gkhanna79/corefx,nbarbettini/corefx,ravimeda/corefx,cydhaselton/corefx,krk/corefx,tijoytom/corefx,zhenlan/corefx,Jiayili1/corefx,parjong/corefx,krk/corefx,nbarbettini/corefx,krk/corefx,yizhang82/corefx,ericstj/corefx,ViktorHofer/corefx,nchikanov/corefx,nchikanov/corefx,the-dwyer/corefx,mmitche/corefx,seanshpark/corefx
src/System.IO.FileSystem/tests/FileSystemTest.cs
src/System.IO.FileSystem/tests/FileSystemTest.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.Diagnostics; using Xunit; namespace System.IO.Tests { public abstract partial class FileSystemTest : RemoteExecutorTestBase { public static readonly byte[] TestBuffer = { 0xBA, 0x5E, 0xBA, 0x11, 0xF0, 0x07, 0xBA, 0x11 }; protected const TestPlatforms CaseInsensitivePlatforms = TestPlatforms.Windows | TestPlatforms.OSX; protected const TestPlatforms CaseSensitivePlatforms = TestPlatforms.AnyUnix & ~TestPlatforms.OSX; public static bool AreAllLongPathsAvailable => PathFeatures.AreAllLongPathsAvailable(); public static bool LongPathsAreNotBlocked => !PathFeatures.AreLongPathsBlocked(); public static bool UsingNewNormalization => !PathFeatures.IsUsingLegacyPathNormalization(); public static TheoryData<string> PathsWithInvalidColons = TestData.PathsWithInvalidColons; public static TheoryData<string> PathsWithInvalidCharacters = TestData.PathsWithInvalidCharacters; public static TheoryData<char> TrailingCharacters = TestData.TrailingCharacters; /// <summary> /// In some cases (such as when running without elevated privileges), /// the symbolic link may fail to create. Only run this test if it creates /// links successfully. /// </summary> protected static bool CanCreateSymbolicLinks => s_canCreateSymbolicLinks.Value; private static readonly Lazy<bool> s_canCreateSymbolicLinks = new Lazy<bool>(() => { try { // Verify file symlink creation string path = Path.GetTempFileName(); string linkPath = path + ".link"; bool success = MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false); try { File.Delete(path); } catch { } try { File.Delete(linkPath); } catch { } // Verify directory symlink creation path = Path.GetTempFileName(); linkPath = path + ".link"; success = success && MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true); try { Directory.Delete(path); } catch { } try { Directory.Delete(linkPath); } catch { } return success; } catch { // Problems with Process.Start (used by CreateSymbolicLinks) on some platforms // https://github.com/dotnet/corefx/issues/19909 return false; } }); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using Xunit; namespace System.IO.Tests { public abstract partial class FileSystemTest : RemoteExecutorTestBase { public static readonly byte[] TestBuffer = { 0xBA, 0x5E, 0xBA, 0x11, 0xF0, 0x07, 0xBA, 0x11 }; protected const TestPlatforms CaseInsensitivePlatforms = TestPlatforms.Windows | TestPlatforms.OSX; protected const TestPlatforms CaseSensitivePlatforms = TestPlatforms.AnyUnix & ~TestPlatforms.OSX; public static bool AreAllLongPathsAvailable => PathFeatures.AreAllLongPathsAvailable(); public static bool LongPathsAreNotBlocked => !PathFeatures.AreLongPathsBlocked(); public static bool UsingNewNormalization => !PathFeatures.IsUsingLegacyPathNormalization(); public static TheoryData<string> PathsWithInvalidColons = TestData.PathsWithInvalidColons; public static TheoryData<string> PathsWithInvalidCharacters = TestData.PathsWithInvalidCharacters; public static TheoryData<char> TrailingCharacters = TestData.TrailingCharacters; /// <summary> /// In some cases (such as when running without elevated privileges), /// the symbolic link may fail to create. Only run this test if it creates /// links successfully. /// </summary> protected static bool CanCreateSymbolicLinks { get; } = ComputeCanCreateSymbolicLinks(); private static bool ComputeCanCreateSymbolicLinks() { bool success = true; // Verify file symlink creation string path = Path.GetTempFileName(); string linkPath = path + ".link"; success = MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: false); try { File.Delete(path); } catch { } try { File.Delete(linkPath); } catch { } // Verify directory symlink creation path = Path.GetTempFileName(); linkPath = path + ".link"; success = success && MountHelper.CreateSymbolicLink(linkPath, path, isDirectory: true); try { Directory.Delete(path); } catch { } try { Directory.Delete(linkPath); } catch { } return success; } } }
mit
C#
467f206e64b16d148e7b78d6bab59a0c5f6b6295
add test data 12 &13
wongjiahau/TTAP-UTAR,wongjiahau/TTAP-UTAR
NUnit.Tests2/Test_HtmlSlotParser.cs
NUnit.Tests2/Test_HtmlSlotParser.cs
using System; using System.Collections.Generic; using HtmlAgilityPack; using NUnit.Framework; using Time_Table_Arranging_Program; using Time_Table_Arranging_Program.Class; using Time_Table_Arranging_Program.Class.Converter; using Time_Table_Arranging_Program.Class.TokenParser; namespace NUnit.Tests2 { [TestFixture] public class Test_HtmlSlotParser { [Test] public void Test_HtmlSlotParser_1() { string input = Helper.RawStringOfTestFile("Sample HTML.txt"); var result = new HtmlSlotParser().Parse(input); Test_SlotParser.TestForResultCorrectness(result); } [Test] public void Test_HtmlSlotParser_2() { string input = Helper.RawStringOfTestFile("Sample HTML.txt"); var actual = new HtmlSlotParser().Parse(input); var expected = new List<Slot>() { new Slot(1,"MPU3113", "HUBUNGAN ETNIK (FOR LOCAL STUDENTS)".Beautify(), "1", "L", Day.Monday,"KB521",new TimePeriod(Time.CreateTime_24HourFormat(9,00), Time.CreateTime_24HourFormat(12,00)),new WeekNumber(new List<int>(){1,2,3,4,5,6,7,8,9,10,11,12,13,14}) ), }; for (int i = 0; i < expected.Count; i++) { Assert.IsTrue(actual[i].Equals(expected[i])); } } [Test] public void Test_htmlslotparser_12() { string input = Helper.RawStringOfTestFile("Sample HTML.txt"); var result = new HtmlSlotParser().Parse(input); var expected = new List<Slot>() { new Slot(11, "MPU32013", "BAHASA KEBANGSAAN A".Beautify(), "1", "L", Day.Tuesday, "KB314", new TimePeriod(Time.CreateTime_24HourFormat(9, 00), Time.CreateTime_24HourFormat(12, 00)), new WeekNumber(new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14})) }; } [Test] public void Test_htmlslotparser_13() { string input = Helper.RawStringOfTestFile("Sample HTML.txt"); var result = new HtmlSlotParser().Parse((input)); var expected = new List<Slot>() { new Slot(12, "MPU32033", "ENGLISH FOR PROFESSIONALS".Beautify(), "1", "L", Day.Monday, "KB301", new TimePeriod(Time.CreateTime_24HourFormat(12, 00), Time.CreateTime_24HourFormat(13, 00)), new WeekNumber(new List<int>() {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14})) }; } } }
using System; using System.Collections.Generic; using HtmlAgilityPack; using NUnit.Framework; using Time_Table_Arranging_Program; using Time_Table_Arranging_Program.Class; using Time_Table_Arranging_Program.Class.Converter; using Time_Table_Arranging_Program.Class.TokenParser; namespace NUnit.Tests2 { [TestFixture] public class Test_HtmlSlotParser { [Test] public void Test_HtmlSlotParser_1() { string input = Helper.RawStringOfTestFile("Sample HTML.txt"); var result = new HtmlSlotParser().Parse(input); Test_SlotParser.TestForResultCorrectness(result); } [Test] public void Test_HtmlSlotParser_2() { string input = Helper.RawStringOfTestFile("Sample HTML.txt"); var actual = new HtmlSlotParser().Parse(input); var expected = new List<Slot>() { new Slot(1,"MPU3113", "HUBUNGAN ETNIK (FOR LOCAL STUDENTS)".Beautify(), "1", "L", Day.Monday,"KB521",new TimePeriod(Time.CreateTime_24HourFormat(9,00), Time.CreateTime_24HourFormat(12,00)),new WeekNumber(new List<int>(){1,2,3,4,5,6,7,8,9,10,11,12,13,14}) ), }; for (int i = 0; i < expected.Count; i++) { Assert.IsTrue(actual[i].Equals(expected[i])); } } } }
agpl-3.0
C#
e45ec3be776e4b9cf74f60544de90c8114dce106
Correct sender total bytes output
brian-dot-net/writeasync,brian-dot-net/writeasync,brian-dot-net/writeasync
projects/CommSample/source/CommSample.App/Sender.cs
projects/CommSample/source/CommSample.App/Sender.cs
//----------------------------------------------------------------------- // <copyright file="Sender.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Threading; using System.Threading.Tasks; internal sealed class Sender { private readonly MemoryChannel channel; private readonly Logger logger; private readonly int bufferSize; private readonly Delay delay; private readonly byte fill; public Sender(MemoryChannel channel, Logger logger, int bufferSize, byte fill, Delay delay) { this.channel = channel; this.logger = logger; this.bufferSize = bufferSize; this.fill = fill; this.delay = delay; } public Task RunAsync(CancellationToken token) { this.logger.WriteLine("Sender B={0}/F=0x{1:x} starting...", this.bufferSize, this.fill); return Task.Factory.StartNew(() => this.RunInner(token), TaskCreationOptions.LongRunning); } private void RunInner(CancellationToken token) { byte[] buffer = new byte[this.bufferSize]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = this.fill; } long totalBytes = 0; while (!token.IsCancellationRequested) { this.channel.Send(buffer); totalBytes += buffer.Length; this.delay.Next(); } this.logger.WriteLine("Sender B={0}/F=0x{1:x} completed. Sent {2} bytes.", this.bufferSize, this.fill, totalBytes); } } }
//----------------------------------------------------------------------- // <copyright file="Sender.cs" company="Brian Rogers"> // Copyright (c) Brian Rogers. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace CommSample { using System; using System.Threading; using System.Threading.Tasks; internal sealed class Sender { private readonly MemoryChannel channel; private readonly Logger logger; private readonly int bufferSize; private readonly Delay delay; private readonly byte fill; public Sender(MemoryChannel channel, Logger logger, int bufferSize, byte fill, Delay delay) { this.channel = channel; this.logger = logger; this.bufferSize = bufferSize; this.fill = fill; this.delay = delay; } public Task RunAsync(CancellationToken token) { this.logger.WriteLine("Sender B={0}/F=0x{1:x} starting...", this.bufferSize, this.fill); return Task.Factory.StartNew(() => this.RunInner(token), TaskCreationOptions.LongRunning); } private void RunInner(CancellationToken token) { byte[] buffer = new byte[this.bufferSize]; for (int i = 0; i < buffer.Length; ++i) { buffer[i] = this.fill; } while (!token.IsCancellationRequested) { this.channel.Send(buffer); this.delay.Next(); } this.logger.WriteLine("Sender B={0}/F=0x{1:x} completed. Sent {2} bytes.", this.bufferSize, this.fill, buffer.Length); } } }
unlicense
C#
2d5b641a78dce39c6609c5f21bf106dc403e8a3f
Add our own Vertices method
charlenni/Mapsui,charlenni/Mapsui
Mapsui/MRect2.cs
Mapsui/MRect2.cs
using System.Collections.Generic; namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); /// <summary> /// Returns the vertices in clockwise order from bottom left around to bottom right /// </summary> public IEnumerable<MPoint> Vertices { get { yield return BottomLeft; yield return TopLeft; yield return TopRight; yield return BottomRight; } } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
namespace Mapsui; public class MRect2 { public MPoint Max { get; } public MPoint Min { get; } public double MaxX => Max.X; public double MaxY => Max.Y; public double MinX => Min.X; public double MinY => Min.Y; public MPoint Centroid => new MPoint(Max.X - Min.X, Max.Y - Min.Y); public double Width => Max.X - MinX; public double Height => Max.Y - MinY; public double Bottom => Min.Y; public double Left => Min.X; public double Top => Max.Y; public double Right => Max.X; public MPoint TopLeft => new MPoint(Left, Top); public MPoint TopRight => new MPoint(Right, Top); public MPoint BottomLeft => new MPoint(Left, Bottom); public MPoint BottomRight => new MPoint(Right, Bottom); //IEnumerable<MPoint> Vertices { get; } //MRect Clone(); //bool Contains(MPoint? p); //bool Contains(MRect r); //bool Equals(MRect? other); //double GetArea(); //MRect Grow(double amount); //MRect Grow(double amountInX, double amountInY); //bool Intersects(MRect? box); //MRect Join(MRect? box); //MRect Multiply(double factor); //MQuad Rotate(double degrees); }
mit
C#
a70221b4688c83cc031831b8ee83020c51f21522
Fix cond
nja/keel,nja/keel
Keel/Library.cs
Keel/Library.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Keel { public class Library { public const string Text = @" (defun null (x) (eq x nil)) (defun not (x) (if (eq x nil) t nil)) (defun length (lst) (if (null lst) 0 (+ 1 (length (cdr lst))))) (defun list x x) (defun caar (x) (car (car x))) (defun cadr (x) (car (cdr x))) (defun cdar (x) (cdr (car x))) (defun caaar (x) (car (car (car x)))) (defun cdaar (x) (cdr (car (car x)))) (defmacro cond args (when (car args) (list 'if (caar args) (cons 'progn (cdar args)) (cons 'cond (cdr args))))) (defun reverse (lst) (defun recur (acc lst) (if (null lst) acc (recur (cons (car lst) acc) (cdr lst)))) (recur nil lst)) (defun some (test list) (if (null list) nil (if (test (car list)) t (some test (cdr list))))) (defun every (test list) (if (null list) t (if (test (car list)) (every test (cdr list)) nil))) (defun map (fn . lists) (defun take (fn lists) (if (null lists) nil (cons (fn (car lists)) (take fn (cdr lists))))) (defun cars () (take car lists)) (defun cdrs () (take cdr lists)) (if (some null lists) nil (cons (apply fn (cars)) (apply map fn (cdrs))))) (defmacro when (test body) (list 'if test body nil)) (defmacro unless (test body) (list 'when (list 'not test) body)) "; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Keel { public class Library { public const string Text = @" (defun null (x) (eq x nil)) (defun not (x) (if (eq x nil) t nil)) (defun length (lst) (if (null lst) 0 (+ 1 (length (cdr lst))))) (defun list x x) (defun caar (x) (car (car x))) (defun cadr (x) (car (cdr x))) (defun cdar (x) (cdr (car x))) (defun caaar (x) (car (car (car x)))) (defun cdaar (x) (cdr (car (car x)))) (defmacro cond args (when (car args) (list 'if (caaar args) (cons 'progn (cdaar args)) (cons 'cond (list (cdar args)))))) (defun reverse (lst) (defun recur (acc lst) (if (null lst) acc (recur (cons (car lst) acc) (cdr lst)))) (recur nil lst)) (defun some (test list) (if (null list) nil (if (test (car list)) t (some test (cdr list))))) (defun every (test list) (if (null list) t (if (test (car list)) (every test (cdr list)) nil))) (defun map (fn . lists) (defun take (fn lists) (if (null lists) nil (cons (fn (car lists)) (take fn (cdr lists))))) (defun cars () (take car lists)) (defun cdrs () (take cdr lists)) (if (some null lists) nil (cons (apply fn (cars)) (apply map fn (cdrs))))) (defmacro when (test body) (list 'if test body nil)) (defmacro unless (test body) (list 'when (list 'not test) body)) "; } }
mit
C#
81218e939b50da2be16e4416dc8e483912c8fbdc
Use settings repository in twitch channel service
dukemiller/twitch-tv-viewer
twitch-tv-viewer/Services/TwitchChannelService.cs
twitch-tv-viewer/Services/TwitchChannelService.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using twitch_tv_viewer.Models; using twitch_tv_viewer.Repositories; namespace twitch_tv_viewer.Services { public class TwitchChannelService : ITwitchChannelService { public TwitchChannelService() { Settings = new SettingsRepository(); } public ISettingsRepository Settings { get; set; } public async Task<string> PlayVideo(TwitchChannel channel, string quality) { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, Settings.Quality); public void OpenChat(TwitchChannel channel) { Process.Start($"http://twitch.tv/{channel.Name}/chat?popout="); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using twitch_tv_viewer.Models; namespace twitch_tv_viewer.Services { public class TwitchChannelService : ITwitchChannelService { public async Task<string> PlayVideo(TwitchChannel channel, string quality) { var startInfo = new ProcessStartInfo { FileName = "livestreamer", Arguments = $"--http-query-param client_id=spyiu9jqdnfjtwv6l1xjk5zgt8qb91l twitch.tv/{channel.Name} {quality}", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; var process = new Process { StartInfo = startInfo }; process.Start(); return await process.StandardOutput.ReadToEndAsync(); } public async Task<string> PlayVideo(TwitchChannel twitchChannel) => await PlayVideo(twitchChannel, "source"); public void OpenChat(TwitchChannel channel) { Process.Start($"http://twitch.tv/{channel.Name}/chat?popout="); } } }
mit
C#
caf098f3b3e1287678c477abe4d8154b52c3fb09
Fix add trophy endpoint
loicteixeira/gj-unity-api
Assets/Plugins/GameJolt/Scripts/API/Constants.cs
Assets/Plugins/GameJolt/Scripts/API/Constants.cs
using UnityEngine; using System.Collections; namespace GameJolt.API { public static class Constants { public const string VERSION = "2.1.0"; public const string SETTINGS_ASSET_NAME = "GJAPISettings"; public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset"; public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/"; public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME; public const string MANAGER_ASSET_NAME = "GameJoltAPI"; public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab"; public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/"; public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME; public const string API_PROTOCOL = "http://"; public const string API_ROOT = "gamejolt.com/api/game/"; public const string API_VERSION = "1"; public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION; public const string API_USERS_AUTH = "/users/auth"; public const string API_USERS_FETCH = "/users"; public const string API_SESSIONS_OPEN = "/sessions/open"; public const string API_SESSIONS_PING = "/sessions/ping"; public const string API_SESSIONS_CLOSE = "/sessions/close"; public const string API_SCORES_ADD = "/scores/add"; public const string API_SCORES_FETCH = "/scores"; public const string API_SCORES_TABLES_FETCH = "/scores/tables"; public const string API_TROPHIES_ADD = "/trophies/add-achieved"; public const string API_TROPHIES_FETCH = "/trophies"; public const string API_DATASTORE_SET = "/data-store/set"; public const string API_DATASTORE_UPDATE = "/data-store/update"; public const string API_DATASTORE_FETCH = "/data-store"; public const string API_DATASTORE_REMOVE = "/data-store/remove"; public const string API_DATASTORE_KEYS_FETCH = "/data-store/get-keys"; public const string IMAGE_RESOURCE_REL_PATH = "Images/"; public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar"; public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME; public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification"; public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME; public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy"; public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME; } }
using UnityEngine; using System.Collections; namespace GameJolt.API { public static class Constants { public const string VERSION = "2.1.0"; public const string SETTINGS_ASSET_NAME = "GJAPISettings"; public const string SETTINGS_ASSET_FULL_NAME = SETTINGS_ASSET_NAME + ".asset"; public const string SETTINGS_ASSET_PATH = "Assets/Plugins/GameJolt/Resources/"; public const string SETTINGS_ASSET_FULL_PATH = SETTINGS_ASSET_PATH + SETTINGS_ASSET_FULL_NAME; public const string MANAGER_ASSET_NAME = "GameJoltAPI"; public const string MANAGER_ASSET_FULL_NAME = MANAGER_ASSET_NAME + ".prefab"; public const string MANAGER_ASSET_PATH = "Assets/Plugins/GameJolt/Prefabs/"; public const string MANAGER_ASSET_FULL_PATH = MANAGER_ASSET_PATH + MANAGER_ASSET_FULL_NAME; public const string API_PROTOCOL = "http://"; public const string API_ROOT = "gamejolt.com/api/game/"; public const string API_VERSION = "1"; public const string API_BASE_URL = API_PROTOCOL + API_ROOT + "v" + API_VERSION; public const string API_USERS_AUTH = "/users/auth"; public const string API_USERS_FETCH = "/users"; public const string API_SESSIONS_OPEN = "/sessions/open"; public const string API_SESSIONS_PING = "/sessions/ping"; public const string API_SESSIONS_CLOSE = "/sessions/close"; public const string API_SCORES_ADD = "/scores/add"; public const string API_SCORES_FETCH = "/scores"; public const string API_SCORES_TABLES_FETCH = "/scores/tables"; public const string API_TROPHIES_ADD = "trophies/add-achieved"; public const string API_TROPHIES_FETCH = "/trophies"; public const string API_DATASTORE_SET = "/data-store/set"; public const string API_DATASTORE_UPDATE = "/data-store/update"; public const string API_DATASTORE_FETCH = "/data-store"; public const string API_DATASTORE_REMOVE = "/data-store/remove"; public const string API_DATASTORE_KEYS_FETCH = "/data-store/get-keys"; public const string IMAGE_RESOURCE_REL_PATH = "Images/"; public const string DEFAULT_AVATAR_ASSET_NAME = "GJAPIDefaultAvatar"; public const string DEFAULT_AVATAR_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_AVATAR_ASSET_NAME; public const string DEFAULT_NOTIFICATION_ASSET_NAME = "GJAPIDefaultNotification"; public const string DEFAULT_NOTIFICATION_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_NOTIFICATION_ASSET_NAME; public const string DEFAULT_TROPHY_ASSET_NAME = "GJAPIDefaultTrophy"; public const string DEFAULT_TROPHY_ASSET_PATH = IMAGE_RESOURCE_REL_PATH + DEFAULT_TROPHY_ASSET_NAME; } }
mit
C#
8c1eb6f9e2620118f0fb6a1491c47357cdfa1030
Refactor OnTargetReached decision
allmonty/BrokenShield,allmonty/BrokenShield
Assets/Scripts/Enemy/Decision_OnTargetReached.cs
Assets/Scripts/Enemy/Decision_OnTargetReached.cs
using UnityEngine; [CreateAssetMenu (menuName = "AI/Decisions/TargetReached")] public class Decision_OnTargetReached : Decision { public bool overrideDistanceToReach; public float distanceToReach; public override bool Decide(StateController controller) { return isTargetReached(controller); } private bool isTargetReached(StateController controller) { var enemyControl = controller as Enemy_StateController; // enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position; // if(!overrideDistanceToReach) // distanceToReach = enemyControl.navMeshAgent.stoppingDistance; // if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) { // return true; // } else { // return false; // } Vector3 enemyPos = enemyControl.gameObject.transform.position; Vector3 playerPos = enemyControl.chaseTarget.position; if (Vector3.Distance(enemyPos, playerPos) <= distanceToReach) { return true; } else { return false; } } }
using UnityEngine; [CreateAssetMenu (menuName = "AI/Decisions/TargetReached")] public class Decision_OnTargetReached : Decision { public bool overrideDistanceToReach; public float distanceToReach; public override bool Decide(StateController controller) { return isTargetReached(controller); } private bool isTargetReached(StateController controller) { var enemyControl = controller as Enemy_StateController; enemyControl.navMeshAgent.destination = enemyControl.chaseTarget.position; if(!overrideDistanceToReach) distanceToReach = enemyControl.navMeshAgent.stoppingDistance; if(enemyControl.navMeshAgent.remainingDistance <= distanceToReach && !enemyControl.navMeshAgent.pathPending) { return true; } else { return false; } } }
apache-2.0
C#
f588e348f7da59babbea085fc06c4174b30b2707
Order by start date by default
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Queries/GetSUTARequests.cs
Battery-Commander.Web/Queries/GetSUTARequests.cs
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetSUTARequests : IRequest<IEnumerable<SUTA>> { [FromRoute] public int Unit { get; set; } // Search by Soldier, Status, Dates private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>> { private readonly Database db; public Handler(Database db) { this.db = db; } public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken) { return await AsQueryable(db) .Where(suta => suta.Soldier.UnitId == request.Unit) .OrderBy(suta => suta.StartDate) .ToListAsync(cancellationToken); } } public static IQueryable<SUTA> AsQueryable(Database db) { return db .SUTAs .Include(suta => suta.Soldier) .ThenInclude(soldier => soldier.Unit) .Include(suta => suta.Supervisor) .Include(suta => suta.Events); } } }
using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BatteryCommander.Web.Models; using MediatR; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace BatteryCommander.Web.Queries { public class GetSUTARequests : IRequest<IEnumerable<SUTA>> { [FromRoute] public int Unit { get; set; } // Search by Soldier, Status, Dates private class Handler : IRequestHandler<GetSUTARequests, IEnumerable<SUTA>> { private readonly Database db; public Handler(Database db) { this.db = db; } public async Task<IEnumerable<SUTA>> Handle(GetSUTARequests request, CancellationToken cancellationToken) { return await AsQueryable(db) .Where(suta => suta.Soldier.UnitId == request.Unit) .ToListAsync(cancellationToken); } } public static IQueryable<SUTA> AsQueryable(Database db) { return db .SUTAs .Include(suta => suta.Soldier) .ThenInclude(soldier => soldier.Unit) .Include(suta => suta.Supervisor) .Include(suta => suta.Events); } } }
mit
C#
c73c30f4b889dd518a2fd063765af02658b24dd3
Increase version from 1.4 to 1.5 before publishing
fredatgithub/UsefulFunctions
CodeGenerationWinForm/Properties/AssemblyInfo.cs
CodeGenerationWinForm/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("CodeGenerationWinForm")] [assembly: AssemblyDescription("This application creates code for unit tests for a series of numbers, a particular number or randomly")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Freddy Juhel")] [assembly: AssemblyProduct("CodeGenerationWinForm")] [assembly: AssemblyCopyright("Copyright © Freddy Juhel MIT 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("b492fe99-f506-48c7-8d6d-b35c2cdef668")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.5.0.0")] [assembly: AssemblyFileVersion("1.5.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("CodeGenerationWinForm")] [assembly: AssemblyDescription("This application creates code for unit tests for a series of numbers, a particular number or randomly")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Freddy Juhel")] [assembly: AssemblyProduct("CodeGenerationWinForm")] [assembly: AssemblyCopyright("Copyright © Freddy Juhel MIT 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("b492fe99-f506-48c7-8d6d-b35c2cdef668")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.0.0")] [assembly: AssemblyFileVersion("1.4.0.0")]
mit
C#
aba08e2c40cc1d190dd92ce1296753ee5d970c81
Fix DeleteBranchCommand error
michael-reichenauer/GitMind
GitMind/Features/Branches/DeleteBranchCommand.cs
GitMind/Features/Branches/DeleteBranchCommand.cs
using System.Threading.Tasks; using GitMind.GitModel; using GitMind.Utils.UI; namespace GitMind.Features.Branches { internal class DeleteBranchCommand : Command<Branch> { private readonly IBranchService branchService; public DeleteBranchCommand(IBranchService branchService) { this.branchService = branchService; } protected override Task RunAsync(Branch branch) { branchService.DeleteBranch(branch); return Task.CompletedTask; } protected override bool CanRun(Branch branch) => branch?.IsActive ?? false; } }
using System.Threading.Tasks; using GitMind.GitModel; using GitMind.Utils.UI; namespace GitMind.Features.Branches { internal class DeleteBranchCommand : Command<Branch> { private readonly IBranchService branchService; public DeleteBranchCommand(IBranchService branchService) { this.branchService = branchService; } protected override Task RunAsync(Branch branch) { branchService.DeleteBranch(branch); return Task.CompletedTask; } protected override bool CanRun(Branch branch) => branch.IsActive; } }
mit
C#
5a50a3567a2914927070e69462aa315d497d0c1e
Build fix.
blattodephobia/BG_Composers,blattodephobia/BG_Composers
BGC.Web/ViewModels/ViewModelBase.cs
BGC.Web/ViewModels/ViewModelBase.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BGC.WebAPI.ViewModels { public abstract partial class ViewModelBase { protected ViewModelBase() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BGC.WebAPI.ViewModels { public partial abstract class ViewModelBase { protected ViewModelBase() { } } }
mit
C#
6540e58c197dee1cca92d247cc0a69a71870802e
Update application version.
RadishSystems/choiceview-webapitester-csharp
ApiTester/Properties/AssemblyInfo.cs
ApiTester/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ApiTester")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Radish Systems, LLC")] [assembly: AssemblyProduct("ChoiceViewIVR")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("11c518e8-6b26-4116-ab41-42f18f80a49a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0")] [assembly: AssemblyFileVersion("1.0.0.1")] [assembly: AssemblyInformationalVersion("1.0 Development")]
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("ApiTester")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ApiTester")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("11c518e8-6b26-4116-ab41-42f18f80a49a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
afd2c5db686e6210b97e81e6252197ec87463ac4
work around Enterprise strangeness
nsnnnnrn/octokit.net,mminns/octokit.net,SmithAndr/octokit.net,TattsGroup/octokit.net,fake-organization/octokit.net,dlsteuer/octokit.net,Sarmad93/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,shana/octokit.net,dampir/octokit.net,rlugojr/octokit.net,thedillonb/octokit.net,dampir/octokit.net,gabrielweyer/octokit.net,fffej/octokit.net,hahmed/octokit.net,devkhan/octokit.net,michaKFromParis/octokit.net,eriawan/octokit.net,darrelmiller/octokit.net,SamTheDev/octokit.net,hitesh97/octokit.net,SLdragon1989/octokit.net,geek0r/octokit.net,magoswiat/octokit.net,mminns/octokit.net,Sarmad93/octokit.net,SamTheDev/octokit.net,alfhenrik/octokit.net,shiftkey/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,cH40z-Lord/octokit.net,octokit-net-test-org/octokit.net,devkhan/octokit.net,ivandrofly/octokit.net,bslliw/octokit.net,chunkychode/octokit.net,naveensrinivasan/octokit.net,thedillonb/octokit.net,gdziadkiewicz/octokit.net,khellang/octokit.net,eriawan/octokit.net,gabrielweyer/octokit.net,daukantas/octokit.net,kolbasov/octokit.net,ChrisMissal/octokit.net,yonglehou/octokit.net,editor-tools/octokit.net,M-Zuber/octokit.net,forki/octokit.net,shiftkey-tester/octokit.net,octokit-net-test-org/octokit.net,octokit/octokit.net,kdolan/octokit.net,shana/octokit.net,octokit/octokit.net,yonglehou/octokit.net,gdziadkiewicz/octokit.net,chunkychode/octokit.net,TattsGroup/octokit.net,rlugojr/octokit.net,shiftkey-tester/octokit.net,takumikub/octokit.net,M-Zuber/octokit.net,alfhenrik/octokit.net,SmithAndr/octokit.net,hahmed/octokit.net,editor-tools/octokit.net,ivandrofly/octokit.net,adamralph/octokit.net,Red-Folder/octokit.net,nsrnnnnn/octokit.net,brramos/octokit.net,octokit-net-test/octokit.net,khellang/octokit.net,shiftkey/octokit.net
Octokit/Models/Plan.cs
Octokit/Models/Plan.cs
namespace Octokit { /// <summary> /// A plan (either paid or free) for a particular user /// </summary> public class Plan { /// <summary> /// The number of collaborators allowed with this plan. /// </summary> /// <remarks>This returns <see cref="long"/> because GitHub Enterprise uses a sentinel value of 999999999999 to denote an "unlimited" number of collaborators.</remarks> public long Collaborators { get; set; } /// <summary> /// The name of the plan. /// </summary> public string Name { get; set; } /// <summary> /// The number of private repositories allowed with this plan. /// </summary> /// <remarks>This returns <see cref="long"/> because GitHub Enterprise uses a sentinel value of 999999999999 to denote an "unlimited" number of plans.</remarks> public long PrivateRepos { get; set; } /// <summary> /// The amount of disk space allowed with this plan. /// </summary> /// <remarks>This returns <see cref="long"/> because GitHub Enterprise uses a sentinel value of 999999999999 to denote an "unlimited" amount of disk space.</remarks> public long Space { get; set; } /// <summary> /// The billing email for the organization. Only has a value in response to editing an organization. /// </summary> public string BillingEmail { get; set; } } }
namespace Octokit { /// <summary> /// A plan (either paid or free) for a particular user /// </summary> public class Plan { /// <summary> /// The number of collaborators allowed with this plan. /// </summary> public int Collaborators { get; set; } /// <summary> /// The name of the plan. /// </summary> public string Name { get; set; } /// <summary> /// The number of private repositories allowed with this plan. /// </summary> public int PrivateRepos { get; set; } /// <summary> /// The amount of disk space allowed with this plan. /// </summary> public int Space { get; set; } /// <summary> /// The billing email for the organization. Only has a value in response to editing an organization. /// </summary> public string BillingEmail { get; set; } } }
mit
C#
9f88283dc113374f6ef74f10832c98f863097385
Comment added
ballamuth/Chrome4Net
src/NativeMessaging/AsyncResult.cs
src/NativeMessaging/AsyncResult.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; namespace Chrome4Net.NativeMessaging { /// <summary> /// This class is an implementation of IAsyncResult interface specific to Chrome4Net.NativeMessaging.Port class. /// </summary> class AsyncResult : IAsyncResult { public object AsyncState { get { return state; } } public WaitHandle AsyncWaitHandle { get { return wait; } } public bool CompletedSynchronously { get { return lengthCompletedSynchronously && messageCompletedSynchronously; } } public bool IsCompleted { get { return lengthIsCompleted && messageIsCompleted; } } public Port port { get; private set; } public AsyncCallback callback { get; private set; } public object state { get; private set; } public ManualResetEvent wait { get; private set; } public bool lengthIsCompleted; public bool lengthCompletedSynchronously; public byte[] lengthBuffer; public int lengthOffset; public Exception lengthException; public bool messageIsCompleted; public bool messageCompletedSynchronously; public byte[] messageBuffer; public int messageOffset; public Exception messageException; public AsyncResult(Port port, AsyncCallback callback, object state) { this.port = port; this.callback = callback; this.state = state; wait = new ManualResetEvent(false); lengthIsCompleted = false; lengthCompletedSynchronously = false; lengthBuffer = null; lengthOffset = 0; lengthException = null; messageIsCompleted = false; messageCompletedSynchronously = false; messageBuffer = null; messageOffset = 0; messageException = null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Threading; namespace Chrome4Net.NativeMessaging { class AsyncResult : IAsyncResult { public object AsyncState { get { return state; } } public WaitHandle AsyncWaitHandle { get { return wait; } } public bool CompletedSynchronously { get { return lengthCompletedSynchronously && messageCompletedSynchronously; } } public bool IsCompleted { get { return lengthIsCompleted && messageIsCompleted; } } public Port port { get; private set; } public AsyncCallback callback { get; private set; } public object state { get; private set; } public ManualResetEvent wait { get; private set; } public bool lengthIsCompleted; public bool lengthCompletedSynchronously; public byte[] lengthBuffer; public int lengthOffset; public Exception lengthException; public bool messageIsCompleted; public bool messageCompletedSynchronously; public byte[] messageBuffer; public int messageOffset; public Exception messageException; public AsyncResult(Port port, AsyncCallback callback, object state) { this.port = port; this.callback = callback; this.state = state; wait = new ManualResetEvent(false); lengthIsCompleted = false; lengthCompletedSynchronously = false; lengthBuffer = null; lengthOffset = 0; lengthException = null; messageIsCompleted = false; messageCompletedSynchronously = false; messageBuffer = null; messageOffset = 0; messageException = null; } } }
apache-2.0
C#
4e228296444f156ee7aed4bb0bdf180336488f7f
Update ProgressReport.cs
tiksn/TIKSN-Framework
TIKSN.Core/Progress/ProgressReport.cs
TIKSN.Core/Progress/ProgressReport.cs
using System.Diagnostics; namespace TIKSN.Progress { public class ProgressReport { public ProgressReport(double percentComplete) { Debug.Assert(percentComplete >= 0d); Debug.Assert(percentComplete <= 100d); this.PercentComplete = percentComplete; } public ProgressReport(int completed, int overall) { Debug.Assert(completed <= overall); Debug.Assert(completed >= 0); this.PercentComplete = overall > 0 ? completed * 100d / overall : 0d; } public double PercentComplete { get; } public static ProgressReport CreateProgressReportWithPercentage(ProgressReport baseReport, double percentComplete) => new(percentComplete); } //public class ProgressStatus<T> : ProgressStatus //{ // public ProgressStatus(T status, double percentage) : base(percentage) // { // Status = status; // } // public ProgressStatus(T status, int completed, int overall) : base(completed, overall) { // Status = status; } // public T Status { get; private set; } //} }
using System.Diagnostics; namespace TIKSN.Progress { public class ProgressReport { public ProgressReport(double percentComplete) { Debug.Assert(percentComplete >= 0d); Debug.Assert(percentComplete <= 100d); PercentComplete = percentComplete; } public ProgressReport(int completed, int overall) { Debug.Assert(completed <= overall); Debug.Assert(completed >= 0); PercentComplete = overall > 0 ? completed * 100d / overall : 0d; } public double PercentComplete { get; private set; } public static ProgressReport CreateProgressReportWithPercentage(ProgressReport baseReport, double percentComplete) { return new ProgressReport(percentComplete); } } //public class ProgressStatus<T> : ProgressStatus //{ // public ProgressStatus(T status, double percentage) : base(percentage) // { // Status = status; // } // public ProgressStatus(T status, int completed, int overall) : base(completed, overall) { // Status = status; } // public T Status { get; private set; } //} }
mit
C#
c5afcf1c9c394c156e791cb7b6d03ea37ac571f3
Move marker file into App_Data a folder that can never be served
mattbrailsford/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,robertjf/Umbraco-CMS,bjarnef/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS
src/Umbraco.Core/IO/SystemFiles.cs
src/Umbraco.Core/IO/SystemFiles.cs
using System.IO; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string TelemetricsIdentifier => SystemDirectories.Data + "/telemetrics-id.umb"; // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IGlobalSettings globalSettings) { return Path.Combine(globalSettings.LocalTempPath, "umbraco.config"); } } }
using System.IO; using Umbraco.Core.Configuration; namespace Umbraco.Core.IO { public class SystemFiles { public static string TinyMceConfig => SystemDirectories.Config + "/tinyMceConfig.config"; public static string TelemetricsIdentifier => SystemDirectories.Umbraco + "/telemetrics-id.umb"; // TODO: Kill this off we don't have umbraco.config XML cache we now have NuCache public static string GetContentCacheXml(IGlobalSettings globalSettings) { return Path.Combine(globalSettings.LocalTempPath, "umbraco.config"); } } }
mit
C#
7cc5fe03b4715f0db261e092a0b4a8df6c0f863e
Change Namespace
muhammedikinci/FuzzyCore
FuzzyCore/ClientProcesses/Client.cs
FuzzyCore/ClientProcesses/Client.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace FuzzyCore.Server { class Client { public int ID { get; set; } public Socket SOCKET { get; set; } public string LASTCONNECTIONTIME { get; set; } public ClosedStates CLOSEDSTATE { get; set; } public int PROCESS { get; set; } public enum ClosedStates { FORCIBLY, NORMAL, NULL } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace fuzzyControl.Server { class Client { public int ID { get; set; } public Socket SOCKET { get; set; } public string LASTCONNECTIONTIME { get; set; } public ClosedStates CLOSEDSTATE { get; set; } public int PROCESS { get; set; } public enum ClosedStates { FORCIBLY, NORMAL, NULL } } }
mit
C#
2c3b0db756297d838b728feb5f3187ed2b25f801
Fix appearing "you already have claim" message if all claim already rejected
leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
Joinrpg/Models/AddClaimViewModel.cs
Joinrpg/Models/AddClaimViewModel.cs
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using JoinRpg.DataModel; using JoinRpg.Web.Helpers; namespace JoinRpg.Web.Models { public class AddClaimViewModel { public int ProjectId { get; set; } public string ProjectName { get; set; } public HtmlString ClaimApplyRules { get; set; } public int? CharacterId { get; set; } public int? CharacterGroupId { get; set; } [DisplayName("Заявка")] public string TargetName { get; set; } public HtmlString Description { get; set; } public bool HasApprovedClaim { get; set; } public bool HasAnyClaim { get; set; } public bool IsAvailable { get; set; } [DataType(DataType.MultilineText),DisplayName("Текст заявки")] public string ClaimText { get; set; } public static AddClaimViewModel Create(Character character, User user) { var vm = CreateImpl(character, user); vm.CharacterId = character.CharacterId; return vm; } public static AddClaimViewModel Create(CharacterGroup group, User user) { var vm = CreateImpl(@group, user); vm.CharacterGroupId = group.CharacterGroupId; return vm; } private static AddClaimViewModel CreateImpl(IClaimSource obj, User user) { var addClaimViewModel = new AddClaimViewModel { ProjectId = obj.ProjectId, ProjectName = obj.Project.ProjectName, HasAnyClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsActive), HasApprovedClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsApproved), TargetName = obj.Name, Description = obj.Description.ToHtmlString(), IsAvailable = obj.IsAvailable, ClaimApplyRules = obj.Project.Details?.ClaimApplyRules?.ToHtmlString() }; return addClaimViewModel; } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using JoinRpg.DataModel; using JoinRpg.Web.Helpers; namespace JoinRpg.Web.Models { public class AddClaimViewModel { public int ProjectId { get; set; } public string ProjectName { get; set; } public HtmlString ClaimApplyRules { get; set; } public int? CharacterId { get; set; } public int? CharacterGroupId { get; set; } [DisplayName("Заявка")] public string TargetName { get; set; } public HtmlString Description { get; set; } public bool HasApprovedClaim { get; set; } public bool HasAnyClaim { get; set; } public bool IsAvailable { get; set; } [DataType(DataType.MultilineText),DisplayName("Текст заявки")] public string ClaimText { get; set; } public static AddClaimViewModel Create(Character character, User user) { var vm = CreateImpl(character, user); vm.CharacterId = character.CharacterId; return vm; } public static AddClaimViewModel Create(CharacterGroup group, User user) { var vm = CreateImpl(@group, user); vm.CharacterGroupId = group.CharacterGroupId; return vm; } private static AddClaimViewModel CreateImpl(IClaimSource obj, User user) { var addClaimViewModel = new AddClaimViewModel { ProjectId = obj.ProjectId, ProjectName = obj.Project.ProjectName, HasAnyClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId), HasApprovedClaim = user.Claims.Any(c => c.ProjectId == obj.ProjectId && c.IsApproved), TargetName = obj.Name, Description = obj.Description.ToHtmlString(), IsAvailable = obj.IsAvailable, ClaimApplyRules = obj.Project.Details?.ClaimApplyRules?.ToHtmlString() }; return addClaimViewModel; } } }
mit
C#
fe2e3ffe7e3431417267a653bc9d99f1bd73d468
Update assembly info for Launcher.
jrick/Paymetheus,decred/Paymetheus
Launcher/Properties/AssemblyInfo.cs
Launcher/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Paymetheus Decred Launcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Paymetheus Launcher")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyMetadata("Organization", "Decred")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyFileVersion("0.4.0.0")]
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Launcher")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Launcher")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
isc
C#
6062ee994db9c67ae85fb1f6acbe7de18a839a6d
Fix build
WildGums/Orc.Sort
src/MethodTimeLogger.cs
src/MethodTimeLogger.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MethodTimeLogger.cs" company="WildGums"> // Copyright (c) 2008 - 2017 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; //using Catel.Logging; using System; /// <summary> /// Note: do not rename this class or put it inside a namespace. /// </summary> internal static class MethodTimeLogger { #region Methods public static void Log(MethodBase methodBase, long milliseconds, string message) { Log(methodBase.DeclaringType, methodBase.Name, milliseconds, message); } public static void Log(Type type, string methodName, long milliseconds, string message) { if (type == null) { return; } var finalMessage = $"[METHODTIMER] {type.Name}.{methodName} took '{milliseconds}' ms"; if (!string.IsNullOrWhiteSpace(message)) { finalMessage += $" | {message}"; } //var logger = LogManager.GetLogger(type); //logger.Debug(finalMessage); } #endregion }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MethodTimeLogger.cs" company="WildGums"> // Copyright (c) 2008 - 2017 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; using Catel.Logging; using System; /// <summary> /// Note: do not rename this class or put it inside a namespace. /// </summary> internal static class MethodTimeLogger { #region Methods public static void Log(MethodBase methodBase, long milliseconds, string message) { Log(methodBase.DeclaringType, methodBase.Name, milliseconds, message); } public static void Log(Type type, string methodName, long milliseconds, string message) { if (type == null) { return; } var finalMessage = $"[METHODTIMER] {type.Name}.{methodName} took '{milliseconds}' ms"; if (!string.IsNullOrWhiteSpace(message)) { finalMessage += $" | {message}"; } var logger = LogManager.GetLogger(type); logger.Debug(finalMessage); } #endregion }
mit
C#
8e8b507fa4525c29cd729538cb2e93acc60413ed
Revert "Fixed weirdness..."
marshallward/TiledSharp
TiledSharp/src/AssemblyInfo.cs
TiledSharp/src/AssemblyInfo.cs
#if !NETCOREAPP using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("TiledSharp")] [assembly: AssemblyDescription ( @"C# library for parsing and importing TMX and TSX files generated by Tiled, a tile map generation tool")] [assembly: AssemblyCompany ("Marshall Ward")] [assembly: AssemblyProduct ("TiledSharp")] [assembly: AssemblyCopyright ("Copyright 2018 Marshall Ward")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("0.15.0.0")] [assembly: AssemblyInformationalVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] // Assume these are true, until I hear otherwise [assembly: CLSCompliant (false)] [assembly: ComVisible (true)] #endif
#if !NETCOREAPP using System.Reflection; using System.Runtime.CompilerServices; // Information about this assembly is defined by the following attributes. // Change them to the values specific to your project. [assembly: AssemblyTitle ("TiledSharp.Test")] [assembly: AssemblyDescription ("")] [assembly: AssemblyConfiguration ("")] [assembly: AssemblyCompany ("")] [assembly: AssemblyProduct ("")] [assembly: AssemblyCopyright ("Marshall Ward")] [assembly: AssemblyTrademark ("")] [assembly: AssemblyCulture ("")] // The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}". // The form "{Major}.{Minor}.*" will automatically update the build and revision, // and "{Major}.{Minor}.{Build}.*" will update just the revision. [assembly: AssemblyVersion ("1.0.0")] // The following attributes are used to specify the signing key for the assembly, // if desired. See the Mono documentation for more information about signing. //[assembly: AssemblyDelaySign(false)] //[assembly: AssemblyKeyFile("")] #endif
apache-2.0
C#