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
04004d67fe341d4f8a6bd7f8f8a2f6e14663c77f
teste f
Thiago-Caramelo/patchsearch
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PatchSearch { // teste teste class Program { static void Main(string[] args) { if (args == null || args.Length == 0) { return; } // obter todos os arquivos da pasta string[] files = Directory.GetFiles(Directory.GetCurrentDirectory()); foreach (var item in files) //teste { using (StreamReader reader = new StreamReader(item)) // teste f { string fileContent = reader.ReadToEnd(); int qt = 0;//teste 7 foreach (var term in args) { if (fileContent.Contains(term)) { qt++; } } if (qt == args.Length) { Console.WriteLine(Path.GetFileName(item)); } } } } } } //teste c //teste d
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PatchSearch { // teste teste class Program { static void Main(string[] args) { if (args == null || args.Length == 0) { return; } // obter todos os arquivos da pasta string[] files = Directory.GetFiles(Directory.GetCurrentDirectory()); foreach (var item in files) //teste { using (StreamReader reader = new StreamReader(item)) { string fileContent = reader.ReadToEnd(); int qt = 0;//teste 7 foreach (var term in args) { if (fileContent.Contains(term)) { qt++; } } if (qt == args.Length) { Console.WriteLine(Path.GetFileName(item)); } } } } } } //teste c //teste d
mit
C#
aae8d420eb6b62e44a7492e2d9574b0c56bca2ef
Bump version.
kyourek/Pagination,kyourek/Pagination,kyourek/Pagination
sln/AssemblyVersion.cs
sln/AssemblyVersion.cs
using System.Reflection; [assembly: AssemblyVersion("2.0.2")]
using System.Reflection; [assembly: AssemblyVersion("2.0.1.1")]
mit
C#
ab601fe8c066861d5f2e931d28091694761a5145
Test change reverted.
pushrbx/squidex,pushrbx/squidex,pushrbx/squidex,Squidex/squidex,Squidex/squidex,pushrbx/squidex,pushrbx/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex
src/Squidex.Infrastructure/Validate.cs
src/Squidex.Infrastructure/Validate.cs
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Squidex.Infrastructure { public static class Validate { public static void It(Func<string> message, Action<Action<ValidationError>> action) { var errors = new List<ValidationError>(); action(errors.Add); if (errors.Any()) { throw new ValidationException(message(), errors); } } public static async Task It(Func<string> message, Func<Action<ValidationError>, Task> action) { var errors = new List<ValidationError>(); await action(errors.Add); if (errors.Any()) { throw new ValidationException(message(), errors); } } } }
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschränkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Squidex.Infrastructure { public static class Validate { public static void It(Func<string> message, Action<Action<ValidationError>> action, IReadOnlyDictionary<string, string> messages = null) { var errors = new List<ValidationError>(); action(errors.Add); if (errors.Any()) { throw new ValidationException(message(), errors); } } public static async Task It(Func<string> message, Func<Action<ValidationError>, Task> action, IReadOnlyDictionary<string, string> messages = null) { var errors = new List<ValidationError>(); await action(errors.Add); if (errors.Any()) { throw new ValidationException(message(), errors); } } } }
mit
C#
477c5ce7a4c99e0ac25764f1a9b0428fc6d72ae5
Improve code documentation in the IAnchorBuilder interface
openchain/openchain
src/Openchain.Ledger/IAnchorBuilder.cs
src/Openchain.Ledger/IAnchorBuilder.cs
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Threading.Tasks; namespace Openchain.Ledger { /// <summary> /// Provides functionality for creating a database anchor. /// </summary> public interface IAnchorBuilder { /// <summary> /// Initializes the instance. /// </summary> /// <returns>The task object representing the asynchronous operation.</returns> Task Initialize(); /// <summary> /// Creates a database anchor for the current state of the database. /// </summary> /// <param name="storageEngine">The source of transactions to use.</param> /// <returns>The task object representing the asynchronous operation.</returns> Task<LedgerAnchor> CreateAnchor(IStorageEngine storageEngine); /// <summary> /// Marks the anchor as successfully recorded in the anchoring medium. /// </summary> /// <param name="anchor">The anchor to commit.</param> /// <returns>The task object representing the asynchronous operation.</returns> Task CommitAnchor(LedgerAnchor anchor); } }
// Copyright 2015 Coinprism, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Threading.Tasks; namespace Openchain.Ledger { /// <summary> /// Provides functionality for creating a database anchor. /// </summary> public interface IAnchorBuilder { Task Initialize(); /// <summary> /// Creates a database anchor for the current state of the database. /// </summary> /// <returns>The task object representing the asynchronous operation.</returns> Task<LedgerAnchor> CreateAnchor(IStorageEngine storageEngine); /// <summary> /// Marks the anchor as successfully recorded in the anchoring medium. /// </summary> /// <param name="anchor">The anchor to commit.</param> /// <returns>The task object representing the asynchronous operation.</returns> Task CommitAnchor(LedgerAnchor anchor); } }
apache-2.0
C#
1513a68353c2a573201cd5057bd1ba23e5e07a65
Remove dlls from startup check.
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
osu!StreamCompanion/Code/Misc/FileChecker.cs
osu!StreamCompanion/Code/Misc/FileChecker.cs
using System; using System.IO; using System.Windows.Forms; namespace osu_StreamCompanion.Code.Misc { class FileChecker { private string[] _requiredFiles = new string[0]; private string caption = "StreamCompanion Error"; private string errorMessage = "It seems that you are missing one or more of the files that are required to run this software." + Environment.NewLine + "Place all downloaded files in a single folder then try running it again." + Environment.NewLine + "Couldn't find: \"{0}\"" + Environment.NewLine + "StreamCompanion will now exit."; public FileChecker() { foreach (var requiredFile in _requiredFiles) { if (!File.Exists(requiredFile)) { MessageBox.Show(string.Format(errorMessage, requiredFile), caption, MessageBoxButtons.OK, MessageBoxIcon.Error); Program.SafeQuit(); } } } } }
using System; using System.IO; using System.Windows.Forms; namespace osu_StreamCompanion.Code.Misc { class FileChecker { private string[] _requiredFiles = new[] { "SQLite.Interop.dll", "System.Data.SQLite.dll" }; private string caption = "StreamCompanion Error"; private string errorMessage = "It seems that you are missing one or more of the files that are required to run this software." + Environment.NewLine + "Place all downloaded files in a single folder then try running it again." + Environment.NewLine + "Couldn't find: \"{0}\"" + Environment.NewLine + "StreamCompanion will now exit."; public FileChecker() { foreach (var requiredFile in _requiredFiles) { if (!File.Exists(requiredFile)) { MessageBox.Show(string.Format(errorMessage, requiredFile), caption, MessageBoxButtons.OK, MessageBoxIcon.Error); Program.SafeQuit(); } } } } }
mit
C#
62d0036c819c0516005f9b5b3938d359e0cac987
Fix using private constructor on MessagePack object
UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu-new,peppy/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,NeoAdonis/osu
osu.Game/Online/Rooms/BeatmapAvailability.cs
osu.Game/Online/Rooms/BeatmapAvailability.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Rooms { /// <summary> /// The local availability information about a certain beatmap for the client. /// </summary> [MessagePackObject] public class BeatmapAvailability : IEquatable<BeatmapAvailability> { /// <summary> /// The beatmap's availability state. /// </summary> [Key(0)] public readonly DownloadState State; /// <summary> /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state. /// </summary> [Key(1)] public readonly float? DownloadProgress; [JsonConstructor] public BeatmapAvailability(DownloadState state, float? downloadProgress = null) { State = state; DownloadProgress = downloadProgress; } public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded); public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress); public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing); public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable); public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress; public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using MessagePack; using Newtonsoft.Json; namespace osu.Game.Online.Rooms { /// <summary> /// The local availability information about a certain beatmap for the client. /// </summary> [MessagePackObject] public class BeatmapAvailability : IEquatable<BeatmapAvailability> { /// <summary> /// The beatmap's availability state. /// </summary> [Key(0)] public readonly DownloadState State; /// <summary> /// The beatmap's downloading progress, null when not in <see cref="DownloadState.Downloading"/> state. /// </summary> [Key(1)] public readonly float? DownloadProgress; [JsonConstructor] private BeatmapAvailability(DownloadState state, float? downloadProgress = null) { State = state; DownloadProgress = downloadProgress; } public static BeatmapAvailability NotDownloaded() => new BeatmapAvailability(DownloadState.NotDownloaded); public static BeatmapAvailability Downloading(float progress) => new BeatmapAvailability(DownloadState.Downloading, progress); public static BeatmapAvailability Importing() => new BeatmapAvailability(DownloadState.Importing); public static BeatmapAvailability LocallyAvailable() => new BeatmapAvailability(DownloadState.LocallyAvailable); public bool Equals(BeatmapAvailability other) => other != null && State == other.State && DownloadProgress == other.DownloadProgress; public override string ToString() => $"{string.Join(", ", State, $"{DownloadProgress:0.00%}")}"; } }
mit
C#
aa875fa4557fa9c0f11f8df447291ef1959837b4
Apply patch Background isn't drawn when using a single char
ForNeVeR/wpf-math
WpfMath/CharBox.cs
WpfMath/CharBox.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media; namespace WpfMath { // Box representing single character. internal class CharBox : Box { public CharBox(TexEnvironment environment, CharInfo charInfo) : base(environment) { this.Character = charInfo; this.Width = charInfo.Metrics.Width; this.Height = charInfo.Metrics.Height; this.Depth = charInfo.Metrics.Depth; } public CharInfo Character { get; private set; } private GlyphRun GetGlyphRun(double scale, double x, double y) { var typeface = this.Character.Font; var glyphIndex = typeface.CharacterToGlyphMap[this.Character.Character]; var glyphRun = new GlyphRun(typeface, 0, false, this.Character.Size * scale, new ushort[] { glyphIndex }, new Point(x * scale, y * scale), new double[] { typeface.AdvanceWidths[glyphIndex] }, null, null, null, null, null, null); return glyphRun; } public override void Draw(DrawingContext drawingContext, double scale, double x, double y) { base.Draw(drawingContext, scale, x, y); GlyphRun glyphRun = GetGlyphRun(scale, x, y); // Draw character at given position. drawingContext.DrawGlyphRun(this.Foreground ?? Brushes.Black, glyphRun); } public override void RenderGeometry(GeometryGroup geometry, double scale, double x, double y) { GlyphRun glyphRun = GetGlyphRun(scale, x, y); GeometryGroup geoGroup = glyphRun.BuildGeometry() as GeometryGroup; PathGeometry pg = geoGroup.GetFlattenedPathGeometry(); geometry.Children.Add(pg); } public override int GetLastFontId() { return this.Character.FontId; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Media; namespace WpfMath { // Box representing single character. internal class CharBox : Box { public CharBox(TexEnvironment environment, CharInfo charInfo) : base(environment) { this.Character = charInfo; this.Width = charInfo.Metrics.Width; this.Height = charInfo.Metrics.Height; this.Depth = charInfo.Metrics.Depth; } public CharInfo Character { get; private set; } private GlyphRun GetGlyphRun(double scale, double x, double y) { var typeface = this.Character.Font; var glyphIndex = typeface.CharacterToGlyphMap[this.Character.Character]; var glyphRun = new GlyphRun(typeface, 0, false, this.Character.Size * scale, new ushort[] { glyphIndex }, new Point(x * scale, y * scale), new double[] { typeface.AdvanceWidths[glyphIndex] }, null, null, null, null, null, null); return glyphRun; } public override void Draw(DrawingContext drawingContext, double scale, double x, double y) { GlyphRun glyphRun = GetGlyphRun(scale, x, y); // Draw character at given position. drawingContext.DrawGlyphRun(this.Foreground ?? Brushes.Black, glyphRun); } public override void RenderGeometry(GeometryGroup geometry, double scale, double x, double y) { GlyphRun glyphRun = GetGlyphRun(scale, x, y); GeometryGroup geoGroup = glyphRun.BuildGeometry() as GeometryGroup; PathGeometry pg = geoGroup.GetFlattenedPathGeometry(); geometry.Children.Add(pg); } public override int GetLastFontId() { return this.Character.FontId; } } }
mit
C#
ca3a520a1d28126060b7687c986614b724d5672d
Fix backtick logic for explicitly implemented non-generic members of generic interfaces.
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
service/DotNetApis.Common/StringExtensions.cs
service/DotNetApis.Common/StringExtensions.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetApis.Common { public static class StringExtensions { /// <summary> /// @-encodes a string to a specific alphabet. /// </summary> /// <param name="text">The string.</param> /// <param name="alphabet">The alphabet of allowed characters.</param> public static string AtEncode(this string text, char[] alphabet) { // First to a quick check to avoid allocating a new string. if (text.IndexOfAny(alphabet) == -1) return text; var sb = new StringBuilder(text.Length); var bytes = Constants.Utf8.GetBytes(text); foreach (var b in bytes) { if (alphabet.Contains((char)b)) sb.Append((char)b); else sb.Append("@" + b.ToString("X2", CultureInfo.InvariantCulture)); } return sb.ToString(); } /// <summary> /// Removes the backtick suffix (if any) of the string. Works for double-backtick suffixed strings as well. /// </summary> public static (string Name, int Value) StripBacktickSuffix(this string s) { var backtickIndex = s.LastIndexOf('`'); if (backtickIndex == -1 || backtickIndex < s.LastIndexOf('.')) return (s, 0); return (s.Substring(0, backtickIndex), int.Parse(s.Substring(s.LastIndexOf('`') + 1), CultureInfo.InvariantCulture)); } /// <summary> /// Trims whitespace at the beginning and end of a string, but keeps a single space at the beginning and end if they previously had whitespace. /// </summary> public static string MinimizeWhitespace(this string source) { if (source == string.Empty) return source; var begin = char.IsWhiteSpace(source[0]) ? " " : string.Empty; var end = char.IsWhiteSpace(source[source.Length - 1]) ? " " : string.Empty; return begin + source.Trim() + end; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DotNetApis.Common { public static class StringExtensions { /// <summary> /// @-encodes a string to a specific alphabet. /// </summary> /// <param name="text">The string.</param> /// <param name="alphabet">The alphabet of allowed characters.</param> public static string AtEncode(this string text, char[] alphabet) { // First to a quick check to avoid allocating a new string. if (text.IndexOfAny(alphabet) == -1) return text; var sb = new StringBuilder(text.Length); var bytes = Constants.Utf8.GetBytes(text); foreach (var b in bytes) { if (alphabet.Contains((char)b)) sb.Append((char)b); else sb.Append("@" + b.ToString("X2", CultureInfo.InvariantCulture)); } return sb.ToString(); } /// <summary> /// Removes the backtick suffix (if any) of the string. Works for double-backtick suffixed strings as well. /// </summary> public static (string Name, int Value) StripBacktickSuffix(this string s) { var backtickIndex = s.IndexOf('`'); if (backtickIndex == -1) return (s, 0); return (s.Substring(0, backtickIndex), int.Parse(s.Substring(s.LastIndexOf('`') + 1), CultureInfo.InvariantCulture)); } /// <summary> /// Trims whitespace at the beginning and end of a string, but keeps a single space at the beginning and end if they previously had whitespace. /// </summary> public static string MinimizeWhitespace(this string source) { if (source == string.Empty) return source; var begin = char.IsWhiteSpace(source[0]) ? " " : string.Empty; var end = char.IsWhiteSpace(source[source.Length - 1]) ? " " : string.Empty; return begin + source.Trim() + end; } } }
mit
C#
f45cfbe50a7e5054be52b42673396b47ebe26cc5
Document the sad reality that it is not possible to run tests on 3.5 anymore
jberezanski/PSKnownFolders
BlaSoft.PowerShell.KnownFolders.Tests/PowerShellTestBase.cs
BlaSoft.PowerShell.KnownFolders.Tests/PowerShellTestBase.cs
using System; using System.Collections; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; #if FX40 namespace BlaSoft.PowerShell.KnownFolders.Tests.Fx40 #else namespace BlaSoft.PowerShell.KnownFolders.Tests #endif { using System.Management.Automation; public abstract class PowerShellTestBase { protected PowerShellTestBase() { } protected static void AssertPowerShellIsExpectedVersion() { using (var psh = PowerShell.Create()) { var output = psh.AddScript("$PSVersionTable").Invoke(); Assert.IsNotNull(output); Assert.AreEqual(1, output.Count); var psObj = output.First(); Assert.IsNotNull(psObj); Assert.IsInstanceOfType(psObj.BaseObject, typeof(Hashtable)); var table = (Hashtable)psObj.BaseObject; Assert.IsTrue(table.ContainsKey("PSVersion")); var psVersion = (Version)table["PSVersion"]; Assert.IsTrue(table.ContainsKey("CLRVersion")); var clrVersion = (Version)table["CLRVersion"]; #if FX40 Assert.AreEqual(4, clrVersion.Major, "Unexpected CLR version."); Assert.AreNotEqual(2, psVersion.Major, "Unexpected PowerShell version."); Assert.AreNotEqual(1, psVersion.Major, "Unexpected PowerShell version."); #else Assert.AreEqual(2, clrVersion.Major, "This test project requires CLR 2.0. Older Visual Studio will use CLR 4 if running tests from .NET 3.5 and 4.0 projects together; to work around this, run tests from this project separately from other test projects. Modern Visual Studio does not support running tests under .NET 3.5 at all (https://github.com/Microsoft/vstest/issues/1896), sorry."); Assert.AreEqual(2, psVersion.Major, "Unexpected PowerShell version."); #endif } } } }
using System; using System.Collections; using System.Linq; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; #if FX40 namespace BlaSoft.PowerShell.KnownFolders.Tests.Fx40 #else namespace BlaSoft.PowerShell.KnownFolders.Tests #endif { using System.Management.Automation; public abstract class PowerShellTestBase { protected PowerShellTestBase() { } protected static void AssertPowerShellIsExpectedVersion() { using (var psh = PowerShell.Create()) { var output = psh.AddScript("$PSVersionTable").Invoke(); Assert.IsNotNull(output); Assert.AreEqual(1, output.Count); var psObj = output.First(); Assert.IsNotNull(psObj); Assert.IsInstanceOfType(psObj.BaseObject, typeof(Hashtable)); var table = (Hashtable)psObj.BaseObject; Assert.IsTrue(table.ContainsKey("PSVersion")); var psVersion = (Version)table["PSVersion"]; Assert.IsTrue(table.ContainsKey("CLRVersion")); var clrVersion = (Version)table["CLRVersion"]; #if FX40 Assert.AreEqual(4, clrVersion.Major, "Unexpected CLR version."); Assert.AreNotEqual(2, psVersion.Major, "Unexpected PowerShell version."); Assert.AreNotEqual(1, psVersion.Major, "Unexpected PowerShell version."); #else Assert.AreEqual(2, clrVersion.Major, "This test project requires CLR 2.0. Visual Studio will use CLR 4 if running tests from .NET 3.5 and 4.0 projects together. To work around this, run tests from this project separately from other test projects."); Assert.AreEqual(2, psVersion.Major, "Unexpected PowerShell version."); #endif } } } }
mit
C#
886297b3e26acb31e3f379dc98400544ebc47e37
Update SebastianFeldmann.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/SebastianFeldmann.cs
src/Firehose.Web/Authors/SebastianFeldmann.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class SebastianFeldmann : IAmACommunityMember { public string FirstName => "Sebastian"; public string LastName => "Feldmann"; public string ShortBioOrTagLine => "dad, musician, sysadmin"; public string StateOrRegion => "Bremen, Germany"; public string EmailAddress => "sebastian@feldmann.io"; public string TwitterHandle => "sebfieldman"; public string GravatarHash => "36fca3ceda7415942ff31f2bad2a8e62"; public string GitHubHandle => "seebus"; public GeoPosition Position => new GeoPosition(53.073635, 8.806422); public Uri WebSite => new Uri("https://blog.feldmann.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.feldmann.io/feed/"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class SebastianFeldmann : IAmACommunityMember { public string FirstName => "Sebastian"; public string LastName => "Feldmann"; public string ShortBioOrTagLine => "dad, musician, sysadmin"; public string StateOrRegion => "Bremen, Germany"; public string EmailAddress => "sebastian@feldmann.io"; public string TwitterHandle => "sebfieldman"; public string GravatarHash => ""; public string GitHubHandle => "seebus"; public GeoPosition Position => new GeoPosition(53.073635, 8.806422); public Uri WebSite => new Uri("https://blog.feldmann.io/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.feldmann.io/feed/"); } } public string FeedLanguageCode => "en"; } }
mit
C#
ab74570bff877cc3e81e95256a9c4b453534e37b
Remove white space
ASP-NET-Core-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework,ASP-NET-MVC-Boilerplate/Framework,ASP-NET-Core-Boilerplate/Framework
Source/Boilerplate.AspNetCore/ContentType.cs
Source/Boilerplate.AspNetCore/ContentType.cs
namespace Boilerplate.AspNetCore { /// <summary> /// A list of internet media types, which are a standard identifier used on the Internet to indicate the type of /// data that a file contains. Web browsers use them to determine how to display, output or handle files and search /// engines use them to classify data files on the web. /// </summary> public static class ContentType { /// <summary>Atom feeds.</summary> public const string Atom = "application/atom+xml"; /// <summary>HTML; Defined in RFC 2854.</summary> public const string Html = "text/html"; /// <summary>Form URL Encoded.</summary> public const string FormUrlEncoded = "application/x-www-form-urlencoded"; /// <summary>GIF image; Defined in RFC 2045 and RFC 2046.</summary> public const string Gif = "image/gif"; /// <summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046.</summary> public const string Jpg = "image/jpeg"; /// <summary>JavaScript Object Notation JSON; Defined in RFC 4627.</summary> public const string Json = "application/json"; /// <summary>Web App Manifest.</summary> public const string Manifest = "application/manifest+json"; /// <summary>Multi-part form daata; Defined in RFC 2388.</summary> public const string MultipartFormData = "multipart/form-data"; /// <summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083.</summary> public const string Png = "image/png"; /// <summary>Rich Site Summary; Defined by Harvard Law.</summary> public const string Rss = "application/rss+xml"; /// <summary>Textual data; Defined in RFC 2046 and RFC 3676.</summary> public const string Text = "text/plain"; /// <summary>Extensible Markup Language; Defined in RFC 3023</summary> public const string Xml = "application/xml"; /// <summary>Compressed ZIP.</summary> public const string Zip = "application/zip"; } }
namespace Boilerplate.AspNetCore { /// <summary> /// A list of internet media types, which are a standard identifier used on the Internet to indicate the type of /// data that a file contains. Web browsers use them to determine how to display, output or handle files and search /// engines use them to classify data files on the web. /// </summary> public static class ContentType { /// <summary>Atom feeds.</summary> public const string Atom = "application/atom+xml"; /// <summary>HTML; Defined in RFC 2854.</summary> public const string Html = "text/html"; /// <summary>Form URL Encoded.</summary> public const string FormUrlEncoded = "application/x-www-form-urlencoded"; /// <summary>GIF image; Defined in RFC 2045 and RFC 2046.</summary> public const string Gif = "image/gif"; /// <summary>JPEG JFIF image; Defined in RFC 2045 and RFC 2046.</summary> public const string Jpg = "image/jpeg"; /// <summary>JavaScript Object Notation JSON; Defined in RFC 4627.</summary> public const string Json = "application/json"; /// <summary>Web App Manifest.</summary> public const string Manifest = "application/manifest+json"; /// <summary>Multi-part form daata; Defined in RFC 2388.</summary> public const string MultipartFormData = "multipart/form-data"; /// <summary>Portable Network Graphics; Registered,[8] Defined in RFC 2083.</summary> public const string Png = "image/png"; /// <summary>Rich Site Summary; Defined by Harvard Law.</summary> public const string Rss = "application/rss+xml"; /// <summary>Textual data; Defined in RFC 2046 and RFC 3676.</summary> public const string Text = "text/plain"; /// <summary>Extensible Markup Language; Defined in RFC 3023</summary> public const string Xml = "application/xml"; /// <summary>Compressed ZIP.</summary> public const string Zip = "application/zip"; } }
mit
C#
4610f9c96261b3340f9a78ac0f4709713b74d294
Update GLTFExportMenu.cs (#338)
robertlong/UnityGLTFLoader,AltspaceVR/UnityGLTF
UnityGLTF/Assets/UnityGLTF/Scripts/Editor/GLTFExportMenu.cs
UnityGLTF/Assets/UnityGLTF/Scripts/Editor/GLTFExportMenu.cs
using System; using UnityEditor; using UnityGLTF; using UnityEngine; using UnityEngine.SceneManagement; public class GLTFExportMenu : EditorWindow { public static string RetrieveTexturePath(UnityEngine.Texture texture) { return AssetDatabase.GetAssetPath(texture); } [MenuItem("GLTF/Settings")] static void Init() { GLTFExportMenu window = (GLTFExportMenu)EditorWindow.GetWindow(typeof(GLTFExportMenu), false, "GLTF Settings"); window.Show(); } void OnGUI() { EditorGUILayout.LabelField("Exporter", EditorStyles.boldLabel); GLTFSceneExporter.ExportFullPath = EditorGUILayout.Toggle("Export using original path", GLTFSceneExporter.ExportFullPath); GLTFSceneExporter.ExportNames = EditorGUILayout.Toggle("Export names of nodes", GLTFSceneExporter.ExportNames); GLTFSceneExporter.RequireExtensions= EditorGUILayout.Toggle("Require extensions", GLTFSceneExporter.RequireExtensions); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Importer", EditorStyles.boldLabel); EditorGUILayout.Separator(); EditorGUILayout.HelpBox("UnityGLTF version 0.1", MessageType.Info); EditorGUILayout.HelpBox("Supported extensions: KHR_material_pbrSpecularGlossiness, ExtTextureTransform", MessageType.Info); } [MenuItem("GLTF/Export Selected")] static void ExportSelected() { string name; if (Selection.transforms.Length > 1) name = SceneManager.GetActiveScene().name; else if (Selection.transforms.Length == 1) name = Selection.activeGameObject.name; else throw new Exception("No objects selected, cannot export."); var exporter = new GLTFSceneExporter(Selection.transforms, RetrieveTexturePath); var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", ""); if (!string.IsNullOrEmpty(path)) { exporter.SaveGLTFandBin (path, name); } } [MenuItem("GLTF/ExportGLB Selected")] static void ExportGLBSelected() { string name; if (Selection.transforms.Length > 1) name = SceneManager.GetActiveScene().name; else if (Selection.transforms.Length == 1) name = Selection.activeGameObject.name; else throw new Exception("No objects selected, cannot export."); var exporter = new GLTFSceneExporter(Selection.transforms, RetrieveTexturePath); var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", ""); if (!string.IsNullOrEmpty(path)) { exporter.SaveGLB(path, name); } } [MenuItem("GLTF/Export Scene")] static void ExportScene() { var scene = SceneManager.GetActiveScene(); var gameObjects = scene.GetRootGameObjects(); var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform); var exporter = new GLTFSceneExporter(transforms, RetrieveTexturePath); var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", ""); if (path != "") { exporter.SaveGLTFandBin (path, scene.name); } } }
using System; using UnityEditor; using UnityGLTF; using UnityEngine; using UnityEngine.SceneManagement; public class GLTFExportMenu : EditorWindow { public static string RetrieveTexturePath(UnityEngine.Texture texture) { return AssetDatabase.GetAssetPath(texture); } [MenuItem("GLTF/Settings")] static void Init() { GLTFExportMenu window = (GLTFExportMenu)EditorWindow.GetWindow(typeof(GLTFExportMenu), false, "GLTF Settings"); window.Show(); } void OnGUI() { EditorGUILayout.LabelField("Exporter", EditorStyles.boldLabel); GLTFSceneExporter.ExportFullPath = EditorGUILayout.Toggle("Export using original path", GLTFSceneExporter.ExportFullPath); GLTFSceneExporter.ExportNames = EditorGUILayout.Toggle("Export names of nodes", GLTFSceneExporter.ExportNames); GLTFSceneExporter.RequireExtensions= EditorGUILayout.Toggle("Require extensions", GLTFSceneExporter.RequireExtensions); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Importer", EditorStyles.boldLabel); EditorGUILayout.Separator(); EditorGUILayout.HelpBox("UnityGLTF version 0.1", MessageType.Info); EditorGUILayout.HelpBox("Supported extensions: KHR_material_pbrSpecularGlossiness, ExtTextureTransform", MessageType.Info); } [MenuItem("GLTF/Export Selected")] static void ExportSelected() { string name; if (Selection.transforms.Length > 1) name = SceneManager.GetActiveScene().name; else if (Selection.transforms.Length == 1) name = Selection.activeGameObject.name; else throw new Exception("No objects selected, cannot export."); var exporter = new GLTFSceneExporter(Selection.transforms, RetrieveTexturePath); var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", ""); if (!string.IsNullOrEmpty(path)) { exporter.SaveGLTFandBin (path, name); } } [MenuItem("GLTF/Export Scene")] static void ExportScene() { var scene = SceneManager.GetActiveScene(); var gameObjects = scene.GetRootGameObjects(); var transforms = Array.ConvertAll(gameObjects, gameObject => gameObject.transform); var exporter = new GLTFSceneExporter(transforms, RetrieveTexturePath); var path = EditorUtility.OpenFolderPanel("glTF Export Path", "", ""); if (path != "") { exporter.SaveGLTFandBin (path, scene.name); } } }
mit
C#
0d436421f9cb938163930ebb27fe6b8d2ad96371
enable only single instance of the app
yaronthurm/Backy
BackyUI/Program.cs
BackyUI/Program.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace Backy { static class Program { static Mutex singleInstanceMutex = new Mutex(true, "{2FA0A600-7B60-4E7B-9C58-8FA0D3D575B0}"); /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (singleInstanceMutex.WaitOne(TimeSpan.Zero, true)) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } else { FocusOnActiveInstance(); } } static void FocusOnActiveInstance() { Process current = Process.GetCurrentProcess(); foreach (Process process in Process.GetProcessesByName(current.ProcessName)) { if (process.Id != current.Id) { SetForegroundWindow(process.MainWindowHandle); break; } } } [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] static extern bool SetForegroundWindow(IntPtr hWnd); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Backy { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } } }
mit
C#
21080fc5be8cf8f416917c108e077f572176b50c
Fix UpdateVersionsRepo to pass file paths instead of a directory
EdwardBlair/cli,johnbeisner/cli,ravimeda/cli,dasMulli/cli,ravimeda/cli,harshjain2/cli,blackdwarf/cli,EdwardBlair/cli,Faizan2304/cli,livarcocc/cli-1,blackdwarf/cli,harshjain2/cli,svick/cli,svick/cli,svick/cli,blackdwarf/cli,ravimeda/cli,dasMulli/cli,Faizan2304/cli,Faizan2304/cli,EdwardBlair/cli,dasMulli/cli,harshjain2/cli,johnbeisner/cli,blackdwarf/cli,livarcocc/cli-1,johnbeisner/cli,livarcocc/cli-1
build_projects/dotnet-cli-build/UpdateVersionsRepo.cs
build_projects/dotnet-cli-build/UpdateVersionsRepo.cs
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.DotNet.VersionTools.Automation; using System.IO; namespace Microsoft.DotNet.Cli.Build { public class UpdateVersionsRepo : Task { [Required] public string BranchName { get; set; } [Required] public string PackagesDirectory { get; set; } [Required] public string GitHubPassword { get; set; } public override bool Execute() { string versionsRepoPath = $"build-info/dotnet/cli/{BranchName}"; GitHubAuth auth = new GitHubAuth(GitHubPassword); GitHubVersionsRepoUpdater repoUpdater = new GitHubVersionsRepoUpdater(auth); repoUpdater.UpdateBuildInfoAsync( Directory.GetFiles(PackagesDirectory, "*.nupkg"), versionsRepoPath).Wait(); return true; } } }
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.DotNet.VersionTools.Automation; namespace Microsoft.DotNet.Cli.Build { public class UpdateVersionsRepo : Task { [Required] public string BranchName { get; set; } [Required] public string PackagesDirectory { get; set; } [Required] public string GitHubPassword { get; set; } public override bool Execute() { string versionsRepoPath = $"build-info/dotnet/cli/{BranchName}"; GitHubAuth auth = new GitHubAuth(GitHubPassword); GitHubVersionsRepoUpdater repoUpdater = new GitHubVersionsRepoUpdater(auth); repoUpdater.UpdateBuildInfoAsync( new [] { PackagesDirectory }, versionsRepoPath).Wait(); return true; } } }
mit
C#
42a3a30bf80edf60b638f249e20fec3ad0c8cd44
Add more browser bindings
quisquous/cactbot,sqt/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,sqt/cactbot,quisquous/cactbot,quisquous/cactbot,quisquous/cactbot,sqt/cactbot
BrowserBindings.cs
BrowserBindings.cs
using Advanced_Combat_Tracker; using FFXIV_ACT_Plugin; using System.Collections.Generic; namespace ACTBossTime { public class BrowserBindings { const int MaxLogLinesRetained = 2000; Queue<string> logLines = new Queue<string>(); public BrowserBindings() { Advanced_Combat_Tracker.ActGlobals.oFormActMain.OnLogLineRead += OnLogLineRead; } ~BrowserBindings() { Advanced_Combat_Tracker.ActGlobals.oFormActMain.OnLogLineRead -= OnLogLineRead; } public string CurrentZone() { return FFXIV_ACT_Plugin.ACTWrapper.CurrentZone; } public bool InCombat() { return FFXIV_ACT_Plugin.ACTWrapper.InCombat; } public void TextToSpeech(string speechText) { // FIXME: This appears to be synchronous. Maybe kick the task to a thread? Advanced_Combat_Tracker.ActGlobals.oFormActMain.TTS(speechText); } public bool HasLogLines() { return logLines.Count > 0; } public string NextLogLine() { return logLines.Dequeue(); } private void OnLogLineRead(bool isImport, LogLineEventArgs args) { if (isImport) return; logLines.Enqueue(args.logLine); // FIXME: expose this error to the browser. if (logLines.Count > MaxLogLinesRetained) logLines.Dequeue(); } } }
using Advanced_Combat_Tracker; using FFXIV_ACT_Plugin; using System.Collections.Generic; namespace ACTBossTime { public class BrowserBindings { const int MaxLogLinesRetained = 2000; Queue<string> logLines = new Queue<string>(); public BrowserBindings() { Advanced_Combat_Tracker.ActGlobals.oFormActMain.OnLogLineRead += OnLogLineRead; } ~BrowserBindings() { Advanced_Combat_Tracker.ActGlobals.oFormActMain.OnLogLineRead -= OnLogLineRead; } public string CurrentZone() { return FFXIV_ACT_Plugin.ACTWrapper.CurrentZone; } public bool HasLogLines() { return logLines.Count > 0; } public string NextLogLine() { return logLines.Dequeue(); } private void OnLogLineRead(bool isImport, LogLineEventArgs args) { if (isImport) return; logLines.Enqueue(args.logLine); // FIXME: expose this error to the browser. if (logLines.Count > MaxLogLinesRetained) logLines.Dequeue(); } } }
apache-2.0
C#
5f701dba88947acaf8a1fc020e864679e2d98150
Use file exists instead of getting file. fixes #262
modulexcite/dotless,r2i-sitecore/dotless,modulexcite/dotless,modulexcite/dotless,rytmis/dotless,rytmis/dotless,modulexcite/dotless,r2i-sitecore/dotless,r2i-sitecore/dotless,dotless/dotless,dotless/dotless,rytmis/dotless,rytmis/dotless,modulexcite/dotless,r2i-sitecore/dotless,r2i-sitecore/dotless,rytmis/dotless,r2i-sitecore/dotless,r2i-sitecore/dotless,modulexcite/dotless,rytmis/dotless,rytmis/dotless,modulexcite/dotless
src/dotless.AspNet/Input/VirtualFileReader.cs
src/dotless.AspNet/Input/VirtualFileReader.cs
namespace dotless.Core.Input { using System.IO; using System.Web.Hosting; public class VirtualFileReader : IFileReader { public byte[] GetBinaryFileContents(string fileName) { var virtualPathProvider = HostingEnvironment.VirtualPathProvider; var virtualFile = virtualPathProvider.GetFile(fileName); using (var stream = virtualFile.Open()) { var buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); return buffer; } } public string GetFileContents(string fileName) { var virtualPathProvider = HostingEnvironment.VirtualPathProvider; var virtualFile = virtualPathProvider.GetFile(fileName); using (var streamReader = new StreamReader(virtualFile.Open())) { return streamReader.ReadToEnd(); } } public bool DoesFileExist(string fileName) { var virtualPathProvider = HostingEnvironment.VirtualPathProvider; return virtualPathProvider.FileExists(fileName); } public bool UseCacheDependencies { get { return false; } } } }
namespace dotless.Core.Input { using System.IO; using System.Web.Hosting; public class VirtualFileReader : IFileReader { public byte[] GetBinaryFileContents(string fileName) { var virtualPathProvider = HostingEnvironment.VirtualPathProvider; var virtualFile = virtualPathProvider.GetFile(fileName); using (var stream = virtualFile.Open()) { var buffer = new byte[stream.Length]; stream.Read(buffer, 0, (int)stream.Length); return buffer; } } public string GetFileContents(string fileName) { var virtualPathProvider = HostingEnvironment.VirtualPathProvider; var virtualFile = virtualPathProvider.GetFile(fileName); using (var streamReader = new StreamReader(virtualFile.Open())) { return streamReader.ReadToEnd(); } } public bool DoesFileExist(string fileName) { var virtualPathProvider = HostingEnvironment.VirtualPathProvider; return virtualPathProvider.GetFile(fileName) != null; } public bool UseCacheDependencies { get { return false; } } } }
apache-2.0
C#
8087b3af6088741f972e9f264f0eb2e198c68a28
reduce cache time down to 30 secs (#814)
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Api/V1/Controllers/BaseController.cs
src/FilterLists.Api/V1/Controllers/BaseController.cs
using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using FilterLists.Services.Seed; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; namespace FilterLists.Api.V1.Controllers { [ApiVersion("1.0")] [Route("v{version:apiVersion}/[controller]")] [ResponseCache(Duration = 30)] public abstract class BaseController : Controller { private static readonly TimeSpan MemoryCacheExpirationDefault = TimeSpan.FromSeconds(30); protected readonly SeedService SeedService; private readonly IMemoryCache memoryCache; protected BaseController() { } protected BaseController(IMemoryCache memoryCache) => this.memoryCache = memoryCache; protected BaseController(IMemoryCache memoryCache, SeedService seedService) { this.memoryCache = memoryCache; SeedService = seedService; } //https://stackoverflow.com/a/52506210/2343739 protected async Task<IActionResult> Get<T>(Func<Task<T>> createAction, int? paramCacheKey = null, [CallerMemberName] string actionName = null) { var cacheKey = GetType().Name + "_" + actionName + "_" + paramCacheKey; var result = await memoryCache.GetOrCreateAsync(cacheKey, entry => { entry.AbsoluteExpirationRelativeToNow = MemoryCacheExpirationDefault; return createAction(); }); return CoalesceNotFound(Json(result)); } private IActionResult CoalesceNotFound(JsonResult result) => result.Value is null ? NotFound() : (IActionResult)result; } }
using System; using System.Runtime.CompilerServices; using System.Threading.Tasks; using FilterLists.Services.Seed; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Caching.Memory; namespace FilterLists.Api.V1.Controllers { [ApiVersion("1.0")] [Route("v{version:apiVersion}/[controller]")] [ResponseCache(Duration = 86400)] public abstract class BaseController : Controller { private static readonly TimeSpan MemoryCacheExpirationDefault = TimeSpan.FromHours(24); protected readonly SeedService SeedService; private readonly IMemoryCache memoryCache; protected BaseController() { } protected BaseController(IMemoryCache memoryCache) => this.memoryCache = memoryCache; protected BaseController(IMemoryCache memoryCache, SeedService seedService) { this.memoryCache = memoryCache; SeedService = seedService; } //https://stackoverflow.com/a/52506210/2343739 protected async Task<IActionResult> Get<T>(Func<Task<T>> createAction, int? paramCacheKey = null, [CallerMemberName] string actionName = null) { var cacheKey = GetType().Name + "_" + actionName + "_" + paramCacheKey; var result = await memoryCache.GetOrCreateAsync(cacheKey, entry => { entry.AbsoluteExpirationRelativeToNow = MemoryCacheExpirationDefault; return createAction(); }); return CoalesceNotFound(Json(result)); } private IActionResult CoalesceNotFound(JsonResult result) => result.Value is null ? NotFound() : (IActionResult)result; } }
mit
C#
d46d05892edf5ee000fd71ed5dbf2ce333478901
Update Index.cshtml
KrishnaIBM/TestCt-1478684487505,KrishnaIBM/TestCt-1478684487505
src/dotnetCloudantWebstarter/Views/Home/Index.cshtml
src/dotnetCloudantWebstarter/Views/Home/Index.cshtml
@{ ViewData["Title"] = "Home Page"; } <form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data"> <input type="file" name="files" multiple /> <input type="submit" value="Upload" /> </form>
@{ ViewData["Title"] = "Home Page"; } <h3>@ViewData["Message"]</h3> <form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data"> <input type="file" name="files" multiple /> <input type="submit" value="Upload" /> </form>
apache-2.0
C#
5daffd14383a264419b5843da5289d0823896925
change progressbar
B1naryStudio/Azimuth,B1naryStudio/Azimuth
Azimuth/Views/Shared/_AudioPlayer.cshtml
Azimuth/Views/Shared/_AudioPlayer.cshtml
<div id="audio-player"> <div id="audio-player-buttons"> <div id="prev-button"><i class="fa fa-backward"></i></div> <div id="play-button"><i class="fa fa-play"></i><i class="fa fa-pause hide"></i></div> <div id="next-button"><i class="fa fa-forward"></i></div> </div> <div id="item-container"> <div class="track-description"> <div class="track-info" data-toggle="modal" data-target="#infoModal"><a href="#"><span class="track-artist"></span> - <span class="track-title"></span></a></div> </div> <div id="progress-bar" style="overflow: hidden;"> <div id="progress-current" class="light-orange"></div> <div class="progress-background"></div> <div class="progress-cache"></div> <div id="progress-move" class="dark-orange"></div> </div> </div> <div id="volume-container"> <i class="fa fa-volume-up"></i> <div id="volumeSlider"></div> </div> <div id="audio-player-controls"> <div id="plus-btn"><i class="fa fa-plus"></i></div> <div id="shuffle-btn"><i class="fa fa-random"></i></div> <div id="repeat-btn"><i class="fa fa-repeat"></i></div> </div> </div>
<div id="audio-player"> <div id="audio-player-buttons"> <div id="prev-button"><i class="fa fa-backward"></i></div> <div id="play-button"><i class="fa fa-play"></i><i class="fa fa-pause hide"></i></div> <div id="next-button"><i class="fa fa-forward"></i></div> </div> <div id="item-container"> <div class="track-description"> <div class="track-info" data-toggle="modal" data-target="#infoModal"><a href="#"><span class="track-artist"></span> - <span class="track-title"></span></a></div> </div> <div id="progress-bar"> <div id="progress-current" class="light-orange"></div> <div class="progress-background"></div> <div class="progress-cache"></div> <div id="progress-move" class="dark-orange"></div> </div> </div> <div id="volume-container"> <i class="fa fa-volume-up"></i> <div id="volumeSlider"></div> </div> <div id="audio-player-controls"> <div id="plus-btn"><i class="fa fa-plus"></i></div> <div id="shuffle-btn"><i class="fa fa-random"></i></div> <div id="repeat-btn"><i class="fa fa-repeat"></i></div> </div> </div>
mit
C#
38050e8c3d202fc3262c25dd21cb06a578701e66
Fix Basic tests (angularjs.org site has been updated)
sergueik/protractor-net,JonWang0/protractor-net,bbaia/protractor-net
examples/Protractor.Samples/Basic/BasicTests.cs
examples/Protractor.Samples/Basic/BasicTests.cs
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Chrome; namespace Protractor.Samples.Basic { [TestFixture] public class BasicTests { private IWebDriver driver; [SetUp] public void SetUp() { // Using NuGet Package 'PhantomJS' driver = new PhantomJSDriver(); // Using NuGet Package 'WebDriver.ChromeDriver.win32' //driver = new ChromeDriver(); driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5)); } [TearDown] public void TearDown() { driver.Quit(); } [Test] public void ShouldGreetUsingBinding() { IWebDriver ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); ngDriver.FindElement(NgBy.Model("yourName")).SendKeys("Julie"); Assert.AreEqual("Hello Julie!", ngDriver.FindElement(NgBy.Binding("yourName")).Text); } [Test] public void ShouldListTodos() { var ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); var elements = ngDriver.FindElements(NgBy.Repeater("todo in todoList.todos")); Assert.AreEqual("build an angular app", elements[1].Text); Assert.AreEqual(false, elements[1].Evaluate("todo.done")); } } }
using System; using NUnit.Framework; using OpenQA.Selenium; using OpenQA.Selenium.PhantomJS; using OpenQA.Selenium.Chrome; namespace Protractor.Samples.Basic { [TestFixture] public class BasicTests { private IWebDriver driver; [SetUp] public void SetUp() { // Using NuGet Package 'PhantomJS' driver = new PhantomJSDriver(); // Using NuGet Package 'WebDriver.ChromeDriver.win32' //driver = new ChromeDriver(); driver.Manage().Timeouts().SetScriptTimeout(TimeSpan.FromSeconds(5)); } [TearDown] public void TearDown() { driver.Quit(); } [Test] public void ShouldGreetUsingBinding() { IWebDriver ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); ngDriver.FindElement(NgBy.Model("yourName")).SendKeys("Julie"); Assert.AreEqual("Hello Julie!", ngDriver.FindElement(NgBy.Binding("yourName")).Text); } [Test] public void ShouldListTodos() { var ngDriver = new NgWebDriver(driver); ngDriver.Navigate().GoToUrl("http://www.angularjs.org"); var elements = ngDriver.FindElements(NgBy.Repeater("todo in todos")); Assert.AreEqual("build an angular app", elements[1].Text); Assert.AreEqual(false, elements[1].Evaluate("todo.done")); } } }
mit
C#
de8b62ff7dcb86359a4a2c4fe096600157a72eef
Set -unsafe on by default.
SaladbowlCreative/Unity3D.IncrementalCompiler,SaladLab/Unity3D.IncrementalCompiler
extra/CompilerPlugin/CustomCSharpCompiler.cs
extra/CompilerPlugin/CustomCSharpCompiler.cs
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using UnityEditor.Scripting; using UnityEditor.Scripting.Compilers; using UnityEditor.Utils; using UnityEngine; internal class CustomCSharpCompiler : MonoCSharpCompiler { #if UNITY4 public CustomCSharpCompiler(MonoIsland island, bool runUpdater) : base(island) { } #else public CustomCSharpCompiler(MonoIsland island, bool runUpdater) : base(island, runUpdater) { } #endif private string GetCompilerPath(List<string> arguments) { var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Compiler"); var compilerPath = Path.Combine(basePath, "UniversalCompiler.exe"); if (File.Exists(compilerPath)) { return compilerPath; } Debug.LogWarning($"Custom C# compiler not found in project directory ({compilerPath}), using the default compiler"); // calling base method via reflection var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; var methodInfo = GetType().BaseType.GetMethod(nameof(GetCompilerPath), bindingFlags); var result = (string)methodInfo.Invoke(this, new object[] {arguments}); return result; } private string[] GetAdditionalReferences() { // calling base method via reflection var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; var methodInfo = GetType().BaseType.GetMethod(nameof(GetAdditionalReferences), bindingFlags); var result = (string[])methodInfo.Invoke(this, null); return result; } // Copy of MonoCSharpCompiler.StartCompiler() // The only reason it exists is to call the new implementation // of GetCompilerPath(...) which is non-virtual unfortunately. protected override Program StartCompiler() { var arguments = new List<string> { "-debug", "-target:library", "-nowarn:0169", "-unsafe", "-out:" + PrepareFileName(_island._output), "-define:__UNITY_PROCESSID__" + System.Diagnostics.Process.GetCurrentProcess().Id }; foreach (var reference in _island._references) { arguments.Add("-r:" + PrepareFileName(reference)); } foreach (var define in _island._defines.Distinct()) { arguments.Add("-define:" + define); } foreach (var file in _island._files) { arguments.Add(PrepareFileName(file)); } var additionalReferences = GetAdditionalReferences(); foreach (string path in additionalReferences) { var text = Path.Combine(GetProfileDirectory(), path); if (File.Exists(text)) { arguments.Add("-r:" + PrepareFileName(text)); } } return StartCompiler(_island._target, GetCompilerPath(arguments), arguments); } }
using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using UnityEditor.Scripting; using UnityEditor.Scripting.Compilers; using UnityEditor.Utils; using UnityEngine; internal class CustomCSharpCompiler : MonoCSharpCompiler { #if UNITY4 public CustomCSharpCompiler(MonoIsland island, bool runUpdater) : base(island) { } #else public CustomCSharpCompiler(MonoIsland island, bool runUpdater) : base(island, runUpdater) { } #endif private string GetCompilerPath(List<string> arguments) { var basePath = Path.Combine(Directory.GetCurrentDirectory(), "Compiler"); var compilerPath = Path.Combine(basePath, "UniversalCompiler.exe"); if (File.Exists(compilerPath)) { return compilerPath; } Debug.LogWarning($"Custom C# compiler not found in project directory ({compilerPath}), using the default compiler"); // calling base method via reflection var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; var methodInfo = GetType().BaseType.GetMethod(nameof(GetCompilerPath), bindingFlags); var result = (string)methodInfo.Invoke(this, new object[] {arguments}); return result; } private string[] GetAdditionalReferences() { // calling base method via reflection var bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic; var methodInfo = GetType().BaseType.GetMethod(nameof(GetAdditionalReferences), bindingFlags); var result = (string[])methodInfo.Invoke(this, null); return result; } // Copy of MonoCSharpCompiler.StartCompiler() // The only reason it exists is to call the new implementation // of GetCompilerPath(...) which is non-virtual unfortunately. protected override Program StartCompiler() { var arguments = new List<string> { "-debug", "-target:library", "-nowarn:0169", "-out:" + PrepareFileName(_island._output), "-define:__UNITY_PROCESSID__" + System.Diagnostics.Process.GetCurrentProcess().Id }; foreach (var reference in _island._references) { arguments.Add("-r:" + PrepareFileName(reference)); } foreach (var define in _island._defines.Distinct()) { arguments.Add("-define:" + define); } foreach (var file in _island._files) { arguments.Add(PrepareFileName(file)); } var additionalReferences = GetAdditionalReferences(); foreach (string path in additionalReferences) { var text = Path.Combine(GetProfileDirectory(), path); if (File.Exists(text)) { arguments.Add("-r:" + PrepareFileName(text)); } } return StartCompiler(_island._target, GetCompilerPath(arguments), arguments); } }
mit
C#
4e735598e10ba3e285f6ec6b7348ff2b78ec9eca
Add tests for attempting escaping root
ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework
osu.Framework.Tests/IO/TestDesktopStorage.cs
osu.Framework.Tests/IO/TestDesktopStorage.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using NUnit.Framework; namespace osu.Framework.Tests.IO { [TestFixture] public class TestDesktopStorage { [Test] public void TestRelativePaths() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { var basePath = storage.GetFullPath(string.Empty); Assert.IsTrue(basePath.EndsWith(guid)); Assert.Throws<ArgumentException>(() => storage.GetFullPath("../")); Assert.Throws<ArgumentException>(() => storage.GetFullPath("..")); Assert.Throws<ArgumentException>(() => storage.GetFullPath("./../")); Assert.AreEqual(Path.GetFullPath(Path.Combine(basePath, "sub", "test")) + Path.DirectorySeparatorChar, storage.GetFullPath("sub/test/")); Assert.AreEqual(Path.GetFullPath(Path.Combine(basePath, "sub", "test")), storage.GetFullPath("sub/test")); } } [Test] public void TestAttemptEscapeRoot() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { Assert.Throws<ArgumentException>(() => storage.GetStream("../test")); Assert.Throws<ArgumentException>(() => storage.GetStorageForDirectory("../")); } } [Test] public void TestGetSubDirectoryStorage() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { Assert.That(storage.GetStorageForDirectory("subdir").GetFullPath(string.Empty), Is.EqualTo(Path.Combine(storage.GetFullPath(string.Empty), "subdir"))); } } [Test] public void TestGetEmptySubDirectoryStorage() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { Assert.That(storage.GetStorageForDirectory(string.Empty).GetFullPath(string.Empty), Is.EqualTo(storage.GetFullPath(string.Empty))); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.IO; using NUnit.Framework; namespace osu.Framework.Tests.IO { [TestFixture] public class TestDesktopStorage { [Test] public void TestRelativePaths() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { var basePath = storage.GetFullPath(string.Empty); Assert.IsTrue(basePath.EndsWith(guid)); Assert.Throws<ArgumentException>(() => storage.GetFullPath("../")); Assert.Throws<ArgumentException>(() => storage.GetFullPath("..")); Assert.Throws<ArgumentException>(() => storage.GetFullPath("./../")); Assert.AreEqual(Path.GetFullPath(Path.Combine(basePath, "sub", "test")) + Path.DirectorySeparatorChar, storage.GetFullPath("sub/test/")); Assert.AreEqual(Path.GetFullPath(Path.Combine(basePath, "sub", "test")), storage.GetFullPath("sub/test")); } } [Test] public void TestGetSubDirectoryStorage() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { Assert.That(storage.GetStorageForDirectory("subdir").GetFullPath(string.Empty), Is.EqualTo(Path.Combine(storage.GetFullPath(string.Empty), "subdir"))); } } [Test] public void TestGetEmptySubDirectoryStorage() { var guid = new Guid().ToString(); using (var storage = new TemporaryNativeStorage(guid)) { Assert.That(storage.GetStorageForDirectory(string.Empty).GetFullPath(string.Empty), Is.EqualTo(storage.GetFullPath(string.Empty))); } } } }
mit
C#
490d48fa5e106b88b5aac1952812689ec444c889
Fix MultiplayerTestCase not being abstract
smoogipooo/osu,DrabWeb/osu,smoogipoo/osu,peppy/osu,naoey/osu,ZLima12/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,DrabWeb/osu,2yangk23/osu,UselessToucan/osu,ppy/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,naoey/osu,2yangk23/osu,peppy/osu-new,ppy/osu,ppy/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,johnneijzen/osu,naoey/osu,ZLima12/osu,NeoAdonis/osu,NeoAdonis/osu
osu.Game/Tests/Visual/MultiplayerTestCase.cs
osu.Game/Tests/Visual/MultiplayerTestCase.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Game.Online.Multiplayer; namespace osu.Game.Tests.Visual { public abstract class MultiplayerTestCase : OsuTestCase { [Cached] private readonly Bindable<Room> currentRoom = new Bindable<Room>(new Room()); protected Room Room { get => currentRoom; set => currentRoom.Value = value; } private CachedModelDependencyContainer<Room> dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent)); dependencies.Model.BindTo(currentRoom); return dependencies; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Configuration; using osu.Game.Online.Multiplayer; namespace osu.Game.Tests.Visual { public class MultiplayerTestCase : OsuTestCase { [Cached] private readonly Bindable<Room> currentRoom = new Bindable<Room>(new Room()); protected Room Room { get => currentRoom; set => currentRoom.Value = value; } private CachedModelDependencyContainer<Room> dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) { dependencies = new CachedModelDependencyContainer<Room>(base.CreateChildDependencies(parent)); dependencies.Model.BindTo(currentRoom); return dependencies; } } }
mit
C#
ef9a3dd99272f14933c5e01856f3e3cf678cbc1a
Update GetVaribleStatement.cs
nilproject/NiL.JS,Oceanswave/NiL.JS,Oceanswave/NiL.JS,nilproject/NiL.JS,Oceanswave/NiL.JS,nilproject/NiL.JS
NiL.JS/Statements/GetVaribleStatement.cs
NiL.JS/Statements/GetVaribleStatement.cs
using System; using NiL.JS.Core.BaseTypes; using NiL.JS.Core; namespace NiL.JS.Statements { internal sealed class GetVaribleStatement : Statement { private Context cacheContext; private JSObject cacheRes; private string varibleName; public GetVaribleStatement(string name) { int i = 0; if ((name != "this") && !Parser.ValidateName(name, ref i, false, true)) throw new ArgumentException("Invalid varible name"); this.varibleName = name; } public override JSObject Invoke(Context context) { if (context == cacheContext) if (cacheRes == null) return (cacheRes = context.GetField(varibleName)); else return cacheRes; cacheContext = context; return cacheRes = context.GetField(varibleName); } public override JSObject Invoke(Context context, JSObject[] args) { throw new NotImplementedException(); } } }
using System; using NiL.JS.Core.BaseTypes; using NiL.JS.Core; namespace NiL.JS.Statements { internal sealed class GetVaribleStatement : Statement { private Context cacheContext; private JSObject cacheRes; private string varibleName; public GetVaribleStatement(string name) { int i = 0; if (!Parser.ValidateName(name, ref i)) throw new ArgumentException("Invalid varible name"); this.varibleName = name; } public override JSObject Invoke(Context context) { if (context == cacheContext) if (cacheRes == null) return (cacheRes = context.GetField(varibleName)); else return cacheRes; cacheContext = context; return cacheRes = context.GetField(varibleName); } public override JSObject Invoke(Context context, JSObject[] args) { throw new NotImplementedException(); } } }
bsd-3-clause
C#
d52e0e376e8a25eebb7606f022b8b11a1ff6d657
Update data dir
Mako88/dxx-tracker
RebirthTracker/RebirthTracker/Globals.cs
RebirthTracker/RebirthTracker/Globals.cs
using System.Collections.Generic; using System.Net.Sockets; using System.Runtime.InteropServices; namespace RebirthTracker { /// <summary> /// Class to keep track of global variables /// </summary> public static class Globals { public readonly static UdpClient MainClient = new UdpClient(9999); public readonly static UdpClient AckClient = new UdpClient(9998); public readonly static HashSet<int> GameIDs = new HashSet<int>(); /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return "..\\..\\..\\..\\..\\"; } return "/var/www/tracker/"; } } }
using System.Collections.Generic; using System.Net.Sockets; using System.Runtime.InteropServices; namespace RebirthTracker { /// <summary> /// Class to keep track of global variables /// </summary> public static class Globals { public readonly static UdpClient MainClient = new UdpClient(9999); public readonly static UdpClient AckClient = new UdpClient(9998); public readonly static HashSet<int> GameIDs = new HashSet<int>(); /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return "..\\..\\..\\..\\..\\"; } return "/var/www/"; } } }
mit
C#
a2217e4874ebda61dca1ed1e276107714bad73bf
Fix ios throwing NotImplementedException when deserializing StripeCharge
richardlawley/stripe.net,stripe/stripe-dotnet,duckwaffle/stripe.net,brentdavid2008/stripe.net
src/Stripe/Infrastructure/SourceConverter.cs
src/Stripe/Infrastructure/SourceConverter.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Stripe.Infrastructure { internal class SourceConverter : JsonConverter { public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var incoming = (JObject.Load(reader)); var source = new Source { Id = incoming.SelectToken("id").ToString() }; if (incoming.SelectToken("object").ToString() == "bank_account") { source.Type = SourceType.BankAccount; source.BankAccount = Mapper<StripeBankAccount>.MapFromJson(incoming.ToString()); } if (incoming.SelectToken("object").ToString() == "card") { source.Type = SourceType.Card; source.Card = Mapper<StripeCard>.MapFromJson(incoming.ToString()); } return source; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Stripe.Infrastructure { internal class SourceConverter : JsonConverter { public override bool CanConvert(Type objectType) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var incoming = (JObject.Load(reader)).ToObject<dynamic>(); var source = new Source { Id = incoming.SelectToken("id") }; if (incoming.SelectToken("object").ToString() == "bank_account") { source.Type = SourceType.BankAccount; source.BankAccount = Mapper<StripeBankAccount>.MapFromJson(incoming.ToString()); } if (incoming.SelectToken("object") == "card") { source.Type = SourceType.Card; source.Card = Mapper<StripeCard>.MapFromJson(incoming.ToString()); } return source; } } }
apache-2.0
C#
1df45026313d16a85cc09fe553e3988cb9dd67d2
fix (#414)
StefH/WireMock.Net,WireMock-Net/WireMock.Net,StefH/WireMock.Net
src/WireMock.Net.StandAlone/StandAloneApp.cs
src/WireMock.Net.StandAlone/StandAloneApp.cs
using JetBrains.Annotations; using System.Linq; using WireMock.Logging; using WireMock.Server; using WireMock.Settings; using WireMock.Validation; namespace WireMock.Net.StandAlone { /// <summary> /// The StandAloneApp /// </summary> public static class StandAloneApp { /// <summary> /// Start WireMock.Net standalone Server based on the FluentMockServerSettings. /// </summary> /// <param name="settings">The FluentMockServerSettings</param> [PublicAPI] public static WireMockServer Start([NotNull] IWireMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); var server = WireMockServer.Start(settings); settings.Logger?.Info("WireMock.Net server listening at {0}", string.Join(",", server.Urls)); return server; } /// <summary> /// Start WireMock.Net standalone Server based on the commandline arguments. /// </summary> /// <param name="args">The commandline arguments</param> /// <param name="logger">The logger</param> [PublicAPI] public static WireMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null) { Check.NotNull(args, nameof(args)); var settings = WireMockServerSettingsParser.ParseArguments(args, logger); settings.Logger?.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); return Start(settings); } } }
using JetBrains.Annotations; using System.Linq; using WireMock.Logging; using WireMock.Server; using WireMock.Settings; using WireMock.Validation; namespace WireMock.Net.StandAlone { /// <summary> /// The StandAloneApp /// </summary> public static class StandAloneApp { /// <summary> /// Start WireMock.Net standalone Server based on the FluentMockServerSettings. /// </summary> /// <param name="settings">The FluentMockServerSettings</param> [PublicAPI] public static WireMockServer Start([NotNull] IWireMockServerSettings settings) { Check.NotNull(settings, nameof(settings)); var server = WireMockServer.Start(settings); settings.Logger.Info("WireMock.Net server listening at {0}", string.Join(",", server.Urls)); return server; } /// <summary> /// Start WireMock.Net standalone Server based on the commandline arguments. /// </summary> /// <param name="args">The commandline arguments</param> /// <param name="logger">The logger</param> [PublicAPI] public static WireMockServer Start([NotNull] string[] args, [CanBeNull] IWireMockLogger logger = null) { Check.NotNull(args, nameof(args)); var settings = WireMockServerSettingsParser.ParseArguments(args); settings.Logger.Debug("WireMock.Net server arguments [{0}]", string.Join(", ", args.Select(a => $"'{a}'"))); return Start(settings); } } }
apache-2.0
C#
ab9cc810380dc44c88d869797e476a2fdc54820f
Update v3 _Layout.cshtml
atata-framework/atata-bootstrap,atata-framework/atata-bootstrap
test/Atata.Bootstrap.TestApp/Pages/v3/_Layout.cshtml
test/Atata.Bootstrap.TestApp/Pages/v3/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewBag.Title - Atata.Bootstrap.TestApp v3</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> @RenderSection("styles", false) </head> <body> <div class="container"> <h1 class="text-center">@ViewBag.Title</h1> @RenderBody() </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> @RenderSection("scripts", false) </body> </html>
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewBag.Title</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> @RenderSection("styles", false) </head> <body> <div class="container"> <h1 class="text-center">@ViewBag.Title</h1> @RenderBody() </div> <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> @RenderSection("scripts", false) </body> </html>
apache-2.0
C#
813a3379ade0b5699bd264d167f78a0af797fe18
Rename field
ethanmoffat/EndlessClient
EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs
EOLib.IO/Services/Serializers/WarpMapEntitySerializer.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using System.Collections.Generic; using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { public class WarpMapEntitySerializer : IMapEntitySerializer<WarpMapEntity> { private readonly INumberEncoderService _numberEncoderService; public int DataSize { get { return 8; } } public MapEntitySerializeType MapEntitySerializeType { get { return MapEntitySerializeType.WarpEntitySerializer; } } public WarpMapEntitySerializer(INumberEncoderService numberEncoderService) { _numberEncoderService = numberEncoderService; } public byte[] SerializeToByteArray(WarpMapEntity mapEntity) { var retBytes = new List<byte>(DataSize); retBytes.AddRange(_numberEncoderService.EncodeNumber(mapEntity.X, 1)); retBytes.AddRange(_numberEncoderService.EncodeNumber(mapEntity.DestinationMapID, 2)); retBytes.AddRange(_numberEncoderService.EncodeNumber(mapEntity.DestinationMapX, 1)); retBytes.AddRange(_numberEncoderService.EncodeNumber(mapEntity.DestinationMapY, 1)); retBytes.AddRange(_numberEncoderService.EncodeNumber(mapEntity.LevelRequirement, 1)); retBytes.AddRange(_numberEncoderService.EncodeNumber((short)mapEntity.DoorType, 2)); return retBytes.ToArray(); } public WarpMapEntity DeserializeFromByteArray(byte[] data) { if (data.Length != DataSize) throw new ArgumentException("Data is improperly sized for deserialization", "data"); return new WarpMapEntity { X = _numberEncoderService.DecodeNumber(data[0]), DestinationMapID = (short) _numberEncoderService.DecodeNumber(data[1], data[2]), DestinationMapX = (byte) _numberEncoderService.DecodeNumber(data[3]), DestinationMapY = (byte) _numberEncoderService.DecodeNumber(data[4]), LevelRequirement = (byte) _numberEncoderService.DecodeNumber(data[5]), DoorType = (DoorSpec) _numberEncoderService.DecodeNumber(data[6], data[7]) }; } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using System; using System.Collections.Generic; using EOLib.IO.Map; namespace EOLib.IO.Services.Serializers { public class WarpMapEntitySerializer : IMapEntitySerializer<WarpMapEntity> { private readonly INumberEncoderService numberEncoderService; public int DataSize { get { return 8; } } public MapEntitySerializeType MapEntitySerializeType { get { return MapEntitySerializeType.WarpEntitySerializer; } } public WarpMapEntitySerializer(INumberEncoderService numberEncoderService) { this.numberEncoderService = numberEncoderService; } public byte[] SerializeToByteArray(WarpMapEntity mapEntity) { var retBytes = new List<byte>(DataSize); retBytes.AddRange(numberEncoderService.EncodeNumber(mapEntity.X, 1)); retBytes.AddRange(numberEncoderService.EncodeNumber(mapEntity.DestinationMapID, 2)); retBytes.AddRange(numberEncoderService.EncodeNumber(mapEntity.DestinationMapX, 1)); retBytes.AddRange(numberEncoderService.EncodeNumber(mapEntity.DestinationMapY, 1)); retBytes.AddRange(numberEncoderService.EncodeNumber(mapEntity.LevelRequirement, 1)); retBytes.AddRange(numberEncoderService.EncodeNumber((short)mapEntity.DoorType, 2)); return retBytes.ToArray(); } public WarpMapEntity DeserializeFromByteArray(byte[] data) { if (data.Length != DataSize) throw new ArgumentException("Data is improperly sized for deserialization", "data"); return new WarpMapEntity { X = numberEncoderService.DecodeNumber(data[0]), DestinationMapID = (short) numberEncoderService.DecodeNumber(data[1], data[2]), DestinationMapX = (byte) numberEncoderService.DecodeNumber(data[3]), DestinationMapY = (byte) numberEncoderService.DecodeNumber(data[4]), LevelRequirement = (byte) numberEncoderService.DecodeNumber(data[5]), DoorType = (DoorSpec) numberEncoderService.DecodeNumber(data[6], data[7]) }; } } }
mit
C#
2bfaf2d86b174c9860d1b973bafa0009422689bd
Build script
SharpeRAD/Cake.Services
build.cake
build.cake
/////////////////////////////////////////////////////////////////////////////// // IMPORTS /////////////////////////////////////////////////////////////////////////////// #load "./build/scripts/imports.cake" ////////////////////////////////////////////////////////////////////// // SOLUTION ////////////////////////////////////////////////////////////////////// // Name var appName = "Cake.Services"; // Projects var projectNames = new List<string>() { "Cake.Services" }; /////////////////////////////////////////////////////////////////////////////// // LOAD /////////////////////////////////////////////////////////////////////////////// #load "./build/scripts/load.cake"
////////////////////////////////////////////////////////////////////// // IMPORTS ////////////////////////////////////////////////////////////////////// #addin "Cake.Slack" #addin "Cake.ReSharperReports" #addin "Cake.AWS.S3" #addin "Cake.FileHelpers" #tool "ReportUnit" #tool "JetBrains.ReSharper.CommandLineTools" ////////////////////////////////////////////////////////////////////// // ARGUMENTS ////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); ////////////////////////////////////////////////////////////////////// // SOLUTION ////////////////////////////////////////////////////////////////////// // Name var appName = "Cake.Services"; // Projects var projectNames = new List<string>() { "Cake.Services" }; /////////////////////////////////////////////////////////////////////////////// // LOAD /////////////////////////////////////////////////////////////////////////////// #load "./build/scripts/load.cake"
mit
C#
c325c7be490315553b204c6b9653b1f33e0689d2
Move build.cake to dotnet sdk api.
sqeezy/FibonacciHeap,sqeezy/FibonacciHeap
build.cake
build.cake
#tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { DotNetCoreTest("./src/FibonacciHeap.Tests/FibonacciHeap.Tests.csproj"); }); Task("Build") .IsDependentOn("Nuget") .Does(()=> { DotNetCoreMSBuild("FibonacciHeap.sln"); }); Task("Nuget") .IsDependentOn("Clean") .Does(()=> { DotNetCoreRestore(); }); Task("Clean") .Does(()=> { CleanDirectories(outputDir+"/**"); }); RunTarget(target);
#tool "nuget:?package=xunit.runner.console" var target = Argument("target", "Default"); var outputDir = "./bin"; Task("Default") .IsDependentOn("Xunit") .Does(() => { }); Task("Xunit") .IsDependentOn("Build") .Does(()=> { XUnit2("./src/FibonacciHeap.Tests/bin/Release/FibonacciHeap.Tests.dll"); }); Task("Build") .IsDependentOn("Nuget") .Does(()=> { MSBuild("FibonacciHeap.sln", new MSBuildSettings { Configuration = "Release" }); }); Task("Nuget") .IsDependentOn("Clean") .Does(()=> { NuGetRestore("./"); }); Task("Clean") .Does(()=> { CleanDirectories(outputDir+"/**"); }); RunTarget(target);
mit
C#
1bb00ff99246cf0777e644b035c3e83f0cdd955f
Update AssemblyInfo.cs
YouTuQiong/DataStructure
DataStructure/Properties/AssemblyInfo.cs
DataStructure/Properties/AssemblyInfo.cs
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("DataStructure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataStructure")] [assembly: AssemblyCopyright("版权所有(C) 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("zh-Hans")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("DataStructure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DataStructure")] [assembly: AssemblyCopyright("版权所有(C) 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("zh-Hans")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
04e6be58a5584436894ba64446bfb06a356bddd3
Switch server back to TCP
ermau/Tempest.Social
Desktop/Tempest.Social.Server/Program.cs
Desktop/Tempest.Social.Server/Program.cs
using System; using System.IO; using System.Net; using System.Text; using System.Threading; using Tempest.Providers.Network; namespace Tempest.Social.Server { class Program { private static readonly PublicKeyIdentityProvider IdentityProvider = new PublicKeyIdentityProvider(); static void Main (string[] args) { Console.WriteLine ("Getting server key..."); RSAAsymmetricKey key = GetKey ("server.key"); Console.WriteLine ("Got it."); var provider = new NetworkConnectionProvider ( new[] { SocialProtocol.Instance }, new Target (Target.AnyIP, 42912), 10000, key); SocialServer server = new SocialServer (new MemoryWatchListProvider(), IdentityProvider); server.ConnectionMade += OnConnectionMade; server.AddConnectionProvider (provider); server.Start(); Console.WriteLine ("Server ready."); while (true) Thread.Sleep (1000); } private static void OnConnectionMade (object sender, ConnectionMadeEventArgs e) { Console.WriteLine ("Connection made"); } private static RSAAsymmetricKey GetKey (string path) { RSAAsymmetricKey key = null; if (!File.Exists (path)) { RSACrypto crypto = new RSACrypto(); key = crypto.ExportKey (true); using (FileStream stream = File.Create (path)) key.Serialize (null, new StreamValueWriter (stream)); } if (key == null) { using (FileStream stream = File.OpenRead (path)) key = new RSAAsymmetricKey (null, new StreamValueReader (stream)); } return key; } } }
using System; using System.IO; using System.Net; using System.Text; using System.Threading; using Tempest.Providers.Network; namespace Tempest.Social.Server { class Program { private static readonly PublicKeyIdentityProvider IdentityProvider = new PublicKeyIdentityProvider(); static void Main (string[] args) { Console.WriteLine ("Getting server key..."); RSAAsymmetricKey key = GetKey ("server.key"); Console.WriteLine ("Got it."); //var provider = new NetworkConnectionProvider ( // new[] { SocialProtocol.Instance }, // new IPEndPoint (IPAddress.Any, 42912), // 10000, // () => new RSACrypto(), // key); var provider = new UdpConnectionProvider ( SocialProtocol.DefaultPort, SocialProtocol.Instance, key); SocialServer server = new SocialServer (new MemoryWatchListProvider(), IdentityProvider); server.ConnectionMade += OnConnectionMade; server.AddConnectionProvider (provider); server.Start(); Console.WriteLine ("Server ready."); while (true) Thread.Sleep (1000); } private static void OnConnectionMade (object sender, ConnectionMadeEventArgs e) { Console.WriteLine ("Connection made"); } private static RSAAsymmetricKey GetKey (string path) { RSAAsymmetricKey key = null; if (!File.Exists (path)) { RSACrypto crypto = new RSACrypto(); key = crypto.ExportKey (true); using (FileStream stream = File.Create (path)) key.Serialize (null, new StreamValueWriter (stream)); } if (key == null) { using (FileStream stream = File.OpenRead (path)) key = new RSAAsymmetricKey (null, new StreamValueReader (stream)); } return key; } } }
mit
C#
edd04a448a38f3f389ddaa241ebd50e7802e9ab0
Print the texts of each row
12joan/hangman
table.cs
table.cs
using System; using System.Collections.Generic; using System.Text; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { List<string> rowTexts = new List<string>(); foreach (var row in Rows) { rowTexts.Add(row.Text); } return String.Join("\n", rowTexts); } } }
using System; namespace Hangman { public class Table { public int Width; public int Spacing; public Row[] Rows; public Table(int width, int spacing, Row[] rows) { Width = width; Spacing = spacing; Rows = rows; } public string Draw() { return "Hello World"; } } }
unlicense
C#
0509fccf02dfd8f93107c4b421cbf0a3b7199822
Update assembly info
hey-red/Markdown
MarkdownSharp/Properties/AssemblyInfo.cs
MarkdownSharp/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("MarkdownSharp")] [assembly: AssemblyDescription("Markdown processor")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("Eureka")] [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("04acaa41-422c-4edb-8781-74ca8a16729a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.14.4.0")] [assembly: AssemblyFileVersion("1.14.4.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MarkdownSharp")] [assembly: AssemblyDescription("Markdown processor")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("")] [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("04acaa41-422c-4edb-8781-74ca8a16729a")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
c8bc54af16a4c62c5ea178bd3d1c8cadab12145b
Update App
jwmarsden/Kinetic3
Kinetic/Kinetic-Example/K3TestApplication1.cs
Kinetic/Kinetic-Example/K3TestApplication1.cs
using System; using System.Drawing; using Kinetic.Base; using Kinetic.IO; using Kinetic.Common; using Kinetic.Math; using Kinetic.Scene; using Kinetic.Resource; using Kinetic.Render; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace KineticExample { public class K3TestApplication1: BaseApplication { Texture _kineticBannerTexture = null; public K3TestApplication1 () { } public override void Initialize() { Display display = _displays[0]; display.SetTitle("Kinetic K3"); string[] extensions = display.SupportedExtensions(); Console.Write("Supported Extensions: "); foreach (string extension in extensions) { Console.Write(string.Format("{0}", extension)); } Console.Write("\r\n"); _kineticBannerTexture = ResourceManager.ImportTexture(MainRenderer.Catalog, "KineticBanner", "KineticBanner.jpg"); } public override void Update(long time) { } public override void ApplicationRender() { MainRenderer.DrawTexture(_kineticBannerTexture); } public static void Main (string[] args) { Console.WriteLine("Running Application."); K3TestApplication1 k3App1 = new K3TestApplication1(); k3App1.start(); } } }
using System; using System.Drawing; using Kinetic.Base; using Kinetic.IO; using Kinetic.Common; using Kinetic.Math; using Kinetic.Scene; using Kinetic.Resource; using Kinetic.Render; using OpenTK; using OpenTK.Graphics; using OpenTK.Graphics.OpenGL; namespace KineticExample { public class K3TestApplication1: BaseApplication { Texture kineticMainImageTexture = null; public K3TestApplication1 () { } public override void Initialize() { Display display = _displays[0]; display.SetTitle("Kinetic K3"); string[] extensions = display.SupportedExtensions(); Console.Write("Supported Extensions: "); foreach (string extension in extensions) { Console.Write(string.Format("{0}", extension)); } Console.Write("\r\n"); kineticMainImageTexture = ResourceManager.ImportTexture(MainRenderer.Catalog, "KineticBanner", "KineticBanner.jpg"); } public override void Update(long time) { } public override void ApplicationRender() { MainRenderer.DrawTexture(kineticMainImageTexture); } public static void Main (string[] args) { Console.WriteLine("Running Application."); K3TestApplication1 k3App1 = new K3TestApplication1(); k3App1.start(); } } }
apache-2.0
C#
d2dfa363ad05dce8877c397f5f749729aef7c404
Update heading on guitars page
michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic,michaelp0730/MichaelsMusic
MichaelsMusic/Views/Guitars/index.cshtml
MichaelsMusic/Views/Guitars/index.cshtml
@model MichaelsMusic.Models.GuitarCollection @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Guitars"; ViewBag.Description = "This is the guitar collections page. These are all guitars that I either: own, used to own, or wish I owned (which is most of them). If you want to look at guitars, but you're not sure which ones, this is the right place to start."; ViewBag.Keywords = "guitars, mcnaught guitars, mcnaught vintage double cut, prs, prs guitars, paul reed smith, paul reed smith guitars, paul reed smith custom 24, prs custom 24, paul reed smith mccarty, prs mccarty, peavey hp custom, gibson midtown custom, king bee oak cliff, 1980 gibson les paul custom, collings city limits deluxe, collings cl deluxe"; } <section class="section section-size1"> <div class="row"> <div class="twelve columns"> <h1>Guitars</h1> <p>This is the guitar collections page. These are all guitars that I either: own, used to own, or wish I owned (which is most of them). If you want to look at guitars, but you're not sure which ones, this is the right place to start.</p> </div> </div> <div class="row"> <div class="column"> <ul class="item-collection"> @foreach (var guitar in Model.Guitars) { <li> <p class="title"> <a href="@($"/guitars/{guitar.Slug}/")">@guitar.DisplayName</a> </p> <a href="@($"/guitars/{guitar.Slug}/")"> <img src=@($"/images/guitars/{guitar.Thumbnail}") alt="" class="pull-right" /> </a> <p>@guitar.ShortDescription</p> <p> <a href="@($"/guitars/{guitar.Slug}/")">Learn more &raquo;</a> </p> </li> } </ul> </div> </div> </section>
@model MichaelsMusic.Models.GuitarCollection @{ Layout = "~/Views/Shared/_Layout.cshtml"; ViewBag.Title = "Guitars"; ViewBag.Description = "This is the guitar collections page. These are all guitars that I either: own, used to own, or wish I owned (which is most of them). If you want to look at guitars, but you're not sure which ones, this is the right place to start."; ViewBag.Keywords = "guitars, mcnaught guitars, mcnaught vintage double cut, prs, prs guitars, paul reed smith, paul reed smith guitars, paul reed smith custom 24, prs custom 24, paul reed smith mccarty, prs mccarty, peavey hp custom, gibson midtown custom, king bee oak cliff, 1980 gibson les paul custom, collings city limits deluxe, collings cl deluxe"; } <section class="section section-size1"> <div class="row"> <div class="twelve columns"> <h2>Guitars</h2> </div> </div> <div class="row"> <div class="column"> <ul class="item-collection"> @foreach (var guitar in Model.Guitars) { <li> <p class="title"> <a href="@($"/guitars/{guitar.Slug}/")">@guitar.DisplayName</a> </p> <a href="@($"/guitars/{guitar.Slug}/")"> <img src=@($"/images/guitars/{guitar.Thumbnail}") alt="" class="pull-right" /> </a> <p>@guitar.ShortDescription</p> <p> <a href="@($"/guitars/{guitar.Slug}/")">Learn more &raquo;</a> </p> </li> } </ul> </div> </div> </section>
mit
C#
dd6b501e140aaa1b8e5ae8f5212d38e2e026faea
Revert "Added StartTile.cs"
iwelina-popova/Blackcurrant-team
MonopolyGame/MonopolyGame/Model/Board.cs
MonopolyGame/MonopolyGame/Model/Board.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonopolyGame.Model { class Board { public Board(int size) { this.BoardArr = new ITile[size]; this.Players = new List<Player>(); //for (int i = 0; i < this.BoardArr.Length; i++) //{ // if (i < this.BoardArr.Length - 2) // { // this.BoardArr[i] = new CardTile(i); // } // this.BoardArr[BoardArr.Length - 1] = new MoneyTile(i); //} } public ITile[] BoardArr { get; private set; } public int PlayerCount { get { return this.Players.Count; } } public List<Player> Players { get; private set; } public void RemovePlayer(Player player) { this.Players.Remove(player); } public void AddPlayer(Player player) { this.Players.Add(player); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MonopolyGame.Model { class Board { public Board() { this.BoardArr = new ITile[40]; this.Players = new List<Player>(); //for (int i = 0; i < this.BoardArr.Length; i++) //{ // if (i < this.BoardArr.Length - 2) // { // this.BoardArr[i] = new CardTile(i); // } // this.BoardArr[BoardArr.Length - 1] = new MoneyTile(i); //} } public ITile[] BoardArr { get; private set; } public int PlayerCount { get { return this.Players.Count; } } public List<Player> Players { get; private set; } public void RemovePlayer(Player player) { this.Players.Remove(player); } public void AddPlayer(Player player) { this.Players.Add(player); } } }
mit
C#
c709932bf3a612531619a67e43f27ce479f2edb6
Make Razor the only ViewEngine
pepinho24/MotivateMe,pepinho24/MotivateMe
MotivateMe/MotivateMe.Web/Global.asax.cs
MotivateMe/MotivateMe.Web/Global.asax.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MotivateMe.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new RazorViewEngine()); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace MotivateMe.Web { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
mit
C#
da6ea93375599b4521abdc9e6d30d583a4dcf5ac
Fix memory leak
pleonex/Ninokuni,pleonex/Ninokuni,pleonex/Ninokuni
Programs/NinoPatcher/NinoPatcher/Animation.cs
Programs/NinoPatcher/NinoPatcher/Animation.cs
// // Animation.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Drawing.Imaging; namespace NinoPatcher { public class Animation { private Control parent; private AnimationElement[] elements; private Timer timer; private int tick; public Animation(int period, Control parent, params AnimationElement[] elements) { this.parent = parent; this.elements = elements; timer = new Timer(); timer.Tick += PaintFrame; timer.Interval = period; } public void Start() { timer.Start(); tick = 0; } public void Stop() { timer.Stop(); } private void PaintFrame(object sender, EventArgs e) { Bitmap bufl = new Bitmap(parent.Width, parent.Height); using (Graphics g = Graphics.FromImage(bufl)) { // Draw background color g.FillRectangle( new SolidBrush(parent.BackColor), new Rectangle(Point.Empty, parent.Size)); // Draw animations foreach (AnimationElement el in elements) el.Draw(g, tick); // Draw image parent.CreateGraphics().DrawImageUnscaled(bufl, Point.Empty); bufl.Dispose(); } tick++; } } }
// // Animation.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Drawing; using System.IO; using System.Windows.Forms; using System.Drawing.Imaging; namespace NinoPatcher { public class Animation { private Control parent; private AnimationElement[] elements; private Timer timer; private int tick; public Animation(int period, Control parent, params AnimationElement[] elements) { this.parent = parent; this.elements = elements; timer = new Timer(); timer.Tick += PaintFrame; timer.Interval = period; } public void Start() { timer.Start(); tick = 0; } public void Stop() { timer.Stop(); } private void PaintFrame(object sender, EventArgs e) { Bitmap bufl = new Bitmap(parent.Width, parent.Height); using (Graphics g = Graphics.FromImage(bufl)) { // Draw background color g.FillRectangle( new SolidBrush(parent.BackColor), new Rectangle(Point.Empty, parent.Size)); // Draw animations foreach (AnimationElement el in elements) el.Draw(g, tick); // Draw image parent.CreateGraphics().DrawImageUnscaled(bufl, Point.Empty); } tick++; } } }
apache-2.0
C#
af1a7347a7c9e37d930611d988a5cedee5f53ad4
Add appropriate constructor for KeyedCollection.
RockFramework/Rock.Core,peteraritchie/Rock.Core,bfriesen/Rock.Core
Rock.Core/Collections/KeyedCollection.cs
Rock.Core/Collections/KeyedCollection.cs
using System; using System.Collections.Generic; namespace Rock.Collections { /// <summary> /// Provides the abstract base class for a collection whose keys are embedded in the values. /// </summary> /// <typeparam name="TKey">The type of keys in the collection.</typeparam> /// <typeparam name="TItem">The type of items in the collection.</typeparam> public abstract class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.KeyedCollection<TKey, TItem>, IKeyedEnumerable<TKey, TItem> { /// <summary> /// Initializes a new instance of the <see cref="KeyedCollection{TKey,TItem}"/> class that /// uses the specified equality comparer and creates a lookup dictionary when the specified /// threshold is exceeded. /// </summary> /// <param name="comparer"> /// The implementation of the <see cref="IEqualityComparer{T}"/> generic interface to use /// when comparing keys, or null to use the default equality comparer for the type of the key, /// obtained from <see cref="EqualityComparer{T}.Default"/>. /// </param> /// <param name="dictionaryCreationThreshold"> /// The number of elements the collection can hold without creating a lookup dictionary /// (0 creates the lookup dictionary when the first item is added), or –1 to specify that a /// lookup dictionary is never created. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="dictionaryCreationThreshold"/> is less than –1 /// </exception> protected KeyedCollection(IEqualityComparer<TKey> comparer = null, int dictionaryCreationThreshold = 0) : base(comparer, dictionaryCreationThreshold) { } } }
namespace Rock.Collections { public abstract class KeyedCollection<TKey, TItem> : System.Collections.ObjectModel.KeyedCollection<TKey, TItem>, IKeyedEnumerable<TKey, TItem> { } }
mit
C#
85e876090dde68f79b05da403f047ab3b1f5c663
Fix for clean directories
MacLeanElectrical/servicestack-authentication-identityserver
build.cake
build.cake
#addin "Cake.Json" var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var dotNetCorePackPath = Directory("./src/IdentityServer4.Contrib.ServiceStack"); var sourcePath = Directory("./src"); var nugetSources = new [] { "https://api.nuget.org/v3/index.json" }; Task("Build") .IsDependentOn("Clean") .IsDependentOn("Version") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("Version") .Does(() => { if (!isLocalBuild) { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var projectJson = ParseJsonFromFile(project); string version = (string)projectJson["version"]; projectJson["version"] = version.Substring(0, version.LastIndexOf('.')) + "." + AppVeyor.Environment.Build.Number.ToString(); SerializeJsonToFile(project, projectJson); } } }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = nugetSources }; DotNetCoreRestore(sourcePath, settings); }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { Directory("./src/IdentityServer4.Contrib.ServiceStack/obj" ), Directory("./src/IdentityServer4.Contrib.ServiceStack/bin" ) }); }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
#addin "Cake.Json" var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor; var dotNetCorePackPath = Directory("./src/IdentityServer4.Contrib.ServiceStack"); var sourcePath = Directory("./src"); var nugetSources = new [] { "https://api.nuget.org/v3/index.json" }; Task("Build") .IsDependentOn("Clean") .IsDependentOn("Version") .IsDependentOn("Restore") .Does(() => { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); Task("Version") .Does(() => { if (!isLocalBuild) { var projects = GetFiles("./**/project.json"); foreach(var project in projects) { var projectJson = ParseJsonFromFile(project); string version = (string)projectJson["version"]; projectJson["version"] = version.Substring(0, version.LastIndexOf('.')) + "." + AppVeyor.Environment.Build.Number.ToString(); SerializeJsonToFile(project, projectJson); } } }); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = nugetSources }; DotNetCoreRestore(sourcePath, settings); }); Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); Task("Default") .IsDependentOn("Build"); RunTarget(target);
mpl-2.0
C#
8e74fc803ad8d00c7c4d44d8efe3e027cdd82fdd
add code to net3 test site to excercise jsnlog.js
mperdeck/jsnlog
jsnlog.test.net3/Pages/Index.cshtml
jsnlog.test.net3/Pages/Index.cshtml
@page <div class="text-center"> <h1>jsnlog.test.net3</h1> </div> <script> window.addEventListener("load", function () { console.log('window load'); // Log a string to the server JL().fatal("fatal log message"); // Cause a run time error that will be caught and logged to the server x = thisvariabledoesnotexist; }); </script>
@page <div class="text-center"> <h1>jsnlog.test.net3</h1> </div>
mit
C#
f32697070a403e4fffdea35e4adc7ceb2088fb20
update ci config file
yuleyule66/Npoi.Core,yuleyule66/Npoi.Core
build.cake
build.cake
#addin "nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1" #load "./build/index.cake" var target = Argument("target", "Default"); var build = BuildParameters.Create(Context); var util = new Util(Context, build); Task("Clean") .Does(() => { if (DirectoryExists("./artifacts")) { DeleteDirectory("./artifacts", true); } }); Task("Restore") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreRestoreSettings { ArgumentCustomization = args => { args.Append($"/p:VersionSuffix={build.Version.Suffix}"); return args; } }; DotNetCoreRestore(settings); }); Task("Build") .IsDependentOn("Restore") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = build.Configuration, VersionSuffix = build.Version.Suffix, ArgumentCustomization = args => { args.Append($"/p:InformationalVersion={build.Version.VersionWithSuffix()}"); return args; } }; foreach (var project in build.ProjectFiles) { DotNetCoreBuild(project.FullPath, settings); } }); Task("Test") .IsDependentOn("Build") .Does(() => { foreach (var testProject in build.TestProjectFiles) { //DotNetCoreTest(testProject.FullPath); } }); Task("Pack") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = build.Configuration, VersionSuffix = build.Version.Suffix, IncludeSymbols = true, OutputDirectory = "./artifacts/packages" }; foreach (var project in build.ProjectFiles) { //DotNetCorePack(project.FullPath, settings); } }); Task("Default") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Pack") .Does(() => { util.PrintInfo(); }); Task("Version") .Does(() => { Information($"{build.FullVersion()}"); }); Task("Print") .Does(() => { util.PrintInfo(); }); RunTarget(target);
#addin "nuget:https://www.nuget.org/api/v2?package=Newtonsoft.Json&version=9.0.1" #load "./build/index.cake" var target = Argument("target", "Default"); var build = BuildParameters.Create(Context); var util = new Util(Context, build); Task("Clean") .Does(() => { if (DirectoryExists("./artifacts")) { DeleteDirectory("./artifacts", true); } }); Task("Restore") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreRestoreSettings { ArgumentCustomization = args => { args.Append($"/p:VersionSuffix={build.Version.Suffix}"); return args; } }; DotNetCoreRestore(settings); }); Task("Build") .IsDependentOn("Restore") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = build.Configuration, VersionSuffix = build.Version.Suffix, ArgumentCustomization = args => { args.Append($"/p:InformationalVersion={build.Version.VersionWithSuffix()}"); return args; } }; foreach (var project in build.ProjectFiles) { DotNetCoreBuild(project.FullPath, settings); } }); Task("Test") .IsDependentOn("Build") .Does(() => { foreach (var testProject in build.TestProjectFiles) { DotNetCoreTest(testProject.FullPath); } }); Task("Pack") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = build.Configuration, VersionSuffix = build.Version.Suffix, IncludeSymbols = true, OutputDirectory = "./artifacts/packages" }; foreach (var project in build.ProjectFiles) { //DotNetCorePack(project.FullPath, settings); } }); Task("Default") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Pack") .Does(() => { util.PrintInfo(); }); Task("Version") .Does(() => { Information($"{build.FullVersion()}"); }); Task("Print") .Does(() => { util.PrintInfo(); }); RunTarget(target);
apache-2.0
C#
c96692d7325f163d38d686b874977483fd62d0ba
Add missing EmitCloseList to backend
akrisiun/xwt,mminns/xwt,hamekoz/xwt,mminns/xwt,residuum/xwt,lytico/xwt,mono/xwt,directhex/xwt,TheBrainTech/xwt,antmicro/xwt,cra0zy/xwt,iainx/xwt,hwthomas/xwt,steffenWi/xwt,sevoku/xwt
Xwt/Xwt.Backends/IMarkdownViewBackend.cs
Xwt/Xwt.Backends/IMarkdownViewBackend.cs
// // IMarkdownViewBackend.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. using System; namespace Xwt.Backends { [Flags] enum MarkdownInlineStyle { Italic, Bold, Monospace } public interface IMarkdownViewBackend : IWidgetBackend { object CreateBuffer (); // Emit unstyled text void EmitText (object buffer, string text); // Emit a header (h1, h2, ...) void EmitHeader (object buffer, string title, int level); // What's outputed afterwards will be a in new paragrapgh void EmitNewParagraph (object buffer); // Emit a list // Chain is: // open-list, open-bullet, <above methods>, close-bullet, close-list void EmitOpenList (object buffer); void EmitOpenBullet (object buffer); void EmitCloseBullet (object buffet); void EmitCloseList (object buffer); // Emit a link displaying text and opening the href URL void EmitLink (object buffer, string href, string text); // Emit code in a preformated blockquote void EmitCodeBlock (object buffer, string code); // Display the passed buffer void SetBuffer (object buffer); } }
// // IMarkdownViewBackend.cs // // Author: // Jérémie Laval <jeremie.laval@xamarin.com> // // Copyright (c) 2012 Xamarin, Inc. using System; namespace Xwt.Backends { [Flags] enum MarkdownInlineStyle { Italic, Bold, Monospace } public interface IMarkdownViewBackend : IWidgetBackend { object CreateBuffer (); // Emit unstyled text void EmitText (object buffer, string text); // Emit a header (h1, h2, ...) void EmitHeader (object buffer, string title, int level); // What's outputed afterwards will be a in new paragrapgh void EmitNewParagraph (object buffer); // Emit a list // Chain is: // open-list, open-bullet, <above methods>, close-bullet, close-list void EmitOpenList (object buffer); void EmitOpenBullet (object buffer); void EmitCloseBullet (object buffet); // Emit a link displaying text and opening the href URL void EmitLink (object buffer, string href, string text); // Emit code in a preformated blockquote void EmitCodeBlock (object buffer, string code); // Display the passed buffer void SetBuffer (object buffer); } }
mit
C#
2c7720befe6ad2bc1798f49bca8aa8f14dab269b
Fix missing await in ConstantsTest.TotalGasesTest
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.IntegrationTests/Tests/Atmos/ConstantsTest.cs
Content.IntegrationTests/Tests/Atmos/ConstantsTest.cs
using System; using System.Linq; using System.Threading.Tasks; using Content.Server.Atmos.EntitySystems; using Content.Shared.Atmos; using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.Atmos { [TestFixture] [TestOf(typeof(Atmospherics))] public class ConstantsTest : ContentIntegrationTest { [Test] public async Task TotalGasesTest() { var server = StartServerDummyTicker(); await server.WaitIdleAsync(); await server.WaitPost(() => { var atmosSystem = EntitySystem.Get<AtmosphereSystem>(); Assert.That(atmosSystem.Gases.Count(), Is.EqualTo(Atmospherics.TotalNumberOfGases)); Assert.That(Enum.GetValues(typeof(Gas)).Length, Is.EqualTo(Atmospherics.TotalNumberOfGases)); }); } } }
using System; using System.Linq; using System.Threading.Tasks; using Content.Server.Atmos.EntitySystems; using Content.Shared.Atmos; using NUnit.Framework; using Robust.Shared.GameObjects; namespace Content.IntegrationTests.Tests.Atmos { [TestFixture] [TestOf(typeof(Atmospherics))] public class ConstantsTest : ContentIntegrationTest { [Test] public async Task TotalGasesTest() { var server = StartServerDummyTicker(); await server.WaitIdleAsync(); server.Post(() => { var atmosSystem = EntitySystem.Get<AtmosphereSystem>(); Assert.That(atmosSystem.Gases.Count(), Is.EqualTo(Atmospherics.TotalNumberOfGases)); Assert.That(Enum.GetValues(typeof(Gas)).Length, Is.EqualTo(Atmospherics.TotalNumberOfGases)); }); } } }
mit
C#
b89578150ff7173496317510c97e8129e546896f
Update IDbSession.cs
PowerMogli/Rabbit.Db
src/RabbitDB/IDbSession.cs
src/RabbitDB/IDbSession.cs
using System; using System.Linq.Expressions; using RabbitDB.Query; namespace RabbitDB.Base { internal interface IDbSession : ITransactionalSession, IDisposable { void ExecuteCommand(string sql, params object[] args); void ExecuteStoredProcedure(StoredProcedure procedureObject); void ExecuteStoredProcedure(string storedProcedureName, params object[] arguments); T ExecuteStoredProcedure<T>(StoredProcedure procedureObject); T ExecuteStoredProcedure<T>(string storedProcedureName, params object[] arguments); V GetColumnValue<T, V>(Expression<Func<T, V>> selector, Expression<Func<T, bool>> criteria); T GetObject<T>(Expression<Func<T, bool>> criteria); T GetObject<T>(object primaryKey, string additionalPredicate = null); T GetObject<T>(object[] primaryKey, string additionalPredicate = null); ObjectSet<T> GetObjectSet<T>(); ObjectSet<T> GetObjectSet<T>(Expression<Func<T, bool>> condition); ObjectSet<T> GetObjectSet<T>(string sql, params object[] args); ObjectSet<T> GetObjectSet<T>(IQuery query); T GetScalarValue<T>(string sql, params object[] args); bool PersistChanges<TEntity>(TEntity entity, bool isToDelete = false) where TEntity : Entity.Entity; void Update<T>(Expression<Func<T, bool>> criteria, params object[] setArguments); //void Update<T>(T data); void Load<TEntity>(TEntity entity) where TEntity : Entity.Entity; void Delete<TEntity>(TEntity entity); void Insert<T>(T data); ObjectReader<T> GetObjectReader<T>(IQuery query); ObjectReader<T> GetObjectReader<T>(); ObjectReader<T> GetObjectReader<T>(Expression<Func<T, bool>> condition); ObjectReader<T> GetObjectReader<T>(string sql, params object[] args); } }
using System; using System.Linq.Expressions; using RabbitDB.Query; namespace RabbitDB.Base { internal interface IDbSession : ITransactionalSession, IDisposable { void ExecuteCommand(string sql, params object[] args); void ExecuteStoredProcedure(StoredProcedure procedureObject); void ExecuteStoredProcedure(string storedProcedureName, params object[] arguments); T ExecuteStoredProcedure<T>(StoredProcedure procedureObject); T ExecuteStoredProcedure<T>(string storedProcedureName, params object[] arguments); V GetColumnValue<T, V>(Expression<Func<T, V>> selector, Expression<Func<T, bool>> criteria); T GetObject<T>(Expression<Func<T, bool>> criteria); T GetObject<T>(object primaryKey, string additionalPredicate = null); T GetObject<T>(object[] primaryKey, string additionalPredicate = null); ObjectSet<T> GetObjectSet<T>(); ObjectSet<T> GetObjectSet<T>(Expression<Func<T, bool>> condition); ObjectSet<T> GetObjectSet<T>(string sql, params object[] args); ObjectSet<T> GetObjectSet<T>(IQuery query); T GetScalarValue<T>(string sql, params object[] args); bool PersistChanges<TEntity>(TEntity entity, bool isToDelete = false) where TEntity : Entity.Entity; void Update<T>(Expression<Func<T, bool>> criteria, params object[] setArguments); //void Update<T>(T data); void Load<TEntity>(TEntity entity) where TEntity : Entity.Entity; void Delete<TEntity>(TEntity entity); void Insert<T>(T data); ObjectReader<T> GetObjectReader<T>(IQuery query); } }
apache-2.0
C#
0a1e6a82739101f3c2db1b6b8a859cfe3dcddec7
Fix storyboard video playback when not starting at beginning of beatmap
ppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,smoogipooo/osu,ppy/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,peppy/osu,peppy/osu
osu.Game/Storyboards/Drawables/DrawableStoryboardVideo.cs
osu.Game/Storyboards/Drawables/DrawableStoryboardVideo.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Video; using osu.Game.Beatmaps; namespace osu.Game.Storyboards.Drawables { public class DrawableStoryboardVideo : CompositeDrawable { public readonly StoryboardVideo Video; private Video video; public override bool RemoveWhenNotAlive => false; public DrawableStoryboardVideo(StoryboardVideo video) { Video = video; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader(true)] private void load(IBindable<WorkingBeatmap> beatmap, TextureStore textureStore) { var path = beatmap.Value.BeatmapSetInfo?.Files?.Find(f => f.Filename.Equals(Video.Path, StringComparison.OrdinalIgnoreCase))?.FileInfo.StoragePath; if (path == null) return; var stream = textureStore.GetStream(path); if (stream == null) return; InternalChild = video = new Video(stream, false) { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, Anchor = Anchor.Centre, Origin = Anchor.Centre, Alpha = 0, }; } protected override void LoadComplete() { base.LoadComplete(); if (video == null) return; using (video.BeginAbsoluteSequence(Video.StartTime)) { Schedule(() => video.PlaybackPosition = Time.Current - Video.StartTime); video.FadeIn(500); } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Video; using osu.Game.Beatmaps; namespace osu.Game.Storyboards.Drawables { public class DrawableStoryboardVideo : CompositeDrawable { public readonly StoryboardVideo Video; private Video video; public override bool RemoveWhenNotAlive => false; public DrawableStoryboardVideo(StoryboardVideo video) { Video = video; RelativeSizeAxes = Axes.Both; } [BackgroundDependencyLoader(true)] private void load(IBindable<WorkingBeatmap> beatmap, TextureStore textureStore) { var path = beatmap.Value.BeatmapSetInfo?.Files?.Find(f => f.Filename.Equals(Video.Path, StringComparison.OrdinalIgnoreCase))?.FileInfo.StoragePath; if (path == null) return; var stream = textureStore.GetStream(path); if (stream == null) return; InternalChild = video = new Video(stream, false) { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, Anchor = Anchor.Centre, Origin = Anchor.Centre, Alpha = 0, }; } protected override void LoadComplete() { base.LoadComplete(); if (video == null) return; video.PlaybackPosition = Clock.CurrentTime - Video.StartTime; using (video.BeginAbsoluteSequence(0)) video.FadeIn(500); } } }
mit
C#
f181e6cbd41364b3658824c9626a30ca60db6ec3
Add NaN check
EasyPeasyLemonSqueezy/MadCat
MadCat/NutEngine/Physics/Collider/ResolveCollision.cs
MadCat/NutEngine/Physics/Collider/ResolveCollision.cs
using Microsoft.Xna.Framework; using NutEngine.Physics.Shapes; using System; namespace NutEngine.Physics { public static partial class Collider { public static void ResolveCollision(Collision collision) { var relVelocity = collision.B.Velocity - collision.A.Velocity; var velocityAlongNormal = Vector2.Dot(relVelocity, collision.Manifold.Normal); // Only if objects moving towards each other if (velocityAlongNormal > 0) { return; } // https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331 float e = Math.Min(collision.A.Material.Restitution, collision.B.Material.Restitution); float j = -(1 + e) * velocityAlongNormal / (collision.A.Mass.MassInv + collision.B.Mass.MassInv); collision.A.ApplyImpulse(-j * collision.Manifold.Normal); collision.B.ApplyImpulse(j * collision.Manifold.Normal); var tangent = relVelocity - (collision.Manifold.Normal * Vector2.Dot(relVelocity, collision.Manifold.Normal)); tangent.Normalize(); float jt = -Vector2.Dot(relVelocity, tangent) / (collision.A.Mass.MassInv + collision.B.Mass.MassInv); if (Single.IsNaN(jt)) { return; } var staticFriction = (float)Math.Sqrt(collision.A.Material.StaticFriction * collision.B.Material.StaticFriction); var dynamicFriction = (float)Math.Sqrt(collision.A.Material.DynamicFriction * collision.B.Material.DynamicFriction); var tangentImpulse = Math.Abs(jt) < j * staticFriction ? tangent * jt : tangent * (-j) * dynamicFriction; collision.A.ApplyImpulse(-tangentImpulse); collision.B.ApplyImpulse(tangentImpulse); } } }
using Microsoft.Xna.Framework; using NutEngine.Physics.Shapes; using System; namespace NutEngine.Physics { public static partial class Collider { public static void ResolveCollision(Collision collision) { var relVelocity = collision.B.Velocity - collision.A.Velocity; var velocityAlongNormal = Vector2.Dot(relVelocity, collision.Manifold.Normal); // Only if objects moving towards each other if (velocityAlongNormal > 0) { return; } // https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331 float e = Math.Min(collision.A.Material.Restitution, collision.B.Material.Restitution); float j = -(1 + e) * velocityAlongNormal / (collision.A.Mass.MassInv + collision.B.Mass.MassInv); collision.A.ApplyImpulse(-j * collision.Manifold.Normal); collision.B.ApplyImpulse(j * collision.Manifold.Normal); var tangent = relVelocity - (collision.Manifold.Normal * Vector2.Dot(relVelocity, collision.Manifold.Normal)); tangent.Normalize(); float jt = -Vector2.Dot(relVelocity, tangent) / (collision.A.Mass.MassInv + collision.B.Mass.MassInv); var staticFriction = (float)Math.Sqrt(collision.A.Material.StaticFriction * collision.B.Material.StaticFriction); var dynamicFriction = (float)Math.Sqrt(collision.A.Material.DynamicFriction * collision.B.Material.DynamicFriction); var tangentImpulse = Math.Abs(jt) < j * staticFriction ? tangent * jt : tangent * (-j) * dynamicFriction; collision.A.ApplyImpulse(-tangentImpulse); collision.B.ApplyImpulse(tangentImpulse); } } }
mit
C#
28ab6072a82fa85abe1d556c9d2b3eb21567a603
Make the WrappedTransaction property of ProfiledDbTransaction become public because in some use cases (eg. Sql Server Bulk insert) this reference is needed.
MiniProfiler/dotnet,MiniProfiler/dotnet
StackExchange.Profiling/Data/ProfiledDbTransaction.cs
StackExchange.Profiling/Data/ProfiledDbTransaction.cs
using System; using System.Data.Common; using System.Data; #pragma warning disable 1591 // xml doc comments warnings namespace StackExchange.Profiling.Data { public class ProfiledDbTransaction : DbTransaction { private ProfiledDbConnection _conn; private DbTransaction _trans; public ProfiledDbTransaction(DbTransaction transaction, ProfiledDbConnection connection) { if (transaction == null) throw new ArgumentNullException("transaction"); if (connection == null) throw new ArgumentNullException("connection"); this._trans = transaction; this._conn = connection; } protected override DbConnection DbConnection { get { return _conn; } } public DbTransaction WrappedTransaction { get { return _trans; } } public override IsolationLevel IsolationLevel { get { return _trans.IsolationLevel; } } public override void Commit() { _trans.Commit(); } public override void Rollback() { _trans.Rollback(); } protected override void Dispose(bool disposing) { if (disposing && _trans != null) { _trans.Dispose(); } _trans = null; _conn = null; base.Dispose(disposing); } } } #pragma warning restore 1591 // xml doc comments warnings
using System; using System.Data.Common; using System.Data; #pragma warning disable 1591 // xml doc comments warnings namespace StackExchange.Profiling.Data { public class ProfiledDbTransaction : DbTransaction { private ProfiledDbConnection _conn; private DbTransaction _trans; public ProfiledDbTransaction(DbTransaction transaction, ProfiledDbConnection connection) { if (transaction == null) throw new ArgumentNullException("transaction"); if (connection == null) throw new ArgumentNullException("connection"); this._trans = transaction; this._conn = connection; } protected override DbConnection DbConnection { get { return _conn; } } internal DbTransaction WrappedTransaction { get { return _trans; } } public override IsolationLevel IsolationLevel { get { return _trans.IsolationLevel; } } public override void Commit() { _trans.Commit(); } public override void Rollback() { _trans.Rollback(); } protected override void Dispose(bool disposing) { if (disposing && _trans != null) { _trans.Dispose(); } _trans = null; _conn = null; base.Dispose(disposing); } } } #pragma warning restore 1591 // xml doc comments warnings
mit
C#
7b88a5613aef3f942f7c289c3f27f7b529e885cf
Update VerbatimMultiLineEscapeQuotes.cs
maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,bigown/SOpt,maniero/SOpt,bigown/SOpt,maniero/SOpt,maniero/SOpt
CSharp/String/VerbatimMultiLineEscapeQuotes.cs
CSharp/String/VerbatimMultiLineEscapeQuotes.cs
public class Program { public static void Main() { var html = @"< !DOCTYPE html > <html lang = ""pt_BR""> <head> <meta charset = ""utf-8""> <meta http - equiv = ""X-UA-Compatible"" content = ""IE=edge""> <meta name = ""viewport"" content = ""width=device-width, initial-scale=1""> <title> Aviso de Produto</title> <link rel = ""stylesheet"" href = ""http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css""> <script src = ""http://imsky.github.com/holder/holder.js""></script> </head> <body> <div class=""container""> <hr/> <h2>Aviso de Produto</h2> <div class=""row""> <div id = ""items -list"" class=""col-xs-8""> <div class=""media""> <a class=""media -left"" href=""#""> <img alt = ""64x64"" width=""150"" height=""100"" src=""http://media.webdevacademy.com.br/2014/02/placeholder.jpg""> </a> <div class=""media -body""> <h4 class=""media -heading"">Titulo</h4> Cras sit amet nibh libero, in gravida nulla.Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.Fusce condimentum nunc ac nisi vulputate fringilla.Donec lacinia congue felis in faucibus. </div> </div> </div> </div> <hr/> <footer class""footer -inverse""> <div class=""container""> <p class=""text -muted"">&copy;2017 - Modelo Exemplo Onofre.</p> </div> </footer> <script src = ""https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js""></script> <script src = ""http://netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js""></script> </body> </html>"; System.Console.WriteLine(html); } } //http://pt.stackoverflow.com/q/191611/101
public class Program { public static void Main() { var html = @"< !DOCTYPE html > < html lang = ""pt_BR""> < head > < meta charset = ""utf-8"" > < meta http - equiv = ""X-UA-Compatible"" content = ""IE=edge"" > < meta name = ""viewport"" content = ""width=device-width, initial-scale=1"" > < title > Aviso de Produto</ title > < link rel = ""stylesheet"" href = ""http://netdna.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css"" > < script src = ""http://imsky.github.com/holder/holder.js"" ></ script > </ head > < body > < div class=""container"" > < hr /> <h2>Aviso de Produto</h2> < div class=""row""> <div id = ""items -list"" class=""col-xs-8""> <div class=""media""> <a class=""media -left"" href=""#""> <img alt = ""64x64"" width=""150"" height=""100"" src=""http://media.webdevacademy.com.br/2014/02/placeholder.jpg""> </a> < div class=""media -body""> <h4 class=""media -heading"">Titulo</h4> Cras sit amet nibh libero, in gravida nulla.Nulla vel metus scelerisque ante sollicitudin commodo. Cras purus odio, vestibulum in vulputate at, tempus viverra turpis.Fusce condimentum nunc ac nisi vulputate fringilla.Donec lacinia congue felis in faucibus. </div> </div> </div> </div> <hr /> < footer class""footer -inverse""> <div class=""container""> <p class=""text -muted"">&copy;2017 - Modelo Exemplo Onofre.</p> </div> </footer> <script src = ""https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"" ></ script > <script src = ""http://netdna.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"" ></ script > </ body > </ html >"; System.Console.WriteLine(html); } } //http://pt.stackoverflow.com/q/191611/101
mit
C#
71f23a659d378446003182557a57cae11c2181c9
Update ExportRangeofCells.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,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET
Examples/CSharp/Articles/ExportRangeofCells.cs
Examples/CSharp/Articles/ExportRangeofCells.cs
using System.IO; using Aspose.Cells; using Aspose.Cells.Rendering; using System.Drawing.Imaging; namespace Aspose.Cells.Examples.Articles { public class ExportRangeofCells { public static void Main() { //ExStart:1 // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir+ "aspose-sample.xlsx"; //Create workbook from source file. Workbook workbook = new Workbook(filePath); //Access the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Set the print area with your desired range worksheet.PageSetup.PrintArea = "E12:H16"; //Set all margins as 0 worksheet.PageSetup.LeftMargin = 0; worksheet.PageSetup.RightMargin = 0; worksheet.PageSetup.TopMargin = 0; worksheet.PageSetup.BottomMargin = 0; //Set OnePagePerSheet option as true ImageOrPrintOptions options = new ImageOrPrintOptions(); options.OnePagePerSheet = true; options.ImageFormat = ImageFormat.Jpeg; //Take the image of your worksheet SheetRender sr = new SheetRender(worksheet, options); sr.ToImage(0, dataDir+ "output.out.jpg"); //ExEnd:1 } } }
using System.IO; using Aspose.Cells; using Aspose.Cells.Rendering; using System.Drawing.Imaging; namespace Aspose.Cells.Examples.Articles { public class ExportRangeofCells { public static void Main() { // The path to the documents directory. string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); string filePath = dataDir+ "aspose-sample.xlsx"; //Create workbook from source file. Workbook workbook = new Workbook(filePath); //Access the first worksheet Worksheet worksheet = workbook.Worksheets[0]; //Set the print area with your desired range worksheet.PageSetup.PrintArea = "E12:H16"; //Set all margins as 0 worksheet.PageSetup.LeftMargin = 0; worksheet.PageSetup.RightMargin = 0; worksheet.PageSetup.TopMargin = 0; worksheet.PageSetup.BottomMargin = 0; //Set OnePagePerSheet option as true ImageOrPrintOptions options = new ImageOrPrintOptions(); options.OnePagePerSheet = true; options.ImageFormat = ImageFormat.Jpeg; //Take the image of your worksheet SheetRender sr = new SheetRender(worksheet, options); sr.ToImage(0, dataDir+ "output.out.jpg"); } } }
mit
C#
41c669dc2e9d974786eb4b6e8791c4f7c5a052c4
Fix packaging
Catel/Catel.Fody
build.cake
build.cake
// Define the required parameters var DefaultSolutionName = "Catel.Fody"; var DefaultCompany = "CatenaLogic"; var DefaultRepositoryUrl = string.Format("https://github.com/{0}/{1}", "Catel", DefaultSolutionName); var StartYear = 2010; // Note: the rest of the variables should be coming from the build server, // see `/deployment/cake/*-variables.cake` for customization options //======================================================= // Components var ComponentsToBuild = new string[] { "Catel.Fody", "Catel.Fody.Attributes", }; //======================================================= // WPF apps var WpfAppsToBuild = new string[] { }; //======================================================= // UWP apps var UwpAppsToBuild = new string[] { }; //======================================================= // Test projects var TestProjectsToBuild = new string[] { "Catel.Fody.Tests" }; //======================================================= // Now all variables are defined, include the tasks, that // script will take care of the rest of the magic #l "./deployment/cake/tasks.cake"
// Define the required parameters var DefaultSolutionName = "Catel.Fody"; var DefaultCompany = "CatenaLogic"; var DefaultRepositoryUrl = string.Format("https://github.com/{0}/{1}", "Catel", DefaultSolutionName); var StartYear = 2010; // Note: the rest of the variables should be coming from the build server, // see `/deployment/cake/*-variables.cake` for customization options //======================================================= // Components var ComponentsToBuild = new string[] { "Catel.Fody.Attributes", }; //======================================================= // WPF apps var WpfAppsToBuild = new string[] { }; //======================================================= // UWP apps var UwpAppsToBuild = new string[] { }; //======================================================= // Test projects var TestProjectsToBuild = new string[] { "Catel.Fody.Tests" }; //======================================================= // Now all variables are defined, include the tasks, that // script will take care of the rest of the magic #l "./deployment/cake/tasks.cake"
mit
C#
bbe3e0a4ec104cf69ebac2a039a9bfc0e676f785
update build script
DelcoigneYves/Xamarin.GoogleAnalytics
build.cake
build.cake
#addin nuget:https://nuget.org/api/v2/?package=Cake.FileHelpers&version=1.0.3.2 #addin nuget:https://nuget.org/api/v2/?package=Cake.Xamarin&version=1.2.3 var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); var libraries = new Dictionary<string, string> { { "./src/Analytics.sln", "Any" }, }; var samples = new Dictionary<string, string> { { "./Sample/Sample.sln", "Win" }, }; var BuildAction = new Action<Dictionary<string, string>> (solutions => { foreach (var sln in solutions) { // If the platform is Any build regardless // If the platform is Win and we are running on windows build // If the platform is Mac and we are running on Mac, build if ((sln.Value == "Any") || (sln.Value == "Win" && IsRunningOnWindows ()) || (sln.Value == "Mac" && IsRunningOnUnix ())) { // Bit of a hack to use nuget3 to restore packages for project.json if (IsRunningOnWindows ()) { Information ("RunningOn: {0}", "Windows"); NuGetRestore (sln.Key, new NuGetRestoreSettings { ToolPath = "./tools/nuget3.exe" }); // Windows Phone / Universal projects require not using the amd64 msbuild MSBuild (sln.Key, c => { c.Configuration = "Release"; c.MSBuildPlatform = Cake.Common.Tools.MSBuild.MSBuildPlatform.x86; }); } else { // Mac is easy ;) NuGetRestore (sln.Key); DotNetBuild (sln.Key, c => c.Configuration = "Release"); } } } }); Task("Libraries").Does(()=> { BuildAction(libraries); }); Task ("NuGet") .IsDependentOn ("Libraries") .Does (() => { if(!DirectoryExists("./Build/nuget/")) CreateDirectory("./Build/nuget"); NuGetPack ("./nuget/Analytics.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./Build/nuget/", BasePath = "./", }); }); //Build the component, which build samples, nugets, and libraries Task ("Default").IsDependentOn("NuGet"); Task ("Clean").Does (() => { CleanDirectory ("./component/tools/"); CleanDirectories ("./Build/"); CleanDirectories ("./**/bin"); CleanDirectories ("./**/obj"); }); RunTarget (TARGET);
#addin nuget:https://nuget.org/api/v2/?package=Cake.FileHelpers&version=1.0.3.2 #addin nuget:https://nuget.org/api/v2/?package=Cake.Xamarin&version=1.2.3 var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); var libraries = new Dictionary<string, string> { { "./src/Analytics.sln", "Any" }, }; var samples = new Dictionary<string, string> { { "./Sample/Sample.sln", "Win" }, }; var BuildAction = new Action<Dictionary<string, string>> (solutions => { foreach (var sln in solutions) { // If the platform is Any build regardless // If the platform is Win and we are running on windows build // If the platform is Mac and we are running on Mac, build if ((sln.Value == "Any") || (sln.Value == "Win" && IsRunningOnWindows ()) || (sln.Value == "Mac" && IsRunningOnUnix ())) { // Bit of a hack to use nuget3 to restore packages for project.json if (IsRunningOnWindows ()) { Information ("RunningOn: {0}", "Windows"); NuGetRestore (sln.Key, new NuGetRestoreSettings { ToolPath = "./tools/nuget3.exe" }); // Windows Phone / Universal projects require not using the amd64 msbuild MSBuild (sln.Key, c => { c.Configuration = "Release"; c.MSBuildPlatform = Cake.Common.Tools.MSBuild.MSBuildPlatform.x86; }); } else { // Mac is easy ;) NuGetRestore (sln.Key); DotNetBuild (sln.Key, c => c.Configuration = "Release"); } } } }); Task("Libraries").Does(()=> { BuildAction(libraries); }); Task("Samples") .IsDependentOn("Libraries") .Does(()=> { BuildAction(samples); }); Task ("NuGet") .IsDependentOn ("Samples") .Does (() => { if(!DirectoryExists("./Build/nuget/")) CreateDirectory("./Build/nuget"); NuGetPack ("./nuget/Analytics.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./Build/nuget/", BasePath = "./", }); }); //Build the component, which build samples, nugets, and libraries Task ("Default").IsDependentOn("NuGet"); Task ("Clean").Does (() => { CleanDirectory ("./component/tools/"); CleanDirectories ("./Build/"); CleanDirectories ("./**/bin"); CleanDirectories ("./**/obj"); }); RunTarget (TARGET);
mit
C#
0518986d1108a29f5436ba3ea289f28cc8293cea
Update ObservableObject.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D
src/Core2D/ObservableObject.cs
src/Core2D/ObservableObject.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Immutable; using System.ComponentModel; using System.Runtime.CompilerServices; using Core2D.Attributes; namespace Core2D { /// <summary> /// Observable object base class. /// </summary> public abstract class ObservableObject : INotifyPropertyChanged { private string _id = null; private string _name = null; private ImmutableArray<ObservableObject> _resources = ImmutableArray.Create<ObservableObject>(); /// <summary> /// Gets or sets resource name. /// </summary> [Name] public string Id { get => _id; set => Update(ref _id, value); } /// <summary> /// Gets or sets resource name. /// </summary> public string Name { get => _name; set => Update(ref _name, value); } /// <summary> /// Gets or sets shape resources. /// </summary> public ImmutableArray<ObservableObject> Resources { get => _resources; set => Update(ref _resources, value); } /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify observers about property changes. /// </summary> /// <param name="propertyName">The property name that changed.</param> public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Update property backing field and notify observers about property change. /// </summary> /// <typeparam name="T">The type of field.</typeparam> /// <param name="field">The field to update.</param> /// <param name="value">The new field value.</param> /// <param name="propertyName">The property name that changed.</param> /// <returns>True if backing field value changed.</returns> public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; Notify(propertyName); return true; } return false; } /// <summary> /// Check whether the <see cref="Id"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeId() => !String.IsNullOrWhiteSpace(_id); /// <summary> /// Check whether the <see cref="Name"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeName() => !String.IsNullOrWhiteSpace(_name); /// <summary> /// Check whether the <see cref="Resources"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeResources() => _resources.IsEmpty == false; } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.ComponentModel; using System.Runtime.CompilerServices; namespace Core2D { /// <summary> /// Observable properties base class. /// </summary> public abstract class ObservableObject : INotifyPropertyChanged { /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// Notify observers about property changes. /// </summary> /// <param name="propertyName">The property name that changed.</param> public void Notify([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } /// <summary> /// Update property backing field and notify observers about property change. /// </summary> /// <typeparam name="T">The type of field.</typeparam> /// <param name="field">The field to update.</param> /// <param name="value">The new field value.</param> /// <param name="propertyName">The property name that changed.</param> /// <returns>True if backing field value changed.</returns> public bool Update<T>(ref T field, T value, [CallerMemberName] string propertyName = null) { if (!Equals(field, value)) { field = value; Notify(propertyName); return true; } return false; } } }
mit
C#
33b66afaee79030d43ed2441e4f4fd07c4bd51ab
Test are fixed
xtrmstep/MvcAjaxGridSample,xtrmstep/MvcAjaxGridSample
MvcAjaxGridSampleTests/Mocks/TestRepository.cs
MvcAjaxGridSampleTests/Mocks/TestRepository.cs
using MvcAjaxGridSample.Types.DataModel; using MvcAjaxGridSample.Types.DataStorage.Implementation; namespace MvcAjaxGridSampleTests.Mocks { internal class TestRepository : Repository<Book> { public TestRepository() { _internalStorage.Clear(); _internalStorage.Add(1, new Book { Id = 1, Title = "Book 1", IssueYear = 2001 }); _internalStorage.Add(2, new Book { Id = 2, Title = "Book 2", IssueYear = 2002 }); _internalStorage.Add(3, new Book { Id = 3, Title = "Book 3", IssueYear = 2003 }); _internalStorage.Add(4, new Book { Id = 4, Title = "Book 4", IssueYear = 2004 }); _internalStorage.Add(5, new Book { Id = 5, Title = "Book 5", IssueYear = 2005 }); } } }
using MvcAjaxGridSample.Types.DataModel; using MvcAjaxGridSample.Types.DataStorage.Implementation; namespace MvcAjaxGridSampleTests.Mocks { internal class TestRepository : Repository<Book> { public TestRepository() { _internalStorage.Add(1, new Book {Id = 1, Title = "Book 1", IssueYear = 2001}); _internalStorage.Add(2, new Book { Id = 2, Title = "Book 2", IssueYear = 2002 }); _internalStorage.Add(3, new Book { Id = 3, Title = "Book 3", IssueYear = 2003 }); _internalStorage.Add(4, new Book { Id = 4, Title = "Book 4", IssueYear = 2004 }); _internalStorage.Add(5, new Book { Id = 5, Title = "Book 5", IssueYear = 2005 }); } } }
mit
C#
980704f703996a0dbebc37ee5347e17ab4607ed5
Set version to 1.2
igece/SoxSharp
src/Properties/AssemblyInfo.cs
src/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("SoxSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("igece.labs")] [assembly: AssemblyProduct("SoxSharp")] [assembly: AssemblyCopyright("Copyright © 2017 igece.labs")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("43ffc71a-e6bb-4e6e-9f53-679a123f68b4")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general sobre un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos atributos para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("SoxSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("igece.labs")] [assembly: AssemblyProduct("SoxSharp")] [assembly: AssemblyCopyright("Copyright © 2017 igece.labs")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible como false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible como true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("43ffc71a-e6bb-4e6e-9f53-679a123f68b4")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o establecer como predeterminados los números de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.1.0.0")] [assembly: AssemblyFileVersion("1.1.0.0")]
apache-2.0
C#
2e27503637cbd4d94646157aaf4bb414164e8187
fix session.Dispose
Ahoo-Wang/SmartSql
SmartSql/DbSession/DbConnectionSessionStore.cs
SmartSql/DbSession/DbConnectionSessionStore.cs
using Microsoft.Extensions.Logging; using SmartSql.Abstractions.DbSession; using SmartSql.Exceptions; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace SmartSql.DbSession { /// <summary> /// DbConnection Session Store /// </summary> public class DbConnectionSessionStore : IDbConnectionSessionStore { private readonly ILogger _logger; const string KEY = "SmartSql-Local-DbSesstion-"; protected string sessionName = string.Empty; private static AsyncLocal<IDictionary<string, IDbConnectionSession>> staticSessions = new AsyncLocal<IDictionary<string, IDbConnectionSession>>(); public DbConnectionSessionStore(ILoggerFactory loggerFactory, String smartSqlMapperId) { _logger = loggerFactory.CreateLogger<DbConnectionSessionStore>(); sessionName = KEY + smartSqlMapperId; } public IDbConnectionSession LocalSession { get { if (staticSessions.Value == null) { return null; }; staticSessions.Value.TryGetValue(sessionName, out IDbConnectionSession session); return session; } } public void Dispose() { if (staticSessions.Value != null) { staticSessions.Value[sessionName].Dispose(); staticSessions.Value[sessionName] = null; } } public void Store(IDbConnectionSession session) { if (staticSessions.Value == null) { staticSessions.Value = new Dictionary<String, IDbConnectionSession>(); } staticSessions.Value[sessionName] = session; } } }
using Microsoft.Extensions.Logging; using SmartSql.Abstractions.DbSession; using SmartSql.Exceptions; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace SmartSql.DbSession { /// <summary> /// DbConnection Session Store /// </summary> public class DbConnectionSessionStore : IDbConnectionSessionStore { private readonly ILogger _logger; const string KEY = "SmartSql-Local-DbSesstion-"; protected string sessionName = string.Empty; private static AsyncLocal<IDictionary<string, IDbConnectionSession>> staticSessions = new AsyncLocal<IDictionary<string, IDbConnectionSession>>(); public DbConnectionSessionStore(ILoggerFactory loggerFactory, String smartSqlMapperId) { _logger = loggerFactory.CreateLogger<DbConnectionSessionStore>(); sessionName = KEY + smartSqlMapperId; } public IDbConnectionSession LocalSession { get { if (staticSessions.Value == null) { return null; }; staticSessions.Value.TryGetValue(sessionName, out IDbConnectionSession session); return session; } } public void Dispose() { if (staticSessions.Value != null) { staticSessions.Value[sessionName] = null; } } public void Store(IDbConnectionSession session) { if (staticSessions.Value == null) { staticSessions.Value = new Dictionary<String, IDbConnectionSession>(); } staticSessions.Value[sessionName] = session; } } }
apache-2.0
C#
a0c075e42f96b26f3cf96a0eec1e02c5878dc8d7
Implement smart playlists limited by file size and duration. Fixes BGO
GNOME/hyena,dufoli/hyena,petejohanson/hyena,arfbtwn/hyena,petejohanson/hyena,dufoli/hyena,GNOME/hyena,arfbtwn/hyena
Hyena/Hyena.Query/QueryOrder.cs
Hyena/Hyena.Query/QueryOrder.cs
// // QueryOrder.cs // // Authors: // Gabriel Burt <gburt@novell.com> // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; namespace Hyena.Query { public class QueryOrder { private string name; public string Name { get { return name; } } private string label; public string Label { get { return label; } set { label = value; } } private string order_sql; public string OrderSql { get { return order_sql; } } public QueryOrder (string name, string label, string order_sql) { this.name = name; this.label = label; this.order_sql = order_sql; } public string ToSql () { return String.Format ("ORDER BY {0}", order_sql); } } }
// // QueryOrder.cs // // Authors: // Gabriel Burt <gburt@novell.com> // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2007-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text; using System.Collections.Generic; namespace Hyena.Query { public class QueryOrder { private string name; public string Name { get { return name; } } private string label; public string Label { get { return label; } set { label = value; } } private string order_sql; public string OrderSql { get { return order_sql; } } public QueryOrder (string name, string label, string order_sql) { this.name = name; this.label = label; this.order_sql = order_sql; } public string ToSql () { return String.Format ("ORDER BY {0}", order_sql); } public string PruneSql (QueryLimit limit, IntegerQueryValue limit_value) { /*"SELECT {0}, {1} FROM {2}", "OrderID", limit.Column, "CoreCache"; long limit = limit_value.IntValue * limit.Factor; long sum = 0; int? limit_id = null; foreach (result) { sum += result[1]; if (sum >= limit) { limit_id = result[0]; break; } } if (limit_id != null) { "DELETE FROM {0} WHERE {1} > {2}", "CoreCache", "OrderID", limit_id }*/ return null; } } }
mit
C#
ffef6c9408d94b1eb967083cedddfe56af8007b2
Add new file userAuth.cpl/Droid/MainActivity.cs
ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl
userAuth.cpl/Droid/MainActivity.cs
userAuth.cpl/Droid/MainActivity.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace userAuth.cpl.Droid { [Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)] public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); // Create your apponlication here } } }
� using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace userAuth.cpl.Droid { [Activity (Label = "userAuth.cpl.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = Android.Content.PM.ConfigChanges.Density | Android.Content.PM.ConfigChanges.Touchscreen)] public class MainActivity : global::Xamarin.Forms.Platform.Android.ActivityIndicatorRenderer { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); // Create your apponlication here } } }
mit
C#
eee024ba96f4165c5bcc6f4a330a9435006b5a4d
Update FastBinaryBondDeserializer.cs
tiksn/TIKSN-Framework
TIKSN.Core/Serialization/Bond/FastBinaryBondDeserializer.cs
TIKSN.Core/Serialization/Bond/FastBinaryBondDeserializer.cs
using Bond.IO.Safe; using Bond.Protocols; namespace TIKSN.Serialization.Bond { public class FastBinaryBondDeserializer : DeserializerBase<byte[]> { protected override T DeserializeInternal<T>(byte[] serial) { var input = new InputBuffer(serial); var reader = new FastBinaryReader<InputBuffer>(input); return global::Bond.Deserialize<T>.From(reader); } } }
using Bond.IO.Safe; using Bond.Protocols; namespace TIKSN.Serialization.Bond { public class FastBinaryBondDeserializer : DeserializerBase<byte[]> { protected override T DeserializeInternal<T>(byte[] serial) { var input = new InputBuffer(serial); var reader = new FastBinaryReader<InputBuffer>(input); return global::Bond.Deserialize<T>.From(reader); } } }
mit
C#
3f294ef880769877cba257d668521ceb00e5872b
Improve assertion granularity
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Common/Tooling/ProcessExtensions.cs
source/Nuke.Common/Tooling/ProcessExtensions.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using Newtonsoft.Json.Linq; using Nuke.Common.IO; using Nuke.Common.Utilities; namespace Nuke.Common.Tooling { [PublicAPI] [DebuggerStepThrough] [DebuggerNonUserCode] public static class ProcessExtensions { [AssertionMethod] public static IProcess AssertWaitForExit( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { ControlFlow.Assert(process != null , "process != null"); ControlFlow.Assert(process.WaitForExit(), "process.WaitForExit()"); return process; } [AssertionMethod] public static IProcess AssertZeroExitCode( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { process.AssertWaitForExit(); if (process.ExitCode != 0) throw new ProcessException(process); return process; } public static IReadOnlyCollection<Output> EnsureOnlyStd(this IReadOnlyCollection<Output> output) { foreach (var o in output) ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std"); return output; } public static string StdToText(this IEnumerable<Output> output) { return output.Where(x => x.Type == OutputType.Std) .Select(x => x.Text) .JoinNewLine(); } public static T StdToJson<T>(this IEnumerable<Output> output) { return SerializationTasks.JsonDeserialize<T>(output.StdToText()); } public static JObject StdToJson(this IEnumerable<Output> output) { return output.StdToJson<JObject>(); } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using Newtonsoft.Json.Linq; using Nuke.Common.IO; using Nuke.Common.Utilities; namespace Nuke.Common.Tooling { [PublicAPI] [DebuggerStepThrough] [DebuggerNonUserCode] public static class ProcessExtensions { [AssertionMethod] public static IProcess AssertWaitForExit( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { ControlFlow.Assert(process != null && process.WaitForExit(), "process != null && process.WaitForExit()"); return process; } [AssertionMethod] public static IProcess AssertZeroExitCode( [AssertionCondition(AssertionConditionType.IS_NOT_NULL)] [CanBeNull] this IProcess process) { process.AssertWaitForExit(); if (process.ExitCode != 0) throw new ProcessException(process); return process; } public static IReadOnlyCollection<Output> EnsureOnlyStd(this IReadOnlyCollection<Output> output) { foreach (var o in output) ControlFlow.Assert(o.Type == OutputType.Std, "o.Type == OutputType.Std"); return output; } public static string StdToText(this IEnumerable<Output> output) { return output.Where(x => x.Type == OutputType.Std) .Select(x => x.Text) .JoinNewLine(); } public static T StdToJson<T>(this IEnumerable<Output> output) { return SerializationTasks.JsonDeserialize<T>(output.StdToText()); } public static JObject StdToJson(this IEnumerable<Output> output) { return output.StdToJson<JObject>(); } } }
mit
C#
ef06156320cd9ecd34860b46ae3987a7c759ad5e
Allow enable and disable of ui pointer renderer
PearMed/Pear-Interaction-Engine
Scripts/UI/UIPointerRenderer.cs
Scripts/UI/UIPointerRenderer.cs
using Pear.InteractionEngine.Interactions; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pear.InteractionEngine.UI { /// <summary> /// Renderer for the UI pointer /// </summary> [RequireComponent(typeof(UIPointer))] public class UIPointerRenderer : MonoBehaviour { [Tooltip("Width of the line")] public float LineWidth = 0.005f; [Tooltip("The colour to change the pointer materials when the pointer collides with a valid object. Set to `Color.clear` to bypass changing material colour on valid collision.")] public Color validCollisionColor = Color.green; [Tooltip("The colour to change the pointer materials when the pointer is not colliding with anything or with an invalid object. Set to `Color.clear` to bypass changing material colour on invalid collision.")] public Color invalidCollisionColor = Color.red; // Pointer private UIPointer _pointer; // Line renderer private LineRenderer _line; void Awake() { _pointer = GetComponent<UIPointer>(); _line = gameObject.AddComponent<LineRenderer>(); _line.startWidth = _line.endWidth = LineWidth; _line.material.color = invalidCollisionColor; _pointer.HoverChangedEvent += (oldHovered, newHovered) => { _line.material.color = newHovered != null ? validCollisionColor : invalidCollisionColor; }; _pointer.IsActiveChangedEvent += isActive => _line.enabled = isActive; } /// <summary> /// Updates the pointer line /// </summary> void Update() { if (_pointer.IsActive) { Vector3 start = _pointer.GetOriginPosition(); Vector3 end = _pointer.HoveredElement != null ? _pointer.pointerEventData.pointerCurrentRaycast.worldPosition : start + _pointer.GetOriginForward() * 10; _line.SetPositions(new Vector3[] { start, end, }); } } private void OnEnable() { _line.enabled = true; } private void OnDisable() { _line.enabled = false; } } }
using Pear.InteractionEngine.Interactions; using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Pear.InteractionEngine.UI { /// <summary> /// Renderer for the UI pointer /// </summary> [RequireComponent(typeof(UIPointer))] public class UIPointerRenderer : MonoBehaviour { [Tooltip("Width of the line")] public float LineWidth = 0.005f; [Tooltip("The colour to change the pointer materials when the pointer collides with a valid object. Set to `Color.clear` to bypass changing material colour on valid collision.")] public Color validCollisionColor = Color.green; [Tooltip("The colour to change the pointer materials when the pointer is not colliding with anything or with an invalid object. Set to `Color.clear` to bypass changing material colour on invalid collision.")] public Color invalidCollisionColor = Color.red; // Pointer private UIPointer _pointer; // Line renderer private LineRenderer _line; void Start() { _pointer = GetComponent<UIPointer>(); _line = gameObject.AddComponent<LineRenderer>(); _line.startWidth = _line.endWidth = LineWidth; _line.material.color = invalidCollisionColor; _pointer.HoverChangedEvent += (oldHovered, newHovered) => { _line.material.color = newHovered != null ? validCollisionColor : invalidCollisionColor; }; _pointer.IsActiveChangedEvent += isActive => _line.enabled = isActive; } /// <summary> /// Updates the pointer line /// </summary> void Update() { if (_pointer.IsActive) { Vector3 start = _pointer.GetOriginPosition(); Vector3 end = _pointer.HoveredElement != null ? _pointer.pointerEventData.pointerCurrentRaycast.worldPosition : start + _pointer.GetOriginForward() * 10; _line.SetPositions(new Vector3[] { start, end, }); } } } }
mit
C#
e191b4e5a7d64f776e998d559c30c4782dc88a60
Update the Empty module template.
techwareone/Kooboo-CMS,jtm789/CMS,andyshao/CMS,andyshao/CMS,jtm789/CMS,andyshao/CMS,lingxyd/CMS,jtm789/CMS,Kooboo/CMS,Kooboo/CMS,lingxyd/CMS,techwareone/Kooboo-CMS,lingxyd/CMS,techwareone/Kooboo-CMS,Kooboo/CMS
Kooboo.CMS/Kooboo.CMS.ModuleArea/Areas/Empty/ModuleAction.cs
Kooboo.CMS/Kooboo.CMS.ModuleArea/Areas/Empty/ModuleAction.cs
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = ModuleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } }
#region License // // Copyright (c) 2013, Kooboo team // // Licensed under the BSD License // See the file LICENSE.txt for details. // #endregion using Kooboo.CMS.Sites.Extension.ModuleArea; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Kooboo.CMS.Sites.Extension; using Kooboo.CMS.ModuleArea.Areas.SampleModule.Models; namespace Kooboo.CMS.ModuleArea.Areas.Empty { [Kooboo.CMS.Common.Runtime.Dependency.Dependency(typeof(IModuleAction), Key = SampleAreaRegistration.ModuleName)] public class ModuleAction : IModuleAction { public void OnExcluded(Sites.Models.Site site) { // Add code here that will be executed when the module was excluded to the site. } public void OnIncluded(Sites.Models.Site site) { // Add code here that will be executed when the module was included to the site. } public void OnInstalling(ControllerContext controllerContext) { var moduleInfo = ModuleInfo.Get(SampleAreaRegistration.ModuleName); var installModel = new InstallModel(); Kooboo.CMS.Sites.Extension.PagePluginHelper.BindModel<InstallModel>(installModel, controllerContext); moduleInfo.DefaultSettings.CustomSettings["DatabaseServer"] = installModel.DatabaseServer; moduleInfo.DefaultSettings.CustomSettings["UserName"] = installModel.UserName; moduleInfo.DefaultSettings.CustomSettings["Password"] = installModel.Password; ModuleInfo.Save(moduleInfo); // Add code here that will be executed when the module installing. } public void OnUninstalling(ControllerContext controllerContext) { // Add code here that will be executed when the module uninstalling. } } }
bsd-3-clause
C#
95eac4dcccda6ac8466427d7fe165659e5387ed5
Add comments
chrkon/helix-toolkit,Iluvatar82/helix-toolkit,JeremyAnsel/helix-toolkit,holance/helix-toolkit,helix-toolkit/helix-toolkit
Source/HelixToolkit.SharpDX.Shared/Shaders/DefaultBuffers.cs
Source/HelixToolkit.SharpDX.Shared/Shaders/DefaultBuffers.cs
/* The MIT License (MIT) Copyright (c) 2018 Helix Toolkit contributors */ #if !NETFX_CORE namespace HelixToolkit.Wpf.SharpDX.Shaders #else namespace HelixToolkit.UWP.Shaders #endif { /// <summary> /// Default buffer names from shader code. Name must match shader code to bind proper buffer /// <para>Note: Constant buffer must match both name and struct size</para> /// </summary> public static class DefaultBufferNames { public static string GlobalTransformCB = "cbTransforms"; public static string ModelCB = "cbModel"; public static string LightCB = "cbLights"; public static string MaterialCB = "cbMaterial"; public static string BoneCB = "BoneSkinning"; public static string ClipParamsCB = "cbClipping"; public static string DiffuseMapTB = "texDiffuseMap"; public static string AlphaMapTB = "texAlphaMap"; public static string NormalMapTB = "texNormalMap"; public static string DisplacementMapTB = "texDisplacementMap"; public static string CubeMapTB = "texCubeMap"; public static string ShadowMapTB = "texShadowMap"; public static string BillboardTB = "billboardTexture"; } }
/* The MIT License (MIT) Copyright (c) 2018 Helix Toolkit contributors */ #if !NETFX_CORE namespace HelixToolkit.Wpf.SharpDX.Shaders #else namespace HelixToolkit.UWP.Shaders #endif { public static class DefaultBufferNames { public static string GlobalTransformCB = "cbTransforms"; public static string ModelCB = "cbModel"; public static string LightCB = "cbLights"; public static string MaterialCB = "cbMaterial"; public static string BoneCB = "BoneSkinning"; public static string ClipParamsCB = "cbClipping"; public static string DiffuseMapTB = "texDiffuseMap"; public static string AlphaMapTB = "texAlphaMap"; public static string NormalMapTB = "texNormalMap"; public static string DisplacementMapTB = "texDisplacementMap"; public static string CubeMapTB = "texCubeMap"; public static string ShadowMapTB = "texShadowMap"; public static string BillboardTB = "billboardTexture"; } //public static class DefaultConstantBufferDescriptions //{ // public static ConstantBufferDescription GlobalTransformCB = new ConstantBufferDescription(DefaultBufferNames.GlobalTransformCB, GlobalTransformStruct.SizeInBytes); // public static ConstantBufferDescription ModelCB = new ConstantBufferDescription(DefaultBufferNames.ModelCB, ModelStruct.SizeInBytes); // public static ConstantBufferDescription LightCB = new ConstantBufferDescription(DefaultBufferNames.LightCB, Model.LightsBufferModel.SizeInBytes); // public static ConstantBufferDescription MaterialCB = new ConstantBufferDescription(DefaultBufferNames.MaterialCB, MaterialStruct.SizeInBytes); // public static ConstantBufferDescription BoneCB = new ConstantBufferDescription(DefaultBufferNames.BoneCB, BoneMatricesStruct.SizeInBytes); // public static ConstantBufferDescription ClipParamsCB = new ConstantBufferDescription(DefaultBufferNames.ClipParamsCB, ClipPlaneStruct.SizeInBytes); //} //public static class DefaultTextureBufferDescriptions //{ // public static TextureDescription DiffuseMapTB = new TextureDescription(nameof(DiffuseMapTB), ShaderStage.Pixel); // public static TextureDescription AlphaMapTB = new TextureDescription(nameof(AlphaMapTB), ShaderStage.Pixel); // public static TextureDescription NormalMapTB = new TextureDescription(nameof(NormalMapTB), ShaderStage.Pixel); // public static TextureDescription DisplacementMapTB = new TextureDescription(nameof(DisplacementMapTB), ShaderStage.Pixel); // public static TextureDescription CubeMapTB = new TextureDescription(nameof(CubeMapTB), ShaderStage.Pixel); // public static TextureDescription ShadowMapTB = new TextureDescription(nameof(ShadowMapTB), ShaderStage.Pixel); // public static TextureDescription BillboardTB = new TextureDescription(nameof(BillboardTB), ShaderStage.Pixel); //} }
mit
C#
605d04580c479cdf6eae30b932fba10ae26d3a9e
Fix subnav on store pairing view (#3438)
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Views/UIStores/_Nav.cshtml
BTCPayServer/Views/UIStores/_Nav.cshtml
@using BTCPayServer.Client @{ var storeId = Context.GetStoreData()?.Id; } <div class="sticky-header-setup"></div> <header class="sticky-header mb-l"> <h2 class="mt-1 mb-2 mb-lg-4">Store Settings</h2> <nav id="SectionNav"> <div class="nav"> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.General))" class="nav-link @ViewData.IsActivePage(StoreNavPages.General)" asp-controller="UIStores" asp-action="GeneralSettings" asp-route-storeId="@storeId">General</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Rates))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Rates)" asp-controller="UIStores" asp-action="Rates" asp-route-storeId="@storeId">Rates</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.CheckoutAppearance))" class="nav-link @ViewData.IsActivePage(StoreNavPages.CheckoutAppearance)" asp-controller="UIStores" asp-action="CheckoutAppearance" asp-route-storeId="@storeId">Checkout Appearance</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Tokens))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Tokens)" asp-controller="UIStores" asp-action="ListTokens" asp-route-storeId="@storeId">Access Tokens</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Users))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Users)" asp-controller="UIStores" asp-action="StoreUsers" asp-route-storeId="@storeId">Users</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Integrations))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Integrations)" asp-controller="UIStores" asp-action="Integrations" asp-route-storeId="@storeId">Integrations</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Webhooks))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Webhooks)" asp-controller="UIStores" asp-action="Webhooks" asp-route-storeId="@storeId">Webhooks</a> <vc:ui-extension-point location="store-nav" model="@Model"/> </div> </nav> </header> <script> const { offsetHeight } = document.querySelector('.sticky-header-setup + .sticky-header'); document.documentElement.style.scrollPaddingTop = `calc(${offsetHeight}px + var(--btcpay-space-m))`; </script>
@using BTCPayServer.Client <div class="sticky-header-setup"></div> <header class="sticky-header mb-l"> <h2 class="mt-1 mb-2 mb-lg-4">Store Settings</h2> <nav id="SectionNav"> <div class="nav"> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.General))" class="nav-link @ViewData.IsActivePage(StoreNavPages.General)" asp-controller="UIStores" asp-action="GeneralSettings" asp-route-storeId="@Context.GetRouteValue("storeId")">General</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Rates))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Rates)" asp-controller="UIStores" asp-action="Rates" asp-route-storeId="@Context.GetRouteValue("storeId")">Rates</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.CheckoutAppearance))" class="nav-link @ViewData.IsActivePage(StoreNavPages.CheckoutAppearance)" asp-controller="UIStores" asp-action="CheckoutAppearance" asp-route-storeId="@Context.GetRouteValue("storeId")">Checkout Appearance</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Tokens))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Tokens)" asp-controller="UIStores" asp-action="ListTokens" asp-route-storeId="@Context.GetRouteValue("storeId")">Access Tokens</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Users))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Users)" asp-controller="UIStores" asp-action="StoreUsers" asp-route-storeId="@Context.GetRouteValue("storeId")">Users</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Integrations))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Integrations)" asp-controller="UIStores" asp-action="Integrations" asp-route-storeId="@Context.GetRouteValue("storeId")">Integrations</a> <a permission="@Policies.CanModifyStoreSettings" id="SectionNav-@(nameof(StoreNavPages.Webhooks))" class="nav-link @ViewData.IsActivePage(StoreNavPages.Webhooks)" asp-controller="UIStores" asp-action="Webhooks" asp-route-storeId="@Context.GetRouteValue("storeId")">Webhooks</a> <vc:ui-extension-point location="store-nav" model="@Model"/> </div> </nav> </header> <script> const { offsetHeight } = document.querySelector('.sticky-header-setup + .sticky-header'); document.documentElement.style.scrollPaddingTop = `calc(${offsetHeight}px + var(--btcpay-space-m))`; </script>
mit
C#
f039bca8a46a8ca6462375d861f0dbe4758fc197
Clarify variable name.
FacilityApi/Facility
src/Facility.Definition/Http/HttpServiceInfo.cs
src/Facility.Definition/Http/HttpServiceInfo.cs
using System.Collections.Generic; using System.Linq; namespace Facility.Definition.Http { /// <summary> /// The HTTP mapping for a service. /// </summary> public sealed class HttpServiceInfo { /// <summary> /// Creates an HTTP mapping for a service. /// </summary> public HttpServiceInfo(ServiceInfo serviceInfo) { Service = serviceInfo; foreach (var parameter in serviceInfo.GetHttpParameters()) { if (parameter.Name == "url") Url = parameter.Value; else throw parameter.CreateInvalidHttpParameterException(); } Methods = serviceInfo.Methods.Select(x => new HttpMethodInfo(x, serviceInfo)).ToList(); ErrorSets = serviceInfo.ErrorSets.Select(x => new HttpErrorSetInfo(x)).ToList(); var unexpectedHttpAttribute = serviceInfo.Dtos.AsEnumerable<IServiceElementInfo>() .Concat(serviceInfo.Dtos.SelectMany(x => x.Fields)) .Concat(serviceInfo.Enums) .Concat(serviceInfo.Enums.SelectMany(x => x.Values)) .Select(x => x.TryGetHttpAttribute()) .FirstOrDefault(x => x != null); if (unexpectedHttpAttribute != null) throw new ServiceDefinitionException("'http' attribute not supported on this element.", unexpectedHttpAttribute.Position); var methodsByRoute = Methods.OrderBy(x => x, HttpMethodInfo.ByRouteComparer).ToList(); for (int index = 1; index < methodsByRoute.Count; index++) { var left = methodsByRoute[index - 1]; var right = methodsByRoute[index]; if (HttpMethodInfo.ByRouteComparer.Compare(left, right) == 0) throw new ServiceDefinitionException($"Methods '{left.ServiceMethod.Name}' and '{right.ServiceMethod.Name}' have the same route: {right.Method} {right.Path}", right.ServiceMethod.Position); } } /// <summary> /// The service. /// </summary> public ServiceInfo Service { get; } /// <summary> /// The URL of the HTTP service. /// </summary> public string Url { get; } /// <summary> /// The HTTP mapping for the methods. /// </summary> public IReadOnlyList<HttpMethodInfo> Methods { get; } /// <summary> /// The HTTP mapping for the error sets. /// </summary> public IReadOnlyList<HttpErrorSetInfo> ErrorSets { get; } } }
using System.Collections.Generic; using System.Linq; namespace Facility.Definition.Http { /// <summary> /// The HTTP mapping for a service. /// </summary> public sealed class HttpServiceInfo { /// <summary> /// Creates an HTTP mapping for a service. /// </summary> public HttpServiceInfo(ServiceInfo serviceInfo) { Service = serviceInfo; foreach (var parameter in serviceInfo.GetHttpParameters()) { if (parameter.Name == "url") Url = parameter.Value; else throw parameter.CreateInvalidHttpParameterException(); } Methods = serviceInfo.Methods.Select(x => new HttpMethodInfo(x, serviceInfo)).ToList(); ErrorSets = serviceInfo.ErrorSets.Select(x => new HttpErrorSetInfo(x)).ToList(); var httpAttribute = serviceInfo.Dtos.AsEnumerable<IServiceElementInfo>() .Concat(serviceInfo.Dtos.SelectMany(x => x.Fields)) .Concat(serviceInfo.Enums) .Concat(serviceInfo.Enums.SelectMany(x => x.Values)) .Select(x => x.TryGetHttpAttribute()) .FirstOrDefault(x => x != null); if (httpAttribute != null) throw new ServiceDefinitionException("'http' attribute not supported on this element.", httpAttribute.Position); var methodsByRoute = Methods.OrderBy(x => x, HttpMethodInfo.ByRouteComparer).ToList(); for (int index = 1; index < methodsByRoute.Count; index++) { var left = methodsByRoute[index - 1]; var right = methodsByRoute[index]; if (HttpMethodInfo.ByRouteComparer.Compare(left, right) == 0) throw new ServiceDefinitionException($"Methods '{left.ServiceMethod.Name}' and '{right.ServiceMethod.Name}' have the same route: {right.Method} {right.Path}", right.ServiceMethod.Position); } } /// <summary> /// The service. /// </summary> public ServiceInfo Service { get; } /// <summary> /// The URL of the HTTP service. /// </summary> public string Url { get; } /// <summary> /// The HTTP mapping for the methods. /// </summary> public IReadOnlyList<HttpMethodInfo> Methods { get; } /// <summary> /// The HTTP mapping for the error sets. /// </summary> public IReadOnlyList<HttpErrorSetInfo> ErrorSets { get; } } }
mit
C#
eccbf67bd27fafba3d5cc96d9e56b52e628a4779
Rename observable
setchi/NotesEditor,setchi/NoteEditor
Assets/Scripts/SoundEffectPlayer.cs
Assets/Scripts/SoundEffectPlayer.cs
using System.Collections.Generic; using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; public class SoundEffectPlayer : MonoBehaviour { [SerializeField] AudioClip clap; [SerializeField] AudioClip click; void Awake() { var model = NotesEditorModel.Instance; var clapOffsetSamples = 1800; var editedDuringPlaybackObservable = Observable.Merge( model.BeatOffsetSamples.Select(_ => false), model.LongNoteObservable.Select(_ => false), model.LongNoteObservable.Select(_ => false)) .Where(_ => model.IsPlaying.Value); model.IsPlaying.Where(isPlaying => isPlaying) .Merge(editedDuringPlaybackObservable) .Select(_ => new Queue<int>( model.NoteObjects.Values .Select(noteObject => noteObject.notePosition.ToSamples(model.Audio.clip.frequency)) .Select(samples => samples + model.BeatOffsetSamples.Value) .Where(samples => model.Audio.timeSamples <= samples) .OrderBy(samples => samples) .Select(samples => samples - clapOffsetSamples))) .SelectMany(samplesQueue => this.LateUpdateAsObservable() .TakeWhile(_ => model.IsPlaying.Value) .TakeUntil(editedDuringPlaybackObservable.Skip(1)) .Select(_ => samplesQueue)) .Where(samplesQueue => samplesQueue.Count > 0) .Where(samplesQueue => samplesQueue.Peek() <= model.Audio.timeSamples) .Do(samplesQueue => samplesQueue.Dequeue()) .Where(_ => model.PlaySoundEffectEnabled.Value) .Subscribe(_ => AudioSource.PlayClipAtPoint(clap, Vector3.zero)); } }
using System.Collections.Generic; using System.Linq; using UniRx; using UniRx.Triggers; using UnityEngine; public class SoundEffectPlayer : MonoBehaviour { [SerializeField] AudioClip clap; [SerializeField] AudioClip click; void Awake() { var model = NotesEditorModel.Instance; var clapOffsetSamples = 1800; var notesChangeDuringPlayObservable = Observable.Merge( model.BeatOffsetSamples.Select(_ => false), model.LongNoteObservable.Select(_ => false), model.LongNoteObservable.Select(_ => false)) .Where(_ => model.IsPlaying.Value); model.IsPlaying.Where(isPlaying => isPlaying) .Merge(notesChangeDuringPlayObservable) .Select(_ => new Queue<int>( model.NoteObjects.Values .Select(noteObject => noteObject.notePosition.ToSamples(model.Audio.clip.frequency)) .Select(samples => samples + model.BeatOffsetSamples.Value) .Where(samples => model.Audio.timeSamples <= samples) .OrderBy(samples => samples) .Select(samples => samples - clapOffsetSamples))) .SelectMany(samplesQueue => this.LateUpdateAsObservable() .TakeWhile(_ => model.IsPlaying.Value) .TakeUntil(notesChangeDuringPlayObservable.Skip(1)) .Select(_ => samplesQueue)) .Where(samplesQueue => samplesQueue.Count > 0) .Where(samplesQueue => samplesQueue.Peek() <= model.Audio.timeSamples) .Do(samplesQueue => samplesQueue.Dequeue()) .Where(_ => model.PlaySoundEffectEnabled.Value) .Subscribe(_ => AudioSource.PlayClipAtPoint(clap, Vector3.zero)); } }
mit
C#
08d687a3d62fb5b2f273841e0a63888f5e78620c
Update EnumerableTests.cs
keith-hall/Extensions,keith-hall/Extensions
tests/EnumerableTests.cs
tests/EnumerableTests.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HallLibrary.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class EnumerableTests { [TestMethod] public void TestCountExceeds() { var src = Enumerable.Range(1, 4).Concat(new[] { 0 }).Select(s => 1 / s); // ReSharper disable once PossibleMultipleEnumeration Assert.AreEqual(src.CountExceeds(3), true); // just doing a Count would give a DivideByZero exception - this could also be demonstrated with the [ExpectedException(typeof(DivideByZeroException))] attribute on this method, but we want to test multiple conditions in a single method try { // ReSharper disable once PossibleMultipleEnumeration // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (src.Count() > 3) Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached."); else Assert.Fail("Count is greater than 3 so this line should never be reached."); } catch (DivideByZeroException) { } catch (Exception) { Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached."); } src = Enumerable.Range(1, 2); Assert.IsFalse(src.CountExceeds(2)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using HallLibrary.Extensions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class EnumerableTests { [TestMethod] public void TestCountExceeds() { var src = Enumerable.Range(1, 4).Concat(new[] { 0 }).Select(s => 1 / s); // ReSharper disable once PossibleMultipleEnumeration Assert.AreEqual(src.CountExceeds(3), true); // just doing a Count would give a DivideByZero exception try { // ReSharper disable once PossibleMultipleEnumeration // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (src.Count() > 3) Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached."); else Assert.Fail("Count is greater than 3 so this line should never be reached."); } catch (DivideByZeroException) { } catch (Exception) { Assert.Fail("The above should cause a DivideByZero Exception so this line should never be reached."); } src = Enumerable.Range(1, 2); Assert.IsFalse(src.CountExceeds(2)); } } }
apache-2.0
C#
784bc52a7dece2a5563f27072d02afda08a0816b
change connection to public
Raffaferreira/Neat.Procedure,achvaicer/Neat.Procedure
src/Neat.Procedure/Neat.Procedure/Connection.cs
src/Neat.Procedure/Neat.Procedure/Connection.cs
using System.Data.SqlClient; using System.Configuration; namespace Neat.Procedure { public static class Connection { private const string DefaultConnectionStringName = "Neat.Procedure.Settings.ConnectionString.Default"; private static string _connectionStringName; private static string _connectionString; private static string _ConnectionStringName { get { return _connectionStringName ?? DefaultConnectionStringName; } } private static string _ConnectionString { get { return _connectionString ?? ConfigurationManager.ConnectionStrings[_ConnectionStringName].ConnectionString; } } public static void ConnectionStringName(string connectionStringName) { _connectionStringName = connectionStringName; } public static void ConnectionString(string connectionString) { _connectionString = connectionString; } internal static bool EnsureIsOpened() { if (Instance == null || Instance.State != System.Data.ConnectionState.Open) { Close(); Instance = new SqlConnection(_ConnectionString); Instance.Open(); return true; } return false; } internal static SqlConnection Instance { get; private set; } internal static void Close() { Transaction.Close(); if (Instance == null) return; Instance.Close(); Instance.Dispose(); } } }
using System.Data.SqlClient; using System.Configuration; namespace Neat.Procedure { internal static class Connection { private const string DefaultConnectionStringName = "Neat.Procedure.Settings.ConnectionString.Default"; private static string _connectionStringName; private static string _connectionString; private static string _ConnectionStringName { get { return _connectionStringName ?? DefaultConnectionStringName; } } private static string _ConnectionString { get { return _connectionString ?? ConfigurationManager.ConnectionStrings[_ConnectionStringName].ConnectionString; } } public static void ConnectionStringName(string connectionStringName) { _connectionStringName = connectionStringName; } public static void ConnectionString(string connectionString) { _connectionString = connectionString; } internal static bool EnsureIsOpened() { if (Instance == null || Instance.State != System.Data.ConnectionState.Open) { Close(); Instance = new SqlConnection(_ConnectionString); Instance.Open(); return true; } return false; } internal static SqlConnection Instance { get; private set; } internal static void Close() { Transaction.Close(); if (Instance == null) return; Instance.Close(); Instance.Dispose(); } } }
mit
C#
2b7d5de7d688e05ee44a48c1e905bf737d74a469
update region tag missed in PR 1233
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
spanner/api/Spanner/GetDatabaseOperations.cs
spanner/api/Spanner/GetDatabaseOperations.cs
// Copyright 2020 Google Inc. // // 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. // [START spanner_list_database_operations] // [START spanner_get_database_operations] using Google.Cloud.Spanner.Admin.Database.V1; using Google.Cloud.Spanner.Common.V1; using System; namespace GoogleCloudSamples.Spanner { public class GetDatabaseOperations { public static object SpannerGetDatabaseOperations(string projectId, string instanceId) { // Create the DatabaseAdminClient instance. DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); var filter = "(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)"; ListDatabaseOperationsRequest request = new ListDatabaseOperationsRequest { ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId), Filter = filter }; // List the optimize restored databases operations on the instance. var operations = databaseAdminClient.ListDatabaseOperations(request); foreach (var operation in operations) { OptimizeRestoredDatabaseMetadata metadata = operation.Metadata.Unpack<OptimizeRestoredDatabaseMetadata>(); Console.WriteLine( $"Database {metadata.Name} restored from backup is " + $"{metadata.Progress.ProgressPercent}% optimized"); } return 0; } } } // [END spanner_get_database_operations] // [END spanner_list_database_operations]
// Copyright 2020 Google Inc. // // 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. // [START spanner_get_database_operations] using Google.Cloud.Spanner.Admin.Database.V1; using Google.Cloud.Spanner.Common.V1; using System; namespace GoogleCloudSamples.Spanner { public class GetDatabaseOperations { public static object SpannerGetDatabaseOperations(string projectId, string instanceId) { // Create the DatabaseAdminClient instance. DatabaseAdminClient databaseAdminClient = DatabaseAdminClient.Create(); var filter = "(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.OptimizeRestoredDatabaseMetadata)"; ListDatabaseOperationsRequest request = new ListDatabaseOperationsRequest { ParentAsInstanceName = InstanceName.FromProjectInstance(projectId, instanceId), Filter = filter }; // List the optimize restored databases operations on the instance. var operations = databaseAdminClient.ListDatabaseOperations(request); foreach (var operation in operations) { OptimizeRestoredDatabaseMetadata metadata = operation.Metadata.Unpack<OptimizeRestoredDatabaseMetadata>(); Console.WriteLine( $"Database {metadata.Name} restored from backup is " + $"{metadata.Progress.ProgressPercent}% optimized"); } return 0; } } } // [END spanner_get_database_operations]
apache-2.0
C#
0e98a738c53d832f93b59af8c79ac108321c455e
Remove shallow copy constructor
charlenni/Mapsui,charlenni/Mapsui,pauldendulk/Mapsui
Mapsui/GeometryLayer/GeometryFeature.cs
Mapsui/GeometryLayer/GeometryFeature.cs
using System; using System.Linq; using Mapsui.Extensions; using Mapsui.Geometries; using Mapsui.Layers; namespace Mapsui.GeometryLayer { public class GeometryFeature : BaseFeature, IGeometryFeature, IDisposable { private bool _disposed; public GeometryFeature() { } public GeometryFeature(IGeometry geometry) { Geometry = geometry; } public IGeometry Geometry { get; set; } public MRect? Extent => Geometry?.BoundingBox.ToMRect(); // Todo: Make not-nullable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~GeometryFeature() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { foreach (var keyValuePair in RenderedGeometry) { var disposable = keyValuePair.Value as IDisposable; disposable?.Dispose(); } RenderedGeometry.Clear(); } _disposed = true; } } }
using System; using System.Linq; using Mapsui.Extensions; using Mapsui.Geometries; using Mapsui.Layers; namespace Mapsui.GeometryLayer { public class GeometryFeature : BaseFeature, IGeometryFeature, IDisposable { private bool _disposed; public GeometryFeature() { } public GeometryFeature(IGeometry geometry) { Geometry = geometry; } public GeometryFeature(IGeometryFeature feature) { Geometry = feature.Geometry; RenderedGeometry = feature.RenderedGeometry.ToDictionary(entry => entry.Key, entry => entry.Value); Styles = feature.Styles.ToList(); foreach (var field in feature.Fields) this[field] = feature[field]; } public IGeometry Geometry { get; set; } public MRect? Extent => Geometry?.BoundingBox.ToMRect(); // Todo: Make not-nullable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } ~GeometryFeature() { Dispose(false); } protected virtual void Dispose(bool disposing) { if (_disposed) return; if (disposing) { foreach (var keyValuePair in RenderedGeometry) { var disposable = keyValuePair.Value as IDisposable; disposable?.Dispose(); } RenderedGeometry.Clear(); } _disposed = true; } } }
mit
C#
c951268a45d8c86cf3997c61b5a02a5569a48270
Update Index.cshtml
btevfik/MvcTestApp,btevfik/MvcTestApp,btevfik/MvcTestApp
MvcAppTest2/Views/Speakers/Index.cshtml
MvcAppTest2/Views/Speakers/Index.cshtml
@model IEnumerable<MvcAppTest2.Models.Speaker> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.EmailAdd) </th> <th> @Html.DisplayNameFor(model => model.BirthDay) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.EmailAdd) </td> <td> @Html.DisplayFor(modelItem => item.BirthDay) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.SpeakerID }) | @Html.ActionLink("Details", "Details", new { id=item.SpeakerID }) | @Html.ActionLink("Delete", "Delete", new { id=item.SpeakerID }) </td> </tr> } </table>
@model IEnumerable<MvcAppTest2.Models.Speaker> <script> $(function () { $("#testui").accordion(); }); </script> @{ ViewBag.Title = "Index"; } <h2>Index</h2> <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model => model.Name) </th> <th> @Html.DisplayNameFor(model => model.EmailAdd) </th> <th> @Html.DisplayNameFor(model => model.BirthDay) </th> </tr> @foreach (var item in Model) { <tr> <td> @Html.DisplayFor(modelItem => item.Name) </td> <td> @Html.DisplayFor(modelItem => item.EmailAdd) </td> <td> @Html.DisplayFor(modelItem => item.BirthDay) </td> <td> @Html.ActionLink("Edit", "Edit", new { id=item.SpeakerID }) | @Html.ActionLink("Details", "Details", new { id=item.SpeakerID }) | @Html.ActionLink("Delete", "Delete", new { id=item.SpeakerID }) </td> </tr> } </table> <div id="testui"> <h3>Test1</h3> <h3>Test2</h3> </div>
unlicense
C#
aca4b432e157c5e9063f551af8bff3de7641b744
Switch async void to async Task (#879)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
test/MusicStore.Test/Models/ShoppingCartTest.cs
test/MusicStore.Test/Models/ShoppingCartTest.cs
// Copyright (c) .NET Foundation. All rights reserved. // See License.txt in the project root for license information using System; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MusicStore.Models; using Xunit; namespace MusicStore.Test { public class ShoppingCartTest : IClassFixture<ShoppingCartFixture> { private readonly ShoppingCartFixture _fixture; public ShoppingCartTest(ShoppingCartFixture fixture) { _fixture = fixture; } [Fact] public async Task ComputesTotal() { var cartId = Guid.NewGuid().ToString(); using (var db = _fixture.CreateContext()) { var a = db.Albums.Add( new Album { Price = 15.99m }).Entity; db.CartItems.Add(new CartItem { Album = a, Count = 2, CartId = cartId }); db.SaveChanges(); Assert.Equal(31.98m, await ShoppingCart.GetCart(db, cartId).GetTotal()); } } } public class ShoppingCartFixture { private readonly IServiceProvider _serviceProvider; public ShoppingCartFixture() { var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider(); var services = new ServiceCollection(); services.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase("Scratch").UseInternalServiceProvider(efServiceProvider)); _serviceProvider = services.BuildServiceProvider(); } public virtual MusicStoreContext CreateContext() => _serviceProvider.GetRequiredService<MusicStoreContext>(); } }
// Copyright (c) .NET Foundation. All rights reserved. // See License.txt in the project root for license information using System; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using MusicStore.Models; using Xunit; namespace MusicStore.Test { public class ShoppingCartTest : IClassFixture<ShoppingCartFixture> { private readonly ShoppingCartFixture _fixture; public ShoppingCartTest(ShoppingCartFixture fixture) { _fixture = fixture; } [Fact] public async void ComputesTotal() { var cartId = Guid.NewGuid().ToString(); using (var db = _fixture.CreateContext()) { var a = db.Albums.Add( new Album { Price = 15.99m }).Entity; db.CartItems.Add(new CartItem { Album = a, Count = 2, CartId = cartId }); db.SaveChanges(); Assert.Equal(31.98m, await ShoppingCart.GetCart(db, cartId).GetTotal()); } } } public class ShoppingCartFixture { private readonly IServiceProvider _serviceProvider; public ShoppingCartFixture() { var efServiceProvider = new ServiceCollection().AddEntityFrameworkInMemoryDatabase().BuildServiceProvider(); var services = new ServiceCollection(); services.AddDbContext<MusicStoreContext>(b => b.UseInMemoryDatabase("Scratch").UseInternalServiceProvider(efServiceProvider)); _serviceProvider = services.BuildServiceProvider(); } public virtual MusicStoreContext CreateContext() => _serviceProvider.GetRequiredService<MusicStoreContext>(); } }
apache-2.0
C#
1368fdc5fb4b1d405e9d118fe088c36cf04f62f6
Update AlexanderKoehler.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/AlexanderKoehler.cs
src/Firehose.Web/Authors/AlexanderKoehler.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlexanderKoehler : IAmACommunityMember { public string FirstName => "Alexander"; public string LastName => "Koehler"; public string ShortBioOrTagLine => "father,system engineer, automation guy, powershell enthusiast"; public string StateOrRegion => "Mengen, Germany"; public string EmailAddress => "planetpowershell@it-koehler.com"; public string TwitterHandle => "ACharburner"; public string GravatarHash => "bc09e87a59be038b93da1e03079aa053"; public string GitHubHandle => "blog-it-koehler-com"; public GeoPosition Position => new GeoPosition(48.03849438437253, 9.326946932715074); public Uri WebSite => new Uri("https://blog.it-koehler.com/en"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.it-koehler.com/rss"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class AlexanderKoehler : IAmACommunityMember { public string FirstName => "Alexander"; public string LastName => "Koehler"; public string ShortBioOrTagLine => "father,system engineer, automation guy, powershell enthusiast"; public string StateOrRegion => "Mengen, Germany"; public string EmailAddress => "planetpowershell@it-koehler.com"; public string TwitterHandle => "ACharburner"; public string GravatarHash => "bc09e87a59be038b93da1e03079aa053"; public string GitHubHandle => "blog-it-koehler-com"; public GeoPosition Position => new GeoPosition(48.03849438437253, 9.326946932715074); public Uri WebSite => new Uri("https://blog.it-koehler.com/en"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.it-koehler.com/rss"); } } } }
mit
C#
63040dac8c7766be6843908208100d824ac955a0
Update DynamicScopeLocator.IsMissing method
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
src/Atata/ScopeSearch/DynamicScopeLocator.cs
src/Atata/ScopeSearch/DynamicScopeLocator.cs
using OpenQA.Selenium; using System; namespace Atata { public class DynamicScopeLocator : IScopeLocator { private readonly Func<SearchOptions, IWebElement> locateFunction; public DynamicScopeLocator(Func<SearchOptions, IWebElement> locateFunction) { this.locateFunction = locateFunction; } public IWebElement GetElement(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return locateFunction(searchOptions); } public IWebElement[] GetElements(SearchOptions searchOptions = null, string xPathCondition = null) { return new[] { GetElement(searchOptions, xPathCondition) }; } public bool IsMissing(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); SearchOptions searchOptionsForElementGet = searchOptions.Clone(); searchOptionsForElementGet.IsSafely = true; IWebElement element = GetElement(searchOptionsForElementGet, xPathCondition); if (element != null && !searchOptions.IsSafely) throw ExceptionFactory.CreateForNotMissingElement(); else return element == null; } } }
using OpenQA.Selenium; using System; namespace Atata { public class DynamicScopeLocator : IScopeLocator { private readonly Func<SearchOptions, IWebElement> locateFunction; public DynamicScopeLocator(Func<SearchOptions, IWebElement> locateFunction) { this.locateFunction = locateFunction; } public IWebElement GetElement(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return locateFunction(searchOptions); } public IWebElement[] GetElements(SearchOptions searchOptions = null, string xPathCondition = null) { return new[] { GetElement(searchOptions, xPathCondition) }; } public bool IsMissing(SearchOptions searchOptions = null, string xPathCondition = null) { return GetElement(searchOptions, xPathCondition) == null; } } }
apache-2.0
C#
352c3e040ddd1065b66f43dd87fcb61a66b75117
Bump version to 2.2.2
rickyah/ini-parser,davidgrupp/ini-parser,rickyah/ini-parser
src/IniFileParser/Properties/AssemblyInfo.cs
src/IniFileParser/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("INIParser")] [assembly: AssemblyDescription("A simple INI file processing library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("INIParser")] [assembly: AssemblyCopyright("")] [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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")] // 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("2.2.2")] [assembly: AssemblyFileVersion("2.2.2")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("INIParser")] [assembly: AssemblyDescription("A simple INI file processing library")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("INIParser")] [assembly: AssemblyCopyright("")] [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("f1db68d3-0ee7-4733-bd6d-60c5db00a1c8")] // 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("2.2.1")] [assembly: AssemblyFileVersion("2.2.1")]
mit
C#
e3ef6bc23ca6e04eaba9719457f8b00ddaef8acc
fix TestPersonGenerator returning Addresses
marcwittke/Backend.Fx,marcwittke/Backend.Fx
src/abstractions/Backend.Fx/RandomData/TestPersonGenerator.cs
src/abstractions/Backend.Fx/RandomData/TestPersonGenerator.cs
using System; using System.Collections.Generic; using System.Linq; namespace Backend.Fx.RandomData { public class TestPersonGenerator : Generator<TestPerson> { private const int Year = 365; private readonly Random _random = TestRandom.Instance; private readonly HashSet<string> _uniqueNames = new HashSet<string>(); public bool EnforceUniqueNames { get; set; } = false; public int FemalePercentage { get; set; } = 55; public int MaximumAgeInDays { get; set; } = 80 * Year; public int MinimumAgeInDays { get; set; } = 18 * Year; public static TestPerson Generate() { return new TestPersonGenerator().First(); } protected override TestPerson Next() { var isFemale = _random.Next(1, 100) < FemalePercentage; TestPerson generated; do { generated = new TestPerson( isFemale ? Names.Female.Random() : Names.Male.Random(), _random.Next(100) < 30 ? isFemale ? Names.Female.Random() : Names.Male.Random() : "", Names.Family.Random(), _random.Next(100) < 20 ? "Dr." : "", isFemale ? TestPerson.Genders.Female : TestPerson.Genders.Male, DateTime.Now.AddDays(-_random.Next(MinimumAgeInDays, MaximumAgeInDays)).Date); } while (EnforceUniqueNames && _uniqueNames.Contains($"{generated.FirstName}{generated.LastName}")); if (EnforceUniqueNames) { _uniqueNames.Add($"{generated.FirstName}{generated.LastName}"); } return generated; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Backend.Fx.RandomData { public class TestPersonGenerator : Generator<TestPerson> { private const int Year = 365; private readonly Random _random = TestRandom.Instance; private readonly HashSet<string> _uniqueNames = new HashSet<string>(); public bool EnforceUniqueNames { get; set; } = false; public int FemalePercentage { get; set; } = 55; public int MaximumAgeInDays { get; set; } = 80 * Year; public int MinimumAgeInDays { get; set; } = 18 * Year; public static TestAddress Generate() { return new TestAddressGenerator().First(); } protected override TestPerson Next() { var isFemale = _random.Next(1, 100) < FemalePercentage; TestPerson generated; do { generated = new TestPerson( isFemale ? Names.Female.Random() : Names.Male.Random(), _random.Next(100) < 30 ? isFemale ? Names.Female.Random() : Names.Male.Random() : "", Names.Family.Random(), _random.Next(100) < 20 ? "Dr." : "", isFemale ? TestPerson.Genders.Female : TestPerson.Genders.Male, DateTime.Now.AddDays(-_random.Next(MinimumAgeInDays, MaximumAgeInDays)).Date); } while (EnforceUniqueNames && _uniqueNames.Contains($"{generated.FirstName}{generated.LastName}")); if (EnforceUniqueNames) { _uniqueNames.Add($"{generated.FirstName}{generated.LastName}"); } return generated; } } }
mit
C#
21a52a46594cdcadec7775e8a812dc32dff497f1
Fix IPerspexList.Count.
danwalmsley/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,susloparovdenis/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,susloparovdenis/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,MrDaedra/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,MrDaedra/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,akrisiun/Perspex,AvaloniaUI/Avalonia,susloparovdenis/Perspex,kekekeks/Perspex,wieslawsoltes/Perspex,OronDF343/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,kekekeks/Perspex,jazzay/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,punker76/Perspex,SuperJMN/Avalonia,jkoritzinsky/Avalonia,susloparovdenis/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,OronDF343/Avalonia,jkoritzinsky/Perspex,grokys/Perspex,jkoritzinsky/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia
src/Perspex.Base/Collections/IPerspexList.cs
src/Perspex.Base/Collections/IPerspexList.cs
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Collections.Generic; namespace Perspex.Collections { /// <summary> /// A notiftying list. /// </summary> /// <typeparam name="T">The type of the items in the list.</typeparam> public interface IPerspexList<T> : IList<T>, IPerspexReadOnlyList<T> { /// <summary> /// Gets the number of items in the list. /// </summary> new int Count { get; } /// <summary> /// Adds multiple items to the collection. /// </summary> /// <param name="items">The items.</param> void AddRange(IEnumerable<T> items); /// <summary> /// Inserts multiple items at the specified index. /// </summary> /// <param name="index">The index.</param> /// <param name="items">The items.</param> void InsertRange(int index, IEnumerable<T> items); /// <summary> /// Removes multiple items from the collection. /// </summary> /// <param name="items">The items.</param> void RemoveAll(IEnumerable<T> items); } }
// Copyright (c) The Perspex Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System.Collections.Generic; namespace Perspex.Collections { /// <summary> /// A notiftying list. /// </summary> /// <typeparam name="T">The type of the items in the list.</typeparam> public interface IPerspexList<T> : IList<T>, IPerspexReadOnlyList<T> { /// <summary> /// Adds multiple items to the collection. /// </summary> /// <param name="items">The items.</param> void AddRange(IEnumerable<T> items); /// <summary> /// Inserts multiple items at the specified index. /// </summary> /// <param name="index">The index.</param> /// <param name="items">The items.</param> void InsertRange(int index, IEnumerable<T> items); /// <summary> /// Removes multiple items from the collection. /// </summary> /// <param name="items">The items.</param> void RemoveAll(IEnumerable<T> items); } }
mit
C#
f90cdad210598ea14c531021d6c016f075a79a84
Update Index.cshtml
gbizet/MVCBlog,gbizet/MVCBlog
src/MVCBlog.Website/Views/About/Index.cshtml
src/MVCBlog.Website/Views/About/Index.cshtml
<p>TODO: Write something interesting about you! Finaxys et le Canada test</p>
<p>TODO: Write something interesting about you! Finaxys</p>
apache-2.0
C#
ff474f771b12613b9686b7707ec3b85c36bc7a3b
make comments in AssemblyInfo more global-friendly
longshine/Mina.NET
Mina.NET/Properties/AssemblyInfo.cs
Mina.NET/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("Mina.NET")] [assembly: AssemblyDescription("Async socket library for high performance and high scalability network applications.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Mina.NET")] [assembly: AssemblyCopyright("Copyright © Longshine 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: System.CLSCompliant(true)] // 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("2070ccbf-2ee3-476e-9715-54e97a5e26c7")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.8")] [assembly: AssemblyFileVersion("2.0.8")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Mina.NET")] [assembly: AssemblyDescription("Async socket library for high performance and high scalability network applications.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Mina.NET")] [assembly: AssemblyCopyright("Copyright © Longshine 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: System.CLSCompliant(true)] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("2070ccbf-2ee3-476e-9715-54e97a5e26c7")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 内部版本号 // 修订号 // // 可以指定所有这些值,也可以使用“内部版本号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.8")] [assembly: AssemblyFileVersion("2.0.8")]
apache-2.0
C#
17d485e3c8d5b192c83f3df2cad1c6ff0d4f9f1f
Disable SSL (for now) - attempting to diagnose SSL/TLS error
IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner
MultiMiner.Blockchain/ApiContext.cs
MultiMiner.Blockchain/ApiContext.cs
using MultiMiner.Blockchain.Data; using MultiMiner.ExchangeApi; using MultiMiner.ExchangeApi.Data; using MultiMiner.Utility.Net; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Text; namespace MultiMiner.Blockchain { public class ApiContext : IApiContext { public IEnumerable<ExchangeInformation> GetExchangeInformation() { WebClient webClient = new ApiWebClient(); webClient.Encoding = Encoding.UTF8; string response = webClient.DownloadString(new Uri(GetApiUrl())); Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response); List<ExchangeInformation> results = new List<ExchangeInformation>(); foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries) { results.Add(new ExchangeInformation() { SourceCurrency = "BTC", TargetCurrency = keyValuePair.Key, TargetSymbol = keyValuePair.Value.Symbol, ExchangeRate = keyValuePair.Value.Last }); } return results; } public string GetInfoUrl() { return "https://blockchain.info"; } public string GetApiUrl() { //use HTTP as HTTPS is down at times and returns: //The request was aborted: Could not create SSL/TLS secure channel. return "http://blockchain.info/ticker"; } public string GetApiName() { return "Blockchain"; } } }
using MultiMiner.Blockchain.Data; using MultiMiner.ExchangeApi; using MultiMiner.ExchangeApi.Data; using MultiMiner.Utility.Net; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Net; using System.Text; namespace MultiMiner.Blockchain { public class ApiContext : IApiContext { public IEnumerable<ExchangeInformation> GetExchangeInformation() { WebClient webClient = new ApiWebClient(); webClient.Encoding = Encoding.UTF8; string response = webClient.DownloadString(new Uri(GetApiUrl())); Dictionary<string, TickerEntry> tickerEntries = JsonConvert.DeserializeObject<Dictionary<string, TickerEntry>>(response); List<ExchangeInformation> results = new List<ExchangeInformation>(); foreach (KeyValuePair<string, TickerEntry> keyValuePair in tickerEntries) { results.Add(new ExchangeInformation() { SourceCurrency = "BTC", TargetCurrency = keyValuePair.Key, TargetSymbol = keyValuePair.Value.Symbol, ExchangeRate = keyValuePair.Value.Last }); } return results; } public string GetInfoUrl() { return "https://blockchain.info"; } public string GetApiUrl() { return "https://blockchain.info/ticker"; } public string GetApiName() { return "Blockchain"; } } }
mit
C#
35889ea69c82f1e6c4217e41c7b5c8de51370978
Bump to version 2.6.0.0
Silv3rPRO/proshine
PROShine/Properties/AssemblyInfo.cs
PROShine/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; 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("PROShine")] [assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Silv3r")] [assembly: AssemblyProduct("PROShine")] [assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")] [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("2.6.0.0")] [assembly: AssemblyFileVersion("2.6.0.0")] [assembly: NeutralResourcesLanguage("en")]
using System.Reflection; using System.Resources; 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("PROShine")] [assembly: AssemblyDescription("A free, open-source and advanced bot for Pokemon Revolution Online.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Silv3r")] [assembly: AssemblyProduct("PROShine")] [assembly: AssemblyCopyright("Copyright © Silv3r, 2016-2032")] [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("2.5.2.0")] [assembly: AssemblyFileVersion("2.5.2.0")] [assembly: NeutralResourcesLanguage("en")]
mit
C#
9e44e458d7642ee1258a0541701941b2a61b4c31
Update Output.cs
kostadriano/EvolutionaryMusic
ParticleSwarmOptimization/Output.cs
ParticleSwarmOptimization/Output.cs
using System; using System.IO; namespace musicaevolutiva { public class Output { public static void FileWriter(int count, Global gParticle, int maxIteration) { if (count == 0) { using (StreamWriter writer = new StreamWriter("gBest.ods", true)) { writer.WriteLine("Population Size," + Particles.PopulationSize + ",Generations," + maxIteration+"\n"); } } using (StreamWriter writer = new StreamWriter("gBest.ods", true)) { writer.WriteLine("Generation," + count + ",Global Memory," + gParticle.GFitness); if (count == maxIteration - 1) writer.WriteLine("\n"); } } } }
using System; using System.IO; namespace musicaevolutiva { public class Output { public static void FileWriter(int count, Global gParticle, int maxIteration) { if (count == 0) { using (StreamWriter writer = new StreamWriter("gBesttemp.ods", true)) { writer.WriteLine("Population Size," + Particles.PopulationSize + ",Generations," + maxIteration+"\n"); } } using (StreamWriter writer = new StreamWriter("gBesttemp.ods", true)) { writer.WriteLine("Generation," + count + ",Global Memory," + gParticle.GFitness); if (count == maxIteration - 1) writer.WriteLine("\n"); } } } }
mit
C#
3df85ce088521fbec50709e38bc8d377ee472426
Update AssemblyInfo.cs
WSDOT-GIS/WSDOT-Traveler-Info-DotNet-Client
UnitTest/Properties/AssemblyInfo.cs
UnitTest/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("UnitTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("WSDOT")] [assembly: AssemblyProduct("UnitTest")] [assembly: AssemblyCopyright("Copyright © WSDOT 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("3cd4e1f9-7c5b-4bc8-b92c-e945e90c3e1f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.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("UnitTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("UnitTest")] [assembly: AssemblyCopyright("Copyright © Microsoft 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("3cd4e1f9-7c5b-4bc8-b92c-e945e90c3e1f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
unlicense
C#
c022b4722f81658a7417bfae1401dbb5fa128f77
Change GlfwHelpers CreateWindow
rafaelvasco/SharpGlfw
SharpGlfw/GlfwHelpers.cs
SharpGlfw/GlfwHelpers.cs
namespace SharpGlfw { public static partial class Glfw { public static void CenterWindow(GlfwWindow window) { int windowW, windowH; GetWindowSize(window, out windowW, out windowH); GlfwVidMode mode = GetVideoMode(GetPrimaryMonitor()); int desktopW = mode.Width; int desktopH = mode.Height; SetWindowPos(window, desktopW / 2 - windowW / 2, desktopH / 2 - windowH / 2); } public static GlfwWindow CreateWindow(int width, int height, string title) { return GlfwCore.glfwCreateWindow(width, height, title, GlfwMonitor.Null, GlfwWindow.Null); } public static GlfwWindow CreateWindow() { GlfwVidMode videoMode = GetVideoMode(GetPrimaryMonitor()); WindowHint(WindowAttrib.Decorated, 0); WindowHint(WindowAttrib.Resizable, 0); return GlfwCore.glfwCreateWindow(videoMode.Width, videoMode.Height, string.Empty, GlfwMonitor.Null, GlfwWindow.Null); } } }
namespace SharpGlfw { public static partial class Glfw { public static void CenterWindow(GlfwWindow window) { int windowW, windowH; GetWindowSize(window, out windowW, out windowH); GlfwVidMode mode = GetVideoMode(GetPrimaryMonitor()); int desktopW = mode.Width; int desktopH = mode.Height; SetWindowPos(window, desktopW / 2 - windowW / 2, desktopH / 2 - windowH / 2); } public static GlfwWindow CreateWindow(int width, int height, string title, bool fullscreen = false) { if (!fullscreen) { return GlfwCore.glfwCreateWindow(width, height, title, GlfwMonitor.Null, GlfwWindow.Null); } GlfwVidMode videoMode = GetVideoMode(GetPrimaryMonitor()); WindowHint(WindowAttrib.Decorated, 0); WindowHint(WindowAttrib.Resizable, 0); return GlfwCore.glfwCreateWindow(videoMode.Width, videoMode.Height, title, GlfwMonitor.Null, GlfwWindow.Null); } } }
mit
C#
8c7c9ede85753557cc0e68f56aa594ecefdd907c
Use new ProcessAsync API for CrashReporter.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/CrashReport/CrashReporter.cs
WalletWasabi.Gui/CrashReport/CrashReporter.cs
using System; using System.Diagnostics; using WalletWasabi.Logging; using WalletWasabi.Microservices; using WalletWasabi.Models; namespace WalletWasabi.Gui.CrashReport { public class CrashReporter { private const int MaxRecursiveCalls = 5; public int Attempts { get; private set; } public string Base64ExceptionString { get; private set; } = null; public bool IsReport { get; private set; } public bool HadException { get; private set; } public bool IsInvokeRequired => !IsReport && HadException; public SerializableException SerializedException { get; private set; } public void TryInvokeCrashReport() { try { if (Attempts >= MaxRecursiveCalls) { throw new InvalidOperationException($"The crash report has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors."); } if (string.IsNullOrEmpty(Base64ExceptionString)) { throw new InvalidOperationException($"The crash report exception message is empty."); } var args = $"crashreport -attempt=\"{Attempts + 1}\" -exception=\"{Base64ExceptionString}\""; ProcessStartInfo startInfo = ProcessStartInfoFactory.Make(Process.GetCurrentProcess().MainModule.FileName, args); using Process p = Process.Start(startInfo); } catch (Exception ex) { Logger.LogWarning($"There was a problem while invoking crash report:{ex.ToUserFriendlyString()}."); } } public void SetShowCrashReport(string base64ExceptionString, int attempts) { Attempts = attempts; Base64ExceptionString = base64ExceptionString; SerializedException = SerializableException.FromBase64String(Base64ExceptionString); IsReport = true; } /// <summary> /// Sets the exception when it occurs the first time and should be reported to the user. /// </summary> public void SetException(Exception ex) { SerializedException = ex.ToSerializableException(); Base64ExceptionString = SerializableException.ToBase64String(SerializedException); HadException = true; } } }
using System; using System.Diagnostics; using WalletWasabi.Logging; using WalletWasabi.Microservices; using WalletWasabi.Models; namespace WalletWasabi.Gui.CrashReport { public class CrashReporter { private const int MaxRecursiveCalls = 5; public int Attempts { get; private set; } public string Base64ExceptionString { get; private set; } = null; public bool IsReport { get; private set; } public bool HadException { get; private set; } public bool IsInvokeRequired => !IsReport && HadException; public SerializableException SerializedException { get; private set; } public void TryInvokeCrashReport() { try { if (Attempts >= MaxRecursiveCalls) { throw new InvalidOperationException($"The crash report has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors."); } if (string.IsNullOrEmpty(Base64ExceptionString)) { throw new InvalidOperationException($"The crash report exception message is empty."); } var args = $"crashreport -attempt=\"{Attempts + 1}\" -exception=\"{Base64ExceptionString}\""; ProcessBridge processBridge = new ProcessBridge(Process.GetCurrentProcess().MainModule.FileName); processBridge.Start(args, false); } catch (Exception ex) { Logger.LogWarning($"There was a problem while invoking crash report:{ex.ToUserFriendlyString()}."); } } public void SetShowCrashReport(string base64ExceptionString, int attempts) { Attempts = attempts; Base64ExceptionString = base64ExceptionString; SerializedException = SerializableException.FromBase64String(Base64ExceptionString); IsReport = true; } /// <summary> /// Sets the exception when it occurs the first time and should be reported to the user. /// </summary> public void SetException(Exception ex) { SerializedException = ex.ToSerializableException(); Base64ExceptionString = SerializableException.ToBase64String(SerializedException); HadException = true; } } }
mit
C#
baade3e0db8a9e7c5a5cf1fc296c26f14ee74647
Fix coldcard capitalization
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Hwi/Models/HardwareWalletType.cs
WalletWasabi/Hwi/Models/HardwareWalletType.cs
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.Hwi.Models { public enum HardwareWalletType { Trezor, Ledger, KeepKey, DigitalBitBox, Coldcard } }
using System; using System.Collections.Generic; using System.Text; namespace WalletWasabi.Hwi.Models { public enum HardwareWalletType { Trezor, Ledger, KeepKey, DigitalBitBox, ColdCard } }
mit
C#
7e852e9865f69338a735497466e0b7d6151eddb9
Fix DisposeValueIfCreated to be extension method
OpenMagic/OpenMagic
source/OpenMagic/Extensions/LazyExtensions.cs
source/OpenMagic/Extensions/LazyExtensions.cs
using System; namespace OpenMagic.Extensions { public static class LazyExtensions { public static void DisposeValueIfCreated<T>(this Lazy<T> obj) where T : IDisposable { if (obj.IsValueCreated) { obj.Value.Dispose(); } } } }
using System; namespace OpenMagic.Extensions { public static class LazyExtensions { public static void DisposeValueIfCreated<T>(Lazy<T> obj) where T : IDisposable { if (obj.IsValueCreated) { obj.Value.Dispose(); } } } }
mit
C#
a7864c36b2e882680b5aef8f7c9b8840271873c7
Test that 'true' unifies correctly
Logicalshift/Reason
LogicalShift.Reason.Tests/Truthiness.cs
LogicalShift.Reason.Tests/Truthiness.cs
using LogicalShift.Reason.Api; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason.Tests { [TestFixture] public class Truthiness { [Test] public void TrueIsTrue() { Assert.IsTrue(Equals(Literal.True(), Literal.True())); } [Test] public void TrueHashesToSelf() { var dict = new Dictionary<ILiteral, bool>(); dict[Literal.True()] = true; Assert.IsTrue(dict[Literal.True()]); } [Test] public void TrueUnifiesWithSelf() { var truthiness = Literal.True(); Assert.AreEqual(1, truthiness.Unify(truthiness).Count()); } [Test] public void TrueDoesNotUnifyWithDifferentAtom() { var truthiness = Literal.True(); var otherAtom = Literal.NewAtom(); Assert.AreEqual(0, truthiness.Unify(otherAtom).Count()); } } }
using LogicalShift.Reason.Api; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; namespace LogicalShift.Reason.Tests { [TestFixture] public class Truthiness { [Test] public void TrueIsTrue() { Assert.IsTrue(Equals(Literal.True(), Literal.True())); } [Test] public void TrueHashesToSelf() { var dict = new Dictionary<ILiteral, bool>(); dict[Literal.True()] = true; Assert.IsTrue(dict[Literal.True()]); } } }
apache-2.0
C#
a3f97e54189bf664b065920a1fd71c27d291d498
Fix compilation errors
SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK,SoftFx/FDK
FDK/SoftFX.Extended.Net/Financial/Adapter/CalculatorAsset.cs
FDK/SoftFX.Extended.Net/Financial/Adapter/CalculatorAsset.cs
namespace SoftFX.Extended.Financial.Adapter { using System; using TickTrader.BusinessLogic; sealed class CalculatorAsset : IAssetModel { readonly Asset asset; public CalculatorAsset(Asset asset) { this.asset = asset; } public decimal Amount { get { return (decimal)this.asset.Volume; } } public decimal LockedAmount { get { return (decimal)this.asset.LockedVolume; } } public decimal FreeAmount { get { return Amount - LockedAmount; } } public short CurrencyId { get { return (short)this.asset.Currency.GetHashCode(); } } public string Currency { get { return this.asset.Currency; } } public decimal Margin { get { return (decimal)this.asset.LockedVolume; } set { this.asset.LockedVolume = (double)this.asset.Owner.RoundingService.RoundMargin(this.asset.Currency, value); } } } }
namespace SoftFX.Extended.Financial.Adapter { using System; using TickTrader.BusinessLogic; sealed class CalculatorAsset : IAssetModel { readonly Asset asset; public CalculatorAsset(Asset asset) { this.asset = asset; } public decimal Amount { get { return (decimal)this.asset.Volume; } } public short CurrencyId { get { return (short)this.asset.Currency.GetHashCode(); } } public decimal Margin { get { return (decimal)this.asset.LockedVolume; } set { this.asset.LockedVolume = (double)this.asset.Owner.RoundingService.RoundMargin(this.asset.Currency, value); } } } }
mit
C#
91df543bb4226115565dcf56e943657049f6ea1d
Trim Request Body to 4096 characters if it is longer.
tdiehl/raygun4net,ddunkin/raygun4net,MindscapeHQ/raygun4net,articulate/raygun4net,nelsonsar/raygun4net,tdiehl/raygun4net,articulate/raygun4net,MindscapeHQ/raygun4net,nelsonsar/raygun4net,ddunkin/raygun4net,MindscapeHQ/raygun4net
Mindscape.Raygun4Net.WebApi/RaygunWebApiDelegatingHandler.cs
Mindscape.Raygun4Net.WebApi/RaygunWebApiDelegatingHandler.cs
using System.Linq; using System.Net.Http; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiDelegatingHandler : DelegatingHandler { public const string RequestBodyKey = "Raygun.RequestBody"; protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var body = await request.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(body)) { request.Properties[RequestBodyKey] = body.Length > 4096 ? body.Substring(0, 4096) : body; } return await base.SendAsync(request, cancellationToken); } } }
using System.Net.Http; namespace Mindscape.Raygun4Net.WebApi { public class RaygunWebApiDelegatingHandler : DelegatingHandler { public const string RequestBodyKey = "Raygun.RequestBody"; protected override async System.Threading.Tasks.Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { var body = await request.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(body)) { request.Properties[RequestBodyKey] = body; } return await base.SendAsync(request, cancellationToken); } } }
mit
C#
ca24a3800fd75ebad8f319563b56ec70bf4c9333
Add failing tests
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Tests/UnitTests/GUI/SendControlViewModelTest.cs
WalletWasabi.Tests/UnitTests/GUI/SendControlViewModelTest.cs
using Xunit; using WalletWasabi.Gui.Controls.WalletExplorer; namespace WalletWasabi.Tests.UnitTests.GUI { public class SendControlViewModelTest { [Theory] [InlineData(false, "0")] [InlineData(false, "0.1")] [InlineData(true, "1.2099999997690000")] [InlineData(false, "1.20999999976900000000000000000000000000000000000000000000000000000000000000000000")] [InlineData(false, "1.209999999769000000000000000000000000000000000000000000000000000000000000000000001")] [InlineData(true, "1")] [InlineData(false, "-1")] [InlineData(true, "47")] [InlineData(true, "47.0")] [InlineData(true, "1111111111111")] [InlineData(false, "11111111111111")] [InlineData(false, "2099999997690000")] [InlineData(false, "2099999997690001")] [InlineData(false, "111111111111111111111111111")] [InlineData(false, "99999999999999999999999999999999999999999999")] [InlineData(false, "abc")] [InlineData(false, "1a2b")] [InlineData(false, "")] [InlineData(false, null)] [InlineData(false, " ")] [InlineData(false, " 2")] [InlineData(true, "1.1")] [InlineData(false, "1.1 ")] [InlineData(false, "1,1")] [InlineData(false, "1. 1")] [InlineData(false, "1 .1")] [InlineData(false, "0. 1")] [InlineData(false, "csszáőüó@")] public void SendControlViewModel_Check_Test_Fees(bool isValid, string feeText) { Assert.Equal(isValid, SendControlViewModel.TryParseUserFee(feeText, out var _)); } } }
using Xunit; using WalletWasabi.Gui.Controls.WalletExplorer; namespace WalletWasabi.Tests.UnitTests.GUI { public class SendControlViewModelTest { [Theory] [InlineData(false, "0")] [InlineData(false, "0.1")] [InlineData(true, "1.2099999997690000")] [InlineData(true, "1")] [InlineData(true, "47")] [InlineData(true, "47.0")] [InlineData(true, "1111111111111")] [InlineData(false, "11111111111111")] [InlineData(false, "2099999997690000")] [InlineData(false, "2099999997690001")] [InlineData(false, "111111111111111111111111111")] [InlineData(false, "99999999999999999999999999999999999999999999")] [InlineData(false, "abc")] [InlineData(false, "1a2b")] [InlineData(false, "")] [InlineData(false, null)] [InlineData(false, " ")] [InlineData(false, " 2")] [InlineData(true, "1.1")] [InlineData(false, "1.1 ")] [InlineData(false, "1,1")] [InlineData(false, "1. 1")] [InlineData(false, "1 .1")] [InlineData(false, "0. 1")] [InlineData(false, "csszáőüó@")] public void SendControlViewModel_Check_Test_Fees(bool isValid, string feeText) { Assert.Equal(isValid, SendControlViewModel.TryParseUserFee(feeText, out var _)); } } }
mit
C#
188ca9fc4696dea519d23dc4e18d52f934fd655d
fix cd decrease
Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns
TCC.Core/Parsing/Messages/S_DECREASE_COOLTIME_SKILL.cs
TCC.Core/Parsing/Messages/S_DECREASE_COOLTIME_SKILL.cs
using TCC.TeraCommon.Game.Messages; using TCC.TeraCommon.Game.Services; namespace TCC.Parsing.Messages { public class S_DECREASE_COOLTIME_SKILL : ParsedMessage { /// <summary> /// Skill's ID /// </summary> public uint SkillId { get; private set; } /// <summary> /// Skill's cooldown in milliseconds /// </summary> public uint Cooldown { get; private set; } public S_DECREASE_COOLTIME_SKILL(TeraMessageReader reader) : base(reader) { SkillId = reader.Factory.ReleaseVersion < 74 ? reader.ReadUInt32() - 0x04000000 : (uint)new SkillId(reader).Id; Cooldown = reader.ReadUInt32(); } } }
using TCC.TeraCommon.Game.Messages; using TCC.TeraCommon.Game.Services; namespace TCC.Parsing.Messages { public class S_DECREASE_COOLTIME_SKILL : ParsedMessage { /// <summary> /// Skill's ID /// </summary> public uint SkillId { get; private set; } /// <summary> /// Skill's cooldown in milliseconds /// </summary> public uint Cooldown { get; private set; } public S_DECREASE_COOLTIME_SKILL(TeraMessageReader reader) : base(reader) { SkillId = reader.ReadUInt32() - 0x04000000; Cooldown = reader.ReadUInt32(); } } }
mit
C#
ad78b2aa4e182770671a101209173240c6e57422
Fix test to run with the NUnitLite in our Integration Tests on IOS
Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet
Tests/IntegrationTests.Shared/StandAloneObjectTests.cs
Tests/IntegrationTests.Shared/StandAloneObjectTests.cs
using NUnit.Framework; using RealmNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IntegrationTests.Shared { [TestFixture] public class StandAloneObjectTests { private Person _person; [SetUp] public void SetUp() { _person = new Person(); } [Test] public void PropertyGet() { string firstName = null; Assert.DoesNotThrow(() => firstName = _person.FirstName); Assert.That(string.IsNullOrEmpty(firstName)); } [Test] public void PropertySet() { const string name = "John"; Assert.DoesNotThrow(() => _person.FirstName = name); Assert.AreEqual(name, _person.FirstName); } [Test] public void AddToRealm() { _person.FirstName = "Arthur"; _person.LastName = "Dent"; _person.IsInteresting = true; using (var realm = Realm.GetInstance(Path.GetTempFileName())) { using (var transaction = realm.BeginWrite()) { realm.Add(_person); transaction.Commit(); } Assert.That(_person.IsManaged); var p = realm.All<Person>().ToList().Single(); Assert.That(p.FirstName, Is.EqualTo("Arthur")); Assert.That(p.LastName, Is.EqualTo("Dent")); Assert.That(p.IsInteresting); } } } }
using NUnit.Framework; using RealmNet; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace IntegrationTests.Shared { [TestFixture] public class StandAloneObjectTests { private Person _person; [SetUp] public void SetUp() { _person = new Person(); } [Test] public void PropertyGet() { string firstName = null; Assert.DoesNotThrow(() => firstName = _person.FirstName); Assert.IsNullOrEmpty(firstName); } [Test] public void PropertySet() { const string name = "John"; Assert.DoesNotThrow(() => _person.FirstName = name); Assert.AreEqual(name, _person.FirstName); } [Test] public void AddToRealm() { _person.FirstName = "Arthur"; _person.LastName = "Dent"; _person.IsInteresting = true; using (var realm = Realm.GetInstance(Path.GetTempFileName())) { using (var transaction = realm.BeginWrite()) { realm.Add(_person); transaction.Commit(); } Assert.That(_person.IsManaged); var p = realm.All<Person>().ToList().Single(); Assert.That(p.FirstName, Is.EqualTo("Arthur")); Assert.That(p.LastName, Is.EqualTo("Dent")); Assert.That(p.IsInteresting); } } } }
apache-2.0
C#
683e1f5be648ba18e6727af0f917e0e15493dadb
Move OpenFileDialog initialization inside try block
wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
src/Core2D.Wpf/Importers/FileImageImporter.cs
src/Core2D.Wpf/Importers/FileImageImporter.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using Core2D.Editor; using Core2D.Interfaces; using Core2D.Wpf.Windows; using Microsoft.Win32; namespace Core2D.Wpf.Importers { /// <summary> /// File image importer. /// </summary> public class FileImageImporter : IImageImporter { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initialize new instance of <see cref="FileImageImporter"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public FileImageImporter(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc/> public async Task<string> GetImageKeyAsync() { try { var dlg = new OpenFileDialog() { Filter = "All (*.*)|*.*", FilterIndex = 0, FileName = "" }; if (dlg.ShowDialog(_serviceProvider.GetService<MainWindow>()) == true) { var path = dlg.FileName; var bytes = System.IO.File.ReadAllBytes(path); var key = _serviceProvider.GetService<ProjectEditor>().Project.AddImageFromFile(path, bytes); return await Task.Run(() => key); } } catch (Exception ex) { _serviceProvider.GetService<ILog>().LogError($"{ex.Message}{Environment.NewLine}{ex.StackTrace}"); } return null; } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Threading.Tasks; using Core2D.Editor; using Core2D.Interfaces; using Core2D.Wpf.Windows; using Microsoft.Win32; namespace Core2D.Wpf.Importers { /// <summary> /// File image importer. /// </summary> public class FileImageImporter : IImageImporter { private readonly IServiceProvider _serviceProvider; /// <summary> /// Initialize new instance of <see cref="FileImageImporter"/> class. /// </summary> /// <param name="serviceProvider">The service provider.</param> public FileImageImporter(IServiceProvider serviceProvider) { _serviceProvider = serviceProvider; } /// <inheritdoc/> public async Task<string> GetImageKeyAsync() { var dlg = new OpenFileDialog() { Filter = "All (*.*)|*.*", FilterIndex = 0, FileName = "" }; if (dlg.ShowDialog(_serviceProvider.GetService<MainWindow>()) == true) { try { var path = dlg.FileName; var bytes = System.IO.File.ReadAllBytes(path); var key = _serviceProvider.GetService<ProjectEditor>().Project.AddImageFromFile(path, bytes); return await Task.Run(() => key); } catch (Exception ex) { _serviceProvider.GetService<ILog>().LogError($"{ex.Message}{Environment.NewLine}{ex.StackTrace}"); } } return null; } } }
mit
C#
0189561d1e1ef70248cbbb8213d5b0018843fe97
Tidy up
dev-academy-phase4/cs-portfolio,dev-academy-phase4/cs-portfolio
Portfolio/Controllers/HomeController.cs
Portfolio/Controllers/HomeController.cs
using System.Web.Mvc; namespace Portfolio.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult Contact() { ViewBag.Message = "Contact details"; return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using Portfolio.Models; namespace Portfolio.Controllers { public class HomeController : Controller { private readonly ApplicationDbContext _db; public HomeController() { _db = new ApplicationDbContext(); } public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } public ActionResult History() { var jobs = _db.Jobs; var vm = new HistoryViewModel { Title = "Work History", Jobs = jobs.ToList() }; return View(vm); } } }
isc
C#
cb47b3145e3ac4b439eae17c54413b82f1c45127
Update ValuesOut.cs
EricZimmerman/RegistryPlugins
RegistryPlugin.OpenSaveMRU/ValuesOut.cs
RegistryPlugin.OpenSaveMRU/ValuesOut.cs
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.OpenSaveMRU { public class ValuesOut:IValueOut { public ValuesOut(string ext, string filename, string valueName, int mruPosition, DateTimeOffset? openedOn) { Extension = ext; Filename = filename; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string Extension { get; } public string ValueName { get; } public int MruPosition { get; } public string Filename { get; } public DateTime? OpenedOn { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"File name: {Filename}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff}"; public string BatchValueData3 => $"MRU: {MruPosition}"; } }
using System; using RegistryPluginBase.Interfaces; namespace RegistryPlugin.OpenSaveMRU { public class ValuesOut:IValueOut { public ValuesOut(string ext, string filename, string valueName, int mruPosition, DateTimeOffset? openedOn) { Extension = ext; Filename = filename; ValueName = valueName; MruPosition = mruPosition; OpenedOn = openedOn?.UtcDateTime; } public string Extension { get; } public string ValueName { get; } public int MruPosition { get; } public string Filename { get; } public DateTime? OpenedOn { get; } public string BatchKeyPath { get; set; } public string BatchValueName { get; set; } public string BatchValueData1 => $"File name: {Filename}"; public string BatchValueData2 => $"Opened: {OpenedOn?.ToUniversalTime():yyyy-MM-dd HH:mm:ss.fffffff})"; public string BatchValueData3 => $"MRU: {MruPosition}"; } }
mit
C#
46eb3c90a24a66a9fa0ed82a59f3bfa2fd6fac1e
fix document get due to bugy query
benhallouk/syntactic-docs,benhallouk/syntactic-docs
src/SyntacticDocs/Services/DocumentService.cs
src/SyntacticDocs/Services/DocumentService.cs
using System.Collections.Generic; using System.Linq; using SyntacticDocs.Models; using SyntacticDocs.Data; using Microsoft.EntityFrameworkCore; namespace SyntacticDocs.Services { public class DocumentService { private readonly ApplicationDbContext _db; public DocumentService(ApplicationDbContext db) { _db = db; _db.SeedData(); } public Document GetDocument(string alias) { return _db.Docs .Include(doc => doc.Documents) .ThenInclude(doc => doc.Documents) .FirstOrDefault(doc => doc.Alias==alias); } public IEnumerable<Document> GetRelatedDocuments(Document document) { return _db.Docs.Where(doc=>doc.Tags.Any(tag=>document.Tags.Contains(tag))); } public Document Save(Document document) { var oldDocument = _db.Docs.FirstOrDefault(doc=>doc.Id==document.Id); oldDocument.Content = document.Content; _db.SaveChanges(); return oldDocument; } } }
using System.Collections.Generic; using System.Linq; using SyntacticDocs.Models; using SyntacticDocs.Data; using Microsoft.EntityFrameworkCore; namespace SyntacticDocs.Services { public class DocumentService { private readonly ApplicationDbContext _db; public DocumentService(ApplicationDbContext db) { _db = db; _db.SeedData(); } public Document GetDocument(string alias) { return _db.Docs .Include(doc => doc.Documents) .ThenInclude(doc => doc.Documents) .Where(doc => doc.Alias==alias) .Single(); } public IEnumerable<Document> GetRelatedDocuments(Document document) { return _db.Docs.Where(doc=>doc.Tags.Any(tag=>document.Tags.Contains(tag))); } public Document Save(Document document) { var oldDocument = _db.Docs.FirstOrDefault(doc=>doc.Id==document.Id); oldDocument.Content = document.Content; _db.SaveChanges(); return oldDocument; } } }
apache-2.0
C#
d5f76cb401b9073ad36c1a721445c8e59085ffef
add ToGridLength()
TakeAsh/cs-WpfUtility
WpfUtility/GridHelper.cs
WpfUtility/GridHelper.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; namespace WpfUtility { public static class GridHelper { public static readonly GridLength AutoGridLength = new GridLength(1, GridUnitType.Auto); public static ColumnDefinition AutoWidthColumnDefinition { get { return new ColumnDefinition() { Width = AutoGridLength, }; } } public static RowDefinition AutoHeightRowDefinition { get { return new RowDefinition() { Height = AutoGridLength, }; } } public static GridLength ToGridLength(this double pixels) { return new GridLength(pixels); } public static GridLength ToGridLength(this double value, GridUnitType type) { return new GridLength(value, type); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; namespace WpfUtility { public static class GridHelper { public static readonly GridLength AutoGridLength = new GridLength(1, GridUnitType.Auto); public static ColumnDefinition AutoWidthColumnDefinition { get { return new ColumnDefinition() { Width = AutoGridLength, }; } } public static RowDefinition AutoHeightRowDefinition { get { return new RowDefinition() { Height = AutoGridLength, }; } } } }
mit
C#