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
fc085739aa9d46d43fb3724a751443ecb54ce58c
update Windows
AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/extensions,MehdyKarimpour/extensions,signumsoftware/framework,signumsoftware/framework,AlejandroCano/extensions,MehdyKarimpour/extensions
Signum.Windows.Extensions/Authorization/OperationAuthClient.cs
Signum.Windows.Extensions/Authorization/OperationAuthClient.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities.Authorization; using Signum.Services; using System.Windows.Markup; using System.Windows; using Signum.Windows.Operations; using Signum.Utilities; using Signum.Entities; namespace Signum.Windows.Authorization { public static class OperationAuthClient { static Dictionary<(OperationSymbol operation, Type type), OperationAllowed> authorizedOperations; public static bool Started { get; private set; } internal static void Start() { Started = true; AuthClient.UpdateCacheEvent += new Action(AuthClient_UpdateCacheEvent); } static void AuthClient_UpdateCacheEvent() { authorizedOperations = Server.Return((IOperationAuthServer s) => s.AllowedOperations()); } public static bool GetAllowed(OperationSymbol operationSymbol, Type type, bool inUserInterface) { var allowed = authorizedOperations.GetOrThrow((operationSymbol, type)); return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface; } } [MarkupExtensionReturnType(typeof(bool))] public class OperationAllowedExtension : MarkupExtension { public bool InUserInterface { get; set; } OperationSymbol operationSymbol; Type type; public OperationAllowedExtension(object value, Type type) { this.operationSymbol = (value is IOperationSymbolContainer) ? ((IOperationSymbolContainer)value).Symbol : (OperationSymbol)value; this.type = type; } public override object ProvideValue(IServiceProvider serviceProvider) { return OperationAuthClient.GetAllowed(operationSymbol, type, InUserInterface); } } [MarkupExtensionReturnType(typeof(Visibility))] public class OperationVisiblityExtension : MarkupExtension { public bool InUserInterface { get; set; } OperationSymbol operationSymbol; Type type; public OperationVisiblityExtension(object value, Type type) { this.operationSymbol = (value is IOperationSymbolContainer) ? ((IOperationSymbolContainer)value).Symbol : (OperationSymbol)value; } public override object ProvideValue(IServiceProvider serviceProvider) { return OperationAuthClient.GetAllowed(operationSymbol, type, InUserInterface) ? Visibility.Visible : Visibility.Collapsed; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Signum.Entities.Authorization; using Signum.Services; using System.Windows.Markup; using System.Windows; using Signum.Windows.Operations; using Signum.Utilities; using Signum.Entities; namespace Signum.Windows.Authorization { public static class OperationAuthClient { static Dictionary<OperationSymbol, OperationAllowed> authorizedOperations; public static bool Started { get; private set; } internal static void Start() { Started = true; AuthClient.UpdateCacheEvent += new Action(AuthClient_UpdateCacheEvent); } static void AuthClient_UpdateCacheEvent() { authorizedOperations = Server.Return((IOperationAuthServer s) => s.AllowedOperations()); } public static bool GetAllowed(OperationSymbol operationSymbol, bool inUserInterface) { var allowed = authorizedOperations.GetOrThrow(operationSymbol); return allowed == OperationAllowed.Allow || allowed == OperationAllowed.DBOnly && !inUserInterface; } } [MarkupExtensionReturnType(typeof(bool))] public class OperationAllowedExtension : MarkupExtension { public bool InUserInterface { get; set; } OperationSymbol operationKey; public OperationAllowedExtension(object value) { this.operationKey = (OperationSymbol)value; } public override object ProvideValue(IServiceProvider serviceProvider) { return OperationAuthClient.GetAllowed(operationKey, InUserInterface); } } [MarkupExtensionReturnType(typeof(Visibility))] public class OperationVisiblityExtension : MarkupExtension { public bool InUserInterface { get; set; } OperationSymbol operationKey; public OperationVisiblityExtension(object value) { this.operationKey = (value is IOperationSymbolContainer) ? ((IOperationSymbolContainer)value).Symbol : (OperationSymbol)value; } public override object ProvideValue(IServiceProvider serviceProvider) { return OperationAuthClient.GetAllowed(operationKey, InUserInterface) ? Visibility.Visible : Visibility.Collapsed; } } }
mit
C#
4751601973861024ca9e46b0c8dbc16b2dd37a70
Add SourceID and SourceType to journal
MatthewSteeples/XeroAPI.Net
source/XeroApi/Model/Journal.cs
source/XeroApi/Model/Journal.cs
using System; namespace XeroApi.Model { public class Journal : EndpointModelBase { [ItemId] public Guid JournalID { get; set; } public DateTime JournalDate { get; set; } public long JournalNumber { get; set; } [ItemUpdatedDate] public DateTime CreatedDateUTC { get; set; } public string Reference { get; set; } public JournalLines JournalLines { get; set; } public Guid SourceID { get; set; } public string SourceType { get; set; } public override string ToString() { return string.Format("Journal:{0}", JournalNumber); } } public class Journals : ModelList<Journal> { } }
using System; namespace XeroApi.Model { public class Journal : EndpointModelBase { [ItemId] public Guid JournalID { get; set; } public DateTime JournalDate { get; set; } public long JournalNumber { get; set; } [ItemUpdatedDate] public DateTime CreatedDateUTC { get; set; } public string Reference { get; set; } public JournalLines JournalLines { get; set; } public override string ToString() { return string.Format("Journal:{0}", JournalNumber); } } public class Journals : ModelList<Journal> { } }
mit
C#
ee0a0a70c00baa2b5db03454947998c0d34d4236
Fix IsStream decoding
martin211/aimp_DiskCover,martin211/aimp_DiskCover
Plugin/CoverFinder/Interface/TrackInfo.cs
Plugin/CoverFinder/Interface/TrackInfo.cs
using System; using System.Diagnostics.Contracts; using AIMP.SDK.Services.Player; namespace AIMP.DiskCover { /// <summary> /// Container for data of various data of /// a musical track which might be required by /// cover finder plugins. /// </summary> public class TrackInfo { private IAimpPlayer _player; /// <summary> /// Creates an instance of <see cref="TrackInfo"/> class. /// </summary> /// <param name="player">An instance of AIMP player to load data from.</param> public TrackInfo(IAimpPlayer player) { Contract.Requires(player != null); _player = player; var trackInfo = player.CurrentFileInfo; //StreamType = player.CurrentPlayingInfo.StreamType; IsStream = trackInfo.FileName.StartsWith("http") || trackInfo.FileName.StartsWith("https") || trackInfo.FileName.StartsWith("ftp") || trackInfo.FileName.Contains("://"); if (trackInfo != null) { Artist = trackInfo.Artist; Album = trackInfo.Album; Title = trackInfo.Title; FileName = trackInfo.FileName; } } public bool IsStream { get; private set; } public String Artist { get; private set; } public String Album { get; private set; } public String Title { get; private set; } public String FileName { get; private set; } } }
using System; using System.Diagnostics.Contracts; using AIMP.SDK.Services.Player; namespace AIMP.DiskCover { /// <summary> /// Container for data of various data of /// a musical track which might be required by /// cover finder plugins. /// </summary> public class TrackInfo { private IAimpPlayer _player; /// <summary> /// Creates an instance of <see cref="TrackInfo"/> class. /// </summary> /// <param name="player">An instance of AIMP player to load data from.</param> public TrackInfo(IAimpPlayer player) { Contract.Requires(player != null); _player = player; var trackInfo = player.CurrentFileInfo; //StreamType = player.CurrentPlayingInfo.StreamType; IsStream = trackInfo.FileName.StartsWith("http") || trackInfo.FileName.StartsWith("https") || trackInfo.FileName.StartsWith("ftp"); if (trackInfo != null) { Artist = trackInfo.Artist; Album = trackInfo.Album; Title = trackInfo.Title; FileName = trackInfo.FileName; } } public bool IsStream { get; private set; } public String Artist { get; private set; } public String Album { get; private set; } public String Title { get; private set; } public String FileName { get; private set; } } }
apache-2.0
C#
6f9a3c777e3b80b9a4571cc353849a59ba8bdede
use 'using' pattern for GValue
freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,GStreamer/gstreamer-sharp,gstreamer-sharp/gstreamer-sharp,freedesktop-unofficial-mirror/gstreamer__gstreamer-sharp,GStreamer/gstreamer-sharp
sources/custom/Object.cs
sources/custom/Object.cs
// Copyright (C) 2013 Stephan Sundermann <stephansundermann@gmail.com> // // 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 System.Runtime.InteropServices; namespace Gst { public class PropertyNotFoundException : Exception {} partial class Object { private Dictionary <string, bool> PropertyNameCache = new Dictionary<string, bool> (); [DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr g_object_class_find_property (IntPtr klass, IntPtr name); bool PropertyExists (string name) { if (PropertyNameCache.ContainsKey (name)) return PropertyNameCache [name]; var ptr = g_object_class_find_property (GType.GetClassPtr (), GLib.Marshaller.StringToPtrGStrdup (name)); var result = ptr != IntPtr.Zero; GLib.Marshaller.Free (ptr); // just cache the positive results because there might // actually be new properties getting installed if (result) PropertyNameCache [name] = result; return result; } public object this[string property] { get { if (PropertyExists (property)) { using (GLib.Value v = GetProperty (property)) { return v.Val; } } else throw new PropertyNotFoundException (); } set { if (PropertyExists (property)) { using (GLib.Value v = new GLib.Value (this, property)) { v.Val = value; SetProperty (property, v); } } else throw new PropertyNotFoundException (); } } public void Connect (string signal, SignalHandler handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, SignalHandler handler) { DynamicSignal.Disconnect (this, signal, handler); } public void Connect (string signal, Delegate handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, Delegate handler) { DynamicSignal.Disconnect (this, signal, handler); } public object Emit (string signal, params object[] parameters) { return DynamicSignal.Emit (this, signal, parameters); } } }
// Copyright (C) 2013 Stephan Sundermann <stephansundermann@gmail.com> // // 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 System.Runtime.InteropServices; namespace Gst { public class PropertyNotFoundException : Exception {} partial class Object { private Dictionary <string, bool> PropertyNameCache = new Dictionary<string, bool> (); [DllImport ("libgobject-2.0-0.dll", CallingConvention = CallingConvention.Cdecl)] static extern IntPtr g_object_class_find_property (IntPtr klass, IntPtr name); bool PropertyExists (string name) { if (PropertyNameCache.ContainsKey (name)) return PropertyNameCache [name]; var ptr = g_object_class_find_property (GType.GetClassPtr (), GLib.Marshaller.StringToPtrGStrdup (name)); var result = ptr != IntPtr.Zero; GLib.Marshaller.Free (ptr); // just cache the positive results because there might // actually be new properties getting installed if (result) PropertyNameCache [name] = result; return result; } public object this[string property] { get { if (PropertyExists (property)) { GLib.Value v = GetProperty (property); object o = v.Val; v.Dispose (); return o; } else throw new PropertyNotFoundException (); } set { if (PropertyExists (property)) { GLib.Value v = new GLib.Value (this, property); v.Val = value; SetProperty (property, v); v.Dispose (); } else throw new PropertyNotFoundException (); } } public void Connect (string signal, SignalHandler handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, SignalHandler handler) { DynamicSignal.Disconnect (this, signal, handler); } public void Connect (string signal, Delegate handler) { DynamicSignal.Connect (this, signal, handler); } public void Disconnect (string signal, Delegate handler) { DynamicSignal.Disconnect (this, signal, handler); } public object Emit (string signal, params object[] parameters) { return DynamicSignal.Emit (this, signal, parameters); } } }
lgpl-2.1
C#
a0460b8216eedbf6dd02bde2f89ebb4ddf568447
Fix bug to find non-existent sys db in mysql
SaladLab/TrackableData,SaladbowlCreative/TrackableData,SaladbowlCreative/TrackableData,SaladLab/TrackableData
plugins/TrackableData.MySql.Tests/Database.cs
plugins/TrackableData.MySql.Tests/Database.cs
using System; using System.Configuration; using System.Data.SqlClient; using MySql.Data.MySqlClient; namespace TrackableData.MySql.Tests { public class Database : IDisposable { public Database() { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; // create TestDb if not exist var cstrForMaster = ""; { var connectionBuilder = new SqlConnectionStringBuilder(cstr); connectionBuilder.InitialCatalog = ""; cstrForMaster = connectionBuilder.ToString(); } using (var conn = new MySqlConnection(cstrForMaster)) { conn.Open(); using (var cmd = new MySqlCommand()) { cmd.CommandText = string.Format(@" DROP DATABASE IF EXISTS {0}; CREATE DATABASE {0}; ", new SqlConnectionStringBuilder(cstr).InitialCatalog); cmd.Connection = conn; var result = cmd.ExecuteScalar(); } } } public MySqlConnection Connection { get { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connection = new MySqlConnection(cstr); connection.Open(); return connection; } } public void Dispose() { } } }
using System; using System.Configuration; using System.Data.SqlClient; using MySql.Data.MySqlClient; namespace TrackableData.MySql.Tests { public class Database : IDisposable { public Database() { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; // create TestDb if not exist var cstrForMaster = ""; { var connectionBuilder = new SqlConnectionStringBuilder(cstr); connectionBuilder.InitialCatalog = "sys"; cstrForMaster = connectionBuilder.ToString(); } using (var conn = new MySqlConnection(cstrForMaster)) { conn.Open(); using (var cmd = new MySqlCommand()) { cmd.CommandText = string.Format(@" DROP DATABASE IF EXISTS {0}; CREATE DATABASE {0}; ", new SqlConnectionStringBuilder(cstr).InitialCatalog); cmd.Connection = conn; var result = cmd.ExecuteScalar(); } } } public MySqlConnection Connection { get { var cstr = ConfigurationManager.ConnectionStrings["TestDb"].ConnectionString; var connection = new MySqlConnection(cstr); connection.Open(); return connection; } } public void Dispose() { } } }
mit
C#
929df35ec0f94d477880205e281e93e1d295a2c5
remove redundant constructor
pseale/monopoly-dotnet,pseale/monopoly-dotnet
src/MonopolyWeb/Models/ASPNETIdentity/IdentityModels.cs
src/MonopolyWeb/Models/ASPNETIdentity/IdentityModels.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Linq; using Microsoft.AspNet.Identity; namespace ASPNETIdentity { // Modify the User class to add extra user information public class User : IUser { public User() : this(String.Empty) { } public User(string userName) { UserName = userName; Id = Guid.NewGuid().ToString(); } [Key] public string Id { get; set; } public string UserName { get; set; } } public class IdentityDbContext : DbContext { // This method ensures that user names are always unique protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items) { if (entityEntry.State == EntityState.Added) { User user = entityEntry.Entity as User; // Check for uniqueness of user name if (user != null && Users.Where(u => u.UserName.ToUpper() == user.UserName.ToUpper()).Count() > 0) { var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>()); result.ValidationErrors.Add(new DbValidationError("User", "User name must be unique.")); return result; } } return base.ValidateEntity(entityEntry, items); } //property injected by EF, oops public DbSet<User> Users { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Entity.Validation; using System.Linq; using Microsoft.AspNet.Identity; namespace ASPNETIdentity { // Modify the User class to add extra user information public class User : IUser { public User() : this(String.Empty) { } public User(string userName) { UserName = userName; Id = Guid.NewGuid().ToString(); } [Key] public string Id { get; set; } public string UserName { get; set; } } public class IdentityDbContext : DbContext { public IdentityDbContext() :base() { } // This method ensures that user names are always unique protected override DbEntityValidationResult ValidateEntity(DbEntityEntry entityEntry, IDictionary<object, object> items) { if (entityEntry.State == EntityState.Added) { User user = entityEntry.Entity as User; // Check for uniqueness of user name if (user != null && Users.Where(u => u.UserName.ToUpper() == user.UserName.ToUpper()).Count() > 0) { var result = new DbEntityValidationResult(entityEntry, new List<DbValidationError>()); result.ValidationErrors.Add(new DbValidationError("User", "User name must be unique.")); return result; } } return base.ValidateEntity(entityEntry, items); } //property injected by EF, oops public DbSet<User> Users { get; set; } } }
mit
C#
537a777947707ca3cdd13e6a217e06de63609a7e
Fix build for VS15
karthiknadig/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS
src/Package/Impl/History/Commands/LoadHistoryCommand.cs
src/Package/Impl/History/Commands/LoadHistoryCommand.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using Microsoft.Common.Core.UI.Commands; using Microsoft.Languages.Editor.Controller.Command; using Microsoft.R.Components.Controller; using Microsoft.R.Components.History; using Microsoft.R.Components.InteractiveWorkflow; using Microsoft.R.Support.Settings; using Microsoft.VisualStudio.R.Package.Commands; using Microsoft.VisualStudio.R.Package.Shell; using Microsoft.VisualStudio.R.Packages.R; using Microsoft.VisualStudio.Text.Editor; #if VS14 using Microsoft.VisualStudio.ProjectSystem.Utilities; #endif using PathHelper = Microsoft.VisualStudio.ProjectSystem.PathHelper; namespace Microsoft.VisualStudio.R.Package.History.Commands { internal class LoadHistoryCommand : ViewCommand { private readonly IApplicationShell _appShell; private readonly IRInteractiveWorkflow _interactiveWorkflow; private readonly IRHistory _history; public LoadHistoryCommand(IApplicationShell appShell, ITextView textView, IRHistoryProvider historyProvider, IRInteractiveWorkflow interactiveWorkflow) : base(textView, RGuidList.RCmdSetGuid, RPackageCommandId.icmdLoadHistory, false) { _appShell = appShell; _interactiveWorkflow = interactiveWorkflow; _history = historyProvider.GetAssociatedRHistory(textView); } public override CommandStatus Status(Guid guid, int id) { return _interactiveWorkflow.ActiveWindow != null ? CommandStatus.SupportedAndEnabled : CommandStatus.Supported; } public override CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) { var initialPath = RToolsSettings.Current.WorkingDirectory != null ? PathHelper.EnsureTrailingSlash(RToolsSettings.Current.WorkingDirectory) : null; var file = _appShell.FileDialog.ShowOpenFileDialog(Resources.HistoryFileFilter, initialPath, Resources.LoadHistoryTitle); if (file != null) { _history.TryLoadFromFile(file); } return CommandResult.Executed; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using Microsoft.Common.Core.UI.Commands; using Microsoft.Languages.Editor.Controller.Command; using Microsoft.R.Components.Controller; using Microsoft.R.Components.History; using Microsoft.R.Components.InteractiveWorkflow; using Microsoft.R.Support.Settings; using Microsoft.VisualStudio.ProjectSystem; using Microsoft.VisualStudio.R.Package.Commands; using Microsoft.VisualStudio.R.Package.Shell; using Microsoft.VisualStudio.R.Packages.R; using Microsoft.VisualStudio.Text.Editor; #if VS14 using Microsoft.VisualStudio.ProjectSystem.Utilities; #endif namespace Microsoft.VisualStudio.R.Package.History.Commands { internal class LoadHistoryCommand : ViewCommand { private readonly IApplicationShell _appShell; private readonly IRInteractiveWorkflow _interactiveWorkflow; private readonly IRHistory _history; public LoadHistoryCommand(IApplicationShell appShell, ITextView textView, IRHistoryProvider historyProvider, IRInteractiveWorkflow interactiveWorkflow) : base(textView, RGuidList.RCmdSetGuid, RPackageCommandId.icmdLoadHistory, false) { _appShell = appShell; _interactiveWorkflow = interactiveWorkflow; _history = historyProvider.GetAssociatedRHistory(textView); } public override CommandStatus Status(Guid guid, int id) { return _interactiveWorkflow.ActiveWindow != null ? CommandStatus.SupportedAndEnabled : CommandStatus.Supported; } public override CommandResult Invoke(Guid group, int id, object inputArg, ref object outputArg) { var initialPath = RToolsSettings.Current.WorkingDirectory != null ? PathHelper.EnsureTrailingSlash(RToolsSettings.Current.WorkingDirectory) : null; var file = _appShell.FileDialog.ShowOpenFileDialog(Resources.HistoryFileFilter, initialPath, Resources.LoadHistoryTitle); if (file != null) { _history.TryLoadFromFile(file); } return CommandResult.Executed; } } }
mit
C#
c2ca4aa37a9b11db026bb774d818fb6d5ceb3ba0
Make UnlinkAppCommand implement ICommand
appharbor/appharbor-cli
src/AppHarbor/Commands/UnlinkAppCommand.cs
src/AppHarbor/Commands/UnlinkAppCommand.cs
using System; namespace AppHarbor.Commands { public class UnlinkAppCommand : ICommand { public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
namespace AppHarbor.Commands { public class UnlinkAppCommand { } }
mit
C#
aa9ea22dda7b88cd3bfe63d6ab1ef0772ce7ed88
Fix concurrent access to OnReceived
alexvictoor/SignalR-Hazelcast,alexvictoor/SignalR-Hazelcast,alexvictoor/SignalR-Hazelcast
SignalR-Hazelcast/HzScaleoutMessageBus.cs
SignalR-Hazelcast/HzScaleoutMessageBus.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hazelcast.Core; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Messaging; namespace SignalR.Hazelcast { class HzScaleoutMessageBus : ScaleoutMessageBus { private readonly ITopic<HzMessage> _topic; private readonly IAtomicLong _counter; private readonly ILock _hzLock; public HzScaleoutMessageBus(IDependencyResolver resolver, HzConfiguration configuration, IHazelcastInstance hzInstance) : base(resolver, configuration) { _topic = hzInstance.GetTopic<HzMessage>(configuration.TopicName); _topic.AddMessageListener(msg => { // TODO real logs //Console.Out.WriteLine("Just received something"); var hzMessage = msg.GetMessageObject(); lock (_hzLock) { OnReceived(0, hzMessage.Id, hzMessage.ScaleoutMessage); } }); _counter = hzInstance.GetAtomicLong(configuration.CounterName); _hzLock = hzInstance.GetLock(configuration.LockName); } protected override Task Send(int streamIndex, IList<Message> messages) { // TODO real logs //Console.Out.WriteLine("About to send something"); return Send(messages); } protected override Task Send(IList<Message> messages) { // TODO real logs //Console.Out.WriteLine("About to send something 2"); _hzLock.Lock(); try { var sqn = (ulong) _counter.IncrementAndGet(); var hzMessage = new HzMessage {Id = sqn, ScaleoutMessage = new ScaleoutMessage(messages)}; _topic.Publish(hzMessage); } finally { _hzLock.Unlock(); } return Task.WhenAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Hazelcast.Core; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Messaging; namespace SignalR.Hazelcast { class HzScaleoutMessageBus : ScaleoutMessageBus { private readonly ITopic<HzMessage> _topic; private readonly IAtomicLong _counter; private readonly ILock _hzLock; public HzScaleoutMessageBus(IDependencyResolver resolver, HzConfiguration configuration, IHazelcastInstance hzInstance) : base(resolver, configuration) { _topic = hzInstance.GetTopic<HzMessage>(configuration.TopicName); _topic.AddMessageListener(msg => { // TODO real logs //Console.Out.WriteLine("Just received something"); var hzMessage = msg.GetMessageObject(); OnReceived(0, hzMessage.Id, hzMessage.ScaleoutMessage); }); _counter = hzInstance.GetAtomicLong(configuration.CounterName); _hzLock = hzInstance.GetLock(configuration.LockName); } protected override Task Send(int streamIndex, IList<Message> messages) { // TODO real logs //Console.Out.WriteLine("About to send something"); return Send(messages); } protected override Task Send(IList<Message> messages) { // TODO real logs //Console.Out.WriteLine("About to send something 2"); _hzLock.Lock(); try { var sqn = (ulong) _counter.IncrementAndGet(); var hzMessage = new HzMessage {Id = sqn, ScaleoutMessage = new ScaleoutMessage(messages)}; _topic.Publish(hzMessage); } finally { _hzLock.Unlock(); } return Task.WhenAll(); } } }
apache-2.0
C#
aabf28b4f5ee897fa356e45148c63ea3cb968c1f
allow execution of scripts with a parameterless Main method (-p:run)
rmartinho/boo,KidFashion/boo,Unity-Technologies/boo,scottstephens/boo,BITechnologies/boo,Unity-Technologies/boo,wbardzinski/boo,drslump/boo,KingJiangNet/boo,KingJiangNet/boo,scottstephens/boo,scottstephens/boo,rmartinho/boo,Unity-Technologies/boo,BitPuffin/boo,hmah/boo,rmartinho/boo,bamboo/boo,hmah/boo,drslump/boo,BITechnologies/boo,KidFashion/boo,rmartinho/boo,scottstephens/boo,Unity-Technologies/boo,drslump/boo,BitPuffin/boo,BitPuffin/boo,drslump/boo,KidFashion/boo,wbardzinski/boo,bamboo/boo,KingJiangNet/boo,boo-lang/boo,BitPuffin/boo,scottstephens/boo,BITechnologies/boo,KidFashion/boo,boo-lang/boo,rmartinho/boo,rmboggs/boo,drslump/boo,rmboggs/boo,BillHally/boo,bamboo/boo,KingJiangNet/boo,BITechnologies/boo,bamboo/boo,scottstephens/boo,wbardzinski/boo,rmboggs/boo,scottstephens/boo,BITechnologies/boo,KidFashion/boo,rmboggs/boo,BitPuffin/boo,wbardzinski/boo,boo-lang/boo,boo-lang/boo,BillHally/boo,hmah/boo,rmboggs/boo,hmah/boo,boo-lang/boo,BillHally/boo,drslump/boo,KidFashion/boo,boo-lang/boo,Unity-Technologies/boo,hmah/boo,bamboo/boo,rmboggs/boo,Unity-Technologies/boo,KingJiangNet/boo,rmboggs/boo,KingJiangNet/boo,bamboo/boo,wbardzinski/boo,BillHally/boo,wbardzinski/boo,rmartinho/boo,drslump/boo,Unity-Technologies/boo,boo-lang/boo,scottstephens/boo,BillHally/boo,rmartinho/boo,hmah/boo,BITechnologies/boo,Unity-Technologies/boo,BillHally/boo,hmah/boo,rmartinho/boo,hmah/boo,wbardzinski/boo,BitPuffin/boo,wbardzinski/boo,BITechnologies/boo,KingJiangNet/boo,BillHally/boo,BitPuffin/boo,BITechnologies/boo,BitPuffin/boo,hmah/boo,rmboggs/boo,KingJiangNet/boo,bamboo/boo,KidFashion/boo,boo-lang/boo
src/Boo.Lang.Compiler/Steps/RunAssembly.cs
src/Boo.Lang.Compiler/Steps/RunAssembly.cs
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; namespace Boo.Lang.Compiler.Steps { public class RunAssembly : AbstractCompilerStep { override public void Run() { if (Errors.Count > 0 || CompilerOutputType.Library == Parameters.OutputType || Context.GeneratedAssembly == null) return; AppDomain.CurrentDomain.AssemblyResolve += ResolveGeneratedAssembly; try { var entryPoint = Context.GeneratedAssembly.EntryPoint; if (entryPoint.GetParameters().Length == 1) entryPoint.Invoke(null, new object[] { new string[0] }); else entryPoint.Invoke(null, null); } finally { AppDomain.CurrentDomain.AssemblyResolve -= ResolveGeneratedAssembly; } } private Assembly ResolveGeneratedAssembly(object sender, ResolveEventArgs args) { return args.Name == Context.GeneratedAssembly.FullName ? Context.GeneratedAssembly : null; } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Reflection; namespace Boo.Lang.Compiler.Steps { public class RunAssembly : AbstractCompilerStep { override public void Run() { if (Errors.Count > 0 || CompilerOutputType.Library == Parameters.OutputType || Context.GeneratedAssembly == null) return; AppDomain.CurrentDomain.AssemblyResolve += ResolveGeneratedAssembly; try { Context.GeneratedAssembly.EntryPoint.Invoke(null, new object[] { new string[0] }); } finally { AppDomain.CurrentDomain.AssemblyResolve -= ResolveGeneratedAssembly; } } private Assembly ResolveGeneratedAssembly(object sender, ResolveEventArgs args) { return args.Name == Context.GeneratedAssembly.FullName ? Context.GeneratedAssembly : null; } } }
bsd-3-clause
C#
892d906ac78f1c66c6b1f77ba0d2339a7d74d27b
Fix tx link in payment request
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Payments/PaymentTypes.Bitcoin.cs
BTCPayServer/Payments/PaymentTypes.Bitcoin.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Services.Invoices; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace BTCPayServer.Payments { public class BitcoinPaymentType : PaymentType { public static BitcoinPaymentType Instance { get; } = new BitcoinPaymentType(); private BitcoinPaymentType() { } public override string ToPrettyString() => "On-Chain"; public override string GetId() => "BTCLike"; public override CryptoPaymentData DeserializePaymentData(string str) { return JsonConvert.DeserializeObject<BitcoinLikePaymentData>(str); } public override IPaymentMethodDetails DeserializePaymentMethodDetails(string str) { return JsonConvert.DeserializeObject<Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod>(str); } public override ISupportedPaymentMethod DeserializeSupportedPaymentMethod(BTCPayNetworkBase network, JToken value) { if (network == null) throw new ArgumentNullException(nameof(network)); if (value == null) throw new ArgumentNullException(nameof(value)); var net = (BTCPayNetwork)network; if (value is JObject jobj) { var scheme = net.NBXplorerNetwork.Serializer.ToObject<DerivationSchemeSettings>(jobj); scheme.Network = net; return scheme; } // Legacy return DerivationSchemeSettings.Parse(((JValue)value).Value<string>(), net); } public override string GetTransactionLink(BTCPayNetworkBase network, string txId) { if (txId == null) throw new ArgumentNullException(nameof(txId)); if (network?.BlockExplorerLink == null) return null; txId = txId.Split('-').First(); return string.Format(CultureInfo.InvariantCulture, network.BlockExplorerLink, txId); } public override string InvoiceViewPaymentPartialName { get; } = "ViewBitcoinLikePaymentData"; } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Services.Invoices; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace BTCPayServer.Payments { public class BitcoinPaymentType : PaymentType { public static BitcoinPaymentType Instance { get; } = new BitcoinPaymentType(); private BitcoinPaymentType() { } public override string ToPrettyString() => "On-Chain"; public override string GetId() => "BTCLike"; public override CryptoPaymentData DeserializePaymentData(string str) { return JsonConvert.DeserializeObject<BitcoinLikePaymentData>(str); } public override IPaymentMethodDetails DeserializePaymentMethodDetails(string str) { return JsonConvert.DeserializeObject<Payments.Bitcoin.BitcoinLikeOnChainPaymentMethod>(str); } public override ISupportedPaymentMethod DeserializeSupportedPaymentMethod(BTCPayNetworkBase network, JToken value) { if (network == null) throw new ArgumentNullException(nameof(network)); if (value == null) throw new ArgumentNullException(nameof(value)); var net = (BTCPayNetwork)network; if (value is JObject jobj) { var scheme = net.NBXplorerNetwork.Serializer.ToObject<DerivationSchemeSettings>(jobj); scheme.Network = net; return scheme; } // Legacy return DerivationSchemeSettings.Parse(((JValue)value).Value<string>(), net); } public override string GetTransactionLink(BTCPayNetworkBase network, string txId) { if (txId == null) throw new ArgumentNullException(nameof(txId)); if (network?.BlockExplorerLink == null) return null; return string.Format(CultureInfo.InvariantCulture, network.BlockExplorerLink, txId); } public override string InvoiceViewPaymentPartialName { get; } = "ViewBitcoinLikePaymentData"; } }
mit
C#
737e86b889ec4a96e8dbe40c37e876a985a612df
add usage check and message
akrisiun/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,antoniusriha/gtk-sharp,antoniusriha/gtk-sharp,openmedicus/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,akrisiun/gtk-sharp,openmedicus/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,antoniusriha/gtk-sharp,orion75/gtk-sharp,openmedicus/gtk-sharp,akrisiun/gtk-sharp,antoniusriha/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,orion75/gtk-sharp,Gankov/gtk-sharp,akrisiun/gtk-sharp,orion75/gtk-sharp,akrisiun/gtk-sharp,Gankov/gtk-sharp,Gankov/gtk-sharp,sillsdev/gtk-sharp,sillsdev/gtk-sharp,openmedicus/gtk-sharp,orion75/gtk-sharp
sample/GstPlayer.cs
sample/GstPlayer.cs
// GstPlayer.cs - a simple Vorbis media player using GStreamer // // Author: Alp Toker <alp@atoker.com> // // Copyright (c) 2002 Alp Toker using System; using Gst; public class GstTest { static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine ("usage: Gst.Player.exe FILE.ogg"); return; } Application.Init (); /* create a new bin to hold the elements */ Pipeline bin = new Pipeline("pipeline"); /* create a disk reader */ Element filesrc = ElementFactory.Make ("filesrc", "disk_source"); filesrc.SetProperty ("location", args[0]); /* now it's time to get the decoder */ Element decoder = ElementFactory.Make ("vorbisfile", "decode"); /* and an audio sink */ Element osssink = ElementFactory.Make ("osssink", "play_audio"); /* add objects to the main pipeline */ bin.Add (filesrc); bin.Add (decoder); bin.Add (osssink); /* connect the elements */ filesrc.Link (decoder); decoder.Link (osssink); /* start playing */ bin.SetState (ElementState.Playing); while (bin.Iterate ()); /* stop the bin */ bin.SetState (ElementState.Null); } }
// GstPlayer.cs - a simple Vorbis media player using GStreamer // // Author: Alp Toker <alp@atoker.com> // // Copyright (c) 2002 Alp Toker using System; using Gst; public class GstTest { static void Main(string[] args) { Application.Init (); /* create a new bin to hold the elements */ Pipeline bin = new Pipeline("pipeline"); /* create a disk reader */ Element filesrc = ElementFactory.Make ("filesrc", "disk_source"); filesrc.SetProperty ("location", args[0]); /* now it's time to get the decoder */ Element decoder = ElementFactory.Make ("vorbisfile", "decode"); /* and an audio sink */ Element osssink = ElementFactory.Make ("osssink", "play_audio"); /* add objects to the main pipeline */ bin.Add (filesrc); bin.Add (decoder); bin.Add (osssink); /* connect the elements */ filesrc.Link (decoder); decoder.Link (osssink); /* start playing */ bin.SetState (ElementState.Playing); while (bin.Iterate ()); /* stop the bin */ bin.SetState (ElementState.Null); } }
lgpl-2.1
C#
d10d81d9ddab27e44563538fb3598372ff8571a3
Update Class1.cs
krabonsz/indywidualne
DokumentyPacjenci/DokumentyPacjenci/Class1.cs
DokumentyPacjenci/DokumentyPacjenci/Class1.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DokumentyPacjenci { public class Class1 { int baba { get; set; } float facet {get;set;} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DokumentyPacjenci { public class Class1 { int baba { get; set; } } }
mit
C#
13a0182942fd1fe1670909d90f396d21db73d7f7
fix error on saving empty content
Franklin89/Blog,Franklin89/Blog
src/MLSoftware.Web/Model/PostExtensions.cs
src/MLSoftware.Web/Model/PostExtensions.cs
using Markdig; using Markdig.Renderers; using System.IO; namespace MLSoftware.Web.Model { public static class PostExtensions { public static string Parse(this PostContent postContent) { var content = postContent.Content; if (string.IsNullOrEmpty(content)) { return string.Empty; } var pipeline = new MarkdownPipelineBuilder().UseYamlFrontMatter().Build(); var doc = Markdown.Parse(content, pipeline); using (var writer = new StringWriter()) { var renderer = new HtmlRenderer(writer); pipeline.Setup(renderer); renderer.Render(doc); writer.Flush(); return writer.ToString(); } } } }
using Markdig; using Markdig.Renderers; using System.IO; namespace MLSoftware.Web.Model { public static class PostExtensions { public static string Parse(this PostContent postContent) { var content = postContent.Content; var pipeline = new MarkdownPipelineBuilder().UseYamlFrontMatter().Build(); var doc = Markdown.Parse(content, pipeline); using (var writer = new StringWriter()) { var renderer = new HtmlRenderer(writer); pipeline.Setup(renderer); renderer.Render(doc); writer.Flush(); return writer.ToString(); } } } }
mit
C#
a8521a832422b20de16bd6cd3f2cdc2a2a999a46
Fix display of title in alert box
eleven41/Eleven41.Web.Mvc.Bootstrap
Eleven41.Web.Mvc.Bootstrap/AlertExtensions.cs
Eleven41.Web.Mvc.Bootstrap/AlertExtensions.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Web.Mvc { public static class AlertExtensions { public static BootstrapAlert BeginSuccessBox(this HtmlHelper html) { return BeginSuccessBox(html, null); } public static BootstrapAlert BeginSuccessBox(this HtmlHelper html, string title) { return BeginAlertHelper(html, "alert-success", title, null, null); } public static BootstrapAlert BeginInfoBox(this HtmlHelper html) { return BeginInfoBox(html, null); } public static BootstrapAlert BeginInfoBox(this HtmlHelper html, string title) { return BeginAlertHelper(html, "alert-info", title, null, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html) { return BeginErrorBox(html, null, null, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html, string title) { return BeginErrorBox(html, title, null, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html, string title, string id) { return BeginErrorBox(html, title, id, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html, string title, string id, string className) { return BeginAlertHelper(html, "alert-error", title, id, className); } public static BootstrapAlert BeginWarningBox(this HtmlHelper html) { return BeginWarningBox(html, null); } public static BootstrapAlert BeginWarningBox(this HtmlHelper html, string title) { return BeginAlertHelper(html, null, title, null, null); } private static BootstrapAlert BeginAlertHelper(this HtmlHelper html, string alertClassName, string title, string id, string className) { TagBuilder tag = new TagBuilder("div"); tag.AddOrMergeAttribute("class", "alert"); if (!String.IsNullOrEmpty(alertClassName)) tag.AddOrMergeAttribute("class", alertClassName); if (!String.IsNullOrEmpty(className)) tag.AddOrMergeAttribute("class", className); if (!String.IsNullOrEmpty(id)) tag.Attributes.Add("id", id); html.ViewContext.Writer.Write(tag.ToString(TagRenderMode.StartTag)); if (!String.IsNullOrEmpty(title)) { TagBuilder titleTag = new TagBuilder("h4"); titleTag.MergeAttribute("class", "alert-heading"); titleTag.SetInnerText(title); html.ViewContext.Writer.Write(titleTag.ToString(TagRenderMode.Normal)); } BootstrapAlert theAlert = new BootstrapAlert(html.ViewContext); return theAlert; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace System.Web.Mvc { public static class AlertExtensions { public static BootstrapAlert BeginSuccessBox(this HtmlHelper html) { return BeginSuccessBox(html, null); } public static BootstrapAlert BeginSuccessBox(this HtmlHelper html, string title) { return BeginAlertHelper(html, "alert-success", title, null, null); } public static BootstrapAlert BeginInfoBox(this HtmlHelper html) { return BeginInfoBox(html, null); } public static BootstrapAlert BeginInfoBox(this HtmlHelper html, string title) { return BeginAlertHelper(html, "alert-info", title, null, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html) { return BeginErrorBox(html, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html, string title) { return BeginErrorBox(html, null, null, null); } public static BootstrapAlert BeginErrorBox(this HtmlHelper html, string title, string id, string className) { return BeginAlertHelper(html, "alert-error", title, id, className); } public static BootstrapAlert BeginWarningBox(this HtmlHelper html) { return BeginWarningBox(html, null); } public static BootstrapAlert BeginWarningBox(this HtmlHelper html, string title) { return BeginAlertHelper(html, null, title, null, null); } private static BootstrapAlert BeginAlertHelper(this HtmlHelper html, string alertClassName, string title, string id, string className) { TagBuilder tag = new TagBuilder("div"); tag.AddOrMergeAttribute("class", "alert"); if (!String.IsNullOrEmpty(alertClassName)) tag.AddOrMergeAttribute("class", alertClassName); if (!String.IsNullOrEmpty(className)) tag.AddOrMergeAttribute("class", className); if (!String.IsNullOrEmpty(id)) tag.Attributes.Add("id", id); html.ViewContext.Writer.Write(tag.ToString(TagRenderMode.StartTag)); if (!String.IsNullOrEmpty(title)) { TagBuilder titleTag = new TagBuilder("h4"); titleTag.MergeAttribute("class", "alert-heading"); titleTag.SetInnerText(title); html.ViewContext.Writer.Write(titleTag.ToString(TagRenderMode.Normal)); } BootstrapAlert theAlert = new BootstrapAlert(html.ViewContext); return theAlert; } } }
mit
C#
664d96cda53f8f0a891a92db3a9db3475fe20f9f
Revert assess changes.
Magneseus/3x-eh
Assets/Scripts/Data/SubTasks/DTask_Assess.cs
Assets/Scripts/Data/SubTasks/DTask_Assess.cs
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using UnityEngine; using SimpleJSON; public class DTask_Assess : DTask { private float assessAmount; public DTask_Assess(DBuilding dBuilding, float assessAmount, int dMaxPeople, string dName) : base(dBuilding, null, dMaxPeople, dName, 0.0f) { //TODO: make this a standard amount this.assessAmount = assessAmount; ForceClean(); ForceFixed(); } public DTask_Assess(DBuilding dBuilding) : this(dBuilding, Constants.DEFAULT_ASSESS_AMOUNT, 4, "Assess") {} public override void TurnUpdate(int numDaysPassed) { foreach (DTaskSlot taskSlot in slotList) { taskSlot.TurnUpdate(numDaysPassed); // TODO: Make this into a exponential scale or something if (taskSlot.IsFunctioning()) { float modifier = taskSlot.Person.Infection == Constants.MERSON_INFECTION_MIN ? 1 : Constants.MERSON_INFECTION_TASK_MODIFIER; building.Assess(assessAmount * Constants.MERSON_INFECTION_TASK_MODIFIER); } } } public override JSONNode SaveToJSON() { JSONNode returnNode = base.SaveToJSON(); returnNode.Add("specialTask", new JSONString("assess")); returnNode.Add("assessAmount", new JSONNumber(assessAmount)); return returnNode; } #region Accessors public float AssessAmount { get { return assessAmount; } set { assessAmount = Mathf.Clamp01(value); } } #endregion }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using UnityEngine; using SimpleJSON; public class DTask_Assess : DTask { private float assessAmount; private float oAssessAmount; private float falloff; public DTask_Assess(DBuilding dBuilding, float assessAmount, int dMaxPeople, string dName) : base(dBuilding, null, dMaxPeople, dName, 0.0f) { //TODO: make this a standard amount this.assessAmount = assessAmount; oAssessAmount = assessAmount; falloff = .9f; ForceClean(); ForceFixed(); } public DTask_Assess(DBuilding dBuilding) : this(dBuilding, Constants.DEFAULT_ASSESS_AMOUNT, 4, "Assess") {} public override void TurnUpdate(int numDaysPassed) { foreach (DTaskSlot taskSlot in slotList) { taskSlot.TurnUpdate(numDaysPassed); // TODO: Make this into a exponential scale or something if (taskSlot.IsFunctioning()) { float modifier = taskSlot.Person.Infection == Constants.MERSON_INFECTION_MIN ? 1 : Constants.MERSON_INFECTION_TASK_MODIFIER; building.Assess(assessAmount * Constants.MERSON_INFECTION_TASK_MODIFIER); assessAmount = Mathf.Max(assessAmount * falloff, oAssessAmount / 16); } } } public override JSONNode SaveToJSON() { JSONNode returnNode = base.SaveToJSON(); returnNode.Add("specialTask", new JSONString("assess")); returnNode.Add("assessAmount", new JSONNumber(assessAmount)); return returnNode; } #region Accessors public float AssessAmount { get { return assessAmount; } set { assessAmount = Mathf.Clamp01(value); } } #endregion }
mit
C#
56109cfb57f4c5bd1a1d5215d1013ecdf726e49f
Fix #3328 Add periodic flush count to FlushStats (#3360)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/CommonOptions/Stats/FlushStats.cs
src/Nest/CommonOptions/Stats/FlushStats.cs
using Newtonsoft.Json; namespace Nest { [JsonObject] public class FlushStats { [JsonProperty("total")] public long Total { get; set; } /// <summary> /// The number of flushes that were periodically triggered when translog exceeded the flush threshold. /// </summary> [JsonProperty("periodic")] public long Periodic { get; set; } /// <summary> /// The total time merges have been executed. /// </summary> [JsonProperty("total_time")] public string TotalTime { get; set; } /// <summary> /// The total time merges have been executed (in milliseconds). /// </summary> [JsonProperty("total_time_in_millis")] public long TotalTimeInMilliseconds { get; set; } } }
using Newtonsoft.Json; namespace Nest { [JsonObject] public class FlushStats { [JsonProperty("total")] public long Total { get; set; } [JsonProperty("total_time")] public string TotalTime { get; set; } [JsonProperty("total_time_in_millis")] public long TotalTimeInMilliseconds { get; set; } } }
apache-2.0
C#
b306a7b0a8ce6c837b20ea0a25d6f9bb2adc2fa4
Add IsWarning to action result
webprofusion/Certify
src/Certify.Models/Config/ActionResult.cs
src/Certify.Models/Config/ActionResult.cs
namespace Certify.Models.Config { public class ActionResult { public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public bool IsSuccess { get; set; } public bool IsWarning { get; set; } public string Message { get; set; } /// <summary> /// Optional field to hold related information such as required info or error details /// </summary> public object Result { get; set; } } public class ActionResult<T> : ActionResult { public new T Result; public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public ActionResult(string msg, bool isSuccess, T result) { Message = msg; IsSuccess = isSuccess; Result = result; } } }
namespace Certify.Models.Config { public class ActionResult { public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public bool IsSuccess { get; set; } public string Message { get; set; } /// <summary> /// Optional field to hold related information such as required info or error details /// </summary> public object Result { get; set; } } public class ActionResult<T> : ActionResult { public new T Result; public ActionResult() { } public ActionResult(string msg, bool isSuccess) { Message = msg; IsSuccess = isSuccess; } public ActionResult(string msg, bool isSuccess, T result) { Message = msg; IsSuccess = isSuccess; Result = result; } } }
mit
C#
9bb224dadcf6af015dcb89f9f683d5957b7dde0b
change fields to static
ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth,ramzzzay/GalleryMVC_With_Auth
GalleryMVC_With_Auth/App_Start/RouteConfig.cs
GalleryMVC_With_Auth/App_Start/RouteConfig.cs
using System.Web.Mvc; using System.Web.Routing; using GalleryMVC_With_Auth.Resources; namespace GalleryMVC_With_Auth { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = Defines.HomeControllerName, action = Defines.IndexView, id = UrlParameter.Optional} ); } } }
using System.Web.Mvc; using System.Web.Routing; namespace GalleryMVC_With_Auth { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute("Default", "{controller}/{action}/{id}", new {controller = "StartHome", action = "Index", id = UrlParameter.Optional} ); } } }
apache-2.0
C#
fb7c11a705364c60cdad36bb0562c361c96df3a0
add guard clauses in engine for reader and writer providers
olebg/Movie-Theater-Project
MovieTheater/MovieTheater.Framework/Core/Engine.cs
MovieTheater/MovieTheater.Framework/Core/Engine.cs
using System; using Bytes2you.Validation; using MovieTheater.Framework.Common.Contracts; using MovieTheater.Framework.Core.Contracts; using MovieTheater.Framework.Core.Providers.Contracts; namespace MovieTheater.Framework.Core { public class Engine : IEngine { private const string CommandParserCheck = "Engine Parser provider"; private const string ReaderCheck = "Engine Reader provider"; private const string WriterCheck = "Engine Writer provider"; private IParser commandParser; private IReader reader; private IWriter writer; public Engine(IParser commandParser, IReader reader, IWriter writer) { Guard.WhenArgument(commandParser, CommandParserCheck).IsNull().Throw(); Guard.WhenArgument(reader, ReaderCheck).IsNull().Throw(); Guard.WhenArgument(writer, WriterCheck).IsNull().Throw(); this.commandParser = commandParser; this.reader = reader; this.writer = writer; } public void Start() { while (true) { var fullCommand = this.reader.Read(); if (fullCommand.ToLower() == "exit") { this.writer.Write("Program terminated."); break; } try { var executionResult = this.commandParser.Process(fullCommand); this.writer.Write(executionResult); } catch (Exception ex) { this.writer.Write(ex.Message); } } } } }
using System; using Bytes2you.Validation; using MovieTheater.Framework.Common.Contracts; using MovieTheater.Framework.Core.Contracts; using MovieTheater.Framework.Core.Providers.Contracts; namespace MovieTheater.Framework.Core { public class Engine : IEngine { private const string CommandParserCheck = "Engine Parser provider"; private IParser commandParser; private IReader reader; private IWriter writer; public Engine(IParser commandParser, IReader reader, IWriter writer) { Guard.WhenArgument(commandParser, CommandParserCheck).IsNull().Throw(); this.commandParser = commandParser; this.reader = reader; this.writer = writer; } public void Start() { while (true) { var fullCommand = this.reader.Read(); if (fullCommand.ToLower() == "exit") { this.writer.Write("Program terminated."); break; } try { var executionResult = this.commandParser.Process(fullCommand); this.writer.Write(executionResult); } catch (Exception ex) { this.writer.Write(ex.Message); } } } } }
mit
C#
f0660c6e0be46af43e9abe43f887af7905c37a22
Include "Line xx" in ToString() output
macro187/nugit
NuGit/VisualStudio/VisualStudioProjectReference.cs
NuGit/VisualStudio/VisualStudioProjectReference.cs
using NuGit.Infrastructure; namespace NuGit.VisualStudio { /// <summary> /// A Visual Studio solution reference to a project /// </summary> /// /// <remarks> /// References are in <c>.sln</c> files in the following format: /// <code> /// Project("&lt;TypeId&gt;") = "&lt;Name&gt;", "&lt;Location&gt;", "&lt;Id&gt;" /// ... /// EndProject /// </code> /// </remarks> /// public class VisualStudioProjectReference { public VisualStudioProjectReference( string id, string typeId, string name, string location, int lineNumber, int lineCount) { Id = id; TypeId = typeId; Name = name; Location = location; LineNumber = lineNumber; LineCount = lineCount; } public string Id { get; private set; } public string TypeId { get; private set; } public string Name { get; private set; } public string Location { get; private set; } public int LineNumber { get; private set; } public int LineCount { get; private set; } public override string ToString() { return StringExtensions.FormatInvariant( "Line {0}:{1}: Project(\"{2}\") = \"{3}\", \"{4}\", \"{5}\"", LineNumber, LineCount, TypeId, Name, Location, Id); } } }
using NuGit.Infrastructure; namespace NuGit.VisualStudio { /// <summary> /// A Visual Studio solution reference to a project /// </summary> /// /// <remarks> /// References are in <c>.sln</c> files in the following format: /// <code> /// Project("&lt;TypeId&gt;") = "&lt;Name&gt;", "&lt;Location&gt;", "&lt;Id&gt;" /// ... /// EndProject /// </code> /// </remarks> /// public class VisualStudioProjectReference { public VisualStudioProjectReference( string id, string typeId, string name, string location, int lineNumber, int lineCount) { Id = id; TypeId = typeId; Name = name; Location = location; LineNumber = lineNumber; LineCount = lineCount; } public string Id { get; private set; } public string TypeId { get; private set; } public string Name { get; private set; } public string Location { get; private set; } public int LineNumber { get; private set; } public int LineCount { get; private set; } public override string ToString() { return StringExtensions.FormatInvariant( "{0}:{1}: Project(\"{2}\") = \"{3}\", \"{4}\", \"{5}\"", LineNumber, LineCount, TypeId, Name, Location, Id); } } }
mit
C#
2a8b84bd3deb0d7d6a8e8f0701e0d5521ee26206
Remove use of UseWorkingDirectory in default template
cake-build/cake,gep13/cake,patriksvensson/cake,devlead/cake,patriksvensson/cake,devlead/cake,gep13/cake,cake-build/cake
src/Cake.Frosting.Template/templates/cakefrosting/build/Program.cs
src/Cake.Frosting.Template/templates/cakefrosting/build/Program.cs
using System.Threading.Tasks; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .Run(args); } } public class BuildContext : FrostingContext { public bool Delay { get; set; } public BuildContext(ICakeContext context) : base(context) { Delay = context.Arguments.HasArgument("delay"); } } [TaskName("Hello")] public sealed class HelloTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.Log.Information("Hello"); } } [TaskName("World")] [IsDependentOn(typeof(HelloTask))] public sealed class WorldTask : AsyncFrostingTask<BuildContext> { // Tasks can be asynchronous public override async Task RunAsync(BuildContext context) { if (context.Delay) { context.Log.Information("Waiting..."); await Task.Delay(1500); } context.Log.Information("World"); } } [TaskName("Default")] [IsDependentOn(typeof(WorldTask))] public class DefaultTask : FrostingTask { }
using System.Threading.Tasks; using Cake.Core; using Cake.Core.Diagnostics; using Cake.Frosting; public static class Program { public static int Main(string[] args) { return new CakeHost() .UseContext<BuildContext>() .UseWorkingDirectory("..") .Run(args); } } public class BuildContext : FrostingContext { public bool Delay { get; set; } public BuildContext(ICakeContext context) : base(context) { Delay = context.Arguments.HasArgument("delay"); } } [TaskName("Hello")] public sealed class HelloTask : FrostingTask<BuildContext> { public override void Run(BuildContext context) { context.Log.Information("Hello"); } } [TaskName("World")] [IsDependentOn(typeof(HelloTask))] public sealed class WorldTask : AsyncFrostingTask<BuildContext> { // Tasks can be asynchronous public override async Task RunAsync(BuildContext context) { if (context.Delay) { context.Log.Information("Waiting..."); await Task.Delay(1500); } context.Log.Information("World"); } } [TaskName("Default")] [IsDependentOn(typeof(WorldTask))] public class DefaultTask : FrostingTask { }
mit
C#
d76e188d28657629f7c61b67953c77f52b8ecb17
Update InsertingWAVFile.cs
aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Articles/InsertingWAVFile.cs
Examples/CSharp/Articles/InsertingWAVFile.cs
using System.IO; using Aspose.Cells; using System; using Aspose.Cells.Drawing; namespace Aspose.Cells.Examples.Articles { public class InsertingWAVFile { public static void Main() { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Define a string variable to store the image path. string ImageUrl = dataDir+ "image2.jpg"; //Get the picture into the streams. FileStream fs = File.OpenRead(ImageUrl); //Define a byte array. byte[] imageData = new Byte[fs.Length]; //Obtain the picture into the array of bytes from streams. fs.Read(imageData, 0, imageData.Length); //Close the stream. fs.Close(); //Get an excel file path in a variable. string path = dataDir+ "chord.wav"; //Get the file into the streams. fs = File.OpenRead(path); //Define an array of bytes. byte[] objectData = new Byte[fs.Length]; //Store the file from streams. fs.Read(objectData, 0, objectData.Length); //Close the stream. fs.Close(); int intIndex = 0; //Instantiate a new Workbook. Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0]; //Add Ole Object sheet.OleObjects.Add(14, 3, 200, 220, imageData); workbook.Worksheets[0].OleObjects[intIndex].FileFormatType = FileFormatType.Unknown; workbook.Worksheets[0].OleObjects[intIndex].ObjectData = objectData; workbook.Worksheets[0].OleObjects[intIndex].ObjectSourceFullName = path; //Save the excel file workbook.Save(dataDir+ "testWAV.out.xlsx"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using System; using Aspose.Cells.Drawing; namespace Aspose.Cells.Examples.Articles { public class InsertingWAVFile { public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); //Define a string variable to store the image path. string ImageUrl = dataDir+ "image2.jpg"; //Get the picture into the streams. FileStream fs = File.OpenRead(ImageUrl); //Define a byte array. byte[] imageData = new Byte[fs.Length]; //Obtain the picture into the array of bytes from streams. fs.Read(imageData, 0, imageData.Length); //Close the stream. fs.Close(); //Get an excel file path in a variable. string path = dataDir+ "chord.wav"; //Get the file into the streams. fs = File.OpenRead(path); //Define an array of bytes. byte[] objectData = new Byte[fs.Length]; //Store the file from streams. fs.Read(objectData, 0, objectData.Length); //Close the stream. fs.Close(); int intIndex = 0; //Instantiate a new Workbook. Workbook workbook = new Workbook(); Worksheet sheet = workbook.Worksheets[0]; //Add Ole Object sheet.OleObjects.Add(14, 3, 200, 220, imageData); workbook.Worksheets[0].OleObjects[intIndex].FileFormatType = FileFormatType.Unknown; workbook.Worksheets[0].OleObjects[intIndex].ObjectData = objectData; workbook.Worksheets[0].OleObjects[intIndex].ObjectSourceFullName = path; //Save the excel file workbook.Save(dataDir+ "testWAV.out.xlsx"); } } }
mit
C#
cca59e6b95eed998bbe1e34103a8f3716eec2103
add PackagePromotionContents
lvermeulen/ProGet.Net
src/ProGet.Net/PackagePromotion/Models/PackagePromotionContents.cs
src/ProGet.Net/PackagePromotion/Models/PackagePromotionContents.cs
// ReSharper disable InconsistentNaming namespace ProGet.Net.PackagePromotion.Models { public class PackagePromotionContents { public string packageName { get; set; } public string groupName { get; set; } public string version { get; set; } public string fromFeed { get; set; } public string toFeed { get; set; } public string comments { get; set; } } }
namespace ProGet.Net.PackagePromotion.Models { public class PackagePromotionContents { } }
mit
C#
bae1e37f3a917c61033cacb12f3a02526961bfd6
Add other upgrades to enum
makerslocal/LudumDare38
bees-in-the-trap/Assets/Scripts/Upgrade.cs
bees-in-the-trap/Assets/Scripts/Upgrade.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Upgrade { NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD, BEEBALL, SCHOOLBUZZ, BUZZFEED, BEACH, GUM, VISOR }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum Upgrade { NONE, ROBOT, NIGHTVISION, UNICORN, ZOMBIE, REDHAT, BEEARD }
mit
C#
96915caad9c08dc8c99b733a7e252af8fd95994f
Fix for .net 4.0.
msallin/SQLiteCodeFirst
SQLite.CodeFirst/Extensions/EntityTypeExtension.cs
SQLite.CodeFirst/Extensions/EntityTypeExtension.cs
using System; using System.Data.Entity.Core.Metadata.Edm; using SQLite.CodeFirst.Builder.NameCreators; using SQLite.CodeFirst.Utility; namespace SQLite.CodeFirst.Extensions { internal static class EntityTypeExtension { public static string GetTableName(this EntityType entityType) { MetadataProperty metadataProperty; if (!entityType.MetadataProperties.TryGetValue("TableName", false, out metadataProperty)) { return entityType.Name; } if (metadataProperty.Value.GetType().Name != "DatabaseName") { return entityType.Name; } object metadataPropertyValue = metadataProperty.Value; Type metadataPropertyValueType = metadataProperty.Value.GetType(); // The type DatabaseName is internal. So we need reflection... // GetValue() overload with one value was introduces in .net 4.5 so use the overload with two parameters. var name = (string)metadataPropertyValueType.GetProperty("Name").GetValue(metadataPropertyValue, null); return TableNameCreator.CreateTableName(name); } } }
using System; using System.Data.Entity.Core.Metadata.Edm; using SQLite.CodeFirst.Builder.NameCreators; using SQLite.CodeFirst.Utility; namespace SQLite.CodeFirst.Extensions { internal static class EntityTypeExtension { public static string GetTableName(this EntityType entityType) { MetadataProperty metadataProperty; if (!entityType.MetadataProperties.TryGetValue("TableName", false, out metadataProperty)) { return entityType.Name; } if (metadataProperty.Value.GetType().Name != "DatabaseName") { return entityType.Name; } object metadataPropertyValue = metadataProperty.Value; Type metadataPropertyValueType = metadataProperty.Value.GetType(); // The type DatabaseName is internal. So we need reflection... var name = (string)metadataPropertyValueType.GetProperty("Name").GetValue(metadataPropertyValue); return TableNameCreator.CreateTableName(name); } } }
apache-2.0
C#
f42a880b3dbafbc79d6a1b2ded19c908a02ee005
Fix PrimitiveDrawable not using color alpha
prime31/Nez,ericmbernier/Nez,Blucky87/Nez,prime31/Nez,prime31/Nez
Nez.Portable/UI/Drawable/PrimitiveDrawable.cs
Nez.Portable/UI/Drawable/PrimitiveDrawable.cs
using System; using Microsoft.Xna.Framework; namespace Nez.UI { public class PrimitiveDrawable : IDrawable { #region IDrawable implementation public float leftWidth { get; set; } public float rightWidth { get; set; } public float topHeight { get; set; } public float bottomHeight { get; set; } public float minWidth { get; set; } public float minHeight { get; set; } public void setPadding( float top, float bottom, float left, float right ) { topHeight = top; bottomHeight = bottom; leftWidth = left; rightWidth = right; } #endregion public Color? color; public bool useFilledRect = true; public PrimitiveDrawable( Color? color = null ) { this.color = color; } public PrimitiveDrawable( Color color, float horizontalPadding ) : this( color ) { leftWidth = rightWidth = horizontalPadding; } public PrimitiveDrawable( Color color, float horizontalPadding, float verticalPadding ) : this( color ) { leftWidth = rightWidth = horizontalPadding; topHeight = bottomHeight = verticalPadding; } public PrimitiveDrawable( float minWidth, float minHeight, Color? color = null ) : this( color ) { this.minWidth = minWidth; this.minHeight = minHeight; } public PrimitiveDrawable( float minSize ) : this( minSize, minSize ) {} public PrimitiveDrawable( float minSize, Color color ) : this( minSize, minSize, color ) {} public virtual void draw( Graphics graphics, float x, float y, float width, float height, Color color ) { var col = this.color.HasValue ? this.color.Value : color; if( color.A != 255 ) col *= ( color.A / 255f ); if (col.A != 255) col *= ( col.A / 255f ); if( useFilledRect ) graphics.batcher.drawRect( x, y, width, height, col ); else graphics.batcher.drawHollowRect( x, y, width, height, col ); } } }
using System; using Microsoft.Xna.Framework; namespace Nez.UI { public class PrimitiveDrawable : IDrawable { #region IDrawable implementation public float leftWidth { get; set; } public float rightWidth { get; set; } public float topHeight { get; set; } public float bottomHeight { get; set; } public float minWidth { get; set; } public float minHeight { get; set; } public void setPadding( float top, float bottom, float left, float right ) { topHeight = top; bottomHeight = bottom; leftWidth = left; rightWidth = right; } #endregion public Color? color; public bool useFilledRect = true; public PrimitiveDrawable( Color? color = null ) { this.color = color; } public PrimitiveDrawable( Color color, float horizontalPadding ) : this( color ) { leftWidth = rightWidth = horizontalPadding; } public PrimitiveDrawable( Color color, float horizontalPadding, float verticalPadding ) : this( color ) { leftWidth = rightWidth = horizontalPadding; topHeight = bottomHeight = verticalPadding; } public PrimitiveDrawable( float minWidth, float minHeight, Color? color = null ) : this( color ) { this.minWidth = minWidth; this.minHeight = minHeight; } public PrimitiveDrawable( float minSize ) : this( minSize, minSize ) {} public PrimitiveDrawable( float minSize, Color color ) : this( minSize, minSize, color ) {} public virtual void draw( Graphics graphics, float x, float y, float width, float height, Color color ) { var col = this.color.HasValue ? this.color.Value : color; if( color.A != 255 ) col *= ( color.A / 255f ); if( useFilledRect ) graphics.batcher.drawRect( x, y, width, height, col ); else graphics.batcher.drawHollowRect( x, y, width, height, col ); } } }
mit
C#
7616c7a6ab30877993a00bbaa53ac185d67a7aa8
Fix to also check the Required property of the JsonProperty when determining if a model property is required or optional.
domaindrivendev/Swashbuckle,domaindrivendev/Swashbuckle,domaindrivendev/Swashbuckle
Swashbuckle.Core/Swagger/JsonPropertyExtensions.cs
Swashbuckle.Core/Swagger/JsonPropertyExtensions.cs
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Swashbuckle.Swagger { public static class JsonPropertyExtensions { public static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<RequiredAttribute>() || jsonProperty.Required == Required.Always; } public static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } public static bool HasAttribute<T>(this JsonProperty jsonProperty) { var propInfo = jsonProperty.PropertyInfo(); return propInfo != null && Attribute.IsDefined(propInfo, typeof (T)); } public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty) { if(jsonProperty.UnderlyingName == null) return null; return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType); } } }
using System; using System.ComponentModel.DataAnnotations; using System.Reflection; using Newtonsoft.Json.Serialization; namespace Swashbuckle.Swagger { public static class JsonPropertyExtensions { public static bool IsRequired(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<RequiredAttribute>(); } public static bool IsObsolete(this JsonProperty jsonProperty) { return jsonProperty.HasAttribute<ObsoleteAttribute>(); } public static bool HasAttribute<T>(this JsonProperty jsonProperty) { var propInfo = jsonProperty.PropertyInfo(); return propInfo != null && Attribute.IsDefined(propInfo, typeof (T)); } public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty) { if(jsonProperty.UnderlyingName == null) return null; return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType); } } }
bsd-3-clause
C#
ab598eafe1d92e5564b31432e45b86843bdf80ae
Set private.config to optional to fix unit tests on build server
CrustyJew/RedditSharp
RedditSharpTests/AuthenticatedTestsFixture.cs
RedditSharpTests/AuthenticatedTestsFixture.cs
using Microsoft.Extensions.Configuration; using Xunit; namespace RedditSharpTests { public class AuthenticatedTestsFixture { public IConfigurationRoot Config { get; private set; } public string AccessToken { get; private set; } public RedditSharp.BotWebAgent WebAgent { get; set; } public string TestUserName { get; private set; } public AuthenticatedTestsFixture() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("private.config",true) .AddEnvironmentVariables(); Config = builder.Build(); WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]); AccessToken = WebAgent.AccessToken; TestUserName = Config["TestUserName"]; } } [CollectionDefinition("AuthenticatedTests")] public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } }
using Microsoft.Extensions.Configuration; using Xunit; namespace RedditSharpTests { public class AuthenticatedTestsFixture { public IConfigurationRoot Config { get; private set; } public string AccessToken { get; private set; } public RedditSharp.BotWebAgent WebAgent { get; set; } public string TestUserName { get; private set; } public AuthenticatedTestsFixture() { ConfigurationBuilder builder = new ConfigurationBuilder(); builder.AddJsonFile("private.config") .AddEnvironmentVariables(); Config = builder.Build(); WebAgent = new RedditSharp.BotWebAgent(Config["TestUserName"], Config["TestUserPassword"], Config["RedditClientID"], Config["RedditClientSecret"], Config["RedditRedirectURI"]); AccessToken = WebAgent.AccessToken; TestUserName = Config["TestUserName"]; } } [CollectionDefinition("AuthenticatedTests")] public class AuthenticatedTestsCollection : ICollectionFixture<AuthenticatedTestsFixture> { // This class has no code, and is never created. Its purpose is simply // to be the place to apply [CollectionDefinition] and all the // ICollectionFixture<> interfaces. } }
mit
C#
437f512831e83a51422a2072f7788b46a1fe6697
fix bug with serializer
OpenTl/OpenTl.Schema
src/OpenTl.Schema/Serialization/Serializer.cs
src/OpenTl.Schema/Serialization/Serializer.cs
namespace OpenTl.Schema.Serialization { using System; using System.Reflection; using DotNetty.Buffers; public static class Serializer { public static IObject Deserialize(IByteBuffer buffer) { return (IObject)Deserialize(buffer, typeof(IObject).GetTypeInfo()); } public static object Deserialize(IByteBuffer buffer, Type expectedType) { return Deserialize(buffer, new SerializationMetadata{PropertyTypeInfo = expectedType.GetTypeInfo()}); } public static IByteBuffer Serialize(object obj) { var buffer = PooledByteBufferAllocator.Default.Buffer(); Serialize(obj, buffer); return buffer; } // ReSharper disable once MethodOverloadWithOptionalParameter internal static object Deserialize(IByteBuffer buffer, SerializationMetadata metadata) { if (metadata != null) { var ser = SerializationMap.GetSerializator(metadata.PropertyTypeInfo); return ser.Deserialize(buffer, metadata); } return Deserialize(buffer, typeof(IObject).GetTypeInfo()); } internal static object Deserialize(IByteBuffer buffer, TypeInfo typeInfo) { var ser = SerializationMap.GetSerializator(typeInfo); return ser.Deserialize(buffer, null); } internal static void Serialize(object obj, IByteBuffer buffer, SerializationMetadata metadata = null) { var ser = SerializationMap.GetSerializator(obj.GetType().GetTypeInfo()); ser.Serialize(obj, buffer, metadata); } } }
namespace OpenTl.Schema.Serialization { using System; using System.Reflection; using DotNetty.Buffers; public static class Serializer { public static IObject Deserialize(IByteBuffer buffer) { return (IObject)Deserialize(buffer, typeof(IObject).GetTypeInfo()); } public static IObject Deserialize(IByteBuffer buffer, Type expectedType) { return (IObject)Deserialize(buffer, new SerializationMetadata{PropertyTypeInfo = expectedType.GetTypeInfo()}); } public static IByteBuffer Serialize(object obj) { var buffer = PooledByteBufferAllocator.Default.Buffer(); Serialize(obj, buffer); return buffer; } // ReSharper disable once MethodOverloadWithOptionalParameter internal static object Deserialize(IByteBuffer buffer, SerializationMetadata metadata) { if (metadata != null) { var ser = SerializationMap.GetSerializator(metadata.PropertyTypeInfo); return ser.Deserialize(buffer, metadata); } return Deserialize(buffer, typeof(IObject).GetTypeInfo()); } internal static object Deserialize(IByteBuffer buffer, TypeInfo typeInfo) { var ser = SerializationMap.GetSerializator(typeInfo); return ser.Deserialize(buffer, null); } internal static void Serialize(object obj, IByteBuffer buffer, SerializationMetadata metadata = null) { var ser = SerializationMap.GetSerializator(obj.GetType().GetTypeInfo()); ser.Serialize(obj, buffer, metadata); } } }
mit
C#
3b1fd660928db28de677b08ed168613b98aee6f4
Reduce packet size, remove bloated time codes
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/GameApi/Messages/ServerTimeMessage.cs
Scripts/GameApi/Messages/ServerTimeMessage.cs
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct ServerTimeMessage : INetSerializable { public int serverUnixTime; public void Deserialize(NetDataReader reader) { serverUnixTime = reader.GetPackedInt(); } public void Serialize(NetDataWriter writer) { writer.PutPackedInt(serverUnixTime); } } }
using System.Collections; using System.Collections.Generic; using LiteNetLib.Utils; namespace LiteNetLibManager { public struct ServerTimeMessage : INetSerializable { public int serverUnixTime; public float serverTime; public void Deserialize(NetDataReader reader) { serverUnixTime = reader.GetInt(); serverTime = reader.GetFloat(); } public void Serialize(NetDataWriter writer) { writer.Put(serverUnixTime); writer.Put(serverTime); } } }
mit
C#
1e09caa0c7a3199afcadb0a3cf2a0f4b16db4bb8
Update version
davghouse/Daves.WordamentPractice
WordamentPractice/Properties/AssemblyInfo.cs
WordamentPractice/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("WordamentPractice")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WordamentPractice")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("2.1.2.0")] [assembly: AssemblyFileVersion("2.1.2.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: AssemblyTitle("WordamentPractice")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WordamentPractice")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
mit
C#
26704e80bdb306925e49baec63037224adc693ef
Remove ToArray
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Crypto/ZeroKnowledge/Verifier.cs
WalletWasabi/Crypto/ZeroKnowledge/Verifier.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge { public static class Verifier { public static bool Verify(KnowledgeOfExponent proof, GroupElement publicPoint, GroupElement generator) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); Guard.False($"{nameof(publicPoint)}.{nameof(publicPoint.IsInfinity)}", publicPoint.IsInfinity); if (publicPoint == proof.Nonce) { throw new InvalidOperationException($"{nameof(publicPoint)} and {nameof(proof.Nonce)} should not be equal."); } var knowledge = new KnowledgeOfRepresentation(proof.Nonce, new[] { proof.Response }); return Verify(knowledge, publicPoint, new[] { generator }); } public static bool Verify(KnowledgeOfRepresentation proof, GroupElement publicPoint, IEnumerable<GroupElement> generators) { foreach (var generator in generators) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); } var nonce = proof.Nonce; var responses = proof.Responses; var challenge = Challenge.HashToScalar(new[] { publicPoint, nonce }.Concat(generators)); var a = challenge * publicPoint + nonce; var b = GroupElement.Infinity; foreach (var (response, generator) in responses.TupleWith(generators)) { b += response * generator; } return a == b; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using WalletWasabi.Crypto.Groups; using WalletWasabi.Helpers; namespace WalletWasabi.Crypto.ZeroKnowledge { public static class Verifier { public static bool Verify(KnowledgeOfExponent proof, GroupElement publicPoint, GroupElement generator) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); Guard.False($"{nameof(publicPoint)}.{nameof(publicPoint.IsInfinity)}", publicPoint.IsInfinity); if (publicPoint == proof.Nonce) { throw new InvalidOperationException($"{nameof(publicPoint)} and {nameof(proof.Nonce)} should not be equal."); } var knowledge = new KnowledgeOfRepresentation(proof.Nonce, new[] { proof.Response }); return Verify(knowledge, publicPoint, new[] { generator }); } public static bool Verify(KnowledgeOfRepresentation proof, GroupElement publicPoint, IEnumerable<GroupElement> generators) { foreach (var generator in generators) { Guard.False($"{nameof(generator)}.{nameof(generator.IsInfinity)}", generator.IsInfinity); } var nonce = proof.Nonce; var responses = proof.Responses.ToArray(); var challenge = Challenge.HashToScalar(new[] { publicPoint, nonce }.Concat(generators)); var a = challenge * publicPoint + nonce; var b = GroupElement.Infinity; foreach (var (response, generator) in responses.TupleWith(generators)) { b += response * generator; } return a == b; } } }
mit
C#
ba02c6944b78a513112806561db451a5074a2864
Change class to be public and clean up some comments.
ronnymgm/csla-light,jonnybee/csla,rockfordlhotka/csla,MarimerLLC/csla,rockfordlhotka/csla,BrettJaner/csla,JasonBock/csla,BrettJaner/csla,rockfordlhotka/csla,ronnymgm/csla-light,MarimerLLC/csla,JasonBock/csla,BrettJaner/csla,jonnybee/csla,JasonBock/csla,MarimerLLC/csla,jonnybee/csla,ronnymgm/csla-light
cslacs/Csla/Reflection/LateBoundObject.cs
cslacs/Csla/Reflection/LateBoundObject.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Csla.Reflection { /// <summary> /// Enables simple invocation of methods /// against the contained object using /// late binding. /// </summary> public class LateBoundObject { /// <summary> /// Object instance managed by LateBoundObject. /// </summary> public object Instance { get; private set; } /// <summary> /// Creates an instance of the specified /// type and contains it within a new /// LateBoundObject. /// </summary> /// <param name="objectType"> /// Type of object to create. /// </param> /// <remarks> /// The specified type must implement a /// default constructor. /// </remarks> public LateBoundObject(Type objectType) : this(MethodCaller.CreateInstance(objectType)) { } /// <summary> /// Contains the provided object within /// a new LateBoundObject. /// </summary> /// <param name="instance"> /// Object to contain. /// </param> public LateBoundObject(object instance) { this.Instance = instance; } /// <summary> /// Uses reflection to dynamically invoke a method /// if that method is implemented on the target object. /// </summary> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public object CallMethodIfImplemented(string method, params object[] parameters) { return MethodCaller.CallMethodIfImplemented(this.Instance, method, parameters); } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="method"> /// Name of the method. /// </param> public object CallMethod(string method) { return MethodCaller.CallMethod(this.Instance, method); } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public object CallMethod(string method, params object[] parameters) { return MethodCaller.CallMethod(this.Instance, method, parameters); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Csla.Reflection { internal class LateBoundObject { /// <summary> /// Object instance managed by LateBoundObject. /// </summary> public object Instance { get; private set; } /// <summary> /// Creates an instance of the specified /// type and contains it within a new /// LateBoundObject. /// </summary> /// <param name="objectType"> /// Type of object to create. /// </param> public LateBoundObject(Type objectType) : this(MethodCaller.CreateInstance(objectType)) { } /// <summary> /// Contains the provided object within /// a new LateBoundObject. /// </summary> /// <param name="instance"> /// Object to contain. /// </param> public LateBoundObject(object instance) { this.Instance = instance; } /// <summary> /// Uses reflection to dynamically invoke a method /// if that method is implemented on the target object. /// </summary> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public object CallMethodIfImplemented(string method, params object[] parameters) { return MethodCaller.CallMethodIfImplemented(this.Instance, method, parameters); } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="method"> /// Name of the method. /// </param> public object CallMethod(string method) { return MethodCaller.CallMethod(this.Instance, method); } /// <summary> /// Uses reflection to dynamically invoke a method, /// throwing an exception if it is not /// implemented on the target object. /// </summary> /// <param name="method"> /// Name of the method. /// </param> /// <param name="parameters"> /// Parameters to pass to method. /// </param> public object CallMethod(string method, params object[] parameters) { return MethodCaller.CallMethod(this.Instance, method, parameters); } } }
mit
C#
1bcab402f15718ed6bb67ad568158d9fd52a2ac1
set version of MahApps.Metro.IconPacks.Browser to 1.0.1
MahApps/MahApps.Metro.IconPacks
src/MahApps.Metro.IconPacks.Browser/Properties/AssemblyInfo.cs
src/MahApps.Metro.IconPacks.Browser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("1.0.1.0")] [assembly: AssemblyFileVersion("1.0.1.0")] [assembly: AssemblyInformationalVersion("1.0.1.0")] [assembly: AssemblyProduct("MahApps.Metro.IconPacks.Browser 1.0.1")] [assembly: AssemblyTitle("MahApps.Metro.IconPacks.Browser")] [assembly: AssemblyDescription("Application for the awesome IconPacks.")] [assembly: AssemblyCopyright("Copyright © MahApps.Metro 2016")] [assembly: AssemblyCompany("MahApps")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; [assembly: ComVisible(false)] [assembly: ThemeInfo(ResourceDictionaryLocation.None, ResourceDictionaryLocation.SourceAssembly)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")] [assembly: AssemblyProduct("MahApps.Metro.IconPacks.Browser 1.0.0")] [assembly: AssemblyTitle("MahApps.Metro.IconPacks.Browser")] [assembly: AssemblyDescription("Application for the awesome IconPacks.")] [assembly: AssemblyCopyright("Copyright © MahApps.Metro 2016")] [assembly: AssemblyCompany("MahApps")]
mit
C#
9b47248a7dc980dfc18a50980f89e708e46129f2
test 2
Yaxuan/BookApp,Yaxuan/BookApp
BookApp/DataAccess/Repository/DataContext.cs
BookApp/DataAccess/Repository/DataContext.cs
using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace BookApp.DataAccess.Repository { public class DataContext : DbContext { public DataContext() : base("name=DataContext") { this.Configuration.LazyLoadingEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } //test 2 public virtual DbSet<Book> Books { get; set; } } }
using System.Data.Entity; using System.Data.Entity.Infrastructure; namespace BookApp.DataAccess.Repository { public class DataContext : DbContext { public DataContext() : base("name=DataContext") { this.Configuration.LazyLoadingEnabled = false; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { throw new UnintentionalCodeFirstException(); } //test public virtual DbSet<Book> Books { get; set; } } }
mit
C#
70ea655bd8ca80934205f9ccced8657a7d31a59d
edit :)
webdude21/Caipirinha
KnightsOfCSharpia/KnightsOfCSharpia/Creatures/Warrior.cs
KnightsOfCSharpia/KnightsOfCSharpia/Creatures/Warrior.cs
using System; using System.Linq; using KnightsOfCSharpia.Common; namespace KnightsOfCSharpia { public class Warrior : Hero { private const uint Strength = 15; private const uint Dexterity = 6; private const uint Intelligence = 2; private const uint Endurance = 12; public Warrior(string name) : base(name, Strength, Dexterity, Intelligence, Endurance) { } public override AttackLog Attack(Hero target) { if (target.IsAlive) { var currentAbility = this.Abilities["basic attack"]; this.CurrentMana -= currentAbility.ManaCost; var attackResult = currentAbility.Effect(this.GetAttackPoints()); string result = target.Defend(attackResult); return new AttackLog(true, String.Format("{0} uses {1} on {2}", this.Name, currentAbility.Name, result)); } else { return AttackLog.AttackFailed; } } public override string Defend(Spells.SpellDamage attackSpell) { throw new NotImplementedException(); } public void SpecialAttack() { throw new System.NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KnightsOfCSharpia.Common; namespace KnightsOfCSharpia { public class Warrior : Hero { private const uint Strength = 15; private const uint Dexterity = 6; private const uint Intelligence = 2; private const uint Endurance = 12; public Warrior(string name) : base(name, Strength, Dexterity, Intelligence, Endurance) { } public override AttackLog Attack(Hero target) { if (target.IsAlive) { var currentAbility = this.Abilities["basic attack"]; this.CurrentMana -= currentAbility.ManaCost; var attackResult = currentAbility.Effect(this.GetAttackPoints()); string result = target.Defend(attackResult); return new AttackLog(true, String.Format("{0} uses {1} on {2}", this.Name, currentAbility.Name, result)); } else { return AttackLog.AttackFailed; } } public override string Defend(Spells.SpellDamage attackSpell) { throw new NotImplementedException(); } public void SpecialAttack() { throw new System.NotImplementedException(); } } }
unlicense
C#
d13fa31e8cc6ae604457dddc23dd8c4edfc7606d
Add missing license header
naoey/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,naoey/osu-framework,paparony03/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,default0/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,ppy/osu-framework,default0/osu-framework,Tom94/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,EVAST9919/osu-framework
osu.Framework/Input/CustomInputManager.cs
osu.Framework/Input/CustomInputManager.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections.Generic; using osu.Framework.Input.Handlers; namespace osu.Framework.Input { /// <summary> /// An <see cref="InputManager"/> implementation which allows managing of <see cref="InputHandler"/>s manually. /// </summary> public class CustomInputManager : InputManager { protected override IEnumerable<InputHandler> InputHandlers => inputHandlers; private readonly List<InputHandler> inputHandlers = new List<InputHandler>(); protected void AddHandler(InputHandler handler) { if (!handler.Initialize(Host)) return; int index = inputHandlers.BinarySearch(handler, new InputHandlerComparer()); if (index < 0) { index = ~index; } inputHandlers.Insert(index, handler); } protected void RemoveHandler(InputHandler handler) => inputHandlers.Remove(handler); protected override void Dispose(bool isDisposing) { foreach (var h in inputHandlers) h.Dispose(); base.Dispose(isDisposing); } } }
using System.Collections.Generic; using osu.Framework.Input.Handlers; namespace osu.Framework.Input { /// <summary> /// An <see cref="InputManager"/> implementation which allows managing of <see cref="InputHandler"/>s manually. /// </summary> public class CustomInputManager : InputManager { protected override IEnumerable<InputHandler> InputHandlers => inputHandlers; private readonly List<InputHandler> inputHandlers = new List<InputHandler>(); protected void AddHandler(InputHandler handler) { if (!handler.Initialize(Host)) return; int index = inputHandlers.BinarySearch(handler, new InputHandlerComparer()); if (index < 0) { index = ~index; } inputHandlers.Insert(index, handler); } protected void RemoveHandler(InputHandler handler) => inputHandlers.Remove(handler); protected override void Dispose(bool isDisposing) { foreach (var h in inputHandlers) h.Dispose(); base.Dispose(isDisposing); } } }
mit
C#
207ae2293f2cfaeac866dea84860889c58f5b667
Update ImageIO.cs
matt77hias/cs-smallpt
cs-smallpt/core/ImageIO.cs
cs-smallpt/core/ImageIO.cs
using System.IO; namespace cs_smallpt { public static class ImageIO { public static void WritePPM(int w, int h, Vector3[] Ls, string fname = "cs-image.ppm") { using (StreamWriter sw = new StreamWriter(fname)) { string sbegin = string.Format("P3\n{0} {1}\n{2}\n", w, h, 255); sw.Write(sbegin); for (int i = 0; i < w * h; ++i) { string s = string.Format("{0} {1} {2} ", MathUtils.ToByte(Ls[i][0]), MathUtils.ToByte(Ls[i][1]), MathUtils.ToByte(Ls[i][2])); sw.Write(s); } } } } }
using System.IO; namespace cs_smallpt { public class ImageIO { public static void WritePPM(int w, int h, Vector3[] Ls, string fname = "cs-image.ppm") { using (StreamWriter sw = new StreamWriter(fname)) { string sbegin = string.Format("P3\n{0} {1}\n{2}\n", w, h, 255); sw.Write(sbegin); for (int i = 0; i < w * h; ++i) { string s = string.Format("{0} {1} {2} ", MathUtils.ToByte(Ls[i][0]), MathUtils.ToByte(Ls[i][1]), MathUtils.ToByte(Ls[i][2])); sw.Write(s); } } } } }
mit
C#
3f349052e88a730eae4cffe247754a931ae46fc8
bump version
alecgorge/adzerk-dot-net
Adzerk.Api/Properties/AssemblyInfo.cs
Adzerk.Api/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Adzerk.Api")] [assembly: AssemblyDescription("Unofficial Adzerk API client.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Exchange")] [assembly: AssemblyProduct("Adzerk.Api")] [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("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")] // 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.0.5")] [assembly: AssemblyFileVersion("0.0.0.5")]
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("Adzerk.Api")] [assembly: AssemblyDescription("Unofficial Adzerk API client.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Stack Exchange")] [assembly: AssemblyProduct("Adzerk.Api")] [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("d05e1e25-d95d-43d6-a74b-3cb38492fa7e")] // 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.0.4")] [assembly: AssemblyFileVersion("0.0.0.4")]
mit
C#
ebe313977b80455160f24d7c93e941b9be9501a8
bump version for 1.3.0 release
bbarnhill/barcodelib,barnhill/barcodelib,barnhill/barcodelib
BarcodeLib/Properties/AssemblyInfo.cs
BarcodeLib/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Security; [assembly: AllowPartiallyTrustedCallers] // 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("BarcodeLib")] [assembly: AssemblyDescription("Barcode Image Generation Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Barnhill Software")] [assembly: AssemblyProduct("BarcodeLib")] [assembly: AssemblyCopyright("Copyright © Brad Barnhill 2007-present")] [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("6b4a01ba-c67e-443d-813f-24c0c0f39a02")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.3.0.0")] [assembly: AssemblyFileVersion("1.3.0.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Security; [assembly: AllowPartiallyTrustedCallers] // 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("BarcodeLib")] [assembly: AssemblyDescription("Barcode Image Generation Library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Barnhill Software")] [assembly: AssemblyProduct("BarcodeLib")] [assembly: AssemblyCopyright("Copyright © Brad Barnhill 2007-present")] [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("6b4a01ba-c67e-443d-813f-24c0c0f39a02")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
apache-2.0
C#
e690bf4b9cf0bd826020a70fff94ffbf9786ad2b
Add a few extra items to the options
csf-dev/ZPT-Sharp,csf-dev/ZPT-Sharp
CSF.Zpt/Rendering/RenderingOptions.cs
CSF.Zpt/Rendering/RenderingOptions.cs
using System; using CSF.Zpt.Tales; namespace CSF.Zpt.Rendering { /// <summary> /// Encapsulates the available options for rendering a <see cref="ZptDocument"/>. /// </summary> public class RenderingOptions { #region fields private static RenderingOptions _defaultOptions; #endregion #region properties /// <summary> /// Gets or sets a value indicating whether source file annotations should be added to the rendered output. /// </summary> /// <value><c>true</c> if source file annotations are to be added; otherwise, <c>false</c>.</value> public bool AddSourceFileAnnotation { get; private set; } /// <summary> /// Gets the TALES evaluator registry implementation. /// </summary> /// <value>The TALES evaluator registry.</value> public IEvaluatorRegistry TalesEvaluatorRegistry { get; private set; } /// <summary> /// Gets the element visitors to be used when processing ZPT documents. /// </summary> /// <value>The element visitors.</value> public ElementVisitor[] ElementVisitors { get; private set; } /// <summary> /// Gets the keyword options passed to the template mechanism, typically via the command-line. /// </summary> /// <value>The keyword options.</value> public TemplateKeywordOptions KeywordOptions { get; private set; } #endregion #region constructor /// <summary> /// Initializes a new instance of the <see cref="CSF.Zpt.Rendering.RenderingOptions"/> class. /// </summary> /// <param name="addSourceFileAnnotation">Indicates whether or not source file annotation is to be added.</param> public RenderingOptions(bool addSourceFileAnnotation = false, IEvaluatorRegistry talesEvaluatorRegistry = null, ElementVisitor[] elementVisitors = null, TemplateKeywordOptions keywordOptions = null) { this.AddSourceFileAnnotation = addSourceFileAnnotation; this.TalesEvaluatorRegistry = talesEvaluatorRegistry?? SimpleEvaluatorRegistry.Default; this.ElementVisitors = elementVisitors?? new ElementVisitor[] { new CSF.Zpt.Metal.MetalVisitor(), new CSF.Zpt.Metal.SourceAnnotationVisitor(), new CSF.Zpt.Tal.TalVisitor(), }; this.KeywordOptions = keywordOptions?? new TemplateKeywordOptions(); } /// <summary> /// Initializes the <see cref="CSF.Zpt.Rendering.RenderingOptions"/> class. /// </summary> static RenderingOptions() { _defaultOptions = new RenderingOptions(); } #endregion #region static properties /// <summary> /// Gets a set of <see cref="RenderingOptions"/> representing the defaults. /// </summary> /// <value>The default rendering options.</value> public static RenderingOptions Default { get { return _defaultOptions; } } #endregion } }
using System; namespace CSF.Zpt.Rendering { /// <summary> /// Encapsulates the available options for rendering a <see cref="ZptDocument"/>. /// </summary> public class RenderingOptions { #region fields private static RenderingOptions _defaultOptions; #endregion #region properties /// <summary> /// Gets or sets a value indicating whether source file annotations should be added to the rendered output. /// </summary> /// <value><c>true</c> if source file annotations are to be added; otherwise, <c>false</c>.</value> public bool AddSourceFileAnnotation { get; private set; } #endregion #region constructor /// <summary> /// Initializes a new instance of the <see cref="CSF.Zpt.Rendering.RenderingOptions"/> class. /// </summary> /// <param name="addSourceFileAnnotation">Indicates whether or not source file annotation is to be added.</param> public RenderingOptions(bool addSourceFileAnnotation) { this.AddSourceFileAnnotation = addSourceFileAnnotation; } /// <summary> /// Initializes the <see cref="CSF.Zpt.Rendering.RenderingOptions"/> class. /// </summary> static RenderingOptions() { _defaultOptions = new RenderingOptions(addSourceFileAnnotation: false); } #endregion #region static properties /// <summary> /// Gets a set of <see cref="RenderingOptions"/> representing the defaults. /// </summary> /// <value>The default rendering options.</value> public static RenderingOptions Default { get { return _defaultOptions; } } #endregion } }
mit
C#
d005bc3ef534a6228818227b3f425364082a3b81
Update rate limiter test
sonvister/Binance
test/Binance.Tests/Api/RateLimiterTest.cs
test/Binance.Tests/Api/RateLimiterTest.cs
using Binance.Api; using System; using System.Diagnostics; using System.Threading.Tasks; using Xunit; namespace Binance.Tests.Api { public class RateLimiterTest { [Fact] public void ConfigureThrows() { var rateLimiter = new RateLimiter(); Assert.Throws<ArgumentException>("count", () => rateLimiter.Configure(-1, TimeSpan.FromSeconds(1))); Assert.Throws<ArgumentException>("count", () => rateLimiter.Configure(0, TimeSpan.FromSeconds(1))); } [Fact] public void Configure() { const int count = 3; var duration = TimeSpan.FromSeconds(3); var enabled = !RateLimiter.EnabledDefault; var rateLimiter = new RateLimiter { IsEnabled = enabled }; rateLimiter.Configure(count, duration); Assert.Equal(count, rateLimiter.Count); Assert.Equal(duration, rateLimiter.Duration); Assert.Equal(enabled, rateLimiter.IsEnabled); } [Fact] public async Task RateLimit() { const int count = 3; const int intervals = 2; var rateLimiter = new RateLimiter { IsEnabled = true }; rateLimiter.Configure(count, TimeSpan.FromSeconds(1)); var stopwatch = Stopwatch.StartNew(); for (var i = 0; i < count * intervals + 1; i++) await rateLimiter.DelayAsync(); stopwatch.Stop(); // Assume elapsed milliseconds is within +/- 30 milliseconds of expected time (15 msec time resolution). // NOTE: Accounts for the error in the timestamp, ignoring Delay() and Stopwatch errors, and processing time. Assert.True(stopwatch.ElapsedMilliseconds > rateLimiter.Duration.TotalMilliseconds * intervals - 30); Assert.False(stopwatch.ElapsedMilliseconds > rateLimiter.Duration.TotalMilliseconds * intervals + 30); } } }
using Binance.Api; using System; using System.Diagnostics; using System.Threading.Tasks; using Xunit; namespace Binance.Tests.Api { public class RateLimiterTest { [Fact] public void ConfigureThrows() { var rateLimiter = new RateLimiter(); Assert.Throws<ArgumentException>("count", () => rateLimiter.Configure(-1, TimeSpan.FromSeconds(1))); Assert.Throws<ArgumentException>("count", () => rateLimiter.Configure(0, TimeSpan.FromSeconds(1))); } [Fact] public void Configure() { const int count = 3; var duration = TimeSpan.FromSeconds(3); var enabled = !RateLimiter.EnabledDefault; var rateLimiter = new RateLimiter { IsEnabled = enabled }; rateLimiter.Configure(count, duration); Assert.Equal(count, rateLimiter.Count); Assert.Equal(duration, rateLimiter.Duration); Assert.Equal(enabled, rateLimiter.IsEnabled); } [Fact] public async Task RateLimit() { const int count = 3; const int intervals = 2; var rateLimiter = new RateLimiter { IsEnabled = true }; rateLimiter.Configure(count, TimeSpan.FromSeconds(1)); var stopwatch = Stopwatch.StartNew(); for (var i = 0; i < count * intervals + 1; i++) await rateLimiter.DelayAsync(); stopwatch.Stop(); Assert.True(stopwatch.ElapsedMilliseconds > rateLimiter.Duration.TotalMilliseconds * (intervals - 0.1)); Assert.False(stopwatch.ElapsedMilliseconds > rateLimiter.Duration.TotalMilliseconds * (intervals + 0.1)); } } }
mit
C#
89281d44989133a2b36bc2c5457d138a41036bfe
test protobuf used
ejona86/grpc,vjpai/grpc,stanley-cheung/grpc,ejona86/grpc,donnadionne/grpc,jtattermusch/grpc,muxi/grpc,jtattermusch/grpc,muxi/grpc,ejona86/grpc,jtattermusch/grpc,nicolasnoble/grpc,firebase/grpc,jboeuf/grpc,firebase/grpc,vjpai/grpc,grpc/grpc,nicolasnoble/grpc,pszemus/grpc,stanley-cheung/grpc,sreecha/grpc,grpc/grpc,grpc/grpc,jboeuf/grpc,grpc/grpc,firebase/grpc,firebase/grpc,sreecha/grpc,ctiller/grpc,stanley-cheung/grpc,muxi/grpc,nicolasnoble/grpc,nicolasnoble/grpc,sreecha/grpc,stanley-cheung/grpc,ejona86/grpc,ejona86/grpc,pszemus/grpc,jboeuf/grpc,firebase/grpc,ctiller/grpc,grpc/grpc,jboeuf/grpc,muxi/grpc,nicolasnoble/grpc,sreecha/grpc,grpc/grpc,sreecha/grpc,grpc/grpc,vjpai/grpc,firebase/grpc,grpc/grpc,ejona86/grpc,pszemus/grpc,stanley-cheung/grpc,donnadionne/grpc,pszemus/grpc,ctiller/grpc,vjpai/grpc,ctiller/grpc,grpc/grpc,vjpai/grpc,muxi/grpc,ejona86/grpc,ctiller/grpc,ctiller/grpc,pszemus/grpc,grpc/grpc,ctiller/grpc,muxi/grpc,nicolasnoble/grpc,jtattermusch/grpc,grpc/grpc,firebase/grpc,vjpai/grpc,muxi/grpc,muxi/grpc,donnadionne/grpc,donnadionne/grpc,muxi/grpc,nicolasnoble/grpc,vjpai/grpc,stanley-cheung/grpc,jtattermusch/grpc,jtattermusch/grpc,sreecha/grpc,jboeuf/grpc,grpc/grpc,stanley-cheung/grpc,donnadionne/grpc,sreecha/grpc,jtattermusch/grpc,jboeuf/grpc,stanley-cheung/grpc,pszemus/grpc,nicolasnoble/grpc,pszemus/grpc,ejona86/grpc,jboeuf/grpc,ctiller/grpc,ejona86/grpc,stanley-cheung/grpc,firebase/grpc,nicolasnoble/grpc,nicolasnoble/grpc,nicolasnoble/grpc,firebase/grpc,sreecha/grpc,ctiller/grpc,jboeuf/grpc,jtattermusch/grpc,vjpai/grpc,vjpai/grpc,ejona86/grpc,jboeuf/grpc,donnadionne/grpc,pszemus/grpc,stanley-cheung/grpc,muxi/grpc,firebase/grpc,donnadionne/grpc,muxi/grpc,nicolasnoble/grpc,sreecha/grpc,ejona86/grpc,ejona86/grpc,donnadionne/grpc,ctiller/grpc,jtattermusch/grpc,pszemus/grpc,muxi/grpc,jboeuf/grpc,jtattermusch/grpc,donnadionne/grpc,firebase/grpc,donnadionne/grpc,jtattermusch/grpc,jtattermusch/grpc,vjpai/grpc,firebase/grpc,pszemus/grpc,pszemus/grpc,vjpai/grpc,sreecha/grpc,stanley-cheung/grpc,sreecha/grpc,ctiller/grpc,jboeuf/grpc,vjpai/grpc,jboeuf/grpc,pszemus/grpc,donnadionne/grpc,stanley-cheung/grpc,sreecha/grpc,ctiller/grpc,donnadionne/grpc
test/distrib/csharp/DistribTest/Program.cs
test/distrib/csharp/DistribTest/Program.cs
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Grpc.Core; namespace TestGrpcPackage { class MainClass { public static void Main(string[] args) { // test codegen works var reply = new Testcodegen.HelloReply(); // This code doesn't do much but makes sure the native extension is loaded // which is what we are testing here. Channel c = new Channel("127.0.0.1:1000", ChannelCredentials.Insecure); c.ShutdownAsync().Wait(); Console.WriteLine("Success!"); } } }
#region Copyright notice and license // Copyright 2015 gRPC authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using Grpc.Core; namespace TestGrpcPackage { class MainClass { public static void Main(string[] args) { // This code doesn't do much but makes sure the native extension is loaded // which is what we are testing here. Channel c = new Channel("127.0.0.1:1000", ChannelCredentials.Insecure); c.ShutdownAsync().Wait(); Console.WriteLine("Success!"); } } }
apache-2.0
C#
a0f703f1334c0b25af0f524f85a61e2ab18afec6
Rename refactor;: GCMonitor.work -> GCMonitor._work
theraot/Theraot
Core/Theraot/Threading/GCMonitor.internal.cs
Core/Theraot/Threading/GCMonitor.internal.cs
// Needed for Workaround using System; using System.Threading; using Theraot.Collections.ThreadSafe; namespace Theraot.Threading { public static partial class GCMonitor { private static class Internal { private static readonly WeakDelegateCollection _collectedEventHandlers; private static readonly WaitCallback _work; static Internal() { _work = _ => RaiseCollected(); _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint); } public static WeakDelegateCollection CollectedEventHandlers { get { return _collectedEventHandlers; } } public static void Invoke() { ThreadPool.QueueUserWorkItem(_work); } private static void RaiseCollected() { var check = Thread.VolatileRead(ref _status); if (check == INT_StatusReady) { try { _collectedEventHandlers.RemoveDeadItems(); _collectedEventHandlers.Invoke(null, new EventArgs()); } catch (Exception exception) { // Pokemon GC.KeepAlive(exception); } Thread.VolatileWrite(ref _status, INT_StatusReady); } } } } }
// Needed for Workaround using System; using System.Threading; using Theraot.Collections.ThreadSafe; namespace Theraot.Threading { public static partial class GCMonitor { private static class Internal { private static readonly WeakDelegateCollection _collectedEventHandlers; private static readonly WaitCallback work; static Internal() { work = _ => RaiseCollected(); _collectedEventHandlers = new WeakDelegateCollection(false, false, INT_MaxProbingHint); } public static WeakDelegateCollection CollectedEventHandlers { get { return _collectedEventHandlers; } } public static void Invoke() { ThreadPool.QueueUserWorkItem(work); } private static void RaiseCollected() { var check = Thread.VolatileRead(ref _status); if (check == INT_StatusReady) { try { _collectedEventHandlers.RemoveDeadItems(); _collectedEventHandlers.Invoke(null, new EventArgs()); } catch (Exception exception) { // Pokemon GC.KeepAlive(exception); } Thread.VolatileWrite(ref _status, INT_StatusReady); } } } } }
mit
C#
4850af7892e354141322950cb05c332f65162c74
Fix issue with node name
michael-reichenauer/Dependinator
Dependinator/ModelViewing/Nodes/NodeName.cs
Dependinator/ModelViewing/Nodes/NodeName.cs
using System; using Dependinator.Utils; namespace Dependinator.ModelViewing.Nodes { internal class NodeName : Equatable<NodeName> { public static NodeName Root = new NodeName(""); private readonly string fullName; private readonly Lazy<string> name; private readonly Lazy<string> shortName; private readonly Lazy<NodeName> parentName; public NodeName(string fullName) { this.fullName = fullName; name = new Lazy<string>(GetName); shortName = new Lazy<string>(GetShortName); parentName = new Lazy<NodeName>(GetParentName); IsEqualWhenSame(fullName); } public string Name => name.Value; public string ShortName => shortName.Value; public NodeName ParentName => parentName.Value; public override string ToString() => this != Root ? fullName : "<root>"; public string AsString() => fullName; private string GetName() { string text = fullName; // Skipping parameters (if method) int index = text.IndexOf('('); if (index > 0) { text = text.Substring(0, index); } // Getting last name part index = text.LastIndexOf('.'); if (index > -1) { text = text.Substring(index + 1); } return text; } private string GetShortName() => string.IsNullOrEmpty(ParentName.Name) ? Name : $"{ParentName.Name}.{Name}"; private NodeName GetParentName() { string text = fullName; // Skipping parameters (if method) int index = text.IndexOf('('); if (index > 0) { text = text.Substring(0, index); } // Getting last name part index = text.LastIndexOf('.'); if (index > -1) { text = text.Substring(0, index); } else { return Root; } return new NodeName(text); } } }
using System; using System.Linq; using Dependinator.Utils; namespace Dependinator.ModelViewing.Nodes { internal class NodeName : Equatable<NodeName> { private static readonly char[] Separator = ".".ToCharArray(); public static NodeName Root = new NodeName(""); private readonly string fullName; private readonly Lazy<string> name; private readonly Lazy<string> shortName; private readonly Lazy<NodeName> parentName; public NodeName(string fullName) { this.fullName = fullName; name = new Lazy<string>(GetName); shortName = new Lazy<string>(GetShortName); parentName = new Lazy<NodeName>(GetParentName); IsEqualWhenSame(fullName); } public string Name => name.Value; public string ShortName => shortName.Value; public NodeName ParentName => parentName.Value; //public static implicit operator string(NodeName nodeName) => nodeName?.fullName; //public static implicit operator NodeName(string fullName) => new NodeName(fullName); public override string ToString() => this != Root ? fullName : "<root>"; public string AsString() => fullName; public int GetLevelCount() => fullName.Count(c => c == '.') + 1; public string GetLevelName(int parts) { return string.Join(".", fullName.Split(Separator).Take(parts)); } private string GetName() { int index = fullName.LastIndexOf('.'); if (index == -1) { // Root is parent return fullName; } return fullName.Substring(index + 1); } private string GetShortName() => string.IsNullOrEmpty(ParentName.Name) ? Name : $"{ParentName.Name}.{Name}"; private NodeName GetParentName() { int index = fullName.LastIndexOf('.'); if (index == -1) { // root namespace return Root; } return new NodeName(fullName.Substring(0, index)); } } }
mit
C#
b938492a8d1b9e01b7cc1a83748c10f102808077
Remove drawing logging.
Azure-Samples/MyDriving,Azure-Samples/MyDriving,Azure-Samples/MyDriving
XamarinApp/MyTrips/MyTrips.iOS/Views/Maps/TripMapView.cs
XamarinApp/MyTrips/MyTrips.iOS/Views/Maps/TripMapView.cs
using System; using Foundation; using UIKit; using MapKit; using CoreLocation; namespace MyTrips.iOS { public partial class TripMapView : MKMapView { public TripMapView(IntPtr handle) : base(handle) { } public void DrawRoute(CLLocationCoordinate2D[] route) { var routeOverlay = MKPolyline.FromCoordinates(route); AddOverlay(routeOverlay); } } }
using System; using Foundation; using UIKit; using MapKit; using CoreLocation; namespace MyTrips.iOS { public partial class TripMapView : MKMapView { public TripMapView(IntPtr handle) : base(handle) { } public void DrawRoute(CLLocationCoordinate2D[] route) { Console.WriteLine(route.Length); foreach (var r in route) Console.WriteLine("{0}, {1}", r.Latitude, r.Longitude); var routeOverlay = MKPolyline.FromCoordinates(route); AddOverlay(routeOverlay); } } }
mit
C#
b32177624a2c26d011316f34d80884b09c2d060c
Handle null parameter.
chtoucas/Narvalo.NET,chtoucas/Narvalo.NET
src/Narvalo.Cerbere/Predicates.cs
src/Narvalo.Cerbere/Predicates.cs
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; public static class Predicates { /// <summary> /// Returns a value indicating whether the specified <paramref name="type"/> is a flags enumeration. /// </summary> /// <param name="type">The type to test.</param> /// <returns><see langword="true"/> if the specified <paramref name="type"/> is a flags enumeration; /// otherwise <see langword="false"/>.</returns> [Pure] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "[Intentionally] The rule does not apply here.")] [SuppressMessage("Gendarme.Rules.Portability", "MonoCompatibilityReviewRule", Justification = "[Intentionally] Method marked as MonoTODO.")] public static bool IsFlagsEnum(Type type) { if (type == null) { return false; } var typeInfo = type.GetTypeInfo(); return type != null && typeInfo.IsEnum && typeInfo.GetCustomAttribute<FlagsAttribute>(inherit: false) != null; } /// <summary> /// Returns a value indicating whether the specified value consists only of white-space characters. /// </summary> /// <param name="value">The string to test.</param> /// <returns><see langword="true"/> if the specified value consists only of white-space characters; /// otherwise <see langword="false"/>.</returns> [Pure] public static bool IsWhiteSpace(string value) { if (value == null) { return false; } for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) { return false; } } return true; } } }
// Copyright (c) Narvalo.Org. All rights reserved. See LICENSE.txt in the project root for license information. namespace Narvalo { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Reflection; public static class Predicates { /// <summary> /// Returns a value indicating whether the specified <paramref name="type"/> is a flags enumeration. /// </summary> /// <param name="type">The type to test.</param> /// <returns><see langword="true"/> if the specified <paramref name="type"/> is a flags enumeration; /// otherwise <see langword="false"/>.</returns> [Pure] [SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Flags", Justification = "[Intentionally] The rule does not apply here.")] [SuppressMessage("Gendarme.Rules.Portability", "MonoCompatibilityReviewRule", Justification = "[Intentionally] Method marked as MonoTODO.")] public static bool IsFlagsEnum(Type type) { var typeInfo = type.GetTypeInfo(); return type != null && typeInfo.IsEnum && typeInfo.GetCustomAttribute<FlagsAttribute>(inherit: false) != null; } /// <summary> /// Returns a value indicating whether the specified value consists only of white-space characters. /// </summary> /// <param name="value">The string to test.</param> /// <returns><see langword="true"/> if the specified value consists only of white-space characters; /// otherwise <see langword="false"/>.</returns> [Pure] public static bool IsWhiteSpace(string value) { if (value == null) { return false; } for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) { return false; } } return true; } } }
bsd-2-clause
C#
9ef9b63b6228a45854131fbb8ca17d55de721445
fix seperator
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
Engine.Core/Context/ContextHelpers.cs
Engine.Core/Context/ContextHelpers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Engine.Core.DataTypes; using Engine.Core.Utils; using LanguageExt; namespace Engine.Core.Context { public class ContextHelpers { internal class FullKey : Tuple<string, string> { public FullKey(string identityType, string key) : base(identityType, key) { } public string IdentityType { get { return Item1; } } public string Key { get { return Item2; } } } internal static Option<FullKey> SplitFullKey(string s) { var fragments = s.Split('.'); return fragments.Length == 2 ? new FullKey(fragments[0], fragments[1]) : Option<FullKey>.None; } internal static GetContextValue ContextValueForId(string id) { return (key) => key == "@@id" ? id : Option<string>.None; } internal static GetLoadedContextByIdentityType GetContextRetrieverByType(GetLoadedContextByIdentity getLoadedContexts, HashSet<Identity> identities) { return (type) => { var identity = identities.Single(x => x.Type == type); return Merge(getLoadedContexts(identity), ContextValueForId(identity.Id)); }; } internal static GetContextValue FlattenLoadedContext(GetLoadedContextByIdentityType getLoadedContext) { return (fullKey) => SplitFullKey(fullKey).Bind(fk => getLoadedContext(fk.IdentityType)(fk.Key)); } internal static GetContextFixedConfigurationValue GetFixedConfigurationContext(GetContextValue getContextValue) { return (fullKey) => SplitFullKey(fullKey) .Bind(fk => getContextValue(fk.IdentityType + ".@fixed_" + fk.Key)) .Select(x => new ConfigurationValue(x)); } internal static GetContextValue Merge(GetContextValue a, GetContextValue b) { return (key) => a(key).IfNone(() => b(key)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Engine.Core.DataTypes; using Engine.Core.Utils; using LanguageExt; namespace Engine.Core.Context { public class ContextHelpers { internal class FullKey : Tuple<string, string> { public FullKey(string identityType, string key) : base(identityType, key) { } public string IdentityType { get { return Item1; } } public string Key { get { return Item2; } } } internal static Option<FullKey> SplitFullKey(string s) { var fragments = s.Split('.'); return fragments.Length == 2 ? new FullKey(fragments[0], fragments[1]) : Option<FullKey>.None; } internal static GetContextValue ContextValueForId(string id) { return (key) => key == "@@id" ? id : Option<string>.None; } internal static GetLoadedContextByIdentityType GetContextRetrieverByType(GetLoadedContextByIdentity getLoadedContexts, HashSet<Identity> identities) { return (type) => { var identity = identities.Single(x => x.Type == type); return Merge(getLoadedContexts(identity), ContextValueForId(identity.Id)); }; } internal static GetContextValue FlattenLoadedContext(GetLoadedContextByIdentityType getLoadedContext) { return (fullKey) => SplitFullKey(fullKey).Bind(fk => getLoadedContext(fk.IdentityType)(fk.Key)); } internal static GetContextFixedConfigurationValue GetFixedConfigurationContext(GetContextValue getContextValue) { return (fullKey) => SplitFullKey(fullKey) .Bind(fk => getContextValue(fk.IdentityType + ":@fixed_" + fk.Key)) .Select(x => new ConfigurationValue(x)); } internal static GetContextValue Merge(GetContextValue a, GetContextValue b) { return (key) => a(key).IfNone(() => b(key)); } } }
mit
C#
7a6b4aefb7d0750d590fd7fe16b4afdb78415a64
Update for new version of Cardboard SDK
JScott/cardboard-controls
CardboardControl/Scripts/ParsedTouchData.cs
CardboardControl/Scripts/ParsedTouchData.cs
using UnityEngine; using System.Collections; /** * Dealing with raw touch input from a Cardboard device */ public class ParsedTouchData { private bool wasTouched = false; public ParsedTouchData() { Cardboard cardboard = CardboardGameObject().GetComponent<Cardboard>(); cardboard.TapIsTrigger = false; } private GameObject CardboardGameObject() { GameObject gameObject = Camera.main.gameObject; return gameObject.transform.parent.parent.gameObject; } public void Update() { wasTouched |= IsDown(); } public bool IsDown() { return Input.touchCount > 0; } public bool IsUp() { if (!IsDown() && wasTouched) { wasTouched = false; return true; } return false; } }
using UnityEngine; using System.Collections; /** * Dealing with raw touch input from a Cardboard device */ public class ParsedTouchData { private bool wasTouched = false; public ParsedTouchData() {} public void Update() { wasTouched |= this.IsDown(); } public bool IsDown() { return Input.touchCount > 0; } public bool IsUp() { if (!this.IsDown() && wasTouched) { wasTouched = false; return true; } return false; } }
mit
C#
606714d6f404fc6ef877b39457f89b98e80424d6
Use default JSON settings when creating serializers.
aj-r/FileManagement
FileManagement.Json/JsonSerializer.cs
FileManagement.Json/JsonSerializer.cs
using System.IO; using System.Text; using Newtonsoft.Json; namespace FileManagement.Json { /// <summary> /// Serializes and deserializes objects in JSON format. /// </summary> public class JsonSerializer : ISerializer { private JsonSerializerSettings settings; /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// </summary> public JsonSerializer() : this(null) { } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// </summary> /// <param name="settings">The JSON serialization settings to use.</param> public JsonSerializer(JsonSerializerSettings settings) { this.settings = settings; } #region ISerializer Members /// <summary> /// Serializes an object. /// </summary> /// <typeparam name="T">The type of object to serialize.</typeparam> /// <param name="stream">The stream to which the object will be serialized.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="obj">The object to serialize.</param> public void Serialize<T>(Stream stream, Encoding encoding, T obj) { using (var writer = new StreamWriter(stream, encoding, 1024, true)) using (var jsonWriter = new JsonTextWriter(writer)) { var serializer = Newtonsoft.Json.JsonSerializer.CreateDefault(settings); serializer.Serialize(jsonWriter, obj); } } /// <summary> /// Deserializes an object. /// </summary> /// <typeparam name="T">The type of object to deserialize</typeparam> /// <param name="stream">The stream from which the object will be deserialized.</param> /// <param name="encoding">The character encoding to use.</param> /// <returns>The deserialized object.</returns> public T Deserialize<T>(Stream stream, Encoding encoding) { using (var reader = new StreamReader(stream, encoding, false, 1024, true)) using (var jsonReader = new JsonTextReader(reader)) { var serializer = Newtonsoft.Json.JsonSerializer.CreateDefault(settings); return serializer.Deserialize<T>(jsonReader); } } #endregion } }
using System.IO; using System.Text; using Newtonsoft.Json; namespace FileManagement.Json { /// <summary> /// Serializes and deserializes objects in JSON format. /// </summary> public class JsonSerializer : ISerializer { private JsonSerializerSettings settings; /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// </summary> public JsonSerializer() : this(null) { } /// <summary> /// Creates a new <see cref="JsonSerializer"/> instance. /// </summary> /// <param name="settings">The JSON serialization settings to use.</param> public JsonSerializer(JsonSerializerSettings settings) { this.settings = settings; } #region ISerializer Members /// <summary> /// Serializes an object. /// </summary> /// <typeparam name="T">The type of object to serialize.</typeparam> /// <param name="stream">The stream to which the object will be serialized.</param> /// <param name="encoding">The character encoding to use.</param> /// <param name="obj">The object to serialize.</param> public void Serialize<T>(Stream stream, Encoding encoding, T obj) { using (var writer = new StreamWriter(stream, encoding, 1024, true)) using (var jsonWriter = new JsonTextWriter(writer)) { var serializer = new Newtonsoft.Json.JsonSerializer(); serializer.Serialize(jsonWriter, obj); } } /// <summary> /// Deserializes an object. /// </summary> /// <typeparam name="T">The type of object to deserialize</typeparam> /// <param name="stream">The stream from which the object will be deserialized.</param> /// <param name="encoding">The character encoding to use.</param> /// <returns>The deserialized object.</returns> public T Deserialize<T>(Stream stream, Encoding encoding) { using (var reader = new StreamReader(stream, encoding, false, 1024, true)) using (var jsonReader = new JsonTextReader(reader)) { var serializer = new Newtonsoft.Json.JsonSerializer(); return serializer.Deserialize<T>(jsonReader); } } #endregion } }
mit
C#
6797890e1d8c58175446c79045972876372e3fbd
Fix a race condition between opening search results window and initializing it if it was closed within a frame.
TautvydasZilys/FileSystemSearch,TautvydasZilys/FileSystemSearch,TautvydasZilys/FileSystemSearch
FileSystemSearch/SearchResultsView.cs
FileSystemSearch/SearchResultsView.cs
using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace FileSystemSearch { class SearchResultsView : HwndHost { private IntPtr childView; private ManualResetEvent createdEvent = new ManualResetEvent(false); protected override HandleRef BuildWindowCore(HandleRef hwndParent) { childView = CreateView(hwndParent.Handle, (int)Width, (int)Height); var childHwnd = GetHwnd(childView); Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { if (childView != IntPtr.Zero) { InitializeView(childView); SizeChanged += OnSizeChanged; ResizeView(childView, (int)ActualWidth, (int)ActualHeight); } createdEvent.Set(); })); return new HandleRef(this, childHwnd); } protected override void DestroyWindowCore(HandleRef hwnd) { Cleanup(); } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { if (childView != IntPtr.Zero) ResizeView(childView, (int)e.NewSize.Width, (int)e.NewSize.Height); } public void AddItem(IntPtr findData, IntPtr itemPath) { createdEvent.WaitOne(); if (childView != IntPtr.Zero) AddItemToView(childView, findData, itemPath); } public void Cleanup() { if (childView != IntPtr.Zero) { SizeChanged -= OnSizeChanged; DestroyView(childView); childView = IntPtr.Zero; } } [DllImport("SearchResultsView.dll")] private static extern IntPtr CreateView(IntPtr parent, int width, int height); [DllImport("SearchResultsView.dll")] private static extern void InitializeView(IntPtr view); [DllImport("SearchResultsView.dll")] private static extern void ResizeView(IntPtr view, int width, int height); [DllImport("SearchResultsView.dll")] private static extern IntPtr GetHwnd(IntPtr view); [DllImport("SearchResultsView.dll")] private static extern void DestroyView(IntPtr view); [DllImport("SearchResultsView.dll")] private static extern void AddItemToView(IntPtr view, IntPtr findData, IntPtr itemPath); } }
using System; using System.Runtime.InteropServices; using System.Threading; using System.Windows; using System.Windows.Interop; using System.Windows.Threading; namespace FileSystemSearch { class SearchResultsView : HwndHost { private IntPtr childView; private ManualResetEvent createdEvent = new ManualResetEvent(false); protected override HandleRef BuildWindowCore(HandleRef hwndParent) { childView = CreateView(hwndParent.Handle, (int)Width, (int)Height); var childHwnd = GetHwnd(childView); Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() => { InitializeView(childView); SizeChanged += OnSizeChanged; ResizeView(childView, (int)ActualWidth, (int)ActualHeight); createdEvent.Set(); })); return new HandleRef(this, childHwnd); } protected override void DestroyWindowCore(HandleRef hwnd) { Cleanup(); } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { if (childView != IntPtr.Zero) ResizeView(childView, (int)e.NewSize.Width, (int)e.NewSize.Height); } public void AddItem(IntPtr findData, IntPtr itemPath) { createdEvent.WaitOne(); if (childView != IntPtr.Zero) AddItemToView(childView, findData, itemPath); } public void Cleanup() { if (childView != IntPtr.Zero) { SizeChanged -= OnSizeChanged; DestroyView(childView); childView = IntPtr.Zero; } } [DllImport("SearchResultsView.dll")] private static extern IntPtr CreateView(IntPtr parent, int width, int height); [DllImport("SearchResultsView.dll")] private static extern void InitializeView(IntPtr view); [DllImport("SearchResultsView.dll")] private static extern void ResizeView(IntPtr view, int width, int height); [DllImport("SearchResultsView.dll")] private static extern IntPtr GetHwnd(IntPtr view); [DllImport("SearchResultsView.dll")] private static extern void DestroyView(IntPtr view); [DllImport("SearchResultsView.dll")] private static extern void AddItemToView(IntPtr view, IntPtr findData, IntPtr itemPath); } }
mit
C#
493a8e1a8feec1562b867d3b86af21c354ea5e51
Refactor PlayerMovement
setchi/kagaribi,setchi/kagaribi
Assets/Scripts/Main/Player/PlayerMovement.cs
Assets/Scripts/Main/Player/PlayerMovement.cs
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; using UniRx; using UniRx.Triggers; public class PlayerMovement : MonoBehaviour { [SerializeField] GameObject operationTarget; [SerializeField] float moveSpeed = 1; void Awake() { var touchDownStream = this.UpdateAsObservable() .Where(_ => Input.GetMouseButtonDown(0)) .Select(_ => Input.mousePosition); var swipeStream = this.UpdateAsObservable() .SkipUntil(touchDownStream) .TakeWhile(_ => !Input.GetMouseButtonUp(0)) .RepeatSafe(); swipeStream.CombineLatest(touchDownStream, (_, startPos) => startPos) .Select(startPos => Input.mousePosition - startPos) .Subscribe(Move); } void Move(Vector3 velocity) { velocity /= Screen.width * 1.5f; float x = Mathf.Clamp(velocity.x, -1f, 1f); float y = Mathf.Clamp(velocity.y, -1f, 1f); operationTarget.transform.Translate( x * moveSpeed, y * moveSpeed, 0 ); } }
using UnityEngine; using UnityEngine.UI; using System; using System.Collections; public class PlayerMovement : MonoBehaviour { public GameObject operationTarget; public float moveSpeed = 1; Vector3 touchPos; bool isTouch = false; void Update () { if (Input.GetMouseButtonDown(0)) { isTouch = true; touchPos = Input.mousePosition; } else if (Input.GetMouseButtonUp(0)) { isTouch = false; } if (isTouch) { Move(Input.mousePosition - touchPos); } } void Move(Vector3 velocity) { velocity.x /= Screen.width * 1.5f; velocity.y /= Screen.width * 1.5f; float x = Mathf.Clamp(velocity.x, -1f, 1f); float y = Mathf.Clamp(velocity.y, -1f, 1f); operationTarget.transform.Translate( x * moveSpeed, y * moveSpeed, 0 ); } }
mit
C#
34912771219524f2a511fc5231a9a8787a1b5625
Update version to 2.1.2 (remove alpha).
jmptrader/elmah-mvc,alexbeletsky/elmah-mvc,fhchina/elmah-mvc,mmsaffari/elmah-mvc
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Elmah.Mvc")] [assembly: AssemblyCopyright("Copyright © Atif Aziz, James Driscoll, Alexander Beletsky 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("2.1.2.*")] [assembly: AssemblyFileVersion("2.1.2")] [assembly: AssemblyInformationalVersion("2.1.2")]
using System.Reflection; [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Elmah.Mvc")] [assembly: AssemblyCopyright("Copyright © Atif Aziz, James Driscoll, Alexander Beletsky 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyVersion("2.1.2.*")] [assembly: AssemblyFileVersion("2.1.2")] [assembly: AssemblyInformationalVersion("2.1.2-alpha2")]
apache-2.0
C#
220c83515fada6ec173657fd4d58b178d9178e02
Add settings view model to view model locator
erooijak/MeditationTimer
src/ViewModel/ViewModelLocator.cs
src/ViewModel/ViewModelLocator.cs
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:Rooijakkers.MeditationTimer" x:Key="Locator" /> </Application.Resources> In the View: DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" You can also use Blend to do all this with the tool's support. See http://www.galasoft.ch/mvvm */ using GalaSoft.MvvmLight.Ioc; using Microsoft.Practices.ServiceLocation; using Rooijakkers.MeditationTimer.Data; using Rooijakkers.MeditationTimer.Data.Contracts; namespace Rooijakkers.MeditationTimer.ViewModel { /// <summary> /// This class contains static references to all the view models in the /// application and provides an entry point for the bindings. /// </summary> public class ViewModelLocator { /// <summary> /// Initializes a new instance of the ViewModelLocator class. /// </summary> public ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<IMeditationDiaryRepository, MeditationDiaryRepository>(); SimpleIoc.Default.Register<TimerViewModel>(); SimpleIoc.Default.Register<DiaryViewModel>(); SimpleIoc.Default.Register<SettingsViewModel>(); } public TimerViewModel Timer => ServiceLocator.Current.GetInstance<TimerViewModel>(); public DiaryViewModel Diary => ServiceLocator.Current.GetInstance<DiaryViewModel>(); public SettingsViewModel Settings => ServiceLocator.Current.GetInstance<SettingsViewModel>(); public static void Cleanup() { // TODO Clear the ViewModels } } }
/* In App.xaml: <Application.Resources> <vm:ViewModelLocator xmlns:vm="clr-namespace:Rooijakkers.MeditationTimer" x:Key="Locator" /> </Application.Resources> In the View: DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}" You can also use Blend to do all this with the tool's support. See http://www.galasoft.ch/mvvm */ using GalaSoft.MvvmLight.Ioc; using Microsoft.Practices.ServiceLocation; using Rooijakkers.MeditationTimer.Data; using Rooijakkers.MeditationTimer.Data.Contracts; namespace Rooijakkers.MeditationTimer.ViewModel { /// <summary> /// This class contains static references to all the view models in the /// application and provides an entry point for the bindings. /// </summary> public class ViewModelLocator { /// <summary> /// Initializes a new instance of the ViewModelLocator class. /// </summary> public ViewModelLocator() { ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default); SimpleIoc.Default.Register<IMeditationDiaryRepository, MeditationDiaryRepository>(); SimpleIoc.Default.Register<TimerViewModel>(); SimpleIoc.Default.Register<DiaryViewModel>(); } public TimerViewModel Timer => ServiceLocator.Current.GetInstance<TimerViewModel>(); public DiaryViewModel Diary => ServiceLocator.Current.GetInstance<DiaryViewModel>(); public static void Cleanup() { // TODO Clear the ViewModels } } }
mit
C#
adfdf52d57990c1b295aa3b196c5f61dcf74baae
patch bump
NinjaVault/NinjaHive,NinjaVault/NinjaHive
NinjaHive.WebApp/Properties/AssemblyInfo.cs
NinjaHive.WebApp/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("NinjaHive.WebApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NinjaHive")] [assembly: AssemblyCopyright("Copyright © 2015 - NinjaVault")] [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("9fbcfa55-af00-423f-a4fa-d7c34af2d13f")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.2.4.*")]
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("NinjaHive.WebApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NinjaHive")] [assembly: AssemblyCopyright("Copyright © 2015 - NinjaVault")] [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("9fbcfa55-af00-423f-a4fa-d7c34af2d13f")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.2.3.*")]
apache-2.0
C#
61fccb7dc546cf48d7d87125a44ea41c393e4e40
Update Localization.cs
yasinkuyu/Localization
src/Localization.cs
src/Localization.cs
// @yasinkuyu // 05/08/2014 namespace Insya.Localization { public static class Localization { private static LocalizationStartup _loc; static Localization() { _loc = new LocalizationStartup(); } /// <summary> /// Alternative calling Localize("id") or Get("id") /// </summary> /// <param name="id"></param> /// <returns></returns> public static string Get(string id) { return _loc.GetLang(id); } /// <summary> /// Example <item id="homepage">Home Page</item> /// </summary> /// <param name="id"></param> /// <returns>xml item id</returns> /// <returns>xml culture name</returns> public static string Get(string id, string culture) { return _loc.GetLang(id, culture); } /// <summary> /// Inline localization /// </summary> /// <param name="lang"></param> public static string Get(Inline lang) { return _loc.GetLang(lang); } /// <summary> /// Example <item id="homepage">Home Page</item> /// </summary> /// <param name="id"></param> /// <returns>xml item id</returns> public static string Localize(string id) { return _loc.GetLang(id); } /// <summary> /// Example <item id="homepage">Home Page</item> /// </summary> /// <param name="id"></param> /// <returns>xml item id</returns> /// <returns>xml culture name</returns> public static string Localize(string id, string culture) { return _loc.GetLang(id, culture); } /// <summary> /// Inline localization /// </summary> /// <param name="lang"></param> public static string Localize(Inline lang) { return _loc.GetLang(lang); } } }
// @yasinkuyu // 05/08/2014 namespace Insya.Localization { public static class Localization { private static LocalizationStartup _loc; static Localization() { _loc = new LocalizationStartup(); } /// <summary> /// Alternative calling Localize("id") or Get("id") /// </summary> /// <param name="id"></param> /// <returns></returns> public static string Get(string id) { return _loc.GetLang(id); } /// <summary> /// Example <item id="homepage">Home Page</item> /// </summary> /// <param name="id"></param> /// <returns>xml item id</returns> public static string Localize(string id) { return _loc.GetLang(id); } /// <summary> /// Alternative calling Localize("id") or Get("id") /// </summary> /// <param name="id"></param> /// <returns></returns> public static string Get(Inline lang) { return _loc.GetLang(lang); } /// <summary> /// Inline localization /// </summary> /// <param name="lang"></param> /// <returns>xml item id</returns> public static string Localize(Inline lang) { return _loc.GetLang(lang); } } }
mit
C#
2de42abec35682c7dec1d1f3eabb86849c414b36
remove test code
Fody/Equals
AssemblyToProcess/EmptyClass.cs
AssemblyToProcess/EmptyClass.cs
using System.Linq; [Equals] public class EmptyClass { }
using System.Linq; [Equals] public class EmptyClass { public bool ggggg() { int[] o = new int[0]; return Enumerable.SequenceEqual(o, o); } }
mit
C#
bf2a2bd457cbd260d6b5bea4d1a7f7cbb3a94bca
Add serializable to class
LunaPg/RoguEvE
Assets/Scripts/Classes/Drone.cs
Assets/Scripts/Classes/Drone.cs
using UnityEngine; using System.Collections; using SimpleJSON; using UnityEngine.Serialization; using System; [Serializable] public class Drone : MonoBehaviour { public string name; public int eveId; //stats public int signatureRadius; public int maxVelocity; public int speed; public int maxRange; public float trackingSpeed; public float entityAttackRange; public float entityFlyRange; public int rechargeRate; public float damageMultiplier; public int agility; public int scanSpeed; public float techLevel; public int droneBandwidthUsed; //structure public int hp; //resistances public float kineticDamageResonance; public float thermalDamageResonance; public float explosiveDamageResonance; public float emDamageResonance; //shield public int shieldCapacity; public int shieldRechargeRate; public float shieldEmDamageResonance; public float shieldExplosiveDamageResonance; public float shieldKineticDamageResonance; public float shieldThermalDamageResonance; //armor public int armorHp; public float armorEmDamageResonance; public float armorExplosiveDamageResonance; public float armorKineticDamageResonance; public float armorThermalDamageResonance; //damage public int emDamage; public int explosiveDamage; public int kineticDamage; public int thermalDamage; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using UnityEngine; using System.Collections; using SimpleJSON; public class Drone : MonoBehaviour { public string name; public int eveId; //stats public int signatureRadius; public int maxVelocity; public int speed; public int maxRange; public float trackingSpeed; public float entityAttackRange; public float entityFlyRange; public int rechargeRate; public float damageMultiplier; public int agility; public int scanSpeed; public float techLevel; public int droneBandwidthUsed; //structure public int hp; //resistances public float kineticDamageResonance; public float thermalDamageResonance; public float explosiveDamageResonance; public float emDamageResonance; //shield public int shieldCapacity; public int shieldRechargeRate; public float shieldEmDamageResonance; public float shieldExplosiveDamageResonance; public float shieldKineticDamageResonance; public float shieldThermalDamageResonance; //armor public int armorHp; public float armorEmDamageResonance; public float armorExplosiveDamageResonance; public float armorKineticDamageResonance; public float armorThermalDamageResonance; //damage public int emDamage; public int explosiveDamage; public int kineticDamage; public int thermalDamage; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
mit
C#
d9ccf8b15416d6c92368fd45e2939ddaab14d6cd
enable CORS
malevy/todo
src/Todo/Startup.cs
src/Todo/Startup.cs
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Diagnostics; using Newtonsoft.Json; using Todo.Formatters.Siren; using Todo.Models; namespace Todo { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // our in-memory task store services.AddSingleton<TodoRepository>(servicesProvider => TodoRepositoryFactory.Build()); services.AddMvcCore() .AddCors() .AddDataAnnotations() .AddFormatterMappings() .AddJsonFormatters() .AddJsonOptions(jsonOptions => jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore); services.AddSirenFormatters(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // app.UseStaticFiles(); app.UseMvc(); app.UseCors(policyBuilder => policyBuilder .AllowAnyHeader() .AllowAnyMethod() .AllowAnyOrigin()); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.AspNetCore.Diagnostics; using Newtonsoft.Json; using Todo.Formatters.Siren; using Todo.Models; namespace Todo { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // our in-memory task store services.AddSingleton<TodoRepository>(servicesProvider => TodoRepositoryFactory.Build()); // services.AddMvc() // .AddJsonOptions(jsonOptions => jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore); services.AddMvcCore() .AddCors() .AddDataAnnotations() .AddFormatterMappings() .AddJsonFormatters() .AddJsonOptions(jsonOptions => jsonOptions.SerializerSettings.NullValueHandling = NullValueHandling.Ignore); services.AddSirenFormatters(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } // app.UseStaticFiles(); app.UseMvc(); } } }
bsd-3-clause
C#
b5ac6c478a1e78b78164cccd5947df1feebe963b
Make window validation taller
gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,DaggerES/LunaMultiPlayer
Client/Windows/Mod/ModWindow.cs
Client/Windows/Mod/ModWindow.cs
using LunaClient.Base; using LunaClient.Localization; using LunaClient.Utilities; using UnityEngine; namespace LunaClient.Windows.Mod { public partial class ModWindow : Window<ModWindow> { private const float WindowHeight = 600; private const float WindowWidth = 600; private static Vector2 _missingExpansionsScrollPos; private static Vector2 _mandatoryFilesNotFoundScrollPos; private static Vector2 _mandatoryFilesDifferentShaScrollPos; private static Vector2 _forbiddenFilesScrollPos; private static Vector2 _nonListedFilesScrollPos; private static Vector2 _mandatoryPartsScrollPos; private static Vector2 _forbiddenPartsScrollPos; public override void Update() { SafeDisplay = Display; } public override void OnGui() { base.OnGui(); if (SafeDisplay) WindowRect = LmpGuiUtil.PreventOffscreenWindow(GUILayout.Window(6706 + MainSystem.WindowOffset, WindowRect, DrawContent, LocalizationContainer.ModWindowText.Title, WindowStyle, LayoutOptions)); } public override void SetStyles() { WindowRect = new Rect(Screen.width/2f - WindowWidth/2f, Screen.height/2f - WindowHeight/2f, WindowWidth, WindowHeight); MoveRect = new Rect(0, 0, 10000, 20); LayoutOptions = new GUILayoutOption[4]; LayoutOptions[0] = GUILayout.MinWidth(WindowWidth); LayoutOptions[1] = GUILayout.MaxWidth(WindowWidth); LayoutOptions[2] = GUILayout.MinHeight(WindowHeight); LayoutOptions[3] = GUILayout.MaxHeight(WindowHeight); } } }
using LunaClient.Base; using LunaClient.Localization; using LunaClient.Utilities; using UnityEngine; namespace LunaClient.Windows.Mod { public partial class ModWindow : Window<ModWindow> { private const float WindowHeight = 400; private const float WindowWidth = 600; private static Vector2 _missingExpansionsScrollPos; private static Vector2 _mandatoryFilesNotFoundScrollPos; private static Vector2 _mandatoryFilesDifferentShaScrollPos; private static Vector2 _forbiddenFilesScrollPos; private static Vector2 _nonListedFilesScrollPos; private static Vector2 _mandatoryPartsScrollPos; private static Vector2 _forbiddenPartsScrollPos; public override void Update() { SafeDisplay = Display; } public override void OnGui() { base.OnGui(); if (SafeDisplay) WindowRect = LmpGuiUtil.PreventOffscreenWindow(GUILayout.Window(6706 + MainSystem.WindowOffset, WindowRect, DrawContent, LocalizationContainer.ModWindowText.Title, WindowStyle, LayoutOptions)); } public override void SetStyles() { WindowRect = new Rect(Screen.width/2f - WindowWidth/2f, Screen.height/2f - WindowHeight/2f, WindowWidth, WindowHeight); MoveRect = new Rect(0, 0, 10000, 20); LayoutOptions = new GUILayoutOption[4]; LayoutOptions[0] = GUILayout.MinWidth(WindowWidth); LayoutOptions[1] = GUILayout.MaxWidth(WindowWidth); LayoutOptions[2] = GUILayout.MinHeight(WindowHeight); LayoutOptions[3] = GUILayout.MaxHeight(WindowHeight); } } }
mit
C#
fbe4c9b66e875dfef853adea1a1f5350ca25da29
implement symmetric encrypt/decrypt
SchmooseSA/Schmoose-BouncyCastle
Crypto/crypto/parameters/ParametersWithIV.cs
Crypto/crypto/parameters/ParametersWithIV.cs
using System; namespace Org.BouncyCastle.Crypto.Parameters { public class ParametersWithIV : ICipherParameters { private readonly ICipherParameters _parameters; private readonly byte[] _iv; public ParametersWithIV(ICipherParameters parameters, byte[] iv) : this(parameters, iv, 0, iv.Length) { } public ParametersWithIV(ICipherParameters parameters, byte[] iv, int ivOff, int ivLen) { if (parameters == null) throw new ArgumentNullException("parameters"); if (iv == null) throw new ArgumentNullException("iv"); _parameters = parameters; _iv = new byte[ivLen]; Array.Copy(iv, ivOff, _iv, 0, ivLen); } public byte[] GetIV() { return (byte[])_iv.Clone(); } public ICipherParameters Parameters { get { return _parameters; } } } }
using System; namespace Org.BouncyCastle.Crypto.Parameters { public class ParametersWithIV : ICipherParameters { private readonly ICipherParameters parameters; private readonly byte[] iv; public ParametersWithIV( ICipherParameters parameters, byte[] iv) : this(parameters, iv, 0, iv.Length) { } public ParametersWithIV( ICipherParameters parameters, byte[] iv, int ivOff, int ivLen) { if (parameters == null) throw new ArgumentNullException("parameters"); if (iv == null) throw new ArgumentNullException("iv"); this.parameters = parameters; this.iv = new byte[ivLen]; Array.Copy(iv, ivOff, this.iv, 0, ivLen); } public byte[] GetIV() { return (byte[]) iv.Clone(); } public ICipherParameters Parameters { get { return parameters; } } } }
mit
C#
fdce8389b56f642393921294f490212351d21e5c
Fix X509 validation
ahmetalpbalkan/Docker.DotNet,jterry75/Docker.DotNet,jterry75/Docker.DotNet
Docker.DotNet.X509/CertificateCredentials.cs
Docker.DotNet.X509/CertificateCredentials.cs
#if !netstandard1_3 using System.Net; #endif using System.Net.Http; using System.Security.Cryptography.X509Certificates; using Microsoft.Net.Http.Client; using System.Net.Security; namespace Docker.DotNet.X509 { public class CertificateCredentials : Credentials { private X509Certificate2 _certificate; public CertificateCredentials(X509Certificate2 clientCertificate) { _certificate = clientCertificate; } public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; } public override HttpMessageHandler GetHandler(HttpMessageHandler innerHandler) { var handler = (ManagedHandler)innerHandler; handler.ClientCertificates = new X509CertificateCollection { _certificate }; handler.ServerCertificateValidationCallback = this.ServerCertificateValidationCallback; #if !NETSTANDARD1_3 if (handler.ServerCertificateValidationCallback == null) { handler.ServerCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback; } #endif return handler; } public override bool IsTlsCredentials() { return true; } public override void Dispose() { } } }
#if !netstandard1_3 using System.Net; #endif using System.Net.Http; using System.Security.Cryptography.X509Certificates; using Microsoft.Net.Http.Client; using System.Net.Security; namespace Docker.DotNet.X509 { public class CertificateCredentials : Credentials { private X509Certificate2 _certificate; public CertificateCredentials(X509Certificate2 clientCertificate) { _certificate = clientCertificate; } public RemoteCertificateValidationCallback ServerCertificateValidationCallback { get; set; } public override HttpMessageHandler GetHandler(HttpMessageHandler innerHandler) { var handler = (ManagedHandler)innerHandler; handler.ClientCertificates = new X509CertificateCollection { _certificate }; #if !netstandard1_3 if (this.ServerCertificateValidationCallback == null) { handler.ServerCertificateValidationCallback = ServicePointManager.ServerCertificateValidationCallback; } #endif handler.ServerCertificateValidationCallback = this.ServerCertificateValidationCallback; return handler; } public override bool IsTlsCredentials() { return true; } public override void Dispose() { } } }
apache-2.0
C#
69c95cb4e0f5fc6d231b8027b6269e8208efe330
Fix HttpServer.cs to use latest version of Kayak
zhdusurfin/HttpMock,mattolenik/HttpMock,hibri/HttpMock,oschwald/HttpMock
src/HttpMock/HttpServer.cs
src/HttpMock/HttpServer.cs
using System; using System.Net; using System.Threading; using Kayak; using Kayak.Http; namespace HttpMock { public interface IHttpServer : IDisposable { RequestHandler Stub(Func<RequestProcessor, RequestHandler> func); IStubHttp WithNewContext(); IStubHttp WithNewContext(string baseUri); void Start(); } public class HttpServer : IHttpServer, IStubHttp { protected RequestProcessor _requestProcessor; protected IScheduler _scheduler; private Thread _thread; private Uri _uri; public HttpServer(Uri uri) { _uri = uri; _scheduler = KayakScheduler.Factory.Create(new SchedulerDelegate()); _requestProcessor = new RequestProcessor(); } public void Start() { _thread = new Thread(StartListening); _thread.Start(); } private void StartListening() { Console.WriteLine("Listener thread about to start"); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _uri.Port); _scheduler.Post(() => { KayakServer.Factory .CreateHttp(_requestProcessor, _scheduler) .Listen(ipEndPoint); }); _scheduler.Start(); } public void Dispose() { try { _requestProcessor.Stop(); _thread.Abort(); } catch (ThreadAbortException) { } _scheduler.Stop(); _scheduler.Dispose(); } public RequestHandler Stub(Func<RequestProcessor, RequestHandler> func) { return func.Invoke(_requestProcessor); } public IStubHttp WithNewContext() { _requestProcessor.ClearHandlers(); return this; } public IStubHttp WithNewContext(string baseUri) { _requestProcessor.SetBaseUri(baseUri); WithNewContext(); return this; } } }
using System; using System.Net; using System.Threading; using Kayak; using Kayak.Http; namespace HttpMock { public interface IHttpServer : IDisposable { RequestHandler Stub(Func<RequestProcessor, RequestHandler> func); IStubHttp WithNewContext(); IStubHttp WithNewContext(string baseUri); void Start(); } public class HttpServer : IHttpServer, IStubHttp { protected RequestProcessor _requestProcessor; protected IScheduler _scheduler; private Thread _thread; private Uri _uri; public HttpServer(Uri uri) { _uri = uri; _scheduler = new KayakScheduler(new SchedulerDelegate()); _requestProcessor = new RequestProcessor(); } public void Start() { _thread = new Thread(StartListening); _thread.Start(); } private void StartListening() { Console.WriteLine("Listener thread about to start"); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, _uri.Port); _scheduler.Post(() => { KayakServer.Factory .CreateHttp(_requestProcessor) .Listen(ipEndPoint); }); _scheduler.Start(); } public void Dispose() { try { _requestProcessor.Stop(); _thread.Abort(); } catch (ThreadAbortException) { } _scheduler.Stop(); _scheduler.Dispose(); } public RequestHandler Stub(Func<RequestProcessor, RequestHandler> func) { return func.Invoke(_requestProcessor); } public IStubHttp WithNewContext() { _requestProcessor.ClearHandlers(); return this; } public IStubHttp WithNewContext(string baseUri) { _requestProcessor.SetBaseUri(baseUri); WithNewContext(); return this; } } }
mit
C#
6635dd253ec7cf745f7e545f73dc691aea80d2d1
Add ctor with inner exception
McNeight/SharpZipLib
src/GZip/GZipException.cs
src/GZip/GZipException.cs
// GzipOutputStream.cs // // Copyright 2004 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; #if !COMPACT_FRAMEWORK using System.Runtime.Serialization; #endif using ICSharpCode.SharpZipLib; namespace ICSharpCode.SharpZipLib.GZip { /// <summary> /// GZipException represents a Gzip specific exception /// </summary> #if !COMPACT_FRAMEWORK [Serializable] #endif public class GZipException : SharpZipBaseException { #if !COMPACT_FRAMEWORK /// <summary> /// Deserialization constructor /// </summary> /// <param name="info"><see cref="SerializationInfo"/> for this constructor</param> /// <param name="context"><see cref="StreamingContext"/> for this constructor</param> protected GZipException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif /// <summary> /// Initialise a new instance of GZipException /// </summary> public GZipException() { } /// <summary> /// Initialise a new instance of GZipException with its message string. /// </summary> /// <param name="message">A <see cref="string"></see>string that describes the error.</param> public GZipException(string message) : base(message) { } /// <summary> /// /// </summary> /// <param name="message">A <see cref="string"></see>string that describes the error.</param> /// <param name="innerException">The inner exception.</param> public GZipException(string message, Exception innerException) : base (message, innerException) { } } }
// GzipOutputStream.cs // // Copyright 2004 John Reilly // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; #if !COMPACT_FRAMEWORK using System.Runtime.Serialization; #endif using ICSharpCode.SharpZipLib; namespace ICSharpCode.SharpZipLib.GZip { /// <summary> /// GZipException represents a Gzip specific exception /// </summary> #if !COMPACT_FRAMEWORK [Serializable] #endif public class GZipException : SharpZipBaseException { #if !COMPACT_FRAMEWORK /// <summary> /// Deserialization constructor /// </summary> /// <param name="info"><see cref="SerializationInfo"/> for this constructor</param> /// <param name="context"><see cref="StreamingContext"/> for this constructor</param> protected GZipException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif /// <summary> /// Initialise a new instance of GZipException /// </summary> public GZipException() { } /// <summary> /// Initialise a new instance of GZipException with its message string. /// </summary> /// <param name="message">A <see cref="string"></see>string that describes the error.</param> public GZipException(string message) : base(message) { } } }
mit
C#
30dbc1125ec61bd24ea2a6678b393dfa0bf4a189
Add str_to_int Error Case
hkdnet/Collection2Model
NameValueCollectionMapper.Test/MapperTest.cs
NameValueCollectionMapper.Test/MapperTest.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Collection2Model.Mapper; using System.Collections.Specialized; namespace Collection2Model.Mapper.Test { [TestClass] public class MapperTest { [TestMethod] public void TestMethod1() { var c = new NameValueCollection(); c.Add("IntProp", "1"); c.Add("BoolProp", "true"); c.Add("StrPropUpper", "STRING"); c.Add("StrPropLower", "string"); c.Add("DoubleProp", "0.0"); var ret = Collection2Model.Mapper.Mapper.MappingFromNameValueCollection<TestModel>(c); Assert.AreEqual<int>(1, ret.IntProp); Assert.AreEqual<bool>(true, ret.BoolProp); Assert.AreEqual<String>("STRING", ret.StrPropUpper); Assert.AreEqual<string>("string", ret.StrPropLower); Assert.AreEqual<double>(0.0, ret.DoubleProp); } [TestMethod] [ExpectedException(typeof(FormatException))] public void Throw_exception_with_str_to_int_convert() { var c = new NameValueCollection(); c.Add("IntProp", "invalid!"); var ret = Collection2Model.Mapper.Mapper.MappingFromNameValueCollection<TestModel>(c); Assert.Fail(); } } public class TestModel { public int IntProp { get; set; } public bool BoolProp { get; set; } public String StrPropUpper { get; set; } public string StrPropLower { get; set; } public double DoubleProp { get; set; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Collection2Model.Mapper; using System.Collections.Specialized; namespace Collection2Model.Mapper.Test { [TestClass] public class MapperTest { [TestMethod] public void TestMethod1() { var c = new NameValueCollection(); c.Add("IntProp", "1"); c.Add("BoolProp", "true"); c.Add("StrPropUpper", "STRING"); c.Add("StrPropLower", "string"); c.Add("DoubleProp", "0.0"); var ret = Collection2Model.Mapper.Mapper.MappingFromNameValueCollection<TestModel>(c); Assert.AreEqual<int>(1, ret.IntProp); Assert.AreEqual<bool>(true, ret.BoolProp); Assert.AreEqual<String>("STRING", ret.StrPropUpper); Assert.AreEqual<string>("string", ret.StrPropLower); Assert.AreEqual<double>(0.0, ret.DoubleProp); } } public class TestModel { public int IntProp { get; set; } public bool BoolProp { get; set; } public String StrPropUpper { get; set; } public string StrPropLower { get; set; } public double DoubleProp { get; set; } } }
mit
C#
bbce4451aa7693ee634b55081c705b4672ae93a2
Add ability to mark auth handle as successful
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer.Abstractions/Security/AuthorizationFilterHandle.cs
BTCPayServer.Abstractions/Security/AuthorizationFilterHandle.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace BTCPayServer.Security; public class AuthorizationFilterHandle { public AuthorizationHandlerContext Context { get; } public PolicyRequirement Requirement { get; } public HttpContext HttpContext { get; } public bool Success { get; private set; } public AuthorizationFilterHandle( AuthorizationHandlerContext context, PolicyRequirement requirement, HttpContext httpContext) { Context = context; Requirement = requirement; HttpContext = httpContext; } public void MarkSuccessful() { Success = true; } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; namespace BTCPayServer.Security; public class AuthorizationFilterHandle { public AuthorizationHandlerContext Context { get; } public PolicyRequirement Requirement { get; } public HttpContext HttpContext { get; } public bool Success { get; } public AuthorizationFilterHandle( AuthorizationHandlerContext context, PolicyRequirement requirement, HttpContext httpContext) { Context = context; Requirement = requirement; HttpContext = httpContext; } }
mit
C#
3d2b2c6d7b13febea51723eca9eca06a2e4890d5
Change html Breviary.cshtml
razsilev/Sv_Naum,razsilev/Sv_Naum,razsilev/Sv_Naum
Source/SvNaum.Web/Views/Home/Breviary.cshtml
Source/SvNaum.Web/Views/Home/Breviary.cshtml
@model IEnumerable<SvNaum.Models.Prayer> @{ ViewBag.Title = "Молитвеник"; } @if (this.User.Identity.IsAuthenticated) { @Html.ActionLink("Create prayer", "PrayerAdd", "Admin") <br /> <br /> } @if (Model != null && Model.Count() > 0) { foreach (var item in Model) { <div> <h2> @Html.DisplayFor(m => item.Title) </h2> <h3> @Html.DisplayFor(m => item.TitleSecond) </h3> <p> @Html.Raw(item.Text) </p> <br /> <div class="avtor"> @Html.DisplayFor(m => item.Author) </div> <br /> <div id="facebookButton" class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button"> </div> @if (this.User.Identity.IsAuthenticated) { <div> @Html.ActionLink("Edit", "PrayerEdit", "Admin", new { id = item.Id }, null) &nbsp; @Html.ActionLink("Delete", "PrayerDelete", "Admin", new { id = item.Id }, null) </div> } </div> } } else { <h3>There is no prayer!</h3> }
@model IEnumerable<SvNaum.Models.Prayer> @{ ViewBag.Title = "Молитвеник"; } <h2>Молитвеник</h2> <br /> @if (this.User.Identity.IsAuthenticated) { @Html.ActionLink("Create prayer", "PrayerAdd", "Admin") <br /> <br /> } @if (Model != null && Model.Count() > 0) { foreach (var item in Model) { <div> <h2> @Html.DisplayFor(m => item.Title) </h2> <h3> @Html.DisplayFor(m => item.TitleSecond) </h3> <p> @Html.Raw(item.Text) </p> <br /> <div class="avtor"> @Html.DisplayFor(m => item.Author) </div> <br /> <div id="facebookButton" class="fb-share-button" data-href="https://developers.facebook.com/docs/plugins/" data-layout="button"> </div> @if (this.User.Identity.IsAuthenticated) { <div> @Html.ActionLink("Edit", "PrayerEdit", "Admin", new { id = item.Id }, null) &nbsp; @Html.ActionLink("Delete", "PrayerDelete", "Admin", new { id = item.Id }, null) </div> } </div> } } else { <h3>There is no prayer!</h3> }
mit
C#
cd30893ad2c35fdbedd829ab7268d8498cba9196
return empty object
simgreci/SQLXEtoEventHub
SQLXEtoEventHub/XEPosition/RegistryStore.cs
SQLXEtoEventHub/XEPosition/RegistryStore.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace SQLXEtoEventHub.XEPosition { public class RegistryStore { protected const string KEY_PATH = "SOFTWARE"; protected const string KEY_NODE = "SQLXEtoEventHub"; protected const string LASTFILE = "LastFile"; protected const string OFFSET = "Offset"; public string Trace { get; protected set; } public RegistryStore(string traceName) { this.Trace = traceName; } public void Update(XEPosition pos) { var root = Registry.CurrentUser.OpenSubKey(KEY_PATH, RegistryKeyPermissionCheck.ReadWriteSubTree); var key = root.CreateSubKey(KEY_NODE, RegistryKeyPermissionCheck.ReadWriteSubTree); if (key == null) throw new UnauthorizedAccessException("Registry key not created. Please run the installer or create it manually"); var trace = key.CreateSubKey(Trace); trace.SetValue(LASTFILE, pos.LastFile, RegistryValueKind.String); trace.SetValue(OFFSET, pos.Offset, RegistryValueKind.QWord); } public XEPosition Read() { var root = Registry.CurrentUser.OpenSubKey(KEY_PATH); var key = root.OpenSubKey(KEY_NODE); if (key == null) return new XEPosition(); var trace = key.OpenSubKey(Trace); if (trace == null) return new XEPosition(); return new XEPosition { LastFile = (string)trace.GetValue(LASTFILE), Offset = (long)trace.GetValue(OFFSET) }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Win32; namespace SQLXEtoEventHub.XEPosition { public class RegistryStore { protected const string KEY_PATH = "SOFTWARE"; protected const string KEY_NODE = "SQLXEtoEventHub"; protected const string LASTFILE = "LastFile"; protected const string OFFSET = "Offset"; public string Trace { get; protected set; } public RegistryStore(string traceName) { this.Trace = traceName; } public void Update(XEPosition pos) { var root = Registry.CurrentUser.OpenSubKey(KEY_PATH, RegistryKeyPermissionCheck.ReadWriteSubTree); var key = root.CreateSubKey(KEY_NODE, RegistryKeyPermissionCheck.ReadWriteSubTree); if (key == null) throw new UnauthorizedAccessException("Registry key not created. Please run the installer or create it manually"); var trace = key.CreateSubKey(Trace); trace.SetValue(LASTFILE, pos.LastFile, RegistryValueKind.String); trace.SetValue(OFFSET, pos.Offset, RegistryValueKind.QWord); } public XEPosition Read() { var root = Registry.CurrentUser.OpenSubKey(KEY_PATH); var key = root.OpenSubKey(KEY_NODE); if (key == null) return null; var trace = key.OpenSubKey(Trace); if (trace == null) return null; return new XEPosition { LastFile = (string)trace.GetValue(LASTFILE), Offset = (long)trace.GetValue(OFFSET) }; } } }
apache-2.0
C#
fe079c082bd383aaf68a8bf21be3f2a1e34cec26
Add imahe url property
toshetoo/TaskManagerMVC,toshetoo/TaskManagerMVC,toshetoo/TaskManagerMVC,toshetoo/TaskManagerMVC
TaskManagerMVC/TaskManagerMVC/Models/Task.cs
TaskManagerMVC/TaskManagerMVC/Models/Task.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TaskManagerMVC.Models { public class Task: BaseModel { public string ProjectID { get; set; } public string AuthorID { get; set; } public string AsigneeID { get; set; } public string Title { get; set; } public TaskStatus Status { get; set; } public string Content { get; set; } public string CreationDate { get; set; } public string ImageURL { get; set; } } public enum TaskStatus { TODO, INPROGRESS, DONE } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace TaskManagerMVC.Models { public class Task: BaseModel { public string ProjectID { get; set; } public string AuthorID { get; set; } public string AsigneeID { get; set; } public string Title { get; set; } public TaskStatus Status { get; set; } public string Content { get; set; } public string CreationDate { get; set; } } public enum TaskStatus { TODO, INPROGRESS, DONE } }
mit
C#
0dfc6e98402b8a2ec33078e51231f10c0e52b0b3
Add display
warpzone81/ColouredCoins,warpzone81/ColouredCoins,warpzone81/ColouredCoins
WebApplication/Views/Shared/_Property.cshtml
WebApplication/Views/Shared/_Property.cshtml
@model IEnumerable<WebApplication.Models.PropertyViewModel> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th> @Html.DisplayNameFor(model => model.Value) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.DisplayFor(modelItem => item.Value) </td> <td> @Html.ActionLink("Details", "Details", new { id=item.ID }) </td> </tr> } </table>
@model IEnumerable<WebApplication.Models.PropertyViewModel> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.Description) </th> <th></th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.Description) </td> <td> @Html.ActionLink("Details", "Details", new { id=item.ID }) </td> </tr> } </table>
mit
C#
19cd2e3d3a5e36d7bade86c34101681407d4c510
Update documentation URL in application template (#397)
nanoframework/nf-Visual-Studio-extension
source/CSharp.BlankApplication/Program.cs
source/CSharp.BlankApplication/Program.cs
using System; using System.Threading; namespace $safeprojectname$ { public class Program { public static void Main() { Console.WriteLine("Hello world!"); Thread.Sleep(Timeout.Infinite); // Browse our samples repository: https://github.com/nanoframework/samples // Check our documentation online: https://docs.nanoframework.net/ // Join our lively Discord community: https://discord.gg/gCyBu8T } } }
using System; using System.Threading; namespace $safeprojectname$ { public class Program { public static void Main() { Console.WriteLine("Hello world!"); Thread.Sleep(Timeout.Infinite); // Browse our samples repository: https://github.com/nanoframework/samples // Check our documentation online: https://docs.nanoframework.net/articles/intro.html // Join our lively Discord community: https://discord.gg/gCyBu8T } } }
mit
C#
aaa3ff3f03b3e711b403e5010fe4ddd0589b4d02
Fix the XenCenterUpdateAlertTests
kc284/xenadmin,minli1/xenadmin,kc284/xenadmin,jijiang/xenadmin,xenserver/xenadmin,stephen-turner/xenadmin,minli1/xenadmin,MihaelaStoica/xenadmin,stephen-turner/xenadmin,MihaelaStoica/xenadmin,minli1/xenadmin,MihaelaStoica/xenadmin,stephen-turner/xenadmin,MihaelaStoica/xenadmin,jijiang/xenadmin,xenserver/xenadmin,jijiang/xenadmin,minli1/xenadmin,kc284/xenadmin,jijiang/xenadmin,kc284/xenadmin,MihaelaStoica/xenadmin,minli1/xenadmin,stephen-turner/xenadmin,kc284/xenadmin,MihaelaStoica/xenadmin,xenserver/xenadmin,stephen-turner/xenadmin,jijiang/xenadmin,stephen-turner/xenadmin,jijiang/xenadmin,minli1/xenadmin
XenAdminTests/UnitTests/AlertTests/XenCenterUpdateAlertTests.cs
XenAdminTests/UnitTests/AlertTests/XenCenterUpdateAlertTests.cs
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using NUnit.Framework; using XenAdmin.Alerts; using XenAdmin.Core; using XenAdminTests.UnitTests.UnitTestHelper; namespace XenAdminTests.UnitTests.AlertTests { [TestFixture, Category(TestCategories.Unit)] public class XenCenterUpdateAlertTests { [Test] public void VerifyStoredDataWithDefaultConstructor() { IUnitTestVerifier validator = new VerifyGetters(new XenCenterUpdateAlert(new XenCenterVersion("6.0.2", "xc", true, false, "http://url", new DateTime(2011, 12, 09).ToString()))); validator.Verify(new AlertClassUnitTestData { AppliesTo = XenAdmin.Branding.BRAND_CONSOLE, FixLinkText = "Go to Web Page", HelpID = "XenCenterUpdateAlert", Description = "xc is now available. Download the new version from the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.", HelpLinkText = "Help", Title = "xc is now available", Priority = "Priority5" }); } } }
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using NUnit.Framework; using XenAdmin.Alerts; using XenAdmin.Core; using XenAdminTests.UnitTests.UnitTestHelper; namespace XenAdminTests.UnitTests.AlertTests { [TestFixture, Category(TestCategories.Unit)] public class XenCenterUpdateAlertTests { [Test] public void VerifyStoredDataWithDefaultConstructor() { IUnitTestVerifier validator = new VerifyGetters(new XenCenterUpdateAlert(new XenCenterVersion("6.0.2", "xc", true, false, "http://url", new DateTime(2011, 12, 09).ToString()))); validator.Verify(new AlertClassUnitTestData { AppliesTo = XenAdmin.Branding.BRAND_CONSOLE, FixLinkText = "Go to Web Page", HelpID = "XenCenterUpdateAlert", Description = "xc is now available. Download the new version from the " + XenAdmin.Branding.COMPANY_NAME_SHORT + " website.", HelpLinkText = "Help", Title = "New " + XenAdmin.Branding.BRAND_CONSOLE + " Available", Priority = "Priority5" }); } } }
bsd-2-clause
C#
bd6a7fdd0b46764a2eaaf4fc9323edb7066a3f39
Update Startup class with the new options
HangfireIO/Hangfire.Highlighter,HangfireIO/Hangfire.Highlighter,HangfireIO/Hangfire.Highlighter
Hangfire.Highlighter/Startup.cs
Hangfire.Highlighter/Startup.cs
using System; using System.Collections.Generic; using System.Transactions; using Hangfire.Dashboard; using Hangfire.Highlighter; using Hangfire.Highlighter.Jobs; using Hangfire.SqlServer; using Microsoft.Owin; using Owin; [assembly:OwinStartup(typeof(Startup))] namespace Hangfire.Highlighter { public class Startup { public static IEnumerable<IDisposable> GetHangfireConfiguration() { GlobalConfiguration.Configuration .SetDataCompatibilityLevel(CompatibilityLevel.Version_170) .UseSimpleAssemblyNameTypeSerializer() .UseRecommendedSerializerSettings() .UseSqlServerStorage("HighlighterDb", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromSeconds(30), QueuePollInterval = TimeSpan.Zero, TransactionIsolationLevel = IsolationLevel.ReadCommitted, SlidingInvisibilityTimeout = TimeSpan.FromMinutes(1), UsePageLocksOnDequeue = true, DisableGlobalLocks = true }); yield return new BackgroundJobServer(); } public void Configuration(IAppBuilder app) { app.MapSignalR(); app.UseHangfireAspNet(GetHangfireConfiguration); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new IDashboardAuthorizationFilter[0] }); RecurringJob.AddOrUpdate<SnippetHighlighter>( "SnippetHighlighter.CleanUp", x => x.CleanUpAsync(), Cron.Daily); } } }
using System; using System.Collections.Generic; using System.Transactions; using Hangfire.Dashboard; using Hangfire.Highlighter; using Hangfire.Highlighter.Jobs; using Hangfire.SqlServer; using Microsoft.Owin; using Owin; [assembly:OwinStartup(typeof(Startup))] namespace Hangfire.Highlighter { public class Startup { public static IEnumerable<IDisposable> GetHangfireConfiguration() { GlobalConfiguration.Configuration.UseSqlServerStorage("HighlighterDb", new SqlServerStorageOptions { CommandBatchMaxTimeout = TimeSpan.FromSeconds(30), QueuePollInterval = TimeSpan.FromTicks(1), TransactionIsolationLevel = IsolationLevel.ReadCommitted, SlidingInvisibilityTimeout = TimeSpan.FromMinutes(1) }); yield return new BackgroundJobServer(); } public void Configuration(IAppBuilder app) { app.MapSignalR(); app.UseHangfireAspNet(GetHangfireConfiguration); app.UseHangfireDashboard("/hangfire", new DashboardOptions { Authorization = new IDashboardAuthorizationFilter[0] }); RecurringJob.AddOrUpdate<SnippetHighlighter>( "SnippetHighlighter.CleanUp", x => x.CleanUpAsync(), Cron.Daily); } } }
mit
C#
1905772d88235d4627f1520ae5243f512a57fe3c
Mark ICCSaxDelegator class as internal.
haithemaraissia/CocosSharp,netonjm/CocosSharp,netonjm/CocosSharp,mono/CocosSharp,MSylvia/CocosSharp,hig-ag/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp,hig-ag/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp,TukekeSoft/CocosSharp,zmaruo/CocosSharp
src/platform/ICCSAXDelegator.cs
src/platform/ICCSAXDelegator.cs
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace CocosSharp { internal interface ICCSAXDelegator { void StartElement(object ctx, string name, string[] atts); void EndElement(object ctx, string name); void TextHandler(object ctx, byte[] ch, int len); } }
/**************************************************************************** Copyright (c) 2010-2012 cocos2d-x.org Copyright (c) 2008-2009 Jason Booth Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace CocosSharp { public interface ICCSAXDelegator { void StartElement(object ctx, string name, string[] atts); void EndElement(object ctx, string name); void TextHandler(object ctx, byte[] ch, int len); } }
mit
C#
511c5cad1221ce608f7d3563e7e815ca9f417ce8
Simplify SkipTypeRule
another-guy/CSharpToTypeScript,another-guy/CSharpToTypeScript
CSharpToTypeScript.Core/Common/SkipTypeRule.cs
CSharpToTypeScript.Core/Common/SkipTypeRule.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using CSharpToTypeScript.Core.Configuration; namespace CSharpToTypeScript.Core.Common { public sealed class SkipTypeRule : ISkipTypeRule { private readonly List<string> _skipTypeAttributeNames; public SkipTypeRule(InputConfiguration inputConfiguration) { _skipTypeAttributeNames = inputConfiguration.SkipTypesWithAttribute.NullToException(new ArgumentNullException(nameof(inputConfiguration.SkipTypesWithAttribute))); } public bool AppliesTo(MemberInfo sourceType) { return sourceType .GetCustomAttributes() .Select(attribute => attribute.GetType().FullName) .Intersect(_skipTypeAttributeNames) .Any(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using CSharpToTypeScript.Core.Configuration; namespace CSharpToTypeScript.Core.Common { public sealed class SkipTypeRule : ISkipTypeRule { private readonly List<string> _skipTypeAttributeNames; public SkipTypeRule(InputConfiguration inputConfiguration) { _skipTypeAttributeNames = inputConfiguration.SkipTypesWithAttribute.NullToException(new ArgumentNullException(nameof(inputConfiguration.SkipTypesWithAttribute))); } public bool AppliesTo(MemberInfo sourceType) { var assignedCustomAttributes = sourceType .GetCustomAttributes() .Select(attribute => attribute.GetType().FullName) .ToList(); return assignedCustomAttributes .Intersect(_skipTypeAttributeNames) .Any(); } } }
mit
C#
161fda06cdc78fa623bdbfdb5b34b4b62d2a2659
Update AssemblyInfo.cs
dotJEM/web-host,dotJEM/web-host,dotJEM/web-host
DotJEM.Web.Host/Properties/AssemblyInfo.cs
DotJEM.Web.Host/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("DotJEM.Web.Host")] [assembly: AssemblyDescription("Simple oppinionated abstraction on top of the Web API for SPA's")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("DotJEM.Web.Host")] [assembly: AssemblyCompany("N/A")] [assembly: AssemblyCopyright("Copyright © DotJEM 014-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("965ef42b-ec21-4c72-b5fb-fe87555112ec")] // 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.0.1")] [assembly: AssemblyFileVersion("0.0.0.1")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DotJEM.Web.Host")] [assembly: AssemblyDescription("Simple oppinionated abstraction on top of the Web API for SPA's")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("DotJEM.Web.Host")] [assembly: AssemblyCompany("N/A")] [assembly: AssemblyCopyright("Copyright © DotJEM A/S 2014-2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("965ef42b-ec21-4c72-b5fb-fe87555112ec")] // 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.0.1")] [assembly: AssemblyFileVersion("0.0.0.1")]
mit
C#
d8cebd20edac75973ad00c65b35421fcab97a9e7
Add xmldoc
EVAST9919/osu,ppy/osu,UselessToucan/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,2yangk23/osu,johnneijzen/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,peppy/osu-new,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,smoogipoo/osu
osu.Game.Rulesets.Osu/UI/Cursor/OsuCursorSprite.cs
osu.Game.Rulesets.Osu/UI/Cursor/OsuCursorSprite.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.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Osu.UI.Cursor { public abstract class OsuCursorSprite : CompositeDrawable { /// <summary> /// The an optional piece of the cursor to expand when in a clicked state. /// If null, the whole cursor will be affected by expansion. /// </summary> public Drawable ExpandTarget { get; protected set; } } }
// 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.Graphics; using osu.Framework.Graphics.Containers; namespace osu.Game.Rulesets.Osu.UI.Cursor { public abstract class OsuCursorSprite : CompositeDrawable { public Drawable ExpandTarget { get; protected set; } } }
mit
C#
aaba8d1a62678f8ac3f61aef98f42b56571d2d05
Simplify VisualStudioExecutionListener, for readability.
fixie/fixie
src/Fixie.VisualStudio.TestAdapter/VisualStudioExecutionListener.cs
src/Fixie.VisualStudio.TestAdapter/VisualStudioExecutionListener.cs
namespace Fixie.VisualStudio.TestAdapter { using System; using Execution; public class VisualStudioExecutionListener : Handler<CaseSkipped>, Handler<CasePassed>, Handler<CaseFailed> { readonly ExecutionRecorder log; public VisualStudioExecutionListener(ExecutionRecorder log) { this.log = log; } public void Handle(CaseSkipped message) { log.RecordResult( FullyQualifiedName(message), message.Name, message.Status.ToString(), message.Duration, message.Output, message.Reason, errorStackTrace: null ); } public void Handle(CasePassed message) { log.RecordResult( FullyQualifiedName(message), message.Name, message.Status.ToString(), message.Duration, message.Output, errorMessage: null, errorStackTrace: null ); } public void Handle(CaseFailed message) { var exception = message.Exception; log.RecordResult( FullyQualifiedName(message), message.Name, message.Status.ToString(), message.Duration, message.Output, exception.Message, exception.TypedStackTrace() ); } static string FullyQualifiedName(CaseCompleted message) => new MethodGroup(message.Class, message.Method).FullName; } }
namespace Fixie.VisualStudio.TestAdapter { using System; using Execution; public class VisualStudioExecutionListener : Handler<CaseSkipped>, Handler<CasePassed>, Handler<CaseFailed> { readonly ExecutionRecorder log; public VisualStudioExecutionListener(ExecutionRecorder log) { this.log = log; } public void Handle(CaseSkipped message) { log.RecordResult( fullyQualifiedName: new MethodGroup(message.Class, message.Method).FullName, displayName: message.Name, outcome: message.Status.ToString(), duration: message.Duration, output: message.Output, errorMessage: message.Reason, errorStackTrace: null ); } public void Handle(CasePassed message) { log.RecordResult( fullyQualifiedName: new MethodGroup(message.Class, message.Method).FullName, displayName: message.Name, outcome: message.Status.ToString(), duration: message.Duration, output: message.Output, errorMessage: null, errorStackTrace: null ); } public void Handle(CaseFailed message) { var exception = message.Exception; log.RecordResult( fullyQualifiedName: new MethodGroup(message.Class, message.Method).FullName, displayName: message.Name, outcome: message.Status.ToString(), duration: message.Duration, output: message.Output, errorMessage: exception.Message, errorStackTrace: exception.TypedStackTrace() ); } } }
mit
C#
23c9cac1e27a1836c40c54ccca36fba0b645e4ec
Fix the issue with settings name
miroslavpopovic/production-ready-apis-sample
BoardGamesApi/Controllers/TempController.cs
BoardGamesApi/Controllers/TempController.cs
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BoardGamesApi.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class TempController : Controller { private readonly IConfiguration _configuration; public TempController(IConfiguration configuration) { _configuration = configuration; } [AllowAnonymous] [Route("/get-token")] public IActionResult GenerateToken(string name = "mscommunity") { var jwt = JwtTokenGenerator .Generate(name, true, _configuration["Tokens:Issuer"], _configuration["Tokens:Key"]); return Ok(jwt); } } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace BoardGamesApi.Controllers { [ApiExplorerSettings(IgnoreApi = true)] public class TempController : Controller { private readonly IConfiguration _configuration; public TempController(IConfiguration configuration) { _configuration = configuration; } [AllowAnonymous] [Route("/get-token")] public IActionResult GenerateToken(string name = "mscommunity") { var jwt = JwtTokenGenerator .Generate(name, true, _configuration["Token:Issuer"], _configuration["Token:Key"]); return Ok(jwt); } } }
mit
C#
30c93d3b261e49bfc668fa4578e7b06f5945265a
Update ContactData.cs
AshleyMedway/MailJet.NET
MailJetClient/Response/Data/ContactData.cs
MailJetClient/Response/Data/ContactData.cs
using MailJet.Client.Enum; using System.Collections.Generic; namespace MailJet.Client.Response.Data { public class ContactData : DataItem { public string Email { get; set; } public string Name { get; set; } public CreateContactAction Action { get; set; } public Dictionary<string, object> Properties { get; set; } } }
using MailJet.Client.Enum; using System.Collections.Generic; namespace MailJet.Client.Response.Data { public class ContactData : DataItem { public string Email { get; set; } public string Name { get; set; } public CreateContactAction Action { get; set; } public Dictionary<string, string> Properties { get; set; } } }
mit
C#
bef8c29596b72a927f989396f723aa5b0bef3e44
Bump version to 0.14.1
ar3cka/Journalist
src/SolutionInfo.cs
src/SolutionInfo.cs
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.14.1")] [assembly: AssemblyInformationalVersionAttribute("0.14.1")] [assembly: AssemblyFileVersionAttribute("0.14.1")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.14.1"; } }
// <auto-generated/> using System.Reflection; [assembly: AssemblyProductAttribute("Journalist")] [assembly: AssemblyVersionAttribute("0.14.0")] [assembly: AssemblyInformationalVersionAttribute("0.14.0")] [assembly: AssemblyFileVersionAttribute("0.14.0")] [assembly: AssemblyCompanyAttribute("Anton Mednonogov")] namespace System { internal static class AssemblyVersionInformation { internal const string Version = "0.14.0"; } }
apache-2.0
C#
e1febe9e9717fe58e2e14783edb99b718c9d36cb
Change version
marcosdimitrio/SolutionCreator
SolutionCreator.Wpf/Properties/AssemblyInfo.cs
SolutionCreator.Wpf/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SolutionCreator.Wpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SolutionCreator.Wpf")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.2.0")] [assembly: AssemblyFileVersion("1.2.2.0")]
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SolutionCreator.Wpf")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SolutionCreator.Wpf")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.1.0")] [assembly: AssemblyFileVersion("1.2.1.0")]
apache-2.0
C#
23fa44446c18012e84a91dcf2c8007fb38e05faa
Add comment
drognanar/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,Hosch250/roslyn,robinsedlaczek/roslyn,DustinCampbell/roslyn,xasx/roslyn,jamesqo/roslyn,MichalStrehovsky/roslyn,tvand7093/roslyn,reaction1989/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,brettfo/roslyn,davkean/roslyn,wvdd007/roslyn,aelij/roslyn,eriawan/roslyn,tannergooding/roslyn,tmeschter/roslyn,CyrusNajmabadi/roslyn,khyperia/roslyn,VSadov/roslyn,eriawan/roslyn,jkotas/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,panopticoncentral/roslyn,tmat/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,physhi/roslyn,AmadeusW/roslyn,cston/roslyn,tvand7093/roslyn,reaction1989/roslyn,mattscheffer/roslyn,mattwar/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,drognanar/roslyn,bkoelman/roslyn,mgoertz-msft/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,paulvanbrenk/roslyn,TyOverby/roslyn,jmarolf/roslyn,reaction1989/roslyn,jmarolf/roslyn,kelltrick/roslyn,dotnet/roslyn,KevinRansom/roslyn,stephentoub/roslyn,jkotas/roslyn,sharwell/roslyn,MattWindsor91/roslyn,OmarTawfik/roslyn,CyrusNajmabadi/roslyn,nguerrera/roslyn,xasx/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,CaptainHayashi/roslyn,mavasani/roslyn,panopticoncentral/roslyn,CaptainHayashi/roslyn,davkean/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,dpoeschl/roslyn,bkoelman/roslyn,ErikSchierboom/roslyn,gafter/roslyn,tmat/roslyn,AlekseyTs/roslyn,khyperia/roslyn,pdelvo/roslyn,amcasey/roslyn,yeaicc/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,mattwar/roslyn,pdelvo/roslyn,panopticoncentral/roslyn,gafter/roslyn,dpoeschl/roslyn,TyOverby/roslyn,MichalStrehovsky/roslyn,Hosch250/roslyn,jasonmalinowski/roslyn,swaroop-sridhar/roslyn,orthoxerox/roslyn,KevinRansom/roslyn,wvdd007/roslyn,aelij/roslyn,paulvanbrenk/roslyn,jcouv/roslyn,Giftednewt/roslyn,mavasani/roslyn,KirillOsenkov/roslyn,tmat/roslyn,mattscheffer/roslyn,tmeschter/roslyn,brettfo/roslyn,amcasey/roslyn,srivatsn/roslyn,bartdesmet/roslyn,jkotas/roslyn,dotnet/roslyn,diryboy/roslyn,sharwell/roslyn,Giftednewt/roslyn,tannergooding/roslyn,khyperia/roslyn,ErikSchierboom/roslyn,davkean/roslyn,physhi/roslyn,KirillOsenkov/roslyn,wvdd007/roslyn,bartdesmet/roslyn,gafter/roslyn,weltkante/roslyn,cston/roslyn,kelltrick/roslyn,stephentoub/roslyn,heejaechang/roslyn,jmarolf/roslyn,jasonmalinowski/roslyn,AnthonyDGreen/roslyn,abock/roslyn,amcasey/roslyn,dotnet/roslyn,nguerrera/roslyn,aelij/roslyn,robinsedlaczek/roslyn,yeaicc/roslyn,stephentoub/roslyn,srivatsn/roslyn,MattWindsor91/roslyn,mattscheffer/roslyn,abock/roslyn,mmitche/roslyn,jamesqo/roslyn,lorcanmooney/roslyn,Hosch250/roslyn,agocke/roslyn,mgoertz-msft/roslyn,kelltrick/roslyn,mmitche/roslyn,paulvanbrenk/roslyn,AlekseyTs/roslyn,lorcanmooney/roslyn,lorcanmooney/roslyn,robinsedlaczek/roslyn,MattWindsor91/roslyn,orthoxerox/roslyn,diryboy/roslyn,CaptainHayashi/roslyn,diryboy/roslyn,physhi/roslyn,jamesqo/roslyn,agocke/roslyn,weltkante/roslyn,weltkante/roslyn,bkoelman/roslyn,shyamnamboodiripad/roslyn,KirillOsenkov/roslyn,xasx/roslyn,OmarTawfik/roslyn,eriawan/roslyn,MattWindsor91/roslyn,MichalStrehovsky/roslyn,tmeschter/roslyn,mgoertz-msft/roslyn,Giftednewt/roslyn,AlekseyTs/roslyn,drognanar/roslyn,abock/roslyn,swaroop-sridhar/roslyn,dpoeschl/roslyn,mattwar/roslyn,genlu/roslyn,AnthonyDGreen/roslyn,brettfo/roslyn,jcouv/roslyn,AnthonyDGreen/roslyn,VSadov/roslyn,tvand7093/roslyn,nguerrera/roslyn,TyOverby/roslyn,agocke/roslyn,orthoxerox/roslyn,heejaechang/roslyn,yeaicc/roslyn,genlu/roslyn,AmadeusW/roslyn,cston/roslyn,genlu/roslyn,DustinCampbell/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,pdelvo/roslyn,tannergooding/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,srivatsn/roslyn
src/Features/Core/Portable/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeRefactoringProvider.cs
src/Features/Core/Portable/GenerateDefaultConstructors/GenerateDefaultConstructorsCodeRefactoringProvider.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateMember.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { /// <summary> /// This <see cref="CodeRefactoringProvider"/> gives users a way to generate constructors for /// a derived type that delegate to a base type. For all accessibly constructors in the base /// type, the user will be offered to create a constructor in the derived type with the same /// signature if they don't already have one. This way, a user can override a type and easily /// create all the forwarding constructors. /// /// Importantly, this type is not responsible for generating constructors when the user types /// something like "new MyType(x, y, z)", nor is it responsible for generating constructors /// for a type based on the fields/properties of that type. /// </summary> [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared] internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; var textSpan = context.Span; var cancellationToken = context.CancellationToken; // TODO: https://github.com/dotnet/roslyn/issues/5778 // Not supported in REPL for now. if (document.Project.IsSubmission) { return; } if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var service = document.GetLanguageService<IGenerateDefaultConstructorsService>(); var actions = await service.GenerateDefaultConstructorsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Composition; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.GenerateMember.GenerateDefaultConstructors; using Microsoft.CodeAnalysis.Shared.Extensions; namespace Microsoft.CodeAnalysis.GenerateDefaultConstructors { [ExportCodeRefactoringProvider(LanguageNames.CSharp, LanguageNames.VisualBasic, Name = PredefinedCodeRefactoringProviderNames.GenerateDefaultConstructors), Shared] internal class GenerateDefaultConstructorsCodeRefactoringProvider : CodeRefactoringProvider { public override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var document = context.Document; var textSpan = context.Span; var cancellationToken = context.CancellationToken; // TODO: https://github.com/dotnet/roslyn/issues/5778 // Not supported in REPL for now. if (document.Project.IsSubmission) { return; } if (document.Project.Solution.Workspace.Kind == WorkspaceKind.MiscellaneousFiles) { return; } var service = document.GetLanguageService<IGenerateDefaultConstructorsService>(); var actions = await service.GenerateDefaultConstructorsAsync(document, textSpan, cancellationToken).ConfigureAwait(false); context.RegisterRefactorings(actions); } } }
mit
C#
2457be6e23a684d746c92ff1cbbd1aa6bbb26cc0
fix su config checker - now sets the correct define
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
Assets/MRTK/Providers/Experimental/WindowsSceneUnderstanding/Editor/WindowsSceneUnderstandingConfigChecker.cs
Assets/MRTK/Providers/Experimental/WindowsSceneUnderstanding/Editor/WindowsSceneUnderstandingConfigChecker.cs
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System.IO; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.WindowsSceneUnderstanding.Experimental { /// <summary> /// Class to perform checks for configuration checks for the Windows Mixed Reality provider. /// </summary> static class WindowsSceneUnderstandingConfigurationChecker { private const string FileName = "Microsoft.MixedReality.SceneUnderstanding.DotNet.dll"; private static readonly string[] definitions = { "SCENE_UNDERSTANDING_PRESENT" }; /// <summary> /// Ensures that the appropriate symbolic constant is defined based on the presence of the SceneUnderstanding binary. /// </summary> [MenuItem("Mixed Reality Toolkit/Utilities/Scene Understanding/Check Configuration")] private static void ReconcileSceneUnderstandingDefine() { FileInfo[] files = FileUtilities.FindFilesInAssets(FileName); if (files.Length > 0) { ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions); } else { ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Utilities.Editor; using System.IO; using UnityEditor; namespace Microsoft.MixedReality.Toolkit.WindowsSceneUnderstanding.Experimental { /// <summary> /// Class to perform checks for configuration checks for the Windows Mixed Reality provider. /// </summary> static class WindowsSceneUnderstandingConfigurationChecker { private const string FileName = "Microsoft.MixedReality.SceneUnderstanding.DotNet.dll"; private static readonly string[] definitions = { "SCENEUNDERSTANDING_PRESENT" }; /// <summary> /// Ensures that the appropriate symbolic constant is defined based on the presence of the SceneUnderstanding binary. /// </summary> [MenuItem("Mixed Reality Toolkit/Utilities/Scene Understanding/Check Configuration")] private static void ReconcileSceneUnderstandingDefine() { FileInfo[] files = FileUtilities.FindFilesInAssets(FileName); if (files.Length > 0) { ScriptUtilities.AppendScriptingDefinitions(BuildTargetGroup.WSA, definitions); } else { ScriptUtilities.RemoveScriptingDefinitions(BuildTargetGroup.WSA, definitions); } } } }
mit
C#
08358c24e29d513f6e29a9db93d2647976777565
Allow Button.Text to be set to null
l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1
Source/Eto.Mac/Forms/Controls/MacButton.cs
Source/Eto.Mac/Forms/Controls/MacButton.cs
using Eto.Forms; using MonoMac.AppKit; using Eto.Drawing; namespace Eto.Mac.Forms.Controls { public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler where TControl: NSButton where TWidget: Control where TCallback: Control.ICallback { public virtual string Text { get { return Control.Title; } set { var oldSize = GetPreferredSize(Size.MaxValue); Control.SetTitleWithMnemonic(value ?? string.Empty); LayoutIfNeeded(oldSize); } } } }
using Eto.Forms; using MonoMac.AppKit; using Eto.Drawing; namespace Eto.Mac.Forms.Controls { public abstract class MacButton<TControl, TWidget, TCallback> : MacControl<TControl, TWidget, TCallback>, TextControl.IHandler where TControl: NSButton where TWidget: Control where TCallback: Control.ICallback { public virtual string Text { get { return Control.Title; } set { var oldSize = GetPreferredSize(Size.MaxValue); Control.SetTitleWithMnemonic(value); LayoutIfNeeded(oldSize); } } } }
bsd-3-clause
C#
bf7705179f5226cf2f1be5e64f0af36c79784169
Update JsonSerializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/JsonSerializer.cs
TIKSN.Core/Serialization/JsonSerializer.cs
using Newtonsoft.Json; namespace TIKSN.Serialization { public class JsonSerializer : SerializerBase<string> { protected override string SerializeInternal(object obj) { return JsonConvert.SerializeObject(obj); } } }
using Newtonsoft.Json; using TIKSN.Analytics.Telemetry; namespace TIKSN.Serialization { public class JsonSerializer : SerializerBase<string> { public JsonSerializer(IExceptionTelemeter exceptionTelemeter) : base(exceptionTelemeter) { } protected override string SerializeInternal(object obj) { return JsonConvert.SerializeObject(obj); } } }
mit
C#
486dd05e2a35589838e2fa74c5dc4b016981725f
Fix Lda formatting.
joshpeterson/mos,joshpeterson/mos,joshpeterson/mos
Mos6510/Instructions/Lda.cs
Mos6510/Instructions/Lda.cs
using System.Collections.Generic; namespace Mos6510.Instructions { public class Lda : Instruction { private static Dictionary<AddressingMode, int> numberOfCycles = new Dictionary<AddressingMode, int> { { AddressingMode.Immediate, 2 }, { AddressingMode.Absolute, 4 }, { AddressingMode.AbsoluteX, 4 }, { AddressingMode.AbsoluteY, 4 }, { AddressingMode.Zeropage, 3 }, { AddressingMode.ZeropageX, 4 }, { AddressingMode.ZeropageY, 4 }, { AddressingMode.IndexedIndirectX, 6 }, { AddressingMode.IndexedIndirectY, 5 }, }; public void Execute(ProgrammingModel model, Memory memory, Argument argument) { model.GetRegister(RegisterName.A).SetValue(argument.value); RegisterUtils.SetZeroFlag(model, RegisterName.A); RegisterUtils.SetNegativeFlag(model, RegisterName.A); } public int CyclesFor(AddressingMode mode) { return numberOfCycles[mode]; } } }
using System.Collections.Generic; namespace Mos6510.Instructions { public class Lda : Instruction { private static Dictionary<AddressingMode, int> numberOfCycles = new Dictionary<AddressingMode, int> { { AddressingMode.Immediate, 2 }, { AddressingMode.Absolute, 4 }, { AddressingMode.AbsoluteX, 4 }, { AddressingMode.AbsoluteY, 4 }, { AddressingMode.Zeropage, 3 }, { AddressingMode.ZeropageX, 4 }, { AddressingMode.ZeropageY, 4 }, { AddressingMode.IndexedIndirectX, 6 }, { AddressingMode.IndexedIndirectY, 5 }, }; public void Execute(ProgrammingModel model, Memory memory, Argument argument) { model.GetRegister(RegisterName.A).SetValue(argument.value); RegisterUtils.SetZeroFlag(model, RegisterName.A); RegisterUtils.SetNegativeFlag(model, RegisterName.A); } public int CyclesFor(AddressingMode mode) { return numberOfCycles[mode]; } } }
mit
C#
3972a282f88f9ed8ed7e256668fefe3e386e542e
Improve CameraConsumer.
Eusth/VRGIN
VRGIN/Helpers/CameraConsumer.cs
VRGIN/Helpers/CameraConsumer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using VRGIN.Core; namespace VRGIN.Helpers { public class CameraConsumer : IScreenGrabber { private RenderTexture _Texture; private bool _SpareMainCamera; private bool _SoftMode; public bool Check(Camera camera) { return !camera.GetComponent("UICamera") && !camera.name.Contains("VR") && camera.targetTexture == null && (!camera.CompareTag("MainCamera") || !_SpareMainCamera); } public IEnumerable<RenderTexture> GetTextures() { yield return _Texture; } public void OnAssign(Camera camera) { if (_SoftMode) { camera.cullingMask = 0; camera.nearClipPlane = 1; camera.farClipPlane = 1; } else { camera.enabled = false; } } public CameraConsumer(bool spareMainCamera = false, bool softMode = false) { _SoftMode = softMode; _SpareMainCamera = spareMainCamera; _Texture = new RenderTexture(1, 1, 0); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using VRGIN.Core; namespace VRGIN.Helpers { public class CameraConsumer : IScreenGrabber { private RenderTexture _Texture; public bool Check(Camera camera) { return !camera.GetComponent("UICamera") && !camera.name.Contains("VR") && camera.targetTexture == null; } public IEnumerable<RenderTexture> GetTextures() { yield return _Texture; } public void OnAssign(Camera camera) { camera.enabled = false; } public CameraConsumer() { _Texture = new RenderTexture(1, 1, 0); } } }
mit
C#
d3a06ba5e5d1c5122123be2ea3cb64a7b0053b7c
Update 20.WriteFileDelimited.cs
MarcosMeli/FileHelpers
FileHelpers.Examples/Examples/10.QuickStart/20.WriteFileDelimited.cs
FileHelpers.Examples/Examples/10.QuickStart/20.WriteFileDelimited.cs
using System; using System.Collections.Generic; using FileHelpers; namespace ExamplesFx { //-> Name:Write Delimited File //-> Description:Example of how to write a Delimited File //-> AutoRun:true public class WriteFileDelimited : ExampleBase { //-> To write an output file, separated by a "|": //-> FileOut: Output.txt // -> You use the same Record Mapping Class as you would to read it: //-> File:RecordClass.cs /// <summary> /// Layout for a file delimited by "|" /// </summary> [DelimitedRecord("|")] public class Orders { public int OrderID; public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime OrderDate; [FieldConverter(ConverterKind.Decimal, ".")] // The decimal separator is "." public decimal Freight; } //-> /File //-> Instantiate a FileHelperEngine and write the file: public override void Run() { //-> File:Example.cs var engine = new FileHelperEngine<Orders>(); var orders = new List<Orders>(); orders.Add(new Orders() { OrderID = 1, CustomerID = "AIRG", Freight = 82.43M, OrderDate = new DateTime(2009, 05, 01) }); orders.Add(new Orders() { OrderID = 2, CustomerID = "JSYV", Freight = 12.22M, OrderDate = new DateTime(2009, 05, 02) }); //engine now supports custom EOL for writing engine.NewLineForWrite = "\n"; engine.WriteFile("Output.Txt", orders); //-> /File Console.WriteLine(engine.WriteString(orders)); } //-> The classes you use could come from anywhere: LINQ to Entities, SQL database reads, or in this case, classes created within an application. } }
using System; using System.Collections.Generic; using FileHelpers; namespace ExamplesFx { //-> Name:Write Delimited File //-> Description:Example of how to write a Delimited File //-> AutoRun:true public class WriteFileDelimited : ExampleBase { //-> To write an output file (separated by a "|"): //-> FileOut: Output.txt // -> You use the same Record Mapping Class as you would to read it: //-> File:RecordClass.cs /// <summary> /// Layout for a file delimited by | /// </summary> [DelimitedRecord("|")] public class Orders { public int OrderID; public string CustomerID; [FieldConverter(ConverterKind.Date, "ddMMyyyy")] public DateTime OrderDate; [FieldConverter(ConverterKind.Decimal, ".")] // The decimal separator is . public decimal Freight; } //-> /File //-> Instantiate a FileHelperEngine and write the file: public override void Run() { //-> File:Example.cs var engine = new FileHelperEngine<Orders>(); var orders = new List<Orders>(); orders.Add(new Orders() { OrderID = 1, CustomerID = "AIRG", Freight = 82.43M, OrderDate = new DateTime(2009, 05, 01) }); orders.Add(new Orders() { OrderID = 2, CustomerID = "JSYV", Freight = 12.22M, OrderDate = new DateTime(2009, 05, 02) }); //engine now supports custom EOL for writing engine.NewLineForWrite = "\n"; engine.WriteFile("Output.Txt", orders); //-> /File Console.WriteLine(engine.WriteString(orders)); } //-> The classes you use could come from anywhere: LINQ to Entities, SQL database reads, or in this case, classes created within an application. } }
mit
C#
b6c683e95be623f4fe2ae4f766da4b3ddaf2b8f4
Set the camera rotation
EightBitBoy/EcoRealms
Assets/Scripts/Camera/CameraMovement.cs
Assets/Scripts/Camera/CameraMovement.cs
using UnityEngine; using System.Collections; namespace ecorealms.camera { public class CameraMovement : MonoBehaviour { private Transform cameraTransform; private Vector3 startPosition = new Vector3(0.0f, 10.0f, -5.0f); private Quaternion startRotation = Quaternion.Euler(45.0f, 45.0f, 0.0f); void Start () { cameraTransform = Camera.main.transform; cameraTransform.position = startPosition; cameraTransform.rotation = startRotation; } void LateUpdate() { } } }
using UnityEngine; using System.Collections; namespace ecorealms.camera { public class CameraMovement : MonoBehaviour { private Vector3 startPosition = new Vector3(0.0f, 10.0f, -5.0f); private Transform cameraTransform; private Quaternion startRotation; void Start () { cameraTransform = Camera.main.transform; cameraTransform.position = startPosition; } void LateUpdate() { } } }
apache-2.0
C#
aec94c283d8f53f8f7605610bd4d5c8291a12138
Make DisposeMethodKind internal to avoid conflicts
pakdev/roslyn-analyzers,dotnet/roslyn-analyzers,mavasani/roslyn-analyzers,mavasani/roslyn-analyzers,dotnet/roslyn-analyzers,pakdev/roslyn-analyzers
src/Utilities/Compiler/DisposeMethodKind.cs
src/Utilities/Compiler/DisposeMethodKind.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Analyzer.Utilities { /// <summary> /// Describes different kinds of Dispose-like methods. /// </summary> internal enum DisposeMethodKind { /// <summary> /// Not a dispose-like method. /// </summary> None, /// <summary> /// An override of <see cref="System.IDisposable.Dispose"/>. /// </summary> Dispose, /// <summary> /// A virtual method named Dispose that takes a single Boolean parameter, as /// is used when implementing the standard Dispose pattern. /// </summary> DisposeBool, /// <summary> /// A method named DisposeAsync that has no parameters and returns Task. /// </summary> DisposeAsync, /// <summary> /// An overridden method named DisposeCoreAsync that takes a single Boolean parameter and returns Task, as /// is used when implementing the standard DisposeAsync pattern. /// </summary> DisposeCoreAsync, /// <summary> /// A method named Close on a type that implements <see cref="System.IDisposable"/>. /// </summary> Close } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Analyzer.Utilities { /// <summary> /// Describes different kinds of Dispose-like methods. /// </summary> public enum DisposeMethodKind { /// <summary> /// Not a dispose-like method. /// </summary> None, /// <summary> /// An override of <see cref="System.IDisposable.Dispose"/>. /// </summary> Dispose, /// <summary> /// A virtual method named Dispose that takes a single Boolean parameter, as /// is used when implementing the standard Dispose pattern. /// </summary> DisposeBool, /// <summary> /// A method named DisposeAsync that has no parameters and returns Task. /// </summary> DisposeAsync, /// <summary> /// An overridden method named DisposeCoreAsync that takes a single Boolean parameter and returns Task, as /// is used when implementing the standard DisposeAsync pattern. /// </summary> DisposeCoreAsync, /// <summary> /// A method named Close on a type that implements <see cref="System.IDisposable"/>. /// </summary> Close } }
mit
C#
21e8ab835769c5be5c66f16b241bdf6cb774b848
Return `ILive` from `ToLive` calls instead of realm-typed instance
ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu
osu.Game/Database/RealmObjectExtensions.cs
osu.Game/Database/RealmObjectExtensions.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using AutoMapper; using osu.Game.Input.Bindings; using Realms; namespace osu.Game.Database { public static class RealmObjectExtensions { private static readonly IMapper mapper = new MapperConfiguration(c => { c.ShouldMapField = fi => false; c.ShouldMapProperty = pi => pi.SetMethod != null && pi.SetMethod.IsPublic; c.CreateMap<RealmKeyBinding, RealmKeyBinding>(); }).CreateMapper(); /// <summary> /// Create a detached copy of the each item in the collection. /// </summary> /// <param name="items">A list of managed <see cref="RealmObject"/>s to detach.</param> /// <typeparam name="T">The type of object.</typeparam> /// <returns>A list containing non-managed copies of provided items.</returns> public static List<T> Detach<T>(this IEnumerable<T> items) where T : RealmObject { var list = new List<T>(); foreach (var obj in items) list.Add(obj.Detach()); return list; } /// <summary> /// Create a detached copy of the item. /// </summary> /// <param name="item">The managed <see cref="RealmObject"/> to detach.</param> /// <typeparam name="T">The type of object.</typeparam> /// <returns>A non-managed copy of provided item. Will return the provided item if already detached.</returns> public static T Detach<T>(this T item) where T : RealmObject { if (!item.IsManaged) return item; return mapper.Map<T>(item); } public static List<ILive<T>> ToLive<T>(this IEnumerable<T> realmList) where T : RealmObject, IHasGuidPrimaryKey { return realmList.Select(l => new RealmLive<T>(l)).Cast<ILive<T>>().ToList(); } public static ILive<T> ToLive<T>(this T realmObject) where T : RealmObject, IHasGuidPrimaryKey { return new RealmLive<T>(realmObject); } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; using AutoMapper; using osu.Game.Input.Bindings; using Realms; namespace osu.Game.Database { public static class RealmObjectExtensions { private static readonly IMapper mapper = new MapperConfiguration(c => { c.ShouldMapField = fi => false; c.ShouldMapProperty = pi => pi.SetMethod != null && pi.SetMethod.IsPublic; c.CreateMap<RealmKeyBinding, RealmKeyBinding>(); }).CreateMapper(); /// <summary> /// Create a detached copy of the each item in the collection. /// </summary> /// <param name="items">A list of managed <see cref="RealmObject"/>s to detach.</param> /// <typeparam name="T">The type of object.</typeparam> /// <returns>A list containing non-managed copies of provided items.</returns> public static List<T> Detach<T>(this IEnumerable<T> items) where T : RealmObject { var list = new List<T>(); foreach (var obj in items) list.Add(obj.Detach()); return list; } /// <summary> /// Create a detached copy of the item. /// </summary> /// <param name="item">The managed <see cref="RealmObject"/> to detach.</param> /// <typeparam name="T">The type of object.</typeparam> /// <returns>A non-managed copy of provided item. Will return the provided item if already detached.</returns> public static T Detach<T>(this T item) where T : RealmObject { if (!item.IsManaged) return item; return mapper.Map<T>(item); } public static List<RealmLive<T>> ToLive<T>(this IEnumerable<T> realmList) where T : RealmObject, IHasGuidPrimaryKey { return realmList.Select(l => new RealmLive<T>(l)).ToList(); } public static RealmLive<T> ToLive<T>(this T realmObject) where T : RealmObject, IHasGuidPrimaryKey { return new RealmLive<T>(realmObject); } } }
mit
C#
99ab22963763e51e3eef41830efdfdb4f89069eb
Improve resp. masters assignment
kirillkos/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net
JoinRpg.Domain/ClaimSourceExtensions.cs
JoinRpg.Domain/ClaimSourceExtensions.cs
 using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JoinRpg.DataModel; using JoinRpg.Helpers; namespace JoinRpg.Domain { public static class ClaimSourceExtensions { public static bool HasClaimForUser(this IClaimSource claimSource, int currentUserId) { return claimSource.Claims.OfUserActive(currentUserId).Any(); } [NotNull, ItemNotNull] public static IEnumerable<User> GetResponsibleMasters([NotNull] this IClaimSource @group, bool includeSelf = true) { if (@group == null) throw new ArgumentNullException(nameof(@group)); if (group.ResponsibleMasterUser != null && includeSelf) { return new[] {group.ResponsibleMasterUser}; } var candidates = new HashSet<CharacterGroup>(); var removedGroups = new HashSet<CharacterGroup>(); var lookupGroups = new HashSet<CharacterGroup>(group.ParentGroups); while (lookupGroups.Any()) { var currentGroup = lookupGroups.First(); lookupGroups.Remove(currentGroup); //Get next group if (removedGroups.Contains(currentGroup) || candidates.Contains(currentGroup)) { continue; } if (currentGroup.ResponsibleMasterUserId != null) { candidates.Add(currentGroup); removedGroups.AddRange(currentGroup.FlatTree(c => c.ParentGroups)); //Some group with set responsible master will shadow out all parents. } else { lookupGroups.AddRange(currentGroup.ParentGroups); } } return candidates.Except(removedGroups).Select(c => c.ResponsibleMasterUser); } private static void AddRange<T>(this ISet<T> set, IEnumerable<T> objectsToAdd) { foreach (var parentGroup in objectsToAdd) { set.Add(parentGroup); } } [NotNull] public static IEnumerable<CharacterGroup> GetParentGroups([CanBeNull] this IClaimSource @group) { return @group.FlatTree(g => g.ParentGroups, includeSelf: false).Cast<CharacterGroup>(); } public static bool HasActiveClaims(this IClaimSource characterGroup) { return characterGroup.Claims.Any(claim => claim.IsActive); } } }
 using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using JoinRpg.DataModel; using JoinRpg.Helpers; namespace JoinRpg.Domain { public static class ClaimSourceExtensions { public static bool HasClaimForUser(this IClaimSource claimSource, int currentUserId) { return claimSource.Claims.OfUserActive(currentUserId).Any(); } public static IEnumerable<User> GetResponsibleMasters(this IClaimSource @group, bool includeSelf = true) { if (group.ResponsibleMasterUser != null && includeSelf) { yield return group.ResponsibleMasterUser; yield break; } var directParents = group.ParentGroups.SelectMany(g => g.GetResponsibleMasters()).WhereNotNull().Distinct(); foreach (var directParent in directParents) { yield return directParent; } } [NotNull] public static IEnumerable<CharacterGroup> GetParentGroups([CanBeNull] this IClaimSource @group) { return @group.FlatTree(g => g.ParentGroups, false).Cast<CharacterGroup>(); } public static bool HasActiveClaims(this IClaimSource characterGroup) { return characterGroup.Claims.Any(claim => claim.IsActive); } } }
mit
C#
d72dcb3fdae7de475afdd042656e133b302f9aaa
Rename variable
appharbor/appharbor-cli
src/AppHarbor/Commands/LoginAuthCommand.cs
src/AppHarbor/Commands/LoginAuthCommand.cs
using System.IO; using RestSharp; using RestSharp.Contrib; namespace AppHarbor.Commands { [CommandHelp("Login to AppHarbor", alias: "login")] public class LoginAuthCommand : ICommand { private readonly IAccessTokenConfiguration _accessTokenConfiguration; private readonly IMaskedInput _maskedInput; private readonly TextReader _reader; private readonly TextWriter _writer; public LoginAuthCommand(IAccessTokenConfiguration accessTokenConfiguration, IMaskedInput maskedConsoleInput, TextReader reader, TextWriter writer) { _accessTokenConfiguration = accessTokenConfiguration; _maskedInput = maskedConsoleInput; _reader = reader; _writer = writer; } public void Execute(string[] arguments) { if (_accessTokenConfiguration.GetAccessToken() != null) { throw new CommandException("You're already logged in"); } _writer.Write("Username: "); var username = _reader.ReadLine(); _writer.Write("Password: "); var password = _maskedInput.Get(); var accessToken = GetAccessToken(username, password); _accessTokenConfiguration.SetAccessToken(accessToken); _writer.WriteLine("Successfully logged in as {0}", username); } public virtual string GetAccessToken(string username, string password) { //NOTE: Remove when merged into AppHarbor.NET library var restClient = new RestClient("https://appharbor-token-client.apphb.com"); var request = new RestRequest("/token", Method.POST); request.AddParameter("username", username); request.AddParameter("password", password); var response = restClient.Execute(request); var accessToken = HttpUtility.ParseQueryString(response.Content)["access_token"]; if (accessToken == null) { throw new CommandException("Couldn't log in. Try again"); } return accessToken; } } }
using System.IO; using RestSharp; using RestSharp.Contrib; namespace AppHarbor.Commands { [CommandHelp("Login to AppHarbor", alias: "login")] public class LoginAuthCommand : ICommand { private readonly IAccessTokenConfiguration _accessTokenConfiguration; private readonly IMaskedInput _maskedConsoleInput; private readonly TextReader _reader; private readonly TextWriter _writer; public LoginAuthCommand(IAccessTokenConfiguration accessTokenConfiguration, IMaskedInput maskedConsoleInput, TextReader reader, TextWriter writer) { _accessTokenConfiguration = accessTokenConfiguration; _maskedConsoleInput = maskedConsoleInput; _reader = reader; _writer = writer; } public void Execute(string[] arguments) { if (_accessTokenConfiguration.GetAccessToken() != null) { throw new CommandException("You're already logged in"); } _writer.Write("Username: "); var username = _reader.ReadLine(); _writer.Write("Password: "); var password = _maskedConsoleInput.Get(); var accessToken = GetAccessToken(username, password); _accessTokenConfiguration.SetAccessToken(accessToken); _writer.WriteLine("Successfully logged in as {0}", username); } public virtual string GetAccessToken(string username, string password) { //NOTE: Remove when merged into AppHarbor.NET library var restClient = new RestClient("https://appharbor-token-client.apphb.com"); var request = new RestRequest("/token", Method.POST); request.AddParameter("username", username); request.AddParameter("password", password); var response = restClient.Execute(request); var accessToken = HttpUtility.ParseQueryString(response.Content)["access_token"]; if (accessToken == null) { throw new CommandException("Couldn't log in. Try again"); } return accessToken; } } }
mit
C#
4c41bcb2ba3ed4ee0c6f381ca2dab7f9ec9ecd54
Make ScrollEvent a MouseEvent
DrabWeb/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework
osu.Framework/Input/Events/ScrollEvent.cs
osu.Framework/Input/Events/ScrollEvent.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Input.States; using OpenTK; namespace osu.Framework.Input.Events { /// <summary> /// An event representing a change of the mouse wheel. /// </summary> public class ScrollEvent : MouseEvent { public readonly Vector2 ScrollDelta; public readonly bool IsPrecise; public ScrollEvent(InputState state, Vector2 scrollDelta, bool isPrecise = false) : base(state) { ScrollDelta = scrollDelta; IsPrecise = isPrecise; } public override string ToString() => $"{GetType().ReadableName()}({ScrollDelta}, {IsPrecise})"; } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using osu.Framework.Extensions.TypeExtensions; using osu.Framework.Input.States; using OpenTK; namespace osu.Framework.Input.Events { /// <summary> /// An event representing a change of the mouse wheel. /// </summary> public class ScrollEvent : UIEvent { public readonly Vector2 ScrollDelta; public readonly bool IsPrecise; public ScrollEvent(InputState state, Vector2 scrollDelta, bool isPrecise = false) : base(state) { ScrollDelta = scrollDelta; IsPrecise = isPrecise; } public override string ToString() => $"{GetType().ReadableName()}({ScrollDelta}, {IsPrecise})"; } }
mit
C#
2857f892a3eda46d5568405c2487d01cdcf5e7ce
Remove some unnessary codes
insthync/LiteNetLibManager,insthync/LiteNetLibManager
Scripts/LiteNetLibServer.cs
Scripts/LiteNetLibServer.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using LiteNetLib; using LiteNetLib.Utils; using LiteNetLibHighLevel.Utils; namespace LiteNetLibHighLevel { public class LiteNetLibServer : INetEventListener { public LiteNetLibManager Manager { get; protected set; } public NetManager NetManager { get; protected set; } public LiteNetLibServer(LiteNetLibManager manager, int maxConnections, string connectKey) { Manager = manager; NetManager = new NetManager(this, maxConnections, connectKey); } public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode) { if (Manager.LogError) Debug.LogError("[" + Manager.name + "] LiteNetLibServer::OnNetworkError endPoint: " + endPoint + " socketErrorCode " + socketErrorCode); Manager.OnServerNetworkError(endPoint, socketErrorCode); } public void OnNetworkLatencyUpdate(NetPeer peer, int latency) { } public void OnNetworkReceive(NetPeer peer, NetDataReader reader) { Manager.ServerReadPacket(peer, reader); } public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType) { if (messageType == UnconnectedMessageType.DiscoveryRequest) Manager.OnServerReceivedDiscoveryRequest(remoteEndPoint, StringBytesConverter.ConvertToString(reader.Data)); } public void OnPeerConnected(NetPeer peer) { if (Manager.LogInfo) Debug.Log("[" + Manager.name + "] LiteNetLibServer::OnPeerConnected peer.ConnectId: " + peer.ConnectId); Manager.AddPeer(peer); Manager.OnServerConnected(peer); } public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { if (Manager.LogInfo) Debug.Log("[" + Manager.name + "] LiteNetLibServer::OnPeerDisconnected peer.ConnectId: " + peer.ConnectId + " disconnectInfo.Reason: " + disconnectInfo.Reason); Manager.RemovePeer(peer); Manager.OnServerDisconnected(peer, disconnectInfo); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using LiteNetLib; using LiteNetLib.Utils; using LiteNetLibHighLevel.Utils; namespace LiteNetLibHighLevel { public class LiteNetLibServer : INetEventListener { public LiteNetLibManager Manager { get; protected set; } public NetManager NetManager { get; protected set; } public LiteNetLibServer(LiteNetLibManager manager, int maxConnections, string connectKey) { this.Manager = manager; NetManager = new NetManager(this, maxConnections, connectKey); } public void OnNetworkError(NetEndPoint endPoint, int socketErrorCode) { if (Manager.LogError) Debug.LogError("[" + Manager.name + "] LiteNetLibServer::OnNetworkError endPoint: " + endPoint + " socketErrorCode " + socketErrorCode); Manager.OnServerNetworkError(endPoint, socketErrorCode); } public void OnNetworkLatencyUpdate(NetPeer peer, int latency) { } public void OnNetworkReceive(NetPeer peer, NetDataReader reader) { Manager.ServerReadPacket(peer, reader); } public void OnNetworkReceiveUnconnected(NetEndPoint remoteEndPoint, NetDataReader reader, UnconnectedMessageType messageType) { if (messageType == UnconnectedMessageType.DiscoveryRequest) Manager.OnServerReceivedDiscoveryRequest(remoteEndPoint, StringBytesConverter.ConvertToString(reader.Data)); } public void OnPeerConnected(NetPeer peer) { if (Manager.LogInfo) Debug.Log("[" + Manager.name + "] LiteNetLibServer::OnPeerConnected peer.ConnectId: " + peer.ConnectId); Manager.AddPeer(peer); Manager.OnServerConnected(peer); } public void OnPeerDisconnected(NetPeer peer, DisconnectInfo disconnectInfo) { if (Manager.LogInfo) Debug.Log("[" + Manager.name + "] LiteNetLibServer::OnPeerDisconnected peer.ConnectId: " + peer.ConnectId + " disconnectInfo.Reason: " + disconnectInfo.Reason); Manager.RemovePeer(peer); Manager.OnServerDisconnected(peer, disconnectInfo); } } }
mit
C#
6084fb1df79884be598b15b26e991e34cd1f7161
Add tests for Sha512 class
ektrah/nsec
tests/Algorithms/Sha512Tests.cs
tests/Algorithms/Sha512Tests.cs
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Algorithms { public static class Sha512Tests { public static readonly string HashOfEmpty = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; [Fact] public static void Properties() { var a = new Sha512(); Assert.Equal(32, a.MinHashSize); Assert.True(a.DefaultHashSize >= a.MinHashSize); Assert.True(a.MaxHashSize >= a.DefaultHashSize); Assert.Equal(64, a.MaxHashSize); } [Fact] public static void HashEmpty() { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty); Assert.Equal(a.DefaultHashSize, actual.Length); Assert.Equal(expected, actual); } [Theory] [InlineData(32)] [InlineData(41)] [InlineData(53)] [InlineData(61)] [InlineData(64)] public static void HashEmptyWithSize(int hashSize) { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex().Substring(0, hashSize); var actual = a.Hash(ReadOnlySpan<byte>.Empty, hashSize); Assert.Equal(hashSize, actual.Length); Assert.Equal(expected, actual); } [Theory] [InlineData(32)] [InlineData(41)] [InlineData(53)] [InlineData(61)] [InlineData(64)] public static void HashEmptyWithSpan(int hashSize) { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex().Substring(0, hashSize); var actual = new byte[hashSize]; a.Hash(ReadOnlySpan<byte>.Empty, actual); Assert.Equal(expected, actual); } } }
using System; using NSec.Cryptography; using Xunit; namespace NSec.Tests.Algorithms { public static class Sha512Tests { public static readonly string HashOfEmpty = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; [Fact] public static void HashEmpty() { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex(); var actual = a.Hash(ReadOnlySpan<byte>.Empty); Assert.Equal(a.DefaultHashSize, actual.Length); Assert.Equal(expected, actual); } [Theory] [InlineData(32)] [InlineData(41)] [InlineData(53)] [InlineData(61)] [InlineData(64)] public static void HashEmptyWithSize(int hashSize) { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex().Substring(0, hashSize); var actual = a.Hash(ReadOnlySpan<byte>.Empty, hashSize); Assert.Equal(hashSize, actual.Length); Assert.Equal(expected, actual); } [Theory] [InlineData(32)] [InlineData(41)] [InlineData(53)] [InlineData(61)] [InlineData(64)] public static void HashEmptyWithSpan(int hashSize) { var a = new Sha512(); var expected = HashOfEmpty.DecodeHex().Substring(0, hashSize); var actual = new byte[hashSize]; a.Hash(ReadOnlySpan<byte>.Empty, actual); Assert.Equal(expected, actual); } } }
mit
C#
fd39ab646271cb34db2ae638571227bf3a29c8ce
Increase HelenaZ jump power
bunashibu/kikan
Assets/Scripts/Skill/Helena/HelenaZ.cs
Assets/Scripts/Skill/Helena/HelenaZ.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UniRx; using UniRx.Triggers; namespace Bunashibu.Kikan { [RequireComponent(typeof(SkillSynchronizer))] public class HelenaZ : Skill { void Awake() { _synchronizer = GetComponent<SkillSynchronizer>(); _hitRistrictor = new HitRistrictor(_hitInfo); Observable.Timer(TimeSpan.FromSeconds(_existTime)) .Where(_ => this != null) .Subscribe(_ => { gameObject.SetActive(false); Observable.Timer(TimeSpan.FromSeconds(5.0f)) .Where(none => this != null) .Subscribe(none => { Destroy(gameObject); }); }); this.UpdateAsObservable() .Where(_ => _skillUserObj != null) .Where(_ => photonView.isMine) .Take(1) .Subscribe(_ => { var skillUser = _skillUserObj.GetComponent<Player>(); Vector2 direction = (skillUser.Renderers[0].flipX) ? Vector2.left : Vector2.right; _synchronizer.SyncForce(skillUser.PhotonView.viewID, _force, direction, false); }); Observable.Timer(TimeSpan.FromSeconds(_firstDamageTime)) .Subscribe(_ => { _attackInfo = new AttackInfo(_continuousDamagePercent, _attackInfo.MaxDeviation, _attackInfo.CriticalPercent); }); } void OnTriggerStay2D(Collider2D collider) { if (PhotonNetwork.isMasterClient) { var target = collider.gameObject.GetComponent<IPhoton>(); if (target == null) return; if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj)) return; if (_hitRistrictor.ShouldRistrict(collider.gameObject)) return; DamageCalculator.Calculate(_skillUserObj, _attackInfo); _synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena); } } [SerializeField] private AttackInfo _attackInfo; [SerializeField] private HitInfo _hitInfo; private SkillSynchronizer _synchronizer; private HitRistrictor _hitRistrictor; private float _existTime = 5.0f; private float _force = 20.0f; private int _continuousDamagePercent = 20; private float _firstDamageTime = 0.3f; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UniRx; using UniRx.Triggers; namespace Bunashibu.Kikan { [RequireComponent(typeof(SkillSynchronizer))] public class HelenaZ : Skill { void Awake() { _synchronizer = GetComponent<SkillSynchronizer>(); _hitRistrictor = new HitRistrictor(_hitInfo); Observable.Timer(TimeSpan.FromSeconds(_existTime)) .Where(_ => this != null) .Subscribe(_ => { gameObject.SetActive(false); Observable.Timer(TimeSpan.FromSeconds(5.0f)) .Where(none => this != null) .Subscribe(none => { Destroy(gameObject); }); }); this.UpdateAsObservable() .Where(_ => _skillUserObj != null) .Where(_ => photonView.isMine) .Take(1) .Subscribe(_ => { var skillUser = _skillUserObj.GetComponent<Player>(); Vector2 direction = (skillUser.Renderers[0].flipX) ? Vector2.left : Vector2.right; _synchronizer.SyncForce(skillUser.PhotonView.viewID, _force, direction, false); }); Observable.Timer(TimeSpan.FromSeconds(_firstDamageTime)) .Subscribe(_ => { _attackInfo = new AttackInfo(_continuousDamagePercent, _attackInfo.MaxDeviation, _attackInfo.CriticalPercent); }); } void OnTriggerStay2D(Collider2D collider) { if (PhotonNetwork.isMasterClient) { var target = collider.gameObject.GetComponent<IPhoton>(); if (target == null) return; if (TeamChecker.IsSameTeam(collider.gameObject, _skillUserObj)) return; if (_hitRistrictor.ShouldRistrict(collider.gameObject)) return; DamageCalculator.Calculate(_skillUserObj, _attackInfo); _synchronizer.SyncAttack(_skillUserViewID, target.PhotonView.viewID, DamageCalculator.Damage, DamageCalculator.IsCritical, HitEffectType.Helena); } } [SerializeField] private AttackInfo _attackInfo; [SerializeField] private HitInfo _hitInfo; private SkillSynchronizer _synchronizer; private HitRistrictor _hitRistrictor; private float _existTime = 5.0f; private float _force = 15.0f; private int _continuousDamagePercent = 20; private float _firstDamageTime = 0.3f; } }
mit
C#
2f255a12b5e0132199bff99602eb5cbc54afb1c9
Fix comments/documentation.
MatthewKing/DeviceId
src/DeviceId/Formatters/StringDeviceIdFormatter.cs
src/DeviceId/Formatters/StringDeviceIdFormatter.cs
using System; using System.Collections.Generic; using System.Linq; namespace DeviceId.Formatters { /// <summary> /// An implementation of <see cref="IDeviceIdFormatter"/> that combines the components into a concatenated string. /// </summary> public class StringDeviceIdFormatter : IDeviceIdFormatter { /// <summary> /// The <see cref="IDeviceIdComponentEncoder"/> instance to use to encode individual components. /// </summary> private readonly IDeviceIdComponentEncoder _encoder; /// <summary> /// The delimiter to use when concatenating the encoded component values. /// </summary> private readonly string _delimiter; /// <summary> /// Initializes a new instance of the <see cref="StringDeviceIdFormatter"/> class. /// </summary> /// <param name="encoder">The <see cref="IDeviceIdComponentEncoder"/> instance to use to encode individual components.</param> public StringDeviceIdFormatter(IDeviceIdComponentEncoder encoder) : this(encoder, ".") { } /// <summary> /// Initializes a new instance of the <see cref="StringDeviceIdFormatter"/> class. /// </summary> /// <param name="encoder">The <see cref="IDeviceIdComponentEncoder"/> instance to use to encode individual components.</param> /// <param name="delimiter">The delimiter to use when concatenating the encoded component values.</param> public StringDeviceIdFormatter(IDeviceIdComponentEncoder encoder, string delimiter) { _encoder = encoder ?? throw new ArgumentNullException(nameof(encoder)); _delimiter = delimiter; } /// <summary> /// Returns the device identifier string created by combining the specified <see cref="IDeviceIdComponent"/> instances. /// </summary> /// <param name="components">A sequence containing the <see cref="IDeviceIdComponent"/> instances to combine into the device identifier string.</param> /// <returns>The device identifier string.</returns> public string GetDeviceId(IEnumerable<IDeviceIdComponent> components) { if (components == null) { throw new ArgumentNullException(nameof(components)); } return string.Join(_delimiter, components.OrderBy(x => x.Name).Select(x => _encoder.Encode(x)).ToArray()); } } }
using System; using System.Collections.Generic; using System.Linq; namespace DeviceId.Formatters { /// <summary> /// An implementation of <see cref="IDeviceIdFormatter"/> that combines the components into a concatenated string. /// </summary> public class StringDeviceIdFormatter : IDeviceIdFormatter { /// <summary> /// The <see cref="IDeviceIdComponentEncoder"/> instance to use to encode individual components. /// </summary> private readonly IDeviceIdComponentEncoder _encoder; /// <summary> /// The delimiter to use when concatenating the encoded component values. /// </summary> private readonly string _delimiter; /// <summary> /// Initializes a new instance of the <see cref="XmlDeviceIdFormatter"/> class. /// </summary> /// <param name="encoder">The <see cref="IDeviceIdComponentEncoder"/> instance to use to encode individual components.</param> public StringDeviceIdFormatter(IDeviceIdComponentEncoder encoder) : this(encoder, ".") { } /// <summary> /// Initializes a new instance of the <see cref="XmlDeviceIdFormatter"/> class. /// </summary> /// <param name="encoder">The <see cref="IDeviceIdComponentEncoder"/> instance to use to encode individual components.</param> /// <param name="delimiter">The delimiter to use when concatenating the encoded component values.</param> public StringDeviceIdFormatter(IDeviceIdComponentEncoder encoder, string delimiter) { _encoder = encoder ?? throw new ArgumentNullException(nameof(encoder)); _delimiter = delimiter; } /// <summary> /// Returns the device identifier string created by combining the specified <see cref="IDeviceIdComponent"/> instances. /// </summary> /// <param name="components">A sequence containing the <see cref="IDeviceIdComponent"/> instances to combine into the device identifier string.</param> /// <returns>The device identifier string.</returns> public string GetDeviceId(IEnumerable<IDeviceIdComponent> components) { if (components == null) { throw new ArgumentNullException(nameof(components)); } return string.Join(_delimiter, components.OrderBy(x => x.Name).Select(x => _encoder.Encode(x)).ToArray()); } } }
mit
C#