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
497a12c78f98a3cc360099748bfc64736fc0a056
Comment fix.
dlemstra/Magick.NET,dlemstra/Magick.NET
Source/Magick.NET/Shared/Defines/ReadDefinesCreator.cs
Source/Magick.NET/Shared/Defines/ReadDefinesCreator.cs
// Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. namespace ImageMagick.Defines { /// <summary> /// Base class that can create read defines. /// </summary> public abstract class ReadDefinesCreator : DefinesCreator, IReadDefines { /// <summary> /// Initializes a new instance of the <see cref="ReadDefinesCreator"/> class. /// </summary> /// <param name="format">The format where the defines are for.</param> protected ReadDefinesCreator(MagickFormat format) : base(format) { } } }
// Copyright 2013-2019 Dirk Lemstra <https://github.com/dlemstra/Magick.NET/> // // Licensed under the ImageMagick License (the "License"); you may not use this file except in // compliance with the License. You may obtain a copy of the License at // // https://www.imagemagick.org/script/license.php // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. namespace ImageMagick.Defines { /// <summary> /// Base class that can create write defines. /// </summary> public abstract class ReadDefinesCreator : DefinesCreator, IReadDefines { /// <summary> /// Initializes a new instance of the <see cref="ReadDefinesCreator"/> class. /// </summary> /// <param name="format">The format where the defines are for.</param> protected ReadDefinesCreator(MagickFormat format) : base(format) { } } }
apache-2.0
C#
cbce9c97a4fb237899556aa2fa152a5f446afce4
Add humanise to encType
GiscardBiamby/NancyContrib.Chameleon,VegasoftTI/ChameleonForms,VegasoftTI/ChameleonForms,GiscardBiamby/NancyContrib.Chameleon,VegasoftTI/ChameleonForms
ChameleonForms/Templates/HtmlHelperExtensions.cs
ChameleonForms/Templates/HtmlHelperExtensions.cs
using System.Collections.Generic; using System.Net.Http; using System.Web; using System.Web.Mvc; using ChameleonForms.Enums; using Humanizer; namespace ChameleonForms.Templates { public static class Html { public static IHtmlString Attribute(string name, string value) { if (value == null) return new HtmlString(string.Empty); //Todo: encode the values here return new HtmlString(string.Format(" {0}=\"{1}\"", name, value)); } public static IHtmlString BuildFormTag(string action, FormMethod method, object htmlAttributes = null, EncType? encType = null) { var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); tagBuilder.MergeAttribute("action", action); tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); if (encType.HasValue) { tagBuilder.MergeAttribute("enctype", encType.Humanize()); } return new HtmlString(tagBuilder.ToString(TagRenderMode.StartTag)); } } }
using System.Collections.Generic; using System.Net.Http; using System.Web; using System.Web.Mvc; namespace ChameleonForms.Templates { public static class Html { public static IHtmlString Attribute(string name, string value) { if (value == null) return new HtmlString(string.Empty); //Todo: encode the values here return new HtmlString(string.Format(" {0}=\"{1}\"", name, value)); } public static IHtmlString BuildFormTag(string action, FormMethod method, object htmlAttributes = null, string encType = null) { var tagBuilder = new TagBuilder("form"); tagBuilder.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); tagBuilder.MergeAttribute("action", action); tagBuilder.MergeAttribute("method", HtmlHelper.GetFormMethodString(method), true); if (!string.IsNullOrEmpty(encType)) { tagBuilder.MergeAttribute("enctype", encType.Humanize()); } return new HtmlString(tagBuilder.ToString(TagRenderMode.StartTag)); } } }
mit
C#
77e258d0734ee728191a9ee1aaf228f4350ef7c1
Use of 'var'.
philjones/nquant,drewnoakes/nquant
nQuant.Core/WuQuantizer.cs
nQuant.Core/WuQuantizer.cs
using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; namespace nQuant { public class WuQuantizer : WuQuantizerBase, IWuQuantizer { private static IEnumerable<byte[]> IndexedPixels(ImageBuffer image, Pixel[] lookups, int alphaThreshold, PaletteColorHistory[] paletteHistogram) { var lineIndexes = new byte[image.Image.Width]; var lookup = new PaletteLookup(lookups); foreach (var pixelLine in image.PixelLines) { for (int pixelIndex = 0; pixelIndex < pixelLine.Length; pixelIndex++) { Pixel pixel = pixelLine[pixelIndex]; byte bestMatch = AlphaColor; if (pixel.Alpha > alphaThreshold) { bestMatch = lookup.GetPaletteIndex(pixel); paletteHistogram[bestMatch].AddPixel(pixel); } lineIndexes[pixelIndex] = bestMatch; } yield return lineIndexes; } } internal override Image GetQuantizedImage(ImageBuffer image, int colorCount, Pixel[] lookups, int alphaThreshold) { var result = new Bitmap(image.Image.Width, image.Image.Height, PixelFormat.Format8bppIndexed); var resultBuffer = new ImageBuffer(result); var paletteHistogram = new PaletteColorHistory[colorCount + 1]; resultBuffer.UpdatePixelIndexes(IndexedPixels(image, lookups, alphaThreshold, paletteHistogram)); result.Palette = BuildPalette(result.Palette, paletteHistogram); return result; } private static ColorPalette BuildPalette(ColorPalette palette, PaletteColorHistory[] paletteHistogram) { for (int paletteColorIndex = 0; paletteColorIndex < paletteHistogram.Length; paletteColorIndex++) { palette.Entries[paletteColorIndex] = paletteHistogram[paletteColorIndex].ToNormalizedColor(); } return palette; } } }
using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; namespace nQuant { public class WuQuantizer : WuQuantizerBase, IWuQuantizer { private static IEnumerable<byte[]> IndexedPixels(ImageBuffer image, Pixel[] lookups, int alphaThreshold, PaletteColorHistory[] paletteHistogram) { var lineIndexes = new byte[image.Image.Width]; PaletteLookup lookup = new PaletteLookup(lookups); foreach (var pixelLine in image.PixelLines) { for (int pixelIndex = 0; pixelIndex < pixelLine.Length; pixelIndex++) { Pixel pixel = pixelLine[pixelIndex]; byte bestMatch = AlphaColor; if (pixel.Alpha > alphaThreshold) { bestMatch = lookup.GetPaletteIndex(pixel); paletteHistogram[bestMatch].AddPixel(pixel); } lineIndexes[pixelIndex] = bestMatch; } yield return lineIndexes; } } internal override Image GetQuantizedImage(ImageBuffer image, int colorCount, Pixel[] lookups, int alphaThreshold) { var result = new Bitmap(image.Image.Width, image.Image.Height, PixelFormat.Format8bppIndexed); var resultBuffer = new ImageBuffer(result); var paletteHistogram = new PaletteColorHistory[colorCount + 1]; resultBuffer.UpdatePixelIndexes(IndexedPixels(image, lookups, alphaThreshold, paletteHistogram)); result.Palette = BuildPalette(result.Palette, paletteHistogram); return result; } private static ColorPalette BuildPalette(ColorPalette palette, PaletteColorHistory[] paletteHistogram) { for (int paletteColorIndex = 0; paletteColorIndex < paletteHistogram.Length; paletteColorIndex++) { palette.Entries[paletteColorIndex] = paletteHistogram[paletteColorIndex].ToNormalizedColor(); } return palette; } } }
apache-2.0
C#
e94bc03e86b2c50af6519de9134610a54e7ea706
make MessageAndError members public so that we can build consumers that are not event-driven
MrGlenThomas/confluent-kafka-dotnet,bjornicus/confluent-kafka-dotnet,treziac/confluent-kafka-dotnet,ah-/rdkafka-dotnet,MrGlenThomas/confluent-kafka-dotnet,treziac/confluent-kafka-dotnet,bjornicus/confluent-kafka-dotnet,MaximGurschi/rdkafka-dotnet
src/RdKafka/Message.cs
src/RdKafka/Message.cs
namespace RdKafka { public struct Message { public string Topic { get; set; } public int Partition { get; set; } public long Offset { get; set; } public byte[] Payload { get; set; } public byte[] Key { get; set; } public TopicPartitionOffset TopicPartitionOffset => new TopicPartitionOffset() { Topic = Topic, Partition = Partition, Offset = Offset }; } public struct MessageAndError { public Message Message; public ErrorCode Error; } }
namespace RdKafka { public struct Message { public string Topic { get; set; } public int Partition { get; set; } public long Offset { get; set; } public byte[] Payload { get; set; } public byte[] Key { get; set; } public TopicPartitionOffset TopicPartitionOffset => new TopicPartitionOffset() { Topic = Topic, Partition = Partition, Offset = Offset }; } public struct MessageAndError { internal Message Message; internal ErrorCode Error; } }
apache-2.0
C#
512edcd02ebfad7e37e49f805325df1687077aff
Sort properties vs. methods; whitespace.
brendanjbaker/StraightSQL
src/StraightSql/IReader.cs
src/StraightSql/IReader.cs
namespace StraightSql { using System; using System.Data.Common; public interface IReader { Type Type { get; } Object Read(DbDataReader reader); } }
namespace StraightSql { using System; using System.Data.Common; public interface IReader { Object Read(DbDataReader reader); Type Type { get; } } }
mit
C#
bf651c68ade0a5aedd742cf63e4f81a662147e0c
Fix font scaling when two monitors are scaled differently (BL-10981)
gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork
src/BloomExe/Properties/AssemblyInfo.cs
src/BloomExe/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("Bloom")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SIL")] [assembly: AssemblyProduct("Bloom")] [assembly: AssemblyCopyright("© SIL International 2012-2020")] [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("0afa7c29-4107-47a8-88cc-c15cb769f35e")] // 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: // Note that an automated process updates these in the TeamCity build; these ones however are important // for whether a local build satisfies BloomParseClient.GetIsThisVersionAllowedToUpload. // [assembly: AssemblyVersion("0.9.999.0")] [assembly: AssemblyVersion("5.1.000.0")] [assembly: AssemblyFileVersion("5.1.000.0")] [assembly: AssemblyInformationalVersion("5.1.000.0")] [assembly: InternalsVisibleTo("BloomTests")] [assembly: InternalsVisibleTo("BloomHarvester")] [assembly: InternalsVisibleTo("BloomHarvesterTests")] [assembly: AssemblyMetadata("SquirrelAwareVersion", "1")] // Without explicitly disabling DPI awareness here, the subsequent // loading of some System.Windows.Media components will cause the // application to change from DPI "Unaware" to DPI "System Aware". // The one place we know this happens currently is when loading font metadata. // This causes problems when one monitor is set to different font scaling than another. // Depending on how far the UI has gotten in setting up when the awareness status changes, // it will either result in inconsistent font/icon sizing or the whole // window will shrink down. See BL-10981. [assembly: System.Windows.Media.DisableDpiAwareness]
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("Bloom")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SIL")] [assembly: AssemblyProduct("Bloom")] [assembly: AssemblyCopyright("© SIL International 2012-2020")] [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("0afa7c29-4107-47a8-88cc-c15cb769f35e")] // 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: // Note that an automated process updates these in the TeamCity build; these ones however are important // for whether a local build satisfies BloomParseClient.GetIsThisVersionAllowedToUpload. // [assembly: AssemblyVersion("0.9.999.0")] [assembly: AssemblyVersion("5.1.000.0")] [assembly: AssemblyFileVersion("5.1.000.0")] [assembly: AssemblyInformationalVersion("5.1.000.0")] [assembly: InternalsVisibleTo("BloomTests")] [assembly: InternalsVisibleTo("BloomHarvester")] [assembly: InternalsVisibleTo("BloomHarvesterTests")] [assembly: AssemblyMetadata("SquirrelAwareVersion", "1")]
mit
C#
7fee8315479244700e46374b28bad668561e2379
Add NotImplemented.ActiveIssue() method. (#3752)
krytarowski/corert,krytarowski/corert,gregkalapos/corert,yizhang82/corert,yizhang82/corert,shrah/corert,krytarowski/corert,yizhang82/corert,shrah/corert,shrah/corert,shrah/corert,yizhang82/corert,krytarowski/corert,gregkalapos/corert,gregkalapos/corert,gregkalapos/corert
src/Common/src/System/NotImplemented.cs
src/Common/src/System/NotImplemented.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { // // Support for tooling-friendly NotImplementedExceptions. // internal static class NotImplemented { /// <summary> /// Permanent NotImplementedException with no message shown to user. /// </summary> internal static Exception ByDesign { get { return new NotImplementedException(); } } /// <summary> /// Permanent NotImplementedException with localized message shown to user. /// </summary> internal static Exception ByDesignWithMessage(string message) { return new NotImplementedException(message); } /// <summary> /// Temporary NotImplementedException with no message shown to user. /// Example: Exception.ActiveIssue("https://github.com/dotnet/corert/issues/xxxx") or Exception.ActiveIssue("TFS xxxxxx"). /// </summary> internal static Exception ActiveIssue(string issue) { return new NotImplementedException(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System { // // This simple class enables one to throw a NotImplementedException using the following // idiom: // // throw NotImplemented.ByDesign; // // Used by methods whose intended implementation is to throw a NotImplementedException (typically // virtual methods in public abstract classes that intended to be subclassed by third parties.) // // This makes it distinguishable both from human eyes and CCI from NYI's that truly represent undone work. // internal static class NotImplemented { internal static Exception ByDesign { get { return new NotImplementedException(); } } internal static Exception ByDesignWithMessage(String message) { return new NotImplementedException(message); } } }
mit
C#
99bb4548db7755c4f3982948147b8f9b66d133c3
Add using lines and namespaces
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/ShaneONeill.cs
src/Firehose.Web/Authors/ShaneONeill.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 ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Shane"; public string LastName => "O'Neill"; public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... "; public string StateOrRegion => "Ireland"; public string EmailAddress => string.Empty; public string TwitterHandle => "SOZDBA"; public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510"; public string GitHubHandle => "shaneis"; public GeoPosition Position => new GeoPosition(53.2707, 9.0568); public Uri WebSite => new Uri("https://nocolumnname.blog/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } } }
public class ShaneONeill : IAmACommunityMember, IFilterMyBlogPosts { public string FirstName => "Shane"; public string LastName => "O'Neill"; public string ShortBioOrTagLine => "DBA. Food, Coffee, Whiskey (not necessarily in that order)... "; public string StateOrRegion => "Ireland"; public string EmailAddress => string.Empty; public string TwitterHandle => "SOZDBA"; public string GravatarHash => "0440d5d8f1b51b4765e3d48aec441510"; public string GitHubHandle => "shaneis"; public GeoPosition Position => new GeoPosition(53.2707, 9.0568); public Uri WebSite => new Uri("https://nocolumnname.blog/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://nocolumnname.blog/feed/"); } } public bool Filter(SyndicationItem item) { // This filters out only the posts that have the "PowerShell" category return item.Categories.Any(c => c.Name.ToLowerInvariant().Equals("powershell")); } }
mit
C#
3ca0d5a660b483a8e503b42d7becebc69afb25e2
Fix bugs in Map
jdno/AIChallengeFramework
Map/Map.cs
Map/Map.cs
// // Copyright 2014 jdno // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; namespace AIChallengeFramework { /// <summary> /// A map is the top-level organizational unit of the gaming board. It contains /// of several continents. /// </summary> public class Map { /// <summary> /// A map consists of several continents. /// </summary> /// <value>The continents.</value> public List<Continent> Continents { get; private set; } /// <summary> /// Dictionary for fast lookup of regions on this map using their ID. /// </summary> /// <value>The regions.</value> public Dictionary<int, Region> Regions { get; private set; } public Map () { Continents = new List<Continent> (); Regions = new Dictionary<int, Region> (); Logger.Info ("Map:\tInitialized."); } /// <summary> /// Adds the continent to the map. /// </summary> /// <param name="continent">Continent.</param> public void AddContinent (Continent continent) { if (!Continents.Contains (continent)) { Continents.Add (continent); foreach (Region r in continent.Regions) { AddRegion (r); } } if (Logger.IsDebug ()) { Logger.Debug (string.Format("Map:\tContinent {0} added.", continent.Id)); } } /// <summary> /// Adds the region to the map. /// </summary> /// <param name="region">Region.</param> public void AddRegion (Region region) { if (!Regions.ContainsKey (region.Id)) { Regions.Add (region.Id, region); AddContinent (region.Continent); if (Logger.IsDebug ()) { Logger.Debug (string.Format("Map:\tRegion {0} added.", region.Id)); } } } /// <summary> /// Return the continent with the given identifier. /// </summary> /// <returns>The continent with the given identifier.</returns> /// <param name="id">Identifier.</param> public Continent ContinentForId (int id) { foreach (Continent c in Continents) { if (c.Id == id) { return c; } } return null; } } }
// // Copyright 2014 jdno // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; namespace AIChallengeFramework { /// <summary> /// A map is the top-level organizational unit of the gaming board. It contains /// of several continents. /// </summary> public class Map { /// <summary> /// A map consists of several continents. /// </summary> /// <value>The continents.</value> public List<Continent> Continents { get; private set; } /// <summary> /// Dictionary for fast lookup of regions on this map using their ID. /// </summary> /// <value>The regions.</value> public Dictionary<int, Region> Regions { get; private set; } public Map () { Continents = new List<Continent> (); Regions = new Dictionary<int, Region> (); Logger.Info ("Map:\tInitialized."); } /// <summary> /// Adds the continent to the map. /// </summary> /// <param name="continent">Continent.</param> public void AddContinent (Continent continent) { if (!Continents.Contains (continent)) { Continents.Add (continent); } if (Logger.IsDebug ()) { Logger.Debug (string.Format("Map:\tContinent {0} added.", continent.Id)); } } /// <summary> /// Adds the region to the map. /// </summary> /// <param name="region">Region.</param> public void AddRegion (Region region) { Regions.Add (region.Id, region); if (Logger.IsDebug ()) { Logger.Debug (string.Format("Map:\tRegion {0} added.", region.Id)); } } /// <summary> /// Return the continent with the given identifier. /// </summary> /// <returns>The continent with the given identifier.</returns> /// <param name="id">Identifier.</param> public Continent ContinentForId (int id) { foreach (Continent c in Continents) { if (c.Id == id) { return c; } } return null; } } }
apache-2.0
C#
cd2ee30be00d7c5c998bc99616c1208c6a90d56a
Update version to 4.3.14
MarimerLLC/cslacontrib,tfreitasleal/cslacontrib,tfreitasleal/cslacontrib,MarimerLLC/cslacontrib,MarimerLLC/cslacontrib,tfreitasleal/cslacontrib,MarimerLLC/cslacontrib
trunk/Source/GlobalAssemblyInfo.cs
trunk/Source/GlobalAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("CslaContrib project")] [assembly: AssemblyCopyright("Copyright CslaContrib 2009-2013")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("4.3.14.0")] [assembly: AssemblyFileVersion("4.3.14.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("CslaContrib project")] [assembly: AssemblyCopyright("Copyright CslaContrib 2009-2012")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("4.3.13.0")] [assembly: AssemblyFileVersion("4.3.13.0")]
mit
C#
7cb10ca3fd2f02f7db837844692eaeeca71ca9f9
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 } } namespace }
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#
e8899fddac5e59c7de68f51c429b331096498e28
add project and legal values
Appleseed/base,Appleseed/base
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
Applications/Appleseed.Base.Alerts.Console/Appleseed.Base.Alerts/Model/SolrResponseItem.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } public DateTime date_last_indexed { get; set; } //ICitations public string act_cfr { get; set; } public string program_area { get; set; } public string description_short { get; set; } public string description_long { get; set; } public DateTime end_date { get; set; } //IClassification public string district_decision { get; set; } public string district { get; set; } public DateTime inspection_end_date { get; set; } public string center { get; set; } public string project_area { get; set; } public string legal_name { get; set; } //IRefusal } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Appleseed.Base.Alerts.Model { class SolrResponseItem { public string id { get; set; } public string item_type { get; set; } public string address_1 { get; set; } public string city { get; set; } public string state { get; set; } public string classification { get; set; } public string country { get; set; } public string postal_code { get; set; } public string product_description { get; set; } public string product_quantity { get; set; } public string product_type { get; set; } public string code_info { get; set; } public string reason_for_recall { get; set; } public DateTime recall_initiation_date { get; set; } public string recall_number { get; set; } public string recalling_firm { get; set; } public string voluntary_mandated { get; set; } public DateTime report_date { get; set; } public string status { get; set; } public DateTime date_last_indexed { get; set; } //ICitations public string act_cfr { get; set; } public string program_area { get; set; } public string description_short { get; set; } public string description_long { get; set; } public DateTime end_date { get; set; } //IClassification public string district_decision { get; set; } public string district { get; set; } public DateTime inspection_end_date { get; set; } public string center { get; set; } //IRefusal } }
apache-2.0
C#
c10c8d4456d51b06361e0b925766d770a4570cf8
Update IDeviceButton.cs
aybe/InputMapper
Assets/InputMapper/IDeviceButton.cs
Assets/InputMapper/IDeviceButton.cs
namespace Assets.InputMapper { /// <summary> /// Defines a device button. /// </summary> public interface IDeviceButton { /// <summary> /// Gets the button description. /// </summary> /// <returns></returns> string GetDescription(); /// <summary> /// Gets analog value for this button. /// </summary> /// <returns>A value between 0.0 and 1.0.</returns> float GetValue(); /// <summary> /// Gets digital value for this button. /// </summary> /// <returns></returns> bool IsPressed(); /// <summary> /// Updates this button (see Remarks). /// </summary> /// <param name="deltaTime"></param> /// <remarks> /// A button such as an analog-emulated keyboard button must be updated to return an accurate value when it is /// queried. /// </remarks> void Update(float deltaTime); } }
namespace Assets.InputMapper { /// <summary> /// Defines a device button. /// </summary> public interface IDeviceButton { /// <summary> /// Gets the button description. /// </summary> /// <returns></returns> string GetDescription(); /// <summary> /// Gets analog value for this button (see Remarks). /// </summary> /// <returns>A value between 0.0 and 1.0.</returns> /// <remarks> /// When underlying button is an emulation such as an analog keyboard button, some easing function such as 'back' /// will return a value outside the 0.0 to 1.0 range. Care should be taken if such easing is used within an axis /// command, i.e. it will behave as if the opposite button of the axis command was pressed instead. /// </remarks> float GetValue(); /// <summary> /// Gets digital value for this button. /// </summary> /// <returns></returns> bool IsPressed(); /// <summary> /// Updates this button (see Remarks). /// </summary> /// <param name="deltaTime"></param> /// <remarks> /// A button such as an analog-emulated keyboard button must be updated to return an accurate value when it is /// queried. /// </remarks> void Update(float deltaTime); } }
mit
C#
658c29cebcc454886451da9528a58408b0cee1c3
Add test for new properties feature.
jonfreeland/Log4Netly
Log4NetlyTesting/Program.cs
Log4NetlyTesting/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; using log4net.Core; namespace Log4NetlyTesting { class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var logger = LogManager.GetLogger(typeof(Program)); ////logger.Info("I know he can get the job, but can he do the job?"); ////logger.Debug("I'm not arguing that with you."); ////logger.Warn("Be careful!"); logger.Error("Have you used a computer before?", new FieldAccessException("You can't access this field.", new AggregateException("You can't aggregate this!"))); try { var hi = 1/int.Parse("0"); } catch (Exception ex) { logger.Error("I'm afraid I can't do that.", ex); } var loggingEvent = new LoggingEvent(typeof(LogManager), logger.Logger.Repository, logger.Logger.Name, Level.Fatal, "Fatal properties, here.", new IndexOutOfRangeException()); loggingEvent.Properties["Foo"] = "Bar"; loggingEvent.Properties["Han"] = "Solo"; loggingEvent.Properties["Two Words"] = "Three words here"; logger.Logger.Log(loggingEvent); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using log4net; namespace Log4NetlyTesting { class Program { static void Main(string[] args) { log4net.Config.XmlConfigurator.Configure(); var logger = LogManager.GetLogger(typeof(Program)); ////logger.Info("I know he can get the job, but can he do the job?"); ////logger.Debug("I'm not arguing that with you."); ////logger.Warn("Be careful!"); logger.Error("Have you used a computer before?", new FieldAccessException("You can't access this field.", new AggregateException("You can't aggregate this!"))); try { var hi = 1/int.Parse("0"); } catch (Exception ex) { logger.Error("I'm afraid I can't do that.", ex); } ////logger.Fatal("That's it. It's over."); Console.ReadKey(); } } }
mit
C#
d50e1cd705cc67b360b9cb4a40ab143c3a901cd8
Make field readonly
mono/cecil,jbevain/cecil,SiliconStudio/Mono.Cecil,fnajera-rac-de/cecil,sailro/cecil
Mono.Cecil.Metadata/Heap.cs
Mono.Cecil.Metadata/Heap.cs
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // namespace Mono.Cecil.Metadata { abstract class Heap { public int IndexSize; readonly internal byte [] data; protected Heap (byte [] data) { this.data = data; } } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // namespace Mono.Cecil.Metadata { abstract class Heap { public int IndexSize; internal byte [] data; protected Heap (byte [] data) { this.data = data; } } }
mit
C#
1dcc2d0fa69d06b55d2ce19715ec21af06f59457
fix test to reflect change from error to warning
cumpstey/robot-test
Tests/BusinessLogic.Tests/ReportCommandTests.cs
Tests/BusinessLogic.Tests/ReportCommandTests.cs
namespace RobotTest.BusinessLogic.Tests { using System; using BusinessLogic.Commands; using Microsoft.VisualStudio.TestTools.UnitTesting; using Utilities.Logging; [TestClass] public class ReportCommandTests { [TestMethod] public void ReportsPositionWhenPlaced() { string output = null; ILogger logger = new CustomisableTextLogger(delegate(string message) { output = message; }); var grid = new Grid(5, 5); State? state = null; Command command = new PlaceCommand(3, 3, MoveDirection.East); state = command.Execute(state, grid, logger); command = new ReportCommand(); state = command.Execute(state, grid, logger); Assert.AreEqual("3,3,East", output); } [TestMethod] public void ReportsWarningWhenNotPlaced() { string output = null; ILogger logger = new CustomisableTextLogger(delegate(string message) { output = message; }); var grid = new Grid(5, 5); State? state = null; var command = new ReportCommand(); state = command.Execute(state, grid, logger); Assert.IsTrue(output != null && output.StartsWith("Warning:")); } } }
namespace RobotTest.BusinessLogic.Tests { using System; using BusinessLogic.Commands; using Microsoft.VisualStudio.TestTools.UnitTesting; using Utilities.Logging; [TestClass] public class ReportCommandTests { [TestMethod] public void ReportsPositionWhenPlaced() { string output = null; ILogger logger = new CustomisableTextLogger(delegate(string message) { output = message; }); var grid = new Grid(5, 5); State? state = null; Command command = new PlaceCommand(3, 3, MoveDirection.East); state = command.Execute(state, grid, logger); command = new ReportCommand(); state = command.Execute(state, grid, logger); Assert.AreEqual("3,3,East", output); } [TestMethod] public void ReportsErrorWhenNotPlaced() { string output = null; ILogger logger = new CustomisableTextLogger(delegate(string message) { output = message; }); var grid = new Grid(5, 5); State? state = null; var command = new ReportCommand(); state = command.Execute(state, grid, logger); Assert.IsTrue(output != null && output.StartsWith("Error:")); } } }
mit
C#
de646649def7d7ca2d0322ab925f386c46343e63
Use test beatmap instead of beatmap manager
ppy/osu,peppy/osu-new,smoogipoo/osu,peppy/osu,UselessToucan/osu,smoogipoo/osu,EVAST9919/osu,UselessToucan/osu,ppy/osu,johnneijzen/osu,EVAST9919/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,peppy/osu,johnneijzen/osu,2yangk23/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,UselessToucan/osu
osu.Game.Tests/Visual/Multiplayer/TestSceneMatchBeatmapDetailArea.cs
osu.Game.Tests/Visual/Multiplayer/TestSceneMatchBeatmapDetailArea.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 NUnit.Framework; using osu.Framework.Graphics; using osu.Game.Online.Multiplayer; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Screens.Multi.Components; using osu.Game.Tests.Beatmaps; using osuTK; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMatchBeatmapDetailArea : MultiplayerTestScene { [SetUp] public void Setup() => Schedule(() => { Room.Playlist.Clear(); Child = new MatchBeatmapDetailArea { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), CreateNewItem = createNewItem }; }); private void createNewItem() { Room.Playlist.Add(new PlaylistItem { ID = Room.Playlist.Count, Beatmap = { Value = new TestBeatmap(new OsuRuleset().RulesetInfo).BeatmapInfo }, Ruleset = { Value = new OsuRuleset().RulesetInfo }, RequiredMods = { new OsuModHardRock(), new OsuModDoubleTime(), new OsuModAutoplay() } }); } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Online.Multiplayer; using osu.Game.Rulesets; using osu.Game.Rulesets.Osu.Mods; using osu.Game.Screens.Multi.Components; using osuTK; namespace osu.Game.Tests.Visual.Multiplayer { public class TestSceneMatchBeatmapDetailArea : MultiplayerTestScene { [Resolved] private BeatmapManager beatmapManager { get; set; } [Resolved] private RulesetStore rulesetStore { get; set; } private MatchBeatmapDetailArea detailArea; [SetUp] public void Setup() => Schedule(() => { Room.Playlist.Clear(); Child = detailArea = new MatchBeatmapDetailArea { Anchor = Anchor.Centre, Origin = Anchor.Centre, Size = new Vector2(500), CreateNewItem = createNewItem }; }); private void createNewItem() { var set = beatmapManager.GetAllUsableBeatmapSetsEnumerable().First(); var rulesets = rulesetStore.AvailableRulesets.ToList(); var beatmap = set.Beatmaps[RNG.Next(0, set.Beatmaps.Count)]; beatmap.BeatmapSet = set; beatmap.Metadata = set.Metadata; Room.Playlist.Add(new PlaylistItem { ID = Room.Playlist.Count, Beatmap = { Value = beatmap }, Ruleset = { Value = rulesets[RNG.Next(0, rulesets.Count)] }, RequiredMods = { new OsuModHardRock(), new OsuModDoubleTime(), new OsuModAutoplay() } }); } } }
mit
C#
58a6575db0c7113a87e8abad501d56a579622cf7
use UNITY_PACKAGE_VERSION to specify package version on export
neuecc/MagicOnion
src/MagicOnion.Client.Unity/Assets/Scripts/Editor/PackageExporter.cs
src/MagicOnion.Client.Unity/Assets/Scripts/Editor/PackageExporter.cs
using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; public static class PackageExporter { [MenuItem("Tools/Export Unitypackage")] public static void Export() { var version = Environment.GetEnvironmentVariable("UNITY_PACKAGE_VERSION"); // configure var roots = new[] { "Scripts/MagicOnion", "Scripts/MagicOnion.Abstractions", "Scripts/MagicOnion.Unity", }; var fileName = string.IsNullOrEmpty(version) ? "MagicOnion.Client.Unity.unitypackage" : $"MagicOnion.Client.Unity.{version}.unitypackage"; var exportPath = "./" + fileName; var packageTargetAssets = roots .SelectMany(root => { var path = Path.Combine(Application.dataPath, root); var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta") .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); return assets; }) .ToArray(); var netStandardsAsset = Directory.EnumerateFiles(Path.Combine(Application.dataPath, "Plugins"), "System.*", SearchOption.AllDirectories) .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); packageTargetAssets = packageTargetAssets.Concat(netStandardsAsset).ToArray(); UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, packageTargetAssets)); AssetDatabase.ExportPackage( packageTargetAssets, exportPath, ExportPackageOptions.Default); UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath)); } }
using System; using System.IO; using System.Linq; using UnityEditor; using UnityEngine; public static class PackageExporter { [MenuItem("Tools/Export Unitypackage")] public static void Export() { // configure var exportPath = "./MagicOnion.Client.Unity.unitypackage"; var roots = new[] { "Scripts/MagicOnion", "Scripts/MagicOnion.Abstractions", "Scripts/MagicOnion.Unity", }; var packageTargetAssets = roots .SelectMany(root => { var path = Path.Combine(Application.dataPath, root); var assets = Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories) .Where(x => Path.GetExtension(x) == ".cs" || Path.GetExtension(x) == ".asmdef" || Path.GetExtension(x) == ".json" || Path.GetExtension(x) == ".meta") .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); return assets; }) .ToArray(); var netStandardsAsset = Directory.EnumerateFiles(Path.Combine(Application.dataPath, "Plugins"), "System.*", SearchOption.AllDirectories) .Select(x => "Assets" + x.Replace(Application.dataPath, "").Replace(@"\", "/")) .ToArray(); packageTargetAssets = packageTargetAssets.Concat(netStandardsAsset).ToArray(); UnityEngine.Debug.Log("Export below files" + Environment.NewLine + string.Join(Environment.NewLine, packageTargetAssets)); AssetDatabase.ExportPackage( packageTargetAssets, exportPath, ExportPackageOptions.Default); UnityEngine.Debug.Log("Export complete: " + Path.GetFullPath(exportPath)); } }
mit
C#
53c0e708f7121116ef73b929b28b7078d4819dd6
Set up "ITestOutputHelper"
dance2die/MyAnimeListSharp
Project.MyAnimeList/Project.MyAnimeList.Test/Tests/MangaValuesTest.cs
Project.MyAnimeList/Project.MyAnimeList.Test/Tests/MangaValuesTest.cs
using Project.MyAnimeList.Test.Fixture; using Xunit.Abstractions; namespace Project.MyAnimeList.Test.Tests { public class MangaValuesTest : CredentialCollectionTest { private const string XML_DECLARATION = @"<?xml version=""1.0"" encoding=""UTF-8""?>"; private readonly ITestOutputHelper _output; //private readonly MangaValues _sut; private readonly string _data = XML_DECLARATION + @"<entry> <chapter>6</chapter> <volume>1</volume> <status>1</status> <score>8</score> <downloaded_chapters></downloaded_chapters> <times_reread></times_reread> <reread_value></reread_value> <date_start></date_start> <date_finish></date_finish> <priority></priority> <enable_discussion></enable_discussion> <enable_rereading></enable_rereading> <comments></comments> <scan_group></scan_group> <tags></tags> <retail_volumes></retail_volumes> </entry>"; public MangaValuesTest(CredentialContextFixture credentialContextFixture, ITestOutputHelper output) : base(credentialContextFixture) { _output = output; } } }
using Project.MyAnimeList.Test.Fixture; namespace Project.MyAnimeList.Test.Tests { public class MangaValuesTest : CredentialCollectionTest { public MangaValuesTest(CredentialContextFixture credentialContextFixture) : base(credentialContextFixture) { } } }
mit
C#
5e17da86e0f5e194bc6399d1b945d1d387d07fd5
Add a cross reference to the docs (#17336)
jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/EventGridSharedAccessSignatureCredential.cs
sdk/eventgrid/Azure.Messaging.EventGrid/src/Customization/EventGridSharedAccessSignatureCredential.cs
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Text; namespace Azure.Messaging.EventGrid { /// <summary> /// SAS token used to authenticate to the Event Grid service. /// </summary> public class EventGridSharedAccessSignatureCredential { /// <summary> /// Initializes a new instance of the <see cref="EventGridSharedAccessSignatureCredential"/> class. /// </summary> /// <param name="signature">SAS token used for authentication. This token can be constructed using /// <see cref="EventGridPublisherClient.BuildSharedAccessSignature"/>.</param> public EventGridSharedAccessSignatureCredential(string signature) { Signature = signature; } /// <summary> /// SAS token used to authenticate to the Event Grid service. /// </summary> public string Signature { get; private set; } /// <summary> /// Updates the SAS token. This is intended to be used when you've regenerated the token and want to update long lived clients. /// </summary> /// <param name="signature">SAS token used for authentication</param> public void Update(string signature) { Signature = signature; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Text; namespace Azure.Messaging.EventGrid { /// <summary> /// SAS token used to authenticate to the Event Grid service. /// </summary> public class EventGridSharedAccessSignatureCredential { /// <summary> /// Initializes a new instance of the <see cref="EventGridSharedAccessSignatureCredential"/> class. /// </summary> /// <param name="signature">SAS token used for authentication</param> public EventGridSharedAccessSignatureCredential(string signature) { Signature = signature; } /// <summary> /// SAS token used to authenticate to the Event Grid service. /// </summary> public string Signature { get; private set; } /// <summary> /// Updates the SAS token. This is intended to be used when you've regenerated the token and want to update long lived clients. /// </summary> /// <param name="signature">SAS token used for authentication</param> public void Update(string signature) { Signature = signature; } } }
mit
C#
bffc70352f387e86a689213af5819ea6277f9eb1
Update Actor.cs
dimmpixeye/Unity3dTools
Runtime/LibMono/Actor.cs
Runtime/LibMono/Actor.cs
// Project : ACTORS // Contacts : Pixeye - ask@pixeye.games using Unity.IL2CPP.CompilerServices; using UnityEngine; #if ODIN_INSPECTOR using Sirenix.OdinInspector; #endif namespace Pixeye.Actors { [Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks | Option.DivideByZeroChecks, false)] public class Actor : MonoCached { public ent entity; #if UNITY_EDITOR [FoldoutGroup("Main"), SerializeField, ReadOnly] internal int _entity; #endif [FoldoutGroup("Main")] public bool isPooled; [FoldoutGroup("Main")] public ScriptableBuild buildFrom; //===============================// // Launch methods //===============================// public sealed override void Bootstrap(LayerCore layer) { Layer = layer; if (!entity.exist) entity = layer.Entity.CreateForActor(this, buildFrom, isPooled); #if UNITY_EDITOR _entity = entity.id; #endif Setup(); HandleEnable(); } internal void Bootstrap(LayerCore layer, ModelComposer model) { Layer = layer; if (!entity.exist) entity = layer.Entity.CreateForActor(this, model, isPooled); #if UNITY_EDITOR _entity = entity.id; #endif Setup(); HandleEnable(); } } }
// Project : ACTORS // Contacts : Pixeye - ask@pixeye.games using Unity.IL2CPP.CompilerServices; using UnityEngine; #if ODIN_INSPECTOR using Sirenix.OdinInspector; #endif namespace Pixeye.Actors { [Il2CppSetOption(Option.NullChecks | Option.ArrayBoundsChecks | Option.DivideByZeroChecks, false)] public class Actor : MonoCached { public ent entity; #if UNITY_EDITOR [FoldoutGroup("Main"), SerializeField, ReadOnly] internal int _entity; #endif [FoldoutGroup("Main")] public bool isPooled; [FoldoutGroup("Main")] public ScriptableBuild buildFrom; //===============================// // Launch methods //===============================// public sealed override void Bootstrap(LayerCore layer) { Layer = layer; if (!entity.exist) entity = layer.Entity.CreateForActor(this, buildFrom, isPooled); #if UNITY_EDITOR _entity = entity.id; #endif Setup(); HandleEnable(); } internal void Bootstrap(LayerCore layer, ModelComposer model) { Layer = layer; if (!entity.exist) entity = layer.Entity.CreateForActor(this, model, isPooled); _entity = entity.id; Setup(); HandleEnable(); } } }
mit
C#
58b50358a025b7cb774280e4f4e2c43943bbae7c
Create backup of databases
ronaldme/Sandbox
SQL.Databases/Program.cs
SQL.Databases/Program.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; namespace SQL.Databases { class Program { private static readonly string dbPath = @"D:\databases"; private static readonly string connectionString = ConfigurationManager.ConnectionStrings["sql-server-db"].ConnectionString; static void Main(string[] args) { var dbNames = GetDatabaseNames(); var systemDbs = new[] {"master", "tempdb", "model", "msdb"}; dbNames.RemoveAll(s => systemDbs.Contains(s)); dbNames.ForEach(Console.WriteLine); Console.WriteLine("Starting to backup databases..."); BackupDatabases(dbNames); Console.WriteLine("Done"); Console.ReadLine(); } private static void BackupDatabases(List<string> databaseNames) { var stopWatch = Stopwatch.StartNew(); foreach (var dbName in databaseNames) { using (var connection = new SqlConnection(connectionString)) { Directory.CreateDirectory($@"{dbPath}\{dbName}"); var date = DateTime.Now.ToString("yyyy-MM-dd-HH-mm"); var cmd = new SqlCommand { CommandText = $@"BACKUP DATABASE ""{dbName}"" TO DISK = '{dbPath}\{dbName}\{date}-{dbName}.bak'", CommandType = CommandType.Text, Connection = connection }; connection.Open(); cmd.ExecuteReader(); connection.Close(); } } Console.WriteLine($"Created database backups in: {stopWatch.ElapsedMilliseconds}ms."); } private static List<string> GetDatabaseNames() { var dbNames = new List<string>(); using (var con = new SqlConnection(connectionString)) { con.Open(); var databases = con.GetSchema("Databases"); foreach (DataRow database in databases.Rows) { string databaseName = database.Field<string>("database_name"); dbNames.Add(databaseName); } } return dbNames; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; namespace SQL.Databases { class Program { static void Main(string[] args) { var dbNames = GetDatabaseNames(); var systemDbs = new[] {"master", "tempdb", "model", "msdb"}; dbNames.RemoveAll(s => systemDbs.Contains(s)); dbNames.ForEach(Console.WriteLine); Console.ReadLine(); } private static List<string> GetDatabaseNames() { var dbNames = new List<string>(); using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["sql-server-db"].ConnectionString)) { con.Open(); var databases = con.GetSchema("Databases"); foreach (DataRow database in databases.Rows) { string databaseName = database.Field<string>("database_name"); dbNames.Add(databaseName); } } return dbNames; } } }
mit
C#
0a43e54dfc5d605d45f55cc1327cb95056fdc262
Fix request failing due to parameters
peppy/osu,ppy/osu,smoogipoo/osu,peppy/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,peppy/osu,UselessToucan/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu-new
osu.Game/Online/Rooms/JoinRoomRequest.cs
osu.Game/Online/Rooms/JoinRoomRequest.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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; return req; } // Todo: Password needs to be specified here rather than via AddParameter() because this is a PUT request. May be a framework bug. protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}?password={Password}"; } }
// 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.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API; namespace osu.Game.Online.Rooms { public class JoinRoomRequest : APIRequest { public readonly Room Room; public readonly string Password; public JoinRoomRequest(Room room, string password) { Room = room; Password = password; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Put; if (!string.IsNullOrEmpty(Password)) req.AddParameter("password", Password); return req; } protected override string Target => $"rooms/{Room.RoomID.Value}/users/{User.Id}"; } }
mit
C#
e0262f5ea57feda545e26269a3396166a47185b3
Fix error in comment
DigDes/SoapCore
src/SoapCore/TrailingServicePathTuner.cs
src/SoapCore/TrailingServicePathTuner.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace SoapCore { /// <summary> /// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc /// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner()); /// </summary> public class TrailingServicePathTuner : IServiceOperationTuner { public void Tune(HttpContext httpContext, object serviceInstance, OperationDescription operation) { string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/')); httpContext.Request.Path = new PathString(trailingPath); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace SoapCore { /// <summary> /// This tuner truncates the incoming http request to the last path-part. ie. /DynamicPath/Service.svc becomes /Service.svc /// Register this tuner in ConfigureServices: services.AddSoapServiceOperationTuner(new TrailingServicePathTuner)); /// </summary> public class TrailingServicePathTuner : IServiceOperationTuner { public void Tune(HttpContext httpContext, object serviceInstance, OperationDescription operation) { string trailingPath = httpContext.Request.Path.Value.Substring(httpContext.Request.Path.Value.LastIndexOf('/')); httpContext.Request.Path = new PathString(trailingPath); } } }
mit
C#
28d87fb5c49f2fba95f21f34a50183fcd813e9b9
Fix cake script
RehanSaeed/Serilog.Exceptions,RehanSaeed/Serilog.Exceptions
build.cake
build.cake
var target = Argument("Target", "Default"); var configuration = HasArgument("Configuration") ? Argument<string>("Configuration") : EnvironmentVariable("Configuration") != null ? EnvironmentVariable("Configuration") : "Release"; var buildNumber = HasArgument("BuildNumber") ? Argument<int>("BuildNumber") : AppVeyor.IsRunningOnAppVeyor ? AppVeyor.Environment.Build.Number : TravisCI.IsRunningOnTravisCI ? TravisCI.Environment.Build.BuildNumber : EnvironmentVariable("BuildNumber") != null ? int.Parse(EnvironmentVariable("BuildNumber")) : 0; var artifactsDirectory = Directory("./Artifacts"); Task("Clean") .Does(() => { CleanDirectory(artifactsDirectory); }); Task("Restore") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(); }); Task("Build") .IsDependentOn("Restore") .Does(() => { foreach(var project in GetFiles("./**/*.xproj")) { DotNetCoreBuild( project.GetDirectory().FullPath, new DotNetCoreBuildSettings() { Configuration = configuration }); } }); Task("Test") .IsDependentOn("Build") .Does(() => { foreach(var project in GetFiles("./**/*.Test.xproj")) { DotNetCoreTest( project.GetDirectory().FullPath, new DotNetCoreTestSettings() { ArgumentCustomization = args => args .Append("-xml") .Append(artifactsDirectory.Path.CombineWithFilePath(project.GetFilenameWithoutExtension()).FullPath + ".xml"), Configuration = configuration, NoBuild = true }); } }); Task("Pack") .IsDependentOn("Test") .Does(() => { var revision = buildNumber.ToString("D4"); foreach (var project in GetFiles("./Source/**/*.xproj")) { DotNetCorePack( project.GetDirectory().FullPath, new DotNetCorePackSettings() { Configuration = configuration, OutputDirectory = artifactsDirectory, VersionSuffix = revision }); } }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("Target", "Default"); var configuration = HasArgument("Configuration") ? Argument("Configuration") : EnvironmentVariable("Configuration") != null ? EnvironmentVariable("Configuration") : "Release"; var buildNumber = HasArgument("BuildNumber") ? Argument<int>("BuildNumber") : AppVeyor.IsRunningOnAppVeyor ? AppVeyor.Environment.Build.Number : TravisCI.IsRunningOnTravisCI ? TravisCI.Environment.Build.BuildNumber : EnvironmentVariable("BuildNumber") != null ? int.Parse(EnvironmentVariable("BuildNumber")) : 0; var artifactsDirectory = Directory("./Artifacts"); Task("Clean") .Does(() => { CleanDirectory(artifactsDirectory); }); Task("Restore") .IsDependentOn("Clean") .Does(() => { DotNetCoreRestore(); }); Task("Build") .IsDependentOn("Restore") .Does(() => { foreach(var project in GetFiles("./**/*.xproj")) { DotNetCoreBuild( project.GetDirectory().FullPath, new DotNetCoreBuildSettings() { Configuration = configuration }); } }); Task("Test") .IsDependentOn("Build") .Does(() => { foreach(var project in GetFiles("./**/*.Test.xproj")) { DotNetCoreTest( project.GetDirectory().FullPath, new DotNetCoreTestSettings() { ArgumentCustomization = args => args .Append("-xml") .Append(artifactsDirectory.Path.CombineWithFilePath(project.GetFilenameWithoutExtension()).FullPath + ".xml"), Configuration = configuration, NoBuild = true }); } }); Task("Pack") .IsDependentOn("Test") .Does(() => { var revision = buildNumber.ToString("D4"); foreach (var project in GetFiles("./Source/**/*.xproj")) { DotNetCorePack( project.GetDirectory().FullPath, new DotNetCorePackSettings() { Configuration = configuration, OutputDirectory = artifactsDirectory, VersionSuffix = revision }); } }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
mit
C#
309e74afac74dfb7420e69995e5173ba832389f4
Move compile to the correct task.
peppy/osu,UselessToucan/osu,naoey/osu,johnneijzen/osu,ppy/osu,ppy/osu,johnneijzen/osu,ZLima12/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,naoey/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,DrabWeb/osu,ZLima12/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,NeoAdonis/osu,UselessToucan/osu,DrabWeb/osu,2yangk23/osu,EVAST9919/osu,ppy/osu,naoey/osu,DrabWeb/osu,UselessToucan/osu,peppy/osu,peppy/osu-new
build.cake
build.cake
#tool "nuget:?package=JetBrains.ReSharper.CommandLineTools" #tool "nuget:?package=NVika.MSBuild" #addin "nuget:?package=CodeFileSanity" var NVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var framework = Argument("framework", "netcoreapp2.1"); var configuration = Argument("configuration", "Release"); var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj"); var osuSolution = new FilePath("./osu.sln"); var testProjects = GetFiles("**/*.Tests.csproj"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings { Framework = framework, Configuration = configuration }); }); Task("Test") .ContinueOnError() .DoesForEach(testProjects, testProject => { DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings { Framework = framework, Configuration = configuration, Logger = $"trx;LogFileName={testProject.GetFilename()}.trx", ResultsDirectory = "./TestResults/" }); }); Task("Restore Nuget") .Does(() => NuGetRestore(osuSolution)); Task("InspectCode") .IsDependentOn("Restore Nuget") .IsDependentOn("Compile") .Does(() => { InspectCode(osuSolution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); StartProcess(NVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = ".", IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
#tool "nuget:?package=JetBrains.ReSharper.CommandLineTools" #tool "nuget:?package=NVika.MSBuild" #addin "nuget:?package=CodeFileSanity" var NVikaToolPath = GetFiles("./tools/NVika.MSBuild.*/tools/NVika.exe").First(); /////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Build"); var framework = Argument("framework", "netcoreapp2.1"); var configuration = Argument("configuration", "Release"); var osuDesktop = new FilePath("./osu.Desktop/osu.Desktop.csproj"); var osuSolution = new FilePath("./osu.sln"); var testProjects = GetFiles("**/*.Tests.csproj"); /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Compile") .Does(() => { DotNetCoreBuild(osuDesktop.FullPath, new DotNetCoreBuildSettings { Framework = framework, Configuration = configuration }); }); Task("Test") .ContinueOnError() .DoesForEach(testProjects, testProject => { DotNetCoreTest(testProject.FullPath, new DotNetCoreTestSettings { Framework = framework, Configuration = configuration, Logger = $"trx;LogFileName={testProject.GetFilename()}.trx", ResultsDirectory = "./TestResults/" }); }); Task("Restore Nuget") .Does(() => NuGetRestore(osuSolution)); Task("InspectCode") .IsDependentOn("Restore Nuget") .Does(() => { InspectCode(osuSolution, new InspectCodeSettings { CachesHome = "inspectcode", OutputFile = "inspectcodereport.xml", }); StartProcess(NVikaToolPath, @"parsereport ""inspectcodereport.xml"" --treatwarningsaserrors"); }); Task("CodeFileSanity") .Does(() => { ValidateCodeSanity(new ValidateCodeSanitySettings { RootDirectory = ".", IsAppveyorBuild = AppVeyor.IsRunningOnAppVeyor }); }); Task("Build") .IsDependentOn("CodeFileSanity") .IsDependentOn("Compile") .IsDependentOn("InspectCode") .IsDependentOn("Test"); RunTarget(target);
mit
C#
0f9d4753e537b113a8044967a92fc49e9da4cbcb
Add test step to build.cake
vCipher/Cake.Hg
build.cake
build.cake
#tool "nuget:?package=NUnit.ConsoleRunner" var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var solution = GetFiles("./*.sln") .First() .GetFilenameWithoutExtension(); Task("Default") .Does(() => { Information("Cake bootstrap completed..."); }); Task("Clean") .Does(() => { CleanDirectories("./build"); }); Task("NuGet-Restore") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./" + solution + ".sln"); }); Task("Build") .IsDependentOn("NuGet-Restore") .Does(() => { MSBuild("./" + solution + ".sln", settings => settings.SetConfiguration(configuration) .WithTarget("Rebuild")); }); Task("Test") .IsDependentOn("Build") .Does(() => { var settings = new NUnit3Settings { NoResults = true }; NUnit3("./**/bin/" + configuration + "/*Tests.dll", settings); }); Task("NuGet-Pack") .IsDependentOn("Test") .Does(() => { var projects = GetFiles("./**/*.nuspec") .Select(file => file.GetFilenameWithoutExtension()) .SelectMany(file => GetFiles("./**/" + file + ".csproj")); var settings = new NuGetPackSettings { Copyright = "Copyright © vCipher " + DateTime.Now.Year, OutputDirectory = "./build", Properties = new Dictionary<string, string> { ["Configuration"] = configuration } }; NuGetPack(projects, settings); }); Task("AppVeyor") .IsDependentOn("NuGet-Pack"); RunTarget(target);
var target = Argument("target", "Build"); var configuration = Argument("configuration", "Release"); var solution = GetFiles("./*.sln") .First() .GetFilenameWithoutExtension(); Task("Default") .Does(() => { Information("Cake bootstrap completed..."); }); Task("Clean") .Does(() => { CleanDirectories("./build"); }); Task("NuGet-Restore") .IsDependentOn("Clean") .Does(() => { NuGetRestore("./" + solution + ".sln"); }); Task("Build") .IsDependentOn("NuGet-Restore") .Does(() => { MSBuild("./" + solution + ".sln", settings => settings.SetConfiguration(configuration) .WithTarget("Rebuild")); }); Task("Test") .IsDependentOn("Build") .Does(() => { Information("Test completed..."); }); Task("NuGet-Pack") .IsDependentOn("Test") .Does(() => { var projects = GetFiles("./**/*.nuspec") .Select(file => file.GetFilenameWithoutExtension()) .SelectMany(file => GetFiles("./**/" + file + ".csproj")); var settings = new NuGetPackSettings { Copyright = "Copyright © vCipher " + DateTime.Now.Year, OutputDirectory = "./build", Properties = new Dictionary<string, string> { ["Configuration"] = configuration } }; NuGetPack(projects, settings); }); Task("AppVeyor") .IsDependentOn("NuGet-Pack"); RunTarget(target);
mit
C#
73f5f6a8790a1fdff9c5835abebe7f4e0f46101b
Add back ShardFailureReason.IOError and mark it as obsolete
BundledSticksInkorperated/Discore
src/Discore/WebSocket/ShardFailureReason.cs
src/Discore/WebSocket/ShardFailureReason.cs
using System; namespace Discore.WebSocket { public enum ShardFailureReason { /// <summary> /// Should be reported to the Discore developers if received. /// </summary> Unknown, [Obsolete("This failure reason can no longer happen, any code handling it can be removed.")] IOError, /// <summary> /// The shard was invalid, given the sharding settings for the application. /// </summary> ShardInvalid, /// <summary> /// The shard failed to authenticate with the Discord Gateway WebSocket API. /// </summary> AuthenticationFailed, /// <summary> /// Occurs if only one shard is used, and that shard would have handled too many guilds. /// More than one shard is required if this happens. /// </summary> ShardingRequired } }
namespace Discore.WebSocket { public enum ShardFailureReason { /// <summary> /// Should be reported to the Discore developers if received. /// </summary> Unknown, /// <summary> /// The shard was invalid, given the sharding settings for the application. /// </summary> ShardInvalid, /// <summary> /// The shard failed to authenticate with the Discord Gateway WebSocket API. /// </summary> AuthenticationFailed, /// <summary> /// Occurs if only one shard is used, and that shard would have handled too many guilds. /// More than one shard is required if this happens. /// </summary> ShardingRequired } }
mit
C#
ffacede948e72eb8dc7135fe53a9ac7ece847d3f
fix an XML Doc tag in the TimerManagerEventset
rl132/RLToolkit
BasicModules/TimerManager/TimerManagerEventset.cs
BasicModules/TimerManager/TimerManagerEventset.cs
using System; namespace RLToolkit.Basic { /// <summary> /// Timer manager EventSet. /// </summary> public class TimerManagerEventset { /// <summary>The EventSet identifier.</summary> public string Id; /// <summary> The next expected tick in DateTime format</summary> public DateTime nextTick; /// <summary>The number of milliseconds inbetween ticking</summary> public int timeInbetweenTick; /// <summary>If the event is paused or not</summary> public bool isPaused = false; /// <summary>The event handler to call when ticking</summary> public event TimerManagerEventHandler eHandler; /// <summary>Method to fire the event</summary> /// <param name="sender">Sender.</param> /// <param name="e">The event information</param> public void executeEvent (object sender, TimerManagerEventArg e) { if (eHandler != null) { eHandler (sender, e); } } } }
using System; namespace RLToolkit.Basic { /// <summary> /// Timer manager EventSet. /// </summary> public class TimerManagerEventset { /// <summary>The EventSet identifier.</summary> public string Id; /// <summary> The next expected tick in DateTime format</summary> public DateTime nextTick; /// <summary>The number of milliseconds inbetween ticking</summary> public int timeInbetweenTick; /// summary>If the event is paused or not</summary> public bool isPaused = false; /// <summary>The event handler to call when ticking</summary> public event TimerManagerEventHandler eHandler; /// <summary>Method to fire the event</summary> /// <param name="sender">Sender.</param> /// <param name="e">The event information</param> public void executeEvent (object sender, TimerManagerEventArg e) { if (eHandler != null) { eHandler (sender, e); } } } }
mit
C#
a665f0660b060cdc221505045f68f089bdd7eade
Add licence to code header
jdh28/EmbedWmpArt
Program.cs
Program.cs
/* * John Hall <john@jdh28.co.uk> * Copyright (c) John Hall. All rights reserved. * * This program is licensed under the MIT licence, see LICENSE.md. */ using System; using System.IO; using System.Linq; using System.Security; using TagLib; namespace EmbedWmpArt { class Program { static int Main(string[] args) { if (args.Length > 1) { Console.Error.Write("Unexpected arguments"); return 1; } try { var rootDir = args.Length == 1 ? args[0] : Environment.CurrentDirectory; foreach (var coverImage in Directory.EnumerateFiles(rootDir, "Folder.jpg", SearchOption.AllDirectories)) ProcessDir(rootDir, coverImage); return 0; } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } catch (UnauthorizedAccessException uae) { Console.Error.WriteLine(uae.Message); } catch (SecurityException se) { Console.Error.WriteLine(se.Message); } return 1; } private static void ProcessDir(string rootDir, string coverImage) { var dir = Path.GetDirectoryName(coverImage); Picture picture = null; foreach (var mp3 in Directory.EnumerateFiles(dir, "*.mp3").Select(f => TagLib.File.Create(f))) { if (mp3.Tag.Pictures.Length == 0) { var displayName = mp3.Name.Substring(rootDir.Length + 1); Console.Out.WriteLine(displayName); if (picture == null) picture = new Picture(coverImage); mp3.Tag.Pictures = new[] { picture }; mp3.Save(); } } } } }
/* * John Hall <john@jdh28.co.uk> * Copyright (c) John Hall. All rights reserved. */ using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security; using System.Text; using TagLib; namespace EmbedWmpArt { class Program { static int Main(string[] args) { if (args.Length > 1) { Console.Error.Write("Unexpected arguments"); return 1; } try { var rootDir = args.Length == 1 ? args[0] : Environment.CurrentDirectory; foreach (var coverImage in Directory.EnumerateFiles(rootDir, "Folder.jpg", SearchOption.AllDirectories)) ProcessDir(rootDir, coverImage); return 0; } catch (IOException ioe) { Console.Error.WriteLine(ioe.Message); } catch (UnauthorizedAccessException uae) { Console.Error.WriteLine(uae.Message); } catch (SecurityException se) { Console.Error.WriteLine(se.Message); } return 1; } private static void ProcessDir(string rootDir, string coverImage) { var dir = Path.GetDirectoryName(coverImage); Picture picture = null; foreach (var mp3 in Directory.EnumerateFiles(dir, "*.mp3").Select(f => TagLib.File.Create(f))) { if (mp3.Tag.Pictures.Length == 0) { var displayName = mp3.Name.Substring(rootDir.Length + 1); Console.Out.WriteLine(displayName); if (picture == null) picture = new Picture(coverImage); mp3.Tag.Pictures = new[] { picture }; mp3.Save(); } } } } }
mit
C#
545806c9c405fb5d0b926b73e92f3ba2375671fc
Refactor ConsoleHelper
attemoi/MoistureBot
MoistureBotLib/Utils/ConsoleHelper.cs
MoistureBotLib/Utils/ConsoleHelper.cs
using System; using System.Collections.Generic; using System.Linq; using Mono.Options; namespace MoistureBot.Utils { public class ConsoleHelper { /// <summary> /// Like System.Console.ReadLine(), only with a mask. /// </summary> /// <param name="mask">a <c>char</c> representing your choice of console mask</param> /// <returns>the string the user typed in </returns> /// <summary> /// Like System.Console.ReadLine(), only with a mask. /// </summary> /// <param name="mask">a <c>char</c> representing your choice of console mask</param> /// <returns>the string the user typed in </returns> public static string ReadPassword(char mask) { ConsoleKey[] FILTERED = { ConsoleKey.Escape, ConsoleKey.Tab }; var pass = new Stack<char>(); ConsoleKeyInfo keyInfo; while ((keyInfo = System.Console.ReadKey(true)).Key != ConsoleKey.Enter) { if (keyInfo.Key.Equals(ConsoleKey.Backspace)) { if (pass.Count > 0) { System.Console.Write("\b \b"); pass.Pop(); } } else if (!FILTERED.Contains(keyInfo.Key)) { pass.Push(keyInfo.KeyChar); System.Console.Write(mask); } } System.Console.WriteLine(); return new string(pass.Reverse().ToArray()); } /// <summary> /// Like System.Console.ReadLine(), only with a mask. /// </summary> /// <returns>the string the user typed in </returns> public static string ReadPassword() { return ReadPassword('\0'); } } }
using System; using System.Collections.Generic; using System.Linq; using Mono.Options; namespace MoistureBot.Utils { public class ConsoleHelper { /// <summary> /// Like System.Console.ReadLine(), only with a mask. /// </summary> /// <param name="mask">a <c>char</c> representing your choice of console mask</param> /// <returns>the string the user typed in </returns> /// <summary> /// Like System.Console.ReadLine(), only with a mask. /// </summary> /// <param name="mask">a <c>char</c> representing your choice of console mask</param> /// <returns>the string the user typed in </returns> public static string ReadPassword(char mask) { ConsoleKey[] FILTERED = { ConsoleKey.Escape, ConsoleKey.Tab }; // const var pass = new Stack<char>(); ConsoleKeyInfo key; while ((key = System.Console.ReadKey(true)).Key != ConsoleKey.Enter) { if (key.Key.Equals(ConsoleKey.Backspace)) { if (pass.Count > 0) { System.Console.Write("\b \b"); pass.Pop(); } } else if (FILTERED.Count(x => key.Key == x) > 0) { } else { pass.Push(key.KeyChar); System.Console.Write(mask); } } System.Console.WriteLine(); return new string(pass.Reverse().ToArray()); } /// <summary> /// Like System.Console.ReadLine(), only with a mask. /// </summary> /// <returns>the string the user typed in </returns> public static string ReadPassword() { return ReadPassword('\0'); } } }
mit
C#
1e5eb4209dcd39b10a4eb12d604dedf6340d616d
Enable automatic versioning and Nuget packaging of shippable Vipr binaries
tonycrider/Vipr,Microsoft/Vipr,MSOpenTech/Vipr,ysanghi/Vipr,tonycrider/Vipr,v-am/Vipr
src/Core/Vipr/Program.cs
src/Core/Vipr/Program.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; namespace Vipr { internal class Program { private static void Main(string[] args) { var bootstrapper = new Bootstrapper(); bootstrapper.Start(args); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.IO; using System.Reflection; using System.Text; using System.Xml.Linq; using Vipr.Core; namespace Vipr { internal class Program { private static void Main(string[] args) { var bootstrapper = new Bootstrapper(); bootstrapper.Start(args); } } }
mit
C#
3527dac1f7e2437115e1a55822299c186e73bb68
Change the ParameterizedType.GetHashCode method to use a simpler algorithm.
studio-nine/Nine.Injection
src/ParameterizedType.cs
src/ParameterizedType.cs
namespace Nine.Injection { using System; struct ParameterizedType { public Type Type; public object[] Parameters; public override string ToString() => $"{ Type.Name }"; public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (!(obj is ParameterizedType)) { return false; } var other = (ParameterizedType)obj; if (Type != other.Type) { return false; } if ((Parameters == null || Parameters.Length == 0) && (other.Parameters == null || other.Parameters.Length == 0)) { return true; } var count = Parameters.Length; for (var i = 0; i < count; i++) { if (!Equals(Parameters[i], other.Parameters[i])) { return false; } } return true; } public override int GetHashCode() { var hash = Type.GetHashCode(); if (Parameters != null) { var count = Parameters.Length; for (var i = 0; i < count; i++) { var item = Parameters[i]; if (item == null) continue; hash = (hash << 5) + hash; hash ^= item.GetHashCode(); } } return hash; } } }
namespace Nine.Injection { using System; struct ParameterizedType { public Type Type; public object[] Parameters; public override string ToString() => $"{ Type.Name }"; public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) { return true; } if (!(obj is ParameterizedType)) { return false; } var other = (ParameterizedType)obj; if (Type != other.Type) { return false; } if ((Parameters == null || Parameters.Length == 0) && (other.Parameters == null || other.Parameters.Length == 0)) { return true; } var count = Parameters.Length; for (var i = 0; i < count; i++) { if (!Equals(Parameters[i], other.Parameters[i])) { return false; } } return true; } public override int GetHashCode() { ulong hash = 2166136261U; hash ^= (ulong)Type.GetHashCode(); if (Parameters != null) { var count = Parameters.Length; for (var i = 0; i < count; i++) { var item = Parameters[i]; if (item == null) continue; hash ^= (ulong)item.GetHashCode(); hash *= 16777619U; } } return (int)hash; } } }
mit
C#
4cf1c939af0156d85ccfaee10be598685b8825c8
Add AttributeUsage attribute to EncryptAttribute.
QuickenLoans/XSerializer,rlyczynski/XSerializer
XSerializer/Encryption/EncryptAttribute.cs
XSerializer/Encryption/EncryptAttribute.cs
using System; namespace XSerializer.Encryption { /// <summary> /// Indicates that the value of a property should be encrypted or decrypted, /// depending on whether the current serialization operation is configured /// to do so. /// </summary> [AttributeUsage(AttributeTargets.Property)] public class EncryptAttribute : Attribute { } }
using System; namespace XSerializer.Encryption { /// <summary> /// Indicates that the value of a property should be encrypted or decrypted, /// depending on whether the current serialization operation is configured /// to do so. /// </summary> public class EncryptAttribute : Attribute { } }
mit
C#
d81d2ec58497507f56971f3f97197a0fda709bf4
Move TreeGridItem.Tag to GridItem.Tag
PowerOfCode/Eto,PowerOfCode/Eto,bbqchickenrobot/Eto-1,PowerOfCode/Eto,l8s/Eto,bbqchickenrobot/Eto-1,l8s/Eto,l8s/Eto,bbqchickenrobot/Eto-1
Source/Eto/Forms/Controls/GridItem.cs
Source/Eto/Forms/Controls/GridItem.cs
using System; using System.Collections.Generic; namespace Eto.Forms { public interface IGridItem { } public class GridItemCollection : DataStoreCollection<IGridItem>, IGridStore { public GridItemCollection () { } public GridItemCollection (IEnumerable<IGridItem> items) : base (items) { } } public class GridItem : IGridItem, IColumnItem { public GridItem () { } public GridItem (params object[] values) { this.Values = values; } public object Tag { get; set; } public object[] Values { get; set; } public virtual object GetValue (int column) { if (Values == null || Values.Length <= column) return null; return Values [column]; } public virtual void SetValue (int column, object value) { if (Values == null) { Values = new object[column + 1]; } else if (column >= Values.Length) { var oldvalues = Values; Values = new object[column + 1]; Array.Copy (oldvalues, Values, oldvalues.Length); } Values [column] = value; } } }
using System; using System.Collections.Generic; namespace Eto.Forms { public interface IGridItem { } public class GridItemCollection : DataStoreCollection<IGridItem>, IGridStore { public GridItemCollection () { } public GridItemCollection (IEnumerable<IGridItem> items) : base (items) { } } public class GridItem : IGridItem, IColumnItem { public GridItem () { } public GridItem (params object[] values) { this.Values = values; } public object[] Values { get; set; } public virtual object GetValue (int column) { if (Values == null || Values.Length <= column) return null; return Values [column]; } public virtual void SetValue (int column, object value) { if (Values == null) { Values = new object[column + 1]; } else if (column >= Values.Length) { var oldvalues = Values; Values = new object[column + 1]; Array.Copy (oldvalues, Values, oldvalues.Length); } Values [column] = value; } } }
bsd-3-clause
C#
c20315b4411e0792422570112732a424ea167b14
Update Subsonic API versions
archrival/SubsonicSharp
Subsonic.Common/SubsonicApiVersion.cs
Subsonic.Common/SubsonicApiVersion.cs
using System; namespace Subsonic.Common { public static class SubsonicApiVersion { public static readonly Version Max = Version1_16_0; public static readonly Version Version1_0_0 = Version.Parse("1.0.0"); public static readonly Version Version1_1_0 = Version.Parse("1.1.0"); public static readonly Version Version1_1_1 = Version.Parse("1.1.1"); public static readonly Version Version1_10_0 = Version.Parse("1.10.0"); public static readonly Version Version1_10_1 = Version.Parse("1.10.1"); public static readonly Version Version1_10_2 = Version.Parse("1.10.2"); public static readonly Version Version1_11_0 = Version.Parse("1.11.0"); public static readonly Version Version1_12_0 = Version.Parse("1.12.0"); public static readonly Version Version1_13_0 = Version.Parse("1.13.0"); public static readonly Version Version1_14_0 = Version.Parse("1.14.0"); public static readonly Version Version1_15_0 = Version.Parse("1.15.0"); public static readonly Version Version1_16_0 = Version.Parse("1.16.0"); public static readonly Version Version1_2_0 = Version.Parse("1.2.0"); public static readonly Version Version1_3_0 = Version.Parse("1.3.0"); public static readonly Version Version1_4_0 = Version.Parse("1.4.0"); public static readonly Version Version1_5_0 = Version.Parse("1.5.0"); public static readonly Version Version1_6_0 = Version.Parse("1.6.0"); public static readonly Version Version1_7_0 = Version.Parse("1.7.0"); public static readonly Version Version1_8_0 = Version.Parse("1.8.0"); public static readonly Version Version1_9_0 = Version.Parse("1.9.0"); } }
using System; namespace Subsonic.Common { public static class SubsonicApiVersion { public static readonly Version Version1_0_0 = Version.Parse("1.0.0"); public static readonly Version Version1_1_0 = Version.Parse("1.1.0"); public static readonly Version Version1_1_1 = Version.Parse("1.1.1"); public static readonly Version Version1_2_0 = Version.Parse("1.2.0"); public static readonly Version Version1_3_0 = Version.Parse("1.3.0"); public static readonly Version Version1_4_0 = Version.Parse("1.4.0"); public static readonly Version Version1_5_0 = Version.Parse("1.5.0"); public static readonly Version Version1_6_0 = Version.Parse("1.6.0"); public static readonly Version Version1_7_0 = Version.Parse("1.7.0"); public static readonly Version Version1_8_0 = Version.Parse("1.8.0"); public static readonly Version Version1_9_0 = Version.Parse("1.9.0"); public static readonly Version Version1_10_0 = Version.Parse("1.10.0"); public static readonly Version Version1_10_1 = Version.Parse("1.10.1"); public static readonly Version Version1_10_2 = Version.Parse("1.10.2"); public static readonly Version Version1_11_0 = Version.Parse("1.11.0"); public static readonly Version Version1_12_0 = Version.Parse("1.12.0"); public static readonly Version Version1_13_0 = Version.Parse("1.13.0"); public static readonly Version Version1_14_0 = Version.Parse("1.14.0"); public static readonly Version Version1_15_0 = Version.Parse("1.15.0"); public static readonly Version Max = Version1_15_0; } }
mit
C#
d395dbcb001331db47bbe9d56d8b0c9038c6eaa1
set singleton as static class
wasteam/waslibs,pellea/waslibs,janabimustafa/waslibs,wasteam/waslibs,wasteam/waslibs,janabimustafa/waslibs,pellea/waslibs,pellea/waslibs,janabimustafa/waslibs
src/AppStudio.Uwp/Singleton.cs
src/AppStudio.Uwp/Singleton.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppStudio.Uwp { public static class Singleton<T> where T : new() { private static ConcurrentDictionary<Type, T> _instances = new ConcurrentDictionary<Type, T>(); public static T Instance { get { return _instances.GetOrAdd(typeof(T), (t) => new T()); } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AppStudio.Uwp { public sealed class Singleton<T> where T : new() { private static ConcurrentDictionary<Type, T> _instances = new ConcurrentDictionary<Type, T>(); private Singleton() { } public static T Instance { get { return _instances.GetOrAdd(typeof(T), (t) => new T()); } } } }
mit
C#
2d5b0a8c3a4d69b99cd16c2ff7e3ab2925632ad8
Sort and remove unused using in /src/Properties
fluentcassandra/fluentcassandra,fluentcassandra/fluentcassandra,fluentcassandra/fluentcassandra
src/Properties/AssemblyInfo.cs
src/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("FluentCassandra")] [assembly: AssemblyDescription("FluentCassandra is a .NET library for accessing Cassandra, which wraps the Thrift client library and provides a more fluent POCO interface for accessing and querying the objects in Cassandra.")] [assembly: AssemblyProduct("FluentCassandra")] [assembly: AssemblyCompany("Managed Fusion, LLC")] [assembly: AssemblyCopyright("Copyright © Nick Berardi, Managed Fusion, LLC 2011")] [assembly: AssemblyConfiguration("")] [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("f2fac76e-0d80-4099-a64f-2686d4d99b6b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.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("FluentCassandra")] [assembly: AssemblyDescription("FluentCassandra is a .NET library for accessing Cassandra, which wraps the Thrift client library and provides a more fluent POCO interface for accessing and querying the objects in Cassandra.")] [assembly: AssemblyProduct("FluentCassandra")] [assembly: AssemblyCompany("Managed Fusion, LLC")] [assembly: AssemblyCopyright("Copyright © Nick Berardi, Managed Fusion, LLC 2011")] [assembly: AssemblyConfiguration("")] [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("f2fac76e-0d80-4099-a64f-2686d4d99b6b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.0.0")] [assembly: AssemblyFileVersion("1.2.0.0")]
apache-2.0
C#
10b63c1246cd64968f1c3393a9162b9387d16414
Fix command line logic
rhargreaves/bbc-xfer,rhargreaves/bbc-xfer
Adf2Adl/Program.cs
Adf2Adl/Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adf2Adl { class Program { static void Main(string[] args) { if (args.Length != 2) { Console.WriteLine("Usage: Adf2Adl.exe <adf_file> <adl_file>"); return; } string adfPath = args[0]; string adlPath = args[1]; ConvertSingleToDoubleSideAdfsImage(adfPath, adlPath); } private static void ConvertSingleToDoubleSideAdfsImage(string adfPath, string adlPath) { const int BBC_ADFS_TRACK_SIZE = 4096; using (FileStream outStream = new FileStream(adlPath, FileMode.Create, FileAccess.Write)) using (FileStream inStream = new FileStream(adfPath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[BBC_ADFS_TRACK_SIZE]; int bytes; while ((bytes = inStream.Read(buffer, 0, BBC_ADFS_TRACK_SIZE)) > 0) { outStream.Write(buffer, 0, bytes); outStream.Write(new byte[BBC_ADFS_TRACK_SIZE], 0, BBC_ADFS_TRACK_SIZE); } } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Adf2Adl { class Program { static void Main(string[] args) { if (args.Length != 0) { Console.WriteLine("Usage: Adf2Adl.exe <adf_file> <adl_file>"); return; } string adfPath = args[0]; string adlPath = args[1]; ConvertSingleToDoubleSideAdfsImage(adfPath, adlPath); } private static void ConvertSingleToDoubleSideAdfsImage(string adfPath, string adlPath) { const int BBC_ADFS_TRACK_SIZE = 4096; using (FileStream outStream = new FileStream(adlPath, FileMode.Create, FileAccess.Write)) using (FileStream inStream = new FileStream(adfPath, FileMode.Open, FileAccess.Read)) { var buffer = new byte[BBC_ADFS_TRACK_SIZE]; int bytes; while ((bytes = inStream.Read(buffer, 0, BBC_ADFS_TRACK_SIZE)) > 0) { outStream.Write(buffer, 0, bytes); outStream.Write(new byte[BBC_ADFS_TRACK_SIZE], 0, BBC_ADFS_TRACK_SIZE); } } } } }
mit
C#
7d819e9af7cf3dbe8b61f7db67727ead4333b69a
Change Commands.Names to return IEnumerable<string>
tparviainen/oscilloscope
SCPI/Commands.cs
SCPI/Commands.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SCPI { public class Commands { private Dictionary<string, ICommand> commands = new Dictionary<string, ICommand>(); /// <summary> /// Creates a list of supported commands in the SCPI assembly /// </summary> /// <returns>The names of the supported commands</returns> public IEnumerable<string> Names() { return SupportedCommands().Select(t => t.Name); } /// <summary> /// Creates an instance of the requested command (if it does not exist) /// and returns it to the caller. /// </summary> /// <param name="command">Command name</param> /// <returns>Instance of the requested command</returns> public ICommand Get(string command) { // Command classes (inherited from ICommand) are always uppercase and thus // command must be uppercase as well to match supported commands. command = command.ToUpper(); if (!commands.TryGetValue(command, out ICommand cmd)) { // Lazy initialization of the command var typeInfo = SupportedCommands().Where(ti => ti.Name.Equals(command)).Single(); cmd = (ICommand)Activator.CreateInstance(typeInfo.AsType()); commands.Add(command, cmd); } return cmd; } private static IEnumerable<TypeInfo> SupportedCommands() { var assembly = typeof(ICommand).GetTypeInfo().Assembly; // Supported commands are the ones that implement ICommand interface var commands = assembly.DefinedTypes.Where(ti => ti.ImplementedInterfaces.Contains(typeof(ICommand))); return commands; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; namespace SCPI { public class Commands { private Dictionary<string, ICommand> commands = new Dictionary<string, ICommand>(); /// <summary> /// Creates a list of supported commands in the SCPI assembly /// </summary> /// <returns>The names of the supported commands</returns> public ICollection<string> Names() { return SupportedCommands().Select(t => t.Name).ToList(); } /// <summary> /// Creates an instance of the requested command (if it does not exist) /// and returns it to the caller. /// </summary> /// <param name="command">Command name</param> /// <returns>Instance of the requested command</returns> public ICommand Get(string command) { // Command classes (inherited from ICommand) are always uppercase and thus // command must be uppercase as well to match supported commands. command = command.ToUpper(); if (!commands.TryGetValue(command, out ICommand cmd)) { // Lazy initialization of the command var typeInfo = SupportedCommands().Where(ti => ti.Name.Equals(command)).Single(); cmd = (ICommand)Activator.CreateInstance(typeInfo.AsType()); commands.Add(command, cmd); } return cmd; } private static IEnumerable<TypeInfo> SupportedCommands() { var assembly = typeof(ICommand).GetTypeInfo().Assembly; // Supported commands are the ones that implement ICommand interface var commands = assembly.DefinedTypes.Where(ti => ti.ImplementedInterfaces.Contains(typeof(ICommand))); return commands; } } }
mit
C#
5727ff203cbe52d5199f24d8aec4c72f971b331e
Remove serializable attribute from RaygunMessageReceived
OpenMagic/OpenMagic.ErrorTracker.Core,OpenMagic/OpenMagic.ErrorTracker.Core
source/OpenMagic.ErrorTracker.Core/Events/RaygunMessageReceived.cs
source/OpenMagic.ErrorTracker.Core/Events/RaygunMessageReceived.cs
using System; using Mindscape.Raygun4Net.Messages; namespace OpenMagic.ErrorTracker.Core.Events { public class RaygunMessageReceived : IEvent { public RaygunMessageReceived(string apiKey, RaygunMessage raygunMessage) { EventId = Guid.NewGuid(); ApiKey = apiKey; Message = raygunMessage; } public Guid EventId { get; } public string ApiKey { get; } public RaygunMessage Message { get; } } }
using System; using Mindscape.Raygun4Net.Messages; namespace OpenMagic.ErrorTracker.Core.Events { [Serializable] public class RaygunMessageReceived : IEvent { public RaygunMessageReceived(string apiKey, RaygunMessage raygunMessage) { EventId = Guid.NewGuid(); ApiKey = apiKey; Message = raygunMessage; } public Guid EventId { get; } public string ApiKey { get; } public RaygunMessage Message { get; } } }
mit
C#
32685798c871749809a454029f297e7aeef6388b
Fix unnecessary suppression missed in another PR
mjedrzejek/nunit,nunit/nunit,mjedrzejek/nunit,nunit/nunit
src/NUnitFramework/framework/Exceptions/MultipleAssertException.cs
src/NUnitFramework/framework/Exceptions/MultipleAssertException.cs
// *********************************************************************** // Copyright (c) 2016 Charlie Poole, Rob Prouse // // 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. // *********************************************************************** #nullable enable using System; namespace NUnit.Framework { using Interfaces; /// <summary> /// Thrown when an assertion failed. /// </summary> [Serializable] public class MultipleAssertException : ResultStateException { /// <summary> /// Construct based on the TestResult so far. This is the constructor /// used normally, when exiting the multiple assert block with failures. /// Not used internally but provided to facilitate debugging. /// </summary> /// <param name="testResult"> /// The current result, up to this point. The result is not used /// internally by NUnit but is provided to facilitate debugging. /// </param> public MultipleAssertException(ITestResult testResult) : base(testResult?.Message) { Guard.ArgumentNotNull(testResult, "testResult"); TestResult = testResult; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. /// <summary> /// Serialization Constructor /// </summary> protected MultipleAssertException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info,context) { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. /// <summary> /// Gets the <see cref="ResultState"/> provided by this exception. /// </summary> public override ResultState ResultState { get { return ResultState.Failure; } } /// <summary> /// Gets the <see cref="ITestResult"/> of this test at the point the exception was thrown, /// </summary> public ITestResult TestResult { get; } } }
// *********************************************************************** // Copyright (c) 2016 Charlie Poole, Rob Prouse // // 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. // *********************************************************************** #nullable enable using System; namespace NUnit.Framework { using Interfaces; /// <summary> /// Thrown when an assertion failed. /// </summary> [Serializable] public class MultipleAssertException : ResultStateException { /// <summary> /// Construct based on the TestResult so far. This is the constructor /// used normally, when exiting the multiple assert block with failures. /// Not used internally but provided to facilitate debugging. /// </summary> /// <param name="testResult"> /// The current result, up to this point. The result is not used /// internally by NUnit but is provided to facilitate debugging. /// </param> public MultipleAssertException(ITestResult testResult) : base(testResult?.Message) { Guard.ArgumentNotNull(testResult!, "testResult"); TestResult = testResult; } #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. /// <summary> /// Serialization Constructor /// </summary> protected MultipleAssertException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info,context) { } #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. /// <summary> /// Gets the <see cref="ResultState"/> provided by this exception. /// </summary> public override ResultState ResultState { get { return ResultState.Failure; } } /// <summary> /// Gets the <see cref="ITestResult"/> of this test at the point the exception was thrown, /// </summary> public ITestResult TestResult { get; } } }
mit
C#
311bcd180673cfb5eff7262ec4abc6821f6b358c
format - workaround roslyn NewLine bug
hach-que/omnisharp-roslyn,khellang/omnisharp-roslyn,nabychan/omnisharp-roslyn,haled/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,RichiCoder1/omnisharp-roslyn,haled/omnisharp-roslyn,filipw/omnisharp-roslyn,hitesh97/omnisharp-roslyn,ianbattersby/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,fishg/omnisharp-roslyn,khellang/omnisharp-roslyn,hitesh97/omnisharp-roslyn,xdegtyarev/omnisharp-roslyn,jtbm37/omnisharp-roslyn,sriramgd/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,sreal/omnisharp-roslyn,hal-ler/omnisharp-roslyn,david-driscoll/omnisharp-roslyn,hal-ler/omnisharp-roslyn,sreal/omnisharp-roslyn,DustinCampbell/omnisharp-roslyn,ChrisHel/omnisharp-roslyn,OmniSharp/omnisharp-roslyn,hach-que/omnisharp-roslyn,filipw/omnisharp-roslyn,fishg/omnisharp-roslyn,nabychan/omnisharp-roslyn,sriramgd/omnisharp-roslyn,jtbm37/omnisharp-roslyn
src/OmniSharp/Api/Formatting/OmnisharpController.FormatDocument.cs
src/OmniSharp/Api/Formatting/OmnisharpController.FormatDocument.cs
using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using OmniSharp.Models; namespace OmniSharp { public partial class OmnisharpController { [HttpPost("codeformat")] public async Task<IActionResult> CodeFormat([FromBody]Request request) { _workspace.EnsureBufferUpdated(request); var options = _workspace.Options .WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, _options.FormattingOptions.NewLine) .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, _options.FormattingOptions.UseTabs) .WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, _options.FormattingOptions.TabSize); var response = new CodeFormatResponse(); var documentId = _workspace.GetDocumentId(request.FileName); if (documentId != null) { var document = _workspace.CurrentSolution.GetDocument(documentId); document = await Formatter.FormatAsync(document, options); response.Buffer = (await document.GetTextAsync()).ToString(); // workaround: https://roslyn.codeplex.com/workitem/484 if(_options.FormattingOptions.NewLine == "\n") { response.Buffer = response.Buffer.Replace("\r\n", "\n"); } } else { return new HttpNotFoundResult(); } return new ObjectResult(response); } } }
using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using OmniSharp.Models; namespace OmniSharp { public partial class OmnisharpController { [HttpPost("codeformat")] public async Task<IActionResult> CodeFormat([FromBody]Request request) { _workspace.EnsureBufferUpdated(request); var options = _workspace.Options .WithChangedOption(FormattingOptions.NewLine, LanguageNames.CSharp, _options.FormattingOptions.NewLine) .WithChangedOption(FormattingOptions.UseTabs, LanguageNames.CSharp, _options.FormattingOptions.UseTabs) .WithChangedOption(FormattingOptions.TabSize, LanguageNames.CSharp, _options.FormattingOptions.TabSize); var response = new CodeFormatResponse(); var documentId = _workspace.GetDocumentId(request.FileName); if (documentId != null) { var document = _workspace.CurrentSolution.GetDocument(documentId); document = await Formatter.FormatAsync(document, options); response.Buffer = (await document.GetTextAsync()).ToString(); } else { return new HttpNotFoundResult(); } return new ObjectResult(response); } } }
mit
C#
3e46e68821157961e3b49359068447538bead6b3
Add missing registration for authentication handler (#32152)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Security/samples/CustomAuthorizationFailureResponse/Startup.cs
src/Security/samples/CustomAuthorizationFailureResponse/Startup.cs
using CustomAuthorizationFailureResponse.Authentication; using CustomAuthorizationFailureResponse.Authorization; using CustomAuthorizationFailureResponse.Authorization.Handlers; using CustomAuthorizationFailureResponse.Authorization.Requirements; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CustomAuthorizationFailureResponse { public class Startup { public const string CustomForbiddenMessage = "Some info about the error"; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services .AddAuthentication(SampleAuthenticationSchemes.CustomScheme) .AddScheme<AuthenticationSchemeOptions, SampleAuthenticationHandler>(SampleAuthenticationSchemes.CustomScheme, o => { }); services.AddAuthorization(options => { options.AddPolicy(SamplePolicyNames.CustomPolicy, policy => policy.AddRequirements(new SampleRequirement())); options.AddPolicy(SamplePolicyNames.CustomPolicyWithCustomForbiddenMessage, policy => policy.AddRequirements(new SampleWithCustomMessageRequirement())); }); services.AddTransient<IAuthorizationHandler, SampleRequirementHandler>(); services.AddTransient<IAuthorizationHandler, SampleWithCustomMessageRequirementHandler>(); services.AddTransient<IAuthorizationMiddlewareResultHandler, SampleAuthorizationMiddlewareResultHandler>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }
using CustomAuthorizationFailureResponse.Authentication; using CustomAuthorizationFailureResponse.Authorization; using CustomAuthorizationFailureResponse.Authorization.Handlers; using CustomAuthorizationFailureResponse.Authorization.Requirements; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CustomAuthorizationFailureResponse { public class Startup { public const string CustomForbiddenMessage = "Some info about the error"; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services .AddAuthentication(SampleAuthenticationSchemes.CustomScheme) .AddScheme<AuthenticationSchemeOptions, SampleAuthenticationHandler>(SampleAuthenticationSchemes.CustomScheme, o => { }); services.AddAuthorization(options => options.AddPolicy(SamplePolicyNames.CustomPolicy, policy => policy.AddRequirements(new SampleRequirement()))); services.AddAuthorization(options => options.AddPolicy(SamplePolicyNames.CustomPolicyWithCustomForbiddenMessage, policy => policy.AddRequirements(new SampleWithCustomMessageRequirement()))); services.AddTransient<IAuthorizationHandler, SampleRequirementHandler>(); services.AddTransient<IAuthorizationMiddlewareResultHandler, SampleAuthorizationMiddlewareResultHandler>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapDefaultControllerRoute(); }); } } }
apache-2.0
C#
bebd093f709be5ff2e413a76f94ebad216e2a4cd
Use the RemoveVersion method to clean up the unnecessary first version
hermanussen/Sitecore.FakeDb,sergeyshushlyapin/Sitecore.FakeDb,pveller/Sitecore.FakeDb
src/Sitecore.FakeDb/Data/Engines/DataCommands/CreateItemCommand.cs
src/Sitecore.FakeDb/Data/Engines/DataCommands/CreateItemCommand.cs
namespace Sitecore.FakeDb.Data.Engines.DataCommands { using System; using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Globalization; public class CreateItemCommand : Sitecore.Data.Engines.DataCommands.CreateItemCommand { private readonly DataStorage dataStorage; public CreateItemCommand(DataStorage dataStorage) { Assert.ArgumentNotNull(dataStorage, "dataStorage"); this.dataStorage = dataStorage; } public DataStorage DataStorage { get { return this.dataStorage; } } protected override Sitecore.Data.Engines.DataCommands.CreateItemCommand CreateInstance() { throw new NotSupportedException(); } protected override Item DoExecute() { var item = new DbItem(this.ItemName, this.ItemId, this.TemplateId) { ParentID = this.Destination.ID }; this.dataStorage.AddFakeItem(item); item.RemoveVersion(Language.Current.Name); return this.dataStorage.GetSitecoreItem(this.ItemId); } } }
namespace Sitecore.FakeDb.Data.Engines.DataCommands { using System; using Sitecore.Data.Items; using Sitecore.Diagnostics; public class CreateItemCommand : Sitecore.Data.Engines.DataCommands.CreateItemCommand { private readonly DataStorage dataStorage; public CreateItemCommand(DataStorage dataStorage) { Assert.ArgumentNotNull(dataStorage, "dataStorage"); this.dataStorage = dataStorage; } public DataStorage DataStorage { get { return this.dataStorage; } } protected override Sitecore.Data.Engines.DataCommands.CreateItemCommand CreateInstance() { throw new NotSupportedException(); } protected override Item DoExecute() { var item = new DbItem(this.ItemName, this.ItemId, this.TemplateId) { ParentID = this.Destination.ID }; this.dataStorage.AddFakeItem(item); item.VersionsCount.Clear(); return this.dataStorage.GetSitecoreItem(this.ItemId); } } }
mit
C#
89f47eaba711d7e2831a15da275d074a66553d24
update version number
poxet/tharga-console
Build/AssemblyVersionInfo.cs
Build/AssemblyVersionInfo.cs
using System.Reflection; [assembly: AssemblyVersion("1.6.0.0")] [assembly: AssemblyFileVersion("1.6.0.0")]
using System.Reflection; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
1699d3f73b818eb04926bd2fbc79b490da0c7752
use gitversion nugetversion
rafaelalmeidatk/MonoGame.Extended,LithiumToast/MonoGame.Extended,rafaelalmeidatk/MonoGame.Extended
build.cake
build.cake
#tool nuget:?package=vswhere #tool nuget:?package=NUnit.Runners&version=2.6.4 #tool nuget:?package=GitVersion.CommandLine var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var solution = "./Source/MonoGame.Extended.sln"; var vsLatest = VSWhereLatest(); var msBuildPath = vsLatest?.CombineWithFilePath("./MSBuild/15.0/Bin/amd64/MSBuild.exe"); Task("Restore") .Does(() => { DotNetCoreRestore(solution); }); Task("Build") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(solution, new DotNetCoreBuildSettings { //ArgumentCustomization = args => args.Append("/unsafe"), Configuration = configuration }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var testRuns = 0; var failedRuns = 0; foreach (var project in GetFiles($"./Source/Tests/**/*.Tests.csproj")) { try { // var filename = project.GetFilename().ChangeExtension("dll"); // var testDll = project.GetDirectory().CombineWithFilePath($"bin/{configuration}/netcoreapp2.0/{filename}"); Information("Test Run {0} - {1}", testRuns++, project); DotNetCoreTest(project.FullPath); } catch { failedRuns++; } } if(failedRuns > 0) throw new Exception($"{failedRuns} of {testRuns} test runs failed."); }); Task("Pack") .IsDependentOn("Test") .Does(() => { var artifactsDirectory = "./artifacts"; var gitVersion = GitVersion(); CreateDirectory(artifactsDirectory); CleanDirectory(artifactsDirectory); foreach (var project in GetFiles($"./Source/MonoGame.Extended*/*.csproj")) { DotNetCorePack(project.FullPath, new DotNetCorePackSettings { IncludeSymbols = true, OutputDirectory = artifactsDirectory, ArgumentCustomization = args => args.Append($"/p:VersionPrefix={gitVersion.NuGetVersion} /p:VersionSuffix=alpha{gitVersion.BuildMetaDataPadded}") }); } }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
#tool nuget:?package=vswhere #tool nuget:?package=NUnit.Runners&version=2.6.4 #tool nuget:?package=GitVersion.CommandLine var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var solution = "./Source/MonoGame.Extended.sln"; var vsLatest = VSWhereLatest(); var msBuildPath = vsLatest?.CombineWithFilePath("./MSBuild/15.0/Bin/amd64/MSBuild.exe"); Task("Restore") .Does(() => { DotNetCoreRestore(solution); }); Task("Build") .IsDependentOn("Restore") .Does(() => { DotNetCoreBuild(solution, new DotNetCoreBuildSettings { //ArgumentCustomization = args => args.Append("/unsafe"), Configuration = configuration }); }); Task("Test") .IsDependentOn("Build") .Does(() => { var testRuns = 0; var failedRuns = 0; foreach (var project in GetFiles($"./Source/Tests/**/*.Tests.csproj")) { try { // var filename = project.GetFilename().ChangeExtension("dll"); // var testDll = project.GetDirectory().CombineWithFilePath($"bin/{configuration}/netcoreapp2.0/{filename}"); Information("Test Run {0} - {1}", testRuns++, project); DotNetCoreTest(project.FullPath); } catch { failedRuns++; } } if(failedRuns > 0) throw new Exception($"{failedRuns} of {testRuns} test runs failed."); }); Task("Pack") .IsDependentOn("Test") .Does(() => { var artifactsDirectory = "./artifacts"; var gitVersion = GitVersion(); CreateDirectory(artifactsDirectory); CleanDirectory(artifactsDirectory); foreach (var project in GetFiles($"./Source/MonoGame.Extended*/*.csproj")) { DotNetCorePack(project.FullPath, new DotNetCorePackSettings { IncludeSymbols = true, OutputDirectory = artifactsDirectory, ArgumentCustomization = args => args.Append($"/p:VersionPrefix={gitVersion.MajorMinorPatch} /p:VersionSuffix=alpha{gitVersion.BuildMetaDataPadded}") }); } }); Task("Default") .IsDependentOn("Pack"); RunTarget(target);
mit
C#
cf4d4fa9bd3987cbd7a4dd3fb2767163399c3270
fix cake
aritchie/userdialogs
build.cake
build.cake
#addin "Cake.Xamarin" #addin "Cake.FileHelpers" #tool nunit.consolerunner #tool gitlink var target = Argument("target", Argument("t", "package")); Setup(x => { DeleteFiles("./*.nupkg"); DeleteFiles("./output/*.*"); if (!DirectoryExists("./output")) CreateDirectory("./output"); }); Task("build") .Does(() => { NuGetRestore("./src/lib.sln"); DotNetBuild("./src/lib.sln", x => x .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithProperty("TreatWarningsAsErrors", "false") ); }); Task("package") .IsDependentOn("build") .Does(() => { GitLink("./", new GitLinkSettings { RepositoryUrl = "https://github.com/aritchie/userdialogs", Branch = "master" }); NuGetPack(new FilePath("./nuspec/Acr.UserDialogs.nuspec"), new NuGetPackSettings()); MoveFiles("./*.nupkg", "./output"); }); Task("publish") .IsDependentOn("package") .Does(() => { NuGetPush("./output/*.nupkg", new NuGetPushSettings { Source = "http://www.nuget.org/api/v2/package", Verbosity = NuGetVerbosity.Detailed }); CopyFiles("./ouput/*.nupkg", "c:\\users\\allan.ritchie\\dropbox\\nuget"); }); RunTarget(target);
#addin "Cake.Xamarin" #addin "Cake.FileHelpers" #tool nunit.consolerunner #tool gitlink var target = Argument("target", Argument("t", "package")); Setup(x => { DeleteFiles("./*.nupkg"); DeleteFiles("./output/*.*"); if (!DirectoryExists("./output")) CreateDirectory("./output"); }); Task("build") .Does(() => { NuGetRestore("./src/lib.sln"); DotNetBuild("./src/lib.sln", x => x .SetConfiguration("Release") .SetVerbosity(Verbosity.Minimal) .WithTarget("build") .WithProperty("TreatWarningsAsErrors", "false") ); }); Task("package") .IsDependentOn("build") .Does(() => { GitLink("./", new GitLinkSettings { RepositoryUrl = "https://github.com/aritchie/userdialogs", Branch = "master" }); NuGetPack(new FilePath("./nuspec/Acr.UserDialogs.nuspec"), new NuGetPackSettings()); MoveFiles("./*.nupkg", "./output"); }); Task("publish") .IsDependentOn("package") .Does(() => { NuGetPush("./output/*.nupkg", new NuGetPushSettings { Source = "http://www.nuget.org/api/v2/package", Verbosity = NuGetVerbosity.Detailed }); CopyFiles("./ouput/*.nupkg", "c:\\users\\allan.ritchie\\dropbox\\nuget"); }); RunTarget(target);
mit
C#
bcbc22bd9239509fec212451b28fe75f59d00f85
Update StackPanel.cs
Clancey/iOSHelpers
iOSHelpers/StackPanel.cs
iOSHelpers/StackPanel.cs
using System; using UIKit; using CoreGraphics; using System.Collections; using CoreGraphics; namespace iOSHelpers { public class StackPanel : UIView , IEnumerable { int columns = 1; public int Columns { get{ return columns;} set { if (columns == value) return; columns = value; this.SetNeedsLayout(); } } public StackPanel () { init (); } public StackPanel (CGRect rect) : base(rect) { init (); } void init () { this.BackgroundColor = UIColor.Clear; } nfloat padding = 10; public nfloat Padding { get{ return padding;} set { if (padding == value) return; padding = value; LayoutSubviews (); } } public nfloat HeightNeeded { get; private set; } public bool AutoSizeChildren { get; set; } public override void LayoutSubviews () { base.LayoutSubviews (); var h = padding + this.SafeAreaInsets.Top; var width = ((this.Bounds.Width - padding) / columns) - padding; nfloat columnH = 0; nfloat maxBottom = 0; for (int i = 0; i < Subviews.Length; i++) { var col = (i % columns); var view = Subviews[i]; if (AutoSizeChildren) view.SizeToFit (); var frame = view.Frame; frame.X = padding + ((width + padding) * col); frame.Y = h; frame.Width = width; view.Frame = frame; maxBottom = NMath.Max (frame.Bottom, maxBottom); columnH = NMath.Max(frame.Bottom + padding,columnH); if(col + 1 == columns) h = columnH; } HeightNeeded = maxBottom + padding; } } }
using System; using UIKit; using CoreGraphics; using System.Collections; using CoreGraphics; namespace iOSHelpers { public class StackPanel : UIView , IEnumerable { int columns = 1; public int Columns { get{ return columns;} set { if (columns == value) return; columns = value; this.SetNeedsLayout(); } } public StackPanel () { init (); } public StackPanel (CGRect rect) : base(rect) { init (); } void init () { this.BackgroundColor = UIColor.Clear; } nfloat padding = 10; public nfloat Padding { get{ return padding;} set { if (padding == value) return; padding = value; LayoutSubviews (); } } public override void LayoutSubviews () { base.LayoutSubviews (); var h = padding; var width = ((this.Bounds.Width - padding) / columns) - padding; nfloat columnH = 0; for (int i = 0; i < Subviews.Length; i++) { var col = (i % columns); var view = Subviews[i]; var frame = view.Frame; frame.X = padding + ((width + padding) * col); frame.Y = h; frame.Width = width; view.Frame = frame; columnH = NMath.Max(frame.Bottom + padding,columnH); if(col + 1 == columns) h = columnH; } } } }
apache-2.0
C#
ec1afb5f5110e7cce0534f470e9baaa2d7cef498
Normalize whitespace in TextExtractor.
thomas11/AzureSearchCrawler
AzureSearchCrawler/TextExtractor.cs
AzureSearchCrawler/TextExtractor.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using HtmlAgilityPack; namespace AzureSearchCrawler { /// <summary> /// Extracts text content from a web page. The default implementation is very simple: it removes all script, style, /// svg, and path tags, and then returns the InnerText of the page body. /// <para/>You can implement your own custom text extraction by overriding the ExtractText method. The protected /// helper methods in this class might be useful. /// </summary> public class TextExtractor { private readonly Regex newlines = new Regex(@"(\r\n|\n)+"); private readonly Regex spaces = new Regex(@"[ \t]+"); public virtual string ExtractText(HtmlDocument doc) { if (doc == null || doc.DocumentNode == null) { return null; } RemoveNodesOfType(doc, "script", "style", "svg", "path"); string content = ExtractTextFromFirstMatchingElement(doc, "//body"); return NormalizeWhitespace(content); } protected string NormalizeWhitespace(string content) { if (content == null) { return null; } content = newlines.Replace(content, "\n"); return spaces.Replace(content, " "); } protected void RemoveNodesOfType(HtmlDocument doc, params string[] types) { string xpath = String.Join(" | ", types.Select(t => "//" + t)); RemoveNodes(doc, xpath); } protected void RemoveNodes(HtmlDocument doc, string xpath) { var nodes = SafeSelectNodes(doc, xpath).ToList(); Console.WriteLine("Removing {0} nodes matching {1}.", nodes.Count, xpath); foreach (var node in nodes) { node.Remove(); } } /// <summary> /// Returns InnerText of the first element matching the xpath expression, or null if no elements match. /// </summary> protected string ExtractTextFromFirstMatchingElement(HtmlDocument doc, string xpath) { return SafeSelectNodes(doc, xpath).FirstOrDefault()?.InnerText; } /// <summary> /// Null-safe DocumentNode.SelectNodes /// </summary> protected IEnumerable<HtmlNode> SafeSelectNodes(HtmlDocument doc, string xpath) { return doc.DocumentNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>(); } } }
using System; using System.Collections.Generic; using System.Linq; using HtmlAgilityPack; namespace AzureSearchCrawler { /// <summary> /// Extracts text content from a web page. The default implementation is very simple: it removes all script, style, /// svg, and path tags, and then returns the InnerText of the page body. /// <para/>You can implement your own custom text extraction by overriding the ExtractText method. The protected /// helper methods in this class might be useful. /// </summary> public class TextExtractor { public virtual string ExtractText(HtmlDocument doc) { if (doc == null || doc.DocumentNode == null) { return null; } RemoveNodesOfType(doc, "script", "style", "svg", "path"); return ExtractTextFromFirstMatchingElement(doc, "//body"); } protected void RemoveNodesOfType(HtmlDocument doc, params string[] types) { string xpath = String.Join(" | ", types.Select(t => "//" + t)); RemoveNodes(doc, xpath); } protected void RemoveNodes(HtmlDocument doc, string xpath) { var nodes = SafeSelectNodes(doc, xpath).ToList(); Console.WriteLine("Removing {0} nodes matching {1}.", nodes.Count, xpath); foreach (var node in nodes) { node.Remove(); } } /// <summary> /// Returns InnerText of the first element matching the xpath expression, or null if no elements match. /// </summary> protected string ExtractTextFromFirstMatchingElement(HtmlDocument doc, string xpath) { return SafeSelectNodes(doc, xpath).FirstOrDefault()?.InnerText; } /// <summary> /// Null-safe DocumentNode.SelectNodes /// </summary> protected IEnumerable<HtmlNode> SafeSelectNodes(HtmlDocument doc, string xpath) { return doc.DocumentNode.SelectNodes(xpath) ?? Enumerable.Empty<HtmlNode>(); } } }
mit
C#
9eda5930544cdb745aad897f945a1e515d8da3bd
Add save window size and position before exiting
fredatgithub/WinFormTemplate
WinFormTemplate/FormMain.cs
WinFormTemplate/FormMain.cs
using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using WinFormTemplate.Properties; namespace WinFormTemplate { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void QuitToolStripMenuItem_Click(object sender, EventArgs e) { SaveWindowValue(); Application.Exit(); } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBoxApplication aboutBoxApplication = new AboutBoxApplication(); aboutBoxApplication.ShowDialog(); } private void DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); Text += string.Format(" V{0}.{1}.{2}.{3}", fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart); } private void FormMain_Load(object sender, EventArgs e) { DisplayTitle(); GetWindowValue(); } private void GetWindowValue() { Width = Settings.Default.WindowWidth; Height = Settings.Default.WindowHeight; Top = Settings.Default.WindowTop < 0 ? 0 : Settings.Default.WindowTop; Left = Settings.Default.WindowLeft < 0 ? 0 : Settings.Default.WindowLeft; } private void SaveWindowValue() { Settings.Default.WindowHeight = Height; Settings.Default.WindowWidth = Width; Settings.Default.WindowLeft = Left; Settings.Default.WindowTop = Top; Settings.Default.Save(); } private void FormMainFormClosing(object sender, FormClosingEventArgs e) { SaveWindowValue(); } } }
using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using WinFormTemplate.Properties; namespace WinFormTemplate { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void QuitToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void AboutToolStripMenuItem_Click(object sender, EventArgs e) { AboutBoxApplication aboutBoxApplication = new AboutBoxApplication(); aboutBoxApplication.ShowDialog(); } private void DisplayTitle() { Assembly assembly = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(assembly.Location); Text += string.Format(" V{0}.{1}.{2}.{3}", fvi.FileMajorPart, fvi.FileMinorPart, fvi.FileBuildPart, fvi.FilePrivatePart); } private void FormMain_Load(object sender, EventArgs e) { DisplayTitle(); GetWindowValue(); } private void GetWindowValue() { Width = Settings.Default.WindowWidth; Height = Settings.Default.WindowHeight; Top = Settings.Default.WindowTop < 0 ? 0 : Settings.Default.WindowTop; Left = Settings.Default.WindowLeft < 0 ? 0 : Settings.Default.WindowLeft; } private void SaveWindowValue() { Settings.Default.WindowHeight = Height; Settings.Default.WindowWidth = Width; Settings.Default.WindowLeft = Left; Settings.Default.WindowTop = Top; Settings.Default.Save(); } private void FormMainFormClosing(object sender, FormClosingEventArgs e) { SaveWindowValue(); } } }
mit
C#
131282f513305e5aa6d6301bdb4d48e6e9473087
Update Config.cs
fqlx/XboxKeyboardMouse
XboxKeyboardMouse/Config.cs
XboxKeyboardMouse/Config.cs
using System.Windows.Input; namespace XboxMouse_Keyboard { class Config { private class Input { private class LeftStick { private Key up; private Key down; private Key right; private Key left; } private class Buttons { private Key a; private Key b; private Key x; private Key y; } private class Bumpers { private Key right; private Key left; } private class Triggers { private uint right; private uint left; } private class StickClick { private Key right; private Key left; } private class Dpad { private Key up; private Key down; private Key right; private Key left; } private Key menu; //aka Start private Key view; //aka Back or Select or Nav private Key home; //aka Guide } private class App { private uint framePerTicks; //private uint innerDeadzone //private uint outerDeadzone; } public class LoadConfig() { } //todo getters and setters } }
using System.Windows.Input; namespace XboxMouse_Keyboard { class Config { private class Input { private class Buttons { private Key a; private Key b; private Key x; private Key y; } private class Dpad { private Key up; private Key down; private Key right; private Key left; } private class Bumpers { private Key right; private Key left; } private class Sticks { private Key right; private Key left; } private Key menu; //aka Start private Key view; //aka Back or Select or Nav private Key home; //aka Guide } private class App { private uint frame_per_ticks; } public class LoadConfig() { } //todo getters and setters } }
apache-2.0
C#
cce8a82ca3639ae4df3630c88fd4348aac3ef142
Update cake script
bcanseco/common-bot-library,bcanseco/common-bot-library
build.cake
build.cake
#addin nuget:?package=NuGet.Core&version=2.14.0 #addin "Cake.ExtendedNuGet" var version = Argument<string>("r"); Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new[] { "https://www.nuget.org/api/v2" } }; DotNetCoreRestore(settings); }); Task("Build") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "./artifacts/", EnvironmentVariables = new Dictionary<string, string> { { "Version", version } }, }; DotNetCorePack("./src/CommonBotLibrary/", settings); DotNetCoreBuild("./tests/CommonBotLibrary.Tests/"); }); Task("Deploy") .Does(() => { var settings = new NuGetPushSettings { Source = "https://www.nuget.org/api/v2/package", ApiKey = EnvironmentVariable("NUGET_KEY") }; var packages = GetFiles("./artifacts/*.nupkg"); NuGetPush(packages, settings); }); Task("Clean") .Does(() => { CleanDirectory("./artifacts"); }); Task("Default") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Deploy") .IsDependentOn("Clean") .Does(() => { Information($"Successfully published {version} to NuGet."); }); RunTarget("Default");
#addin nuget:?package=NuGet.Core&version=2.14.0 #addin "Cake.ExtendedNuGet" Task("Restore") .Does(() => { var settings = new DotNetCoreRestoreSettings { Sources = new[] { "https://www.nuget.org/api/v2" } }; DotNetCoreRestore(settings); }); Task("Build") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = "Release", OutputDirectory = "./artifacts/", EnvironmentVariables = new Dictionary<string, string> { { "ReleaseNotes", "Testing..." }, }, }; DotNetCorePack("./src/CommonBotLibrary/", settings); DotNetCoreBuild("./tests/CommonBotLibrary.Tests/"); }); Task("Deploy") .WithCriteria(Branch == "dev") .Does(() => { var settings = new NuGetPushSettings { Source = "https://www.nuget.org/api/v2/package", ApiKey = EnvironmentVariable("NUGET_KEY") }; var packages = GetFiles("./artifacts/*.nupkg"); NuGetPush(packages, settings); }); Task("Default") .IsDependentOn("Restore") .IsDependentOn("Build") .IsDependentOn("Deploy") .Does(() => { Information("Successfully pushed to NuGet."); }); RunTarget("Default");
mit
C#
2ef808c5f15a1434c7522714f06424970acdcde4
Add docker push
syedhassaanahmed/log-storage-service,syedhassaanahmed/log-storage-service,syedhassaanahmed/log-storage-service
build.cake
build.cake
#addin Cake.Coveralls #addin Cake.Docker #tool "nuget:?package=OpenCover" #tool "nuget:?package=ReportGenerator" #tool "nuget:?package=coveralls.io" var testProj = "./ValidationPipeline.LogStorage.Tests/ValidationPipeline.LogStorage.Tests.csproj"; var testSettings = new DotNetCoreTestSettings { Framework = "netcoreapp1.1", Configuration = "Release" }; var coverageDir = "./coverageOutput/"; var coverageOutput = coverageDir + "coverage.xml"; var dockerRegistryServer = "logstorageservice.azurecr.io"; Task("StartStorageEmulator") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .Does(() => { StartProcess(@"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe", new ProcessSettings{ Arguments = "start" }); }); Task("Clean") .Does(() => { if (DirectoryExists(coverageDir)) DeleteDirectory(coverageDir, recursive:true); CreateDirectory(coverageDir); }); Task("Restore") .Does(() => DotNetCoreRestore("ValidationPipeline.LogStorage.sln")); Task("TestWithCoverage") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .IsDependentOn("StartStorageEmulator") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Action<ICakeContext> testAction = tool => tool.DotNetCoreTest(testProj, testSettings); OpenCover(testAction, coverageOutput, new OpenCoverSettings { OldStyle = true, // Needed for .NET Core Register = "user", ArgumentCustomization = args => args.Append("-hideskipped:all") }.WithFilter("+[ValidationPipeline.LogStorage*]*")); ReportGenerator(coverageOutput, coverageDir); }); Task("CoverallsUpload") .WithCriteria(() => FileExists(coverageOutput)) .WithCriteria(() => BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { CoverallsIo(coverageOutput, new CoverallsIoSettings { RepoToken = EnvironmentVariable("coveralls_repo_token") }); }); Task("Build") .WithCriteria(() => !BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { DockerComposeUp(new DockerComposeUpSettings { Files = new [] { "docker-compose.ci.build.yml" } }); DockerComposeBuild(); }); Task("DockerPush") .WithCriteria(() => BuildSystem.IsRunningOnTravisCI) .IsDependentOn("Build") .Does(() => { DockerLogin(new DockerLoginSettings { Username = EnvironmentVariable("DOCKER_USERNAME"), Password = EnvironmentVariable("DOCKER_PASSWORD") }, dockerRegistryServer); var imageName = dockerRegistryServer + "/dev"; DockerTag("validationpipeline.logstorage", imageName); DockerPush(imageName); }); Task("Default") .IsDependentOn("DockerPush") .IsDependentOn("CoverallsUpload"); RunTarget("Default");
#addin Cake.Coveralls #addin Cake.Docker #tool "nuget:?package=OpenCover" #tool "nuget:?package=ReportGenerator" #tool "nuget:?package=coveralls.io" var testProj = "./ValidationPipeline.LogStorage.Tests/ValidationPipeline.LogStorage.Tests.csproj"; var testSettings = new DotNetCoreTestSettings { Framework = "netcoreapp1.1", Configuration = "Release" }; var coverageDir = "./coverageOutput/"; var coverageOutput = coverageDir + "coverage.xml"; Task("StartStorageEmulator") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .Does(() => { StartProcess(@"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe", new ProcessSettings{ Arguments = "start" }); }); Task("Clean") .Does(() => { if (DirectoryExists(coverageDir)) DeleteDirectory(coverageDir, recursive:true); CreateDirectory(coverageDir); }); Task("Restore") .Does(() => DotNetCoreRestore("ValidationPipeline.LogStorage.sln")); Task("TestWithCoverage") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .IsDependentOn("StartStorageEmulator") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Action<ICakeContext> testAction = tool => tool.DotNetCoreTest(testProj, testSettings); OpenCover(testAction, coverageOutput, new OpenCoverSettings { OldStyle = true, // Needed for .NET Core Register = "user", ArgumentCustomization = args => args.Append("-hideskipped:all") }.WithFilter("+[ValidationPipeline.LogStorage*]*")); ReportGenerator(coverageOutput, coverageDir); }); Task("CoverallsUpload") .WithCriteria(() => FileExists(coverageOutput)) .WithCriteria(() => BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { CoverallsIo(coverageOutput, new CoverallsIoSettings { RepoToken = EnvironmentVariable("coveralls_repo_token") }); }); Task("Build") .WithCriteria(() => !BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { DockerComposeUp(new DockerComposeUpSettings { Files = new [] { "docker-compose.ci.build.yml" } }); DockerComposeBuild(); }); Task("DockerPush") .WithCriteria(() => BuildSystem.IsRunningOnTravisCI) .IsDependentOn("Build") .Does(() => { }); Task("Default") .IsDependentOn("DockerPush") .IsDependentOn("CoverallsUpload"); RunTarget("Default");
mit
C#
5cf2f78954df649a56fea0854ee3a70fd4add6da
Disable Test coverage for Travis
syedhassaanahmed/log-storage-service,syedhassaanahmed/log-storage-service,syedhassaanahmed/log-storage-service
build.cake
build.cake
#addin Cake.Coveralls #addin Cake.Docker #tool "nuget:?package=OpenCover" #tool "nuget:?package=ReportGenerator" #tool "nuget:?package=coveralls.io" var testProj = "./ValidationPipeline.LogStorage.Tests/ValidationPipeline.LogStorage.Tests.csproj"; var testSettings = new DotNetCoreTestSettings { Framework = "netcoreapp1.1", Configuration = "Release" }; var coverageDir = "./coverageOutput/"; var coverageOutput = coverageDir + "coverage.xml"; Task("StartStorageEmulator") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .Does(() => { StartProcess(@"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe", new ProcessSettings{ Arguments = "start" }); }); Task("Clean") .Does(() => { if (DirectoryExists(coverageDir)) DeleteDirectory(coverageDir, recursive:true); CreateDirectory(coverageDir); DockerComposeRm(new DockerComposeRmSettings { Force = true }); }); Task("Restore") .Does(() => DotNetCoreRestore("ValidationPipeline.LogStorage.sln")); Task("TestWithCoverage") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .IsDependentOn("StartStorageEmulator") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Action<ICakeContext> testAction = tool => tool.DotNetCoreTest(testProj, testSettings); OpenCover(testAction, coverageOutput, new OpenCoverSettings { OldStyle = true, // Needed for .NET Core Register = "user", ArgumentCustomization = args => args.Append("-hideskipped:all") }.WithFilter("+[ValidationPipeline.LogStorage*]*")); ReportGenerator(coverageOutput, coverageDir); }); Task("CoverallsUpload") .WithCriteria(() => FileExists(coverageOutput)) .WithCriteria(() => BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { CoverallsIo(coverageOutput, new CoverallsIoSettings { RepoToken = EnvironmentVariable("coveralls_repo_token") }); }); Task("Build") .WithCriteria(() => !BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { DockerComposeUp(new DockerComposeUpSettings { Files = new [] { "docker-compose.ci.build.yml" } }); DockerComposeBuild(); }); Task("DockerPush") .WithCriteria(() => BuildSystem.IsRunningOnTravisCI) .IsDependentOn("Build") .Does(() => { }); Task("Default") .IsDependentOn("DockerPush") .IsDependentOn("CoverallsUpload"); RunTarget("Default");
#addin Cake.Coveralls #addin Cake.Docker #tool "nuget:?package=OpenCover" #tool "nuget:?package=ReportGenerator" #tool "nuget:?package=coveralls.io" var testProj = "./ValidationPipeline.LogStorage.Tests/ValidationPipeline.LogStorage.Tests.csproj"; var testSettings = new DotNetCoreTestSettings { Framework = "netcoreapp1.1", Configuration = "Release" }; var coverageDir = "./coverageOutput/"; var coverageOutput = coverageDir + "coverage.xml"; Task("StartStorageEmulator") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .Does(() => { StartProcess(@"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe", new ProcessSettings{ Arguments = "start" }); }); Task("Clean") .Does(() => { if (DirectoryExists(coverageDir)) DeleteDirectory(coverageDir, recursive:true); CreateDirectory(coverageDir); DockerComposeRm(new DockerComposeRmSettings { Force = true }); }); Task("Restore") .Does(() => DotNetCoreRestore("ValidationPipeline.LogStorage.sln")); Task("TestWithCoverage") .WithCriteria(() => !BuildSystem.IsRunningOnTravisCI) .IsDependentOn("StartStorageEmulator") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { Action<ICakeContext> testAction = tool => tool.DotNetCoreTest(testProj, testSettings); OpenCover(testAction, coverageOutput, new OpenCoverSettings { OldStyle = true, // Needed for .NET Core Register = "user", ArgumentCustomization = args => args.Append("-hideskipped:all") }.WithFilter("+[ValidationPipeline.LogStorage*]*")); ReportGenerator(coverageOutput, coverageDir); }); Task("CoverallsUpload") .WithCriteria(() => FileExists(coverageOutput)) .WithCriteria(() => BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .Does(() => { CoverallsIo(coverageOutput, new CoverallsIoSettings { RepoToken = EnvironmentVariable("coveralls_repo_token") }); }); Task("Build") .WithCriteria(() => !BuildSystem.IsRunningOnAppVeyor) .IsDependentOn("TestWithCoverage") .IsDependentOn("TestWithoutCoverage") .Does(() => { DockerComposeUp(new DockerComposeUpSettings { Files = new [] { "docker-compose.ci.build.yml" } }); DockerComposeBuild(); }); Task("DockerPush") .WithCriteria(() => BuildSystem.IsRunningOnTravisCI) .IsDependentOn("Build") .Does(() => { }); Task("Default") .IsDependentOn("DockerPush") .IsDependentOn("CoverallsUpload"); RunTarget("Default");
mit
C#
8ee6d75e20f7232ef6ef157abdc38f479051e3f7
Change db migration.
markshark05/GForum,markshark05/GForum
GForum/GForum.Data/DbInitializer.cs
GForum/GForum.Data/DbInitializer.cs
using System.Data.Entity; using GForum.Common; using GForum.Data.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace GForum.Data { internal class DbInitializer : CreateDatabaseIfNotExists<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); // Seed roles var adminRole = new IdentityRole { Name = Globals.AdminRoleName }; roleManager.Create(adminRole); // Seed users var admin = new ApplicationUser { UserName = Globals.DefaultAdminUsername, EmailConfirmed = true, }; userManager.Create(admin, Globals.DefaultAdminPassword); userManager.AddToRole(admin.Id, Globals.AdminRoleName); // Seed catgeories var category = new Category { Title = Globals.DefaultCategoryTitle, Author = admin, }; context.Set<Category>().Add(category); // Seed posts var post = new Post { Title = "README", Content = $"An admin account has been created " + $"with username - *{Globals.DefaultAdminUsername}* and password - *{Globals.DefaultAdminPassword}*.\n\n" + $"**Please change the passowrd ASAP!**", Category = category, Author = admin, }; category.Posts.Add(post); // Complete context.SaveChanges(); base.Seed(context); } } }
using System.Data.Entity; using GForum.Common; using GForum.Data.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; namespace GForum.Data { internal class DbInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext> { protected override void Seed(ApplicationDbContext context) { var roleStore = new RoleStore<IdentityRole>(context); var roleManager = new RoleManager<IdentityRole>(roleStore); var userStore = new UserStore<ApplicationUser>(context); var userManager = new UserManager<ApplicationUser>(userStore); // Seed roles var adminRole = new IdentityRole { Name = Globals.AdminRoleName }; roleManager.Create(adminRole); // Seed users var admin = new ApplicationUser { UserName = Globals.DefaultAdminUsername, EmailConfirmed = true, }; userManager.Create(admin, Globals.DefaultAdminPassword); userManager.AddToRole(admin.Id, Globals.AdminRoleName); // Seed catgeories var category = new Category { Title = Globals.DefaultCategoryTitle, Author = admin, }; context.Set<Category>().Add(category); // Seed posts var post = new Post { Title = "README", Content = $"An admin account has been created " + $"with username - *{Globals.DefaultAdminUsername}* and password - *{Globals.DefaultAdminPassword}*.\n\n" + $"**Please change the passowrd ASAP!**", Category = category, Author = admin, }; category.Posts.Add(post); // Complete context.SaveChanges(); base.Seed(context); } } }
mit
C#
c1618c0adac2e7babc079003054b92d04d62e720
update assembly info
AxelAndersen/quickpay-dotnet-client,QuickPay/quickpay-dotnet-client
QuickPay/Properties/AssemblyInfo.cs
QuickPay/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("Quickpay dotnet client")] [assembly: AssemblyDescription("QuickPay dotnet client")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Quickpay")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b61ea31a-b0bf-491b-8f9d-7b1307dcea86")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Quickpay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Quickpay")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b61ea31a-b0bf-491b-8f9d-7b1307dcea86")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
820a672940b151a43b54f510dc03b8476bd95ce9
Reword xmldoc to make more sense
NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu
osu.Game/Rulesets/Mods/ModUsage.cs
osu.Game/Rulesets/Mods/ModUsage.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. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine whether it's playable in such context. /// </summary> public enum ModUsage { /// <summary> /// Used for a per-user gameplay session. Determines whether the mod is playable by an end user. /// </summary> User, /// <summary> /// Used as a "required mod" for a multiplayer match. /// </summary> MultiplayerRequired, /// <summary> /// Used as a "free mod" for a multiplayer match. /// </summary> MultiplayerFree, } }
// 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. namespace osu.Game.Rulesets.Mods { /// <summary> /// The usage of this mod to determine its playability. /// </summary> public enum ModUsage { /// <summary> /// In a solo gameplay session. /// </summary> User, /// <summary> /// In a multiplayer match, as a required mod. /// </summary> MultiplayerRequired, /// <summary> /// In a multiplayer match, as a "free" mod. /// </summary> MultiplayerFree, } }
mit
C#
0812d98a809fcae56fcfb84333b5541bf1b89713
add group disable
Mooophy/158212
as3/as3/Form1.cs
as3/as3/Form1.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace as3 { using Images = global::as3.Properties.Resources; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { pictureBox1.Image = Images.Chile; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { pictureBox1.Image = Images.Germany; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { pictureBox1.Image = Images.Cameroon; } private void radioButton4_CheckedChanged(object sender, EventArgs e) { pictureBox2.Image = Images.Chile; } private void radioButton5_CheckedChanged(object sender, EventArgs e) { pictureBox2.Image = Images.Germany; } private void radioButton6_CheckedChanged(object sender, EventArgs e) { pictureBox2.Image = Images.Cameroon; } private void tick_EventHandler(object sender, EventArgs e) { ++elapsed; label1.Text = getTimeStr(); } private void button1_Click(object sender, EventArgs e) { timer1.Start(); groupBox1.Enabled = groupBox2.Enabled = false; } private void button2_Click(object sender, EventArgs e) { timer1.Stop(); } private String getTimeStr() { lambda isTooShort = number => number < 10; var min = (isTooShort(elapsed / 60) ? "0" : "") + (elapsed / 60).ToString(); var sec = (isTooShort(elapsed % 60) ? "0" : "") + (elapsed % 60).ToString(); return min + ":" + sec; } private int elapsed; delegate bool lambda(int i); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace as3 { using Images = global::as3.Properties.Resources; public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { pictureBox1.Image = Images.Chile; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { pictureBox1.Image = Images.Germany; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { pictureBox1.Image = Images.Cameroon; } private void radioButton4_CheckedChanged(object sender, EventArgs e) { pictureBox2.Image = Images.Chile; } private void radioButton5_CheckedChanged(object sender, EventArgs e) { pictureBox2.Image = Images.Germany; } private void radioButton6_CheckedChanged(object sender, EventArgs e) { pictureBox2.Image = Images.Cameroon; } private void tick_EventHandler(object sender, EventArgs e) { ++elapsed; label1.Text = getTimeStr(); } private void button1_Click(object sender, EventArgs e) { timer1.Start(); } private String getTimeStr() { lambda isTooShort = number => number < 10; var min = (isTooShort(elapsed / 60) ? "0" : "") + (elapsed / 60).ToString(); var sec = (isTooShort(elapsed % 60) ? "0" : "") + (elapsed % 60).ToString(); return min + ":" + sec; } private int elapsed; delegate bool lambda(int i); private void button2_Click(object sender, EventArgs e) { timer1.Stop(); } } }
mit
C#
e30750001553f78a80759d73aadbade45397fac8
Fix missing dependency
twenzel/Cake.MarkdownToPdf,twenzel/Cake.MarkdownToPdf,twenzel/Cake.MarkdownToPdf
build.cake
build.cake
#tool "nuget:?package=GitVersion.CommandLine&version=5.7.0" #tool "nuget:?package=NuGet.CommandLine&version=5.8.1" var target = Argument("target", "Default"); ////////////////////////////////////////////////////////////////////// // Build Variables ///////////////////////////////////////////////////////////////////// var solution = "./Cake.MarkdownToPdf.sln"; var project = "./src/Cake.MarkdownToPdf/Cake.MarkdownToPdf.csproj"; var outputDir = "./buildArtifacts/"; var outputDirAddin = outputDir+"Addin/"; var outputDirNuget = outputDir+"NuGet/"; var nuspecDir = "./nuspec/"; ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Removes the output directory") .Does(() => { if (DirectoryExists(outputDir)) { DeleteDirectory(outputDir, new DeleteDirectorySettings { Recursive = true, Force = true }); } CreateDirectory(outputDir); }); GitVersion versionInfo = null; Task("Version") .Description("Retrieves the current version from the git repository") .Does(() => { versionInfo = GitVersion(new GitVersionSettings { UpdateAssemblyInfo = false }); Information("Version: "+ versionInfo.FullSemVer); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Version") .Does(() => { var msBuildSettings = new DotNetCoreMSBuildSettings() .WithProperty("Version", versionInfo.AssemblySemVer) .WithProperty("InformationalVersion", versionInfo.InformationalVersion); var settings = new DotNetCorePublishSettings { Configuration = "Release", OutputDirectory = outputDirAddin, MSBuildSettings = msBuildSettings }; DotNetCorePublish(project, settings); }); Task("Test") .IsDependentOn("Build") .Does(() => { var projectFiles = GetFiles("./tests/**/*.csproj"); foreach(var file in projectFiles) { DotNetCoreTest(file.FullPath); } }); Task("Pack") .IsDependentOn("Test") .IsDependentOn("Version") .Does(() => { var nuGetPackSettings = new NuGetPackSettings { Version = versionInfo.NuGetVersionV2, BasePath = outputDirAddin, OutputDirectory = outputDirNuget, NoPackageAnalysis = true }; NuGetPack(nuspecDir + "Cake.MarkdownToPdf.nuspec", nuGetPackSettings); }); Task("Default") .IsDependentOn("Test"); RunTarget(target);
#tool "nuget:?package=GitVersion.CommandLine&version=5.7.0" var target = Argument("target", "Default"); ////////////////////////////////////////////////////////////////////// // Build Variables ///////////////////////////////////////////////////////////////////// var solution = "./Cake.MarkdownToPdf.sln"; var project = "./src/Cake.MarkdownToPdf/Cake.MarkdownToPdf.csproj"; var outputDir = "./buildArtifacts/"; var outputDirAddin = outputDir+"Addin/"; var outputDirNuget = outputDir+"NuGet/"; var nuspecDir = "./nuspec/"; ////////////////////////////////////////////////////////////////////// // TASKS ////////////////////////////////////////////////////////////////////// Task("Clean") .Description("Removes the output directory") .Does(() => { if (DirectoryExists(outputDir)) { DeleteDirectory(outputDir, new DeleteDirectorySettings { Recursive = true, Force = true }); } CreateDirectory(outputDir); }); GitVersion versionInfo = null; Task("Version") .Description("Retrieves the current version from the git repository") .Does(() => { versionInfo = GitVersion(new GitVersionSettings { UpdateAssemblyInfo = false }); Information("Version: "+ versionInfo.FullSemVer); }); Task("Build") .IsDependentOn("Clean") .IsDependentOn("Version") .Does(() => { var msBuildSettings = new DotNetCoreMSBuildSettings() .WithProperty("Version", versionInfo.AssemblySemVer) .WithProperty("InformationalVersion", versionInfo.InformationalVersion); var settings = new DotNetCorePublishSettings { Configuration = "Release", OutputDirectory = outputDirAddin, MSBuildSettings = msBuildSettings }; DotNetCorePublish(project, settings); }); Task("Test") .IsDependentOn("Build") .Does(() => { var projectFiles = GetFiles("./tests/**/*.csproj"); foreach(var file in projectFiles) { DotNetCoreTest(file.FullPath); } }); Task("Pack") .IsDependentOn("Test") .IsDependentOn("Version") .Does(() => { var nuGetPackSettings = new NuGetPackSettings { Version = versionInfo.NuGetVersionV2, BasePath = outputDirAddin, OutputDirectory = outputDirNuget, NoPackageAnalysis = true }; NuGetPack(nuspecDir + "Cake.MarkdownToPdf.nuspec", nuGetPackSettings); }); Task("Default") .IsDependentOn("Test"); RunTarget(target);
mit
C#
22bc9fa46ae5ab74072eea36732a982e7dbc755d
update GetDayOfWeek
zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning
ParallelTask/Program.cs
ParallelTask/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ParallelTask { public class Program { private static readonly Action<string> logger = Console.WriteLine; static void Main(string[] args) { GetDayOfWeek(); Console.ReadKey(); } public static void GetDayOfWeek() { //运行在另外一个线程中 var dayName = Task.Run<string>(() => { logger("wating"); Thread.Sleep(2000); return new DateTime().DayOfWeek.ToString(); }); logger("今天是: " + dayName.Result); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParallelTask { class Program { static void Main(string[] args) { } } }
mit
C#
eed07096f6b39c7e6948543a092ed9f1f387f0b3
Remove method from interface because it's only useful for testing. Generates incorrect results if not used right
PKRoma/refit,onovotny/refit,mteper/refit,PureWeen/refit,jlucansky/refit,ammachado/refit,jlucansky/refit,mteper/refit,onovotny/refit,PureWeen/refit,paulcbetts/refit,paulcbetts/refit,ammachado/refit
Refit/RequestBuilder.cs
Refit/RequestBuilder.cs
using System; using System.Collections.Generic; using System.Net.Http; namespace Refit { public interface IRequestBuilder { IEnumerable<string> InterfaceHttpMethods { get; } Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName); } interface IRequestBuilderFactory { IRequestBuilder Create(Type interfaceType, RefitSettings settings); } public static class RequestBuilder { static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory(); public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings) { return platformRequestBuilderFactory.Create(interfaceType, settings); } public static IRequestBuilder ForType(Type interfaceType) { return platformRequestBuilderFactory.Create(interfaceType, null); } public static IRequestBuilder ForType<T>(RefitSettings settings) { return ForType(typeof(T), settings); } public static IRequestBuilder ForType<T>() { return ForType(typeof(T), null); } } #if PORTABLE class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null) { throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!"); } } #endif }
using System; using System.Collections.Generic; using System.Net.Http; namespace Refit { public interface IRequestBuilder { IEnumerable<string> InterfaceHttpMethods { get; } Func<object[], HttpRequestMessage> BuildRequestFactoryForMethod(string methodName, string basePath = ""); Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName); } interface IRequestBuilderFactory { IRequestBuilder Create(Type interfaceType, RefitSettings settings); } public static class RequestBuilder { static readonly IRequestBuilderFactory platformRequestBuilderFactory = new RequestBuilderFactory(); public static IRequestBuilder ForType(Type interfaceType, RefitSettings settings) { return platformRequestBuilderFactory.Create(interfaceType, settings); } public static IRequestBuilder ForType(Type interfaceType) { return platformRequestBuilderFactory.Create(interfaceType, null); } public static IRequestBuilder ForType<T>(RefitSettings settings) { return ForType(typeof(T), settings); } public static IRequestBuilder ForType<T>() { return ForType(typeof(T), null); } } #if PORTABLE class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null) { throw new NotImplementedException("You've somehow included the PCL version of Refit in your app. You need to use the platform-specific version!"); } } #endif }
mit
C#
e69c0a19ab58ad8fdb1f5c3736cd2c9b53614dbf
add placeholder test for once job project controller is finished
mzrimsek/resume-site-api
Test.Integration/ControllerTests/JobControllerTests/DeleteJobShould.cs
Test.Integration/ControllerTests/JobControllerTests/DeleteJobShould.cs
using Microsoft.AspNetCore.TestHost; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net; using System.Net.Http; using Test.Integration.TestHelpers; using Web.Models.JobModels; namespace Test.Integration.ControllerTests.JobControllerTests { [TestClass] public class DeleteJobShould { private TestServer _server; private HttpClient _client; [TestInitialize] public void SetUp() { (_server, _client) = new TestSetupHelper().GetTestServerAndClient(); } [TestCleanup] public void TearDown() { _client.Dispose(); _server.Dispose(); } [TestMethod] public void ReturnStatusCodeNotFound_WhenGivenInvalidId() { var response = _client.DeleteAsync($"{ControllerRouteEnum.JOB}/1").Result; Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } [TestMethod] public void ReturnStatusCodeNoContent_WhenGivenValidId() { var model = TestObjectCreator.GetAddUpdateJobViewModel(); var postRequestContent = RequestHelper.GetRequestContentFromObject(model); var postResponse = _client.PostAsync($"{ControllerRouteEnum.JOB}", postRequestContent).Result; var jobId = RequestHelper.GetObjectFromResponseContent<JobViewModel>(postResponse).Id; var deleteReponse = _client.DeleteAsync($"{ControllerRouteEnum.JOB}/{jobId}").Result; Assert.AreEqual(HttpStatusCode.NoContent, deleteReponse.StatusCode); } [TestMethod] public void DeleteJob() { var model = TestObjectCreator.GetAddUpdateJobViewModel(); var postRequestContent = RequestHelper.GetRequestContentFromObject(model); var postResponse = _client.PostAsync($"{ControllerRouteEnum.JOB}", postRequestContent).Result; var jobId = RequestHelper.GetObjectFromResponseContent<JobViewModel>(postResponse).Id; var _ = _client.DeleteAsync($"{ControllerRouteEnum.JOB}/{jobId}").Result; var getResponse = _client.GetAsync($"{ControllerRouteEnum.JOB}/${jobId}").Result; Assert.AreEqual(HttpStatusCode.NotFound, getResponse.StatusCode); } [TestMethod] public void DeleteJobProjectsForJob() { Assert.Fail(); } } }
using Microsoft.AspNetCore.TestHost; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net; using System.Net.Http; using Test.Integration.TestHelpers; using Web.Models.JobModels; namespace Test.Integration.ControllerTests.JobControllerTests { [TestClass] public class DeleteJobShould { private TestServer _server; private HttpClient _client; [TestInitialize] public void SetUp() { (_server, _client) = new TestSetupHelper().GetTestServerAndClient(); } [TestCleanup] public void TearDown() { _client.Dispose(); _server.Dispose(); } [TestMethod] public void ReturnStatusCodeNotFound_WhenGivenInvalidId() { var response = _client.DeleteAsync($"{ControllerRouteEnum.JOB}/1").Result; Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode); } [TestMethod] public void ReturnStatusCodeNoContent_WhenGivenValidId() { var model = TestObjectCreator.GetAddUpdateJobViewModel(); var postRequestContent = RequestHelper.GetRequestContentFromObject(model); var postResponse = _client.PostAsync($"{ControllerRouteEnum.JOB}", postRequestContent).Result; var jobId = RequestHelper.GetObjectFromResponseContent<JobViewModel>(postResponse).Id; var deleteReponse = _client.DeleteAsync($"{ControllerRouteEnum.JOB}/{jobId}").Result; Assert.AreEqual(HttpStatusCode.NoContent, deleteReponse.StatusCode); } [TestMethod] public void DeleteJob() { var model = TestObjectCreator.GetAddUpdateJobViewModel(); var postRequestContent = RequestHelper.GetRequestContentFromObject(model); var postResponse = _client.PostAsync($"{ControllerRouteEnum.JOB}", postRequestContent).Result; var jobId = RequestHelper.GetObjectFromResponseContent<JobViewModel>(postResponse).Id; var _ = _client.DeleteAsync($"{ControllerRouteEnum.JOB}/{jobId}").Result; var getResponse = _client.GetAsync($"{ControllerRouteEnum.JOB}/${jobId}").Result; Assert.AreEqual(HttpStatusCode.NotFound, getResponse.StatusCode); } } }
mit
C#
b6e96d871149b365183f9f225ee70c4e2c6b98ce
Fix trading bugs
blackpanther989/ArchiSteamFarm,KlappPc/ArchiSteamFarm,i3at/ArchiSteamFarm,i3at/ArchiSteamFarm,blackpanther989/ArchiSteamFarm,JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,KlappPc/ArchiSteamFarm
ArchiSteamFarm/SteamItem.cs
ArchiSteamFarm/SteamItem.cs
/* _ _ _ ____ _ _____ / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| Copyright 2015-2016 Łukasz "JustArchi" Domeradzki Contact: JustArchi@JustArchi.net 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 Newtonsoft.Json; namespace ArchiSteamFarm { internal sealed class SteamItem { // REF: https://developer.valvesoftware.com/wiki/Steam_Web_API/IEconService#CEcon_Asset [JsonProperty(Required = Required.DisallowNull)] internal string appid { get; set; } [JsonProperty(Required = Required.DisallowNull)] internal string contextid { get; set; } [JsonProperty(Required = Required.DisallowNull)] internal string assetid { get; set; } [JsonProperty(Required = Required.DisallowNull)] internal string id { get { return assetid; } set { assetid = value; } } [JsonProperty(Required = Required.AllowNull)] internal string classid { get; set; } [JsonProperty(Required = Required.AllowNull)] internal string instanceid { get; set; } [JsonProperty(Required = Required.Always)] internal string amount { get; set; } } }
/* _ _ _ ____ _ _____ / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| Copyright 2015-2016 Łukasz "JustArchi" Domeradzki Contact: JustArchi@JustArchi.net 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 Newtonsoft.Json; namespace ArchiSteamFarm { internal sealed class SteamItem { // REF: https://developer.valvesoftware.com/wiki/Steam_Web_API/IEconService#CEcon_Asset [JsonProperty(Required = Required.Always)] internal string appid { get; set; } [JsonProperty(Required = Required.Always)] internal string contextid { get; set; } [JsonProperty(Required = Required.Always)] internal string assetid { get; set; } [JsonProperty] internal string id { get { return assetid; } set { assetid = value; } } [JsonProperty(Required = Required.Always)] internal string classid { get; set; } [JsonProperty(Required = Required.Always)] internal string instanceid { get; set; } [JsonProperty(Required = Required.Always)] internal string amount { get; set; } } }
apache-2.0
C#
af2fff34a299bb37c5c2e6b66fa60b1e97f6d282
Fix Windows Runtime library build error
nemanja88/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,pankajsn/azure-sdk-for-net,marcoippel/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,oaastest/azure-sdk-for-net,scottrille/azure-sdk-for-net,pilor/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,dominiqa/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,jtlibing/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,yoreddy/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pomortaz/azure-sdk-for-net,smithab/azure-sdk-for-net,djyou/azure-sdk-for-net,begoldsm/azure-sdk-for-net,xindzhan/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,herveyw/azure-sdk-for-net,mabsimms/azure-sdk-for-net,shipram/azure-sdk-for-net,AzCiS/azure-sdk-for-net,AzCiS/azure-sdk-for-net,ailn/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,amarzavery/azure-sdk-for-net,relmer/azure-sdk-for-net,r22016/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,scottrille/azure-sdk-for-net,btasdoven/azure-sdk-for-net,lygasch/azure-sdk-for-net,hyonholee/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,shutchings/azure-sdk-for-net,abhing/azure-sdk-for-net,alextolp/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,djyou/azure-sdk-for-net,hyonholee/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,amarzavery/azure-sdk-for-net,pankajsn/azure-sdk-for-net,pilor/azure-sdk-for-net,marcoippel/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,marcoippel/azure-sdk-for-net,samtoubia/azure-sdk-for-net,shuagarw/azure-sdk-for-net,shuagarw/azure-sdk-for-net,stankovski/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,alextolp/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,amarzavery/azure-sdk-for-net,vhamine/azure-sdk-for-net,rohmano/azure-sdk-for-net,lygasch/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,cwickham3/azure-sdk-for-net,dominiqa/azure-sdk-for-net,pomortaz/azure-sdk-for-net,AuxMon/azure-sdk-for-net,guiling/azure-sdk-for-net,naveedaz/azure-sdk-for-net,AuxMon/azure-sdk-for-net,begoldsm/azure-sdk-for-net,rohmano/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jamestao/azure-sdk-for-net,travismc1/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,pattipaka/azure-sdk-for-net,peshen/azure-sdk-for-net,bgold09/azure-sdk-for-net,makhdumi/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,shipram/azure-sdk-for-net,ogail/azure-sdk-for-net,juvchan/azure-sdk-for-net,gubookgu/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,tpeplow/azure-sdk-for-net,shutchings/azure-sdk-for-net,dasha91/azure-sdk-for-net,jamestao/azure-sdk-for-net,ogail/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,enavro/azure-sdk-for-net,Nilambari/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,pankajsn/azure-sdk-for-net,nathannfan/azure-sdk-for-net,enavro/azure-sdk-for-net,shuainie/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,arijitt/azure-sdk-for-net,guiling/azure-sdk-for-net,robertla/azure-sdk-for-net,hovsepm/azure-sdk-for-net,msfcolombo/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,atpham256/azure-sdk-for-net,dasha91/azure-sdk-for-net,vhamine/azure-sdk-for-net,btasdoven/azure-sdk-for-net,makhdumi/azure-sdk-for-net,zaevans/azure-sdk-for-net,dasha91/azure-sdk-for-net,samtoubia/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,samtoubia/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,olydis/azure-sdk-for-net,pinwang81/azure-sdk-for-net,shipram/azure-sdk-for-net,atpham256/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,namratab/azure-sdk-for-net,bgold09/azure-sdk-for-net,hallihan/azure-sdk-for-net,oaastest/azure-sdk-for-net,pattipaka/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pinwang81/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,pilor/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,cwickham3/azure-sdk-for-net,djoelz/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jamestao/azure-sdk-for-net,gubookgu/azure-sdk-for-net,pattipaka/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,pinwang81/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,olydis/azure-sdk-for-net,jtlibing/azure-sdk-for-net,oburlacu/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,shutchings/azure-sdk-for-net,herveyw/azure-sdk-for-net,juvchan/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,hovsepm/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,zaevans/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,djyou/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,relmer/azure-sdk-for-net,abhing/azure-sdk-for-net,makhdumi/azure-sdk-for-net,mumou/azure-sdk-for-net,peshen/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,smithab/azure-sdk-for-net,naveedaz/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,nathannfan/azure-sdk-for-net,tpeplow/azure-sdk-for-net,tpeplow/azure-sdk-for-net,MabOneSdk/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,nemanja88/azure-sdk-for-net,arijitt/azure-sdk-for-net,yitao-zhang/azure-sdk-for-net,smithab/azure-sdk-for-net,lygasch/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,SpotLabsNET/azure-sdk-for-net,huangpf/azure-sdk-for-net,yadavbdev/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net,markcowl/azure-sdk-for-net,robertla/azure-sdk-for-net,zaevans/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,mihymel/azure-sdk-for-net,bgold09/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,nathannfan/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,mabsimms/azure-sdk-for-net,hallihan/azure-sdk-for-net,oburlacu/azure-sdk-for-net,peshen/azure-sdk-for-net,alextolp/azure-sdk-for-net,vladca/azure-sdk-for-net,stankovski/azure-sdk-for-net,AuxMon/azure-sdk-for-net,enavro/azure-sdk-for-net,ailn/azure-sdk-for-net,akromm/azure-sdk-for-net,jamestao/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,jasper-schneider/azure-sdk-for-net,jtlibing/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,xindzhan/azure-sdk-for-net,herveyw/azure-sdk-for-net,abhing/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,jianghaolu/azure-sdk-for-net,hovsepm/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,dominiqa/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,gubookgu/azure-sdk-for-net,kagamsft/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,kagamsft/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,hyonholee/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,AzCiS/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,akromm/azure-sdk-for-net,juvchan/azure-sdk-for-net,samtoubia/azure-sdk-for-net,cwickham3/azure-sdk-for-net,robertla/azure-sdk-for-net,rohmano/azure-sdk-for-net,pomortaz/azure-sdk-for-net,ogail/azure-sdk-for-net,nacaspi/azure-sdk-for-net,mabsimms/azure-sdk-for-net,atpham256/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,relmer/azure-sdk-for-net,mihymel/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,naveedaz/azure-sdk-for-net,begoldsm/azure-sdk-for-net,akromm/azure-sdk-for-net,r22016/azure-sdk-for-net,vivsriaus/azure-sdk-for-net,shuagarw/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,vladca/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,namratab/azure-sdk-for-net,tonytang-microsoft-com/azure-sdk-for-net,Matt-Westphal/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,xindzhan/azure-sdk-for-net,kagamsft/azure-sdk-for-net,shuainie/azure-sdk-for-net,divyakgupta/azure-sdk-for-net,mumou/azure-sdk-for-net,oaastest/azure-sdk-for-net,vladca/azure-sdk-for-net,Nilambari/azure-sdk-for-net,nemanja88/azure-sdk-for-net,hyonholee/azure-sdk-for-net,r22016/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,nacaspi/azure-sdk-for-net,yoreddy/azure-sdk-for-net,btasdoven/azure-sdk-for-net,avijitgupta/azure-sdk-for-net,DeepakRajendranMsft/azure-sdk-for-net,mihymel/azure-sdk-for-net,scottrille/azure-sdk-for-net,yoreddy/azure-sdk-for-net,djoelz/azure-sdk-for-net,guiling/azure-sdk-for-net,shixiaoyu/azure-sdk-for-net,namratab/azure-sdk-for-net,ailn/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,oburlacu/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,olydis/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,Nilambari/azure-sdk-for-net,felixcho-msft/azure-sdk-for-net
microsoft-azure-api/Services/Storage/Lib/RT/Properties/AssemblyInfo.cs
microsoft-azure-api/Services/Storage/Lib/RT/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; 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("Microsoft.WindowsAzure.Storage.WinMD")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Windows Azure Storage")] [assembly: AssemblyCopyright("Copyright © 2012 Microsoft Corp.")] [assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.5.0")] [assembly: ComVisible(false)] #if SIGN [assembly: InternalsVisibleTo( "Microsoft.WindowsAzure.Storage.Table, PublicKey=" + "0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67" + "871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0b" + "d333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307" + "e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c3" + "08055da9")] #else [assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Storage.Table")] #endif [assembly: NeutralResourcesLanguageAttribute("en-US")]
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("Microsoft.WindowsAzure.Storage.WinMD")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Windows Azure Storage")] [assembly: AssemblyCopyright("Copyright © 2012 Microsoft Corp.")] [assembly: AssemblyTrademark("Microsoft ® is a registered trademark of Microsoft Corporation.")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.5.0")] [assembly: ComVisible(false)] #if SIGN [assembly: InternalsVisibleTo( "Microsoft.WindowsAzure.Storage.Table, PublicKey=" + "0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67" + "871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0b" + "d333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307" + "e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c3" + "08055da9")] #else [assembly: InternalsVisibleTo("Microsoft.WindowsAzure.Storage.Table")] #endif [assembly: NeutralResourcesLanguageAttribute("en-US")]
mit
C#
14ccf7db552e20a91ae7609d3b959555f78d60f2
Update UrlTokenGenerator.cs
jgveire/Vanguard.Framework
src/Vanguard.Framework.Core/UrlTokenGenerator.cs
src/Vanguard.Framework.Core/UrlTokenGenerator.cs
namespace Vanguard.Framework.Core { using System; using System.Security.Cryptography; /// <summary> /// The URL token generator. /// It generates a token that can be used in URL's to valid /// for example email addresses, password resets, etc. /// </summary> public class UrlTokenGenerator : IUrlTokenGenerator { private static readonly RNGCryptoServiceProvider CryptoProvider = new RNGCryptoServiceProvider(); /// <summary> /// Gets the default URL token generator instance. /// </summary> public static IUrlTokenGenerator Instance { get; } = new UrlTokenGenerator(); /// <summary> /// Generates an URL token according to the specified length. /// </summary> /// <param name="length">The length of the token.</param> /// <returns>An URL token.</returns> public string Generate(int length) { Guard.ArgumentInRange(length, 1, int.MaxValue, nameof(length)); // Make sure the length is dividable by 3 // otherwise we will get padding characters. int byteLength = length - (length % 3) + 3; var bytes = new byte[byteLength]; CryptoProvider.GetBytes(bytes); // Convert to string and replace padding characters. string token = Convert .ToBase64String(bytes) .Replace('/', 'a') .Replace('=', 'B') .Replace('+', 'c'); return token.Substring(0, length); } } }
namespace Vanguard.Framework.Core { using System; using System.Security.Cryptography; /// <summary> /// The URL token generator. /// It generates a token that can be used in URL's to valid /// for example email addresses, password resets, etc. /// </summary> public class UrlTokenGenerator : IUrlTokenGenerator { private static readonly RNGCryptoServiceProvider CryptoProvider = new RNGCryptoServiceProvider(); /// <summary> /// Gets the default URL token generator instance. /// </summary> public static IUrlTokenGenerator Instance { get; } = new UrlTokenGenerator(); /// <summary> /// Generates an URL token according to the specified length. /// </summary> /// <param name="length">The length of the token.</param> /// <returns>An URL token.</returns> public string Generate(int length) { Guard.ArgumentInRange(length, 1, int.MaxValue, nameof(length)); // Make sure the length is dividable by 3 // other we will get padding characters. int byteLength = length - (length % 3) + 3; var bytes = new byte[byteLength]; CryptoProvider.GetBytes(bytes); string token = Convert .ToBase64String(bytes) .Replace('/', 'a') .Replace('=', 'B') .Replace('+', 'c'); return token.Substring(0, length); } } }
mit
C#
04b07b774bf56985c0f55b2484c5d3c1dcf600c9
Allow null DataTemplate.DataType.
wieslawsoltes/Perspex,jkoritzinsky/Perspex,OronDF343/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,punker76/Perspex,wieslawsoltes/Perspex,jazzay/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,MrDaedra/Avalonia,susloparovdenis/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex,Perspex/Perspex,akrisiun/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,susloparovdenis/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,MrDaedra/Avalonia,wieslawsoltes/Perspex,OronDF343/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,susloparovdenis/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,susloparovdenis/Perspex,AvaloniaUI/Avalonia
src/Markup/Perspex.Markup.Xaml/Templates/DataTemplate.cs
src/Markup/Perspex.Markup.Xaml/Templates/DataTemplate.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; using System.Reflection; using Perspex.Controls; using Perspex.Controls.Templates; using Perspex.Metadata; namespace Perspex.Markup.Xaml.Templates { public class DataTemplate : IDataTemplate { public Type DataType { get; set; } [Content] public TemplateContent Content { get; set; } public bool Match(object data) { if (DataType == null) { return true; } else { return DataType.GetTypeInfo().IsAssignableFrom(data.GetType().GetTypeInfo()); } } public IControl Build(object data) { var visualTreeForItem = Content.Load(); visualTreeForItem.DataContext = data; return visualTreeForItem; } } }
// 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; using System.Reflection; using Perspex.Controls; using Perspex.Controls.Templates; using Perspex.Metadata; namespace Perspex.Markup.Xaml.Templates { public class DataTemplate : IDataTemplate { public Type DataType { get; set; } [Content] public TemplateContent Content { get; set; } public bool Match(object data) { if (DataType == null) { throw new InvalidOperationException("DataTemplate must have a DataType."); } return DataType.GetTypeInfo().IsAssignableFrom(data.GetType().GetTypeInfo()); } public IControl Build(object data) { var visualTreeForItem = Content.Load(); visualTreeForItem.DataContext = data; return visualTreeForItem; } } }
mit
C#
8df1c2258cd6bc4a7421cde91d709f1350cd051a
Add uuid to indices stats (#3437)
elastic/elasticsearch-net,elastic/elasticsearch-net
src/Nest/Indices/Monitoring/IndicesStats/IndicesStats.cs
src/Nest/Indices/Monitoring/IndicesStats/IndicesStats.cs
using System.Collections.Generic; using Newtonsoft.Json; namespace Nest { [JsonObject] public class IndicesStats { /// <summary> /// Universal Unique Identifier for the index /// </summary> /// <remarks> /// Introduced in Elasticsearch 6.4.0 /// </remarks> [JsonProperty("uuid")] public string UUID { get; } [JsonProperty("primaries")] public IndexStats Primaries { get; internal set; } [JsonProperty("total")] public IndexStats Total { get; internal set; } [JsonProperty("shards")] [JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter<string, ShardStats[]>))] public IReadOnlyDictionary<string, ShardStats[]> Shards { get; internal set; } = EmptyReadOnly<string, ShardStats[]>.Dictionary; } }
using System.Collections.Generic; using Newtonsoft.Json; namespace Nest { [JsonObject] public class IndicesStats { [JsonProperty("primaries")] public IndexStats Primaries { get; internal set; } [JsonProperty("total")] public IndexStats Total { get; internal set; } [JsonProperty("shards")] [JsonConverter(typeof(VerbatimDictionaryKeysJsonConverter<string, ShardStats[]>))] public IReadOnlyDictionary<string, ShardStats[]> Shards { get; internal set; } = EmptyReadOnly<string, ShardStats[]>.Dictionary; } }
apache-2.0
C#
c0d207f2286b15034254e2214a9807fb14c26700
Fix potential NRE in lucene index
jimasp/Orchard,jersiovic/Orchard,LaserSrl/Orchard,abhishekluv/Orchard,ehe888/Orchard,yersans/Orchard,omidnasri/Orchard,Codinlab/Orchard,LaserSrl/Orchard,hbulzy/Orchard,Lombiq/Orchard,jersiovic/Orchard,Dolphinsimon/Orchard,Codinlab/Orchard,hannan-azam/Orchard,tobydodds/folklife,jimasp/Orchard,rtpHarry/Orchard,jtkech/Orchard,SouleDesigns/SouleDesigns.Orchard,hbulzy/Orchard,mvarblow/Orchard,grapto/Orchard.CloudBust,Dolphinsimon/Orchard,jimasp/Orchard,omidnasri/Orchard,Praggie/Orchard,li0803/Orchard,Praggie/Orchard,grapto/Orchard.CloudBust,tobydodds/folklife,grapto/Orchard.CloudBust,vairam-svs/Orchard,hannan-azam/Orchard,sfmskywalker/Orchard,li0803/Orchard,abhishekluv/Orchard,bedegaming-aleksej/Orchard,Fogolan/OrchardForWork,yersans/Orchard,jimasp/Orchard,omidnasri/Orchard,LaserSrl/Orchard,jersiovic/Orchard,jtkech/Orchard,Fogolan/OrchardForWork,IDeliverable/Orchard,sfmskywalker/Orchard,rtpHarry/Orchard,OrchardCMS/Orchard,xkproject/Orchard,xkproject/Orchard,abhishekluv/Orchard,jimasp/Orchard,jtkech/Orchard,jchenga/Orchard,Fogolan/OrchardForWork,OrchardCMS/Orchard,vairam-svs/Orchard,Dolphinsimon/Orchard,mvarblow/Orchard,gcsuk/Orchard,Praggie/Orchard,rtpHarry/Orchard,yersans/Orchard,AdvantageCS/Orchard,OrchardCMS/Orchard,AdvantageCS/Orchard,xkproject/Orchard,rtpHarry/Orchard,hannan-azam/Orchard,omidnasri/Orchard,omidnasri/Orchard,li0803/Orchard,LaserSrl/Orchard,bedegaming-aleksej/Orchard,mvarblow/Orchard,vairam-svs/Orchard,gcsuk/Orchard,jersiovic/Orchard,aaronamm/Orchard,mvarblow/Orchard,bedegaming-aleksej/Orchard,jchenga/Orchard,grapto/Orchard.CloudBust,hbulzy/Orchard,Lombiq/Orchard,li0803/Orchard,sfmskywalker/Orchard,aaronamm/Orchard,Lombiq/Orchard,aaronamm/Orchard,hbulzy/Orchard,omidnasri/Orchard,grapto/Orchard.CloudBust,Codinlab/Orchard,jtkech/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,fassetar/Orchard,Dolphinsimon/Orchard,hannan-azam/Orchard,Serlead/Orchard,ehe888/Orchard,yersans/Orchard,Dolphinsimon/Orchard,Lombiq/Orchard,vairam-svs/Orchard,brownjordaninternational/OrchardCMS,sfmskywalker/Orchard,fassetar/Orchard,IDeliverable/Orchard,abhishekluv/Orchard,omidnasri/Orchard,sfmskywalker/Orchard,li0803/Orchard,mvarblow/Orchard,gcsuk/Orchard,brownjordaninternational/OrchardCMS,SouleDesigns/SouleDesigns.Orchard,Codinlab/Orchard,brownjordaninternational/OrchardCMS,abhishekluv/Orchard,sfmskywalker/Orchard,vairam-svs/Orchard,aaronamm/Orchard,SouleDesigns/SouleDesigns.Orchard,gcsuk/Orchard,tobydodds/folklife,grapto/Orchard.CloudBust,tobydodds/folklife,aaronamm/Orchard,ehe888/Orchard,rtpHarry/Orchard,sfmskywalker/Orchard,jersiovic/Orchard,Serlead/Orchard,Praggie/Orchard,hbulzy/Orchard,IDeliverable/Orchard,Serlead/Orchard,Serlead/Orchard,IDeliverable/Orchard,omidnasri/Orchard,brownjordaninternational/OrchardCMS,SouleDesigns/SouleDesigns.Orchard,abhishekluv/Orchard,AdvantageCS/Orchard,Fogolan/OrchardForWork,IDeliverable/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,OrchardCMS/Orchard,Serlead/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,bedegaming-aleksej/Orchard,xkproject/Orchard,dmitry-urenev/extended-orchard-cms-v10.1,dmitry-urenev/extended-orchard-cms-v10.1,jchenga/Orchard,ehe888/Orchard,ehe888/Orchard,AdvantageCS/Orchard,tobydodds/folklife,xkproject/Orchard,AdvantageCS/Orchard,OrchardCMS/Orchard,fassetar/Orchard,jtkech/Orchard,bedegaming-aleksej/Orchard,Praggie/Orchard,Fogolan/OrchardForWork,brownjordaninternational/OrchardCMS,tobydodds/folklife,yersans/Orchard,gcsuk/Orchard,fassetar/Orchard,Lombiq/Orchard,jchenga/Orchard,Codinlab/Orchard,sfmskywalker/Orchard,SouleDesigns/SouleDesigns.Orchard,LaserSrl/Orchard,jchenga/Orchard,omidnasri/Orchard,hannan-azam/Orchard,fassetar/Orchard
src/Orchard.Web/Modules/Lucene/Models/LuceneSearchHit.cs
src/Orchard.Web/Modules/Lucene/Models/LuceneSearchHit.cs
using System; using Lucene.Net.Documents; using Orchard.Indexing; namespace Lucene.Models { public class LuceneSearchHit : ISearchHit { private readonly Document _doc; private readonly float _score; public float Score { get { return _score; } } public LuceneSearchHit(Document document, float score) { _doc = document; _score = score; } public int ContentItemId { get { return GetInt("id"); } } public int GetInt(string name) { var field = _doc.GetField(name); return field == null ? 0 : Int32.Parse(field.StringValue); } public double GetDouble(string name) { var field = _doc.GetField(name); return field == null ? 0 : double.Parse(field.StringValue); } public bool GetBoolean(string name) { return GetInt(name) > 0; } public string GetString(string name) { var field = _doc.GetField(name); return field == null ? null : field.StringValue; } public DateTime GetDateTime(string name) { var field = _doc.GetField(name); return field == null ? DateTime.MinValue : DateTools.StringToDate(field.StringValue); } } }
using System; using Lucene.Net.Documents; using Orchard.Indexing; namespace Lucene.Models { public class LuceneSearchHit : ISearchHit { private readonly Document _doc; private readonly float _score; public float Score { get { return _score; } } public LuceneSearchHit(Document document, float score) { _doc = document; _score = score; } public int ContentItemId { get { return int.Parse(GetString("id")); } } public int GetInt(string name) { var field = _doc.GetField(name); return field == null ? 0 : Int32.Parse(field.StringValue); } public double GetDouble(string name) { var field = _doc.GetField(name); return field == null ? 0 : double.Parse(field.StringValue); } public bool GetBoolean(string name) { return GetInt(name) > 0; } public string GetString(string name) { var field = _doc.GetField(name); return field == null ? null : field.StringValue; } public DateTime GetDateTime(string name) { var field = _doc.GetField(name); return field == null ? DateTime.MinValue : DateTools.StringToDate(field.StringValue); } } }
bsd-3-clause
C#
255e7bf66084b9358324b6dea56f93bff2e525fc
Implement autoreconnect class
IvionSauce/MeidoBot
MeidoBot/AutoReconnect.cs
MeidoBot/AutoReconnect.cs
using System; using System.Threading; using Meebey.SmartIrc4net; namespace MeidoBot { class AutoReconnect { readonly static TimeSpan minInterval = TimeSpan.FromSeconds(15); readonly static TimeSpan maxInterval = TimeSpan.FromMinutes(32); TimeSpan currentInterval = minInterval; readonly IrcClient irc; string[] serverAddresses; int serverPort; public AutoReconnect(IrcClient irc) { irc.OnConnectionError += OnConnectionError; this.irc = irc; } public void SuccessfulConnect() { currentInterval = minInterval; serverAddresses = new string[irc.AddressList.Length]; irc.AddressList.CopyTo(serverAddresses, 0); serverPort = irc.Port; } void OnConnectionError(object sender, EventArgs e) { try { irc.Disconnect(); } catch (NotConnectedException) { // Well, we're disconnected. Which is the state we want to be in. } EndlessReconnect(); } void EndlessReconnect() { while (!irc.IsConnected) { var reconnectInterval = currentInterval; currentInterval = NewInterval(currentInterval); Thread.Sleep(reconnectInterval); try { irc.Connect(serverAddresses, serverPort); } catch (CouldNotConnectException) { // We'll keep retrying with an increasing interval. } } } static TimeSpan NewInterval(TimeSpan interval) { if (interval < maxInterval) { var newInterval = TimeSpan.FromSeconds(interval.TotalSeconds * 2); if (newInterval <= maxInterval) return newInterval; } return maxInterval; } } }
using System; namespace MeidoBot { public class AutoReconnect { public AutoReconnect () { } } }
bsd-2-clause
C#
f83c5fa81d8f5291e0c3d75b37e65a35ec8b2a8a
Add backing bindable for major field
smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu-new,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu,ppy/osu,peppy/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu
osu.Game.Rulesets.Taiko/Objects/BarLine.cs
osu.Game.Rulesets.Taiko/Objects/BarLine.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.Bindables; using osu.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Taiko.Objects { public class BarLine : TaikoHitObject, IBarLine { public bool Major { get => MajorBindable.Value; set => MajorBindable.Value = value; } public readonly Bindable<bool> MajorBindable = new BindableBool(); public override Judgement CreateJudgement() => new IgnoreJudgement(); } }
// 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.Game.Rulesets.Judgements; using osu.Game.Rulesets.Objects; namespace osu.Game.Rulesets.Taiko.Objects { public class BarLine : TaikoHitObject, IBarLine { public bool Major { get; set; } public override Judgement CreateJudgement() => new IgnoreJudgement(); } }
mit
C#
a5b0307cfb472342bb56a08548b8245d7a8604be
Apply same fix to legacy accuracy counter
UselessToucan/osu,NeoAdonis/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,peppy/osu,smoogipooo/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,smoogipoo/osu,ppy/osu
osu.Game/Skinning/LegacyAccuracyCounter.cs
osu.Game/Skinning/LegacyAccuracyCounter.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osuTK; namespace osu.Game.Skinning { public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter { private readonly ISkin skin; public LegacyAccuracyCounter(ISkin skin) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; Scale = new Vector2(0.6f); Margin = new MarginPadding(10); this.skin = skin; } [Resolved(canBeNull: true)] private HUDOverlay hud { get; set; } protected sealed override OsuSpriteText CreateSpriteText() => (OsuSpriteText)skin?.GetDrawableComponent(new HUDSkinComponent(HUDSkinComponents.ScoreText)) ?.With(s => s.Anchor = s.Origin = Anchor.TopRight); protected override void Update() { base.Update(); if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score) { // for now align with the score counter. eventually this will be user customisable. Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y; } } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Screens.Play; using osu.Game.Screens.Play.HUD; using osuTK; namespace osu.Game.Skinning { public class LegacyAccuracyCounter : PercentageCounter, IAccuracyCounter { private readonly ISkin skin; public LegacyAccuracyCounter(ISkin skin) { Anchor = Anchor.TopRight; Origin = Anchor.TopRight; Scale = new Vector2(0.6f); Margin = new MarginPadding(10); this.skin = skin; } [Resolved(canBeNull: true)] private HUDOverlay hud { get; set; } protected sealed override OsuSpriteText CreateSpriteText() => (OsuSpriteText)skin?.GetDrawableComponent(new HUDSkinComponent(HUDSkinComponents.ScoreText)); protected override void Update() { base.Update(); if (hud?.ScoreCounter.Drawable is LegacyScoreCounter score) { // for now align with the score counter. eventually this will be user customisable. Y = Parent.ToLocalSpace(score.ScreenSpaceDrawQuad.BottomRight).Y; } } } }
mit
C#
558ca5ec4616176048f3fbbf3ecab59d7d8d67bd
Fix bug in BodyCollider.
jguarShark/Unity2D-Components,cmilr/Unity2D-Components
Actor/BodyCollider.cs
Actor/BodyCollider.cs
using UnityEngine; using System.Collections; using Matcha.Lib; [RequireComponent(typeof(BoxCollider2D))] public class BodyCollider : CacheBehaviour { private bool alreadyCollided; private PickupEntity pickupEntity; private EntityBehaviour entityBehaviour; // private CharacterEntity charEntity; void Start() { base.CacheComponents(); MLib2D.IgnoreLayerCollisionWith(gameObject, "One-Way Platform", true); MLib2D.IgnoreLayerCollisionWith(gameObject, "Platform", true); } void OnTriggerEnter2D(Collider2D coll) { GetColliderComponents(coll); if (coll.tag == "Prize" && !alreadyCollided) { Messenger.Broadcast<int>("prize collected", pickupEntity.worth); pickupEntity.React(); } if (coll.tag == "Enemy" && !alreadyCollided) { Messenger.Broadcast<string, Collider2D>("player dead", "StruckDown", coll); } if (coll.tag == "Water" && !alreadyCollided) { Messenger.Broadcast<string, Collider2D>("player dead", "Drowned", coll); } if (coll.tag == "Wall") { Messenger.Broadcast<bool>("touching wall", true); } } void OnTriggerExit2D(Collider2D coll) { if (coll.tag == "Wall") { Messenger.Broadcast<bool>("touching wall", false); } } void GetColliderComponents(Collider2D coll) { pickupEntity = coll.GetComponent<PickupEntity>() as PickupEntity; // charEntity = coll.GetComponent<CharacterEntity>() as CharacterEntity; if (coll.GetComponent<EntityBehaviour>()) { entityBehaviour = coll.GetComponent<EntityBehaviour>(); alreadyCollided = entityBehaviour.alreadyCollided; } } }
using UnityEngine; using System.Collections; using Matcha.Lib; [RequireComponent(typeof(BoxCollider2D))] public class BodyCollider : CacheBehaviour { private bool alreadyCollided; private PickupEntity pickupEntity; private EntityBehaviour entityBehaviour; // private CharacterEntity charEntity; void Start() { base.CacheComponents(); MLib2D.IgnoreLayerCollisionWith(gameObject, "One-Way Platform", true); MLib2D.IgnoreLayerCollisionWith(gameObject, "Platform", true); } void OnTriggerEnter2D(Collider2D coll) { GetColliderComponents(coll); if (coll.tag == "Prize" && !alreadyCollided) { Messenger.Broadcast<int>("prize collected", pickupEntity.worth); pickupEntity.React(); } if (coll.tag == "Enemy" && !alreadyCollided) { Messenger.Broadcast<string, Collider2D>("player dead", "StruckDown", coll); } if (coll.tag == "Water" && !alreadyCollided) { Messenger.Broadcast<string, Collider2D>("player dead", "Drowned", coll); } if (coll.tag == "Wall") { Messenger.Broadcast<bool>("touching wall", true); } } void GetColliderComponents(Collider2D coll) { pickupEntity = coll.GetComponent<PickupEntity>() as PickupEntity; // charEntity = coll.GetComponent<CharacterEntity>() as CharacterEntity; if (coll.GetComponent<EntityBehaviour>()) { entityBehaviour = coll.GetComponent<EntityBehaviour>(); alreadyCollided = entityBehaviour.alreadyCollided; } } }
mit
C#
e22f4409099619194187dd1b4e8688443fee1f4d
Apply velocity based on rotational value
bastuijnman/open-park
Assets/Scripts/Player.cs
Assets/Scripts/Player.cs
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Movement speed, can be set in the editor public float speed = 1.0f; // Player (camera) rotation private Vector3 playerRotation = new Vector3 (35, 0, 0); // Player (camera) height private float playerHeight = 5.0f; void Start () { // Setup the player camera Camera camera = gameObject.AddComponent<Camera> (); // This is probably stupid to do gameObject.tag = "MainCamera"; } void Update () { float horizontalMovement = Input.GetAxis ("Horizontal"); float verticalMovement = Input.GetAxis ("Vertical"); float rotationMovement = 0.0f; // Handle camera rotation if (Input.GetKey (KeyCode.Q)) { rotationMovement = -1.0f; } else if (Input.GetKey (KeyCode.E)) { rotationMovement = 1.0f; } playerRotation.y += rotationMovement * (speed / 2); // Calculate movement velocity Vector3 velocityVertical = transform.forward * speed * verticalMovement; Vector3 velocityHorizontal = transform.right * speed * horizontalMovement; Vector3 calculatedVelocity = velocityHorizontal + velocityVertical; calculatedVelocity.y = 0.0f; // Apply calculated velocity GetComponent<Rigidbody>().velocity = calculatedVelocity; // Keep position with a variable height transform.position = new Vector3 (transform.position.x, playerHeight, transform.position.z); // Set player rotation transform.rotation = Quaternion.Euler (playerRotation); } }
using UnityEngine; using System.Collections; public class Player : MonoBehaviour { // Movement speed, can be set in the editor public float speed = 1.0f; // Player (camera) rotation private Vector3 playerRotation = new Vector3 (35, 0, 0); // Player (camera) height private float playerHeight = 5.0f; void Start () { // Setup the player camera Camera camera = gameObject.AddComponent<Camera> (); } void Update () { float horizontalMovement = Input.GetAxis ("Horizontal"); float verticalMovement = Input.GetAxis ("Vertical"); float rotationMovement = 0.0f; // Handle camera rotation if (Input.GetKey (KeyCode.Q)) { rotationMovement = -1.0f; } else if (Input.GetKey (KeyCode.E)) { rotationMovement = 1.0f; } playerRotation.y += rotationMovement * (speed / 2); // Handle movement on the terrain Vector3 movement = new Vector3 (horizontalMovement, 0.0f, verticalMovement); GetComponent<Rigidbody>().velocity = movement * speed; // Keep position with a variable height transform.position = new Vector3 (transform.position.x, playerHeight, transform.position.z); // Set player rotation transform.rotation = Quaternion.Euler (playerRotation); } }
mit
C#
8aeb2693cab358d7bd411f6b559a53957fb8ad8f
fix flags
bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL
CSharpGL4/Scene/Flags.cs
CSharpGL4/Scene/Flags.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { /// <summary> /// /// </summary> [Flags] public enum TwoFlags : byte { /// <summary> /// /// </summary> None = 0, /// <summary> /// /// </summary> BeforeChildren = 2, /// <summary> /// /// </summary> Children = 4, } /// <summary> /// /// </summary> [Flags] public enum ThreeFlags : byte { /// <summary> /// /// </summary> None = 0, /// <summary> /// /// </summary> BeforeChildren = 2, /// <summary> /// /// </summary> Children = 4, /// <summary> /// /// </summary> AfterChildren = 8, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { /// <summary> /// /// </summary> [Flags] public enum TwoFlags : byte { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> BeforeChildren, /// <summary> /// /// </summary> Children, } /// <summary> /// /// </summary> [Flags] public enum ThreeFlags : byte { /// <summary> /// /// </summary> None, /// <summary> /// /// </summary> BeforeChildren, /// <summary> /// /// </summary> Children, /// <summary> /// /// </summary> AfterChildren, } }
mit
C#
0741d618febe2b433b08573e2139c4d5b9f4b0dd
remove extra argument I was not using
mschray/CalendarHelper
shared/LogHelper.csx
shared/LogHelper.csx
public static class LogHelper { private static TraceWriter logger; public static void Initialize(TraceWriter log) { if (logger == null) logger = log; } public static void Info(string logtext) { logger.Info(logtext); } public static void Error(string logtext) { logger.Error(logtext); } }
public static class LogHelper { private static TraceWriter logger; public static void Initialize(TraceWriter log) { if (logger == null) logger = log; } public static void Info(TraceWriter log, string logtext) { logger.Info(logtext); } public static void Error(TraceWriter log, string logtext) { logger.Error(logtext); } }
mit
C#
c792ff072ce10e32d0782610ec7027f3183d4828
increment patch version,
jwChung/Experimentalism,jwChung/Experimentalism
build/CommonAssemblyInfo.cs
build/CommonAssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.18.1")] [assembly: AssemblyInformationalVersion("0.18.1")] /* * Version 0.18.1 * * - [FIX-BREAKING-CHANGE] Renames some extension methods to clarify. * ToMembers -> GetIdiomaticMembers * * - [FIX-BREAKING-CHANGE] Renames `TypeMembers` to `IdiomaticMembers` to * clarify. * * - [FIX] Fixes the error for private accessors of a property in * `MemberKindCollector`. * * - [FIX-BREAKING-CHANGE] Simplifies the constructor of `IdiomaticMembers`. */
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Jin-Wook Chung")] [assembly: AssemblyCopyright("Copyright (c) 2014, Jin-Wook Chung")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyProduct("")] [assembly: AssemblyVersion("0.18.0")] [assembly: AssemblyInformationalVersion("0.18.0")] /* * Version 0.18.1 * * - [FIX-BREAKING-CHANGE] Renames some extension methods to clarify. * ToMembers -> GetIdiomaticMembers * * - [FIX-BREAKING-CHANGE] Renames `TypeMembers` to `IdiomaticMembers` to * clarify. * * - [FIX] Fixes the error for private accessors of a property in * `MemberKindCollector`. * * - [FIX-BREAKING-CHANGE] Simplifies the constructor of `IdiomaticMembers`. */
mit
C#
4e5ddea40188ffb027c392ed139eeb412c354631
Update completion triggers in LSP to better match local completion.
physhi/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,ErikSchierboom/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,wvdd007/roslyn,genlu/roslyn,aelij/roslyn,bartdesmet/roslyn,AmadeusW/roslyn,AlekseyTs/roslyn,stephentoub/roslyn,genlu/roslyn,weltkante/roslyn,bartdesmet/roslyn,sharwell/roslyn,diryboy/roslyn,gafter/roslyn,reaction1989/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,dotnet/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,davkean/roslyn,panopticoncentral/roslyn,KevinRansom/roslyn,eriawan/roslyn,brettfo/roslyn,heejaechang/roslyn,physhi/roslyn,panopticoncentral/roslyn,dotnet/roslyn,tmat/roslyn,AmadeusW/roslyn,brettfo/roslyn,tmat/roslyn,tmat/roslyn,jmarolf/roslyn,jmarolf/roslyn,AlekseyTs/roslyn,sharwell/roslyn,davkean/roslyn,physhi/roslyn,heejaechang/roslyn,gafter/roslyn,aelij/roslyn,stephentoub/roslyn,tannergooding/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,weltkante/roslyn,reaction1989/roslyn,tannergooding/roslyn,diryboy/roslyn,wvdd007/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,stephentoub/roslyn,mavasani/roslyn,ErikSchierboom/roslyn,jmarolf/roslyn,KevinRansom/roslyn,genlu/roslyn,KirillOsenkov/roslyn,davkean/roslyn,jasonmalinowski/roslyn,gafter/roslyn,eriawan/roslyn,diryboy/roslyn,sharwell/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,reaction1989/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,aelij/roslyn,mavasani/roslyn
src/Features/LanguageServer/Protocol/Handler/Initialize/InitializeHandler.cs
src/Features/LanguageServer/Protocol/Handler/Initialize/InitializeHandler.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [Shared] [ExportLspMethod(Methods.InitializeName)] internal class InitializeHandler : IRequestHandler<InitializeParams, InitializeResult> { private static readonly InitializeResult s_initializeResult = new InitializeResult { Capabilities = new ServerCapabilities { DefinitionProvider = true, ImplementationProvider = true, CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new[] { ".", " ", "#", "<", ">", "\"", ":", "[", "(", "~" } }, SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { "(", "," } }, DocumentSymbolProvider = true, WorkspaceSymbolProvider = true, DocumentFormattingProvider = true, DocumentRangeFormattingProvider = true, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "}", MoreTriggerCharacter = new[] { ";", "\n" } }, DocumentHighlightProvider = true, } }; public Task<InitializeResult> HandleRequestAsync(Solution solution, InitializeParams request, ClientCapabilities clientCapabilities, CancellationToken cancellationToken) => Task.FromResult(s_initializeResult); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.Handler { [Shared] [ExportLspMethod(Methods.InitializeName)] internal class InitializeHandler : IRequestHandler<InitializeParams, InitializeResult> { private static readonly InitializeResult s_initializeResult = new InitializeResult { Capabilities = new ServerCapabilities { DefinitionProvider = true, ImplementationProvider = true, CompletionProvider = new CompletionOptions { ResolveProvider = true, TriggerCharacters = new[] { "." } }, SignatureHelpProvider = new SignatureHelpOptions { TriggerCharacters = new[] { "(", "," } }, DocumentSymbolProvider = true, WorkspaceSymbolProvider = true, DocumentFormattingProvider = true, DocumentRangeFormattingProvider = true, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions { FirstTriggerCharacter = "}", MoreTriggerCharacter = new[] { ";", "\n" } }, DocumentHighlightProvider = true, } }; public Task<InitializeResult> HandleRequestAsync(Solution solution, InitializeParams request, ClientCapabilities clientCapabilities, CancellationToken cancellationToken) => Task.FromResult(s_initializeResult); } }
mit
C#
caad842d84849150200be2e2d23466e90c456ccf
Add comment.
brettfo/roslyn,tannergooding/roslyn,lorcanmooney/roslyn,AlekseyTs/roslyn,MattWindsor91/roslyn,agocke/roslyn,tvand7093/roslyn,OmarTawfik/roslyn,Hosch250/roslyn,srivatsn/roslyn,lorcanmooney/roslyn,heejaechang/roslyn,jamesqo/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,VSadov/roslyn,sharwell/roslyn,diryboy/roslyn,sharwell/roslyn,bkoelman/roslyn,Hosch250/roslyn,ErikSchierboom/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,cston/roslyn,jamesqo/roslyn,KirillOsenkov/roslyn,orthoxerox/roslyn,swaroop-sridhar/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,VSadov/roslyn,paulvanbrenk/roslyn,kelltrick/roslyn,tmeschter/roslyn,jasonmalinowski/roslyn,nguerrera/roslyn,khyperia/roslyn,abock/roslyn,paulvanbrenk/roslyn,tmat/roslyn,swaroop-sridhar/roslyn,mattscheffer/roslyn,gafter/roslyn,OmarTawfik/roslyn,srivatsn/roslyn,ErikSchierboom/roslyn,brettfo/roslyn,cston/roslyn,AlekseyTs/roslyn,dpoeschl/roslyn,paulvanbrenk/roslyn,AnthonyDGreen/roslyn,abock/roslyn,TyOverby/roslyn,eriawan/roslyn,tmeschter/roslyn,eriawan/roslyn,weltkante/roslyn,jmarolf/roslyn,CyrusNajmabadi/roslyn,tvand7093/roslyn,gafter/roslyn,heejaechang/roslyn,swaroop-sridhar/roslyn,DustinCampbell/roslyn,tmat/roslyn,pdelvo/roslyn,srivatsn/roslyn,reaction1989/roslyn,reaction1989/roslyn,AlekseyTs/roslyn,orthoxerox/roslyn,nguerrera/roslyn,CaptainHayashi/roslyn,VSadov/roslyn,robinsedlaczek/roslyn,xasx/roslyn,brettfo/roslyn,shyamnamboodiripad/roslyn,bkoelman/roslyn,agocke/roslyn,jasonmalinowski/roslyn,gafter/roslyn,xasx/roslyn,Giftednewt/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,cston/roslyn,KirillOsenkov/roslyn,panopticoncentral/roslyn,CaptainHayashi/roslyn,khyperia/roslyn,jcouv/roslyn,agocke/roslyn,aelij/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,wvdd007/roslyn,kelltrick/roslyn,CaptainHayashi/roslyn,dotnet/roslyn,tmat/roslyn,Hosch250/roslyn,physhi/roslyn,stephentoub/roslyn,reaction1989/roslyn,jkotas/roslyn,genlu/roslyn,stephentoub/roslyn,mavasani/roslyn,davkean/roslyn,weltkante/roslyn,eriawan/roslyn,wvdd007/roslyn,davkean/roslyn,TyOverby/roslyn,Giftednewt/roslyn,KevinRansom/roslyn,khyperia/roslyn,diryboy/roslyn,dpoeschl/roslyn,robinsedlaczek/roslyn,MichalStrehovsky/roslyn,MichalStrehovsky/roslyn,nguerrera/roslyn,genlu/roslyn,wvdd007/roslyn,sharwell/roslyn,AmadeusW/roslyn,orthoxerox/roslyn,shyamnamboodiripad/roslyn,lorcanmooney/roslyn,abock/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,dotnet/roslyn,TyOverby/roslyn,dpoeschl/roslyn,bartdesmet/roslyn,kelltrick/roslyn,tmeschter/roslyn,robinsedlaczek/roslyn,physhi/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mmitche/roslyn,diryboy/roslyn,mmitche/roslyn,heejaechang/roslyn,MattWindsor91/roslyn,jcouv/roslyn,genlu/roslyn,jmarolf/roslyn,bkoelman/roslyn,jamesqo/roslyn,mattscheffer/roslyn,pdelvo/roslyn,jkotas/roslyn,mattscheffer/roslyn,mgoertz-msft/roslyn,mavasani/roslyn,tannergooding/roslyn,MattWindsor91/roslyn,xasx/roslyn,stephentoub/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,CyrusNajmabadi/roslyn,jkotas/roslyn,davkean/roslyn,bartdesmet/roslyn,physhi/roslyn,aelij/roslyn,aelij/roslyn,KevinRansom/roslyn,AnthonyDGreen/roslyn,DustinCampbell/roslyn,bartdesmet/roslyn,jcouv/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,MichalStrehovsky/roslyn,Giftednewt/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,tannergooding/roslyn,MattWindsor91/roslyn,tvand7093/roslyn,jmarolf/roslyn,AnthonyDGreen/roslyn,AmadeusW/roslyn,mavasani/roslyn,panopticoncentral/roslyn,pdelvo/roslyn
src/Workspaces/Core/Portable/CodeActions/Annotations/NavigationAnnotation.cs
src/Workspaces/Core/Portable/CodeActions/Annotations/NavigationAnnotation.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Apply this annotation to an appropriate Syntax element to request that it should be /// navigated to by the user after a code action is applied. If present the host should /// try to place the user's caret at the beginning of the element. /// </summary> /// <remarks> /// By using a <see cref="SyntaxAnnotation"/> this navigation location will be resilient /// to the transformations performed by the <see cref="CodeAction"/> infrastructure. /// Namely it will be resilient to the formatting, reduction or case correction that /// automatically occures. This allows a code action to specify a desired location for /// the user caret to be placed without knowing what actual position that location will /// end up at when the action is finally applied. /// </remarks> internal static class NavigationAnnotation { public const string Kind = "CodeAction_Navigation"; public static SyntaxAnnotation Create() => new SyntaxAnnotation(Kind); } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Microsoft.CodeAnalysis.CodeActions { /// <summary> /// Apply this annotation to an appropriate Syntax element to request that it should be /// navigated to by the user after the action. /// </summary> internal static class NavigationAnnotation { public const string Kind = "CodeAction_Navigation"; public static SyntaxAnnotation Create() => new SyntaxAnnotation(Kind); } }
apache-2.0
C#
b908670cac139d427777c103c4a4dd1c5e9dac1a
Prepare for removing `workFolderPath` & `network` parameters from the class's constructor
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Stores/BitcoinStore.cs
WalletWasabi/Stores/BitcoinStore.cs
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using WalletWasabi.Blockchain.Blocks; using WalletWasabi.Blockchain.Mempool; using WalletWasabi.Blockchain.P2p; using WalletWasabi.Blockchain.Transactions; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Stores { /// <summary> /// The purpose of this class is to safely and performantly manage all the Bitcoin related data /// that's being serialized to disk, like transactions, wallet files, keys, blocks, index files, etc... /// </summary> public class BitcoinStore { public BitcoinStore( string workFolderPath, Network network, IndexStore indexStore, AllTransactionStore transactionStore, MempoolService mempoolService) { var workFolderPath2 = Guard.NotNullOrEmptyOrWhitespace(nameof(workFolderPath), workFolderPath, trim: true); IoHelpers.EnsureDirectoryExists(workFolderPath2); Guard.NotNull(nameof(network), network); NetworkWorkFolderPath = Path.Combine(workFolderPath2, network.ToString()); IndexStoreFolderPath = Path.Combine(NetworkWorkFolderPath, "IndexStore"); IndexStore = indexStore; TransactionStore = transactionStore; MempoolService = mempoolService; } public bool IsInitialized { get; private set; } private string NetworkWorkFolderPath { get; } private string IndexStoreFolderPath { get; } public IndexStore IndexStore { get; } public AllTransactionStore TransactionStore { get; } public SmartHeaderChain SmartHeaderChain => IndexStore.SmartHeaderChain; public MempoolService MempoolService { get; } /// <summary> /// This should not be a property, but a creator function, because it'll be cloned left and right by NBitcoin later. /// So it should not be assumed it's some singleton. /// </summary> public UntrustedP2pBehavior CreateUntrustedP2pBehavior() => new UntrustedP2pBehavior(MempoolService); public async Task InitializeAsync() { using (BenchmarkLogger.Measure()) { var initTasks = new[] { IndexStore.InitializeAsync(IndexStoreFolderPath), TransactionStore.InitializeAsync(NetworkWorkFolderPath) }; await Task.WhenAll(initTasks).ConfigureAwait(false); IsInitialized = true; } } } }
using NBitcoin; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using WalletWasabi.Blockchain.Blocks; using WalletWasabi.Blockchain.Mempool; using WalletWasabi.Blockchain.P2p; using WalletWasabi.Blockchain.Transactions; using WalletWasabi.Helpers; using WalletWasabi.Logging; namespace WalletWasabi.Stores { /// <summary> /// The purpose of this class is to safely and performantly manage all the Bitcoin related data /// that's being serialized to disk, like transactions, wallet files, keys, blocks, index files, etc... /// </summary> public class BitcoinStore { public BitcoinStore( string workFolderPath, Network network, IndexStore indexStore, AllTransactionStore transactionStore, MempoolService mempoolService) { WorkFolderPath = Guard.NotNullOrEmptyOrWhitespace(nameof(workFolderPath), workFolderPath, trim: true); IoHelpers.EnsureDirectoryExists(WorkFolderPath); Network = Guard.NotNull(nameof(network), network); IndexStore = indexStore; TransactionStore = transactionStore; MempoolService = mempoolService; } public bool IsInitialized { get; private set; } private string WorkFolderPath { get; } public Network Network { get; } public IndexStore IndexStore { get; } public AllTransactionStore TransactionStore { get; } public SmartHeaderChain SmartHeaderChain => IndexStore.SmartHeaderChain; public MempoolService MempoolService { get; } /// <summary> /// This should not be a property, but a creator function, because it'll be cloned left and right by NBitcoin later. /// So it should not be assumed it's some singleton. /// </summary> public UntrustedP2pBehavior CreateUntrustedP2pBehavior() => new UntrustedP2pBehavior(MempoolService); public async Task InitializeAsync() { using (BenchmarkLogger.Measure()) { var networkWorkFolderPath = Path.Combine(WorkFolderPath, Network.ToString()); var indexStoreFolderPath = Path.Combine(networkWorkFolderPath, "IndexStore"); var initTasks = new[] { IndexStore.InitializeAsync(indexStoreFolderPath), TransactionStore.InitializeAsync(networkWorkFolderPath) }; await Task.WhenAll(initTasks).ConfigureAwait(false); IsInitialized = true; } } } }
mit
C#
802ae6daffbe96d18c34fcdb5cd9682ab79fc88f
Add MRound
imasm/CSharpExtensions
CSharpEx/DoubleEx.cs
CSharpEx/DoubleEx.cs
using System; namespace CSharpEx { /// <summary> /// Double extensions /// </summary> public static class DoubleEx { /// <summary> /// Compare two double values. Returns true if the diference is lower than tolerance /// </summary> /// <param name="value1">First double value</param> /// <param name="value2">Second double value</param> /// <param name="tolerance">Tolerance permitted</param> /// <returns>True if values are closer.</returns> public static bool AreEqual(this double value1, double value2, double tolerance = double.Epsilon) { return (Math.Abs(value1 - value2) < tolerance); } /// <summary> /// Compare two double values. /// Uses the BitConverter.DoubleToInt64Bits method to convert a double-precision floating-point value to its integer representation. /// </summary> /// <param name="value1">First double value</param> /// <param name="value2">Second double value</param> /// <param name="units">Units used as tolerance</param> /// <returns>True if values are closer.</returns> public static bool HasMinimalDifference(this double value1, double value2, int units = 1) { long lValue1 = BitConverter.DoubleToInt64Bits(value1); long lValue2 = BitConverter.DoubleToInt64Bits(value2); // If the signs are different, return false except for +0 and -0. if ((lValue1 >> 63) != (lValue2 >> 63)) { if (value1 == value2) return true; return false; } long diff = Math.Abs(lValue1 - lValue2); if (diff <= (long)units) return true; return false; } /// <summary> /// Returns a number rounded to the desired multiple /// </summary> public static double MRound(this double value, double divisor) { return Math.Truncate(value / divisor) * divisor; } } }
using System; namespace CSharpEx { /// <summary> /// Double extensions /// </summary> public static class DoubleEx { /// <summary> /// Compare two double values. Returns true if the diference is lower than tolerance /// </summary> /// <param name="value1">First double value</param> /// <param name="value2">Second double value</param> /// <param name="tolerance">Tolerance permitted</param> /// <returns>True if values are closer.</returns> public static bool AreEqual(this double value1, double value2, double tolerance = double.Epsilon) { return (Math.Abs(value1 - value2) < tolerance); } /// <summary> /// Compare two double values. /// Uses the BitConverter.DoubleToInt64Bits method to convert a double-precision floating-point value to its integer representation. /// </summary> /// <param name="value1">First double value</param> /// <param name="value2">Second double value</param> /// <param name="units">Units used as tolerance</param> /// <returns>True if values are closer.</returns> public static bool HasMinimalDifference(this double value1, double value2, int units = 1) { long lValue1 = BitConverter.DoubleToInt64Bits(value1); long lValue2 = BitConverter.DoubleToInt64Bits(value2); // If the signs are different, return false except for +0 and -0. if ((lValue1 >> 63) != (lValue2 >> 63)) { if (value1 == value2) return true; return false; } long diff = Math.Abs(lValue1 - lValue2); if (diff <= (long)units) return true; return false; } } }
apache-2.0
C#
baf0fb2f836cefb149f44598096c8d41dacf3d9b
Update test to check that breadcrumbs are returned in correct order when MaximumBreadcrumbs is exceeded
bugsnag/bugsnag-dotnet,bugsnag/bugsnag-dotnet
tests/Bugsnag.Tests/BreadcrumbsTests.cs
tests/Bugsnag.Tests/BreadcrumbsTests.cs
using System.Linq; using Xunit; namespace Bugsnag.Tests { public class BreadcrumbsTests { [Fact] public void RestrictsMaxNumberOfBreadcrumbs() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 30; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(25, breadcrumbs.Retrieve().Count()); } [Fact] public void WhenRetrievingBreadcrumbsCorrectNumberIsReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(10, breadcrumbs.Retrieve().Count()); } [Fact] public void CorrectBreadcrumbsAreReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 5 }); for (int i = 0; i < 6; i++) { breadcrumbs.Leave($"{i}"); } var breadcrumbNames = breadcrumbs.Retrieve().Select(b => b.Name); Assert.Equal(new string[] { "1", "2", "3", "4", "5" }, breadcrumbNames); } } }
using System.Linq; using Xunit; namespace Bugsnag.Tests { public class BreadcrumbsTests { [Fact] public void RestrictsMaxNumberOfBreadcrumbs() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 30; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(25, breadcrumbs.Retrieve().Count()); } [Fact] public void WhenRetrievingBreadcrumbsCorrectNumberIsReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 25 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } Assert.Equal(10, breadcrumbs.Retrieve().Count()); } [Fact] public void CorrectBreadcrumbsAreReturned() { var breadcrumbs = new Breadcrumbs(new Configuration { MaximumBreadcrumbs = 5 }); for (int i = 0; i < 10; i++) { breadcrumbs.Leave($"{i}"); } var breadcrumbNames = breadcrumbs.Retrieve().Select(b => b.Name); Assert.Equal(new string[] { "5", "6", "7", "8", "9" }, breadcrumbNames); } } }
mit
C#
09290e346d44a58c1406e1060847fd50a0b5d10d
change default e-mail and username
tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web
src/Tugberk.Web/BlogDbContextExtensions.cs
src/Tugberk.Web/BlogDbContextExtensions.cs
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Tugberk.Persistance.SqlServer; namespace Tugberk.Web { public static class BlogDbContextExtensions { public static void EnsureSeedData(this BlogDbContext context, UserManager<IdentityUser> userManager) { if(!context.Users.AnyAsync().Result) { var defaultUser = new IdentityUser { UserName = "default@example.com", Email = "default@example.com" }; userManager.CreateAsync(defaultUser, "P@asW0rd").Wait(); } } } }
using Microsoft.AspNetCore.Identity; using Microsoft.EntityFrameworkCore; using Tugberk.Persistance.SqlServer; namespace Tugberk.Web { public static class BlogDbContextExtensions { public static void EnsureSeedData(this BlogDbContext context, UserManager<IdentityUser> userManager) { if(!context.Users.AnyAsync().Result) { var defaultUser = new IdentityUser { UserName = "default", Email = "foo@example.com" }; userManager.CreateAsync(defaultUser, "P@asW0rd").Wait(); } } } }
agpl-3.0
C#
355f3162617a70e8c3fe068a9ea16a123e930e8c
allow running as a console app
abock/conservatorio,abock/conservatorio,abock/conservatorio
Conservatorio.Mac/Main.cs
Conservatorio.Mac/Main.cs
// // Main.cs // // Author: // Aaron Bockover <aaron.bockover@gmail.com> // // Copyright 2015 Aaron Bockover. All rights reserved. // // 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.IO; using System.Threading; using Foundation; using AppKit; namespace Conservatorio.Mac { static class MainClass { static int Main (string[] args) { NSApplication.Init (); if (args.Length > 0) { // the init above will set this thread's sync context to // integrate with NSRunLoop, which we do not want SynchronizationContext.SetSynchronizationContext (null); return new ConsoleApp ().Main (args); } var sparkleFx = Path.Combine (NSBundle.MainBundle.BundlePath, "Contents", "Frameworks", "Sparkle.framework", "Sparkle"); ObjCRuntime.Dlfcn.dlopen (sparkleFx, 0); NSApplication.Main (new string[0]); return 0; } } }
// // Main.cs // // Author: // Aaron Bockover <aaron.bockover@gmail.com> // // Copyright 2015 Aaron Bockover. All rights reserved. // // 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.IO; using AppKit; namespace Conservatorio.Mac { static class MainClass { static void Main (string[] args) { NSApplication.Init (); var sparkleFx = Path.Combine (Foundation.NSBundle.MainBundle.BundlePath, "Contents", "Frameworks", "Sparkle.framework", "Sparkle"); ObjCRuntime.Dlfcn.dlopen (sparkleFx, 0); NSApplication.Main (args); } } }
mit
C#
12840963b2457b0dc3827925d6f5e5d70441faab
Add subscriber name
iron-io/iron_dotnet
src/IronSharp.IronMQ/Subscriber.cs
src/IronSharp.IronMQ/Subscriber.cs
using System; using System.Net; using Newtonsoft.Json; namespace IronSharp.IronMQ { public class Subscriber { public Subscriber() : this(null) { } public Subscriber(string url) { Url = url; } [JsonProperty("name", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Name { get; set; } [JsonProperty("retries_delay", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? RetriesDelay { get; set; } [JsonProperty("retries_remaining", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? RetriesRemaining { get; set; } [JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Status { get; set; } [JsonProperty("status_code", DefaultValueHandling = DefaultValueHandling.Ignore)] protected int? Code { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("error_queue", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ErrorQueue { get; set; } [JsonIgnore] public HttpStatusCode StatusCode { get { return (HttpStatusCode) Code.GetValueOrDefault(200); } } public static implicit operator Subscriber(string url) { return new Subscriber(url); } public static implicit operator Subscriber(Uri uri) { return new Subscriber(uri.ToString()); } } }
using System; using System.Net; using Newtonsoft.Json; namespace IronSharp.IronMQ { public class Subscriber { public Subscriber() : this(null) { } public Subscriber(string url) { Url = url; } [JsonProperty("retries_delay", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? RetriesDelay { get; set; } [JsonProperty("retries_remaining", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? RetriesRemaining { get; set; } [JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Status { get; set; } [JsonProperty("status_code", DefaultValueHandling = DefaultValueHandling.Ignore)] protected int? Code { get; set; } [JsonProperty("url")] public string Url { get; set; } [JsonProperty("error_queue", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ErrorQueue { get; set; } [JsonIgnore] public HttpStatusCode StatusCode { get { return (HttpStatusCode) Code.GetValueOrDefault(200); } } public static implicit operator Subscriber(string url) { return new Subscriber(url); } public static implicit operator Subscriber(Uri uri) { return new Subscriber(uri.ToString()); } } }
mit
C#
82122db3a2c64a7a0977463529e99167da2ddb8b
Use Span<char> as possible
KodamaSakuno/Sakuno.Base
src/Sakuno.Base/ArrayExtensions.cs
src/Sakuno.Base/ArrayExtensions.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Sakuno { [EditorBrowsable(EditorBrowsableState.Never)] public static class ArrayExtensions { public static unsafe string ToHexString(this byte[] bytes) { var bufferSize = bytes.Length * 2; #if NETSTANDARD2_1 Span<char> buffer = bufferSize <= 64 ? stackalloc char[bufferSize] : new char[bufferSize]; #else var buffer = new char[bufferSize]; #endif var position = 0; foreach (var b in bytes) { buffer[position++] = GetHexValue(b / 16); buffer[position++] = GetHexValue(b % 16); } return new string(buffer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] static char GetHexValue(int value) => (char)(value < 10 ? value + '0' : value - 10 + 'a'); public static bool SequenceEqual<T>(this T[] array, T[] value) => array.SequenceEqual(value, null); public static bool SequenceEqual<T>(this T[] array, T[] value, IEqualityComparer<T> comparer) { if (array == value) return true; if (array == null || value == null) return false; if (array.Length != value.Length) return false; if (comparer == null) comparer = EqualityComparer<T>.Default; for (var i = 0; i < array.Length; i++) if (!comparer.Equals(array[i], value[i])) return false; return true; } } }
using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; namespace Sakuno { [EditorBrowsable(EditorBrowsableState.Never)] public static class ArrayExtensions { public static string ToHexString(this byte[] bytes) { var buffer = new char[bytes.Length * 2]; var position = 0; foreach (var b in bytes) { buffer[position++] = GetHexValue(b / 16); buffer[position++] = GetHexValue(b % 16); } return new string(buffer); } [MethodImpl(MethodImplOptions.AggressiveInlining)] static char GetHexValue(int value) => (char)(value < 10 ? value + '0' : value - 10 + 'a'); public static bool SequenceEqual<T>(this T[] array, T[] value) => array.SequenceEqual(value, null); public static bool SequenceEqual<T>(this T[] array, T[] value, IEqualityComparer<T> comparer) { if (array == value) return true; if (array == null || value == null) return false; if (array.Length != value.Length) return false; if (comparer == null) comparer = EqualityComparer<T>.Default; for (var i = 0; i < array.Length; i++) if (!comparer.Equals(array[i], value[i])) return false; return true; } } }
mit
C#
d24c4ea2687db9bcbc15b22e5552ab1bb42451d1
fix target framework in build file.
IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4
build.cake
build.cake
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var packPath = Directory("./src/IdentityServer4"); var buildArtifacts = Directory("./artifacts/packages"); var isAppVeyor = AppVeyor.IsRunningOnAppVeyor; var isWindows = IsRunningOnWindows(); /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); /////////////////////////////////////////////////////////////////////////////// // Build /////////////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; var projects = GetFiles("./src/**/*.csproj"); foreach(var project in projects) { DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Test /////////////////////////////////////////////////////////////////////////////// Task("Test") .IsDependentOn("Clean") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration }; if (!isWindows) { Information("Not running on Windows - skipping tests for .NET Framework"); settings.Framework = "netcoreapp2.1"; } var projects = GetFiles("./test/**/*.csproj"); foreach(var project in projects) { DotNetCoreTest(project.FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = buildArtifacts, ArgumentCustomization = args => args.Append("--include-symbols") }; // add build suffix for CI builds if(isAppVeyor) { settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0'); } DotNetCorePack(packPath, settings); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Pack"); RunTarget(target);
var target = Argument("target", "Default"); var configuration = Argument<string>("configuration", "Release"); /////////////////////////////////////////////////////////////////////////////// // GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////////////// var packPath = Directory("./src/IdentityServer4"); var buildArtifacts = Directory("./artifacts/packages"); var isAppVeyor = AppVeyor.IsRunningOnAppVeyor; var isWindows = IsRunningOnWindows(); /////////////////////////////////////////////////////////////////////////////// // Clean /////////////////////////////////////////////////////////////////////////////// Task("Clean") .Does(() => { CleanDirectories(new DirectoryPath[] { buildArtifacts }); }); /////////////////////////////////////////////////////////////////////////////// // Build /////////////////////////////////////////////////////////////////////////////// Task("Build") .IsDependentOn("Clean") .Does(() => { var settings = new DotNetCoreBuildSettings { Configuration = configuration }; var projects = GetFiles("./src/**/*.csproj"); foreach(var project in projects) { DotNetCoreBuild(project.GetDirectory().FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Test /////////////////////////////////////////////////////////////////////////////// Task("Test") .IsDependentOn("Clean") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCoreTestSettings { Configuration = configuration }; if (!isWindows) { Information("Not running on Windows - skipping tests for .NET Framework"); settings.Framework = "netcoreapp2.0"; } var projects = GetFiles("./test/**/*.csproj"); foreach(var project in projects) { DotNetCoreTest(project.FullPath, settings); } }); /////////////////////////////////////////////////////////////////////////////// // Pack /////////////////////////////////////////////////////////////////////////////// Task("Pack") .IsDependentOn("Clean") .IsDependentOn("Build") .Does(() => { var settings = new DotNetCorePackSettings { Configuration = configuration, OutputDirectory = buildArtifacts, ArgumentCustomization = args => args.Append("--include-symbols") }; // add build suffix for CI builds if(isAppVeyor) { settings.VersionSuffix = "build" + AppVeyor.Environment.Build.Number.ToString().PadLeft(5,'0'); } DotNetCorePack(packPath, settings); }); Task("Default") .IsDependentOn("Build") .IsDependentOn("Test") .IsDependentOn("Pack"); RunTarget(target);
apache-2.0
C#
d05881e6c7f5e67a731720317c28d265ff35c0eb
switch to top level statements
adamralph/liteguard,adamralph/liteguard
targets/Program.cs
targets/Program.cs
using static Bullseye.Targets; using static SimpleExec.Command; Target("build", () => RunAsync("dotnet", "build --configuration Release --nologo --verbosity quiet")); Target( "pack", DependsOn("build"), ForEach("LiteGuard.nuspec", "LiteGuard.Source.nuspec"), async nuspec => await RunAsync( "dotnet", "pack LiteGuard --configuration Release --no-build --nologo", configureEnvironment: env => env.Add("NUSPEC_FILE", nuspec))); Target( "test", DependsOn("build"), () => RunAsync("dotnet", "test --configuration Release --no-build --nologo")); Target("default", DependsOn("pack", "test")); await RunTargetsAndExitAsync(args, ex => ex is SimpleExec.NonZeroExitCodeException);
using System.Threading.Tasks; using SimpleExec; using static Bullseye.Targets; using static SimpleExec.Command; internal class Program { public static Task Main(string[] args) { Target("build", () => RunAsync("dotnet", "build --configuration Release --nologo --verbosity quiet")); Target( "pack", DependsOn("build"), ForEach("LiteGuard.nuspec", "LiteGuard.Source.nuspec"), async nuspec => await RunAsync( "dotnet", "pack LiteGuard --configuration Release --no-build --nologo", configureEnvironment: env => env.Add("NUSPEC_FILE", nuspec))); Target( "test", DependsOn("build"), () => RunAsync("dotnet", "test --configuration Release --no-build --nologo")); Target("default", DependsOn("pack", "test")); return RunTargetsAndExitAsync(args, ex => ex is NonZeroExitCodeException); } }
mit
C#
daf7709c715ec6066fc2f0022df4198df3414f78
Update cake!
jamesmontemagno/xamarin.forms-toolkit
build.cake
build.cake
var TARGET = Argument ("target", Argument ("t", "Default")); var VERSION = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); var CONFIG = Argument("configuration", EnvironmentVariable ("CONFIGURATION") ?? "Release"); var SLN = "./FormsToolkit.sln"; Task("Libraries").Does(()=> { NuGetRestore (SLN); MSBuild (SLN, c => { c.Configuration = CONFIG; c.MSBuildPlatform = Cake.Common.Tools.MSBuild.MSBuildPlatform.x86; }); }); Task ("NuGet") .IsDependentOn ("Libraries") .Does (() => { if(!DirectoryExists("./Build/nuget/")) CreateDirectory("./Build/nuget"); NuGetPack ("./FormsToolkit.nuspec", new NuGetPackSettings { Version = VERSION, 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 "Cake.FileHelpers" var TARGET = Argument ("target", Argument ("t", "Default")); var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999"); Task ("Default").Does (() => { NuGetRestore ("./FormsToolkit.sln"); DotNetBuild ("./FormsToolkit.sln", c => c.Configuration = "Release"); }); Task ("NuGetPack") .IsDependentOn ("Default") .Does (() => { NuGetPack ("./FormsToolkit.nuspec", new NuGetPackSettings { Version = version, Verbosity = NuGetVerbosity.Detailed, OutputDirectory = "./", BasePath = "./", }); }); RunTarget (TARGET);
mit
C#
17157bf7b768938b9100d66e252d82dac3ea4147
Add cake tasks
CoraleStudios/Colore
build.cake
build.cake
/////////////////////////////////////////////////////////////////////////////// // ARGUMENTS /////////////////////////////////////////////////////////////////////////////// var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var platform = Argument("Platform", "AnyCPU"); var tag = Argument("Tag", "cake"); /////////////////////////////////////////////////////////////////////////////// // SETUP / TEARDOWN /////////////////////////////////////////////////////////////////////////////// Setup(ctx => { // Executed BEFORE the first task. Information("Running tasks..."); }); Teardown(ctx => { // Executed AFTER the last task. Information("Finished running tasks."); }); var projects = new[] { "Corale.Colore", "Corale.Colore.Tests" }; /////////////////////////////////////////////////////////////////////////////// // TASKS /////////////////////////////////////////////////////////////////////////////// Task("Restore") .Does(() => { DotNetCoreRestore("src/"); }); Task("Build") .IsDependentOn("Restore") .Does(() => { foreach (var project in projects) DotNetCoreBuild($"src/{project}/{project}.csproj"); }); Task("Test") .IsDependentOn("Build") .Does(() => { DotNetCoreTest($"src/Corale.Colore.Tests/Corale.Colore.Tests.csproj"); }); Task("Publish") .IsDependentOn("Test") .Does(() => { var settings = new DotNetCorePublishSettings { Framework = "netstandard1.6", Configuration = "Release", OutputDirectory = "./publish/", VersionSuffix = tag }; DotNetCorePublish("src/Corale.Colore", settings); }); Task("Default") .IsDependentOn("Test"); RunTarget(target);
mit
C#
24a56e3a0b26e7bf784fb0b28b51c130f7fe75b9
Tweak emailmessage.send()
hatton/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,chrisvire/libpalaso,marksvc/libpalaso,hatton/libpalaso,mccarthyrb/libpalaso,darcywong00/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,gmartin7/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,marksvc/libpalaso,andrew-polk/libpalaso,andrew-polk/libpalaso,gmartin7/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,JohnThomson/libpalaso,sillsdev/libpalaso,ddaspit/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,sillsdev/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,mccarthyrb/libpalaso,marksvc/libpalaso,ermshiperete/libpalaso,tombogle/libpalaso,hatton/libpalaso,glasseyes/libpalaso,chrisvire/libpalaso,andrew-polk/libpalaso,hatton/libpalaso,tombogle/libpalaso,ddaspit/libpalaso,sillsdev/libpalaso,JohnThomson/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,tombogle/libpalaso,darcywong00/libpalaso,mccarthyrb/libpalaso,glasseyes/libpalaso,ermshiperete/libpalaso,glasseyes/libpalaso,ddaspit/libpalaso,tombogle/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,chrisvire/libpalaso
Reporting/EmailMessage.cs
Reporting/EmailMessage.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Palaso.Reporting { public class EmailMessage { private string _body= ""; private string _address = ""; private string _subject = ""; // private string _attachmentPath; public void Send() { //string body = _body.Replace(System.Environment.NewLine, "%0A").Replace("\"", "%22").Replace("&", "%26"); string body = Uri.EscapeDataString(_body); string subject = Uri.EscapeDataString(_subject); System.Diagnostics.Process p = new Process(); p.StartInfo.FileName =String.Format("mailto:{0}?subject={1}&body={2}", _address, subject, body); p.StartInfo.UseShellExecute = true; p.StartInfo.ErrorDialog = true; p.Start(); } /// <summary> /// /// </summary> public string Address { set { _address = value; } get { return _address; } } /// <summary> /// the e-mail subject /// </summary> public string Subject { set { _subject = value; } get { return _subject; } } /// <summary> /// /// </summary> public string Body { set { _body = value; } get { return _body; } } // public string AttachmentPath // { // set // { // _attachmentPath = value; // } // } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; namespace Palaso.Reporting { public class EmailMessage { private string _body= ""; private string _address = ""; private string _subject = ""; // private string _attachmentPath; public void Send() { //string body = _body.Replace(System.Environment.NewLine, "%0A").Replace("\"", "%22").Replace("&", "%26"); string body = Uri.EscapeDataString(_body); string subject = Uri.EscapeDataString(_subject); System.Diagnostics.Process p = new Process(); p.StartInfo.FileName =String.Format("mailto:{0}?subject={1}&body={2}", _address, subject, body); p.Start(); } /// <summary> /// /// </summary> public string Address { set { _address = value; } get { return _address; } } /// <summary> /// the e-mail subject /// </summary> public string Subject { set { _subject = value; } get { return _subject; } } /// <summary> /// /// </summary> public string Body { set { _body = value; } get { return _body; } } // public string AttachmentPath // { // set // { // _attachmentPath = value; // } // } } }
mit
C#
c81a158ac7cede25aed3b8152013db0e82553952
Use SampleOverrideLongestPlaying for audio samples.
Damnae/storybrew
brewlib/Audio/AudioSample.cs
brewlib/Audio/AudioSample.cs
using ManagedBass; using System; using System.Diagnostics; using System.Resources; namespace BrewLib.Audio { public class AudioSample { private const int MaxSimultaneousPlayBacks = 8; private string path; public string Path => path; private int sample; public readonly AudioManager Manager; internal AudioSample(AudioManager audioManager, string path, ResourceManager resourceManager) { Manager = audioManager; this.path = path; sample = Bass.SampleLoad(path, 0, 0, MaxSimultaneousPlayBacks, BassFlags.SampleOverrideLongestPlaying); if (sample == 0) { Trace.WriteLine($"Failed to load audio sample ({path}): {Bass.LastError}"); return; } } public void Play(float volume = 1) { if (sample == 0) return; var channel = new AudioChannel(Manager, Bass.SampleGetChannel(sample), true) { Volume = volume, }; Manager.RegisterChannel(channel); channel.Playing = true; } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { } if (sample != 0) { Bass.SampleFree(sample); sample = 0; } disposedValue = true; } } ~AudioSample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
using ManagedBass; using System; using System.Diagnostics; using System.Resources; namespace BrewLib.Audio { public class AudioSample { private const int MaxSimultaneousPlayBacks = 8; private string path; public string Path => path; private int sample; public readonly AudioManager Manager; internal AudioSample(AudioManager audioManager, string path, ResourceManager resourceManager) { Manager = audioManager; this.path = path; sample = Bass.SampleLoad(path, 0, 0, MaxSimultaneousPlayBacks, BassFlags.Default); if (sample == 0) { Trace.WriteLine($"Failed to load audio sample ({path}): {Bass.LastError}"); return; } } public void Play(float volume = 1) { if (sample == 0) return; var channel = new AudioChannel(Manager, Bass.SampleGetChannel(sample), true) { Volume = volume, }; Manager.RegisterChannel(channel); channel.Playing = true; } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { } if (sample != 0) { Bass.SampleFree(sample); sample = 0; } disposedValue = true; } } ~AudioSample() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
mit
C#
0467850a4c94a46cacbdff643a27e57d6a8e5f14
Add Entity.ToString override
copygirl/EntitySystem
src/Entity.cs
src/Entity.cs
using System; namespace EntitySystem { public struct Entity : IEquatable<Entity>, IComparable<Entity> { readonly uint _id; internal Entity(uint id) { _id = id; } public bool Equals(Entity other) => (_id == other._id); public int CompareTo(Entity other) => _id.CompareTo(other._id); public override bool Equals(object obj) => ((obj is Entity) && Equals((Entity)obj)); public static bool operator ==(Entity left, Entity right) => left.Equals(right); public static bool operator !=(Entity left, Entity right) => !left.Equals(right); public override int GetHashCode() => _id.GetHashCode(); public override string ToString() => $"[Entity { _id :X}]"; } }
using System; namespace EntitySystem { public struct Entity : IEquatable<Entity>, IComparable<Entity> { readonly uint _id; internal Entity(uint id) { _id = id; } public bool Equals(Entity other) => (_id == other._id); public int CompareTo(Entity other) => _id.CompareTo(other._id); public override bool Equals(object obj) => ((obj is Entity) && Equals((Entity)obj)); public static bool operator ==(Entity left, Entity right) => left.Equals(right); public static bool operator !=(Entity left, Entity right) => !left.Equals(right); public override int GetHashCode() => _id.GetHashCode(); } }
mit
C#
af2dfae166fcc5001e6b94ce83d8850b524401a6
Make BooleanValue class sealed.
alldne/school,alldne/school
School/Evaluator/Value.cs
School/Evaluator/Value.cs
using System; namespace School.Evaluator { public abstract class Value { } public sealed class UnitValue : Value { public static readonly UnitValue Singleton = new UnitValue(); private UnitValue() { } public override string ToString() { return "()"; } } public class IntValue : Value { private readonly int value; public int Value { get { return value; } } public IntValue(int value) { this.value = value; } public override string ToString() { return value.ToString(); } } public sealed class BooleanValue : Value { public static readonly BooleanValue True = new BooleanValue(true); public static readonly BooleanValue False = new BooleanValue(false); private readonly bool value; public bool Value { get { return value; } } private BooleanValue(bool value) { this.value = value; } public override string ToString() { return value.ToString(); } } public class FunValue : Value { private readonly Func<Value, Value> value; public Func<Value, Value> Value { get { return value; } } public FunValue(Func<Value, Value> value) { this.value = value; } public Value Apply(Value arg) { return value(arg); } } }
using System; namespace School.Evaluator { public abstract class Value { } public sealed class UnitValue : Value { public static readonly UnitValue Singleton = new UnitValue(); private UnitValue() { } public override string ToString() { return "()"; } } public class IntValue : Value { private readonly int value; public int Value { get { return value; } } public IntValue(int value) { this.value = value; } public override string ToString() { return value.ToString(); } } public class BooleanValue : Value { public static readonly BooleanValue True = new BooleanValue(true); public static readonly BooleanValue False = new BooleanValue(false); private readonly bool value; public bool Value { get { return value; } } private BooleanValue(bool value) { this.value = value; } public override string ToString() { return value.ToString(); } } public class FunValue : Value { private readonly Func<Value, Value> value; public Func<Value, Value> Value { get { return value; } } public FunValue(Func<Value, Value> value) { this.value = value; } public Value Apply(Value arg) { return value(arg); } } }
apache-2.0
C#
d0faa36dd7ae7b7beafbde4cb69d07ca88b00506
Add version=3 for SQLite
jahav/Nerula
Nerula.Test/DatabaseTest.cs
Nerula.Test/DatabaseTest.cs
using Nerula.Data; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Tool.hbm2ddl; namespace Nerula.Test { /// <summary> /// Base class for tests that utilize the in memory database. /// /// IMPORTANT: You will probably encounter "The Process cannot access the file 'SQLite.Interop.dll' because it is being used by another process" /// when trying to build test multiple times. The error is cause by test runner of Visual Studio, the runner is /// kept alive between test runs and while it is alive, it is accessing the SQLite.Interop.dll because property of the dll is set /// to "Copy Always", it tries to override the running version. There are two ways to solve this: set properties to "Copy If Newer" /// or change test runner settings so it is not alive between tests runs (may cause performance penalty). The option is in TOOLS -> /// Options -> Web Performance Test Tools: Uncheck the "Test Execution Keep test execution engine running between test runs". /// Source: stackoverflow#12919447 /// </summary> public class DatabaseTest { private ISession keepAliveSession; public ISessionFactory SessionFactory { get; private set; } public void DatabaseSetup(params System.Type[] mappedEntityTypes) { // Also note the ReleaseConnections "on_close" var configuration = new Configuration() .SetProperty(Environment.ReleaseConnections, "on_close") // http://www.codethinked.com/nhibernate-20-sqlite-and-in-memory-databases .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName) .SetProperty(Environment.ConnectionProvider, typeof(SQLiteInMemoryConnectionProvider).AssemblyQualifiedName) .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName) .SetProperty(Environment.ShowSql, "true") .SetProperty(Environment.ConnectionString, "data source=:memory:;version=3") .SetProperty(Environment.CollectionTypeFactoryClass, typeof(Net4CollectionTypeFactory).AssemblyQualifiedName) ; foreach (var entityType in mappedEntityTypes) { configuration = configuration.AddClass(entityType); } SessionFactory = configuration.BuildSessionFactory(); keepAliveSession = SessionFactory.OpenSession(); // Note: since in-memory db is destroyed when session is closed, you can't use // new SchemaExport(configuration).Execute(true, true, false), because it creates a session, creates schemas // and then disposes of the created session - effectively destroying db. Thus the other opened session // doesn't have schemas ready. The result are errors like SQL logic error or missing database no such table // We must create schema using our session. new SchemaExport(configuration).Execute(true, true, false, keepAliveSession.Connection, null); } public void DatabaseTearDown() { keepAliveSession.Dispose(); } } }
using Nerula.Data; using NHibernate; using NHibernate.Cfg; using NHibernate.Dialect; using NHibernate.Driver; using NHibernate.Tool.hbm2ddl; namespace Nerula.Test { /// <summary> /// Base class for tests that utilize the in memory database. /// /// IMPORTANT: You will probably encounter "The Process cannot access the file 'SQLite.Interop.dll' because it is being used by another process" /// when trying to build test multiple times. The error is cause by test runner of Visual Studio, the runner is /// kept alive between test runs and while it is alive, it is accessing the SQLite.Interop.dll because property of the dll is set /// to "Copy Always", it tries to override the running version. There are two ways to solve this: set properties to "Copy If Newer" /// or change test runner settings so it is not alive between tests runs (may cause performance penalty). The option is in TOOLS -> /// Options -> Web Performance Test Tools: Uncheck the "Test Execution Keep test execution engine running between test runs". /// Source: stackoverflow#12919447 /// </summary> public class DatabaseTest { private ISession keepAliveSession; public ISessionFactory SessionFactory { get; private set; } public void DatabaseSetup(params System.Type[] mappedEntityTypes) { // Also note the ReleaseConnections "on_close" var configuration = new Configuration() .SetProperty(Environment.ReleaseConnections, "on_close") // http://www.codethinked.com/nhibernate-20-sqlite-and-in-memory-databases .SetProperty(Environment.Dialect, typeof(SQLiteDialect).AssemblyQualifiedName) .SetProperty(Environment.ConnectionProvider, typeof(SQLiteInMemoryConnectionProvider).AssemblyQualifiedName) .SetProperty(Environment.ConnectionDriver, typeof(SQLite20Driver).AssemblyQualifiedName) .SetProperty(Environment.ShowSql, "true") .SetProperty(Environment.ConnectionString, "data source=:memory:") .SetProperty(Environment.CollectionTypeFactoryClass, typeof(Net4CollectionTypeFactory).AssemblyQualifiedName) ; foreach (var entityType in mappedEntityTypes) { configuration = configuration.AddClass(entityType); } SessionFactory = configuration.BuildSessionFactory(); keepAliveSession = SessionFactory.OpenSession(); // Note: since in-memory db is destroyed when session is closed, you can't use // new SchemaExport(configuration).Execute(true, true, false), because it creates a session, creates schemas // and then disposes of the created session - effectively destroying db. Thus the other opened session // doesn't have schemas ready. The result are errors like SQL logic error or missing database no such table // We must create schema using our session. new SchemaExport(configuration).Execute(true, true, false, keepAliveSession.Connection, null); } public void DatabaseTearDown() { keepAliveSession.Dispose(); } } }
unlicense
C#
08a9001ad6eaf3c2a3ec87c63155571b7ee90acd
speed up bullets for better effects
pako1337/raim,pako1337/raim,pako1337/raim
PaCode.Raim/Model/Bullet.cs
PaCode.Raim/Model/Bullet.cs
using System; namespace PaCode.Raim.Model { public class Bullet : IGameObject, IDestroyable { private DateTime lastUpdate = DateTime.Now; public Guid Id { get; private set; } public Vector2d Position { get; private set; } public Vector2d Speed { get; private set; } public Vector2d FacingDirection { get; private set; } public bool IsDestroyed { get; private set; } public int TimeToLive { get; private set; } public int Size { get; } = 2; private Bullet() { } public static Bullet Create(Vector2d position, Vector2d direction) { return new Bullet() { Id = Guid.NewGuid(), Position = position, FacingDirection = direction, Speed = direction.Unit().Scale(50), TimeToLive = (int)TimeSpan.FromSeconds(5).TotalMilliseconds, }; } public void Update(DateTime updateTime) { if (TimeToLive <= 0) { IsDestroyed = true; return; } var changeTime = updateTime; var timeBetweenEvents = changeTime - lastUpdate; Position.X += Speed.X * timeBetweenEvents.TotalSeconds; Position.Y += Speed.Y * timeBetweenEvents.TotalSeconds; TimeToLive -= (int)timeBetweenEvents.TotalMilliseconds; lastUpdate = changeTime; } } }
using System; namespace PaCode.Raim.Model { public class Bullet : IGameObject, IDestroyable { private DateTime lastUpdate = DateTime.Now; public Guid Id { get; private set; } public Vector2d Position { get; private set; } public Vector2d Speed { get; private set; } public Vector2d FacingDirection { get; private set; } public bool IsDestroyed { get; private set; } public int TimeToLive { get; private set; } public int Size { get; } = 2; private Bullet() { } public static Bullet Create(Vector2d position, Vector2d direction) { return new Bullet() { Id = Guid.NewGuid(), Position = position, FacingDirection = direction, Speed = direction.Unit().Scale(10), TimeToLive = (int)TimeSpan.FromSeconds(5).TotalMilliseconds, }; } public void Update(DateTime updateTime) { if (TimeToLive <= 0) { IsDestroyed = true; return; } var changeTime = updateTime; var timeBetweenEvents = changeTime - lastUpdate; Position.X += Speed.X * timeBetweenEvents.TotalSeconds; Position.Y += Speed.Y * timeBetweenEvents.TotalSeconds; TimeToLive -= (int)timeBetweenEvents.TotalMilliseconds; lastUpdate = changeTime; } } }
mit
C#
a3de2273902fb402a2a65bde7c9ccb2949731b2f
Update DeviceInfoImplementation.cs
jamesmontemagno/Xamarin.Plugins,tim-hoff/Xamarin.Plugins,labdogg1003/Xamarin.Plugins,monostefan/Xamarin.Plugins,predictive-technology-laboratory/Xamarin.Plugins,LostBalloon1/Xamarin.Plugins,JC-Chris/Xamarin.Plugins
DeviceInfo/DeviceInfo/DeviceInfo.Plugin.iOS/DeviceInfoImplementation.cs
DeviceInfo/DeviceInfo/DeviceInfo.Plugin.iOS/DeviceInfoImplementation.cs
/* * Ported with permission from: Thomasz Cielecki @Cheesebaron * AppId: https://github.com/Cheesebaron/Cheesebaron.MvxPlugins */ //--------------------------------------------------------------------------------- // Copyright 2013 Tomasz Cielecki (tomasz@ostebaronen.dk) // 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 // THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, // INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR // CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing // permissions and limitations under the License. //--------------------------------------------------------------------------------- using DeviceInfo.Plugin.Abstractions; #if __UNIFIED__ using UIKit; #else using MonoTouch.UIKit; #endif using System; namespace DeviceInfo.Plugin { /// <summary> /// Implementation for DeviceInfo /// </summary> public class DeviceInfoImplementation : IDeviceInfo { public string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null) { var appId = ""; if (!string.IsNullOrEmpty(prefix)) appId += prefix; appId += Guid.NewGuid().ToString(); if (usingPhoneId) appId += Id; if (!string.IsNullOrEmpty(suffix)) appId += suffix; return appId; } public string Id { get { // iOS 6 and up return UIDevice.CurrentDevice.IdentifierForVendor.AsString(); } } public string Model { get { return UIDevice.CurrentDevice.Model; } } public string Version { get { return UIDevice.CurrentDevice.SystemVersion; } } public Platform Platform { get { return Platform.iOS; } } } }
using DeviceInfo.Plugin.Abstractions; #if __UNIFIED__ using UIKit; #else using MonoTouch.UIKit; #endif using System; namespace DeviceInfo.Plugin { /// <summary> /// Implementation for DeviceInfo /// </summary> public class DeviceInfoImplementation : IDeviceInfo { public string GenerateAppId(bool usingPhoneId = false, string prefix = null, string suffix = null) { var appId = ""; if (!string.IsNullOrEmpty(prefix)) appId += prefix; appId += Guid.NewGuid().ToString(); if (usingPhoneId) appId += Id; if (!string.IsNullOrEmpty(suffix)) appId += suffix; return appId; } public string Id { get { // iOS 6 and up return UIDevice.CurrentDevice.IdentifierForVendor.AsString(); } } public string Model { get { return UIDevice.CurrentDevice.Model; } } public string Version { get { return UIDevice.CurrentDevice.SystemVersion; } } public Platform Platform { get { return Platform.iOS; } } } }
mit
C#
24cc80ef93dd22602a5ee945cbf8802ea3a3b76e
Make it possible to specify custom hipchat server
modulexcite/Hipchat-CS,KyleGobel/Hipchat-CS
src/Api/HipchatEndpoints.cs
src/Api/HipchatEndpoints.cs
using ServiceStack; using System; using System.Configuration; namespace HipchatApiV2 { public class HipchatEndpoints { private static string EndpointHost = null; static HipchatEndpoints() { EndpointHost = ConfigurationManager.AppSettings["hipchat_endpoint_host"] ?? "api.hipchat.com"; } private HipchatEndpoints() {} public static string CreateWebhookEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}/webhook", EndpointHost); } } private string SendMessageEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}/notification?auth_token={{1}}", EndpointHost); } } public static string CreateRoomEndpoint { get { return String.Format("https://{0}/v2/room", EndpointHost); } } public static string GetAllRoomsEndpoint { get { return String.Format("https://{0}/v2/room", EndpointHost); } } public static string GenerateTokenEndpoint { get { return String.Format("https://{0}/v2/oauth/token", EndpointHost); } } public static string SendNotificationEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}/notification", EndpointHost); } } public static string GetRoomEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}", EndpointHost); } } public static string DeleteRoomEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}", EndpointHost); } } public static string GetAllWebhooksEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}/webhook", EndpointHost); } } public static string DeleteWebhookEndpointFormat { get { return String.Format("https://{0}/v2/room/{{0}}/webhook/{{1}}", EndpointHost); } } public static string UpdateRoomEndpoingFormat { get { return String.Format("https://{0}/v2/room/{{0}}", EndpointHost); } } public static string GetAllUsersEndpoint { get { return String.Format("https://{0}/v2/user", EndpointHost); } } public static string SetTopicEnpdointFormat { get { return String.Format("https://{0}/v2/room/{{0}}/topic", EndpointHost); } } public static string GetAllEmoticonsEndpoint { get { return String.Format("https://{0}/v2/emoticon", EndpointHost); } } public static string GetEmoticonEndpoint { get { return String.Format("https://{0}/v2/emoticon/{{0}}", EndpointHost); } } public static string CreateUserEndpointFormat { get { return String.Format("https://{0}/v2/user", EndpointHost); } } public static string DeleteUserEndpointFormat { get { return String.Format("https://{0}/v2/user/{{0}}", EndpointHost); } } } }
using ServiceStack; namespace HipchatApiV2 { public class HipchatEndpoints { private HipchatEndpoints() {} public static readonly string CreateWebhookEndpointFormat = "https://api.hipchat.com/v2/room/{0}/webhook"; private const string SendMessageEndpointFormat = "https://api.hipchat.com/v2/room/{0}/notification?auth_token={1}"; public static readonly string CreateRoomEndpoint = "https://api.hipchat.com/v2/room"; public static readonly string GetAllRoomsEndpoint = "https://api.hipchat.com/v2/room"; public static readonly string GenerateTokenEndpoint = "https://api.hipchat.com/v2/oauth/token"; public static readonly string SendNotificationEndpointFormat = "https://api.hipchat.com/v2/room/{0}/notification"; public static readonly string GetRoomEndpointFormat = "https://api.hipchat.com/v2/room/{0}"; public static readonly string DeleteRoomEndpointFormat = "https://api.hipchat.com/v2/room/{0}"; public static readonly string GetAllWebhooksEndpointFormat = "https://api.hipchat.com/v2/room/{0}/webhook"; public static readonly string DeleteWebhookEndpointFormat = "https://api.hipchat.com/v2/room/{0}/webhook/{1}"; public static readonly string UpdateRoomEndpoingFormat = "https://api.hipchat.com/v2/room/{0}"; public static readonly string GetAllUsersEndpoint = "https://api.hipchat.com/v2/user"; public static readonly string SetTopicEnpdointFormat = "https://api.hipchat.com/v2/room/{0}/topic"; public static readonly string GetAllEmoticonsEndpoint = "https://api.hipchat.com/v2/emoticon"; public static readonly string GetEmoticonEndpoint = "https://api.hipchat.com/v2/emoticon/{0}"; public static readonly string CreateUserEndpointFormat = "https://api.hipchat.com/v2/user"; public static readonly string DeleteUserEndpointFormat = "https://api.hipchat.com/v2/user/{0}"; } }
mit
C#
e171378902fa446e7827aa57a7db8f5d22730686
Fix arg
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/AddWallet/TermsAndConditionsViewModel.cs
WalletWasabi.Fluent/ViewModels/AddWallet/TermsAndConditionsViewModel.cs
using System.IO; using System.Reactive.Linq; using System.Windows.Input; using ReactiveUI; using WalletWasabi.Fluent.ViewModels.Navigation; using WalletWasabi.Legal; namespace WalletWasabi.Fluent.ViewModels.AddWallet { public class TermsAndConditionsViewModel : RoutableViewModel { private bool _isAgreed; public TermsAndConditionsViewModel(LegalDocuments legalDocuments, RoutableViewModel next) { ViewTermsCommand = ReactiveCommand.CreateFromTask( async () => { var content = await File.ReadAllTextAsync(legalDocuments.FilePath); var legalDocs = new LegalDocumentsViewModel(content, backOnNext: true); Navigate().To(legalDocs); }); NextCommand = ReactiveCommand.Create( () => { Navigate().BackTo(next); }, this.WhenAnyValue(x => x.IsAgreed).ObserveOn(RxApp.MainThreadScheduler)); } public bool IsAgreed { get => _isAgreed; set => this.RaiseAndSetIfChanged(ref _isAgreed, value); } public ICommand ViewTermsCommand { get; } } }
using System.IO; using System.Reactive.Linq; using System.Windows.Input; using ReactiveUI; using WalletWasabi.Fluent.ViewModels.Navigation; using WalletWasabi.Legal; namespace WalletWasabi.Fluent.ViewModels.AddWallet { public class TermsAndConditionsViewModel : RoutableViewModel { private bool _isAgreed; public TermsAndConditionsViewModel(LegalDocuments legalDocuments, RoutableViewModel next) { ViewTermsCommand = ReactiveCommand.CreateFromTask( async () => { var content = await File.ReadAllTextAsync(legalDocuments.FilePath); var legalDocs = new LegalDocumentsViewModel(content, backOnNext: false); Navigate().To(legalDocs); }); NextCommand = ReactiveCommand.Create( () => { Navigate().BackTo(next); }, this.WhenAnyValue(x => x.IsAgreed).ObserveOn(RxApp.MainThreadScheduler)); } public bool IsAgreed { get => _isAgreed; set => this.RaiseAndSetIfChanged(ref _isAgreed, value); } public ICommand ViewTermsCommand { get; } } }
mit
C#
44e3f5cc970486e0be771c5fb80fefef4ee33fcc
拡張子やエンコードはシステムごとに統一される可能性が高いので、サブクラスで指定したいと思いvirtualにしました。
SunriseDigital/cs-sdx
Sdx/Config.cs
Sdx/Config.cs
using System.Collections.Generic; using Sdx.Data; using System.Text; using System.IO; using System; namespace Sdx { public class Config<T> where T : Tree, new() { private static Dictionary<string, Tree> memoryCache; static Config() { memoryCache = new Dictionary<string, Tree>(); } public string BaseDir { get; set; } public virtual Tree Get(string fileName) { return this.CreateTree(fileName, null, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, string extension) { return this.CreateTree(fileName, extension, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, Encoding encoding) { return this.CreateTree(fileName, null, encoding); } public Tree Get(string fileName, string extension, Encoding encoding) { return this.CreateTree(fileName, extension, encoding); } public void ClearCache() { memoryCache.Clear(); } private Tree CreateTree(string fileName, string extension, Encoding encoding) { //置換しないとBaseを`/path/to/foo`まで含めたGet("bar")と、`/path/to`の時のGet("foo/bar")が //同じファイルを指しているのに別のキャッシュになる fileName = fileName.Replace('/', Path.DirectorySeparatorChar); Tree tree = new T(); var path = BaseDir + Path.DirectorySeparatorChar + fileName; if (extension != null) { path += "." + extension; } if(memoryCache.ContainsKey(path)) { return memoryCache[path]; } using (var fs = new FileStream(path, FileMode.Open)) { var input = new StreamReader(fs, encoding); tree.Load(input); } memoryCache[path] = tree; return tree; } } }
using System.Collections.Generic; using Sdx.Data; using System.Text; using System.IO; using System; namespace Sdx { public class Config<T> where T : Tree, new() { private static Dictionary<string, Tree> memoryCache; static Config() { memoryCache = new Dictionary<string, Tree>(); } public string BaseDir { get; set; } public Tree Get(string fileName) { return this.CreateTree(fileName, null, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, string extension) { return this.CreateTree(fileName, extension, Encoding.GetEncoding("utf-8")); } public Tree Get(string fileName, Encoding encoding) { return this.CreateTree(fileName, null, encoding); } public Tree Get(string fileName, string extension, Encoding encoding) { return this.CreateTree(fileName, extension, encoding); } public void ClearCache() { memoryCache.Clear(); } private Tree CreateTree(string fileName, string extension, Encoding encoding) { //置換しないとBaseを`/path/to/foo`まで含めたGet("bar")と、`/path/to`の時のGet("foo/bar")が //同じファイルを指しているのに別のキャッシュになる fileName = fileName.Replace('/', Path.DirectorySeparatorChar); Tree tree = new T(); var path = BaseDir + Path.DirectorySeparatorChar + fileName; if (extension != null) { path += "." + extension; } if(memoryCache.ContainsKey(path)) { return memoryCache[path]; } using (var fs = new FileStream(path, FileMode.Open)) { var input = new StreamReader(fs, encoding); tree.Load(input); } memoryCache[path] = tree; return tree; } } }
mit
C#