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
5631118a72bba49f90b61c3ee70b8d4f05506f26
Add NavigationPage.
ijufumi/garbage_calendar
garbage_calendar/App.xaml.cs
garbage_calendar/App.xaml.cs
using System; using garbage_calendar.Views; using Prism.Unity; using Xamarin.Forms; namespace garbage_calendar { public partial class App : PrismApplication { public App(IPlatformInitializer initializer) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync("NavigationPage/CalendarPage"); } protected override void RegisterTypes() { Container.RegisterTypeForNavigation<NavigationPage>(); Container.RegisterTypeForNavigation<CalendarPage>(); } } }
using System; using garbage_calendar.Views; using Prism.Unity; using Xamarin.Forms; namespace garbage_calendar { public partial class App : PrismApplication { public App(IPlatformInitializer initializer) : base(initializer) { } protected override void OnInitialized() { InitializeComponent(); NavigationService.NavigateAsync("CalendarPage"); } protected override void RegisterTypes() { Container.RegisterTypeForNavigation<CalendarPage>(); } } }
mit
C#
79de543bc52a53c5c68ef88261c3ba1eba361de3
Rename endpoint to instances
mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard,mvno/Okanshi.Dashboard
src/Okanshi.Dashboard/DashboardModule.cs
src/Okanshi.Dashboard/DashboardModule.cs
using Nancy; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public class DashboardModule : NancyModule { private readonly IGetHealthChecks _getHealthChecks; public DashboardModule(IConfiguration configuration, IGetMetrics getMetrics, IGetHealthChecks getHealthChecks) { _getHealthChecks = getHealthChecks; Get["/"] = p => View["index.html", configuration.GetAll()]; Get["/instances/{instanceName}"] = p => { string instanceName = p.instanceName.ToString(); var service = new Service { Metrics = getMetrics.Execute(instanceName), HealthChecks = _getHealthChecks.Execute(instanceName) }; return Response.AsJson(service); }; } } }
using Nancy; using Okanshi.Dashboard.Models; namespace Okanshi.Dashboard { public class DashboardModule : NancyModule { private readonly IGetHealthChecks _getHealthChecks; public DashboardModule(IConfiguration configuration, IGetMetrics getMetrics, IGetHealthChecks getHealthChecks) { _getHealthChecks = getHealthChecks; Get["/"] = p => View["index.html", configuration.GetAll()]; Get["/instance/{instanceName}"] = p => { string instanceName = p.instanceName.ToString(); var service = new Service { Metrics = getMetrics.Execute(instanceName), HealthChecks = _getHealthChecks.Execute(instanceName) }; return Response.AsJson(service); }; } } }
mit
C#
6b3196987414c05b77419c434fa3b2812b423fab
Correct contains
verybadcat/CSharpMath
CSharpMath.Xaml.Tests.NuGet/Test.cs
CSharpMath.Xaml.Tests.NuGet/Test.cs
namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Contains(forms.Length, new[] { 344, 797 }); // 797 on Mac, 344 on Ubuntu using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } }
namespace CSharpMath.Xaml.Tests.NuGet { using Avalonia; using SkiaSharp; using Forms; public class Program { static string File(string platform, [System.Runtime.CompilerServices.CallerFilePath] string thisDir = "") => System.IO.Path.Combine(thisDir, "..", $"Test.{platform}.png"); [Xunit.Fact] public void TestImage() { global::Avalonia.Skia.SkiaPlatform.Initialize(); Xamarin.Forms.Device.PlatformServices = new Xamarin.Forms.Core.UnitTests.MockPlatformServices(); using (var forms = System.IO.File.OpenWrite(File(nameof(Forms)))) new Forms.MathView { LaTeX = "1" }.Painter.DrawAsStream()?.CopyTo(forms); using (var avalonia = System.IO.File.OpenWrite(File(nameof(Avalonia)))) new Avalonia.MathView { LaTeX = "1" }.Painter.DrawAsPng(avalonia); using (var forms = System.IO.File.OpenRead(File(nameof(Forms)))) Xunit.Assert.Contains(new long[] { 344, 797 }, forms.Length); // 797 on Mac, 344 on Ubuntu using (var avalonia = System.IO.File.OpenRead(File(nameof(Avalonia)))) Xunit.Assert.Equal(344, avalonia.Length); } } }
mit
C#
c907baa3929597a244066afab8c34f145b71c759
Bump version to 8.0.0.18336
HearthSim/HearthDb
HearthDb/Properties/AssemblyInfo.cs
HearthDb/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("HearthDb")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HearthSim")] [assembly: AssemblyProduct("HearthDb")] [assembly: AssemblyCopyright("Copyright © HearthSim 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")] // 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("8.0.0.18336")] [assembly: AssemblyFileVersion("8.0.0.18336")]
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("HearthDb")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HearthSim")] [assembly: AssemblyProduct("HearthDb")] [assembly: AssemblyCopyright("Copyright © HearthSim 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")] // 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("7.1.1.17994")] [assembly: AssemblyFileVersion("7.1.1.17994")]
mit
C#
69a59dd2469e5c64e9830eb6b547f0edd40d33c4
Verify preorder - right
Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews,Gerula/interviews
LeetCode/bootleg/verify_preorder.cs
LeetCode/bootleg/verify_preorder.cs
// http://lcoj.tk/problems/verify-preorder-serialization-of-a-binary-tree-dietpepsi-review/ // // Given a string of comma separated values, // verify whether it is a correct preorder traversal serialization of a binary tree. // Find an algorithm without reconstructing the tree. // // A value in the string is either an integer or a character '#' representing null pointer. // // A correct serialization will contain all the numbers and null pointers in the binary tree. using System; static class Program { static bool ValidTree(this String a) { var diff = 1; foreach (var c in a.Split(new [] { ',' })) { if (--diff < 0) { return false; } if (c != "#") { diff += 2; } } return diff == 0; } static void Main() { foreach (var x in new [] { "9,3,4,#,#,1,#,#,2,#,6,#,#", "1,#", "9,#,#,1" }) { Console.WriteLine("{0} - {1}", x, x.ValidTree()); } } }
// http://lcoj.tk/problems/verify-preorder-serialization-of-a-binary-tree-dietpepsi-review/ // // Given a string of comma separated values, // verify whether it is a correct preorder traversal serialization of a binary tree. // Find an algorithm without reconstructing the tree. // // A value in the string is either an integer or a character '#' representing null pointer. // // A correct serialization will contain all the numbers and null pointers in the binary tree. using System; using System.Collections.Generic; static class Program { static bool ValidTree(this String a) { var s = new Stack<String>(); foreach (var c in a.Split(new [] { ',' })) { if (c == "#") { if (s.Count == 0) { return false; } s.Pop(); } else { s.Push(c); s.Push(c); } } return s.Count == 0; } static void Main() { foreach (var x in new [] { "9,3,4,#,#,1,#,#,2,#,6,#,#", "1,#", "9,#,#,1" }) { Console.WriteLine("{0} - {1}", x, x.ValidTree()); } } }
mit
C#
535551245194fdc2859a45f41a4d0b4d78d9b624
Load image from bundle
Didux/MvvmCross-Plugins,MatthewSannes/MvvmCross-Plugins,lothrop/MvvmCross-Plugins,martijn00/MvvmCross-Plugins
Cirrious/DownloadCache/Cirrious.MvvmCross.Plugins.DownloadCache.Touch/MvxTouchLocalFileImageLoader.cs
Cirrious/DownloadCache/Cirrious.MvvmCross.Plugins.DownloadCache.Touch/MvxTouchLocalFileImageLoader.cs
// MvxTouchLocalFileImageLoader.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Cirrious.CrossCore; using Cirrious.MvvmCross.Plugins.File; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Cirrious.MvvmCross.Plugins.DownloadCache.Touch { public class MvxTouchLocalFileImageLoader : IMvxLocalFileImageLoader<UIImage> { private const string ResourcePrefix = "res:"; public MvxImage<UIImage> Load(string localPath, bool shouldCache) { UIImage uiImage; if (localPath.StartsWith(ResourcePrefix)) { var resourcePath = localPath.Substring(ResourcePrefix.Length); uiImage = LoadResourceImage(resourcePath, shouldCache); } else { uiImage = LoadUIImage(localPath); } return new MvxTouchImage(uiImage); } private UIImage LoadUIImage(string localPath) { var file = Mvx.Resolve<IMvxFileStore>(); var nativePath = file.NativePath(localPath); return UIImage.FromFile(nativePath); } private UIImage LoadResourceImage(string resourcePath, bool shouldCache) { return UIImage.FromBundle(resourcePath); } } }
// MvxTouchLocalFileImageLoader.cs // (c) Copyright Cirrious Ltd. http://www.cirrious.com // MvvmCross is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Stuart Lodge, @slodge, me@slodge.com using Cirrious.CrossCore; using Cirrious.MvvmCross.Plugins.File; using MonoTouch.Foundation; using MonoTouch.UIKit; namespace Cirrious.MvvmCross.Plugins.DownloadCache.Touch { public class MvxTouchLocalFileImageLoader : IMvxLocalFileImageLoader<UIImage> { private const string ResourcePrefix = "res:"; public MvxImage<UIImage> Load(string localPath, bool shouldCache) { UIImage uiImage; if (localPath.StartsWith(ResourcePrefix)) { var resourcePath = localPath.Substring(ResourcePrefix.Length); uiImage = LoadResourceImage(resourcePath, shouldCache); } else { uiImage = LoadUIImage(localPath); } return new MvxTouchImage(uiImage); } private UIImage LoadUIImage(string localPath) { var file = Mvx.Resolve<IMvxFileStore>(); var nativePath = file.NativePath(localPath); return UIImage.FromFile(nativePath); } private UIImage LoadResourceImage(string resourcePath, bool shouldCache) { if (shouldCache) return UIImage.FromFile(resourcePath); else return UIImage.FromFileUncached(resourcePath); } } }
mit
C#
a0ee3fb677b019009127b586e2ceb44d27ecfd9a
Implement RequestExistsByProviderIdQueryHandlerShould
colhountech/allReady,HamidMosalla/allReady,mipre100/allReady,VishalMadhvani/allReady,forestcheng/allReady,dpaquette/allReady,mgmccarthy/allReady,colhountech/allReady,gitChuckD/allReady,c0g1t8/allReady,arst/allReady,arst/allReady,bcbeatty/allReady,GProulx/allReady,GProulx/allReady,BillWagner/allReady,forestcheng/allReady,JowenMei/allReady,binaryjanitor/allReady,gitChuckD/allReady,jonatwabash/allReady,dpaquette/allReady,JowenMei/allReady,chinwobble/allReady,BillWagner/allReady,VishalMadhvani/allReady,MisterJames/allReady,chinwobble/allReady,GProulx/allReady,binaryjanitor/allReady,gitChuckD/allReady,forestcheng/allReady,colhountech/allReady,dpaquette/allReady,bcbeatty/allReady,HTBox/allReady,gitChuckD/allReady,mgmccarthy/allReady,c0g1t8/allReady,stevejgordon/allReady,GProulx/allReady,dpaquette/allReady,anobleperson/allReady,jonatwabash/allReady,bcbeatty/allReady,JowenMei/allReady,chinwobble/allReady,HamidMosalla/allReady,mipre100/allReady,jonatwabash/allReady,colhountech/allReady,arst/allReady,forestcheng/allReady,binaryjanitor/allReady,HamidMosalla/allReady,stevejgordon/allReady,mipre100/allReady,arst/allReady,anobleperson/allReady,MisterJames/allReady,c0g1t8/allReady,MisterJames/allReady,mgmccarthy/allReady,mgmccarthy/allReady,chinwobble/allReady,BillWagner/allReady,c0g1t8/allReady,stevejgordon/allReady,HTBox/allReady,HTBox/allReady,VishalMadhvani/allReady,HamidMosalla/allReady,stevejgordon/allReady,anobleperson/allReady,MisterJames/allReady,HTBox/allReady,JowenMei/allReady,mipre100/allReady,BillWagner/allReady,jonatwabash/allReady,binaryjanitor/allReady,VishalMadhvani/allReady,anobleperson/allReady,bcbeatty/allReady
AllReadyApp/Web-App/AllReady.UnitTest/Features/Requests/RequestExistsByProviderIdQueryHandlerShould.cs
AllReadyApp/Web-App/AllReady.UnitTest/Features/Requests/RequestExistsByProviderIdQueryHandlerShould.cs
using AllReady.Features.Requests; using AllReady.Models; using Xunit; namespace AllReady.UnitTest.Features.Requests { public class RequestExistsByProviderIdQueryHandlerShould : InMemoryContextTest { [Fact] public void ReturnsTrueWhenRequestExists() { const string providerRequestId = "ProviderId"; var request = new Request { ProviderId = providerRequestId }; Context.Requests.Add(request); Context.SaveChanges(); var message = new RequestExistsByProviderIdQuery { ProviderRequestId = providerRequestId }; var sut = new RequestExistsByProviderIdQueryHandler(Context); var result = sut.Handle(message); Assert.True(result); } [Fact] public void ReturnsFalseWhenRequestDoesNotExist() { const string providerRequestId = "AnotherProviderId"; var message = new RequestExistsByProviderIdQuery { ProviderRequestId = providerRequestId }; var sut = new RequestExistsByProviderIdQueryHandler(Context); var result = sut.Handle(message); Assert.False(result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AllReady.UnitTest.Features.Requests { public class RequestExistsByProviderIdQueryHandlerShould { } }
mit
C#
a70c96ea9799d737e9e6c9506b2ac82fa6725104
Use a BandStub for the DesignBandPageViewModel data
corsairmarks/band.personalize
src/Band.Personalize/Band.Personalize.App.Universal/ViewModels/Design/DesignBandPageViewModel.cs
src/Band.Personalize/Band.Personalize.App.Universal/ViewModels/Design/DesignBandPageViewModel.cs
// Copyright 2016 Nicholas Butcher // // 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 Band.Personalize.App.Universal.ViewModels.Design { using Model.Library.Band; using Prism.Windows.Navigation; /// <summary> /// The design View Model for the Band Page. /// </summary> public class DesignBandPageViewModel : BandPageViewModel { /// <summary> /// Initializes a new instance of the <see cref="DesignBandPageViewModel"/> class. /// </summary> public DesignBandPageViewModel() : base(BandPersonalizerStub.Instance) { this.OnNavigatedTo( new NavigatedToEventArgs { Parameter = new BandStub { Name = "Band F0:F0", ConnectionType = ConnectionType.Usb, HardwareRevision = HardwareRevision.Band, HardwareVersion = 21, }, }, null); } } }
// Copyright 2016 Nicholas Butcher // // 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 Band.Personalize.App.Universal.ViewModels.Design { using Prism.Windows.Navigation; /// <summary> /// The design View Model for the Band Page. /// </summary> public class DesignBandPageViewModel : BandPageViewModel { /// <summary> /// Initializes a new instance of the <see cref="DesignBandPageViewModel"/> class. /// </summary> public DesignBandPageViewModel() : base(BandPersonalizerStub.Instance) { this.OnNavigatedTo( new NavigatedToEventArgs { Parameter = null, }, null); } } }
apache-2.0
C#
6b9f663f3481f0b86c2a7ff5ceaeea59d93e166e
update community page links (#558)
reactiveui/website,reactiveui/website,reactiveui/website,reactiveui/website
input/contribute/community/index.cshtml
input/contribute/community/index.cshtml
Order: 100 --- <ul> <li> <a href="https://reddit.com/r/Clojure/comments/73yznc/on_whose_authority/do1olag" target="_blank">reddit.com</a> </li> <li> <a href="https://olivierlacan.com/posts/ruby-heroes-farewell/" target="_blank">Ruby Heroes Farewell</a> </li> </ul> @Html.Partial("_ChildPages") <div class="video-iframe-wrapper"> <div class="video-iframe-item"> <?# YouTube ZSFDm3UYkeE /?> </div> </div>
Order: 100 --- https://reddit.com/r/Clojure/comments/73yznc/on_whose_authority/do1olag https://olivierlacan.com/posts/ruby-heroes-farewell/ @Html.Partial("_ChildPages") <div class="video-iframe-wrapper"> <div class="video-iframe-item"> <?# YouTube ZSFDm3UYkeE /?> </div> </div>
mit
C#
0152b156bcbee3d19896991fce0f91732ebb124d
Update LocalizablePropertyProcessor.cs
rolembergfilho/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,WasimAhmad/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,rolembergfilho/Serenity,volkanceylan/Serenity,rolembergfilho/Serenity,WasimAhmad/Serenity,volkanceylan/Serenity,volkanceylan/Serenity
Serenity.Services/RequestHandlers/IntegratedFeatures/Localization/LocalizablePropertyProcessor.cs
Serenity.Services/RequestHandlers/IntegratedFeatures/Localization/LocalizablePropertyProcessor.cs
using Serenity.ComponentModel; using Serenity.Data; using System; using System.ComponentModel; using System.Reflection; namespace Serenity.PropertyGrid { public partial class LocalizablePropertyProcessor : PropertyProcessor { private ILocalizationRowHandler localizationRowHandler; public override void Initialize() { if (BasedOnRow == null) return; var attr = BasedOnRow.GetType().GetCustomAttribute<LocalizationRowAttribute>(false); if (attr != null) localizationRowHandler = Activator.CreateInstance(typeof(LocalizationRowHandler<>) .MakeGenericType(BasedOnRow.GetType())) as ILocalizationRowHandler; } public override void Process(IPropertySource source, PropertyItem item) { var attr = source.GetAttribute<LocalizableAttribute>(); if (attr != null) { if (attr.IsLocalizable) item.Localizable = true; return; } if (!ReferenceEquals(null, source.BasedOnField) && localizationRowHandler != null && localizationRowHandler.IsLocalized(source.BasedOnField)) { item.Localizable = true; } } public override int Priority { get { return 15; } } } }
using Serenity.ComponentModel; using Serenity.Data; using System; using System.ComponentModel; using System.Reflection; namespace Serenity.PropertyGrid { public partial class LocalizablePropertyProcessor : PropertyProcessor { private ILocalizationRowHandler localizationRowHandler; public override void Initialize() { if (BasedOnRow == null) return; var attr = BasedOnRow.GetType().GetCustomAttribute<LocalizationRowAttribute>(false); if (attr != null) localizationRowHandler = Activator.CreateInstance(typeof(LocalizationRowHandler<>) .MakeGenericType(BasedOnRow.GetType())) as ILocalizationRowHandler; } public override void Process(IPropertySource source, PropertyItem item) { var attr = source.GetAttribute<LocalizableAttribute>(); if (attr != null) { if (item.IsLocalizable) item.Localizable = true; return; } if (!ReferenceEquals(null, source.BasedOnField) && localizationRowHandler != null && localizationRowHandler.IsLocalized(source.BasedOnField)) { item.Localizable = true; } } public override int Priority { get { return 15; } } } }
mit
C#
b219842567ccf88fc6c228dac898f3d6de874ac1
Use NetLib client
ashfordl/netlib
ConsoleApplication1/Program.cs
ConsoleApplication1/Program.cs
using NetLib.Client; using NetLib.Server; using System; using System.Net; using System.Net.Sockets; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int port = 6565; Server server = new Server(port); server.Serve(); IPEndPoint ip = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); //Client client = new Client(ip); Client client = new Client(IPAddress.Parse("127.0.0.1"), port); //Client client = new Client("127.0.0.1", port); client.Send("Bonjour, wie gehts dir?"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NetLib.Client; using NetLib.Server; using System.Net.Sockets; using System.Net; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { int port = 6565; Server server = new Server(port); server.Serve(); Client(port); Console.WriteLine("Client: Message sent"); } static void Client(int port) { TcpClient client = new TcpClient(); IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port); client.Connect(serverEndPoint); NetworkStream clientStream = client.GetStream(); string message = "yo hello team"; // Encode message in bytes byte[] msgBuffer = Encoding.ASCII.GetBytes(message); byte[] lenBuffer = BitConverter.GetBytes(msgBuffer.Length); // 4 bytes // Concat two byte arrays byte[] buffer = new byte[4 + msgBuffer.Length]; lenBuffer.CopyTo(buffer, 0); msgBuffer.CopyTo(buffer, 4); // Send the data clientStream.Write(buffer, 0, buffer.Length); } } }
mit
C#
f43fc6433f67c74d9026de4e7fdeacc0f6b6448e
change error file name
jongha/clickoncedm,jongha/clickoncedm
src/ClickOnceDMLib/Process/LogProcess.cs
src/ClickOnceDMLib/Process/LogProcess.cs
using ClickOnceDMLib.Path; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ClickOnceDMLib.Process { public class LogProcess { private enum LOGTYPE { INFO, ERROR }; public static void Error(string message) { WriteLog(LOGTYPE.ERROR, message); } public static void Info(string message) { WriteLog(LOGTYPE.INFO, message); } private static void WriteLog(LOGTYPE logType, string message) { string file = string.Empty; switch (logType) { default: case LOGTYPE.INFO: file = PathInfo.CombinePath(PathInfo.Log, DateTime.Now.ToString("yyyyMMddHH")) + ".log"; break; case LOGTYPE.ERROR: file = PathInfo.CombinePath(PathInfo.Log, DateTime.Now.ToString("yyyyMMdd")) + ".error"; break; } if (!string.IsNullOrEmpty(file)) { using (StreamWriter writer = new StreamWriter(file, true)) { writer.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString("u"), message)); } } } } }
using ClickOnceDMLib.Path; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ClickOnceDMLib.Process { public class LogProcess { private enum LOGTYPE { INFO, ERROR }; public static void Error(string message) { WriteLog(LOGTYPE.ERROR, message); } public static void Info(string message) { WriteLog(LOGTYPE.INFO, message); } private static void WriteLog(LOGTYPE logType, string message) { string file = PathInfo.CombinePath(PathInfo.Log, DateTime.Now.ToString("yyyyMMddHH")); if (logType == LOGTYPE.INFO) { file += ".log"; } else if(logType == LOGTYPE.ERROR) { file += ".error"; } using (StreamWriter writer = new StreamWriter(file, true)) { writer.WriteLine(string.Format("{0} {1}", DateTime.Now.ToString("u"), message)); } } } }
mit
C#
0a9a9d6756184d8db4c189f79ab9a7d3acac93f2
Debug logging
DMagic1/Science-Contracts
ContractScienceUtils.cs
ContractScienceUtils.cs
#region license /*The MIT License (MIT) Science Contract Utilities Copyright (c) 2014 DMagic 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. */ #endregion using System; using System.Collections.Generic; using UnityEngine; namespace Contract_Science { static class ContractScienceUtils { internal static System.Random rand; internal static Dictionary<string, contractScienceContainer> availableScience; internal static float science, reward, forward, penalty; internal static List<string> storyList; internal static float getSubjectValue(ExperimentSituations s, CelestialBody body) { float subV = 1; if (s == ExperimentSituations.SrfLanded) subV = body.scienceValues.LandedDataValue; else if (s == ExperimentSituations.SrfSplashed) subV = body.scienceValues.SplashedDataValue; else if (s == ExperimentSituations.FlyingLow || s == ExperimentSituations.FlyingHigh) subV = body.scienceValues.FlyingLowDataValue; else if (s == ExperimentSituations.InSpaceLow || s == ExperimentSituations.InSpaceHigh) subV = body.scienceValues.InSpaceLowDataValue; return subV; } internal static void Logging(string s, params object[] stringObjects) { s = string.Format(s, stringObjects); string finalLog = string.Format("[CS] {0}", s); Debug.Log(finalLog); } #region Debug Logging [System.Diagnostics.Conditional("DEBUG")] internal static void DebugLog(string s, params object[] stringObjects) { s = string.Format(s, stringObjects); string finalLog = string.Format("[CS] {0}", s); Debug.Log(finalLog); } #endregion } }
#region license /*The MIT License (MIT) Science Contract Utilities Copyright (c) 2014 DMagic 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. */ #endregion using System; using System.Collections.Generic; using UnityEngine; namespace Contract_Science { static class ContractScienceUtils { internal static System.Random rand; internal static Dictionary<string, contractScienceContainer> availableScience; internal static float science, reward, forward, penalty; internal static List<string> storyList; internal static float getSubjectValue(ExperimentSituations s, CelestialBody body) { float subV = 1; if (s == ExperimentSituations.SrfLanded) subV = body.scienceValues.LandedDataValue; else if (s == ExperimentSituations.SrfSplashed) subV = body.scienceValues.SplashedDataValue; else if (s == ExperimentSituations.FlyingLow || s == ExperimentSituations.FlyingHigh) subV = body.scienceValues.FlyingLowDataValue; else if (s == ExperimentSituations.InSpaceLow || s == ExperimentSituations.InSpaceHigh) subV = body.scienceValues.InSpaceLowDataValue; return subV; } internal static void Logging(string s, params object[] stringObjects) { s = string.Format(s, stringObjects); string finalLog = string.Format("[CS] {0}", s); Debug.Log(finalLog); } #region Debug Logging internal static void DebugLog(string s, params object[] stringObjects) { #if DEBUG s = string.Format(s, stringObjects); string finalLog = string.Format("[CS] {0}", s); Debug.Log(finalLog); #endif } #endregion } }
mit
C#
55590a5bf6f0b765bb4994de2730c529b60d3306
Revert "Update HttpHelpers.cs"
mperdeck/jsnlog
src/JSNLog/Infrastructure/HttpHelpers.cs
src/JSNLog/Infrastructure/HttpHelpers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; #if NET40 using System.Web; #else using Microsoft.AspNetCore.Http; #endif namespace JSNLog.Infrastructure { internal static class HttpHelpers { private static Regex _regex = new Regex(@";\s*charset=(?<charset>[^\s;]+)"); public static Encoding GetEncoding(string contentType) { if (string.IsNullOrEmpty(contentType)) { return Encoding.UTF8; } string charset = "utf-8"; var match = _regex.Match(contentType); if (match.Success) { charset = match.Groups["charset"].Value; } try { return Encoding.GetEncoding(charset); } catch { return Encoding.UTF8; } } public static string GetUserIp(this HttpContext httpContext) { #if NET40 string userIp = httpContext.Request.UserHostAddress; #else string userIp = Utils.SafeToString(httpContext.Connection.RemoteIpAddress); #endif return userIp; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; #if NET40 using System.Web; #else using Microsoft.AspNetCore.Http; #endif namespace JSNLog.Infrastructure { internal static class HttpHelpers { private static Regex _regex = new Regex(@";\s*charset=(?<charset>[^\s;]+)"); public static Encoding GetEncoding(string contentType) { if (string.IsNullOrEmpty(contentType)) { return Encoding.UTF8; } string charset = "utf-8"; var match = _regex.Match(contentType); if (match.Success) { charset = match.Groups["charset"].Value; } try { return Encoding.GetEncoding(charset); } catch { return Encoding.UTF8; } } public static string GetUserIp(this HttpContext httpContext) { #if NET40 string userIp = (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? httpContext.Request.UserHostAddress : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]); #else string userIp = (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) ? Utils.SafeToString(httpContext.Connection.RemoteIpAddress) : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]); #endif return userIp; } } }
mit
C#
753871749cfbe9bb6108ef7638297661e84e1236
remove check for args for /xyzzy
yadyn/JabbR,yadyn/JabbR,yadyn/JabbR
JabbR/Commands/XyzzyCommand.cs
JabbR/Commands/XyzzyCommand.cs
using System; using System.Linq; using JabbR.Models; using Microsoft.AspNet.SignalR; namespace JabbR.Commands { [Command("xyzzy", "Xyzzy_CommandInfo", "note", "user")] public class XyzzyCommand : UserCommand { public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { ChatRoom room = context.Repository.VerifyUserRoom(context.Cache, callingUser, callerContext.RoomName); room.EnsureOpen(); var content = String.Join(" ", args); context.NotificationService.OnXyzzy(room); } } }
using System; using System.Linq; using JabbR.Models; using Microsoft.AspNet.SignalR; namespace JabbR.Commands { [Command("xyzzy", "Xyzzy_CommandInfo", "note", "user")] public class XyzzyCommand : UserCommand { public override void Execute(CommandContext context, CallerContext callerContext, ChatUser callingUser, string[] args) { ChatRoom room = context.Repository.VerifyUserRoom(context.Cache, callingUser, callerContext.RoomName); room.EnsureOpen(); if (args.Length == 0) { throw new HubException(LanguageResources.Me_ActionRequired); } var content = String.Join(" ", args); context.NotificationService.OnXyzzy(room); } } }
mit
C#
f37a3cb206cbd7b09c2861045a64e2cfb4d3d4b7
fix #2604 add position_length on analyze api response (#2622)
CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,elastic/elasticsearch-net,adam-mccoy/elasticsearch-net,elastic/elasticsearch-net,CSGOpenSource/elasticsearch-net,adam-mccoy/elasticsearch-net
src/Nest/Indices/Analyze/AnalyzeToken.cs
src/Nest/Indices/Analyze/AnalyzeToken.cs
using Newtonsoft.Json; namespace Nest { [JsonObject] public class AnalyzeToken { [JsonProperty(PropertyName = "token")] public string Token { get; internal set; } [JsonProperty(PropertyName = "type")] public string Type { get; internal set; } //TODO change to long in 6.0 [JsonProperty(PropertyName = "start_offset")] public int StartOffset { get; internal set; } [JsonProperty(PropertyName = "end_offset")] public int EndPostion { get; internal set; } [JsonProperty(PropertyName = "position")] public int Position { get; internal set; } [JsonProperty(PropertyName = "position_length")] public long? PositionLength { get; internal set; } } }
using Newtonsoft.Json; namespace Nest { [JsonObject] public class AnalyzeToken { [JsonProperty(PropertyName = "token")] public string Token { get; internal set; } [JsonProperty(PropertyName = "type")] public string Type { get; internal set; } [JsonProperty(PropertyName = "start_offset")] public int StartOffset { get; internal set; } [JsonProperty(PropertyName = "end_offset")] public int EndPostion { get; internal set; } [JsonProperty(PropertyName = "position")] public int Position { get; internal set; } } }
apache-2.0
C#
61c15ad4a656b02884290a299bdaa080d7014818
Update 20.12
aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET
Examples/CSharp/Articles/ManagingWorkbooksWorksheets/ExportExcelDataToDataTableWithoutFormatting.cs
Examples/CSharp/Articles/ManagingWorkbooksWorksheets/ExportExcelDataToDataTableWithoutFormatting.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Aspose.Cells.Examples.CSharp.Articles.ManagingWorkbooksWorksheets { class ExportExcelDataToDataTableWithoutFormatting { public static void Run() { // ExStart:ExportExcelDataToDataTableWithoutFormatting // Create workbook Workbook workbook = new Workbook(); // Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Access cell A1 Cell cell = worksheet.Cells["A1"]; // Put value inside the cell cell.PutValue(0.012345); // Format the cell that it should display 0.01 instead of 0.012345 Style style = cell.GetStyle(); style.Number = 2; cell.SetStyle(style); // Display the cell values as it displays in excel Console.WriteLine("Cell String Value: " + cell.StringValue); // Export Data Table Options with FormatStrategy as CellStyle ExportTableOptions opts = new ExportTableOptions(); opts.ExportAsString = true; opts.FormatStrategy = CellValueFormatStrategy.CellStyle; // Export Data Table DataTable dt = worksheet.Cells.ExportDataTable(0, 0, 1, 1, opts); // Display the value of very first cell Console.WriteLine("Export Data Table with Format Strategy as Cell Style: " + dt.Rows[0][0].ToString()); // Export Data Table Options with FormatStrategy as None opts.FormatStrategy = CellValueFormatStrategy.None; dt = worksheet.Cells.ExportDataTable(0, 0, 1, 1, opts); // Display the value of very first cell Console.WriteLine("Export Data Table with Format Strategy as None: " + dt.Rows[0][0].ToString()); // ExEnd:ExportExcelDataToDataTableWithoutFormatting } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; namespace Aspose.Cells.Examples.CSharp.Articles.ManagingWorkbooksWorksheets { class ExportExcelDataToDataTableWithoutFormatting { public static void Run() { // ExStart:ExportExcelDataToDataTableWithoutFormatting // Create workbook Workbook workbook = new Workbook(); // Access first worksheet Worksheet worksheet = workbook.Worksheets[0]; // Access cell A1 Cell cell = worksheet.Cells["A1"]; // Put value inside the cell cell.PutValue(0.012345); // Format the cell that it should display 0.01 instead of 0.012345 Style style = cell.GetStyle(); style.Number = 2; cell.SetStyle(style); // Display the cell values as it displays in excel Console.WriteLine("Cell String Value: " + cell.StringValue); // Display the cell value without any format Console.WriteLine("Cell String Value without Format: " + cell.StringValueWithoutFormat); // Export Data Table Options with FormatStrategy as CellStyle ExportTableOptions opts = new ExportTableOptions(); opts.ExportAsString = true; opts.FormatStrategy = CellValueFormatStrategy.CellStyle; // Export Data Table DataTable dt = worksheet.Cells.ExportDataTable(0, 0, 1, 1, opts); // Display the value of very first cell Console.WriteLine("Export Data Table with Format Strategy as Cell Style: " + dt.Rows[0][0].ToString()); // Export Data Table Options with FormatStrategy as None opts.FormatStrategy = CellValueFormatStrategy.None; dt = worksheet.Cells.ExportDataTable(0, 0, 1, 1, opts); // Display the value of very first cell Console.WriteLine("Export Data Table with Format Strategy as None: " + dt.Rows[0][0].ToString()); // ExEnd:ExportExcelDataToDataTableWithoutFormatting } } }
mit
C#
9612f7f4655aac02794a1d834674f64fe8ac0583
Handle missing ratelimit headers (can occur with uploadtexttrack)
mohibsheth/vimeo-dot-net,mfilippov/vimeo-dot-net,needham-develop/vimeo-dot-net
src/VimeoDotNet/VimeoClient_RateLimit.cs
src/VimeoDotNet/VimeoClient_RateLimit.cs
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; using VimeoDotNet.Constants; using VimeoDotNet.Enums; using VimeoDotNet.Exceptions; using VimeoDotNet.Models; using VimeoDotNet.Net; namespace VimeoDotNet { public partial class VimeoClient : IVimeoClient { public long RateLimit { get { if (_headers != null) { var v = _headers.FirstOrDefault(h => h.Name.Equals("X-RateLimit-Limit")); return Convert.ToInt64(v != null ? v.Value.ToString() : "0"); } return 0; } } public long RateLimitRemaining { get { if (_headers != null) { var v = _headers.FirstOrDefault(h => h.Name.Equals("X-RateLimit-Remaining")); return Convert.ToInt64(v != null ? v.Value.ToString() : "0"); } return 0; } } public DateTime RateLimitReset { get { if (_headers != null) { var v = _headers.FirstOrDefault(h => h.Name.Equals("X-RateLimit-Reset")); if (v != null) { return DateTime.Parse(v.Value.ToString()); } } return DateTime.UtcNow; } } private IList<Parameter> _headers = null; private void UpdateRateLimit(IRestResponse response) { _headers = response.Headers; } } }
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.RegularExpressions; using System.Threading.Tasks; using VimeoDotNet.Constants; using VimeoDotNet.Enums; using VimeoDotNet.Exceptions; using VimeoDotNet.Models; using VimeoDotNet.Net; namespace VimeoDotNet { public partial class VimeoClient : IVimeoClient { public long RateLimit { get { if (_headers != null) { var v = _headers.FirstOrDefault(h => h.Name.Equals("X-RateLimit-Limit")); return Convert.ToInt64(v.Value.ToString()); } return 0; } } public long RateLimitRemaining { get { if (_headers != null) { var v = _headers.FirstOrDefault(h => h.Name.Equals("X-RateLimit-Remaining")); return Convert.ToInt64(v.Value.ToString()); } return 0; } } public DateTime RateLimitReset { get { if (_headers != null) { var v = _headers.FirstOrDefault(h => h.Name.Equals("X-RateLimit-Reset")); return DateTime.Parse(v.Value.ToString()); } return DateTime.UtcNow; } } private IList<Parameter> _headers = null; private void UpdateRateLimit(IRestResponse response) { _headers = response.Headers; } } }
mit
C#
792bbd19bc2ddc2514df3737600bb40a43edcc57
Handle NLayer failures.
Meowtrix/osu-Auto-Mapping-Toolkit
MusicProcess/MusicProcesser.cs
MusicProcess/MusicProcesser.cs
using NLayer; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Meowtrix.osuAMT.MusicProcess { public class MusicProcessException : Exception { public MusicProcessException() : base() { } public MusicProcessException(string message) : base(message) { } public MusicProcessException(string message, Exception innerException) : base(message, innerException) { } } public static class MusicProcesser { /// <summary> /// Set this to change the FFT implementation used; default to a managed version FFT implementation. /// User may consider provide some optimized or accelerated implementation wrapping MKL, cuFFT or so on. /// </summary> public static FFT256 FFT256Implementation = ManagedFFT256.Execute; /// <summary> /// Process mp3 data for use in training and evaluating the machine learning models. /// </summary> /// <param name="mp3">Mp3 data in memory.</param> /// <returns>Matrix as data for the ML models. One row for a data point in the sequence.</returns> public static float[,] ProcessMp3(Stream mp3) { var file = new MpegFile(mp3) { StereoMode = StereoMode.DownmixToMono }; if (file.SampleRate != 44100) throw new MusicProcessException("Sample rate is not 44100. Consider conversion."); var sampleCount = (int)(file.Length / (file.Channels * sizeof(float))); var downSampledSampleCount = (sampleCount + 255) / 256; // Ceiling to multiple of 256 var pcm = new float[downSampledSampleCount * 256]; try { file.ReadSamples(pcm, 0, sampleCount); } catch { throw new MusicProcessException("NLayer Error."); } // Execute FFT. FFT256Implementation(pcm); // Reshape the result into desired dimension. var reshaped = new float[downSampledSampleCount, 64]; // Only copying first 64 point of each FFT result: cutting off frequency data above ~11kHz should be ok for normal "music". for (int i = 0; i < downSampledSampleCount; ++i) Buffer.BlockCopy(pcm, i * 256 * sizeof(float), reshaped, i * 64 * sizeof(float), 64 * sizeof(float)); return reshaped; } } }
using NLayer; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Meowtrix.osuAMT.MusicProcess { public class MusicProcessException : Exception { public MusicProcessException() : base() { } public MusicProcessException(string message) : base(message) { } public MusicProcessException(string message, Exception innerException) : base(message, innerException) { } } public static class MusicProcesser { /// <summary> /// Set this to change the FFT implementation used; default to a managed version FFT implementation. /// User may consider provide some optimized or accelerated implementation wrapping MKL, cuFFT or so on. /// </summary> public static FFT256 FFT256Implementation = ManagedFFT256.Execute; /// <summary> /// Process mp3 data for use in training and evaluating the machine learning models. /// </summary> /// <param name="mp3">Mp3 data in memory.</param> /// <returns>Matrix as data for the ML models. One row for a data point in the sequence.</returns> public static float[,] ProcessMp3(Stream mp3) { var file = new MpegFile(mp3) { StereoMode = StereoMode.DownmixToMono }; if (file.SampleRate != 44100) throw new MusicProcessException("Sample rate is not 44100. Consider conversion."); var sampleCount = (int)(file.Length / (file.Channels * sizeof(float))); var downSampledSampleCount = (sampleCount + 255) / 256; // Ceiling to multiple of 256 var pcm = new float[downSampledSampleCount * 256]; file.ReadSamples(pcm, 0, sampleCount); // Execute FFT. FFT256Implementation(pcm); // Reshape the result into desired dimension. var reshaped = new float[downSampledSampleCount, 64]; // Only copying first 64 point of each FFT result: cutting off frequency data above ~11kHz should be ok for normal "music". for (int i = 0; i < downSampledSampleCount; ++i) Buffer.BlockCopy(pcm, i * 256 * sizeof(float), reshaped, i * 64 * sizeof(float), 64 * sizeof(float)); return reshaped; } } }
mit
C#
262129b96b695b5b2c3652dff7a4006c3b7a883a
Remove unused property from chat message (#5053)
johnneijzen/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,smoogipoo/osu,johnneijzen/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,2yangk23/osu,ZLima12/osu,peppy/osu,UselessToucan/osu,ZLima12/osu,2yangk23/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu
osu.Game/Online/Chat/Message.cs
osu.Game/Online/Chat/Message.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Users; namespace osu.Game.Online.Chat { public class Message : IComparable<Message>, IEquatable<Message> { [JsonProperty(@"message_id")] public readonly long? Id; [JsonProperty(@"channel_id")] public long ChannelId; [JsonProperty(@"is_action")] public bool IsAction; [JsonProperty(@"timestamp")] public DateTimeOffset Timestamp; [JsonProperty(@"content")] public string Content; [JsonProperty(@"sender")] public User Sender; [JsonConstructor] public Message() { } /// <summary> /// The text that is displayed in chat. /// </summary> public string DisplayContent { get; set; } /// <summary> /// The links found in this message. /// </summary> /// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks> public List<Link> Links; public Message(long? id) { Id = id; } public int CompareTo(Message other) { if (!Id.HasValue) return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp); if (!other.Id.HasValue) return -1; return Id.Value.CompareTo(other.Id.Value); } public virtual bool Equals(Message other) => Id == other?.Id; // ReSharper disable once ImpureMethodCallOnReadonlyValueField public override int GetHashCode() => Id.GetHashCode(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using Newtonsoft.Json; using osu.Game.Users; namespace osu.Game.Online.Chat { public class Message : IComparable<Message>, IEquatable<Message> { [JsonProperty(@"message_id")] public readonly long? Id; //todo: this should be inside sender. [JsonProperty(@"sender_id")] public long UserId; [JsonProperty(@"channel_id")] public long ChannelId; [JsonProperty(@"is_action")] public bool IsAction; [JsonProperty(@"timestamp")] public DateTimeOffset Timestamp; [JsonProperty(@"content")] public string Content; [JsonProperty(@"sender")] public User Sender; [JsonConstructor] public Message() { } /// <summary> /// The text that is displayed in chat. /// </summary> public string DisplayContent { get; set; } /// <summary> /// The links found in this message. /// </summary> /// <remarks>The <see cref="Link"/>s' <see cref="Link.Index"/> and <see cref="Link.Length"/>s are according to <see cref="DisplayContent"/></remarks> public List<Link> Links; public Message(long? id) { Id = id; } public int CompareTo(Message other) { if (!Id.HasValue) return other.Id.HasValue ? 1 : Timestamp.CompareTo(other.Timestamp); if (!other.Id.HasValue) return -1; return Id.Value.CompareTo(other.Id.Value); } public virtual bool Equals(Message other) => Id == other?.Id; // ReSharper disable once ImpureMethodCallOnReadonlyValueField public override int GetHashCode() => Id.GetHashCode(); } }
mit
C#
9f52cb17c480fbae83dc736bf5dbdb2dd6e9a69f
Update gio-sharp
mono/f-spot,mans0954/f-spot,Sanva/f-spot,dkoeb/f-spot,GNOME/f-spot,Yetangitu/f-spot,dkoeb/f-spot,mans0954/f-spot,dkoeb/f-spot,Sanva/f-spot,mono/f-spot,Sanva/f-spot,Yetangitu/f-spot,dkoeb/f-spot,Sanva/f-spot,GNOME/f-spot,Yetangitu/f-spot,Yetangitu/f-spot,mans0954/f-spot,dkoeb/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,dkoeb/f-spot,GNOME/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,nathansamson/F-Spot-Album-Exporter,mono/f-spot,NguyenMatthieu/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,NguyenMatthieu/f-spot,GNOME/f-spot,mans0954/f-spot,mans0954/f-spot,mans0954/f-spot,Sanva/f-spot,GNOME/f-spot,mono/f-spot,Yetangitu/f-spot,NguyenMatthieu/f-spot,NguyenMatthieu/f-spot
gio-sharp/gio/FileFactory.cs
gio-sharp/gio/FileFactory.cs
// // FileFactory.cs // // Author(s): // Stephane Delcroix <stephane@delcroix.org> // // Copyright (c) 2008 Stephane Delcroix // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. using System; using System.Runtime.InteropServices; namespace GLib { public class FileFactory { [DllImport ("libgio-2.0-0.dll")] private static extern IntPtr g_file_new_for_uri (string uri); public static File NewForUri (string uri) { return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri), false) as File; } public static File NewForUri (Uri uri) { return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri.ToString ()), false) as File; } [DllImport ("libgio-2.0-0.dll")] private static extern IntPtr g_file_new_for_path (string path); public static File NewForPath (string path) { return GLib.FileAdapter.GetObject (g_file_new_for_path (path), false) as File; } [DllImport ("libgio-2.0-0.dll")] private static extern IntPtr g_file_new_for_commandline_arg (string arg); public static File NewFromCommandlineArg (string arg) { return GLib.FileAdapter.GetObject (g_file_new_for_commandline_arg (arg), false) as File; } } }
// // FileFactory.cs // // Author(s): // Stephane Delcroix <stephane@delcroix.org> // // Copyright (c) 2008 Stephane Delcroix // // This program is free software; you can redistribute it and/or // modify it under the terms of version 2 of the Lesser GNU General // Public License as published by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this program; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. using System; using System.Runtime.InteropServices; namespace GLib { public class FileFactory { [DllImport ("libgio-2.0-0.dll")] private static extern IntPtr g_file_new_for_uri (string uri); public static File NewForUri (string uri) { return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri), false) as File; } public static File NewForUri (Uri uri) { return GLib.FileAdapter.GetObject (g_file_new_for_uri (uri.ToString ()), false) as File; } [DllImport ("libgio-2.0-0.dll")] private static extern IntPtr g_file_new_for_path (string path); public static File NewForPath (string path) { return GLib.FileAdapter.GetObject (g_file_new_for_path (path), false) as File; } [DllImport ("libgio-2.0-0.dll")] private static extern IntPtr g_file_new_for_commandline_args (string args); public static File NewForCommandlineArgs (string args) { return GLib.FileAdapter.GetObject (g_file_new_for_commandline_args (args), false) as File; } } }
mit
C#
de47b86a9682dd0e15687e74382bb6bee809e18c
添加bFold字段,标识该项在面板中是否展开
Andy-Sun/Unity3d-Sequential
scripts/DataSource.cs
scripts/DataSource.cs
/* * Author: AndySun * Date: 2015-07-02 * Description: The DataStruct for xml file & Unity Scripts Communication with each other. */ using System.Collections.Generic; using System.Xml; using UnityEngine; /// <summary> /// 操作的类型 /// </summary> public enum EOperType { Trans, Rot, SetParent } /// <summary> /// 操作对象 /// </summary> [System.Serializable] public class OperItem { /// <summary> /// 判断该项在面板中是否展开 /// </summary> public bool bFold = false; /// <summary> /// 操作名称 /// </summary> public string name = ""; /// <summary> /// 当前操作的物体 /// </summary> public GameObject go; /// <summary> /// 操作的类型 /// </summary> public EOperType type; /// <summary> /// 操作数值 /// </summary> public Vector3 param; /// <summary> /// 操作参数,父物体 /// </summary> public Transform parent; /// <summary> /// 操作时的步骤提示 /// </summary> public string msg = ""; /// <summary> /// 操作错误信息 /// </summary> public string errorMsg = ""; /// <summary> /// 操作分组,组内动作可以同时执行,只有所有动作都完成后才可继续执行 /// </summary> public bool group = false; public string groupID; }
/* * Author: AndySun * Date: 2015-07-02 * Description: The DataStruct for xml file & Unity Scripts Communication with each other. */ using System.Collections.Generic; using System.Xml; using UnityEngine; /// <summary> /// 操作的类型 /// </summary> public enum EOperType { Trans, Rot, SetParent } /// <summary> /// 操作对象 /// </summary> [System.Serializable] public class OperItem { /// <summary> /// 操作名称 /// </summary> public string name = ""; /// <summary> /// 当前操作的物体 /// </summary> public GameObject go; /// <summary> /// 操作的类型 /// </summary> public EOperType type; /// <summary> /// 操作数值 /// </summary> public Vector3 param; /// <summary> /// 操作参数,父物体 /// </summary> public Transform parent; /// <summary> /// 操作时的步骤提示 /// </summary> public string msg = ""; /// <summary> /// 操作错误信息 /// </summary> public string errorMsg = ""; /// <summary> /// 操作分组,组内动作可以同时执行,只有所有动作都完成后才可继续执行 /// </summary> public bool group = false; public string groupID; }
mit
C#
66c004c8a008f9603b7aa96956749486e838e201
Add doc comment.
nguerrera/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,aelij/roslyn,KevinRansom/roslyn,CyrusNajmabadi/roslyn,dpoeschl/roslyn,physhi/roslyn,brettfo/roslyn,genlu/roslyn,gafter/roslyn,agocke/roslyn,weltkante/roslyn,DustinCampbell/roslyn,davkean/roslyn,agocke/roslyn,wvdd007/roslyn,swaroop-sridhar/roslyn,sharwell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tmeschter/roslyn,dpoeschl/roslyn,xasx/roslyn,AlekseyTs/roslyn,heejaechang/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,tmeschter/roslyn,genlu/roslyn,AmadeusW/roslyn,abock/roslyn,VSadov/roslyn,wvdd007/roslyn,stephentoub/roslyn,jcouv/roslyn,DustinCampbell/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,wvdd007/roslyn,tmat/roslyn,physhi/roslyn,diryboy/roslyn,weltkante/roslyn,nguerrera/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,brettfo/roslyn,MichalStrehovsky/roslyn,VSadov/roslyn,sharwell/roslyn,davkean/roslyn,agocke/roslyn,KevinRansom/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,jmarolf/roslyn,tannergooding/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,mavasani/roslyn,bartdesmet/roslyn,weltkante/roslyn,davkean/roslyn,abock/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,jasonmalinowski/roslyn,KirillOsenkov/roslyn,dotnet/roslyn,panopticoncentral/roslyn,gafter/roslyn,diryboy/roslyn,diryboy/roslyn,KevinRansom/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,tmat/roslyn,xasx/roslyn,VSadov/roslyn,jcouv/roslyn,jasonmalinowski/roslyn,KirillOsenkov/roslyn,swaroop-sridhar/roslyn,mgoertz-msft/roslyn,reaction1989/roslyn,jmarolf/roslyn,aelij/roslyn,mavasani/roslyn,mgoertz-msft/roslyn,abock/roslyn,eriawan/roslyn,physhi/roslyn,AlekseyTs/roslyn,dotnet/roslyn,AmadeusW/roslyn,tannergooding/roslyn,CyrusNajmabadi/roslyn,MichalStrehovsky/roslyn,sharwell/roslyn,xasx/roslyn,gafter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,MichalStrehovsky/roslyn,cston/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,ErikSchierboom/roslyn,dpoeschl/roslyn,eriawan/roslyn,cston/roslyn,nguerrera/roslyn,tmeschter/roslyn,AlekseyTs/roslyn,mavasani/roslyn,cston/roslyn,dotnet/roslyn,swaroop-sridhar/roslyn,reaction1989/roslyn,aelij/roslyn,jmarolf/roslyn,bartdesmet/roslyn,jcouv/roslyn,tmat/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,reaction1989/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,genlu/roslyn
src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.cs
src/Features/Core/Portable/GenerateEqualsAndGetHashCodeFromMembers/IGenerateEqualsAndGetHashCodeService.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.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { /// <summary> /// Service that can be used to generate <see cref="object.Equals(object)"/> and /// <see cref="object.GetHashCode"/> overloads for use from other IDE features. /// </summary> internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService { Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string localNameOpt, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Host; namespace Microsoft.CodeAnalysis.GenerateEqualsAndGetHashCodeFromMembers { internal interface IGenerateEqualsAndGetHashCodeService : ILanguageService { Task<Document> FormatDocumentAsync(Document document, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, string localNameOpt, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateEqualsMethodThroughIEquatableEqualsAsync(Document document, INamedTypeSymbol namedType, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateIEquatableEqualsMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); Task<IMethodSymbol> GenerateGetHashCodeMethodAsync(Document document, INamedTypeSymbol namedType, ImmutableArray<ISymbol> members, CancellationToken cancellationToken); } }
mit
C#
aedc9816942d3f32f78f4a6d8fa1005fb2306e6d
deal with null
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Core/Extensions/StringExtensions.cs
Anlab.Core/Extensions/StringExtensions.cs
using System; using System.Globalization; namespace Anlab.Core.Extensions { public static class StringExtensions { public static string SafeToUpper(this string value) { if (value == null) { return null; } return value.ToUpper(CultureInfo.InvariantCulture); } public static bool ClearOutSetupPrice(this string value) { //If we have other special cases, add them here return string.Equals(value, "GRNDONLY", StringComparison.OrdinalIgnoreCase); //Deals with null, which would only happen in my tests } public static bool IsGroupTest(this string value) { return value.StartsWith("G-", StringComparison.OrdinalIgnoreCase); } } }
using System; using System.Globalization; namespace Anlab.Core.Extensions { public static class StringExtensions { public static string SafeToUpper(this string value) { if (value == null) { return null; } return value.ToUpper(CultureInfo.InvariantCulture); } public static bool ClearOutSetupPrice(this string value) { //If we have other special cases, add them here return value.Equals("GRNDONLY", StringComparison.OrdinalIgnoreCase); } public static bool IsGroupTest(this string value) { return value.StartsWith("G-", StringComparison.OrdinalIgnoreCase); } } }
mit
C#
a3f2ea7b10b3ce422787062603a5da0a64c111a3
Set FormatterFactory as public
PKRoma/refit,martijn00/refit,mteper/refit,onovotny/refit,martijn00/refit,mteper/refit,onovotny/refit,ammachado/refit,paulcbetts/refit,jlucansky/refit,paulcbetts/refit,PureWeen/refit,jlucansky/refit,ammachado/refit,PureWeen/refit
Refit/RequestBuilder.cs
Refit/RequestBuilder.cs
using System; using System.Collections.Generic; using System.Net.Http; namespace Refit { public interface IRequestBuilder { IEnumerable<string> InterfaceHttpMethods { get; } Func<object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = ""); Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName); } interface IRequestBuilderFactory { IRequestBuilder Create(Type interfaceType, IRequestParameterFormatter requestParameterFormatter); } public static class RequestBuilder { public static Func<Type, IRequestParameterFormatter> FormatterFactory = type => new DefaultRequestParameterFormatter(type); static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory(); public static IRequestBuilder ForType(Type interfaceType) { return platformRequestBuilderFactory.Create(interfaceType, FormatterFactory(interfaceType)); } public static IRequestBuilder ForType<T>() { return ForType(typeof(T)); } } #if PORTABLE class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, IRequestParameterFormatter requestParameterFormatter) { throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!"); } } #endif }
using System; using System.Collections.Generic; using System.Net.Http; namespace Refit { public interface IRequestBuilder { IEnumerable<string> InterfaceHttpMethods { get; } Func<object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = ""); Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName); } interface IRequestBuilderFactory { IRequestBuilder Create(Type interfaceType, IRequestParameterFormatter requestParameterFormatter); } public static class RequestBuilder { static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory(); static Func<Type, IRequestParameterFormatter> FormatterFactory = type => new DefaultRequestParameterFormatter(type); public static IRequestBuilder ForType(Type interfaceType) { return platformRequestBuilderFactory.Create(interfaceType, FormatterFactory(interfaceType)); } public static IRequestBuilder ForType<T>() { return ForType(typeof(T)); } } #if PORTABLE class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, IRequestParameterFormatter requestParameterFormatter) { throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!"); } } #endif }
mit
C#
ed53c1c00bd48c65145df2cc80232110b252ca3b
Fix assembly resolve on x64
simontaylor81/DirectXTex.net,simontaylor81/DirectXTex.net,simontaylor81/DirectXTex.net
src/DirectXTexNet/DirectXTex.cs
src/DirectXTexNet/DirectXTex.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DirectXTexNet { public static class DirectXTex { public static IScratchImage LoadFromDDSFile(string filename) { return Impl.DirectXTex.LoadFromDDSFile(filename); } public static IScratchImage LoadFromWICFile(string filename) { return Impl.DirectXTex.LoadFromWICFile(filename); } public static IScratchImage LoadFromTGAFile(string filename) { return Impl.DirectXTex.LoadFromTGAFile(filename); } public static IScratchImage Create2D(IntPtr data, int pitch, int width, int height, uint format) { return Impl.DirectXTex.Create2D(data, pitch, width, height, format); } static DirectXTex() { AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolve; } // Custom assembly resolver to find the architecture-specific implementation assembly. private static Assembly AssemblyResolve(object sender, ResolveEventArgs args) { if (args.Name.StartsWith("DirectXTexNetImpl", StringComparison.OrdinalIgnoreCase)) { var path = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), // Our path ArchitectureMoniker, "DirectXTexNetImpl.dll"); Console.WriteLine("Looking in " + path); return Assembly.LoadFile(path); } return null; } // Note: currently no support for ARM. // Don't use %PROCESSOR_ARCHITECTURE% as it calls x64 'AMD64'. private static string ArchitectureMoniker => Environment.Is64BitProcess ? "x64" : "x86"; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace DirectXTexNet { public static class DirectXTex { public static IScratchImage LoadFromDDSFile(string filename) { return Impl.DirectXTex.LoadFromDDSFile(filename); } public static IScratchImage LoadFromWICFile(string filename) { return Impl.DirectXTex.LoadFromWICFile(filename); } public static IScratchImage LoadFromTGAFile(string filename) { return Impl.DirectXTex.LoadFromTGAFile(filename); } public static IScratchImage Create2D(IntPtr data, int pitch, int width, int height, uint format) { return Impl.DirectXTex.Create2D(data, pitch, width, height, format); } static DirectXTex() { AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve; } // Custom assembly resolver to find the architecture-specific implementation assembly. private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { if (args.Name.StartsWith("DirectXTexNetImpl", StringComparison.OrdinalIgnoreCase)) { var path = Path.Combine( Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), // Our path Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"), // x86 or x64 "DirectXTexNetImpl.dll"); return Assembly.LoadFile(path); } return null; } } }
mit
C#
570e79f23c9e8237502394924fe1be3068e94d15
add todo
kreeben/resin,kreeben/resin
src/DocumentTable/Compressor.cs
src/DocumentTable/Compressor.cs
using System.IO; using System.IO.Compression; namespace DocumentTable { public static class Deflator { //TODO: write directly to output stream public static byte[] Compress(string text) { if (string.IsNullOrWhiteSpace(text)) return new byte[0]; var bytes = TableSerializer.Encoding.GetBytes(text); return Compress(bytes); } public static byte[] Compress(byte[] data) { var output = new MemoryStream(); using (var dstream = new DeflateStream(output, CompressionLevel.Optimal)) { dstream.Write(data, 0, data.Length); } return output.ToArray(); } public static byte[] Deflate(byte[] data) { var input = new MemoryStream(data); var output = new MemoryStream(); using (var dstream = new DeflateStream(input, CompressionMode.Decompress)) { dstream.CopyTo(output); } return output.ToArray(); } } }
using System.IO; using System.IO.Compression; namespace DocumentTable { public static class Deflator { public static byte[] Compress(string text) { if (string.IsNullOrWhiteSpace(text)) return new byte[0]; var bytes = TableSerializer.Encoding.GetBytes(text); return Compress(bytes); } public static byte[] Compress(byte[] data) { var output = new MemoryStream(); using (var dstream = new DeflateStream(output, CompressionLevel.Optimal)) { dstream.Write(data, 0, data.Length); } return output.ToArray(); } public static byte[] Deflate(byte[] data) { var input = new MemoryStream(data); var output = new MemoryStream(); using (var dstream = new DeflateStream(input, CompressionMode.Decompress)) { dstream.CopyTo(output); } return output.ToArray(); } } }
mit
C#
723627c77630de08f75a77da5c8adc80d80c86e5
Simplify control flow and reduce excessive calls to IEnumerable.Any().
plioi/parsley
src/Parsley/ErrorMessageList.cs
src/Parsley/ErrorMessageList.cs
namespace Parsley; public class ErrorMessageList { public static readonly ErrorMessageList Empty = new(); readonly ErrorMessage? head; readonly ErrorMessageList? tail; ErrorMessageList() { head = null; tail = null; } ErrorMessageList(ErrorMessage head, ErrorMessageList tail) { this.head = head; this.tail = tail; } public ErrorMessageList With(ErrorMessage errorMessage) { return new ErrorMessageList(errorMessage, this); } public ErrorMessageList Merge(ErrorMessageList errors) { var result = this; foreach (var error in errors.All<ErrorMessage>()) result = result.With(error); return result; } public override string ToString() { if (this == Empty) return ""; var expectationErrors = new List<string>(All<ExpectedErrorMessage>() .Select(error => error.Expectation) .Distinct() .OrderBy(expectation => expectation)); var backtrackErrors = All<BacktrackErrorMessage>().ToArray(); var parts = new List<string>(); if (expectationErrors.Any()) { var suffixes = Separators(expectationErrors.Count - 1).Concat(new[] { " expected" }); parts.Add(string.Join("", expectationErrors.Zip(suffixes, (error, suffix) => error + suffix))); } if (backtrackErrors.Any()) parts.Add(string.Join(" ", backtrackErrors.Select(backtrack => $"[{backtrack.Position}: {backtrack.Errors}]"))); return parts.Count > 0 ? string.Join(" ", parts) : "Parse error."; } static IEnumerable<string> Separators(int count) { if (count <= 0) return Enumerable.Empty<string>(); return Enumerable.Repeat(", ", count - 1).Concat(new[] { " or " }); } IEnumerable<T> All<T>() where T : ErrorMessage { if (head is T match) yield return match; if (tail != null) foreach (var message in tail.All<T>()) yield return message; } }
namespace Parsley; public class ErrorMessageList { public static readonly ErrorMessageList Empty = new(); readonly ErrorMessage? head; readonly ErrorMessageList? tail; ErrorMessageList() { head = null; tail = null; } ErrorMessageList(ErrorMessage head, ErrorMessageList tail) { this.head = head; this.tail = tail; } public ErrorMessageList With(ErrorMessage errorMessage) { return new ErrorMessageList(errorMessage, this); } public ErrorMessageList Merge(ErrorMessageList errors) { var result = this; foreach (var error in errors.All<ErrorMessage>()) result = result.With(error); return result; } public override string ToString() { if (this == Empty) return ""; var expectationErrors = new List<string>(All<ExpectedErrorMessage>() .Select(error => error.Expectation) .Distinct() .OrderBy(expectation => expectation)); var backtrackErrors = All<BacktrackErrorMessage>().ToArray(); if (!expectationErrors.Any() && !backtrackErrors.Any()) return "Parse error."; var parts = new List<string>(); if (expectationErrors.Any()) { var suffixes = Separators(expectationErrors.Count - 1).Concat(new[] { " expected" }); parts.Add(string.Join("", expectationErrors.Zip(suffixes, (error, suffix) => error + suffix))); } if (backtrackErrors.Any()) parts.Add(string.Join(" ", backtrackErrors.Select(backtrack => $"[{backtrack.Position}: {backtrack.Errors}]"))); return string.Join(" ", parts); } static IEnumerable<string> Separators(int count) { if (count <= 0) return Enumerable.Empty<string>(); return Enumerable.Repeat(", ", count - 1).Concat(new[] { " or " }); } IEnumerable<T> All<T>() where T : ErrorMessage { if (head is T match) yield return match; if (tail != null) foreach (var message in tail.All<T>()) yield return message; } }
mit
C#
ddc4c7dc95be9432fc96c095b226dac305ec325f
update example
jasarsoft/ipcs-primjeri
ipcs_36/primjer01/Program.cs
ipcs_36/primjer01/Program.cs
using System; using System.Collections; namespace primjer01 { class Program { static void Main(string[] args) { //deklarisemo kolekciju tipa ArrayList ArrayList names = new ArrayList(); Console.WriteLine("Incjalizovani broj elemenata: " + names.Count + "\n"); //dodoavanje elemenata u listu names.Add("Andjela"); names.Add("Nevena"); names.Add("Ana"); Console.WriteLine("Broj elemenata nakon dodavanje {0}", names.Count); //prikazivanje cijele liste koriscenjem indeksera Console.WriteLine("Trenutni sadrzaj: "); for (int i = 0; i < names.Count; i++) Console.Write(names[i] + " "); Console.WriteLine("\n"); Console.WriteLine("Uklanjanje elemenata u toku..."); Console.WriteLine("Uklonjen elemenet Ana"); names.Remove("Ana"); Console.WriteLine("Trenutni broj elemenata: {0}", names.Count); //iscrtavanje elemenata upotreba foreach petlje Console.Write("Elementi: "); foreach (string name in names) Console.Write(name + " "); Console.WriteLine("\n"); //mjenjanje sadrzaja Console.WriteLine("Mijenja se prvi element: "); names[0] = "Milena"; Console.Write("Ponovo izlistavanje sadrzaja: "); foreach (string name in names) Console.Write(name + " "); Console.Read(); } } }
using System; using System.Collections; namespace primjer01 { class Program { static void Main(string[] args) { //deklarisemo kolekciju tipa ArrayList ArrayList names = new ArrayList(); Console.WriteLine("Incjalizovani broj elemenata: " + names.Count + "\n"); //dodoavanje elemenata u listu names.Add("Andjela"); names.Add("Nevena"); names.Add("Ana"); Console.WriteLine("Broj elemenata nakon dodavanje {0}\n", names.Count); //prikazivanje cijele liste koriscenjem indeksera Console.WriteLine("Trenutni sadrzaj: "); for (int i = 0; i < names.Count; i++) Console.Write(names[i] + " "); } } }
apache-2.0
C#
d9dbfcc2c7fe8b977ac4251e37d79005fd3ac674
Add Tasker to global service provider 🗜
Huex/VKDiscordBot
VKDiscordBot/Program.cs
VKDiscordBot/Program.cs
using Discord.Commands; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using System.Threading.Tasks; using VKDiscordBot.Models; using VKDiscordBot.Services; namespace VKDiscordBot { public class Program { static void Main(string[] args) { new Program().MainAsync().GetAwaiter().GetResult(); } private async Task MainAsync() { var data = new DataManager(); data.LoadBotSettings("Configurations/Settings.json"); var logger = new Logger(data.BotSettings.LogLevel); data.Log += logger.Log; data.LoadGuildsSettings("Configurations/Guilds/"); var client = new DiscordSocketClient(data.BotSettings.ToDiscordSocketConfig()); client.Log += logger.Log; var tasker = new Tasker(); var commands = new CommandService(); commands.Log += logger.Log; // Команды добавить здесь var vk = new VkService("Configurations/Secrets/VkAuthParams.json"); vk.Log += logger.Log; // Создать сервисы здесь var services = new ServiceCollection(); services.AddSingleton(data); services.AddSingleton(commands); services.AddSingleton(vk); services.AddSingleton(tasker); // Сервисы добавить здесь var commandHandler = new CommandHandler(client, services.BuildServiceProvider()); client.MessageReceived += commandHandler.HandleCommandAsync; client.GuildAvailable += data.CheckGuildSettings; await client.LoginAsync(Discord.TokenType.Bot, File.ReadAllText("Configurations/Secrets/Token.txt")); await client.StartAsync(); await Task.Delay(-1); } } }
using Discord.Commands; using Discord.WebSocket; using Microsoft.Extensions.DependencyInjection; using System; using System.IO; using System.Threading.Tasks; using VKDiscordBot.Services; namespace VKDiscordBot { public class Program { static void Main(string[] args) { new Program().MainAsync().GetAwaiter().GetResult(); } private async Task MainAsync() { var data = new DataManager(); data.LoadBotSettings("Configurations/Settings.json"); var logger = new Logger(data.BotSettings.LogLevel); data.Log += logger.Log; data.LoadGuildsSettings("Configurations/Guilds/"); var client = new DiscordSocketClient(data.BotSettings.ToDiscordSocketConfig()); client.Log += logger.Log; var commands = new CommandService(); commands.Log += logger.Log; // Команды добавить здесь var vk = new VkService("Configurations/Secrets/VkAuthParams.json"); vk.Log += logger.Log; // Создать сервисы здесь var services = new ServiceCollection(); services.AddSingleton(data); services.AddSingleton(commands); services.AddSingleton(vk); // Сервисы добавить здесь var commandHandler = new CommandHandler(client, services.BuildServiceProvider()); client.MessageReceived += commandHandler.HandleCommandAsync; client.GuildAvailable += data.CheckGuildSettings; await client.LoginAsync(Discord.TokenType.Bot, File.ReadAllText("Configurations/Secrets/Token.txt")); await client.StartAsync(); await Task.Delay(-1); } } }
mit
C#
06a00b85bde05cc78cc548334a1393b2fecf39d5
Update IMapperBuilder.cs
NN---/CodeJam,rsdn/CodeJam
CodeJam.Blocks/Mapping/IMapperBuilder.cs
CodeJam.Blocks/Mapping/IMapperBuilder.cs
#if !LESSTHAN_NET40 using System; using System.Collections.Generic; using System.Linq.Expressions; using CodeJam.Reflection; using JetBrains.Annotations; namespace CodeJam.Mapping { /// <summary> /// Builds a mapper that maps an object of <i>TFrom</i> type to an object of <i>TTo</i> type. /// </summary> [PublicAPI] public interface IMapperBuilder { /// <summary> /// Mapping schema. /// </summary> [NotNull] MappingSchema MappingSchema { get; set; } /// <summary> /// Returns a mapper expression to map an object of <i>TFrom</i> type to an object of <i>TTo</i> type. /// Returned expression is compatible to IQueriable. /// </summary> /// <returns>Mapping expression.</returns> [Pure] LambdaExpression GetMapperLambdaExpressionEx(); /// <summary> /// Returns a mapper expression to map an object of <i>TFrom</i> type to an object of <i>TTo</i> type. /// </summary> /// <returns>Mapping expression.</returns> [Pure] LambdaExpression GetMapperLambdaExpression(); /// <summary> /// Filters target members to map. /// </summary> Func<MemberAccessor,bool> MemberFilter { get; set; } /// <summary> /// Defines member name mapping for source types. /// </summary> Dictionary<Type,Dictionary<string,string>> FromMappingDictionary { get; set; } /// <summary> /// Defines member name mapping for destination types. /// </summary> Dictionary<Type,Dictionary<string,string>> ToMappingDictionary { get; set; } /// <summary> /// Member mappers. /// </summary> List<MemberMapper> MemberMappers { get; set; } /// <summary> /// If true, processes object cross references. /// if default (null), the <see cref="GetMapperLambdaExpressionEx"/> method does not process cross references, /// however the <see cref="GetMapperLambdaExpression"/> method does. /// </summary> bool? ProcessCrossReferences { get; set; } /// <summary> /// If true, performs deep copy. /// if default (null), the <see cref="GetMapperLambdaExpressionEx"/> method does not do deep copy, /// however the <see cref="GetMapperLambdaExpression"/> method does. /// </summary> bool? DeepCopy { get; set; } /// <summary> /// Type to map from. /// </summary> [NotNull] Type FromType { get; } /// <summary> /// Type to map to. /// </summary> [NotNull] Type ToType { get; } } /// <summary>Member Mapper</summary> public struct MemberMapper { /// <summary>Constructor</summary> public MemberMapper(LambdaExpression from, LambdaExpression to) { From = from; To = to; } /// <summary>From</summary> public readonly LambdaExpression From; /// <summary>To</summary> public readonly LambdaExpression To; } } #endif
#if !LESSTHAN_NET40 using System; using System.Collections.Generic; using System.Linq.Expressions; using CodeJam.Reflection; using JetBrains.Annotations; namespace CodeJam.Mapping { /// <summary> /// Builds a mapper that maps an object of <i>TFrom</i> type to an object of <i>TTo</i> type. /// </summary> [PublicAPI] public interface IMapperBuilder { /// <summary> /// Mapping schema. /// </summary> [NotNull] MappingSchema MappingSchema { get; set; } /// <summary> /// Returns a mapper expression to map an object of <i>TFrom</i> type to an object of <i>TTo</i> type. /// Returned expression is compatible to IQueriable. /// </summary> /// <returns>Mapping expression.</returns> [Pure] LambdaExpression GetMapperLambdaExpressionEx(); /// <summary> /// Returns a mapper expression to map an object of <i>TFrom</i> type to an object of <i>TTo</i> type. /// </summary> /// <returns>Mapping expression.</returns> [Pure] LambdaExpression GetMapperLambdaExpression(); /// <summary> /// Filters target members to map. /// </summary> Func<MemberAccessor,bool> MemberFilter { get; set; } /// <summary> /// Defines member name mapping for source types. /// </summary> Dictionary<Type,Dictionary<string,string>> FromMappingDictionary { get; set; } /// <summary> /// Defines member name mapping for destination types. /// </summary> Dictionary<Type,Dictionary<string,string>> ToMappingDictionary { get; set; } /// <summary> /// Member mappers. /// </summary> List<MemberMapper> MemberMappers { get; set; } /// <summary> /// If true, processes object cross references. /// if default (null), the <see cref="GetMapperLambdaExpressionEx"/> method does not process cross references, /// however the <see cref="GetMapperLambdaExpression"/> method does. /// </summary> bool? ProcessCrossReferences { get; set; } /// <summary> /// If true, performs deep copy. /// if default (null), the <see cref="GetMapperLambdaExpressionEx"/> method does not do deep copy, /// however the <see cref="GetMapperLambdaExpression"/> method does. /// </summary> bool? DeepCopy { get; set; } /// <summary> /// Type to map from. /// </summary> [NotNull] Type FromType { get; } /// <summary> /// Type to map to. /// </summary> [NotNull] Type ToType { get; } } /// <summary>Member Mapper</summary> public struct MemberMapper { /// <summary>Constructor</summary> public MemberMapper(LambdaExpression from, LambdaExpression to) { From = from; To = to; } /// <summary>From</summary> public readonly LambdaExpression From; /// <summary>To</summary> public readonly LambdaExpression To; } } #endif
mit
C#
b288499bc81cf8e309ad59888c57f1c2ae49ebc3
Update Program.cs
sqfish/cheers
Cheers/Cheers/Program.cs
Cheers/Cheers/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cheers { class Program { static void Main(string[] args) { //Get the user's name and print it. Console.WriteLine("What's your name?"); string name = Console.ReadLine(); Console.WriteLine("Hi, " + name); //Cheer the user on. foreach (char letter in name) { string vowels = "aeiofhlmnrsx"; string article = "a"; if (vowels.Contains(Char.ToLower(letter)) == true) { article = "an"; } Console.WriteLine("Give me " + article + " " + letter); } Console.WriteLine(name + " is GRAND!"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cheers { class Program { static void Main(string[] args) { //Get the user's name and print it. Console.WriteLine("What's your name?"); string name = Console.ReadLine(); Console.WriteLine("Hi, " + name); //Cheer the user on. foreach (char letter in name) { string vowels = "aeiouhlmnrsx"; string article = "a"; if (vowels.Contains(Char.ToLower(letter)) == true) { article = "an"; } Console.WriteLine("Give me " + article + " " + letter); } Console.WriteLine(name + " is GRAND!"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } }
mit
C#
f27349abfef05c59264b9f8f5886a8ed331c3140
Add cast Environment to int
SIROK/growthbeat-unity,SIROK/growthbeat-unity,growthbeat/growthbeat-unity,growthbeat/growthbeat-unity
source/Assets/Plugins/Growthbeat/GrowthPush.cs
source/Assets/Plugins/Growthbeat/GrowthPush.cs
// // GrowthPush.cs // Growthbeat-unity // // Created by Baekwoo Chung on 2015/06/15. // Copyright (c) 2015年 SIROK, Inc. All rights reserved. // using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; public class GrowthPush { private static GrowthPush instance = new GrowthPush (); public enum Environment { Unknown = 0, Development = 1, Production = 2 } #if UNITY_IPHONE [DllImport("__Internal")] private static extern void growthPushRequestDeviceToken(int environment); [DllImport("__Internal")] private static extern void growthPushSetDeviceToken(string deviceToken); [DllImport("__Internal")] private static extern void growthPushClearBadge(); [DllImport("__Internal")] private static extern void growthPushSetTag(string name, string value); [DllImport("__Internal")] private static extern void growthPushTrackEvent(string name, string value); [DllImport("__Internal")] private static extern void growthPushSetDeviceTags(); #endif public static GrowthPush GetInstance () { return GrowthPush.instance; } public void RequestDeviceToken (Environment environment) { #if UNITY_ANDROID #elif UNITY_IPHONE && !UNITY_EDITOR growthPushRequestDeviceToken((int)environment); #endif } public void SetDeviceToken (string deviceToken) { #if UNITY_ANDROID #elif UNITY_IPHONE && !UNITY_EDITOR growthPushSetDeviceToken(deviceToken); #endif } public void RequestRegistrationId (string senderId) { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().RequestRegistrationId(senderId); #endif } public void ClearBadge () { #if UNITY_IPHONE && !UNITY_EDITOR growthPushClearBadge(); #endif } public void SetTag (string name) { SetTag (name, null); } public void SetTag (string name, string value) { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().SetTag(name, value); #elif UNITY_IPHONE && !UNITY_EDITOR growthPushSetTag(name, value); #endif } public void TrackEvent(string name) { TrackEvent (name, null); } public void TrackEvent (string name, string value) { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().TrackEvent(name, value); #elif UNITY_IPHONE && !UNITY_EDITOR growthPushTrackEvent(name, value); #endif } public void SetDeviceTags () { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().SetDeviceTags(); #elif UNITY_IPHONE && !UNITY_EDITOR growthPushSetDeviceTags(); #endif } }
// // GrowthPush.cs // Growthbeat-unity // // Created by Baekwoo Chung on 2015/06/15. // Copyright (c) 2015年 SIROK, Inc. All rights reserved. // using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; public class GrowthPush { private static GrowthPush instance = new GrowthPush (); public enum Environment { Unknown = 0, Development = 1, Production = 2 } #if UNITY_IPHONE [DllImport("__Internal")] private static extern void growthPushRequestDeviceToken(int environment); [DllImport("__Internal")] private static extern void growthPushSetDeviceToken(string deviceToken); [DllImport("__Internal")] private static extern void growthPushClearBadge(); [DllImport("__Internal")] private static extern void growthPushSetTag(string name, string value); [DllImport("__Internal")] private static extern void growthPushTrackEvent(string name, string value); [DllImport("__Internal")] private static extern void growthPushSetDeviceTags(); #endif public static GrowthPush GetInstance () { return GrowthPush.instance; } public void RequestDeviceToken (Environment environment) { #if UNITY_ANDROID #elif UNITY_IPHONE && !UNITY_EDITOR growthPushRequestDeviceToken(environment); #endif } public void SetDeviceToken (string deviceToken) { #if UNITY_ANDROID #elif UNITY_IPHONE && !UNITY_EDITOR growthPushSetDeviceToken(deviceToken); #endif } public void RequestRegistrationId (string senderId) { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().RequestRegistrationId(senderId); #endif } public void ClearBadge () { #if UNITY_IPHONE && !UNITY_EDITOR growthPushClearBadge(); #endif } public void SetTag (string name) { SetTag (name, null); } public void SetTag (string name, string value) { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().SetTag(name, value); #elif UNITY_IPHONE && !UNITY_EDITOR growthPushSetTag(name, value); #endif } public void TrackEvent(string name) { TrackEvent (name, null); } public void TrackEvent (string name, string value) { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().TrackEvent(name, value); #elif UNITY_IPHONE && !UNITY_EDITOR growthPushTrackEvent(name, value); #endif } public void SetDeviceTags () { #if UNITY_ANDROID GrowthPushAndroid.GetInstance().SetDeviceTags(); #elif UNITY_IPHONE && !UNITY_EDITOR growthPushSetDeviceTags(); #endif } }
apache-2.0
C#
98ced92bec2e933eeff9f9e0e65e2e51f70b104d
add new tags
patrickpissurno/samecitysameshit
GGJ2016/Assets/Scripts/Domain/TagType.cs
GGJ2016/Assets/Scripts/Domain/TagType.cs
using UnityEngine; using System.Collections; public class TagType { public const string BusStop = "BusStop"; public const string Limit = "Limit"; public const string Bus = "Bus"; public const string Car = "Car"; public const string Taxi = "Taxi"; public const string Rebu = "Rebu"; public const string Train = "Train"; public const string Garage = "Garage"; }
using UnityEngine; using System.Collections; public class TagType { public const string BusStop = "BusStop"; public const string Limit = "Limit"; }
cc0-1.0
C#
e4e63cea2e7dbc92d2f7410d6c8edcc4e5025107
add ContextFreeTask.Run methods for creating ContextFreeTask
ufcpp/ContextFreeTask
src/ContextFreeTasks.Shared/ContextFreeTask.cs
src/ContextFreeTasks.Shared/ContextFreeTask.cs
using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using ContextFreeTasks.Internal; using static System.Threading.Tasks.Task; namespace ContextFreeTasks { [AsyncMethodBuilder(typeof(AsyncContextFreeTaskMethodBuilder))] public struct ContextFreeTask { private readonly Task _task; public Task Task => _task ?? FromResult(default(object)); internal ContextFreeTask(Task t) => _task = t; public ContextFreeTaskAwaiter GetAwaiter() => new ContextFreeTaskAwaiter(Task); public void Wait() => _task?.Wait(); public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => Task.ConfigureAwait(continueOnCapturedContext); public static ContextFreeTask Run(Action action) => new ContextFreeTask(Task.Run(action)); public static ContextFreeTask Run(Func<ContextFreeTask> function) => new ContextFreeTask(Task.Run(async () => await function().ConfigureAwait(false))); public static ContextFreeTask<T> Run<T>(Func<T> function) => new ContextFreeTask<T>(Task.Run(function)); public static ContextFreeTask<T> Run<T>(Func<ContextFreeTask<T>> function) => new ContextFreeTask<T>(Task.Run(async () => await function().ConfigureAwait(false))); } }
using System.Runtime.CompilerServices; using System.Threading.Tasks; using ContextFreeTasks.Internal; using static System.Threading.Tasks.Task; namespace ContextFreeTasks { [AsyncMethodBuilder(typeof(AsyncContextFreeTaskMethodBuilder))] public struct ContextFreeTask { private readonly Task _task; public Task Task => _task ?? FromResult(default(object)); internal ContextFreeTask(Task t) => _task = t; public ContextFreeTaskAwaiter GetAwaiter() => new ContextFreeTaskAwaiter(Task); public void Wait() => _task?.Wait(); public ConfiguredTaskAwaitable ConfigureAwait(bool continueOnCapturedContext) => Task.ConfigureAwait(continueOnCapturedContext); } }
mit
C#
fcf29a4b139e23d81fa066e878df7d85c31e25e5
Add a single-instance check on application startup
Phrynohyas/eve-o-preview,Phrynohyas/eve-o-preview,Ligraph/eve-o-preview
Eve-O-Preview/Program.cs
Eve-O-Preview/Program.cs
using System; using System.Threading; using System.Windows.Forms; using EveOPreview.Configuration; using EveOPreview.UI; namespace EveOPreview { static class Program { private static string MutexName = "EVE-O Preview Single Instance Mutex"; private static string ConfigParameterName = "--config:"; /// <summary>The main entry point for the application.</summary> [STAThread] static void Main(string[] args) { // The very usual Mutex-based single-instance screening // 'token' variable is used to store reference to the instance Mutex // during the app lifetime object token = Program.GetInstanceToken(); // If it was not possible to aquite the app token then another app instance is already running // Nothing to do here if (token == null) { return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); IIocContainer container = new LightInjectContainer(); // UI classes IApplicationController controller = new ApplicationController(container) .RegisterView<IMainView, MainForm>() .RegisterView<IThumbnailView, ThumbnailView>() .RegisterView<IThumbnailDescriptionView, ThumbnailDescriptionView>() .RegisterInstance(new ApplicationContext()); // Application services controller.RegisterService<IThumbnailManager, ThumbnailManager>() .RegisterService<IThumbnailViewFactory, ThumbnailViewFactory>() .RegisterService<IThumbnailDescriptionViewFactory, ThumbnailDescriptionViewFactory>() .RegisterService<IConfigurationStorage, ConfigurationStorage>() .RegisterInstance<IAppConfig>(new AppConfig()) .RegisterInstance<IThumbnailConfig>(new ThumbnailConfig()); controller.Create<IAppConfig>().ConfigFileName = Program.GetCustomConfigFile(args); controller.Run<MainPresenter>(); token = null; } // Parse startup parameters // Simple approach is used because something like NParams would be an overkill here private static string GetCustomConfigFile(string[] args) { string configFile = null; foreach (string arg in args) { if ((arg.Length <= Program.ConfigParameterName.Length) || !arg.StartsWith(Program.ConfigParameterName, StringComparison.Ordinal)) { continue; } configFile = arg.Substring(Program.ConfigParameterName.Length); break; } if (string.IsNullOrEmpty(configFile)) { return ""; } // One more check to drop trailing " if ((configFile.Length > 3) && (configFile[0] == '"') && (configFile[configFile.Length - 1] == '"')) { configFile = configFile.Substring(1, configFile.Length - 2); } return configFile; } private static object GetInstanceToken() { // The code might look overcomplicated here for a single Mutex operation // Yet we had already experienced a Windows-level issue // where .NET finalizer theread was literally paralyzed by // a failed Mutex operation. That did lead to weird OutOfMemory // exceptions later try { Mutex mutex = Mutex.OpenExisting(Program.MutexName); // if that didn't fail then anotherinstance is already running return null; } catch (UnauthorizedAccessException) { return null; } catch (Exception) { bool result; Mutex token = new Mutex(true, Program.MutexName, out result); return result ? token : null; } } } }
using System; using System.Windows.Forms; using EveOPreview.Configuration; using EveOPreview.UI; namespace EveOPreview { static class Program { private static string ConfigParameterName = "--config:"; /// <summary>The main entry point for the application.</summary> [STAThread] static void Main(string[] args) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // TODO Switch to another container that provides signed assemblies IIocContainer container = new LightInjectContainer(); // UI classes IApplicationController controller = new ApplicationController(container) .RegisterView<IMainView, MainForm>() .RegisterView<IThumbnailView, ThumbnailView>() .RegisterView<IThumbnailDescriptionView, ThumbnailDescriptionView>() .RegisterInstance(new ApplicationContext()); // Application services controller.RegisterService<IThumbnailManager, ThumbnailManager>() .RegisterService<IThumbnailViewFactory, ThumbnailViewFactory>() .RegisterService<IThumbnailDescriptionViewFactory, ThumbnailDescriptionViewFactory>() .RegisterService<IConfigurationStorage, ConfigurationStorage>() .RegisterInstance<IAppConfig>(new AppConfig()) .RegisterInstance<IThumbnailConfig>(new ThumbnailConfig()); controller.Create<IAppConfig>().ConfigFileName = Program.GetCustomConfigFile(args); controller.Run<MainPresenter>(); } // Parse startup parameters // Simple approach is used because something like NParams would be an overkill here private static string GetCustomConfigFile(string[] args) { string configFile = null; foreach (string arg in args) { if ((arg.Length <= Program.ConfigParameterName.Length) || !arg.StartsWith(Program.ConfigParameterName, StringComparison.Ordinal)) { continue; } configFile = arg.Substring(Program.ConfigParameterName.Length); break; } if (string.IsNullOrEmpty(configFile)) { return ""; } // One more check to drop trailing " if ((configFile.Length > 3) && (configFile[0] == '"') && (configFile[configFile.Length - 1] == '"')) { configFile = configFile.Substring(1, configFile.Length - 2); } return configFile; } } }
mit
C#
cd101571a4ecfb5a28e645bef7b458e6e82c7224
enable calibration for image
myxini/block-program
block-program/Execution/BlockProgramExecuter.cs
block-program/Execution/BlockProgramExecuter.cs
using Myxini.Communication; using Myxini.Recognition; using Myxini.Recognition.Image; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myxini.Execution { public class BlockProgramExecuter : IBlockProgramExecuter { private WhiteBoard whiteboard = new WhiteBoard(); /// <summary> /// 通信するやつ /// </summary> private CommunicationService service; /// <summary> /// ホワイトボードを撮るカメラ /// </summary> private ICamera camera; public BlockProgramExecuter(CommunicationService service) { this.service = service; Initialize(); } /// <summary> /// ホワイトボード上に構成されたプログラムを1回読んで実行する /// </summary> public void Execute() { // カメラでホワイトボードをパシャリ IImage image_whiteboard = camera.Capture(); // 写真からScriptを作る Recognizer recognizer = new Recognition.Recognizer(); Script script = recognizer.Recognition( whiteboard.GetBackgroundDeleteImage(image_whiteboard) ); // 通信するやつを使ってScriptを実行 service.Run(script); } /// <summary> /// 実行中のプログラムがあれば停止する /// </summary> public void Stop() { // 通信するやつを使って実行を停止 service.Stop(); } private void Initialize() { camera = new Kinect(); // キャリブレーション whiteboard.Calibration(camera); } } }
using Myxini.Communication; using Myxini.Recognition; using Myxini.Recognition.Image; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Myxini.Execution { public class BlockProgramExecuter : IBlockProgramExecuter { /// <summary> /// 通信するやつ /// </summary> private CommunicationService service; /// <summary> /// ホワイトボードを撮るカメラ /// </summary> private ICamera camera = new Kinect(); public BlockProgramExecuter(CommunicationService service) { this.service = service; } /// <summary> /// ホワイトボード上に構成されたプログラムを1回読んで実行する /// </summary> public void Execute() { // カメラでホワイトボードをパシャリ IImage image_whiteboard = camera.Capture(); // 写真からScriptを作る Recognizer recognizer = new Recognition.Recognizer(); Script script = recognizer.Recognition(image_whiteboard); // 通信するやつを使ってScriptを実行 service.Run(script); } /// <summary> /// 実行中のプログラムがあれば停止する /// </summary> public void Stop() { // 通信するやつを使って実行を停止 service.Stop(); } } }
mit
C#
225ca60f8772c5cad3d6172e793524d24d41a299
Add unknown MissionObjectiveType values
feliwir/openSage,feliwir/openSage
src/OpenSage.Game/Data/Map/MissionObjective.cs
src/OpenSage.Game/Data/Map/MissionObjective.cs
using System.IO; using OpenSage.Data.Utilities.Extensions; namespace OpenSage.Data.Map { [AddedIn(SageGame.Ra3)] public sealed class MissionObjective { public string ID { get; private set; } public string Text { get; private set; } public string Description { get; private set; } public bool IsBonusObjective { get; private set; } public MissionObjectiveType ObjectiveType { get; private set; } internal static MissionObjective Parse(BinaryReader reader) { return new MissionObjective { ID = reader.ReadUInt16PrefixedAsciiString(), Text = reader.ReadUInt16PrefixedAsciiString(), Description = reader.ReadUInt16PrefixedAsciiString(), IsBonusObjective = reader.ReadBooleanChecked(), ObjectiveType = reader.ReadUInt32AsEnum<MissionObjectiveType>() }; } internal void WriteTo(BinaryWriter writer) { writer.WriteUInt16PrefixedAsciiString(ID); writer.WriteUInt16PrefixedAsciiString(Text); writer.WriteUInt16PrefixedAsciiString(Description); writer.Write(IsBonusObjective); writer.Write((uint) ObjectiveType); } } [AddedIn(SageGame.Ra3)] public enum MissionObjectiveType : uint { Attack = 0, Unknown1 = 1, Unknown2 = 2, Build = 3, Capture = 4, Move = 5, Protect = 6 } }
using System.IO; using OpenSage.Data.Utilities.Extensions; namespace OpenSage.Data.Map { [AddedIn(SageGame.Ra3)] public sealed class MissionObjective { public string ID { get; private set; } public string Text { get; private set; } public string Description { get; private set; } public bool IsBonusObjective { get; private set; } public MissionObjectiveType ObjectiveType { get; private set; } internal static MissionObjective Parse(BinaryReader reader) { return new MissionObjective { ID = reader.ReadUInt16PrefixedAsciiString(), Text = reader.ReadUInt16PrefixedAsciiString(), Description = reader.ReadUInt16PrefixedAsciiString(), IsBonusObjective = reader.ReadBooleanChecked(), ObjectiveType = reader.ReadUInt32AsEnum<MissionObjectiveType>() }; } internal void WriteTo(BinaryWriter writer) { writer.WriteUInt16PrefixedAsciiString(ID); writer.WriteUInt16PrefixedAsciiString(Text); writer.WriteUInt16PrefixedAsciiString(Description); writer.Write(IsBonusObjective); writer.Write((uint) ObjectiveType); } } [AddedIn(SageGame.Ra3)] public enum MissionObjectiveType : uint { Attack = 0, Build = 3, Capture = 4, Move = 5, Protect = 6 } }
mit
C#
78d2e9b18a3610c2e016e6de454646d719090163
Rename variable to make more sense
codeforamerica/denver-schedules-api,schlos/denver-schedules-api,schlos/denver-schedules-api,codeforamerica/denver-schedules-api
Schedules.API/Modules/RemindersModule.cs
Schedules.API/Modules/RemindersModule.cs
using Nancy; using Nancy.ModelBinding; using Schedules.API.Models; using Simpler; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Modules { public class RemindersModule : NancyModule { public RemindersModule () { Post["/reminders/sms"] = _ => { var createSMSReminder = CreateAReminder("sms"); return Response.AsJson(createSMSReminder.Out.Reminder, HttpStatusCode.Created); }; Post["/reminders/email"] = _ => { var createEmailReminder = CreateAReminder("email"); return Response.AsJson(createEmailReminder.Out.Reminder, HttpStatusCode.Created); }; } private CreateReminder CreateAReminder(string reminderTypeName) { var createReminder = Task.New<CreateReminder>(); createReminder.In.ReminderTypeName = reminderTypeName; createReminder.In.Reminder = this.Bind<Reminder>(); createReminder.Execute(); return createReminder; } } }
using Nancy; using Nancy.ModelBinding; using Schedules.API.Models; using Simpler; using Schedules.API.Tasks.Reminders; namespace Schedules.API.Modules { public class RemindersModule : NancyModule { public RemindersModule () { Post["/reminders/sms"] = _ => { var createSMSReminder = CreateAReminder("sms"); return Response.AsJson(createSMSReminder.Out.Reminder, HttpStatusCode.Created); }; Post["/reminders/email"] = _ => { var createSMSReminder = CreateAReminder("email"); return Response.AsJson(createSMSReminder.Out.Reminder, HttpStatusCode.Created); }; } private CreateReminder CreateAReminder(string reminderTypeName) { var createReminder = Task.New<CreateReminder>(); createReminder.In.ReminderTypeName = reminderTypeName; createReminder.In.Reminder = this.Bind<Reminder>(); createReminder.Execute(); return createReminder; } } }
mit
C#
f16369d8001b32a901c419f60d757c0583764d3f
Prepare 0.5.0
pleonex/deblocus,pleonex/deblocus
Deblocus/Properties/AssemblyInfo.cs
Deblocus/Properties/AssemblyInfo.cs
// // AssemblyInfo.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. 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("Deblocus")] [assembly: AssemblyDescription("A card manager for students.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Benito Palacios Sánchez")] [assembly: AssemblyProduct("Deblocus")] [assembly: AssemblyCopyright("Copyright (c) 2015 Benito Palacios Sánchez")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.5.0.*")]
// // AssemblyInfo.cs // // Author: // Benito Palacios Sánchez (aka pleonex) <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez (c) 2015 // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. 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("Deblocus")] [assembly: AssemblyDescription("A card manager for students.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Benito Palacios Sánchez")] [assembly: AssemblyProduct("Deblocus")] [assembly: AssemblyCopyright("Copyright (c) 2015 Benito Palacios Sánchez")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("0.4.0.*")]
agpl-3.0
C#
46e321bd18d0038d41414874974380a25bd68784
fix ref
Fody/MethodTimer
Tests/AssemblyTestersests/IgnoreCodes.cs
Tests/AssemblyTestersests/IgnoreCodes.cs
using System.Collections.Generic; public static class IgnoreCodes { public static IEnumerable<string> GetIgnoreCoders() { #if NET461 return System.Linq.Enumerable.Empty<string>(); #endif #if NETCOREAPP2_0 return new[] { "0x80131869" }; #endif } }
using System.Collections.Generic; public static class IgnoreCodes { public static IEnumerable<string> GetIgnoreCoders() { #if NET461 return Enumerable.Empty<string>(); #endif #if NETCOREAPP2_0 return new[] { "0x80131869" }; #endif } }
mit
C#
db2840fe28500c2ab1969d89dfd16fe9b4367e38
Remove InternalsVisibleTo because it causes tight coupling and type confliction.
scopely/msgpack-cli,modulexcite/msgpack-cli,msgpack/msgpack-cli,undeadlabs/msgpack-cli,scopely/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,modulexcite/msgpack-cli
cli/src/MsgPack.Mono/Properties/AssemblyInfo.cs
cli/src/MsgPack.Mono/Properties/AssemblyInfo.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System.Reflection; using System.Runtime.CompilerServices; using System.Security; [assembly: AssemblyTitle( "MessagePack for CLI Mono binding" )] [assembly: AssemblyDescription( "MessagePack for CLI Mono binding packing/unpacking library." )] [assembly: AssemblyConfiguration( "Beta" )] [assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2012" )] // TODO: use script. Major = Informational-Major, Minor = Informational-Minor, Build = Epoc days from 2010/1/1, Revision = Epoc minutes from 00:00:00 [assembly: AssemblyFileVersion( "0.2.0.0" )] [assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )] [assembly: AllowPartiallyTrustedCallers] #if DEBUG || PERFORMANCE_TEST [assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] #endif
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System.Reflection; using System.Runtime.CompilerServices; using System.Security; [assembly: AssemblyTitle( "MessagePack for CLI Mono binding" )] [assembly: AssemblyDescription( "MessagePack for CLI Mono binding packing/unpacking library." )] [assembly: AssemblyConfiguration( "Beta" )] [assembly: AssemblyCopyright( "Copyright © FUJIWARA, Yusuke 2012" )] // TODO: use script. Major = Informational-Major, Minor = Informational-Minor, Build = Epoc days from 2010/1/1, Revision = Epoc minutes from 00:00:00 [assembly: AssemblyFileVersion( "0.2.0.0" )] [assembly: SecurityRules( SecurityRuleSet.Level2, SkipVerificationInFullTrust = true )] [assembly: AllowPartiallyTrustedCallers] // For internal utilities related to emittions. [assembly: InternalsVisibleTo( "MsgPack.Rpc.Server, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] #if DEBUG || PERFORMANCE_TEST [assembly: InternalsVisibleTo( "MsgPack.UnitTest, PublicKey=0024000004800000940000000602000000240000525341310004000001000100a967de8de9d45380b93a6aa56f64fc2cb2d3c9d4b400e00de01f31ba9e15cf5ca95926dbf8760cce413eabd711e23df0c133193a570da8a3bb1bdc00ef170fccb2bc033266fa5346442c9cf0b071133d5b484845eab17095652aeafeeb71193506b8294d9c8c91e3fd01cc50bdbc2d0eb78dd655bb8cd0bd3cdbbcb192549cb4" )] #endif
apache-2.0
C#
4d16812f874be3da362700adb28c7674e85becc9
test fixed from removing dependency.
BrettStory/Macabre2D
UI/Tests/Services/ProjectServiceTests.cs
UI/Tests/Services/ProjectServiceTests.cs
namespace Macabre2D.UI.Tests.Services { using Macabre2D.UI.Models; using Macabre2D.UI.ServiceInterfaces; using Macabre2D.UI.Services; using NSubstitute; using NUnit.Framework; using System; using System.IO; using System.Threading.Tasks; [TestFixture] public static class ProjectServiceTests { [Test] [Category("Integration Test")] public static async Task ProjectService_CreateProjectTest() { var fileService = Substitute.For<IFileService>(); var loggingService = Substitute.For<ILoggingService>(); var sceneService = Substitute.For<ISceneService>(); var projectService = new ProjectService(fileService, loggingService, sceneService); var projectDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestProject"); fileService.ProjectDirectoryPath.Returns(projectDirectory); if (Directory.Exists(projectDirectory)) { Directory.Delete(projectDirectory, true); } var sceneAsset = new SceneAsset(Path.Combine(projectDirectory, Guid.NewGuid().ToString())); sceneService.CreateScene(Arg.Any<FolderAsset>(), Arg.Any<string>()).Returns(sceneAsset); sceneService.LoadScene(Arg.Any<Project>(), Arg.Any<SceneAsset>()).Returns(sceneAsset); try { Directory.CreateDirectory(projectDirectory); var project = await projectService.CreateProject(); Assert.NotNull(project); Assert.NotNull(projectService.CurrentProject); Assert.AreEqual(project, projectService.CurrentProject); Assert.True(File.Exists(projectService.GetPathToProject())); } finally { if (Directory.Exists(projectDirectory)) { Directory.Delete(projectDirectory, true); } } } } }
namespace Macabre2D.UI.Tests.Services { using Macabre2D.UI.Models; using Macabre2D.UI.ServiceInterfaces; using Macabre2D.UI.Services; using NSubstitute; using NUnit.Framework; using System; using System.IO; using System.Threading.Tasks; [TestFixture] public static class ProjectServiceTests { [Test] [Category("Integration Test")] public static async Task ProjectService_CreateProjectTest() { var dialogService = Substitute.For<IDialogService>(); var fileService = Substitute.For<IFileService>(); var loggingService = Substitute.For<ILoggingService>(); var sceneService = Substitute.For<ISceneService>(); var projectService = new ProjectService(dialogService, fileService, loggingService, sceneService); var projectDirectory = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestProject"); fileService.ProjectDirectoryPath.Returns(projectDirectory); if (Directory.Exists(projectDirectory)) { Directory.Delete(projectDirectory, true); } var sceneAsset = new SceneAsset(Path.Combine(projectDirectory, Guid.NewGuid().ToString())); sceneService.CreateScene(Arg.Any<FolderAsset>(), Arg.Any<string>()).Returns(sceneAsset); sceneService.LoadScene(Arg.Any<Project>(), Arg.Any<SceneAsset>()).Returns(sceneAsset); try { Directory.CreateDirectory(projectDirectory); var project = await projectService.CreateProject(); Assert.NotNull(project); Assert.NotNull(projectService.CurrentProject); Assert.AreEqual(project, projectService.CurrentProject); Assert.True(File.Exists(projectService.GetPathToProject())); } finally { if (Directory.Exists(projectDirectory)) { Directory.Delete(projectDirectory, true); } } } } }
mit
C#
6bc507d49ed2bc76cbbaffc5dc9ddac087a5bd8f
Increase coordinate parsing limits
peppy/osu,ppy/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,smoogipooo/osu
osu.Game/Beatmaps/Formats/Parsing.cs
osu.Game/Beatmaps/Formats/Parsing.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Globalization; namespace osu.Game.Beatmaps.Formats { /// <summary> /// Helper methods to parse from string to number and perform very basic validation. /// </summary> public static class Parsing { public const int MAX_COORDINATE_VALUE = 131072; public const double MAX_PARSE_VALUE = int.MaxValue; public static float ParseFloat(string input, float parseLimit = (float)MAX_PARSE_VALUE) { var output = float.Parse(input, CultureInfo.InvariantCulture); if (output < -parseLimit) throw new OverflowException("Value is too low"); if (output > parseLimit) throw new OverflowException("Value is too high"); if (float.IsNaN(output)) throw new FormatException("Not a number"); return output; } public static double ParseDouble(string input, double parseLimit = MAX_PARSE_VALUE) { var output = double.Parse(input, CultureInfo.InvariantCulture); if (output < -parseLimit) throw new OverflowException("Value is too low"); if (output > parseLimit) throw new OverflowException("Value is too high"); if (double.IsNaN(output)) throw new FormatException("Not a number"); return output; } public static int ParseInt(string input, int parseLimit = (int)MAX_PARSE_VALUE) { var output = int.Parse(input, CultureInfo.InvariantCulture); if (output < -parseLimit) throw new OverflowException("Value is too low"); if (output > parseLimit) throw new OverflowException("Value is too high"); return output; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Globalization; namespace osu.Game.Beatmaps.Formats { /// <summary> /// Helper methods to parse from string to number and perform very basic validation. /// </summary> public static class Parsing { public const int MAX_COORDINATE_VALUE = 65536; public const double MAX_PARSE_VALUE = int.MaxValue; public static float ParseFloat(string input, float parseLimit = (float)MAX_PARSE_VALUE) { var output = float.Parse(input, CultureInfo.InvariantCulture); if (output < -parseLimit) throw new OverflowException("Value is too low"); if (output > parseLimit) throw new OverflowException("Value is too high"); if (float.IsNaN(output)) throw new FormatException("Not a number"); return output; } public static double ParseDouble(string input, double parseLimit = MAX_PARSE_VALUE) { var output = double.Parse(input, CultureInfo.InvariantCulture); if (output < -parseLimit) throw new OverflowException("Value is too low"); if (output > parseLimit) throw new OverflowException("Value is too high"); if (double.IsNaN(output)) throw new FormatException("Not a number"); return output; } public static int ParseInt(string input, int parseLimit = (int)MAX_PARSE_VALUE) { var output = int.Parse(input, CultureInfo.InvariantCulture); if (output < -parseLimit) throw new OverflowException("Value is too low"); if (output > parseLimit) throw new OverflowException("Value is too high"); return output; } } }
mit
C#
75d8a4c28522492767ba59a6bdbd10e1d941d6cc
Bump version to 12.2.0.26757
HearthSim/HearthDb
HearthDb/Properties/AssemblyInfo.cs
HearthDb/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("HearthDb")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HearthSim")] [assembly: AssemblyProduct("HearthDb")] [assembly: AssemblyCopyright("Copyright © HearthSim 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")] // 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("12.2.0.26757")] [assembly: AssemblyFileVersion("12.2.0.26757")]
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("HearthDb")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("HearthSim")] [assembly: AssemblyProduct("HearthDb")] [assembly: AssemblyCopyright("Copyright © HearthSim 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7ed14243-e02b-4b94-af00-a67a62c282f0")] // 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("12.0.0.25770")] [assembly: AssemblyFileVersion("12.0.0.25770")]
mit
C#
6aff137a8a165fc9f5443414c3ab6ee011d29d5d
Make example DownloadHandler public
haozhouxu/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,haozhouxu/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,Livit/CefSharp,joshvera/CefSharp,Haraguroicha/CefSharp,twxstar/CefSharp,rlmcneary2/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,VioletLife/CefSharp,windygu/CefSharp,twxstar/CefSharp,windygu/CefSharp,AJDev77/CefSharp,AJDev77/CefSharp,battewr/CefSharp,VioletLife/CefSharp,yoder/CefSharp,ruisebastiao/CefSharp,joshvera/CefSharp,battewr/CefSharp,zhangjingpu/CefSharp,gregmartinhtc/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,Livit/CefSharp,joshvera/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,Haraguroicha/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,battewr/CefSharp,AJDev77/CefSharp,rover886/CefSharp,gregmartinhtc/CefSharp,windygu/CefSharp,ITGlobal/CefSharp,Octopus-ITSM/CefSharp,zhangjingpu/CefSharp,windygu/CefSharp,ruisebastiao/CefSharp,rover886/CefSharp,twxstar/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,wangzheng888520/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,NumbersInternational/CefSharp,rlmcneary2/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,yoder/CefSharp,NumbersInternational/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,ITGlobal/CefSharp,wangzheng888520/CefSharp,rover886/CefSharp,NumbersInternational/CefSharp,wangzheng888520/CefSharp,Octopus-ITSM/CefSharp,rover886/CefSharp,rlmcneary2/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,zhangjingpu/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,illfang/CefSharp,illfang/CefSharp,haozhouxu/CefSharp
CefSharp.Example/DownloadHandler.cs
CefSharp.Example/DownloadHandler.cs
namespace CefSharp.Example { public class DownloadHandler : IDownloadHandler { public bool OnBeforeDownload(DownloadItem downloadItem, out string downloadPath, out bool showDialog) { downloadPath = downloadItem.SuggestedFileName; showDialog = true; return true; } public bool OnDownloadUpdated(DownloadItem downloadItem) { return false; } } }
namespace CefSharp.Example { internal class DownloadHandler : IDownloadHandler { public bool OnBeforeDownload(DownloadItem downloadItem, out string downloadPath, out bool showDialog) { downloadPath = downloadItem.SuggestedFileName; showDialog = true; return true; } public bool OnDownloadUpdated(DownloadItem downloadItem) { return false; } } }
bsd-3-clause
C#
3e0cf9188fc6993fed4eb6bb3622b5a00f0b3e89
Add DebuggerDisplay attribute for Token class
igitur/ClosedXML,ClosedXML/ClosedXML
ClosedXML/Excel/CalcEngine/Token.cs
ClosedXML/Excel/CalcEngine/Token.cs
using System.Diagnostics; namespace ClosedXML.Excel.CalcEngine { /// <summary> /// Represents a node in the expression tree. /// </summary> [DebuggerDisplay("{Value} ({ID} {Type})")] internal class Token { // ** fields public TKID ID; public TKTYPE Type; public object Value; // ** ctor public Token(object value, TKID id, TKTYPE type) { Value = value; ID = id; Type = type; } } /// <summary> /// Token types (used when building expressions, sequence defines operator priority) /// </summary> internal enum TKTYPE { COMPARE, // < > = <= >= ADDSUB, // + - MULDIV, // * / POWER, // ^ MULDIV_UNARY,// % GROUP, // ( ) , . LITERAL, // 123.32, "Hello", etc. IDENTIFIER, // functions, external objects, bindings ERROR // e.g. #REF! } /// <summary> /// Token ID (used when evaluating expressions) /// </summary> internal enum TKID { GT, LT, GE, LE, EQ, NE, // COMPARE ADD, SUB, // ADDSUB MUL, DIV, DIVINT, MOD, // MULDIV POWER, // POWER DIV100, // MULTIV_UNARY OPEN, CLOSE, END, COMMA, PERIOD, // GROUP ATOM, // LITERAL, IDENTIFIER CONCAT } }
namespace ClosedXML.Excel.CalcEngine { /// <summary> /// Represents a node in the expression tree. /// </summary> internal class Token { // ** fields public TKID ID; public TKTYPE Type; public object Value; // ** ctor public Token(object value, TKID id, TKTYPE type) { Value = value; ID = id; Type = type; } } /// <summary> /// Token types (used when building expressions, sequence defines operator priority) /// </summary> internal enum TKTYPE { COMPARE, // < > = <= >= ADDSUB, // + - MULDIV, // * / POWER, // ^ MULDIV_UNARY,// % GROUP, // ( ) , . LITERAL, // 123.32, "Hello", etc. IDENTIFIER, // functions, external objects, bindings ERROR // e.g. #REF! } /// <summary> /// Token ID (used when evaluating expressions) /// </summary> internal enum TKID { GT, LT, GE, LE, EQ, NE, // COMPARE ADD, SUB, // ADDSUB MUL, DIV, DIVINT, MOD, // MULDIV POWER, // POWER DIV100, // MULTIV_UNARY OPEN, CLOSE, END, COMMA, PERIOD, // GROUP ATOM, // LITERAL, IDENTIFIER CONCAT } }
mit
C#
7acb0ae402273e349718827c782f87ba4ab53344
Add data copier test
TheAngryByrd/DataflowEx,gridsum/DataflowEx
Gridsum.DataflowEx.Test/TestDataCopier.cs
Gridsum.DataflowEx.Test/TestDataCopier.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Gridsum.DataflowEx.Test { [TestClass] public class TestDataCopier { [TestMethod] public async Task TestDataCopier1() { var random = new Random(); var dataCopier = new DataCopier<int>(); int sum1 = 0; int sum2 = 0; var action1 = new ActionBlock<int>(i => sum1 = sum1 + i); var action2 = new ActionBlock<int>(i => sum2 = sum2 + i); dataCopier.OutputBlock.LinkTo(action1, new DataflowLinkOptions() {PropagateCompletion = true}); dataCopier.CopiedOutputBlock.LinkTo(action2, new DataflowLinkOptions() {PropagateCompletion = true}); for (int j = 0; j < 1000; j++) { dataCopier.InputBlock.Post((int) (random.NextDouble()*10000)); } dataCopier.InputBlock.Complete(); await Task.WhenAll(action1.Completion, action2.Completion); Console.WriteLine("sum1 = {0} , sum2 = {1}", sum1, sum2); Assert.AreEqual(sum1, sum2); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Gridsum.DataflowEx.Test { [TestClass] public class TestDataCopier { [TestMethod] public void TestDataCopier1() { } } }
mit
C#
c0009360bc9f59cbcc155cab694579581614eed6
Mark TreeEntryTargetType.Tag as obsolete
dlsteuer/libgit2sharp,AArnott/libgit2sharp,xoofx/libgit2sharp,OidaTiftla/libgit2sharp,GeertvanHorrik/libgit2sharp,sushihangover/libgit2sharp,Zoxive/libgit2sharp,AArnott/libgit2sharp,vorou/libgit2sharp,rcorre/libgit2sharp,rcorre/libgit2sharp,Zoxive/libgit2sharp,oliver-feng/libgit2sharp,OidaTiftla/libgit2sharp,AMSadek/libgit2sharp,xoofx/libgit2sharp,whoisj/libgit2sharp,Skybladev2/libgit2sharp,shana/libgit2sharp,github/libgit2sharp,whoisj/libgit2sharp,red-gate/libgit2sharp,ethomson/libgit2sharp,dlsteuer/libgit2sharp,jorgeamado/libgit2sharp,ethomson/libgit2sharp,mono/libgit2sharp,jeffhostetler/public_libgit2sharp,libgit2/libgit2sharp,nulltoken/libgit2sharp,shana/libgit2sharp,oliver-feng/libgit2sharp,vorou/libgit2sharp,github/libgit2sharp,psawey/libgit2sharp,GeertvanHorrik/libgit2sharp,vivekpradhanC/libgit2sharp,jamill/libgit2sharp,psawey/libgit2sharp,jeffhostetler/public_libgit2sharp,red-gate/libgit2sharp,jorgeamado/libgit2sharp,Skybladev2/libgit2sharp,nulltoken/libgit2sharp,mono/libgit2sharp,sushihangover/libgit2sharp,vivekpradhanC/libgit2sharp,jamill/libgit2sharp,AMSadek/libgit2sharp,PKRoma/libgit2sharp
LibGit2Sharp/TreeEntryTargetType.cs
LibGit2Sharp/TreeEntryTargetType.cs
using System; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Underlying type of the target a <see cref = "TreeEntry" /> /// </summary> public enum TreeEntryTargetType { /// <summary> /// A file revision object. /// </summary> Blob = 1, /// <summary> /// A tree object. /// </summary> Tree, /// <summary> /// An annotated tag object. /// </summary> [Obsolete("This entry will be removed in the next release as it is not a valid TreeEntryTargetType.")] Tag, /// <summary> /// A pointer to a commit object in another repository. /// </summary> GitLink, } internal static class TreeEntryTargetTypeExtensions { public static GitObjectType ToGitObjectType(this TreeEntryTargetType type) { switch (type) { case TreeEntryTargetType.Tree: return GitObjectType.Tree; case TreeEntryTargetType.Blob: return GitObjectType.Blob; default: throw new InvalidOperationException(string.Format("Cannot map {0} to a GitObjectType.", type)); } } } }
using System; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Underlying type of the target a <see cref = "TreeEntry" /> /// </summary> public enum TreeEntryTargetType { /// <summary> /// A file revision object. /// </summary> Blob = 1, /// <summary> /// A tree object. /// </summary> Tree, /// <summary> /// An annotated tag object. /// </summary> Tag, /// <summary> /// A pointer to a commit object in another repository. /// </summary> GitLink, } internal static class TreeEntryTargetTypeExtensions { public static GitObjectType ToGitObjectType(this TreeEntryTargetType type) { switch (type) { case TreeEntryTargetType.Tree: return GitObjectType.Tree; case TreeEntryTargetType.Blob: return GitObjectType.Blob; default: throw new InvalidOperationException(string.Format("Cannot map {0} to a GitObjectType.", type)); } } } }
mit
C#
6f9c6a5ec5755d79eeba67635e5d4894a295d26c
update error message
pacal/NPoco_Identity_Provider
NPoco_Idenity_Provider/RoleStore.cs
NPoco_Idenity_Provider/RoleStore.cs
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Identity; namespace Pacal.NPoco_Idenity_Provider { public class RoleStore<TRole>: IQueryableRoleStore<TRole> where TRole : IdentityRole { private RoleTable roleTable; public DataProvider Database { get; set; } public RoleStore(DataProvider database) { roleTable = new RoleTable(database); Database = database; } public Task CreateAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Insert(role); return Task.FromResult<object>(null); } public Task UpdateAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Update(role); return Task.FromResult<Object>(null); } public Task DeleteAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Delete(role); return Task.FromResult<Object>(null); } public Task<TRole> FindByIdAsync(string roleId) { TRole result = roleTable.GetRoleById(roleId) as TRole; return Task.FromResult<TRole>(result); } public Task<TRole> FindByNameAsync(string roleName) { TRole result = roleTable.GetRoleByName(roleName) as TRole; return Task.FromResult<TRole>(result); } public IQueryable<TRole> Roles { get; } public void Dispose() { if (Database != null) { Database.Dispose(); Database = null; } } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Identity; namespace Pacal.NPoco_Idenity_Provider { public class RoleStore<TRole>: IQueryableRoleStore<TRole> where TRole : IdentityRole { private RoleTable roleTable; public DataProvider Database { get; set; } public RoleStore(DataProvider database) { roleTable = new RoleTable(database); Database = database; } public Task CreateAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Insert(role); return Task.FromResult<object>(null); } public Task UpdateAsync(TRole role) { if (role == null) { throw new ArgumentNullException("user"); } roleTable.Update(role); return Task.FromResult<Object>(null); } public Task DeleteAsync(TRole role) { if (role == null) { throw new ArgumentNullException("role"); } roleTable.Delete(role); return Task.FromResult<Object>(null); } public Task<TRole> FindByIdAsync(string roleId) { TRole result = roleTable.GetRoleById(roleId) as TRole; return Task.FromResult<TRole>(result); } public Task<TRole> FindByNameAsync(string roleName) { TRole result = roleTable.GetRoleByName(roleName) as TRole; return Task.FromResult<TRole>(result); } public IQueryable<TRole> Roles { get; } public void Dispose() { if (Database != null) { Database.Dispose(); Database = null; } } } }
mit
C#
606378cb41ee89ee2201692411b91ff81be6d473
Remove redundant Type on Button
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
Ooui/Button.cs
Ooui/Button.cs
using System; namespace Ooui { public class Button : FormControl { string val = ""; public string Value { get => val; set => SetProperty (ref val, value, "value"); } public event EventHandler Clicked { add => AddEventListener ("click", value); remove => RemoveEventListener ("click", value); } public Button () : base ("button") { } public Button (string text) : this () { Text = text; } } }
using System; namespace Ooui { public class Button : FormControl { string typ = "submit"; public string Type { get => typ; set => SetProperty (ref typ, value, "type"); } string val = ""; public string Value { get => val; set => SetProperty (ref val, value, "value"); } public event EventHandler Clicked { add => AddEventListener ("click", value); remove => RemoveEventListener ("click", value); } public Button () : base ("button") { } public Button (string text) : this () { Text = text; } } }
mit
C#
b578d005aebad97f77087b68bbf48446c66edd7f
Make shop more robust
Particular/SagaMasterClass
Shop/Program.cs
Shop/Program.cs
namespace Shop { using System; using NServiceBus; using NServiceBus.Logging; class Program { static void Main() { LogManager.Use<DefaultFactory>().Level(LogLevel.Error); var busConfiguration = new BusConfiguration(); using (var bus = Bus.CreateSendOnly(busConfiguration)) { var commandContext = new CommandContext(bus); Console.Out.WriteLine("Welcome to the Acme, please start a new order using `StartOrder`. Type `exit` to exit"); RunCommandLoop(commandContext); } } static void RunCommandLoop(CommandContext context) { Command command; do { GeneratePrompt(context); var requestedCommand = Console.ReadLine(); command = Command.Parse(requestedCommand); context.SetParameters(requestedCommand); try { command.Execute(context); } catch (Exception) { Console.WriteLine("Unable to understand input"); } } while (!(command is ExitCommand)); } static void GeneratePrompt(CommandContext context) { ShoppingCart cart; string promptContext = null; if (context.TryGet(out cart)) { promptContext = cart.OrderId.Substring(0, 6); } if (!string.IsNullOrEmpty(promptContext)) { promptContext = $" [{promptContext}]"; } Console.Out.Write($"Shop{promptContext}>"); } } }
namespace Shop { using System; using NServiceBus; using NServiceBus.Logging; class Program { static void Main() { LogManager.Use<DefaultFactory>().Level(LogLevel.Error); var busConfiguration = new BusConfiguration(); using (var bus = Bus.CreateSendOnly(busConfiguration)) { var commandContext = new CommandContext(bus); Console.Out.WriteLine("Welcome to the Acme, please start a new order using `StartOrder`. Type `exit` to exit"); RunCommandLoop(commandContext); } } static void RunCommandLoop(CommandContext context) { Command command; do { GeneratePrompt(context); var requestedCommand = Console.ReadLine(); command = Command.Parse(requestedCommand); context.SetParameters(requestedCommand); command.Execute(context); } while (!(command is ExitCommand)); } static void GeneratePrompt(CommandContext context) { ShoppingCart cart; string promptContext = null; if (context.TryGet(out cart)) { promptContext = cart.OrderId.Substring(0, 6); } if (!string.IsNullOrEmpty(promptContext)) { promptContext = $" [{promptContext}]"; } Console.Out.Write($"Shop{promptContext}>"); } } }
mit
C#
8d786ef8a9735f5c2f376d97ed0c60c8f92d89d4
undo version change.
bdukes/Dnn.Platform,RichardHowells/Dnn.Platform,robsiera/Dnn.Platform,RichardHowells/Dnn.Platform,valadas/Dnn.Platform,janjonas/Dnn.Platform,EPTamminga/Dnn.Platform,svdv71/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,SCullman/Dnn.Platform,wael101/Dnn.Platform,janjonas/Dnn.Platform,mitchelsellers/Dnn.Platform,RichardHowells/Dnn.Platform,bdukes/Dnn.Platform,RichardHowells/Dnn.Platform,mitchelsellers/Dnn.Platform,janjonas/Dnn.Platform,mitchelsellers/Dnn.Platform,robsiera/Dnn.Platform,dnnsoftware/Dnn.Platform,valadas/Dnn.Platform,EPTamminga/Dnn.Platform,SCullman/Dnn.Platform,dnnsoftware/Dnn.Platform,dnnsoftware/Dnn.Platform,wael101/Dnn.Platform,SCullman/Dnn.Platform,valadas/Dnn.Platform,nvisionative/Dnn.Platform,dnnsoftware/Dnn.Platform,nvisionative/Dnn.Platform,bdukes/Dnn.Platform,dnnsoftware/Dnn.Platform,mitchelsellers/Dnn.Platform,bdukes/Dnn.Platform,svdv71/Dnn.Platform,wael101/Dnn.Platform,mitchelsellers/Dnn.Platform,EPTamminga/Dnn.Platform,robsiera/Dnn.Platform,valadas/Dnn.Platform,svdv71/Dnn.Platform
SolutionInfo.cs
SolutionInfo.cs
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2017 // by DotNetNuke Corporation // // 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. #endregion #region Usings using System.Reflection; #endregion // 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. // Review the values of the assembly attributes [assembly: AssemblyCompany("DNN Corporation")] [assembly: AssemblyProduct("http://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2017 by DNN Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DNN")] // 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("9.1.0.0")] [assembly: AssemblyFileVersion("9.1.0.0")]
#region Copyright // // DotNetNuke® - http://www.dotnetnuke.com // Copyright (c) 2002-2017 // by DotNetNuke Corporation // // 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. #endregion #region Usings using System.Reflection; #endregion // 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. // Review the values of the assembly attributes [assembly: AssemblyCompany("DNN Corporation")] [assembly: AssemblyProduct("http://www.dnnsoftware.com")] [assembly: AssemblyCopyright("DotNetNuke is copyright 2002-2017 by DNN Corporation. All Rights Reserved.")] [assembly: AssemblyTrademark("DNN")] // 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("9.1.0.75")] [assembly: AssemblyFileVersion("9.1.0.75")]
mit
C#
07b22caf93f98e7e6ee03554923eb2aab083fb51
bump ver
AntonyCorbett/OnlyT,AntonyCorbett/OnlyT
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2019 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.2.0.1")]
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2019 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.1.0.68")]
mit
C#
9532e8e7b7e5deca6e7b2866ff0803101eb5885c
bump ver
AntonyCorbett/OnlyT,AntonyCorbett/OnlyT
SolutionInfo.cs
SolutionInfo.cs
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2019, 2020 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.2.0.29")]
using System.Reflection; [assembly: AssemblyCompany("SoundBox")] [assembly: AssemblyProduct("OnlyT")] [assembly: AssemblyCopyright("Copyright © 2019, 2020 Antony Corbett")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("1.2.0.28")]
mit
C#
632bff021237121214f12005120e88f5365d319b
Bump the version to v5.0.2
RachelTucker/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,shabtaisharon/ds3_net_sdk,SpectraLogic/ds3_net_sdk,shabtaisharon/ds3_net_sdk,RachelTucker/ds3_net_sdk,SpectraLogic/ds3_net_sdk
VersionInfo.cs
VersionInfo.cs
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.0.2.0")] [assembly: AssemblyFileVersion("5.0.2.0")]
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ using System.Reflection; // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("5.0.1.0")] [assembly: AssemblyFileVersion("5.0.1.0")]
apache-2.0
C#
d89cad2509204ac1cceece359bf7ba77b9b23439
Fix lobby player duplication on WarpAck
HelloKitty/Booma.Proxy
src/Booma.Proxy.Client.Unity.Ship/Handlers/Command/Warping/BlockOtherClientAlertedExistenceEventhandler.cs
src/Booma.Proxy.Client.Unity.Ship/Handlers/Command/Warping/BlockOtherClientAlertedExistenceEventhandler.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; using SceneJect.Common; using UnityEngine; namespace Booma.Proxy { [AdditionalRegisterationAs(typeof(IRemoteClientAcknowledgedWarpEventSubscribable))] [SceneTypeCreate(GameSceneType.LobbyDefault)] public sealed class BlockOtherClientAlertedExistenceEventHandler : Command60Handler<Sub60FinishedWarpAckCommand>, IRemoteClientAcknowledgedWarpEventSubscribable //we don't need context { private IUnitScalerStrategy UnitScaler { get; } private IEntityGuidMappable<WorldTransform> WorldTransformMappable { get; } private IEntityGuidMappable<PlayerZoneData> ZoneDataMappable { get; } /// <inheritdoc /> public event EventHandler<RemotePlayerWarpAcknowledgementEventArgs> OnRemotePlayerAcknowledgedWarp; /// <inheritdoc /> public BlockOtherClientAlertedExistenceEventHandler([NotNull] IUnitScalerStrategy unitScaler, [NotNull] ILog logger, [NotNull] IEntityGuidMappable<WorldTransform> worldTransformMappable, [NotNull] IEntityGuidMappable<PlayerZoneData> zoneDataMappable) : base(logger) { UnitScaler = unitScaler ?? throw new ArgumentNullException(nameof(unitScaler)); WorldTransformMappable = worldTransformMappable ?? throw new ArgumentNullException(nameof(worldTransformMappable)); ZoneDataMappable = zoneDataMappable ?? throw new ArgumentNullException(nameof(zoneDataMappable)); } /// <inheritdoc /> protected override Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, Sub60FinishedWarpAckCommand command) { int entityGuid = EntityGuid.ComputeEntityGuid(EntityType.Player, command.Identifier); if(Logger.IsInfoEnabled) Logger.Info($"Client broadcasted existence Id: {command.Identifier} ZoneId: {command.ZoneId}"); //The reason we have to do this is because remote players, that we already known about, //could be broadcasting out a warp ack to alert other players that they exist //but not intend for it to reach us really. In this case, we already have the player existing //so if we don't do it this way then we will end up with duplicate spawns if(WorldTransformMappable.ContainsKey(entityGuid) && ZoneDataMappable.ContainsKey(entityGuid)) { //TODO: Should we ever assume they will ack a new zone??? Probably never legit in the lobby but might happen in games? Unsure. InitializeAckDataToEntityMappables(command, entityGuid); } else { HandleUnknownEntityWarpAck(command, entityGuid); } return Task.CompletedTask; } private void HandleUnknownEntityWarpAck(Sub60FinishedWarpAckCommand command, int entityGuid) { InitializeAckDataToEntityMappables(command, entityGuid); //At this point, it should be able to spawn the player so we should let any listeners know about //the ack OnRemotePlayerAcknowledgedWarp?.Invoke(this, new RemotePlayerWarpAcknowledgementEventArgs(entityGuid)); } private void InitializeAckDataToEntityMappables(Sub60FinishedWarpAckCommand command, int entityGuid) { //We have to do basically what the 3 packet process does for newly joining clients //We need to create the world transform so that it will be known where to spawn. float rotation = UnitScaler.ScaleYRotation(command.YAxisRotation); Vector3 position = UnitScaler.Scale(command.Position); WorldTransformMappable[entityGuid] = new WorldTransform(position, Quaternion.Euler(0.0f, rotation, 0.0f)); //Then we have to actually create/set the zone data so that //it's known which zone the player is in ZoneDataMappable[entityGuid] = new PlayerZoneData(command.ZoneId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logging; using GladNet; using SceneJect.Common; using UnityEngine; namespace Booma.Proxy { [AdditionalRegisterationAs(typeof(IRemoteClientAcknowledgedWarpEventSubscribable))] [SceneTypeCreate(GameSceneType.LobbyDefault)] public sealed class BlockOtherClientAlertedExistenceEventHandler : Command60Handler<Sub60FinishedWarpAckCommand>, IRemoteClientAcknowledgedWarpEventSubscribable //we don't need context { private IUnitScalerStrategy UnitScaler { get; } private IEntityGuidMappable<WorldTransform> WorldTransformMappable { get; } private IEntityGuidMappable<PlayerZoneData> ZoneDataMappable { get; } /// <inheritdoc /> public event EventHandler<RemotePlayerWarpAcknowledgementEventArgs> OnRemotePlayerAcknowledgedWarp; /// <inheritdoc /> public BlockOtherClientAlertedExistenceEventHandler([NotNull] IUnitScalerStrategy unitScaler, [NotNull] ILog logger, [NotNull] IEntityGuidMappable<WorldTransform> worldTransformMappable, [NotNull] IEntityGuidMappable<PlayerZoneData> zoneDataMappable) : base(logger) { UnitScaler = unitScaler ?? throw new ArgumentNullException(nameof(unitScaler)); WorldTransformMappable = worldTransformMappable ?? throw new ArgumentNullException(nameof(worldTransformMappable)); ZoneDataMappable = zoneDataMappable ?? throw new ArgumentNullException(nameof(zoneDataMappable)); } /// <inheritdoc /> protected override Task HandleSubMessage(IPeerMessageContext<PSOBBGamePacketPayloadClient> context, Sub60FinishedWarpAckCommand command) { int entityGuid = EntityGuid.ComputeEntityGuid(EntityType.Player, command.Identifier); if(Logger.IsInfoEnabled) Logger.Info($"Client broadcasted existence Id: {command.Identifier} ZoneId: {command.ZoneId}"); //We have to do basically what the 3 packet process does for newly joining clients //We need to create the world transform so that it will be known where to spawn. float rotation = UnitScaler.ScaleYRotation(command.YAxisRotation); Vector3 position = UnitScaler.Scale(command.Position); WorldTransformMappable[entityGuid] = new WorldTransform(position, Quaternion.Euler(0.0f, rotation, 0.0f)); //Then we have to actually create/set the zone data so that //it's known which zone the player is in ZoneDataMappable[entityGuid] = new PlayerZoneData(command.ZoneId); //At this point, it should be able to spawn the player so we should let any listeners know about //the ack OnRemotePlayerAcknowledgedWarp?.Invoke(this, new RemotePlayerWarpAcknowledgementEventArgs(entityGuid)); return Task.CompletedTask; } } }
agpl-3.0
C#
962f0f2fb8126750bf2ae299ce61d6a6eac7874f
Add test
sakapon/Samples-2014,sakapon/Samples-2014,sakapon/Samples-2014
MonadSample/MonadConsole/Program.cs
MonadSample/MonadConsole/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonadConsole { class Program { static void Main(string[] args) { MonadTest(); MaybeTest(); FlowTest(); } static void MonadTest() { var r1 = from x in 0.ToMonad() select x; var r2 = from x in 1.ToMonad() from y in 2.ToMonad() select x + y; } static void MaybeTest() { var r1 = from x in 2.ToMaybe() where x % 3 == 1 select x + 1; var r2 = from x in 1.ToMaybe() from y in 2.ToMaybe() where x % 3 == 1 select x + y; } static void FlowTest() { var r1 = from x in 1.ToFlow() from y in 0.ToFlow() select x / y; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonadConsole { class Program { static void Main(string[] args) { } } }
mit
C#
0dd7830dbfe7986c03925e9a5c3d42837b0be7d0
make mocks strict by default
Unity-Technologies/CodeEditor,Unity-Technologies/CodeEditor
src/CodeEditor.Testing/MockBasedTest.cs
src/CodeEditor.Testing/MockBasedTest.cs
using Moq; using NUnit.Framework; namespace CodeEditor.Testing { public abstract class MockBasedTest { [SetUp] public void SetUpMockRepository() { _mocks = new MockRepository(MockBehavior.Strict); } protected Mock<T> MockFor<T>() where T : class { return MockFor<T>(MockBehavior.Strict); } protected Mock<T> MockFor<T>(MockBehavior mockBehavior) where T : class { return _mocks.Create<T>(mockBehavior); } protected void VerifyAllMocks() { _mocks.VerifyAll(); } private MockRepository _mocks; } }
using Moq; using NUnit.Framework; namespace CodeEditor.Testing { public abstract class MockBasedTest { [SetUp] public void SetUpMockRepository() { _mocks = new MockRepository(MockBehavior.Strict); } protected Mock<T> MockFor<T>() where T : class { return MockFor<T>(MockBehavior.Default); } protected Mock<T> MockFor<T>(MockBehavior mockBehavior) where T : class { return _mocks.Create<T>(mockBehavior); } protected void VerifyAllMocks() { _mocks.VerifyAll(); } private MockRepository _mocks; } }
mit
C#
6e66722a9efd9047cb49a4470094ddd375d15dc3
Add XML doc comment
modulexcite/dnlib,picrap/dnlib,0xd4d/dnlib,ZixiangBoy/dnlib,jorik041/dnlib,ilkerhalil/dnlib,kiootic/dnlib,yck1509/dnlib,Arthur2e5/dnlib
src/DotNet/Writer/Extensions.cs
src/DotNet/Writer/Extensions.cs
using System.IO; namespace dot10.DotNet.Writer { /// <summary> /// Extension methods /// </summary> public static partial class Extensions { /// <summary> /// Write zeros /// </summary> /// <param name="writer">this</param> /// <param name="count">Number of zeros</param> public static void WriteZeros(this BinaryWriter writer, int count) { if (count <= 0x20) { for (int i = 0; i < count; i++) writer.Write((byte)0); } else writer.Write(new byte[count]); } } }
using System.IO; namespace dot10.DotNet.Writer { /// <summary> /// Extension methods /// </summary> public static partial class Extensions { public static void WriteZeros(this BinaryWriter writer, int count) { if (count <= 0x20) { for (int i = 0; i < count; i++) writer.Write((byte)0); } else writer.Write(new byte[count]); } } }
mit
C#
238d7c1ba8c6491085178192aa03522341da6185
Fix crash with null exception (#578)
NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper
NuKeeper.Inspection/Logging/ConfigurableLogger.cs
NuKeeper.Inspection/Logging/ConfigurableLogger.cs
using System; using NuKeeper.Abstractions.Logging; namespace NuKeeper.Inspection.Logging { public class ConfigurableLogger : INuKeeperLogger, IConfigureLogger { private IInternalLogger _inner; public void Initialise(LogLevel logLevel, LogDestination destination, string filePath) { _inner = CreateLogger(logLevel, destination, filePath); } public void Error(string message, Exception ex) { CheckLoggerCreated(); _inner.LogError(message, ex); if (ex?.InnerException != null) { Error("Inner Exception", ex.InnerException); } } public void Minimal(string message) { CheckLoggerCreated(); _inner.Log(LogLevel.Minimal, message); } public void Normal(string message) { CheckLoggerCreated(); _inner.Log(LogLevel.Normal, message); } public void Detailed(string message) { CheckLoggerCreated(); _inner.Log(LogLevel.Detailed, message); } private void CheckLoggerCreated() { if (_inner == null) { _inner = CreateLogger(LogLevel.Detailed, LogDestination.Console, string.Empty); } } private static IInternalLogger CreateLogger( LogLevel logLevel, LogDestination destination, string filePath) { switch (destination) { case LogDestination.Console: return new ConsoleLogger(logLevel); case LogDestination.File: return new FileLogger(filePath, logLevel); case LogDestination.Off: return new NullLogger(); default: throw new Exception($"Unknown log destination {destination}"); } } } }
using System; using NuKeeper.Abstractions.Logging; namespace NuKeeper.Inspection.Logging { public class ConfigurableLogger : INuKeeperLogger, IConfigureLogger { private IInternalLogger _inner; public void Initialise(LogLevel logLevel, LogDestination destination, string filePath) { _inner = CreateLogger(logLevel, destination, filePath); } public void Error(string message, Exception ex) { CheckLoggerCreated(); _inner.LogError(message, ex); if (ex.InnerException != null) { Error("Inner Exception", ex.InnerException); } } public void Minimal(string message) { CheckLoggerCreated(); _inner.Log(LogLevel.Minimal, message); } public void Normal(string message) { CheckLoggerCreated(); _inner.Log(LogLevel.Normal, message); } public void Detailed(string message) { CheckLoggerCreated(); _inner.Log(LogLevel.Detailed, message); } private void CheckLoggerCreated() { if (_inner == null) { _inner = CreateLogger(LogLevel.Detailed, LogDestination.Console, string.Empty); } } private static IInternalLogger CreateLogger( LogLevel logLevel, LogDestination destination, string filePath) { switch (destination) { case LogDestination.Console: return new ConsoleLogger(logLevel); case LogDestination.File: return new FileLogger(filePath, logLevel); case LogDestination.Off: return new NullLogger(); default: throw new Exception($"Unknown log destination {destination}"); } } } }
apache-2.0
C#
144fcd36b43066ee11d21a4dd4f6538d091859fc
Fix build for UE4.2 - Add SlateCore as new module dependency
SRombauts/UE4GitPlugin,SRombauts/UE4GitPlugin,SRombauts/UE4GitPlugin
Source/GitSourceControl/GitSourceControl.Build.cs
Source/GitSourceControl/GitSourceControl.Build.cs
// Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com) // // Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt // or copy at http://opensource.org/licenses/MIT) using UnrealBuildTool; public class GitSourceControl : ModuleRules { public GitSourceControl(TargetInfo Target) { PrivateDependencyModuleNames.AddRange( new string[] { "Core", "Slate", "SlateCore", "EditorStyle", "SourceControl", } ); } }
// Copyright (c) 2014 Sebastien Rombauts (sebastien.rombauts@gmail.com) // // Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt // or copy at http://opensource.org/licenses/MIT) using UnrealBuildTool; public class GitSourceControl : ModuleRules { public GitSourceControl(TargetInfo Target) { PrivateDependencyModuleNames.AddRange( new string[] { "Core", "Slate", "EditorStyle", "SourceControl", } ); } }
mit
C#
f07bf5bbb24fa376d7cb53423a235de0803773b0
Enable callback test only when url is set
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
SupportManager.Web/Pages/User/ApiKeys/List.cshtml
SupportManager.Web/Pages/User/ApiKeys/List.cshtml
@page @model SupportManager.Web.Pages.User.ApiKeys.ListModel @{ Layout = "/Features/Shared/_Layout.cshtml"; ViewData["Title"] = "API Keys"; } <h2>API Keys</h2> @if (!Model.Data.ApiKeys.Any()) { <div class="jumbotron"> <p> No API keys created yet. </p> <p> <a class="btn btn-primary btn-lg" asp-page="Create">Create API key</a> </p> </div> } else { <p> <a asp-page="Create">Create API key</a> </p> <table class="table table-striped"> <thead> <tr> <th> Key </th> <th> Callback URL </th> <th></th> </tr> </thead> <tbody> @{ int i = 0;} @foreach (var item in Model.Data.ApiKeys) { <tr> <td> <code>@Model.Data.ApiKeys[i].Value</code> </td> <td> @Model.Data.ApiKeys[i].CallbackUrl </td> <td> @if (@Model.Data.ApiKeys[i].CallbackUrl != null) { <a asp-page="Test" asp-route-id="@item.Id">Test</a> } <a asp-page="Delete" asp-route-id="@item.Id">Delete</a> </td> </tr> i++; } </tbody> </table> }
@page @model SupportManager.Web.Pages.User.ApiKeys.ListModel @{ Layout = "/Features/Shared/_Layout.cshtml"; ViewData["Title"] = "API Keys"; } <h2>API Keys</h2> @if (!Model.Data.ApiKeys.Any()) { <div class="jumbotron"> <p> No API keys created yet. </p> <p> <a class="btn btn-primary btn-lg" asp-page="Create">Create API key</a> </p> </div> } else { <p> <a asp-page="Create">Create API key</a> </p> <table class="table table-striped"> <thead> <tr> <th> Key </th> <th> Callback URL </th> <th></th> </tr> </thead> <tbody> @{ int i = 0;} @foreach (var item in Model.Data.ApiKeys) { <tr> <td> <code>@Model.Data.ApiKeys[i].Value</code> </td> <td> @Model.Data.ApiKeys[i].CallbackUrl </td> <td> <a asp-page="Test" asp-route-id="@item.Id">Test</a> <a asp-page="Delete" asp-route-id="@item.Id">Delete</a> </td> </tr> i++; } </tbody> </table> }
mit
C#
f9c3a251a0eac9c4e775ef9db135674ca12ca9a2
Make Expirable smarter, automatic update on Value retrieve
fiinix00/DNSRootServerResolver
Expirable.cs
Expirable.cs
using System; namespace DNSRootServerResolver { public class Expirable<T> { private bool initialized; private Func<T> renewer; private Func<T, DateTime> reexpirator; public DateTime ExpiresAt { get; set; } private T value; public T Value { get { Refresh(); return value; } set { this.value = value; } } public Expirable(Func<T> renewer, Func<T, DateTime> reexpirator) { this.renewer = renewer; this.reexpirator = reexpirator; } public bool Expired { get { if (!initialized) Refresh(); return DateTime.Now > ExpiresAt; } } public void Refresh() { if (!initialized || Expired) { this.value = this.renewer(); this.ExpiresAt = this.reexpirator(this.value); } initialized = true; } } }
using System; namespace DNSRootServerResolver { public class Expirable<T> { private Func<T> renewer; private Func<T, DateTime> reexpirator; public DateTime ExpiresAt { get; set; } public T Value { get; set; } public Expirable(Func<T> renewer, Func<T, DateTime> reexpirator) { this.renewer = renewer; this.reexpirator = reexpirator; this.Refresh(); } public bool Expired { get { return DateTime.Now > ExpiresAt; } } public void Refresh() { Value = this.renewer(); ExpiresAt = this.reexpirator(Value); } public T RefreshIfExpired() { if (Expired) { Refresh(); } return Value; } } }
mit
C#
ca00deca82371897aa57f4f96011d93a1a7f50fe
Update Models
gOOvaUY/Plexo.Models,gOOvaUY/Goova.Plexo.Models
FieldType.cs
FieldType.cs
using System.Runtime.Serialization; // ReSharper disable InconsistentNaming namespace Goova.Plexo { [DataContract] public enum FieldType { [EnumMember] Pan, [EnumMember] Expiration, [EnumMember] Pin, [EnumMember] CVC, [EnumMember] Name, [EnumMember] Address, [EnumMember] ZipCode, [EnumMember] Email, [EnumMember] AmountLimitExtension } }
using System.Runtime.Serialization; // ReSharper disable InconsistentNaming namespace Goova.Plexo { [DataContract] public enum FieldType { [EnumMember] Pan, [EnumMember] Expiration, [EnumMember] Pin, [EnumMember] CVC, [EnumMember] Name, [EnumMember] Address, [EnumMember] ZipCode, [EnumMember] Email } }
agpl-3.0
C#
de632c1bc7f29e637a9690a1e06dfe83cb6bbfd8
Add MethodSemanticsAttributes.None
Arthur2e5/dnlib,jorik041/dnlib,picrap/dnlib,ZixiangBoy/dnlib,kiootic/dnlib,ilkerhalil/dnlib,0xd4d/dnlib,modulexcite/dnlib,yck1509/dnlib
src/DotNet/MethodSemanticsAttributes.cs
src/DotNet/MethodSemanticsAttributes.cs
// dnlib: See LICENSE.txt for more info using System; namespace dnlib.DotNet { /// <summary> /// Method semantics flags, see CorHdr.h/CorMethodSemanticsAttr /// </summary> [Flags] public enum MethodSemanticsAttributes : ushort { /// <summary>No bit is set</summary> None = 0, /// <summary>Setter for property</summary> Setter = 0x0001, /// <summary>Getter for property</summary> Getter = 0x0002, /// <summary>other method for property or event</summary> Other = 0x0004, /// <summary>AddOn method for event</summary> AddOn = 0x0008, /// <summary>RemoveOn method for event</summary> RemoveOn = 0x0010, /// <summary>Fire method for event</summary> Fire = 0x0020, } }
// dnlib: See LICENSE.txt for more info using System; namespace dnlib.DotNet { /// <summary> /// Method semantics flags, see CorHdr.h/CorMethodSemanticsAttr /// </summary> [Flags] public enum MethodSemanticsAttributes : ushort { /// <summary>Setter for property</summary> Setter = 0x0001, /// <summary>Getter for property</summary> Getter = 0x0002, /// <summary>other method for property or event</summary> Other = 0x0004, /// <summary>AddOn method for event</summary> AddOn = 0x0008, /// <summary>RemoveOn method for event</summary> RemoveOn = 0x0010, /// <summary>Fire method for event</summary> Fire = 0x0020, } }
mit
C#
4dc5b1b2985c7729ab7ea38c8e52a7da148d1aab
Update ScribbleShape.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D.Core/Shapes/ScribbleShape.cs
src/Draw2D.Core/Shapes/ScribbleShape.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 System.Collections.Generic; using System.Collections.ObjectModel; using Draw2D.Core.Renderers; namespace Draw2D.Core.Shapes { public class ScribbleShape : ConnectableShape, ICopyable<ScribbleShape> { public ScribbleShape() : base() { } public ScribbleShape(ObservableCollection<PointShape> points) : base() { this.Points = points; } public override IEnumerable<PointShape> GetPoints() { foreach (var point in Points) { yield return point; } } public override void Draw(object dc, ShapeRenderer r, double dx, double dy) { base.BeginTransform(dc, r); if (Points.Count >= 2 && Style != null) { r.DrawPolyLine(dc, Points, Style, dx, dy); } foreach (var point in Points) { if (r.Selected.Contains(point)) { point.Draw(dc, r, dx, dy); } } base.EndTransform(dc, r); } public override void Move(ISet<ShapeObject> selected, double dx, double dy) { foreach (var point in Points) { if (!selected.Contains(point)) { point.Move(selected, dx, dy); } } } public ScribbleShape Copy() { return new ScribbleShape() { Style = this.Style, Transform = this.Transform?.Copy() }; } } }
// 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 System.Collections.Generic; using System.Collections.ObjectModel; using Draw2D.Core.Renderers; namespace Draw2D.Core.Shapes { public class ScribbleShape : ConnectableShape, ICopyable<ScribbleShape> { public ScribbleShape() : base() { } public ScribbleShape(ObservableCollection<PointShape> points) : base() { this.Points = points; } public override IEnumerable<PointShape> GetPoints() { foreach (var point in Points) { yield return point; } } public override void Draw(object dc, ShapeRenderer r, double dx, double dy) { base.BeginTransform(dc, r); if (_points.Count >= 2 && Style != null) { r.DrawPolyLine(dc, _points, Style, dx, dy); } foreach (var point in _points) { if (r.Selected.Contains(point)) { point.Draw(dc, r, dx, dy); } } base.EndTransform(dc, r); } public override void Move(ISet<ShapeObject> selected, double dx, double dy) { if (!selected.Contains(_start)) { _start.Move(selected, dx, dy); } foreach (var point in Points) { if (!selected.Contains(point)) { point.Move(selected, dx, dy); } } } public ScribbleShape Copy() { return new ScribbleShape() { Style = this.Style, Transform = this.Transform?.Copy() }; } } }
mit
C#
b90e0cc002904cd7109b7ea53d121c532762226c
Use String.Split(...) instead of recreating it.
fixie/fixie
src/Fixie.Assertions/AssertException.cs
src/Fixie.Assertions/AssertException.cs
namespace Fixie.Assertions { using System; using System.Collections.Generic; public class AssertException : Exception { public static string FilterStackTraceAssemblyPrefix = "Fixie.Assertions."; public AssertException(string message) : base(message) { } public override string StackTrace => FilterStackTrace(base.StackTrace); static string FilterStackTrace(string stackTrace) { if (stackTrace == null) return null; var results = new List<string>(); foreach (var line in Lines(stackTrace)) { var trimmedLine = line.TrimStart(); if (!trimmedLine.StartsWith("at " + FilterStackTraceAssemblyPrefix)) results.Add(line); } return string.Join(Environment.NewLine, results.ToArray()); } static string[] Lines(string input) { return input.Split(new[] {Environment.NewLine}, StringSplitOptions.None); } } }
namespace Fixie.Assertions { using System; using System.Collections.Generic; public class AssertException : Exception { public static string FilterStackTraceAssemblyPrefix = "Fixie.Assertions."; public AssertException(string message) : base(message) { } public override string StackTrace => FilterStackTrace(base.StackTrace); static string FilterStackTrace(string stackTrace) { if (stackTrace == null) return null; var results = new List<string>(); foreach (var line in SplitLines(stackTrace)) { var trimmedLine = line.TrimStart(); if (!trimmedLine.StartsWith( "at " + FilterStackTraceAssemblyPrefix) ) results.Add(line); } return string.Join(Environment.NewLine, results.ToArray()); } // Our own custom string.Split because Silverlight/CoreCLR doesn't support the version we were using static IEnumerable<string> SplitLines(string input) { while (true) { int idx = input.IndexOf(Environment.NewLine); if (idx < 0) { yield return input; break; } yield return input.Substring(0, idx); input = input.Substring(idx + Environment.NewLine.Length); } } } }
mit
C#
28f6af5ac266c604b4cb4d2fea5cfb33652ac1de
Simplify help messages
TrackerMigrator/IssueMigrator
src/IssueMigrator/CommandLineOptions.cs
src/IssueMigrator/CommandLineOptions.cs
 using CommandLine; using CommandLine.Text; namespace CodePlexIssueMigrator { /// <summary> /// The options class which contains the different options to CodePlex to GitHub migration utility. /// </summary> public class CommandLineOptions { #region HelpText const string CodeplexProjectHelpText = "CodePlex project to migrate."; const string GitHubRepositoryHelpText = "GitHub repository."; const string GitHubOwnerHelpText = "GitHub repository owner/organization."; const string GitHubAccessTokenHelpText = "GitHub Access Token."; [HelpOption] public string GetHelp() { return HelpText.AutoBuild(this, c => HelpText.DefaultParsingErrorsHandler(this, c)); } #endregion [Option("from", Required = true, HelpText = CodeplexProjectHelpText)] public string CodeplexProject { get; set; } [Option("to", Required = true, HelpText = GitHubRepositoryHelpText)] public string GitHubRepository { get; set; } [Option("owner", Required = true, HelpText = GitHubOwnerHelpText)] public string GitHubOwner { get; set; } [Option("key", Required = true, HelpText = GitHubAccessTokenHelpText)] public string GitHubAccessToken { get; set; } } }
 using CommandLine; using CommandLine.Text; namespace CodePlexIssueMigrator { /// <summary> /// The options class which contains the different options to CodePlex to GitHub migration utility. /// </summary> public class CommandLineOptions { #region HelpText const string CodeplexProjectHelpText = "The name of the CodePlex project to migrate."; const string GitHubRepositoryHelpText = "The name of the GitHub repository."; const string GitHubOwnerHelpText = "The name of the dump GitHub repository owner/organization."; const string GitHubAccessTokenHelpText = "The name of the dump GitHub Access Token."; [HelpOption] public string GetHelp() { return HelpText.AutoBuild(this, c => HelpText.DefaultParsingErrorsHandler(this, c)); } #endregion [Option("from", Required = true, HelpText = CodeplexProjectHelpText)] public string CodeplexProject { get; set; } [Option("to", Required = true, HelpText = GitHubRepositoryHelpText)] public string GitHubRepository { get; set; } [Option("owner", Required = true, HelpText = GitHubOwnerHelpText)] public string GitHubOwner { get; set; } [Option("key", Required = true, HelpText = GitHubAccessTokenHelpText)] public string GitHubAccessToken { get; set; } } }
mit
C#
043f8fda61931ee23416bd68865f3623f3ce2ac2
Fix typo (delegate) in documentation (#830)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Microsoft.AspNetCore.Http.Abstractions/Extensions/UseExtensions.cs
src/Microsoft.AspNetCore.Http.Abstractions/Extensions/UseExtensions.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Extension methods for adding middleware. /// </summary> public static class UseExtensions { /// <summary> /// Adds a middleware delegate defined in-line to the application's request pipeline. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="middleware">A function that handles the request or calls the given next function.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) { return app.Use(next => { return context => { Func<Task> simpleNext = () => next(context); return middleware(context, simpleNext); }; }); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Microsoft.AspNetCore.Builder { /// <summary> /// Extension methods for adding middleware. /// </summary> public static class UseExtensions { /// <summary> /// Adds a middleware delagate defined in-line to the application's request pipeline. /// </summary> /// <param name="app">The <see cref="IApplicationBuilder"/> instance.</param> /// <param name="middleware">A function that handles the request or calls the given next function.</param> /// <returns>The <see cref="IApplicationBuilder"/> instance.</returns> public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) { return app.Use(next => { return context => { Func<Task> simpleNext = () => next(context); return middleware(context, simpleNext); }; }); } } }
apache-2.0
C#
34893657170b7726c142887c6087c8380a7e68b6
add photo.cs
Cream2015/VoteWeb,Cream2015/VoteWeb,Cream2015/VoteWeb
VoteWeb/src/VoteWeb/Models/Photo.cs
VoteWeb/src/VoteWeb/Models/Photo.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VoteWeb.Models { public class Photo { /// <summary> /// 作者ID /// </summary> public long PhotoID { get; set; } /// <summary> /// 作品名称 /// </summary> public string Title { get; set; } /// <summary> /// 作品地址 /// </summary> public string PhotoURL { get; set; } /// <summary> /// 作者ID /// </summary> public long AuthorID { get; set; } /// <summary> /// 创建时间 /// </summary> public DateTime CreateTime { get; set; } /// <summary> /// 作品简介 /// </summary> public string Introduction { get; set; } /// <summary> /// 是否展示 /// </summary> public int IsDisplay { get; set; } /// <summary> /// 是否删除 /// </summary> public int IsDelete { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VoteWeb.Models { public class Photo { /// <summary> /// 作品ID /// </summary> public long PhotoID { get; set; } /// <summary> /// 作品标题 /// </summary> public string Title { get; set; } /// <summary> /// 类型ID /// </summary> public long CategoryID { get; set; } /// <summary> /// 作者ID /// </summary> public long AuthorID { get; set; } /// <summary> /// 作品URL /// </summary> public string PhotoURL { get; set; } /// <summary> /// 作品简介 /// </summary> public string Introduction { get; set; } /// <summary> /// 是否已经删除 /// </summary> public int IsDelete { get; set; } } }
mit
C#
d101a7ecd47a8caf9dd253f4aa4e8477eafe276c
Load footer image in JavaScript disabled
martincostello/website,martincostello/website,martincostello/website,martincostello/website
src/Website/Views/Shared/_Footer.cshtml
src/Website/Views/Shared/_Footer.cshtml
@model SiteOptions <hr /> <footer> <p> &copy; @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year | <a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information"> Site Status &amp; Uptime </a> | Built from <a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub"> @string.Join(string.Empty, GitMetadata.Commit.Take(7)) </a> on <a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub"> @GitMetadata.Branch </a> | Sponsored by <a id="link-browserstack" href="https://www.browserstack.com/"> <noscript> <img src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" asp-append-version="true" /> </noscript> <lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" /> </a> </p> </footer>
@model SiteOptions <hr /> <footer> <p> &copy; @Model.Metadata.Author.Name @DateTimeOffset.UtcNow.Year | <a id="link-status" href="@Model.ExternalLinks.Status.AbsoluteUri" target="_blank" title="View site uptime information"> Site Status &amp; Uptime </a> | Built from <a id="link-git" href="@Model.Metadata.Repository/commit/@GitMetadata.Commit" title="View commit @GitMetadata.Commit on GitHub"> @string.Join(string.Empty, GitMetadata.Commit.Take(7)) </a> on <a href="@Model.Metadata.Repository/tree/@GitMetadata.Branch" title="View branch @GitMetadata.Branch on GitHub"> @GitMetadata.Branch </a> | Sponsored by <a id="link-browserstack" href="https://www.browserstack.com/"> <lazyimg src="~/assets/img/browserstack.svg" viewBox="0 0 428.5 92.3" height="20" alt="Sponsored by BrowserStack" title="Sponsored by BrowserStack" /> </a> </p> </footer>
apache-2.0
C#
9425542d170e4367a9e0b836b606a67947da279c
Generalize NamespaceDoc
YallaDotNet/Yalla.Core
src/Yalla.Core/Portable/NamespaceDoc.cs
src/Yalla.Core/Portable/NamespaceDoc.cs
namespace Yalla { /// <summary> /// Yalla types. /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] internal sealed class NamespaceDoc { } }
namespace Yalla { /// <summary> /// Yalla Core classes, interfaces and enumerations. /// </summary> [System.Runtime.CompilerServices.CompilerGenerated] internal sealed class NamespaceDoc { } }
apache-2.0
C#
8d3541e82bb9d83c51de633859474fccc1e4b7e5
Adjust columns for guitars home
michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic
MichaelsMusic/Views/Guitars/index.cshtml
MichaelsMusic/Views/Guitars/index.cshtml
@model MichaelsMusic.Models.GuitarCollection @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Guitars"; ViewBag.Description = "This is the guitar collections page. These are all guitars that I either: own, used to own, or wish I owned (which is most of them). If you want to look at guitars, but you're not sure which ones, this is the right place to start."; ViewBag.Keywords = "guitars, mcnaught guitars, mcnaught vintage double cut, prs, prs guitars, paul reed smith, paul reed smith guitars, paul reed smith custom 24, prs custom 24, paul reed smith mccarty, prs mccarty, peavey hp custom, gibson midtown custom, king bee oak cliff, 1980 gibson les paul custom, collings city limits deluxe, collings cl deluxe"; } <section class="section section-size1"> <div class="row"> <div class="nine columns"> <h1>Guitars</h1> <p>This is the guitars collection page. If you want to look at guitars, but you're not sure which ones, this is the right place to start.</p> </div> </div> <div class="row"> <div class="column"> <ul class="item-collection"> @foreach (var guitar in Model.Guitars) { <li> <p class="title"> <a href="@($"/guitars/{guitar.Slug}/")">@guitar.DisplayName</a> </p> <a href="@($"/guitars/{guitar.Slug}/")"> <img src=@($"/images/guitars/{guitar.Thumbnail}") alt="" /> </a> <p>@guitar.ShortDescription</p> <p> <a href="@($"/guitars/{guitar.Slug}/")">Learn more &raquo;</a> </p> </li> } </ul> </div> </div> </section>
@model MichaelsMusic.Models.GuitarCollection @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Guitars"; ViewBag.Description = "This is the guitar collections page. These are all guitars that I either: own, used to own, or wish I owned (which is most of them). If you want to look at guitars, but you're not sure which ones, this is the right place to start."; ViewBag.Keywords = "guitars, mcnaught guitars, mcnaught vintage double cut, prs, prs guitars, paul reed smith, paul reed smith guitars, paul reed smith custom 24, prs custom 24, paul reed smith mccarty, prs mccarty, peavey hp custom, gibson midtown custom, king bee oak cliff, 1980 gibson les paul custom, collings city limits deluxe, collings cl deluxe"; } <section class="section section-size1"> <div class="row"> <div class="twelve columns"> <h1>Guitars</h1> <p>This is the guitars collection page. If you want to look at guitars, but you're not sure which ones, this is the right place to start.</p> </div> </div> <div class="row"> <div class="column"> <ul class="item-collection"> @foreach (var guitar in Model.Guitars) { <li> <p class="title"> <a href="@($"/guitars/{guitar.Slug}/")">@guitar.DisplayName</a> </p> <a href="@($"/guitars/{guitar.Slug}/")"> <img src=@($"/images/guitars/{guitar.Thumbnail}") alt="" /> </a> <p>@guitar.ShortDescription</p> <p> <a href="@($"/guitars/{guitar.Slug}/")">Learn more &raquo;</a> </p> </li> } </ul> </div> </div> </section>
mit
C#
c5f9cf87bd3a18e4acf130a001f84b249598acc4
Exclude the first word
BinaryTENSHi/mountain-thoughts
mountain-thoughts/Program.cs
mountain-thoughts/Program.cs
using System; using System.Diagnostics; using System.Linq; namespace mountain_thoughts { public class Program { public static void Main(string[] args) { Process mountainProcess = NativeMethods.GetMountainProcess(); if (mountainProcess == null) { Console.WriteLine("Could not get process. Is Mountain running?"); Console.ReadLine(); Environment.Exit(1); } IntPtr handle = mountainProcess.Handle; IntPtr address = NativeMethods.GetStringAddress(mountainProcess); Twitter.Authenticate(); NativeMethods.StartReadingString(handle, address, Callback); Console.ReadLine(); NativeMethods.StopReadingString(); } private static void Callback(string thought) { string properThought = string.Empty; foreach (string word in thought.Split(' ').Skip(1)) { string lowerWord = word; if (word != "I") lowerWord = word.ToLowerInvariant(); properThought += lowerWord + " "; } properThought = properThought.Trim(); Console.WriteLine(properThought); Twitter.Tweet(string.Format("\"{0}\"", properThought)); } } }
using System; using System.Diagnostics; namespace mountain_thoughts { public class Program { public static void Main(string[] args) { Process mountainProcess = NativeMethods.GetMountainProcess(); if (mountainProcess == null) { Console.WriteLine("Could not get process. Is Mountain running?"); Console.ReadLine(); Environment.Exit(1); } IntPtr handle = mountainProcess.Handle; IntPtr address = NativeMethods.GetStringAddress(mountainProcess); Twitter.Authenticate(); NativeMethods.StartReadingString(handle, address, Callback); Console.ReadLine(); NativeMethods.StopReadingString(); } private static void Callback(string thought) { string properThought = string.Empty; foreach (string word in thought.Split(' ')) { string lowerWord = word; if (word != "I") lowerWord = word.ToLowerInvariant(); properThought += lowerWord + " "; } properThought = properThought.Trim(); Console.WriteLine(properThought); Twitter.Tweet(string.Format("\"{0}\"", properThought)); } } }
mit
C#
6578aa82f894f6c4c4a5d83c12b330bb673355b8
add safe post
gridsum/DataflowEx,TheAngryByrd/DataflowEx
Gridsum.DataflowEx/BlockContainerUtils.cs
Gridsum.DataflowEx/BlockContainerUtils.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Gridsum.DataflowEx.AutoCompletion; using Gridsum.DataflowEx.Exceptions; using Microsoft.CSharp.RuntimeBinder; namespace Gridsum.DataflowEx { public static class BlockContainerUtils { public static BlockContainer<TIn, TOut> FromBlock<TIn, TOut>(IPropagatorBlock<TIn, TOut> block) { return new PropagatorBlockContainer<TIn, TOut>(block); } public static BlockContainer<TIn, TOut> FromBlock<TIn, TOut>(IPropagatorBlock<TIn, TOut> block, BlockContainerOptions options) { return new PropagatorBlockContainer<TIn, TOut>(block, options); } public static BlockContainer<TIn, TOut> AutoComplete<TIn, TOut>(this BlockContainer<TIn, TOut> blockContainer, TimeSpan timeout) where TIn : ITracableItem where TOut : ITracableItem { var autoCompletePair = new AutoCompleteContainerPair<TIn, TOut>(timeout); var merged = new BlockContainerMerger<TIn, TIn, TOut, TOut>( autoCompletePair.Before, blockContainer, autoCompletePair.After); return merged; } public static void SafePost<TIn>(this ITargetBlock<TIn> target, TIn item) { bool posted = target.Post(item); if (posted) return; for(int i = 1; i <=3 ;i ++) { Thread.Sleep(500 * i); posted = target.Post(item); if (posted) return; } throw new PostToInputBlockFailedException("Safe post to " + Utils.GetFriendlyName(target.GetType()) + " failed"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; using Gridsum.DataflowEx.AutoCompletion; using Microsoft.CSharp.RuntimeBinder; namespace Gridsum.DataflowEx { public static class BlockContainerUtils { public static BlockContainer<TIn, TOut> FromBlock<TIn, TOut>(IPropagatorBlock<TIn, TOut> block) { return new PropagatorBlockContainer<TIn, TOut>(block); } public static BlockContainer<TIn, TOut> FromBlock<TIn, TOut>(IPropagatorBlock<TIn, TOut> block, BlockContainerOptions options) { return new PropagatorBlockContainer<TIn, TOut>(block, options); } public static BlockContainer<TIn, TOut> AutoComplete<TIn, TOut>(this BlockContainer<TIn, TOut> blockContainer, TimeSpan timeout) where TIn : ITracableItem where TOut : ITracableItem { var autoCompletePair = new AutoCompleteContainerPair<TIn, TOut>(timeout); var merged = new BlockContainerMerger<TIn, TIn, TOut, TOut>( autoCompletePair.Before, blockContainer, autoCompletePair.After); return merged; } } }
mit
C#
cbf464b37078cb374df563bfebb2fb00a64638ca
fix progress bars
RelistenNet/RelistenApi,alecgorge/RelistenApi,RelistenNet/RelistenApi,alecgorge/RelistenApi,RelistenNet/RelistenApi,RelistenNet/RelistenApi
RelistenApi/Vendor/ProgressExtensions.cs
RelistenApi/Vendor/ProgressExtensions.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using Hangfire.Console.Progress; namespace Relisten { public static class ProgressExtensions { public static async Task<IList<T>> AsyncForEachWithProgress<T>(this IList<T> list, IProgressBar bar, Func<T, Task> action) { var count = 1; foreach (var item in list) { await action(item); bar.SetValue(100.0 * count / list.Count); count++; } return list; } public static IList<T> ForEachWithProgress<T>(this IList<T> list, IProgressBar bar, Action<T> action) { var count = 1; foreach (var item in list) { action(item); bar.SetValue(100.0 * count / list.Count); count++; } return list; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Hangfire.Console.Progress; namespace Relisten { public static class ProgressExtensions { public static async Task<IList<T>> AsyncForEachWithProgress<T>(this IList<T> list, IProgressBar bar, Func<T, Task> action) { var count = 1; foreach (var item in list) { await action(item); bar.SetValue(100.0 * count / list.Count); } return list; } public static IList<T> ForEachWithProgress<T>(this IList<T> list, IProgressBar bar, Action<T> action) { var count = 1; foreach (var item in list) { action(item); bar.SetValue(100.0 * count / list.Count); } return list; } } }
mit
C#
84a3c9cdc70e0a9d8a1ffba94fc05ab0ebfd91f1
Correct a typo in comment for 'Invoke-WebRequest' (#6700)
JamesWTruher/PowerShell-1,daxian-dbw/PowerShell,PaulHigin/PowerShell,JamesWTruher/PowerShell-1,TravisEz13/PowerShell,PaulHigin/PowerShell,TravisEz13/PowerShell,JamesWTruher/PowerShell-1,daxian-dbw/PowerShell,PaulHigin/PowerShell,daxian-dbw/PowerShell,JamesWTruher/PowerShell-1,daxian-dbw/PowerShell,TravisEz13/PowerShell,PaulHigin/PowerShell,TravisEz13/PowerShell
src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs
src/Microsoft.PowerShell.Commands.Utility/commands/utility/WebCmdlet/CoreCLR/InvokeWebRequestCommand.CoreClr.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Management.Automation; using System.Net.Http; using System.IO; namespace Microsoft.PowerShell.Commands { /// <summary> /// The Invoke-WebRequest command. /// This command makes an HTTP or HTTPS request to a web server and returns the results. /// </summary> [Cmdlet(VerbsLifecycle.Invoke, "WebRequest", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217035", DefaultParameterSetName = "StandardMethod")] public class InvokeWebRequestCommand : WebRequestPSCmdlet { #region Virtual Method Overrides /// <summary> /// Default constructor for InvokeWebRequestCommand /// </summary> public InvokeWebRequestCommand() : base() { this._parseRelLink = true; } /// <summary> /// Process the web response and output corresponding objects. /// </summary> /// <param name="response"></param> internal override void ProcessResponse(HttpResponseMessage response) { if (null == response) { throw new ArgumentNullException("response"); } Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) { // creating a MemoryStream wrapper to response stream here to support IsStopping. responseStream = new WebResponseContentMemoryStream(responseStream, StreamHelper.ChunkSize, this); WebResponseObject ro = WebResponseObjectFactory.GetResponseObject(response, responseStream, this.Context); ro.RelationLink = _relationLink; WriteObject(ro); // use the rawcontent stream from WebResponseObject for further // processing of the stream. This is need because WebResponse's // stream can be used only once. responseStream = ro.RawContentStream; responseStream.Seek(0, SeekOrigin.Begin); } if (ShouldSaveToOutFile) { StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this); } } #endregion Virtual Method Overrides } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Management.Automation; using System.Net.Http; using System.IO; namespace Microsoft.PowerShell.Commands { /// <summary> /// The Invoke-RestMethod command /// This command makes an HTTP or HTTPS request to a web server and returns the results. /// </summary> [Cmdlet(VerbsLifecycle.Invoke, "WebRequest", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=217035", DefaultParameterSetName = "StandardMethod")] public class InvokeWebRequestCommand : WebRequestPSCmdlet { #region Virtual Method Overrides /// <summary> /// Default constructor for InvokeWebRequestCommand /// </summary> public InvokeWebRequestCommand() : base() { this._parseRelLink = true; } /// <summary> /// Process the web response and output corresponding objects. /// </summary> /// <param name="response"></param> internal override void ProcessResponse(HttpResponseMessage response) { if (null == response) { throw new ArgumentNullException("response"); } Stream responseStream = StreamHelper.GetResponseStream(response); if (ShouldWriteToPipeline) { // creating a MemoryStream wrapper to response stream here to support IsStopping. responseStream = new WebResponseContentMemoryStream(responseStream, StreamHelper.ChunkSize, this); WebResponseObject ro = WebResponseObjectFactory.GetResponseObject(response, responseStream, this.Context); ro.RelationLink = _relationLink; WriteObject(ro); // use the rawcontent stream from WebResponseObject for further // processing of the stream. This is need because WebResponse's // stream can be used only once. responseStream = ro.RawContentStream; responseStream.Seek(0, SeekOrigin.Begin); } if (ShouldSaveToOutFile) { StreamHelper.SaveStreamToFile(responseStream, QualifiedOutFile, this); } } #endregion Virtual Method Overrides } }
mit
C#
44b42284baf0812e4e9a55b2df72ce47ba1780c7
Add summary
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MixedRealityToolkit.Providers/WindowsMixedReality/Shared/Definitions/IWindowsMixedRealityUtilitiesProvider.cs
Assets/MixedRealityToolkit.Providers/WindowsMixedReality/Shared/Definitions/IWindowsMixedRealityUtilitiesProvider.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality { /// <summary> /// Defines a set of IntPtr properties that are used by the static <see cref="WindowsMixedRealityUtilities"/> /// to provide access to specific underlying native objects relevant to Windows Mixed Reality. /// </summary> /// <remarks> /// This is intended to be used to support both XR SDK and Unity's legacy XR pipeline, which provide /// different APIs to access these native objects. /// </remarks> public interface IWindowsMixedRealityUtilitiesProvider { /// <summary> /// The current native root <see href="https://docs.microsoft.com/uwp/api/windows.perception.spatial.spatialcoordinatesystem">ISpatialCoordinateSystem</see>. /// </summary> IntPtr ISpatialCoordinateSystemPtr { get; } /// <summary> /// The current native <see href="https://docs.microsoft.com/uwp/api/Windows.Graphics.Holographic.HolographicFrame">IHolographicFrame</see>. /// </summary> IntPtr IHolographicFramePtr { get; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; namespace Microsoft.MixedReality.Toolkit.WindowsMixedReality { public interface IWindowsMixedRealityUtilitiesProvider { /// <summary> /// The current native root <see href="https://docs.microsoft.com/uwp/api/windows.perception.spatial.spatialcoordinatesystem">ISpatialCoordinateSystem</see>. /// </summary> IntPtr ISpatialCoordinateSystemPtr { get; } /// <summary> /// The current native <see href="https://docs.microsoft.com/uwp/api/Windows.Graphics.Holographic.HolographicFrame">IHolographicFrame</see>. /// </summary> IntPtr IHolographicFramePtr { get; } } }
mit
C#
306b86077182956a43addc6c4e140e8ad3ce8ac9
Fix MSTest test
atata-framework/atata-samples
MSTest/AtataSamples.MSTest/SampleTests.cs
MSTest/AtataSamples.MSTest/SampleTests.cs
using Atata; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AtataSamples.MSTest { [TestClass] public class SampleTests : UITestFixture { /// <summary> /// Simple test approach when you don't need to add exception/error information to the log. /// For example, when you use Visual Studio or CI system to view the log, as exception is displayed there any way. /// </summary> [TestMethod] public void MSTest() { Go.To<HomePage>(). Header.Should.Equal("Atata Sample App"); } /// <summary> /// Use such approach with <see cref="UITestFixture.Execute(System.Action)"/> method when you need to add exception/error information to the log. /// It is needed if you log to file or other external source. /// </summary> [TestMethod] public void MSTestWithExceptionLogging() { Execute(() => { Go.To<HomePage>(). Header.Should.Equal("Atata Sample App"); ////Header.Should.Equal("Unknown Title"); }); } } }
using Atata; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace AtataSamples.MSTest { [TestClass] public class SampleTests : UITestFixture { /// <summary> /// Simple test approach when you don't need to add exception/error information to the log. /// For example, when you use Visual Studio or CI system to view the log, as exception is displayed there any way. /// </summary> [TestMethod] public void MSTest() { Go.To<HomePage>(). Header.Should.Equal("Atata Sample A1pp"); } /// <summary> /// Use such approach with <see cref="UITestFixture.Execute(System.Action)"/> method when you need to add exception/error information to the log. /// It is needed if you log to file or other external source. /// </summary> [TestMethod] public void MSTestWithExceptionLogging() { Execute(() => { Go.To<HomePage>(). Header.Should.Equal("Atata Sample App"); ////Header.Should.Equal("Unknown Title"); }); } } }
apache-2.0
C#
9254640d1c6ffbbb3ca9bbfe5641cd70cb7ce095
Update for IIS
WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework,WorkplaceX/Framework
Framework/Server/Startup.cs
Framework/Server/Startup.cs
namespace Server { using Framework; using Framework.Server; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Diagnostics; /// <summary> /// Derived class Startup has to be declared in Server assembly. /// </summary> public abstract class StartupBase { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddMemoryCache(); services.AddSingleton<UnitTestService>(); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); // Needed for IIS. Otherwise new HttpContextAccessor(); results in null reference exception. // if (Debugger.IsAttached) { UtilServer.StartUniversalServer(); } } private static bool debugIsException = true; // Enable exception page. // If running on IIS make sure web.config contains: arguments="Server.dll" if you get HTTP Error 502.5 - Process Failure public const string ControllerPath = "/"; // "/web/"; // Enable debug mode. Path when WebController kicks in. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (debugIsException) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); // Enable access to files in folder wwwwroot. app.UseMvc(); // Enable WebController. app.Run(async (context) => // Fallback if no URL matches. { await context.Response.WriteAsync("<html><head><title></title></head><body><h1>Debug</h1><a href='web/config/'>Config</a><br /><a href='web/demo/'>Demo</a></body></html>"); }); } } }
namespace Server { using Framework; using Framework.Server; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using System.Diagnostics; /// <summary> /// Derived class Startup has to be declared in Server assembly. /// </summary> public abstract class StartupBase { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddMemoryCache(); services.AddSingleton(new UnitTestService()); // if (Debugger.IsAttached) { UtilServer.StartUniversalServer(); } } private static bool debugIsException = true; // Enable exception page. // If running on IIS make sure web.config contains: arguments="Server.dll" if you get HTTP Error 502.5 - Process Failure public const string ControllerPath = "/"; // "/web/"; // Enable debug mode. Path when WebController kicks in. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(); if (debugIsException) { app.UseDeveloperExceptionPage(); } app.UseStaticFiles(); // Enable access to files in folder wwwwroot. app.UseMvc(); // Enable WebController. app.Run(async (context) => // Fallback if no URL matches. { await context.Response.WriteAsync("<html><head><title></title></head><body><h1>Debug</h1><a href='web/config/'>Config</a><br /><a href='web/demo/'>Demo</a></body></html>"); }); } } }
mit
C#
7d22a94564beaa9bf18bc937ace85415325bce44
Update for SSL error with site
irfancharania/HackyNewsClone
HackyNewsWeb/Global.asax.cs
HackyNewsWeb/Global.asax.cs
using System.Net; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace HackyNewsWeb { public class Global : HttpApplication { protected void Application_Start() { // to account for SSL error ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12; AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace HackyNewsWeb { public class Global : HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
mit
C#
4c47fabfc9016d5506e6cdaded694dc7f911a17d
fix shockwave
danyaal/CTFUnity,danyaal/CTFUnity
Assets/Scripts/Shockwave.cs
Assets/Scripts/Shockwave.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using System; public class Shockwave : DropItem { const int numEdgePoints = 200; const float maxScale = 8f; const float initialLifeTime = 0.6f; LineRenderer line; Vector3 startScale; Color startColor; void Start() { lifeTime = initialLifeTime; line = GetComponent <LineRenderer>(); line.SetVertexCount(numEdgePoints); startColor = line.material.color; DrawEdge(); Destroy(gameObject, lifeTime); } void DrawEdge() { startScale = transform.localScale; Enumerable.Range(0, numEdgePoints) .ToList() .ForEach(i => { float rad = ((float)i)/((float)numEdgePoints-1) * 2f*Mathf.PI; Vector3 linePart = new Vector3(Mathf.Sin(rad), 0, Mathf.Cos(rad)); line.SetPosition(i, linePart); }); } new void Update() { base.Update(); float prog = 1-(lifeTime/initialLifeTime); float scaleFactor = maxScale * (0.2f+prog); transform.localScale = Vector3.Scale(startScale.normalized, new Vector3(scaleFactor, 1, scaleFactor)); line.material.color = Color.Lerp(startColor, Color.clear, prog); } void OnTriggerEnter2D(Collider2D coll) { HitEdge(coll); } void OnTriggerExit2D(Collider2D coll) { HitEdge(coll); } void HitEdge(Collider2D coll) { Player p = coll.GetComponent<Player>(); if (p && p.team != owner.team) { p.rigidbody2D.AddForce(ForceForColl(coll), ForceMode2D.Impulse); p.hasKnockback = true; } // Flag f = coll.GetComponent<Flag>(); // if (f) { // f.Drop(); // Debug.Log(ForceForColl(coll)); // f.rigidbody2D.AddForce(ForceForColl(coll), ForceMode2D.Impulse); // } } Vector2 ForceForColl(Collider2D coll) { GameObject go = coll.gameObject; Vector2 toTarget = go.transform.position - transform.position; toTarget = toTarget.normalized * (maxScale - toTarget.magnitude); return toTarget * 10f; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Linq; using System; public class Shockwave : DropItem { const int numEdgePoints = 200; const float maxScale = 5f; LineRenderer line; List<Vector3> points; Vector3 startScale; Color startColor; float startTime; void Start() { lifeTime = 0.5f; line = GetComponent <LineRenderer>(); line.SetVertexCount(numEdgePoints); startTime = Time.time; startColor = line.material.color; DrawEdge(); Destroy(gameObject, lifeTime); } void DrawEdge() { startScale = transform.localScale; Enumerable.Range(0, numEdgePoints) .ToList() .ForEach(i => { float rad = ((float)i)/((float)numEdgePoints) * 2f*Mathf.PI; Vector3 linePart = new Vector3(Mathf.Sin(rad), 0, Mathf.Cos(rad)); line.SetPosition(i, linePart); }); } new void Update() { base.Update(); float prog = (Time.time - startTime)/lifeTime; float scaleFactor = maxScale * (0.2f+prog); transform.localScale = Vector3.Scale(startScale.normalized, new Vector3(scaleFactor, 1, scaleFactor)); line.material.color = Color.Lerp(startColor, Color.clear, prog); } void OnTriggerEnter2D(Collider2D coll) { HitEdge(coll); } void OnTriggerExit2D(Collider2D coll) { HitEdge(coll); } void HitEdge(Collider2D coll) { Player p = coll.GetComponent<Player>(); if (p && p.team != owner.team) { p.rigidbody2D.AddForce(ForceForColl(coll), ForceMode2D.Impulse); p.hasKnockback = true; } // Flag f = coll.GetComponent<Flag>(); // if (f) { // f.Drop(); // Debug.Log(ForceForColl(coll)); // f.rigidbody2D.AddForce(ForceForColl(coll), ForceMode2D.Impulse); // } } Vector2 ForceForColl(Collider2D coll) { GameObject go = coll.gameObject; Vector2 toTarget = go.transform.position - transform.position; toTarget = toTarget.normalized * (maxScale - toTarget.magnitude); return toTarget * 10f; } }
mit
C#
6852b767e6384e02bea8787c79db017427a2fb9e
Add an extension point for defining more tables on a schema during SchemaBuilder.Build();
SilkStack/Silk.Data.SQL.ORM
Silk.Data.SQL.ORM/Schema/SchemaBuilder.cs
Silk.Data.SQL.ORM/Schema/SchemaBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using Silk.Data.SQL.ORM.Modelling; namespace Silk.Data.SQL.ORM.Schema { public class SchemaBuilder { private readonly List<EntitySchemaOptions> _entityTypes = new List<EntitySchemaOptions>(); protected virtual IEnumerable<Table> GetNonEntityTables(EntityModelCollection entityModels) => null; public EntitySchemaOptions<T> DefineEntity<T>() { var options = new EntitySchemaOptions<T>(this); _entityTypes.Add(options); return options; } public EntityModelTransformer GetModelTransformer(Type type) { var options = _entityTypes.FirstOrDefault(q => q.GetEntityModel().EntityType == type); if (options == null) return null; return options.ModelTransformer; } public Schema Build() { var fieldAdded = true; while (fieldAdded) { fieldAdded = false; foreach (var entityType in _entityTypes) { if (entityType.PerformTransformationPass()) fieldAdded = true; } } var entityModelCollection = new EntityModelCollection( _entityTypes.Select(q => q.GetEntityModel()) ); var tables = new List<Table>( entityModelCollection.Select(q => q.EntityTable) ); var schema = new Schema(entityModelCollection); foreach (var fieldWithBuildFinalizer in entityModelCollection.SelectMany(q => q.Fields) .OfType<IModelBuildFinalizerField>()) { fieldWithBuildFinalizer.FinalizeModelBuild(schema, tables); } foreach (var modelWithBuildFinalizer in entityModelCollection.OfType<IModelBuilderFinalizer>()) { modelWithBuildFinalizer.FinalizeBuiltModel(schema, tables); } var additionalTables = GetNonEntityTables(entityModelCollection); if (additionalTables != null) tables.AddRange(additionalTables); schema.SetTables(tables); return schema; } } }
using System; using System.Collections.Generic; using System.Linq; using Silk.Data.SQL.ORM.Modelling; namespace Silk.Data.SQL.ORM.Schema { public class SchemaBuilder { private readonly List<EntitySchemaOptions> _entityTypes = new List<EntitySchemaOptions>(); public EntitySchemaOptions<T> DefineEntity<T>() { var options = new EntitySchemaOptions<T>(this); _entityTypes.Add(options); return options; } public EntityModelTransformer GetModelTransformer(Type type) { var options = _entityTypes.FirstOrDefault(q => q.GetEntityModel().EntityType == type); if (options == null) return null; return options.ModelTransformer; } public Schema Build() { var fieldAdded = true; while (fieldAdded) { fieldAdded = false; foreach (var entityType in _entityTypes) { if (entityType.PerformTransformationPass()) fieldAdded = true; } } var entityModelCollection = new EntityModelCollection( _entityTypes.Select(q => q.GetEntityModel()) ); var tables = new List<Table>( entityModelCollection.Select(q => q.EntityTable) ); var schema = new Schema(entityModelCollection); foreach (var fieldWithBuildFinalizer in entityModelCollection.SelectMany(q => q.Fields) .OfType<IModelBuildFinalizerField>()) { fieldWithBuildFinalizer.FinalizeModelBuild(schema, tables); } foreach (var modelWithBuildFinalizer in entityModelCollection.OfType<IModelBuilderFinalizer>()) { modelWithBuildFinalizer.FinalizeBuiltModel(schema, tables); } schema.SetTables(tables); return schema; } } }
mit
C#
1f48378ce72b4036601eb09d0a6090ba51434d38
Add xmldoc to SnapFinder
UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,peppy/osu-new
osu.Game/Rulesets/Objects/SnapFinder.cs
osu.Game/Rulesets/Objects/SnapFinder.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Objects { /// <summary> /// Used to find the lowest beat divisor that a <see cref="HitObject"/> aligns to in an <see cref="IBeatmap"/> /// </summary> public class SnapFinder { private readonly IBeatmap beatmap; /// <summary> /// Creates a new SnapFinder instance. /// </summary> /// <param name="beatmap">The beatmap to align to when evaulating.</param> public SnapFinder(IBeatmap beatmap) { this.beatmap = beatmap; } private readonly static int[] snaps = { 1, 2, 3, 4, 6, 8, 12, 16 }; /// <summary> /// Finds the lowest beat divisor that the given HitObject aligns to. /// </summary> /// <param name="hitObject">The <see cref="HitObject"/> to evaluate.</param> public int FindSnap(HitObject hitObject) { TimingControlPoint currentTimingPoint = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime); double snapResult = (hitObject.StartTime - currentTimingPoint.Time) % (currentTimingPoint.BeatLength * 4); foreach (var snap in snaps) { if (almostDivisibleBy(snapResult, currentTimingPoint.BeatLength / (double)snap)) return snap; } return 0; } private const double leniency_ms = 1.0; private static bool almostDivisibleBy(double dividend, double divisor) { double remainder = Math.Abs(dividend) % divisor; return Precision.AlmostEquals(remainder, 0, leniency_ms) || Precision.AlmostEquals(remainder - divisor, 0, leniency_ms); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Rulesets.Objects { public class SnapFinder { private readonly IBeatmap beatmap; public SnapFinder(IBeatmap beatmap) { this.beatmap = beatmap; } private readonly static int[] snaps = { 1, 2, 3, 4, 6, 8, 12, 16 }; public int FindSnap(HitObject hitObject) { TimingControlPoint currentTimingPoint = beatmap.ControlPointInfo.TimingPointAt(hitObject.StartTime); double snapResult = (hitObject.StartTime - currentTimingPoint.Time) % (currentTimingPoint.BeatLength * 4); foreach (var snap in snaps) { if (almostDivisibleBy(snapResult, currentTimingPoint.BeatLength / (double)snap)) return snap; } return 0; } private const double leniency_ms = 1.0; private static bool almostDivisibleBy(double dividend, double divisor) { double remainder = Math.Abs(dividend) % divisor; return Precision.AlmostEquals(remainder, 0, leniency_ms) || Precision.AlmostEquals(remainder - divisor, 0, leniency_ms); } } }
mit
C#
b51e714ae5d5997bcc952ba8dc6cd53acf08c318
Fix xmldoc
peppy/osu,ppy/osu,ppy/osu,naoey/osu,DrabWeb/osu,UselessToucan/osu,smoogipoo/osu,DrabWeb/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,DrabWeb/osu,peppy/osu,EVAST9919/osu,smoogipoo/osu,2yangk23/osu,2yangk23/osu,naoey/osu,NeoAdonis/osu,naoey/osu,EVAST9919/osu,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,johnneijzen/osu,UselessToucan/osu,UselessToucan/osu,johnneijzen/osu
osu.Game/Rulesets/RulesetConfigCache.cs
osu.Game/Rulesets/RulesetConfigCache.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; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; namespace osu.Game.Rulesets { /// <summary> /// A cache that provides a single <see cref="IRulesetConfigManager"/> per-ruleset. /// This is done to support referring to and updating ruleset configs from multiple locations in the absence of inter-config bindings. /// </summary> public class RulesetConfigCache : Component { private readonly Dictionary<int, IRulesetConfigManager> configCache = new Dictionary<int, IRulesetConfigManager>(); private readonly SettingsStore settingsStore; public RulesetConfigCache(SettingsStore settingsStore) { this.settingsStore = settingsStore; } /// <summary> /// Retrieves the <see cref="IRulesetConfigManager"/> for a <see cref="Ruleset"/>. /// </summary> /// <param name="ruleset">The <see cref="Ruleset"/> to retrieve the <see cref="IRulesetConfigManager"/> for.</param> /// <returns>The <see cref="IRulesetConfigManager"/> defined by <paramref name="ruleset"/>, null if <paramref name="ruleset"/> doesn't define one.</returns> /// <exception cref="InvalidOperationException">If <paramref name="ruleset"/> doesn't have a valid <see cref="RulesetInfo.ID"/>.</exception> public IRulesetConfigManager GetConfigFor(Ruleset ruleset) { if (ruleset.RulesetInfo.ID == null) throw new InvalidOperationException("The provided ruleset doesn't have a valid id."); if (configCache.TryGetValue(ruleset.RulesetInfo.ID.Value, out var existing)) return existing; return configCache[ruleset.RulesetInfo.ID.Value] = ruleset.CreateConfig(settingsStore); } } }
// 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; using System.Collections.Generic; using osu.Framework.Graphics; using osu.Game.Configuration; using osu.Game.Rulesets.Configuration; namespace osu.Game.Rulesets { /// <summary> /// A cache that provides a single <see cref="IRulesetConfigManager"/> per-ruleset /// This is done to support referring to and updating ruleset configs from multiple locations in the absence of inter-config bindings. /// </summary> public class RulesetConfigCache : Component { private readonly Dictionary<int, IRulesetConfigManager> configCache = new Dictionary<int, IRulesetConfigManager>(); private readonly SettingsStore settingsStore; public RulesetConfigCache(SettingsStore settingsStore) { this.settingsStore = settingsStore; } /// <summary> /// Retrieves the <see cref="IRulesetConfigManager"/> for a <see cref="Ruleset"/>. /// </summary> /// <param name="ruleset">The <see cref="Ruleset"/> to retrieve the <see cref="IRulesetConfigManager"/> for.</param> /// <returns>The <see cref="IRulesetConfigManager"/> defined by <paramref name="ruleset"/>, null if <paramref name="ruleset"/> doesn't define one.</returns> /// <exception cref="InvalidOperationException">If <paramref name="ruleset"/> doesn't have a valid <see cref="RulesetInfo.ID"/>.</exception> public IRulesetConfigManager GetConfigFor(Ruleset ruleset) { if (ruleset.RulesetInfo.ID == null) throw new InvalidOperationException("The provided ruleset doesn't have a valid id."); if (configCache.TryGetValue(ruleset.RulesetInfo.ID.Value, out var existing)) return existing; return configCache[ruleset.RulesetInfo.ID.Value] = ruleset.CreateConfig(settingsStore); } } }
mit
C#
ae05b8de04303f9e9fd4fb54452d81912596158d
Prepare 0.6.2 release
LouisTakePILLz/ArgumentParser
ArgumentParser/Properties/AssemblyInfo.cs
ArgumentParser/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("ArgumentParser")] [assembly: AssemblyDescription("A rich and elegant library for parameter-parsing that supports various syntaxes and flavors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a67b27e2-8841-4951-a6f0-a00d93f59560")] // 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.6.2.0")] [assembly: AssemblyFileVersion("0.6.2.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ArgumentParser")] [assembly: AssemblyDescription("A rich and elegant library for parameter-parsing that supports various syntaxes and flavors.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("LouisTakePILLz")] [assembly: AssemblyProduct("ArgumentParser")] [assembly: AssemblyCopyright("Copyright © LouisTakePILLz 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a67b27e2-8841-4951-a6f0-a00d93f59560")] // 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.6.1.0")] [assembly: AssemblyFileVersion("0.6.1.0")]
apache-2.0
C#
b585267fe660283573a2cb0439b512fe63e1aa86
Update Startup.cs
stevejgordon/CorrelationId
samples/2.2/MvcSample/Startup.cs
samples/2.2/MvcSample/Startup.cs
using CorrelationId; using CorrelationId.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace MvcSample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDefaultCorrelationId(opt => opt.UpdateTraceIdentifier = true); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCorrelationId(); app.UseMvc(); } } }
using CorrelationId; using CorrelationId.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace MvcSample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDefaultCorrelationId(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseCorrelationId(new CorrelationIdOptions { UpdateTraceIdentifier = true }); app.UseMvc(); } } }
mit
C#
be4a8ab0be14b47566b366b7b266dd489d5441ad
add RecursiveDataStructuresStackOverflowTest
acple/ParsecSharp
UnitTest.ParsecSharp/StackOverflowTest.cs
UnitTest.ParsecSharp/StackOverflowTest.cs
#if !DEBUG using System; using System.Linq; using ChainingAssertion; using Microsoft.VisualStudio.TestTools.UnitTesting; using static ParsecSharp.Parser; using static ParsecSharp.Text; namespace UnitTest.ParsecSharp { [TestClass] [TestCategory("SkipWhenLiveUnitTesting")] public class StackOverflowTest { [TestMethod] public void SimpleRecursionStackOverflowTest() { // 単純な再帰ループ var parser = SkipMany(Any<int>()); var source = new int[1000000]; parser.Parse(source); } [TestMethod] public void ValueTypesStackOverflowTest() { // トークンが値型の場合 var parser = Many(Any<(int, int, int)>()); var source = Enumerable.Range(0, 1000000).Select(x => (x, x, x)); parser.Parse(source); } [TestMethod] public void ReferenceTypesStackOverflowTest() { // トークンが参照型の場合 var parser = Many(Any<Tuple<int, int, int>>()); var source = Enumerable.Range(0, 1000000).Select(x => Tuple.Create(x, x, x)); parser.Parse(source); } [TestMethod] public void RecursiveDataStructuresStackOverflowTest() { // 極端に深い構造を辿る場合 const int depth = 10000; var source = Enumerable.Repeat('[', depth).Concat(Enumerable.Repeat(']', depth)).ToArray(); var parser = Fix<char, int>(self => self.Or(Pure(1234)).Between(Char('['), Char(']'))).End(); parser.Parse(source).CaseOf( fail => Assert.Fail(fail.ToString()), success => success.Value.Is(1234)); } } } #endif
#if !DEBUG using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using static ParsecSharp.Parser; namespace UnitTest.ParsecSharp { [TestClass] [TestCategory("SkipWhenLiveUnitTesting")] public class StackOverflowTest { [TestMethod] public void SimpleRecursionStackOverflowTest() { // 単純な再帰ループ var parser = SkipMany(Any<int>()); var source = new int[1000000]; parser.Parse(source); } [TestMethod] public void ValueTypesStackOverflowTest() { // トークンが値型の場合 var parser = Many(Any<(int, int, int)>()); var source = Enumerable.Range(0, 1000000).Select(x => (x, x, x)); parser.Parse(source); } [TestMethod] public void ReferenceTypesStackOverflowTest() { // トークンが参照型の場合 var parser = Many(Any<Tuple<int, int, int>>()); var source = Enumerable.Range(0, 1000000).Select(x => Tuple.Create(x, x, x)); parser.Parse(source); } } } #endif
mit
C#
958a3d7798f1ceb5352bddbab4aab9d955c738c7
Fix path of libinfo file
nikeee/HolzShots
src/patch-version.csx
src/patch-version.csx
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; const string git = "git"; const string gitArgs = "describe --tags --long"; var libInfoFile = @"HolzShots.Common\LibraryInformation.cs"; Console.WriteLine($"Using Info File: {libInfoFile}"); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = git, Arguments = gitArgs, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); var gitOutput = proc.StandardOutput.ReadToEnd(); // Sample: // v0.1.0-0-gfe83453 var m = Regex.Match(gitOutput, @"v(?<version>.*)-(?<commits>\d+)-(?<hash>[A-Za-z0-9]+)"); if (!m.Success) throw new InvalidDataException($"invalid match"); var version = m.Groups["version"].Value; var commits = m.Groups["commits"].Value; var hash = m.Groups["hash"].Value; if (string.IsNullOrWhiteSpace(version)) throw new InvalidDataException($"invalid {nameof(version)}"); if (string.IsNullOrWhiteSpace(commits)) throw new InvalidDataException($"invalid {nameof(commits)}"); if (string.IsNullOrWhiteSpace(hash)) throw new InvalidDataException($"invalid {nameof(hash)}"); var buildDate = DateTime.Now.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture); var info = File.ReadAllText(libInfoFile); var newInfo = info.Replace("%VERSION%", version) .Replace("%COMMITS-SINCE-TAG%", commits) .Replace("%COMMIT-ID%", hash) .Replace("%BUILD-DATE%", buildDate); Console.WriteLine($"Version: {version}"); Console.WriteLine($"Commits since tag: {commits}"); Console.WriteLine($"Commit ID: {hash}"); Console.WriteLine($"Build Date: {buildDate}"); File.WriteAllText(libInfoFile, newInfo);
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; const string git = "git"; const string gitArgs = "describe --tags --long"; var libInfoFile = @"src\HolzShots.Common\LibraryInformation.cs"; Console.WriteLine($"Using Info File: {libInfoFile}"); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = git, Arguments = gitArgs, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); var gitOutput = proc.StandardOutput.ReadToEnd(); // Sample: // v0.1.0-0-gfe83453 var m = Regex.Match(gitOutput, @"v(?<version>.*)-(?<commits>\d+)-(?<hash>[A-Za-z0-9]+)"); if (!m.Success) throw new InvalidDataException($"invalid match"); var version = m.Groups["version"].Value; var commits = m.Groups["commits"].Value; var hash = m.Groups["hash"].Value; if (string.IsNullOrWhiteSpace(version)) throw new InvalidDataException($"invalid {nameof(version)}"); if (string.IsNullOrWhiteSpace(commits)) throw new InvalidDataException($"invalid {nameof(commits)}"); if (string.IsNullOrWhiteSpace(hash)) throw new InvalidDataException($"invalid {nameof(hash)}"); var buildDate = DateTime.Now.ToString("MM/dd/yyyy", System.Globalization.CultureInfo.InvariantCulture); var info = File.ReadAllText(libInfoFile); var newInfo = info.Replace("%VERSION%", version) .Replace("%COMMITS-SINCE-TAG%", commits) .Replace("%COMMIT-ID%", hash) .Replace("%BUILD-DATE%", buildDate); Console.WriteLine($"Version: {version}"); Console.WriteLine($"Commits since tag: {commits}"); Console.WriteLine($"Commit ID: {hash}"); Console.WriteLine($"Build Date: {buildDate}"); File.WriteAllText(libInfoFile, newInfo);
agpl-3.0
C#
345e30f2f019f6fed9060ba681b1693845174450
Add tooltips to the Settings asset
loicteixeira/gj-unity-api
Assets/Plugins/GameJolt/Scripts/API/Settings.cs
Assets/Plugins/GameJolt/Scripts/API/Settings.cs
using UnityEngine; namespace GameJolt.API { [System.Serializable] public class Settings : ScriptableObject { [Header("Game")] [Tooltip("The game ID. It can be found on the Game Jolt website under Dashboard > YOUR-GAME > Game API > API Settings.")] public int gameID; [Tooltip("The game Private Key. It can be found on the Game Jolt website under Dashboard > YOUR-GAME > Game API > API Settings.")] public string privateKey; [Header("Settings")] [Tooltip("The time in seconds before an API call should timeout and return failure.")] public float timeout = 10f; [Tooltip("Automatically create and ping sessions once a user has been authentified.")] public bool autoPing = true; [Tooltip("Cache High Score Tables and Trophies information for faster display.")] public bool useCaching = true; [Header("Debug")] [Tooltip("AutoConnect in the Editor as if the game was hosted on GameJolt.")] public bool autoConnect = false; [Tooltip("The username to use for AutoConnect.")] public string user; [Tooltip("The token to use for AutoConnect.")] public string token; } }
using UnityEngine; namespace GameJolt.API { [System.Serializable] public class Settings : ScriptableObject { [Header("Game")] public int gameID; public string privateKey; [Header("Settings")] public float timeout = 10f; public bool autoPing = true; public bool useCaching = true; [Header("Debug")] public bool autoConnect = false; public string user; public string token; } }
mit
C#
c4dc4e80493d15382e5ccf99b7d2bef4ef62dedf
Fix CCLog compile error on Windows platforms. Windows gives an error while assigning Debug.WriteLine to a delegate where Xamarin is not as stringent.
zmaruo/CocosSharp,zmaruo/CocosSharp,haithemaraissia/CocosSharp,mono/CocosSharp,TukekeSoft/CocosSharp,MSylvia/CocosSharp,TukekeSoft/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp
src/platform/CCLog.cs
src/platform/CCLog.cs
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Diagnostics; namespace CocosSharp { public static class CCLog { public delegate void LogDelegate (string value, params object[] args); public static LogDelegate Logger; static CCLog () { Logger = (format, args) => { Debug.WriteLine(format, args); }; } public static void Log(string format, params object[] args) { var localLogAction = Logger; if (localLogAction != null) localLogAction.Invoke(format, args); } } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Diagnostics; namespace CocosSharp { public static class CCLog { public delegate void LogDelegate (string value, params object[] args); public static LogDelegate Logger; static CCLog () { #if DEBUG Logger = Debug.WriteLine; #endif } public static void Log(string format, params object[] args) { var localLogAction = Logger; if (localLogAction != null) localLogAction.Invoke(format, args); } } }
mit
C#
a85049ec558d79797ccf78448e628f04f2e9652c
Add checking for end of text
lzcd/LeanGoldfish
LeanGoldfish/IsCharacter.cs
LeanGoldfish/IsCharacter.cs
using System; namespace LeanGoldfish { public class IsCharacter : ParsingUnit { private char character; public IsCharacter(char character) { this.character = character; } internal override ParsingResult TryParse(string text, int position) { if (position >= text.Length || text[position] != character) { return new ParsingResult() { Succeeded = false, StartPosition = position, EndPosition = position }; } return new ParsingResult() { Succeeded = true, StartPosition = position, EndPosition = position }; } } }
using System; namespace LeanGoldfish { public class IsCharacter : ParsingUnit { private char character; public IsCharacter(char character) { this.character = character; } internal override ParsingResult TryParse(string text, int position) { if (text[position] != character) { return new ParsingResult() { Succeeded = false, StartPosition = position, EndPosition = position }; } return new ParsingResult() { Succeeded = true, StartPosition = position, EndPosition = position }; } } }
mit
C#
3d7dae1f70cfe46550a3e437513f2cfc714ed582
Initialize TypeNameMatcher with a collection of candidate types
appharbor/appharbor-cli
src/AppHarbor/TypeNameMatcher.cs
src/AppHarbor/TypeNameMatcher.cs
using System; using System.Collections.Generic; namespace AppHarbor { public class TypeNameMatcher { private readonly IEnumerable<Type> _candidateTypes; public TypeNameMatcher(IEnumerable<Type> candidateTypes) { _candidateTypes = candidateTypes; } } }
namespace AppHarbor { public class TypeNameMatcher { } }
mit
C#
8c7d905154fccb998d904ed426dd368f808f474c
use a queueingBasicConsumer so we can support timeouts
Pondidum/RabbitHarness,Pondidum/RabbitHarness
RabbitHarness/Extensions.cs
RabbitHarness/Extensions.cs
using System; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace RabbitHarness { public static class Extensions { public static void Query<TResponse>(this ConnectionFactory factory, string queueName, object message, Action<ResponseContext<TResponse>> callback) { var context = new QueryContext { QueueName = queueName, }; factory.Query(context, message, callback); } public static void Query<TResponse>(this ConnectionFactory factory, QueryContext context, object message, Action<ResponseContext<TResponse>> callback) { var connection = context.CreateConnection(factory); var channel = connection.CreateModel(); var correlationID = context.CreateCorrelationId(); var replyTo = channel.QueueDeclare().QueueName; var t = new Task(() => { var listener = new QueueingBasicConsumer(channel); channel.BasicConsume(replyTo, true, listener); try { while (true) { var e = listener.Queue.Dequeue(); if (e.BasicProperties.CorrelationId != correlationID) continue; var rc = new ResponseContext<TResponse> { Content = MessageFrom<TResponse>(e.Body), Headers = e.BasicProperties, }; callback(rc); } } finally { channel.Dispose(); connection.Dispose(); } }); var props = channel.CreateBasicProperties(); props.CorrelationId = correlationID; props.ReplyTo = replyTo; context.CustomiseProperties(props); t.Start(); channel.BasicPublish( exchange: context.ExchangeName, routingKey: context.QueueName, basicProperties: props, body: BodyFrom(message)); } private static byte[] BodyFrom(object message) { var json = JsonConvert.SerializeObject(message); return Encoding.UTF8.GetBytes(json); } private static T MessageFrom<T>(byte[] body) { var json = Encoding.UTF8.GetString(body); return JsonConvert.DeserializeObject<T>(json); } } }
using System; using System.Text; using Newtonsoft.Json; using RabbitMQ.Client; using RabbitMQ.Client.Events; namespace RabbitHarness { public static class Extensions { public static void Query<TResponse>(this ConnectionFactory factory, string queueName, object message, Action<ResponseContext<TResponse>> callback) { var context = new QueryContext { QueueName = queueName, }; factory.Query(context, message, callback); } public static void Query<TResponse>(this ConnectionFactory factory, QueryContext context, object message, Action<ResponseContext<TResponse>> callback) { var connection = context.CreateConnection(factory); var channel = connection.CreateModel(); var correlationID = context.CreateCorrelationId(); var replyTo = channel.QueueDeclare().QueueName; var listener = new EventingBasicConsumer(channel); channel.BasicConsume(replyTo, true, listener); listener.Received += (s, e) => { if (e.BasicProperties.CorrelationId != correlationID) return; try { var rc = new ResponseContext<TResponse> { Content = MessageFrom<TResponse>(e.Body), Headers = e.BasicProperties, }; callback(rc); } finally { channel.Dispose(); connection.Dispose(); } }; var props = channel.CreateBasicProperties(); props.CorrelationId = correlationID; props.ReplyTo = replyTo; context.CustomiseProperties(props); channel.BasicPublish( exchange: context.ExchangeName, routingKey: context.QueueName, basicProperties: props, body: BodyFrom(message)); } private static byte[] BodyFrom(object message) { var json = JsonConvert.SerializeObject(message); return Encoding.UTF8.GetBytes(json); } private static T MessageFrom<T>(byte[] body) { var json = Encoding.UTF8.GetString(body); return JsonConvert.DeserializeObject<T>(json); } } }
lgpl-2.1
C#
1f10b62077b0aa9adad1d53f9e1261beddca233c
Change highlight.js style
stvnhrlnd/SH,stvnhrlnd/SH,stvnhrlnd/SH
SH.Site/Views/Master.cshtml
SH.Site/Views/Master.cshtml
@inherits UmbracoViewPage<IMaster> @{ var website = Model.Ancestor<Website>(); var menuItems = website.Children<IMaster>(); } <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@Model.SeoMetadata.Title</title> <meta name="description" content="@Model.SeoMetadata.Description" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" /> <link rel="stylesheet" href="//yui.yahooapis.com/pure/0.6.0/pure-min.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/monokai-sublime.min.css" /> <link rel="stylesheet" href="~/css/base.css" /> <link rel="stylesheet" href="~/css/layout/main.css" /> <link rel="stylesheet" href="~/css/layout/menu.css" /> <link rel="stylesheet" href="~/css/components/header.css" /> <link rel="stylesheet" href="~/css/components/post.css" /> </head> <body> <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@website.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in menuItems) { var selected = Model.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div> <div id="main"> @RenderBody() </div> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script> <script src="~/scripts/highlighting.js"></script> <script src="~/scripts/menu.js"></script> </body> </html>
@inherits UmbracoViewPage<IMaster> @{ var website = Model.Ancestor<Website>(); var menuItems = website.Children<IMaster>(); } <!doctype html> <html lang="en"> <head> <meta charset="utf-8" /> <title>@Model.SeoMetadata.Title</title> <meta name="description" content="@Model.SeoMetadata.Description" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" /> <link rel="stylesheet" href="//yui.yahooapis.com/pure/0.6.0/pure-min.css" /> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/styles/default.min.css" /> <link rel="stylesheet" href="~/css/base.css" /> <link rel="stylesheet" href="~/css/layout/main.css" /> <link rel="stylesheet" href="~/css/layout/menu.css" /> <link rel="stylesheet" href="~/css/components/header.css" /> <link rel="stylesheet" href="~/css/components/post.css" /> </head> <body> <a href="#menu" id="menu-link"> <i class="fa fa-bars" aria-hidden="true"></i> <i class="fa fa-times" aria-hidden="true"></i> </a> <div id="menu"> <div class="pure-menu"> <span class="pure-menu-heading">@website.SiteName</span> <ul class="pure-menu-list"> @foreach (var item in menuItems) { var selected = Model.Path.Split(',').Select(int.Parse).Contains(item.Id); <li class="pure-menu-item @(selected ? "pure-menu-selected": "")"> <a href="@item.Url" class="pure-menu-link"> @item.Name </a> </li> } </ul> </div> </div> <div id="main"> @RenderBody() </div> <script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.3.0/highlight.min.js"></script> <script src="~/scripts/highlighting.js"></script> <script src="~/scripts/menu.js"></script> </body> </html>
mit
C#
4af41e326baa9efa939b74a77936eda4da007ea3
fix missing field
kerzyte/OWLib,overtools/OWLib
STULib/STUFieldAttribute.cs
STULib/STUFieldAttribute.cs
using System; namespace STULib { [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class STUFieldAttribute : Attribute { public bool ReferenceArray = false; public bool ReferenceValue = false; public object Verify = null; public uint Checksum = 0; public uint[] STUVersionOnly = null; public STUFieldAttribute() {} public STUFieldAttribute(uint Checksum) { this.Checksum = Checksum; } } }
using System; namespace STULib { [AttributeUsage(AttributeTargets.Field, AllowMultiple = false, Inherited = true)] public class STUFieldAttribute : Attribute { public bool ReferenceArray = false; public bool ReferenceValue = false; public object Verify = null; public uint Checksum = 0; public uint[] STUVersionOnly = null; public STUFieldAttribute() {} public STUFieldAttribute(uint Checksum) { this.Checksum = Checksum; } public STUFieldAttribute(uint Checksum, params string[] DependsOn) { this.Checksum = Checksum; this.DependsOn = DependsOn; } } }
mit
C#
6be31d1e6024628760e848206f0d3ab335969925
Join up hardcoded lines in a Row
12joan/hangman
row.cs
row.cs
using System; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return String.Join("\n", Lines()); } public string[] Lines() { return new string[] { "Line 1", "Line 2" }; } } }
using System; namespace Hangman { public class Row { public Cell[] Cells; public Row(Cell[] cells) { Cells = cells; } public string Draw(int width) { // return new String(' ', width - Text.Length) + Text; return "I have many cells!"; } } }
unlicense
C#
c9ae0a7fa434a7266f33ca5281670b86842c2571
Remove magic number.
scopely/msgpack-cli,scopely/msgpack-cli,undeadlabs/msgpack-cli,msgpack/msgpack-cli,modulexcite/msgpack-cli,msgpack/msgpack-cli,modulexcite/msgpack-cli,undeadlabs/msgpack-cli
cli/src/MsgPack/Serialization/DataMemberContract.cs
cli/src/MsgPack/Serialization/DataMemberContract.cs
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Diagnostics.Contracts; using System.Reflection; using System.Runtime.Serialization; namespace MsgPack.Serialization { /// <summary> /// Represents member's data contract. /// </summary> internal struct DataMemberContract { internal const int UnspecifiedOrder = -1; private readonly MemberInfo _member; private readonly DataMemberAttribute _attribute; /// <summary> /// Gets the name of the member. /// </summary> /// <value> /// The name of the member. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public string Name { get { return this._attribute == null ? this._member.Name : ( this._attribute.Name ?? this._member.Name ); } } /// <summary> /// Gets the order of the member. /// </summary> /// <value> /// The order of the member. Default is <c>-1</c>. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public int Order { get { return this._attribute == null ? UnspecifiedOrder : this._attribute.Order; } } // TODO: IsRequired /// <summary> /// Gets a value indicating whether this instance is required. /// </summary> /// <value> /// <c>true</c> if this instance is required; otherwise, <c>false</c>. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public bool IsRequired { get { return this._attribute == null ? false : this._attribute.IsRequired; } } // TODO: EmitDefaultValue /// <summary> /// Gets a value indicating whether emits default value or not. /// </summary> /// <value> /// <c>true</c> if emits default value; otherwise, <c>false</c>. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public bool EmitDefaultValue { get { return this._attribute == null ? true : this._attribute.EmitDefaultValue; } } /// <summary> /// Initializes a new instance of the <see cref="DataMemberContract"/> struct. /// </summary> /// <param name="member">The target member.</param> /// <param name="attribute">The data contract member attribute. This value can be <c>null</c>.</param> public DataMemberContract( MemberInfo member, DataMemberAttribute attribute ) { Contract.Assert( member != null ); this._member = member; this._attribute = attribute; } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- using System; using System.Reflection; using System.Runtime.Serialization; using System.Diagnostics.Contracts; namespace MsgPack.Serialization { /// <summary> /// Represents member's data contract. /// </summary> internal struct DataMemberContract { private readonly MemberInfo _member; private readonly DataMemberAttribute _attribute; /// <summary> /// Gets the name of the member. /// </summary> /// <value> /// The name of the member. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public string Name { get { return this._attribute == null ? this._member.Name : ( this._attribute.Name ?? this._member.Name ); } } /// <summary> /// Gets the order of the member. /// </summary> /// <value> /// The order of the member. Default is <c>-1</c>. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public int Order { get { return this._attribute == null ? -1 : this._attribute.Order; } } // TODO: IsRequired /// <summary> /// Gets a value indicating whether this instance is required. /// </summary> /// <value> /// <c>true</c> if this instance is required; otherwise, <c>false</c>. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public bool IsRequired { get { return this._attribute == null ? false : this._attribute.IsRequired; } } // TODO: EmitDefaultValue /// <summary> /// Gets a value indicating whether emits default value or not. /// </summary> /// <value> /// <c>true</c> if emits default value; otherwise, <c>false</c>. /// </value> /// <seealso cref="System.Runtime.Serialization.DataMemberAttribute"/> public bool EmitDefaultValue { get { return this._attribute == null ? true : this._attribute.EmitDefaultValue; } } /// <summary> /// Initializes a new instance of the <see cref="DataMemberContract"/> struct. /// </summary> /// <param name="member">The target member.</param> /// <param name="attribute">The data contract member attribute. This value can be <c>null</c>.</param> public DataMemberContract( MemberInfo member, DataMemberAttribute attribute ) { Contract.Assert( member != null ); this._member = member; this._attribute = attribute; } } }
apache-2.0
C#
1e50cb7767e58e9e2780ef25e7c0cde4c3ce9bbf
Remove redundant partial classes
cwensley/maccore,mono/maccore,jorik041/maccore
src/CoreImage/Enums.cs
src/CoreImage/Enums.cs
// // Copyright 2011, Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace MonoMac.CoreImage { public enum CIImageOrientation { TopLeft = 1, TopRight = 2, BottomRight = 3, BottomLeft = 4, LeftTop = 5, RightTop = 6, RightBottom = 7, LeftBottom = 8 } }
// // Copyright 2011, Xamarin, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; namespace MonoMac.CoreImage { public enum CIImageOrientation { TopLeft = 1, TopRight = 2, BottomRight = 3, BottomLeft = 4, LeftTop = 5, RightTop = 6, RightBottom = 7, LeftBottom = 8 } public static partial class CIFilterAttributes {} public static partial class CIFilterCategory {} public static partial class CIFilterInputKey {} public static partial class CIFilterOutputKey {} }
apache-2.0
C#