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
b65d0621b2fce7b8d8ab2fd2cce5f7244186f257
Add new file UITests/Tests.cs
ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl,ArcanaMagus/userAuth.cpl
UITests/Tests.cs
UITests/Tests.cs
using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Android; using Xamarin.UITest.Queries; namespace userAuth.cpl.UITests { [TestFixture] public class Tests { AndroidApp app; [SetUp] public void BeforeEachTest () { app = ConfigureApp.Android.StartApp (); } [Test] public void WelcomeTextIsDisplayed () { AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!")); app.Screenshot ("Welcome screen."); Assert.IsTrue (results.Any ()); } } } namespace userAuth.cpl.Droid struct init_struct () { forms = userAuth.Forms.ApplicationException.Android.Config } [TestFixtureSetUp] public class preTest { AndroidDevice device; [SetUpFixture] public void AlternateBeforeTestParam () { device = IDevice.AndroidConfig.TestDevice (); } [TestAction] public void TestResultsAreDisplayed () { ITestAction[] actions = device.DisplayCurrentElement (c => c.Marked ("Results of the Droid Test are:") + results); device.ImageCap ("Test Results."); Math.IsInstance (actions.String ()); } } } namespace Test.userAuth.cpl.Droid static void Launch(string[]EventArgs) { System.Console.WriteLine("Renter the frames to count"); Console.WriteLine("Enter any additional parameters"); Console.ReadLine(); } struct command(start) { start: (ev:Sysyem.Path) "PathTo" = internal.interface(cmdLet) path = scanner("&B", "%6"); [Builtin] public class start { InitUI init; (stable): from userAuth.FrameAnchor import into internal InitUI(on: op) } }
 �using System; using System.IO; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.Android; using Xamarin.UITest.Queries; namespace userAuth.cpl.UITests { [TestFixture] public class Tests { AndroidApp app; [SetUp] public void BeforeEachTest () { app = ConfigureApp.Android.StartApp (); } [Test] public void WelcomeTextIsDisplayed () { AppResult[] results = app.WaitForElement (c => c.Marked ("Welcome to Xamarin Forms!")); app.Screenshot ("Welcome screen."); Assert.IsTrue (results.Any ()); } } } namespace userAuth.cpl.Droid struct init_struct () { forms = userAuth.Forms.ApplicationException.Android.Config } [TestFixtureSetUp] public class preTest { AndroidDevice device; [SetUpFixture] public void AlternateBeforeTestParam () { device = IDevice.AndroidConfig.TestDevice (); } [TestAction] public void TestResultsAreDisplayed () { ITestAction[] actions = device.DisplayCurrentElement (c => c.Marked ("Results of the Droid Test are:") + results); device.ImageCap ("Test Results."); Math.IsInstance (actions.String ()); } } } namespace Test.userAuth.cpl.Droid static void Launch(string[]EventArgs) { System.Console.WriteLine("Renter the frames to count"); Console.WriteLine("Enter any additional parameters"); Console.ReadLine(); } struct command(start) { start: (ev:Sysyem.Path) "PathTo" = internal.interface(cmdLet) path = scanner("&B", "%6"); [Builtin] public class start { InitUI init; (stable): from userAuth.FrameAnchor import into internal InitUI(on: op) } }
mit
C#
948564d54bd4b18c3f1ca1189ee2693fbf62b952
Add tests for new eventing behavior.
peterlanoie/aspnet-mvc-slack
src/Pelasoft.AspNet.Mvc.Slack.TestWeb/App_Start/FilterConfig.cs
src/Pelasoft.AspNet.Mvc.Slack.TestWeb/App_Start/FilterConfig.cs
using System.Web; using System.Web.Mvc; using Pelasoft.AspNet.Mvc.Slack; using System.Configuration; namespace Pelasoft.AspNet.Mvc.Slack.TestWeb { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); var slackReport = new WebHookErrorReportFilter( new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"]) { ChannelName = ConfigurationManager.AppSettings["slack:channel"], UserName = ConfigurationManager.AppSettings["slack:username"], IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"], AttachmentColor = ConfigurationManager.AppSettings["slack:color"], AttachmentTitle = ConfigurationManager.AppSettings["slack:title"], AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"], Text = ConfigurationManager.AppSettings["slack:text"], } ) { IgnoreHandled = true, IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) }, }; filters.Add(slackReport, 1); var slackReportEvented = new WebHookErrorReportFilter(); slackReportEvented.OnExceptionReporting += slackReportEvented_OnExceptionReporting; filters.Add(slackReportEvented); } static void slackReportEvented_OnExceptionReporting(ExceptionReportingEventArgs args) { args.Options = new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"]) { Text = "Options reported via the event.", ChannelName = ConfigurationManager.AppSettings["slack:channel"], }; // args.CancelReport = true; } } }
using System.Web; using System.Web.Mvc; using Pelasoft.AspNet.Mvc.Slack; using System.Configuration; namespace Pelasoft.AspNet.Mvc.Slack.TestWeb { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); var slackReport = new WebHookErrorReportFilter( new WebHookOptions(ConfigurationManager.AppSettings["slack:webhookurl"]) { ChannelName = ConfigurationManager.AppSettings["slack:channel"], UserName = ConfigurationManager.AppSettings["slack:username"], IconEmoji = ConfigurationManager.AppSettings["slack:iconEmoji"], AttachmentColor = ConfigurationManager.AppSettings["slack:color"], AttachmentTitle = ConfigurationManager.AppSettings["slack:title"], AttachmentTitleLink = ConfigurationManager.AppSettings["slack:link"], Text = ConfigurationManager.AppSettings["slack:text"], } ) { IgnoreHandled = true, IgnoreExceptionTypes = new[] { typeof(System.ApplicationException) }, }; filters.Add(slackReport, 1); } } }
mit
C#
dca27b0c6389bb90551dd1625ceb8d8cc35456cb
fix namespace
Chatham/ServiceStack.Text.TupleSerializer
src/ServiceStack.Text.InlineTupleSerializer/PassThroughCache.cs
src/ServiceStack.Text.InlineTupleSerializer/PassThroughCache.cs
using System; using ServiceStack.Text.InlineTupleSerializer.Api; namespace ServiceStack.Text.InlineTupleSerializer { public class PassThroughCache<TKey, TValue> : ICache<TKey, TValue> { public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory) { return valueFactory(key); } } }
using System; using ServiceStack.Text.InlineTupleSerializer.Api; namespace ServiceStack.Text.InlineTupleSerializer.UnitTests { public class PassThroughCache<TKey, TValue> : ICache<TKey, TValue> { public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory) { return valueFactory(key); } } }
mit
C#
1937d0fd26bdfd26b7582395ff9edafff3bc7e02
Update the release/editorial endpoint schema
gregsochanik/SevenDigital.Api.Wrapper,actionshrimp/SevenDigital.Api.Wrapper,bnathyuw/SevenDigital.Api.Wrapper,minkaotic/SevenDigital.Api.Wrapper,luiseduardohdbackup/SevenDigital.Api.Wrapper,danbadge/SevenDigital.Api.Wrapper,mattgray/SevenDigital.Api.Wrapper,raoulmillais/SevenDigital.Api.Wrapper,bettiolo/SevenDigital.Api.Wrapper,AnthonySteele/SevenDigital.Api.Wrapper,emashliles/SevenDigital.Api.Wrapper,danhaller/SevenDigital.Api.Wrapper
src/SevenDigital.Api.Schema/ReleaseEndpoint/ReleaseEditorial.cs
src/SevenDigital.Api.Schema/ReleaseEndpoint/ReleaseEditorial.cs
using System; using System.Xml.Serialization; using SevenDigital.Api.Schema.Attributes; using SevenDigital.Api.Schema.ParameterDefinitions.Get; namespace SevenDigital.Api.Schema.ReleaseEndpoint { [XmlRoot("editorial")] [ApiEndpoint("release/editorial")] [Serializable] public class ReleaseEditorial : HasReleaseIdParameter { [XmlElement("review")] public TextItem Review { get; set; } [XmlElement("promotionalText")] public TextItem PromotionalText { get; set; } } public class TextItem { [XmlElement("text")] public string Text { get; set; } } }
using System; using System.Xml.Serialization; using SevenDigital.Api.Schema.Attributes; using SevenDigital.Api.Schema.ParameterDefinitions.Get; namespace SevenDigital.Api.Schema.ReleaseEndpoint { [XmlRoot("editorial")] [ApiEndpoint("release/editorial")] [Serializable] public class ReleaseEditorial : HasReleaseIdParameter { [XmlElement("review")] public Review Review { get; set; } [XmlElement("staffRecommendation")] public Review StaffRecommendation { get; set; } [XmlElement("promotionalText")] public string PromotionalText { get; set; } } public class Review { [XmlElement("text")] public string Text { get; set; } } }
mit
C#
79315faba86bd25e7a91761d5087937186b0259a
Fix cert auth sample (#28699)
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/Security/Authentication/Certificate/samples/Certificate.Sample/Program.cs
src/Security/Authentication/Certificate/samples/Certificate.Sample/Program.cs
using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.Extensions.Hosting; namespace Certificate.Sample { 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>() .ConfigureKestrel(options => { options.ConfigureHttpsDefaults(opt => { opt.ClientCertificateMode = ClientCertificateMode.RequireCertificate; }); }); }); } }
using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Server.Kestrel.Https; using Microsoft.Extensions.Hosting; namespace Certificate.Sample { public class Program { public static Task Main(string[] args) { var host = Host.CreateDefaultBuilder(args) .ConfigureWebHost(webHostBuilder => { webHostBuilder .UseStartup<Startup>() .ConfigureKestrel(options => { options.ConfigureHttpsDefaults(opt => { opt.ClientCertificateMode = ClientCertificateMode.RequireCertificate; }); }); }) .Build(); return host.RunAsync(); } } }
apache-2.0
C#
9ba17068fe9978121210a2652deadf655e58e28d
Revert "Revert "added try catch, test commit""
durayakar/PnP,SPDoctor/PnP,rencoreab/PnP,SPDoctor/PnP,SuryaArup/PnP,MaurizioPz/PnP,SPDoctor/PnP,jlsfernandez/PnP,Arknev/PnP,kendomen/PnP,grazies/PnP,GSoft-SharePoint/PnP,Chowdarysandhya/PnPTest,OfficeDev/PnP,svarukala/PnP,levesquesamuel/PnP,dalehhirt/PnP,rencoreab/PnP,BartSnyckers/PnP,erwinvanhunen/PnP,OneBitSoftware/PnP,briankinsella/PnP,spdavid/PnP,ebbypeter/PnP,spdavid/PnP,RickVanRousselt/PnP,vnathalye/PnP,gautekramvik/PnP,Chowdarysandhya/PnPTest,IDTimlin/PnP,rgueldenpfennig/PnP,aammiitt2/PnP,SuryaArup/PnP,vnathalye/PnP,werocool/PnP,8v060htwyc/PnP,kendomen/PnP,r0ddney/PnP,baldswede/PnP,OfficeDev/PnP,worksofwisdom/PnP,SuryaArup/PnP,russgove/PnP,Arknev/PnP,valt83/PnP,ebbypeter/PnP,markcandelora/PnP,patrick-rodgers/PnP,sjuppuh/PnP,shankargurav/PnP,vman/PnP,sndkr/PnP,darei-fr/PnP,ivanvagunin/PnP,durayakar/PnP,sjuppuh/PnP,grazies/PnP,rgueldenpfennig/PnP,levesquesamuel/PnP,kevhoyt/PnP,shankargurav/PnP,andreasblueher/PnP,grazies/PnP,svarukala/PnP,shankargurav/PnP,JBeerens/PnP,ifaham/Test,vnathalye/PnP,vman/PnP,PieterVeenstra/PnP,tomvr2610/PnP,machadosantos/PnP,SimonDoy/PnP,bbojilov/PnP,GSoft-SharePoint/PnP,aammiitt2/PnP,hildabarbara/PnP,miksteri/OfficeDevPnP,mauricionr/PnP,pdfshareforms/PnP,aammiitt2/PnP,darei-fr/PnP,JonathanHuss/PnP,NexploreDev/PnP-PowerShell,sjuppuh/PnP,perolof/PnP,rroman81/PnP,sandhyagaddipati/PnPSamples,brennaman/PnP,timothydonato/PnP,r0ddney/PnP,miksteri/OfficeDevPnP,narval32/Shp,JilleFloridor/PnP,gavinbarron/PnP,valt83/PnP,kendomen/PnP,tomvr2610/PnP,dalehhirt/PnP,sandhyagaddipati/PnPSamples,svarukala/PnP,ifaham/Test,kendomen/PnP,bhoeijmakers/PnP,briankinsella/PnP,bhoeijmakers/PnP,SteenMolberg/PnP,JonathanHuss/PnP,afsandeberg/PnP,andreasblueher/PnP,8v060htwyc/PnP,lamills1/PnP,jeroenvanlieshout/PnP,joaopcoliveira/PnP,Anil-Lakhagoudar/PnP,IvanTheBearable/PnP,nishantpunetha/PnP,srirams007/PnP,NexploreDev/PnP-PowerShell,pascalberger/PnP,NavaneethaDev/PnP,GSoft-SharePoint/PnP,valt83/PnP,jlsfernandez/PnP,kevhoyt/PnP,edrohler/PnP,Chowdarysandhya/PnPTest,ivanvagunin/PnP,IvanTheBearable/PnP,perolof/PnP,markcandelora/PnP,chrisobriensp/PnP,PieterVeenstra/PnP,afsandeberg/PnP,bhoeijmakers/PnP,lamills1/PnP,selossej/PnP,Anil-Lakhagoudar/PnP,gavinbarron/PnP,SimonDoy/PnP,machadosantos/PnP,perolof/PnP,weshackett/PnP,comblox/PnP,rbarten/PnP,bbojilov/PnP,edrohler/PnP,baldswede/PnP,SteenMolberg/PnP,srirams007/PnP,zrahui/PnP,grazies/PnP,pbjorklund/PnP,BartSnyckers/PnP,mauricionr/PnP,brennaman/PnP,rroman81/PnP,weshackett/PnP,IDTimlin/PnP,durayakar/PnP,erwinvanhunen/PnP,jeroenvanlieshout/PnP,jeroenvanlieshout/PnP,comblox/PnP,pdfshareforms/PnP,darei-fr/PnP,OfficeDev/PnP,ebbypeter/PnP,rroman81/PnP,sndkr/PnP,OzMakka/PnP,SteenMolberg/PnP,timschoch/PnP,narval32/Shp,PieterVeenstra/PnP,JBeerens/PnP,biste5/PnP,OneBitSoftware/PnP,yagoto/PnP,joaopcoliveira/PnP,GeiloStylo/PnP,Claire-Hindhaugh/PnP,rbarten/PnP,JilleFloridor/PnP,JonathanHuss/PnP,OzMakka/PnP,rgueldenpfennig/PnP,joaopcoliveira/PnP,NavaneethaDev/PnP,bbojilov/PnP,SimonDoy/PnP,hildabarbara/PnP,timothydonato/PnP,machadosantos/PnP,markcandelora/PnP,miksteri/OfficeDevPnP,ifaham/Test,werocool/PnP,erwinvanhunen/PnP,zrahui/PnP,JonathanHuss/PnP,BartSnyckers/PnP,Arknev/PnP,NavaneethaDev/PnP,nishantpunetha/PnP,8v060htwyc/PnP,gautekramvik/PnP,rencoreab/PnP,MaurizioPz/PnP,JBeerens/PnP,bstenberg64/PnP,pbjorklund/PnP,rahulsuryawanshi/PnP,russgove/PnP,jlsfernandez/PnP,Rick-Kirkham/PnP,comblox/PnP,baldswede/PnP,OzMakka/PnP,Claire-Hindhaugh/PnP,dalehhirt/PnP,tomvr2610/PnP,kevhoyt/PnP,Rick-Kirkham/PnP,OneBitSoftware/PnP,OfficeDev/PnP,narval32/Shp,rahulsuryawanshi/PnP,JilleFloridor/PnP,afsandeberg/PnP,yagoto/PnP,IDTimlin/PnP,sandhyagaddipati/PnPSamples,NexploreDev/PnP-PowerShell,nishantpunetha/PnP,OneBitSoftware/PnP,RickVanRousselt/PnP,GeiloStylo/PnP,ivanvagunin/PnP,weshackett/PnP,levesquesamuel/PnP,srirams007/PnP,briankinsella/PnP,yagoto/PnP,timschoch/PnP,rahulsuryawanshi/PnP,brennaman/PnP,worksofwisdom/PnP,worksofwisdom/PnP,yagoto/PnP,vman/PnP,PaoloPia/PnP,RickVanRousselt/PnP,russgove/PnP,pbjorklund/PnP,chrisobriensp/PnP,PaoloPia/PnP,zrahui/PnP,pdfshareforms/PnP,selossej/PnP,8v060htwyc/PnP,andreasblueher/PnP,pascalberger/PnP,biste5/PnP,MaurizioPz/PnP,biste5/PnP,r0ddney/PnP,werocool/PnP,spdavid/PnP,lamills1/PnP,hildabarbara/PnP,PaoloPia/PnP,patrick-rodgers/PnP,bstenberg64/PnP,timschoch/PnP,pascalberger/PnP,PaoloPia/PnP,Arknev/PnP,rencoreab/PnP,gavinbarron/PnP,Rick-Kirkham/PnP,gautekramvik/PnP,bbojilov/PnP,chrisobriensp/PnP,mauricionr/PnP,GeiloStylo/PnP,bstenberg64/PnP,Claire-Hindhaugh/PnP,Anil-Lakhagoudar/PnP,sndkr/PnP,selossej/PnP,IvanTheBearable/PnP,ivanvagunin/PnP,timothydonato/PnP,pbjorklund/PnP,edrohler/PnP,rbarten/PnP,patrick-rodgers/PnP
Samples/Core.CrossDomainImages/Core.CrossDomainImagesWeb/Pages/Default.aspx.cs
Samples/Core.CrossDomainImages/Core.CrossDomainImagesWeb/Pages/Default.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { try { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } catch (Exception) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Core.CrossDomainImagesWeb { public partial class Default : System.Web.UI.Page { protected void Page_PreInit(object sender, EventArgs e) { Uri redirectUrl; switch (SharePointContextProvider.CheckRedirectionStatus(Context, out redirectUrl)) { case RedirectionStatus.Ok: return; case RedirectionStatus.ShouldRedirect: Response.Redirect(redirectUrl.AbsoluteUri, endResponse: true); break; case RedirectionStatus.CanNotRedirect: Response.Write("An error occurred while processing your request."); Response.End(); break; } } protected void Page_Load(object sender, EventArgs e) { var spContext = SharePointContextProvider.Current.GetSharePointContext(Context); using (var clientContext = spContext.CreateUserClientContextForSPAppWeb()) { //set access token in hidden field for client calls hdnAccessToken.Value = spContext.UserAccessTokenForSPAppWeb; //set images Image1.ImageUrl = spContext.SPAppWebUrl + "AppImages/O365.png"; Services.ImgService svc = new Services.ImgService(); Image2.ImageUrl = svc.GetImage(spContext.UserAccessTokenForSPAppWeb, spContext.SPAppWebUrl.ToString(), "AppImages", "O365.png"); } } } }
mit
C#
ba1073239dac56fe483cacb350aa16314c6a9ce5
Fix FindAndModifyResult.
samus/mongodb-csharp,zh-huan/mongodb,mongodb-csharp/mongodb-csharp
MongoDBDriver/Results/FindAndModifyResult.cs
MongoDBDriver/Results/FindAndModifyResult.cs
using MongoDB.Driver.Attributes; namespace MongoDB.Driver.Results { internal class FindAndModifyResult<T> : CommandResultBase { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> [MongoName("value")] public T Value { get; set; } } }
namespace MongoDB.Driver.Results { internal class FindAndModifyResult<T> : CommandResultBase { /// <summary> /// Gets or sets the value. /// </summary> /// <value>The value.</value> public T Value { get; set; } } }
apache-2.0
C#
a9cb1e2497a3104ecdd34318842821e67723aa68
Address review.
AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia
src/Avalonia.Controls/Converters/StringFormatConverter.cs
src/Avalonia.Controls/Converters/StringFormatConverter.cs
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Avalonia.Data.Converters; namespace Avalonia.Controls.Converters; /// <summary> /// Calls <see cref="string.Format(string, object[])"/> on the passed in values, where the first element in the list /// is the string, and everything after it is passed into the object array in order. /// </summary> public class StringFormatConverter : IMultiValueConverter { public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture) { if (values[0] is string format) { try { return string.Format(format, values.Skip(1).ToArray()); } catch { return AvaloniaProperty.UnsetValue; } } return AvaloniaProperty.UnsetValue; } }
using System; using System.Collections.Generic; using System.Globalization; using Avalonia.Data.Converters; namespace Avalonia.Controls.Converters; /// <summary> /// Calls <see cref="string.Format(string, object[])"/> on the passed in values, where the first element in the list /// is the string, and everything after it is passed into the object array in order. /// </summary> public class StringFormatConverter : IMultiValueConverter { public object? Convert(IList<object?> values, Type targetType, object? parameter, CultureInfo culture) { if (values != null && values.Count == 5 && values[0] is string format && values[1] is double && values[2] is double && values[3] is double && values[4] is double) { try { return string.Format(format, values[1], values[2], values[3], values[4]); } catch { return AvaloniaProperty.UnsetValue; } } return AvaloniaProperty.UnsetValue; } }
mit
C#
cc64a61480e7510d81c91c600a0fcc4d4ab3d386
Rename field to better match type.
Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW
src/MitternachtBot/Modules/Games/Services/GamesService.cs
src/MitternachtBot/Modules/Games/Services/GamesService.cs
using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using Mitternacht.Modules.Games.Common; using Mitternacht.Services; namespace Mitternacht.Modules.Games.Services { public class GamesService : IMService { private readonly IBotConfigProvider _bcp; public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>(); public readonly ImmutableArray<string> EightBallResponses; public readonly string TypingArticlesPath = "data/typing_articles2.json"; public GamesService(IBotConfigProvider bcp) { _bcp = bcp; EightBallResponses = _bcp.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray(); var timer = new Timer(_ => { GirlRatings.Clear(); }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1)); } } }
using System; using System.Collections.Concurrent; using System.Collections.Immutable; using System.Linq; using System.Threading; using Mitternacht.Modules.Games.Common; using Mitternacht.Services; namespace Mitternacht.Modules.Games.Services { public class GamesService : IMService { private readonly IBotConfigProvider _bc; public readonly ConcurrentDictionary<ulong, GirlRating> GirlRatings = new ConcurrentDictionary<ulong, GirlRating>(); public readonly ImmutableArray<string> EightBallResponses; public readonly string TypingArticlesPath = "data/typing_articles2.json"; public GamesService(IBotConfigProvider bc) { _bc = bc; EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray(); var timer = new Timer(_ => { GirlRatings.Clear(); }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1)); } } }
mit
C#
1673828e90bde16a1e397246612fc695fc091d60
remove unused code
tenpn/upm,tenpn/upm
upm-tool/upm-tool/Program.cs
upm-tool/upm-tool/Program.cs
using System; namespace upmtool { class MainClass { public static void Main (string[] args) { Console.WriteLine ("Hello World!"); } } }
using System; namespace upmtool { class MainClass { public static void Main (string[] args) { Console.WriteLine ("Hello World!"); foreach (var packageName in GithubPackagesStore.GetPackages ()) { Console.WriteLine (packageName); } } } }
mit
C#
e242bec84f34de58c7038f67b9e01a51c1fa53d9
Make the duplicate addition more robust in Dictionary
alphonsekurian/corefx,ViktorHofer/corefx,kkurni/corefx,dotnet-bot/corefx,Chrisboh/corefx,ptoonen/corefx,dotnet-bot/corefx,cartermp/corefx,weltkante/corefx,JosephTremoulet/corefx,marksmeltzer/corefx,parjong/corefx,stone-li/corefx,richlander/corefx,rahku/corefx,kkurni/corefx,benjamin-bader/corefx,nchikanov/corefx,weltkante/corefx,shmao/corefx,wtgodbe/corefx,rahku/corefx,yizhang82/corefx,Chrisboh/corefx,ellismg/corefx,Ermiar/corefx,tijoytom/corefx,elijah6/corefx,gkhanna79/corefx,the-dwyer/corefx,gkhanna79/corefx,khdang/corefx,YoupHulsebos/corefx,tstringer/corefx,gkhanna79/corefx,shahid-pk/corefx,rjxby/corefx,yizhang82/corefx,seanshpark/corefx,fgreinacher/corefx,dhoehna/corefx,krk/corefx,krk/corefx,elijah6/corefx,elijah6/corefx,wtgodbe/corefx,Ermiar/corefx,jcme/corefx,shahid-pk/corefx,JosephTremoulet/corefx,ravimeda/corefx,ravimeda/corefx,mmitche/corefx,ellismg/corefx,ellismg/corefx,rjxby/corefx,jhendrixMSFT/corefx,lggomez/corefx,mafiya69/corefx,cydhaselton/corefx,cydhaselton/corefx,pallavit/corefx,benpye/corefx,seanshpark/corefx,alphonsekurian/corefx,MaggieTsang/corefx,mmitche/corefx,dotnet-bot/corefx,mokchhya/corefx,janhenke/corefx,Jiayili1/corefx,krk/corefx,rjxby/corefx,kkurni/corefx,pallavit/corefx,mokchhya/corefx,richlander/corefx,ptoonen/corefx,axelheer/corefx,wtgodbe/corefx,adamralph/corefx,krytarowski/corefx,jlin177/corefx,ellismg/corefx,ptoonen/corefx,wtgodbe/corefx,shahid-pk/corefx,pallavit/corefx,mazong1123/corefx,mafiya69/corefx,billwert/corefx,ravimeda/corefx,janhenke/corefx,Jiayili1/corefx,mokchhya/corefx,ptoonen/corefx,manu-silicon/corefx,stephenmichaelf/corefx,rubo/corefx,the-dwyer/corefx,kkurni/corefx,ravimeda/corefx,yizhang82/corefx,cartermp/corefx,stone-li/corefx,manu-silicon/corefx,jhendrixMSFT/corefx,seanshpark/corefx,dsplaisted/corefx,stone-li/corefx,YoupHulsebos/corefx,alexperovich/corefx,iamjasonp/corefx,shahid-pk/corefx,MaggieTsang/corefx,jlin177/corefx,wtgodbe/corefx,rahku/corefx,benjamin-bader/corefx,alphonsekurian/corefx,iamjasonp/corefx,elijah6/corefx,jlin177/corefx,shimingsg/corefx,ViktorHofer/corefx,krk/corefx,the-dwyer/corefx,DnlHarvey/corefx,richlander/corefx,twsouthwick/corefx,benjamin-bader/corefx,Priya91/corefx-1,mazong1123/corefx,nbarbettini/corefx,fgreinacher/corefx,tstringer/corefx,ericstj/corefx,mazong1123/corefx,richlander/corefx,pallavit/corefx,marksmeltzer/corefx,rubo/corefx,DnlHarvey/corefx,MaggieTsang/corefx,seanshpark/corefx,shahid-pk/corefx,stephenmichaelf/corefx,mmitche/corefx,ptoonen/corefx,lggomez/corefx,SGuyGe/corefx,alphonsekurian/corefx,richlander/corefx,alphonsekurian/corefx,ericstj/corefx,jcme/corefx,YoupHulsebos/corefx,yizhang82/corefx,billwert/corefx,cartermp/corefx,iamjasonp/corefx,alexperovich/corefx,YoupHulsebos/corefx,benpye/corefx,yizhang82/corefx,cartermp/corefx,nbarbettini/corefx,adamralph/corefx,nchikanov/corefx,tstringer/corefx,mafiya69/corefx,dhoehna/corefx,alexperovich/corefx,parjong/corefx,weltkante/corefx,gkhanna79/corefx,shmao/corefx,zhenlan/corefx,the-dwyer/corefx,janhenke/corefx,jcme/corefx,mokchhya/corefx,twsouthwick/corefx,ravimeda/corefx,cydhaselton/corefx,jcme/corefx,axelheer/corefx,lggomez/corefx,YoupHulsebos/corefx,nchikanov/corefx,SGuyGe/corefx,MaggieTsang/corefx,wtgodbe/corefx,BrennanConroy/corefx,jcme/corefx,mazong1123/corefx,marksmeltzer/corefx,gkhanna79/corefx,parjong/corefx,krytarowski/corefx,weltkante/corefx,krk/corefx,MaggieTsang/corefx,rubo/corefx,twsouthwick/corefx,Jiayili1/corefx,cartermp/corefx,shmao/corefx,Petermarcu/corefx,Chrisboh/corefx,seanshpark/corefx,jhendrixMSFT/corefx,seanshpark/corefx,khdang/corefx,lggomez/corefx,manu-silicon/corefx,cydhaselton/corefx,mmitche/corefx,khdang/corefx,weltkante/corefx,manu-silicon/corefx,YoupHulsebos/corefx,ViktorHofer/corefx,marksmeltzer/corefx,DnlHarvey/corefx,nbarbettini/corefx,shimingsg/corefx,alphonsekurian/corefx,dotnet-bot/corefx,tijoytom/corefx,stone-li/corefx,pallavit/corefx,axelheer/corefx,khdang/corefx,cartermp/corefx,Priya91/corefx-1,jcme/corefx,mafiya69/corefx,weltkante/corefx,jhendrixMSFT/corefx,shmao/corefx,cydhaselton/corefx,fgreinacher/corefx,lggomez/corefx,tstringer/corefx,ViktorHofer/corefx,tijoytom/corefx,the-dwyer/corefx,Jiayili1/corefx,mmitche/corefx,gkhanna79/corefx,Priya91/corefx-1,mokchhya/corefx,manu-silicon/corefx,nchikanov/corefx,axelheer/corefx,Petermarcu/corefx,mafiya69/corefx,shimingsg/corefx,shimingsg/corefx,Petermarcu/corefx,Jiayili1/corefx,alphonsekurian/corefx,jlin177/corefx,nbarbettini/corefx,krk/corefx,marksmeltzer/corefx,lggomez/corefx,shimingsg/corefx,rahku/corefx,MaggieTsang/corefx,ericstj/corefx,DnlHarvey/corefx,yizhang82/corefx,mafiya69/corefx,tijoytom/corefx,ericstj/corefx,janhenke/corefx,dsplaisted/corefx,Ermiar/corefx,iamjasonp/corefx,nbarbettini/corefx,the-dwyer/corefx,parjong/corefx,shimingsg/corefx,benjamin-bader/corefx,mazong1123/corefx,dhoehna/corefx,alexperovich/corefx,DnlHarvey/corefx,seanshpark/corefx,billwert/corefx,nchikanov/corefx,marksmeltzer/corefx,the-dwyer/corefx,billwert/corefx,yizhang82/corefx,Ermiar/corefx,billwert/corefx,dhoehna/corefx,JosephTremoulet/corefx,JosephTremoulet/corefx,tstringer/corefx,DnlHarvey/corefx,jhendrixMSFT/corefx,richlander/corefx,stephenmichaelf/corefx,tstringer/corefx,iamjasonp/corefx,jhendrixMSFT/corefx,zhenlan/corefx,iamjasonp/corefx,wtgodbe/corefx,twsouthwick/corefx,dotnet-bot/corefx,stone-li/corefx,krytarowski/corefx,zhenlan/corefx,dhoehna/corefx,Priya91/corefx-1,shmao/corefx,pallavit/corefx,ellismg/corefx,gkhanna79/corefx,stone-li/corefx,ellismg/corefx,dsplaisted/corefx,billwert/corefx,DnlHarvey/corefx,Chrisboh/corefx,JosephTremoulet/corefx,ericstj/corefx,manu-silicon/corefx,stephenmichaelf/corefx,jlin177/corefx,janhenke/corefx,janhenke/corefx,fgreinacher/corefx,BrennanConroy/corefx,stephenmichaelf/corefx,ViktorHofer/corefx,tijoytom/corefx,twsouthwick/corefx,SGuyGe/corefx,elijah6/corefx,SGuyGe/corefx,richlander/corefx,ptoonen/corefx,Chrisboh/corefx,mazong1123/corefx,krk/corefx,ravimeda/corefx,kkurni/corefx,marksmeltzer/corefx,khdang/corefx,shmao/corefx,benpye/corefx,benjamin-bader/corefx,ViktorHofer/corefx,elijah6/corefx,krytarowski/corefx,nbarbettini/corefx,cydhaselton/corefx,Jiayili1/corefx,benpye/corefx,rahku/corefx,rahku/corefx,iamjasonp/corefx,Petermarcu/corefx,Petermarcu/corefx,ravimeda/corefx,alexperovich/corefx,zhenlan/corefx,mokchhya/corefx,zhenlan/corefx,rjxby/corefx,Chrisboh/corefx,nchikanov/corefx,rjxby/corefx,adamralph/corefx,zhenlan/corefx,jlin177/corefx,jhendrixMSFT/corefx,rjxby/corefx,weltkante/corefx,Ermiar/corefx,Petermarcu/corefx,MaggieTsang/corefx,twsouthwick/corefx,axelheer/corefx,mazong1123/corefx,cydhaselton/corefx,parjong/corefx,benpye/corefx,stephenmichaelf/corefx,alexperovich/corefx,benpye/corefx,rahku/corefx,elijah6/corefx,Ermiar/corefx,Jiayili1/corefx,parjong/corefx,BrennanConroy/corefx,ptoonen/corefx,Ermiar/corefx,manu-silicon/corefx,ericstj/corefx,shahid-pk/corefx,JosephTremoulet/corefx,tijoytom/corefx,Priya91/corefx-1,kkurni/corefx,nchikanov/corefx,benjamin-bader/corefx,zhenlan/corefx,alexperovich/corefx,Priya91/corefx-1,jlin177/corefx,parjong/corefx,Petermarcu/corefx,dhoehna/corefx,nbarbettini/corefx,dotnet-bot/corefx,shimingsg/corefx,JosephTremoulet/corefx,dotnet-bot/corefx,shmao/corefx,stephenmichaelf/corefx,ViktorHofer/corefx,axelheer/corefx,dhoehna/corefx,SGuyGe/corefx,stone-li/corefx,ericstj/corefx,khdang/corefx,lggomez/corefx,rjxby/corefx,rubo/corefx,billwert/corefx,SGuyGe/corefx,twsouthwick/corefx,krytarowski/corefx,rubo/corefx,tijoytom/corefx,mmitche/corefx,krytarowski/corefx,krytarowski/corefx,mmitche/corefx,YoupHulsebos/corefx
src/System.Data.Common/src/System/Data/Common/DbColumn.cs
src/System.Data.Common/src/System/Data/Common/DbColumn.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace System.Data.Common { public class DbColumn { private readonly Dictionary<string, object> _customValues = new Dictionary<string, object>(); public virtual bool AllowDBNull { get; set; } public virtual string BaseCatalogName { get; set; } public virtual string BaseColumnName { get; set; } public virtual string BaseSchemaName { get; set; } public virtual string BaseServerName { get; set; } public virtual string BaseTableName { get; set; } public virtual string ColumnName { get; set; } public virtual int ColumnOrdinal { get; set; } public virtual int ColumnSize { get; set; } public virtual bool IsAliased { get; set; } public virtual bool IsAutoIncrement { get; set; } public virtual bool IsExpression { get; set; } public virtual bool IsHidden { get; set; } public virtual bool IsIdentity { get; set; } public virtual bool IsKey { get; set; } public virtual bool IsLong { get; set; } public virtual bool IsReadOnly { get; set; } public virtual bool IsUnique { get; set; } public virtual int NumericPrecision { get; set; } public virtual int NumericScale { get; set; } public virtual string UdtAssemblyQualifiedName { get; set; } public virtual Type DataType { get; set; } public virtual string DataTypeName { get; set; } public virtual object this[string property] { get { object value; _customValues.TryGetValue(property, out value); return value; } set { _customValues[property] = value; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace System.Data.Common { public class DbColumn { private readonly Dictionary<string, object> _customValues = new Dictionary<string, object>(); public virtual bool AllowDBNull { get; set; } public virtual string BaseCatalogName { get; set; } public virtual string BaseColumnName { get; set; } public virtual string BaseSchemaName { get; set; } public virtual string BaseServerName { get; set; } public virtual string BaseTableName { get; set; } public virtual string ColumnName { get; set; } public virtual int ColumnOrdinal { get; set; } public virtual int ColumnSize { get; set; } public virtual bool IsAliased { get; set; } public virtual bool IsAutoIncrement { get; set; } public virtual bool IsExpression { get; set; } public virtual bool IsHidden { get; set; } public virtual bool IsIdentity { get; set; } public virtual bool IsKey { get; set; } public virtual bool IsLong { get; set; } public virtual bool IsReadOnly { get; set; } public virtual bool IsUnique { get; set; } public virtual int NumericPrecision { get; set; } public virtual int NumericScale { get; set; } public virtual string UdtAssemblyQualifiedName { get; set; } public virtual Type DataType { get; set; } public virtual string DataTypeName { get; set; } public virtual object this[string property] { get { object value; _customValues.TryGetValue(property, out value); return value; } set { _customValues.Add(property, value); } } } }
mit
C#
8690c319ab47b9ea5216be65f1e3f5f1dd9a8351
Disable metrics collection in OWIN Autofac sample
SteelToeOSS/Samples,SteelToeOSS/Samples,SteelToeOSS/Samples,SteelToeOSS/Samples
Management/src/AspDotNet4/CloudFoundryOwinAutofac/Global.asax.cs
Management/src/AspDotNet4/CloudFoundryOwinAutofac/Global.asax.cs
using Autofac; using Autofac.Integration.Mvc; using Steeltoe.CloudFoundry.ConnectorAutofac; using Steeltoe.Common.Configuration.Autofac; using Steeltoe.Extensions.Configuration.CloudFoundry; using Steeltoe.Management.EndpointAutofac; using Steeltoe.Management.EndpointAutofac.Actuators; using System; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; namespace CloudFoundryOwinAutofac { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); ApplicationConfig.Register("development"); ApplicationConfig.ConfigureLogging(); var builder = new ContainerBuilder(); // Register all the controllers with Autofac builder.RegisterControllers(typeof(Global).Assembly); builder.RegisterCloudFoundryOptions(ApplicationConfig.Configuration); builder.RegisterConfiguration(ApplicationConfig.Configuration); builder.RegisterMySqlConnection(ApplicationConfig.Configuration); builder.RegisterCloudFoundryActuators(ApplicationConfig.Configuration); // Uncomment if you want to enable metrics actuator endpoint, it's not enabled by default // builder.RegisterMetricsActuator(ApplicationConfig.Configuration); // Uncomment if you want to enable exporting of metrics to PCF Metrics, it's not enabled by default // builder.RegisterMetricsForwarderExporter(ApplicationConfig.Configuration); var container = ApplicationConfig.Container = builder.Build(); container.StartActuators(); // Uncomment if you want to enable exporting of metrics to the Cloud Foundry metrics exporter, it's not enabled by default // container.StartMetricsExporter(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
using Autofac; using Autofac.Integration.Mvc; using Steeltoe.CloudFoundry.ConnectorAutofac; using Steeltoe.Common.Configuration.Autofac; using Steeltoe.Extensions.Configuration.CloudFoundry; using Steeltoe.Management.EndpointAutofac; using Steeltoe.Management.EndpointAutofac.Actuators; using System; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Routing; namespace CloudFoundryOwinAutofac { public class Global : HttpApplication { void Application_Start(object sender, EventArgs e) { // Code that runs on application startup AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); RouteConfig.RegisterRoutes(RouteTable.Routes); ApplicationConfig.Register("development"); ApplicationConfig.ConfigureLogging(); var builder = new ContainerBuilder(); // Register all the controllers with Autofac builder.RegisterControllers(typeof(Global).Assembly); builder.RegisterCloudFoundryOptions(ApplicationConfig.Configuration); builder.RegisterConfiguration(ApplicationConfig.Configuration); builder.RegisterMySqlConnection(ApplicationConfig.Configuration); builder.RegisterCloudFoundryActuators(ApplicationConfig.Configuration); // Uncomment if you want to enable metrics actuator endpoint, it's not enabled by default builder.RegisterMetricsActuator(ApplicationConfig.Configuration); // Uncomment if you want to enable exporting of metrics to PCF Metrics, it's not enabled by default builder.RegisterMetricsForwarderExporter(ApplicationConfig.Configuration); var container = ApplicationConfig.Container = builder.Build(); container.StartActuators(); // Uncomment if you want to enable exporting of metrics to the Cloud Foundry metrics exporter, it's not enabled by default container.StartMetricsExporter(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); } } }
apache-2.0
C#
ee500b7b58e26d862f0e455d73af34366695a9a7
Call GetBaseException instead of manually unwrapping exception types.
OneGet/nuget,xoofx/NuGet,chocolatey/nuget-chocolatey,jholovacs/NuGet,ctaggart/nuget,jmezach/NuGet2,xero-github/Nuget,themotleyfool/NuGet,oliver-feng/nuget,oliver-feng/nuget,alluran/node.net,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,mrward/nuget,antiufo/NuGet2,anurse/NuGet,ctaggart/nuget,rikoe/nuget,dolkensp/node.net,RichiCoder1/nuget-chocolatey,GearedToWar/NuGet2,indsoft/NuGet2,RichiCoder1/nuget-chocolatey,GearedToWar/NuGet2,zskullz/nuget,mono/nuget,GearedToWar/NuGet2,rikoe/nuget,indsoft/NuGet2,oliver-feng/nuget,RichiCoder1/nuget-chocolatey,mrward/nuget,antiufo/NuGet2,xoofx/NuGet,jmezach/NuGet2,ctaggart/nuget,pratikkagda/nuget,pratikkagda/nuget,alluran/node.net,antiufo/NuGet2,akrisiun/NuGet,zskullz/nuget,oliver-feng/nuget,GearedToWar/NuGet2,atheken/nuget,indsoft/NuGet2,chocolatey/nuget-chocolatey,pratikkagda/nuget,dolkensp/node.net,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,jmezach/NuGet2,mrward/nuget,chester89/nugetApi,chocolatey/nuget-chocolatey,mono/nuget,jholovacs/NuGet,kumavis/NuGet,chester89/nugetApi,jmezach/NuGet2,indsoft/NuGet2,kumavis/NuGet,themotleyfool/NuGet,jholovacs/NuGet,mono/nuget,mrward/nuget,dolkensp/node.net,oliver-feng/nuget,mrward/NuGet.V2,OneGet/nuget,GearedToWar/NuGet2,mrward/NuGet.V2,xoofx/NuGet,zskullz/nuget,pratikkagda/nuget,themotleyfool/NuGet,anurse/NuGet,mrward/NuGet.V2,rikoe/nuget,pratikkagda/nuget,mrward/NuGet.V2,indsoft/NuGet2,oliver-feng/nuget,mrward/NuGet.V2,indsoft/NuGet2,OneGet/nuget,GearedToWar/NuGet2,ctaggart/nuget,antiufo/NuGet2,dolkensp/node.net,antiufo/NuGet2,alluran/node.net,antiufo/NuGet2,xoofx/NuGet,atheken/nuget,jholovacs/NuGet,mrward/nuget,xoofx/NuGet,chocolatey/nuget-chocolatey,zskullz/nuget,xoofx/NuGet,akrisiun/NuGet,pratikkagda/nuget,mrward/nuget,jmezach/NuGet2,jholovacs/NuGet,OneGet/nuget,alluran/node.net,rikoe/nuget,jholovacs/NuGet,mono/nuget,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,jmezach/NuGet2
src/Core/Utility/ExceptionUtility.cs
src/Core/Utility/ExceptionUtility.cs
using System; using System.Reflection; namespace NuGet { public static class ExceptionUtility { public static Exception Unwrap(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (exception.InnerException == null) { return exception; } // Always return the inner exception from a target invocation exception if (exception is AggregateException || exception is TargetInvocationException) { return exception.GetBaseException(); } return exception; } } }
using System; using System.Reflection; namespace NuGet { public static class ExceptionUtility { public static Exception Unwrap(Exception exception) { if (exception == null) { throw new ArgumentNullException("exception"); } if (exception.InnerException == null) { return exception; } // Always return the inner exception from a target invocation exception if (exception.GetType() == typeof(TargetInvocationException)) { return exception.InnerException; } // Flatten the aggregate before getting the inner exception if (exception.GetType() == typeof(AggregateException)) { return ((AggregateException)exception).Flatten().InnerException; } return exception; } } }
apache-2.0
C#
11ac0abf8fe4aa822076ee8d76287577660ffa94
fix incorrect condition for OpenSubkey
dwmkerr/sharpshell,dwmkerr/sharpshell,dwmkerr/sharpshell,dwmkerr/sharpshell
SharpShell/SharpShell.Tests/Registry/InMemoryRegistryKeyTests.cs
SharpShell/SharpShell.Tests/Registry/InMemoryRegistryKeyTests.cs
using System; using Microsoft.Win32; using NUnit.Framework; using SharpShell.Registry; namespace SharpShell.Tests.Registry { public class InMemoryRegistryKeyTests { [Test] public void Can_Get_And_Set_Default_Values() { // Bounce a default value, which has slightly different treatment in the code. var registry = new InMemoryRegistry(); using (var key = registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { key.SetValue(null, @"Default"); Assert.That(key.GetValue(null), Is.EqualTo(@"Default")); Assert.That(key.GetValue(null, "(This is used if missing)"), Is.EqualTo(@"Default")); } } [Test] public void Open_SubKey_Returns_Null_For_Missing_Keys() { var registry = new InMemoryRegistry(); using (var key = registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { var subkey = key.OpenSubKey("Missing"); Assert.That(subkey, Is.Null); } } [Test] public void Can_Create_Deep_SubKey() { var registry = new InMemoryRegistry(); using (var key = registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { var subkey = key.OpenSubKey(@"Deep\Subkey"); Assert.That(subkey, Is.Null); } } } }
using System; using Microsoft.Win32; using NUnit.Framework; using SharpShell.Registry; namespace SharpShell.Tests.Registry { public class InMemoryRegistryKeyTests { [Test] public void Can_Get_And_Set_Default_Values() { // Bounce a default value, which has slightly different treatment in the code. var registry = new InMemoryRegistry(); using (var key = registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { key.SetValue(null, @"Default"); Assert.That(key.GetValue(null), Is.EqualTo(@"Default")); Assert.That(key.GetValue(null, "(This is used if missing)"), Is.EqualTo(@"Default")); } } [Test] public void Open_SubKey_Returns_Null_For_Missing_Keys() { var registry = new InMemoryRegistry(); using (var key = registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { var subkey = key.OpenSubKey("Missing"); Assert.That(subkey, Is.Null); } } [Test] public void Can_Create_Deep_SubKey() { var registry = new InMemoryRegistry(); using (var key = registry.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Registry64)) { var subkey = key.CreateSubKey(@"Deep\Subkey"); Assert.That(subkey, Is.Null); } } } }
mit
C#
0f3640c4546fe8961fb40d046ee1ede6e7cd20bf
Fix good bard base race table tests
DnDGen/CharacterGen,DnDGen/CharacterGen
Tests/Integration/Tables/Races/BaseRaces/Good/GoodBardBaseRacesTests.cs
Tests/Integration/Tables/Races/BaseRaces/Good/GoodBardBaseRacesTests.cs
using System; using NPCGen.Common.Races; using NUnit.Framework; namespace NPCGen.Tests.Integration.Tables.Races.BaseRaces.Good { [TestFixture] public class GoodBardBaseRacesTests : PercentileTests { protected override String tableName { get { return "GoodBardBaseRaces"; } } [TestCase(RaceConstants.BaseRaces.Aasimar, 1)] [TestCase(RaceConstants.BaseRaces.WildElf, 37)] [TestCase(RaceConstants.BaseRaces.WoodElf, 38)] [TestCase(RaceConstants.BaseRaces.ForestGnome, 39)] [TestCase(RaceConstants.BaseRaces.LightfootHalfling, 54)] [TestCase(RaceConstants.BaseRaces.DeepHalfling, 55)] [TestCase(RaceConstants.BaseRaces.Svirfneblin, 98)] public override void Percentile(String content, Int32 roll) { base.Percentile(content, roll); } [TestCase(RaceConstants.BaseRaces.HillDwarf, 2, 6)] [TestCase(RaceConstants.BaseRaces.GrayElf, 7, 11)] [TestCase(RaceConstants.BaseRaces.HighElf, 12, 36)] [TestCase(RaceConstants.BaseRaces.RockGnome, 40, 44)] [TestCase(RaceConstants.BaseRaces.HalfElf, 45, 53)] [TestCase(RaceConstants.BaseRaces.TallfellowHalfling, 56, 57)] [TestCase(RaceConstants.BaseRaces.Human, 58, 97)] [TestCase(EmptyContent, 99, 100)] public override void Percentile(String content, Int32 lower, Int32 upper) { base.Percentile(content, lower, upper); } } }
using System; using NPCGen.Common.Races; using NUnit.Framework; namespace NPCGen.Tests.Integration.Tables.Races.BaseRaces.Good { [TestFixture] public class GoodBardBaseRacesTests : PercentileTests { protected override String tableName { get { return "GoodBardBaseRaces"; } } [Test] public void GoodBardAasimarPercentile() { AssertPercentile(RaceConstants.BaseRaces.Aasimar, 1); } [Test] public void GoodBardHillDwarfPercentile() { AssertPercentile(RaceConstants.BaseRaces.HillDwarf, 2, 6); } [Test] public void GoodBardGrayElfPercentile() { AssertPercentile(RaceConstants.BaseRaces.GrayElf, 7, 11); } [Test] public void GoodBardHighElfPercentile() { AssertPercentile(RaceConstants.BaseRaces.HighElf, 12, 36); } [Test] public void GoodBardWildElfPercentile() { AssertPercentile(RaceConstants.BaseRaces.WildElf, 37); } [Test] public void GoodBardWoodElfPercentile() { AssertPercentile(RaceConstants.BaseRaces.WoodElf, 38); } [Test] public void GoodBardForestGnomePercentile() { AssertPercentile(RaceConstants.BaseRaces.ForestGnome, 39); } [Test] public void GoodBardRockGnomePercentile() { AssertPercentile(RaceConstants.BaseRaces.RockGnome, 40, 44); } [Test] public void GoodBardHalfElfPercentile() { AssertPercentile(RaceConstants.BaseRaces.HalfElf, 45, 53); } [Test] public void GoodBardLightfootHalflingPercentile() { AssertPercentile(RaceConstants.BaseRaces.LightfootHalfling, 54); } [Test] public void GoodBardDeepHalflingPercentile() { AssertPercentile(RaceConstants.BaseRaces.DeepHalfling, 55); } [Test] public void GoodBardTallfellowHalflingPercentile() { AssertPercentile(RaceConstants.BaseRaces.TallfellowHalfling, 56, 57); } [Test] public void GoodBardHumanPercentile() { AssertPercentile(RaceConstants.BaseRaces.Human, 58, 97); } [Test] public void GoodBardSvirfneblinPercentile() { AssertPercentile(RaceConstants.BaseRaces.Svirfneblin, 98); } [Test] public void GoodBardEmptyPercentile() { AssertPercentile(EmptyContent, 99, 100); } } }
mit
C#
571fa547a1e11499b15b17e7af59f0a28b945a9c
remove sort mode option
rafaelalmeidatk/MonoGame.Extended,HyperionMT/MonoGame.Extended,Aurioch/MonoGame.Extended,LithiumToast/MonoGame.Extended,rafaelalmeidatk/MonoGame.Extended,cra0zy/MonoGame.Extended
Source/MonoGame.Extended/Graphics/Batching/BatchSortMode.cs
Source/MonoGame.Extended/Graphics/Batching/BatchSortMode.cs
namespace MonoGame.Extended.Graphics.Batching { public enum BatchSortMode { Immediate, Deferred } }
namespace MonoGame.Extended.Graphics.Batching { public enum BatchSortMode { Immediate, Deferred, DrawContext } }
mit
C#
3d0715a641c9dad506a0f133c9904be2b0e8f0a6
Make variable getter and setter not need var prefix
NitorInc/NitoriWare,Barleytree/NitoriWare,plrusek/NitoriWare,NitorInc/NitoriWare,uulltt/NitoriWare,Barleytree/NitoriWare
Assets/Scripts/Helper/TextHelper.cs
Assets/Scripts/Helper/TextHelper.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System.Text.RegularExpressions; public class TextHelper { private static Dictionary<string, string> variables; /// <summary> /// Gets localized text and checks for redundancies, use this for most purposes, prefix key with "var." to access a variable /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> public static string getLocalizedText(string key, string defaultValue) { if (key.StartsWith("var.")) return getVariable("var." + key, defaultValue); return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValue(key, defaultValue); } /// <summary> /// Gets localized text with prefix "microgame.[ID]," added automatically /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string getLocalizedMicrogameText(string key, string defaultValue) { Scene scene = MicrogameController.instance.gameObject.scene; return getLocalizedText("microgame." + scene.name.Substring(0, scene.name.Length - 1) + "." + key, defaultValue); } /// <summary> /// Returns the text without displaying warnings when a key isn't found, for debug purposes /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string getLocalizedTextNoWarnings(string key, string defaultValue) { return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValueNoWarnings(key, defaultValue); } /// <summary> /// Replaces all instances of text formatted "{key}" with their appropriate values, works with variables /// </summary> /// <param name="text"></param> /// <returns></returns> public static string fillInParameters(string text) { if (variables == null) variables = new Dictionary<string, string>(); int tries = 100; while (true) { string match = Regex.Match(text, @"\{[\w\.]+\}").ToString(); if (!string.IsNullOrEmpty(match) && tries > 0) { match = match.Replace("{", "").Replace("}", ""); if (match.StartsWith("var.")) text = text.Replace("{" + match + "}", getVariable("var." + match, "(TEXT NOT FOUND)")); else text = text.Replace("{" + match + "}", getLocalizedText(match, "(TEXT NOT FOUND)")); } else break; tries--; } return text; } /// <summary> /// Sets text variable for given key, value can contain key or variable parameters formatted "{key}" /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void setVariable(string key, string value) { if (!key.StartsWith("var.")) key = "var." + key; if (variables.ContainsKey(key)) variables[key] = value; else variables.Add(key, value); } // Returns the text variable with the given key private static string getVariable(string key, string defaultValue) { if (!key.StartsWith("var.")) key = "var." + key; return fillInParameters(variables.ContainsKey(key) ? variables[key] : defaultValue); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using System.Text.RegularExpressions; public class TextHelper { private static Dictionary<string, string> variables; /// <summary> /// Gets localized text and checks for redundancies, use this for most purposes /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> public static string getLocalizedText(string key, string defaultValue) { if (key.StartsWith("var.")) return getVariable(key, defaultValue); return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValue(key, defaultValue); } /// <summary> /// Gets localized text with prefix "microgame.[ID]," added automatically /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string getLocalizedMicrogameText(string key, string defaultValue) { Scene scene = MicrogameController.instance.gameObject.scene; return getLocalizedText("microgame." + scene.name.Substring(0, scene.name.Length - 1) + "." + key, defaultValue); } /// <summary> /// Returns the text without displaying warnings when a key isn't found, for debug purpose /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string getLocalizedTextNoWarnings(string key, string defaultValue) { return LocalizationManager.instance == null ? defaultValue : LocalizationManager.instance.getLocalizedValueNoWarnings(key, defaultValue); } /// <summary> /// Replaces all instances of text formatted {key} with their appropriate values, works with variables /// </summary> /// <param name="text"></param> /// <returns></returns> public static string fillInParameters(string text) { if (variables == null) variables = new Dictionary<string, string>(); int tries = 100; while (true) { string match = Regex.Match(text, @"\{[\w\.]+\}").ToString(); if (!string.IsNullOrEmpty(match) && tries > 0) { match = match.Replace("{", "").Replace("}", ""); if (match.StartsWith("var.")) text = text.Replace("{" + match + "}", getVariable(match, "(TEXT NOT FOUND)")); else text = text.Replace("{" + match + "}", getLocalizedText(match, "(TEXT NOT FOUND)")); } else break; tries--; } return text; } public static void setVariable(string key, string value) { if (variables.ContainsKey(key)) variables[key] = value; else variables.Add(key, value); } /// <summary> /// Returns the text variable with the given key, must be set beforehand or els the default value will be returned. Can contain key parameters formatted {key} /// </summary> /// <param name="key"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static string getVariable(string key, string defaultValue) { return fillInParameters(variables.ContainsKey(key) ? variables[key] : defaultValue); } }
mit
C#
2919a05b7d8b5597f02554010036a20d732f6ef1
Fix view location paths
maximegelinas-cegepsth/GEC-strawberry-sass,maximegelinas-cegepsth/GEC-strawberry-sass
StrawberrySass/src/StrawberrySass/UI/UILocationExpander.cs
StrawberrySass/src/StrawberrySass/UI/UILocationExpander.cs
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Razor; namespace StrawberrySass.UI { public class UILocationExpander : IViewLocationExpander { public void PopulateValues(ViewLocationExpanderContext context) { } public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { return new[] { "~/UI/{1}/{0}.cshtml", "~/UI/Shared/{0}.cshtml" }; } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Razor; namespace StrawberrySass.UI { public class UILocationExpander : IViewLocationExpander { public void PopulateValues(ViewLocationExpanderContext context) { } public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { return new[] { "/UI/{1}/{0}.cshtml", "/UI/Shared/{0}.cshtml" }; } } }
mit
C#
b5e89e2f3b05418ec84197ce59ae5c2934675cef
Add additional testing to check for extra children in the future
peppy/osu,ppy/osu,2yangk23/osu,peppy/osu,DrabWeb/osu,smoogipoo/osu,EVAST9919/osu,DrabWeb/osu,UselessToucan/osu,EVAST9919/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,NeoAdonis/osu,DrabWeb/osu,smoogipoo/osu,2yangk23/osu,ppy/osu,ZLima12/osu,johnneijzen/osu,NeoAdonis/osu,peppy/osu-new,ZLima12/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,ppy/osu,johnneijzen/osu
osu.Game.Tests/Visual/TestCaseUpdateableBeatmapBackgroundSprite.cs
osu.Game.Tests/Visual/TestCaseUpdateableBeatmapBackgroundSprite.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osu.Game.Tests.Beatmaps.IO; namespace osu.Game.Tests.Visual { public class TestCaseUpdateableBeatmapBackgroundSprite : OsuTestCase { private TestUpdateableBeatmapBackgroundSprite backgroundSprite; [Resolved] private BeatmapManager beatmaps { get; set; } [BackgroundDependencyLoader] private void load(OsuGameBase osu, APIAccess api, RulesetStore rulesets) { Bindable<BeatmapInfo> beatmapBindable = new Bindable<BeatmapInfo>(); var imported = ImportBeatmapTest.LoadOszIntoOsu(osu); Child = backgroundSprite = new TestUpdateableBeatmapBackgroundSprite { RelativeSizeAxes = Axes.Both }; backgroundSprite.Beatmap.BindTo(beatmapBindable); var req = new GetBeatmapSetRequest(1); api.Queue(req); AddStep("load null beatmap", () => beatmapBindable.Value = null); AddWaitStep(20, "wait for transition..."); AddAssert("ensure only 1 child is present", () => backgroundSprite.ChildCount == 1); AddStep("load imported beatmap", () => beatmapBindable.Value = imported.Beatmaps.First()); AddWaitStep(20, "wait for transition..."); AddAssert("ensure only 1 child is present", () => backgroundSprite.ChildCount == 1); if (api.IsLoggedIn) { AddUntilStep(() => req.Result != null, "wait for api response"); AddStep("load online beatmap", () => beatmapBindable.Value = new BeatmapInfo { BeatmapSet = req.Result?.ToBeatmapSet(rulesets) }); AddWaitStep(20, "wait for transition..."); AddAssert("ensure only 1 child is present", () => backgroundSprite.ChildCount == 1); } else { AddStep("online (login first)", () => { }); } } private class TestUpdateableBeatmapBackgroundSprite : UpdateableBeatmapBackgroundSprite { public int ChildCount => InternalChildren.Count; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Linq; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Game.Beatmaps; using osu.Game.Beatmaps.Drawables; using osu.Game.Online.API; using osu.Game.Online.API.Requests; using osu.Game.Rulesets; using osu.Game.Tests.Beatmaps.IO; namespace osu.Game.Tests.Visual { public class TestCaseUpdateableBeatmapBackgroundSprite : OsuTestCase { private UpdateableBeatmapBackgroundSprite backgroundSprite; [Resolved] private BeatmapManager beatmaps { get; set; } [BackgroundDependencyLoader] private void load(OsuGameBase osu, APIAccess api, RulesetStore rulesets) { Bindable<BeatmapInfo> beatmapBindable = new Bindable<BeatmapInfo>(); var imported = ImportBeatmapTest.LoadOszIntoOsu(osu); Child = backgroundSprite = new UpdateableBeatmapBackgroundSprite { RelativeSizeAxes = Axes.Both }; backgroundSprite.Beatmap.BindTo(beatmapBindable); var req = new GetBeatmapSetRequest(1); api.Queue(req); AddStep("null", () => beatmapBindable.Value = null); AddStep("imported", () => beatmapBindable.Value = imported.Beatmaps.First()); if (api.IsLoggedIn) { AddUntilStep(() => req.Result != null, "wait for api response"); AddStep("online", () => beatmapBindable.Value = new BeatmapInfo { BeatmapSet = req.Result?.ToBeatmapSet(rulesets) }); } else { AddStep("online (login first)", () => { }); } } } }
mit
C#
41caf106b96365b9476c48d1b4723141d7dc2458
add basic test
tannergooding/roslyn,weltkante/roslyn,tannergooding/roslyn,aelij/roslyn,bartdesmet/roslyn,brettfo/roslyn,genlu/roslyn,genlu/roslyn,eriawan/roslyn,mavasani/roslyn,sharwell/roslyn,physhi/roslyn,jasonmalinowski/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,shyamnamboodiripad/roslyn,AmadeusW/roslyn,jmarolf/roslyn,jmarolf/roslyn,diryboy/roslyn,KevinRansom/roslyn,tmat/roslyn,AmadeusW/roslyn,dotnet/roslyn,heejaechang/roslyn,mgoertz-msft/roslyn,gafter/roslyn,tmat/roslyn,mavasani/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,aelij/roslyn,jmarolf/roslyn,tmat/roslyn,eriawan/roslyn,KevinRansom/roslyn,sharwell/roslyn,diryboy/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,gafter/roslyn,panopticoncentral/roslyn,AlekseyTs/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,stephentoub/roslyn,heejaechang/roslyn,dotnet/roslyn,mavasani/roslyn,dotnet/roslyn,wvdd007/roslyn,brettfo/roslyn,diryboy/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,brettfo/roslyn,stephentoub/roslyn,tannergooding/roslyn,genlu/roslyn,CyrusNajmabadi/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,physhi/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,gafter/roslyn,aelij/roslyn,weltkante/roslyn,wvdd007/roslyn,stephentoub/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,sharwell/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn
src/Analyzers/CSharp/Tests/ConvertNameOf/ConvertNameOfTests.cs
src/Analyzers/CSharp/Tests/ConvertNameOf/ConvertNameOfTests.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.ConvertNameOf; using Microsoft.CodeAnalysis.CSharp.CSharpConvertNameOfCodeFixProvider; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNameOf { public partial class ConvertNameOfTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpConvertNameOfDiagnosticAnalyzer(), new CSharpConvertNameOfCodeFixProvider()); [Fact] public async Task BasicType() { var text = @" class Test { void Method() { var typeName = [||]typeof(Test).Name; } } "; var expected = @" class Test { void Method() { var typeName = [||]nameof(Test); } } "; await TestInRegularAndScriptAsync(text, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.ConvertNameOf; using Microsoft.CodeAnalysis.CSharp.CSharpConvertNameOfCodeFixProvider; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNameOf { public partial class ConvertNameOfTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpConvertNameOfDiagnosticAnalyzer(), new CSharpConvertNameOfCodeFixProvider()); } }
mit
C#
6d1fbfeba28cb8ed3bf8fef2aaf32631d4ffc3a0
Allow export division info as vCard
roman-yagodin/R7.University,roman-yagodin/R7.University,roman-yagodin/R7.University
R7.University/entities/DivisionInfo.cs
R7.University/entities/DivisionInfo.cs
using System; using DotNetNuke.Data; using DotNetNuke.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; namespace R7.University { // More attributes for class: // Set caching for table: [Cacheable("R7.University_Divisions", CacheItemPriority.Default, 20)] // Explicit mapping declaration: [DeclareColumns] // More attributes for class properties: // Custom column name: [ColumnName("DivisionID")] // Explicit include column: [IncludeColumn] // Note: DAL 2 have no AutoJoin analogs from PetaPOCO at this time [TableName ("University_Divisions")] [PrimaryKey ("DivisionID", AutoIncrement = true)] public class DivisionInfo : EntityBase, IReferenceEntity { #region Fields #endregion /// <summary> /// Empty default cstor /// </summary> public DivisionInfo () { } #region IReferenceEntity implementation public string Title { get; set; } public string ShortTitle { get; set; } #endregion #region Properties public int DivisionID { get; set; } public int? ParentDivisionID { get; set; } public int? DivisionTermID { get; set; } public string HomePage { get; set; } public string WebSite { get; set; } public string Phone { get; set; } public string Fax { get; set; } public string Email { get; set; } public string SecondaryEmail { get; set; } public string Location { get; set; } public string WorkingHours { get; set; } #endregion [IgnoreColumn] public VCard VCard { get { var vcard = new VCard (); // org. name if (!string.IsNullOrWhiteSpace (Title)) vcard.OrganizationName = Title; // email if (!string.IsNullOrWhiteSpace (Email)) vcard.Emails.Add (Email); // secondary email if (!string.IsNullOrWhiteSpace (SecondaryEmail)) vcard.Emails.Add (SecondaryEmail); // phone if (!string.IsNullOrWhiteSpace(Phone)) vcard.Phones.Add (new VCardPhone () { Number = Phone, Type = VCardPhoneType.Work }); // fax if (!string.IsNullOrWhiteSpace(Fax)) vcard.Phones.Add (new VCardPhone () { Number = Fax, Type = VCardPhoneType.Fax }); // website if (!string.IsNullOrWhiteSpace (WebSite)) vcard.Url = WebSite; // location if (!string.IsNullOrWhiteSpace (Location)) // TODO: Add organization address vcard.DeliveryAddress = Location; // revision vcard.LastRevision = LastModifiedOnDate; return vcard; } } } }
using System; using DotNetNuke.Data; using DotNetNuke.ComponentModel.DataAnnotations; using DotNetNuke.Entities.Portals; using DotNetNuke.Entities.Users; namespace R7.University { // More attributes for class: // Set caching for table: [Cacheable("R7.University_Divisions", CacheItemPriority.Default, 20)] // Explicit mapping declaration: [DeclareColumns] // More attributes for class properties: // Custom column name: [ColumnName("DivisionID")] // Explicit include column: [IncludeColumn] // Note: DAL 2 have no AutoJoin analogs from PetaPOCO at this time [TableName ("University_Divisions")] [PrimaryKey ("DivisionID", AutoIncrement = true)] public class DivisionInfo : EntityBase, IReferenceEntity { #region Fields #endregion /// <summary> /// Empty default cstor /// </summary> public DivisionInfo () { } #region IReferenceEntity implementation public string Title { get; set; } public string ShortTitle { get; set; } #endregion #region Properties public int DivisionID { get; set; } public int? ParentDivisionID { get; set; } public int? DivisionTermID { get; set; } public string HomePage { get; set; } public string WebSite { get; set; } public string Phone { get; set; } public string Fax { get; set; } public string Email { get; set; } public string SecondaryEmail { get; set; } public string Location { get; set; } public string WorkingHours { get; set; } #endregion } }
agpl-3.0
C#
dec4382deda4777dca52e3b11946354f769703e9
Build fix
blebougge/Catel
src/Catel.MVVM/Catel.MVVM.Shared/Services/MessageService.sl.cs
src/Catel.MVVM/Catel.MVVM.Shared/Services/MessageService.sl.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MessageService.sl.cs" company="Catel development team"> // Copyright (c) 2008 - 2014 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if SL5 namespace Catel.Services { using System; using System.Threading.Tasks; using System.Windows; using Windows; public partial class MessageService { /// <summary> /// Shows the message box. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <param name="button">The button.</param> /// <param name="icon">The icon.</param> /// <returns>The message result.</returns> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> protected virtual Task<MessageResult> ShowMessageBox(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None) { Argument.IsNotNullOrWhitespace("message", message); var tcs = new TaskCompletionSource<MessageResult>(); _dispatcherService.BeginInvoke(() => { MessageBoxResult result; var messageBoxButton = TranslateMessageButton(button); result = MessageBox.Show(message, caption, messageBoxButton); tcs.SetResult(TranslateMessageBoxResult(result)); }); return tcs.Task; } } } #endif
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MessageService.sl.cs" company="Catel development team"> // Copyright (c) 2008 - 2014 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if SL5 namespace Catel.Services { using System; using System.Threading.Tasks; using System.Windows; public partial class MessageService { /// <summary> /// Shows the message box. /// </summary> /// <param name="message">The message.</param> /// <param name="caption">The caption.</param> /// <param name="button">The button.</param> /// <param name="icon">The icon.</param> /// <returns>The message result.</returns> /// <exception cref="ArgumentException">The <paramref name="message"/> is <c>null</c> or whitespace.</exception> protected virtual Task<MessageResult> ShowMessageBox(string message, string caption = "", MessageButton button = MessageButton.OK, MessageImage icon = MessageImage.None) { Argument.IsNotNullOrWhitespace("message", message); var tcs = new TaskCompletionSource<MessageResult>(); _dispatcherService.BeginInvoke(() => { MessageBoxResult result; var messageBoxButton = TranslateMessageButton(button); var messageBoxImage = TranslateMessageImage(icon); result = MessageBox.Show(message, caption, messageBoxButton, messageBoxImage); tcs.SetResult(TranslateMessageBoxResult(result)); }); return tcs.Task; } } } #endif
mit
C#
1254cb6f4df10a220248b28b35c902172207cd57
Add OperationWithExponentialBackoff flavor with return values.
gep13/GitVersion,ermshiperete/GitVersion,gep13/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,ermshiperete/GitVersion,GitTools/GitVersion,GitTools/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion
src/GitVersion.Core/Helpers/OperationWithExponentialBackoff.cs
src/GitVersion.Core/Helpers/OperationWithExponentialBackoff.cs
using System; using System.Collections.Generic; using System.Threading.Tasks; using GitVersion.Logging; namespace GitVersion.Helpers { internal class OperationWithExponentialBackoff<T> : OperationWithExponentialBackoff<T, bool> where T : Exception { public OperationWithExponentialBackoff(IThreadSleep threadSleep, ILog log, Action operation, int maxRetries = 5) : base(threadSleep, log, () => { operation(); return false; }, maxRetries) { } public new Task ExecuteAsync() { return base.ExecuteAsync(); } } internal class OperationWithExponentialBackoff<T, Result> where T : Exception { private readonly IThreadSleep threadSleep; private readonly ILog log; private readonly Func<Result> operation; private readonly int maxRetries; public OperationWithExponentialBackoff(IThreadSleep threadSleep, ILog log, Func<Result> operation, int maxRetries = 5) { if (maxRetries < 0) throw new ArgumentOutOfRangeException(nameof(maxRetries)); this.threadSleep = threadSleep ?? throw new ArgumentNullException(nameof(threadSleep)); this.log = log; this.operation = operation; this.maxRetries = maxRetries; } public async Task<Result> ExecuteAsync() { var exceptions = new List<Exception>(); var tries = 0; var sleepMSec = 500; while (tries <= maxRetries) { tries++; try { return operation(); } catch (T e) { exceptions.Add(e); if (tries > maxRetries) { throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions); } } log.Info($"Operation failed, retrying in {sleepMSec} milliseconds."); await threadSleep.SleepAsync(sleepMSec); sleepMSec *= 2; } return default; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using GitVersion.Logging; namespace GitVersion.Helpers { internal class OperationWithExponentialBackoff<T> where T : Exception { private readonly IThreadSleep threadSleep; private readonly ILog log; private readonly Action operation; private readonly int maxRetries; public OperationWithExponentialBackoff(IThreadSleep threadSleep, ILog log, Action operation, int maxRetries = 5) { if (maxRetries < 0) throw new ArgumentOutOfRangeException(nameof(maxRetries)); this.threadSleep = threadSleep ?? throw new ArgumentNullException(nameof(threadSleep)); this.log = log; this.operation = operation; this.maxRetries = maxRetries; } public async Task ExecuteAsync() { var exceptions = new List<Exception>(); var tries = 0; var sleepMSec = 500; while (tries <= maxRetries) { tries++; try { operation(); break; } catch (T e) { exceptions.Add(e); if (tries > maxRetries) { throw new AggregateException("Operation failed after maximum number of retries were exceeded.", exceptions); } } log.Info($"Operation failed, retrying in {sleepMSec} milliseconds."); await threadSleep.SleepAsync(sleepMSec); sleepMSec *= 2; } } } }
mit
C#
52e21ce384c1279fd0d4b7685e5cc40280aa7af5
make b2_authorize_account API use JSON-encoded request
NebulousConcept/b2-csharp-client
b2-csharp-client/B2.Client/Apis/AuthorizeAccountV1/AuthorizeAccountV1Request.cs
b2-csharp-client/B2.Client/Apis/AuthorizeAccountV1/AuthorizeAccountV1Request.cs
using System; using System.Text; using B2.Client.Rest.Request; using B2.Client.Rest.Request.Param; namespace B2.Client.Apis.AuthorizeAccountV1 { /// <summary> /// Request object for the 'b2_authorize_account' version 1 API. /// </summary> public sealed class AuthorizeAccountV1Request : JsonPostRestRequest { /// <summary> /// Create a new authorization request. /// </summary> /// <param name="accountId">The identifier of the B2 account.</param> /// <param name="accountKey">The application key to use for the specified account.</param> public AuthorizeAccountV1Request(string accountId, string accountKey) : base(UrlParams.Empty, new HeaderParams( RequiredParam.Of("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(accountId + ":" + accountKey))) ), BodyParams.Empty) { } } }
using System; using System.Text; using B2.Client.Rest.Request; using B2.Client.Rest.Request.Param; namespace B2.Client.Apis.AuthorizeAccountV1 { /// <summary> /// Request object for the 'b2_authorize_account' version 1 API. /// </summary> public sealed class AuthorizeAccountV1Request : MultipartPostRestRequest { /// <summary> /// Create a new authorization request. /// </summary> /// <param name="authorization">The authorization header value to use.</param> /// <param name="accountId">The identifier of the B2 account.</param> /// <param name="accountKey">The application key to use for the specified account.</param> public AuthorizeAccountV1Request(string accountId, string accountKey) : base(UrlParams.Empty, new HeaderParams( RequiredParam.Of("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(accountId + ":" + accountKey))) ), BodyParams.Empty, DataParams.Empty) { } } }
mit
C#
33cfed0ce98649ad6637ca84ccef474629481e64
Fix nullref that can occur if the serial devices change.
clough42/extron-matrix-touch,clough42/extron-matrix-touch,clough42/extron-matrix-touch
src/ExtronTouchSwitch/VidSwitch/Service/SerialPort.cs
src/ExtronTouchSwitch/VidSwitch/Service/SerialPort.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.SerialCommunication; using Windows.Storage.Streams; namespace VidSwitch.Service { class SerialPort { private string portName; private SerialDevice serialDevice; private DataWriter writer; public uint BaudRate { get; set; } public SerialPort(String portName) { this.portName = portName; } public async void Open() { this.serialDevice = await SerialDevice.FromIdAsync(this.portName); if (this.serialDevice != null) { this.serialDevice.BaudRate = this.BaudRate; this.serialDevice.DataBits = 8; this.serialDevice.StopBits = SerialStopBitCount.One; this.serialDevice.Parity = SerialParity.None; this.serialDevice.Handshake = SerialHandshake.None; this.writer = new DataWriter(serialDevice.OutputStream); } } public async void Write(String content) { if (this.serialDevice != null) { this.writer.WriteString(content); await this.writer.StoreAsync(); } } public void Close() { if( this.writer != null ) { this.writer.DetachStream(); this.writer.Dispose(); this.writer = null; } if (this.serialDevice != null) { this.serialDevice.Dispose(); this.serialDevice = null; } } public static async Task<string[]> GetPortNames() { List<string> idList = new List<string>(); var selector = SerialDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(selector); foreach (var device in devices) { idList.Add(device.Id); } return idList.ToArray(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Enumeration; using Windows.Devices.SerialCommunication; using Windows.Storage.Streams; namespace VidSwitch.Service { class SerialPort { private string portName; private SerialDevice serialDevice; private DataWriter writer; public uint BaudRate { get; set; } public SerialPort(String portName) { this.portName = portName; } public async void Open() { this.serialDevice = await SerialDevice.FromIdAsync(this.portName); this.serialDevice.BaudRate = this.BaudRate; this.serialDevice.DataBits = 8; this.serialDevice.StopBits = SerialStopBitCount.One; this.serialDevice.Parity = SerialParity.None; this.serialDevice.Handshake = SerialHandshake.None; this.writer = new DataWriter(serialDevice.OutputStream); } public async void Write(String content) { this.writer.WriteString(content); await this.writer.StoreAsync(); } public void Close() { if (this.serialDevice != null) { this.serialDevice.Dispose(); this.serialDevice = null; } } public static async Task<string[]> GetPortNames() { List<string> idList = new List<string>(); var selector = SerialDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(selector); foreach (var device in devices) { idList.Add(device.Id); } return idList.ToArray(); } } }
apache-2.0
C#
dde7e28f60ebc2282f6ea55b6ce42188183ea69a
Return value in Dump ext. method.
ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab,ashmind/SharpLab
source/Runtime/SharpLabObjectExtensions.cs
source/Runtime/SharpLabObjectExtensions.cs
using System.ComponentModel; using System.Text; using SharpLab.Runtime.Internal; public static class SharpLabObjectExtensions { // LinqPad/etc compatibility only [EditorBrowsable(EditorBrowsableState.Never)] public static T Dump<T>(this T value) { value.Inspect(title: "Dump"); return value; } public static void Inspect<T>(this T value, string title = "Inspect") { var builder = new StringBuilder(); ObjectAppender.Append(builder, value); var data = new SimpleInspectionResult(title, builder); Output.Write(data); } }
using System.ComponentModel; using System.Text; using SharpLab.Runtime.Internal; public static class SharpLabObjectExtensions { // LinqPad/etc compatibility only [EditorBrowsable(EditorBrowsableState.Never)] public static T Dump<T>(this T value) => value.Inspect(title: "Dump"); public static void Inspect<T>(this T value, string title = "Inspect") { var builder = new StringBuilder(); ObjectAppender.Append(builder, value); var data = new SimpleInspectionResult(title, builder); Output.Write(data); } }
bsd-2-clause
C#
86adf9e5f62f35391e60d36261fa37d3dbc13733
support default proxy
ElderByte-/Archimedes.Locco
Archimedes.Locco/BackendProviders/GitHubProvider.cs
Archimedes.Locco/BackendProviders/GitHubProvider.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Octokit; using Octokit.Internal; namespace Archimedes.Locco.BackendProviders { public class GitHubProvider : IReportBackend { private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); private readonly IPropertyProvider _propertyProvider; public GitHubProvider(IPropertyProvider propertyProvider) { _propertyProvider = propertyProvider; } public string IdName { get { return "github"; } } public async Task SendIssueReportAsync(IssueReport report) { var appId = _propertyProvider.GetProperty("locco.github.appId"); var accessToken = _propertyProvider.GetProperty("locco.github.token"); var repoOwner = _propertyProvider.GetProperty("locco.github.owner"); var repoName = _propertyProvider.GetProperty("locco.github.repository"); // Support default proxy var proxy = WebRequest.DefaultWebProxy; var httpClient = new HttpClientAdapter(() => HttpMessageHandlerFactory.CreateDefault(proxy)); var connection = new Connection(new ProductHeaderValue(appId), httpClient); if (proxy != null) { Log.Info(string.Format("Using proxy server '{0}' to connect to github!", proxy.GetProxy(new Uri("https://api.github.com/")))); } var client = new GitHubClient(connection) { Credentials = new Credentials(accessToken) }; // Creates a new GitHub Issue var newIssue = new NewIssue(report.Title) { Body = MarkdownReportUtil.CompileBodyMarkdown(report, 220000), }; newIssue.Labels.Add("bot"); var issue = await client.Issue.Create(repoOwner, repoName, newIssue); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Octokit; namespace Archimedes.Locco.BackendProviders { public class GitHubProvider : IReportBackend { private readonly IPropertyProvider _propertyProvider; public GitHubProvider(IPropertyProvider propertyProvider) { _propertyProvider = propertyProvider; } public string IdName { get { return "github"; } } public async Task SendIssueReportAsync(IssueReport report) { var appId = _propertyProvider.GetProperty("locco.github.appId"); var accessToken = _propertyProvider.GetProperty("locco.github.token"); var repoOwner = _propertyProvider.GetProperty("locco.github.owner"); var repoName = _propertyProvider.GetProperty("locco.github.repository"); var client = new GitHubClient(new ProductHeaderValue(appId)) { Credentials = new Credentials(accessToken) }; // Creates a new GitHub Issue var newIssue = new NewIssue(report.Title) { Body = MarkdownReportUtil.CompileBodyMarkdown(report, 220000), }; //newIssue.Labels.Add("locco"); var issue = await client.Issue.Create(repoOwner, repoName, newIssue); } } }
mit
C#
2dee9fe7753c8873f111e479baf100d0f6811e69
Allow overriding of locomotion implementation
mysticfall/Alensia
Assets/Alensia/Core/Locomotion/LocomotionControl.cs
Assets/Alensia/Core/Locomotion/LocomotionControl.cs
using Alensia.Core.Input; namespace Alensia.Core.Locomotion { public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T> where T : class, ILocomotion { public abstract T Locomotion { get; } public override bool Valid => base.Valid && Locomotion != null && Locomotion.Active; protected LocomotionControl(IInputManager inputManager) : base(inputManager) { } } }
using Alensia.Core.Input; using UnityEngine.Assertions; namespace Alensia.Core.Locomotion { public abstract class LocomotionControl<T> : Control.Control, ILocomotionControl<T> where T : class, ILocomotion { public T Locomotion { get; } public override bool Valid => base.Valid && Locomotion.Active; protected LocomotionControl(T locomotion, IInputManager inputManager) : base(inputManager) { Assert.IsNotNull(locomotion, "locomotion != null"); Locomotion = locomotion; } } }
apache-2.0
C#
d0550bc591d2aa90b2edad08557234a3e5b325fc
Check for email recipients before failing
mattgwagner/alert-roster
alert-roster.web/Models/EmailSender.cs
alert-roster.web/Models/EmailSender.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; namespace alert_roster.web.Models { public class EmailSender { public static String EmailSubject = ConfigurationManager.AppSettings["Email.Subject"]; public static String FromAddress = ConfigurationManager.AppSettings["Email.FromAddress"]; public static String SmtpServer = ConfigurationManager.AppSettings["MAILGUN_SMTP_SERVER"]; public static int SmtpPort = int.Parse(ConfigurationManager.AppSettings["MAILGUN_SMTP_PORT"]); public static String SmtpUser = ConfigurationManager.AppSettings["MAILGUN_SMTP_LOGIN"]; public static String SmtpPassword = ConfigurationManager.AppSettings["MAILGUN_SMTP_PASSWORD"]; public static Boolean EnableSsl = true; public static Boolean IsBodyHtml = false; public void Send(String content) { using (var db = new AlertRosterDbContext()) using (var smtp = new SmtpClient { Host = SmtpServer, Port = SmtpPort, EnableSsl = EnableSsl, Credentials = new NetworkCredential { UserName = SmtpUser, Password = SmtpPassword } }) using (var message = new MailMessage { IsBodyHtml = IsBodyHtml }) { var recipients = (from u in db.Users where u.EmailEnabled select u.EmailAddress); if (recipients.Any()) { message.From = new MailAddress(FromAddress); message.Subject = EmailSubject; foreach (var recipient in recipients) { message.Bcc.Add(new MailAddress(recipient)); } message.Body = content; smtp.Send(message); } } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; namespace alert_roster.web.Models { public class EmailSender { public static String EmailSubject = ConfigurationManager.AppSettings["Email.Subject"]; public static String FromAddress = ConfigurationManager.AppSettings["Email.FromAddress"]; public static String SmtpServer = ConfigurationManager.AppSettings["MAILGUN_SMTP_SERVER"]; public static int SmtpPort = int.Parse(ConfigurationManager.AppSettings["MAILGUN_SMTP_PORT"]); public static String SmtpUser = ConfigurationManager.AppSettings["MAILGUN_SMTP_LOGIN"]; public static String SmtpPassword = ConfigurationManager.AppSettings["MAILGUN_SMTP_PASSWORD"]; public static Boolean EnableSsl = true; public static Boolean IsBodyHtml = false; public void Send(String content) { using (var db = new AlertRosterDbContext()) using (var smtp = new SmtpClient { Host = SmtpServer, Port = SmtpPort, EnableSsl = EnableSsl, Credentials = new NetworkCredential { UserName = SmtpUser, Password = SmtpPassword } }) using (var message = new MailMessage { IsBodyHtml = IsBodyHtml }) { var recipients = from u in db.Users where u.EmailEnabled select u.EmailAddress; message.From = new MailAddress(FromAddress); message.Subject = EmailSubject; foreach (var recipient in recipients) { message.Bcc.Add(new MailAddress(recipient)); } message.Body = content; smtp.Send(message); } } } }
mit
C#
7acc6ae567902eaca53a6517cbad9151c10a84bd
Implement Map Point Tool Mouse events
Esri/visibility-addin-dotnet
source/ArcMapAddinVisibility/ArcMapAddinVisibility/MapPointTool.cs
source/ArcMapAddinVisibility/ArcMapAddinVisibility/MapPointTool.cs
using System; using System.Collections.Generic; using System.Text; using System.IO; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ArcMapAddinVisibility.Helpers; namespace ArcMapAddinVisibility { public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool { public MapPointTool() { } protected override void OnUpdate() { Enabled = ArcMap.Application != null; } protected override void OnMouseDown(ESRI.ArcGIS.Desktop.AddIns.Tool.MouseEventArgs arg) { if (arg.Button != System.Windows.Forms.MouseButtons.Left) return; try { //Get the active view from the ArcMap static class. IActiveView activeView = ArcMap.Document.FocusMap as IActiveView; var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint; Mediator.NotifyColleagues(Constants.NEW_MAP_POINT, point); } catch (Exception ex) { Console.WriteLine(ex.Message); } } protected override void OnMouseMove(MouseEventArgs arg) { IActiveView activeView = ArcMap.Document.FocusMap as IActiveView; var point = activeView.ScreenDisplay.DisplayTransformation.ToMapPoint(arg.X, arg.Y) as IPoint; Mediator.NotifyColleagues(Constants.MOUSE_MOVE_POINT, point); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace ArcMapAddinVisibility { public class MapPointTool : ESRI.ArcGIS.Desktop.AddIns.Tool { public MapPointTool() { } protected override void OnUpdate() { Enabled = ArcMap.Application != null; } } }
apache-2.0
C#
1dbb5830a85504fb85a7d9be9d1730c7dd36e1c0
Exclude AssemblyMetadataAttribute
SeanFeldman/ServiceBus.AttachmentPlugin
src/ServiceBus.AttachmentPlugin.Tests/ApiApprovals.cs
src/ServiceBus.AttachmentPlugin.Tests/ApiApprovals.cs
namespace ServiceBus.AttachmentPlugin.Tests { using PublicApiGenerator; using Xunit; public class ApiApprovals { [Fact] public void AzureStorageAttachmentPlugin() { var publicApi = typeof(AzureStorageAttachment).Assembly.GeneratePublicApi(new ApiGeneratorOptions { WhitelistedNamespacePrefixes = new[] {"Microsoft.Azure.ServiceBus."}, ExcludeAttributes = new[] { "System.Runtime.Versioning.TargetFrameworkAttribute", "System.Reflection.AssemblyMetadataAttribute" } }); Approver.Verify(publicApi); } } }
namespace ServiceBus.AttachmentPlugin.Tests { using PublicApiGenerator; using Xunit; public class ApiApprovals { [Fact] public void AzureStorageAttachmentPlugin() { var publicApi = ApiGenerator.GeneratePublicApi(typeof(AzureStorageAttachment).Assembly, new ApiGeneratorOptions { WhitelistedNamespacePrefixes = new[] {"Microsoft.Azure.ServiceBus."}, ExcludeAttributes = new[] {"System.Runtime.Versioning.TargetFrameworkAttribute"} }); Approver.Verify(publicApi); } } }
mit
C#
d67a53a561d64799fcd4ef09dcf0df2068944cad
update OwinWorkContextMiddleWare
saturn72/saturn72
src/Modules/Owin/Saturn72.Module.Owin/OwinWorkContextMiddleWare.cs
src/Modules/Owin/Saturn72.Module.Owin/OwinWorkContextMiddleWare.cs
using System; using System.ComponentModel; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin; using Saturn72.Core; using Saturn72.Core.Infrastructure; using Saturn72.Extensions; namespace Saturn72.Module.Owin { public class OwinWorkContextMiddleWare<TUserId> : OwinMiddleware { private static TypeConverter _converter; public OwinWorkContextMiddleWare(OwinMiddleware next) : base(next) { } public IWorkContext<TUserId> CurrentWorkContext { get; private set; } public static void Initialized() { _converter = CommonHelper.GetCustomTypeConverter(typeof(TUserId)); if (!_converter.CanConvertTo(typeof(TUserId))) throw new NotSupportedException("OwinWorkContextMiddleware cannot convert user Identity to typeof " + typeof(TUserId).FullName); } public override async Task Invoke(IOwinContext context) { BuildWorkContext(context); await Next.Invoke(context); } protected void BuildWorkContext(IOwinContext context) { var identity = context.Request.User?.Identity as ClaimsIdentity; if (identity.IsNull()) return; var userIdClaim = identity.FindFirst(ClaimTypes.NameIdentifier); if (userIdClaim.IsNull()) return; CurrentWorkContext = AppEngine.Current.Resolve<IWorkContext<TUserId>>(); CurrentWorkContext.CurrentUserId = (TUserId) _converter.ConvertFrom(userIdClaim.Value); } } }
using System; using System.ComponentModel; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin; using Saturn72.Core; using Saturn72.Core.Infrastructure; using Saturn72.Extensions; namespace Saturn72.Module.Owin { public class OwinWorkContextMiddleWare<TUserId> : OwinMiddleware { private static TypeConverter _converter; public OwinWorkContextMiddleWare(OwinMiddleware next) : base(next) { } public IWorkContext<TUserId> CurrentWorkContext { get; private set; } public void Initialized() { _converter = CommonHelper.GetCustomTypeConverter(typeof(TUserId)); if (!_converter.CanConvertTo(typeof(TUserId))) throw new NotSupportedException("OwinWorkContextMiddleware cannot convert user Identity to typeof " + typeof(TUserId).FullName); } public override async Task Invoke(IOwinContext context) { BuildWorkContext(context); await Next.Invoke(context); } protected void BuildWorkContext(IOwinContext context) { var identity = context.Request.User.Identity as ClaimsIdentity; if (identity.IsNull()) return; var userId = identity.FindFirst(ClaimTypes.NameIdentifier); if (userId.IsNull()) return; CurrentWorkContext = AppEngine.Current.Resolve<IWorkContext<TUserId>>(); CurrentWorkContext.CurrentUserId = (TUserId) _converter.ConvertFrom(userId.Value); } } }
mit
C#
f5b6fadf4850c4a2751709746c6ed6f4097c1ef9
Make BuildTimeHelper static
chloe747/LiveSplit,Fluzzarn/LiveSplit,Jiiks/LiveSplit,ROMaster2/LiveSplit,chloe747/LiveSplit,madzinah/LiveSplit,stoye/LiveSplit,kugelrund/LiveSplit,drtchops/LiveSplit,glasnonck/LiveSplit,zoton2/LiveSplit,Fluzzarn/LiveSplit,CryZe/LiveSplit,drtchops/LiveSplit,Fluzzarn/LiveSplit,CryZe/LiveSplit,CryZe/LiveSplit,Dalet/LiveSplit,drtchops/LiveSplit,Seldszar/LiveSplit,PackSciences/LiveSplit,kugelrund/LiveSplit,ROMaster2/LiveSplit,kugelrund/LiveSplit,ROMaster2/LiveSplit,Dalet/LiveSplit,stoye/LiveSplit,PackSciences/LiveSplit,Jiiks/LiveSplit,madzinah/LiveSplit,Glurmo/LiveSplit,Glurmo/LiveSplit,zoton2/LiveSplit,Seldszar/LiveSplit,chloe747/LiveSplit,glasnonck/LiveSplit,glasnonck/LiveSplit,Jiiks/LiveSplit,Dalet/LiveSplit,zoton2/LiveSplit,madzinah/LiveSplit,PackSciences/LiveSplit,stoye/LiveSplit,Glurmo/LiveSplit,LiveSplit/LiveSplit,Seldszar/LiveSplit
LiveSplit/LiveSplit.Core/Updates/BuildTimeHelper.cs
LiveSplit/LiveSplit.Core/Updates/BuildTimeHelper.cs
using System; namespace LiveSplit.Updates { public static class BuildTimeHelper { public static DateTime GetBuildTime() { var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; var buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision)); return buildDateTime; } } }
using System; namespace LiveSplit.Updates { public class BuildTimeHelper { public static DateTime GetBuildTime() { var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; var buildDateTime = new DateTime(2000, 1, 1).Add(new TimeSpan(TimeSpan.TicksPerDay * version.Build + TimeSpan.TicksPerSecond * 2 * version.Revision)); return buildDateTime; } } }
mit
C#
f118cae2a0dde164a5378c12b41db06347f98bb4
Initialize AppConfigCommand with an IAppHarborClient
appharbor/appharbor-cli
src/AppHarbor/Commands/AddConfigCommand.cs
src/AppHarbor/Commands/AddConfigCommand.cs
using System; namespace AppHarbor.Commands { public class AddConfigCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; private readonly IAppHarborClient _appharborClient; public AddConfigCommand(IApplicationConfiguration applicationConfiguration, IAppHarborClient appharborClient) { _applicationConfiguration = applicationConfiguration; _appharborClient = appharborClient; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
using System; namespace AppHarbor.Commands { public class AddConfigCommand : ICommand { private readonly IApplicationConfiguration _applicationConfiguration; public AddConfigCommand(IApplicationConfiguration applicationConfiguration) { _applicationConfiguration = applicationConfiguration; } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
mit
C#
8e376fed7df226fae8b080a04c665871f300117c
Add SearchContext property to PlainScopeLocator
atata-framework/atata,YevgeniyShunevych/Atata,YevgeniyShunevych/Atata,atata-framework/atata
src/Atata/ScopeSearch/PlainScopeLocator.cs
src/Atata/ScopeSearch/PlainScopeLocator.cs
using System; using System.Linq; using OpenQA.Selenium; namespace Atata { public class PlainScopeLocator : IScopeLocator { private readonly Func<By> byCreator; private By by; public PlainScopeLocator(By by) { by.CheckNotNull(nameof(by)); this.by = by; } public PlainScopeLocator(Func<By> byCreator) { byCreator.CheckNotNull(nameof(byCreator)); this.byCreator = byCreator; } private By By { get { return by ?? (by = byCreator()); } } public ISearchContext SearchContext { get; set; } = ATContext.Current.Driver; public IWebElement GetElement(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return SearchContext.Get(By.With(searchOptions)); } public IWebElement[] GetElements(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return SearchContext.GetAll(By.With(searchOptions)).ToArray(); } public bool IsMissing(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return SearchContext.Missing(By.With(searchOptions)); } } }
using System; using System.Linq; using OpenQA.Selenium; namespace Atata { public class PlainScopeLocator : IScopeLocator { private readonly Func<By> byCreator; private By by; public PlainScopeLocator(By by) { by.CheckNotNull(nameof(by)); this.by = by; } public PlainScopeLocator(Func<By> byCreator) { byCreator.CheckNotNull(nameof(byCreator)); this.byCreator = byCreator; } private By By { get { return by ?? (by = byCreator()); } } public IWebElement GetElement(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return ATContext.Current.Driver.Get(By.With(searchOptions)); } public IWebElement[] GetElements(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return ATContext.Current.Driver.GetAll(By.With(searchOptions)).ToArray(); } public bool IsMissing(SearchOptions searchOptions = null, string xPathCondition = null) { searchOptions = searchOptions ?? SearchOptions.Safely(false); return ATContext.Current.Driver.Missing(By.With(searchOptions)); } } }
apache-2.0
C#
50a669a0339c9e26bdf36513e949e57651aecaa4
Fix for filename lowercase matches - to fix missing .PNG images
Red-Folder/docs.functions
src/DocFunctions.Lib/Models/Github/AbstractAction.cs
src/DocFunctions.Lib/Models/Github/AbstractAction.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DocFunctions.Lib.Models.Github { public abstract class AbstractAction { public string FullFilename { get; set; } public string CommitSha { get; set; } public string CommitShaForRead { get; set; } public string Path { get { if (FullFilename.Contains("/")) { return FullFilename.Replace("/" + Filename, ""); } else { return FullFilename.Replace(Filename, ""); } } } public string Filename { get { return System.IO.Path.GetFileName(FullFilename); } } public bool IsBlogFile { get { return (Extension.ToLower() == ".md" || Extension.ToLower() == ".json"); } } public bool IsImageFile { get { return (Extension.ToLower() == ".png" || Extension.ToLower() == ".jpg" || Extension.ToLower() == ".gif"); } } private string Extension { get { return System.IO.Path.GetExtension(FullFilename); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DocFunctions.Lib.Models.Github { public abstract class AbstractAction { public string FullFilename { get; set; } public string CommitSha { get; set; } public string CommitShaForRead { get; set; } public string Path { get { if (FullFilename.Contains("/")) { return FullFilename.Replace("/" + Filename, ""); } else { return FullFilename.Replace(Filename, ""); } } } public string Filename { get { return System.IO.Path.GetFileName(FullFilename); } } public bool IsBlogFile { get { return (Extension == ".md" || Extension == ".json"); } } public bool IsImageFile { get { return (Extension == ".png" || Extension == ".jpg" || Extension == ".gif"); } } private string Extension { get { return System.IO.Path.GetExtension(FullFilename); } } } }
mit
C#
c87d894ebf10d975b253ed9294bc4d69b2cb793d
Apply fixes to duplicate file
vbfox/pinvoke,fearthecowboy/pinvoke,AArnott/pinvoke,jmelosegui/pinvoke
src/Kernel32.Shared/Kernel32+FindFirstFileExFlags.cs
src/Kernel32.Shared/Kernel32+FindFirstFileExFlags.cs
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; /// <content> /// Contains the <see cref="FindFirstFileExFlags"/> nested enum. /// </content> public partial class Kernel32 { /// <summary> /// Optional flags to pass to the <see cref="FindFirstFileEx"/> method. /// </summary> [Flags] public enum FindFirstFileExFlags { /// <summary> /// No flags. /// </summary> None = 0x0, /// <summary> /// Searches are case-sensitive. /// </summary> CaseSensitive = 0x1, /// <summary> /// Uses a larger buffer for directory queries, which can increase performance of the find operation. /// </summary> LargeFetch = 0x2, } } }
// Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. namespace PInvoke { using System; /// <content> /// Contains the <see cref="FindFirstFileExFlags"/> nested enum. /// </content> public partial class Kernel32 { /// <summary> /// Optional flags to pass to the <see cref="FindFirstFileEx"/> method. /// </summary> [Flags] public enum FindFirstFileExFlags { /// <summary> /// Searches are case-sensitive. /// </summary> CaseSensitive, /// <summary> /// Uses a larger buffer for directory queries, which can increase performance of the find operation. /// </summary> LargeFetch, } } }
mit
C#
29011461d8a10d5a8560f5a311bbe1ccd7511384
Set Activity tags in addition to calling the new API.
mysql-net/MySqlConnector,mysql-net/MySqlConnector
src/MySqlConnector/Utilities/ActivitySourceHelper.cs
src/MySqlConnector/Utilities/ActivitySourceHelper.cs
using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace MySqlConnector.Utilities; internal static class ActivitySourceHelper { public const string DatabaseConnectionIdTagName = "db.connection_id"; public const string DatabaseConnectionStringTagName = "db.connection_string"; public const string DatabaseNameTagName = "db.name"; public const string DatabaseStatementTagName = "db.statement"; public const string DatabaseSystemTagName = "db.system"; public const string DatabaseUserTagName = "db.user"; public const string NetPeerIpTagName = "net.peer.ip"; public const string NetPeerNameTagName = "net.peer.name"; public const string NetPeerPortTagName = "net.peer.port"; public const string NetTransportTagName = "net.transport"; public const string StatusCodeTagName = "otel.status_code"; public const string ThreadIdTagName = "thread.id"; public const string DatabaseSystemValue = "mysql"; public const string NetTransportNamedPipeValue = "pipe"; public const string NetTransportTcpIpValue = "ip_tcp"; public const string NetTransportUnixValue = "unix"; public const string ExecuteActivityName = "Execute"; public const string OpenActivityName = "Open"; public static Activity? StartActivity(string name, IEnumerable<KeyValuePair<string, object?>>? activityTags = null) { var activity = ActivitySource.StartActivity(name, ActivityKind.Client, default(ActivityContext), activityTags); if (activity is { IsAllDataRequested: true }) activity.SetTag(ActivitySourceHelper.ThreadIdTagName, Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); return activity; } public static void SetSuccess(this Activity activity) { #if NET6_0_OR_GREATER activity.SetStatus(ActivityStatusCode.Ok); #endif activity.SetTag(StatusCodeTagName, "OK"); } public static void SetException(this Activity activity, Exception exception) { var description = exception is MySqlException mySqlException ? mySqlException.ErrorCode.ToString() : exception.Message; #if NET6_0_OR_GREATER activity.SetStatus(ActivityStatusCode.Error, description); #endif activity.SetTag(StatusCodeTagName, "ERROR"); activity.SetTag("otel.status_description", description); activity.AddEvent(new ActivityEvent("exception", tags: new ActivityTagsCollection { { "exception.type", exception.GetType().FullName }, { "exception.message", exception.Message }, { "exception.stacktrace", exception.ToString() }, })); } private static ActivitySource ActivitySource { get; } = CreateActivitySource(); private static ActivitySource CreateActivitySource() { var assembly = typeof(ActivitySourceHelper).Assembly; var version = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version; return new("MySqlConnector", version); } }
using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; namespace MySqlConnector.Utilities; internal static class ActivitySourceHelper { public const string DatabaseConnectionIdTagName = "db.connection_id"; public const string DatabaseConnectionStringTagName = "db.connection_string"; public const string DatabaseNameTagName = "db.name"; public const string DatabaseStatementTagName = "db.statement"; public const string DatabaseSystemTagName = "db.system"; public const string DatabaseUserTagName = "db.user"; public const string NetPeerIpTagName = "net.peer.ip"; public const string NetPeerNameTagName = "net.peer.name"; public const string NetPeerPortTagName = "net.peer.port"; public const string NetTransportTagName = "net.transport"; #if !NET6_0_OR_GREATER public const string StatusCodeTagName = "otel.status_code"; #endif public const string ThreadIdTagName = "thread.id"; public const string DatabaseSystemValue = "mysql"; public const string NetTransportNamedPipeValue = "pipe"; public const string NetTransportTcpIpValue = "ip_tcp"; public const string NetTransportUnixValue = "unix"; public const string ExecuteActivityName = "Execute"; public const string OpenActivityName = "Open"; public static Activity? StartActivity(string name, IEnumerable<KeyValuePair<string, object?>>? activityTags = null) { var activity = ActivitySource.StartActivity(name, ActivityKind.Client, default(ActivityContext), activityTags); if (activity is { IsAllDataRequested: true }) activity.SetTag(ActivitySourceHelper.ThreadIdTagName, Environment.CurrentManagedThreadId.ToString(CultureInfo.InvariantCulture)); return activity; } public static void SetSuccess(this Activity activity) { #if NET6_0_OR_GREATER activity.SetStatus(ActivityStatusCode.Ok); #else activity.SetTag(StatusCodeTagName, "OK"); #endif } public static void SetException(this Activity activity, Exception exception) { var description = exception is MySqlException mySqlException ? mySqlException.ErrorCode.ToString() : exception.Message; #if NET6_0_OR_GREATER activity.SetStatus(ActivityStatusCode.Error, description); #else activity.SetTag(StatusCodeTagName, "ERROR"); activity.SetTag("otel.status_description", description); #endif activity.AddEvent(new ActivityEvent("exception", tags: new ActivityTagsCollection { { "exception.type", exception.GetType().FullName }, { "exception.message", exception.Message }, { "exception.stacktrace", exception.ToString() }, })); } private static ActivitySource ActivitySource { get; } = CreateActivitySource(); private static ActivitySource CreateActivitySource() { var assembly = typeof(ActivitySourceHelper).Assembly; var version = assembly.GetCustomAttribute<AssemblyFileVersionAttribute>()!.Version; return new("MySqlConnector", version); } }
mit
C#
3ce71f7a9f17ede4384b3794912eeba9c2e52f4c
Improve efficiency of iOS texture loading
smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,DrabWeb/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework.iOS/Graphics/Textures/IOSTextureLoaderStore.cs
osu.Framework.iOS/Graphics/Textures/IOSTextureLoaderStore.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.IO; using System.Runtime.InteropServices; using CoreGraphics; using Foundation; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using SixLabors.ImageSharp; using UIKit; namespace osu.Framework.iOS.Graphics.Textures { public class IOSTextureLoaderStore : TextureLoaderStore { public IOSTextureLoaderStore(IResourceStore<byte[]> store) : base(store) { } protected unsafe override Image<TPixel> ImageFromStream<TPixel>(Stream stream) { using (var uiImage = UIImage.LoadFromData(NSData.FromStream(stream))) { int width = (int)uiImage.Size.Width; int height = (int)uiImage.Size.Height; IntPtr data = Marshal.AllocHGlobal(width * height * 4); using (CGBitmapContext textureContext = new CGBitmapContext(data, width, height, 8, width * 4, uiImage.CGImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) textureContext.DrawImage(new CGRect(0, 0, width, height), uiImage.CGImage); // NOTE: this will probably only be correct for Rgba32, will need to look into other pixel formats var image = Image.LoadPixelData<TPixel>( new ReadOnlySpan<byte>(data.ToPointer(), width * height * 4), width, height); Marshal.FreeHGlobal(data); return image; } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.IO; using System.Runtime.InteropServices; using CoreGraphics; using Foundation; using osu.Framework.Graphics.Textures; using osu.Framework.IO.Stores; using SixLabors.ImageSharp; using UIKit; namespace osu.Framework.iOS.Graphics.Textures { public class IOSTextureLoaderStore : TextureLoaderStore { public IOSTextureLoaderStore(IResourceStore<byte[]> store) : base(store) { } protected override Image<TPixel> ImageFromStream<TPixel>(Stream stream) { var uiImage = UIImage.LoadFromData(NSData.FromStream(stream)); int width = (int)uiImage.Size.Width; int height = (int)uiImage.Size.Height; IntPtr data = Marshal.AllocHGlobal(width * height * 4); using (CGBitmapContext textureContext = new CGBitmapContext(data, width, height, 8, width * 4, uiImage.CGImage.ColorSpace, CGImageAlphaInfo.PremultipliedLast)) textureContext.DrawImage(new CGRect(0, 0, width, height), uiImage.CGImage); var pixels = new byte[width * height * 4]; Marshal.Copy(data, pixels, 0, pixels.Length); Marshal.FreeHGlobal(data); // NOTE: this will probably only be correct for Rgba32, will need to look into other pixel formats return Image.LoadPixelData<TPixel>(pixels, width, height); } } }
mit
C#
cb77f3e123707ca617da8da9d973beb9be6524a4
Add RSS Infomation for Andreas Bittner
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/AndreasBittner.cs
src/Firehose.Web/Authors/AndreasBittner.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 AndreasBittner : IAmACommunityMember { public string FirstName => "Andreas"; public string LastName => "Bittner"; public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2"; public string StateOrRegion => "Saxony, Germany"; public string EmailAddress => ""; public string TwitterHandle => "Andreas_Bittner"; public string GitHubHandle => "bobruhny"; public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755"; public GeoPosition Position => new GeoPosition(49,4833, 10,7167); public Uri WebSite => new Uri("http://joinpowershell.de/de/new/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("http://joinpowershell.de/de/feed/"); } } } }
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 AndreasBittner : IAmACommunityMember { public string FirstName => "Andreas"; public string LastName => "Bittner"; public string ShortBioOrTagLine => "DevOp and MCSE Server 2012R2"; public string StateOrRegion => "Saxony, Germany"; public string EmailAddress => ""; public string TwitterHandle => "Andreas_Bittner"; public string GitHubHandle => "bobruhny"; public string GravatarHash => "9e94e1e9014ad138df3f5281f814d755"; public GeoPosition Position => new GeoPosition(49,4833, 10,7167); public Uri WebSite => new Uri("http://joinpowershell.de/de/new/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri(""); } } } }
mit
C#
629db40f16ef89f28ad96fb460c1c10c1a60df2a
Fix bug in RabbitReceiverMessage when received message has no headers
RockFramework/Rock.Messaging
RockLib.Messaging.RabbitMQ/RabbitReceiverMessage.cs
RockLib.Messaging.RabbitMQ/RabbitReceiverMessage.cs
using RabbitMQ.Client.Events; using RabbitMQ.Client; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Text; namespace RockLib.Messaging.RabbitMQ { /// <summary> /// An implementation of IReceiverMessage for use by the <see cref="RabbitReceiver"/> /// class. /// </summary> public sealed class RabbitReceiverMessage : ReceiverMessage { private static readonly Task CompletedTask = Task.FromResult(0); private readonly BasicDeliverEventArgs _args; private readonly IModel _channel; private readonly bool _autoAck; internal RabbitReceiverMessage(BasicDeliverEventArgs args, IModel channel, bool autoAck) : base(() => args.Body) { _args = args; _channel = channel; _autoAck = autoAck; } /// <inheritdoc /> protected override void InitializeHeaders(IDictionary<string, object> headers) { if (_args.BasicProperties?.Headers == null) return; foreach (var header in _args.BasicProperties.Headers) { if (header.Value is byte[] binary) headers.Add(header.Key, Encoding.UTF8.GetString(binary)); else headers.Add(header); } } /// <inheritdoc /> protected override Task AcknowledgeMessageAsync(CancellationToken cancellationToken) { if (!_autoAck) _channel.BasicAck(_args.DeliveryTag, false); return CompletedTask; } /// <inheritdoc /> protected override Task RollbackMessageAsync(CancellationToken cancellationToken) { if (!_autoAck) _channel.BasicNack(_args.DeliveryTag, false, true); return CompletedTask; } /// <inheritdoc /> protected override Task RejectMessageAsync(CancellationToken cancellationToken) { if (!_autoAck) _channel.BasicNack(_args.DeliveryTag, false, false); return CompletedTask; } } }
using RabbitMQ.Client.Events; using RabbitMQ.Client; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using System.Text; namespace RockLib.Messaging.RabbitMQ { /// <summary> /// An implementation of IReceiverMessage for use by the <see cref="RabbitReceiver"/> /// class. /// </summary> public sealed class RabbitReceiverMessage : ReceiverMessage { private static readonly Task CompletedTask = Task.FromResult(0); private readonly BasicDeliverEventArgs _args; private readonly IModel _channel; private readonly bool _autoAck; internal RabbitReceiverMessage(BasicDeliverEventArgs args, IModel channel, bool autoAck) : base(() => args.Body) { _args = args; _channel = channel; _autoAck = autoAck; } /// <inheritdoc /> protected override void InitializeHeaders(IDictionary<string, object> headers) { foreach (var header in _args.BasicProperties.Headers) { if (header.Value is byte[] binary) headers.Add(header.Key, Encoding.UTF8.GetString(binary)); else headers.Add(header); } } /// <inheritdoc /> protected override Task AcknowledgeMessageAsync(CancellationToken cancellationToken) { if (!_autoAck) _channel.BasicAck(_args.DeliveryTag, false); return CompletedTask; } /// <inheritdoc /> protected override Task RollbackMessageAsync(CancellationToken cancellationToken) { if (!_autoAck) _channel.BasicNack(_args.DeliveryTag, false, true); return CompletedTask; } /// <inheritdoc /> protected override Task RejectMessageAsync(CancellationToken cancellationToken) { if (!_autoAck) _channel.BasicNack(_args.DeliveryTag, false, false); return CompletedTask; } } }
mit
C#
b1df04b670ffc55d55b159367a6592ecc0c30654
Increment versions
SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk
SnapMD.ConnectedCare.Sdk/Properties/AssemblyInfo.cs
SnapMD.ConnectedCare.Sdk/Properties/AssemblyInfo.cs
// Copyright 2015 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.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("SnapMD.ConnectedCare.Sdk")] [assembly: AssemblyDescription("Open-source wrapper for the REST API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SnapMD")] [assembly: AssemblyProduct("Connected Care")] [assembly: AssemblyCopyright("Copyright © 2015 SnapMD, Inc.")] [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("fc089857-9e43-41eb-b5e3-e397174f7f00")] // 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.10.5")] [assembly: AssemblyFileVersion("1.0.0.0")]
// Copyright 2015 SnapMD, Inc. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.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("SnapMD.ConnectedCare.Sdk")] [assembly: AssemblyDescription("Open-source wrapper for the REST API")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("SnapMD")] [assembly: AssemblyProduct("Connected Care")] [assembly: AssemblyCopyright("Copyright © 2015 SnapMD, Inc.")] [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("fc089857-9e43-41eb-b5e3-e397174f7f00")] // 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.10.3")] [assembly: AssemblyFileVersion("1.0.0.0")]
apache-2.0
C#
e1d3ef3a00775626529447943960f3348927e608
add ScheduleId to TaskInfo
iron-io/iron_dotnet
src/IronSharp.IronWorker/Tasks/TaskInfo.cs
src/IronSharp.IronWorker/Tasks/TaskInfo.cs
using System; using IronSharp.Core; using Newtonsoft.Json; namespace IronSharp.IronWorker { public class TaskInfo : IMsg, IInspectable { [JsonProperty("code_id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CodeId { get; set; } [JsonProperty("code_name", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CodeName { get; set; } [JsonProperty("created_at", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? CreatedAt { get; set; } [JsonProperty("duration", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Duration { get; set; } [JsonProperty("end_time", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? EndTime { get; set; } [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Id { get; set; } [JsonProperty("schedule_id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ScheduleId { get; set; } [JsonProperty("msg", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Message { get; set; } [JsonProperty("percent", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Percent { get; set; } [JsonProperty("project_id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ProjectId { get; set; } [JsonProperty("run_times", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? RunTimes { get; set; } [JsonProperty("start_time", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? StartTime { get; set; } [JsonIgnore] public TaskStates Status { get { return StatusValue.As<TaskStates>(); } set { StatusValue = Convert.ToString(value).ToLower(); } } [JsonProperty("timeout", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Timeout { get; set; } [JsonProperty("updated_at", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? UpdatedAt { get; set; } [JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Ignore)] protected string StatusValue { get; set; } } }
using System; using IronSharp.Core; using Newtonsoft.Json; namespace IronSharp.IronWorker { public class TaskInfo : IMsg, IInspectable { [JsonProperty("code_id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CodeId { get; set; } [JsonProperty("code_name", DefaultValueHandling = DefaultValueHandling.Ignore)] public string CodeName { get; set; } [JsonProperty("created_at", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? CreatedAt { get; set; } [JsonProperty("duration", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Duration { get; set; } [JsonProperty("end_time", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? EndTime { get; set; } [JsonProperty("id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Id { get; set; } [JsonProperty("msg", DefaultValueHandling = DefaultValueHandling.Ignore)] public string Message { get; set; } [JsonProperty("percent", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Percent { get; set; } [JsonProperty("project_id", DefaultValueHandling = DefaultValueHandling.Ignore)] public string ProjectId { get; set; } [JsonProperty("run_times", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? RunTimes { get; set; } [JsonProperty("start_time", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? StartTime { get; set; } [JsonIgnore] public TaskStates Status { get { return StatusValue.As<TaskStates>(); } set { StatusValue = Convert.ToString(value).ToLower(); } } [JsonProperty("timeout", DefaultValueHandling = DefaultValueHandling.Ignore)] public int? Timeout { get; set; } [JsonProperty("updated_at", DefaultValueHandling = DefaultValueHandling.Ignore)] public DateTime? UpdatedAt { get; set; } [JsonProperty("status", DefaultValueHandling = DefaultValueHandling.Ignore)] protected string StatusValue { get; set; } } }
mit
C#
6df2b666ac395e3d0df748937777a66a381ef43e
Set UI exe assembly title
webprofusion/Certify
src/Certify.UI/Properties/AssemblyInfo.cs
src/Certify.UI/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] [assembly: AssemblyTitle("Certify The Web (UI)")]
using System.Runtime.InteropServices; using System.Windows; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )]
mit
C#
36237398fa307f6939306df065e897b4683cf740
Remove accidental leftover nullable BDL spec
smoogipoo/osu,peppy/osu-new,ppy/osu,NeoAdonis/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,NeoAdonis/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu
osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyReverseArrow.cs
osu.Game.Rulesets.Osu/Skinning/Legacy/LegacyReverseArrow.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Skinning.Legacy { public class LegacyReverseArrow : CompositeDrawable { private ISkin skin { get; } [Resolved(canBeNull: true)] private DrawableHitObject drawableHitObject { get; set; } private Drawable proxy; public LegacyReverseArrow(ISkin skin) { this.skin = skin; } [BackgroundDependencyLoader] private void load() { AutoSizeAxes = Axes.Both; string lookupName = new OsuSkinComponent(OsuSkinComponents.ReverseArrow).LookupName; InternalChild = skin.GetAnimation(lookupName, true, true) ?? Empty(); } protected override void LoadComplete() { base.LoadComplete(); proxy = CreateProxy(); if (drawableHitObject != null) { drawableHitObject.HitObjectApplied += onHitObjectApplied; onHitObjectApplied(drawableHitObject); } } private void onHitObjectApplied(DrawableHitObject drawableObject) { Debug.Assert(proxy.Parent == null); // see logic in LegacySliderHeadHitCircle. (drawableObject as DrawableSliderRepeat)?.DrawableSlider .OverlayElementContainer.Add(proxy); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (drawableHitObject != null) drawableHitObject.HitObjectApplied -= onHitObjectApplied; } } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Diagnostics; using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; using osu.Game.Skinning; namespace osu.Game.Rulesets.Osu.Skinning.Legacy { public class LegacyReverseArrow : CompositeDrawable { private ISkin skin { get; } [Resolved(canBeNull: true)] private DrawableHitObject drawableHitObject { get; set; } private Drawable proxy; public LegacyReverseArrow(ISkin skin) { this.skin = skin; } [BackgroundDependencyLoader(true)] private void load() { AutoSizeAxes = Axes.Both; string lookupName = new OsuSkinComponent(OsuSkinComponents.ReverseArrow).LookupName; InternalChild = skin.GetAnimation(lookupName, true, true) ?? Empty(); } protected override void LoadComplete() { base.LoadComplete(); proxy = CreateProxy(); if (drawableHitObject != null) { drawableHitObject.HitObjectApplied += onHitObjectApplied; onHitObjectApplied(drawableHitObject); } } private void onHitObjectApplied(DrawableHitObject drawableObject) { Debug.Assert(proxy.Parent == null); // see logic in LegacySliderHeadHitCircle. (drawableObject as DrawableSliderRepeat)?.DrawableSlider .OverlayElementContainer.Add(proxy); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (drawableHitObject != null) drawableHitObject.HitObjectApplied -= onHitObjectApplied; } } }
mit
C#
699c7bbf56684e73b0d71b7ab6b15983c53f546c
Replace SmsSid with MessageSid
TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets,TwilioDevEd/api-snippets
rest/messages/sms-handle-callback/sms-handle-callback.5.x.cs
rest/messages/sms-handle-callback/sms-handle-callback.5.x.cs
// In Package Manager, run: // Install-Package Twilio.Mvc -DependencyVersion HighestMinor using System.Diagnostics; using System.Web.Mvc; public class MessageStatusController : Controller { [HttpPost] public ActionResult Index() { // Log the message id and status var smsSid = Request.Form["MessageSid"]; var messageStatus = Request.Form["MessageStatus"]; var logMessage = $"\"{smsSid}\", \"{messageStatus}\""; Trace.WriteLine(logMessage); return Content("Handled"); } }
// In Package Manager, run: // Install-Package Twilio.Mvc -DependencyVersion HighestMinor using System.Diagnostics; using System.Web.Mvc; public class MessageStatusController : Controller { [HttpPost] public ActionResult Index() { // Log the message id and status var smsSid = Request.Form["SmsSid"]; var messageStatus = Request.Form["MessageStatus"]; var logMessage = $"\"{smsSid}\", \"{messageStatus}\""; Trace.WriteLine(logMessage); return Content("Handled"); } }
mit
C#
e301af39072df98ac9c7cae08c9c8279d257701d
Add support for specifying HTTP method in MVC fluent API
AnthonySteele/MvcRouteTester,AlexisArce/MvcRouteTester
src/MvcRouteTester/Fluent/UrlAndRoutes.cs
src/MvcRouteTester/Fluent/UrlAndRoutes.cs
using System; using System.Linq.Expressions; using System.Net.Http; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.Routing; using MvcRouteTester.ApiRoute; using MvcRouteTester.WebRoute; namespace MvcRouteTester.Fluent { public class UrlAndRoutes { private string requestBody = string.Empty; private BodyFormat bodyFormat = BodyFormat.None; private string requestAppPath = "/"; public UrlAndRoutes(RouteCollection routes, string url) { Routes = routes; Url = url; } public string Url { get; private set; } public RouteCollection Routes { get; private set; } public UrlAndRoutes WithFormUrlBody(string body) { requestBody = body; bodyFormat = BodyFormat.FormUrl; return this; } public UrlAndRoutes WithJsonBody(string body) { requestBody = body; bodyFormat = BodyFormat.Json; return this; } public UrlAndRoutes WithAppPath(string appPath) { requestAppPath = appPath; return this; } public void To<TController>(Expression<Func<TController, ActionResult>> action) where TController : Controller { To(HttpMethod.Get, action); } public void To<TController>(HttpMethod httpMethod, Expression<Func<TController, ActionResult>> action) where TController : Controller { var expressionReader = new ExpressionReader(); var expectedProps = expressionReader.Read(action); WebRouteAssert.HasRoute(Routes, httpMethod, Url, requestBody, bodyFormat, expectedProps); } public void To<TController>(Expression<Func<TController, Task<ActionResult>>> action) where TController : Controller { To(HttpMethod.Get, action); } public void To<TController>(HttpMethod httpMethod, Expression<Func<TController, Task<ActionResult>>> action) where TController : Controller { var expressionReader = new ExpressionReader(); var expectedProps = expressionReader.Read(action); WebRouteAssert.HasRoute(Routes, httpMethod, Url, requestBody, bodyFormat, expectedProps); } public void ToNoRoute() { WebRouteAssert.NoRoute(Routes, Url); } public void ToIgnoredRoute() { WebRouteAssert.IsIgnoredRoute(Routes, Url); } public void ToNonIgnoredRoute() { WebRouteAssert.IsNotIgnoredRoute(Routes, Url); } public void From<TController>(Expression<Func<TController, ActionResult>> action) where TController : Controller { var expressionReader = new ExpressionReader(); var fromProps = expressionReader.Read(action); WebRouteAssert.GeneratesActionUrl(Routes, HttpMethod.Get, Url, fromProps, appPath: requestAppPath, requestBody: requestBody); } } }
using System; using System.Linq.Expressions; using System.Net.Http; using System.Threading.Tasks; using System.Web.Mvc; using System.Web.Routing; using MvcRouteTester.ApiRoute; using MvcRouteTester.WebRoute; namespace MvcRouteTester.Fluent { public class UrlAndRoutes { private string requestBody = string.Empty; private BodyFormat bodyFormat = BodyFormat.None; private string requestAppPath = "/"; public UrlAndRoutes(RouteCollection routes, string url) { Routes = routes; Url = url; } public string Url { get; private set; } public RouteCollection Routes { get; private set; } public UrlAndRoutes WithFormUrlBody(string body) { requestBody = body; bodyFormat = BodyFormat.FormUrl; return this; } public UrlAndRoutes WithJsonBody(string body) { requestBody = body; bodyFormat = BodyFormat.Json; return this; } public UrlAndRoutes WithAppPath(string appPath) { requestAppPath = appPath; return this; } public void To<TController>(Expression<Func<TController, ActionResult>> action) where TController : Controller { var expressionReader = new ExpressionReader(); var expectedProps = expressionReader.Read(action); WebRouteAssert.HasRoute(Routes, HttpMethod.Get, Url, requestBody, bodyFormat, expectedProps); } public void To<TController>(Expression<Func<TController, Task<ActionResult>>> action) where TController : Controller { var expressionReader = new ExpressionReader(); var expectedProps = expressionReader.Read(action); WebRouteAssert.HasRoute(Routes, HttpMethod.Get, Url, requestBody, bodyFormat, expectedProps); } public void ToNoRoute() { WebRouteAssert.NoRoute(Routes, Url); } public void ToIgnoredRoute() { WebRouteAssert.IsIgnoredRoute(Routes, Url); } public void ToNonIgnoredRoute() { WebRouteAssert.IsNotIgnoredRoute(Routes, Url); } public void From<TController>(Expression<Func<TController, ActionResult>> action) where TController : Controller { var expressionReader = new ExpressionReader(); var fromProps = expressionReader.Read(action); WebRouteAssert.GeneratesActionUrl(Routes, HttpMethod.Get, Url, fromProps, appPath: requestAppPath, requestBody: requestBody); } } }
apache-2.0
C#
251835619f7e7d7015053919a4d29edb07544b4a
Send email to template
tigranv/CRM_Project_C,tigranv/CRM_Project_C
CRM_Project_C/Source/CRM.WebApi/Controllers/SendEmailsController.cs
CRM_Project_C/Source/CRM.WebApi/Controllers/SendEmailsController.cs
using CRM.EntityFrameWorkLib; using CRM.WebApi.Filters; using CRM.WebApi.Infrastructure; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; namespace CRM.WebApi.Controllers { [NotImplExceptionFilterAttribute] public class SendEmailsController : ApiController { ApplicationManager appManager = new ApplicationManager(); EmailProvider emprovider = new EmailProvider(); public async Task<IHttpActionResult> PostSendEmails([FromBody] List<Guid> guidlist, [FromUri] int template) { List<Contact> ContactsToSend = await appManager.GetContactsByGuIdList(guidlist); if (ContactsToSend.Count == 0) return NotFound(); await emprovider.SendEmailToContacts(ContactsToSend, template); return Ok(); } public async Task<IHttpActionResult> PostSendEmailsByEmailList([FromUri] int template, [FromUri] int emaillistId) { EmailList emlist = await appManager.GetEmailListById(emaillistId); if (emlist == null) return NotFound(); List<Contact> list = new List<Contact>(); foreach (var item in emlist.Contacts) { if(item != null) list.Add(item); } await emprovider.SendEmailToContacts(list, template); return Ok(); } protected override void Dispose(bool disposing) { if (disposing) { appManager.Dispose(); emprovider.Dispose(); } base.Dispose(disposing); } } }
using CRM.EntityFrameWorkLib; using CRM.WebApi.Filters; using CRM.WebApi.Infrastructure; using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; namespace CRM.WebApi.Controllers { [NotImplExceptionFilterAttribute] public class SendEmailsController : ApiController { ApplicationManager AppManager = new ApplicationManager(); EmailProvider emprovider = new EmailProvider(); public async Task<IHttpActionResult> PostSendEmails([FromBody] List<Guid> guidlist, [FromUri] int template) { List<Contact> ContactsToSend = await AppManager.GetContactsByGuIdList(guidlist); if (ContactsToSend.Count == 0) return NotFound(); await emprovider.SendEmailToContacts(ContactsToSend, template); return Ok(); } public async Task<IHttpActionResult> PostSendEmailsByEmailList([FromUri] int template, [FromUri] int emaillistId) { List<Contact> contactsToSend = (await AppManager.GetEmailListById(emaillistId)).Contacts as List<Contact>; if (contactsToSend == null || contactsToSend.Count == 0) return NotFound(); await emprovider.SendEmailToContacts(contactsToSend, template); return Ok(); } protected override void Dispose(bool disposing) { if (disposing) { AppManager.Dispose(); emprovider.Dispose(); } base.Dispose(disposing); } } }
mit
C#
672343a14d54bc529396bb39bc3bd388b44969a3
Handle cancel click
MumbaiHackerspace/Visage,MumbaiHackerspace/Visage,MumbaiHackerspace/Visage,MumbaiHackerspace/Visage
visage-xfapp/Visage/ViewModels/LoginWithEventbriteViewModel.cs
visage-xfapp/Visage/ViewModels/LoginWithEventbriteViewModel.cs
using System; using System.Windows.Input; using Visage.Helpers; using Visage.Pages; using Xamarin.Forms; namespace Visage.ViewModels { public class LoginWithEventbriteViewModel : BaseViewModel { public String Email { get; set; } public string Password { get; set; } public ICommand LoginCommand { get; set; } public ICommand CancelCommand { get; set; } public LoginWithEventbriteViewModel() { LoginCommand = new Command(ExecuteLoginCommand); CancelCommand = new Command(ExecuteCancelCommand); } void ExecuteLoginCommand() { Application.Current.MainPage = new MainPage(); } void ExecuteCancelCommand() { //TODO: Handle cancel click //await Navigation.PopAsync(); } } }
using System; using System.Windows.Input; using Visage.Helpers; using Visage.Pages; using Xamarin.Forms; namespace Visage.ViewModels { public class LoginWithEventbriteViewModel : BaseViewModel { public String Email { get; set; } public string Password { get; set; } public ICommand LoginCommand { get; set; } public ICommand CancelCommand { get; set; } public LoginWithEventbriteViewModel() { LoginCommand = new Command(ExecuteLoginCommand); CancelCommand = new Command(ExecuteCancelCommand); } void ExecuteLoginCommand() { Application.Current.MainPage = new MainPage(); } async void ExecuteCancelCommand() { await Navigation.PopAsync(); } } }
mit
C#
ffaaf530a6e3c90f57fadf955139043454e6598d
Fix bug about that DateTimeToPointInTime is not handling string that are dateTime
Seddryck/NBi,Seddryck/NBi
NBi.Core/Transformation/Transformer/Native/DateTimeToPointInTime.cs
NBi.Core/Transformation/Transformer/Native/DateTimeToPointInTime.cs
using NBi.Core.Scalar.Casting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Transformation.Transformer.Native { abstract class DateTimeToPointInTime : INativeTransformation { public object Evaluate(object value) { switch (value) { case null: return null; case DateTime dt: return EvaluateDateTime(dt); default: var caster = new DateTimeCaster(); var dateTime = caster.Execute(value); return EvaluateDateTime(dateTime); } } protected abstract object EvaluateDateTime(DateTime value); } class DateTimeToFirstOfMonth : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, value.Month, 1); } class DateTimeToFirstOfYear : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, 1, 1); } class DateTimeToLastOfMonth : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, value.Month, 1).AddMonths(1).AddDays(-1); } class DateTimeToLastOfYear : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, 12, 31); } class DateTimeToClip : DateTimeToPointInTime { public DateTime Min { get; } public DateTime Max { get; } public DateTimeToClip(string min, string max) { var caster = new DateTimeCaster(); Min = caster.Execute(min); Max = caster.Execute(max); } protected override object EvaluateDateTime(DateTime value) => (value < Min) ? Min : (value > Max) ? Max : value; } }
using NBi.Core.Scalar.Casting; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Transformation.Transformer.Native { abstract class DateTimeToPointInTime : INativeTransformation { public object Evaluate(object value) { if (value == null) return null; else if (value is DateTime) return EvaluateDateTime((DateTime)value); else throw new NotImplementedException(); } protected abstract object EvaluateDateTime(DateTime value); } class DateTimeToFirstOfMonth : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, value.Month, 1); } class DateTimeToFirstOfYear : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, 1, 1); } class DateTimeToLastOfMonth : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, value.Month, 1).AddMonths(1).AddDays(-1); } class DateTimeToLastOfYear : DateTimeToPointInTime { protected override object EvaluateDateTime(DateTime value) => new DateTime(value.Year, 12, 31); } class DateTimeToClip : DateTimeToPointInTime { public DateTime Min { get; } public DateTime Max { get; } public DateTimeToClip(string min, string max) { var caster = new DateTimeCaster(); Min = caster.Execute(min); Max = caster.Execute(max); } protected override object EvaluateDateTime(DateTime value) => (value < Min) ? Min : (value > Max) ? Max : value; } }
apache-2.0
C#
1e3959eb5d61ef601de134abbd570465e9904e8e
fix build break
ErikEJ/EntityFramework.SqlServerCompact,ErikEJ/EntityFramework7.SqlServerCompact
src/Provider40/Properties/AssemblyInfo.cs
src/Provider40/Properties/AssemblyInfo.cs
using System.Reflection; using Microsoft.EntityFrameworkCore.Design; [assembly: DesignTimeProviderServices("EFCore.SqlCe.Design.Internal.SqlCeDesignTimeServices")] #if SQLCE35 [assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact35")] [assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact35")] #else [assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact40")] [assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact40")] #endif [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-rtm")]
using System.Reflection; using Microsoft.EntityFrameworkCore.Design; [assembly: DesignTimeProviderServices("EFCore.SqlCe.Scaffolding.Internal.SqlCeDesignTimeServices")] #if SQLCE35 [assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact35")] [assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact35")] #else [assembly: AssemblyTitle("EntityFrameworkCore.SqlServerCompact40")] [assembly: AssemblyProduct("EntityFrameworkCore.SqlServerCompact40")] #endif [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-rtm")]
apache-2.0
C#
2681c65cd5ee521cac8e3302329aa564d95d0cb9
替换Consumer的拦截方式 添加对数据库访问操作的支持
imyounghan/umizoo
src/Samples/UserRegistration/ReadModel/UserQueryHandler.cs
src/Samples/UserRegistration/ReadModel/UserQueryHandler.cs
using System.Collections.Generic; using System.Linq; using Umizoo.Messaging; using Umizoo.Messaging.Handling; using UserRegistration.Events; namespace UserRegistration.ReadModel { public class UserQueryHandler : IQueryHandler<FindAllUser, IEnumerable<UserModel>>, //IQueryHandler<FindAllUser, PageResult<UserModel>>, IQueryHandler<UserAuthentication, bool> { private readonly IUserDao dao; private readonly IMessageBus<IEvent> bus; public UserQueryHandler(IUserDao userDao, IMessageBus<IEvent> messageBus) { this.dao = userDao; this.bus = messageBus; } #region IQueryMultipleFetcher<FindAllData,UserModel> 成员 public IEnumerable<UserModel> Handle(FindAllUser parameter) { return dao.GetAll().ToList(); } //public PageResult<UserModel> Handle(FindAllUser parameter) //{ // return new PageResult<UserModel>(dao.GetAll()); //} #endregion #region IQueryFetcher<UserAuthentication,bool> 成员 public bool Handle(UserAuthentication parameter) { var user = dao.Find(parameter.LoginId); if(user == null) return false; if(user.Password != parameter.Password) return false; var userSigned = new UserSigned(parameter.LoginId, parameter.IpAddress); bus.Publish(userSigned); return true; } #endregion } }
using System.Collections.Generic; using System.Linq; using Umizoo.Messaging; using Umizoo.Messaging.Handling; using UserRegistration.Events; namespace UserRegistration.ReadModel { public class UserQueryHandler : IQueryHandler<FindAllUser, IEnumerable<UserModel>>, //IQueryHandler<FindAllUser, PageResult<UserModel>>, IQueryHandler<UserAuthentication, bool> { private readonly IUserDao dao; private readonly IMessageBus<IEvent> bus; public UserQueryHandler(IUserDao userDao, IMessageBus<IEvent> messageBus) { this.dao = userDao; this.bus = messageBus; } #region IQueryMultipleFetcher<FindAllData,UserModel> 成员 public IEnumerable<UserModel> Handle(FindAllUser parameter) { return dao.GetAll().ToList(); } //public PageResult<UserModel> Handle(FindAllUser parameter) //{ // return new PageResult<UserModel>(dao.GetAll()); //} #endregion #region IQueryFetcher<UserAuthentication,bool> 成员 public bool Handle(UserAuthentication parameter) { var user = dao.Find(parameter.LoginId); if(user == null) return false; if(user.Password != parameter.Password) return false; var userSigned = new UserSigned(parameter.LoginId, parameter.IpAddress); bus.Send(userSigned); return true; } #endregion } }
apache-2.0
C#
01baf19d12793af780db88cc008f1d603f6cecd6
Update AssemblyInfo.cs
YAFNET/YAF.SampleWebApplication,YAFNET/YAF.SampleWebApplication,YAFNET/YAF.SampleWebApplication
YAF.SampleWebApplication/Properties/AssemblyInfo.cs
YAF.SampleWebApplication/Properties/AssemblyInfo.cs
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2021 Ingo Herbote * https://www.yetanotherforum.net/ * * 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.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("YAF.SampleWebApplication")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YAF.SampleWebApplication")] [assembly: AssemblyCopyright("Copyright © Yet Another Forum.NET")] [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("12f2a60e-9d98-45ea-bc2c-ccc0af015773")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("3.0.0.00")] [assembly: AssemblyFileVersion("3.0.0.00")]
/* Yet Another Forum.NET * Copyright (C) 2003-2005 Bjørnar Henden * Copyright (C) 2006-2013 Jaben Cargman * Copyright (C) 2014-2020 Ingo Herbote * https://www.yetanotherforum.net/ * * 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.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("YAF.SampleWebApplication")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("YAF.SampleWebApplication")] [assembly: AssemblyCopyright("Copyright © Yet Another Forum.NET")] [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("12f2a60e-9d98-45ea-bc2c-ccc0af015773")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("2.3.2.00")] [assembly: AssemblyFileVersion("2.3.2.00")]
apache-2.0
C#
d6f7908e55c579b50b9360bf8adc4daa6ad02274
Update system on deconstruct
fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation
UnityProject/Assets/Scripts/Construction/Managers/Deconstruction.cs
UnityProject/Assets/Scripts/Construction/Managers/Deconstruction.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Deconstruction : MonoBehaviour { public GameObject wallGirderPrefab; //Server only: public void TryTileDeconstruct(TileChangeManager tileChangeManager, TileType tileType, Vector3 cellPos) { var cellPosInt = Vector3Int.RoundToInt(cellPos); switch (tileType) { case TileType.Wall: DoWallDeconstruction(cellPosInt, tileChangeManager); tileChangeManager.gameObject.GetComponent<SystemManager>().UpdateAt(cellPosInt); break; } } //Server only public void ProcessDeconstructRequest(GameObject player, GameObject matrixRoot, TileType tileType, Vector3 cellPos, Vector3 worldCellPos) { if (Vector3.Distance(player.transform.position, worldCellPos) > 1.5f) { //Not in range on the server, do not process any further: return; } //Process Wall deconstruct request: if (tileType == TileType.Wall) { //Set up the action to be invoked when progress bar finishes: var progressFinishAction = new FinishProgressAction( FinishProgressAction.Action.TileDeconstruction, matrixRoot.GetComponent<TileChangeManager>(), tileType, cellPos, player ); //Start the progress bar: UIManager.ProgressBar.StartProgress(Vector3Int.RoundToInt(worldCellPos), 10f, progressFinishAction, player); } } private void DoWallDeconstruction(Vector3Int cellPos, TileChangeManager tcm) { tcm.RemoveTile(cellPos, TileChangeLayer.Wall); //TODO do sfx and spawn girders } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Deconstruction : MonoBehaviour { public GameObject wallGirderPrefab; //Server only: public void TryTileDeconstruct(TileChangeManager tileChangeManager, TileType tileType, Vector3 cellPos) { switch (tileType) { case TileType.Wall: DoWallDeconstruction(Vector3Int.RoundToInt(cellPos), tileChangeManager); break; } } //Server only public void ProcessDeconstructRequest(GameObject player, GameObject matrixRoot, TileType tileType, Vector3 cellPos, Vector3 worldCellPos) { if (Vector3.Distance(player.transform.position, worldCellPos) > 1.5f) { //Not in range on the server, do not process any further: return; } //Process Wall deconstruct request: if (tileType == TileType.Wall) { //Set up the action to be invoked when progress bar finishes: var progressFinishAction = new FinishProgressAction( FinishProgressAction.Action.TileDeconstruction, matrixRoot.GetComponent<TileChangeManager>(), tileType, cellPos, player ); //Start the progress bar: UIManager.ProgressBar.StartProgress(Vector3Int.RoundToInt(worldCellPos), 10f, progressFinishAction, player); } } private void DoWallDeconstruction(Vector3Int cellPos, TileChangeManager tcm) { tcm.RemoveTile(cellPos, TileChangeLayer.Wall); //TODO do sfx and spawn girders } }
agpl-3.0
C#
a6ad48c49778abe03e8d928f3540ee6d64fc54dc
Enable TLS 1.1 and 1.2 and disable SSLv3 for external calls.
opserver/Opserver,opserver/Opserver,vebin/Opserver,michaelholzheimer/Opserver,rducom/Opserver,manesiotise/Opserver,rducom/Opserver,GABeech/Opserver,michaelholzheimer/Opserver,volkd/Opserver,dteg/Opserver,vbfox/Opserver,maurobennici/Opserver,wuanunet/Opserver,GABeech/Opserver,mqbk/Opserver,dteg/Opserver,mqbk/Opserver,jeddytier4/Opserver,geffzhang/Opserver,VictoriaD/Opserver,maurobennici/Opserver,vbfox/Opserver,volkd/Opserver,VictoriaD/Opserver,geffzhang/Opserver,opserver/Opserver,manesiotise/Opserver,manesiotise/Opserver,vebin/Opserver,wuanunet/Opserver,jeddytier4/Opserver
Opserver.Core/OpserverCore.cs
Opserver.Core/OpserverCore.cs
using System.Net; using StackExchange.Elastic; namespace StackExchange.Opserver { public class OpserverCore { // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so. public static void Init() { try { ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix; // We're going to get errors - that's kinda the point of monitoring // No need to log every one here unless for crazy debugging //ElasticException.ExceptionOccurred += e => Current.LogException(e); } catch { } // Enable TLS only for SSL negotiation, SSL has been broken for some time. ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; } } }
using StackExchange.Elastic; namespace StackExchange.Opserver { public class OpserverCore { // Initializes various bits in OpserverCore like exception logging and such so that projects using the core need not load up all references to do so. public static void Init() { try { ElasticException.ExceptionDataPrefix = ExtensionMethods.ExceptionLogPrefix; // We're going to get errors - that's kinda the point of monitoring // No need to log every one here unless for crazy debugging //ElasticException.ExceptionOccurred += e => Current.LogException(e); } catch { } } } }
mit
C#
406142b084b121cb5f4c34a7e5203585c5141353
Fix V3025
bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL
Infrastructure/CSharpGL.Models/SimpleObjFileFormat/PartParsers/TexCoordParser.cs
Infrastructure/CSharpGL.Models/SimpleObjFileFormat/PartParsers/TexCoordParser.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { public class TexCoordParser : ObjParserBase { public override void Parse(ObjVNFContext context) { ObjVNFMesh mesh = context.Mesh; if (mesh.texCoords.Length > 0) { vec2[] texCoords = ArrangeTexCoords(context); mesh.texCoords = texCoords; } } private vec2[] ArrangeTexCoords(ObjVNFContext context) { var texCoords = new vec2[context.vertexCount]; ObjVNFMesh mesh = context.Mesh; for (int i = 0; i < context.faceCount; i++) { ObjVNFFace face = mesh.faces[i]; uint[] texCoordIndexes = (from item in face.TexCoordIndexes() select item).ToArray(); uint[] vertexIndexes = (from item in face.VertexIndexes() select item).ToArray(); if (texCoordIndexes.Length != vertexIndexes.Length) { throw new Exception(string.Format( "texCoordIndexes.Length [{0}] != vertexIndexes.Length [{1}]!", texCoordIndexes.Length, vertexIndexes.Length)); } for (int t = 0; t < vertexIndexes.Length; t++) { texCoords[vertexIndexes[t]] = mesh.texCoords[texCoordIndexes[t]]; } } return texCoords; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CSharpGL { public class TexCoordParser : ObjParserBase { public override void Parse(ObjVNFContext context) { ObjVNFMesh mesh = context.Mesh; if (mesh.texCoords.Length > 0) { vec2[] texCoords = ArrangeTexCoords(context); mesh.texCoords = texCoords; } } private vec2[] ArrangeTexCoords(ObjVNFContext context) { var texCoords = new vec2[context.vertexCount]; ObjVNFMesh mesh = context.Mesh; for (int i = 0; i < context.faceCount; i++) { ObjVNFFace face = mesh.faces[i]; uint[] texCoordIndexes = (from item in face.TexCoordIndexes() select item).ToArray(); uint[] vertexIndexes = (from item in face.VertexIndexes() select item).ToArray(); if (texCoordIndexes.Length != vertexIndexes.Length) { throw new Exception(string.Format( "normalIndexes.Length [{0}] != vertexIndexes.Length [{0}]!", texCoordIndexes.Length, vertexIndexes.Length)); } for (int t = 0; t < vertexIndexes.Length; t++) { texCoords[vertexIndexes[t]] = mesh.texCoords[texCoordIndexes[t]]; } } return texCoords; } } }
mit
C#
1363c238d7eebf0de5462c6e0200fe0a56f0ff1c
Implement unconditional toggle of the first item when a toolstrip menu is initialized.
Miragecoder/Urbanization,Miragecoder/Urbanization,Miragecoder/Urbanization
src/Mirage.Urbanization.WinForms/ToolstripMenuInitializer.cs
src/Mirage.Urbanization.WinForms/ToolstripMenuInitializer.cs
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Mirage.Urbanization.WinForms { public abstract class ToolstripMenuInitializer<TOption> where TOption : IToolstripMenuOption { protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options) { ToolStripMenuItem first = null; foreach (var option in options) { var localOption = option; var item = new ToolStripMenuItem(option.Name); item.Click += (sender, e) => { foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>()) x.Checked = false; item.Checked = true; _currentOption = localOption; if (OnSelectionChanged != null) OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption)); }; targetToopToolStripMenuItem.DropDownItems.Add(item); if (first == null) first = item; } first.PerformClick(); } public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged; private TOption _currentOption; public TOption GetCurrentOption() { return _currentOption; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace Mirage.Urbanization.WinForms { public abstract class ToolstripMenuInitializer<TOption> where TOption : IToolstripMenuOption { protected ToolstripMenuInitializer(ToolStripMenuItem targetToopToolStripMenuItem, IEnumerable<TOption> options) { foreach (var option in options) { var localOption = option; var item = new ToolStripMenuItem(option.Name); item.Click += (sender, e) => { foreach (var x in targetToopToolStripMenuItem.DropDownItems.Cast<ToolStripMenuItem>()) x.Checked = false; item.Checked = true; _currentOption = localOption; if (OnSelectionChanged != null) OnSelectionChanged(this, new ToolstripMenuOptionChangedEventArgs<TOption>(_currentOption)); }; targetToopToolStripMenuItem.DropDownItems.Add(item); item.PerformClick(); } } public event EventHandler<ToolstripMenuOptionChangedEventArgs<TOption>> OnSelectionChanged; private TOption _currentOption; public TOption GetCurrentOption() { return _currentOption; } } }
mit
C#
b93ea0ee210847ffe1d4e652c6ccc4efc0f68498
Update RyanYates.cs
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/RyanYates.cs
src/Firehose.Web/Authors/RyanYates.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 RyanYatesMVP : IFilterMyBlogPosts, IAmAMicrosoftMVP { public string FirstName => "Ryan"; public string LastName => "Yates"; public string ShortBioOrTagLine => "is a Microsoft MVP, Consultant at Black Marble, Lead Coordinator for UK PowerShell User Groups."; public string StateOrRegion => "England, UK"; public string EmailAddress => "ryan.yates@kilasuit.org"; public string TwitterHandle => "ryanyates1990"; public string GravatarHash => "3dfa95e0c1d6efa49d57dfd89010d0a7"; public GeoPosition Position => new GeoPosition(53.690760, -1.629070); public Uri WebSite => new Uri("https://blog.kilasuit.org/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.kilasuit.org/feed/"); } } public string GitHubHandle => "kilasuit"; public bool Filter(SyndicationItem item) { return item.Categories.Where(i => i.Name.Equals("PowerShell", StringComparison.OrdinalIgnoreCase)).Any(); } } }
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 RyanYatesMVP : IFilterMyBlogPosts, IAmAMicrosoftMVP { public string FirstName => "Ryan"; public string LastName => "Yates"; public string ShortBioOrTagLine => "is a Microsoft MVP, Consultant at Black Marble, Lead Coordinator for UK PowerShell User Groups."; public string StateOrRegion => "England, UK"; public string EmailAddress => "ryan.yates@kilasuit.org"; public string TwitterHandle => "ryanyates1990"; public string GravatarHash => "3dfa95e0c1d6efa49d57dfd89010d0a7"; public Uri WebSite => new Uri("https://blog.kilasuit.org/"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://blog.kilasuit.org/feed/"); } } public string GitHubHandle => "kilasuit"; public bool Filter(SyndicationItem item) { return item.Categories.Where(i => i.Name.Equals("PowerShell", StringComparison.OrdinalIgnoreCase)).Any(); } } }
mit
C#
8686eb8231b5154e243756f7cbd61c6950c2922e
Remove unused using
Cyberboss/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server,tgstation/tgstation-server,tgstation/tgstation-server-tools
src/Tgstation.Server.Api/Models/Internal/DreamDaemonLaunchParameters.cs
src/Tgstation.Server.Api/Models/Internal/DreamDaemonLaunchParameters.cs
using System.ComponentModel.DataAnnotations; namespace Tgstation.Server.Api.Models.Internal { /// <summary> /// Launch settings for DreamDaemon /// </summary> public class DreamDaemonLaunchParameters { /// <summary> /// If the BYOND web client can be used to connect to the game server /// </summary> [Required] public bool? AllowWebClient { get; set; } /// <summary> /// The <see cref="DreamDaemonSecurity"/> level of <see cref="DreamDaemon"/> /// </summary> [Required] public DreamDaemonSecurity? SecurityLevel { get; set; } /// <summary> /// The first port <see cref="DreamDaemon"/> uses. This should be the publically advertised port /// </summary> [Required] public ushort? PrimaryPort { get; set; } /// <summary> /// The second port <see cref="DreamDaemon"/> uses /// </summary> [Required] public ushort? SecondaryPort { get; set; } /// <summary> /// The DreamDaemon startup timeout in seconds /// </summary> [Required] public uint? StartupTimeout { get; set; } /// <summary> /// Check if we match a given set of <paramref name="otherParameters"/> /// </summary> /// <param name="otherParameters">The <see cref="DreamDaemonLaunchParameters"/> to compare against</param> /// <returns><see langword="true"/> if they match, <see langword="false"/> otherwise</returns> public bool Match(DreamDaemonLaunchParameters otherParameters) => AllowWebClient == otherParameters.AllowWebClient && SecurityLevel == otherParameters.SecurityLevel && PrimaryPort == otherParameters.PrimaryPort && SecondaryPort == otherParameters.SecondaryPort && StartupTimeout == otherParameters.StartupTimeout; } }
using System; using System.ComponentModel.DataAnnotations; namespace Tgstation.Server.Api.Models.Internal { /// <summary> /// Launch settings for DreamDaemon /// </summary> public class DreamDaemonLaunchParameters { /// <summary> /// If the BYOND web client can be used to connect to the game server /// </summary> [Required] public bool? AllowWebClient { get; set; } /// <summary> /// The <see cref="DreamDaemonSecurity"/> level of <see cref="DreamDaemon"/> /// </summary> [Required] public DreamDaemonSecurity? SecurityLevel { get; set; } /// <summary> /// The first port <see cref="DreamDaemon"/> uses. This should be the publically advertised port /// </summary> [Required] public ushort? PrimaryPort { get; set; } /// <summary> /// The second port <see cref="DreamDaemon"/> uses /// </summary> [Required] public ushort? SecondaryPort { get; set; } /// <summary> /// The DreamDaemon startup timeout in seconds /// </summary> [Required] public uint? StartupTimeout { get; set; } /// <summary> /// Check if we match a given set of <paramref name="otherParameters"/> /// </summary> /// <param name="otherParameters">The <see cref="DreamDaemonLaunchParameters"/> to compare against</param> /// <returns><see langword="true"/> if they match, <see langword="false"/> otherwise</returns> public bool Match(DreamDaemonLaunchParameters otherParameters) => AllowWebClient == otherParameters.AllowWebClient && SecurityLevel == otherParameters.SecurityLevel && PrimaryPort == otherParameters.PrimaryPort && SecondaryPort == otherParameters.SecondaryPort && StartupTimeout == otherParameters.StartupTimeout; } }
agpl-3.0
C#
8ee875f7cdaf3fbb756f4b12b827c83d56dc615e
Remove unused overload of Remove for QueryStringParametersList
vivet/GoogleApi
GoogleApi/Helpers/QueryStringParametersList.cs
GoogleApi/Helpers/QueryStringParametersList.cs
using System; using System.Collections.Generic; using System.Linq; namespace GoogleApi.Helpers { /// <summary> /// Helper class to build querystrings for Google Requests. /// </summary> public sealed class QueryStringParametersList : Dictionary<string, string>, IDictionary<string, string> { /// <summary> /// Adds a parameter. /// </summary> /// <param name="key"></param> /// <param name="value"></param> public new void Add(string key, string value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); if (base.ContainsKey(key)) { base[key] = value; } else { base.Add(key, value); } } /// <summary> /// returns the query string collection as url paremer string. /// </summary> /// <returns></returns> public string GetQueryStringPostfix() { return string.Join("&", this.Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value))); } } }
using System; using System.Collections.Generic; using System.Linq; namespace GoogleApi.Helpers { /// <summary> /// Helper class to build querystrings for Google Requests. /// </summary> public sealed class QueryStringParametersList : Dictionary<string, string>, IDictionary<string, string> { /// <summary> /// Adds a parameter. /// </summary> /// <param name="key"></param> /// <param name="value"></param> public new void Add(string key, string value) { if (key == null) throw new ArgumentNullException(nameof(key)); if (value == null) throw new ArgumentNullException(nameof(value)); if (base.ContainsKey(key)) { base[key] = value; } else { base.Add(key, value); } } /// <summary> /// Remove a parameter. /// </summary> /// <param name="key"></param> public new bool Remove(string key) { if (key == null) throw new ArgumentNullException(nameof(key)); base.Remove(key); return true; } /// <summary> /// returns the query string collection as url paremer string. /// </summary> /// <returns></returns> public string GetQueryStringPostfix() { return string.Join("&", this.Select(x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value))); } } }
mit
C#
672c36166644a8c87ec2bfca99e05ed74ffb0b42
Mark AFNetworkHandler obsolete.
Ideine/Cheesebaron.MvxPlugins,Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins
ModernHttpClient/Core/HttpClientHandlerType.cs
ModernHttpClient/Core/HttpClientHandlerType.cs
using System; namespace Cheesebaron.MvxPlugins.ModernHttpClient { public enum HttpClientHandlerType { /// <summary> /// AFNetworkHandler (Only available on iOS) /// </summary> [Obsolete("Use CFNetworkHandler instead")] AFNetworkHandler = 0, /// <summary> /// CFNetworkHandler (Only available on iOS) /// </summary> CFNetworkHandler = 1, /// <summary> /// NSUrlSessionHandler (Only available on iOS) /// </summary> NSUrlSessionHandler = 2, /// <summary> /// OkHttpHandler (Only available on Android) /// </summary> OkHttpHandler = 3, /// <summary> /// HttpClientHandler, default handler used in HttpClient /// </summary> HttpClientHandler = 4 } }
namespace Cheesebaron.MvxPlugins.ModernHttpClient { public enum HttpClientHandlerType { /// <summary> /// OBSOLETE!!! AFNetworkHandler (Only available on iOS) /// </summary> AFNetworkHandler = 0, /// <summary> /// CFNetworkHandler (Only available on iOS) /// </summary> CFNetworkHandler = 1, /// <summary> /// NSUrlSessionHandler (Only available on iOS) /// </summary> NSUrlSessionHandler = 2, /// <summary> /// OkHttpHandler (Only available on Android) /// </summary> OkHttpHandler = 3, /// <summary> /// HttpClientHandler, default handler used in HttpClient /// </summary> HttpClientHandler = 4 } }
apache-2.0
C#
dc15b6ff7d93e196b2005bea58d67bbe29fb11c0
add aliases for command line args
skolima/NuKeeper,skolima/NuKeeper,skolima/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper,NuKeeperDotNet/NuKeeper,skolima/NuKeeper,NuKeeperDotNet/NuKeeper,AnthonySteele/NuKeeper,NuKeeperDotNet/NuKeeper
NuKeeper/Configuration/CommandLineArguments.cs
NuKeeper/Configuration/CommandLineArguments.cs
using System; using EasyConfig.Attributes; namespace NuKeeper.Configuration { public class CommandLineArguments { [CommandLine("mode", "m"), Required] public string Mode; [CommandLine("github_token", "t"), Required, SensitiveInformation] public string GithubToken; [CommandLine("github_repository_uri", "repo")] public Uri GithubRepositoryUri; [CommandLine("github_organisation_name", "org")] public string GithubOrganisationName; [CommandLine("github_api_endpoint", "api"), Default("https://api.github.com")] public Uri GithubApiEndpoint; } }
using System; using EasyConfig.Attributes; namespace NuKeeper.Configuration { public class CommandLineArguments { [CommandLine("mode"), Required] public string Mode; [CommandLine("github_token"), Required, SensitiveInformation] public string GithubToken; [CommandLine("github_repository_uri")] public Uri GithubRepositoryUri; [CommandLine("github_organisation_name")] public string GithubOrganisationName; [CommandLine("github_api_endpoint"), Default("https://api.github.com")] public Uri GithubApiEndpoint; } }
apache-2.0
C#
8fb13e0ad3662633e7c514311dec9ac71bb0ad6e
Update Epsilon.cs
idormenco/PolyBool.Net
Polybool.Net/Objects/Epsilon.cs
Polybool.Net/Objects/Epsilon.cs
namespace Polybool.Net.Objects { public static class Epsilon { public static decimal Eps { get; set; } = 0.00001m; } }
namespace Polybool.Net.Objects { public static class Epsilon { public static decimal Eps => 0.00001m; } }
mit
C#
59c4d0f260bf134fb62e8d4ced96df1838956314
Update Log.cs
wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D
src/Draw2D/Log.cs
src/Draw2D/Log.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Draw2D { public static class Log { public static void WriteLine(string message) { #if DEBUG System.Diagnostics.Debug.WriteLine(message); #else System.Console.WriteLine(message); #endif } } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; namespace Draw2D { public static class Log { public static void WriteLine(string message) { Console.WriteLine(message); } } }
mit
C#
10842eb0d720a8dd5272a24c1bcf319d7fb56cf1
Update SignIn.cshtml
tariqs-repo/SignalR-Notification-State-Manager,tariqs-repo/SignalR-Notification-State-Manager
Sample_Project/SingnalRNotificationStateManager/Views/Home/SignIn.cshtml
Sample_Project/SingnalRNotificationStateManager/Views/Home/SignIn.cshtml
 @{ ViewBag.Title = "SingIn"; } <h2>SingIn</h2> <b>Mock login. Type anything to signin.</b> @using(Html.BeginForm("SignIn", "Home")) { @Html.ValidationSummary() <table> <tr> <td>Username</td> <td>@Html.TextBox("Username", "dhetteri")</td> </tr> <tr> <td>Password</td> <td>@Html.TextBox("password", "vuila gesi", new { type="password" })</td> </tr> <tr> <td></td> <td><input type="submit" value="Signin" /></td> </tr> </table> }
 @{ ViewBag.Title = "SingIn"; } <h2>SingIn</h2> <b>Mock login. Type anything to signin.</b> @using(Html.BeginForm("SignIn", "Home")) { @Html.ValidationSummary() <table> <tr> <td>Username</td> <td>@Html.TextBox("Username", "dhetteri")</td> </tr> <tr> <td>Password</td> <td>@Html.TextBox("password", "vuila gesi", new { type="password" })</td> </tr> <tr> <td></td> <td><input type="submit" value="Submit" /></td> </tr> </table> }
apache-2.0
C#
b03ccbeeacbb94fd4d9d3c7e8129265006251661
Update HarvestInfoCache.cs
kbilsted/StatePrinter
StatePrinter/Introspection/HarvestInfoCache.cs
StatePrinter/Introspection/HarvestInfoCache.cs
// Copyright 2014 Kasper B. Graversen // // 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.Collections.Generic; using System.Threading; namespace StatePrinting.Introspection { /// <summary> /// Assume that types don't change at run-time. Cache harvested information. /// </summary> class HarvestInfoCache : IDisposable { /// <summary> /// Due to supporting C# 3.5 we cannot use ConcurrentDictionary /// </summary> readonly Dictionary<Type, ReflectionInfo> harvestCache = new Dictionary<Type, ReflectionInfo>(); readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(); public ReflectionInfo TryGet(Type type) { cacheLock.EnterReadLock(); try { ReflectionInfo res; harvestCache.TryGetValue(type, out res); return res; } finally { cacheLock.ExitReadLock(); } } public void TryAdd(Type type, ReflectionInfo fields) { cacheLock.EnterWriteLock(); try { if (!harvestCache.ContainsKey(type)) harvestCache.Add(type, fields); } finally { cacheLock.ExitWriteLock(); } } public void Dispose() { cacheLock.Dispose(); } } }
// Copyright 2014 Kasper B. Graversen // // 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.Collections.Generic; using System.Threading; namespace StatePrinting.Introspection { /// <summary> /// Assume that types don't change at run-time. Cache harvested information. /// </summary> class HarvestInfoCache : IDisposable { /// <summary> /// Due to supporting C# 3.5 we cannot use ConcurrentDictionary /// </summary> readonly Dictionary<Type, ReflectionInfo> harvestCache = new Dictionary<Type, ReflectionInfo>(); readonly ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim(); public ReflectionInfo TryGet(Type type) { cacheLock.EnterReadLock(); try { ReflectionInfo res; harvestCache.TryGetValue(type, out res); return res; } finally { cacheLock.ExitReadLock(); } } public void TryAdd(Type type, ReflectionInfo fields) { cacheLock.EnterWriteLock(); try { if (!harvestCache.ContainsKey(type)) harvestCache.Add(type, fields); } finally { cacheLock.ExitWriteLock(); } } public void Dispose() { cacheLock.Dispose(); } } }
apache-2.0
C#
d925729f3f6a297f14bcab9c4f4f23fae0568847
Set up project
bcreagh/story-generator
StoryGenerator/Controllers/ValuesController.cs
StoryGenerator/Controllers/ValuesController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace StoryGenerator.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2", "value3" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace StoryGenerator.Controllers { [Route("api/[controller]")] public class ValuesController : Controller { // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
mit
C#
fb40cb20535fbb7071931d8eb3d82d6f4c762022
Raise store mocking project version.
affecto/dotnet-IdentityManagement
IdentityManagement.Store.Mocking/Properties/AssemblyInfo.cs
IdentityManagement.Store.Mocking/Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")] [assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")] [assembly: AssemblyProduct("Affecto.IdentityManagement")] [assembly: AssemblyCompany("Affecto")] [assembly: AssemblyVersion("8.0.4.0")] [assembly: AssemblyFileVersion("8.0.4.0")] // This version is used by NuGet: [assembly: AssemblyInformationalVersion("8.0.4-prerelease01")]
using System.Reflection; [assembly: AssemblyTitle("Affecto.IdentityManagement.Store.Mocking")] [assembly: AssemblyDescription("Identity Management store layer using Effort mock database.")] [assembly: AssemblyProduct("Affecto.IdentityManagement")] [assembly: AssemblyCompany("Affecto")] [assembly: AssemblyVersion("8.0.3.0")] [assembly: AssemblyFileVersion("8.0.3.0")] // This version is used by NuGet: [assembly: AssemblyInformationalVersion("8.0.3")]
mit
C#
eb95c6999f0f6d1b5b019fe67e99823a6eb8d82e
update WinPhone81
jcphlux/XamarinAudioManager
AudioManager.Demo/AudioManager.Demo.WinPhone/MainPage.xaml.cs
AudioManager.Demo/AudioManager.Demo.WinPhone/MainPage.xaml.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AudioManager.Demo.WinPhone { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : IAudioManagerContainer { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new AudioManager.Demo.App()); AudioManagerContainer = this.Content as Canvas; } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } public Canvas AudioManagerContainer { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238 namespace AudioManager.Demo.WinPhone { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new AudioManager.Demo.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
mit
C#
9b0274ecaabf14728bb44de43135429ee41809a9
Debug Util: Wraps log error.
ethankennerly/UnityToykit
DebugUtil.cs
DebugUtil.cs
using System.Diagnostics; using UnityEngine; namespace Finegamedesign.Utils { /// <summary> /// Wrapper of logging. /// Conditionally compiles if in debug mode or editor. /// </summary> public sealed class DebugUtil { [Conditional("DEBUG")] [Conditional("UNITY_EDITOR")] public static void Log(string message) { UnityEngine.Debug.Log(message); } [Conditional("DEBUG")] [Conditional("UNITY_EDITOR")] public static void LogWarning(string message) { UnityEngine.Debug.LogWarning(message); } public static void LogError(string message) { UnityEngine.Debug.LogError(message); } [Conditional("DEBUG")] [Conditional("UNITY_EDITOR")] public static void Assert(bool condition, string message = "") { UnityEngine.Debug.Assert(condition, message); } } }
using System.Diagnostics; using UnityEngine; namespace Finegamedesign.Utils { /// <summary> /// Wrapper of logging. /// Conditionally compiles if in debug mode or editor. /// </summary> public sealed class DebugUtil { [Conditional("DEBUG")] [Conditional("UNITY_EDITOR")] public static void Log(string message) { UnityEngine.Debug.Log(message); } [Conditional("DEBUG")] [Conditional("UNITY_EDITOR")] public static void LogWarning(string message) { UnityEngine.Debug.LogWarning(message); } [Conditional("DEBUG")] [Conditional("UNITY_EDITOR")] public static void Assert(bool condition, string message = "") { UnityEngine.Debug.Assert(condition, message); } } }
mit
C#
1bfa28a4c3a3eb6b5df24c63bc9a9c99c6cee4d5
fix unicorn not loading health overlay
StefanoFiumara/Harry-Potter-Unity
Assets/Scripts/HarryPotterUnity/Cards/CareOfMagicalCreatures/Creatures/Unicorn.cs
Assets/Scripts/HarryPotterUnity/Cards/CareOfMagicalCreatures/Creatures/Unicorn.cs
using JetBrains.Annotations; namespace HarryPotterUnity.Cards.CareOfMagicalCreatures.Creatures { [UsedImplicitly] public class Unicorn : BaseCreature { public override void OnInPlayBeforeTurnAction() { Player.AddActions(1); } public override void OnEnterInPlayAction() { base.OnEnterInPlayAction(); Player.AddActions(1); } } }
using JetBrains.Annotations; namespace HarryPotterUnity.Cards.CareOfMagicalCreatures.Creatures { [UsedImplicitly] public class Unicorn : BaseCreature { public override void OnInPlayBeforeTurnAction() { Player.AddActions(1); } public override void OnEnterInPlayAction() { Player.AddActions(1); } } }
mit
C#
d62f08d5896558d14331c20cddb5b0cc7ea09344
Update file version to 3.0.4.0
JKennedy24/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps,amay077/Xamarin.Forms.GoogleMaps
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2018"; public const string Trademark = ""; public const string Version = "3.0.4.0"; } }
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2018"; public const string Trademark = ""; public const string Version = "3.0.3.0"; } }
mit
C#
51fb5bf595b67c2b5108c94d1e454b1e8ce2f1e2
Change RaycastSingle return type (it shouldn't be List<>)
florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho
Bindings/Portable/Octree.cs
Bindings/Portable/Octree.cs
using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Urho { partial class Octree { [DllImport(Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Octree_Raycast(IntPtr handle, ref Ray ray, ref RayQueryLevel level, float maxDistance, uint drawableFlags, uint viewMask, bool single, out int count); List<RayQueryResult> Raycast(Ray ray, RayQueryLevel level, float maxDistance, DrawableFlags drawableFlags, bool single, uint viewMask = UInt32.MaxValue) { Runtime.ValidateRefCounted(this); List<RayQueryResult> result = new List<RayQueryResult>(); int count; var ptr = Octree_Raycast(Handle, ref ray, ref level, maxDistance, (uint)drawableFlags, viewMask, single, out count); if (ptr == IntPtr.Zero) return result; int structSize = Marshal.SizeOf(typeof (RayQueryResult)); for (int i = 0; i < count; i++) { IntPtr data = new IntPtr(ptr.ToInt64() + structSize * i); RayQueryResult item = (RayQueryResult)Marshal.PtrToStructure(data, typeof(RayQueryResult)); result.Add(item); } return result; } public List<RayQueryResult> Raycast(Ray ray, RayQueryLevel level, float maxDistance, DrawableFlags drawableFlags, uint viewMask = UInt32.MaxValue) { Runtime.ValidateRefCounted(this); return Raycast(ray, level, maxDistance, drawableFlags, false, viewMask); } public RayQueryResult? RaycastSingle(Ray ray, RayQueryLevel level, float maxDistance, DrawableFlags drawableFlags, uint viewMask = UInt32.MaxValue) { Runtime.ValidateRefCounted(this); var result = Raycast(ray, level, maxDistance, drawableFlags, true, viewMask); if (result != null && result.Count > 0) return result[0]; return null; } } }
using System; using System.Collections.Generic; using System.Runtime.InteropServices; namespace Urho { partial class Octree { [DllImport(Consts.NativeImport, CallingConvention = CallingConvention.Cdecl)] internal static extern IntPtr Octree_Raycast(IntPtr handle, ref Ray ray, ref RayQueryLevel level, float maxDistance, uint drawableFlags, uint viewMask, bool single, out int count); List<RayQueryResult> Raycast(Ray ray, RayQueryLevel level, float maxDistance, DrawableFlags drawableFlags, bool single, uint viewMask = UInt32.MaxValue) { Runtime.ValidateRefCounted(this); List<RayQueryResult> result = new List<RayQueryResult>(); int count; var ptr = Octree_Raycast(Handle, ref ray, ref level, maxDistance, (uint)drawableFlags, viewMask, single, out count); if (ptr == IntPtr.Zero) return result; int structSize = Marshal.SizeOf(typeof (RayQueryResult)); for (int i = 0; i < count; i++) { IntPtr data = new IntPtr(ptr.ToInt64() + structSize * i); RayQueryResult item = (RayQueryResult)Marshal.PtrToStructure(data, typeof(RayQueryResult)); result.Add(item); } return result; } public List<RayQueryResult> Raycast(Ray ray, RayQueryLevel level, float maxDistance, DrawableFlags drawableFlags, uint viewMask = UInt32.MaxValue) { Runtime.ValidateRefCounted(this); return Raycast(ray, level, maxDistance, drawableFlags, false, viewMask); } public List<RayQueryResult> RaycastSingle(Ray ray, RayQueryLevel level, float maxDistance, DrawableFlags drawableFlags, uint viewMask = UInt32.MaxValue) { Runtime.ValidateRefCounted(this); return Raycast(ray, level, maxDistance, drawableFlags, true, viewMask); } } }
mit
C#
a6c07d41716f29ccf92bd329b95eccd917226283
fix Upgrade_20220607_DockerNodeVersion
signumsoftware/framework,signumsoftware/framework
Signum.Upgrade/Upgrades/Upgrade_20220607_DockerNodeVersion.cs
Signum.Upgrade/Upgrades/Upgrade_20220607_DockerNodeVersion.cs
namespace Signum.Upgrade.Upgrades; class Upgrade_20220601_Dockerfile : CodeUpgradeBase { public override string Description => "Update Dockerfile to Node 16"; public override void Execute(UpgradeContext uctx) { uctx.ChangeCodeFile(@"Southwind.React\Dockerfile", file => { file.Replace("https://deb.nodesource.com/setup_15.x", "https://deb.nodesource.com/setup_16.x"); }); } }
namespace Signum.Upgrade.Upgrades; class Upgrade_20220601_Dockerfile : CodeUpgradeBase { public override string Description => "Update Dockerfile to Node 16"; public override void Execute(UpgradeContext uctx) { uctx.ForeachCodeFile(@"Souwhtind.React\Dockerfile", file => { file.Replace("https://deb.nodesource.com/setup_15.x", "https://deb.nodesource.com/setup_16.x"); }); } }
mit
C#
ba537e225d758869039619139a67f7afa14c86a9
fix build.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/Dialogs/DialogViewModelBase.cs
WalletWasabi.Fluent/ViewModels/Dialogs/DialogViewModelBase.cs
using System; using System.Reactive.Linq; using System.Threading.Tasks; using ReactiveUI; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent.ViewModels.Dialogs { /// <summary> /// CommonBase class. /// </summary> public abstract class DialogViewModelBase : ViewModelBase { // Intended to be empty. } }
using System; using System.Reactive.Linq; using System.Threading.Tasks; using ReactiveUI; namespace WalletWasabi.Fluent.ViewModels.Dialogs { /// <summary> /// CommonBase class. /// </summary> public abstract class DialogViewModelBase : ViewModelBase { // Intended to be empty. } }
mit
C#
5f45008f08e27f92ece924292d43d0c985969977
update training program extension methods to match employer commitments
SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice,SkillsFundingAgency/das-providerapprenticeshipsservice
src/SFA.DAS.ProviderApprenticeshipsService.Application/Extensions/ITrainingProgrammeExtensions.cs
src/SFA.DAS.ProviderApprenticeshipsService.Application/Extensions/ITrainingProgrammeExtensions.cs
using System; using System.Linq; using SFA.DAS.ProviderApprenticeshipsService.Domain.Models.ApprenticeshipCourse; namespace SFA.DAS.ProviderApprenticeshipsService.Application.Extensions { public static class ITrainingProgrammeExtensions { public static bool IsActiveOn(this ITrainingProgramme course, DateTime date) { return GetStatusOn(course.EffectiveFrom, course.EffectiveTo, date) == TrainingProgrammeStatus.Active; } public static TrainingProgrammeStatus GetStatusOn(this ITrainingProgramme course, DateTime date) { return GetStatusOn(course.EffectiveFrom, course.EffectiveTo, date); } public static int FundingCapOn(this ITrainingProgramme course, DateTime date) { //todo: would probably be better to return int? null or throw if out of range if (!course.IsActiveOn(date)) return 0; var applicableFundingPeriod = course.FundingPeriods.FirstOrDefault(x => GetStatusOn(x.EffectiveFrom, x.EffectiveTo, date) == TrainingProgrammeStatus.Active); return applicableFundingPeriod?.FundingCap ?? 0; } /// <remarks> /// we make use of the same logic to determine ActiveOn and FundingBandOn so that if the programme is active, it should fall within a funding band /// </remarks> private static TrainingProgrammeStatus GetStatusOn(DateTime? effectiveFrom, DateTime? effectiveTo, DateTime date) { var dateOnly = date.Date; if (effectiveFrom.HasValue && effectiveFrom.Value.FirstOfMonth() > dateOnly) return TrainingProgrammeStatus.Pending; if (!effectiveTo.HasValue || effectiveTo.Value >= dateOnly) return TrainingProgrammeStatus.Active; return TrainingProgrammeStatus.Expired; } } }
using System; using System.Linq; using SFA.DAS.ProviderApprenticeshipsService.Domain.Models.ApprenticeshipCourse; namespace SFA.DAS.ProviderApprenticeshipsService.Application.Extensions { public static class ITrainingProgrammeExtensions { public static bool IsActiveOn(this ITrainingProgramme course, DateTime effectiveDate) { return (!course.EffectiveFrom.HasValue || course.EffectiveFrom.Value.FirstOfMonth() <= effectiveDate.Date) && (!course.EffectiveTo.HasValue || course.EffectiveTo.Value.Date >= effectiveDate.FirstOfMonth()); } public static TrainingProgrammeStatus GetStatusOn(this ITrainingProgramme course, DateTime effectiveDate) { if ((!course.EffectiveFrom.HasValue || course.EffectiveFrom.Value.FirstOfMonth() <= effectiveDate)) { if (!course.EffectiveTo.HasValue || course.EffectiveTo.Value >= effectiveDate.FirstOfMonth()) { return TrainingProgrammeStatus.Active; } return TrainingProgrammeStatus.Expired; } return TrainingProgrammeStatus.Pending; } public static int FundingCapOn(this ITrainingProgramme course, DateTime effectiveDate) { if (!course.IsActiveOn(effectiveDate)) return 0; var applicableFundingPeriod = course.FundingPeriods.FirstOrDefault(x => (!x.EffectiveFrom.HasValue || x.EffectiveFrom.Value.Date <= effectiveDate.Date) && (!x.EffectiveTo.HasValue || x.EffectiveTo.Value.Date >= effectiveDate.Date)); return applicableFundingPeriod?.FundingCap ?? 0; } } }
mit
C#
159a0818b37afa2de5309ed45570c5ebd4c784b0
Remove unused code, but still can't remove the HystrixTask class since the reference to CircuitBreaker is otherwise optimized out. Need to make a stronger connection without as much weight.
bloritsch/DHaven.Faux
DHaven.Faux/HttpSupport/HystrixTask.cs
DHaven.Faux/HttpSupport/HystrixTask.cs
using System.Diagnostics.CodeAnalysis; using System.Reactive; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Steeltoe.CircuitBreaker.Hystrix; namespace DHaven.Faux.HttpSupport { [SuppressMessage("ReSharper", "UnusedMember.Global")] public class HystrixTask : HystrixCommand { private readonly Task run; private readonly Task fallback; public HystrixTask(IHystrixCommandOptions options, Task run, Task fallback, ILogger logger) : base(options, null, null, logger) { this.run = run; this.fallback = fallback; } protected override async Task<Unit> RunAsync() { await run; return Unit.Default; } protected override async Task<Unit> RunFallbackAsync() { await fallback; return Unit.Default; } } }
using System.Diagnostics.CodeAnalysis; using System.Reactive; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Steeltoe.CircuitBreaker.Hystrix; namespace DHaven.Faux.HttpSupport { [SuppressMessage("ReSharper", "UnusedMember.Global")] public class HystrixTask : HystrixCommand { private readonly Task run; private readonly Task fallback; public HystrixTask(IHystrixCommandOptions options, Task run, Task fallback, ILogger logger) : base(options, null, null, logger) { this.run = run; this.fallback = fallback; } protected override async Task<Unit> RunAsync() { await run; return Unit.Default; } protected override async Task<Unit> RunFallbackAsync() { await fallback; return Unit.Default; } } [SuppressMessage("ReSharper", "UnusedMember.Global")] public class HystrixTask<TResult> : HystrixCommand<TResult> { private readonly Task<TResult> run; private readonly Task<TResult> fallback; public HystrixTask(IHystrixCommandOptions options, Task<TResult> run, Task<TResult> fallback, ILogger logger) : base(options, null, null, logger) { this.run = run; this.fallback = fallback; } protected override Task<TResult> RunAsync() { return run; } protected override Task<TResult> RunFallbackAsync() { return fallback; } } }
apache-2.0
C#
1487ed68cf04f37f52fba1065395bb9751cfff3c
Remove Teamcity hack
slvnperron/NUnit-retry
src/NUnit-retry/RetriedTestMethod.cs
src/NUnit-retry/RetriedTestMethod.cs
// ///////////////////////////////////////////////////////////////////// // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // ///////////////////////////////////////////////////////////////////// using System; namespace NUnit_retry { using System.Reflection; using NUnit.Core; public class RetriedTestMethod : NUnitTestMethod { private readonly int requiredPassCount; private readonly int tryCount; public RetriedTestMethod(MethodInfo method, int tryCount, int requiredPassCount) : base(method) { this.tryCount = tryCount; this.requiredPassCount = requiredPassCount; } public override TestResult Run(EventListener listener, ITestFilter filter) { var successCount = 0; TestResult failureResult = null; for (var i = 0; i < this.tryCount; i++) { var result = base.Run(listener, filter); if (!TestFailed(result)) { if (i == 0) { return result; } if (++successCount >= this.requiredPassCount) { return result; } } else { failureResult = result; } } return failureResult; } private static bool TestFailed(TestResult result) { return result.ResultState == ResultState.Error || result.ResultState == ResultState.Failure; } } }
// ///////////////////////////////////////////////////////////////////// // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // ///////////////////////////////////////////////////////////////////// using System; namespace NUnit_retry { using System.Reflection; using NUnit.Core; public class RetriedTestMethod : NUnitTestMethod { private readonly int requiredPassCount; private readonly int tryCount; protected static int repeatedFailures = 0; public RetriedTestMethod(MethodInfo method, int tryCount, int requiredPassCount) : base(method) { this.tryCount = tryCount; this.requiredPassCount = requiredPassCount; } public override TestResult Run(EventListener listener, ITestFilter filter) { var successCount = 0; TestResult failureResult = null; for (var i = 0; i < this.tryCount; i++) { var result = base.Run(listener, filter); if (!TestFailed(result)) { if (i == 0) { return result; } if (++successCount >= this.requiredPassCount) { // Small hack for teamCity if (repeatedFailures == 0) Console.WriteLine("\n##teamcity[buildStatus status='SUCCESS' text='{build.status.text}. Important: all failed tests are passed succesfully after fail.']\n"); return result; } } else { failureResult = result; } } repeatedFailures++; return failureResult; } private static bool TestFailed(TestResult result) { return result.ResultState == ResultState.Error || result.ResultState == ResultState.Failure; } } }
mit
C#
b7d0dda0cac4d41b3cb064773ac4eab754c01816
revise version
plantain-00/Bootstrap.Pagination,plantain-00/Bootstrap.Pagination
Bootstrap.Pagination.net40/Properties/AssemblyInfo.cs
Bootstrap.Pagination.net40/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Bootstrap.Pagination")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Bootstrap.Pagination")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("757a88cf-4c42-4aef-96d5-c92e4932befc")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")]
using System.Reflection; using System.Runtime.InteropServices; // 有关程序集的常规信息通过以下 // 特性集控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("Bootstrap.Pagination")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Bootstrap.Pagination")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 使此程序集中的类型 // 对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型, // 则将该类型上的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("757a88cf-4c42-4aef-96d5-c92e4932befc")] // 程序集的版本信息由下面四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值, // 方法是按如下所示使用“*”: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.2.0")] [assembly: AssemblyFileVersion("1.0.2.0")]
mit
C#
cd3eb73c6b3e5a3350405e3eb300046c60291ad1
Remove leftover var: Address from StatusResponse
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
HiddenWallet/ChaumianCoinJoin/Models/StatusResponse.cs
HiddenWallet/ChaumianCoinJoin/Models/StatusResponse.cs
using HiddenWallet.SharedApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HiddenWallet.ChaumianCoinJoin.Models { public class StatusResponse : BaseResponse { public StatusResponse() => Success = true; public string Phase { get; set; } public string Denomination { get; set; } public int AnonymitySet { get; set; } public int TimeSpentInInputRegistrationInSeconds { get; set; } public int MaximumInputsPerAlices { get; set; } public string FeePerInputs { get; set; } public string FeePerOutputs { get; set; } public string Version { get; set; } } }
using HiddenWallet.SharedApi.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HiddenWallet.ChaumianCoinJoin.Models { public class StatusResponse : BaseResponse { public StatusResponse() => Success = true; public string Address { get; set; } public string Phase { get; set; } public string Denomination { get; set; } public int AnonymitySet { get; set; } public int TimeSpentInInputRegistrationInSeconds { get; set; } public int MaximumInputsPerAlices { get; set; } public string FeePerInputs { get; set; } public string FeePerOutputs { get; set; } public string Version { get; set; } } }
mit
C#
a367d333046e3e951f80c42244fb8fbc09474e31
add iequatable for neural network gene
jobeland/NeuralNetwork
NeuralNetwork/NeuralNetwork/Genes/NeuralNetworkGene.cs
NeuralNetwork/NeuralNetwork/Genes/NeuralNetworkGene.cs
using System; using System.Collections.Generic; using System.Linq; namespace ArtificialNeuralNetwork.Genes { public class NeuralNetworkGene : IEquatable<NeuralNetworkGene> { public LayerGene InputGene; public IList<LayerGene> HiddenGenes; public LayerGene OutputGene; #region Equality Members /// <summary> /// Returns true if the fields of the NeuralNetworkGene objects are the same. /// </summary> /// <param name="obj">The NeuralNetworkGene object to compare with.</param> /// <returns> /// True if the fields of the NeuralNetworkGene objects are the same; false otherwise. /// </returns> public override bool Equals(object obj) { if (obj == null || GetType() != obj.GetType()) { return false; } return Equals(obj as NeuralNetworkGene); } /// <summary> /// Returns true if the fields of the NeuralNetworkGene objects are the same. /// </summary> /// <param name="neuralNetworkGene">The NeuralNetworkGene object to compare with.</param> /// <returns> /// True if the fields of the NeuralNetworkGene objects are the same; false otherwise. /// </returns> public bool Equals(NeuralNetworkGene neuralNetworkGene) { if (neuralNetworkGene == null) { return false; } if (neuralNetworkGene.InputGene != InputGene || neuralNetworkGene.OutputGene != OutputGene || neuralNetworkGene.HiddenGenes.Count != HiddenGenes.Count) { return false; } return !HiddenGenes.Where((t, i) => t != neuralNetworkGene.HiddenGenes[i]).Any(); } /// <summary> /// Returns true if the fields of the NeuralNetworkGene objects are the same. /// </summary> /// <param name="a">The NeuralNetworkGene object to compare.</param> /// <param name="b">The NeuralNetworkGene object to compare.</param> /// <returns> /// True if the objects are the same, are both null, or have the same values; /// false otherwise. /// </returns> public static bool operator ==(NeuralNetworkGene a, NeuralNetworkGene b) { // If both are null, or both are same instance, return true. if (ReferenceEquals(a, b)) { return true; } // If one or the other is null, return false. if (ReferenceEquals(a, null) || ReferenceEquals(b, null)) { return false; } return a.Equals(b); } public static bool operator !=(NeuralNetworkGene a, NeuralNetworkGene b) { return !(a == b); } // Following this algorithm: http://stackoverflow.com/a/263416 /// <summary> /// Returns the hash code of the NeuralNetworkGene. /// </summary> /// <returns>The hash code of the NeuralNetworkGene.</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hash = (int)2166136261; hash = hash * 16777619 ^ InputGene.GetHashCode() ^ HiddenGenes.GetHashCode() ^ OutputGene.GetHashCode(); return hash; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; namespace ArtificialNeuralNetwork.Genes { public class NeuralNetworkGene { public LayerGene InputGene; public IList<LayerGene> HiddenGenes; public LayerGene OutputGene; } }
mit
C#
84f113912f1e8253d95d3cfe181e77a2a3f20352
Update first char of Object names to UpperCase
AndreyZM/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge
ScriptKit.CLR/NET/Object.cs
ScriptKit.CLR/NET/Object.cs
using ScriptKit.CLR; namespace System { [Ignore] [Name("Object")] [Constructor("{ }")] public class Object { public object this[string name] { get { return null; } set { } } public virtual string ToString() { return null; } public virtual string ToLocaleString() { return null; } public virtual object ValueOf() { return null; } public bool HasOwnProperty(object v) { return false; } public bool IsPrototypeOf(object v) { return false; } public bool PropertyIsEnumerable(object v) { return false; } } }
namespace System { [ScriptKit.CLR.Ignore] [ScriptKit.CLR.Name("Object")] [ScriptKit.CLR.Constructor("{ }")] public class Object { public object this[string name] { get { return null; } set { } } public virtual string toString() { return null; } public virtual string toLocaleString() { return null; } public virtual object valueOf() { return null; } public bool hasOwnProperty(object v) { return false; } public bool isPrototypeOf(object v) { return false; } public bool propertyIsEnumerable(object v) { return false; } } }
apache-2.0
C#
926539af91919bf0579d9408f65a31856b27e036
Add optional Url and ShowOnCashBasisReports fields for MJs [v2.15]
jcvandan/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,TDaphneB/XeroAPI.Net,XeroAPI/XeroAPI.Net
source/XeroApi/Model/ManualJournal.cs
source/XeroApi/Model/ManualJournal.cs
using System; using System.Xml.Serialization; namespace XeroApi.Model { public class ManualJournal : ModelBase { [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } [ItemId] public Guid ManualJournalID { get; set; } public DateTime? Date { get; set; } public string Status { get; set; } public LineAmountType LineAmountTypes { get; set; } public string Narration { get; set; } public string Url { get; set; } public bool? ShowOnCashBasisReports { get; set; } [XmlArrayItem("JournalLine")] public ManualJournalLineItems JournalLines { get; set; } } public class ManualJournals : ModelList<ManualJournal> { } }
using System; using System.Xml.Serialization; namespace XeroApi.Model { public class ManualJournal : ModelBase { [ItemUpdatedDate] public DateTime? UpdatedDateUTC { get; set; } [ItemId] public Guid ManualJournalID { get; set; } public DateTime? Date { get; set; } public string Status { get; set; } public LineAmountType LineAmountTypes { get; set; } public string Narration { get; set; } [XmlArrayItem("JournalLine")] public ManualJournalLineItems JournalLines { get; set; } } public class ManualJournals : ModelList<ManualJournal> { } }
mit
C#
7e69c9feae2d019d47a61f0df97b0cbef0f31e3f
fix path of json files like the assignment says. resolve #5
DatabaseApp-Team-Linnaeus/DatabasesApp,DatabaseApp-Team-Linnaeus/DatabasesApp
SupermarketsChain/SupermarketsChain.ReportToJson/JsonTest.cs
SupermarketsChain/SupermarketsChain.ReportToJson/JsonTest.cs
namespace SupermarketsChain.ReportToJson { using System; using System.Linq; using Newtonsoft.Json; using SupermarketsChain.ConsoleClient.Infrastructure; using SupermarketsChain.Data; public class JsonTest { public static void Main() { var data = ObjectFactory.Get<ISupermarketsChainData>(); var obj = data.Sales.GetAllByDateInterval(new DateTime(1950, 1, 1), DateTime.Now) .GroupBy(y => new { y.Product, y.Product.Vendor }) .Select( x => new TestDTO { ProductId = x.Key.Product.Id, ProductName = x.Key.Product.Name, VendorName = x.Key.Product.Vendor.Name, TotalQuantity = x.Sum(y => y.Quantity), TotalCost = x.Sum(y => y.Quantity * y.PricePerUnit), }); foreach (var file in obj) { string json = JsonConvert.SerializeObject(file, Formatting.Indented); System.IO.File.WriteAllText(@"D:\Json-Reports\" + file.ProductId + ".json", json); } } } }
namespace SupermarketsChain.ReportToJson { using System; using System.Linq; using Newtonsoft.Json; using SupermarketsChain.ConsoleClient.Infrastructure; using SupermarketsChain.Data; public class JsonTest { public static void Main() { var data = ObjectFactory.Get<ISupermarketsChainData>(); var obj = data.Sales.GetAllByDateInterval(new DateTime(1950, 1, 1), DateTime.Now) .GroupBy(y => new { y.Product, y.Product.Vendor }) .Select( x => new TestDTO { ProductId = x.Key.Product.Id, ProductName = x.Key.Product.Name, VendorName = x.Key.Product.Vendor.Name, TotalQuantity = x.Sum(y => y.Quantity), TotalCost = x.Sum(y => y.Quantity * y.PricePerUnit), }); foreach (var file in obj) { string json = JsonConvert.SerializeObject(file, Formatting.Indented); System.IO.File.WriteAllText(@"D:\" + file.ProductId + ".json", json); } } } }
mit
C#
9485cb4bdfe9281a8f3e0dcfe081890ffd466828
Implement IInstanceInfo
martbrow/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,JosefDvorak/KInspector,martbrow/KInspector,ChristopherJennings/KInspector,JosefDvorak/KInspector,ChristopherJennings/KInspector,JosefDvorak/KInspector,Kentico/KInspector,ChristopherJennings/KInspector,Kentico/KInspector,Kentico/KInspector,martbrow/KInspector
KInspector.Modules/Modules/General/OldWebFarmTasks.cs
KInspector.Modules/Modules/General/OldWebFarmTasks.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Web; using System.Web.Configuration; using Kentico.KInspector.Core; namespace Kentico.KInspector.Modules { public class OldWebFarmTasks : IModule { public ModuleMetadata GetModuleMetadata() { return new ModuleMetadata { Name = "Old Web Farm Tasks", Comment = @"As of Kentico 9 Web Farm health is monitored and managed, one of these features is that tasks are not generated after 24 hours. Tasks that are older than 24 hours in age on Kentico 8.x and earlier versions indicate that there is a problem with the web farm health. https://docs.kentico.com/display/K9/Troubleshooting+web+farms", SupportedVersions = new[] { new Version("7.0"), new Version("8.0"), new Version("8.1"), new Version("8.2") } }; } public ModuleResults GetResults(IInstanceInfo instanceInfo) { List<string> responses = new List<string>(); var dbService = instanceInfo.DBService; var taskRowCount = dbService.ExecuteAndGetScalar<int>("SELECT count(*) FROM CMS_WebFarmTask WHERE TaskCreated < DATEADD(hour, -24, GETDATE());"); if (taskRowCount > 0) { responses.Add("There are tasks over 24 hours old in the web farm (" + taskRowCount + " tasks exactly)."); return new ModuleResults { Result = responses, ResultComment = "There are tasks that are over 24 hours old in the CMS_WebFarmTask table. Please check the health of the web farm.", Status = Status.Error, }; } return new ModuleResults { ResultComment = "There are no aged tasks pending.", Status = Status.Good }; } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.IO; using System.Web; using System.Web.Configuration; using Kentico.KInspector.Core; namespace Kentico.KInspector.Modules { public class OldWebFarmTasks : IModule { public ModuleMetadata GetModuleMetadata() { return new ModuleMetadata { Name = "Old Web Farm Tasks", Comment = @"As of Kentico 9 Web Farm health is monitored and managed, one of these features is that tasks are not generated after 24 hours. Tasks that are older than 24 hours in age on Kentico 8.x and earlier versions indicate that there is a problem with the web farm health. https://docs.kentico.com/display/K9/Troubleshooting+web+farms", SupportedVersions = new[] { new Version("7.0"), new Version("8.0"), new Version("8.1"), new Version("8.2") } }; } public ModuleResults GetResults(InstanceInfo instanceInfo) { List<string> responses = new List<string>(); var dbService = instanceInfo.DBService; var taskRowCount = dbService.ExecuteAndGetScalar<int>("SELECT count(*) FROM CMS_WebFarmTask WHERE TaskCreated < DATEADD(hour, -24, GETDATE());"); if (taskRowCount > 0) { responses.Add("There are tasks over 24 hours old in the web farm (" + taskRowCount + " tasks exactly)."); return new ModuleResults { Result = responses, ResultComment = "There are tasks that are over 24 hours old in the CMS_WebFarmTask table. Please check the health of the web farm.", Status = Status.Error, }; } return new ModuleResults { ResultComment = "There are no aged tasks pending.", Status = Status.Good }; } } }
mit
C#
d354aa6d83b327e0e4f84a258091fad37b7e0140
Fix IsAppContainerProcess for Windows 7
axelheer/corefx,fgreinacher/corefx,ericstj/corefx,Jiayili1/corefx,zhenlan/corefx,zhenlan/corefx,Ermiar/corefx,BrennanConroy/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,Ermiar/corefx,wtgodbe/corefx,shimingsg/corefx,axelheer/corefx,seanshpark/corefx,ptoonen/corefx,Jiayili1/corefx,mmitche/corefx,zhenlan/corefx,ptoonen/corefx,ViktorHofer/corefx,Jiayili1/corefx,Ermiar/corefx,parjong/corefx,wtgodbe/corefx,fgreinacher/corefx,shimingsg/corefx,parjong/corefx,ravimeda/corefx,ericstj/corefx,axelheer/corefx,Jiayili1/corefx,ViktorHofer/corefx,wtgodbe/corefx,ravimeda/corefx,parjong/corefx,ravimeda/corefx,seanshpark/corefx,fgreinacher/corefx,ravimeda/corefx,parjong/corefx,Jiayili1/corefx,ViktorHofer/corefx,shimingsg/corefx,Jiayili1/corefx,seanshpark/corefx,mmitche/corefx,seanshpark/corefx,parjong/corefx,Ermiar/corefx,mmitche/corefx,ravimeda/corefx,seanshpark/corefx,mmitche/corefx,axelheer/corefx,axelheer/corefx,ViktorHofer/corefx,Ermiar/corefx,wtgodbe/corefx,Ermiar/corefx,ptoonen/corefx,BrennanConroy/corefx,wtgodbe/corefx,zhenlan/corefx,zhenlan/corefx,zhenlan/corefx,fgreinacher/corefx,seanshpark/corefx,seanshpark/corefx,ericstj/corefx,parjong/corefx,shimingsg/corefx,Ermiar/corefx,shimingsg/corefx,wtgodbe/corefx,zhenlan/corefx,ptoonen/corefx,parjong/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,ericstj/corefx,mmitche/corefx,ravimeda/corefx,ericstj/corefx,mmitche/corefx,ptoonen/corefx,ericstj/corefx,ptoonen/corefx,Jiayili1/corefx,axelheer/corefx,ptoonen/corefx,ViktorHofer/corefx,ravimeda/corefx,BrennanConroy/corefx
src/System.Diagnostics.PerformanceCounter/src/misc/EnvironmentHelpers.cs
src/System.Diagnostics.PerformanceCounter/src/misc/EnvironmentHelpers.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Security; using System.Security.Principal; namespace System { internal static class EnvironmentHelpers { private static volatile bool s_isAppContainerProcess; private static volatile bool s_isAppContainerProcessInitalized; internal const int TokenIsAppContainer = 29; public static bool IsAppContainerProcess { get { if(!s_IsAppContainerProcessInitalized) { if(Environment.OSVersion.Platform != PlatformID.Win32NT) { s_IsAppContainerProcess = false; } else if(Environment.OSVersion.Version.Major < 6 || (Environment.OSVersion.Version.Major == 6 && Environment.OSVersion.Version.Minor <= 1)) { // Windows 7 or older. s_IsAppContainerProcess = false; } else { s_IsAppContainerProcess = HasAppContainerToken(); } s_IsAppContainerProcessInitalized = true; } return s_IsAppContainerProcess; } } [SecuritySafeCritical] private static unsafe bool HasAppContainerToken() { int* dwIsAppContainerPtr = stackalloc int[1]; uint dwLength = 0; using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query)) { if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength)) { throw new Win32Exception(); } } return (*dwIsAppContainerPtr != 0); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Security; using System.Security.Principal; namespace System { internal static class EnvironmentHelpers { private static volatile bool s_isAppContainerProcess; private static volatile bool s_isAppContainerProcessInitalized; internal const int TokenIsAppContainer = 29; public static bool IsAppContainerProcess { get { if (!s_isAppContainerProcessInitalized) { s_isAppContainerProcess = HasAppContainerToken(); s_isAppContainerProcessInitalized = true; } return s_isAppContainerProcess; } } [SecuritySafeCritical] private static unsafe bool HasAppContainerToken() { int* dwIsAppContainerPtr = stackalloc int[1]; uint dwLength = 0; using (WindowsIdentity wi = WindowsIdentity.GetCurrent(TokenAccessLevels.Query)) { if (!Interop.Advapi32.GetTokenInformation(wi.Token, TokenIsAppContainer, new IntPtr(dwIsAppContainerPtr), sizeof(int), out dwLength)) { throw new Win32Exception(); } } return (*dwIsAppContainerPtr != 0); } } }
mit
C#
cf7b1894c617ad61ccd34aa7e46a45e0ee47eb0e
add doc for the Misc API client
ChrisMissal/octokit.net,SmithAndr/octokit.net,eriawan/octokit.net,nsnnnnrn/octokit.net,naveensrinivasan/octokit.net,shiftkey-tester/octokit.net,thedillonb/octokit.net,brramos/octokit.net,SamTheDev/octokit.net,rlugojr/octokit.net,Sarmad93/octokit.net,magoswiat/octokit.net,gdziadkiewicz/octokit.net,geek0r/octokit.net,M-Zuber/octokit.net,editor-tools/octokit.net,hahmed/octokit.net,cH40z-Lord/octokit.net,shiftkey-tester/octokit.net,hahmed/octokit.net,M-Zuber/octokit.net,hitesh97/octokit.net,octokit/octokit.net,khellang/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,dampir/octokit.net,editor-tools/octokit.net,yonglehou/octokit.net,fffej/octokit.net,daukantas/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,chunkychode/octokit.net,forki/octokit.net,shana/octokit.net,gabrielweyer/octokit.net,gdziadkiewicz/octokit.net,devkhan/octokit.net,bslliw/octokit.net,mminns/octokit.net,TattsGroup/octokit.net,octokit-net-test-org/octokit.net,michaKFromParis/octokit.net,shiftkey/octokit.net,SLdragon1989/octokit.net,ivandrofly/octokit.net,Sarmad93/octokit.net,nsrnnnnn/octokit.net,eriawan/octokit.net,alfhenrik/octokit.net,mminns/octokit.net,shana/octokit.net,adamralph/octokit.net,octokit-net-test-org/octokit.net,thedillonb/octokit.net,alfhenrik/octokit.net,takumikub/octokit.net,kdolan/octokit.net,ivandrofly/octokit.net,SmithAndr/octokit.net,darrelmiller/octokit.net,dampir/octokit.net,yonglehou/octokit.net,shiftkey/octokit.net,TattsGroup/octokit.net,fake-organization/octokit.net,octokit/octokit.net,khellang/octokit.net,Red-Folder/octokit.net,rlugojr/octokit.net,SamTheDev/octokit.net,dlsteuer/octokit.net,devkhan/octokit.net,gabrielweyer/octokit.net,octokit-net-test/octokit.net,kolbasov/octokit.net,chunkychode/octokit.net
Octokit/Clients/MiscellaneousClient.cs
Octokit/Clients/MiscellaneousClient.cs
using System; using System.Collections.Generic; #if NET_45 using System.Collections.ObjectModel; #endif using System.Linq; using System.Threading.Tasks; namespace Octokit { /// <summary> /// /// A client for GitHub's miscellaneous APIs. /// </summary> /// <remarks> /// See the <a href="http://developer.github.com/v3/misc/">miscellaneous API documentation</a> for more details. /// </remarks> public class MiscellaneousClient : IMiscellaneousClient { readonly IConnection _connection; /// <summary> /// Initializes a new GitHub miscellaneous API client. /// </summary> /// <param name="connection">An API connection.</param> public MiscellaneousClient(IConnection connection) { Ensure.ArgumentNotNull(connection, "connection"); _connection = connection; } /// <summary> /// Gets all the emojis available to use on GitHub. /// </summary> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>An <see cref="IReadOnlyDictionary{TKey,TValue}"/> of emoji and their URI.</returns> public async Task<IReadOnlyDictionary<string, Uri>> GetEmojis() { var endpoint = new Uri("/emojis", UriKind.Relative); var response = await _connection.GetAsync<Dictionary<string, string>>(endpoint, null); return new ReadOnlyDictionary<string, Uri>( response.BodyAsObject.ToDictionary(kvp => kvp.Key, kvp => new Uri(kvp.Value))); } /// <summary> /// Gets the rendered Markdown for the specified plain-text Markdown document. /// </summary> /// <param name="markdown">A plain-text Markdown document.</param> /// <exception cref="ApiException">Thrown when a general API error occurs.</exception> /// <returns>The rendered Markdown.</returns> public async Task<string> RenderRawMarkdown(string markdown) { var endpoint = new Uri("/markdown/raw", UriKind.Relative); var response = await _connection.PostAsync<string>(endpoint, markdown, "text/plain", "text/html"); return response.Body; } } }
using System; using System.Collections.Generic; #if NET_45 using System.Collections.ObjectModel; #endif using System.Linq; using System.Threading.Tasks; using Octokit.Internal; namespace Octokit { public class MiscellaneousClient : IMiscellaneousClient { readonly IConnection _connection; public MiscellaneousClient(IConnection connection) { Ensure.ArgumentNotNull(connection, "connection"); _connection = connection; } public async Task<IReadOnlyDictionary<string, Uri>> GetEmojis() { var endpoint = new Uri("/emojis", UriKind.Relative); var response = await _connection.GetAsync<Dictionary<string, string>>(endpoint, null); return new ReadOnlyDictionary<string, Uri>( response.BodyAsObject.ToDictionary(kvp => kvp.Key, kvp => new Uri(kvp.Value))); } public async Task<string> RenderRawMarkdown(string markdown) { var endpoint = new Uri("/markdown/raw", UriKind.Relative); var response = await _connection.PostAsync<string>(endpoint, markdown, "text/plain", "text/html"); return response.Body; } } }
mit
C#
e844330c3c199163a09908612da5f37a07373ae2
Add default LinkCommand constructor
appharbor/appharbor-cli
src/AppHarbor/Commands/LinkCommand.cs
src/AppHarbor/Commands/LinkCommand.cs
using System; namespace AppHarbor.Commands { public class LinkCommand : ICommand { public LinkCommand() { } public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
using System; namespace AppHarbor.Commands { public class LinkCommand : ICommand { public void Execute(string[] arguments) { throw new NotImplementedException(); } } }
mit
C#
8f5bb1b0f8eb4a5b5219dfe84b941646a3a8e71d
Use property rather than method invocation.
neitsa/PrepareLanding,neitsa/PrepareLanding
src/Core/Extensions/ListExtensions.cs
src/Core/Extensions/ListExtensions.cs
using System.Collections.Generic; using System.Linq; namespace PrepareLanding.Core.Extensions { public static class ListExtensions { public static bool ContainsAll<T>(this List<T> thisList, List<T> other) { return thisList.Intersect(other).Count() == other.Count; } public static bool ContainsAll<T>(this IEnumerable<T> thisEnumerable, IEnumerable<T> other) { var otherList = other as IList<T> ?? other.ToList(); return thisEnumerable.Intersect(otherList).Count() == otherList.Count; } public static bool IsSubset<T>(this IEnumerable<T> thisEnumerable, IEnumerable<T> other) { return !thisEnumerable.Except(other).Any(); } public static bool IsSubsetInOrder<T>(this List<T> subsetList, List<T> containingList) { if (!IsSubset(subsetList, containingList)) return false; var otherIndex = containingList.IndexOf(subsetList[0]); return !subsetList.Where((t, i) => Comparer<T>.Default.Compare(containingList[i + otherIndex], t) != 0) .Any(); } public static bool IsSubsetInOrderSamePos<T>(this List<T> subsetList, List<T> containingList) { if (subsetList.Count > containingList.Count) return false; if (!subsetList.IsSubset(containingList)) return false; //return !subsetList.Where((t, i) => Comparer<T>.Default.Compare(t, containingList[i]) != 0).Any(); var count = subsetList.Count; for (var i = 0; i < count; i++) if (!EqualityComparer<T>.Default.Equals(subsetList[i], containingList[i])) return false; return true; } } }
using System.Collections.Generic; using System.Linq; namespace PrepareLanding.Core.Extensions { public static class ListExtensions { public static bool ContainsAll<T>(this List<T> thisList, List<T> other) { return thisList.Intersect(other).Count() == other.Count; } public static bool ContainsAll<T>(this IEnumerable<T> thisEnumerable, IEnumerable<T> other) { var otherList = other as IList<T> ?? other.ToList(); return thisEnumerable.Intersect(otherList).Count() == otherList.Count(); } public static bool IsSubset<T>(this IEnumerable<T> thisEnumerable, IEnumerable<T> other) { return !thisEnumerable.Except(other).Any(); } public static bool IsSubsetInOrder<T>(this List<T> subsetList, List<T> containingList) { if (!IsSubset(subsetList, containingList)) return false; var otherIndex = containingList.IndexOf(subsetList[0]); return !subsetList.Where((t, i) => Comparer<T>.Default.Compare(containingList[i + otherIndex], t) != 0) .Any(); } public static bool IsSubsetInOrderSamePos<T>(this List<T> subsetList, List<T> containingList) { if (subsetList.Count > containingList.Count) return false; if (!subsetList.IsSubset(containingList)) return false; //return !subsetList.Where((t, i) => Comparer<T>.Default.Compare(t, containingList[i]) != 0).Any(); var count = subsetList.Count; for (var i = 0; i < count; i++) if (!EqualityComparer<T>.Default.Equals(subsetList[i], containingList[i])) return false; return true; } } }
mit
C#
505611022a73a77d737dbdaab85edde4ef6295c0
Add parameterless constructor for IdentityDocument and static Parse method (needed for serialization)
takenet/lime-csharp
src/Lime.Protocol/IdentityDocument.cs
src/Lime.Protocol/IdentityDocument.cs
using System; using System.Runtime.Serialization; namespace Lime.Protocol { /// <summary> /// Represents an identity document. /// </summary> [DataContract(Namespace = "http://limeprotocol.org/2014")] public sealed class IdentityDocument : Document { public const string MIME_TYPE = "application/vnd.lime.identity"; public static readonly MediaType MediaType = MediaType.Parse(MIME_TYPE); #region Constructors public IdentityDocument() : base(MediaType) { } public IdentityDocument(string identity) : this() { if (!string.IsNullOrWhiteSpace(identity)) { throw new ArgumentException("Invalid identity."); } this.Value = Identity.Parse(identity); } #endregion /// <summary> /// The value of the document /// </summary> public Identity Value { get; set; } public override string ToString() => Value.ToString(); /// <summary> /// Parses the string to a /// IdentityDocument instance. /// </summary> /// <param name="value"></param> /// <returns></returns> public static IdentityDocument Parse(string value) => new IdentityDocument(value); } }
using System; using System.Collections.Generic; using System.Text; namespace Lime.Protocol { /// <summary> /// Represents an identity document. /// </summary> public sealed class IdentityDocument : Document { public const string MIME_TYPE = "application/vnd.lime.identity"; public static readonly MediaType MediaType = MediaType.Parse(MIME_TYPE); #region Constructor public IdentityDocument(string identity) : base(MediaType) { if (!string.IsNullOrWhiteSpace(identity)) { throw new ArgumentException("Invalid identity."); } this.Value = Identity.Parse(identity); } #endregion /// <summary> /// The value of the document /// </summary> public Identity Value { get; private set; } public override string ToString() { return this.Value.ToString(); } } }
apache-2.0
C#
0e702a952787815734e435fc3fb540ff61b0826b
Use standard syntax to build propfind requests
skazantsev/WebDavClient
src/WebDav/WebDav.Client/Request/PropfindRequestBuilder.cs
src/WebDav/WebDav.Client/Request/PropfindRequestBuilder.cs
using System.Linq; using System.Xml.Linq; using WebDav.Helpers; namespace WebDav.Request { internal static class PropfindRequestBuilder { public static string BuildRequestBody(string[] customProperties) { var doc = new XDocument(new XDeclaration("1.0", "utf-8", null)); var propfind = new XElement("{DAV:}propfind", new XAttribute(XNamespace.Xmlns + "D", "DAV:")); propfind.Add(new XElement("{DAV:}allprop")); if (customProperties.Any()) { var include = new XElement("{DAV:}include"); foreach (var prop in customProperties) { include.Add(new XElement(XName.Get(prop, "DAV:"))); } propfind.Add(include); } doc.Add(propfind); return doc.ToStringWithDeclaration(); } } }
using System.Linq; using System.Xml.Linq; using WebDav.Helpers; namespace WebDav.Request { internal static class PropfindRequestBuilder { public static string BuildRequestBody(string[] customProperties) { XNamespace webDavNs = "DAV:"; var doc = new XDocument(new XDeclaration("1.0", "utf-8", null)); var propfind = new XElement(webDavNs + "propfind", new XAttribute(XNamespace.Xmlns + "D", webDavNs)); propfind.Add(new XElement(webDavNs + "allprop")); if (customProperties.Any()) { var include = new XElement(webDavNs + "include"); foreach (var prop in customProperties) { include.Add(new XElement(webDavNs + prop)); } propfind.Add(include); } doc.Add(propfind); return doc.ToStringWithDeclaration(); } } }
mit
C#
814e4406434d248e84c691fdc26a77013775b488
remove unused code
SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake
src/Snowflake.Support.StoneProvider/FileSignatures/Formats/N64/Int32SwapStream.cs
src/Snowflake.Support.StoneProvider/FileSignatures/Formats/N64/Int32SwapStream.cs
/* cor64 - https://github.com/bryanperris/cor64 MIT License Copyright (c) 2019 Bryan Perris Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; namespace Snowflake.Stone.FileSignatures.Formats.N64 { internal sealed class Int32SwapStream : ByteSwapStream { public Int32SwapStream(Stream baseStream) : base(baseStream) { } /// <inheritdoc/> protected override long ComputeNextSwapPosition(long position) { return (position & unchecked(0x7FFFFFFFFFFFFFFCL)) + 3 - (position % 4); } } }
/* cor64 - https://github.com/bryanperris/cor64 MIT License Copyright (c) 2019 Bryan Perris Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.IO; namespace Snowflake.Stone.FileSignatures.Formats.N64 { internal sealed class Swap32Stream : ByteSwapStream { public Swap32Stream(Stream baseStream) : base(baseStream) { } protected override long ComputeNextSwapPosition(long position) { return (position & unchecked(0x7FFFFFFFFFFFFFFCL)) + 3 - (position % 4); } } internal sealed class Int32SwapStream : ByteSwapStream { public Int32SwapStream(Stream baseStream) : base(baseStream) { } /// <inheritdoc/> protected override long ComputeNextSwapPosition(long position) { return (position & unchecked(0x7FFFFFFFFFFFFFFCL)) + 3 - (position % 4); } } }
mpl-2.0
C#
d9516da508aa9fc3350394aca041a5651b593996
Fix issue by type wrong data type was being written to the json
Ackara/Mockaroo.NET
src/Mockaroo.Core/Fields/FieldBase.cs
src/Mockaroo.Core/Fields/FieldBase.cs
namespace Gigobyte.Mockaroo.Fields { /// <summary> /// Base class for <see cref="IField"/>. /// </summary> /// <seealso cref="Gigobyte.Mockaroo.Fields.IField"/> [System.Runtime.Serialization.DataContract] [System.Diagnostics.DebuggerDisplay("{ToDebuggerView()}")] public abstract class FieldBase : IField { /// <summary> /// Gets or sets the identifier of this field. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets the data type. /// </summary> /// <value>The data type.</value> public abstract DataType Type { get; } /// <summary> /// Gets or sets the rate blank values should be generated for this field. /// </summary> /// <value>The blank percentage.</value> public int BlankPercentage { get { return _blankPercentage; } set { _blankPercentage = value.Between(minInclusive: 0, maxInclusive: 99); } } /// <summary> /// Gets or sets the Ruby script to generate data based on custom logic. see more at https://mockaroo.com/help/formulas /// </summary> /// <value>The formula.</value> public string Formula { get; set; } public virtual string ToJson() { return $"{{\"name\":\"{Name}\",\"type\":\"{Type.ToMockarooTypeName()}\",\"percentageBlank\":\"{_blankPercentage}\",\"formula\":\"{Formula}\"}}"; } /// <summary> /// Get the string value that will represent this instance in the debugger window. /// </summary> /// <returns></returns> internal string ToDebuggerView() { string name = (string.IsNullOrEmpty(Name) ? "<Empty>" : Name); return $"{{{name}: {Type.ToMockarooTypeName()}}}"; } #region Private Members private int _blankPercentage; private string _dataType; #endregion Private Members } }
namespace Gigobyte.Mockaroo.Fields { /// <summary> /// Base class for <see cref="IField"/>. /// </summary> /// <seealso cref="Gigobyte.Mockaroo.Fields.IField"/> [System.Runtime.Serialization.DataContract] [System.Diagnostics.DebuggerDisplay("{ToDebuggerView()}")] public abstract class FieldBase : IField { /// <summary> /// Gets or sets the identifier of this field. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Gets the data type. /// </summary> /// <value>The data type.</value> public abstract DataType Type { get; } /// <summary> /// Gets or sets the rate blank values should be generated for this field. /// </summary> /// <value>The blank percentage.</value> public int BlankPercentage { get { return _blankPercentage; } set { _blankPercentage = value.Between(minInclusive: 0, maxInclusive: 99); } } /// <summary> /// Gets or sets the Ruby script to generate data based on custom logic. see more at https://mockaroo.com/help/formulas /// </summary> /// <value>The formula.</value> public string Formula { get; set; } public virtual string ToJson() { return $"{{\"name\":\"{Name}\",\"type\":\"{Type}\",\"percentageBlank\":\"{_blankPercentage}\",\"formula\":\"{Formula}\"}}"; } /// <summary> /// Get the string value that will represent this instance in the debugger window. /// </summary> /// <returns></returns> internal string ToDebuggerView() { string name = (string.IsNullOrEmpty(Name) ? "<Empty>" : Name); return $"{{{name}: {Type.ToMockarooTypeName()}}}"; } #region Private Members private int _blankPercentage; private string _dataType; #endregion Private Members } }
mit
C#
8bf0b0b0abc729c7b0c1ed9db6ad126d1f100fd9
Fix boot strapping order so that IShell is registered before MainViewModel.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Gui/Program.cs
WalletWasabi.Gui/Program.cs
using Avalonia; using AvalonStudio.Shell; using AvalonStudio.Shell.Extensibility.Platforms; using NBitcoin; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Logging; namespace WalletWasabi.Gui { internal class Program { #pragma warning disable IDE1006 // Naming Styles private static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { StatusBarViewModel statusBar = null; try { BuildAvaloniaApp().BeforeStarting(async builder => { try { MainWindowViewModel.Instance = new MainWindowViewModel(); Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo<Config>("Config is successfully initialized."); Global.InitializeConfig(config); if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it. { var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath)); if (File.Exists(cachedIndexFilePath)) { File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false); } } Global.InitializeNoWallet(); statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker); MainWindowViewModel.Instance.StatusBar = statusBar; if (Global.IndexDownloader.Network != Network.Main) { MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}"; } } catch (Exception ex) { Logger.LogCritical<Program>(ex); } }).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", null, () => MainWindowViewModel.Instance); } catch (Exception ex) { Logger.LogCritical<Program>(ex); } finally { statusBar?.Dispose(); await Global.DisposeAsync(); } } private static AppBuilder BuildAvaloniaApp() { return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI(); } } }
using Avalonia; using AvalonStudio.Shell; using AvalonStudio.Shell.Extensibility.Platforms; using NBitcoin; using System; using System.IO; using System.Runtime.InteropServices; using System.Threading.Tasks; using WalletWasabi.Gui.ViewModels; using WalletWasabi.Logging; namespace WalletWasabi.Gui { internal class Program { #pragma warning disable IDE1006 // Naming Styles private static async Task Main(string[] args) #pragma warning restore IDE1006 // Naming Styles { StatusBarViewModel statusBar = null; try { MainWindowViewModel.Instance = new MainWindowViewModel(); BuildAvaloniaApp().AfterSetup(async builder => { try { Logger.InitializeDefaults(Path.Combine(Global.DataDir, "Logs.txt")); var configFilePath = Path.Combine(Global.DataDir, "Config.json"); var config = new Config(configFilePath); await config.LoadOrCreateDefaultFileAsync(); Logger.LogInfo<Config>("Config is successfully initialized."); Global.InitializeConfig(config); if (!File.Exists(Global.IndexFilePath)) // Load the index file from working folder if we have it. { var cachedIndexFilePath = Path.Combine("Assets", Path.GetFileName(Global.IndexFilePath)); if (File.Exists(cachedIndexFilePath)) { File.Copy(cachedIndexFilePath, Global.IndexFilePath, overwrite: false); } } Global.InitializeNoWallet(); statusBar = new StatusBarViewModel(Global.Nodes.ConnectedNodes, Global.MemPoolService, Global.IndexDownloader, Global.UpdateChecker); MainWindowViewModel.Instance.StatusBar = statusBar; if (Global.IndexDownloader.Network != Network.Main) { MainWindowViewModel.Instance.Title += $" - {Global.IndexDownloader.Network}"; } } catch (Exception ex) { Logger.LogCritical<Program>(ex); } }).StartShellApp<AppBuilder, MainWindow>("Wasabi Wallet", new DefaultLayoutFactory(), () => MainWindowViewModel.Instance); } catch (Exception ex) { Logger.LogCritical<Program>(ex); } finally { statusBar?.Dispose(); await Global.DisposeAsync(); } } private static AppBuilder BuildAvaloniaApp() { return AppBuilder.Configure<App>().UsePlatformDetect().UseReactiveUI(); } } }
mit
C#
a68addc81a15cdbc739c31880722cb56a7149aca
upgrade C#
hahoyer/reni.cs,hahoyer/reni.cs,hahoyer/reni.cs
src/Reni/SyntaxFactory/ThenHandler.cs
src/Reni/SyntaxFactory/ThenHandler.cs
using hw.DebugFormatter; using Reni.SyntaxTree; using Reni.TokenClasses; namespace Reni.SyntaxFactory; sealed class ThenHandler : DumpableObject, IValueProvider { ValueSyntax IValueProvider.Get(BinaryTree target, Factory factory, Anchor anchor) => new CondSyntax ( factory.GetValueSyntax(target.Left) , factory.GetValueSyntax(target.Right) , null , Anchor.Create(target).Combine(anchor) ); }
using hw.DebugFormatter; using Reni.SyntaxTree; using Reni.TokenClasses; namespace Reni.SyntaxFactory { class ThenHandler : DumpableObject, IValueProvider { ValueSyntax IValueProvider.Get(BinaryTree target, Factory factory, Anchor anchor) => new CondSyntax ( factory.GetValueSyntax(target.Left) , factory.GetValueSyntax(target.Right) , null , Anchor.Create(target).Combine(anchor) ); } }
mit
C#
f251d29b28932348ffdc9da8402a31156f86811c
Comment change commit (#11)
machovec/INPTP01,rodi0878/INPTP01,zLordZachy/INPTP01,jame581/INPTP01,MaderaJan/INPTP01,janobol/INPTP01,seri300/INPTP01
INPTP_AppForFixing/Entity/Employee.cs
INPTP_AppForFixing/Entity/Employee.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INPTP_AppForFixing { public class Employee { public int id; public string firstName, lastName, job; public DateTime ourBirthDate; public double monthlySalaryCZK; public static double taxRate = 0.21; /// <summary> /// This method gets age of employee /// </summary> /// <returns>Age of employee</returns> public int GetAge() { int x = 0; DateTime endDate = DateTime.Now; TimeSpan timeSpan = endDate - ourBirthDate; if (timeSpan.TotalDays > 365) x = (int)Math.Round((timeSpan.TotalDays / 365), MidpointRounding.ToEven); return x; } public virtual double CalcYearlySalaryCZK() { return monthlySalaryCZK * 12; } public virtual double CalcYearlyIncome() { return CalcYearlySalaryCZK() * (1 - taxRate); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace INPTP_AppForFixing { public class Employee { public int id; public string firstName, lastName, job; public DateTime ourBirthDate; public double monthlySalaryCZK; public static double taxRate = 0.21; public int GetAge() { int x = 0; DateTime endDate = DateTime.Now; TimeSpan timeSpan = endDate - ourBirthDate; if (timeSpan.TotalDays > 365) x = (int)Math.Round((timeSpan.TotalDays / 365), MidpointRounding.ToEven); return x; } public virtual double CalcYearlySalaryCZK() { return monthlySalaryCZK * 12; } public virtual double CalcYearlyIncome() { return CalcYearlySalaryCZK() * (1 - taxRate); } } }
unlicense
C#
9373660ccc165409c21ad3040fb78922dfc5c680
Use Id to compare users. Use profile.real_name.
anthonychu/slack-user-change-alerts
src/SlackUserChangeAlerts.Function/CheckUserListChanges/run.csx
src/SlackUserChangeAlerts.Function/CheckUserListChanges/run.csx
#r "Newtonsoft.Json" using Newtonsoft.Json; static HttpClient httpClient = new HttpClient(); static MemberComparer comparer = new MemberComparer(); public static async Task<string> Run(TimerInfo myTimer, string previousUsersJson, TraceWriter log) { var currentUsersJson = await httpClient.GetStringAsync($"https://slack.com/api/users.list?token={Env("SlackApiToken")}&pretty=1"); if (!string.IsNullOrEmpty(previousUsersJson)) { var currentUsers = DeserializeMembers(currentUsersJson); var previousUsers = DeserializeMembers(previousUsersJson); var deletedUsers = previousUsers.Except(currentUsers, comparer).ToList(); var newUsers = currentUsers.Except(previousUsers, comparer).ToList(); await SendMessage("These users just got deleted: ", deletedUsers, log); await SendMessage("These users just got added: ", newUsers, log); } return currentUsersJson; } private static async Task SendMessage(string message, IEnumerable<Member> users, TraceWriter log) { if (users.Any()) { var slackMessage = message + string.Join(", ", users.Select(u => $"{u.Name}({u.Profile?.Real_name ?? ""})")); log.Info($"Sending to {Env("ChannelsToNotify")}:\n{slackMessage}"); var channels = Env("ChannelsToNotify").Split(','); foreach (var channel in channels) { await httpClient.PostAsync($"{Env("SlackbotUrl")}&channel={channel.Trim()}", new StringContent(slackMessage)); } } } private static IEnumerable<Member> DeserializeMembers(string json) => JsonConvert.DeserializeObject<UserCollection>(json).Members.Where(m => !m.Deleted); private static string Env(string name) => System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process); public class UserCollection { public IEnumerable<Member> Members { get; set; } = new List<Member>(); } public class Member { public string Id { get; set; } public string Name { get; set; } public bool Deleted { get; set; } public Profile Profile { get; set; } } public class Profile { public string Real_name { get; set; } } public class MemberComparer : IEqualityComparer<Member> { public bool Equals(Member x, Member y) => x.Id == y.Id; public int GetHashCode(Member m) => 0; }
#r "Newtonsoft.Json" using Newtonsoft.Json; static HttpClient httpClient = new HttpClient(); static MemberComparer comparer = new MemberComparer(); public static async Task<string> Run(TimerInfo myTimer, string previousUsersJson, TraceWriter log) { var currentUsersJson = await httpClient.GetStringAsync($"https://slack.com/api/users.list?token={Env("SlackApiToken")}&pretty=1"); if (!string.IsNullOrEmpty(previousUsersJson)) { var currentUsers = DeserializeMembers(currentUsersJson); var previousUsers = DeserializeMembers(previousUsersJson); var deletedUsers = previousUsers.Except(currentUsers, comparer).ToList(); var newUsers = currentUsers.Except(previousUsers, comparer).ToList(); await SendMessage("These users just got deleted: ", deletedUsers, log); await SendMessage("These users just got added: ", newUsers, log); } return currentUsersJson; } private static async Task SendMessage(string message, IEnumerable<Member> users, TraceWriter log) { if (users.Any()) { var slackMessage = message + string.Join(", ", users.Select(u => $"{u.Name}({u.Real_name ?? ""})")); log.Info($"Sending to {Env("ChannelsToNotify")}:\n{slackMessage}"); var channels = Env("ChannelsToNotify").Split(','); foreach (var channel in channels) { await httpClient.PostAsync($"{Env("SlackbotUrl")}&channel={channel.Trim()}", new StringContent(slackMessage)); } } } private static IEnumerable<Member> DeserializeMembers(string json) => JsonConvert.DeserializeObject<UserCollection>(json).Members.Where(m => !m.Deleted); private static string Env(string name) => System.Environment.GetEnvironmentVariable(name, EnvironmentVariableTarget.Process); public class UserCollection { public IEnumerable<Member> Members { get; set; } = new List<Member>(); } public class Member { public string Name { get; set; } public string Real_name { get; set; } public bool Deleted { get; set; } } public class MemberComparer : IEqualityComparer<Member> { public bool Equals(Member x, Member y) => x.Name == y.Name; public int GetHashCode(Member m) => 0; }
apache-2.0
C#
855a80d1c44723e0d611b6a7981a75004a9ccdf8
Remove unused script
johanhelsing/vaskelista,johanhelsing/vaskelista
Vaskelista/Views/Shared/_Layout.cshtml
Vaskelista/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Vaskelista</title> @Styles.Render("~/Content/css") @Mvc.RazorTools.BundleManager.Styles.Render() @Styles.Render("~/Content/less") @Scripts.Render("~/bundles/modernizr") <link href='http://fonts.googleapis.com/css?family=Patrick+Hand+SC|Schoolbell' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Roboto:400,100,700' rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="../favicon.ico" /> </head> <body> <!--<header class="el-header"> <ul> <li class="valgt">Min uke</li> <li>Oppgaver</li> <li>Aktiviteter</li> </ul> </header>--> <main class="main container body-content"> @RenderBody() </main> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Vaskelista</title> @Styles.Render("~/Content/css") @Mvc.RazorTools.BundleManager.Styles.Render() @Styles.Render("~/Content/less") @Scripts.Render("~/bundles/modernizr") @Mvc.RazorTools.BundleManager.Scripts.Render() <link href='http://fonts.googleapis.com/css?family=Patrick+Hand+SC|Schoolbell' rel='stylesheet' type='text/css'> <link href='//fonts.googleapis.com/css?family=Roboto:400,100,700' rel='stylesheet' type='text/css' /> <link rel="shortcut icon" href="../favicon.ico" /> </head> <body> <!--<header class="el-header"> <ul> <li class="valgt">Min uke</li> <li>Oppgaver</li> <li>Aktiviteter</li> </ul> </header>--> <main class="main container body-content"> @RenderBody() </main> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
f2bbf87ff011da2a587dc4fc781b8f8ff5fbeb70
Add annotations for AgateLib.Physics.
eylvisaker/AgateLib
AgateLib.Physics/Properties/AssemblyInfo.cs
AgateLib.Physics/Properties/AssemblyInfo.cs
using System.Resources; 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("AgateLib Physics Engine")] [assembly: AssemblyDescription("Physics engine for use with AgateLib")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("AgateLib")] [assembly: AssemblyProduct("AgateLib")] [assembly: AssemblyCopyright("Copyright © 2016-2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
using System.Resources; 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("RigidBodyDynamics")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RigidBodyDynamics")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
0102f239bf22923be35ff2740b70087aa9a459af
Add a gear icon
ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab,ucdavis/Anlab
Anlab.Mvc/Views/Shared/_LoginPartial.cshtml
Anlab.Mvc/Views/Shared/_LoginPartial.cshtml
@using Anlab.Core.Domain @using Microsoft.AspNetCore.Http @inject SignInManager<User> SignInManager @inject UserManager<User> UserManager @if (User.Identity.IsAuthenticated) { var user = await UserManager.GetUserAsync(User); <form class="flexer" asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <p><a asp-area="" asp-controller="Profile" asp-action="Index" title="Manage">Hello @user.Name! <i class="fa fa-gear"></i></a></p> <button type="submit" class="btn-hollow">Sign out</button> </form> } else { <p><a asp-area="" asp-controller="Account" asp-action="Login">Sign in</a></p> }
@using Anlab.Core.Domain @using Microsoft.AspNetCore.Http @inject SignInManager<User> SignInManager @inject UserManager<User> UserManager @if (User.Identity.IsAuthenticated) { var user = await UserManager.GetUserAsync(User); <form class="flexer" asp-area="" asp-controller="Account" asp-action="Logout" method="post" id="logoutForm"> <p><a asp-area="" asp-controller="Profile" asp-action="Index" title="Manage">Hello @user.Name!</a></p> <button type="submit" class="btn-hollow">Sign out</button> </form> } else { <p><a asp-area="" asp-controller="Account" asp-action="Login">Sign in</a></p> }
mit
C#