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
3b28020e1204077dfbbd1f7eda2758c4e0212be3
add subject name property
Lone-Coder/letsencrypt-win-simple
letsencrypt-win-simple/CertificateInfo.cs
letsencrypt-win-simple/CertificateInfo.cs
using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace LetsEncrypt.ACME.Simple { public class CertificateInfo { public X509Certificate2 Certificate { get; set; } public X509Store Store { get; set; } public FileInfo PfxFile { get; set; } public string SubjectName { get { AsnEncodedData asndata = new AsnEncodedData(Certificate.SubjectName.Oid, Certificate.SubjectName.RawData); return asndata.Format(true).Replace("DNS Name=", "").Trim(); } } public List<string> HostNames { get { var ret = new List<string>(); foreach (var x in Certificate.Extensions) { if (x.Oid.Value.Equals("2.5.29.17")) { AsnEncodedData asndata = new AsnEncodedData(x.Oid, x.RawData); ret.Add(asndata.Format(true).Replace("DNS Name=", "").Trim()); } } return ret; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace LetsEncrypt.ACME.Simple { public class CertificateInfo { public X509Certificate2 Certificate { get; set; } public X509Store Store { get; set; } public FileInfo PfxFile { get; set; } public List<string> HostNames { get { var ret = new List<string>(); foreach (var x in Certificate.Extensions) { if (x.Oid.Value.Equals("2.5.29.17")) { AsnEncodedData asndata = new AsnEncodedData(x.Oid, x.RawData); ret.Add(asndata.Format(true).Replace("DNS Name=", "").Trim()); } } return ret; } } } }
apache-2.0
C#
91171c51824b39550532fe1b05245d83ceb4fdc4
Update to PaginationParameter
smartsheet-platform/smartsheet-csharp-sdk,smartsheet-platform/smartsheet-csharp-sdk
main/Smartsheet/Api/Models/PaginationParameters.cs
main/Smartsheet/Api/Models/PaginationParameters.cs
using Smartsheet.Api.Internal.Util; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { public class PaginationParameters { private bool includeAll; private int? pageSize; private int? page; public PaginationParameters(bool includeAll, int? pageSize, int? page) { this.includeAll = includeAll; this.pageSize = pageSize; this.page = page; } public bool IncludeAll { get { return includeAll; } set { includeAll = value; } } public int? PageSize { get { return pageSize; } set { pageSize = value; } } public int? Page { get { return page; } set { page = value; } } public string ToQueryString() { IDictionary<string, string> parameters = this.toDictionary(); return QueryUtil.GenerateUrl(null, parameters); } public IDictionary<string, string> toDictionary() { Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("includeAll", includeAll.ToString().ToLower()); if (!includeAll) { if (pageSize.HasValue) { parameters.Add("pageSize", pageSize.ToString().ToLower()); } if (page.HasValue) { parameters.Add("page", page.ToString().ToLower()); } } return parameters; } } }
using Smartsheet.Api.Internal.Util; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Smartsheet.Api.Models { public class PaginationParameters { private bool includeAll; private int? pageSize; private int? page; public PaginationParameters(bool includeAll, int? pageSize, int? page) { this.includeAll = includeAll; this.pageSize = pageSize; this.page = page; } public bool IncludeAll { get { return includeAll; } set { includeAll = value; } } public int? PageSize { get { return pageSize; } set { pageSize = value; } } public int? Page { get { return page; } set { page = value; } } public string ToQueryString() { IDictionary<string, string> parameters = this.toDictionary(); return QueryUtil.GenerateUrl(null, parameters); } public IDictionary<string, string> toDictionary() { Dictionary<string, string> parameters = new Dictionary<string, string>(); parameters.Add("includeAll", includeAll.ToString()); if (!includeAll) { if (pageSize.HasValue) { parameters.Add("pageSize", pageSize.ToString()); } if (page.HasValue) { parameters.Add("page", page.ToString()); } } return parameters; } } }
apache-2.0
C#
5e34db1293fb2c1939694d40021b1bd9ff879afe
Create multiple events, serialize and re-load.
rianjs/ical.net
Example2/Program.cs
Example2/Program.cs
using System; using System.Collections.Generic; using System.Text; using DDay.iCal; using DDay.iCal.Components; using DDay.iCal.DataTypes; using DDay.iCal.Serialization; namespace Example2 { public class Program { /// <summary> /// Creates a string representation of an event. /// </summary> /// <param name="evt">The event to display</param> /// <returns>A string representation of the event.</returns> static string GetDescription(Event evt) { string summary = evt.Summary + ": " + evt.Start.Local.ToShortDateString(); if (evt.IsAllDay) { return summary + " (all day)"; } else { summary += ", " + evt.Start.Local.ToShortTimeString(); return summary + " (" + Math.Round((double)(evt.End - evt.Start).TotalHours) + " hours)"; } } /// <summary> /// The main program execution. /// </summary> static void Main(string[] args) { // Create a new iCalendar iCalendar iCal = new iCalendar(); // Create the event, and add it to the iCalendar Event evt = Event.Create(iCal); // Set information about the event evt.Start = DateTime.Today; evt.Start = evt.Start.AddHours(8); evt.End = evt.Start.AddHours(18); // This also sets the duration evt.DTStamp = DateTime.Now; evt.Description = "The event description"; evt.Location = "Event location"; evt.Summary = "18 hour event summary"; // Set information about the second event evt = Event.Create(iCal); evt.Start = DateTime.Today.AddDays(5); evt.End = evt.Start.AddDays(1); evt.IsAllDay = true; evt.DTStamp = DateTime.Now; evt.Summary = "All-day event"; // Display each event foreach(Event e in iCal.Events) Console.WriteLine("Event created: " + GetDescription(e)); // Serialize (save) the iCalendar iCalendarSerializer serializer = new iCalendarSerializer(iCal); serializer.Serialize(@"iCalendar.ics"); Console.WriteLine("iCalendar file saved." + Environment.NewLine); iCal = iCalendar.LoadFromFile(@"iCalendar.ics"); Console.WriteLine("iCalendar file loaded."); foreach (Event e in iCal.Events) Console.WriteLine("Event loaded: " + GetDescription(e)); } } }
using System; using System.Collections.Generic; using System.Text; using DDay.iCal; using DDay.iCal.Components; using DDay.iCal.Serialization; namespace Example2 { public class Program { static void Main(string[] args) { // Create a new iCalendar iCalendar iCal = new iCalendar(); // Create the event, and add it to the iCalendar Event evt = Event.Create(iCal); // Set information about the event evt.Start = DateTime.Today; evt.End = DateTime.Today.AddDays(1); // This also sets the duration evt.DTStamp = DateTime.Now; evt.Description = "The event description"; evt.Location = "Event location"; evt.Summary = "The summary of the event"; // Serialize (save) the iCalendar iCalendarSerializer serializer = new iCalendarSerializer(iCal); serializer.Serialize(@"iCalendar.ics"); } } }
mit
C#
5cb32ba792b02cce85185b643d7d3fd01a1f0ca8
Remove unneeded usings
Joe4evr/Discord.Addons
src/Discord.Addons.MpGame/Collections/ICardWrapper.cs
src/Discord.Addons.MpGame/Collections/ICardWrapper.cs
namespace Discord.Addons.MpGame.Collections { public interface ICardWrapper<TCard> where TCard : class { /// <summary> /// Unwraps the wrapped card. /// </summary> /// <returns>The unwrapped <typeparamref name="TCard"/>.</returns> TCard Unwrap(); /// <summary> /// Called when ownership of the wrapper has /// transfered from one pile to a different pile. /// </summary> /// <param name="newPile">The new Pile that /// now owns this wrapper.</param> void Reset<TWrapper>(Pile<TCard, TWrapper> newPile) where TWrapper : ICardWrapper<TCard>; } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Discord.Addons.Core; namespace Discord.Addons.MpGame.Collections { public interface ICardWrapper<TCard> where TCard : class { /// <summary> /// Unwraps the wrapped card. /// </summary> /// <returns>The unwrapped <typeparamref name="TCard"/>.</returns> TCard Unwrap(); /// <summary> /// Called when ownership of the wrapper has /// transfered from one pile to a different pile. /// </summary> /// <param name="newPile">The new Pile that /// now owns this wrapper.</param> void Reset<TWrapper>(Pile<TCard, TWrapper> newPile) where TWrapper : ICardWrapper<TCard>; } }
mit
C#
87d17a819aa9e06dd85dcebf05cca092584d4621
Make ObjectSession thread-safe
eposgmbh/Epos.Foundation
src/Epos.Utilities.Web/ObjectSession/ObjectSession.cs
src/Epos.Utilities.Web/ObjectSession/ObjectSession.cs
using System; using System.Collections.Concurrent; using System.Collections.Generic; using Microsoft.AspNetCore.Http; namespace Epos.Utilities.Web { internal class ObjectSession : IObjectSession { private const string ObjectSessionKey = "ObjectSession"; private readonly IHttpContextAccessor myHttpContextAccessor; private static readonly IDictionary<Guid, IDictionary<string, object>> mySession = new ConcurrentDictionary<Guid, IDictionary<string, object>>(); public ObjectSession(IHttpContextAccessor httpContextAccessor) { myHttpContextAccessor = httpContextAccessor; } public object this[string key] { get { string theGuidString = myHttpContextAccessor.HttpContext.Session.GetString(ObjectSessionKey); if (theGuidString == null) { return null; } var theGuid = Guid.Parse(theGuidString); IDictionary<string, object> theSession = mySession.Get(theGuid); if (theSession == null) { theSession = new Dictionary<string, object>(); mySession[theGuid] = theSession; } return theSession.Get(key); } set { string theGuidString = myHttpContextAccessor.HttpContext.Session.GetString(ObjectSessionKey); if (theGuidString == null) { theGuidString = Guid.NewGuid().ToString(); myHttpContextAccessor.HttpContext.Session.SetString(ObjectSessionKey, theGuidString); } var theGuid = Guid.Parse(theGuidString); IDictionary<string, object> theSession = mySession.Get(theGuid); if (theSession == null) { theSession = new Dictionary<string, object>(); mySession[theGuid] = theSession; } theSession[key] = value; } } } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; namespace Epos.Utilities.Web { internal class ObjectSession : IObjectSession { private const string ObjectSessionKey = "ObjectSession"; private readonly IHttpContextAccessor myHttpContextAccessor; private static readonly Dictionary<Guid, IDictionary<string, object>> mySession = new Dictionary<Guid, IDictionary<string, object>>(); public ObjectSession(IHttpContextAccessor httpContextAccessor) { myHttpContextAccessor = httpContextAccessor; } public object this[string key] { get { var theGuidString = myHttpContextAccessor.HttpContext.Session.GetString(ObjectSessionKey); if (theGuidString == null) { return null; } Guid theGuid = Guid.Parse(theGuidString); var theSession = mySession.Get(theGuid); if (theSession == null) { theSession = new Dictionary<string, object>(); mySession[theGuid] = theSession; } return theSession.Get(key); } set { var theGuidString = myHttpContextAccessor.HttpContext.Session.GetString(ObjectSessionKey); if (theGuidString == null) { theGuidString = Guid.NewGuid().ToString(); myHttpContextAccessor.HttpContext.Session.SetString(ObjectSessionKey, theGuidString); } Guid theGuid = Guid.Parse(theGuidString); var theSession = mySession.Get(theGuid); if (theSession == null) { theSession = new Dictionary<string, object>(); mySession[theGuid] = theSession; } theSession[key] = value; } } } }
mit
C#
e05f9843bada5fa8ef34427a1e2d98ad610ae7bc
Use strongly typed ReaderProgress instead of object[]
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
src/SharpCompress/Common/ReaderExtractionEventArgs.cs
src/SharpCompress/Common/ReaderExtractionEventArgs.cs
using System; using SharpCompress.Readers; namespace SharpCompress.Common { public class ReaderExtractionEventArgs<T> : EventArgs { internal ReaderExtractionEventArgs(T entry, ReaderProgress readerProgress = null) { Item = entry; ReaderProgress = readerProgress; } public T Item { get; private set; } public ReaderProgress ReaderProgress { get; private set; } } }
using System; namespace SharpCompress.Common { public class ReaderExtractionEventArgs<T> : EventArgs { internal ReaderExtractionEventArgs(T entry, params object[] paramList) { Item = entry; ParamList = paramList; } public T Item { get; private set; } public object[] ParamList { get; private set; } } }
mit
C#
4f2b32b7577f9baaf770500d1c50c7b320e4c11c
Fix IPV6 issue with BindTest
tgstation/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server
src/Tgstation.Server.Host/Extensions/SocketExtensions.cs
src/Tgstation.Server.Host/Extensions/SocketExtensions.cs
using System.Net; using System.Net.Sockets; namespace Tgstation.Server.Host.Extensions { /// <summary> /// Extension methods for the <see cref="Socket"/> <see langword="class"/>. /// </summary> static class SocketExtensions { /// <summary> /// Attempt to exclusively bind to a given <paramref name="port"/>. /// </summary> /// <param name="port">The port number to bind to.</param> /// <param name="includeIPv6">If IPV6 should be tested as well.</param> public static void BindTest(ushort port, bool includeIPv6) { using var socket = new Socket( includeIPv6 ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (includeIPv6) socket.DualMode = true; socket.Bind( new IPEndPoint( includeIPv6 ? IPAddress.IPv6Any : IPAddress.Any, port)); } } }
using System.Net; using System.Net.Sockets; namespace Tgstation.Server.Host.Extensions { /// <summary> /// Extension methods for the <see cref="Socket"/> <see langword="class"/>. /// </summary> static class SocketExtensions { /// <summary> /// Attempt to exclusively bind to a given <paramref name="port"/>. /// </summary> /// <param name="port">The port number to bind to.</param> /// <param name="includeIPv6">If IPV6 should be tested as well.</param> public static void BindTest(ushort port, bool includeIPv6) { using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ExclusiveAddressUse, true); socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, false); if (includeIPv6) socket.DualMode = true; socket.Bind( new IPEndPoint( includeIPv6 ? IPAddress.IPv6Any : IPAddress.Any, port)); } } }
agpl-3.0
C#
01bd97f4da951e05f4066056904f607aa7866c12
Add AssemblyBuilder
IEVin/PropertyChangedNotificator
src/Core/DynamicBuilder.cs
src/Core/DynamicBuilder.cs
using System; using System.Reflection; using System.Reflection.Emit; namespace NotifyAutoImplementer.Core { public static class DynamicBuilder { const string AssemblyBuilderName = "DynamicAssembly_871"; static Lazy<AssemblyBuilder> s_assemblyBuilder = new Lazy<AssemblyBuilder>( () => AppDomain.CurrentDomain.DefineDynamicAssembly( new AssemblyName( AssemblyBuilderName ), AssemblyBuilderAccess.Run ) ); public static T CreateInstanceProxy<T>() { return (T)CreateProxy( typeof(T) ); } static object CreateProxy( Type type ) { // stub return Activator.CreateInstance( type ); } } }
using System; namespace NotifyAutoImplementer.Core { public static class DynamicBuilder { public static T CreateInstanceProxy<T>() { return (T)CreateProxy( typeof(T) ); } static object CreateProxy( Type type ) { // stub return Activator.CreateInstance( type ); } } }
mit
C#
337dbd3080065e920367086cca31941bb71a384e
Add tests.
yeaicc/roslyn,eriawan/roslyn,abock/roslyn,jasonmalinowski/roslyn,jeffanders/roslyn,panopticoncentral/roslyn,khellang/roslyn,amcasey/roslyn,cston/roslyn,jamesqo/roslyn,orthoxerox/roslyn,davkean/roslyn,orthoxerox/roslyn,KevinRansom/roslyn,jamesqo/roslyn,diryboy/roslyn,mgoertz-msft/roslyn,jeffanders/roslyn,drognanar/roslyn,eriawan/roslyn,basoundr/roslyn,KevinRansom/roslyn,jaredpar/roslyn,wvdd007/roslyn,TyOverby/roslyn,mavasani/roslyn,khyperia/roslyn,OmarTawfik/roslyn,bartdesmet/roslyn,sharwell/roslyn,weltkante/roslyn,sharadagrawal/Roslyn,KevinH-MS/roslyn,vslsnap/roslyn,KirillOsenkov/roslyn,KevinH-MS/roslyn,xoofx/roslyn,heejaechang/roslyn,jhendrixMSFT/roslyn,AnthonyDGreen/roslyn,natidea/roslyn,Hosch250/roslyn,Hosch250/roslyn,zooba/roslyn,agocke/roslyn,tmeschter/roslyn,ericfe-ms/roslyn,OmarTawfik/roslyn,MattWindsor91/roslyn,ericfe-ms/roslyn,khyperia/roslyn,nguerrera/roslyn,xoofx/roslyn,TyOverby/roslyn,gafter/roslyn,KirillOsenkov/roslyn,genlu/roslyn,xasx/roslyn,AnthonyDGreen/roslyn,bkoelman/roslyn,rgani/roslyn,tmat/roslyn,dpoeschl/roslyn,AlekseyTs/roslyn,brettfo/roslyn,michalhosala/roslyn,heejaechang/roslyn,rgani/roslyn,ErikSchierboom/roslyn,Giftednewt/roslyn,mattscheffer/roslyn,genlu/roslyn,panopticoncentral/roslyn,mattwar/roslyn,tannergooding/roslyn,balajikris/roslyn,VSadov/roslyn,mattscheffer/roslyn,leppie/roslyn,mmitche/roslyn,KiloBravoLima/roslyn,AArnott/roslyn,davkean/roslyn,MatthieuMEZIL/roslyn,DustinCampbell/roslyn,dpoeschl/roslyn,robinsedlaczek/roslyn,tmeschter/roslyn,KiloBravoLima/roslyn,brettfo/roslyn,jcouv/roslyn,budcribar/roslyn,CaptainHayashi/roslyn,dotnet/roslyn,jkotas/roslyn,wvdd007/roslyn,paulvanbrenk/roslyn,stephentoub/roslyn,a-ctor/roslyn,reaction1989/roslyn,weltkante/roslyn,panopticoncentral/roslyn,jcouv/roslyn,Shiney/roslyn,mattwar/roslyn,basoundr/roslyn,sharwell/roslyn,heejaechang/roslyn,mmitche/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,pdelvo/roslyn,zooba/roslyn,zooba/roslyn,orthoxerox/roslyn,weltkante/roslyn,mattwar/roslyn,stephentoub/roslyn,ljw1004/roslyn,nguerrera/roslyn,dotnet/roslyn,KiloBravoLima/roslyn,xasx/roslyn,Pvlerick/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,abock/roslyn,jmarolf/roslyn,shyamnamboodiripad/roslyn,diryboy/roslyn,VSadov/roslyn,tvand7093/roslyn,rgani/roslyn,AmadeusW/roslyn,akrisiun/roslyn,reaction1989/roslyn,dpoeschl/roslyn,davkean/roslyn,cston/roslyn,vslsnap/roslyn,reaction1989/roslyn,srivatsn/roslyn,pdelvo/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,sharwell/roslyn,mattscheffer/roslyn,amcasey/roslyn,tmat/roslyn,akrisiun/roslyn,dotnet/roslyn,AArnott/roslyn,Shiney/roslyn,leppie/roslyn,brettfo/roslyn,mavasani/roslyn,natidea/roslyn,swaroop-sridhar/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,physhi/roslyn,Shiney/roslyn,bkoelman/roslyn,Hosch250/roslyn,DustinCampbell/roslyn,natidea/roslyn,wvdd007/roslyn,budcribar/roslyn,KevinRansom/roslyn,eriawan/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,gafter/roslyn,srivatsn/roslyn,balajikris/roslyn,physhi/roslyn,OmarTawfik/roslyn,jhendrixMSFT/roslyn,agocke/roslyn,vslsnap/roslyn,MattWindsor91/roslyn,tannergooding/roslyn,a-ctor/roslyn,kelltrick/roslyn,jkotas/roslyn,aelij/roslyn,gafter/roslyn,tmeschter/roslyn,srivatsn/roslyn,bbarry/roslyn,MichalStrehovsky/roslyn,akrisiun/roslyn,aelij/roslyn,jamesqo/roslyn,CaptainHayashi/roslyn,xasx/roslyn,mavasani/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,tvand7093/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,lorcanmooney/roslyn,mgoertz-msft/roslyn,ljw1004/roslyn,xoofx/roslyn,ErikSchierboom/roslyn,diryboy/roslyn,amcasey/roslyn,Pvlerick/roslyn,AmadeusW/roslyn,kelltrick/roslyn,robinsedlaczek/roslyn,balajikris/roslyn,a-ctor/roslyn,bbarry/roslyn,khyperia/roslyn,yeaicc/roslyn,agocke/roslyn,michalhosala/roslyn,MatthieuMEZIL/roslyn,ljw1004/roslyn,jaredpar/roslyn,KirillOsenkov/roslyn,leppie/roslyn,MichalStrehovsky/roslyn,bkoelman/roslyn,lorcanmooney/roslyn,Pvlerick/roslyn,nguerrera/roslyn,sharadagrawal/Roslyn,CyrusNajmabadi/roslyn,budcribar/roslyn,mmitche/roslyn,AlekseyTs/roslyn,Giftednewt/roslyn,jcouv/roslyn,MichalStrehovsky/roslyn,cston/roslyn,jmarolf/roslyn,swaroop-sridhar/roslyn,pdelvo/roslyn,AmadeusW/roslyn,jaredpar/roslyn,AlekseyTs/roslyn,jeffanders/roslyn,ericfe-ms/roslyn,robinsedlaczek/roslyn,MattWindsor91/roslyn,tvand7093/roslyn,MattWindsor91/roslyn,aelij/roslyn,jmarolf/roslyn,khellang/roslyn,abock/roslyn,DustinCampbell/roslyn,bbarry/roslyn,drognanar/roslyn,Giftednewt/roslyn,mgoertz-msft/roslyn,yeaicc/roslyn,paulvanbrenk/roslyn,KevinH-MS/roslyn,paulvanbrenk/roslyn,AArnott/roslyn,MatthieuMEZIL/roslyn,jasonmalinowski/roslyn,jkotas/roslyn,AnthonyDGreen/roslyn,physhi/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,michalhosala/roslyn,sharadagrawal/Roslyn,jhendrixMSFT/roslyn,kelltrick/roslyn,shyamnamboodiripad/roslyn,drognanar/roslyn,CyrusNajmabadi/roslyn,stephentoub/roslyn,TyOverby/roslyn,VSadov/roslyn,khellang/roslyn,genlu/roslyn,basoundr/roslyn,bartdesmet/roslyn
src/Workspaces/CoreTest/UtilityTest/SpellCheckerTests.cs
src/Workspaces/CoreTest/UtilityTest/SpellCheckerTests.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.UtilityTest { public class WordSimilarityCheckerTests { [Fact] public void TestCloseMatch() { Assert.False(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "variabledeclaratorsyntaxextensions")); Assert.True(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "variabledeclaratorsyntaxextensions", substringsAreSimilar: true)); Assert.False(WordSimilarityChecker.AreSimilar("expressionsyntax", "expressionsyntaxextensions")); Assert.True(WordSimilarityChecker.AreSimilar("expressionsyntax", "expressionsyntaxextensions", substringsAreSimilar: true)); Assert.False(WordSimilarityChecker.AreSimilar("expressionsyntax", "expressionsyntaxgeneratorvisitor")); Assert.True(WordSimilarityChecker.AreSimilar("expressionsyntax", "expressionsyntaxgeneratorvisitor", substringsAreSimilar: true)); } [Fact] public void TestNotCloseMatch() { Assert.False(WordSimilarityChecker.AreSimilar("propertyblocksyntax", "ipropertysymbol")); Assert.False(WordSimilarityChecker.AreSimilar("propertyblocksyntax", "ipropertysymbolextensions")); Assert.False(WordSimilarityChecker.AreSimilar("propertyblocksyntax", "typeblocksyntaxextensions")); Assert.False(WordSimilarityChecker.AreSimilar("fielddeclarationsyntax", "declarationinfo")); Assert.False(WordSimilarityChecker.AreSimilar("fielddeclarationsyntax", "declarationcomputer")); Assert.False(WordSimilarityChecker.AreSimilar("fielddeclarationsyntax", "filelinepositionspan")); Assert.False(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "visualbasicdeclarationcomputer")); Assert.False(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "ilineseparatorservice")); Assert.False(WordSimilarityChecker.AreSimilar("expressionsyntax", "awaitexpressioninfo")); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Roslyn.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.UnitTests.UtilityTest { public class WordSimilarityCheckerTests { [Fact] public void TestCloseMatch() { Assert.True(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "variabledeclaratorsyntaxextensions")); Assert.True(WordSimilarityChecker.AreSimilar("expressionsyntax", "expressionsyntaxextensions")); Assert.True(WordSimilarityChecker.AreSimilar("expressionsyntax", "expressionsyntaxgeneratorvisitor")); } [Fact] public void TestNotCloseMatch() { Assert.False(WordSimilarityChecker.AreSimilar("propertyblocksyntax", "ipropertysymbol")); Assert.False(WordSimilarityChecker.AreSimilar("propertyblocksyntax", "ipropertysymbolextensions")); Assert.False(WordSimilarityChecker.AreSimilar("propertyblocksyntax", "typeblocksyntaxextensions")); Assert.False(WordSimilarityChecker.AreSimilar("fielddeclarationsyntax", "declarationinfo")); Assert.False(WordSimilarityChecker.AreSimilar("fielddeclarationsyntax", "declarationcomputer")); Assert.False(WordSimilarityChecker.AreSimilar("fielddeclarationsyntax", "filelinepositionspan")); Assert.False(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "visualbasicdeclarationcomputer")); Assert.False(WordSimilarityChecker.AreSimilar("variabledeclaratorsyntax", "ilineseparatorservice")); Assert.False(WordSimilarityChecker.AreSimilar("expressionsyntax", "awaitexpressioninfo")); } } }
mit
C#
c1da5b3925c18c61ca700bc7d0b301e9fd60ac47
Make Maybe immutable.
j2jensen/CallMeMaybe
CallMeMaybe/Maybe.cs
CallMeMaybe/Maybe.cs
namespace CallMeMaybe { public struct Maybe<T> { private readonly T value; private readonly bool _hasValue; public bool HasValue { get { return _hasValue; } } } }
namespace CallMeMaybe { public struct Maybe<T> { private T value; private bool _hasValue; public bool HasValue { get { return _hasValue; } } } }
mit
C#
ee052f804dd963488e1087646fab90a8e02e03c2
Add abstract GetValidMoves
ProgramFOX/Chess.NET
ChessDotNet/Piece.cs
ChessDotNet/Piece.cs
using System.Collections.ObjectModel; namespace ChessDotNet { public abstract class Piece { public abstract Player Owner { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj == null || GetType() != obj.GetType()) return false; Piece piece1 = this; Piece piece2 = (Piece)obj; return piece1.Owner == piece2.Owner; } public override int GetHashCode() { return new { Piece = GetFenCharacter(), Owner }.GetHashCode(); } public static bool operator ==(Piece piece1, Piece piece2) { if (ReferenceEquals(piece1, piece2)) return true; if ((object)piece1 == null || (object)piece2 == null) return false; return piece1.Equals(piece2); } public static bool operator !=(Piece piece1, Piece piece2) { if (ReferenceEquals(piece1, piece2)) return false; if ((object)piece1 == null || (object)piece2 == null) return true; return !piece1.Equals(piece2); } public abstract char GetFenCharacter(); public abstract bool IsValidMove(Move move, ChessGame game); public abstract float GetRelativePieceValue(); public abstract ReadOnlyCollection<Move> GetValidMoves(Position from, bool returnIfAny, ChessGame game); } }
namespace ChessDotNet { public abstract class Piece { public abstract Player Owner { get; set; } public override bool Equals(object obj) { if (ReferenceEquals(this, obj)) return true; if (obj == null || GetType() != obj.GetType()) return false; Piece piece1 = this; Piece piece2 = (Piece)obj; return piece1.Owner == piece2.Owner; } public override int GetHashCode() { return new { Piece = GetFenCharacter(), Owner }.GetHashCode(); } public static bool operator ==(Piece piece1, Piece piece2) { if (ReferenceEquals(piece1, piece2)) return true; if ((object)piece1 == null || (object)piece2 == null) return false; return piece1.Equals(piece2); } public static bool operator !=(Piece piece1, Piece piece2) { if (ReferenceEquals(piece1, piece2)) return false; if ((object)piece1 == null || (object)piece2 == null) return true; return !piece1.Equals(piece2); } public abstract char GetFenCharacter(); public abstract bool IsValidMove(Move move, ChessGame game); public abstract float GetRelativePieceValue(); } }
mit
C#
26b001c7eee93fedc1c3ff8811555ac6a1551d46
Improve performance counter test stability
mvno/Okanshi,mvno/Okanshi,mvno/Okanshi
tests/Okanshi.Tests/PerformanceCounterTest.cs
tests/Okanshi.Tests/PerformanceCounterTest.cs
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 500000, "Because memory usage can change between the two values"); } } }
using System.Diagnostics; using FluentAssertions; using Xunit; namespace Okanshi.Test { public class PerformanceCounterTest { [Fact] public void Performance_counter_without_instance_name() { var performanceCounter = new PerformanceCounter("Memory", "Available Bytes"); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Memory", "Available Bytes")); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 100000, "Because memory usage can change between the two values"); } [Fact] public void Performance_counter_with_instance_name() { var performanceCounter = new PerformanceCounter("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName); var monitor = new PerformanceCounterMonitor(MonitorConfig.Build("Test"), PerformanceCounterConfig.Build("Process", "Private Bytes", Process.GetCurrentProcess().ProcessName)); monitor.GetValue() .Should() .BeGreaterThan(0) .And.BeApproximately(performanceCounter.NextValue(), 100000, "Because memory usage can change between the two values"); } } }
mit
C#
ba888d685eda2cdf078f122a980a78dbf13e794e
Update version to 1.0.1
logjam2/logjam,logjam2/logjam
build/Version.cs
build/Version.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Version.cs"> // Copyright (c) 2011-2014 logjam.codeplex.com. // </copyright> // Licensed under the <a href="http://logjam.codeplex.com/license">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Reflection; // 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. #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("LogJam Contributors")] [assembly: AssemblyProduct("LogJam")] [assembly: AssemblyCopyright("Copyright 2011-2015")] // 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")] // Semantic version (http://semver.org). Assembly version changes less than the semver; semver must increment for every release. [assembly: AssemblyInformationalVersion("1.0.1-beta")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Version.cs"> // Copyright (c) 2011-2014 logjam.codeplex.com. // </copyright> // Licensed under the <a href="http://logjam.codeplex.com/license">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Reflection; // 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. #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("LogJam Contributors")] [assembly: AssemblyProduct("LogJam")] [assembly: AssemblyCopyright("Copyright 2011-2015")] // 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")] // Semantic version (http://semver.org). Assembly version changes less than the semver; semver must increment for every release. [assembly: AssemblyInformationalVersion("1.0.0-beta")]
apache-2.0
C#
89613208f1e5211101eaf92e36775733f8a20515
remove TODO
StefanoFiumara/Harry-Potter-Unity
Assets/Scripts/HarryPotterUnity/Cards/CareOfMagicalCreatures/Items/GuideToHouseholdPests.cs
Assets/Scripts/HarryPotterUnity/Cards/CareOfMagicalCreatures/Items/GuideToHouseholdPests.cs
using System.Collections.Generic; using System.Linq; using HarryPotterUnity.Cards.BasicBehavior; using HarryPotterUnity.Cards.PlayRequirements; using UnityEngine; namespace HarryPotterUnity.Cards.CareOfMagicalCreatures.Items { [RequireComponent(typeof(InputRequirement))] public class GuideToHouseholdPests : ItemLessonProvider { public override List<BaseCard> GetInPlayActionTargets() { return Player.OppositePlayer.InPlay.Creatures.Concat(Player.InPlay.Creatures).ToList(); } public override bool CanPerformInPlayAction() { return Player.IsLocalPlayer && Player.CanUseActions(); } public override void OnInPlayAction(List<BaseCard> targets = null) { if (targets != null) { Player.Discard.Add(this); var target = targets.First(); ((BaseCreature)target).TakeDamage(4); Player.UseActions(); } } } }
using System.Collections.Generic; using System.Linq; using HarryPotterUnity.Cards.BasicBehavior; using HarryPotterUnity.Cards.PlayRequirements; using UnityEngine; namespace HarryPotterUnity.Cards.CareOfMagicalCreatures.Items { [RequireComponent(typeof(InputRequirement))] public class GuideToHouseholdPests : ItemLessonProvider { public override List<BaseCard> GetInPlayActionTargets() { return Player.OppositePlayer.InPlay.Creatures.Concat(Player.InPlay.Creatures).ToList(); } public override bool CanPerformInPlayAction() { return Player.IsLocalPlayer && Player.CanUseActions(); } //TODO: Test this public override void OnInPlayAction(List<BaseCard> targets = null) { if (targets != null) { Player.Discard.Add(this); var target = targets.First(); ((BaseCreature)target).TakeDamage(4); Player.UseActions(); } } } }
mit
C#
7315d2a3511966af71d59e2f974077fe8a95ad63
make example main async
nopara73/DotNetTor
src/DotNetTor.Example/Program.cs
src/DotNetTor.Example/Program.cs
using System; using System.Net.Http; using DotNetTor.SocksPort; using System.Linq; using System.IO; using System.Threading.Tasks; namespace DotNetTor.Example { public class Program { // For proper configuraion see https://github.com/nopara73/DotNetTor #pragma warning disable IDE1006 // Naming Styles private static async Task Main() #pragma warning restore IDE1006 // Naming Styles { await DoARandomRequestAsync(); await RequestWith3IpAsync(); await CanRequestDifferentDomainsWithSameHandlerAsync(); Console.WriteLine("Press a key to exit.."); Console.ReadKey(); } private static async Task DoARandomRequestAsync() { using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", 9050))) { HttpResponseMessage message = await httpClient.GetAsync("http://api.qbit.ninja/whatisit/what%20is%20my%20future"); var content = await message.Content.ReadAsStringAsync(); Console.WriteLine(content); } } private static async Task RequestWith3IpAsync() { var requestUri = "https://api.ipify.org/"; // 1. Get real IP using (var httpClient = new HttpClient()) { var message = await httpClient.GetAsync(requestUri); var content = await message.Content.ReadAsStringAsync(); Console.WriteLine($"Your real IP: \t\t{content}"); } // 2. Get TOR IP using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", socksPort: 9050))) { var message = await httpClient.GetAsync(requestUri); var content = await message.Content.ReadAsStringAsync(); Console.WriteLine($"Your TOR IP: \t\t{content}"); // 3. Change TOR IP var controlPortClient = new ControlPort.Client("127.0.0.1", controlPort: 9051, password: "ILoveBitcoin21"); await controlPortClient.ChangeCircuitAsync(); // 4. Get changed TOR IP message = await httpClient.GetAsync(requestUri); content = await message.Content.ReadAsStringAsync(); Console.WriteLine($"Your other TOR IP: \t{content}"); } } private static async Task CanRequestDifferentDomainsWithSameHandlerAsync() { using (var httpClient = new HttpClient(new SocksPortHandler())) { var message = await httpClient.GetAsync("https://api.ipify.org/"); var content = await message.Content.ReadAsStringAsync(); Console.WriteLine($"Your TOR IP: \t\t{content}"); try { message = await httpClient.GetAsync("http://api.qbit.ninja/whatisit/what%20is%20my%20future"); content = await message.Content.ReadAsStringAsync(); Console.WriteLine(content); } catch (AggregateException ex) when (ex.InnerException is TorException) { Console.WriteLine("Don't do this!"); Console.WriteLine(ex.InnerException.Message); } } } } }
using System; using System.Net.Http; using DotNetTor.SocksPort; using System.Linq; using System.IO; namespace DotNetTor.Example { public class Program { // For proper configuraion see https://github.com/nopara73/DotNetTor private static void Main() { DoARandomRequest(); RequestWith3Ip(); //CanRequestDifferentDomainsWithSameHandler(); Console.WriteLine("Press a key to exit.."); Console.ReadKey(); } private static void DoARandomRequest() { using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", 9050))) { HttpResponseMessage message = httpClient.GetAsync("http://api.qbit.ninja/whatisit/what%20is%20my%20future").Result; var content = message.Content.ReadAsStringAsync().Result; Console.WriteLine(content); } } private static void RequestWith3Ip() { var requestUri = "https://api.ipify.org/"; // 1. Get real IP using (var httpClient = new HttpClient()) { var message = httpClient.GetAsync(requestUri).Result; var content = message.Content.ReadAsStringAsync().Result; Console.WriteLine($"Your real IP: \t\t{content}"); } // 2. Get TOR IP using (var httpClient = new HttpClient(new SocksPortHandler("127.0.0.1", socksPort: 9050))) { var message = httpClient.GetAsync(requestUri).Result; var content = message.Content.ReadAsStringAsync().Result; Console.WriteLine($"Your TOR IP: \t\t{content}"); // 3. Change TOR IP var controlPortClient = new ControlPort.Client("127.0.0.1", controlPort: 9051, password: "ILoveBitcoin21"); controlPortClient.ChangeCircuitAsync().Wait(); // 4. Get changed TOR IP message = httpClient.GetAsync(requestUri).Result; content = message.Content.ReadAsStringAsync().Result; Console.WriteLine($"Your other TOR IP: \t{content}"); } } private static void CanRequestDifferentDomainsWithSameHandler() { using (var httpClient = new HttpClient(new SocksPortHandler())) { var message = httpClient.GetAsync("https://api.ipify.org/").Result; var content = message.Content.ReadAsStringAsync().Result; Console.WriteLine($"Your TOR IP: \t\t{content}"); try { message = httpClient.GetAsync("http://api.qbit.ninja/whatisit/what%20is%20my%20future").Result; content = message.Content.ReadAsStringAsync().Result; Console.WriteLine(content); } catch (AggregateException ex) when (ex.InnerException is TorException) { Console.WriteLine("Don't do this!"); Console.WriteLine(ex.InnerException.Message); } } } } }
mit
C#
da5eb470ca84601db3de3df74f6ca4aaf6662d77
exit Agent by return 0
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
src/FilterLists.Agent/Program.cs
src/FilterLists.Agent/Program.cs
using System; using System.IO; using FilterLists.Services.DependencyInjection.Extensions; using FilterLists.Services.SnapshotService; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace FilterLists.Agent { public class Program { private static TelemetryClient telemetryClient; private static ServiceProvider serviceProvider; private static IConfigurationRoot configurationRoot; public static int Main(string[] args) { InstantiateConfigurationRoot(); InstantiateTelemetryClient(); InstantiateServiceProvider(); //TODO: capture batchSize from args const int batchSize = 1; CaptureSnapshots(batchSize); return 0; } private static void InstantiateConfigurationRoot() { configurationRoot = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .Build(); } private static void InstantiateTelemetryClient() { TelemetryConfiguration.Active.InstrumentationKey = configurationRoot["ApplicationInsights:InstrumentationKey"]; telemetryClient = new TelemetryClient(); } private static void InstantiateServiceProvider() { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); serviceProvider = serviceCollection.BuildServiceProvider(); } private static void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddFilterListsServices(configurationRoot); } private static void CaptureSnapshots(int batchSize) { var snapshotService = serviceProvider.GetService<SnapshotService>(); Log("Capturing FilterList snapshots..."); snapshotService.CaptureSnapshotsAsync(batchSize).Wait(); Log("\nSnapshots captured."); telemetryClient.Flush(); } private static void Log(string message) { Console.WriteLine(message); telemetryClient.TrackTrace(message); } } }
using System; using System.IO; using FilterLists.Services.DependencyInjection.Extensions; using FilterLists.Services.SnapshotService; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace FilterLists.Agent { public class Program { private static TelemetryClient telemetryClient; private static ServiceProvider serviceProvider; private static IConfigurationRoot configurationRoot; public static void Main(string[] args) { InstantiateConfigurationRoot(); InstantiateTelemetryClient(); InstantiateServiceProvider(); //TODO: capture batchSize from args const int batchSize = 1; CaptureSnapshots(batchSize); } private static void InstantiateConfigurationRoot() { configurationRoot = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .Build(); } private static void InstantiateTelemetryClient() { TelemetryConfiguration.Active.InstrumentationKey = configurationRoot["ApplicationInsights:InstrumentationKey"]; telemetryClient = new TelemetryClient(); } private static void InstantiateServiceProvider() { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); serviceProvider = serviceCollection.BuildServiceProvider(); } private static void ConfigureServices(IServiceCollection serviceCollection) { serviceCollection.AddFilterListsServices(configurationRoot); } private static void CaptureSnapshots(int batchSize) { var snapshotService = serviceProvider.GetService<SnapshotService>(); Log("Capturing FilterList snapshots..."); snapshotService.CaptureSnapshotsAsync(batchSize).Wait(); Log("\nSnapshots captured."); telemetryClient.Flush(); } private static void Log(string message) { Console.WriteLine(message); telemetryClient.TrackTrace(message); } } }
mit
C#
ac054ca27bf6ee35c318d5a47a3434dc17c1bbb0
Write dump.log in the temp directory
murador/xsp,arthot/xsp,arthot/xsp,murador/xsp,arthot/xsp,stormleoxia/xsp,stormleoxia/xsp,murador/xsp,arthot/xsp,murador/xsp,stormleoxia/xsp,stormleoxia/xsp
test/DumpExtension.cs
test/DumpExtension.cs
// // DumpExtension.cs // // Author: // Lluis Sanchez Gual ([email protected]) // // Copyright (C) Ximian, Inc. 2003 // using System; using System.Text; using System.Web.Services; using System.Web.Services.Protocols; using System.IO; using System.Net; public class DumpExtension : SoapExtension { Stream oldStream; MemoryStream newStream; string filename = "dump.log"; bool dump; public DumpExtension () { } public override Stream ChainStream( Stream stream ) { if (!dump) return stream; oldStream = stream; newStream = new MemoryStream (); return newStream; } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return false; } public override object GetInitializer(Type webServiceType) { if (webServiceType.GetCustomAttributes (typeof (DumpAttribute), false).Length > 0) return true; else return false; } public override void Initialize(object initializer) { dump = (bool) initializer; } public override void ProcessMessage(SoapMessage message) { if (!dump) return; switch (message.Stage) { case SoapMessageStage.BeforeSerialize: break; case SoapMessageStage.AfterSerialize: DumpOut (); break; case SoapMessageStage.BeforeDeserialize: DumpIn (); break; case SoapMessageStage.AfterDeserialize: break; default: throw new Exception("invalid stage"); } } public void DumpOut () { Dump (newStream, ">> Outgoing"); newStream.WriteTo (oldStream); } public void DumpIn () { byte[] buffer = new byte[1000]; int n=0; while ((n=oldStream.Read (buffer, 0, 1000)) > 0) newStream.Write (buffer, 0, n); newStream.Position = 0; Dump (newStream, ">> Incoming"); } public void Dump (MemoryStream stream, string msg) { string fn = Path.Combine (Path.GetTempPath (), filename); FileStream fs = new FileStream (fn, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter (fs); sw.WriteLine (); sw.WriteLine (msg); sw.Flush (); stream.WriteTo (fs); fs.Close (); stream.Position = 0; } } public class DumpAttribute: Attribute { }
// // DumpExtension.cs // // Author: // Lluis Sanchez Gual ([email protected]) // // Copyright (C) Ximian, Inc. 2003 // using System; using System.Text; using System.Web.Services; using System.Web.Services.Protocols; using System.IO; using System.Net; public class DumpExtension : SoapExtension { Stream oldStream; MemoryStream newStream; string filename = "dump.log"; bool dump; public DumpExtension () { } public override Stream ChainStream( Stream stream ) { if (!dump) return stream; oldStream = stream; newStream = new MemoryStream (); return newStream; } public override object GetInitializer(LogicalMethodInfo methodInfo, SoapExtensionAttribute attribute) { return false; } public override object GetInitializer(Type webServiceType) { if (webServiceType.GetCustomAttributes (typeof (DumpAttribute), false).Length > 0) return true; else return false; } public override void Initialize(object initializer) { dump = (bool) initializer; } public override void ProcessMessage(SoapMessage message) { if (!dump) return; switch (message.Stage) { case SoapMessageStage.BeforeSerialize: break; case SoapMessageStage.AfterSerialize: DumpOut (); break; case SoapMessageStage.BeforeDeserialize: DumpIn (); break; case SoapMessageStage.AfterDeserialize: break; default: throw new Exception("invalid stage"); } } public void DumpOut () { Dump (newStream, ">> Outgoing"); newStream.WriteTo (oldStream); } public void DumpIn () { byte[] buffer = new byte[1000]; int n=0; while ((n=oldStream.Read (buffer, 0, 1000)) > 0) newStream.Write (buffer, 0, n); newStream.Position = 0; Dump (newStream, ">> Incoming"); } public void Dump (MemoryStream stream, string msg) { FileStream fs = new FileStream(filename, FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter (fs); sw.WriteLine (); sw.WriteLine (msg); sw.Flush (); stream.WriteTo (fs); fs.Close (); stream.Position = 0; } } public class DumpAttribute: Attribute { }
mit
C#
25a8e998f47bad109b875d8832a822570eb74c7e
Fix error when deserializing response with BodySize set to null (tested with HAR file exported with Firefox).
giacomelli/HarSharp
src/HarSharp/MessageBase.cs
src/HarSharp/MessageBase.cs
using System.Collections.Generic; namespace HarSharp { /// <summary> /// A base class for HTTP messages. /// </summary> public abstract class MessageBase : EntityBase { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MessageBase"/> class. /// </summary> protected MessageBase() { Cookies = new List<Cookie>(); Headers = new List<Header>(); } #endregion #region Properties /// <summary> /// Gets or sets the HTTP Version. /// </summary> public string HttpVersion { get; set; } /// <summary> /// Gets the list of cookie objects. /// </summary> public IList<Cookie> Cookies { get; private set; } /// <summary> /// Gets the list of header objects. /// </summary> public IList<Header> Headers { get; private set; } /// <summary> /// Gets or sets the total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. /// </summary> public int HeadersSize { get; set; } /// <summary> /// Gets or sets the size of the request body (POST data payload) in bytes. /// </summary> public int? BodySize { get; set; } #endregion } }
using System.Collections.Generic; namespace HarSharp { /// <summary> /// A base class for HTTP messages. /// </summary> public abstract class MessageBase : EntityBase { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="MessageBase"/> class. /// </summary> protected MessageBase() { Cookies = new List<Cookie>(); Headers = new List<Header>(); } #endregion #region Properties /// <summary> /// Gets or sets the HTTP Version. /// </summary> public string HttpVersion { get; set; } /// <summary> /// Gets the list of cookie objects. /// </summary> public IList<Cookie> Cookies { get; private set; } /// <summary> /// Gets the list of header objects. /// </summary> public IList<Header> Headers { get; private set; } /// <summary> /// Gets or sets the total number of bytes from the start of the HTTP request message until (and including) the double CRLF before the body. /// </summary> public int HeadersSize { get; set; } /// <summary> /// Gets or sets the size of the request body (POST data payload) in bytes. /// </summary> public int BodySize { get; set; } #endregion } }
mit
C#
2c07c178de8ea0f27877788ac97f38f20160b346
Remove reference to obsolete `searchHighlight()` javascript function from ClearSilver footer template.
netjunki/trac-Pygit2,netjunki/trac-Pygit2,walty8/trac,jun66j5/trac-ja,netjunki/trac-Pygit2,jun66j5/trac-ja,walty8/trac,walty8/trac,jun66j5/trac-ja,jun66j5/trac-ja,walty8/trac
templates/footer.cs
templates/footer.cs
<?cs if:len(chrome.links.alternate) ?> <div id="altlinks"><h3>Download in other formats:</h3><ul><?cs each:link = chrome.links.alternate ?><?cs set:isfirst = name(link) == 0 ?><?cs set:islast = name(link) == len(chrome.links.alternate) - 1?><li<?cs if:isfirst || islast ?> class="<?cs if:isfirst ?>first<?cs /if ?><?cs if:isfirst && islast ?> <?cs /if ?><?cs if:islast ?>last<?cs /if ?>"<?cs /if ?>><a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a></li><?cs /each ?></ul></div><?cs /if ?> </div> <div id="footer"> <hr /> <a id="tracpowered" href="http://trac.edgewall.org/"><img src="<?cs var:htdocs_location ?>trac_logo_mini.png" height="30" width="107" alt="Trac Powered"/></a> <p class="left"> Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs var:trac.version ?></strong></a><br /> By <a href="http://www.edgewall.org/">Edgewall Software</a>. </p> <p class="right"> <?cs var:project.footer ?> </p> </div> <?cs include "site_footer.cs" ?> </body> </html>
<script type="text/javascript">searchHighlight()</script><?cs if:len(chrome.links.alternate) ?> <div id="altlinks"><h3>Download in other formats:</h3><ul><?cs each:link = chrome.links.alternate ?><?cs set:isfirst = name(link) == 0 ?><?cs set:islast = name(link) == len(chrome.links.alternate) - 1?><li<?cs if:isfirst || islast ?> class="<?cs if:isfirst ?>first<?cs /if ?><?cs if:isfirst && islast ?> <?cs /if ?><?cs if:islast ?>last<?cs /if ?>"<?cs /if ?>><a href="<?cs var:link.href ?>"<?cs if:link.class ?> class="<?cs var:link.class ?>"<?cs /if ?>><?cs var:link.title ?></a></li><?cs /each ?></ul></div><?cs /if ?> </div> <div id="footer"> <hr /> <a id="tracpowered" href="http://trac.edgewall.org/"><img src="<?cs var:htdocs_location ?>trac_logo_mini.png" height="30" width="107" alt="Trac Powered"/></a> <p class="left"> Powered by <a href="<?cs var:trac.href.about ?>"><strong>Trac <?cs var:trac.version ?></strong></a><br /> By <a href="http://www.edgewall.org/">Edgewall Software</a>. </p> <p class="right"> <?cs var:project.footer ?> </p> </div> <?cs include "site_footer.cs" ?> </body> </html>
bsd-3-clause
C#
15d7e187d91c6bdb5015f4b49557e7bd8f35d4b5
Update GetProviderUsersRequest.cs
SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/ApprovalsOuterApi/GetProviderUsersRequest.cs
src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/ApprovalsOuterApi/GetProviderUsersRequest.cs
using System; using System.Collections.Generic; using System.Text; namespace SFA.DAS.CommitmentsV2.Models.ApprovalsOuterApi { public class GetProviderUsersRequest : IGetApiRequest { public long Ukprn { get; } public GetProviderUsersRequest(long ukprn) { Ukprn = ukprn; } public string GetUrl => $"providers/{Ukprn}/users"; } }
using System; using System.Collections.Generic; using System.Text; namespace SFA.DAS.CommitmentsV2.Models.ApprovalsOuterApi { public class GetProviderUsersRequest : IGetApiRequest { public long Ukprn { get; } public GetProviderUsersRequest(long ukprn) { Ukprn = ukprn; } public string GetUrl => $"/providers/{Ukprn}/users"; } }
mit
C#
a1a1d80625d70e99fa2fbd8185d1bc33b91222c9
add ImageTargetTestData
OlegKleyman/Omego.Selenium
tests/unit/Omego.Selenium.Tests.Unit/ImageTargetTests.cs
tests/unit/Omego.Selenium.Tests.Unit/ImageTargetTests.cs
namespace Omego.Selenium.Tests.Unit { public class ImageTargetTests { private class ImageTargetTestData { } } }
namespace Omego.Selenium.Tests.Unit { public class ImageTargetTests { } }
unlicense
C#
2e35d0e1780af1e83cc09f5fb7c3f319e8fd17e3
Fix coldcard wallet export path (#2809)
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
BTCPayServer/Views/Stores/ImportWallet/File.cshtml
BTCPayServer/Views/Stores/ImportWallet/File.cshtml
@model WalletSetupViewModel @addTagHelper *, BundlerMinifier.TagHelpers @{ Layout = "_LayoutWalletSetup"; ViewData.SetActivePageAndTitle(StoreNavPages.Wallet, "Import your wallet file", Context.GetStoreData().StoreName); } @section Navbar { <a asp-controller="Stores" asp-action="ImportWallet" asp-route-storeId="@Model.StoreId" asp-route-cryptoCode="@Model.CryptoCode" asp-route-method=""> <vc:icon symbol="back" /> </a> } <header class="text-center"> <h1>@ViewData["Title"]</h1> <p class="lead text-secondary mt-3">Upload the file exported from your wallet.</p> </header> <form method="post" enctype="multipart/form-data" class="my-5"> <div class="form-group"> <label asp-for="WalletFile" class="form-label"></label> <input asp-for="WalletFile" type="file" class="form-control" required> <span asp-validation-for="WalletFile" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Continue</button> </form> <table class="table table-sm"> <thead> <tr> <th>Wallet</th> <th>Instructions</th> </tr> </thead> <tbody> <tr> <td class="text-nowrap">Cobo Vault</td> <td>Settings ❯ Watch-Only Wallet ❯ BTCPay ❯ Export Wallet</td> </tr> <tr> <td>ColdCard</td> <td>Advanced ❯ MicroSD Card ❯ Export Wallet ❯ Electrum Wallet</td> </tr> <tr> <td>Electrum</td> <td>File ❯ Save backup (not encrypted with a password)</td> </tr> <tr> <td>Wasabi</td> <td>Tools ❯ Wallet Manager ❯ Open Wallets Folder</td> </tr> <tr> <td class="text-nowrap">Specter Desktop</td> <td>Wallet ❯ Settings ❯ Export ❯ Export To Wallet Software ❯ Save wallet file</td> </tr> </tbody> </table>
@model WalletSetupViewModel @addTagHelper *, BundlerMinifier.TagHelpers @{ Layout = "_LayoutWalletSetup"; ViewData.SetActivePageAndTitle(StoreNavPages.Wallet, "Import your wallet file", Context.GetStoreData().StoreName); } @section Navbar { <a asp-controller="Stores" asp-action="ImportWallet" asp-route-storeId="@Model.StoreId" asp-route-cryptoCode="@Model.CryptoCode" asp-route-method=""> <vc:icon symbol="back" /> </a> } <header class="text-center"> <h1>@ViewData["Title"]</h1> <p class="lead text-secondary mt-3">Upload the file exported from your wallet.</p> </header> <form method="post" enctype="multipart/form-data" class="my-5"> <div class="form-group"> <label asp-for="WalletFile" class="form-label"></label> <input asp-for="WalletFile" type="file" class="form-control" required> <span asp-validation-for="WalletFile" class="text-danger"></span> </div> <button type="submit" class="btn btn-primary">Continue</button> </form> <table class="table table-sm"> <thead> <tr> <th>Wallet</th> <th>Instructions</th> </tr> </thead> <tbody> <tr> <td class="text-nowrap">Cobo Vault</td> <td>Settings ❯ Watch-Only Wallet ❯ BTCPay ❯ Export Wallet</td> </tr> <tr> <td>ColdCard</td> <td>Advanced ❯ MicroSD Card ❯ Electrum Wallet</td> </tr> <tr> <td>Electrum</td> <td>File ❯ Save backup (not encrypted with a password)</td> </tr> <tr> <td>Wasabi</td> <td>Tools ❯ Wallet Manager ❯ Open Wallets Folder</td> </tr> <tr> <td class="text-nowrap">Specter Desktop</td> <td>Wallet ❯ Settings ❯ Export ❯ Export To Wallet Software ❯ Save wallet file</td> </tr> </tbody> </table>
mit
C#
0e39951d482ec771b2b4d53243e48c64cb805a15
Add total row
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/UnitStatsViewModel.cs
Battery-Commander.Web/Models/UnitStatsViewModel.cs
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using static BatteryCommander.Web.Models.Soldier; namespace BatteryCommander.Web.Models { public class UnitStatsViewModel { public Unit Unit { get; set; } // Assigned Passed Failed Not Tested % Pass/Assigned public Stat ABCP { get; set; } = new Stat { }; public Stat APFT { get; set; } = new Stat { }; public ICollection<SSDStat> SSD { get; set; } = new List<SSDStat>(); public SSDStat SSDTotal => new SSDStat { Assigned = SSD.Select(s => s.Assigned).Sum(), Completed = SSD.Select(s => s.Completed).Sum() }; public class SSDStat { public Rank Rank { get; set; } public int Assigned { get; set; } public int Completed { get; set; } [DisplayFormat(DataFormatString = SSDStatusModel.Format)] public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero; } public class Stat { public int Assigned { get; set; } public int Passed { get; set; } public int Failed { get; set; } [Display(Name = "Not Tested")] public int NotTested { get; set; } [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.Format)] public Decimal PercentPass => (Decimal)Passed / Assigned; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using static BatteryCommander.Web.Models.Soldier; namespace BatteryCommander.Web.Models { public class UnitStatsViewModel { public Unit Unit { get; set; } // Assigned Passed Failed Not Tested % Pass/Assigned public Stat ABCP { get; set; } = new Stat { }; public Stat APFT { get; set; } = new Stat { }; public ICollection<SSDStat> SSD { get; set; } = new List<SSDStat>(); public class SSDStat { public Rank Rank { get; set; } public int Assigned { get; set; } public int Completed { get; set; } [DisplayFormat(DataFormatString = SSDStatusModel.Format)] public Decimal Percentage => Assigned > 0 ? (Decimal)Completed / Assigned : Decimal.Zero; } public class Stat { public int Assigned { get; set; } public int Passed { get; set; } public int Failed { get; set; } [Display(Name = "Not Tested")] public int NotTested { get; set; } [Display(Name = "Pass %"), DisplayFormat(DataFormatString = SSDStatusModel.Format)] public Decimal PercentPass => (Decimal)Passed / Assigned; } } }
mit
C#
d324fe0f202790030a4deb99080e0c427cee52e4
Remove irrelevant AppDomain usages from ConsoleTestAppDomain's net452 implementation. These usages are irrelevant now that the test assembly *is* the console application, so all assembly loading and config file concerns are already correct in the primary/default AppDomain already in effect.
fixie/fixie
src/Fixie/Execution/ConsoleTestAppDomain.cs
src/Fixie/Execution/ConsoleTestAppDomain.cs
namespace Fixie.Execution { #if NET452 using System; class ConsoleTestAppDomain : IDisposable { public ConsoleTestAppDomain(string assemblyFullPath) { } public T CreateFrom<T>() where T : LongLivedMarshalByRefObject, new() => new T(); public T Create<T>(params object[] arguments) where T : LongLivedMarshalByRefObject => (T)Activator.CreateInstance(typeof(T), arguments); public void Dispose() { } } #else using System; class ConsoleTestAppDomain : IDisposable { public ConsoleTestAppDomain(string assemblyFullPath) { } public T CreateFrom<T>() where T : LongLivedMarshalByRefObject, new() => new T(); public T Create<T>(params object[] arguments) where T : LongLivedMarshalByRefObject => (T)Activator.CreateInstance(typeof(T), arguments); public void Dispose() { } } #endif }
namespace Fixie.Execution { #if NET452 using System; using System.IO; using System.Security; using System.Security.Permissions; class ConsoleTestAppDomain : IDisposable { readonly AppDomain appDomain; public ConsoleTestAppDomain(string assemblyFullPath) { var setup = new AppDomainSetup { ApplicationBase = Path.GetDirectoryName(assemblyFullPath), ApplicationName = Guid.NewGuid().ToString(), ConfigurationFile = GetOptionalConfigFullPath(assemblyFullPath) }; appDomain = AppDomain.CreateDomain(setup.ApplicationName, null, setup, new PermissionSet(PermissionState.Unrestricted)); } public T CreateFrom<T>() where T : LongLivedMarshalByRefObject, new() { return (T)appDomain.CreateInstanceFromAndUnwrap(typeof(T).Assembly.Location, typeof(T).FullName, false, 0, null, null, null, null); } public T Create<T>(params object[] arguments) where T : LongLivedMarshalByRefObject { return (T)appDomain.CreateInstanceAndUnwrap(typeof(T).Assembly.FullName, typeof(T).FullName, false, 0, null, arguments, null, null); } static string GetOptionalConfigFullPath(string assemblyFullPath) { var configFullPath = assemblyFullPath + ".config"; return File.Exists(configFullPath) ? configFullPath : null; } public void Dispose() { AppDomain.Unload(appDomain); } } #else using System; class ConsoleTestAppDomain : IDisposable { public ConsoleTestAppDomain(string assemblyFullPath) { } public T CreateFrom<T>() where T : LongLivedMarshalByRefObject, new() => new T(); public T Create<T>(params object[] arguments) where T : LongLivedMarshalByRefObject => (T)Activator.CreateInstance(typeof(T), arguments); public void Dispose() { } } #endif }
mit
C#
61880f922e362d00720da49bd7a2e7e8279bda56
remove unused method
ericnewton76/gmaps-api-net
src/Google.Maps/Internal/HttpGetResponse.cs
src/Google.Maps/Internal/HttpGetResponse.cs
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.IO; using System.Net; using Newtonsoft.Json; namespace Google.Maps.Internal { public class HttpGetResponse { protected Uri RequestUri { get; set; } public HttpGetResponse(Uri uri) { RequestUri = uri; } protected virtual StreamReader GetStreamReader(Uri uri) { return GetStreamReader(uri, GoogleSigned.SigningInstance); } protected virtual StreamReader GetStreamReader(Uri uri, GoogleSigned signingInstance) { if (signingInstance != null) { uri = new Uri(signingInstance.GetSignedUri(uri)); } WebResponse response = WebRequest.Create(uri).GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); return sr; } public virtual T As<T>() where T : class { T output = null; using (var reader = GetStreamReader(this.RequestUri)) { JsonTextReader jsonReader = new JsonTextReader(reader); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new JsonEnumTypeConverter()); serializer.Converters.Add(new JsonLocationConverter()); output = serializer.Deserialize<T>(jsonReader); } return output; } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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.IO; using System.Net; using Newtonsoft.Json; namespace Google.Maps.Internal { public class HttpGetResponse { protected Uri RequestUri { get; set; } public HttpGetResponse(Uri uri) { RequestUri = uri; } protected virtual StreamReader GetStreamReader(Uri uri) { return GetStreamReader(uri, GoogleSigned.SigningInstance); } protected virtual StreamReader GetStreamReader(Uri uri, GoogleSigned signingInstance) { if (signingInstance != null) { uri = new Uri(signingInstance.GetSignedUri(uri)); } WebResponse response = WebRequest.Create(uri).GetResponse(); StreamReader sr = new StreamReader(response.GetResponseStream()); return sr; } public virtual string AsString() { var output = String.Empty; using (var reader = GetStreamReader(this.RequestUri)) { output = reader.ReadToEnd(); } return output; } public virtual T As<T>() where T : class { T output = null; using (var reader = GetStreamReader(this.RequestUri)) { JsonTextReader jsonReader = new JsonTextReader(reader); JsonSerializer serializer = new JsonSerializer(); serializer.Converters.Add(new JsonEnumTypeConverter()); serializer.Converters.Add(new JsonLocationConverter()); output = serializer.Deserialize<T>(jsonReader); } return output; } } }
apache-2.0
C#
b4880bed80a5214a802073a5451447ee9f0fa68e
Update FilePageMessage.cs
jpdante/HTCSharp
HtcSharp.Core/Models/Http/Pages/FilePageMessage.cs
HtcSharp.Core/Models/Http/Pages/FilePageMessage.cs
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace HtcSharp.Core.Models.Http.Pages { public class FilePageMessage : IPageMessage { private readonly string _pageFileName; public int StatusCode { get; } public FilePageMessage(string fileName, int statusCode) { _pageFileName = fileName; StatusCode = statusCode; } public string GetPageMessage(HtcHttpContext httpContext) { var fileContent = File.ReadAllText(_pageFileName, Encoding.UTF8); fileContent = fileContent.Replace("{Request.Path}", httpContext.Request.Path); fileContent = fileContent.Replace("{Request.Host}", httpContext.Request.Host); fileContent = fileContent.Replace("{Request.PathBase}", httpContext.Request.PathBase); fileContent = fileContent.Replace("{Request.Protocol}", httpContext.Request.Protocol); fileContent = fileContent.Replace("{Request.QueryString}", httpContext.Request.QueryString); fileContent = fileContent.Replace("{Request.RequestFilePath}", httpContext.Request.RequestFilePath); fileContent = fileContent.Replace("{Request.RequestPath}", httpContext.Request.RequestPath); fileContent = fileContent.Replace("{Request.Scheme}", httpContext.Request.Scheme); fileContent = fileContent.Replace("{Request.TranslatedPath}", httpContext.Request.TranslatedPath); fileContent = fileContent.Replace("{Request.IsHttps}", httpContext.Request.IsHttps.ToString()); fileContent = fileContent.Replace("{Request.Method}", httpContext.Request.Method.ToString()); fileContent = fileContent.Replace("{Connection.Id}", httpContext.Connection.Id); fileContent = fileContent.Replace("{Connection.RemoteIpAddress}", httpContext.Connection.RemoteIpAddress.ToString()); fileContent = fileContent.Replace("{Connection.RemotePort}", httpContext.Connection.RemotePort.ToString()); return fileContent; } public void ExecutePageMessage(HtcHttpContext httpContext) { if (httpContext.Response.HasStarted) return; var fileContent = File.ReadAllText(_pageFileName, Encoding.UTF8); fileContent = fileContent.Replace("{Request.Path}", httpContext.Request.Path); fileContent = fileContent.Replace("{Request.Host}", httpContext.Request.Host); fileContent = fileContent.Replace("{Request.PathBase}", httpContext.Request.PathBase); fileContent = fileContent.Replace("{Request.Protocol}", httpContext.Request.Protocol); fileContent = fileContent.Replace("{Request.QueryString}", httpContext.Request.QueryString); fileContent = fileContent.Replace("{Request.RequestFilePath}", httpContext.Request.RequestFilePath); fileContent = fileContent.Replace("{Request.RequestPath}", httpContext.Request.RequestPath); fileContent = fileContent.Replace("{Request.Scheme}", httpContext.Request.Scheme); fileContent = fileContent.Replace("{Request.TranslatedPath}", httpContext.Request.TranslatedPath); fileContent = fileContent.Replace("{Request.IsHttps}", httpContext.Request.IsHttps.ToString()); fileContent = fileContent.Replace("{Request.Method}", httpContext.Request.Method.ToString()); fileContent = fileContent.Replace("{Connection.Id}", httpContext.Connection.Id); fileContent = fileContent.Replace("{Connection.RemoteIpAddress}", httpContext.Connection.RemoteIpAddress.ToString()); fileContent = fileContent.Replace("{Connection.RemotePort}", httpContext.Connection.RemotePort.ToString()); httpContext.Response.StatusCode = StatusCode; httpContext.Response.WriteAsync(fileContent).GetAwaiter().GetResult(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace HtcSharp.Core.Models.Http.Pages { public class FilePageMessage : IPageMessage { private readonly string _pageFileName; public int StatusCode { get; } public FilePageMessage(string fileName, int statusCode) { _pageFileName = fileName; StatusCode = statusCode; } public string GetPageMessage(HtcHttpContext httpContext) { var fileContent = File.ReadAllText(_pageFileName, Encoding.UTF8); fileContent = fileContent.Replace("%REQUESTURL%", httpContext.Request.Path); return fileContent; } public void ExecutePageMessage(HtcHttpContext httpContext) { if (httpContext.Response.HasStarted) return; var fileContent = File.ReadAllText(_pageFileName, Encoding.UTF8); fileContent = fileContent.Replace("%REQUESTURL%", httpContext.Request.Path); httpContext.Response.WriteAsync(fileContent).GetAwaiter().GetResult(); } } }
mit
C#
95759f7f0a0ead2a8738fa0e18a45e4c1f9c7b5c
Fix typo
Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager,dsolovay/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager
src/SIM.Client/Commands/MainCommandGroup.cs
src/SIM.Client/Commands/MainCommandGroup.cs
namespace SIM.Client.Commands { using CommandLine; using CommandLine.Text; using Sitecore.Diagnostics.Base.Annotations; public class MainCommandGroup : MainCommandGroupBase { #region Nested Commands [CanBeNull] [UsedImplicitly] [VerbOption("list", HelpText = "Show already installed instances.")] public ListCommandFacade ListCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("state", HelpText = "Show state of an instance.")] public StateCommandFacade StateCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("start", HelpText="Start stopped instance.")] public StartCommandFacade StartCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("stop", HelpText = "Stop an instance.")] public StopCommandFacade StopCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("repository", HelpText = "Show contents of repository.")] public RepositoryCommandFacade RepositoryCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("profile", HelpText = "Show profile.")] public ProfileCommandFacade ProfileCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("install", HelpText = "Install Sitecore instance.")] public InstallCommandFacade InstallCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("installmodule", HelpText = "Install Sitecore module.")] public InstallModuleCommandFacade InstallModuleCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("delete", HelpText = "Delete Sitecore instance.")] public DeleteCommandFacade DeleteCommandFacade { get; set; } #endregion [CanBeNull] [UsedImplicitly] [HelpVerbOption] public string GetUsage([CanBeNull] string verb) { return HelpText.AutoBuild(this, verb); } } }
namespace SIM.Client.Commands { using CommandLine; using CommandLine.Text; using Sitecore.Diagnostics.Base.Annotations; public class MainCommandGroup : MainCommandGroupBase { #region Nested Commands [CanBeNull] [UsedImplicitly] [VerbOption("list", HelpText = "Show already installed instances.")] public ListCommandFacade ListCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("state", HelpText = "Shows state of an instance.")] public StateCommandFacade StateCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("start", HelpText="Start stopped instance.")] public StartCommandFacade StartCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("stop", HelpText = "Stops an instance.")] public StopCommandFacade StopCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("repository", HelpText = "Show contents of repository.")] public RepositoryCommandFacade RepositoryCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("profile", HelpText = "Show profile.")] public ProfileCommandFacade ProfileCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("install", HelpText = "Install Sitecore instance.")] public InstallCommandFacade InstallCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("installmodule", HelpText = "Install Sitecore module.")] public InstallModuleCommandFacade InstallModuleCommandFacade { get; set; } [CanBeNull] [UsedImplicitly] [VerbOption("delete", HelpText = "Delete Sitecore instance.")] public DeleteCommandFacade DeleteCommandFacade { get; set; } #endregion [CanBeNull] [UsedImplicitly] [HelpVerbOption] public string GetUsage([CanBeNull] string verb) { return HelpText.AutoBuild(this, verb); } } }
mit
C#
f41f4e9a288aebbea5775eda636885cd20766619
fix to xml comments
RockFramework/Rock.Core,peteraritchie/Rock.Core
Rock.Core/Serialization/SerializationExtensions.cs
Rock.Core/Serialization/SerializationExtensions.cs
using System; namespace Rock.Serialization { public static class SerializationExtensions { /// <summary> /// Deserializes an XML string into an object of type T. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The XML string to deserialize</param> /// <returns>An object of type T</returns> public static T FromXml<T>(this string str) { return DefaultXmlSerializer.Current.DeserializeFromString<T>(str); } /// <summary> /// A reflection-friendly method to deserialize an XML string into an object. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The XML string to deserialize</param> /// <returns>An object</returns> public static object FromXml(this string str, System.Type type) { return DefaultXmlSerializer.Current.DeserializeFromString(str, type); } /// <summary> /// Deserializes a JSON string into an object of type T. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The JSON string to deserialize</param> /// <returns>An object of type T</returns> public static T FromJson<T>(this string str) { return DefaultJsonSerializer.Current.DeserializeFromString<T>(str); } /// <summary> /// A reflection-friendly method to deserialize an JSON string into an object. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The JSON string to deserialize</param> /// <returns>An object</returns> public static object FromJson(this string str, Type type) { return DefaultJsonSerializer.Current.DeserializeFromString(str, type); } } }
using System; namespace Rock.Serialization { public static class SerializationExtensions { /// <summary> /// Deserializes an XML string into an object of type T. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The XML string to deserialize</param> /// <returns>An object of type T</returns> public static T FromXml<T>(this string str) { return DefaultXmlSerializer.Current.DeserializeFromString<T>(str); } /// <summary> /// A reflection-friendly method to deserialize an XML string into an object. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The XML string to deserialize</param> /// <returns>An object of type T</returns> public static object FromXml(this string str, System.Type type) { return DefaultXmlSerializer.Current.DeserializeFromString(str, type); } /// <summary> /// Deserializes a JSON string into an object of type T. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The JSON string to deserialize</param> /// <returns>An object</returns> public static T FromJson<T>(this string str) { return DefaultJsonSerializer.Current.DeserializeFromString<T>(str); } /// <summary> /// A reflection-friendly method to deserialize an JSON string into an object. /// </summary> /// <typeparam name="T">The type of object represented by this string</typeparam> /// <param name="str">The JSON string to deserialize</param> /// <returns>An object</returns> public static object FromJson(this string str, Type type) { return DefaultJsonSerializer.Current.DeserializeFromString(str, type); } } }
mit
C#
975c07a20928f73b995dbaeae3925c27d4bdc595
change order of barter offers in Comment.aspx
WebFormsTeamFyodorDostoevsky/ASP-NET-Web-Forms-Teamwork,WebFormsTeamFyodorDostoevsky/ASP-NET-Web-Forms-Teamwork
BarterSystem/BarterSystem.WebForms/Barter/Comment.aspx.cs
BarterSystem/BarterSystem.WebForms/Barter/Comment.aspx.cs
using BarterSystem.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.Identity; using BarterSystem.Models.Enums; using BarterSystem.WebForms.Models; using BarterSystem.Common; namespace BarterSystem.WebForms.Barter { public partial class Comment : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (this.User == null || !this.User.Identity.IsAuthenticated) { Server.Transfer("~/Account/Login.aspx", true); } var uow = new BarterSystemData(); var userId = this.User.Identity.GetUserId(); var username = this.User.Identity.GetUserName(); this.ListViewBarters.DataSource = uow.Advertisments .All() .Where(a => (a.AcceptUserId == userId && !a.CommentedByAcceptUser) || (a.UserId == userId && !a.CommentedByUser) && a.Status == Status.AwaitingFeedback) .OrderByDescending(a => a.CreationDate) .Select(a => new BarterForCommentViewModel() { UserName = username, Content = a.Content, Title = a.Title, Id = a.Id, ImageUrl = GlobalConstants.ImagesPath + a.ImageUrl, CreationDate = a.CreationDate }) .ToList(); Page.DataBind(); } } }
using BarterSystem.Data; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.Identity; using BarterSystem.Models.Enums; using BarterSystem.WebForms.Models; using BarterSystem.Common; namespace BarterSystem.WebForms.Barter { public partial class Comment : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (this.User == null || !this.User.Identity.IsAuthenticated) { Server.Transfer("~/Account/Login.aspx", true); } var uow = new BarterSystemData(); var userId = this.User.Identity.GetUserId(); var username = this.User.Identity.GetUserName(); this.ListViewBarters.DataSource = uow.Advertisments .All() .Where(a => (a.AcceptUserId == userId && !a.CommentedByAcceptUser) || (a.UserId == userId && !a.CommentedByUser) && a.Status == Status.AwaitingFeedback) .Select(a => new BarterForCommentViewModel() { UserName = username, Content = a.Content, Title = a.Title, Id = a.Id, ImageUrl = GlobalConstants.ImagesPath + a.ImageUrl, CreationDate = a.CreationDate }) .ToList(); Page.DataBind(); } } }
mit
C#
2d53ccf31648772ec9f951a556caa2e2749a522c
Disable ClaimWorkStopped filter
leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
JoinRpg.Domain/ClaimProblemFilters/ClaimWorkStopped.cs
JoinRpg.Domain/ClaimProblemFilters/ClaimWorkStopped.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JoinRpg.DataModel; namespace JoinRpg.Domain.ClaimProblemFilters { internal class ClaimWorkStopped : IClaimProblemFilter { public IEnumerable<ClaimProblem> GetProblems(Claim claim) { yield break; if (!claim.IsApproved) // Our concern is only approved claims { yield break; } if (DateTime.UtcNow.Subtract(claim.CreateDate) < TimeSpan.FromDays(2)) //If filed only recently, do nothing { yield break; } if (!claim.GetMasterAnswers().Any()) { yield return new ClaimProblem(ClaimProblemType.ClaimNeverAnswered); } else if (!claim.GetMasterAnswers().InLastXDays(30).Any()) { yield return new ClaimProblem(ClaimProblemType.ClaimWorkStopped, claim.GetMasterAnswers().Last().CreatedTime); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JoinRpg.DataModel; namespace JoinRpg.Domain.ClaimProblemFilters { internal class ClaimWorkStopped : IClaimProblemFilter { public IEnumerable<ClaimProblem> GetProblems(Claim claim) { if (!claim.IsApproved) // Our concern is only approved claims { yield break; } if (DateTime.UtcNow.Subtract(claim.CreateDate) < TimeSpan.FromDays(2)) //If filed only recently, do nothing { yield break; } if (!claim.GetMasterAnswers().Any()) { yield return new ClaimProblem(ClaimProblemType.ClaimNeverAnswered); } else if (!claim.GetMasterAnswers().InLastXDays(30).Any()) { yield return new ClaimProblem(ClaimProblemType.ClaimWorkStopped, claim.GetMasterAnswers().Last().CreatedTime); } } } }
mit
C#
e477b1fbdf8563b917ba4d2260a4b9729893a85f
return HTTP 400 when function keys are malformatted, fix issue #2341
EricSten-MSFT/kudu,projectkudu/kudu,shibayan/kudu,EricSten-MSFT/kudu,projectkudu/kudu,projectkudu/kudu,puneet-gupta/kudu,projectkudu/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,puneet-gupta/kudu,EricSten-MSFT/kudu,shibayan/kudu,projectkudu/kudu,shibayan/kudu,shibayan/kudu,shibayan/kudu
Kudu.Services/Filters/FunctionExceptionFilterAttribute.cs
Kudu.Services/Filters/FunctionExceptionFilterAttribute.cs
using Kudu.Services.Arm; using System; using System.IO; using System.Net; using System.Net.Http; using System.Web.Http.Filters; namespace Kudu.Services.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public sealed class FunctionExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { var statusCode = HttpStatusCode.InternalServerError; if (context.Exception is FileNotFoundException) { statusCode = HttpStatusCode.NotFound; } else if (context.Exception is InvalidOperationException) { statusCode = HttpStatusCode.Conflict; } else if (context.Exception is ArgumentException) { statusCode = HttpStatusCode.BadRequest; } else if (context.Exception is FormatException) { statusCode = HttpStatusCode.BadRequest; } context.Response = ArmUtils.CreateErrorResponse(context.Request, statusCode, context.Exception); } } }
using Kudu.Services.Arm; using System; using System.IO; using System.Net; using System.Net.Http; using System.Web.Http.Filters; namespace Kudu.Services.Filters { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public sealed class FunctionExceptionFilterAttribute : ExceptionFilterAttribute { public override void OnException(HttpActionExecutedContext context) { var statusCode = HttpStatusCode.InternalServerError; if (context.Exception is FileNotFoundException) { statusCode = HttpStatusCode.NotFound; } else if (context.Exception is InvalidOperationException) { statusCode = HttpStatusCode.Conflict; } else if (context.Exception is ArgumentException) { statusCode = HttpStatusCode.BadRequest; } context.Response = ArmUtils.CreateErrorResponse(context.Request, statusCode, context.Exception); } } }
apache-2.0
C#
e3a562d3c9a80b5dc55367a4162660374119194a
Add file and line number to documentation attribute (#6122)
QuantConnect/Lean,AlexCatarino/Lean,jameschch/Lean,JKarathiya/Lean,jameschch/Lean,jameschch/Lean,JKarathiya/Lean,QuantConnect/Lean,QuantConnect/Lean,AlexCatarino/Lean,AlexCatarino/Lean,jameschch/Lean,JKarathiya/Lean,AlexCatarino/Lean,jameschch/Lean,JKarathiya/Lean,QuantConnect/Lean
Common/DocumentationAttribute.cs
Common/DocumentationAttribute.cs
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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.Linq; using Newtonsoft.Json; using System.Reflection; namespace QuantConnect { /// <summary> /// Custom attribute used for documentation /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] [DocumentationAttribute("Reference")] public sealed class DocumentationAttribute : Attribute { private static readonly DocumentationAttribute Attribute = typeof(DocumentationAttribute).GetCustomAttributes<DocumentationAttribute>().Single(); private static readonly string BasePath = Attribute.FileName.Substring(0, Attribute.FileName.LastIndexOf("Common", StringComparison.Ordinal)); /// <summary> /// The documentation tag /// </summary> [JsonProperty(PropertyName = "tag")] public string Tag { get; } /// <summary> /// The associated weight of this attribute and tag /// </summary> [JsonProperty(PropertyName = "weight")] public int Weight { get; } /// <summary> /// The associated line of this attribute /// </summary> [JsonProperty(PropertyName = "line")] public int Line { get; } /// <summary> /// The associated file name of this attribute /// </summary> [JsonProperty(PropertyName = "fileName")] public string FileName { get; } /// <summary> /// The attributes type id, we override it to ignore it when serializing /// </summary> [JsonIgnore] public override object TypeId => base.TypeId; /// <summary> /// Creates a new instance /// </summary> public DocumentationAttribute(string tag, int weight = 0, [System.Runtime.CompilerServices.CallerLineNumber] int line = 0, [System.Runtime.CompilerServices.CallerFilePath] string fileName = "") { Tag = tag; Line = line; Weight = weight; // will be null for the attribute of DocumentationAttribute itself if (BasePath != null) { FileName = fileName.Replace(BasePath, string.Empty, StringComparison.InvariantCultureIgnoreCase); } else { FileName = fileName; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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 Newtonsoft.Json; namespace QuantConnect { /// <summary> /// Custom attribute used for documentation /// </summary> [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public sealed class DocumentationAttribute : Attribute { /// <summary> /// The documentation tag /// </summary> [JsonProperty(PropertyName = "tag")] public string Tag { get; } /// <summary> /// The associated weight of this attribute and tag /// </summary> [JsonProperty(PropertyName = "weight")] public int Weight { get; } /// <summary> /// The attributes type id, we override it to ignore it when serializing /// </summary> [JsonIgnore] public override object TypeId => base.TypeId; /// <summary> /// Creates a new instance /// </summary> public DocumentationAttribute(string tag, int weight = 0) { Tag = tag; Weight = weight; } } }
apache-2.0
C#
783f47a27cfb4618526b25da887834b9ab98f4e9
Add comments to code Removed unused namespace Add Buoyancy class to Game namespace
liferaftsim/development
Unity/LifeRaftSim/Assets/_Game/Scripts/Buoyancy.cs
Unity/LifeRaftSim/Assets/_Game/Scripts/Buoyancy.cs
using UnityEngine; namespace Game { /// <summary> /// Very simple non-physics based buoyancy behaviour used for hero, items and debris. /// </summary> public class Buoyancy : MonoBehaviour { /// <summary> /// Additional height offset relative to the ocean surface. /// </summary> [SerializeField] private float yOffset = 0.0f; /// <summary> /// Name of the game object that represents the ocean surface. /// The Y position of this game object is used as ocean surface position. /// </summary> [SerializeField] private string waterGameObjectName = "Water"; /// <summary> /// Speed of the cosine function. /// The cosine is used to add noise to the buoyancy. /// This affects how fast the noise is moving the game object up and down. /// </summary> [SerializeField] private float yConsineSpeed = 1.0f; /// <summary> /// Multiplier of the cosine function result. /// The cosine is used to add noise to the buoyancy. /// This affects the min and max of the added y position. /// </summary> [SerializeField] private float yConsineMultiplier = 1.0f; /// <summary> /// The ocean surface game object. /// </summary> private Transform water; /// <summary> /// Called by Unity. /// </summary> private void Start() { this.CacheWater(); } /// <summary> /// Called by Unity. /// </summary> private void Update() { this.MoveY(); } /// <summary> /// Finds and stores the ocean surface game object for later reference. /// </summary> private void CacheWater() { var waterGameObject = GameObject.Find(this.waterGameObjectName); if (waterGameObject == null) { Debug.LogError(this.name + ": No game object named \"" + this.waterGameObjectName + "\" found."); this.enabled = false; return; } this.water = waterGameObject.transform; } /// <summary> /// Positions the game object to match the ocean surface. /// </summary> private void MoveY() { var position = this.transform.position; position.y = this.water.position.y + this.yOffset + Mathf.Cos(Time.time * this.yConsineSpeed) * this.yConsineMultiplier; this.transform.position = position; } } }
using UnityEngine; using System.Collections; public class Buoyancy : MonoBehaviour { [SerializeField] private float yOffset = 0.0f; [SerializeField] private string waterGameObjectName = "Water"; [SerializeField] private float yConsineSpeed = 1.0f; [SerializeField] private float yConsineMultiplier = 1.0f; private Transform water; private void Start() { this.CacheWater(); } private void Update() { this.MoveY(); } private void CacheWater() { var waterGameObject = GameObject.Find(this.waterGameObjectName); if (waterGameObject == null) { Debug.LogError(this.name + ": No game object named \"" + this.waterGameObjectName + "\" found."); this.enabled = false; return; } this.water = waterGameObject.transform; } private void MoveY() { var position = this.transform.position; position.y = this.water.position.y + this.yOffset + Mathf.Cos(Time.time * this.yConsineSpeed) * this.yConsineMultiplier; this.transform.position = position; } }
unlicense
C#
7974601487fb987c227cb721ded359ffb329a710
Use system-agnostic path separator
Mako88/dxx-tracker
RebirthTracker/RebirthTracker/Configuration.cs
RebirthTracker/RebirthTracker/Configuration.cs
namespace RebirthTracker { /// <summary> /// Class to keep track of OS-specific configuration settings /// </summary> public static class Configuration { /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { return "..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}..{Path.DirectorySeparatorChar}"; } } }
using System.Runtime.InteropServices; namespace RebirthTracker { /// <summary> /// Class to keep track of OS-specific configuration settings /// </summary> public static class Configuration { /// <summary> /// Get the folder where files should be stored /// </summary> public static string GetDataDir() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return "..\\..\\..\\..\\..\\"; } return string.Empty; } } }
mit
C#
42d0e149a72ce99b61e24ef407bc769cf37a8000
create directory added
Risvana/Code.Library,Abhith/Code.Library,Abhith/Code.Library
Source/Code.Library/Code.Library/FileHelper.cs
Source/Code.Library/Code.Library/FileHelper.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="FileHelper.cs" company="Open Source"> // File Helper // </copyright> // <summary> // The file helper. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Code.Library { using System.IO; /// <summary> /// The file helper. /// </summary> public static class FileHelper { /// <summary> /// The delete file. /// </summary> /// <param name="fileName"> /// The file name. /// </param> public static void DeleteFile(string fileName) { if (string.IsNullOrEmpty(fileName)) { return; } if (File.Exists(fileName)) { File.Delete(fileName); } } /// <summary> /// The create directory. /// </summary> /// <param name="path"> /// The path. /// </param> public static void CreateDirectory(string path) { var exists = Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(path)); if (!exists) { Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(path)); } } } }
using System.IO; namespace Code.Library { public static class FileHelper { /// <summary> /// Delete file /// Author : Abhith /// Date : 14 July 2015 /// Reference : Sysberries /// </summary> /// <param name="fileName"></param> public static void DeleteFile(string fileName) { if (string.IsNullOrEmpty(fileName)) { return; } if (File.Exists(fileName)) { File.Delete(fileName); } } } }
apache-2.0
C#
f105fcbd0e80d433c791038bea09c7c1a9a65921
Enable user secrets
JohnnyCrazy/SpotifyAPI-NET,JohnnyCrazy/SpotifyAPI-NET,JohnnyCrazy/SpotifyAPI-NET,JohnnyCrazy/SpotifyAPI-NET
SpotifyAPI.Web.Examples/Example.ASP/Program.cs
SpotifyAPI.Web.Examples/Example.ASP/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Example.ASP { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureAppConfiguration((httpContext, builder) => { builder.AddUserSecrets<Program>(); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace Example.ASP { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
mit
C#
8ad76164008753a114c722dba0d61e8540a05d73
Allow about page viewing
mattgwagner/alert-roster
alert-roster.web/Controllers/HomeController.cs
alert-roster.web/Controllers/HomeController.cs
using alert_roster.web.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace alert_roster.web.Controllers { public class HomeController : Controller { public ActionResult Index() { using (var db = new AlertRosterDbContext()) { var messages = db.Messages.OrderByDescending(m => m.PostedDate).Take(10).ToList(); return View(messages); } } [AllowAnonymous] public ActionResult About() { return View(); } [AllowAnonymous] public ActionResult Login() { return View(); } [AllowAnonymous, HttpPost, ValidateAntiForgeryToken] public ActionResult Login(String password, String ReturnUrl = "") { Authentication.Authenticate(password); if (String.IsNullOrWhiteSpace(ReturnUrl)) { return RedirectToAction("Index"); } return Redirect(ReturnUrl); } [Authorize(Users = Authentication.ReadWriteRole)] public ActionResult New() { return View(); } [Authorize(Users = Authentication.ReadWriteRole), HttpPost, ValidateAntiForgeryToken] public ActionResult New([Bind(Include = "Content")]Message message) { if (ModelState.IsValid) { using (var db = new AlertRosterDbContext()) { message.PostedDate = DateTime.UtcNow; db.Messages.Add(message); db.SaveChanges(); } return RedirectToAction("Index"); } return View(message); } } }
using alert_roster.web.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace alert_roster.web.Controllers { public class HomeController : Controller { public ActionResult Index() { using (var db = new AlertRosterDbContext()) { var messages = db.Messages.OrderByDescending(m => m.PostedDate).Take(10).ToList(); return View(messages); } } public ActionResult About() { return View(); } [AllowAnonymous] public ActionResult Login() { return View(); } [AllowAnonymous, HttpPost, ValidateAntiForgeryToken] public ActionResult Login(String password, String ReturnUrl = "") { Authentication.Authenticate(password); if (String.IsNullOrWhiteSpace(ReturnUrl)) { return RedirectToAction("Index"); } return Redirect(ReturnUrl); } [Authorize(Users = Authentication.ReadWriteRole)] public ActionResult New() { return View(); } [Authorize(Users = Authentication.ReadWriteRole), HttpPost, ValidateAntiForgeryToken] public ActionResult New([Bind(Include = "Content")]Message message) { if (ModelState.IsValid) { using (var db = new AlertRosterDbContext()) { message.PostedDate = DateTime.UtcNow; db.Messages.Add(message); db.SaveChanges(); } return RedirectToAction("Index"); } return View(message); } } }
mit
C#
80da3f954b844fddfaf7338097eb0829ad89e086
Add note about supported Visual Studio versions
cake-build/website,cake-build/website,cake-build/website
input/docs/integrations/editors/visualstudio/index.cshtml
input/docs/integrations/editors/visualstudio/index.cshtml
Order: 30 Title: Visual Studio Description: Extensions and supported features for Visual Studio RedirectFrom: docs/editors/visualstudio --- <p> The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio </a> brings the following features to Visual Studio: <ul> <li>Language support for Cake build scripts</li> <li><a href="/docs/integrations/editors/visualstudio/templates">Templates</a></li> <li><a href="/docs/integrations/editors/visualstudio/commands">Commands</a> for working with Cake files</li> <li><a href="/docs/integrations/editors/visualstudio/snippets">Snippets</a></li> <li><a href="/docs/integrations/editors/visualstudio/task-runner">Integration with Task Runner Explorer</a></li> </ul> </p> <h1>Installation & configuration</h1> <p> See <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> for instructions how to install and configure the extension. </p> <div class="alert alert-info"> <p> The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> supports Visual Studio 2017 and newer. </p> </div> <h1>Child pages</h1> @Html.Partial("_ChildPages")
Order: 30 Title: Visual Studio Description: Extensions and supported features for Visual Studio RedirectFrom: docs/editors/visualstudio --- <p> The <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio </a> brings the following features to Visual Studio: <ul> <li>Language support for Cake build scripts</li> <li><a href="/docs/integrations/editors/visualstudio/templates">Templates</a></li> <li><a href="/docs/integrations/editors/visualstudio/commands">Commands</a> for working with Cake files</li> <li><a href="/docs/integrations/editors/visualstudio/snippets">Snippets</a></li> <li><a href="/docs/integrations/editors/visualstudio/task-runner">Integration with Task Runner Explorer</a></li> </ul> </p> <h1>Installation & configuration</h1> See <a href="https://marketplace.visualstudio.com/items?itemName=vs-publisher-1392591.CakeforVisualStudio" target="_blank">Cake extension for Visual Studio</a> for instructions how to install and configure the extension. <h1>Child pages</h1> @Html.Partial("_ChildPages")
mit
C#
8fa504d207d150f3d8f5206b033f2eccd3c3b4a3
Fix compiler error
LordMike/TMDbLib
TMDbLib/Client/TMDbClientFind.cs
TMDbLib/Client/TMDbClientFind.cs
using System.Threading.Tasks; using RestSharp; using RestSharp.Contrib; using TMDbLib.Objects.Find; using TMDbLib.Utilities; namespace TMDbLib.Client { public partial class TMDbClient { /// <summary> /// Find movies, people and tv shows by an external id. /// The following trypes can be found based on the specified external id's /// - Movies: Imdb /// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage /// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb /// </summary> /// <param name="source">The source the specified id belongs to</param> /// <param name="id">The id of the object you wish to located</param> /// <returns>A list of all objects in TMDb that matched your id</returns> public async Task<FindContainer> Find(FindExternalSource source, string id) { RestRequest req = new RestRequest("find/{id}"); if (source == FindExternalSource.FreeBaseId || source == FindExternalSource.FreeBaseMid) // No url encoding for freebase Id's (they include /-slashes) req.AddUrlSegment("id", id); else req.AddUrlSegment("id", HttpUtility.UrlEncode(id)); req.AddParameter("external_source", source.GetDescription()); IRestResponse<FindContainer> resp = await _client.ExecuteGetTaskAsync<FindContainer>(req).ConfigureAwait(false); return resp.Data; } } }
using System.Threading.Tasks; using RestSharp; using RestSharp.Extensions.MonoHttp; using TMDbLib.Objects.Find; using TMDbLib.Utilities; namespace TMDbLib.Client { public partial class TMDbClient { /// <summary> /// Find movies, people and tv shows by an external id. /// The following trypes can be found based on the specified external id's /// - Movies: Imdb /// - People: Imdb, FreeBaseMid, FreeBaseId, TvRage /// - TV Series: Imdb, FreeBaseMid, FreeBaseId, TvRage, TvDb /// </summary> /// <param name="source">The source the specified id belongs to</param> /// <param name="id">The id of the object you wish to located</param> /// <returns>A list of all objects in TMDb that matched your id</returns> public async Task<FindContainer> Find(FindExternalSource source, string id) { RestRequest req = new RestRequest("find/{id}"); if (source == FindExternalSource.FreeBaseId || source == FindExternalSource.FreeBaseMid) // No url encoding for freebase Id's (they include /-slashes) req.AddUrlSegment("id", id); else req.AddUrlSegment("id", HttpUtility.UrlEncode(id)); req.AddParameter("external_source", source.GetDescription()); IRestResponse<FindContainer> resp = await _client.ExecuteGetTaskAsync<FindContainer>(req).ConfigureAwait(false); return resp.Data; } } }
mit
C#
f2e1eb2eb44aa3577c3f30d452067123a19b1aaf
Test conflit
MetalRono/TestGitTeam
TestGITHUB/TestGITHUB/Program.cs
TestGITHUB/TestGITHUB/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGITHUB { class Program { static void Main(string[] args) { for (int i = 0; i < 200; i++) { Console.WriteLine("Jouons à Pokémon!!!"); Console.WriteLine("S/M sort le 18 novembre"); } Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestGITHUB { class Program { static void Main(string[] args) { for (int i = 0; i < 200; i++) { Console.WriteLine("Jouons à Pokémon!!!"); Console.WriteLine("S/M sort le 18 nov"); } Console.ReadKey(); } } }
mit
C#
3e65c2e8913f5bc381cd3fdb4c028e996dd2e74a
Fix Xablu's language (#639)
planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin
src/Firehose.Web/Authors/Xablu.cs
src/Firehose.Web/Authors/Xablu.cs
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class Xablu : IAmACommunityMember { public string FirstName => "Xablu"; public string LastName => ""; public string StateOrRegion => "Amsterdam, the Netherlands"; public string EmailAddress => "[email protected]"; public string ShortBioOrTagLine => "a 100% pure Xamarin company."; public Uri WebSite => new Uri("https://www.xablu.com/"); public string TwitterHandle => "xabluhq"; public string GitHubHandle => "xablu"; public string GravatarHash => "508b1a99bb81e09c189e7487ecb69167"; public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.xablu.com/tag/planet-xamarin/feed/"); } } public GeoPosition Position => new GeoPosition(52.3702, 4.8952); public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class Xablu : IAmACommunityMember { public string FirstName => "Xablu"; public string LastName => ""; public string StateOrRegion => "Amsterdam, the Netherlands"; public string EmailAddress => "[email protected]"; public string ShortBioOrTagLine => "a 100% pure Xamarin company."; public Uri WebSite => new Uri("https://www.xablu.com/"); public string TwitterHandle => "xabluhq"; public string GitHubHandle => "xablu"; public string GravatarHash => "508b1a99bb81e09c189e7487ecb69167"; public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://www.xablu.com/tag/planet-xamarin/feed/"); } } public GeoPosition Position => new GeoPosition(52.3702, 4.8952); public string FeedLanguageCode => "es"; } }
mit
C#
c5b71d2cb7c18f94329cf1f85c02b3b9699027df
Remove unused using
peppy/osu,peppy/osu-new,smoogipoo/osu,NeoAdonis/osu,peppy/osu,Frontear/osuKyzer,NeoAdonis/osu,Nabile-Rahmani/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,naoey/osu,naoey/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,ZLima12/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,DrabWeb/osu,smoogipooo/osu,johnneijzen/osu,EVAST9919/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu,ppy/osu,naoey/osu,2yangk23/osu,ppy/osu,DrabWeb/osu,ZLima12/osu
osu.Game/Tests/Visual/OsuTestCase.cs
osu.Game/Tests/Visual/OsuTestCase.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.IO; using System.Reflection; using osu.Framework.Testing; namespace osu.Game.Tests.Visual { public abstract class OsuTestCase : TestCase { public override void RunTest() { using (var host = new CleanRunHeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false)) host.Run(new OsuTestCaseTestRunner(this)); } public class OsuTestCaseTestRunner : OsuGameBase { private readonly OsuTestCase testCase; protected override string MainResourceFile => File.Exists(base.MainResourceFile) ? base.MainResourceFile : Assembly.GetExecutingAssembly().Location; public OsuTestCaseTestRunner(OsuTestCase testCase) { this.testCase = testCase; } protected override void LoadComplete() { base.LoadComplete(); Add(new TestCaseTestRunner.TestRunner(testCase)); } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.IO; using System.Reflection; using osu.Framework.Platform; using osu.Framework.Testing; namespace osu.Game.Tests.Visual { public abstract class OsuTestCase : TestCase { public override void RunTest() { using (var host = new CleanRunHeadlessGameHost($"test-{Guid.NewGuid()}", realtime: false)) host.Run(new OsuTestCaseTestRunner(this)); } public class OsuTestCaseTestRunner : OsuGameBase { private readonly OsuTestCase testCase; protected override string MainResourceFile => File.Exists(base.MainResourceFile) ? base.MainResourceFile : Assembly.GetExecutingAssembly().Location; public OsuTestCaseTestRunner(OsuTestCase testCase) { this.testCase = testCase; } protected override void LoadComplete() { base.LoadComplete(); Add(new TestCaseTestRunner.TestRunner(testCase)); } } } }
mit
C#
0c255d5c3a1b30a96512adcf0ca0689a1c2f0c0f
Adjust to new model. Provide change callback for task.
mono-soc-2012/Tasque,mono-soc-2012/Tasque,mono-soc-2012/Tasque
src/Addins/SqliteBackend/SqliteNote.cs
src/Addins/SqliteBackend/SqliteNote.cs
// SqliteNote.cs created with MonoDevelop // User: calvin at 10:56 AM 2/12/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // using System; namespace Tasque.Backends.Sqlite { public class SqliteNote : TaskNote { public SqliteNote (int id, string text) : base (text) { Id = id; } public int Id { get; private set; } protected override void OnTextChanged () { if (OnTextChangedAction != null) OnTextChangedAction (); base.OnTextChanged (); } internal Action OnTextChangedAction { get; set; } } }
// SqliteNote.cs created with MonoDevelop // User: calvin at 10:56 AM 2/12/2008 // // To change standard headers go to Edit->Preferences->Coding->Standard Headers // namespace Tasque.Backends.Sqlite { public class SqliteNote : TaskNote { private int id; private string text; public SqliteNote (int id, string text) { this.id = id; this.text = text; } public string Text { get { return this.text; } set { this.text = value; } } public int ID { get { return this.id; } } } }
mit
C#
533996115b6bbaac8edb86c795d23466848673e7
Normalize path so NuGet.Core's GetFiles(path) works correctly.
googol/NuGet.Lucene,Stift/NuGet.Lucene,themotleyfool/NuGet.Lucene
source/NuGet.Lucene/FastZipPackageFile.cs
source/NuGet.Lucene/FastZipPackageFile.cs
using System.Collections.Generic; using System.IO; using System.Runtime.Versioning; namespace NuGet.Lucene { public class FastZipPackageFile : IPackageFile { private readonly IFastZipPackage fastZipPackage; private readonly FrameworkName targetFramework; internal FastZipPackageFile(IFastZipPackage fastZipPackage, string path) { this.fastZipPackage = fastZipPackage; Path = Normalize(path); string effectivePath; targetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Path, out effectivePath); EffectivePath = effectivePath; } private string Normalize(string path) { return path .Replace('/', System.IO.Path.DirectorySeparatorChar) .TrimStart(System.IO.Path.DirectorySeparatorChar); } public string Path { get; private set; } public string EffectivePath { get; private set; } public FrameworkName TargetFramework { get { return targetFramework; } } IEnumerable<FrameworkName> IFrameworkTargetable.SupportedFrameworks { get { if (TargetFramework != null) { yield return TargetFramework; } } } public Stream GetStream() { return fastZipPackage.GetZipEntryStream(Path); } public override string ToString() { return Path; } } }
using System.Collections.Generic; using System.IO; using System.Runtime.Versioning; namespace NuGet.Lucene { public class FastZipPackageFile : IPackageFile { private readonly IFastZipPackage fastZipPackage; private readonly FrameworkName targetFramework; internal FastZipPackageFile(IFastZipPackage fastZipPackage, string path) { this.fastZipPackage = fastZipPackage; Path = path; string effectivePath; targetFramework = VersionUtility.ParseFrameworkNameFromFilePath(Normalize(path), out effectivePath); EffectivePath = effectivePath; } private string Normalize(string path) { return path .Replace('/', System.IO.Path.DirectorySeparatorChar) .TrimStart(System.IO.Path.DirectorySeparatorChar); } public string Path { get; private set; } public string EffectivePath { get; private set; } public FrameworkName TargetFramework { get { return targetFramework; } } IEnumerable<FrameworkName> IFrameworkTargetable.SupportedFrameworks { get { if (TargetFramework != null) { yield return TargetFramework; } } } public Stream GetStream() { return fastZipPackage.GetZipEntryStream(Path); } public override string ToString() { return Path; } } }
apache-2.0
C#
a0d5fd8eb96b359df6be13ff0bb12f31b2a5d7d7
upgrade version to 1.4.8
tangxuehua/ecommon,Aaron-Liu/ecommon
src/ECommon/Properties/AssemblyInfo.cs
src/ECommon/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ECommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ECommon")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b3edf459-8725-465e-a484-410b9a68df1f")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.8")] [assembly: AssemblyFileVersion("1.4.8")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("ECommon")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ECommon")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("b3edf459-8725-465e-a484-410b9a68df1f")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.4.7")] [assembly: AssemblyFileVersion("1.4.7")]
mit
C#
14fb6c61adbd2c26ecccece70e6d5ff8f82002ee
Remove requirement on master branch existing
ermshiperete/GitVersion,onovotny/GitVersion,pascalberger/GitVersion,onovotny/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,Philo/GitVersion,ermshiperete/GitVersion,ParticularLabs/GitVersion,gep13/GitVersion,dpurge/GitVersion,JakeGinnivan/GitVersion,dpurge/GitVersion,Philo/GitVersion,GitTools/GitVersion,ermshiperete/GitVersion,FireHost/GitVersion,onovotny/GitVersion,DanielRose/GitVersion,JakeGinnivan/GitVersion,pascalberger/GitVersion,JakeGinnivan/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,FireHost/GitVersion,pascalberger/GitVersion,GitTools/GitVersion,DanielRose/GitVersion,dazinator/GitVersion,dpurge/GitVersion,dazinator/GitVersion,ParticularLabs/GitVersion,asbjornu/GitVersion,gep13/GitVersion,JakeGinnivan/GitVersion
src/GitVersionCore/GitVersionFinder.cs
src/GitVersionCore/GitVersionFinder.cs
namespace GitVersion { using System.IO; using System.Linq; using GitVersion.VersionCalculation; using LibGit2Sharp; public class GitVersionFinder { public SemanticVersion FindVersion(GitVersionContext context) { Logger.WriteInfo(string.Format("Running against branch: {0} ({1})", context.CurrentBranch.Name, context.CurrentCommit.Sha)); EnsureMainTopologyConstraints(context); var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt"); if (File.Exists(filePath)) { throw new WarningException("NextVersion.txt has been depreciated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement"); } return new NextVersionCalculator().FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) { EnsureHeadIsNotDetached(context); } void EnsureHeadIsNotDetached(GitVersionContext context) { if (!context.CurrentBranch.IsDetachedHead()) { return; } var message = string.Format( "It looks like the branch being examined is a detached Head pointing to commit '{0}'. " + "Without a proper branch name GitVersion cannot determine the build version.", context.CurrentCommit.Id.ToString(7)); throw new WarningException(message); } } }
namespace GitVersion { using System.IO; using System.Linq; using GitVersion.VersionCalculation; using LibGit2Sharp; public class GitVersionFinder { public SemanticVersion FindVersion(GitVersionContext context) { Logger.WriteInfo(string.Format("Running against branch: {0} ({1})", context.CurrentBranch.Name, context.CurrentCommit.Sha)); EnsureMainTopologyConstraints(context); var filePath = Path.Combine(context.Repository.GetRepositoryDirectory(), "NextVersion.txt"); if (File.Exists(filePath)) { throw new WarningException("NextVersion.txt has been depreciated. See http://gitversion.readthedocs.org/en/latest/configuration/ for replacement"); } return new NextVersionCalculator().FindVersion(context); } void EnsureMainTopologyConstraints(GitVersionContext context) { EnsureLocalBranchExists(context.Repository, "master"); EnsureHeadIsNotDetached(context); } void EnsureHeadIsNotDetached(GitVersionContext context) { if (!context.CurrentBranch.IsDetachedHead()) { return; } var message = string.Format( "It looks like the branch being examined is a detached Head pointing to commit '{0}'. " + "Without a proper branch name GitVersion cannot determine the build version.", context.CurrentCommit.Id.ToString(7)); throw new WarningException(message); } void EnsureLocalBranchExists(IRepository repository, string branchName) { if (repository.FindBranch(branchName) != null) { return; } var existingBranches = string.Format("'{0}'", string.Join("', '", repository.Branches.Select(x => x.CanonicalName))); throw new WarningException(string.Format("This repository doesn't contain a branch named '{0}'. Please create one. Existing branches: {1}", branchName, existingBranches)); } } }
mit
C#
35d0c688ca5a5e28e96b207a6535859563d73226
Fix a memory leak in StreamNode.
jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Perspex,wieslawsoltes/Perspex,grokys/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,grokys/Perspex
src/Avalonia.Base/Data/Core/StreamNode.cs
src/Avalonia.Base/Data/Core/StreamNode.cs
using System; using System.Reactive.Linq; using Avalonia.Data.Core.Plugins; namespace Avalonia.Data.Core { public class StreamNode : ExpressionNode { private IStreamPlugin _customPlugin = null; private IDisposable _subscription; public override string Description => "^"; public StreamNode() { } public StreamNode(IStreamPlugin customPlugin) { _customPlugin = customPlugin; } protected override void StartListeningCore(WeakReference<object> reference) { _subscription = GetPlugin(reference)?.Start(reference).Subscribe(ValueChanged); } protected override void StopListeningCore() { _subscription?.Dispose(); _subscription = null; } private IStreamPlugin GetPlugin(WeakReference<object> reference) { if (_customPlugin != null) { return _customPlugin; } foreach (var plugin in ExpressionObserver.StreamHandlers) { if (plugin.Match(reference)) { return plugin; } } // TODO: Improve error ValueChanged(new BindingNotification( new MarkupBindingChainException("Stream operator applied to unsupported type", Description), BindingErrorType.Error)); return null; } } }
using System; using System.Reactive.Linq; using Avalonia.Data.Core.Plugins; namespace Avalonia.Data.Core { public class StreamNode : ExpressionNode { private IStreamPlugin _customPlugin = null; private IDisposable _subscription; public override string Description => "^"; public StreamNode() { } public StreamNode(IStreamPlugin customPlugin) { _customPlugin = customPlugin; } protected override void StartListeningCore(WeakReference<object> reference) { GetPlugin(reference)?.Start(reference).Subscribe(ValueChanged); } protected override void StopListeningCore() { _subscription?.Dispose(); _subscription = null; } private IStreamPlugin GetPlugin(WeakReference<object> reference) { if (_customPlugin != null) { return _customPlugin; } foreach (var plugin in ExpressionObserver.StreamHandlers) { if (plugin.Match(reference)) { return plugin; } } // TODO: Improve error ValueChanged(new BindingNotification( new MarkupBindingChainException("Stream operator applied to unsupported type", Description), BindingErrorType.Error)); return null; } } }
mit
C#
0f26f8b6ef146f9d271a2634cfebbb34ebf17d8c
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.46.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © Damnae 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.45.*")]
mit
C#
c1eed9543cc7322b427312eef0374a2145889311
Write arbitrary content to the repl
FlorianRappl/Mages,FlorianRappl/Mages
src/Mages.Repl/Functions/ReplObject.cs
src/Mages.Repl/Functions/ReplObject.cs
namespace Mages.Repl.Functions { using Mages.Core.Runtime; using System; sealed class ReplObject { public String Read() { return Console.ReadLine(); } public void Write(Object value) { var str = Stringify.This(value); Console.Write(str); } public void WriteLine(Object value) { var str = Stringify.This(value); Console.WriteLine(str); } } }
namespace Mages.Repl.Functions { using System; sealed class ReplObject { public String Read() { return Console.ReadLine(); } public void Write(String str) { Console.Write(str); } public void WriteLine(String str) { Console.WriteLine(str); } } }
mit
C#
dd95379c6dda87423c218d1b2d2040d2c7fb9ca2
Add global exception handler
OvidiuCaba/BulkScriptRunner
src/RunQueries/App.xaml.cs
src/RunQueries/App.xaml.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Threading; namespace RunQueries { public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { RegisterGlobalExceptionHandling(); } private void RegisterGlobalExceptionHandling() { AppDomain.CurrentDomain.UnhandledException += (sender, args) => CurrentDomainOnUnhandledException(args); Dispatcher.UnhandledException += (sender, args) => DispatcherOnUnhandledException(args); Application.Current.DispatcherUnhandledException += (sender, args) => CurrentOnDispatcherUnhandledException(args); TaskScheduler.UnobservedTaskException += (sender, args) => TaskSchedulerOnUnobservedTaskException(args); } private static void TaskSchedulerOnUnobservedTaskException(UnobservedTaskExceptionEventArgs args) { MessageBox.Show(args.Exception.Message); args.SetObserved(); } private static void CurrentOnDispatcherUnhandledException(DispatcherUnhandledExceptionEventArgs args) { MessageBox.Show(args.Exception.Message); args.Handled = true; } private static void DispatcherOnUnhandledException(DispatcherUnhandledExceptionEventArgs args) { MessageBox.Show(args.Exception.Message); args.Handled = true; } private static void CurrentDomainOnUnhandledException(UnhandledExceptionEventArgs args) { var exception = args.ExceptionObject as Exception; var terminatingMessage = args.IsTerminating ? " The application is terminating." : string.Empty; var exceptionMessage = exception?.Message ?? "An unmanaged exception occured."; var message = string.Concat(exceptionMessage, terminatingMessage); MessageBox.Show(message); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace RunQueries { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
mit
C#
a92e1347fa83985aa2961c5b1da2d418b32c7756
Make Git metadata more sensible for local builds
martincostello/website,martincostello/website,martincostello/website,martincostello/website
src/Website/GitMetadata.cs
src/Website/GitMetadata.cs
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website { using System; using System.Globalization; using System.Linq; using System.Reflection; /// <summary> /// A class containing Git metadata for the assembly. This class cannot be inherited. /// </summary> public static class GitMetadata { /// <summary> /// Gets the SHA for the Git branch the assembly was compiled from. /// </summary> public static string Branch { get; } = GetMetadataValue("CommitBranch", "Unknown"); /// <summary> /// Gets the SHA for the Git commit the assembly was compiled from. /// </summary> public static string Commit { get; } = GetMetadataValue("CommitHash", "HEAD"); /// <summary> /// Gets the timestamp the assembly was compiled at. /// </summary> public static DateTime Timestamp { get; } = DateTime.Parse(GetMetadataValue("BuildTimestamp", DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture)), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); /// <summary> /// Gets the Git commit SHA associated with this revision of the application. /// </summary> /// <returns> /// A <see cref="string"/> containing the Git SHA-1 for the revision of the application. /// </returns> private static string GetMetadataValue(string name, string defaultValue) { return typeof(GitMetadata).GetTypeInfo().Assembly .GetCustomAttributes<AssemblyMetadataAttribute>() .Where((p) => string.Equals(p.Key, name, StringComparison.Ordinal)) .Select((p) => p.Value) .DefaultIfEmpty(defaultValue) .FirstOrDefault(); } } }
// Copyright (c) Martin Costello, 2016. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. namespace MartinCostello.Website { using System; using System.Globalization; using System.Linq; using System.Reflection; /// <summary> /// A class containing Git metadata for the assembly. This class cannot be inherited. /// </summary> public static class GitMetadata { /// <summary> /// Gets the SHA for the Git branch the assembly was compiled from. /// </summary> public static string Branch { get; } = GetMetadataValue("CommitBranch", "Unknown"); /// <summary> /// Gets the SHA for the Git commit the assembly was compiled from. /// </summary> public static string Commit { get; } = GetMetadataValue("CommitHash", "Local"); /// <summary> /// Gets the timestamp the assembly was compiled at. /// </summary> public static DateTime Timestamp { get; } = DateTime.Parse(GetMetadataValue("BuildTimestamp", "0001-01-01T00:00:00Z"), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal); /// <summary> /// Gets the Git commit SHA associated with this revision of the application. /// </summary> /// <returns> /// A <see cref="string"/> containing the Git SHA-1 for the revision of the application. /// </returns> private static string GetMetadataValue(string name, string defaultValue) { return typeof(GitMetadata).GetTypeInfo().Assembly .GetCustomAttributes<AssemblyMetadataAttribute>() .Where((p) => string.Equals(p.Key, name, StringComparison.Ordinal)) .Select((p) => p.Value) .DefaultIfEmpty(defaultValue) .FirstOrDefault(); } } }
apache-2.0
C#
a44a032fa9590841d433b53e250681da19afb007
Change assemblyinfo for quartz package.
carldai0106/aspnetboilerplate,ShiningRush/aspnetboilerplate,fengyeju/aspnetboilerplate,oceanho/aspnetboilerplate,berdankoca/aspnetboilerplate,carldai0106/aspnetboilerplate,4nonym0us/aspnetboilerplate,ryancyq/aspnetboilerplate,ryancyq/aspnetboilerplate,yuzukwok/aspnetboilerplate,andmattia/aspnetboilerplate,s-takatsu/aspnetboilerplate,s-takatsu/aspnetboilerplate,berdankoca/aspnetboilerplate,berdankoca/aspnetboilerplate,beratcarsi/aspnetboilerplate,zquans/aspnetboilerplate,fengyeju/aspnetboilerplate,fengyeju/aspnetboilerplate,andmattia/aspnetboilerplate,ShiningRush/aspnetboilerplate,ilyhacker/aspnetboilerplate,jaq316/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,AlexGeller/aspnetboilerplate,verdentk/aspnetboilerplate,Nongzhsh/aspnetboilerplate,carldai0106/aspnetboilerplate,4nonym0us/aspnetboilerplate,ZhaoRd/aspnetboilerplate,zclmoon/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,verdentk/aspnetboilerplate,ShiningRush/aspnetboilerplate,zquans/aspnetboilerplate,virtualcca/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,oceanho/aspnetboilerplate,AlexGeller/aspnetboilerplate,ZhaoRd/aspnetboilerplate,ZhaoRd/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,abdllhbyrktr/aspnetboilerplate,yuzukwok/aspnetboilerplate,ilyhacker/aspnetboilerplate,oceanho/aspnetboilerplate,virtualcca/aspnetboilerplate,beratcarsi/aspnetboilerplate,ryancyq/aspnetboilerplate,zclmoon/aspnetboilerplate,andmattia/aspnetboilerplate,virtualcca/aspnetboilerplate,zclmoon/aspnetboilerplate,Nongzhsh/aspnetboilerplate,jaq316/aspnetboilerplate,carldai0106/aspnetboilerplate,4nonym0us/aspnetboilerplate,yuzukwok/aspnetboilerplate,aspnetboilerplate/aspnetboilerplate,zquans/aspnetboilerplate,jaq316/aspnetboilerplate,ryancyq/aspnetboilerplate,Nongzhsh/aspnetboilerplate,s-takatsu/aspnetboilerplate,luchaoshuai/aspnetboilerplate,AlexGeller/aspnetboilerplate,beratcarsi/aspnetboilerplate,verdentk/aspnetboilerplate,luchaoshuai/aspnetboilerplate,ilyhacker/aspnetboilerplate
src/Abp.Quartz/Properties/AssemblyInfo.cs
src/Abp.Quartz/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("Abp.Quartz")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Volosoft")] [assembly: AssemblyProduct("Abp.Quartz")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f90b1606-f375-4c84-9118-ab0c1ddeb0df")]
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Abp.Quartz")] [assembly: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f90b1606-f375-4c84-9118-ab0c1ddeb0df")]
mit
C#
94ef78d0129c4204b98083cce7c3ef29cfe366b0
Update RoberthStrand.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/RoberthStrand.cs
src/Firehose.Web/Authors/RoberthStrand.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 RoberthStrand : IAmACommunityMember { public string FirstName => "Roberth"; public string LastName => "Strand"; public string ShortBioOrTagLine => "PowerShell, Azure, Security and other fun stuff!"; public string StateOrRegion => "Tromsø, Norway"; public string EmailAddress => "[email protected]"; public string TwitterHandle => "RoberthTweets"; public string GravatarHash => "0f8d0c1b68924de4beed584aefd30e20"; public string GitHubHandle => "roberthstrand"; public GeoPosition Position => new GeoPosition(69.648491, 18.983705); public Uri WebSite => new Uri("https://robstr.dev"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://robstr.dev/powershell"); } } public string FeedLanguageCode => "en"; } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class RoberthStrand : IAmACommunityMember { public string FirstName => "Roberth"; public string LastName => "Strand"; public string ShortBioOrTagLine => "Norwegian consultant writing about PowerShell, cloud, security and other fun topics."; public string StateOrRegion => "Tromsø, Norway"; public string EmailAddress => "[email protected]"; public string TwitterHandle => "RoberthTweets"; public string GravatarHash => "0f8d0c1b68924de4beed584aefd30e20"; public string GitHubHandle => "roberthstrand"; public GeoPosition Position => new GeoPosition(69.648491, 18.983705); public Uri WebSite => new Uri("https://blog.destruktive.one"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://destruktive.one/category/powershell/feed/"); } } public string FeedLanguageCode => "en"; } }
mit
C#
3ab5784cdf54b6f2ea503ef94da537e5918bc12b
use GetAwaiter().GetResult() for Tasks instead of .Wait or .Result, #236
alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Ky7m/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Ky7m/BenchmarkDotNet
src/BenchmarkDotNet.Core/Running/AsyncMethodInvoker.cs
src/BenchmarkDotNet.Core/Running/AsyncMethodInvoker.cs
using System; using System.Threading.Tasks; using HideFromIntelliSense = System.ComponentModel.EditorBrowsableAttribute; // we don't want people to use it namespace BenchmarkDotNet.Running { // if you want to rename any of these methods you need to update DeclarationsProvider's code as well // ReSharper disable MemberCanBePrivate.Global public static class TaskMethodInvoker { // can't use Task.CompletedTask here because it's new in .NET 4.6 (we target 4.5) private static readonly Task Completed = Task.FromResult((object)null); [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static void Idle() => ExecuteBlocking(() => Completed); // we use GetAwaiter().GetResult() because it's fastest way to obtain the result in blocking way, // and will eventually throw actual exception, not aggregated one [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static void ExecuteBlocking(Func<Task> future) => future.Invoke().GetAwaiter().GetResult(); } public static class TaskMethodInvoker<T> { private static readonly Task<T> Completed = Task.FromResult(default(T)); [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T Idle() => ExecuteBlocking(() => Completed); // we use GetAwaiter().GetResult() because it's fastest way to obtain the result in blocking way, // and will eventually throw actual exception, not aggregated one [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T ExecuteBlocking(Func<Task<T>> future) => future.Invoke().GetAwaiter().GetResult(); } public static class ValueTaskMethodInvoker<T> { [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T Idle() => ExecuteBlocking(() => new ValueTask<T>(default(T))); // we use .Result instead of .GetAwaiter().GetResult() because it's faster [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T ExecuteBlocking(Func<ValueTask<T>> future) => future.Invoke().Result; } // ReSharper restore MemberCanBePrivate.Global }
using System; using System.Threading.Tasks; using HideFromIntelliSense = System.ComponentModel.EditorBrowsableAttribute; // we don't want people to use it namespace BenchmarkDotNet.Running { // if you want to rename any of these methods you need to update DeclarationsProvider's code as well // ReSharper disable MemberCanBePrivate.Global public static class TaskMethodInvoker { // can't use Task.CompletedTask here because it's new in .NET 4.6 (we target 4.5) private static readonly Task Completed = Task.FromResult((object)null); [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static void Idle() => ExecuteBlocking(() => Completed); [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static void ExecuteBlocking(Func<Task> future) => future.Invoke().Wait(); } public static class TaskMethodInvoker<T> { private static readonly Task<T> Completed = Task.FromResult(default(T)); [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T Idle() => ExecuteBlocking(() => Completed); // we use .Result because it's blocking and will eventually rethrow any exception [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T ExecuteBlocking(Func<Task<T>> future) => future.Invoke().Result; } public static class ValueTaskMethodInvoker<T> { [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T Idle() => ExecuteBlocking(() => new ValueTask<T>(default(T))); [HideFromIntelliSense(System.ComponentModel.EditorBrowsableState.Never)] public static T ExecuteBlocking(Func<ValueTask<T>> future) => future.Invoke().Result; } // ReSharper restore MemberCanBePrivate.Global }
mit
C#
1f040ac2ffb26b59c14a4a7bb7ed2cf242abeb7c
Fix for link sdk assemblies only on iOS
paulpatarinski/Xamarin.Forms.Plugins
RoundedBoxView/RoundedBoxView/RoundedBoxView.Forms.Plugin.iOSUnified/RoundedBoxViewImplementation.cs
RoundedBoxView/RoundedBoxView/RoundedBoxView.Forms.Plugin.iOSUnified/RoundedBoxViewImplementation.cs
using System.ComponentModel; using RoundedBoxView.Forms.Plugin.iOSUnified; using RoundedBoxView.Forms.Plugin.iOSUnified.ExtensionMethods; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; using Foundation; using System; [assembly: ExportRenderer(typeof (RoundedBoxView.Forms.Plugin.Abstractions.RoundedBoxView), typeof (RoundedBoxViewRenderer))] namespace RoundedBoxView.Forms.Plugin.iOSUnified { /// <summary> /// Source From : https://gist.github.com/rudyryk/8cbe067a1363b45351f6 /// </summary> [Preserve(AllMembers = true)] public class RoundedBoxViewRenderer : BoxRenderer { /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { var temp = DateTime.Now; } private Abstractions.RoundedBoxView _formControl { get { return Element as Abstractions.RoundedBoxView; } } protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e) { base.OnElementChanged(e); this.InitializeFrom(_formControl); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); this.UpdateFrom(_formControl, e.PropertyName); } } }
using System.ComponentModel; using RoundedBoxView.Forms.Plugin.iOSUnified; using RoundedBoxView.Forms.Plugin.iOSUnified.ExtensionMethods; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof (RoundedBoxView.Forms.Plugin.Abstractions.RoundedBoxView), typeof (RoundedBoxViewRenderer))] namespace RoundedBoxView.Forms.Plugin.iOSUnified { /// <summary> /// Source From : https://gist.github.com/rudyryk/8cbe067a1363b45351f6 /// </summary> public class RoundedBoxViewRenderer : BoxRenderer { /// <summary> /// Used for registration with dependency service /// </summary> public static void Init() { } private Abstractions.RoundedBoxView _formControl { get { return Element as Abstractions.RoundedBoxView; } } protected override void OnElementChanged(ElementChangedEventArgs<BoxView> e) { base.OnElementChanged(e); this.InitializeFrom(_formControl); } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); this.UpdateFrom(_formControl, e.PropertyName); } } }
mit
C#
f21e9052b4fbd137b12c4ec33717fee9b9917e9e
Update version number.
Damnae/storybrew
editor/Properties/AssemblyInfo.cs
editor/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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.13.*")]
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("storybrew editor")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("storybrew editor")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ff59aeea-c133-4bf8-8a0b-620a3c99022b")] // 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.12.*")]
mit
C#
fc7117cb781e5c1460901ab320b0202468de9fbc
Make sure we always use the same save directory
edwinj85/ezDoom
ezDoom/Code/GameProcessHandler.cs
ezDoom/Code/GameProcessHandler.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; namespace ezDoom.Code { /// <summary> /// This class handles launching the doom engine with chosen settings. /// </summary> public static class GameProcessHandler { /// <summary> /// This method launches the doom engine with chosen settings. /// </summary> public static void RunGame(string IWADPath, IEnumerable<GamePackage> mods) { //use a string builder to take all the chosen mods and turn them into a string we can pass as an argument. StringBuilder sb = new StringBuilder(); foreach (GamePackage item in mods) { sb.AppendFormat(" \"../{0}/{1}\" ", ConstStrings.ModsFolderName, item.FullName); } string chosenPackages = sb.ToString(); //create process to launch the game. var details = new ProcessStartInfo(ConstStrings.EngineFolderName + "/gzdoom.exe"); details.UseShellExecute = false; //we need to set UseShellExecute to false to make the exe run from the local folder. //Store game saves in the user's saved games folder. var userDirectory = Environment.ExpandEnvironmentVariables("%USERPROFILE%"); var savesDirectory = Path.Combine(userDirectory, "Saved Games", "ezDoom"); savesDirectory = string.Format("\"{0}\"", savesDirectory); //launch GZDoom with the correct args. details.Arguments = string.Format("-iwad \"../iwads/{0}\" -file {1} -savedir {2}", IWADPath, chosenPackages, savesDirectory); //we wrap the process in a using statement to make sure the handle is always disposed after use. using (Process process = Process.Start(details)) { }; } } }
using System.Collections.Generic; using System.Deployment.Application; using System.Diagnostics; using System.Text; namespace ezDoom.Code { /// <summary> /// This class handles launching the doom engine with chosen settings. /// </summary> public static class GameProcessHandler { /// <summary> /// This method launches the doom engine with chosen settings. /// </summary> public static void RunGame(string IWADPath, IEnumerable<GamePackage> mods) { //use a string builder to take all the chosen mods and turn them into a string we can pass as an argument. StringBuilder sb = new StringBuilder(); foreach (GamePackage item in mods) { sb.AppendFormat(" \"../{0}/{1}\" ", ConstStrings.ModsFolderName, item.FullName); } string chosenPackages = sb.ToString(); //create process to launch the game. var details = new ProcessStartInfo(ConstStrings.EngineFolderName + "/gzdoom.exe"); details.UseShellExecute = false; //we need to set UseShellExecute to false to make the exe run from the local folder. //attempt to use the clickonce data directory folder for saves to keep them persistent between updates. //Default to the /Saves directory if this fails. var savesDirectory = "/Saves"; if (ApplicationDeployment.IsNetworkDeployed) { savesDirectory = System.Deployment.Application.ApplicationDeployment.CurrentDeployment.DataDirectory; } //launch GZDoom with the correct args. details.Arguments = string.Format("-iwad \"../iwads/{0}\" -file {1} -savedir {2}", IWADPath, chosenPackages, savesDirectory); //we wrap the process in a using statement to make sure the handle is always disposed after use. using (Process process = Process.Start(details)) { }; } } }
apache-2.0
C#
b898782efc101a9ed60524553f6b05b8413d96b1
Update Gunnery.cs (#33)
BosslandGmbH/BuddyWing.DefaultCombat
trunk/DefaultCombat/Routines/Advanced/Commando/Gunnery.cs
trunk/DefaultCombat/Routines/Advanced/Commando/Gunnery.cs
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { internal class Gunnery : RotationBase { public override string Name { get { return "Commando Gunnery"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Fortification") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Tenacity"), Spell.Buff("Reactive Shield", ret => Me.HealthPercent <= 70), Spell.Cast("Echoing Deterrence", ret => Me.HealthPercent <= 30), Spell.Buff("Adrenaline Rush", ret => Me.HealthPercent <= 30), Spell.Buff("Recharge Cells", ret => Me.ResourceStat <= 40), Spell.Buff("Supercharged Cell", ret => Me.BuffCount("Supercharge") == 10), Spell.Buff("Reserve Powercell", ret => Me.ResourceStat <= 60) ); } } public override Composite SingleTarget { get { return new PrioritySelector( Spell.Cast("Hammer Shot", ret => Me.ResourcePercent() < 60), //Movement CombatMovement.CloseDistance(Distance.Ranged), //Rotation Spell.Cast("Disabling Shot", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled), Spell.Cast("Boltstorm", ret => Me.HasBuff("Curtain of Fire") && Me.Level >= 57), Spell.Cast("Full Auto", ret => Me.HasBuff("Curtain of Fire") && Me.Level < 57), Spell.Cast("Demolition Round", ret => Me.CurrentTarget.HasDebuff("Gravity Vortex")), Spell.Cast("Electro Net"), Spell.Cast("Vortex Bolt"), Spell.Cast("High Impact Bolt", ret => Me.BuffCount("Charged Barrel") == 5), Spell.Cast("Grav Round") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.Cast("Sticky Grenade"), Spell.Cast("Tech Override"), Spell.CastOnGround("Mortar Volley"), Spell.Cast("Plasma Grenade", ret => Me.ResourceStat >= 90 && Me.HasBuff("Tech Override")), Spell.Cast("Pulse Cannon", ret => Me.CurrentTarget.Distance <= 1f), Spell.CastOnGround("Hail of Bolts", ret => Me.ResourceStat >= 90) )); } } } }
// Copyright (C) 2011-2016 Bossland GmbH // See the file LICENSE for the source code's detailed license using Buddy.BehaviorTree; using DefaultCombat.Core; using DefaultCombat.Helpers; namespace DefaultCombat.Routines { internal class Gunnery : RotationBase { public override string Name { get { return "Commando Gunnery"; } } public override Composite Buffs { get { return new PrioritySelector( Spell.Buff("Fortification") ); } } public override Composite Cooldowns { get { return new PrioritySelector( Spell.Buff("Tenacity"), Spell.Buff("Reactive Shield", ret => Me.HealthPercent <= 70), Spell.Buff("Adrenaline Rush", ret => Me.HealthPercent <= 30), Spell.Buff("Recharge Cells", ret => Me.ResourceStat <= 40), Spell.Buff("Supercharged Cell", ret => Me.BuffCount("Supercharge") == 10), Spell.Buff("Reserve Powercell", ret => Me.ResourceStat <= 60) ); } } public override Composite SingleTarget { get { return new PrioritySelector( Spell.Cast("Hammer Shot", ret => Me.ResourcePercent() < 60), //Movement CombatMovement.CloseDistance(Distance.Ranged), //Rotation Spell.Cast("Disabling Shot", ret => Me.CurrentTarget.IsCasting && !DefaultCombat.MovementDisabled), Spell.Cast("Boltstorm", ret => Me.HasBuff("Curtain of Fire") && Me.Level >= 57), Spell.Cast("Full Auto", ret => Me.HasBuff("Curtain of Fire") && Me.Level < 57), Spell.Cast("Demolition Round", ret => Me.CurrentTarget.HasDebuff("Gravity Vortex")), Spell.Cast("Electro Net"), Spell.Cast("Vortex Bolt"), Spell.Cast("High Impact Bolt", ret => Me.BuffCount("Charged Barrel") == 5), Spell.Cast("Grav Round") ); } } public override Composite AreaOfEffect { get { return new Decorator(ret => Targeting.ShouldAoe, new PrioritySelector( Spell.Cast("Sticky Grenade"), Spell.Cast("Tech Override"), Spell.CastOnGround("Mortar Volley"), Spell.Cast("Plasma Grenade", ret => Me.ResourceStat >= 90 && Me.HasBuff("Tech Override")), Spell.Cast("Pulse Cannon", ret => Me.CurrentTarget.Distance <= 1f), Spell.CastOnGround("Hail of Bolts", ret => Me.ResourceStat >= 90) )); } } } }
apache-2.0
C#
5e15d083bb2df04990b9168f2fe632cfd9eeb68a
rename to aviod "hungarian notation"
wikibus/Argolis
src/Argolis.Tests/Serialization/SerializationTestsBase.cs
src/Argolis.Tests/Serialization/SerializationTestsBase.cs
using JsonLD.Core; using JsonLD.Entities; using Newtonsoft.Json.Linq; namespace Argolis.Tests.Serialization { public abstract class SerializationTestsBase { private readonly IEntitySerializer serializer; protected SerializationTestsBase() { this.serializer = new EntitySerializer(); } public IEntitySerializer Serializer { get { return this.serializer; } } protected JObject Serialize(object obj) { var jsonObject = this.serializer.Serialize(obj); return JsonLdProcessor.Compact(jsonObject, new JObject(), new JsonLdOptions()); } } }
using JsonLD.Core; using JsonLD.Entities; using Newtonsoft.Json.Linq; namespace Argolis.Tests.Serialization { public abstract class SerializationTestsBase { private readonly IEntitySerializer serializer; protected SerializationTestsBase() { this.serializer = new EntitySerializer(); } public IEntitySerializer Serializer { get { return this.serializer; } } protected JObject Serialize(object obj) { var jObject = this.serializer.Serialize(obj); return JsonLdProcessor.Compact(jObject, new JObject(), new JsonLdOptions()); } } }
mit
C#
d2a39c50dff7798fe983f0269951ece9fa33bbf7
Fix the comments in the options
folkelib/Folke.Localization.Json
src/Folke.Localization.Json/JsonStringLocalizerFactory.cs
src/Folke.Localization.Json/JsonStringLocalizerFactory.cs
using System; using Microsoft.Framework.Localization; using Microsoft.Framework.OptionsModel; namespace Folke.Localization.Json { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class JsonStringLocalizerFactory : IStringLocalizerFactory { private readonly JsonStringLocalizerOptions options; public JsonStringLocalizerFactory(IOptions<JsonStringLocalizerOptions> options) { this.options = options.Value; } /// <summary> /// Creates an <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/> using the <see cref="T:System.Reflection.Assembly"/> and /// <see cref="P:System.Type.FullName"/> of the specified <see cref="T:System.Type"/>. /// </summary> /// <param name="resourceSource">The <see cref="T:System.Type"/>.</param> /// <returns> /// The <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/>. /// </returns> public IStringLocalizer Create(Type resourceSource) { return new JsonStringLocalizer(options.ResourceFilesDirectory, resourceSource.FullName, options.DefaultBaseName, null); } /// <summary> /// Creates an <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/>. /// </summary> /// <param name="baseName">The base name of the resource to load strings from.</param><param name="location">The location to load resources from.</param> /// <returns> /// The <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/>. /// </returns> public IStringLocalizer Create(string baseName, string location) { return new JsonStringLocalizer(location ?? options.ResourceFilesDirectory, baseName, options.DefaultBaseName, null); } } public class JsonStringLocalizerOptions { /// <summary> /// Where the resource directory are stored. The resource directories have the type full name and must /// contain file whose names are the supported culture name (with the .json extension). If a file is /// not found, default.json is open. /// </summary> public string ResourceFilesDirectory { get; set; } /// <summary> /// If the directory of a type is not found, use this name as a default. /// </summary> public string DefaultBaseName { get; set; } } }
using System; using Microsoft.Framework.Localization; using Microsoft.Framework.OptionsModel; namespace Folke.Localization.Json { // This project can output the Class library as a NuGet Package. // To enable this option, right-click on the project and select the Properties menu item. In the Build tab select "Produce outputs on build". public class JsonStringLocalizerFactory : IStringLocalizerFactory { private readonly JsonStringLocalizerOptions options; public JsonStringLocalizerFactory(IOptions<JsonStringLocalizerOptions> options) { this.options = options.Value; } /// <summary> /// Creates an <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/> using the <see cref="T:System.Reflection.Assembly"/> and /// <see cref="P:System.Type.FullName"/> of the specified <see cref="T:System.Type"/>. /// </summary> /// <param name="resourceSource">The <see cref="T:System.Type"/>.</param> /// <returns> /// The <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/>. /// </returns> public IStringLocalizer Create(Type resourceSource) { return new JsonStringLocalizer(options.ResourceFilesDirectory, resourceSource.FullName, options.DefaultBaseName, null); } /// <summary> /// Creates an <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/>. /// </summary> /// <param name="baseName">The base name of the resource to load strings from.</param><param name="location">The location to load resources from.</param> /// <returns> /// The <see cref="T:Microsoft.Framework.Localization.IStringLocalizer"/>. /// </returns> public IStringLocalizer Create(string baseName, string location) { return new JsonStringLocalizer(location ?? options.ResourceFilesDirectory, baseName, options.DefaultBaseName, null); } } public class JsonStringLocalizerOptions { /// <summary> /// Where the resource files are stored /// </summary> public string ResourceFilesDirectory { get; set; } /// <summary> /// If the json file for the type is not found, use this name /// </summary> public string DefaultBaseName { get; set; } } }
mit
C#
2a8582a5398e71e4a1d21aa734135a348a3f7e46
Make the export public
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio/Helpers/ActiveDocumentSnapshot.cs
src/GitHub.VisualStudio/Helpers/ActiveDocumentSnapshot.cs
using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TextManager.Interop; using System; using System.ComponentModel.Composition; using System.Diagnostics; namespace GitHub.VisualStudio { [Export(typeof(IActiveDocumentSnapshot))] [PartCreationPolicy(CreationPolicy.NonShared)] public class ActiveDocumentSnapshot : IActiveDocumentSnapshot { public string Name { get; private set; } public int StartLine { get; private set; } public int EndLine { get; private set; } [ImportingConstructor] public ActiveDocumentSnapshot([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) { StartLine = EndLine = -1; Name = Services.Dte2?.ActiveDocument?.FullName; var textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; Debug.Assert(textManager != null, "No SVsTextManager service available"); if (textManager == null) return; IVsTextView view; int anchorLine, anchorCol, endLine, endCol; if (ErrorHandler.Succeeded(textManager.GetActiveView(0, null, out view)) && ErrorHandler.Succeeded(view.GetSelection(out anchorLine, out anchorCol, out endLine, out endCol))) { StartLine = anchorLine + 1; EndLine = endLine + 1; } } } }
using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TextManager.Interop; using System; using System.ComponentModel.Composition; using System.Diagnostics; namespace GitHub.VisualStudio { [Export(typeof(IActiveDocumentSnapshot))] [PartCreationPolicy(CreationPolicy.NonShared)] class ActiveDocumentSnapshot : IActiveDocumentSnapshot { public string Name { get; private set; } public int StartLine { get; private set; } public int EndLine { get; private set; } [ImportingConstructor] public ActiveDocumentSnapshot([Import(typeof(SVsServiceProvider))] IServiceProvider serviceProvider) { StartLine = EndLine = -1; Name = Services.Dte2?.ActiveDocument?.FullName; var textManager = serviceProvider.GetService(typeof(SVsTextManager)) as IVsTextManager; Debug.Assert(textManager != null, "No SVsTextManager service available"); if (textManager == null) return; IVsTextView view; int anchorLine, anchorCol, endLine, endCol; if (ErrorHandler.Succeeded(textManager.GetActiveView(0, null, out view)) && ErrorHandler.Succeeded(view.GetSelection(out anchorLine, out anchorCol, out endLine, out endCol))) { StartLine = anchorLine + 1; EndLine = endLine + 1; } } } }
mit
C#
527367bc95142c8ec0bff339fd962245892a9bb9
update metadata interactionid
nhsconnect/gpconnect-provider-testing
GPConnect.Provider.AcceptanceTests/Constants/SpineConst.cs
GPConnect.Provider.AcceptanceTests/Constants/SpineConst.cs
namespace GPConnect.Provider.AcceptanceTests.Constants { internal static class SpineConst { internal static class InteractionIds { private const string BaseInteraction = "urn:nhs:names:services:gpconnect:fhir:"; public const string GpcGetCareRecord = BaseInteraction + "operation:gpc.getcarerecord"; public const string OrganizationSearch = BaseInteraction + "rest:search:organization"; public const string OrganizationRead = BaseInteraction + "rest:read:organization"; public const string PractitionerSearch = BaseInteraction + "rest:search:practitioner"; public const string PractitionerRead = BaseInteraction + "rest:read:practitioner"; public const string PatientSearch = BaseInteraction + "rest:search:patient"; public const string PatientRead = BaseInteraction + "rest:read:patient"; public const string LocationSearch = BaseInteraction + "rest:search:location"; public const string LocationRead = BaseInteraction + "rest:read:location"; public static string RegisterPatient = BaseInteraction + "operation:gpc.registerpatient"; public static string AppointmentCreate => BaseInteraction + "rest:create:appointment"; public static string AppointmentSearch => BaseInteraction + "rest:search:patient_appointments"; public static string AppointmentAmend => BaseInteraction + "rest:update:appointment"; public static string AppointmentCancel => BaseInteraction + "rest:cancel:appointment"; public static string AppointmentRead => BaseInteraction + "rest:read:appointment"; public static string SlotSearch => BaseInteraction + "rest:search:slot"; public static string MetadataRead => BaseInteraction + "rest:read:metadata-1"; public const string kFhirPractitioner = "urn:nhs:names:services:gpconnect:fhir:rest:search:practitioner"; } } }
namespace GPConnect.Provider.AcceptanceTests.Constants { internal static class SpineConst { internal static class InteractionIds { private const string BaseInteraction = "urn:nhs:names:services:gpconnect:fhir:"; public const string GpcGetCareRecord = BaseInteraction + "operation:gpc.getcarerecord"; public const string OrganizationSearch = BaseInteraction + "rest:search:organization"; public const string OrganizationRead = BaseInteraction + "rest:read:organization"; public const string PractitionerSearch = BaseInteraction + "rest:search:practitioner"; public const string PractitionerRead = BaseInteraction + "rest:read:practitioner"; public const string PatientSearch = BaseInteraction + "rest:search:patient"; public const string PatientRead = BaseInteraction + "rest:read:patient"; public const string LocationSearch = BaseInteraction + "rest:search:location"; public const string LocationRead = BaseInteraction + "rest:read:location"; public static string RegisterPatient = BaseInteraction + "operation:gpc.registerpatient"; public static string AppointmentCreate => BaseInteraction + "rest:create:appointment"; public static string AppointmentSearch => BaseInteraction + "rest:search:patient_appointments"; public static string AppointmentAmend => BaseInteraction + "rest:update:appointment"; public static string AppointmentCancel => BaseInteraction + "rest:cancel:appointment"; public static string AppointmentRead => BaseInteraction + "rest:read:appointment"; public static string SlotSearch => BaseInteraction + "rest:search:slot"; public static string MetadataRead => BaseInteraction + "rest:read:metadata"; public const string kFhirPractitioner = "urn:nhs:names:services:gpconnect:fhir:rest:search:practitioner"; } } }
apache-2.0
C#
6ab941aefdebec1bb960ac73a81a84bea2fafe4e
Print method to display debug information added
wtertinek/AcadTestRunner
AcadTestRunner/TestResult.cs
AcadTestRunner/TestResult.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AcadTestRunner { [DebuggerStepThrough] public class TestResult { private TestResult(IReadOnlyCollection<string> fullOutput) { Passed = true; Message = ""; BuildFullOutput(fullOutput); } private TestResult(string message, IReadOnlyCollection<string> fullOutput) { Passed = false; Message = message; BuildFullOutput(fullOutput); } private void BuildFullOutput(IReadOnlyCollection<string> fullOutput) { var skipEverySecondLine = true; for (int i = 1; i < fullOutput.Count - 1; i += 2) { if (!string.IsNullOrEmpty(fullOutput.ElementAt(i).Trim())) { skipEverySecondLine = false; } } if (skipEverySecondLine) { var builder = new StringBuilder(); for (int i = 0; i < fullOutput.Count; i += 2) { builder.AppendLine(fullOutput.ElementAt(i)); } FullOutput = builder.ToString(); } else { FullOutput = string.Join(Environment.NewLine, fullOutput); } } public bool Passed { get; private set; } public string Message { get; private set; } public string FullOutput { get; private set; } public void DebugPrintFullOutput(string testName) { var header = "---------- " + testName + " ----------"; Debug.WriteLine(header); Debug.WriteLine(FullOutput); Debug.WriteLine(new string('-', header.Length)); } internal static TestResult TestPassed(IReadOnlyCollection<string> fullOutput) { return new TestResult(fullOutput); } internal static TestResult TestFailed(string message, IReadOnlyCollection<string> fullOutput) { return new TestResult(message, fullOutput); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AcadTestRunner { [DebuggerStepThrough] public class TestResult { private TestResult(IReadOnlyCollection<string> fullOutput) { Passed = true; Message = ""; BuildFullOutput(fullOutput); } private TestResult(string message, IReadOnlyCollection<string> fullOutput) { Passed = false; Message = message; BuildFullOutput(fullOutput); } private void BuildFullOutput(IReadOnlyCollection<string> fullOutput) { var skipEverySecondLine = true; for (int i = 1; i < fullOutput.Count - 1; i += 2) { if (!string.IsNullOrEmpty(fullOutput.ElementAt(i).Trim())) { skipEverySecondLine = false; } } if (skipEverySecondLine) { var builder = new StringBuilder(); for (int i = 0; i < fullOutput.Count; i += 2) { builder.AppendLine(fullOutput.ElementAt(i)); } FullOutput = builder.ToString(); } else { FullOutput = string.Join(Environment.NewLine, fullOutput); } } public bool Passed { get; private set; } public string Message { get; private set; } public string FullOutput { get; private set; } internal static TestResult TestPassed(IReadOnlyCollection<string> fullOutput) { return new TestResult(fullOutput); } internal static TestResult TestFailed(string message, IReadOnlyCollection<string> fullOutput) { return new TestResult(message, fullOutput); } } }
mit
C#
c2457005a6aaf6f83fb004d68b888148577a1d8c
Revert "a"
MaikelE/aspnetboilerplate-fork,MaikelE/aspnetboilerplate-fork,MaikelE/aspnetboilerplate-fork
src/Abp/Domain/Uow/AbpDataFilters.cs
src/Abp/Domain/Uow/AbpDataFilters.cs
using Abp.Domain.Entities; namespace Abp.Domain.Uow { /// <summary> /// Standard filters of ABP. /// </summary> public static class AbpDataFilters { /// <summary> /// "SoftDelete". /// Soft delete filter. /// Prevents getting deleted data from database. /// See <see cref="ISoftDelete"/> interface. /// </summary> public const string SoftDelete = "SoftDelete"; /// <summary> /// "MustHaveTenant". /// Tenant filter to prevent getting data that is /// not belong to current tenant. /// </summary> public const string MustHaveTenant = "MustHaveTenant"; /// <summary> /// "MayHaveTenant". /// Tenant filter to prevent getting data that is /// not belong to current tenant. /// </summary> public const string MayHaveTenant = "MayHaveTenant"; /// <summary> /// Standard parameters of ABP. /// </summary> public static class Parameters { /// <summary> /// "tenantId". /// </summary> public const string TenantId = "tenantId"; } } }
using Abp.Domain.Entities; namespace Abp.Domain.Uow { /// <summary> /// Standard filters of ABP. /// </summary> public static class AbpDataFilters { /// <summary> /// "SoftDelete". /// Soft delete filter. /// Prevents getting deleted data from database. /// See <see cref="ISoftDelete"/> interface. /// </summary> public const string SoftDelete = "SoftDelete"; /// <summary> /// "MustHaveTenant". /// Tenant filter to prevent getting data that is /// not belong to current tenant. /// </summary> public const string MustHaveTenant = "MustHaveTenant"; /// <summary> /// "MayHaveTenant". /// Tenant filter to prevent getting data that is /// not belong to current tenant. /// </summary> public const string MayHaveTenant = "MayHaveTenant"; /// <summary> /// Standard parameters of ABP. /// </summary> public static class Parameters { /// <summary> /// "tenantId". /// </summary> public const string TenantId = "tenantId"; /// <summary> /// "UserTenants". /// </summary> public const string UserTenants = "userTenants"; } } }
mit
C#
deaa24c0e21cf5d3e39c3d1d5526110c35ff52ce
Remove resharper comment and override the Count prop
EVAST9919/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,peppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework
osu.Framework/Configuration/IBindableCollection.cs
osu.Framework/Configuration/IBindableCollection.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections; using System.Collections.Generic; namespace osu.Framework.Configuration { public interface IBindableCollection : ICollection, IParseable, ICanBeDisabled, IUnbindable, IHasDescription { /// <summary> /// Binds self to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindableCollection them); /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> IBindableCollection GetBoundCopy(); } /// <summary> /// An interface which can be bound to other <see cref="IBindableCollection{T}"/>s in order to watch for (and react to) <see cref="IBindableCollection{T}.Disabled"/> and item changes. /// </summary> /// <typeparam name="T">The type of value encapsulated by this <see cref="IBindable{T}"/>.</typeparam> public interface IBindableCollection<T> : ICollection<T>, IBindableCollection, IReadonlyBindableCollection<T> { /// <summary> /// Adds the elements of the specified collection to this collection. /// </summary> /// <param name="collection">The collection whose elements should be added to this collection.</param> void AddRange(IEnumerable<T> collection); /// <summary> /// Binds self to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindableCollection<T> them); /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> new IBindableCollection<T> GetBoundCopy(); //avoiding possible ambiguity new int Count { get; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System.Collections; using System.Collections.Generic; namespace osu.Framework.Configuration { // ReSharper disable PossibleInterfaceMemberAmbiguity public interface IBindableCollection : ICollection, IParseable, ICanBeDisabled, IUnbindable, IHasDescription { // ReSharper restore PossibleInterfaceMemberAmbiguity /// <summary> /// Binds self to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindableCollection them); /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> IBindableCollection GetBoundCopy(); } /// <summary> /// An interface which can be bound to other <see cref="IBindableCollection{T}"/>s in order to watch for (and react to) <see cref="IBindableCollection{T}.Disabled"/> and item changes. /// </summary> /// <typeparam name="T">The type of value encapsulated by this <see cref="IBindable{T}"/>.</typeparam> public interface IBindableCollection<T> : ICollection<T>, IBindableCollection, IReadonlyBindableCollection<T> { /// <summary> /// Adds the elements of the specified collection to this collection. /// </summary> /// <param name="collection">The collection whose elements should be added to this collection.</param> void AddRange(IEnumerable<T> collection); /// <summary> /// Binds self to another bindable such that we receive any values and value limitations of the bindable we bind width. /// </summary> /// <param name="them">The foreign bindable. This should always be the most permanent end of the bind (ie. a ConfigManager)</param> void BindTo(IBindableCollection<T> them); /// <summary> /// Retrieve a new bindable instance weakly bound to the configuration backing. /// If you are further binding to events of a bindable retrieved using this method, ensure to hold /// a local reference. /// </summary> /// <returns>A weakly bound copy of the specified bindable.</returns> new IBindableCollection<T> GetBoundCopy(); } }
mit
C#
6b1acdfa82f77e2e9f6d629f70ae448ef7e36cf9
Replace a string.Remove with slicing.
EVAST9919/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework
osu.Framework/IO/Stores/NamespacedResourceStore.cs
osu.Framework/IO/Stores/NamespacedResourceStore.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; namespace osu.Framework.IO.Stores { public class NamespacedResourceStore<T> : ResourceStore<T> where T : class { public string Namespace; /// <summary> /// Initializes a resource store with a single store. /// </summary> /// <param name="store">The store.</param> /// <param name="ns">The namespace to add.</param> public NamespacedResourceStore(IResourceStore<T> store, string ns) : base(store) { Namespace = ns; } protected override IEnumerable<string> GetFilenames(string name) => base.GetFilenames($@"{Namespace}/{name}"); public override IEnumerable<string> GetAvailableResources() => base.GetAvailableResources() .Where(x => x.StartsWith($"{Namespace}/")) .Select(x => x[(Namespace.Length + 1)..]); } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using System.Linq; namespace osu.Framework.IO.Stores { public class NamespacedResourceStore<T> : ResourceStore<T> where T : class { public string Namespace; /// <summary> /// Initializes a resource store with a single store. /// </summary> /// <param name="store">The store.</param> /// <param name="ns">The namespace to add.</param> public NamespacedResourceStore(IResourceStore<T> store, string ns) : base(store) { Namespace = ns; } protected override IEnumerable<string> GetFilenames(string name) => base.GetFilenames($@"{Namespace}/{name}"); public override IEnumerable<string> GetAvailableResources() => base.GetAvailableResources() .Where(x => x.StartsWith($"{Namespace}/")) .Select(x => x.Remove(0, $"{Namespace}/".Length)); } }
mit
C#
e3ded9eb60a17a5b5be285c849580fb9454def73
Remove unused using
peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework
osu.Framework.Templates/templates/template-flappy/FlappyDon.Game.Tests/Visual/TestScenePipeObstacle.cs
osu.Framework.Templates/templates/template-flappy/FlappyDon.Game.Tests/Visual/TestScenePipeObstacle.cs
using FlappyDon.Game.Elements; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing; namespace FlappyDon.Game.Tests.Visual { /// <summary> /// A scene to test the layout and /// positioning and rotation of two pipe sprites. /// </summary> public class TestScenePipeObstacle : TestScene { [BackgroundDependencyLoader] private void load() { Add(new PipeObstacle { Anchor = Anchor.Centre, Origin = Anchor.Centre, }); } } }
using FlappyDon.Game.Elements; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Testing; using osuTK; namespace FlappyDon.Game.Tests.Visual { /// <summary> /// A scene to test the layout and /// positioning and rotation of two pipe sprites. /// </summary> public class TestScenePipeObstacle : TestScene { [BackgroundDependencyLoader] private void load() { Add(new PipeObstacle { Anchor = Anchor.Centre, Origin = Anchor.Centre, }); } } }
mit
C#
70fb0e2a5549191a10a61399a94fa6847a8a2535
clean using
DemgelOpenSource/DemgelRedis
Converters/GuidConverter.cs
Converters/GuidConverter.cs
using System; using Demgel.Redis.Interfaces; using StackExchange.Redis; namespace Demgel.Redis.Converters { public class GuidConverter : ITypeConverter { /// <summary> /// Used to convert Guids to a byte[] array ready to be stored in a Redis Cache /// </summary> /// <param name="prop"></param> /// <returns></returns> public RedisValue ToWrite(object prop) { var guid = prop as Guid?; return guid?.ToByteArray() ?? Guid.Empty.ToByteArray(); } public object OnRead(RedisValue value) { Guid guid; if (Guid.TryParse(value, out guid)) return guid; try { guid = new Guid((byte[])value); } catch { guid = Guid.Empty; } return guid; } } }
using System; using System.Reflection; using Demgel.Redis.Interfaces; using StackExchange.Redis; namespace Demgel.Redis.Converters { public class GuidConverter : ITypeConverter { /// <summary> /// Used to convert Guids to a byte[] array ready to be stored in a Redis Cache /// </summary> /// <param name="prop"></param> /// <returns></returns> public RedisValue ToWrite(object prop) { var guid = prop as Guid?; return guid?.ToByteArray() ?? Guid.Empty.ToByteArray(); } public object OnRead(RedisValue value) { Guid guid; if (Guid.TryParse(value, out guid)) return guid; try { guid = new Guid((byte[])value); } catch { guid = Guid.Empty; } return guid; } } }
mit
C#
1605bbdf4b8b8ea66f2f1469d41bb7c67cd70f0f
Remove unused usings
picklesdoc/pickles,picklesdoc/pickles,picklesdoc/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,dirkrombauts/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,magicmonty/pickles,blorgbeard/pickles,ludwigjossieaux/pickles,magicmonty/pickles,magicmonty/pickles,blorgbeard/pickles,dirkrombauts/pickles,dirkrombauts/pickles,blorgbeard/pickles,magicmonty/pickles,blorgbeard/pickles
src/Pickles/Pickles/FeatureParser.cs
src/Pickles/Pickles/FeatureParser.cs
#region License /* Copyright [2011] [Jeffrey Cameron] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.IO.Abstractions; using PicklesDoc.Pickles.ObjectModel; using TextReader = System.IO.TextReader; namespace PicklesDoc.Pickles { public class FeatureParser { private readonly IFileSystem fileSystem; public FeatureParser(IFileSystem fileSystem) { this.fileSystem = fileSystem; } public Feature Parse(string filename) { Feature feature = null; using (var reader = this.fileSystem.FileInfo.FromFileName(filename).OpenText()) { try { feature = this.Parse(reader); } catch (Exception e) { string message = string.Format("There was an error parsing the feature file here: {0}{1}Errormessage was:'{2}'", this.fileSystem.Path.GetFullPath(filename), Environment.NewLine, e.Message); throw new FeatureParseException(message, e); } reader.Close(); } return feature; } public Feature Parse(TextReader featureFileReader) { var gherkinParser = new Gherkin3.Parser(); Gherkin3.Ast.Feature feature = gherkinParser.Parse(featureFileReader); Feature result = new Mapper(feature.Language).MapToFeature(feature); return result; } } }
#region License /* Copyright [2011] [Jeffrey Cameron] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #endregion using System; using System.IO.Abstractions; using PicklesDoc.Pickles.ObjectModel; using PicklesDoc.Pickles.Parser; using gherkin.lexer; using TextReader = System.IO.TextReader; namespace PicklesDoc.Pickles { public class FeatureParser { private readonly IFileSystem fileSystem; public FeatureParser(IFileSystem fileSystem) { this.fileSystem = fileSystem; } public Feature Parse(string filename) { Feature feature = null; using (var reader = this.fileSystem.FileInfo.FromFileName(filename).OpenText()) { try { feature = this.Parse(reader); } catch (Exception e) { string message = string.Format("There was an error parsing the feature file here: {0}{1}Errormessage was:'{2}'", this.fileSystem.Path.GetFullPath(filename), Environment.NewLine, e.Message); throw new FeatureParseException(message, e); } reader.Close(); } return feature; } public Feature Parse(TextReader featureFileReader) { var gherkinParser = new Gherkin3.Parser(); Gherkin3.Ast.Feature feature = gherkinParser.Parse(featureFileReader); Feature result = new Mapper(feature.Language).MapToFeature(feature); return result; } } }
apache-2.0
C#
094dacdb08b677b15b525928e540cf77da260c4b
Include Data attribute in JSON Document even when null
huysentruitw/simple-json-api
src/SimpleJsonApi/Models/Document.cs
src/SimpleJsonApi/Models/Document.cs
using System.Collections.Generic; using Newtonsoft.Json; namespace SimpleJsonApi.Models { internal sealed class Document { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public IDictionary<string, string> Links { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Include)] public DocumentData Data { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<Error> Errors { get; set; } } }
using System.Collections.Generic; using Newtonsoft.Json; namespace SimpleJsonApi.Models { internal sealed class Document { [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public IDictionary<string, string> Links { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public DocumentData Data { get; set; } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public IEnumerable<Error> Errors { get; set; } } }
apache-2.0
C#
8f4bb6580a36385e6acfc74582cd8c0fd76256ff
Fix Examples.Call.CreateCall
messagebird/csharp-rest-api
Examples/Call/CreateCall.cs
Examples/Call/CreateCall.cs
using MessageBird; using MessageBird.Exceptions; using MessageBird.Objects.Voice; using System; using System.Collections.Generic; using System.Linq; namespace Examples.Call { internal class CreateCall { const string YourAccessKey = "YOUR_ACCESS_KEY"; // your access key here. internal static void Main(string[] args) { var client = Client.CreateDefault(YourAccessKey); var newCallFlow = new MessageBird.Objects.Voice.CallFlow { Title = "Forward call to 31612345678", Record = true, Steps = new List<Step> { new Step { Action = "transfer", Options = new Options { Destination = "31612345678" } } } }; var newCall = new MessageBird.Objects.Voice.Call { Source = "31644556677", Destination = "33766723144", CallFlow = newCallFlow }; try { var callResponse = client.CreateCall(newCall); var call = callResponse.Data.FirstOrDefault(); Console.WriteLine("The Call Flow Created with Id = {0}", call.Id); } catch (ErrorException e) { // Either the request fails with error descriptions from the endpoint. if (e.HasErrors) { foreach (var error in e.Errors) { Console.WriteLine("code: {0} description: '{1}' parameter: '{2}'", error.Code, error.Description, error.Parameter); } } // or fails without error information from the endpoint, in which case the reason contains a 'best effort' description. if (e.HasReason) { Console.WriteLine(e.Reason); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
using MessageBird; using MessageBird.Exceptions; using MessageBird.Objects.Voice; using System; using System.Collections.Generic; using System.Linq; namespace Examples.Call { internal class CreateCall { const string YourAccessKey = "YOUR_ACCESS_KEY"; // your access key here. internal static void Main(string[] args) { var client = Client.CreateDefault(YourAccessKey); var newCallFlow = new CallFlow { Title = "Forward call to 31612345678", Record = true, Steps = new List<Step> { new Step { Action = "transfer", Options = new Options { Destination = "31612345678" } } } }; var newCall = new Call { source = "31644556677", destination = "33766723144", callFlow = newCallFlow }; try { var callResponse = client.CreateCall(newCall); var call = callResponse.Data.FirstOrDefault(); Console.WriteLine("The Call Flow Created with Id = {0}", call.Id); } catch (ErrorException e) { // Either the request fails with error descriptions from the endpoint. if (e.HasErrors) { foreach (var error in e.Errors) { Console.WriteLine("code: {0} description: '{1}' parameter: '{2}'", error.Code, error.Description, error.Parameter); } } // or fails without error information from the endpoint, in which case the reason contains a 'best effort' description. if (e.HasReason) { Console.WriteLine(e.Reason); } } Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } }
isc
C#
6eb69a169c55c5700c1fd6798c01859f3ed81989
Remove redundant method
ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks
src/BuildingBlocks.Store.RavenDB/RavenDbStorage.cs
src/BuildingBlocks.Store.RavenDB/RavenDbStorage.cs
using System; using Raven.Client; namespace BuildingBlocks.Store.RavenDB { public class RavenDbStorage : IStorage { private readonly IDocumentStore _documentStore; private RavenDbSessionSettings _sessionSettings; public RavenDbStorage(IDocumentStore documentStore, RavenDbSessionSettings sessionSettings = null) { _documentStore = documentStore; SessionSettings = sessionSettings; } public IDocumentStore DocumentStore { get { return _documentStore; } } public RavenDbSessionSettings SessionSettings { get { return _sessionSettings; } set { _sessionSettings = value ?? new RavenDbSessionSettings(); } } public IStorageSession OpenSession() { return new RavenDbSession(_documentStore, _sessionSettings); } public void CheckConnection(int timeoutMilliseconds) { try { var task = _documentStore.AsyncDatabaseCommands.GetBuildNumberAsync(); task.Wait(timeoutMilliseconds); } catch (Exception ex) { throw new StorageConnectionFailedException(ex); } } } }
using System; using Raven.Client; namespace BuildingBlocks.Store.RavenDB { public class RavenDbStorage : IStorage { private readonly IDocumentStore _documentStore; private RavenDbSessionSettings _sessionSettings; public RavenDbStorage(IDocumentStore documentStore, RavenDbSessionSettings sessionSettings = null) { _documentStore = documentStore; SessionSettings = sessionSettings; } public IDocumentStore DocumentStore { get { return _documentStore; } } public RavenDbSessionSettings SessionSettings { get { return _sessionSettings; } set { _sessionSettings = value ?? new RavenDbSessionSettings(); } } public void CheckConnection() { } public IStorageSession OpenSession() { return new RavenDbSession(_documentStore, _sessionSettings); } public void CheckConnection(int timeoutMilliseconds) { try { var task = _documentStore.AsyncDatabaseCommands.GetBuildNumberAsync(); task.Wait(timeoutMilliseconds); } catch (Exception ex) { throw new StorageConnectionFailedException(ex); } } } }
apache-2.0
C#
59aa01c8b4dd5aa969cb4f0b491e5152b6b4e0da
Update OriginalException xmldoc
RossLieberman/NEST,elastic/elasticsearch-net,elastic/elasticsearch-net,KodrAus/elasticsearch-net,TheFireCookie/elasticsearch-net,adam-mccoy/elasticsearch-net,adam-mccoy/elasticsearch-net,CSGOpenSource/elasticsearch-net,UdiBen/elasticsearch-net,cstlaurent/elasticsearch-net,adam-mccoy/elasticsearch-net,RossLieberman/NEST,UdiBen/elasticsearch-net,UdiBen/elasticsearch-net,azubanov/elasticsearch-net,azubanov/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,cstlaurent/elasticsearch-net,RossLieberman/NEST,TheFireCookie/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,KodrAus/elasticsearch-net,azubanov/elasticsearch-net,cstlaurent/elasticsearch-net
src/Elasticsearch.Net/Responses/IApiCallDetails.cs
src/Elasticsearch.Net/Responses/IApiCallDetails.cs
using System; using System.Collections.Generic; using System.Diagnostics; namespace Elasticsearch.Net { public interface IApiCallDetails { /// <summary> /// The response status code is in the 200 range or is in the allowed list of status codes set on the request. /// </summary> bool Success { get; } /// <summary> /// If Success is false this will hold the original exception. /// This will be the orginating CLR exception in most cases. /// </summary> Exception OriginalException { get; } /// <summary> /// The error returned by Elasticsearch /// </summary> ServerError ServerError { get; } /// <summary> /// The HTTP method used by the request /// </summary> HttpMethod HttpMethod { get; } /// <summary> /// The url as requested /// </summary> Uri Uri { get; } /// <summary> /// The HTTP status code as returned by Elasticsearch /// </summary> int? HttpStatusCode { get; } /// <summary> /// The raw byte response, only set when IncludeRawResponse() is set on Connection configuration /// </summary> [DebuggerDisplay("{ResponseBodyInBytes != null ? System.Text.Encoding.UTF8.GetString(ResponseBodyInBytes) : null,nq}")] byte[] ResponseBodyInBytes { get; } [DebuggerDisplay("{RequestBodyInBytes != null ? System.Text.Encoding.UTF8.GetString(RequestBodyInBytes) : null,nq}")] byte[] RequestBodyInBytes { get; } List<Audit> AuditTrail { get; } } }
using System; using System.Collections.Generic; using System.Diagnostics; namespace Elasticsearch.Net { public interface IApiCallDetails { /// <summary> /// The response status code is in the 200 range or is in the allowed list of status codes set on the request. /// </summary> bool Success { get; } //TODO revalidate this summary when we refactor exceptions /// <summary> /// If Success is false this will hold the original exception. /// Can be a CLR exception or a mapped server side exception (ElasticsearchServerException) /// </summary> Exception OriginalException { get; } /// <summary> /// The error returned by Elasticsearch /// </summary> ServerError ServerError { get; } /// <summary> /// The HTTP method used by the request /// </summary> HttpMethod HttpMethod { get; } /// <summary> /// The url as requested /// </summary> Uri Uri { get; } /// <summary> /// The HTTP status code as returned by Elasticsearch /// </summary> int? HttpStatusCode { get; } /// <summary> /// The raw byte response, only set when IncludeRawResponse() is set on Connection configuration /// </summary> [DebuggerDisplay("{ResponseBodyInBytes != null ? System.Text.Encoding.UTF8.GetString(ResponseBodyInBytes) : null,nq}")] byte[] ResponseBodyInBytes { get; } [DebuggerDisplay("{RequestBodyInBytes != null ? System.Text.Encoding.UTF8.GetString(RequestBodyInBytes) : null,nq}")] byte[] RequestBodyInBytes { get; } List<Audit> AuditTrail { get; } } }
apache-2.0
C#
539e01799d4f823b1597788344cd8a1a64d8eaae
Fix merge issue on property name
lukencode/FluentEmail,lukencode/FluentEmail
src/Senders/FluentEmail.Mailtrap/MailtrapSender.cs
src/Senders/FluentEmail.Mailtrap/MailtrapSender.cs
using System; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; using FluentEmail.Core; using FluentEmail.Core.Interfaces; using FluentEmail.Core.Models; using FluentEmail.Smtp; namespace FluentEmail.Mailtrap { /// <summary> /// Send emails to a Mailtrap.io inbox /// </summary> public class MailtrapSender : ISender, IDisposable { private readonly SmtpClient _smtpClient; private static readonly int[] ValidPorts = {25, 465, 2525}; /// <summary> /// Creates a sender that uses the given Mailtrap credentials, but does not dispose it. /// </summary> /// <param name="userName">Username of your mailtrap.io SMTP inbox</param> /// <param name="password">Password of your mailtrap.io SMTP inbox</param> /// <param name="host">Host address for the Mailtrap.io SMTP inbox</param> /// <param name="port">Port for the Mailtrap.io SMTP server. Accepted values are 25, 465 or 2525.</param> public MailtrapSender(string userName, string password, string host = "smtp.mailtrap.io", int? port = null) { if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentException("Mailtrap UserName needs to be supplied", nameof(userName)); if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Mailtrap Password needs to be supplied", nameof(password)); if (port.HasValue && !ValidPorts.Contains(port.Value)) throw new ArgumentException("Mailtrap Port needs to be either 25, 465 or 2525", nameof(port)); _smtpClient = new SmtpClient(host, port.GetValueOrDefault(2525)) { Credentials = new NetworkCredential(userName, password), EnableSsl = true }; } public void Dispose() => _smtpClient?.Dispose(); public SendResponse Send(IFluentEmail email, CancellationToken? token = null) { var smtpSender = new SmtpSender(_smtpClient); return smtpSender.Send(email, token); } public Task<SendResponse> SendAsync(IFluentEmail email, CancellationToken? token = null) { var smtpSender = new SmtpSender(_smtpClient); return smtpSender.SendAsync(email, token); } } }
using System; using System.Linq; using System.Net; using System.Net.Mail; using System.Threading; using System.Threading.Tasks; using FluentEmail.Core; using FluentEmail.Core.Interfaces; using FluentEmail.Core.Models; using FluentEmail.Smtp; namespace FluentEmail.Mailtrap { /// <summary> /// Send emails to a Mailtrap.io inbox /// </summary> public class MailtrapSender : ISender, IDisposable { private readonly SmtpClient _smtpClient; private static readonly int[] ValidPorts = {25, 465, 2525}; /// <summary> /// Creates a sender that uses the given Mailtrap credentials, but does not dispose it. /// </summary> /// <param name="userName">Username of your mailtrap.io SMTP inbox</param> /// <param name="password">Password of your mailtrap.io SMTP inbox</param> /// <param name="host">Host address for the Mailtrap.io SMTP inbox</param> /// <param name="port">Port for the Mailtrap.io SMTP server. Accepted values are 25, 465 or 2525.</param> public MailtrapSender(string userName, string password, string host = "smtp.mailtrap.io", int? port = null) { if (string.IsNullOrWhiteSpace(userName)) throw new ArgumentException("Mailtrap UserName needs to be supplied", nameof(userName)); if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Mailtrap Password needs to be supplied", nameof(password)); if (port.HasValue && !ValidPorts.Contains(port.Value)) throw new ArgumentException("Mailtrap Port needs to be either 25, 465 or 2525", nameof(port)); _smtpClient = new SmtpClient(host, port.GetValueOrDefault(2525)) { Credentials = new NetworkCredential(userName, password), EnableSsl = true }; } public void Dispose() => this.smtpClient.Dispose(); public SendResponse Send(IFluentEmail email, CancellationToken? token = null) { var smtpSender = new SmtpSender(_smtpClient); return smtpSender.Send(email, token); } public Task<SendResponse> SendAsync(IFluentEmail email, CancellationToken? token = null) { var smtpSender = new SmtpSender(_smtpClient); return smtpSender.SendAsync(email, token); } } }
mit
C#
71891ffc98113413604da5eaa22e7470d50937e4
use WriteVerbose instead pipeline for texts
thoemmi/7Zip4Powershell
7Zip4Powershell/ThreadedCmdlet.cs
7Zip4Powershell/ThreadedCmdlet.cs
using System; using System.Collections.Concurrent; using System.Management.Automation; using System.Threading; using SevenZip; namespace SevenZip4PowerShell { public abstract class ThreadedCmdlet : PSCmdlet { protected abstract CmdletWorker CreateWorker(); private Thread _thread; protected override void EndProcessing() { SevenZipBase.SetLibraryPath(Utils.SevenZipLibraryPath); var queue = new BlockingCollection<object>(); var worker = CreateWorker(); worker.Queue = queue; _thread = StartBackgroundThread(worker); foreach (var o in queue.GetConsumingEnumerable()) { var record = o as ProgressRecord; var errorRecord = o as ErrorRecord; if (record != null) { WriteProgress(record); } else if (errorRecord != null) { WriteError(errorRecord); } else if (o is string) { WriteVerbose((string) o); } else { WriteObject(o); } } _thread.Join(); } private static Thread StartBackgroundThread(CmdletWorker worker) { var thread = new Thread(() => { try { worker.Execute(); } catch (Exception ex) { worker.Queue.Add(new ErrorRecord(ex, "err01", ErrorCategory.NotSpecified, worker)); } finally { worker.Queue.CompleteAdding(); } }) { IsBackground = true }; thread.Start(); return thread; } protected override void StopProcessing() { _thread?.Abort(); } } public abstract class CmdletWorker { public BlockingCollection<object> Queue { get; set; } protected void Write(string text) { Queue.Add(text); } protected void WriteProgress(ProgressRecord progressRecord) { Queue.Add(progressRecord); } public abstract void Execute(); } }
using System; using System.Collections.Concurrent; using System.Management.Automation; using System.Threading; using SevenZip; namespace SevenZip4PowerShell { public abstract class ThreadedCmdlet : PSCmdlet { protected abstract CmdletWorker CreateWorker(); private Thread _thread; protected override void EndProcessing() { SevenZipBase.SetLibraryPath(Utils.SevenZipLibraryPath); var queue = new BlockingCollection<object>(); var worker = CreateWorker(); worker.Queue = queue; _thread = StartBackgroundThread(worker); foreach (var o in queue.GetConsumingEnumerable()) { var record = o as ProgressRecord; var errorRecord = o as ErrorRecord; if (record != null) { WriteProgress(record); } else if (errorRecord != null) { WriteError(errorRecord); } else { WriteObject(o); } } _thread.Join(); } private static Thread StartBackgroundThread(CmdletWorker worker) { var thread = new Thread(() => { try { worker.Execute(); } catch (Exception ex) { worker.Queue.Add(new ErrorRecord(ex, "err01", ErrorCategory.NotSpecified, worker)); } finally { worker.Queue.CompleteAdding(); } }) { IsBackground = true }; thread.Start(); return thread; } protected override void StopProcessing() { _thread?.Abort(); } } public abstract class CmdletWorker { public BlockingCollection<object> Queue { get; set; } protected void Write(string text) { Queue.Add(text); } protected void WriteProgress(ProgressRecord progressRecord) { Queue.Add(progressRecord); } public abstract void Execute(); } }
lgpl-2.1
C#
93b02960f5e7eb252520255a42484bd9d34be003
Test simplified
ravibpatel/CrashReporter.NET
CrashReporterTest/Program.cs
CrashReporterTest/Program.cs
using System; using System.Globalization; using System.Windows.Forms; using CrashReporterDotNET; namespace CrashReporterTest { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.ThreadException += (sender, args) => SendCrashReport(args.Exception); AppDomain.CurrentDomain.UnhandledException += (sender, args) => { SendCrashReport((Exception) args.ExceptionObject); Environment.Exit(0); }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } public static void SendCrashReport(Exception exception, string developerMessage = "") { var reportCrash = new ReportCrash { AnalyzeWithDoctorDump = true, DeveloperMessage = developerMessage, ToEmail = "Email where you want to receive crash reports.", DoctorDumpSettings = new DoctorDumpSettings { OpenReportInBrowser = true }, }; reportCrash.Send(exception); } } }
using System; using System.Globalization; using System.Windows.Forms; using CrashReporterDotNET; namespace CrashReporterTest { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.ThreadException += (sender, args) => SendCrashReport(args.Exception); AppDomain.CurrentDomain.UnhandledException += (sender, args) => { SendCrashReport((Exception) args.ExceptionObject); Environment.Exit(0); }; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormMain()); } public static void SendCrashReport(Exception exception, string developerMessage = "") { var reportCrash = new ReportCrash { AnalyzeWithDoctorDump = true, DeveloperMessage = developerMessage, ToEmail = "Email where you want to receive crash reports.", DoctorDumpSettings = new DoctorDumpSettings { ApplicationID = new Guid("Application ID you received from DrDump.com"), OpenReportInBrowser = true }, }; reportCrash.Send(exception); } } }
mit
C#
85b56f7ca6f28f19f49e4c356855b1698c521d4c
Use Activator.CreateInstance
JohanLarsson/Gu.Inject
Gu.Inject/Internals/Ctor.cs
Gu.Inject/Internals/Ctor.cs
namespace Gu.Inject { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; internal static class Ctor { private static readonly ConcurrentDictionary<Type, IFactory> Ctors = new ConcurrentDictionary<Type, IFactory>(); internal static IFactory GetFactory(Type type) { return Ctors.GetOrAdd(type, Create); } private static IFactory Create(Type type) { var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (ctors.Length > 1) { var message = $"Type {type.PrettyName()} has more than one constructor.\r\n" + "Add a binding specifying which constructor to use."; throw new ResolveException(type, message); } var ctor = ctors[0]; var parameters = ctor.GetParameters() .Select(x => x.ParameterType) .ToArray(); if (ctor.IsPublic) { return new CreateInstanceFactory(type, parameters); } return new Factory(ctor, parameters); } internal class Factory : IFactory { private readonly ConstructorInfo ctor; public Factory(ConstructorInfo ctor, IReadOnlyList<Type> parameterTypes) { this.ctor = ctor; this.ParameterTypes = parameterTypes; } public IReadOnlyList<Type> ParameterTypes { get; } public object Create(object[] args) { return this.ctor.Invoke(args); } } internal class CreateInstanceFactory : IFactory { private readonly Type type; public CreateInstanceFactory(Type type, IReadOnlyList<Type> parameterTypes) { this.type = type; this.ParameterTypes = parameterTypes; } public IReadOnlyList<Type> ParameterTypes { get; } public object Create(object[] args) { return Activator.CreateInstance(this.type, args); } } } }
namespace Gu.Inject { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; internal static class Ctor { private static readonly ConcurrentDictionary<Type, Factory> Ctors = new ConcurrentDictionary<Type, Factory>(); internal static Factory GetFactory(Type type) { return Ctors.GetOrAdd(type, Create); } private static Factory Create(Type type) { var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (ctors.Length > 1) { var message = $"Type {type.PrettyName()} has more than one constructor.\r\n" + "Add a binding specifying which constructor to use."; throw new ResolveException(type, message); } var ctor = ctors[0]; return new Factory(ctor, ctor.GetParameters().Select(x => x.ParameterType).ToArray()); } internal class Factory : IFactory { private readonly ConstructorInfo ctor; public Factory(ConstructorInfo ctor, IReadOnlyList<Type> parameterTypes) { this.ctor = ctor; this.ParameterTypes = parameterTypes; } public IReadOnlyList<Type> ParameterTypes { get; } public object Create(object[] args) { return this.ctor.Invoke(args); } } } }
mit
C#
4462c4a26c945ac6f6a6c3bbaf3b516db4aef61b
tweak CSL syntax
stwalkerster/eyeinthesky,stwalkerster/eyeinthesky,stwalkerster/eyeinthesky
EyeInTheSky/StalkNodes/XorNode.cs
EyeInTheSky/StalkNodes/XorNode.cs
using System; using System.Xml; namespace EyeInTheSky.StalkNodes { class XorNode : DoubleChildLogicalNode { #region Overrides of StalkNode public override bool match(RecentChange rc) { return (LeftChildNode.match(rc) ^ RightChildNode.match(rc)); } public static new StalkNode newFromXmlFragment(XmlNode xmlNode) { XorNode s = new XorNode(); s.LeftChildNode = StalkNode.newFromXmlFragment(xmlNode.ChildNodes[0]); s.RightChildNode = StalkNode.newFromXmlFragment(xmlNode.ChildNodes[1]); return s; } public override XmlElement toXmlFragment(XmlDocument doc, string xmlns) { XmlElement e = doc.CreateElement("xor", xmlns); e.AppendChild(LeftChildNode.toXmlFragment(doc, xmlns)); e.AppendChild(RightChildNode.toXmlFragment(doc, xmlns)); return e; } public override string ToString() { return "(^:" + LeftChildNode + RightChildNode + ")"; } #endregion } }
using System; using System.Xml; namespace EyeInTheSky.StalkNodes { class XorNode : DoubleChildLogicalNode { #region Overrides of StalkNode public override bool match(RecentChange rc) { return (LeftChildNode.match(rc) ^ RightChildNode.match(rc)); } public static new StalkNode newFromXmlFragment(XmlNode xmlNode) { XorNode s = new XorNode(); s.LeftChildNode = StalkNode.newFromXmlFragment(xmlNode.ChildNodes[0]); s.RightChildNode = StalkNode.newFromXmlFragment(xmlNode.ChildNodes[1]); return s; } public override XmlElement toXmlFragment(XmlDocument doc, string xmlns) { XmlElement e = doc.CreateElement("xor", xmlns); e.AppendChild(LeftChildNode.toXmlFragment(doc, xmlns)); e.AppendChild(RightChildNode.toXmlFragment(doc, xmlns)); return e; } public override string ToString() { return "(" + LeftChildNode + "^" + RightChildNode + ")"; } #endregion } }
mit
C#
03505669007494c6591095f852ef534e0f0ee789
Add test CreateNoteTest.WithTags
orodriguez/FTF,orodriguez/FTF,orodriguez/FTF
FTF.Tests.XUnit/CreateNoteTest.cs
FTF.Tests.XUnit/CreateNoteTest.cs
using System; using System.Linq; using FTF.Api; using FTF.IoC.SimpleInjector; using Xunit; namespace FTF.Tests.XUnit { public class CreateNoteTest : IDisposable { private readonly IApplication _app; public CreateNoteTest() { _app = new ApplicationFactory() .Make(getCurrentDate: () => new DateTime(2016, 2, 20)); _app.AuthService.SignUp("orodriguez"); _app.AuthService.SignIn("orodriguez"); } public void Dispose() => _app.Dispose(); [Fact] public void SimpleNote() { var noteId = _app.Notes.Create("I was born"); var note = _app.Notes.Retrieve(noteId); Assert.Equal("I was born", note.Text); Assert.Equal(new DateTime(2016, 2, 20), note.CreationDate); Assert.Equal("orodriguez", note.UserName); } [Fact] public void WithTags() { var noteId = _app.Notes.Create("#Buy cheese at #SuperMarket"); var note = _app.Notes.Retrieve(noteId); Assert.Equal(new[] { "Buy", "SuperMarket" }, note.Tags.Select(t => t.Name)); } } }
using System; using FTF.Api; using FTF.IoC.SimpleInjector; using Xunit; namespace FTF.Tests.XUnit { public class CreateNoteTest : IDisposable { private readonly IApplication _app; public CreateNoteTest() { _app = new ApplicationFactory() .Make(getCurrentDate: () => new DateTime(2016, 2, 20)); _app.AuthService.SignUp("orodriguez"); _app.AuthService.SignIn("orodriguez"); } public void Dispose() => _app.Dispose(); [Fact] public void SimpleNote() { var noteId = _app.Notes.Create("I was born"); var note = _app.Notes.Retrieve(noteId); Assert.Equal("I was born", note.Text); Assert.Equal(new DateTime(2016, 2, 20), note.CreationDate); Assert.Equal("orodriguez", note.UserName); } } }
mit
C#
f84ffbec8d00f845fbaffd3097e631d3c22863b4
Fix potential infinite loop in SkipWhitespace
DbUp/DbUp
src/dbup-mysql/MySqlCommandReader.cs
src/dbup-mysql/MySqlCommandReader.cs
using System; using System.Text; using DbUp.Support; namespace DbUp.MySql { /// <summary> /// Reads MySQL commands from an underlying text stream. Supports DELIMITED .. statement /// </summary> public class MySqlCommandReader : SqlCommandReader { const string DelimiterKeyword = "DELIMITER"; /// <summary> /// Creates an instance of MySqlCommandReader /// </summary> public MySqlCommandReader(string sqlText) : base(sqlText, ";", delimiterRequiresWhitespace: false) { } /// <summary> /// Hook to support custom statements /// </summary> protected override bool IsCustomStatement => TryPeek(DelimiterKeyword.Length - 1, out var statement) && string.Equals(DelimiterKeyword, CurrentChar + statement, StringComparison.OrdinalIgnoreCase); /// <summary> /// Read a custom statement /// </summary> protected override void ReadCustomStatement() { // Move past Delimiter keyword var count = DelimiterKeyword.Length + 1; Read(new char[count], 0, count); SkipWhitespace(); // Read until we hit the end of line. var delimiter = new StringBuilder(); do { delimiter.Append(CurrentChar); if (Read() == FailedRead) { break; } } while (!IsEndOfLine && !IsWhiteSpace); Delimiter = delimiter.ToString(); } void SkipWhitespace() { int result; do { result = Read(); } while (result != FailedRead && char.IsWhiteSpace(CurrentChar)); } } }
using System; using System.Text; using DbUp.Support; namespace DbUp.MySql { /// <summary> /// Reads MySQL commands from an underlying text stream. Supports DELIMITED .. statement /// </summary> public class MySqlCommandReader : SqlCommandReader { const string DelimiterKeyword = "DELIMITER"; /// <summary> /// Creates an instance of MySqlCommandReader /// </summary> public MySqlCommandReader(string sqlText) : base(sqlText, ";", delimiterRequiresWhitespace: false) { } /// <summary> /// Hook to support custom statements /// </summary> protected override bool IsCustomStatement => TryPeek(DelimiterKeyword.Length - 1, out var statement) && string.Equals(DelimiterKeyword, CurrentChar + statement, StringComparison.OrdinalIgnoreCase); /// <summary> /// Read a custom statement /// </summary> protected override void ReadCustomStatement() { // Move past Delimiter keyword var count = DelimiterKeyword.Length + 1; Read(new char[count], 0, count); SkipWhitespace(); // Read until we hit the end of line. var delimiter = new StringBuilder(); do { delimiter.Append(CurrentChar); if (Read() == FailedRead) { break; } } while (!IsEndOfLine && !IsWhiteSpace); Delimiter = delimiter.ToString(); } void SkipWhitespace() { while (char.IsWhiteSpace(CurrentChar)) { Read(); } } } }
mit
C#
76b3cb70327f7f7d80c5a5d3a627b5d8d79b9059
Fix immediate recreation via LifetimeStart/LifetimeEnd requests
ppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,ppy/osu-framework,ZLima12/osu-framework
osu.Framework/Graphics/Containers/DelayedLoadUnloadWrapper.cs
osu.Framework/Graphics/Containers/DelayedLoadUnloadWrapper.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using osu.Framework.Threading; namespace osu.Framework.Graphics.Containers { public class DelayedLoadUnloadWrapper : DelayedLoadWrapper { private readonly Func<Drawable> createContentFunction; private readonly double timeBeforeUnload; public DelayedLoadUnloadWrapper(Func<Drawable> createContentFunction, double timeBeforeLoad = 500, double timeBeforeUnload = 1000) : base(createContentFunction(), timeBeforeLoad) { this.createContentFunction = createContentFunction; this.timeBeforeUnload = timeBeforeUnload; } private double timeHidden; private ScheduledDelegate unloadSchedule; protected bool ShouldUnloadContent => timeBeforeUnload == 0 || timeHidden > timeBeforeUnload; public override double LifetimeStart { get => base.Content?.LifetimeStart ?? double.MinValue; set => throw new NotSupportedException(); } public override double LifetimeEnd { get => base.Content?.LifetimeEnd ?? double.MaxValue; set => throw new NotSupportedException(); } public override Drawable Content => base.Content ?? (Content = createContentFunction()); protected override void EndDelayedLoad(Drawable content) { base.EndDelayedLoad(content); Debug.Assert(unloadSchedule == null); unloadSchedule = OptimisingContainer?.ScheduleCheckAction(checkForUnload); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); unloadSchedule?.Cancel(); unloadSchedule = null; } private void checkForUnload() { // This code can be expensive, so only run if we haven't yet loaded. if (IsIntersecting) timeHidden = 0; else timeHidden += Time.Elapsed; if (ShouldUnloadContent) { ClearInternal(); Content = null; timeHidden = 0; unloadSchedule?.Cancel(); unloadSchedule = null; Unload(); } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Diagnostics; using osu.Framework.Threading; namespace osu.Framework.Graphics.Containers { public class DelayedLoadUnloadWrapper : DelayedLoadWrapper { private readonly Func<Drawable> createContentFunction; private readonly double timeBeforeUnload; public DelayedLoadUnloadWrapper(Func<Drawable> createContentFunction, double timeBeforeLoad = 500, double timeBeforeUnload = 1000) : base(createContentFunction(), timeBeforeLoad) { this.createContentFunction = createContentFunction; this.timeBeforeUnload = timeBeforeUnload; } private double timeHidden; private ScheduledDelegate unloadSchedule; protected bool ShouldUnloadContent => timeBeforeUnload == 0 || timeHidden > timeBeforeUnload; public override Drawable Content => base.Content ?? (Content = createContentFunction()); protected override void EndDelayedLoad(Drawable content) { base.EndDelayedLoad(content); Debug.Assert(unloadSchedule == null); unloadSchedule = OptimisingContainer?.ScheduleCheckAction(checkForUnload); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); unloadSchedule?.Cancel(); unloadSchedule = null; } private void checkForUnload() { // This code can be expensive, so only run if we haven't yet loaded. if (IsIntersecting) timeHidden = 0; else timeHidden += Time.Elapsed; if (ShouldUnloadContent) { ClearInternal(); Content = null; timeHidden = 0; unloadSchedule?.Cancel(); unloadSchedule = null; Unload(); } } } }
mit
C#
23d792615d303aecaa0993bdf819f9b0e3619bea
resolve warning
mgj/fetcher,mgj/fetcher
Fetcher.Core.Tests/Services/Mocks/FetcherServiceMock.cs
Fetcher.Core.Tests/Services/Mocks/FetcherServiceMock.cs
using artm.Fetcher.Core.Models; using artm.Fetcher.Core.Services; using Moq; using System; namespace artm.Fetcher.Core.Tests.Services.Mocks { public class FetcherServiceMock : FetcherService { public FetcherServiceMock() :base(null, new FetcherRepositoryServiceMock()) { SetWebserviceDummy(); } public FetcherServiceMock(IFetcherRepositoryService repository) : base(null, repository) { SetWebserviceDummy(); } public FetcherServiceMock(Mock<IFetcherWebService> web) : base(web.Object, new FetcherRepositoryServiceMock()) { WebServiceMock = web; base.Webservice = WebServiceMock.Object; } private void SetWebserviceDummy() { WebServiceMock = new Mock<IFetcherWebService>(); WebServiceMock.Setup(x => x.DoPlatformWebRequest(It.IsAny<Uri>())).Returns(() => new FetcherWebResponse() { IsSuccess = true, Body = "myBody" }); base.Webservice = WebServiceMock.Object; } public Mock<IFetcherWebService> WebServiceMock { get; private set; } } }
using artm.Fetcher.Core.Models; using artm.Fetcher.Core.Services; using Moq; using System; namespace artm.Fetcher.Core.Tests.Services.Mocks { public class FetcherServiceMock : FetcherService { private Mock<IFetcherWebService> web; public FetcherServiceMock() :base(null, new FetcherRepositoryServiceMock()) { SetWebserviceDummy(); } public FetcherServiceMock(IFetcherRepositoryService repository) : base(null, repository) { SetWebserviceDummy(); } public FetcherServiceMock(Mock<IFetcherWebService> web) : base(web.Object, new FetcherRepositoryServiceMock()) { WebServiceMock = web; base.Webservice = WebServiceMock.Object; } private void SetWebserviceDummy() { WebServiceMock = new Mock<IFetcherWebService>(); WebServiceMock.Setup(x => x.DoPlatformWebRequest(It.IsAny<Uri>())).Returns(() => new FetcherWebResponse() { IsSuccess = true, Body = "myBody" }); base.Webservice = WebServiceMock.Object; } public Mock<IFetcherWebService> WebServiceMock { get; private set; } } }
apache-2.0
C#
d9f7ef9dc7ab196c1c754281823d90d613a9ebe2
Implement fake tag parser to test integration
orodriguez/FTF,orodriguez/FTF,orodriguez/FTF
FTF.Core/Notes/CreateNote.cs
FTF.Core/Notes/CreateNote.cs
using System; using System.Collections.Generic; namespace FTF.Core.Notes { public class CreateNote { private readonly Func<int> _generateId; private readonly Func<DateTime> _getCurrentDate; private readonly Action<Note> _saveNote; private readonly Action _saveChanges; public CreateNote(Func<int> generateId, Func<DateTime> getCurrentDate, Action<Note> saveNote, Action saveChanges) { _generateId = generateId; _getCurrentDate = getCurrentDate; _saveNote = saveNote; _saveChanges = saveChanges; } public void Create(int id, string text) { _saveNote(new Note { Id = _generateId(), Text = text, CreationDate = _getCurrentDate(), Tags = ParseTags(text) }); _saveChanges(); } private ICollection<Tag> ParseTags(string text) => new List<Tag> { new Tag { Name = "Buy"} }; } }
using System; namespace FTF.Core.Notes { public class CreateNote { private readonly Func<int> _generateId; private readonly Func<DateTime> _getCurrentDate; private readonly Action<Note> _saveNote; private readonly Action _saveChanges; public CreateNote(Func<int> generateId, Func<DateTime> getCurrentDate, Action<Note> saveNote, Action saveChanges) { _generateId = generateId; _getCurrentDate = getCurrentDate; _saveNote = saveNote; _saveChanges = saveChanges; } public void Create(int id, string text) { _saveNote(new Note { Id = _generateId(), Text = text, CreationDate = _getCurrentDate() }); _saveChanges(); } } }
mit
C#
c8b0a5434b6f88b7cabad8ed2d6250c7c3c7a430
Fix formating in the And instruction.
joshpeterson/mos,joshpeterson/mos,joshpeterson/mos
Mos6510/Instructions/And.cs
Mos6510/Instructions/And.cs
using System.Collections.Generic; namespace Mos6510.Instructions { public class And : Instruction { private static Dictionary<AddressingMode, int> numberOfCycles = new Dictionary<AddressingMode, int> { { AddressingMode.Immediate, 2 }, { AddressingMode.Absolute, 4 }, { AddressingMode.AbsoluteX, 4 }, { AddressingMode.AbsoluteY, 4 }, { AddressingMode.Zeropage, 3 }, { AddressingMode.ZeropageX, 4 }, { AddressingMode.ZeropageY, 4 }, { AddressingMode.IndexedIndirectX, 6 }, { AddressingMode.IndexedIndirectY, 5 }, }; public virtual void Execute(ProgrammingModel model, Memory memory, byte argument) { var accumulator = model.GetRegister(RegisterName.A); accumulator.SetValue((byte)accumulator.GetValue() & argument); } public virtual int CyclesFor(AddressingMode mode) { return numberOfCycles[mode]; } } }
using System.Collections.Generic; namespace Mos6510.Instructions { public class And : Instruction { private static Dictionary<AddressingMode, int> numberOfCycles = new Dictionary<AddressingMode, int> { { AddressingMode.Immediate, 2 }, { AddressingMode.Absolute, 4 }, { AddressingMode.AbsoluteX, 4 }, { AddressingMode.AbsoluteY, 4 }, { AddressingMode.Zeropage, 3 }, { AddressingMode.ZeropageX, 4 }, { AddressingMode.ZeropageY, 4 }, { AddressingMode.IndexedIndirectX, 6 }, { AddressingMode.IndexedIndirectY, 5 }, }; public virtual void Execute(ProgrammingModel model, Memory memory, byte argument) { var accumulator = model.GetRegister(RegisterName.A); accumulator.SetValue((byte)accumulator.GetValue() & argument); } public virtual int CyclesFor(AddressingMode mode) { return numberOfCycles[mode]; } } }
mit
C#
10f2807b58758b438b44e14ffd32eb911e0bbe45
Increment to 1.0.3.0 for future additions/changes
axomic/openasset-rest-cs
OpenAsset.RestClient.Library/Properties/AssemblyInfo.cs
OpenAsset.RestClient.Library/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("OpenAsset.RestClient.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Axomic Ltd")] [assembly: AssemblyProduct("OpenAsset RestClient Library")] [assembly: AssemblyCopyright("Copyright © Axomic Ltd 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("137fd3b7-9fa8-4003-a734-bb82cf0e2586")] // 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.3.0")] [assembly: AssemblyFileVersion("1.0.3.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("OpenAsset.RestClient.Library")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Axomic Ltd")] [assembly: AssemblyProduct("OpenAsset RestClient Library")] [assembly: AssemblyCopyright("Copyright © Axomic Ltd 2013-2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("137fd3b7-9fa8-4003-a734-bb82cf0e2586")] // 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.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
mit
C#
a9836ebec0985865784eef865c4105356ae0097b
Add documentation to ColorHexConverter.cs
exodrifter/unity-raconteur,dpek/unity-raconteur
Assets/Raconteur/Util/ColorHexConverter.cs
Assets/Raconteur/Util/ColorHexConverter.cs
using UnityEngine; namespace DPek.Raconteur.Util { /// <summary> /// A utility for converting hex strings such as #F93 to colors. /// </summary> public class ColorHexConverter { private ColorHexConverter() { // Nothing to do } /// <summary> /// Converts a single hex character to the corresponding int value. /// </summary> /// <returns> /// The number value of the hex character. /// </returns> /// <param name="ch"> /// The character to get the hex value of. /// </param> private static int FromHex(char c) { c = char.ToLower(c); // Check if the character is a letter if(96 < c && c < 103) { return c - 86; } // Check if the character is a number else if (47 < c && c < 58) { return c - 48; } // Invalid character var msg = "\'" + c + "\' is not a hex character."; throw new System.ArgumentException(msg); } /// <summary> /// Converts a hex string to a number. /// </summary> /// <returns> /// The number value of the hex string. /// </returns> /// <param name="str"> /// The string to get the hex value of. /// </param> private static int FromHex(string str) { int totalVal = 0; for(int i = str.Length-1; i >= 0; --i) { totalVal *= 16; totalVal += FromHex(str[i]); } return totalVal; } /// <summary> /// Parses a hex string in the format #RGB or RGB. /// /// The hex string (when considered without the '#' character) may be /// any multiple of 3. For example, if the hex string is #FF9930, the /// format is assumed to be #RRGGBB or RRGGBB. /// </summary> /// <returns> /// The color as defined by the hex string. /// </returns> /// <param name="str"> /// The hex string that defines the color. /// </param> public static Color FromRGB(string str) { if(str[0] == '#') { str = str.Substring(1); } // Figure out the size of each color in the #RGB format int size = str.Length / 3; float maxVal = Mathf.Pow(16, size); // Calculate RGB values float r, g, b = 0; r = FromHex(str.Substring(0, size)) / maxVal; g = FromHex(str.Substring(size, size)) / maxVal; b = FromHex(str.Substring(size*2, size)) / maxVal; return new Color(r, g, b); } } }
using UnityEngine; namespace DPek.Raconteur.Util { public class ColorHexConverter { private ColorHexConverter() { // Nothing to do } // Converts a single hex character to an int value private static int FromHex(char c) { c = char.ToLower(c); // Check if the character is a letter if(96 < c && c < 103) { return c - 86; } // Check if the character is a number else if (47 < c && c < 58) { return c - 48; } // Invalid character var msg = "\'" + c + "\' is not a hex character."; throw new System.ArgumentException(msg); } private static int FromHex(string str) { int totalVal = 0; for(int i = str.Length-1; i >= 0; --i) { totalVal *= 16; totalVal += FromHex(str[i]); } return totalVal; } public static Color FromRGB(string str) { if(str[0] == '#') { str = str.Substring(1); } float r, g, b = 0; // Figure out the size of each color in the #RGB format int size = str.Length / 3; float maxVal = Mathf.Pow(16,size); r = FromHex (str.Substring(0,size)) / maxVal; g = FromHex (str.Substring(size,size)) / maxVal; b = FromHex (str.Substring(size*2,size)) / maxVal; return new Color(r, g, b); } } }
bsd-3-clause
C#
03d26ec4fd5832c731c30a009688a739fe8a6c8a
Add disconnect at the end of the mission.
DragonEyes7/ConcoursUBI17,DragonEyes7/ConcoursUBI17
Proto/Assets/Scripts/Exit.cs
Proto/Assets/Scripts/Exit.cs
using UnityEngine; public class Exit : Interactive { GameManager m_GameManager; GameObject m_Player; PhotonView m_PhotonView; protected new void Start () { base.Start(); m_PhotonView = GetComponent<PhotonView>(); m_GameManager = FindObjectOfType<GameManager>(); } void OnTriggerEnter(Collider other) { Action act = other.GetComponent<Action>(); if (act) { if(act.enabled) { m_Player = other.gameObject; m_HUD.ShowActionPrompt("Exit mission"); act.SetInteract(true); act.SetInteractionObject(this); } } } void OnTriggerExit(Collider other) { Action act = other.GetComponent<Action>(); if (act) { if(act.enabled) { m_HUD.HideActionPrompt(); act.SetInteract(false); } } } public override void Interact() { m_Player.SetActive(false); string msg = ""; if (m_GameManager.ObjectivesCompleted()) { msg = "Mission Successfull"; if(m_GameManager.GetInnocentTargetKilled() > 0) { msg += "\nYou killed " + m_GameManager.GetInnocentTargetKilled() + " innocents."; } } else { msg = "Mission Failed"; msg += "\nYou didn't complete your objectives."; } m_PhotonView.RPC("RPCInteract", PhotonTargets.All, msg, 5f); } [PunRPC] void RPCInteract(string msg, float duration) { m_HUD.ShowMessages(msg,duration); if (m_GameManager.isMaster) { duration += 1f; } Invoke("Disconnect", duration + 1f); } void Disconnect() { PhotonNetwork.Disconnect(); } }
using UnityEngine; public class Exit : Interactive { GameManager m_GameManager; GameObject m_Player; PhotonView m_PhotonView; protected new void Start () { base.Start(); m_PhotonView = GetComponent<PhotonView>(); m_GameManager = FindObjectOfType<GameManager>(); } void OnTriggerEnter(Collider other) { Action act = other.GetComponent<Action>(); if (act) { if(act.enabled) { m_Player = other.gameObject; m_HUD.ShowActionPrompt("Exit mission"); act.SetInteract(true); act.SetInteractionObject(this); } } } void OnTriggerExit(Collider other) { Action act = other.GetComponent<Action>(); if (act) { if(act.enabled) { m_HUD.HideActionPrompt(); act.SetInteract(false); } } } public override void Interact() { m_Player.SetActive(false); string msg = ""; if (m_GameManager.ObjectivesCompleted()) { msg = "Mission Successfull"; if(m_GameManager.GetInnocentTargetKilled() > 0) { msg += "\nYou killed " + m_GameManager.GetInnocentTargetKilled() + " innocents."; } } else { msg = "Mission Failed"; msg += "\nYou didn't complete your objectives."; } m_PhotonView.RPC("RPCInteract", PhotonTargets.All, msg, 5f); } [PunRPC] void RPCInteract(string msg, float duration) { m_HUD.ShowMessages(msg,duration); } }
mit
C#
dc11b583527fb0acdb2a5442f4966c927455bf00
Make MutableLanguage public
hrzafer/nuve
nuve/Lang/MutableLanguage.cs
nuve/Lang/MutableLanguage.cs
using System.Collections.Generic; using System.Linq; using Nuve.Morphologic; using Nuve.Morphologic.Structure; using Nuve.Orthographic; namespace Nuve.Lang { public class MutableLanguage : Language { private MutableLanguage(string code, Orthography orthography, Morphotactics morphotactics, MorphemeContainer<Root> roots, MorphemeContainer<Suffix> suffixes) : base(code, orthography, morphotactics, roots, suffixes) { } public static MutableLanguage CopyFrom(Language language) { var roots = MorphemeContainer<Root>.CopyOf(language.Roots); return new MutableLanguage(language.Code, language.Orthography, language.Morphotactics, roots, language.Suffixes); } public bool TryAdd(RootEntry entry) { if (Roots.ById.ContainsKey(entry.Id)) { return false; } Add(entry); return true; } private void Add(RootEntry entry) { var rules = Orthography.GetRules(entry.Rules); var root = new Root(entry.Pos, entry.Lex, entry.Labels, rules, entry.PrimarySurface); Roots.ById.Add(entry.Id, root); foreach (string surface in entry.Surfaces) { Roots.BySurface.Add(surface, root); } } } }
using System.Collections.Generic; using System.Linq; using Nuve.Morphologic; using Nuve.Morphologic.Structure; using Nuve.Orthographic; namespace Nuve.Lang { internal class MutableLanguage : Language { private MutableLanguage(string code, Orthography orthography, Morphotactics morphotactics, MorphemeContainer<Root> roots, MorphemeContainer<Suffix> suffixes) : base(code, orthography, morphotactics, roots, suffixes) { } public static MutableLanguage CopyFrom(Language language) { var roots = MorphemeContainer<Root>.CopyOf(language.Roots); return new MutableLanguage(language.Code, language.Orthography, language.Morphotactics, roots, language.Suffixes); } public bool TryAdd(RootEntry entry) { if (Roots.ById.ContainsKey(entry.Id)) { return false; } Add(entry); return true; } private void Add(RootEntry entry) { var rules = Orthography.GetRules(entry.Rules); var root = new Root(entry.Pos, entry.Lex, entry.Labels, rules, entry.PrimarySurface); Roots.ById.Add(entry.Id, root); foreach (string surface in entry.Surfaces) { Roots.BySurface.Add(surface, root); } } } }
mit
C#
ea9cdeb3348d8230c49f2477aa60f6069631ee89
Disable display test that is failing in CI build.
eylvisaker/AgateLib
UnitTests/Display/DisplayTests.cs
UnitTests/Display/DisplayTests.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AgateLib; using AgateLib.Drivers; using AgateLib.DisplayLib; namespace AgateLib.UnitTests.DisplayTest { [TestClass] public class DisplayTest { /* [TestMethod] public void InitializeDisplay() { using (AgateSetup setup = new AgateSetup()) { setup.PreferredDisplay = (DisplayTypeID) 1000; setup.InitializeDisplay((DisplayTypeID)1000); Assert.IsFalse(setup.WasCanceled); DisplayWindow wind = DisplayWindow.CreateWindowed("Title", 400, 400); } } * */ } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using AgateLib; using AgateLib.Drivers; using AgateLib.DisplayLib; namespace AgateLib.UnitTests.DisplayTest { [TestClass] public class DisplayTest { [TestMethod] public void InitializeDisplay() { using (AgateSetup setup = new AgateSetup()) { setup.PreferredDisplay = (DisplayTypeID) 1000; setup.InitializeDisplay((DisplayTypeID)1000); Assert.IsFalse(setup.WasCanceled); DisplayWindow wind = DisplayWindow.CreateWindowed("Title", 400, 400); } } } }
mit
C#
dc126f8bc7497d6668f41ca3da61ba491476aa45
Update copyright notice in assembly info
LavishSoftware/PropertyTools,ZHZG/PropertyTools,punker76/PropertyTools,ZHZG/PropertyTools,jogibear9988/PropertyTools,objorke/PropertyTools,Mitch-Connor/PropertyTools,jogibear9988/PropertyTools,johnsonlu/PropertyTools
Source/GlobalAssemblyInfo.cs
Source/GlobalAssemblyInfo.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="PropertyTools"> // The MIT License (MIT) // // Copyright (c) 2014 PropertyTools contributors // // 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. // </copyright> // <summary> // Shared assembly attributes. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("PropertyTools for WPF")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright (C) PropertyTools contributors 2014.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.1.1.1")] [assembly: AssemblyFileVersion("2014.1.1.1")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GlobalAssemblyInfo.cs" company="PropertyTools"> // The MIT License (MIT) // // Copyright (c) 2014 PropertyTools contributors // // 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. // </copyright> // <summary> // Shared assembly attributes. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System.Reflection; [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("PropertyTools for WPF")] [assembly: AssemblyCompany("")] [assembly: AssemblyCopyright("Copyright (C) Oystein Bjorke 2012.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("2014.1.1.1")] [assembly: AssemblyFileVersion("2014.1.1.1")]
mit
C#
53688677fedbc11d0ff190e110391c14a5422c2b
build version: 3.9.71.9
wiesel78/Canwell.OrmLite.MSAccess2003
Source/GlobalAssemblyInfo.cs
Source/GlobalAssemblyInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyCompany("canwell - IT Solutions")] [assembly: AssemblyVersion("3.9.71.9")] [assembly: AssemblyFileVersion("3.9.71.9")] [assembly: AssemblyInformationalVersion("3.9.71.9")] [assembly: AssemblyCopyright("Copyright © 2016")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by Cake. // </auto-generated> //------------------------------------------------------------------------------ using System.Reflection; [assembly: AssemblyCompany("canwell - IT Solutions")] [assembly: AssemblyVersion("3.9.71.8")] [assembly: AssemblyFileVersion("3.9.71.8")] [assembly: AssemblyInformationalVersion("3.9.71.8")] [assembly: AssemblyCopyright("Copyright © 2016")]
bsd-3-clause
C#
26c4826f2b05f3c8d2bdfe4a77b2e754964883d8
Update version to 7.3.0
roberthardy/Synthesis,kamsar/Synthesis
Source/SharedAssemblyInfo.cs
Source/SharedAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System; [assembly: AssemblyCompany("ISITE Design")] [assembly: AssemblyProduct("Synthesis")] [assembly: AssemblyCopyright("Copyright © Kam Figy, ISITE Design")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("7.3.0.0")] [assembly: AssemblyFileVersion("7.3.0.0")] [assembly: AssemblyInformationalVersion("7.3.0")] [assembly: CLSCompliant(false)]
using System.Reflection; using System.Runtime.InteropServices; using System; [assembly: AssemblyCompany("ISITE Design")] [assembly: AssemblyProduct("Synthesis")] [assembly: AssemblyCopyright("Copyright © Kam Figy, ISITE Design")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("7.2.1.0")] [assembly: AssemblyFileVersion("7.2.1.0")] [assembly: AssemblyInformationalVersion("7.2.1")] [assembly: CLSCompliant(false)]
mit
C#
268979264bd755d689409a23343bfcd73c776169
Add a comment for exported DefaultProperties.
EliotVU/Unreal-Library
Core/Decompilers/UnTextBufferDecompiler.cs
Core/Decompilers/UnTextBufferDecompiler.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using UELib; using UELib.Core; namespace UELib.Core { public partial class UTextBuffer : UObject { public override string Decompile() { if( _bDeserializeOnDemand ) { BeginDeserializing(); } if( ScriptText.Length != 0 ) { if( Outer is UStruct ) { try { return ScriptText + (((UClass)Outer).Properties != null && ((UClass)Outer).Properties.Count > 0 ? "// Decompiled with UE Explorer." : "// No DefaultProperties.") + ((UClass)Outer).FormatDefaultProperties(); } catch { return ScriptText + "\r\n// Failed to decompile defaultproperties for this object."; } } return ScriptText; } return "TextBuffer is empty!"; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using UELib; using UELib.Core; namespace UELib.Core { public partial class UTextBuffer : UObject { public override string Decompile() { if( _bDeserializeOnDemand ) { BeginDeserializing(); } if( ScriptText.Length != 0 ) { if( Outer is UStruct ) { try { return ScriptText + ((UClass)Outer).FormatDefaultProperties(); } catch { return ScriptText + "\r\n// Failed to decompile defaultproperties for this object."; } } return ScriptText; } return "TextBuffer is empty!"; } } }
mit
C#
f56cde8f7583cd15b3b8f53f55659a08a825d0ce
Update Startup.cs
Konard/ASP.NET-5-CoreCLR-WebSocket-Example,Konard/ASP.NET-5-CoreCLR-WebSocket-Example
WebSocketExample/Startup.cs
WebSocketExample/Startup.cs
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using System.Net.WebSockets; using Microsoft.AspNetCore.StaticFiles; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace WebSocketExample { public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseFileServer(enableDirectoryBrowsing: true); app.UseWebSockets(); // Only for Kestrel app.Map("/ws", builder => { builder.Use(async (context, next) => { if (context.WebSockets.IsWebSocketRequest) { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(webSocket); return; } await next(); }); }); } private async Task Echo(WebSocket webSocket) { byte[] buffer = new byte[1024 * 4]; var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } } }
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using System.Net.WebSockets; //using Microsoft.AspNetCore.WebSockets.Server; using Microsoft.AspNetCore.StaticFiles; using Microsoft.AspNetCore.Http; using System.Collections.Generic; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace WebSocketExample { public class Startup { public void ConfigureServices(IServiceCollection services) { } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseDefaultFiles(); app.UseStaticFiles(); app.UseFileServer(enableDirectoryBrowsing: true); app.UseWebSockets(); // Only for Kestrel app.Map("/ws", builder => { builder.Use(async (context, next) => { if (context.WebSockets.IsWebSocketRequest) { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); await Echo(webSocket); return; } await next(); }); }); } private async Task Echo(WebSocket webSocket) { byte[] buffer = new byte[1024 * 4]; var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); } } }
mit
C#
4d47b749b1956c75aa320f7a6de6a1ae9365a6f9
Test - Avoid displaying Form in WinForms Test
Livit/CefSharp,Livit/CefSharp,Livit/CefSharp,Livit/CefSharp
CefSharp.Test/WinForms/WinFormsBrowserBasicFacts.cs
CefSharp.Test/WinForms/WinFormsBrowserBasicFacts.cs
// Copyright © 2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Threading.Tasks; using CefSharp.WinForms; using Xunit; using Xunit.Abstractions; namespace CefSharp.Test.WinForms { //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] public class WinFormsBrowserBasicFacts { private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; public WinFormsBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; } [WinFormsFact] public async Task CanLoadGoogle() { using (var browser = new ChromiumWebBrowser("www.google.com")) { browser.Size = new System.Drawing.Size(1024, 768); browser.CreateControl(); await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.True(mainFrame.Url.Contains("www.google")); output.WriteLine("Url {0}", mainFrame.Url); } } } }
// Copyright © 2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. using System.Threading.Tasks; using CefSharp.WinForms; using Xunit; using Xunit.Abstractions; namespace CefSharp.Test.WinForms { //NOTE: All Test classes must be part of this collection as it manages the Cef Initialize/Shutdown lifecycle [Collection(CefSharpFixtureCollection.Key)] public class WinFormsBrowserBasicFacts { private readonly ITestOutputHelper output; private readonly CefSharpFixture fixture; public WinFormsBrowserBasicFacts(ITestOutputHelper output, CefSharpFixture fixture) { this.fixture = fixture; this.output = output; } [WinFormsFact] public async Task CanLoadGoogle() { using (var browser = new ChromiumWebBrowser("www.google.com")) { var form = new System.Windows.Forms.Form(); form.Controls.Add(browser); form.Show(); await browser.LoadPageAsync(); var mainFrame = browser.GetMainFrame(); Assert.True(mainFrame.IsValid); Assert.True(mainFrame.Url.Contains("www.google")); output.WriteLine("Url {0}", mainFrame.Url); } } } }
bsd-3-clause
C#
f4c4ee5fd77e699e7f588a50ec4d508ab3e0cab6
Use a warmup task to relieve the noticeable delay on first script evaluation
discosultan/quake-console
Interpreters/RoslynInterpreter/RoslynInterpreter.cs
Interpreters/RoslynInterpreter/RoslynInterpreter.cs
using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using QuakeConsole.Input; using QuakeConsole.Output; using System; using System.Threading.Tasks; namespace QuakeConsole { public class RoslynInterpreter : ICommandInterpreter { private Script _previousInput; private Task _warmupTask; public RoslynInterpreter() { _warmupTask = Task.Factory.StartNew(() => { // Assignment and literal evaluation to warm up the scripting context. // Without warmup, there is a considerable delay on first command evaluation since scripts // are being run synchronously. CSharpScript.EvaluateAsync("int x = 1; 1"); _previousInput = CSharpScript.Create(null); }); } /// <summary> /// Gets or sets if the user entered command should be shown in the output. /// </summary> public bool EchoEnabled { get; set; } = true; public void Autocomplete(IConsoleInput input, bool forward) { } public void Execute(IConsoleOutput output, string command) { if (EchoEnabled) output.Append(command); try { _warmupTask.Wait(); Script script = _previousInput.ContinueWith(command); ScriptState endState = script.RunAsync().Result; _previousInput = endState.Script; if (endState.ReturnValue != null) output.Append(endState.ReturnValue.ToString()); } catch (CompilationErrorException e) { output.Append(string.Join(Environment.NewLine, e.Diagnostics)); } } } }
using Microsoft.CodeAnalysis.CSharp.Scripting; using Microsoft.CodeAnalysis.Scripting; using QuakeConsole.Input; using QuakeConsole.Output; using System; namespace QuakeConsole { public class RoslynInterpreter : ICommandInterpreter { private Script _previousInput; /// <summary> /// Gets or sets if the user entered command should be shown in the output. /// </summary> public bool EchoEnabled { get; set; } = true; public void Autocomplete(IConsoleInput input, bool forward) { input.Value = "your mother"; } public void Execute(IConsoleOutput output, string command) { if (EchoEnabled) output.Append(command); try { Script script; if (_previousInput == null) script = CSharpScript.Create(command); else script = _previousInput.ContinueWith(command); ScriptState endState = script.RunAsync().Result; _previousInput = endState.Script; if (endState.ReturnValue != null) output.Append(endState.ReturnValue.ToString()); } catch (CompilationErrorException e) { output.Append(string.Join(Environment.NewLine, e.Diagnostics)); } } } }
mit
C#
2188a70dea441ca56a24fad8df0012b0bb75102c
Fix build errors
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/Services/Terminate/TerminateService.cs
WalletWasabi/Services/Terminate/TerminateService.cs
using System; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Services.Terminate { public class TerminateService { private readonly Func<Task> TerminateApplicationAsync; private const long TerminateStatusIdle = 0; private const long TerminateStatusInProgress = 1; private const long TerminateStatusFinished = 2; private long _terminateStatus; public TerminateService(Func<Task> terminateApplicationAsync) { TerminateApplicationAsync = terminateApplicationAsync; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; Console.CancelKeyPress += Console_CancelKeyPress; } private void CurrentDomain_ProcessExit(object? sender, EventArgs e) { Logger.LogDebug("ProcessExit was called."); // This must be a blocking call because after this the OS will terminate Wasabi process if exists. Terminate(); } private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e) { Logger.LogWarning($"Process termination was requested using '{e.SpecialKey}' keyboard shortcut."); // This must be a blocking call because after this the OS will terminate Wasabi process if it exists. // In some cases CurrentDomain_ProcessExit is called after this by the OS. Terminate(); } /// <summary> /// Terminates the application. /// </summary> /// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark> public void Terminate(int exitCode = 0) { var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle); Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}"); if (prevValue != TerminateStatusIdle) { // Secondary callers will be blocked until the end of the termination. while (_terminateStatus != TerminateStatusFinished) { } return; } // First caller starts the terminate procedure. Logger.LogDebug("Start shutting down the application."); // Async termination has to be started on another thread otherwise there is a possibility of deadlock. // We still need to block the caller so ManualResetEvent applied. using ManualResetEvent resetEvent = new ManualResetEvent(false); Task.Run(async () => { try { await TerminateApplicationAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.LogWarning(ex.ToTypeMessageString()); } resetEvent.Set(); }); resetEvent.WaitOne(); AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit; Console.CancelKeyPress -= Console_CancelKeyPress; // Indicate that the termination procedure finished. So other callers can return. Interlocked.Exchange(ref _terminateStatus, TerminateStatusFinished); Environment.Exit(exitCode); } public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle; } }
using System; using System.Threading; using System.Threading.Tasks; using WalletWasabi.Logging; namespace WalletWasabi.Services.Terminate { public class TerminateService { private readonly Func<Task> _terminateApplicationAsync; private const long TerminateStatusIdle = 0; private const long TerminateStatusInProgress = 1; private const long TerminateStatusFinished = 2; private long _terminateStatus; public TerminateService(Func<Task> terminateApplicationAsync) { _terminateApplicationAsync = terminateApplicationAsync; AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; Console.CancelKeyPress += Console_CancelKeyPress; } private void CurrentDomain_ProcessExit(object? sender, EventArgs e) { Logger.LogDebug("ProcessExit was called."); // This must be a blocking call because after this the OS will terminate Wasabi process if exists. Terminate(); } private void Console_CancelKeyPress(object? sender, ConsoleCancelEventArgs e) { Logger.LogWarning($"Process termination was requested using '{e.SpecialKey}' keyboard shortcut."); // This must be a blocking call because after this the OS will terminate Wasabi process if it exists. // In some cases CurrentDomain_ProcessExit is called after this by the OS. Terminate(); } /// <summary> /// Terminates the application. /// </summary> /// <remark>This is a blocking method. Note that program execution ends at the end of this method due to <see cref="Environment.Exit(int)"/> call.</remark> public void Terminate(int exitCode = 0) { var prevValue = Interlocked.CompareExchange(ref _terminateStatus, TerminateStatusInProgress, TerminateStatusIdle); Logger.LogTrace($"Terminate was called from ThreadId: {Thread.CurrentThread.ManagedThreadId}"); if (prevValue != TerminateStatusIdle) { // Secondary callers will be blocked until the end of the termination. while (_terminateStatus != TerminateFinished) { } return; } // First caller starts the terminate procedure. Logger.LogDebug("Start shutting down the application."); // Async termination has to be started on another thread otherwise there is a possibility of deadlock. // We still need to block the caller so ManualResetEvent applied. using ManualResetEvent resetEvent = new ManualResetEvent(false); Task.Run(async () => { try { await _terminateApplicationAsync().ConfigureAwait(false); } catch (Exception ex) { Logger.LogWarning(ex.ToTypeMessageString()); } resetEvent.Set(); }); resetEvent.WaitOne(); AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit; Console.CancelKeyPress -= Console_CancelKeyPress; // Indicate that the termination procedure finished. So other callers can return. Interlocked.Exchange(ref _terminateStatus, TerminateFinished); Environment.Exit(exitCode); } public bool IsTerminateRequested => Interlocked.Read(ref _terminateStatus) > TerminateStatusIdle; } }
mit
C#
16bdf4e6bd250ac5dd9cb6fa497d80e984002af1
Update english to be more readable
peppy/osu-new,UselessToucan/osu,2yangk23/osu,EVAST9919/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipooo/osu,2yangk23/osu,peppy/osu,ppy/osu,johnneijzen/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu
osu.Game/Overlays/BeatmapSet/Scores/NoScoresPlaceholder.cs
osu.Game/Overlays/BeatmapSet/Scores/NoScoresPlaceholder.cs
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Screens.Select.Leaderboards; using osu.Framework.Graphics.Sprites; namespace osu.Game.Overlays.BeatmapSet.Scores { public class NoScoresPlaceholder : Container { private readonly SpriteText text; public NoScoresPlaceholder() { AutoSizeAxes = Axes.Both; Child = text = new SpriteText { Font = OsuFont.GetFont(), }; } public void UpdateText(BeatmapLeaderboardScope scope) { switch (scope) { default: text.Text = @"No scores have been set yet. Maybe you can be the first!"; return; case BeatmapLeaderboardScope.Friend: text.Text = @"None of your friends have set a score on this map yet."; return; case BeatmapLeaderboardScope.Country: text.Text = @"No one from your country has set a score on this map yet."; return; } } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Graphics; using osu.Game.Screens.Select.Leaderboards; using osu.Framework.Graphics.Sprites; namespace osu.Game.Overlays.BeatmapSet.Scores { public class NoScoresPlaceholder : Container { private readonly SpriteText text; public NoScoresPlaceholder() { AutoSizeAxes = Axes.Both; Child = text = new SpriteText { Font = OsuFont.GetFont(), }; } public void UpdateText(BeatmapLeaderboardScope scope) { switch (scope) { default: case BeatmapLeaderboardScope.Global: text.Text = @"No scores yet. Maybe should try setting some?"; return; case BeatmapLeaderboardScope.Friend: text.Text = @"None of your friends has set a score on this map yet!"; return; case BeatmapLeaderboardScope.Country: text.Text = @"No one from your country has set a score on this map yet!"; return; } } } }
mit
C#
05e13158ff2b9c47a8f7a69fe2ff1fb8a89c2f10
Check for null datum.
predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,jtb8vm/sensus,predictive-technology-laboratory/sensus,predictive-technology-laboratory/sensus,jtb8vm/sensus,jtb8vm/sensus,jtb8vm/sensus,jtb8vm/sensus,jtb8vm/sensus
Sensus.Shared/Probes/DataRateCalculator.cs
Sensus.Shared/Probes/DataRateCalculator.cs
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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; using System.Linq; namespace Sensus.Probes { public class DataRateCalculator { private List<Datum> _sample; private TimeSpan _sampleDuration; public double DataPerSecond { get { lock (_sample) { double dataRate = 0; if (_sample.Count >= 2) dataRate = _sample.Count / (_sample.Last().Timestamp - _sample.First().Timestamp).TotalSeconds; return dataRate; } } } public DataRateCalculator(TimeSpan sampleDuration) { _sampleDuration = sampleDuration; _sample = new List<Datum>(); } public double Add(Datum datum) { // probes are allowed to generate null data (e.g., the POI probe indicating that no POI are nearby). for the purposes of data rate // calculation, these should be ignored. if (datum != null) { // maintain a sample of the given duration lock (_sample) { // remove any data that are older than the sample duration _sample.Add(datum); while (_sample.Count > 0 && (DateTimeOffset.Now - _sample.First().Timestamp).TotalSeconds > _sampleDuration.TotalSeconds) _sample.RemoveAt(0); } } return DataPerSecond; } } }
// Copyright 2014 The Rector & Visitors of the University of Virginia // // 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; using System.Linq; namespace Sensus.Probes { public class DataRateCalculator { private List<Datum> _sample; private TimeSpan _sampleDuration; public double DataPerSecond { get { lock (_sample) { double dataRate = 0; if (_sample.Count >= 2) dataRate = _sample.Count / (_sample.Last().Timestamp - _sample.First().Timestamp).TotalSeconds; return dataRate; } } } public DataRateCalculator(TimeSpan sampleDuration) { _sampleDuration = sampleDuration; _sample = new List<Datum>(); } public double Add(Datum datum) { // maintain a sample of the given duration lock (_sample) { // remove any data that are older than the sample duration _sample.Add(datum); while (_sample.Count > 0 && (DateTimeOffset.Now - _sample.First().Timestamp).TotalSeconds > _sampleDuration.TotalSeconds) _sample.RemoveAt(0); return DataPerSecond; } } } }
apache-2.0
C#
3a149045e80baf5a6185aba3e9d85fc27bb99892
change default game state to playing
MrErdalUral/Cyborg-Ninja-Training-Program
Assets/Script/GameManager.cs
Assets/Script/GameManager.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager Instance; public GameState GameState = GameState.PLAYING; /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { DontDestroyOnLoad(this); if (Instance != this) { Destroy(Instance); } Instance = this; GameState = GameState.MENU; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { switch (GameState) { case GameState.MENU: case GameState.LEVEL_START: case GameState.LEVEL_ENDED: case GameState.PLAYING: case GameState.PAUSED: case GameState.DEAD: default: return; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameManager : MonoBehaviour { public static GameManager Instance; public GameState GameState; /// <summary> /// Awake is called when the script instance is being loaded. /// </summary> void Awake() { DontDestroyOnLoad(this); if (Instance != this) { Destroy(Instance); } Instance = this; GameState = GameState.MENU; } // Use this for initialization void Start () { } // Update is called once per frame void Update () { switch (GameState) { case GameState.MENU: case GameState.LEVEL_START: case GameState.LEVEL_ENDED: case GameState.PLAYING: case GameState.PAUSED: case GameState.DEAD: default: return; } } }
apache-2.0
C#