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
09080d8e2ed771e677cf51b826bab877b4f2e39d
Change name of marketplaceBankAccount
balanced/balanced-csharp
scenarios/snippets/order-credit-marketplace.cs
scenarios/snippets/order-credit-marketplace.cs
BankAccount marketplaceBankAccount = Marketplace.Mine.owner_customer.bank_accounts.First(); Dictionary<string, object> creditPayload = new Dictionary<string, object>(); creditPayload.Add("amount", 2000); creditPayload.Add("description", "Credit from order escrow to marketplace bank account"); Credit credit = order.CreditTo(marketplaceBankAccount, creditPayload);
BankAccount marketplaceAccount = Marketplace.Mine.owner_customer.bank_accounts.First(); Dictionary<string, object> creditPayload = new Dictionary<string, object>(); creditPayload.Add("amount", 2000); creditPayload.Add("description", "Credit from order escrow to marketplace bank account"); Credit credit = order.CreditTo(marketplaceAccount, creditPayload);
mit
C#
eb5211e7a50b8f30c58e0f197901b12e6573edbf
Switch the option on push command to be false by default. This makes it cleaner to turn off publishing. "nuget push -co vs. nuget push -pub-"
mono/nuget,GearedToWar/NuGet2,mrward/NuGet.V2,mrward/NuGet.V2,jmezach/NuGet2,antiufo/NuGet2,pratikkagda/nuget,pratikkagda/nuget,OneGet/nuget,chester89/nugetApi,antiufo/NuGet2,OneGet/nuget,mrward/nuget,oliver-feng/nuget,mrward/NuGet.V2,kumavis/NuGet,OneGet/nuget,ctaggart/nuget,mrward/NuGet.V2,mrward/nuget,RichiCoder1/nuget-chocolatey,xoofx/NuGet,antiufo/NuGet2,rikoe/nuget,dolkensp/node.net,jholovacs/NuGet,alluran/node.net,pratikkagda/nuget,anurse/NuGet,zskullz/nuget,antiufo/NuGet2,chocolatey/nuget-chocolatey,GearedToWar/NuGet2,mrward/nuget,chester89/nugetApi,jholovacs/NuGet,indsoft/NuGet2,pratikkagda/nuget,indsoft/NuGet2,jmezach/NuGet2,GearedToWar/NuGet2,rikoe/nuget,atheken/nuget,jmezach/NuGet2,RichiCoder1/nuget-chocolatey,pratikkagda/nuget,jmezach/NuGet2,jholovacs/NuGet,chocolatey/nuget-chocolatey,themotleyfool/NuGet,themotleyfool/NuGet,mono/nuget,GearedToWar/NuGet2,GearedToWar/NuGet2,mrward/nuget,mrward/nuget,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,themotleyfool/NuGet,RichiCoder1/nuget-chocolatey,indsoft/NuGet2,ctaggart/nuget,jholovacs/NuGet,mrward/NuGet.V2,jholovacs/NuGet,indsoft/NuGet2,xoofx/NuGet,dolkensp/node.net,zskullz/nuget,mono/nuget,mono/nuget,chocolatey/nuget-chocolatey,mrward/nuget,indsoft/NuGet2,GearedToWar/NuGet2,mrward/NuGet.V2,RichiCoder1/nuget-chocolatey,oliver-feng/nuget,ctaggart/nuget,xoofx/NuGet,zskullz/nuget,anurse/NuGet,xoofx/NuGet,alluran/node.net,antiufo/NuGet2,oliver-feng/nuget,oliver-feng/nuget,chocolatey/nuget-chocolatey,kumavis/NuGet,zskullz/nuget,rikoe/nuget,jmezach/NuGet2,alluran/node.net,akrisiun/NuGet,xero-github/Nuget,dolkensp/node.net,RichiCoder1/nuget-chocolatey,dolkensp/node.net,OneGet/nuget,jmezach/NuGet2,xoofx/NuGet,oliver-feng/nuget,chocolatey/nuget-chocolatey,akrisiun/NuGet,jholovacs/NuGet,indsoft/NuGet2,alluran/node.net,chocolatey/nuget-chocolatey,atheken/nuget,xoofx/NuGet,antiufo/NuGet2,oliver-feng/nuget,rikoe/nuget,ctaggart/nuget
src/CommandLine/Commands/PushCommand.cs
src/CommandLine/Commands/PushCommand.cs
namespace NuGet.Commands { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using NuGet.Common; [Export(typeof(ICommand))] [Command(typeof(NuGetResources), "push", "PushCommandDescription", AltName="pu", MinArgs = 2, MaxArgs = 2, UsageDescriptionResourceName = "PushCommandUsageDescription", UsageSummaryResourceName = "PushCommandUsageSummary")] public class PushCommand : Command { private string _apiKey; private string _packagePath; [Option(typeof(NuGetResources), "PushCommandPublishDescription", AltName = "co")] public bool CreateOnly { get; set; } [Option(typeof(NuGetResources), "PushCommandSourceDescription", AltName = "src")] public string Source { get; set; } public PushCommand() { CreateOnly = true; } public override void ExecuteCommand() { //Frist argument should be the package _packagePath = Arguments[0]; //Second argument should be the API Key _apiKey = Arguments[1]; GalleryServer gallery; if (String.IsNullOrEmpty(Source)) { gallery = new GalleryServer(); } else { gallery = new GalleryServer(Source); } ZipPackage pkg = new ZipPackage(_packagePath); Console.WriteLine(NuGetResources.PushCommandCreatingPackage, pkg.Id, pkg.Version); using (Stream pkgStream = pkg.GetStream()) { gallery.CreatePackage(_apiKey, pkgStream); } Console.WriteLine(NuGetResources.PushCommandPackageCreated); if (!CreateOnly) { var cmd = new PublishCommand(); cmd.Console = Console; cmd.Source = Source; cmd.Arguments = new List<string> { pkg.Id, pkg.Version.ToString(), _apiKey }; cmd.Execute(); } } } }
namespace NuGet.Commands { using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.IO; using NuGet.Common; [Export(typeof(ICommand))] [Command(typeof(NuGetResources), "push", "PushCommandDescription", AltName="pu", MinArgs = 2, MaxArgs = 2, UsageDescriptionResourceName = "PushCommandUsageDescription", UsageSummaryResourceName = "PushCommandUsageSummary")] public class PushCommand : Command { private string _apiKey; private string _packagePath; [Option(typeof(NuGetResources), "PushCommandPublishDescription", AltName = "pub")] public bool Publish { get; set; } [Option(typeof(NuGetResources), "PushCommandSourceDescription", AltName = "src")] public string Source { get; set; } public PushCommand() { Publish = true; } public override void ExecuteCommand() { //Frist argument should be the package _packagePath = Arguments[0]; //Second argument should be the API Key _apiKey = Arguments[1]; GalleryServer gallery; if (String.IsNullOrEmpty(Source)) { gallery = new GalleryServer(); } else { gallery = new GalleryServer(Source); } ZipPackage pkg = new ZipPackage(_packagePath); Console.WriteLine(NuGetResources.PushCommandCreatingPackage, pkg.Id, pkg.Version); using (Stream pkgStream = pkg.GetStream()) { gallery.CreatePackage(_apiKey, pkgStream); } Console.WriteLine(NuGetResources.PushCommandPackageCreated); if (Publish) { var cmd = new PublishCommand(); cmd.Console = Console; cmd.Source = Source; cmd.Arguments = new List<string> { pkg.Id, pkg.Version.ToString(), _apiKey }; cmd.Execute(); } } } }
apache-2.0
C#
7b834d88e77b0b067a62972ac0257915e1e71b6e
Update PageControl.xaml.cs
Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D.UI/Views/PageControl.xaml.cs
src/Core2D.UI/Views/PageControl.xaml.cs
using Avalonia.Controls; using Avalonia.Controls.PanAndZoom; using Avalonia.Markup.Xaml; namespace Core2D.UI.Views { /// <summary> /// Interaction logic for <see cref="PageControl"/> xaml. /// </summary> public class PageControl : UserControl { private ScrollViewer _scrollViewer; private ZoomBorder _zoomBorder; private PresenterControl _presenterControlData; private PresenterControl _presenterControlTemplate; private PresenterControl _presenterControlEditor; //private TextBox _textEditor; /// <summary> /// Initializes a new instance of the <see cref="PageControl"/> class. /// </summary> public PageControl() { InitializeComponent(); _scrollViewer = this.FindControl<ScrollViewer>("scrollViewer"); _zoomBorder = this.FindControl<ZoomBorder>("zoomBorder"); _presenterControlData = this.FindControl<PresenterControl>("presenterControlData"); _presenterControlTemplate = this.FindControl<PresenterControl>("presenterControlTemplate"); _presenterControlEditor = this.FindControl<PresenterControl>("presenterControlEditor"); //_textEditor = this.FindControl<TextBox>("textEditor"); } /// <summary> /// Initialize the Xaml components. /// </summary> private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
using Avalonia.Controls; using Avalonia.Controls.PanAndZoom; using Avalonia.Markup.Xaml; namespace Core2D.UI.Views { /// <summary> /// Interaction logic for <see cref="PageControl"/> xaml. /// </summary> public class PageControl : UserControl { private ScrollViewer _scrollViewer; private ZoomBorder _zoomBorder; private PresenterControl _presenterControlData; private PresenterControl _presenterControlTemplate; private PresenterControl _presenterControlEditor; /// <summary> /// Initializes a new instance of the <see cref="PageControl"/> class. /// </summary> public PageControl() { InitializeComponent(); _scrollViewer = this.FindControl<ScrollViewer>("scrollViewer"); _zoomBorder = this.FindControl<ZoomBorder>("zoomBorder"); _presenterControlData = this.FindControl<PresenterControl>("presenterControlData"); _presenterControlTemplate = this.FindControl<PresenterControl>("presenterControlTemplate"); _presenterControlEditor = this.FindControl<PresenterControl>("presenterControlEditor"); } /// <summary> /// Initialize the Xaml components. /// </summary> private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } }
mit
C#
3a872eac896fc5dac3cdae5196f1bffa43b0407c
Add permission and remarks
Auxes/Dogey
src/Dogey.SQLite/Modules/GuildModule.cs
src/Dogey.SQLite/Modules/GuildModule.cs
using Discord; using Discord.Commands; using System.Threading.Tasks; namespace Dogey.SQLite.Modules { public class GuildModule : ModuleBase<SocketCommandContext> { private ConfigDatabase _db; protected override void BeforeExecute() { _db = new ConfigDatabase(); } protected override void AfterExecute() { _db.Dispose(); } [Command("prefix")] [Remarks("Check what prefix this guild has configured.")] public async Task PrefixAsync() { var config = await _db.GetConfigAsync(Context.Guild.Id); if (config.Prefix == null) await ReplyAsync("This guild has no prefix"); else await ReplyAsync($"This guild's prefix is `{config.Prefix}`"); } [Command("setprefix")] [Remarks("Change or remove this guild's string prefix.")] [RequireUserPermission(GuildPermission.Administrator)] public async Task SetPrefixAsync([Remainder]string prefix) { var config = await _db.GetConfigAsync(Context.Guild.Id); await _db.SetPrefixAsync(config, prefix); await ReplyAsync($"This guild's prefix is now `{prefix}`"); } } }
using Discord.Commands; using System.Threading.Tasks; namespace Dogey.SQLite.Modules { public class GuildModule : ModuleBase<SocketCommandContext> { private ConfigDatabase _db; protected override void BeforeExecute() { _db = new ConfigDatabase(); } protected override void AfterExecute() { _db.Dispose(); } [Command("prefix")] public async Task PrefixAsync() { var config = await _db.GetConfigAsync(Context.Guild.Id); if (config.Prefix == null) await ReplyAsync("This guild has no prefix"); else await ReplyAsync($"This guild's prefix is `{config.Prefix}`"); } [Command("setprefix")] public async Task SetPrefixAsync([Remainder]string prefix) { var config = await _db.GetConfigAsync(Context.Guild.Id); await _db.SetPrefixAsync(config, prefix); await ReplyAsync($"This guild's prefix is now `{prefix}`"); } } }
apache-2.0
C#
de07804952c2de14b01835f3ed2e5263b440de91
Fix for blinking tests issue
pshort/nsupertest
NSuperTest/Registration/RegistrationDiscoverer.cs
NSuperTest/Registration/RegistrationDiscoverer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace NSuperTest.Registration { public static class AssemblyExtensions { public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) { try { return assembly.GetTypes(); } catch (ReflectionTypeLoadException e) { return e.Types.Where(t => t != null); } } } public class RegistrationDiscoverer { public IEnumerable<IRegisterServers> FindRegistrations() { var type = typeof(IRegisterServers); var registries = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetLoadableTypes()) .Where(t => type.IsAssignableFrom(t) && !t.IsInterface) .Select(t => Activator.CreateInstance(t) as IRegisterServers); return registries; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NSuperTest.Registration { public class RegistrationDiscoverer { public IEnumerable<IRegisterServers> FindRegistrations() { var type = typeof(IRegisterServers); var registries = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where(t => type.IsAssignableFrom(t) && !t.IsInterface) .Select(t => Activator.CreateInstance(t) as IRegisterServers); return registries; } } }
mit
C#
1aa0a826e8aea16f771b036db559aa563a1e6903
Raise an exception when the returned value is null.
dlemstra/Magick.NET,dlemstra/Magick.NET
src/Magick.NET/Native/NativeInstance.cs
src/Magick.NET/Native/NativeInstance.cs
// Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using System; namespace ImageMagick { internal abstract class NativeInstance : NativeHelper, INativeInstance, IDisposable { private IntPtr _instance = IntPtr.Zero; public static INativeInstance Zero => new ZeroInstance(); public IntPtr Instance { get { if (_instance == IntPtr.Zero) throw new ObjectDisposedException(TypeName); return _instance; } set { if (_instance != IntPtr.Zero) Dispose(_instance); _instance = value; } } public bool IsDisposed => _instance == IntPtr.Zero; protected abstract string TypeName { get; } public void Dispose() { Instance = IntPtr.Zero; GC.SuppressFinalize(this); } protected abstract void Dispose(IntPtr instance); protected void CheckException(IntPtr exception, IntPtr result) { var magickException = MagickExceptionHelper.Create(exception); if (magickException == null) return; if (magickException is MagickErrorException) { if (result != IntPtr.Zero) Dispose(result); throw magickException; } RaiseWarning(magickException); if (result == IntPtr.Zero) throw new MagickErrorException("The operation returned null but did not raise an exception."); } private class ZeroInstance : INativeInstance { public IntPtr Instance => IntPtr.Zero; public void Dispose() { } } } }
// Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. using System; namespace ImageMagick { internal abstract class NativeInstance : NativeHelper, INativeInstance, IDisposable { private IntPtr _instance = IntPtr.Zero; public static INativeInstance Zero => new ZeroInstance(); public IntPtr Instance { get { if (_instance == IntPtr.Zero) throw new ObjectDisposedException(TypeName); return _instance; } set { if (_instance != IntPtr.Zero) Dispose(_instance); _instance = value; } } public bool IsDisposed => _instance == IntPtr.Zero; protected abstract string TypeName { get; } public void Dispose() { Instance = IntPtr.Zero; GC.SuppressFinalize(this); } protected abstract void Dispose(IntPtr instance); protected void CheckException(IntPtr exception, IntPtr result) { var magickException = MagickExceptionHelper.Create(exception); if (magickException == null) return; if (magickException is MagickErrorException) { if (result != IntPtr.Zero) Dispose(result); throw magickException; } RaiseWarning(magickException); } private class ZeroInstance : INativeInstance { public IntPtr Instance => IntPtr.Zero; public void Dispose() { } } } }
apache-2.0
C#
4eede296d25ed7c5b918d7f514b422c5980d8027
add available proteomes download
rmillikin/MetaMorpheus
GUI/DownloadUniProtDatabaseWindow.xaml.cs
GUI/DownloadUniProtDatabaseWindow.xaml.cs
using MzLibUtil; using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using UsefulProteomicsDatabases; namespace MetaMorpheusGUI { /// <summary> /// Interaction logic for DownloadUniProtDatabaseWindow.xaml /// </summary> public partial class DownloadUniProtDatabaseWindow : Window { public DownloadUniProtDatabaseWindow() { InitializeComponent(); //string filepath = @"E:\junk"; //string downloadedFilePath = ProteinDbRetriever.DownloadAvailableUniProtProteomes(filepath); string downloadedFilePath = @"E:\junk\availableUniProtProteomes.txt.gz"; Dictionary<string, string> uniprotProteoms = ProteinDbRetriever.UniprotProteomesList(downloadedFilePath); } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace MetaMorpheusGUI { /// <summary> /// Interaction logic for DownloadUniProtDatabaseWindow.xaml /// </summary> public partial class DownloadUniProtDatabaseWindow : Window { public DownloadUniProtDatabaseWindow() { InitializeComponent(); } } }
mit
C#
3fa6821e92d9a9ec8d9bf64ff8c5ebd54568d097
Change document handle to id.
yojimbo87/ArangoDB-NET,kangkot/ArangoDB-NET
src/Arango/Arango.Client/API/ArangoDocument.cs
src/Arango/Arango.Client/API/ArangoDocument.cs
//using System; using System.Collections.Generic; using System.Dynamic; namespace Arango.Client { public class ArangoDocument { public string ID { get; set; } public string Revision { get; set; } public dynamic JsonObject { get; set; } public ArangoDocument() { JsonObject = new ExpandoObject(); } public bool Has(string fieldName) { if (fieldName.Contains(".")) { var fields = fieldName.Split('.'); var iteration = 1; var json = (IDictionary<string, object>)JsonObject; foreach (var field in fields) { if (json.ContainsKey(field)) { if (iteration == fields.Length) { return true; } json = (IDictionary<string, object>)json[field]; iteration++; } else { return false; } } } else { return ((IDictionary<string, object>)JsonObject).ContainsKey(fieldName); } return false; } } }
//using System; using System.Collections.Generic; using System.Dynamic; namespace Arango.Client { public class ArangoDocument { public string Handle { get; set; } public string Revision { get; set; } public dynamic JsonObject { get; set; } public ArangoDocument() { JsonObject = new ExpandoObject(); } public bool Has(string fieldName) { if (fieldName.Contains(".")) { var fields = fieldName.Split('.'); var iteration = 1; var json = (IDictionary<string, object>)JsonObject; foreach (var field in fields) { if (json.ContainsKey(field)) { if (iteration == fields.Length) { return true; } json = (IDictionary<string, object>)json[field]; iteration++; } else { return false; } } } else { return ((IDictionary<string, object>)JsonObject).ContainsKey(fieldName); } return false; } } }
mit
C#
6d9331c49d36ce9590cd6c1cae6c69f41dbc8679
Improve documentation of 0100664 mode usage
OidaTiftla/libgit2sharp,dlsteuer/libgit2sharp,AMSadek/libgit2sharp,vivekpradhanC/libgit2sharp,libgit2/libgit2sharp,psawey/libgit2sharp,psawey/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,dlsteuer/libgit2sharp,oliver-feng/libgit2sharp,PKRoma/libgit2sharp,jamill/libgit2sharp,GeertvanHorrik/libgit2sharp,xoofx/libgit2sharp,github/libgit2sharp,nulltoken/libgit2sharp,rcorre/libgit2sharp,Zoxive/libgit2sharp,rcorre/libgit2sharp,shana/libgit2sharp,whoisj/libgit2sharp,xoofx/libgit2sharp,jorgeamado/libgit2sharp,jeffhostetler/public_libgit2sharp,ethomson/libgit2sharp,mono/libgit2sharp,Skybladev2/libgit2sharp,red-gate/libgit2sharp,AMSadek/libgit2sharp,github/libgit2sharp,whoisj/libgit2sharp,OidaTiftla/libgit2sharp,vorou/libgit2sharp,AArnott/libgit2sharp,jeffhostetler/public_libgit2sharp,nulltoken/libgit2sharp,vorou/libgit2sharp,shana/libgit2sharp,AArnott/libgit2sharp,GeertvanHorrik/libgit2sharp,vivekpradhanC/libgit2sharp,sushihangover/libgit2sharp,sushihangover/libgit2sharp,jamill/libgit2sharp,mono/libgit2sharp,yishaigalatzer/LibGit2SharpCheckOutTests,Skybladev2/libgit2sharp,Zoxive/libgit2sharp,red-gate/libgit2sharp,ethomson/libgit2sharp,oliver-feng/libgit2sharp,jorgeamado/libgit2sharp
LibGit2Sharp/Mode.cs
LibGit2Sharp/Mode.cs
namespace LibGit2Sharp { /// <summary> /// Git specific modes for entries. /// </summary> public enum Mode { // Inspired from http://stackoverflow.com/a/8347325/335418 /// <summary> /// 000000 file mode (the entry doesn't exist) /// </summary> Nonexistent = 0, /// <summary> /// 040000 file mode /// </summary> Directory = 0x4000, /// <summary> /// 100644 file mode /// </summary> NonExecutableFile = 0x81A4, /// <summary> /// Obsolete 100664 file mode. /// <para>0100664 mode is an early Git design mistake. It's kept for /// ascendant compatibility as some <see cref="Tree"/> and /// <see cref="Repository.Index"/> entries may still bear /// this mode in some old git repositories, but it's now deprecated. /// </para> /// </summary> NonExecutableGroupWritableFile = 0x81B4, /// <summary> /// 100755 file mode /// </summary> ExecutableFile = 0x81ED, /// <summary> /// 120000 file mode /// </summary> SymbolicLink = 0xA000, /// <summary> /// 160000 file mode /// </summary> GitLink = 0xE000 } }
namespace LibGit2Sharp { /// <summary> /// Git specific modes for entries. /// </summary> public enum Mode { // Inspired from http://stackoverflow.com/a/8347325/335418 /// <summary> /// 000000 file mode (the entry doesn't exist) /// </summary> Nonexistent = 0, /// <summary> /// 040000 file mode /// </summary> Directory = 0x4000, /// <summary> /// 100644 file mode /// </summary> NonExecutableFile = 0x81A4, /// <summary> /// 100664 file mode /// </summary> NonExecutableGroupWritableFile = 0x81B4, /// <summary> /// 100755 file mode /// </summary> ExecutableFile = 0x81ED, /// <summary> /// 120000 file mode /// </summary> SymbolicLink = 0xA000, /// <summary> /// 160000 file mode /// </summary> GitLink = 0xE000 } }
mit
C#
ca24f81f7f5f789723f942b9acad04949e8a7cdf
fix to partial view locations for areas
stevehodgkiss/restful-routing,restful-routing/restful-routing,restful-routing/restful-routing,restful-routing/restful-routing,stevehodgkiss/restful-routing,stevehodgkiss/restful-routing
src/RestfulRouting/RestfulRoutingViewEngine.cs
src/RestfulRouting/RestfulRoutingViewEngine.cs
using System.Web.Mvc; namespace RestfulRouting { public class RestfulRoutingViewEngine : WebFormViewEngine { public RestfulRoutingViewEngine() { AreaMasterLocationFormats = new[] { "~/Views/{2}/{1}/{0}.master", "~/Views/{2}/Shared/{0}.master", }; AreaViewLocationFormats = new[] { "~/Views/{2}/{1}/{0}.aspx", "~/Views/{2}/{1}/{0}.ascx", "~/Views/{2}/Shared/{0}.aspx", "~/Views/{2}/Shared/{0}.ascx", }; AreaPartialViewLocationFormats = AreaViewLocationFormats; } } }
using System.Web.Mvc; namespace RestfulRouting { public class RestfulRoutingViewEngine : WebFormViewEngine { public RestfulRoutingViewEngine() { AreaMasterLocationFormats = new[] { "~/Views/{2}/{1}/{0}.master", "~/Views/{2}/Shared/{0}.master", }; AreaViewLocationFormats = new[] { "~/Views/{2}/{1}/{0}.aspx", "~/Views/{2}/{1}/{0}.ascx", "~/Views/{2}/Shared/{0}.aspx", "~/Views/{2}/Shared/{0}.ascx", }; AreaPartialViewLocationFormats = AreaPartialViewLocationFormats; } } }
mit
C#
ba6d20bd985d06ba83d6091d68f7fceeecf48488
Bump version after the sidechain commit (#3304)
bokobza/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,bokobza/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,mikedennis/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode,Neurosploit/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode
src/Stratis.Bitcoin/Properties/AssemblyInfo.cs
src/Stratis.Bitcoin/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("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.2.1")] [assembly: AssemblyFileVersion("3.0.2.1")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
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("Stratis.Bitcoin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Stratis.Bitcoin")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.0.2.0")] [assembly: AssemblyFileVersion("3.0.2.0")] [assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
mit
C#
c4835920b2dccd5d2259cb97ee94ae554db36fe7
allow setting default fore/back color
nerai/Unlog
src/Unlog.AdditionalTargets/WpfRtfLogTarget.cs
src/Unlog.AdditionalTargets/WpfRtfLogTarget.cs
using System; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using Unlog.Util; namespace Unlog.AdditionalTargets { public class WpfRtfLogTarget : ILogTarget { private readonly RichTextBox _RTF; private Color _Fore; private Color _Back; public Color DefaultForegroundColor = Colors.Black; public Color DefaultBackgroundColor = Colors.White; public WpfRtfLogTarget (RichTextBox rtf) { _RTF = rtf; ResetColors (); } public void Write (string s) { // Capture state locally var fore = _Fore; var back = _Back; _RTF.Dispatcher.BeginInvoke ((Action) (() => { var range = new TextRange (_RTF.Document.ContentEnd, _RTF.Document.ContentEnd); range.Text = s; range.ApplyPropertyValue (TextElement.ForegroundProperty, new SolidColorBrush (fore)); range.ApplyPropertyValue (TextElement.BackgroundProperty, new SolidColorBrush (back)); _RTF.ScrollToEnd (); })); } public void SetForegroundColor (ConsoleColor c) { var dcol = c.ToRGB (); _Fore = Color.FromArgb (dcol.A, dcol.R, dcol.G, dcol.B); } public void SetBackgroundColor (ConsoleColor c) { var dcol = c.ToRGB (); _Back = Color.FromArgb (dcol.A, dcol.R, dcol.G, dcol.B); } public void ResetColors () { _Fore = DefaultForegroundColor; _Back = DefaultBackgroundColor; } public void Flush () { // empty } } }
using System; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using Unlog.Util; namespace Unlog.AdditionalTargets { public class WpfRtfLogTarget : ILogTarget { private readonly RichTextBox _RTF; private Color _Fore; private Color _Back; public WpfRtfLogTarget (RichTextBox rtf) { _RTF = rtf; ResetColors (); } public void Write (string s) { // Capture state locally var fore = _Fore; var back = _Back; _RTF.Dispatcher.BeginInvoke ((Action) (() => { var range = new TextRange (_RTF.Document.ContentEnd, _RTF.Document.ContentEnd); range.Text = s; range.ApplyPropertyValue (TextElement.ForegroundProperty, new SolidColorBrush (fore)); range.ApplyPropertyValue (TextElement.BackgroundProperty, new SolidColorBrush (back)); _RTF.ScrollToEnd (); })); } public void SetForegroundColor (ConsoleColor c) { var dcol = c.ToRGB (); _Fore = Color.FromArgb (dcol.A, dcol.R, dcol.G, dcol.B); } public void SetBackgroundColor (ConsoleColor c) { var dcol = c.ToRGB (); _Back = Color.FromArgb (dcol.A, dcol.R, dcol.G, dcol.B); } public void ResetColors () { _Fore = Colors.Black; _Back = Colors.White; } public void Flush () { // empty } } }
mit
C#
510e940d555a782600fbdf82c92ac8ac6d83ebbd
Comment to Balance
NikIvRu/NectarineProject
Mall/Basic/Balnce.cs
Mall/Basic/Balnce.cs
namespace Mall.Staff { abstract class Balnce { //Balance for employes and clients protected decimal Balance { get; set; } abstract public void GetPaid(decimal sum) { } abstract public bool Pay(decimal sum) { return true; } } }
namespace Mall.Staff { abstract class Balnce { protected decimal Balance { get; set; } abstract public void GetPaid(decimal sum) { } abstract public bool Pay(decimal sum) { return true; } } }
mit
C#
4c4cc620fe88d0da1b9ea28706d71eccb094231f
Change comments header
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/WpfMinesweeper/App.xaml.cs
src2/WpfMinesweeper/App.xaml.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="App.xaml.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // Interaction logic for App.xaml // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System.Windows; /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="App.xaml.cs" company=""> // // </copyright> // <summary> // Interaction logic for App.xaml // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System.Windows; /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
mit
C#
2fda0b71fe44891089d59ecdfbbc10bffdd8d340
Add method to get a computer’s printers
christianz/printnode-net
PrintNodeComputer.cs
PrintNodeComputer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using PrintNodeNet.Http; namespace PrintNodeNet { public sealed class PrintNodeComputer { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("inet")] public string Inet { get; set; } [JsonProperty("inet6")] public string Inet6 { get; set; } [JsonProperty("hostName")] public string HostName { get; set; } [JsonProperty("jre")] public string Jre { get; set; } [JsonProperty("createTimeStamp")] public DateTime CreateTimeStamp { get; set; } [JsonProperty("state")] public string State { get; set; } public static async Task<IEnumerable<PrintNodeComputer>> ListAsync(PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get("/computers", options); return JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); } public static async Task<PrintNodeComputer> GetAsync(long id, PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get($"/computers/{id}", options); var list = JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); return list.FirstOrDefault(); } public async Task<IEnumerable<PrintNodePrinter>> ListPrinters(PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get($"/computers/{Id}/printers", options); return JsonConvert.DeserializeObject<List<PrintNodePrinter>>(response); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Newtonsoft.Json; using PrintNodeNet.Http; namespace PrintNodeNet { public sealed class PrintNodeComputer { [JsonProperty("id")] public long Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("inet")] public string Inet { get; set; } [JsonProperty("inet6")] public string Inet6 { get; set; } [JsonProperty("hostName")] public string HostName { get; set; } [JsonProperty("jre")] public string Jre { get; set; } [JsonProperty("createTimeStamp")] public DateTime CreateTimeStamp { get; set; } [JsonProperty("state")] public string State { get; set; } public static async Task<IEnumerable<PrintNodeComputer>> ListAsync(PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get("/computers", options); return JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); } public static async Task<PrintNodeComputer> GetAsync(long id, PrintNodeRequestOptions options = null) { var response = await PrintNodeApiHelper.Get($"/computers/{id}", options); var list = JsonConvert.DeserializeObject<List<PrintNodeComputer>>(response); return list.FirstOrDefault(); } } }
mit
C#
00a8a8a141fc4cd0802466f9bd6fb16a0a47223a
Add ReadAsLocalTimeProperty to Connection.
mongodb-csharp/mongodb-csharp,samus/mongodb-csharp,zh-huan/mongodb
source/MongoDB/Configuration/MongoConfiguration.cs
source/MongoDB/Configuration/MongoConfiguration.cs
using MongoDB.Configuration.Mapping; using MongoDB.Serialization; namespace MongoDB.Configuration { /// <summary> /// /// </summary> public class MongoConfiguration { /// <summary> /// MongoDB-CSharp default configuration. /// </summary> public static readonly MongoConfiguration Default = new MongoConfiguration(); /// <summary> /// Initializes a new instance of the <see cref="MongoConfiguration"/> class. /// </summary> public MongoConfiguration(){ ConnectionString = string.Empty; MappingStore = new AutoMappingStore(); SerializationFactory = new SerializationFactory(this); } /// <summary> /// Gets or sets the connection string. /// </summary> /// <value>The connection string.</value> public string ConnectionString { get; set; } /// <summary> /// Gets or sets the serialization factory. /// </summary> /// <value>The serialization factory.</value> public ISerializationFactory SerializationFactory { get; set; } /// <summary> /// Gets or sets the mapping store. /// </summary> /// <value>The mapping store.</value> public IMappingStore MappingStore { get; set; } /// <summary> /// Reads DataTime from server as local time. /// </summary> /// <value><c>true</c> if [read local time]; otherwise, <c>false</c>.</value> /// <remarks> /// MongoDB stores all time values in UTC timezone. If true the /// time is converted from UTC to local timezone after is was read. /// </remarks> public bool ReadLocalTime { get; set; } /// <summary> /// Validates this instance. /// </summary> public void Validate(){ if(ConnectionString == null) throw new MongoException("ConnectionString can not be null"); if(MappingStore == null) throw new MongoException("MappingStore can not be null"); if(SerializationFactory == null) throw new MongoException("SerializationFactory can not be null"); } } }
using MongoDB.Configuration.Mapping; using MongoDB.Serialization; namespace MongoDB.Configuration { /// <summary> /// /// </summary> public class MongoConfiguration { /// <summary> /// MongoDB-CSharp default configuration. /// </summary> public static readonly MongoConfiguration Default = new MongoConfiguration(); /// <summary> /// Initializes a new instance of the <see cref="MongoConfiguration"/> class. /// </summary> public MongoConfiguration(){ ConnectionString = string.Empty; MappingStore = new AutoMappingStore(); SerializationFactory = new SerializationFactory(this); } /// <summary> /// Gets or sets the connection string. /// </summary> /// <value>The connection string.</value> public string ConnectionString { get; set; } /// <summary> /// Gets or sets the serialization factory. /// </summary> /// <value>The serialization factory.</value> public ISerializationFactory SerializationFactory { get; set; } /// <summary> /// Gets or sets the mapping store. /// </summary> /// <value>The mapping store.</value> public IMappingStore MappingStore { get; set; } /// <summary> /// Validates this instance. /// </summary> public void Validate(){ if(ConnectionString == null) throw new MongoException("ConnectionString can not be null"); if(MappingStore == null) throw new MongoException("MappingStore can not be null"); if(SerializationFactory == null) throw new MongoException("SerializationFactory can not be null"); } } }
apache-2.0
C#
8b0325613a293d8bd3f55af06a55bbfa3715e4b2
Optimize InstrumentFieldsMiddleware when metrics are disabled (#3130)
graphql-dotnet/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet,graphql-dotnet/graphql-dotnet,joemcbride/graphql-dotnet
src/GraphQL/Instrumentation/InstrumentFieldsMiddleware.cs
src/GraphQL/Instrumentation/InstrumentFieldsMiddleware.cs
namespace GraphQL.Instrumentation { /// <summary> /// Middleware required for Apollo tracing to record performance metrics of field resolvers. /// </summary> public class InstrumentFieldsMiddleware : IFieldMiddleware { /// <inheritdoc/> public ValueTask<object?> ResolveAsync(IResolveFieldContext context, FieldMiddlewareDelegate next) { return context.Metrics.Enabled ? ResolveWhenMetricsEnabledAsync(context, next) : next(context); } private async ValueTask<object?> ResolveWhenMetricsEnabledAsync(IResolveFieldContext context, FieldMiddlewareDelegate next) { var name = context.FieldAst.Name.StringValue; //ISSUE:allocation var metadata = new Dictionary<string, object?> { { "typeName", context.ParentType.Name }, { "fieldName", name }, { "returnTypeName", context.FieldDefinition.ResolvedType!.ToString() }, { "path", context.Path }, }; using (context.Metrics.Subject("field", name, metadata)) return await next(context).ConfigureAwait(false); } } }
namespace GraphQL.Instrumentation { /// <summary> /// Middleware required for Apollo tracing to record performance metrics of field resolvers. /// </summary> public class InstrumentFieldsMiddleware : IFieldMiddleware { /// <inheritdoc/> public async ValueTask<object?> ResolveAsync(IResolveFieldContext context, FieldMiddlewareDelegate next) { var name = context.FieldAst.Name.StringValue; //ISSUE:allocation var metadata = new Dictionary<string, object?> { { "typeName", context.ParentType.Name }, { "fieldName", name }, { "returnTypeName", context.FieldDefinition.ResolvedType!.ToString() }, { "path", context.Path }, }; using (context.Metrics.Subject("field", name, metadata)) return await next(context).ConfigureAwait(false); } } }
mit
C#
77f8df930f7530d4e20d187c517729125498ecd8
Build edit page for enabled RPs
rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2,kjnilsson/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,rfavillejr/Thinktecture.IdentityServer.v2,IdentityServer/IdentityServer2,IdentityServer/IdentityServer2,kjnilsson/Thinktecture.IdentityServer.v2
src/OnPremise/WebSite/ViewModels/RelyingPartyViewModel.cs
src/OnPremise/WebSite/ViewModels/RelyingPartyViewModel.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Thinktecture.IdentityServer.Web.ViewModels { public class RelyingPartyViewModel { public string ID { get; set; } public string DisplayName { get; set; } public bool Enabled { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Thinktecture.IdentityServer.Web.ViewModels { public class RelyingPartyViewModel { public int ID { get; set; } public string DisplayName { get; set; } } }
bsd-3-clause
C#
ffd17f9c4cbb2b99fd59e5c01d08f34a28df9ee5
rename the test to clarify.
jwChung/Experimentalism,jwChung/Experimentalism
test/ExperimentalUnitTest/Scenario.cs
test/ExperimentalUnitTest/Scenario.cs
using Xunit; namespace Jwc.Experimental { public class Scenario { [Theorem] public void TheoremAttributeOnMethodIndicatesTestCase() { Assert.True(true, "excuted."); } } }
using Xunit; namespace Jwc.Experimental { public class Scenario { [Theorem] public void TheoremActAsFactAttribute() { Assert.True(true, "Excuted"); } } }
mit
C#
883872b1d9ed38f9dc5e3a26c5bc1ec39450bd46
Change htmlEncoder to optional in FormDataSetExtensions.CreateBody
AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp
src/AngleSharp/Html/Forms/FormDataSetExtensions.cs
src/AngleSharp/Html/Forms/FormDataSetExtensions.cs
namespace AngleSharp.Html.Forms { using AngleSharp.Html.Forms.Submitters; using AngleSharp.Io; using AngleSharp.Text; using System; using System.IO; using System.Text; static class FormDataSetExtensions { public static Stream CreateBody(this FormDataSet formDataSet, String enctype, String? charset, IHtmlEncoder? htmlEncoder) { var encoding = TextEncoding.Resolve(charset); return formDataSet.CreateBody(enctype, encoding, htmlEncoder ?? new DefaultHtmlEncoder()); } public static Stream CreateBody(this FormDataSet formDataSet, String enctype, Encoding encoding, IHtmlEncoder htmlEncoder) { if (enctype.Isi(MimeTypeNames.UrlencodedForm)) { return formDataSet.AsUrlEncoded(encoding); } else if (enctype.Isi(MimeTypeNames.MultipartForm)) { return formDataSet.AsMultipart(htmlEncoder, encoding); } else if (enctype.Isi(MimeTypeNames.Plain)) { return formDataSet.AsPlaintext(encoding); } else if (enctype.Isi(MimeTypeNames.ApplicationJson)) { return formDataSet.AsJson(); } return MemoryStream.Null; } } }
namespace AngleSharp.Html.Forms { using AngleSharp.Html.Forms.Submitters; using AngleSharp.Io; using AngleSharp.Text; using System; using System.IO; using System.Text; static class FormDataSetExtensions { public static Stream CreateBody(this FormDataSet formDataSet, String enctype, String? charset, IHtmlEncoder htmlEncoder) { var encoding = TextEncoding.Resolve(charset); return formDataSet.CreateBody(enctype, encoding, htmlEncoder); } public static Stream CreateBody(this FormDataSet formDataSet, String enctype, Encoding encoding, IHtmlEncoder htmlEncoder) { if (enctype.Isi(MimeTypeNames.UrlencodedForm)) { return formDataSet.AsUrlEncoded(encoding); } else if (enctype.Isi(MimeTypeNames.MultipartForm)) { return formDataSet.AsMultipart(htmlEncoder, encoding); } else if (enctype.Isi(MimeTypeNames.Plain)) { return formDataSet.AsPlaintext(encoding); } else if (enctype.Isi(MimeTypeNames.ApplicationJson)) { return formDataSet.AsJson(); } return MemoryStream.Null; } } }
mit
C#
94a67d946e31035b28042ee8c0645eb72dca13f0
Implement Servers model.
DimensionDataResearch/cloudcontrol-client-core
src/DD.CloudControl.Client/Models/Server/Server.cs
src/DD.CloudControl.Client/Models/Server/Server.cs
using Newtonsoft.Json; using System.Collections.Generic; using System; namespace DD.CloudControl.Client.Models.Server { /// <summary> /// Represents an MCP 2.0 Server (virtual machine). /// </summary> public class Server : Resource { /// <summary> /// The server name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The server description. /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// Information about the server's operating system. /// </summary> [JsonProperty("operatingSystem", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public OperatingSystem OperatingSystem { get; } = new OperatingSystem(); /// <summary> /// Information about the server's CPU(s). /// </summary> [JsonProperty("cpu", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public VirtualMachineCpu Cpu { get; } = new VirtualMachineCpu(); /// <summary> /// The amount of RAM (in gigabytes) assigned to the server. /// </summary> [JsonProperty("memoryGb")] public int MemoryGB { get; set; } /// <summary> /// The server's disk configuration. /// </summary> [JsonProperty("disk", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public List<VirtualMachineDisk> Disks { get; } = new List<VirtualMachineDisk>(); /// <summary> /// The server's network configuration. /// </summary> [JsonProperty("networkInfo", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public VirtualMachineNetwork Network { get; } = new VirtualMachineNetwork(); /// <summary> /// The Id of the image from which the server was created. /// </summary> public Guid SourceImageId { get; set; } /// <summary> /// Is the server's deployment complete? /// </summary> [JsonProperty("deployed")] public bool IsDeployed { get; set; } /// <summary> /// Is the server running? /// </summary> [JsonProperty("started")] public bool IsRunning { get; set; } } /// <summary> /// Represents a page of <see cref="Server"/> results. /// </summary> public class Servers : PagedResult<Server> { /// <summary> /// The servers. /// </summary> [JsonProperty("server", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public override List<Server> Items { get; } = new List<Server>(); } }
using Newtonsoft.Json; using System.Collections.Generic; using System; namespace DD.CloudControl.Client.Models.Server { /// <summary> /// Represents an MCP 2.0 Server (virtual machine). /// </summary> public class Server : Resource { /// <summary> /// The server name. /// </summary> [JsonProperty("name")] public string Name { get; set; } /// <summary> /// The server description. /// </summary> [JsonProperty("description")] public string Description { get; set; } /// <summary> /// Information about the server's operating system. /// </summary> [JsonProperty("operatingSystem", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public OperatingSystem OperatingSystem { get; } = new OperatingSystem(); /// <summary> /// Information about the server's CPU(s). /// </summary> [JsonProperty("cpu", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public VirtualMachineCpu Cpu { get; } = new VirtualMachineCpu(); /// <summary> /// The amount of RAM (in gigabytes) assigned to the server. /// </summary> [JsonProperty("memoryGb")] public int MemoryGB { get; set; } /// <summary> /// The server's disk configuration. /// </summary> [JsonProperty("disk", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public List<VirtualMachineDisk> Disks { get; } = new List<VirtualMachineDisk>(); /// <summary> /// The server's network configuration. /// </summary> [JsonProperty("networkInfo", ObjectCreationHandling = ObjectCreationHandling.Reuse)] public VirtualMachineNetwork Network { get; } = new VirtualMachineNetwork(); /// <summary> /// The Id of the image from which the server was created. /// </summary> public Guid SourceImageId { get; set; } /// <summary> /// Is the server's deployment complete? /// </summary> [JsonProperty("deployed")] public bool IsDeployed { get; set; } /// <summary> /// Is the server running? /// </summary> [JsonProperty("started")] public bool IsRunning { get; set; } } }
mit
C#
53f7f0a9f08d041e639ed071350f852c7e7ac1bd
Update in creation of table
pontazaricardo/DBMS_Parser_Insert
main/dbms_gui_02/dbms_gui_02/dbms_objects_data/Table.cs
main/dbms_gui_02/dbms_gui_02/dbms_objects_data/Table.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace dbms_objects_data { class Table { public DataTable table = new DataTable(); public Table() { } public bool insertRows(string[] listOfNames, Type[] listOfTypes) { if((listOfNames == null) || (listOfTypes == null)) { return false; } if(listOfNames.Length != listOfTypes.Length) { return false; } for(int i = 0; i < listOfNames.Length; i++) { table.Columns.Add(listOfNames[i], listOfTypes[i]); } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; namespace dbms_objects_data { class Table { public DataTable table = new DataTable(); public Table() { } public bool insertRows(string[] listOfNames, Type[] listOfTypes) { if((listOfNames == null) || (listOfTypes == null)) { return false; } for(int i = 0; i < listOfNames.Length; i++) { table.Columns.Add(listOfNames[i], listOfTypes[i]); } return true; } } }
mpl-2.0
C#
1b1b74961fc0cb258dad9cb0c1c12125f7bc1079
fix Signum.Upgrade
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Program.cs
Signum.Upgrade/Program.cs
using Signum.Utilities; using System; namespace Signum.Upgrade; class Program { static void Main(string[] args) { Console.WriteLine(); Console.WriteLine(" ..:: Welcome to Signum Upgrade ::.."); Console.WriteLine(); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " This application helps you upgrade a Signum Framework application by modifying your source code."); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " The closer your application resembles Southwind, the better it works."); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " Review all the changes carefully"); Console.WriteLine(); var uctx = UpgradeContext.CreateFromCurrentDirectory(); Console.Write(" RootFolder = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.RootFolder); Console.Write(" ApplicationName = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.ApplicationName); //UpgradeContext.DefaultIgnoreDirectories = UpgradeContext.DefaultIgnoreDirectories.Where(a => a != "Framework").ToArray(); new CodeUpgradeRunner(autoDiscover: true).Run(uctx); } }
using Signum.Utilities; using System; namespace Signum.Upgrade; class Program { static void Main(string[] args) { Console.WriteLine(); Console.WriteLine(" ..:: Welcome to Signum Upgrade ::.."); Console.WriteLine(); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " This application helps you upgrade a Signum Framework application by modifying your source code."); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " The closer your application resembles Southwind, the better it works."); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, " Review all the changes carefully"); Console.WriteLine(); var uctx = UpgradeContext.CreateFromCurrentDirectory(); Console.Write(" RootFolder = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.RootFolder); Console.Write(" ApplicationName = "); SafeConsole.WriteLineColor(ConsoleColor.DarkGray, uctx.ApplicationName); UpgradeContext.DefaultIgnoreDirectories = UpgradeContext.DefaultIgnoreDirectories.Where(a => a != "Framework").ToArray(); new CodeUpgradeRunner(autoDiscover: true).Run(uctx); } }
mit
C#
69615a76b5563e2d240d439b9d6392e1cc34ec50
remove discus from drafts
boyarincev/boyarincev.net,boyarincev/boyarincev.net
Snow/themes/snowbyte/_layouts/post.cshtml
Snow/themes/snowbyte/_layouts/post.cshtml
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Snow.ViewModels.PostViewModel> @using System.Collections.Generic @{ Layout = "default.cshtml"; } <div class="post"> <h1>@Model.Title</h1> <div class="meta"> <p class="posted">@Model.PostDate.ToString("dd MMM yyyy")</p> <ul class="categories"> @foreach(var category in Model.Categories) { <li><a href="/category/@category.Url" title="@category">@category.Name</a></li> } </ul> </div> <!--div class="addthis_toolbox addthis_default_style" style="float:right;"> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_button_google_plusone" g:plusone:size="medium"></a> <a class="addthis_button_linkedin_counter"></a> <a class="addthis_counter addthis_pill_style"></a> </div--> </div> @Html.RenderSeries() @Html.Raw(Model.PostContent) @if (Model.Published == Published.True) { @Html.RenderDisqusComments("boyarincev") } <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-****"></script> </div>
@inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Snow.ViewModels.PostViewModel> @using System.Collections.Generic @{ Layout = "default.cshtml"; } <div class="post"> <h1>@Model.Title</h1> <div class="meta"> <p class="posted">@Model.PostDate.ToString("dd MMM yyyy")</p> <ul class="categories"> @foreach(var category in Model.Categories) { <li><a href="/category/@category.Url" title="@category">@category.Name</a></li> } </ul> </div> <!--div class="addthis_toolbox addthis_default_style" style="float:right;"> <a class="addthis_button_facebook_like" fb:like:layout="button_count"></a> <a class="addthis_button_tweet"></a> <a class="addthis_button_google_plusone" g:plusone:size="medium"></a> <a class="addthis_button_linkedin_counter"></a> <a class="addthis_counter addthis_pill_style"></a> </div--> </div> @Html.RenderSeries() @Html.Raw(Model.PostContent) @if (Model.Published.True) { @Html.RenderDisqusComments("boyarincev") } <script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-****"></script> </div>
mit
C#
2eba48db81e3e0c62079437cfb178ac9fbe0307e
Reformat IFiles
coryrwest/B2.NET
src/IFiles.cs
src/IFiles.cs
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using B2Net.Models; namespace B2Net { public interface IFiles { Task<B2File> Delete(string fileId, string fileName, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadById(string fileId, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadById(string fileId, int startByte, int endByte, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadByName(string fileName, string bucketName, CancellationToken cancelToken = default(CancellationToken)); Task<B2DownloadAuthorization> GetDownloadAuthorization(string fileNamePrefix, int validDurationInSeconds, string bucketId = "", string b2ContentDisposition = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadByName(string fileName, string bucketName, int startByte, int endByte, CancellationToken cancelToken = default(CancellationToken)); string GetFriendlyDownloadUrl(string fileName, string bucketName, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> GetInfo(string fileId, CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetList(string startFileName = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetListWithPrefixOrDemiliter(string startFileName = "", string prefix = "", string delimiter = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2UploadUrl> GetUploadUrl(string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetVersions(string startFileName = "", string startFileId = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetVersionsWithPrefixOrDelimiter(string startFileName = "", string startFileId = "", string prefix = "", string delimiter = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Hide(string fileName, string bucketId = "", string fileId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Upload(byte[] fileData, string fileName, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, bool autoRetry, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)); } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using B2Net.Models; namespace B2Net { public interface IFiles { Task<B2File> Delete(string fileId, string fileName, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadById(string fileId, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadById(string fileId, int startByte, int endByte, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadByName(string fileName, string bucketName, CancellationToken cancelToken = default(CancellationToken)); Task<B2DownloadAuthorization> GetDownloadAuthorization(string fileNamePrefix, int validDurationInSeconds, string bucketId = "", string b2ContentDisposition = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2File> DownloadByName(string fileName, string bucketName, int startByte, int endByte, CancellationToken cancelToken = default(CancellationToken)); string GetFriendlyDownloadUrl(string fileName, string bucketName, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> GetInfo(string fileId, CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetList(string startFileName = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetListWithPrefixOrDemiliter(string startFileName = "", string prefix = "", string delimiter = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2UploadUrl> GetUploadUrl(string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetVersions(string startFileName = "", string startFileId = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2FileList> GetVersionsWithPrefixOrDelimiter(string startFileName = "", string startFileId = "", string prefix = "", string delimiter = "", int? maxFileCount = null, string bucketId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Hide(string fileName, string bucketId = "", string fileId = "", CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Upload(byte[] fileData, string fileName, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)); Task<B2File> Upload(byte[] fileData, string fileName, B2UploadUrl uploadUrl, bool autoRetry, string bucketId = "", Dictionary<string, string> fileInfo = null, CancellationToken cancelToken = default(CancellationToken)); } }
mit
C#
c61b5bb979d682a5d7bf527578e4b82b7adc78bf
Add expiration to client secret
chicoribas/IdentityServer3,jonathankarsh/IdentityServer3,delRyan/IdentityServer3,delloncba/IdentityServer3,roflkins/IdentityServer3,angelapper/IdentityServer3,openbizgit/IdentityServer3,ryanvgates/IdentityServer3,bodell/IdentityServer3,tonyeung/IdentityServer3,charoco/IdentityServer3,tuyndv/IdentityServer3,uoko-J-Go/IdentityServer,wondertrap/IdentityServer3,tbitowner/IdentityServer3,18098924759/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,mvalipour/IdentityServer3,bodell/IdentityServer3,codeice/IdentityServer3,yanjustino/IdentityServer3,wondertrap/IdentityServer3,uoko-J-Go/IdentityServer,SonOfSam/IdentityServer3,jackswei/IdentityServer3,charoco/IdentityServer3,EternalXw/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,mvalipour/IdentityServer3,IdentityServer/IdentityServer3,bestwpw/IdentityServer3,delRyan/IdentityServer3,jackswei/IdentityServer3,paulofoliveira/IdentityServer3,jonathankarsh/IdentityServer3,paulofoliveira/IdentityServer3,angelapper/IdentityServer3,roflkins/IdentityServer3,delRyan/IdentityServer3,olohmann/IdentityServer3,olohmann/IdentityServer3,wondertrap/IdentityServer3,EternalXw/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,Agrando/IdentityServer3,IdentityServer/IdentityServer3,openbizgit/IdentityServer3,ryanvgates/IdentityServer3,iamkoch/IdentityServer3,chicoribas/IdentityServer3,mvalipour/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,Agrando/IdentityServer3,codeice/IdentityServer3,SonOfSam/IdentityServer3,buddhike/IdentityServer3,buddhike/IdentityServer3,roflkins/IdentityServer3,jackswei/IdentityServer3,buddhike/IdentityServer3,codeice/IdentityServer3,iamkoch/IdentityServer3,tuyndv/IdentityServer3,Agrando/IdentityServer3,bestwpw/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,kouweizhong/IdentityServer3,uoko-J-Go/IdentityServer,faithword/IdentityServer3,chicoribas/IdentityServer3,iamkoch/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,ryanvgates/IdentityServer3,EternalXw/IdentityServer3,remunda/IdentityServer3,faithword/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,charoco/IdentityServer3,olohmann/IdentityServer3,tbitowner/IdentityServer3,delloncba/IdentityServer3,kouweizhong/IdentityServer3,bestwpw/IdentityServer3,delloncba/IdentityServer3,angelapper/IdentityServer3,kouweizhong/IdentityServer3,18098924759/IdentityServer3,paulofoliveira/IdentityServer3,SonOfSam/IdentityServer3,openbizgit/IdentityServer3,remunda/IdentityServer3,yanjustino/IdentityServer3,18098924759/IdentityServer3,tonyeung/IdentityServer3,jonathankarsh/IdentityServer3,tuyndv/IdentityServer3,tbitowner/IdentityServer3,faithword/IdentityServer3,IdentityServer/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,remunda/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,bodell/IdentityServer3,tonyeung/IdentityServer3,yanjustino/IdentityServer3
source/Core/Models/ClientSecret.cs
source/Core/Models/ClientSecret.cs
/* * Copyright 2014 Dominick Baier, Brock Allen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Thinktecture.IdentityServer.Core.Models { /// <summary> /// Models a client secret with identifier and expiration /// </summary> public class ClientSecret { /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public string Id { get; set; } /// <summary> /// Gets or sets the value. /// </summary> /// <value> /// The value. /// </value> public string Value { get; set; } /// <summary> /// Gets or sets the expiration. /// </summary> /// <value> /// The expiration. /// </value> public DateTimeOffset? Expiration { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ClientSecret"/> class. /// </summary> /// <param name="value">The value.</param> /// <param name="expiration">The expiration.</param> public ClientSecret(string value, DateTimeOffset? expiration = null) { Value = value; Expiration = expiration; } /// <summary> /// Initializes a new instance of the <see cref="ClientSecret"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="value">The value.</param> /// <param name="expiration">The expiration.</param> public ClientSecret(string id, string value, DateTimeOffset? expiration = null) { Id = id; Value = value; Expiration = expiration; } } }
/* * Copyright 2014 Dominick Baier, Brock Allen * * 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 Thinktecture.IdentityServer.Core.Models { public class ClientSecret { public string Id { get; set; } public string Value { get; set; } public ClientSecret(string value) { Value = value; } public ClientSecret(string id, string value) { Id = id; Value = value; } } }
apache-2.0
C#
5abf26dbf6badcf4191cd9b8d26eaf071759452f
Change meter name to Microsoft.Orleans (#8107)
waynemunro/orleans,hoopsomuah/orleans,waynemunro/orleans,dotnet/orleans,hoopsomuah/orleans,dotnet/orleans
src/Orleans.Core/Diagnostics/Metrics/Instruments.cs
src/Orleans.Core/Diagnostics/Metrics/Instruments.cs
using System.Diagnostics.Metrics; namespace Orleans.Runtime; internal static class Instruments { internal static readonly Meter Meter = new("Microsoft.Orleans"); }
using System.Diagnostics.Metrics; namespace Orleans.Runtime; internal static class Instruments { internal static readonly Meter Meter = new("Orleans"); }
mit
C#
8b2c370635ca9e2fab55bb7e2c1bd8b10e8bacda
add new route for vote with code
KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem,KristianMariyanov/VotingSystem
VotingSystem.Web/App_Start/RouteConfig.cs
VotingSystem.Web/App_Start/RouteConfig.cs
namespace VotingSystem.Web { using System.Web.Mvc; using System.Web.Routing; public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Vote with code", url: "Votes/VoteWithCode/{code}", defaults: new { controller = "Votes", action = "VoteWithCode" }, namespaces: new[] { "VotingSystem.Web.Controllers" }); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "VotingSystem.Web.Controllers" }); routes.MapRoute( "Redirect", "", new { controller = "Home", action = "index" }, new[] { "VotingSystem.Web.Controllers" }); } } }
namespace VotingSystem.Web { using System.Web.Mvc; using System.Web.Routing; public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }, namespaces: new[] { "VotingSystem.Web.Controllers" } ); } } }
mit
C#
2922998dddb3ab81209ad06ec6bf491c7e23ed0d
Create test for inherited private validator function
dbrizov/NaughtyAttributes
Assets/NaughtyAttributes/Scripts/Test/ValidateInputTest.cs
Assets/NaughtyAttributes/Scripts/Test/ValidateInputTest.cs
using UnityEngine; namespace NaughtyAttributes.Test { public class ValidateInputTest : MonoBehaviour { [ValidateInput("NotZero0", "int0 must not be zero")] public int int0; private bool NotZero0(int value) { return value != 0; } public ValidateInputNest1 nest1; public ValidateInputInheritedNest inheritedNest; } [System.Serializable] public class ValidateInputNest1 { [ValidateInput("NotZero1")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int1; private bool NotZero1(int value) { return value != 0; } public ValidateInputNest2 nest2; } [System.Serializable] public class ValidateInputNest2 { [ValidateInput("NotZero2")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int2; private bool NotZero2(int value) { return value != 0; } } [System.Serializable] public class ValidateInputInheritedNest : ValidateInputNest1 { } }
using UnityEngine; namespace NaughtyAttributes.Test { public class ValidateInputTest : MonoBehaviour { [ValidateInput("NotZero0", "int0 must not be zero")] public int int0; private bool NotZero0(int value) { return value != 0; } public ValidateInputNest1 nest1; } [System.Serializable] public class ValidateInputNest1 { [ValidateInput("NotZero1")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int1; private bool NotZero1(int value) { return value != 0; } public ValidateInputNest2 nest2; } [System.Serializable] public class ValidateInputNest2 { [ValidateInput("NotZero2")] [AllowNesting] // Because it's nested we need to explicitly allow nesting public int int2; private bool NotZero2(int value) { return value != 0; } } }
mit
C#
09b20b57eb580782b64161ace9b34b8ae2ecdd4b
simplify generator
robkeim/xcsharp,exercism/xcsharp,ErikSchierboom/xcsharp,ErikSchierboom/xcsharp,robkeim/xcsharp,exercism/xcsharp
generators/Exercises/Generators/SgfParsing.cs
generators/Exercises/Generators/SgfParsing.cs
using System; using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { public class SgfParsing : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { if (testMethod.Expected is Dictionary<string, object> && (testMethod.Expected as Dictionary<string, object>).ContainsKey("error")) testMethod.ExceptionThrown = typeof(ArgumentException); else testMethod.Expected = RenderTree(testMethod.Expected); testMethod.TestedClass = "SgfParser"; testMethod.TestedMethod = "ParseTree"; testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; testMethod.Input["encoded"] = testMethod.Input.FirstOrDefault().Value.Replace("\\","\\\\"); } protected override void UpdateNamespaces(ISet<string> namespaces) { namespaces.Add(typeof(ArgumentException).Namespace); namespaces.Add(typeof(Dictionary<string, string[]>).Namespace); } private UnescapedValue RenderTree(dynamic tree) { if (tree == null) { return null; } var label = Render.Object(tree["properties"]).Replace("object", "string[]"); if (tree.ContainsKey("children")) { var children = string.Empty; if(tree["children"] is JArray) children = string.Join(",", ((JArray)tree["children"]).Select(RenderTree)); if (tree["children"] is object[]) children = string.Join(", ", ((object[])tree["children"]).Select(RenderTree)); if (!string.IsNullOrEmpty(children)) children = "," + children; return new UnescapedValue($"new SgfTree({label} {children})"); } return new UnescapedValue($"new SgfTree({label})"); } } }
using System; using System.Collections.Generic; using System.Linq; using Exercism.CSharp.Output; using Exercism.CSharp.Output.Rendering; using Newtonsoft.Json.Linq; namespace Exercism.CSharp.Exercises.Generators { public class SgfParsing : GeneratorExercise { protected override void UpdateTestMethod(TestMethod testMethod) { if (testMethod.Expected is Dictionary<string, object> && (testMethod.Expected as Dictionary<string, object>).ContainsKey("error")) testMethod.ExceptionThrown = typeof(ArgumentException); else testMethod.Expected = RenderTree(testMethod.Expected); testMethod.TestedClass = "SgfParser"; testMethod.TestedMethod = "ParseTree"; testMethod.UseVariablesForInput = true; testMethod.UseVariableForExpected = true; testMethod.Input["encoded"] = testMethod.Input.FirstOrDefault().Value.Replace("\\","\\\\"); } protected override void UpdateNamespaces(ISet<string> namespaces) { namespaces.Add(typeof(ArgumentException).Namespace); namespaces.Add(typeof(Dictionary<string, string[]>).Namespace); } private UnescapedValue RenderTree(dynamic tree) { if (tree == null) { return null; } var label = Render.Object(tree["properties"]); label = (label as string).Replace("object", "string[]"); if (tree.ContainsKey("children")) { var children = string.Empty; if(tree["children"] is JArray) children = string.Join(",", ((JArray)tree["children"]).Select(RenderTree)); if (tree["children"] is object[]) children = string.Join(", ", ((object[])tree["children"]).Select(RenderTree)); if (!string.IsNullOrEmpty(children)) children = "," + children; return new UnescapedValue($"new SgfTree({label} {children})"); } return new UnescapedValue($"new SgfTree({label})"); } } }
mit
C#
ffdebd0ea720748ef612298160643729834114f7
Update BlockRef to use some ChunkBlockStorage
copygirl/EntitySystem
src/World/BlockRef.cs
src/World/BlockRef.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using EntitySystem.Components.World; using EntitySystem.Utility; namespace EntitySystem.World { public class BlockRef : IEntityRef { public ChunkManager ChunkManager { get; private set; } public BlockPos Position { get; private set; } public EntityManager EntityManager => ChunkManager.EntityManager; public ChunkRef Chunk => ChunkManager.GetChunkRef(Position); public BlockPos ChunkRelPos => ChunkManager.GetChunkRelativeBlock(Position); internal BlockRef(ChunkManager chunks, BlockPos pos) { Debug.Assert(chunks != null); ChunkManager = chunks; Position = pos; } // IEntityRef implementation public Option<Entity> Entity => Chunk.Get<ChunkBlockEntities>().Map((blockEntities) => blockEntities.Get(ChunkRelPos)); public IEnumerable<IComponent> Components => Entity.Map((block) => EntityManager[block].Components) .Or(Enumerable.Empty<IComponent>()) // .Concat() with ChunkBlockStorage values .Follow(new Block(Position)); public bool Has<T>() where T : IComponent => Entity.Map((block) => EntityManager[block].Has<T>()) .Or(() => Chunk.Has<ChunkBlockStorage<T>>()); public Option<T> Get<T>() where T : IComponent => Entity.Map((block) => EntityManager[block].Get<T>()) .Or(() => Chunk.Get<ChunkBlockStorage<T>>() .Map((storage) => storage.Get(ChunkRelPos))); public Option<T> Set<T>(Option<T> value) where T : IComponent { throw new NotImplementedException(); } public Option<T> Remove<T>() where T : IComponent => Entity.Map((block) => EntityManager[block].Remove<T>()) .Or(() => Chunk.Get<ChunkBlockStorage<T>>() .Map((storage) => storage.Set(ChunkRelPos, default(T)))); } }
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using EntitySystem.Components.World; using EntitySystem.Utility; namespace EntitySystem.World { public class BlockRef : IEntityRef { public ChunkManager ChunkManager { get; private set; } public BlockPos Position { get; private set; } public EntityManager EntityManager => ChunkManager.EntityManager; internal BlockRef(ChunkManager chunks, BlockPos pos) { Debug.Assert(chunks != null); ChunkManager = chunks; Position = pos; } // IEntityRef implementation // TODO: BlockStorage public Option<Entity> Entity => ChunkManager.GetChunkRef(Position) .Get<ChunkBlockEntities>().Map((blockEntities) => blockEntities.Get(ChunkManager.GetChunkRelativeBlock(Position))); public IEnumerable<IComponent> Components => Entity.Map((block) => EntityManager[block].Components) .Or(Enumerable.Empty<IComponent>()) // .Concat() .Follow(new Block(Position)); public bool Has<T>() where T : IComponent => Entity.Map((chunk) => EntityManager[chunk].Has<T>()) .Or(false); public Option<T> Get<T>() where T : IComponent => Entity.Map((block) => EntityManager[block].Get<T>()); public Option<T> Set<T>(Option<T> value) where T : IComponent => EntityManager[ChunkManager.GetOrCreateChunk(Position)].Set<T>(value); public Option<T> Remove<T>() where T : IComponent => Entity.Map((chunk) => EntityManager[chunk].Remove<T>()); } }
mit
C#
9793ef6296932edae4892c11256c2d19055f0b0b
Use I18N where possible. Added OpenUserFile() method.
Zastai/POLUtils
PlayOnline.FFXI/Character.cs
PlayOnline.FFXI/Character.cs
using System; using System.IO; using Microsoft.Win32; using PlayOnline.Core; namespace PlayOnline.FFXI { public class Character { internal Character(string ContentID) { this.ID_ = ContentID; this.DataDir_ = Path.Combine(POL.GetApplicationPath(AppID.FFXI), Path.Combine("User", ContentID)); } #region Data Members public string ID { get { return this.ID_; } } public string Name { get { string value = String.Format("Unknown Character ({0})", this.ID_); RegistryKey NameMappings = Registry.LocalMachine.OpenSubKey(@"Software\Pebbles\POLUtils\Character Names"); if (NameMappings != null) { value = NameMappings.GetValue(this.ID_, value) as string; NameMappings.Close(); } return value; } set { RegistryKey NameMappings = Registry.LocalMachine.CreateSubKey(@"Software\Pebbles\POLUtils\Character Names"); if (NameMappings != null) { if (value == null) NameMappings.DeleteValue(this.ID_, false); else NameMappings.SetValue(this.ID_, value); NameMappings.Close(); } } } public MacroFolderCollection MacroBars { get { if (this.MacroBars_ == null) this.LoadMacroBars(); return this.MacroBars_; } } #region Private Fields private string ID_; private string DataDir_; private MacroFolderCollection MacroBars_; #endregion #endregion public override string ToString() { return this.Name; } public FileStream OpenUserFile(string FileName, FileMode Mode, FileAccess Access) { FileStream Result = null; try { Result = new FileStream(Path.Combine(this.DataDir_, FileName), Mode, Access, FileShare.Read); } catch (Exception E) { Console.WriteLine("{0}", E.ToString()); } return Result; } public void SaveMacroBar(int Index) { this.MacroBars_[Index].WriteToMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", Index))); } private void LoadMacroBars() { this.MacroBars_ = new MacroFolderCollection(); for (int i = 0; i < 10; ++i) { MacroFolder MF = MacroFolder.LoadFromMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", i))); MF.Name = String.Format(I18N.GetText("MacroBarLabel"), i + 1); this.MacroBars_.Add(MF); } } } }
using System; using System.IO; using Microsoft.Win32; using PlayOnline.Core; namespace PlayOnline.FFXI { public class Character { #region Data Members public string ID { get { return this.ID_; } } public string Name { get { string value = String.Format("Unknown Character ({0})", this.ID_); RegistryKey NameMappings = Registry.LocalMachine.OpenSubKey(@"Software\Pebbles\POLUtils\Character Names"); if (NameMappings != null) { value = NameMappings.GetValue(this.ID_, value) as string; NameMappings.Close(); } return value; } set { RegistryKey NameMappings = Registry.LocalMachine.CreateSubKey(@"Software\Pebbles\POLUtils\Character Names"); if (NameMappings != null) { if (value == null) NameMappings.DeleteValue(this.ID_, false); else NameMappings.SetValue(this.ID_, value); NameMappings.Close(); } } } public MacroFolderCollection MacroBars { get { return this.MacroBars_; } } #region Private Fields private string ID_; private string DataDir_; private MacroFolderCollection MacroBars_; #endregion #endregion internal Character(string ContentID) { this.ID_ = ContentID; this.DataDir_ = Path.Combine(POL.GetApplicationPath(AppID.FFXI), Path.Combine("User", ContentID)); this.MacroBars_ = new MacroFolderCollection(); for (int i = 0; i < 10; ++i) { MacroFolder MF = MacroFolder.LoadFromMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", i))); MF.Name = String.Format("Macro Bar #{0}", i + 1); this.MacroBars_.Add(MF); } } public void SaveMacroBar(int Index) { this.MacroBars_[Index].WriteToMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", Index))); } } }
apache-2.0
C#
420e84ef6a7ce9bd67d444f60a3013f123a2266b
Use POL.OpenPOLUtilsConfigKey() where applicable. Adjusted retrieval of character name mappings to avoid problems/crashes if the registry entry is somehow not a string value.
Vicrelant/polutils,Vicrelant/polutils,graspee/polutils,graspee/polutils
PlayOnline.FFXI/Character.cs
PlayOnline.FFXI/Character.cs
using System; using System.IO; using Microsoft.Win32; using PlayOnline.Core; namespace PlayOnline.FFXI { public class Character { internal Character(string ContentID) { this.ID_ = ContentID; this.DataDir_ = Path.Combine(POL.GetApplicationPath(AppID.FFXI), Path.Combine("User", ContentID)); } #region Data Members public string ID { get { return this.ID_; } } public string Name { get { string DefaultName = String.Format("Unknown Character ({0})", this.ID_); string value = null; using (RegistryKey NameMappings = POL.OpenPOLUtilsConfigKey(true)) { if (NameMappings != null) value = NameMappings.GetValue(this.ID_, null) as string; } return ((value == null) ? DefaultName : value); } set { using (RegistryKey NameMappings = POL.OpenPOLUtilsConfigKey(true)) { if (NameMappings != null) { if (value == null) NameMappings.DeleteValue(this.ID_, false); else NameMappings.SetValue(this.ID_, value); } } } } public MacroFolderCollection MacroBars { get { if (this.MacroBars_ == null) this.LoadMacroBars(); return this.MacroBars_; } } #region Private Fields private string ID_; private string DataDir_; private MacroFolderCollection MacroBars_; #endregion #endregion public override string ToString() { return this.Name; } public FileStream OpenUserFile(string FileName, FileMode Mode, FileAccess Access) { FileStream Result = null; try { Result = new FileStream(Path.Combine(this.DataDir_, FileName), Mode, Access, FileShare.Read); } catch (Exception E) { Console.WriteLine("{0}", E.ToString()); } return Result; } public void SaveMacroBar(int Index) { this.MacroBars_[Index].WriteToMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", Index))); } private void LoadMacroBars() { this.MacroBars_ = new MacroFolderCollection(); for (int i = 0; i < 10; ++i) { MacroFolder MF = MacroFolder.LoadFromMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", i))); MF.Name = String.Format(I18N.GetText("MacroBarLabel"), i + 1); this.MacroBars_.Add(MF); } } } }
using System; using System.IO; using Microsoft.Win32; using PlayOnline.Core; namespace PlayOnline.FFXI { public class Character { internal Character(string ContentID) { this.ID_ = ContentID; this.DataDir_ = Path.Combine(POL.GetApplicationPath(AppID.FFXI), Path.Combine("User", ContentID)); } #region Data Members public string ID { get { return this.ID_; } } public string Name { get { string value = String.Format("Unknown Character ({0})", this.ID_); RegistryKey NameMappings = Registry.LocalMachine.OpenSubKey(@"Software\Pebbles\POLUtils\Character Names"); if (NameMappings != null) { value = NameMappings.GetValue(this.ID_, value) as string; NameMappings.Close(); } return value; } set { RegistryKey NameMappings = Registry.LocalMachine.CreateSubKey(@"Software\Pebbles\POLUtils\Character Names"); if (NameMappings != null) { if (value == null) NameMappings.DeleteValue(this.ID_, false); else NameMappings.SetValue(this.ID_, value); NameMappings.Close(); } } } public MacroFolderCollection MacroBars { get { if (this.MacroBars_ == null) this.LoadMacroBars(); return this.MacroBars_; } } #region Private Fields private string ID_; private string DataDir_; private MacroFolderCollection MacroBars_; #endregion #endregion public override string ToString() { return this.Name; } public FileStream OpenUserFile(string FileName, FileMode Mode, FileAccess Access) { FileStream Result = null; try { Result = new FileStream(Path.Combine(this.DataDir_, FileName), Mode, Access, FileShare.Read); } catch (Exception E) { Console.WriteLine("{0}", E.ToString()); } return Result; } public void SaveMacroBar(int Index) { this.MacroBars_[Index].WriteToMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", Index))); } private void LoadMacroBars() { this.MacroBars_ = new MacroFolderCollection(); for (int i = 0; i < 10; ++i) { MacroFolder MF = MacroFolder.LoadFromMacroBar(Path.Combine(this.DataDir_, String.Format("mcr{0:#}.dat", i))); MF.Name = String.Format(I18N.GetText("MacroBarLabel"), i + 1); this.MacroBars_.Add(MF); } } } }
apache-2.0
C#
c3e7deb62760559b6a0d24d8b2941ddfe217d579
Fix CA
tom-englert/Wax
Wax.Model/Wix/WixNames.cs
Wax.Model/Wix/WixNames.cs
namespace tomenglertde.Wax.Model.Wix { using System.Diagnostics.Contracts; using System.Xml.Linq; using JetBrains.Annotations; public class WixNames { [NotNull] private readonly string _namespace; public WixNames([NotNull] string @namespace) { Contract.Requires(@namespace != null); _namespace = @namespace; } [NotNull] public XName FileNode => XName.Get("File", _namespace); [NotNull] public XName DirectoryNode => XName.Get("Directory", _namespace); [NotNull] public XName FragmentNode => XName.Get("Fragment", _namespace); [NotNull] public XName DirectoryRefNode => XName.Get("DirectoryRef", _namespace); [NotNull] public XName ComponentNode => XName.Get("Component", _namespace); [NotNull] public XName ComponentGroupNode => XName.Get("ComponentGroup", _namespace); [NotNull] public XName ComponentGroupRefNode => XName.Get("ComponentGroupRef", _namespace); [NotNull] public XName FeatureNode => XName.Get("Feature", _namespace); [NotNull] public XName PropertyNode => XName.Get("Property", _namespace); [NotNull] public XName RegistrySearch => XName.Get("RegistrySearch", _namespace); [NotNull] public XName CustomActionRefNode => XName.Get("CustomActionRef", _namespace); [NotNull] public const string Define = "define"; } }
namespace tomenglertde.Wax.Model.Wix { using System.Diagnostics.Contracts; using System.Xml.Linq; using JetBrains.Annotations; public class WixNames { [NotNull] private readonly string _namespace; public WixNames([NotNull] string @namespace) { Contract.Requires(@namespace != null); _namespace = @namespace; } [NotNull] public XName FileNode => XName.Get("File", _namespace); [NotNull] public XName DirectoryNode => XName.Get("Directory", _namespace); [NotNull] public XName FragmentNode => XName.Get("Fragment", _namespace); [NotNull] public XName DirectoryRefNode => XName.Get("DirectoryRef", _namespace); [NotNull] public XName ComponentNode => XName.Get("Component", _namespace); [NotNull] public XName ComponentGroupNode => XName.Get("ComponentGroup", _namespace); [NotNull] public XName ComponentGroupRefNode => XName.Get("ComponentGroupRef", _namespace); [NotNull] public XName FeatureNode => XName.Get("Feature", _namespace); [NotNull] public XName PropertyNode => XName.Get("Property", _namespace); [NotNull] public XName RegistrySearch => XName.Get("RegistrySearch", _namespace); [NotNull] public XName CustomActionRefNode => XName.Get("CustomActionRef", _namespace); [NotNull] public string Define => "define"; } }
mit
C#
ab1e46330d81f047ad514d0a6f75b389d29ec573
Add and adapt MetallkeferController
emazzotta/unity-tower-defense
Assets/Scripts/Enemies/MetallKeferController.cs
Assets/Scripts/Enemies/MetallKeferController.cs
using UnityEngine; using System.Collections; public class MetallKeferController : MonoBehaviour { public GameObject towerBasesWaypoint; private GameObject baseStart; // Use this for initialization void Start () { this.FindInititalWaypoint (); } // Update is called once per frame void Update () { } void FindInititalWaypoint() { Debug.Log ("MetallKefer Controller Start"); } }
using UnityEngine; using System.Collections; public class MetallKeferController : MonoBehaviour { private GameObject baseStart; // Use this for initialization void Start () { this.FindInititalWaypoint (); } // Update is called once per frame void Update () { } void FindInititalWaypoint() { Debug.Log ("Ant Controller Start"); } }
mit
C#
3f87b52706ce0b304107d9b9a5c8a60bf38a946e
add subscription models
grokify/ringcentral-sdk-csharp-simple
RingCentralSimple/Request.cs
RingCentralSimple/Request.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace RingCentralSimple.Model { public class Base { public string ToJson() { return JsonConvert.SerializeObject( this, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } ); } } } namespace RingCentralSimple.Model.Request { public class Caller { public string phoneNumber { get; set; } } } namespace RingCentralSimple.Model.Request { public class FaxMeta :Base { public List<Caller> to { get; set; } public string resolution { get; set; } public string sendTime { get; set; } public string coverIndex { get; set; } public string coverPageText { get; set; } public string originalMessageId { get; set; } } } namespace RingCentralSimple.Model.Request { public class SMS: Base { public Caller from { get; set; } public List<Caller> to { get; set; } public string text { get; set; } } } namespace RingCentralSimple.Model.Info { public class SubscriptionDeliveryMode { public string transportType { get; set; } public string encryption { get; set; } public string address { get; set; } public string subscriberKey { get; set; } } } namespace RingCentralSimple.Model.Request { public class Subscription : Base { public List<string> eventFilters { get; set; } public RingCentralSimple.Model.Info.SubscriptionDeliveryMode deliveryMode { get; set; } } public class SubscriptionDeliveryMode { public string transportType { get; set; } public string encryption { get; set; } public string address { get; set; } public string subscriberKey { get; set; } } } namespace RingCentralSimple.Model.Response { public class Subscription { public string id { get; set; } public RingCentralSimple.Model.Info.SubscriptionDeliveryMode deliveryMode { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; namespace RingCentralSimple.Model { public class Base { public string ToJson() { return JsonConvert.SerializeObject( this, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } ); } } } namespace RingCentralSimple.Model.Request { public class Caller { public string phoneNumber { get; set; } } } namespace RingCentralSimple.Model.Request { public class FaxMeta :Base { public List<Caller> to { get; set; } public string resolution { get; set; } public string sendTime { get; set; } public string coverIndex { get; set; } public string coverPageText { get; set; } public string originalMessageId { get; set; } } } namespace RingCentralSimple.Model.Request { public class SMS: Base { public Caller from { get; set; } public List<Caller> to { get; set; } public string text { get; set; } } }
mit
C#
2a584ecb8760a64653aad6f9e46d027ade6700d5
update existing object type
thestonefox/VRTK,TMaloteaux/SteamVR_Unity_Toolkit,red-horizon/VRTK,mattboy64/SteamVR_Unity_Toolkit,gpvigano/VRTK,virror/VRTK,Fulby/VRTK,gpvigano/SteamVR_Unity_Toolkit,gomez-addams/SteamVR_Unity_Toolkit,adamjweaver/VRTK,thestonefox/SteamVR_Unity_Toolkit,Innoactive/IA-unity-VR-toolkit-VRTK
Assets/VRTK/Scripts/Internal/VRTK_PlayerObject.cs
Assets/VRTK/Scripts/Internal/VRTK_PlayerObject.cs
//==================================================================================== // // Purpose: Provide a way of tagging game objects as player specific objects to // allow other scripts to identify these specific objects without needing to use tags // or without needing to append the name of the game object. // //==================================================================================== namespace VRTK { using UnityEngine; public sealed class VRTK_PlayerObject : MonoBehaviour { public enum ObjectTypes { Null, CameraRig, Headset, Controller, Pointer, Highlighter, Collider } public ObjectTypes objectType; /// <summary> /// The SetPlayerObject method tags the given game object with a special player object class for easier identification. /// </summary> /// <param name="obj">The game object to add the player object class to.</param> /// <param name="objType">The type of player object that is to be assigned.</param> public static void SetPlayerObject(GameObject obj, ObjectTypes objType) { var currentPlayerObject = obj.GetComponent<VRTK_PlayerObject>(); if (currentPlayerObject == null) { currentPlayerObject = obj.AddComponent<VRTK_PlayerObject>(); } currentPlayerObject.objectType = objType; } /// <summary> /// The IsPlayerObject method determines if the given game object is a player object and can also check if it's of a specific type. /// </summary> /// <param name="obj">The GameObjet to check if it's a player object.</param> /// <param name="ofType">An optional ObjectType to check if the given GameObject is of a specific player object.</param> /// <returns>Returns true if the object is a player object with the optional given type.</returns> public static bool IsPlayerObject(GameObject obj, ObjectTypes ofType = ObjectTypes.Null) { foreach (var playerObject in obj.GetComponentsInParent<VRTK_PlayerObject>(true)) { if (ofType == ObjectTypes.Null || ofType == playerObject.objectType) { return true; } } return false; } } }
//==================================================================================== // // Purpose: Provide a way of tagging game objects as player specific objects to // allow other scripts to identify these specific objects without needing to use tags // or without needing to append the name of the game object. // //==================================================================================== namespace VRTK { using UnityEngine; public sealed class VRTK_PlayerObject : MonoBehaviour { public enum ObjectTypes { Null, CameraRig, Headset, Controller, Pointer, Highlighter, Collider } public ObjectTypes objectType; /// <summary> /// The SetPlayerObject method tags the given game object with a special player object class for easier identification. /// </summary> /// <param name="obj">The game object to add the player object class to.</param> /// <param name="objType">The type of player object that is to be assigned.</param> public static void SetPlayerObject(GameObject obj, ObjectTypes objType) { if (!obj.GetComponent<VRTK_PlayerObject>()) { var playerObject = obj.AddComponent<VRTK_PlayerObject>(); playerObject.objectType = objType; } } /// <summary> /// The IsPlayerObject method determines if the given game object is a player object and can also check if it's of a specific type. /// </summary> /// <param name="obj">The GameObjet to check if it's a player object.</param> /// <param name="ofType">An optional ObjectType to check if the given GameObject is of a specific player object.</param> /// <returns>Returns true if the object is a player object with the optional given type.</returns> public static bool IsPlayerObject(GameObject obj, ObjectTypes ofType = ObjectTypes.Null) { foreach (var playerObject in obj.GetComponentsInParent<VRTK_PlayerObject>(true)) { if (ofType == ObjectTypes.Null || ofType == playerObject.objectType) { return true; } } return false; } } }
mit
C#
450f944007f8d0029ad5f283acc975fd5e8d3cdc
Write tests
mdsol/mauth-client-dotnet
tests/Medidata.MAuth.Tests/UtilityExtensionsTest.cs
tests/Medidata.MAuth.Tests/UtilityExtensionsTest.cs
using System; using System.Threading.Tasks; using Medidata.MAuth.Core; using Medidata.MAuth.Tests.Infrastructure; using Xunit; namespace Medidata.MAuth.Tests { public static class UtilityExtensionsTest { [Fact] public static async Task TryParseAuthenticationHeader_WithValidAuthHeader_WillSucceed() { // Arrange var request = await "GET".FromResource(); var expected = (request.ApplicationUuid, request.Payload); // Act var result = request.MAuthHeader.TryParseAuthenticationHeader(out var actual); // Assert Assert.True(result); Assert.Equal(expected, actual); } [Fact] public static void TryParseAuthenticationHeader_WithInvalidAuthHeader_WillFail() { // Arrange var invalid = "invalid"; // Act var result = invalid.TryParseAuthenticationHeader(out var actual); // Assert Assert.False(result); } [Fact] public static void ParseAuthenticationHeader_WithInvalidAuthHeader_WillThrowException() { // Arrange var invalid = "invalid"; // Act, Assert Assert.Throws<ArgumentException>(() => invalid.ParseAuthenticationHeader()); } [Theory] [InlineData("GET")] [InlineData("DELETE")] [InlineData("POST")] [InlineData("PUT")] public static async Task Authenticate_WithValidRequest_WillAuthenticate(string method) { // Arrange var testData = await method.FromResource(); var signedRequest = await testData.ToHttpRequestMessage() .AddAuthenticationInfo(new PrivateKeyAuthenticationInfo() { ApplicationUuid = testData.ApplicationUuid, PrivateKey = TestExtensions.ClientPrivateKey, SignedTime = testData.SignedTime }); // Act var isAuthenticated = await signedRequest.Authenticate(TestExtensions.ServerOptions); // Assert Assert.True(isAuthenticated); } } }
using System; using System.Threading.Tasks; using Medidata.MAuth.Core; using Medidata.MAuth.Tests.Infrastructure; using Xunit; namespace Medidata.MAuth.Tests { public static class UtilityExtensionsTest { [Fact] public static async Task TryParseAuthenticationHeader_WithValidAuthHeader_WillSucceed() { // Arrange var request = await "GET".FromResource(); var expected = (request.ApplicationUuid, request.Payload); // Act var result = request.MAuthHeader.TryParseAuthenticationHeader(out var actual); // Assert Assert.True(result); Assert.Equal(expected, actual); } [Fact] public static void TryParseAuthenticationHeader_WithInvalidAuthHeader_WillFail() { // Arrange var invalid = "invalid"; // Act var result = invalid.TryParseAuthenticationHeader(out var actual); // Assert Assert.False(result); } [Fact] public static void ParseAuthenticationHeader_WithInvalidAuthHeader_WillThrowException() { // Arrange var invalid = "invalid"; // Act, Assert Assert.Throws<ArgumentException>(() => invalid.ParseAuthenticationHeader()); } } }
mit
C#
45e23e1ad95a440ec75c0d8095deabfc32183eff
Add unqualified name lookup to the MissingMemberName test
jonathanvdc/ecsc
tests/cs-errors/misspelled-name/MisspelledMemberName.cs
tests/cs-errors/misspelled-name/MisspelledMemberName.cs
using static System.Console; public class Counter { public Counter() { } public int Count; public Counter Increment() { Count++; return this; } } public static class Program { public static readonly Counter printCounter = new Counter(); public static void Main() { WriteLine(printCounter.Increment().Coutn); WriteLine(printCounter.Inrement().Count); WriteLine(printCoutner.Increment().Count); } }
using static System.Console; public class Counter { public Counter() { } public int Count; public Counter Increment() { Count++; return this; } } public static class Program { public static readonly Counter printCounter = new Counter(); public static void Main() { WriteLine(printCounter.Increment().Coutn); WriteLine(printCounter.Inrement().Count); } }
mit
C#
620006fa7689f779b248b2d9fa720afa9f596552
Test for sequence in JSON
xtrmstep/xtrmstep.extractor
Extractor/Extractor.Core.Tests/FileReaderTests.cs
Extractor/Extractor.Core.Tests/FileReaderTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Xtrmstep.Extractor.Core.Tests { public class FileReaderTests { const string testDataFolder = @"c:\TestData\"; [Fact(DisplayName = "Read JSON Files / One entry")] public void Should_read_an_entry() { var filePath = testDataFolder + "jsonFormat.txt"; var fileReader = new FileReader(); var values = fileReader.Read(filePath).ToArray(); Assert.Equal(1, values.Length); Assert.Equal("url_text", values[0].url); Assert.Equal("html_text", values[0].result); } [Fact(DisplayName = "Read JSON Files / Several entries")] public void Should_read_sequence() { var filePath = testDataFolder + "jsonSequence.txt"; var fileReader = new FileReader(); var values = fileReader.Read(filePath).ToArray(); Assert.Equal(2, values.Length); Assert.Equal("url_text_1", values[0].url); Assert.Equal("html_text_1", values[0].result); Assert.Equal("url_text_2", values[1].url); Assert.Equal("html_text_2", values[1].result); } [Fact(DisplayName = "Read JSON Files / Big file")] public void Should_read_big_file() { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace Xtrmstep.Extractor.Core.Tests { public class FileReaderTests { const string testDataFolder = @"f:\TestData\"; [Fact(DisplayName = "Read JSON Files / One entry")] public void Should_read_an_entry() { var filePath = testDataFolder + "jsonFormat.txt"; var fileReader = new FileReader(); var values = fileReader.Read(filePath).ToArray(); Assert.Equal(1, values.Length); Assert.Equal("url_text", values[0].url); Assert.Equal("html_text", values[0].result); } [Fact(DisplayName = "Read JSON Files / Several entries")] public void Should_read_sequence() { throw new NotImplementedException(); } [Fact(DisplayName = "Read JSON Files / Big file")] public void Should_read_big_file() { throw new NotImplementedException(); } } }
mit
C#
5f85a2587d1ceb94315dc388be71dcf7c8cd37b7
implement much of the match logic
Aggrathon/rps_tournament
Assets/Scripts/RPS/Match.cs
Assets/Scripts/RPS/Match.cs
using System.Collections.Generic; public class Match { public enum RPS { Rock = 0, Paper = 1, Scissors = 2 } private IRPSPlayer player1; private IRPSPlayer player2; private bool player1HasPlayed; private bool player2HasPlayed; private LinkedList<RPS> player1Choices; private LinkedList<RPS> player2Choices; public Match(IRPSPlayer player1, IRPSPlayer player2) { this.player1 = player1; this.player2 = player2; player1Choices = new LinkedList<RPS>(); player2Choices = new LinkedList<RPS>(); newRound(); } public IRPSPlayer playerOne { get { return player1; } } public IRPSPlayer playerTwo { get { return player2; } } public LinkedList<RPS> playerOneChoices { get { return player1Choices; } } public LinkedList<RPS> playerTwoChoices { get { return player2Choices; } } public RPS getLastChoiceOther(IRPSPlayer player) { if(player == player1) { return player2Choices.Last.Value; } else { return player1Choices.Last.Value; } } private void newRound() { player1HasPlayed = false; player2HasPlayed = false; player1Choices.AddLast(RPS.Rock); player2Choices.AddLast(RPS.Rock); player1.newTurn(); player2.newTurn(); } public void setPlayerChoice(IRPSPlayer player, RPS choice) { if(player == player1) { player1Choices.Last.Value = choice; player1HasPlayed = true; if(player2HasPlayed) { endRound(); } } else if(player == player2) { player2Choices.Last.Value = choice; player2HasPlayed = true; if (player1HasPlayed) { endRound(); } } } private void endRound() { int result = player1Choices.Last.Value - player2Choices.Last.Value; if(result < 0) { result += 3; } if(result == 1) { //player 1 has won } else if (result == 2) { //player 2 has won } } }
using System.Collections.Generic; public class Match { private IRPSPlayer player1; private IRPSPlayer player2; public Match(IRPSPlayer player1, IRPSPlayer player2) { this.player1 = player1; this.player2 = player2; } }
mit
C#
fda448d6083bd1701e5e3c459507da116f48495d
fix for infinite DG
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/ClassSpecific/ClassAbnormalityTracker.cs
TCC.Core/ClassSpecific/ClassAbnormalityTracker.cs
using System; using System.Collections.Generic; using TCC.Data; using TCC.Data.Skills; using TCC.Parsing.Messages; namespace TCC.ClassSpecific { public class ClassAbnormalityTracker { protected static readonly List<ulong> MarkedTargets = new List<ulong>(); public static event Action<ulong> MarkingRefreshed; public static event Action MarkingExpired; public virtual void CheckAbnormality(S_ABNORMALITY_BEGIN p) { } public virtual void CheckAbnormality(S_ABNORMALITY_REFRESH p) { } public virtual void CheckAbnormality(S_ABNORMALITY_END p) { } protected static bool CheckByIconName(uint id, string iconName) { if (!SessionManager.DB.AbnormalityDatabase.Abnormalities.TryGetValue(id, out var ab)) return false; if (ab.Infinity) return false; return ab.IconName == iconName; } protected static void InvokeMarkingExpired() => MarkingExpired?.Invoke(); protected static void InvokeMarkingRefreshed(ulong duration) => MarkingRefreshed?.Invoke(duration); public static void CheckMarkingOnDespawn(ulong target) { if (!MarkedTargets.Contains(target)) return; MarkedTargets.Remove(target); if (MarkedTargets.Count == 0) InvokeMarkingExpired(); } public static void ClearMarkedTargets() { App.BaseDispatcher.Invoke(() => MarkedTargets.Clear()); } protected static void StartPrecooldown(Skill sk, uint duration) { SkillManager.AddSkillDirectly(sk, duration, CooldownType.Skill, CooldownMode.Pre); //CooldownWindowViewModel.Instance.AddOrRefresh(new Cooldown(sk, duration, CooldownType.Skill, CooldownMode.Pre)); } protected ClassAbnormalityTracker() { ClearMarkedTargets(); } } }
using System; using System.Collections.Generic; using TCC.Data; using TCC.Data.Skills; using TCC.Parsing.Messages; namespace TCC.ClassSpecific { public class ClassAbnormalityTracker { protected static readonly List<ulong> MarkedTargets = new List<ulong>(); public static event Action<ulong> MarkingRefreshed; public static event Action MarkingExpired; public virtual void CheckAbnormality(S_ABNORMALITY_BEGIN p) { } public virtual void CheckAbnormality(S_ABNORMALITY_REFRESH p) { } public virtual void CheckAbnormality(S_ABNORMALITY_END p) { } protected static bool CheckByIconName(uint id, string iconName) { if (!SessionManager.DB.AbnormalityDatabase.Abnormalities.TryGetValue(id, out var ab)) return false; return ab.IconName == iconName; } protected static void InvokeMarkingExpired() => MarkingExpired?.Invoke(); protected static void InvokeMarkingRefreshed(ulong duration) => MarkingRefreshed?.Invoke(duration); public static void CheckMarkingOnDespawn(ulong target) { if (!MarkedTargets.Contains(target)) return; MarkedTargets.Remove(target); if (MarkedTargets.Count == 0) InvokeMarkingExpired(); } public static void ClearMarkedTargets() { App.BaseDispatcher.Invoke(() => MarkedTargets.Clear()); } protected static void StartPrecooldown(Skill sk, uint duration) { SkillManager.AddSkillDirectly(sk, duration, CooldownType.Skill, CooldownMode.Pre); //CooldownWindowViewModel.Instance.AddOrRefresh(new Cooldown(sk, duration, CooldownType.Skill, CooldownMode.Pre)); } protected ClassAbnormalityTracker() { ClearMarkedTargets(); } } }
mit
C#
0109167e0513ac670a2efdb5088dc57298f07047
Add anti-parallelization attribute to get all tests running under NUnit
madelson/MedallionShell
MedallionShell.Tests/Properties/AssemblyInfo.cs
MedallionShell.Tests/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("MedallionShell.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MedallionShell.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("48a9dc15-f400-4443-80ba-c508f6810826")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // we can't use parallel tests, since tests such as TestCloseReadSide() try to measure // memory and therefore don't work when things are running in parallel [assembly: Xunit.CollectionBehavior(DisableTestParallelization = true)]
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("MedallionShell.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MedallionShell.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("48a9dc15-f400-4443-80ba-c508f6810826")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
f2fa4c357b0d233d9266a36a7cf2d261fe5ca853
Work on AstReflection.
rsdn/nitra,JetBrains/Nitra,JetBrains/Nitra,rsdn/nitra
Nitra.Visualizer/ViewModels/AstNodeViewModel.cs
Nitra.Visualizer/ViewModels/AstNodeViewModel.cs
using Nitra.ClientServer.Client; using Nitra.ClientServer.Messages; using ReactiveUI; using ReactiveUI.Fody.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using JetBrains.Util; namespace Nitra.Visualizer.ViewModels { public class AstNodeViewModel : ReactiveObject { public class Context { public NitraClient Client { get; private set; } public int FileId { get; private set; } public int FileVersion { get; private set; } public Context(NitraClient client, int fileId, int fileVersion) { Client = client; FileId = fileId; FileVersion = fileVersion; } } readonly ObjectDescriptor _objectDescriptor; readonly Context _context; [Reactive] public bool NeedLoadContent { get; private set; } public ReactiveList<AstNodeViewModel> Items { get; set; } [Reactive] public bool IsSelected { get; set; } [Reactive] public bool IsExpanded { get; set; } public string Caption { get { return _objectDescriptor.ToString(); } } public IReactiveCommand<IEnumerable<AstNodeViewModel>> LoadItems { get; set; } public AstNodeViewModel(Context context, ObjectDescriptor objectDescriptor) { _context = context; _objectDescriptor = objectDescriptor; Items = new ReactiveList<AstNodeViewModel>(); if (objectDescriptor.IsObject || objectDescriptor.IsSeq && objectDescriptor.Count > 0) { NeedLoadContent = true; Items.Add(null); } LoadItems = ReactiveCommand.CreateAsyncTask(_ => { // load items somehow var client = _context.Client; client.Send(new ClientMessage.GetObjectContent(_context.FileId, _context.FileVersion, _objectDescriptor.Id)); var content = client.Receive<ServerMessage.ObjectContent>(); _objectDescriptor.SetContent(content.content); var span = new NSpan(0, _textEditor.Document.TextLength); var root = new ObjectDescriptor.Ast(span, 0, members.members); return Task.FromResult(Enumerable.Empty<AstNodeViewModel>()); }); LoadItems.ObserveOn(RxApp.MainThreadScheduler) .Subscribe(items => Items.AddRange(items)); this.WhenAnyValue(vm => vm.IsExpanded) .Where(isExpanded => isExpanded) .InvokeCommand(LoadItems); } } }
using Nitra.ClientServer.Client; using Nitra.ClientServer.Messages; using ReactiveUI; using ReactiveUI.Fody.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nitra.Visualizer.ViewModels { public class AstNodeViewModel : ReactiveObject { readonly ObjectDescriptor _objectDescriptor; readonly NitraClient _client; [Reactive] public bool NeedLoadContent { get; private set; } public ReactiveList<AstNodeViewModel> Items { get; set; } [Reactive] public bool IsSelected { get; set; } [Reactive] public bool IsExpanded { get; set; } public AstNodeViewModel(NitraClient client, ObjectDescriptor objectDescriptor) { _client = client; _objectDescriptor = objectDescriptor; Items = new ReactiveList<AstNodeViewModel>(); if (objectDescriptor.IsObject || objectDescriptor.IsSeq && objectDescriptor.Count > 0) { NeedLoadContent = true; Items.Add(null); } this.WhenAnyValue(vm => vm.IsExpanded) .Where(isExpanded => isExpanded) .InvokeCommand(OnLoadItems); } private void OnLoadItems(object x) { } } }
apache-2.0
C#
7ce2ddb4001a6cb5cefd4c788f2255ed23135357
fix moneromoney util
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer.Common/Altcoins/Monero/Utils/MoneroMoney.cs
BTCPayServer.Common/Altcoins/Monero/Utils/MoneroMoney.cs
using System.Globalization; namespace BTCPayServer.Services.Altcoins.Monero.Utils { public class MoneroMoney { public static decimal Convert(long piconero) { var amt = piconero.ToString(CultureInfo.InvariantCulture).PadLeft(12, '0'); amt = amt.Length == 12 ? $"0.{amt}" : amt.Insert(amt.Length - 12, "."); return decimal.Parse(amt, CultureInfo.InvariantCulture); } public static long Convert(decimal monero) { return System.Convert.ToInt64(monero * 1000000000000); } } }
using System.Globalization; namespace BTCPayServer.Services.Altcoins.Monero.Utils { public class MoneroMoney { public static decimal Convert(long atoms) { var amt = atoms.ToString(CultureInfo.InvariantCulture).PadLeft(12, '0'); amt = amt.Length == 12 ? $"0.{amt}" : amt.Insert(amt.Length - 12, "."); return decimal.Parse(amt, CultureInfo.InvariantCulture); } public static long Convert(decimal monero) { return System.Convert.ToInt64(monero); } } }
mit
C#
c7f67a111dad10c1b691e0f4eb0de33ca578587b
Remove Console.WriteLine
akatakritos/SassSharp
SassSharp/SassCompiler.cs
SassSharp/SassCompiler.cs
using SassSharp.Ast; using SassSharp.Tokens; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp { public class SassCompiler { public string Compile(string sass) { var tokenizer = new Tokenizer(); var builder = new SyntaxTreeBuilder(tokenizer.Tokenize(sass)); var compiler = new AstCompiler(); var render = new CssRenderer(); var ast = builder.Build(); return render.Render(compiler.Compile(ast)); } } }
using SassSharp.Ast; using SassSharp.Tokens; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SassSharp { public class SassCompiler { public string Compile(string sass) { var tokenizer = new Tokenizer(); var builder = new SyntaxTreeBuilder(tokenizer.Tokenize(sass)); var compiler = new AstCompiler(); var render = new CssRenderer(); var ast = builder.Build(); Console.WriteLine(SyntaxTreeDumper.Dump(ast)); return render.Render(compiler.Compile(ast)); } } }
mit
C#
aeee80e13bf961bdba7d64e93b1be1c62bfdcd88
Remove culture
laedit/SemanticReleaseNotesParser,laedit/SemanticReleaseNotesParser,laedit/AV-GH-release-notes
SemanticReleaseNotesParser.Core/Properties/AssemblyInfo.cs
SemanticReleaseNotesParser.Core/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("SemanticReleaseNotesParser.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SemanticReleaseNotesParser.Core")] [assembly: AssemblyCopyright("Copyright © Laedit 2015")] [assembly: AssemblyTrademark("")] // 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("589794ec-4420-4b76-9b88-924d15148d51")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
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("SemanticReleaseNotesParser.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SemanticReleaseNotesParser.Core")] [assembly: AssemblyCopyright("Copyright © Laedit 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("en-US")] // 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("589794ec-4420-4b76-9b88-924d15148d51")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
fa7be52fa71ab991d7911c558b05ed48f2a1cda3
Revert "Force fix for new databases"
stevenhillcox/voting-application,Generic-Voting-Application/voting-application,tpkelly/voting-application,JDawes-ScottLogic/voting-application,stevenhillcox/voting-application,stevenhillcox/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application,JDawes-ScottLogic/voting-application,tpkelly/voting-application,Generic-Voting-Application/voting-application
VotingApplication/VotingApplication.Web.Api/Global.asax.cs
VotingApplication/VotingApplication.Web.Api/Global.asax.cs
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using VotingApplication.Data.Context; using VotingApplication.Web.Api.Migrations; namespace VotingApplication.Web.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...] // by not populating the Option.OptionSets after already encountering Session.OptionSet GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //Enable automatic migrations Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>()); new VotingContext().Database.Initialize(false); } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Newtonsoft.Json; using VotingApplication.Data.Context; using VotingApplication.Web.Api.Migrations; namespace VotingApplication.Web.Api { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); // Fix the infinite recursion of Session.OptionSet.Options[0].OptionSets[0].Options[0].[...] // by not populating the Option.OptionSets after already encountering Session.OptionSet GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; //Enable automatic migrations //Database.SetInitializer(new MigrateDatabaseToLatestVersion<VotingContext, Configuration>()); //new VotingContext().Database.Initialize(false); } } }
apache-2.0
C#
e40327226bd482b5b9cec20f5248aeb4929876f7
Update code task
roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon
R7.Epsilon/Skins/SkinObjects/EpsilonMenuBase.cs
R7.Epsilon/Skins/SkinObjects/EpsilonMenuBase.cs
// // File: EpsilonMenuBase.cs // Project: R7.Epsilon // // Author: Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015-2019 Roman M. Yagodin, R7.Labs // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using DotNetNuke.Web.DDRMenu.TemplateEngine; // aliases using DDRMenu = DotNetNuke.Web.DDRMenu; namespace R7.Epsilon.Skins.SkinObjects { // WTF: Removing this class causes issues with passing template arguments public abstract class EpsilonMenuBase: EpsilonSkinObjectBase { #region Controls protected DDRMenu.SkinObject Menu; #endregion } }
// // File: EpsilonMenuBase.cs // Project: R7.Epsilon // // Author: Roman M. Yagodin <roman.yagodin@gmail.com> // // Copyright (c) 2015-2019 Roman M. Yagodin, R7.Labs // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using DotNetNuke.Web.DDRMenu.TemplateEngine; // aliases using DDRMenu = DotNetNuke.Web.DDRMenu; namespace R7.Epsilon.Skins.SkinObjects { // TODO: Remove as not needed public abstract class EpsilonMenuBase: EpsilonSkinObjectBase { #region Controls protected DDRMenu.SkinObject Menu; #endregion } }
agpl-3.0
C#
e77b0a65a72eb7daeb005537a73d45334cc9f119
save of DGML fixed
ronin4net/Plainion.GraphViz,plainionist/Plainion.GraphViz,ronin4net/Plainion.GraphViz,plainionist/Plainion.GraphViz
src/Plainion.GraphViz.Modules.Documents/DGMLExporter.cs
src/Plainion.GraphViz.Modules.Documents/DGMLExporter.cs
using System; using System.IO; using System.Security; using Plainion.GraphViz.Model; namespace Plainion.GraphViz.Modules.Documents { class DgmlExporter { public static void Export(IGraph graph, Func<Node, string> GetNodeLabel, TextWriter writer) { Contract.RequiresNotNull(graph, "graph"); Contract.RequiresNotNull(writer, "writer"); writer.WriteLine("<DirectedGraph xmlns=\"http://schemas.microsoft.com/vs/2009/dgml\">"); writer.WriteLine(" <Nodes>"); foreach (var node in graph.Nodes) { writer.WriteLine(" <Node Id=\"{0}\" Label=\"{1}\" />", SecurityElement.Escape(node.Id), SecurityElement.Escape(GetNodeLabel(node))); } writer.WriteLine(" </Nodes>"); writer.WriteLine(" <Links>"); foreach (var edge in graph.Edges) { writer.WriteLine(" <Link Source=\"{0}\" Target=\"{1}\" />", SecurityElement.Escape(edge.Source.Id), SecurityElement.Escape(edge.Target.Id)); } writer.WriteLine(" </Links>"); writer.WriteLine("</DirectedGraph>"); } } }
using System; using System.IO; using Plainion.GraphViz.Model; namespace Plainion.GraphViz.Modules.Documents { class DgmlExporter { public static void Export(IGraph graph, Func<Node, string> GetNodeLabel, TextWriter writer) { Contract.RequiresNotNull(graph, "graph"); Contract.RequiresNotNull(writer, "writer"); writer.WriteLine("<DirectedGraph xmlns=\"http://schemas.microsoft.com/vs/2009/dgml\">"); writer.WriteLine(" <Nodes>"); foreach (var node in graph.Nodes) { writer.WriteLine(" <Node Id=\"{0}\" Label=\"{1}\" />", node.Id, GetNodeLabel(node)); } writer.WriteLine(" </Nodes>"); writer.WriteLine(" <Links>"); foreach (var edge in graph.Edges) { writer.WriteLine(" <Link Source=\"{0}\" Target=\"{1}\" />", edge.Source.Id, edge.Target.Id); } writer.WriteLine(" </Links>"); writer.WriteLine("</DirectedGraph>"); } } }
bsd-3-clause
C#
f10b86c9ec58018681d4df4e4a7a023da7c58dca
Fix RelationMapperProfiler
tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,KevinJump/Umbraco-CMS,hfloyd/Umbraco-CMS,mattbrailsford/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,madsoulswe/Umbraco-CMS,tcmorris/Umbraco-CMS,tcmorris/Umbraco-CMS,madsoulswe/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,lars-erik/Umbraco-CMS,mattbrailsford/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,lars-erik/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,bjarnef/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmuseeg/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,umbraco/Umbraco-CMS,madsoulswe/Umbraco-CMS,leekelleher/Umbraco-CMS,NikRimington/Umbraco-CMS,lars-erik/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,leekelleher/Umbraco-CMS
src/Umbraco.Web/Models/Mapping/RelationMapperProfile.cs
src/Umbraco.Web/Models/Mapping/RelationMapperProfile.cs
using AutoMapper; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { internal class RelationMapperProfile : Profile { public RelationMapperProfile() { // FROM IRelationType to RelationTypeDisplay CreateMap<IRelationType, RelationTypeDisplay>() .ForMember(dest => dest.Icon, opt => opt.Ignore()) .ForMember(dest => dest.Trashed, opt => opt.Ignore()) .ForMember(dest => dest.Alias, opt => opt.Ignore()) .ForMember(dest => dest.Path, opt => opt.Ignore()) .ForMember(dest => dest.AdditionalData, opt => opt.Ignore()) .ForMember(dest => dest.ChildObjectTypeName, opt => opt.Ignore()) .ForMember(dest => dest.ParentObjectTypeName, opt => opt.Ignore()) .ForMember(dest => dest.Relations, opt => opt.Ignore()) .ForMember(dest => dest.ParentId, opt => opt.Ignore()) .ForMember(dest => dest.Notifications, opt => opt.Ignore()) .ForMember(dest => dest.Udi, opt => opt.MapFrom(content => Udi.Create(Constants.UdiEntityType.RelationType, content.Key))) .AfterMap((src, dest) => { // Build up the path dest.Path = "-1," + src.Id; // Set the "friendly" names for the parent and child object types dest.ParentObjectTypeName = ObjectTypes.GetUmbracoObjectType(src.ParentObjectType).GetFriendlyName(); dest.ChildObjectTypeName = ObjectTypes.GetUmbracoObjectType(src.ChildObjectType).GetFriendlyName(); }); // FROM IRelation to RelationDisplay CreateMap<IRelation, RelationDisplay>() .ForMember(dest => dest.ParentName, opt => opt.Ignore()) .ForMember(dest => dest.ChildName, opt => opt.Ignore()); // FROM RelationTypeSave to IRelationType CreateMap<RelationTypeSave, IRelationType>() .ForMember(dest => dest.CreateDate, opt => opt.Ignore()) .ForMember(dest => dest.UpdateDate, opt => opt.Ignore()) .ForMember(dest => dest.DeleteDate, opt => opt.Ignore()); } } }
using AutoMapper; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Web.Models.ContentEditing; namespace Umbraco.Web.Models.Mapping { internal class RelationMapperProfile : Profile { public RelationMapperProfile() { // FROM IRelationType to RelationTypeDisplay CreateMap<IRelationType, RelationTypeDisplay>() .ForMember(x => x.Icon, expression => expression.Ignore()) .ForMember(x => x.Trashed, expression => expression.Ignore()) .ForMember(x => x.Alias, expression => expression.Ignore()) .ForMember(x => x.Path, expression => expression.Ignore()) .ForMember(x => x.AdditionalData, expression => expression.Ignore()) .ForMember(x => x.ChildObjectTypeName, expression => expression.Ignore()) .ForMember(x => x.ParentObjectTypeName, expression => expression.Ignore()) .ForMember(x => x.Relations, expression => expression.Ignore()) .ForMember( x => x.Udi, expression => expression.MapFrom( content => Udi.Create(Constants.UdiEntityType.RelationType, content.Key))) .AfterMap((src, dest) => { // Build up the path dest.Path = "-1," + src.Id; // Set the "friendly" names for the parent and child object types dest.ParentObjectTypeName = ObjectTypes.GetUmbracoObjectType(src.ParentObjectType).GetFriendlyName(); dest.ChildObjectTypeName = ObjectTypes.GetUmbracoObjectType(src.ChildObjectType).GetFriendlyName(); }); // FROM IRelation to RelationDisplay CreateMap<IRelation, RelationDisplay>(); // FROM RelationTypeSave to IRelationType CreateMap<RelationTypeSave, IRelationType>(); } } }
mit
C#
bc48ccef88b3ccd5231aaa3882d5d9e953923b1f
Add recurring job for reading status
mycroes/SupportManager,mycroes/SupportManager,mycroes/SupportManager
SupportManager.Control/SupportManagerService.cs
SupportManager.Control/SupportManagerService.cs
using Hangfire; using StructureMap; using SupportManager.Contracts; using SupportManager.Control.Infrastructure; using Topshelf; namespace SupportManager.Control { public class SupportManagerService : ServiceControl { private readonly IContainer container; private BackgroundJobServer jobServer; public SupportManagerService() { GlobalConfiguration.Configuration.UseSqlServerStorage("HangFire"); container = new Container(c => c.AddRegistry<AppRegistry>()); } public bool Start(HostControl hostControl) { jobServer = new BackgroundJobServer(GetJobServerOptions()); RecurringJob.AddOrUpdate<IForwarder>(f => f.ReadAllTeamStatus(), Cron.Minutely); return true; } public bool Stop(HostControl hostControl) { jobServer.Dispose(); return true; } private BackgroundJobServerOptions GetJobServerOptions() { return new BackgroundJobServerOptions { Activator = new NestedContainerActivator(container) }; } } }
using Hangfire; using StructureMap; using SupportManager.Control.Infrastructure; using Topshelf; namespace SupportManager.Control { public class SupportManagerService : ServiceControl { private readonly IContainer container; private BackgroundJobServer jobServer; public SupportManagerService() { GlobalConfiguration.Configuration.UseSqlServerStorage("HangFire"); container = new Container(c => c.AddRegistry<AppRegistry>()); } public bool Start(HostControl hostControl) { jobServer = new BackgroundJobServer(GetJobServerOptions()); return true; } public bool Stop(HostControl hostControl) { jobServer.Dispose(); return true; } private BackgroundJobServerOptions GetJobServerOptions() { return new BackgroundJobServerOptions { Activator = new NestedContainerActivator(container) }; } } }
mit
C#
eb3926e52cae67b32ba4832806ef185a4fc60f2c
fix cookies
FirebrandTech/fcs-sdk-net,FirebrandTech/fcs-sdk-net,FirebrandTech/fcs-sdk-net
Src/Framework/IContext.cs
Src/Framework/IContext.cs
// Copyright © 2010-2015 Firebrand Technologies using System; using System.Web; using System.Web.Security; using ServiceStack; using ServiceStack.Logging; namespace Fcs.Framework { public interface IContext { string CurrentUserName { get; } HttpCookie GetRequestCookie(string name); void SetResponseCookie(string name, string value, DateTime expires); } public class AspNetContext : IContext { private static readonly ILog Logger = LogManager.GetLogger("FcsClient"); public string CurrentUserName { get { if (HttpContext.Current == null) return null; if (HttpContext.Current.User == null) return null; if (HttpContext.Current.User.Identity == null) return null; return HttpContext.Current.User.Identity.Name; } } public HttpCookie GetRequestCookie(string name) { if (HttpContext.Current == null) return null; var cookies = HttpContext.Current.Request.Cookies; return cookies.Get(name); } public void SetResponseCookie(string name, string value, DateTime expires) { if (HttpContext.Current == null) return; var cookies = HttpContext.Current.Response.Cookies; value = HttpUtility.UrlEncode(value); var cookie = new HttpCookie(name) { Value = value, Path = FormsAuthentication.FormsCookiePath, HttpOnly = false, Secure = FormsAuthentication.RequireSSL, Expires = expires }; if (!string.IsNullOrWhiteSpace(FormsAuthentication.CookieDomain)) { cookie.Domain = FormsAuthentication.CookieDomain; } Logger.DebugFormat("SET COOKIE: {0}", cookie.ToJsv()); if (cookies.Get(name) != null) cookies.Remove(name); cookies.Add(cookie); } } }
// Copyright © 2010-2015 Firebrand Technologies using System; using System.Web; using System.Web.Security; namespace Fcs.Framework { public interface IContext { string CurrentUserName { get; } HttpCookie GetRequestCookie(string name); void SetResponseCookie(string name, string value, DateTime expires); } public class AspNetContext : IContext { public string CurrentUserName { get { if (HttpContext.Current == null) return null; if (HttpContext.Current.User == null) return null; if (HttpContext.Current.User.Identity == null) return null; return HttpContext.Current.User.Identity.Name; } } public HttpCookie GetRequestCookie(string name) { if (HttpContext.Current == null) return null; var cookies = HttpContext.Current.Request.Cookies; return cookies.Get(name); } public void SetResponseCookie(string name, string value, DateTime expires) { if (HttpContext.Current == null) return; var cookies = HttpContext.Current.Response.Cookies; value = HttpUtility.UrlEncode(value); var cookie = new HttpCookie(name) { Value = value, Path = FormsAuthentication.FormsCookiePath, HttpOnly = false, Secure = FormsAuthentication.RequireSSL, Expires = expires }; if (!string.IsNullOrWhiteSpace(FormsAuthentication.CookieDomain)) { cookie.Domain = FormsAuthentication.CookieDomain; } cookies.Remove(name); cookies.Add(cookie); } } }
mit
C#
5169a8f3b883929bc9af61bbac3ad449b8d7c6b1
Make Project visible by default.
ForNeVeR/ProjectAutomata
Importer.cs
Importer.cs
using System.Collections.Generic; using Microsoft.Office.Interop.MSProject; namespace ProjectAutomata { class Importer { public void Import(string fileName) { var tasks = GetTasks(fileName); var project = OpenProject(); CreateTasks(project, tasks); } private IEnumerable<TaskDescription> GetTasks(string fileName) { var parser = new Parser(); var stack = new Stack<TaskDescription>(); var allTasks = new List<TaskDescription>(parser.Parse(fileName)); foreach (var task in allTasks) { if (stack.Count == 0 || task.Level == 1) { stack.Push(task); continue; } while (task.Level <= stack.Peek().Level) { stack.Pop(); } stack.Peek().Children.Add(task); } return allTasks; } private Project OpenProject() { var msProject = new Application { Visible = true }; var application = msProject.Application; var project = application.Projects.Add(); return project; } private void CreateTasks(Project project, IEnumerable<TaskDescription> tasks) { foreach (var taskDescription in tasks) { var task = project.Tasks.Add(taskDescription.Name); task.OutlineLevel = (short)taskDescription.Level; task.Notes = taskDescription.Note; if (taskDescription.Children.Count == 0) { double work = taskDescription.Estimation.TotalMinutes; task.Work = work; } } } } }
using System.Collections.Generic; using Microsoft.Office.Interop.MSProject; namespace ProjectAutomata { class Importer { public void Import(string fileName) { var tasks = GetTasks(fileName); var project = OpenProject(); CreateTasks(project, tasks); } private IEnumerable<TaskDescription> GetTasks(string fileName) { var parser = new Parser(); var stack = new Stack<TaskDescription>(); var allTasks = new List<TaskDescription>(parser.Parse(fileName)); foreach (var task in allTasks) { if (stack.Count == 0 || task.Level == 1) { stack.Push(task); continue; } while (task.Level <= stack.Peek().Level) { stack.Pop(); } stack.Peek().Children.Add(task); } return allTasks; } private Project OpenProject() { var msProject = new Application(); var application = msProject.Application; var project = application.Projects.Add(); return project; } private void CreateTasks(Project project, IEnumerable<TaskDescription> tasks) { foreach (var taskDescription in tasks) { var task = project.Tasks.Add(taskDescription.Name); task.OutlineLevel = (short)taskDescription.Level; task.Notes = taskDescription.Note; if (taskDescription.Children.Count == 0) { double work = taskDescription.Estimation.TotalMinutes; task.Work = work; } } } } }
mit
C#
cb3e032b6228c04d44fc8414eb8e4f5dcd3433eb
Make sure grid is not still initializing when verifying its data
2sky/Vidyano,2sky/Vidyano,2sky/Vidyano,2sky/Vidyano,2sky/Vidyano
test/GlobalSearch.cs
test/GlobalSearch.cs
using NUnit.Framework; using OpenQA.Selenium; using System.Linq; namespace Vidyano.Test { [TestFixture("chrome")] [TestFixture("safari")] [TestFixture("firefox")] [TestFixture("edge")] [TestFixture("ie")] [Parallelizable(ParallelScope.Fixtures)] public class GlobalSearch: BrowserStackTestBase { public GlobalSearch(string profile): base(profile) {} [Test] public void Search() { var search = "pei"; var input = driver.FindElement(By.CssSelector("vi-menu vi-input-search > input")); input.SendKeys(search); input.SendKeys(Keys.Enter); Assert.That(driver.FindElement(By.CssSelector("vi-query-grid:not(.initializing)")), Is.Not.Null); var firstRow = driver.FindElement(By.CssSelector("vi-query-grid tr[is='vi-query-grid-table-data-row']:first-of-type")); Assert.That(firstRow, Is.Not.Null, "Unable to find first data row."); Assert.That(driver.Title.StartsWith(search), Is.True, "Invalid title after search."); var cells = firstRow.FindElements(By.TagName("vi-query-grid-cell-default")); Assert.That(cells.FirstOrDefault(c => c.Text.Contains(search)), Is.Not.Null, "No match found."); } } }
using NUnit.Framework; using OpenQA.Selenium; using System.Linq; namespace Vidyano.Test { [TestFixture("chrome")] [TestFixture("safari")] [TestFixture("firefox")] [TestFixture("edge")] [TestFixture("ie")] [Parallelizable(ParallelScope.Fixtures)] public class GlobalSearch: BrowserStackTestBase { public GlobalSearch(string profile): base(profile) {} [Test] public void Search() { var search = "pei"; var input = driver.FindElement(By.CssSelector("vi-menu vi-input-search > input")); input.SendKeys(search); input.SendKeys(Keys.Enter); var firstRow = driver.FindElement(By.CssSelector("vi-query-grid tr[is='vi-query-grid-table-data-row']:first-of-type")); Assert.That(firstRow, Is.Not.Null, "Unable to find first data row."); Assert.That(driver.Title.StartsWith(search), Is.True, "Invalid title after search."); var cells = firstRow.FindElements(By.TagName("vi-query-grid-cell-default")); Assert.That(cells.FirstOrDefault(c => c.Text.Contains(search)), Is.Not.Null, "No match found."); } } }
mit
C#
502c48416913fac5ea777da555afc4c7d7d0bf74
Make WbEntityEditEntry sealed.
CXuesong/WikiClientLibrary
WikiClientLibrary.Wikibase/WbEntityEditEntry.cs
WikiClientLibrary.Wikibase/WbEntityEditEntry.cs
using System; using System.Collections.Generic; using System.Text; namespace WikiClientLibrary.Wikibase { /// <summary> /// Represents an item of coarse-grained modification information on <see cref="WbEntity"/>. /// </summary> public sealed class WbEntityEditEntry { private WbEntityEditEntryState _State; public WbEntityEditEntry(string propertyName, object value) : this(propertyName, value, WbEntityEditEntryState.Updated) { } public WbEntityEditEntry(string propertyName, object value, WbEntityEditEntryState state) { PropertyName = propertyName; Value = value; State = state; } public WbEntityEditEntry() { } /// <summary> /// The CLR property name of the changed value. /// </summary> /// <remarks> /// This is usually a property name in <see cref="WbEntity"/>. /// </remarks> public string PropertyName { get; set; } /// <summary> /// The new item, updated existing item, or for the deletion, /// the item that has enough information to determine the item to remove. /// </summary> public object Value { get; set; } /// <summary> /// The operation performed on this entry. /// </summary> public WbEntityEditEntryState State { get { return _State; } set { if (value != WbEntityEditEntryState.Updated && value != WbEntityEditEntryState.Removed) throw new ArgumentOutOfRangeException(nameof(value)); _State = value; } } } public enum WbEntityEditEntryState { /// <summary> /// Either the entry is a new item, or the value inside the item has been changed. /// </summary> Updated = 0, /// <summary> /// The entry represents an item to be removed. /// </summary> Removed = 1, } }
using System; using System.Collections.Generic; using System.Text; namespace WikiClientLibrary.Wikibase { /// <summary> /// Represents an item of coarse-grained modification information on <see cref="WbEntity"/>. /// </summary> public class WbEntityEditEntry { private WbEntityEditEntryState _State; public WbEntityEditEntry(string propertyName, object value) : this(propertyName, value, WbEntityEditEntryState.Updated) { } public WbEntityEditEntry(string propertyName, object value, WbEntityEditEntryState state) { PropertyName = propertyName; Value = value; State = state; } public WbEntityEditEntry() { } /// <summary> /// The CLR property name of the changed value. /// </summary> /// <remarks> /// This is usually a property name in <see cref="WbEntity"/>. /// </remarks> public string PropertyName { get; set; } /// <summary> /// The new item, updated existing item, or for the deletion, /// the item that has enough information to determine the item to remove. /// </summary> public object Value { get; set; } /// <summary> /// The operation performed on this entry. /// </summary> public WbEntityEditEntryState State { get { return _State; } set { if (value != WbEntityEditEntryState.Updated && value != WbEntityEditEntryState.Removed) throw new ArgumentOutOfRangeException(nameof(value)); _State = value; } } } public enum WbEntityEditEntryState { /// <summary> /// Either the entry is a new item, or the inside value of the item has been changed. /// </summary> Updated = 0, Removed = 1, } }
apache-2.0
C#
5964bb9c134c29dfa1b7023c851e7f660eac4d13
Check hack to generate partial methods in c#
vjacquet/WmcSoft
WmcSoft.CodeDom.Tests/CodeDomExtensionsTests.cs
WmcSoft.CodeDom.Tests/CodeDomExtensionsTests.cs
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.IO; using System.Text; using Microsoft.CSharp; using Xunit; using Xunit.Abstractions; namespace WmcSoft.CodeDom.Tests { public class CodeDomExtensionsTests { private readonly ITestOutputHelper _output; public CodeDomExtensionsTests(ITestOutputHelper output) { _output = output; } [Fact] public void CanCreateTryCatchFinallyBlocks() { var compileUnit = new CodeCompileUnit(); var samples = new CodeNamespace("Samples"); samples.Imports.Add(new CodeNamespaceImport("System")); compileUnit.Namespaces.Add(samples); var class1 = new CodeTypeDeclaration("Class1"); samples.Types.Add(class1); var start = new CodeEntryPointMethod(); class1.Members.Add(start); var try1 = new CodeTryCatchFinallyStatement(); var cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); var result = try1.Try(new CodeExpressionStatement(cs1)) .Catch<ArgumentException>("e"); Assert.Equal(try1, result); var provider = new CSharpCodeProvider(); var sb = new StringBuilder(); using (var writer = new IndentedTextWriter(new StringWriter(sb), " ")) provider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions { }); _output.WriteLine(sb.ToString()); } [Fact] public void CanCreatePartialMethod() { var compileUnit = new CodeCompileUnit(); var samples = new CodeNamespace("Samples"); samples.Imports.Add(new CodeNamespaceImport("System")); compileUnit.Namespaces.Add(samples); var c = new CodeTypeDeclaration("C") { IsPartial = true }; samples.Types.Add(c); var m = new CodeMemberMethod { Attributes = MemberAttributes.Abstract, Name = "M", ReturnType = new CodeTypeReference() }; var provider = new CSharpCodeProvider(); var sb = new StringBuilder(); using (var writer = new IndentedTextWriter(new StringWriter(sb), " ")) provider.GenerateCodeFromMember(m, writer, new CodeGeneratorOptions { }); var text = " " + string.Join("partial", sb.ToString().Trim().Split(new[] { "abstract" }, 2, StringSplitOptions.None)); var snippet = new CodeSnippetTypeMember(text); c.Members.Add(snippet); sb.Clear(); using (var writer = new IndentedTextWriter(new StringWriter(sb), " ")) provider.GenerateCodeFromCompileUnit(compileUnit, writer, new CodeGeneratorOptions { }); var result = sb.ToString(); Assert.NotNull(result); _output.WriteLine(result); } } }
using System; using System.CodeDom; using Xunit; namespace WmcSoft.CodeDom.Tests { public class CodeDomExtensionsTests { [Fact] public void CanCreateTryCatchFinallyBlocks() { var compileUnit = new CodeCompileUnit(); var samples = new CodeNamespace("Samples"); samples.Imports.Add(new CodeNamespaceImport("System")); compileUnit.Namespaces.Add(samples); var class1 = new CodeTypeDeclaration("Class1"); samples.Types.Add(class1); var start = new CodeEntryPointMethod(); class1.Members.Add(start); var try1 = new CodeTryCatchFinallyStatement(); var cs1 = new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("System.Console"), "WriteLine", new CodePrimitiveExpression("Hello World!")); var result = try1.Try(new CodeExpressionStatement(cs1)) .Catch<ArgumentException>("e"); Assert.Equal(try1, result); } } }
mit
C#
0a9411f09fcc74bafd348718158b14ab02363387
Update PrimeNumbers.cs
DanielaPopova/TelerikAcademy_Homeworks,DanielaPopova/TelerikAcademy_Homeworks,DanielaPopova/TelerikAcademy_Homeworks
C#2/Arrays_HW/Problem15_PrimeNumbers/PrimeNumbers.cs
C#2/Arrays_HW/Problem15_PrimeNumbers/PrimeNumbers.cs
// 100/100 bgcoder namespace Homeworks { using System; class Program { static void Main() { int length = int.Parse(Console.ReadLine()); byte[] isPrime = new byte[length + 1]; int biggestPrime = 0; for (int i = 2; i <= length; i++) { if (isPrime[i] == 0) { biggestPrime = i; for (int j = i * 2; j <= length; j += i) { isPrime[j] = 1; } } } Console.WriteLine(biggestPrime); } } } //using System; //class PrimeNumbers //{ // static void Main() // { // //60/100 bgcoder - timeLimit // int num = int.Parse(Console.ReadLine()); // int[] array = new int[num + 1]; // int maxNum = int.MinValue; // int count = 2; // for (int i = 2; i <= num; i++) // { // array[i] = count; // count++; // } // for (int i = 2; i * i <= num; i++) // { // for (int j = (i * i); j <= num; j = j + i) // { // array[j] = 0; // } // } // Array.Sort(array); // maxNum = array[array.Length - 1]; // Console.WriteLine(maxNum); // } //}
using System; class PrimeNumbers { static void Main() { //60/100 bgcoder - timeLimit int num = int.Parse(Console.ReadLine()); int[] array = new int[num + 1]; int maxNum = int.MinValue; int count = 2; for (int i = 2; i <= num; i++) { array[i] = count; count++; } for (int i = 2; i * i <= num; i++) { for (int j = (i * i); j <= num; j = j + i) { array[j] = 0; } } Array.Sort(array); maxNum = array[array.Length - 1]; Console.WriteLine(maxNum); } } // 100/100 bgcoder //namespace Homeworks //{ // using System; // class Program // { // static void Main() // { // int length = int.Parse(Console.ReadLine()); // byte[] isPrime = new byte[length + 1]; // int biggestPrime = 0; // for (int i = 2; i <= length; i++) // { // if (isPrime[i] == 0) // { // biggestPrime = i; // for (int j = i * 2; j <= length; j += i) // { // isPrime[j] = 1; // } // } // } // Console.WriteLine(biggestPrime); // } // } //}
mit
C#
f1bfc9d56a5233622a36252ee5bb8769792f1e1c
Fix converter for possible null values.
igitur/ClosedXML,b0bi79/ClosedXML,ClosedXML/ClosedXML
ClosedXML/Utils/OpenXmlHelper.cs
ClosedXML/Utils/OpenXmlHelper.cs
using DocumentFormat.OpenXml; namespace ClosedXML.Utils { internal static class OpenXmlHelper { public static BooleanValue GetBooleanValue(bool value, bool defaultValue) { return value == defaultValue ? null : new BooleanValue(value); } public static bool GetBooleanValueAsBool(BooleanValue value, bool defaultValue) { return (value?.HasValue ?? false) ? value.Value : defaultValue; } } }
using DocumentFormat.OpenXml; namespace ClosedXML.Utils { internal static class OpenXmlHelper { public static BooleanValue GetBooleanValue(bool value, bool defaultValue) { return value == defaultValue ? null : new BooleanValue(value); } public static bool GetBooleanValueAsBool(BooleanValue value, bool defaultValue) { return value.HasValue ? value.Value : defaultValue; } } }
mit
C#
de249140c017a508db7ed8ce68c648d76728e3e2
Fix an issue where SUBTOTAL would include non-tokenized subtotal precedents.
jetreports/EPPlus
EPPlus/FormulaParsing/Excel/Functions/CellStateHelper.cs
EPPlus/FormulaParsing/Excel/Functions/CellStateHelper.cs
/* Copyright (C) 2011 Jan Källman * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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. * * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html * * All code and executables are provided "as is" with no warranty either express or implied. * The author accepts no liability for any damage or loss of business that this product may cause. * * Code change notes: * * Author Change Date ******************************************************************************* * Mats Alm Added 2013-12-03 *******************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using OfficeOpenXml.FormulaParsing.LexicalAnalysis; namespace OfficeOpenXml.FormulaParsing.Excel.Functions { internal static class CellStateHelper { #region Static Methods private static bool IsSubTotal(ExcelDataProvider.ICellInfo c, ParsingContext context) { IEnumerable<Token> tokens = c.Tokens; if (tokens == null) { if (string.IsNullOrEmpty(c.Formula)) return false; else { tokens = context.Parser.Lexer.Tokenize(c.Formula); } } return tokens.Any(token => token.TokenType == TokenType.Function && token.Value.Equals("SUBTOTAL", StringComparison.InvariantCultureIgnoreCase) ); } internal static bool ShouldIgnore(bool ignoreHiddenValues, ExcelDataProvider.ICellInfo c, ParsingContext context) { return (ignoreHiddenValues && c.IsHiddenRow) || (context.Scopes.Current.IsSubtotal && CellStateHelper.IsSubTotal(c, context)); } internal static bool ShouldIgnore(bool ignoreHiddenValues, FunctionArgument arg, ParsingContext context) { return (ignoreHiddenValues && arg.ExcelStateFlagIsSet(ExcelCellState.HiddenCell)); } #endregion } }
/* Copyright (C) 2011 Jan Källman * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * This library 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. * * The GNU Lesser General Public License can be viewed at http://www.opensource.org/licenses/lgpl-license.php * If you unfamiliar with this license or have questions about it, here is an http://www.gnu.org/licenses/gpl-faq.html * * All code and executables are provided "as is" with no warranty either express or implied. * The author accepts no liability for any damage or loss of business that this product may cause. * * Code change notes: * * Author Change Date ******************************************************************************* * Mats Alm Added 2013-12-03 *******************************************************************************/ using System; using System.Linq; namespace OfficeOpenXml.FormulaParsing.Excel.Functions { internal static class CellStateHelper { private static bool IsSubTotal(ExcelDataProvider.ICellInfo c) { var tokens = c.Tokens; if (tokens == null) return false; return c.Tokens.Any(token => token.TokenType == LexicalAnalysis.TokenType.Function && token.Value.Equals("SUBTOTAL", StringComparison.InvariantCultureIgnoreCase) ); } internal static bool ShouldIgnore(bool ignoreHiddenValues, ExcelDataProvider.ICellInfo c, ParsingContext context) { return (ignoreHiddenValues && c.IsHiddenRow) || (context.Scopes.Current.IsSubtotal && IsSubTotal(c)); } internal static bool ShouldIgnore(bool ignoreHiddenValues, FunctionArgument arg, ParsingContext context) { return (ignoreHiddenValues && arg.ExcelStateFlagIsSet(ExcelCellState.HiddenCell)); } } }
lgpl-2.1
C#
d3efd35417d9bb0603c923ce66f68d1248c40d07
Fix cross thread error
nwoolls/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,IWBWbiz/MultiMiner
MultiMiner.Win/HourGlass.cs
MultiMiner.Win/HourGlass.cs
using System; using System.Windows.Forms; using System.Runtime.InteropServices; using MultiMiner.Utility; namespace MultiMiner.Win { public class HourGlass : IDisposable { public HourGlass() { Enabled = true; } public void Dispose() { Enabled = false; } public static bool Enabled { get { return Application.UseWaitCursor; } set { if (value == Application.UseWaitCursor) return; Application.UseWaitCursor = value; Form activeForm = Form.ActiveForm; if (activeForm != null) { if (activeForm.InvokeRequired) activeForm.BeginInvoke((Action)(() => { CheckAndShowCursor(activeForm); })); else CheckAndShowCursor(activeForm); } Application.DoEvents(); } } private static void CheckAndShowCursor(Form activeForm) { if (activeForm.Handle != null && (OSVersionPlatform.GetGenericPlatform() != PlatformID.Unix)) // Send WM_SETCURSOR SendMessage(activeForm.Handle, 0x20, activeForm.Handle, (IntPtr)1); } [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); } }
using System; using System.Windows.Forms; using System.Runtime.InteropServices; using MultiMiner.Utility; namespace MultiMiner.Win { public class HourGlass : IDisposable { public HourGlass() { Enabled = true; } public void Dispose() { Enabled = false; } public static bool Enabled { get { return Application.UseWaitCursor; } set { if (value == Application.UseWaitCursor) return; Application.UseWaitCursor = value; Form f = Form.ActiveForm; if (f != null && f.Handle != null && (OSVersionPlatform.GetGenericPlatform() != PlatformID.Unix)) // Send WM_SETCURSOR SendMessage(f.Handle, 0x20, f.Handle, (IntPtr)1); Application.DoEvents(); } } [DllImport("user32.dll")] private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp); } }
mit
C#
35d04bd22355bcc5d873524c1f66c2a70366db58
increment TableIO ver
nabehiro/TableIO
src/TableIO/Properties/AssemblyInfo.cs
src/TableIO/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TableIO")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TableIO")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("aaf3b134-9271-4aca-8ca4-d4bdb420839c")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: InternalsVisibleTo("TableIO.Tests")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("TableIO")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TableIO")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("aaf3b134-9271-4aca-8ca4-d4bdb420839c")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: InternalsVisibleTo("TableIO.Tests")]
apache-2.0
C#
d585354d4ecbfca1066d7b886c0f056efd7c89ef
Increment version to 2.0.0
MacDennis76/Unicorn,bllue78/Unicorn,kamsar/Unicorn,PetersonDave/Unicorn,rmwatson5/Unicorn,GuitarRich/Unicorn,rmwatson5/Unicorn,MacDennis76/Unicorn,GuitarRich/Unicorn,kamsar/Unicorn,PetersonDave/Unicorn,bllue78/Unicorn
src/Unicorn/Properties/AssemblyInfo.cs
src/Unicorn/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("Unicorn")] [assembly: AssemblyDescription("Sitecore serialization helper framework")] // 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("c7d93d67-1319-4d3c-b2f8-f74fdff6fb07")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Unicorn")] [assembly: AssemblyDescription("Sitecore serialization helper framework")] // 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("c7d93d67-1319-4d3c-b2f8-f74fdff6fb07")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-RC10")]
mit
C#
b8749164a20129a0f220d9f61b05333138fef5f2
Revert the CWD update change
robinrodricks/FluentFTP,robinrodricks/FluentFTP,robinrodricks/FluentFTP
FluentFTP/Client/BaseClient/Execute.cs
FluentFTP/Client/BaseClient/Execute.cs
using System; using FluentFTP.Client.Modules; using FluentFTP.Helpers; namespace FluentFTP.Client.BaseClient { public partial class BaseFtpClient { /// <summary> /// Executes a command /// </summary> /// <param name="command">The command to execute</param> /// <returns>The servers reply to the command</returns> FtpReply IInternalFtpClient.ExecuteInternal(string command) { FtpReply reply; lock (m_lock) { if (Config.StaleDataCheck && Status.AllowCheckStaleData) { ReadStaleData(true, true, "prior to command execution"); } if (!IsConnected) { if (command == "QUIT") { LogWithPrefix(FtpTraceLevel.Info, "Not sending QUIT because the connection has already been closed."); return new FtpReply() { Code = "200", Message = "Connection already closed." }; } ((IInternalFtpClient)this).ConnectInternal(); } // hide sensitive data from logs string commandClean = LogMaskModule.MaskCommand(this, command); Log(FtpTraceLevel.Info, "Command: " + commandClean); // send command to FTP server m_stream.WriteLine(m_textEncoding, command); LastCommandTimestamp = DateTime.UtcNow; reply = GetReplyInternal(command); if (reply.Success) { OnPostExecute(command); } return reply; } } protected void OnPostExecute(string command) { // Update stored values if (command.TrimEnd() == "CWD" || command.StartsWith("CWD ", StringComparison.Ordinal)) { Status.LastWorkingDir = null; } else if (command.StartsWith("TYPE I", StringComparison.Ordinal)) { Status.CurrentDataType = FtpDataType.Binary; } else if (command.StartsWith("TYPE A", StringComparison.Ordinal)) { Status.CurrentDataType = FtpDataType.ASCII; } } } }
using System; using FluentFTP.Client.Modules; using FluentFTP.Helpers; namespace FluentFTP.Client.BaseClient { public partial class BaseFtpClient { /// <summary> /// Executes a command /// </summary> /// <param name="command">The command to execute</param> /// <returns>The servers reply to the command</returns> FtpReply IInternalFtpClient.ExecuteInternal(string command) { FtpReply reply; lock (m_lock) { if (Config.StaleDataCheck && Status.AllowCheckStaleData) { ReadStaleData(true, true, "prior to command execution"); } if (!IsConnected) { if (command == "QUIT") { LogWithPrefix(FtpTraceLevel.Info, "Not sending QUIT because the connection has already been closed."); return new FtpReply() { Code = "200", Message = "Connection already closed." }; } ((IInternalFtpClient)this).ConnectInternal(); } // hide sensitive data from logs string commandClean = LogMaskModule.MaskCommand(this, command); Log(FtpTraceLevel.Info, "Command: " + commandClean); // send command to FTP server m_stream.WriteLine(m_textEncoding, command); LastCommandTimestamp = DateTime.UtcNow; reply = GetReplyInternal(command); if (reply.Success) { OnPostExecute(command); } return reply; } } protected void OnPostExecute(string command) { // Update stored values if (command.TrimEnd() == "CWD") { Status.LastWorkingDir = null; } else if (command.StartsWith("CWD ", StringComparison.Ordinal)) { Status.LastWorkingDir = command.Substring(4).Trim(); } else if (command.StartsWith("TYPE I", StringComparison.Ordinal)) { Status.CurrentDataType = FtpDataType.Binary; } else if (command.StartsWith("TYPE A", StringComparison.Ordinal)) { Status.CurrentDataType = FtpDataType.ASCII; } } } }
mit
C#
cf25e98eb6becdc60cc74fc1e17a5c4e698e13f7
fix Upgrade_20210824_UpdateNugets
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20210824_UpdateNugets.cs
Signum.Upgrade/Upgrades/Upgrade_20210824_UpdateNugets.cs
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20210824_UpdateNugets : CodeUpgradeBase { public override string Description => "Upgrade some Nugets"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"*.csproj", file => { file.UpdateNugetReference("Signum.Analyzer", "3.1.0"); file.UpdateNugetReference("Microsoft.TypeScript.MSBuild", "4.3.5"); file.UpdateNugetReference("Microsoft.VisualStudio.Azure.Containers.Tools.Targets", "1.11.1"); file.UpdateNugetReference("Swashbuckle.AspNetCore", "6.1.5"); file.UpdateNugetReference("SciSharp.TensorFlow.Redist", "2.6.0"); file.UpdateNugetReference("Microsoft.NET.Test.Sdk", "16.11.0"); file.UpdateNugetReference("DocumentFormat.OpenXml", "2.13.1"); }); } } }
using Signum.Utilities; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; namespace Signum.Upgrade.Upgrades { class Upgrade_20210824_UpdateNugets : CodeUpgradeBase { public override string Description => "Upgrade some Nugets"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"*.csproj", file => { file.UpdateNugetReference("Signum.Analyzer", "3.1.0"); file.UpdateNugetReference("Microsoft.TypeScript.MSBuild", "4.3.5"); file.UpdateNugetReference("Microsoft.VisualStudio.Azure.Containers.Tools.Targets", "1.11.1"); file.UpdateNugetReference("Swashbuckle.AspNetCore", "6.1.5"); file.UpdateNugetReference("SciSharp.TensorFlow.Redist", "2.6.0"); file.UpdateNugetReference("Microsoft.NET.Test.Sdk", "16.11.0"); }); } } }
mit
C#
e6f4cf34043f1bac3e7acdc42ca6db54984ab479
Update BigAppliances.cs
jkanchelov/Telerik-OOP-Team-StarFruit
TeamworkStarFruit/CatalogueLib/Products/BigAppliances.cs
TeamworkStarFruit/CatalogueLib/Products/BigAppliances.cs
namespace CatalogueLib { using System.Text; using CatalogueLib.Products.Enumerations; public abstract class BigAppliances : Product { public BigAppliances() { } public BigAppliances(int ID, decimal price, bool isAvailable, Brand brand, string Color, string CountryOfOrigin) : base(ID, price, isAvailable, brand) { this.Color = Color; this.CountryOfOrigin = CountryOfOrigin; } public string Color { get; private set; } public string CountryOfOrigin { get; private set; } public override string ToString() { StringBuilder outline = new StringBuilder(); outline = outline.Append(string.Format("{0}", base.ToString())); outline = outline.Append(string.Format(" Color: {0}", this.Color)); outline = outline.AppendLine(); outline = outline.Append(string.Format(" Made in: {0}", this.CountryOfOrigin)); return outline.AppendLine().ToString(); } } }
namespace CatalogueLib { using System.Text; using CatalogueLib.Products.Enumerations; public abstract class BigAppliances : Product { public BigAppliances() { } public BigAppliances(int ID, decimal price, bool isAvailable, Brand brand, string Color, string CountryOfOrigin) : base(ID, price, isAvailable, brand) { this.Color = Color; this.CountryOfOrigin = CountryOfOrigin; } public string Color { get; private set; } public string CountryOfOrigin { get; private set; } public override string ToString() { StringBuilder stroitel = new StringBuilder(); stroitel = stroitel.Append(string.Format("{0}", base.ToString())); stroitel = stroitel.Append(string.Format(" Color: {0}\n Country of origin: {1}", this.Color, this.CountryOfOrigin)); return stroitel.AppendLine().ToString(); } } }
mit
C#
ad739f06bc52fd8504d87e61408ef7f8cd1eecc6
Use calculated property.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Models/TransactionBuilding/PaymentIntent.cs
WalletWasabi/Models/TransactionBuilding/PaymentIntent.cs
using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalletWasabi.Helpers; namespace WalletWasabi.Models.TransactionBuilding { public class PaymentIntent { public IEnumerable<DestinationRequest> Requests { get; } public ChangeStrategy ChangeStrategy { get; } public Money TotalAmount { get; } public int Count => Requests.Count(); public PaymentIntent(Script scriptPubKey, Money amount, string label = "") : this(scriptPubKey, MoneyRequest.Create(amount), label) { } public PaymentIntent(Script scriptPubKey, MoneyRequest amount, string label = "") : this(scriptPubKey.GetDestination(), amount, label) { } public PaymentIntent(IDestination destination, Money amount, string label = "") : this(destination, MoneyRequest.Create(amount), label) { } public PaymentIntent(IDestination destination, MoneyRequest amount, string label = "") : this(new DestinationRequest(destination, amount, label)) { } public PaymentIntent(params DestinationRequest[] requests) : this(requests as IEnumerable<DestinationRequest>) { } public PaymentIntent(IEnumerable<DestinationRequest> requests) { Guard.NotNullOrEmpty(nameof(requests), requests); foreach (var request in requests) { Guard.NotNull(nameof(request), request); } var allSpendCount = requests.Count(x => x.Amount.Type == MoneyRequestType.AllRemaining); if (allSpendCount == 0) { ChangeStrategy = ChangeStrategy.Auto; } else if (allSpendCount == 1) { ChangeStrategy = ChangeStrategy.Custom; } else { throw new ArgumentException($"Only one request can contain an all remaining money request."); } Requests = requests; TotalAmount = requests.Where(x => x.Amount.Type == MoneyRequestType.Value).Sum(x => x.Amount.Amount); } public bool TryGetCustomChange(out DestinationRequest customChange) { customChange = Requests.FirstOrDefault(x => x.Amount.Type == MoneyRequestType.AllRemaining); return customChange != null; } } }
using NBitcoin; using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalletWasabi.Helpers; namespace WalletWasabi.Models.TransactionBuilding { public class PaymentIntent { public IEnumerable<DestinationRequest> Requests { get; } public ChangeStrategy ChangeStrategy { get; } public Money TotalAmount { get; } public int Count { get; } public PaymentIntent(Script scriptPubKey, Money amount, string label = "") : this(scriptPubKey, MoneyRequest.Create(amount), label) { } public PaymentIntent(Script scriptPubKey, MoneyRequest amount, string label = "") : this(scriptPubKey.GetDestination(), amount, label) { } public PaymentIntent(IDestination destination, Money amount, string label = "") : this(destination, MoneyRequest.Create(amount), label) { } public PaymentIntent(IDestination destination, MoneyRequest amount, string label = "") : this(new DestinationRequest(destination, amount, label)) { } public PaymentIntent(params DestinationRequest[] requests) : this(requests as IEnumerable<DestinationRequest>) { } public PaymentIntent(IEnumerable<DestinationRequest> requests) { Guard.NotNullOrEmpty(nameof(requests), requests); foreach (var request in requests) { Guard.NotNull(nameof(request), request); } var allSpendCount = requests.Count(x => x.Amount.Type == MoneyRequestType.AllRemaining); if (allSpendCount == 0) { ChangeStrategy = ChangeStrategy.Auto; } else if (allSpendCount == 1) { ChangeStrategy = ChangeStrategy.Custom; } else { throw new ArgumentException($"Only one request can contain an all remaining money request."); } Requests = requests; TotalAmount = requests.Where(x => x.Amount.Type == MoneyRequestType.Value).Sum(x => x.Amount.Amount); Count = requests.Count(); } public bool TryGetCustomChange(out DestinationRequest customChange) { customChange = Requests.FirstOrDefault(x => x.Amount.Type == MoneyRequestType.AllRemaining); return customChange != null; } } }
mit
C#
9040a7586ce0a81cfa1f810d448a729328a67df4
fix bug
sagivo/ggj16
Assets/Scripts/GameController.cs
Assets/Scripts/GameController.cs
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameController : BaseObject { //Color originalColor; Item pressedItem; public Image[] lifeImages; public int life = 3; public Sprite decImage; public static GameController game; public Text t; // Use this for initialization new void Start () { base.Start (); if (!game) game = this; MiniGestureRecognizer.Swipe += (MiniGestureRecognizer.SwipeDirection dir) => { //t.text = dir.ToString(); if (pressedItem && pressedItem.swipeDirection == dir && pressedItem.state != Item.ItemState.Broken) reset(); }; } // Update is called once per frame new void Update () { base.Update (); if (Input.GetMouseButtonDown (0) && !pressedItem) { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast (ray, out hit, 100) && hit.collider.GetComponent<Item> ()) { pressedItem = hit.collider.GetComponent<Item> (); if (pressedItem && pressedItem.state != Item.ItemState.Broken) { if (pressedItem.swipeDirection == MiniGestureRecognizer.SwipeDirection.NONE) { pressedItem.press (); Invoke ("reset", pressedItem.holdToResetPerState [(int)pressedItem.state]); } } } } else if (Input.GetMouseButtonUp (0) && pressedItem) { CancelInvoke ("reset"); pressedItem.release (); pressedItem = null; } } void reset(){ pressedItem.reset (); if (pressedItem) Invoke ("reset", pressedItem.holdToResetPerState [(int)pressedItem.state]); } public void dec(){ life--; if (life >= 0) { lifeImages [life].sprite = decImage; } else die (); } public void die(){ l ("i'm dead!"); ApplicationModel.ObjectID = 11; Application.LoadLevel ("letter"); } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class GameController : BaseObject { //Color originalColor; Item pressedItem; public Image[] lifeImages; public int life = 3; public Sprite decImage; public static GameController game; public Text t; // Use this for initialization new void Start () { base.Start (); if (!game) game = this; MiniGestureRecognizer.Swipe += (MiniGestureRecognizer.SwipeDirection dir) => { //t.text = dir.ToString(); if (pressedItem && pressedItem.swipeDirection == dir) reset(); }; } // Update is called once per frame new void Update () { base.Update (); if (Input.GetMouseButtonDown (0) && !pressedItem) { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if (Physics.Raycast (ray, out hit, 100) && hit.collider.GetComponent<Item> ()) { pressedItem = hit.collider.GetComponent<Item> (); if (pressedItem && pressedItem.state != Item.ItemState.Broken) { if (pressedItem.swipeDirection == MiniGestureRecognizer.SwipeDirection.NONE) { pressedItem.press (); Invoke ("reset", pressedItem.holdToResetPerState [(int)pressedItem.state]); } } } } else if (Input.GetMouseButtonUp (0) && pressedItem) { CancelInvoke ("reset"); pressedItem.release (); pressedItem = null; } } void reset(){ pressedItem.reset (); if (pressedItem) Invoke ("reset", pressedItem.holdToResetPerState [(int)pressedItem.state]); } public void dec(){ life--; if (life >= 0) { lifeImages [life].sprite = decImage; } else die (); } public void die(){ l ("i'm dead!"); ApplicationModel.ObjectID = 11; Application.LoadLevel ("letter"); } }
apache-2.0
C#
b02c06f210ce74e37394dc2c38966925a0b770ab
Make randompath failsafe
emazzotta/unity-tower-defense
Assets/Scripts/GameController.cs
Assets/Scripts/GameController.cs
using UnityEngine; using System.Collections; using System; public class GameController : MonoBehaviour { public GameObject originalBase; public GameObject baseFolder; private GameObject gameField; private GameObject[,] bases; private GameObject[] waypoints; private int gameFieldWidth = 0; private int gameFieldHeight = 0; private Color wayColor; void Awake () { this.wayColor = Color.Lerp(Color.green, Color.green, 0F); this.gameField = GameObject.Find("Ground"); this.gameFieldWidth = (int)(gameField.transform.localScale.x); this.gameFieldHeight = (int)(gameField.transform.localScale.z); this.bases = new GameObject[this.gameFieldWidth, this.gameFieldHeight]; this.waypoints = new GameObject[this.gameFieldWidth]; this.initGamePlatform (); this.drawWaypoint (); } void initGamePlatform() { for (int x = 0; x < this.gameFieldWidth; x++) { for (int z = 0; z < this.gameFieldHeight; z++) { GameObject newTowerBase = Instantiate (originalBase); newTowerBase.transform.SetParent (baseFolder.transform); newTowerBase.GetComponent<BaseController>().setBuildable(true); newTowerBase.transform.position = new Vector3 (originalBase.transform.position.x + x, 0.1f, originalBase.transform.position.z - z); this.bases [x, z] = newTowerBase; } } } void drawWaypoint() { int zAxis = 5; int x = 0; while (x < this.gameFieldWidth) { Debug.Log (zAxis); Debug.Log (this.gameFieldHeight); GameObject baseZ = this.bases[x, zAxis]; baseZ.GetComponent<Renderer> ().material.color = wayColor; baseZ.GetComponent<BaseController>().setBuildable(false); this.waypoints[x] = baseZ; float randNumber = (float)Math.Round(UnityEngine.Random.Range(-1.0f, 1.0f)); if ( randNumber != 0 ) { x += 1; } if ( zAxis >= -1 && zAxis <= this.gameFieldHeight + 1 ) { zAxis += (int)randNumber; } if ( zAxis < 1 ) { zAxis += 1; } if ( zAxis >= this.gameFieldHeight ) { zAxis -= 1; } } } public GameObject[] getWaypoints() { return this.waypoints; } }
using UnityEngine; using System.Collections; using System; public class GameController : MonoBehaviour { public GameObject originalBase; public GameObject baseFolder; private GameObject gameField; private GameObject[,] bases; private GameObject[] waypoints; private int gameFieldWidth = 0; private int gameFieldHeight = 0; private Color wayColor; void Awake () { this.wayColor = Color.Lerp(Color.green, Color.green, 0F); this.gameField = GameObject.Find("Ground"); this.gameFieldWidth = (int)(gameField.transform.localScale.x); this.gameFieldHeight = (int)(gameField.transform.localScale.z); this.bases = new GameObject[this.gameFieldWidth, this.gameFieldHeight]; this.waypoints = new GameObject[this.gameFieldWidth]; this.initGamePlatform (); this.drawWaypoint (); } void initGamePlatform() { for (int x = 0; x < this.gameFieldWidth; x++) { for (int z = 0; z < this.gameFieldHeight; z++) { GameObject newTowerBase = Instantiate (originalBase); newTowerBase.transform.SetParent (baseFolder.transform); newTowerBase.GetComponent<BaseController>().setBuildable(true); newTowerBase.transform.position = new Vector3 (originalBase.transform.position.x + x, 0.1f, originalBase.transform.position.z - z); this.bases [x, z] = newTowerBase; } } } void drawWaypoint() { int zAxis = 5; int x = 0; while (x < this.gameFieldWidth) { GameObject baseZ = this.bases[x, zAxis]; baseZ.GetComponent<Renderer> ().material.color = wayColor; baseZ.GetComponent<BaseController>().setBuildable(false); this.waypoints[x] = baseZ; float randNumber = (float)Math.Round(UnityEngine.Random.Range(-1.0f, 1.0f)); if (zAxis > 0 && zAxis < this.gameFieldHeight - 1) { zAxis += (int)randNumber; } if (randNumber != 0) { x += 1; } } } public GameObject[] getWaypoints() { return this.waypoints; } }
mit
C#
e9c07873087d1e4ececebb6f9a74c03d6101d583
Support list of package sources
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
AspNetCoreSdkTests/NuGetPackageSource.cs
AspNetCoreSdkTests/NuGetPackageSource.cs
using System; using System.Linq; namespace AspNetCoreSdkTests { public class NuGetPackageSource { public static NuGetPackageSource None { get; } = new NuGetPackageSource { Name = nameof(None), SourceArgumentLazy = new Lazy<string>(string.Empty), }; public static NuGetPackageSource NuGetOrg { get; } = new NuGetPackageSource { Name = nameof(NuGetOrg), SourceArgumentLazy = new Lazy<string>("--source https://api.nuget.org/v3/index.json"), }; public static NuGetPackageSource DotNetCore { get; } = new NuGetPackageSource { Name = nameof(DotNetCore), SourceArgumentLazy = new Lazy<string>("--source https://dotnet.myget.org/F/dotnet-core/api/v3/index.json"), }; public static NuGetPackageSource EnvironmentVariable { get; } = new NuGetPackageSource { Name = nameof(EnvironmentVariable), SourceArgumentLazy = new Lazy<string>(() => GetSourceArgumentFromEnvironment()), }; public static NuGetPackageSource EnvironmentVariableAndNuGetOrg { get; } = new NuGetPackageSource { Name = nameof(EnvironmentVariableAndNuGetOrg), SourceArgumentLazy = new Lazy<string>(() => string.Join(" ", EnvironmentVariable.SourceArgument, NuGetOrg.SourceArgument)), }; private NuGetPackageSource() { } public string Name { get; private set; } public string SourceArgument => SourceArgumentLazy.Value; private Lazy<string> SourceArgumentLazy { get; set; } public override string ToString() => Name; private static string GetSourceArgumentFromEnvironment() { var sourceString = Environment.GetEnvironmentVariable("NUGET_PACKAGE_SOURCE") ?? throw new InvalidOperationException("Environment variable NUGET_PACKAGE_SOURCE is required but not set"); return string.Join(" ", sourceString.Split(',').Select(s => $"--source {s}")); } } }
using System; namespace AspNetCoreSdkTests { public class NuGetPackageSource { public static NuGetPackageSource None { get; } = new NuGetPackageSource { Name = nameof(None), SourceArgumentLazy = new Lazy<string>(string.Empty), }; public static NuGetPackageSource NuGetOrg { get; } = new NuGetPackageSource { Name = nameof(NuGetOrg), SourceArgumentLazy = new Lazy<string>("--source https://api.nuget.org/v3/index.json"), }; public static NuGetPackageSource DotNetCore { get; } = new NuGetPackageSource { Name = nameof(DotNetCore), SourceArgumentLazy = new Lazy<string>("--source https://dotnet.myget.org/F/dotnet-core/api/v3/index.json"), }; public static NuGetPackageSource EnvironmentVariable { get; } = new NuGetPackageSource { Name = nameof(EnvironmentVariable), SourceArgumentLazy = new Lazy<string>(() => $"--source {GetPackageSourceFromEnvironment()}"), }; public static NuGetPackageSource EnvironmentVariableAndNuGetOrg { get; } = new NuGetPackageSource { Name = nameof(EnvironmentVariableAndNuGetOrg), SourceArgumentLazy = new Lazy<string>(() => string.Join(" ", EnvironmentVariable.SourceArgument, NuGetOrg.SourceArgument)), }; private NuGetPackageSource() { } public string Name { get; private set; } public string SourceArgument => SourceArgumentLazy.Value; private Lazy<string> SourceArgumentLazy { get; set; } public override string ToString() => Name; private static string GetPackageSourceFromEnvironment() { return Environment.GetEnvironmentVariable("NUGET_PACKAGE_SOURCE") ?? throw new InvalidOperationException("Environment variable NUGET_PACKAGE_SOURCE is required but not set"); } } }
apache-2.0
C#
56ea75cb666d5ef7bcb6092218ea9ff370e25783
fix doco
Fody/PropertyChanged,0x53A/PropertyChanged,user1568891/PropertyChanged
PropertyChanged/ImplementPropertyChangedAttribute.cs
PropertyChanged/ImplementPropertyChangedAttribute.cs
using System; using System.ComponentModel; namespace PropertyChanged { /// <summary> /// Specifies that PropertyChanged Notification will be added to a class. /// <para> /// PropertyChanged.Fody will weave the <see cref="INotifyPropertyChanged"/> interface and implementation into the class. /// When the value of a property changes, the PropertyChanged notification will be raised automatically /// </para> /// <para> /// see https://github.com/Fody/PropertyChanged <see href="https://github.com/Fody/PropertyChanged">(link)</see> for more information. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ImplementPropertyChangedAttribute : Attribute { } }
using System; namespace PropertyChanged { /// <summary> /// Specifies that PropertyChanged Notification will be added to a class. /// <para> /// PropertyChanged.Fody will weave the <c>INotifyPropertyChanged</c> interface and implementation into the class. /// When the value of a property changes, the PropertyChanged notification will be raised automatically /// </para> /// <para> /// see https://github.com/Fody/PropertyChanged <see href="https://github.com/Fody/PropertyChanged">(link)</see> for more information. /// </para> /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ImplementPropertyChangedAttribute : Attribute { } }
mit
C#
c8576df38e57d7a648b7db373ffa4a3bdd2e9e26
Remove DataService namespace
zindlsn/RosaroterTiger
RosaroterPanterWPF/RosaroterPanterWPF/DataService.cs
RosaroterPanterWPF/RosaroterPanterWPF/DataService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RosaroterPanterWPF { public class Color { public byte R { get; set; } public byte G { get; set; } public byte B { get; set; } public Color() { R = 0; G = 0; B = 0; } public Color(byte r, byte g, byte b) { R = r; G = g; B = b; } } public class Task { public Color Color { get; set; } public string Name { get; set; } public string Description { get; set; } public double TotalTime { get; set; } public bool Finished { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RosaroterPanterWPF { namespace DataService { public class Color { public byte R { get; set; } public byte G { get; set; } public byte B { get; set; } public Color() { R = 0; G = 0; B = 0; } public Color(byte r, byte g, byte b) { R = r; G = g; B = b; } } public class Task { public Color Color{ get; set; } public string Name { get; set; } public string Description { get; set; } public double TotalTime { get; set; } public bool Finished { get; set; } } } }
mit
C#
7a862d822c52021c913bf6621a79d81893052b57
Tweak mapping test page
jnoellsch/ektron-fluentapi
Src/Ektron.SharedSource.Sandbox/MappingTests.aspx.cs
Src/Ektron.SharedSource.Sandbox/MappingTests.aspx.cs
using System; using System.Web.UI; using Ektron.Cms.Common; using Ektron.Cms.Content; using Ektron.Cms.Framework.Content; using Ektron.SharedSource.FluentApi; using Ektron.SharedSource.FluentApi.Mapping; namespace Ektron.SharedSource.Sandbox { public partial class MappingTests : Page { protected void Page_Load(object sender, EventArgs e) { var manager = new ContentManager(); var criteria = new ContentCriteria(); var items = manager.GetList(criteria).AsContentType<Content>(); this.rptrContent.DataSource = items; this.rptrContent.DataBind(); } } }
using System; using System.Web.UI; using Ektron.Cms.Content; using Ektron.Cms.Framework.Content; using Ektron.SharedSource.FluentApi; using Ektron.SharedSource.FluentApi.Mapping; namespace Ektron.SharedSource.Sandbox { public partial class MappingTests : Page { protected void Page_Load(object sender, EventArgs e) { var manager = new ContentManager(); var criteria = new ContentCriteria(); Mapper.RegisterMapping<Content>((contentData, t) => { t.Title = t.Title.ToUpper(); }); var items = manager.GetList(criteria).AsContentType<Content>(); this.rptrContent.DataSource = items; this.rptrContent.DataBind(); } } }
mit
C#
34fe4641d87f9051d8576465c892abdd8756bad7
Add startup time measurement
medoni/Wox,Megasware128/Wox,dstiert/Wox,zlphoenix/Wox,dstiert/Wox,JohnTheGr8/Wox,kayone/Wox,Megasware128/Wox,medoni/Wox,dstiert/Wox,zlphoenix/Wox,JohnTheGr8/Wox,kayone/Wox,danisein/Wox,kayone/Wox,yozora-hitagi/Saber,Launchify/Launchify,jondaniels/Wox,jondaniels/Wox,danisein/Wox,yozora-hitagi/Saber,Launchify/Launchify
Wox/App.xaml.cs
Wox/App.xaml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Wox.CommandArgs; using Wox.Core.Plugin; using Wox.Helper; using Wox.Infrastructure; namespace Wox { public partial class App : Application, ISingleInstanceApp { private const string Unique = "Wox_Unique_Application_Mutex"; public static MainWindow Window { get; private set; } [STAThread] public static void Main() { if (SingleInstance<App>.InitializeAsFirstInstance(Unique)) { var application = new App(); application.InitializeComponent(); application.Run(); SingleInstance<App>.Cleanup(); } } protected override void OnStartup(StartupEventArgs e) { using (new Timeit("Startup Time")) { base.OnStartup(e); DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle; Window = new MainWindow(); PluginManager.Init(Window); ImageLoader.ImageLoader.PreloadImages(); CommandArgsFactory.Execute(e.Args.ToList()); } } public bool OnActivate(IList<string> args) { CommandArgsFactory.Execute(args); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows; using Wox.CommandArgs; using Wox.Core.Plugin; using Wox.Helper; namespace Wox { public partial class App : Application, ISingleInstanceApp { private const string Unique = "Wox_Unique_Application_Mutex"; public static MainWindow Window { get; private set; } [STAThread] public static void Main() { if (SingleInstance<App>.InitializeAsFirstInstance(Unique)) { var application = new App(); application.InitializeComponent(); application.Run(); SingleInstance<App>.Cleanup(); } } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); DispatcherUnhandledException += ErrorReporting.DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += ErrorReporting.UnhandledExceptionHandle; Window = new MainWindow(); PluginManager.Init(Window); ImageLoader.ImageLoader.PreloadImages(); CommandArgsFactory.Execute(e.Args.ToList()); } public bool OnActivate(IList<string> args) { CommandArgsFactory.Execute(args); return true; } } }
mit
C#
ce111480fc0b285962f6b9cd1fbf48854baae6c6
Rename Card Values
Olorin71/RetreatCode,Olorin71/RetreatCode
c#/TexasHoldEmSolution/TexasHoldEm/CardValue.cs
c#/TexasHoldEmSolution/TexasHoldEm/CardValue.cs
namespace TexasHoldEm { public enum CardValue { Ace = 14, King = 13, Queen = 12, Jack = 11, Ten = 10, Nine = 9, Eight = 8, Seven = 7, Six = 6, Five = 5, Four = 4, Three = 3, Two = 2 } }
namespace TexasHoldEm { public enum CardValue { A = 14, K = 13, Q = 12, J = 11, Ten = 10, Nine = 9, Eight = 8, Seven = 7, Six = 6, Five = 5, Four = 4, Three = 3, Two = 2 } }
mit
C#
128ac7cc7923286aa1a0e15881161e6f8057f697
Fix for iOS
HiP-App/HiP-Forms
Sources/HipMobileUI.iOS/AppDelegate.cs
Sources/HipMobileUI.iOS/AppDelegate.cs
using de.upb.hip.mobile.pcl.Common; using de.upb.hip.mobile.pcl.Common.Contracts; using Foundation; using HipMobileUI.iOS.Contracts; using HipMobileUI.Navigation; using HipMobileUI.Pages; using UIKit; namespace HipMobileUI.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { IoCManager.RegisterType<IImageDimension, IosImageDimensions>(); // Init Navigation NavigationService.Instance.RegisterViewModels (typeof(MainPage).Assembly); IoCManager.RegisterInstance (typeof(INavigationService), NavigationService.Instance); IoCManager.RegisterInstance(typeof(IViewCreator), NavigationService.Instance); global::Xamarin.Forms.Forms.Init(); Xamarin.FormsMaps.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
using de.upb.hip.mobile.pcl.Common; using de.upb.hip.mobile.pcl.Common.Contracts; using Foundation; using HipMobileUI.iOS.Contracts; using HipMobileUI.Navigation; using UIKit; namespace HipMobileUI.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { IoCManager.RegisterType<IImageDimension, IosImageDimensions>(); // Init Navigation //NavigationService.Instance.RegisterViewModels (typeof(MainPage).Assembly); IoCManager.RegisterInstance (typeof(INavigationService), NavigationService.Instance); global::Xamarin.Forms.Forms.Init(); Xamarin.FormsMaps.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
apache-2.0
C#
0acdec547fc342ffbc85353453062492d9e13022
modify json serialization options.
tangxuehua/ecommon,Aaron-Liu/ecommon
src/Extensions/ECommon.JsonNet/NewtonsoftJsonSerializer.cs
src/Extensions/ECommon.JsonNet/NewtonsoftJsonSerializer.cs
using System; using System.Collections.Generic; using System.Reflection; using ECommon.Serializing; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace ECommon.JsonNet { /// <summary>Json.Net implementationof IJsonSerializer. /// </summary> public class NewtonsoftJsonSerializer : IJsonSerializer { private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new IsoDateTimeConverter() }, ContractResolver = new CustomContractResolver() }; /// <summary>Serialize an object to json string. /// </summary> /// <param name="obj"></param> /// <returns></returns> public string Serialize(object obj) { return obj == null ? null : JsonConvert.SerializeObject(obj, Settings); } /// <summary>Deserialize a json string to an object. /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> public object Deserialize(string value, Type type) { return JsonConvert.DeserializeObject(value, type, Settings); } /// <summary>Deserialize a json string to a strong type object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public T Deserialize<T>(string value) where T : class { return JsonConvert.DeserializeObject<T>(JObject.Parse(value).ToString(), Settings); } } class CustomContractResolver : DefaultContractResolver { public CustomContractResolver() { DefaultMembersSearchFlags |= BindingFlags.NonPublic; } protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var jsonProperty = base.CreateProperty(member, memberSerialization); if (jsonProperty.Writable) return jsonProperty; var property = member as PropertyInfo; if (property == null) return jsonProperty; var hasPrivateSetter = property.GetSetMethod(true) != null; jsonProperty.Writable = hasPrivateSetter; return jsonProperty; } } }
using System; using System.Collections.Generic; using System.Reflection; using ECommon.Serializing; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace ECommon.JsonNet { /// <summary>Json.Net implementationof IJsonSerializer. /// </summary> public class NewtonsoftJsonSerializer : IJsonSerializer { private static readonly JsonSerializerSettings Settings = new JsonSerializerSettings { Converters = new List<JsonConverter> { new IsoDateTimeConverter() }, ContractResolver = new SisoJsonDefaultContractResolver() }; /// <summary>Serialize an object to json string. /// </summary> /// <param name="obj"></param> /// <returns></returns> public string Serialize(object obj) { return obj == null ? null : JsonConvert.SerializeObject(obj, Settings); } /// <summary>Deserialize a json string to an object. /// </summary> /// <param name="value"></param> /// <param name="type"></param> /// <returns></returns> public object Deserialize(string value, Type type) { return JsonConvert.DeserializeObject(value, type); } /// <summary>Deserialize a json string to a strong type object. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value"></param> /// <returns></returns> public T Deserialize<T>(string value) where T : class { return JsonConvert.DeserializeObject<T>(JObject.Parse(value).ToString(), Settings); } } /// <summary> /// </summary> public class SisoJsonDefaultContractResolver : DefaultContractResolver { /// <summary> /// </summary> /// <param name="member"></param> /// <param name="memberSerialization"></param> /// <returns></returns> protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization) { var jsonProperty = base.CreateProperty(member, memberSerialization); if (jsonProperty.Writable) return jsonProperty; var property = member as PropertyInfo; if (property == null) return jsonProperty; var hasPrivateSetter = property.GetSetMethod(true) != null; jsonProperty.Writable = hasPrivateSetter; return jsonProperty; } } }
mit
C#
c8b600802b49f859e56c1db63bc610b33da485e0
Use an actual available choice for LaTeX
verybadcat/CSharpMath
CSharpMath.Ios.Example/IosMathViewController.cs
CSharpMath.Ios.Example/IosMathViewController.cs
using UIKit; namespace CSharpMath.Ios.Example { public class IosMathViewController : UIViewController { public override void ViewDidLoad() { View.BackgroundColor = UIColor.White; var latexView = IosMathLabels.MathView(Rendering.Tests.MathData.IntegralColorBoxCorrect, 50); // WJWJWJ latex here latexView.ContentInsets = new UIEdgeInsets(10, 10, 10, 10); var size = latexView.SizeThatFits(new CoreGraphics.CGSize(370, 280)); latexView.Frame = new CoreGraphics.CGRect(0, 40, size.Width, size.Height); View.Add(latexView); } } }
using UIKit; namespace CSharpMath.Ios.Example { public class IosMathViewController : UIViewController { public override void ViewDidLoad() { View.BackgroundColor = UIColor.White; var latexView = IosMathLabels.MathView(Rendering.Tests.MathData.ColorBox, 50); // WJWJWJ latex here latexView.ContentInsets = new UIEdgeInsets(10, 10, 10, 10); var size = latexView.SizeThatFits(new CoreGraphics.CGSize(370, 280)); latexView.Frame = new CoreGraphics.CGRect(0, 40, size.Width, size.Height); View.Add(latexView); } } }
mit
C#
22dfa4bacf9496dd04e7af2e961f844b0902a906
mark assembly as alpha
ntent-ad/Metrics.NET,mnadel/Metrics.NET,alhardy/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,MetaG8/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,huoxudong125/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,etishor/Metrics.NET,DeonHeyns/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,Liwoj/Metrics.NET
Src/Metrics/Properties/AssemblyInfo.cs
Src/Metrics/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("Metrics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Metrics")] [assembly: AssemblyCopyright("Copyright Iulian Margarintescu © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("40660849-2188-4650-81e7-16d62e4576f8")] // 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.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")] [assembly: AssemblyInformationalVersion("0.0.1-alpha")]
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("Metrics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Metrics")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("40660849-2188-4650-81e7-16d62e4576f8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
902e846b84d6e2100d64e4a0b5bdf2679d8ecfee
Fix Otk_Reporter to workaround bug in gmcs.
eylvisaker/AgateLib
Drivers/AgateOTK/Otk_Reporter.cs
Drivers/AgateOTK/Otk_Reporter.cs
using System; using System.Collections.Generic; using System.Text; using AgateLib.Drivers; namespace AgateOTK { class Otk_Reporter : AgateDriverReporter { public override IEnumerable<AgateDriverInfo> ReportDrivers() { yield return new AgateDriverInfo( DisplayTypeID.OpenGL, typeof(GL_Display), "OpenGL through OpenTK 0.9.2", 1120); if (ReportOpenAL()) { yield return new AgateDriverInfo( AudioTypeID.OpenAL, typeof(AL_Audio), "OpenAL through OpenTK 0.9.2", 100); } } bool ReportOpenAL() { try { // test for the presence of working OpenAL. new OpenTK.Audio.AudioContext().Dispose(); return true; } catch (Exception e) { return false; } } } }
using System; using System.Collections.Generic; using System.Text; using AgateLib.Drivers; namespace AgateOTK { class Otk_Reporter : AgateDriverReporter { public override IEnumerable<AgateDriverInfo> ReportDrivers() { yield return new AgateDriverInfo( DisplayTypeID.OpenGL, typeof(GL_Display), "OpenGL through OpenTK 0.9.2", 1120); bool reportOpenAL = true; try { // test for the presence of working OpenAL. new OpenTK.Audio.AudioContext().Dispose(); } catch (Exception e) { reportOpenAL = false; } if (reportOpenAL) { yield return new AgateDriverInfo( AudioTypeID.OpenAL, typeof(AL_Audio), "OpenAL through OpenTK 0.9.2", 100); } } } }
mit
C#
611a08956205b352a535fe1d0f665e0c1711e1cc
Fix the release lookup link
flagbug/Espera,punker76/Espera
Espera/Espera.Core/MusicBrainzArtworkFetcher.cs
Espera/Espera.Core/MusicBrainzArtworkFetcher.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Xml.Linq; using Newtonsoft.Json.Linq; using ReactiveMarrow; using ReactiveUI; namespace Espera.Core { public class MusicBrainzArtworkFetcher : IArtworkFetcher { private const string ArtworkEndpoint = "http://coverartarchive.org/release/{0}/"; private const string SearchEndpoint = "http://www.musicbrainz.org/ws/2/release/?query=artist:{0}+release:{1}"; private readonly RateLimitedOperationQueue queue; public MusicBrainzArtworkFetcher() { this.queue = new RateLimitedOperationQueue(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler); } public async Task<Uri> RetrieveAsync(string artist, string album) { // Only searches are rate-limited, artwork retrievals are fine string releaseId = await this.queue.EnqueueOperation(() => GetReleaseIdAsync(artist, album)); return await GetArtworkLinkAsync(releaseId); } private static async Task<Uri> GetArtworkLinkAsync(string releaseId) { using (var client = new HttpClient()) { string artworkRequestUrl = string.Format(ArtworkEndpoint, releaseId); string response = await client.GetStringAsync(artworkRequestUrl); string artworkUrl = JObject.Parse(response).SelectToken("images[0].image").Value<string>(); return new Uri(artworkUrl); } } private static async Task<string> GetReleaseIdAsync(string artist, string album) { using (var client = new HttpClient()) { string searchRequestUrl = string.Format(SearchEndpoint, artist, album); string searchResponse = await client.GetStringAsync(searchRequestUrl); XNamespace ns = "http://musicbrainz.org/ns/mmd-2.0#"; var releases = XDocument.Parse(searchResponse).Descendants(ns + "release"); IEnumerable<string> releaseIds = releases.Select(x => x.Attribute("id").Value); return releaseIds.First(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Xml.Linq; using Newtonsoft.Json.Linq; using ReactiveMarrow; using ReactiveUI; namespace Espera.Core { public class MusicBrainzArtworkFetcher : IArtworkFetcher { private const string ArtworkEndpoint = "http://coverartarchive.org/release/{0}/"; private const string SearchEndpoint = "http://www.musicbrainz.org/ws/2/recording/?query=artist:{0}+release:{1}"; private readonly RateLimitedOperationQueue queue; public MusicBrainzArtworkFetcher() { this.queue = new RateLimitedOperationQueue(TimeSpan.FromSeconds(1), RxApp.TaskpoolScheduler); } public async Task<Uri> RetrieveAsync(string artist, string album) { // Only searches are rate-limited, artwork retrievals are fine string releaseId = await this.queue.EnqueueOperation(() => GetReleaseIdAsync(artist, album)); return await GetArtworkLinkAsync(releaseId); } private static async Task<Uri> GetArtworkLinkAsync(string releaseId) { using (var client = new HttpClient()) { string artworkRequestUrl = string.Format(ArtworkEndpoint, releaseId); string response = await client.GetStringAsync(artworkRequestUrl); string artworkUrl = JObject.Parse(response).SelectToken("images[0].image").Value<string>(); return new Uri(artworkUrl); } } private static async Task<string> GetReleaseIdAsync(string artist, string album) { using (var client = new HttpClient()) { string searchRequestUrl = string.Format(SearchEndpoint, artist, album); string searchResponse = await client.GetStringAsync(searchRequestUrl); XNamespace ns = "http://musicbrainz.org/ns/mmd-2.0#"; var releases = XDocument.Parse(searchResponse).Descendants(ns + "release"); IEnumerable<string> releaseIds = releases.Select(x => x.Attribute("id").Value); return releaseIds.First(); } } } }
mit
C#
92e3dffe562b3087e177925ff25fde856b731652
fix bug
fredatgithub/DeleteLine
FluentAssertionsUnitTests/UnitTestAllMethods.cs
FluentAssertionsUnitTests/UnitTestAllMethods.cs
using NUnit.Framework; using FluentAssertions; namespace FluentAssertionsUnitTests { [TestFixture] public class UnitTestAllMethods { [Test] public void Should_Start_With_Example() { const string actual = "ABCDEFGHI"; actual.Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9); } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using NUnit.Framework; using FluentAssertions; namespace FluentAssertionsUnitTests { [TestClass] public class UnitTestAllMethods { [TestCase] public void Should_Start_With_Example() { const string actual = "ABCDEFGHI"; actual.Should().StartWith("AB").And.EndWith("HI").And.Contain("EF").And.HaveLength(9); } } }
mit
C#
ff4e5adfab4f2d480c2b0e771a0f478e0f03f868
clean up
jefking/King.Service
King.Service/InitializeRunner.cs
King.Service/InitializeRunner.cs
namespace King.Service { using System; using System.Reflection; /// <summary> /// Initialize Runner /// </summary> public class InitializeRunner : InitializeTask { #region Members /// <summary> /// Instance /// </summary> protected readonly object instance; /// <summary> /// Method /// </summary> protected readonly MethodInfo method; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <param name="instance">Instance</param> /// <param name="method">Method</param> public InitializeRunner(object instance, MethodInfo method) { if (null == instance) { throw new ArgumentNullException("Instance can not be null."); } if (null == method) { throw new ArgumentNullException("Method for invocation can not be null."); } this.instance = instance; this.method = method; } #endregion #region Methods /// <summary> /// Run /// </summary> public override void Run() { this.method.Invoke(instance, null); } #endregion } }
namespace King.Service { using System; using System.Reflection; /// <summary> /// Initialize Runner /// </summary> public class InitializeRunner : InitializeTask { #region Members /// <summary> /// Instance /// </summary> protected readonly object instance; /// <summary> /// Method /// </summary> protected readonly MethodInfo method; #endregion #region Constructors /// <summary> /// Default Constructor /// </summary> /// <param name="instance">Instance</param> /// <param name="method">Method</param> public InitializeRunner(object instance, MethodInfo method) { if (null == instance) { throw new ArgumentNullException("Instance can not be null."); } if (null == method) { throw new ArgumentNullException("Method for invocation can not be null."); } this.instance = instance; this.method = method; } #endregion #region Methods /// <summary> /// Run /// </summary> public override void Run() { var result = this.method.Invoke(instance, null); } #endregion } }
mit
C#
c09755cfbff589dfbf74ee47bf2501988a24bf9f
Remove SetCoverTaskbarWhenMaximized method from IWindowImpl
jkoritzinsky/Avalonia,MrDaedra/Avalonia,SuperJMN/Avalonia,MrDaedra/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,grokys/Perspex,jazzay/Perspex,grokys/Perspex,AvaloniaUI/Avalonia
src/Avalonia.Controls/Platform/IWindowImpl.cs
src/Avalonia.Controls/Platform/IWindowImpl.cs
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls; namespace Avalonia.Platform { /// <summary> /// Defines a platform-specific window implementation. /// </summary> public interface IWindowImpl : ITopLevelImpl { /// <summary> /// Gets or sets the minimized/maximized state of the window. /// </summary> WindowState WindowState { get; set; } /// <summary> /// Sets the title of the window. /// </summary> /// <param name="title">The title.</param> void SetTitle(string title); /// <summary> /// Shows the window as a dialog. /// </summary> /// <returns> /// An <see cref="IDisposable"/> that should be used to close the window. /// </returns> IDisposable ShowDialog(); /// <summary> /// Enables of disables system window decorations (title bar, buttons, etc) /// </summary> void SetSystemDecorations(bool enabled); /// <summary> /// Sets the icon of this window. /// </summary> void SetIcon(IWindowIconImpl icon); } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls; namespace Avalonia.Platform { /// <summary> /// Defines a platform-specific window implementation. /// </summary> public interface IWindowImpl : ITopLevelImpl { /// <summary> /// Gets or sets the minimized/maximized state of the window. /// </summary> WindowState WindowState { get; set; } /// <summary> /// Sets the title of the window. /// </summary> /// <param name="title">The title.</param> void SetTitle(string title); /// <summary> /// Shows the window as a dialog. /// </summary> /// <returns> /// An <see cref="IDisposable"/> that should be used to close the window. /// </returns> IDisposable ShowDialog(); /// <summary> /// Enables of disables system window decorations (title bar, buttons, etc) /// </summary> void SetSystemDecorations(bool enabled); /// <summary> /// When system decorations are disabled sets if the maximized state covers the entire screen or just the working area. /// </summary> void SetCoverTaskbarWhenMaximized(bool enable); /// <summary> /// Sets the icon of this window. /// </summary> void SetIcon(IWindowIconImpl icon); } }
mit
C#
ec9957d623bc2025341b87fd059203c3311075ff
Update version for NuGet
jehugaleahsa/NRest
NRest/Properties/AssemblyInfo.cs
NRest/Properties/AssemblyInfo.cs
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NRest")] [assembly: AssemblyDescription("A simple REST client for making API calls using a fluent syntax.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Truncon")] [assembly: AssemblyProduct("NRest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("ef25bcfd-d3d9-43d6-b3c0-9db02924b672")] [assembly: AssemblyVersion("0.0.0.19")] [assembly: AssemblyFileVersion("0.0.0.19")] [assembly: CLSCompliant(true)]
using System; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NRest")] [assembly: AssemblyDescription("A simple REST client for making API calls using a fluent syntax.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Truncon")] [assembly: AssemblyProduct("NRest")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("ef25bcfd-d3d9-43d6-b3c0-9db02924b672")] [assembly: AssemblyVersion("0.0.0.18")] [assembly: AssemblyFileVersion("0.0.0.18")] [assembly: CLSCompliant(true)]
unlicense
C#
ddac3f23ae75409784e49a39819c052a7d516c7c
Move away from v0 approach.
EusthEnoptEron/Sketchball
Sketchball/Elements/Ball.cs
Sketchball/Elements/Ball.cs
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sketchball.Elements { public class Ball : PinballElement, IPhysics { public Vector2 Velocity { get; set; } public Ball() { Velocity = new Vector2(); Mass = 0.2f; Width = 60; Height = 60; } public override void Draw(System.Drawing.Graphics g) { //g.FillEllipse(Brushes.Peru, 0, 0, Width, Height); g.DrawImage(Properties.Resources.BallWithAlpha, 0, 0, Width, Height); } public override void Update(long delta) { base.Update(delta); Velocity += World.Acceleration * (delta / 1000f); Location += Velocity * (delta / 1000f); } public float Mass { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sketchball.Elements { public class Ball : PinballElement, IPhysics { private Vector2 v; private Vector2 v0; long t = 0; public Vector2 Velocity { get { return v; } set { v0 = value; t = 0; v = v0; } } public Ball() { Velocity = new Vector2(); Mass = 0.2f; Width = 60; Height = 60; } public override void Draw(System.Drawing.Graphics g) { //g.FillEllipse(Brushes.Peru, 0, 0, Width, Height); g.DrawImage(Properties.Resources.BallWithAlpha, 0, 0, Width, Height); } public override void Update(long delta) { t += delta; base.Update(delta); v = v0 + (t / 1000f) * World.Acceleration; Location += v * (delta / 1000f); } public float Mass { get; set; } } }
mit
C#
e14a60040c0eb09065424885ecfbe54132a8f14f
fix file header comment
t-ashula/bl4n
bl4n/Data/IStatus.cs
bl4n/Data/IStatus.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IStatus.cs"> // bl4n - Backlog.jp API Client library // this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015/ // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Runtime.Serialization; namespace BL4N.Data { public interface IStatus { long Id { get; } string Name { get; } } [DataContract] internal sealed class Status : IStatus { [DataMember(Name = "id")] public long Id { get; private set; } [DataMember(Name = "name")] public string Name { get; private set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IIssue.cs"> // bl4n - Backlog.jp API Client library // this file is part of bl4n, license under MIT license. http://t-ashula.mit-license.org/2015/ // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Runtime.Serialization; namespace BL4N.Data { public interface IStatus { long Id { get; } string Name { get; } } [DataContract] internal sealed class Status : IStatus { [DataMember(Name = "id")] public long Id { get; private set; } [DataMember(Name = "name")] public string Name { get; private set; } } }
mit
C#
40941c5b60a4413eedab7c582008e35f6d7573f9
Update addin info showing that addin uses TypeScript 1.5.3
mrward/typescript-addin,mrward/typescript-addin
src/TypeScriptBinding/Properties/AddinInfo.cs
src/TypeScriptBinding/Properties/AddinInfo.cs
 using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ("TypeScript", Namespace = "MonoDevelop", Version = "0.6", Category = "Web Development")] [assembly:AddinName ("TypeScript")] [assembly:AddinDescription ("Adds TypeScript support. Updated to use TypeScript 1.5.3")] [assembly:AddinDependency ("Core", "5.0")] [assembly:AddinDependency ("Ide", "5.0")] [assembly:AddinDependency ("SourceEditor2", "5.0")] [assembly:AddinDependency ("Refactoring", "5.0")]
 using System; using Mono.Addins; using Mono.Addins.Description; [assembly:Addin ("TypeScript", Namespace = "MonoDevelop", Version = "0.6", Category = "Web Development")] [assembly:AddinName ("TypeScript")] [assembly:AddinDescription ("Adds TypeScript support. Updated to use TypeScript 1.4")] [assembly:AddinDependency ("Core", "5.0")] [assembly:AddinDependency ("Ide", "5.0")] [assembly:AddinDependency ("SourceEditor2", "5.0")] [assembly:AddinDependency ("Refactoring", "5.0")]
mit
C#
1828a30c1dcd0df2db8dd18583dc6d5397d4eaf2
Make the custom action not have to use Debugger.Launch to prove that it works.
jquintus/spikes,jquintus/spikes,jquintus/spikes,jquintus/spikes
ConsoleApps/FunWithSpikes/Wix.CustomActions/CustomAction.cs
ConsoleApps/FunWithSpikes/Wix.CustomActions/CustomAction.cs
using Microsoft.Deployment.WindowsInstaller; using System; using System.IO; namespace Wix.CustomActions { public class CustomActions { [CustomAction] public static ActionResult CloseIt(Session session) { try { string fileFullPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "CustomAction.txt"); if (!File.Exists(fileFullPath)) File.Create(fileFullPath); File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now)); session.Log("Close DotTray!"); } catch (Exception ex) { session.Log("ERROR in custom action CloseIt {0}", ex.ToString()); return ActionResult.Failure; } return ActionResult.Success; } } }
using System; using Microsoft.Deployment.WindowsInstaller; namespace Wix.CustomActions { using System.IO; using System.Diagnostics; public class CustomActions { [CustomAction] public static ActionResult CloseIt(Session session) { try { Debugger.Launch(); const string fileFullPath = @"c:\KensCustomAction.txt"; if (!File.Exists(fileFullPath)) File.Create(fileFullPath); File.AppendAllText(fileFullPath, string.Format("{0}Yes, we have a hit at {1}", Environment.NewLine, DateTime.Now)); session.Log("Close DotTray!"); } catch (Exception ex) { session.Log("ERROR in custom action CloseIt {0}", ex.ToString()); return ActionResult.Failure; } return ActionResult.Success; } } }
mit
C#
417dc888832a8a9a5b0130403b6e4a893bccd036
Remove unneeded space
PearMed/Pear-Interaction-Engine
Scripts/EventListeners/Resize.cs
Scripts/EventListeners/Resize.cs
using Pear.InteractionEngine.Utils; using UnityEngine; using Pear.InteractionEngine.Events; using Pear.InteractionEngine.Interactions; namespace Pear.InteractionEngine.EventListeners { /// <summary> /// Resize a game object based on change in event /// </summary> public class Resize : MonoBehaviour, IEventListener<Vector3> { [Tooltip("Resize percentage per second")] public float ResizePercentPerSecond = 10f; [Tooltip("Should we resize the same amount in each direction?")] public bool Uniform = true; [Tooltip("If true, this object will remain in it's relative position to the camera while zooming")] public bool InPlace; // The directions to resize in private Vector3 _directions = Vector3.zero; /// <summary> /// Loops over each registered property and resizes it's owning game object /// </summary> void Update() { if(_directions == Vector3.zero) { return; } Transform objectToResizeTransform = transform.GetOrAddComponent<ObjectWithAnchor>() .AnchorElement .transform; float currentSize = objectToResizeTransform.localScale.x; float maxResizeAmount = (ResizePercentPerSecond * currentSize / 100) * Time.deltaTime; // Get the relative position of the camera // In case we zoom in place Vector3 cameraOriginalLocalOffset = transform.InverseTransformPoint(Camera.main.transform.position); objectToResizeTransform.localScale += _directions * maxResizeAmount; if (InPlace) { Vector3 cameraCurrentLocalOffset = transform.InverseTransformPoint(Camera.main.transform.position); Vector3 offsetCorrection = transform.TransformPoint(cameraCurrentLocalOffset) - transform.TransformPoint(cameraOriginalLocalOffset); objectToResizeTransform.position += offsetCorrection; } } /// <summary> /// Saves the even't new value as the direction to resize in /// </summary> /// <param name="args">event args</param> public void ValueChanged(EventArgs<Vector3> args) { // If we're scalling the amount in each direction use the vector's magnitude if (Uniform) { _directions = Vector3.one * args.NewValue.magnitude; // If the direction is negative mult by -1 if (args.NewValue.x + args.NewValue.y + args.NewValue.z < 0) _directions *= -1; } else { _directions = args.NewValue; } } } }
using Pear.InteractionEngine.Utils; using UnityEngine; using Pear.InteractionEngine.Events; using Pear.InteractionEngine.Interactions; namespace Pear.InteractionEngine.EventListeners { /// <summary> /// Resize a game object based on change in event /// </summary> public class Resize : MonoBehaviour, IEventListener<Vector3> { [Tooltip("Resize percentage per second")] public float ResizePercentPerSecond = 10f; [Tooltip("Should we resize the same amount in each direction?")] public bool Uniform = true; [Tooltip("If true, this object will remain in it's relative position to the camera while zooming")] public bool InPlace; // The directions to resize in private Vector3 _directions = Vector3.zero; /// <summary> /// Loops over each registered property and resizes it's owning game object /// </summary> void Update() { if(_directions == Vector3.zero) { return; } Transform objectToResizeTransform = transform.GetOrAddComponent<ObjectWithAnchor>() .AnchorElement .transform; float currentSize = objectToResizeTransform.localScale.x; float maxResizeAmount = (ResizePercentPerSecond * currentSize / 100) * Time.deltaTime; // Get the relative position of the camera // In case we zoom in place Vector3 cameraOriginalLocalOffset = transform.InverseTransformPoint(Camera.main.transform.position); objectToResizeTransform.localScale += _directions * maxResizeAmount; if (InPlace ) { Vector3 cameraCurrentLocalOffset = transform.InverseTransformPoint(Camera.main.transform.position); Vector3 offsetCorrection = transform.TransformPoint(cameraCurrentLocalOffset) - transform.TransformPoint(cameraOriginalLocalOffset); objectToResizeTransform.position += offsetCorrection; } } /// <summary> /// Saves the even't new value as the direction to resize in /// </summary> /// <param name="args">event args</param> public void ValueChanged(EventArgs<Vector3> args) { // If we're scalling the amount in each direction use the vector's magnitude if (Uniform) { _directions = Vector3.one * args.NewValue.magnitude; // If the direction is negative mult by -1 if (args.NewValue.x + args.NewValue.y + args.NewValue.z < 0) _directions *= -1; } else { _directions = args.NewValue; } } } }
mit
C#
08faef694bde8b66b7234c231ea58b89a058a951
Add change handling for difficulty section
ppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu-new,smoogipooo/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu
osu.Game/Screens/Edit/Timing/DifficultySection.cs
osu.Game/Screens/Edit/Timing/DifficultySection.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Screens.Edit.Timing { internal class DifficultySection : Section<DifficultyControlPoint> { private SliderWithTextBoxInput<double> multiplierSlider; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier") { Current = new DifficultyControlPoint().SpeedMultiplierBindable } }); } protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point) { if (point.NewValue != null) { multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable; multiplierSlider.Current.BindValueChanged(_ => ChangeHandler?.SaveState()); } } protected override DifficultyControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time); return new DifficultyControlPoint { SpeedMultiplier = reference.SpeedMultiplier, }; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Game.Beatmaps.ControlPoints; namespace osu.Game.Screens.Edit.Timing { internal class DifficultySection : Section<DifficultyControlPoint> { private SliderWithTextBoxInput<double> multiplierSlider; [BackgroundDependencyLoader] private void load() { Flow.AddRange(new[] { multiplierSlider = new SliderWithTextBoxInput<double>("Speed Multiplier") { Current = new DifficultyControlPoint().SpeedMultiplierBindable } }); } protected override void OnControlPointChanged(ValueChangedEvent<DifficultyControlPoint> point) { if (point.NewValue != null) { multiplierSlider.Current = point.NewValue.SpeedMultiplierBindable; } } protected override DifficultyControlPoint CreatePoint() { var reference = Beatmap.Value.Beatmap.ControlPointInfo.DifficultyPointAt(SelectedGroup.Value.Time); return new DifficultyControlPoint { SpeedMultiplier = reference.SpeedMultiplier, }; } } }
mit
C#
7ac04d04782837946bf6247434d8303d99e1760a
Fix potential crash when exiting editor test mode
ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game/Screens/Edit/GameplayTest/EditorPlayer.cs
osu.Game/Screens/Edit/GameplayTest/EditorPlayer.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Framework.Allocation; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Overlays; using osu.Game.Screens.Play; namespace osu.Game.Screens.Edit.GameplayTest { public class EditorPlayer : Player { private readonly Editor editor; private readonly EditorState editorState; [Resolved] private MusicController musicController { get; set; } public EditorPlayer(Editor editor) : base(new PlayerConfiguration { ShowResults = false }) { this.editor = editor; editorState = editor.GetState(); } protected override GameplayClockContainer CreateGameplayClockContainer(WorkingBeatmap beatmap, double gameplayStart) => new MasterGameplayClockContainer(beatmap, gameplayStart) { StartTime = editorState.Time }; protected override void LoadComplete() { base.LoadComplete(); ScoreProcessor.HasCompleted.BindValueChanged(completed => { if (completed.NewValue) { Scheduler.AddDelayed(() => { if (this.IsCurrentScreen()) this.Exit(); }, RESULTS_DISPLAY_DELAY); } }); } protected override void PrepareReplay() { // don't record replays. } protected override bool CheckModsAllowFailure() => false; // never fail. public override void OnEntering(ScreenTransitionEvent e) { base.OnEntering(e); // finish alpha transforms on entering to avoid gameplay starting in a half-hidden state. // the finish calls are purposefully not propagated to children to avoid messing up their state. FinishTransforms(); GameplayClockContainer.FinishTransforms(false, nameof(Alpha)); } public override bool OnExiting(ScreenExitEvent e) { musicController.Stop(); editorState.Time = GameplayClockContainer.CurrentTime; editor.RestoreState(editorState); return base.OnExiting(e); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. #nullable disable using osu.Framework.Allocation; using osu.Framework.Screens; using osu.Game.Beatmaps; using osu.Game.Overlays; using osu.Game.Screens.Play; namespace osu.Game.Screens.Edit.GameplayTest { public class EditorPlayer : Player { private readonly Editor editor; private readonly EditorState editorState; [Resolved] private MusicController musicController { get; set; } public EditorPlayer(Editor editor) : base(new PlayerConfiguration { ShowResults = false }) { this.editor = editor; editorState = editor.GetState(); } protected override GameplayClockContainer CreateGameplayClockContainer(WorkingBeatmap beatmap, double gameplayStart) => new MasterGameplayClockContainer(beatmap, gameplayStart) { StartTime = editorState.Time }; protected override void LoadComplete() { base.LoadComplete(); ScoreProcessor.HasCompleted.BindValueChanged(completed => { if (completed.NewValue) Scheduler.AddDelayed(this.Exit, RESULTS_DISPLAY_DELAY); }); } protected override void PrepareReplay() { // don't record replays. } protected override bool CheckModsAllowFailure() => false; // never fail. public override void OnEntering(ScreenTransitionEvent e) { base.OnEntering(e); // finish alpha transforms on entering to avoid gameplay starting in a half-hidden state. // the finish calls are purposefully not propagated to children to avoid messing up their state. FinishTransforms(); GameplayClockContainer.FinishTransforms(false, nameof(Alpha)); } public override bool OnExiting(ScreenExitEvent e) { musicController.Stop(); editorState.Time = GameplayClockContainer.CurrentTime; editor.RestoreState(editorState); return base.OnExiting(e); } } }
mit
C#
240e968200f13af5abbf52bdbe67fb1e1eabcd9a
Teste usando o validation helper em portugues, assim aumenta a cobertura de testes. Nao sei se isto eh legal.
LiteFx/LiteFx,LiteFx/LiteFx,LiteFx/LiteFx
LiteFx.Specs/ValidationSpecs/Category.cs
LiteFx.Specs/ValidationSpecs/Category.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LiteFx.Validation.PtBr; namespace LiteFx.Specs.ValidationSpecs { class Category : EntityBaseWithValidation<int> { public string Name { get; set; } public override void ConfigureValidation() { Assert<Category>().Que(c => c.Name).NaoSejaNuloOuVazio(); } } class SuperCategory : Category { public int Rank { get; set; } public override void ConfigureValidation() { Assert<SuperCategory>().Que(s => s.Rank).Minimo(1); base.ConfigureValidation(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using LiteFx.Validation; namespace LiteFx.Specs.ValidationSpecs { class Category : EntityBaseWithValidation<int> { public string Name { get; set; } public override void ConfigureValidation() { Assert<Category>().That(c => c.Name).IsNotNullOrEmpty(); } } class SuperCategory : Category { public int Rank { get; set; } public override void ConfigureValidation() { Assert<SuperCategory>().That(s => s.Rank).Min(1); base.ConfigureValidation(); } } }
mit
C#
7ec3e532a8b7613efee59aebb20f83f43e44554b
Update to Abp.Zero 0.7.0.0
volkd/module-zero,AndHuang/module-zero,daywrite/module-zero,volkd/module-zero,asauriol/module-zero,AndHuang/module-zero,andmattia/module-zero,Jerome2606/module-zero,abdllhbyrktr/module-zero,lemestrez/module-zero,CooperLiu/module-zero,lemestrez/module-zero,chilin/module-zero,ilyhacker/module-zero,aspnetboilerplate/module-zero,Jerome2606/module-zero,asauriol/module-zero
sample/ModuleZeroSampleProject.Core/Users/UserManager.cs
sample/ModuleZeroSampleProject.Core/Users/UserManager.cs
using Abp.Authorization; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Zero.Configuration; using ModuleZeroSampleProject.Authorization; using ModuleZeroSampleProject.MultiTenancy; namespace ModuleZeroSampleProject.Users { public class UserManager : AbpUserManager<Tenant, Role, User> { public UserManager( UserStore userStore, RoleManager roleManager, IRepository<Tenant> tenantRepository, IMultiTenancyConfig multiTenancyConfig, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IUserManagementConfig userManagementConfig, IIocResolver iocResolver, Abp.Runtime.Caching.ICacheManager cacheManager) : base( userStore, roleManager, tenantRepository, multiTenancyConfig, permissionManager, unitOfWorkManager, settingManager, userManagementConfig, iocResolver, cacheManager) { } } }
using Abp.Authorization; using Abp.Authorization.Users; using Abp.Configuration; using Abp.Configuration.Startup; using Abp.Dependency; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Zero.Configuration; using ModuleZeroSampleProject.Authorization; using ModuleZeroSampleProject.MultiTenancy; namespace ModuleZeroSampleProject.Users { public class UserManager : AbpUserManager<Tenant, Role, User> { public UserManager( UserStore store, RoleManager roleManager, IRepository<Tenant> tenantRepository, IMultiTenancyConfig multiTenancyConfig, IPermissionManager permissionManager, IUnitOfWorkManager unitOfWorkManager, ISettingManager settingManager, IUserManagementConfig userManagementConfig, IIocResolver iocResolver) : base( store, roleManager, tenantRepository, multiTenancyConfig, permissionManager, unitOfWorkManager, settingManager, userManagementConfig, iocResolver) { } } }
mit
C#
08e7a3e122162029a5d86816e861e60f53747c94
Add LChflagsCanSetHiddenFlag plug
CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos,CosmosOS/Cosmos
source/Cosmos.System2_Plugs/Interop/System.NativeImpl.cs
source/Cosmos.System2_Plugs/Interop/System.NativeImpl.cs
using IL2CPU.API.Attribs; using System; using System.IO; namespace Cosmos.System_Plugs.Interop { [Plug("Interop+Sys, System.Private.CoreLib")] class SysImpl { [PlugMethod(Signature = "System_Void__Interop_Sys_GetNonCryptographicallySecureRandomBytes_System_Byte___System_Int32_")] public static unsafe void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length) { throw new NotImplementedException(); } [PlugMethod(Signature = "System_Int32__Interop_Sys_LChflagsCanSetHiddenFlag__")] public static int LChflagsCanSetHiddenFlag() { throw new NotImplementedException(); } } }
using IL2CPU.API.Attribs; using System; using System.IO; namespace Cosmos.System_Plugs.Interop { [Plug("Interop+Sys, System.Private.CoreLib")] class SysImpl { [PlugMethod(Signature = "System_Void__Interop_Sys_GetNonCryptographicallySecureRandomBytes_System_Byte___System_Int32_")] public static unsafe void GetNonCryptographicallySecureRandomBytes(byte* buffer, int length) { throw new NotImplementedException(); } } }
bsd-3-clause
C#
abd4c753ef09ee2f3098e2d5fe019bd003bdd32a
update assembly info
levid-gc/IdentityServer3.Dapper
source/IdentityServer3.Dapper/Properties/AssemblyInfo.cs
source/IdentityServer3.Dapper/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("IdentityServer3.Dapper")] [assembly: AssemblyDescription("Dapper for IdentityServer3 including Clinet, Scope and Token etc.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IdentityServer3.Dapper")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3965edac-c7f8-493a-a27d-8954b111b457")] // 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.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("IdentityServer3.Dapper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IdentityServer3.Dapper")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3965edac-c7f8-493a-a27d-8954b111b457")] // 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.0.1.0")] [assembly: AssemblyFileVersion("0.0.1.0")]
apache-2.0
C#
10f1e785034974f759d3bbbb1f641999bc757f99
Fix MemoryBlobStorage
yufeih/Nine.Storage,studio-nine/Nine.Storage
src/Nine.Storage.Abstractions/Blobs/MemoryBlobStorage.cs
src/Nine.Storage.Abstractions/Blobs/MemoryBlobStorage.cs
namespace Nine.Storage.Blobs { using System; using System.Collections.Concurrent; using System.IO; using System.Threading; using System.Threading.Tasks; public class MemoryBlobStorage : IBlobStorage { private readonly ConcurrentDictionary<string, byte[]> _store = new ConcurrentDictionary<string, byte[]>(StringComparer.OrdinalIgnoreCase); public virtual Task<bool> Exists(string key) { if (string.IsNullOrEmpty(key)) return Task.FromResult(false); return Task.FromResult(_store.ContainsKey(key)); } public virtual Task<string> GetUri(string key) => CommonTasks.NullString; public virtual Task<Stream> Get(string key, IProgress<ProgressInBytes> progress = null, CancellationToken cancellation = default(CancellationToken)) { byte[] result; if (string.IsNullOrEmpty(key)) return Task.FromResult<Stream>(null); if (_store.TryGetValue(key, out result) && result != null) { return Task.FromResult<Stream>(new MemoryStream(result, writable: false)); } return CommonTasks.Null<Stream>(); } public virtual Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellation = default(CancellationToken)) { long length; try { length = stream.Length; } catch (NotSupportedException) { var ms = new MemoryStream(); stream.CopyTo(ms); _store.GetOrAdd(key, ms.ToArray()); return Task.FromResult(key); } var bytes = new byte[length]; stream.Read(bytes, 0, bytes.Length); _store.GetOrAdd(key, bytes); return Task.FromResult(key); } public virtual Task Delete(string key) { byte[] removed; _store.TryRemove(key, out removed); return CommonTasks.Completed; } } }
namespace Nine.Storage.Blobs { using System; using System.Collections.Concurrent; using System.IO; using System.Threading; using System.Threading.Tasks; public class MemoryBlobStorage : IBlobStorage { private readonly ConcurrentDictionary<string, MemoryStream> _store = new ConcurrentDictionary<string, MemoryStream>(StringComparer.OrdinalIgnoreCase); public virtual Task<bool> Exists(string key) { if (string.IsNullOrEmpty(key)) return Task.FromResult(false); return Task.FromResult(_store.ContainsKey(key)); } public virtual Task<string> GetUri(string key) => CommonTasks.NullString; public virtual Task<Stream> Get(string key, IProgress<ProgressInBytes> progress = null, CancellationToken cancellation = default(CancellationToken)) { MemoryStream result; if (string.IsNullOrEmpty(key)) return Task.FromResult<Stream>(null); if (_store.TryGetValue(key, out result) && result != null) { result.Seek(0, SeekOrigin.Begin); return Task.FromResult<Stream>(result); } return CommonTasks.Null<Stream>(); } public virtual Task<string> Put(string key, Stream stream, IProgress<ProgressInBytes> progress = null, CancellationToken cancellation = default(CancellationToken)) { var ms = new MemoryStream(); stream.CopyTo(ms); ms.Seek(0, SeekOrigin.Begin); _store.GetOrAdd(key, ms); return Task.FromResult(key); } public virtual Task Delete(string key) { MemoryStream removed; _store.TryRemove(key, out removed); return CommonTasks.Completed; } } }
mit
C#
6d94006cd8418ea5c8dc22bb9a1f16543f77c936
Use correct casing
DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,OmniSharp/omnisharp-roslyn
src/OmniSharp.Abstractions/Models/v2/CodeFoldingBlock.cs
src/OmniSharp.Abstractions/Models/v2/CodeFoldingBlock.cs
namespace OmniSharp.Models.V2 { public class CodeFoldingBlock { public CodeFoldingBlock(Range textSpan, string type) { Range = textSpan; Type = type; } /// <summary> /// The span of text to collapse. /// </summary> public Range Range { get; } /// <summary> /// If the block is one of the types specified in <see cref="CodeFoldingBlockKind"/>, that type. /// Otherwise, null. /// </summary> public string Type { get; } } public class CodeFoldingBlockKind { public static readonly string Comment = nameof(Comment); public static readonly string Imports = nameof(Imports); public static readonly string Region = nameof(Region); } }
namespace OmniSharp.Models.V2 { public class CodeFoldingBlock { public CodeFoldingBlock(Range textSpan, string type) { Range = textSpan; Type = type; } /// <summary> /// The span of text to collapse. /// </summary> public Range Range { get; } /// <summary> /// If the block is one of the types specified in <see cref="CodeFoldingBlockKind"/>, that type. /// Otherwise, null. /// </summary> public string Type { get; } } public class CodeFoldingBlockKind { public static readonly string Comment = nameof(Comment).ToLowerInvariant(); public static readonly string Imports = nameof(Imports).ToLowerInvariant(); public static readonly string Region = nameof(Region).ToLowerInvariant(); } }
mit
C#
4f12029a96c8d64a9f14dbee159ebbde2be0931a
Handle null better
stormpath/stormpath-dotnet-owin-middleware
src/Stormpath.Owin.Middleware/RequireCustomDataFilter.cs
src/Stormpath.Owin.Middleware/RequireCustomDataFilter.cs
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Stormpath.Owin.Abstractions; using Stormpath.SDK.Account; using Stormpath.SDK.Sync; namespace Stormpath.Owin.Middleware { public sealed class RequireCustomDataFilter : IAuthorizationFilter { private readonly string _key; private readonly object _value; private readonly IEqualityComparer<object> _comparer; public RequireCustomDataFilter(string key, object value) : this(key, value, new DefaultSmartComparer()) { } public RequireCustomDataFilter(string key, object value, IEqualityComparer<object> comparer) { _key = key; _value = value; _comparer = comparer ?? new DefaultSmartComparer(); } public bool IsAuthorized(IAccount account) { var customData = account?.GetCustomData(); return _comparer.Equals(customData?[_key], _value); } public async Task<bool> IsAuthorizedAsync(IAccount account, CancellationToken cancellationToken) { var customData = account == null ? null : await account.GetCustomDataAsync(cancellationToken).ConfigureAwait(false); return _comparer.Equals(customData?[_key], _value); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Stormpath.Owin.Abstractions; using Stormpath.SDK.Account; using Stormpath.SDK.Sync; namespace Stormpath.Owin.Middleware { public sealed class RequireCustomDataFilter : IAuthorizationFilter { private readonly string _key; private readonly object _value; private readonly IEqualityComparer<object> _comparer; public RequireCustomDataFilter(string key, object value) : this(key, value, new DefaultSmartComparer()) { } public RequireCustomDataFilter(string key, object value, IEqualityComparer<object> comparer) { _key = key; _value = value; _comparer = comparer; } public bool IsAuthorized(IAccount account) { var customData = account?.GetCustomData(); return _comparer.Equals(customData?[_key], _value); } public async Task<bool> IsAuthorizedAsync(IAccount account, CancellationToken cancellationToken) { var customData = account == null ? null : await account.GetCustomDataAsync(cancellationToken).ConfigureAwait(false); return _comparer.Equals(customData?[_key], _value); } } }
apache-2.0
C#
b86f2aaea56f7cc57cec0af3a1128cfbe84aeca3
Make MT Contact ctor/setters public
xamarin/Xamarin.Mobile,haithemaraissia/Xamarin.Mobile,xamarin/Xamarin.Mobile,nexussays/Xamarin.Mobile,orand/Xamarin.Mobile,moljac/Xamarin.Mobile
MonoTouch/MonoMobile.Extensions/Contacts/Contact.cs
MonoTouch/MonoMobile.Extensions/Contacts/Contact.cs
using System.Collections.Generic; using MonoTouch.AddressBook; using MonoTouch.Foundation; using MonoTouch.UIKit; using System; using System.Runtime.InteropServices; namespace Xamarin.Contacts { public class Contact { public Contact() { } internal Contact (ABPerson person) { Id = person.Id.ToString(); this.person = person; } public string Id { get; private set; } public bool IsAggregate { get; private set; } public string DisplayName { get; set; } public string Prefix { get; set; } public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public string Nickname { get; set; } public string Suffix { get; set; } public IEnumerable<Address> Addresses { get; set; } public IEnumerable<InstantMessagingAccount> InstantMessagingAccounts { get; set; } public IEnumerable<Website> Websites { get; set; } public IEnumerable<Organization> Organizations { get; set; } public IEnumerable<Note> Notes { get; set; } public IEnumerable<Email> Emails { get; set; } public IEnumerable<Phone> Phones { get; set; } public UIImage PhotoThumbnail { get { LoadThumbnail(); return this.thumbnail; } } private readonly ABPerson person; private bool thumbnailLoaded; private UIImage thumbnail; [DllImport ("/System/Library/Frameworks/AddressBook.framework/AddressBook")] private static extern IntPtr ABPersonCopyImageDataWithFormat (IntPtr handle, ABPersonImageFormat format); private void LoadThumbnail() { if (this.thumbnailLoaded || this.person == null) return; this.thumbnailLoaded = true; if (!this.person.HasImage) return; NSData imageData = new NSData (ABPersonCopyImageDataWithFormat (person.Handle, ABPersonImageFormat.Thumbnail)); if (imageData != null) this.thumbnail = new UIImage (imageData); } } }
using System.Collections.Generic; using MonoTouch.AddressBook; using MonoTouch.Foundation; using MonoTouch.UIKit; using System; using System.Runtime.InteropServices; namespace Xamarin.Contacts { public class Contact { internal Contact (ABPerson person) { Id = person.Id.ToString(); this.person = person; } public string Id { get; private set; } public bool IsAggregate { get; private set; } public string DisplayName { get; internal set; } public string Prefix { get; internal set; } public string FirstName { get; internal set; } public string MiddleName { get; internal set; } public string LastName { get; internal set; } public string Nickname { get; internal set; } public string Suffix { get; internal set; } public IEnumerable<Address> Addresses { get; internal set; } public IEnumerable<InstantMessagingAccount> InstantMessagingAccounts { get; internal set; } public IEnumerable<Website> Websites { get; internal set; } public IEnumerable<Organization> Organizations { get; internal set; } public IEnumerable<Note> Notes { get; internal set; } public IEnumerable<Email> Emails { get; internal set; } public IEnumerable<Phone> Phones { get; internal set; } public UIImage PhotoThumbnail { get { LoadThumbnail(); return this.thumbnail; } } private readonly ABPerson person; private bool thumbnailLoaded; private UIImage thumbnail; [DllImport ("/System/Library/Frameworks/AddressBook.framework/AddressBook")] private static extern IntPtr ABPersonCopyImageDataWithFormat (IntPtr handle, ABPersonImageFormat format); private void LoadThumbnail() { if (this.thumbnailLoaded) return; this.thumbnailLoaded = true; if (!this.person.HasImage) return; NSData imageData = new NSData (ABPersonCopyImageDataWithFormat (person.Handle, ABPersonImageFormat.Thumbnail)); if (imageData != null) this.thumbnail = new UIImage (imageData); } } }
apache-2.0
C#