commit
stringlengths
40
40
old_file
stringlengths
4
237
new_file
stringlengths
4
237
old_contents
stringlengths
1
4.24k
new_contents
stringlengths
1
4.87k
subject
stringlengths
15
778
message
stringlengths
15
8.75k
lang
stringclasses
266 values
license
stringclasses
13 values
repos
stringlengths
5
127k
2992012e045cebd52c1f01799097ec93e4ae2c9e
demos/CoreClrConsoleApplications/HelloWorld/HelloWorld.cs
demos/CoreClrConsoleApplications/HelloWorld/HelloWorld.cs
using System; class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); foreach (var arg in args) { Console.Write("Hello "); Console.Write(arg); Console.WriteLine("!"); } Console.WriteLine("Press ENTER to exit ..."); Console.ReadLine(); } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal class Program { private static void Main(string[] args) { Console.WriteLine("Hello World!"); foreach (var arg in args) { Console.Write("Hello "); Console.Write(arg); Console.WriteLine("!"); } Console.WriteLine("Press ENTER to exit ..."); Console.ReadLine(); } }
Make coding style consistent with corefx
Make coding style consistent with corefx
C#
mit
benaadams/corefxlab,ericstj/corefxlab,whoisj/corefxlab,alexperovich/corefxlab,nguerrera/corefxlab,stephentoub/corefxlab,Vedin/corefxlab,ericstj/corefxlab,mafiya69/corefxlab,stephentoub/corefxlab,ericstj/corefxlab,stephentoub/corefxlab,weshaggard/corefxlab,Vedin/corefxlab,tarekgh/corefxlab,livarcocc/corefxlab,whoisj/corefxlab,KrzysztofCwalina/corefxlab,VSadov/corefxlab,ahsonkhan/corefxlab,VSadov/corefxlab,Vedin/corefxlab,dotnet/corefxlab,axxu/corefxlab,stephentoub/corefxlab,t-roblo/corefxlab,VSadov/corefxlab,Vedin/corefxlab,Vedin/corefxlab,jamesqo/corefxlab,dalbanhi/corefxlab,ravimeda/corefxlab,adamsitnik/corefxlab,ahsonkhan/corefxlab,ericstj/corefxlab,hanblee/corefxlab,VSadov/corefxlab,ericstj/corefxlab,ericstj/corefxlab,joshfree/corefxlab,VSadov/corefxlab,Vedin/corefxlab,shhsu/corefxlab,VSadov/corefxlab,benaadams/corefxlab,KrzysztofCwalina/corefxlab,hanblee/corefxlab,joshfree/corefxlab,adamsitnik/corefxlab,dotnet/corefxlab,stephentoub/corefxlab,tarekgh/corefxlab,stephentoub/corefxlab
4af90871e166293d31668dfeff513265f70029bb
UnitySDK/Assets/TiltBrush/Scripts/Editor/GammaSettings.cs
UnitySDK/Assets/TiltBrush/Scripts/Editor/GammaSettings.cs
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEditor; using System.Collections; using System.Reflection; namespace TiltBrushToolkit { [InitializeOnLoad] public class GammaSettings : EditorWindow { static ColorSpace m_LastColorSpace; static GammaSettings() { EditorApplication.update += OnUpdate; SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } static void OnUpdate() { if (m_LastColorSpace != PlayerSettings.colorSpace) { SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } } static void SetKeywords() { bool linear = PlayerSettings.colorSpace == ColorSpace.Linear; if (linear) { Shader.DisableKeyword("FORCE_SRGB"); } else { Shader.EnableKeyword("FORCE_SRGB"); } } } }
// Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using UnityEngine; using UnityEditor; using System.Collections; using System.Reflection; namespace TiltBrushToolkit { [InitializeOnLoad] public class GammaSettings : EditorWindow { static ColorSpace m_LastColorSpace; static GammaSettings() { EditorApplication.update += OnUpdate; SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } static void OnUpdate() { if (m_LastColorSpace != PlayerSettings.colorSpace) { SetKeywords(); m_LastColorSpace = PlayerSettings.colorSpace; } } static void SetKeywords() { bool linear = PlayerSettings.colorSpace == ColorSpace.Linear; if (linear) { Shader.EnableKeyword("TBT_LINEAR_TARGET"); } else { Shader.DisableKeyword("TBT_LINEAR_TARGET"); } } } }
Use correct TBT_LINEAR_TARGET shader feature keyword.
Use correct TBT_LINEAR_TARGET shader feature keyword. Change-Id: Iaa498426ff3ec9c678ca0e02e5c510121654eded
C#
apache-2.0
googlevr/tilt-brush-toolkit,googlevr/tilt-brush-toolkit
a9e4979db93549716d38e7b19bca4797531328bc
osu.Framework/Audio/Sample/SampleBass.cs
osu.Framework/Audio/Sample/SampleBass.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using ManagedBass; using System; using System.Collections.Concurrent; namespace osu.Framework.Audio.Sample { internal class SampleBass : Sample, IBassAudio { private volatile int sampleId; public override bool IsLoaded => sampleId != 0; public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null) { if (customPendingActions != null) PendingActions = customPendingActions; PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default); }); } protected override void Dispose(bool disposing) { Bass.SampleFree(sampleId); base.Dispose(disposing); } void IBassAudio.UpdateDevice(int deviceIndex) { if (IsLoaded) // counter-intuitively, this is the correct API to use to migrate a sample to a new device. Bass.ChannelSetDevice(sampleId, deviceIndex); } public int CreateChannel() => Bass.SampleGetChannel(sampleId); } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using ManagedBass; using System; using System.Collections.Concurrent; namespace osu.Framework.Audio.Sample { internal class SampleBass : Sample, IBassAudio { private volatile int sampleId; public override bool IsLoaded => sampleId != 0; public SampleBass(byte[] data, ConcurrentQueue<Action> customPendingActions = null) { if (customPendingActions != null) PendingActions = customPendingActions; PendingActions.Enqueue(() => { sampleId = Bass.SampleLoad(data, 0, data.Length, 8, BassFlags.Default | BassFlags.SampleOverrideLongestPlaying); }); } protected override void Dispose(bool disposing) { Bass.SampleFree(sampleId); base.Dispose(disposing); } void IBassAudio.UpdateDevice(int deviceIndex) { if (IsLoaded) // counter-intuitively, this is the correct API to use to migrate a sample to a new device. Bass.ChannelSetDevice(sampleId, deviceIndex); } public int CreateChannel() => Bass.SampleGetChannel(sampleId); } }
Allow bass sample channels to overwrite older ones by default.
Allow bass sample channels to overwrite older ones by default.
C#
mit
smoogipooo/osu-framework,ppy/osu-framework,naoey/osu-framework,paparony03/osu-framework,default0/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,ppy/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,RedNesto/osu-framework,default0/osu-framework,paparony03/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,naoey/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,RedNesto/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework
ad54ba3c2264869a73bc743aa07fb134ea36dbb4
src/backend/SO115App.SignalR/Sender/GestioneUtenti/NotificationDeleteUtente.cs
src/backend/SO115App.SignalR/Sender/GestioneUtenti/NotificationDeleteUtente.cs
using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti; using System; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneUtenti { public class NotificationDeleteUtente : INotifyDeleteUtente { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id); } } }
using Microsoft.AspNetCore.SignalR; using SO115App.Models.Servizi.CQRS.Commands.GestioneUtenti.CancellazioneUtente; using SO115App.Models.Servizi.Infrastruttura.GestioneUtenti.GetUtenti; using SO115App.Models.Servizi.Infrastruttura.Notification.GestioneUtenti; using System; using System.Threading.Tasks; namespace SO115App.SignalR.Sender.GestioneUtenti { public class NotificationDeleteUtente : INotifyDeleteUtente { private readonly IHubContext<NotificationHub> _notificationHubContext; private readonly IGetUtenteByCF _getUtenteByCF; public NotificationDeleteUtente(IHubContext<NotificationHub> notificationHubContext, IGetUtenteByCF getUtenteByCF) { _notificationHubContext = notificationHubContext; _getUtenteByCF = getUtenteByCF; } public async Task Notify(DeleteUtenteCommand command) { var utente = _getUtenteByCF.Get(command.CodFiscale); //await _notificationHubContext.Clients.Group(utente.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); //await _notificationHubContext.Clients.Group(command.UtenteRimosso.Sede.Codice).SendAsync("NotifyRefreshUtenti", true); await _notificationHubContext.Clients.All.SendAsync("NotifyDeleteUtente", command.UtenteRimosso.Id); } } }
Fix - Modificata notifica delete utente
Fix - Modificata notifica delete utente
C#
agpl-3.0
vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf,vvfosprojects/sovvf
49fbbafa4683d1763fc228ef0165ee931984bad9
src/Hosting/PageLocationExpander.cs
src/Hosting/PageLocationExpander.cs
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Wangkanai.Detection.Hosting { public class ResponsivePageLocationExpander : IViewLocationExpander { private const string ValueKey = "device"; public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { context.Values.TryGetValue(ValueKey, out var device); if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor)) return viewLocations; if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device)) return viewLocations; var expandLocations = ExpandPageHierarchy().ToList(); return expandLocations; IEnumerable<string> ExpandPageHierarchy() { foreach (var location in viewLocations) { if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/")) { yield return location; continue; } yield return location.Replace("{0}", "{0}." + device); yield return location; } } } public void PopulateValues(ViewLocationExpanderContext context) { context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower(); } } }
// Copyright (c) 2014-2020 Sarin Na Wangkanai, All Rights Reserved. // The Apache v2. See License.txt in the project root for license information. using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Razor; using Microsoft.AspNetCore.Mvc.RazorPages; namespace Wangkanai.Detection.Hosting { public class ResponsivePageLocationExpander : IViewLocationExpander { private const string ValueKey = "device"; public IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { context.Values.TryGetValue(ValueKey, out var device); if (!(context.ActionContext.ActionDescriptor is PageActionDescriptor)) return viewLocations; if (string.IsNullOrEmpty(context.PageName) || string.IsNullOrEmpty(device)) return viewLocations; var expandLocations = ExpandPageHierarchy().ToList(); return expandLocations; IEnumerable<string> ExpandPageHierarchy() { foreach (var location in viewLocations) { if (!location.Contains("/{1}/") && !location.Contains("/Shared/") || location.Contains("/Views/")) { yield return location; continue; } // Device View if exist on disk yield return location.Replace("{0}", "{0}." + device); // Fallback to the original default view yield return location; } } } public void PopulateValues(ViewLocationExpanderContext context) { context.Values[ValueKey] = context.ActionContext.HttpContext.GetDevice().ToString().ToLower(); } } }
Add explanation of why having 2 yield return
Add explanation of why having 2 yield return
C#
apache-2.0
wangkanai/Detection
645542356a4c3863f9f34f211b447593c39f9a7c
Battery-Commander.Web/Program.cs
Battery-Commander.Web/Program.cs
namespace BatteryCommander.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; public class Program { public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information); public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369") .UseStartup<Startup>(); }) .ConfigureLogging((context, builder) => { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName) .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName) .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}") .WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), compact: true, controlLevelSwitch: LogLevel) .MinimumLevel.ControlledBy(LogLevel) .CreateLogger(); builder.AddSerilog(); }); } }
namespace BatteryCommander.Web { using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Serilog; using Serilog.Core; public class Program { public static LoggingLevelSwitch LogLevel { get; } = new LoggingLevelSwitch(Serilog.Events.LogEventLevel.Information); public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } private static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder .UseSentry(dsn: "https://78e464f7456f49a98e500e78b0bb4b13@o255975.ingest.sentry.io/1447369") .UseStartup<Startup>(); }) .ConfigureLogging((context, builder) => { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .Enrich.WithProperty("Application", context.HostingEnvironment.ApplicationName) .Enrich.WithProperty("Environment", context.HostingEnvironment.EnvironmentName) .Enrich.WithProperty("Version", $"{typeof(Startup).Assembly.GetName().Version}") .WriteTo.Seq(serverUrl: "https://logs.redleg.app", apiKey: context.Configuration.GetValue<string>("Seq:ApiKey"), controlLevelSwitch: LogLevel) .MinimumLevel.ControlledBy(LogLevel) .CreateLogger(); builder.AddSerilog(); }); } }
Remove Seq compact flag, default now
Remove Seq compact flag, default now
C#
mit
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
b46645b9a83c5bf143dcc15e50989eb0229927ec
src/Dommel.Json/JsonObjectTypeHandler.cs
src/Dommel.Json/JsonObjectTypeHandler.cs
using System; using System.Data; using System.Text.Json; using Dapper; namespace Dommel.Json { internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler { private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, }; public void SetValue(IDbDataParameter parameter, object? value) { parameter.Value = value is null || value is DBNull ? (object)DBNull.Value : JsonSerializer.Serialize(value, JsonOptions); parameter.DbType = DbType.String; } public object? Parse(Type destinationType, object? value) => value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null; } }
using System; using System.Data; using System.Text.Json; using System.Text.Json.Serialization; using Dapper; namespace Dommel.Json { internal class JsonObjectTypeHandler : SqlMapper.ITypeHandler { private static readonly JsonSerializerOptions JsonOptions = new() { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, NumberHandling = JsonNumberHandling.AllowReadingFromString, }; public void SetValue(IDbDataParameter parameter, object? value) { parameter.Value = value is null || value is DBNull ? DBNull.Value : JsonSerializer.Serialize(value, JsonOptions); parameter.DbType = DbType.String; } public object? Parse(Type destinationType, object? value) => value is string str ? JsonSerializer.Deserialize(str, destinationType, JsonOptions) : null; } }
Allow reading numbers from strings in JSON
Allow reading numbers from strings in JSON
C#
mit
henkmollema/Dommel
b51b017005e73e4b5694547631204b74eb8d4d4b
Plugins/PluginScriptGenerator.cs
Plugins/PluginScriptGenerator.cs
using System.Text; namespace TweetDck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150); build.Append("(function(").Append(environment.GetScriptVariables()).Append("){"); build.Append("let tmp={"); build.Append("id:\"").Append(pluginIdentifier).Append("\","); build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}"); build.Append("});"); build.Append("tmp.obj.$token=").Append(pluginToken).Append(";"); build.Append("window.TD_PLUGINS.install(tmp);"); build.Append("})(").Append(environment.GetScriptVariables()).Append(");"); return build.ToString(); } } }
using System.Text; namespace TweetDck.Plugins{ static class PluginScriptGenerator{ public static string GenerateConfig(PluginConfig config){ return config.AnyDisabled ? "window.TD_PLUGINS.disabled = [\""+string.Join("\",\"",config.DisabledPlugins)+"\"];" : string.Empty; } public static string GeneratePlugin(string pluginIdentifier, string pluginContents, int pluginToken, PluginEnvironment environment){ StringBuilder build = new StringBuilder(pluginIdentifier.Length+pluginContents.Length+150); build.Append("(function(").Append(environment.GetScriptVariables()).Append("){"); build.Append("let tmp={"); build.Append("id:\"").Append(pluginIdentifier).Append("\","); build.Append("obj:new class extends PluginBase{").Append(pluginContents).Append("}"); build.Append("};"); build.Append("tmp.obj.$token=").Append(pluginToken).Append(";"); build.Append("window.TD_PLUGINS.install(tmp);"); build.Append("})(").Append(environment.GetScriptVariables()).Append(");"); return build.ToString(); } } }
Fix plugin script generator causing JS syntax error
Fix plugin script generator causing JS syntax error
C#
mit
chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck,chylex/TweetDuck
37bcf85b7242c5fc2a19d5378eb8dd783786b345
tests/FreecraftCore.Serializer.Tests/Tests/StringTests.cs
tests/FreecraftCore.Serializer.Tests/Tests/StringTests.cs
using FreecraftCore.Serializer.KnownTypes; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreecraftCore.Serializer.Tests { [TestFixture] public class StringTests { [Test] public static void Test_String_Serializer_Serializes() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize<string>(serializer.Serialize("Hello!")); //assert Assert.AreEqual(value, "Hello!"); } } }
using FreecraftCore.Serializer.KnownTypes; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FreecraftCore.Serializer.Tests { [TestFixture] public class StringTests { [Test] public static void Test_String_Serializer_Serializes() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize<string>(serializer.Serialize("Hello!")); //assert Assert.AreEqual(value, "Hello!"); } [Test] public static void Test_String_Serializer_Can_Serialize_Empty_String() { //arrange SerializerService serializer = new SerializerService(); serializer.Compile(); //act string value = serializer.Deserialize<string>(serializer.Serialize("")); //assert Assert.Null(value); } } }
Add empty to null check
Add empty to null check
C#
agpl-3.0
FreecraftCore/FreecraftCore.Payload.Serializer,FreecraftCore/FreecraftCore.Serializer,FreecraftCore/FreecraftCore.Serializer
7ddb5346e8632660698a0d0df3e508157554f325
AudioWorks/AudioWorks.Extensions/ExtensionContainerBase.cs
AudioWorks/AudioWorks.Extensions/ExtensionContainerBase.cs
using System; using System.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Loader; namespace AudioWorks.Extensions { abstract class ExtensionContainerBase { static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty, "Extensions")); protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration() .WithAssemblies(_extensionRoot .EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories) .Select(f => f.FullName) .Select(Assembly.LoadFrom)) .CreateContainer(); static ExtensionContainerBase() { // Search all extension directories for unresolved references // .NET Core AssemblyLoadContext.Default.Resolving += (context, name) => AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); // Full Framework AppDomain.CurrentDomain.AssemblyResolve += (context, name) => Assembly.LoadFrom(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); } } }
using System; using System.Composition.Hosting; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; namespace AudioWorks.Extensions { abstract class ExtensionContainerBase { static readonly DirectoryInfo _extensionRoot = new DirectoryInfo(Path.Combine( Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath) ?? string.Empty, "Extensions")); protected static CompositionHost CompositionHost { get; } = new ContainerConfiguration() .WithAssemblies(_extensionRoot .EnumerateFiles("AudioWorks.Extensions.*.dll", SearchOption.AllDirectories) .Select(f => f.FullName) .Select(Assembly.LoadFrom)) .CreateContainer(); static ExtensionContainerBase() { // Search all extension directories for unresolved references // Assembly.LoadFrom only works on the full framework if (RuntimeInformation.FrameworkDescription.StartsWith(".NET Framework", StringComparison.Ordinal)) AppDomain.CurrentDomain.AssemblyResolve += (context, name) => Assembly.LoadFrom(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); // Use AssemblyLoadContext on .NET Core else UseAssemblyLoadContext(); } static void UseAssemblyLoadContext() { // Workaround - this needs to reside in a separate method to avoid a binding exception with the desktop // framework, as System.Runtime.Loader does not include a net462 library. AssemblyLoadContext.Default.Resolving += (context, name) => AssemblyLoadContext.Default.LoadFromAssemblyPath(_extensionRoot .EnumerateFiles($"{name.Name}.dll", SearchOption.AllDirectories) .FirstOrDefault()? .FullName); } } }
Resolve binding exception on netfx.
Resolve binding exception on netfx.
C#
agpl-3.0
jherby2k/AudioWorks
bc6f672f73f6a3b3923b037820fc646a1189cc2e
Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml
Joinrpg/Views/Shared/EditorTemplates/MarkdownString.cshtml
@model JoinRpg.DataModel.MarkdownString @{ var requiredMsg = new MvcHtmlString(""); var validation = false; foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata)) { if (attr.Key == "data-val-required") { requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'"); validation = true; } } } <div> Можно использовать MarkDown (**<b>полужирный</b>**, _<i>курсив</i>_) <br/> <textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea> </div> @if (validation) { @Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" }) }
@model JoinRpg.DataModel.MarkdownString @{ var requiredMsg = new MvcHtmlString(""); var validation = false; foreach (var attr in @Html.GetUnobtrusiveValidationAttributes(@ViewData.TemplateInfo.HtmlFieldPrefix, @ViewData.ModelMetadata)) { if (attr.Key == "data-val-required") { requiredMsg = new MvcHtmlString("data-val-required='" + HttpUtility.HtmlAttributeEncode((string) attr.Value) + "'"); validation = true; } } } <div> Можно использовать <a href="http://daringfireball.net/projects/markdown/syntax">MarkDown</a> (**<b>полужирный</b>**, _<i>курсив</i>_) <br/> <textarea cols="100" id="@(ViewData.TemplateInfo.HtmlFieldPrefix)_Contents" name="@(ViewData.TemplateInfo.HtmlFieldPrefix).Contents" @requiredMsg @(validation ? "data-val=true" : "") rows="4">@(Model == null ? "" : Model.Contents)</textarea> </div> @if (validation) { @Html.ValidationMessageFor(model => Model.Contents, "", new { @class = "text-danger" }) }
Add link to Markdown help
Add link to Markdown help
C#
mit
leotsarev/joinrpg-net,kirillkos/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,kirillkos/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
93b3d5bc88a161913d36ee5e576b7ef7e080fbac
Examples/TweetAnalysis/TweetAnalysisClass/TweetAnalysis.cs
Examples/TweetAnalysis/TweetAnalysisClass/TweetAnalysis.cs
using Microsoft.Analytics.Interfaces; using Microsoft.Analytics.Types.Sql; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; // TweetAnalysis Assembly // Show the use of a U-SQL user-defined function (UDF) // // Register this assembly at master.TweetAnalysis e`ither using Register Assembly on TweetAnalysisClass project in Visual Studio // or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script. // namespace TweetAnalysis { public class Udfs { // SqlArray<string> get_mentions(string tweet) // // Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet. // public static SqlArray<string> get_mentions(string tweet) { return new SqlArray<string>( tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@")) ); } } }
using Microsoft.Analytics.Interfaces; using Microsoft.Analytics.Types.Sql; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Linq; // TweetAnalysis Assembly // Show the use of a U-SQL user-defined function (UDF) // // Register this assembly at master.TweetAnalysis either using Register Assembly on TweetAnalysisClass project in Visual Studio // or by compiling the assembly, uploading it (if you want to run it in Azure), and registering it with REGISTER ASSEMBLY U-SQL script. // namespace TweetAnalysis { public class Udfs { // SqlArray<string> get_mentions(string tweet) // // Returns a U-SQL array of string containing the twitter handles that were mentioned inside the tweet. // public static SqlArray<string> get_mentions(string tweet) { return new SqlArray<string>( tweet.Split(new char[] { ' ', ',', '.', ':', '!', ';', '"', '“' }).Where(x => x.StartsWith("@")) ); } } }
Fix a typo in comment
Fix a typo in comment
C#
mit
Azure/usql
50729f1bab989d176019033d88853f53c8a46cde
src/Tasks/Microsoft.NET.Build.Tasks/CheckForImplicitPackageReferenceOverrides.cs
src/Tasks/Microsoft.NET.Build.Tasks/CheckForImplicitPackageReferenceOverrides.cs
using Microsoft.Build.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Microsoft.NET.Build.Tasks { public class CheckForImplicitPackageReferenceOverrides : TaskBase { const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined"; [Required] public ITaskItem [] PackageReferenceItems { get; set; } [Required] public string MoreInformationLink { get; set; } [Output] public ITaskItem[] ItemsToRemove { get; set; } protected override void ExecuteCore() { var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec.ToLowerInvariant()).Where(g => g.Count() > 1); var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where( item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase))); ItemsToRemove = duplicateItemsToRemove.ToArray(); foreach (var itemToRemove in ItemsToRemove) { string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning, itemToRemove.ItemSpec, MoreInformationLink); Log.LogWarning(message); } } } }
using Microsoft.Build.Framework; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Microsoft.NET.Build.Tasks { public class CheckForImplicitPackageReferenceOverrides : TaskBase { const string MetadataKeyForItemsToRemove = "IsImplicitlyDefined"; [Required] public ITaskItem [] PackageReferenceItems { get; set; } [Required] public string MoreInformationLink { get; set; } [Output] public ITaskItem[] ItemsToRemove { get; set; } protected override void ExecuteCore() { var duplicateItems = PackageReferenceItems.GroupBy(i => i.ItemSpec, StringComparer.OrdinalIgnoreCase).Where(g => g.Count() > 1); var duplicateItemsToRemove = duplicateItems.SelectMany(g => g.Where( item => item.GetMetadata(MetadataKeyForItemsToRemove).Equals("true", StringComparison.OrdinalIgnoreCase))); ItemsToRemove = duplicateItemsToRemove.ToArray(); foreach (var itemToRemove in ItemsToRemove) { string message = string.Format(CultureInfo.CurrentCulture, Strings.PackageReferenceOverrideWarning, itemToRemove.ItemSpec, MoreInformationLink); Log.LogWarning(message); } } } }
Switch to OrdinalIgnoreCase comparison for PackageReference deduplication
Switch to OrdinalIgnoreCase comparison for PackageReference deduplication
C#
mit
nkolev92/sdk,nkolev92/sdk
ea2896a7c2a1767a030404bf8078dedab7a92341
editor/Resources/scripttemplate.csx
editor/Resources/scripttemplate.csx
using OpenTK; using OpenTK.Graphics; using StorybrewCommon.Mapset; using StorybrewCommon.Scripting; using StorybrewCommon.Storyboarding; using StorybrewCommon.Storyboarding.Util; using StorybrewCommon.Subtitles; using StorybrewCommon.Util; using System; using System.Collections.Generic; using System.Linq; namespace StorybrewScripts { public class %CLASSNAME% : StoryboardObjectGenerator { public override void Generate() { } } }
using OpenTK; using OpenTK.Graphics; using StorybrewCommon.Mapset; using StorybrewCommon.Scripting; using StorybrewCommon.Storyboarding; using StorybrewCommon.Storyboarding.Util; using StorybrewCommon.Subtitles; using StorybrewCommon.Util; using System; using System.Collections.Generic; using System.Linq; namespace StorybrewScripts { public class %CLASSNAME% : StoryboardObjectGenerator { public override void Generate() { } } }
Remove extra tab in the script template.
Remove extra tab in the script template.
C#
mit
Damnae/storybrew
849d16f485b67929d05ce528d330b6b59f4b89c1
Ooui/Iframe.cs
Ooui/Iframe.cs
namespace Ooui { public class Iframe : Element { public string Source { get => GetStringAttribute ("src", null); set => SetAttributeProperty ("src", value); } public Iframe () : base ("iframe") { } } }
namespace Ooui { public class Iframe : Element { public string Source { get => GetStringAttribute ("src", null); set => SetAttributeProperty ("src", value); } public Iframe () : base ("iframe") { } protected override bool HtmlNeedsFullEndElement => true; } }
Fix closing tag on iframe
Fix closing tag on iframe Fixes #223
C#
mit
praeclarum/Ooui,praeclarum/Ooui,praeclarum/Ooui
92300d011c48b4142c62f5b237812f04c18d31f9
UnityProject/Assets/Scripts/Weapons/Projectiles/Behaviours/ProjectileDecalOnDespawn.cs
UnityProject/Assets/Scripts/Weapons/Projectiles/Behaviours/ProjectileDecalOnDespawn.cs
using UnityEngine; namespace Weapons.Projectiles.Behaviours { /// <summary> /// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something. /// </summary> public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn { [SerializeField] private GameObject decal = null; [Tooltip("Living time of decal.")] [SerializeField] private float animationTime = 0; [Tooltip("Spawn decal on collision?")] [SerializeField] private bool isTriggeredOnHit = true; public void OnDespawn(RaycastHit2D hit, Vector2 point) { if (isTriggeredOnHit && hit.collider != null) { OnBeamEnd(hit.point); } else { OnBeamEnd(point); } } private bool OnBeamEnd(Vector2 position) { var newDecal = Spawn.ClientPrefab(decal.name, position).GameObject; var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>(); timeLimitedDecal.SetUpDecal(animationTime); return false; } } }
using UnityEngine; namespace Weapons.Projectiles.Behaviours { /// <summary> /// Identical to ProjectileDecal.cs, but creates a decal upon despawning instead of on hitting something. /// </summary> public class ProjectileDecalOnDespawn : MonoBehaviour, IOnDespawn { [SerializeField] private GameObject decal = null; [Tooltip("Living time of decal.")] [SerializeField] private float animationTime = 0; [Tooltip("Spawn decal on collision?")] [SerializeField] private bool isTriggeredOnHit = true; public void OnDespawn(RaycastHit2D hit, Vector2 point) { if (isTriggeredOnHit && hit.collider != null) { OnBeamEnd(hit.point); } else { OnBeamEnd(point); } } private void OnBeamEnd(Vector2 position) { var newDecal = Spawn.ClientPrefab(decal.name, position).GameObject; var timeLimitedDecal = newDecal.GetComponent<TimeLimitedDecal>(); timeLimitedDecal.SetUpDecal(animationTime); } } }
Make decal on despawn script use void.
Make decal on despawn script use void.
C#
agpl-3.0
fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation,fomalsd/unitystation
8f14afc3fb2d0bef209940d27123f42481137b03
src/Hops/Views/Search/Results.cshtml
src/Hops/Views/Search/Results.cshtml
@using Hops.Models; @model ListModel<HopModel> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } @{ ViewBag.Title = "Search results - Hops"; } @if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm)) { <h3>Search results for "@Model.Pagination.SearchTerm":</h3> } @Html.Partial("~/Views/Hop/List", Model)
@using Hops.Models; @model ListModel<HopModel> @{ Layout = "~/Views/Shared/_Layout.cshtml"; } @{ ViewBag.Title = "Search results - Hops"; } @if (!string.IsNullOrEmpty(Model.Pagination.SearchTerm)) { <h3>Search results for "@Model.Pagination.SearchTerm":</h3> } @Html.Partial("~/Views/Hop/List.cshtml", Model)
Fix search result when returning multiple results
Fix search result when returning multiple results
C#
mit
sboulema/Hops,sboulema/Hops,sboulema/Hops
d3ca07c04a7ea74bc76a93c7b55e28207c594bd0
src/Glob/Properties/AssemblyInfo.cs
src/Glob/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Glob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Glob")] [assembly: AssemblyCopyright("Copyright © 2011")] [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)] // 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")] [assembly: InternalsVisibleTo("Glob.Tests")] [assembly: InternalsVisibleTo("Glob.Benchmarks")]
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("Glob")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Glob")] [assembly: AssemblyCopyright("Copyright © 2011")] [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)] // 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: InternalsVisibleTo("Glob.Tests")] [assembly: InternalsVisibleTo("Glob.Benchmarks")]
Fix extra assembly info attributes since they are generated by nuget
Fix extra assembly info attributes since they are generated by nuget
C#
mit
kthompson/csharp-glob,kthompson/glob,kthompson/glob
6408705f82979db60e2a7d1ec81fb56a2f81c3df
src/Markdig.WebApp/ApiController.cs
src/Markdig.WebApp/ApiController.cs
using System; using System.Text; using Microsoft.AspNetCore.Mvc; namespace Markdig.WebApp { public class ApiController : Controller { // GET api/to_html?text=xxx&extensions=advanced [Route("api/to_html")] [HttpGet()] public object Get([FromQuery] string text, [FromQuery] string extension) { try { if (text == null) { text = string.Empty; } if (text.Length > 1000) { text = text.Substring(0, 1000); } var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build(); var result = Markdown.ToHtml(text, pipeline); return new {name = "markdig", html = result, version = Markdown.Version}; } catch (Exception ex) { return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version }; } } private static string GetPrettyMessageFromException(Exception exception) { var builder = new StringBuilder(); while (exception != null) { builder.Append(exception.Message); exception = exception.InnerException; } return builder.ToString(); } } }
using System; using System.Text; using Microsoft.AspNetCore.Mvc; namespace Markdig.WebApp { public class ApiController : Controller { [HttpGet()] [Route("")] public string Empty() { return string.Empty; } // GET api/to_html?text=xxx&extensions=advanced [Route("api/to_html")] [HttpGet()] public object Get([FromQuery] string text, [FromQuery] string extension) { try { if (text == null) { text = string.Empty; } if (text.Length > 1000) { text = text.Substring(0, 1000); } var pipeline = new MarkdownPipelineBuilder().Configure(extension).Build(); var result = Markdown.ToHtml(text, pipeline); return new {name = "markdig", html = result, version = Markdown.Version}; } catch (Exception ex) { return new { name = "markdig", html = "exception: " + GetPrettyMessageFromException(ex), version = Markdown.Version }; } } private static string GetPrettyMessageFromException(Exception exception) { var builder = new StringBuilder(); while (exception != null) { builder.Append(exception.Message); exception = exception.InnerException; } return builder.ToString(); } } }
Return an empty string for / on markdig webapi
Return an empty string for / on markdig webapi
C#
bsd-2-clause
lunet-io/markdig
7d6e27a23ec88138ada829f50e473cea394df189
src/runtime/Codecs/EnumPyIntCodec.cs
src/runtime/Codecs/EnumPyIntCodec.cs
using System; namespace Python.Runtime.Codecs { [Obsolete] public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder { public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec(); public bool CanDecode(PyType objectType, Type targetType) { return targetType.IsEnum && objectType.IsSubclass(Runtime.PyLongType); } public bool CanEncode(Type type) { return type == typeof(object) || type == typeof(ValueType) || type.IsEnum; } public bool TryDecode<T>(PyObject pyObj, out T? value) { value = default; if (!typeof(T).IsEnum) return false; Type etype = Enum.GetUnderlyingType(typeof(T)); if (!PyInt.IsIntType(pyObj)) return false; object? result; try { result = pyObj.AsManagedObject(etype); } catch (InvalidCastException) { return false; } if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum()) { value = (T)Enum.ToObject(typeof(T), result); return true; } return false; } public PyObject? TryEncode(object value) { if (value is null) return null; var enumType = value.GetType(); if (!enumType.IsEnum) return null; return new PyInt(Convert.ToInt64(value)); } private EnumPyIntCodec() { } } }
using System; namespace Python.Runtime.Codecs { [Obsolete] public sealed class EnumPyIntCodec : IPyObjectEncoder, IPyObjectDecoder { public static EnumPyIntCodec Instance { get; } = new EnumPyIntCodec(); public bool CanDecode(PyType objectType, Type targetType) { return targetType.IsEnum && objectType.IsSubclass(Runtime.PyLongType); } public bool CanEncode(Type type) { return type == typeof(object) || type == typeof(ValueType) || type.IsEnum; } public bool TryDecode<T>(PyObject pyObj, out T? value) { value = default; if (!typeof(T).IsEnum) return false; Type etype = Enum.GetUnderlyingType(typeof(T)); if (!PyInt.IsIntType(pyObj)) return false; object? result; try { result = pyObj.AsManagedObject(etype); } catch (InvalidCastException) { return false; } if (Enum.IsDefined(typeof(T), result) || typeof(T).IsFlagsEnum()) { value = (T)Enum.ToObject(typeof(T), result); return true; } return false; } public PyObject? TryEncode(object value) { if (value is null) return null; var enumType = value.GetType(); if (!enumType.IsEnum) return null; try { return new PyInt(Convert.ToInt64(value)); } catch (OverflowException) { return new PyInt(Convert.ToUInt64(value)); } } private EnumPyIntCodec() { } } }
Allow conversion of UInt64 based enums
Allow conversion of UInt64 based enums
C#
mit
pythonnet/pythonnet,pythonnet/pythonnet,pythonnet/pythonnet
9a22b6e1df22c8e7de3f8dce967d296a8c662385
Examples/LeagueGeneration/Program.cs
Examples/LeagueGeneration/Program.cs
/* Copyright © Iain McDonald 2010-2020 This file is part of Decider. */ using System; using System.Collections.Generic; using System.Linq; namespace Decider.Example.LeagueGeneration { public class Program { static void Main(string[] args) { var leagueGeneration = new LeagueGeneration((args.Length >= 1) ? Int32.Parse(args[0]) : 20); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); for (var i = 0; i < leagueGeneration.FixtureWeeks.Length; ++i) { for (var j = 0; j < leagueGeneration.FixtureWeeks[i].Length; ++j) Console.Write(string.Format("{0,2}", leagueGeneration.FixtureWeeks[i][j]) + " "); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Runtime:\t{0}\nBacktracks:\t{1}", leagueGeneration.State.Runtime, leagueGeneration.State.Backtracks); Console.WriteLine("Solutions:\t{0}", leagueGeneration.State.NumberOfSolutions); } } }
/* Copyright © Iain McDonald 2010-2020 This file is part of Decider. */ using System; using System.Collections.Generic; using System.Linq; namespace Decider.Example.LeagueGeneration { public class Program { static void Main(string[] args) { var leagueGeneration = new LeagueGeneration((args.Length >= 1) ? Int32.Parse(args[0]) : 20); leagueGeneration.Search(); leagueGeneration.GenerateFixtures(); for (var i = 0; i < leagueGeneration.FixtureWeeks.Length; ++i) { for (var j = 0; j < leagueGeneration.FixtureWeeks[i].Length; ++j) Console.Write(string.Format("{0,2}", leagueGeneration.FixtureWeeks[i][j]) + " "); Console.WriteLine(); } Console.WriteLine(); Console.WriteLine("Runtime:\t{0}\nBacktracks:\t{1}", leagueGeneration.State.Runtime, leagueGeneration.State.Backtracks); Console.WriteLine("Solutions:\t{0}", leagueGeneration.State.NumberOfSolutions); } } }
Create first automated acceptance test
Create first automated acceptance test
C#
mit
lifebeyondfife/Decider
cfa1ebd7c0d11c574e1967ed947501d16f674921
Source/Nett/TomlConverter.cs
Source/Nett/TomlConverter.cs
using System; using System.Diagnostics; namespace Nett { [DebuggerDisplay("{FromType} -> {ToType}")] internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo> { private readonly Func<TFrom, TTo> convert; public TomlConverter(Func<TFrom, TTo> convert) { if (convert == null) { throw new ArgumentNullException(nameof(convert)); } this.convert = convert; } public override TTo Convert(TFrom from, Type targetType) => this.convert(from); } }
using System; namespace Nett { internal sealed class TomlConverter<TFrom, TTo> : TomlConverterBase<TFrom, TTo> { private readonly Func<TFrom, TTo> convert; public TomlConverter(Func<TFrom, TTo> convert) { if (convert == null) { throw new ArgumentNullException(nameof(convert)); } this.convert = convert; } public override TTo Convert(TFrom from, Type targetType) => this.convert(from); } }
Remove DebuggerDisplay attribute not applicable anymore
Remove DebuggerDisplay attribute not applicable anymore
C#
mit
paiden/Nett
e970acad7f21c954a8808f603a07ad884addae5f
TAUtil/Tdf/TdfNodeAdapter.cs
TAUtil/Tdf/TdfNodeAdapter.cs
namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } }
namespace TAUtil.Tdf { using System.Collections.Generic; public class TdfNodeAdapter : ITdfNodeAdapter { private readonly Stack<TdfNode> nodeStack = new Stack<TdfNode>(); public TdfNodeAdapter() { this.RootNode = new TdfNode(); this.nodeStack.Push(this.RootNode); } public TdfNode RootNode { get; private set; } public void BeginBlock(string name) { name = name.ToLowerInvariant(); TdfNode n = new TdfNode(name); this.nodeStack.Peek().Keys[name] = n; this.nodeStack.Push(n); } public void AddProperty(string name, string value) { name = name.ToLowerInvariant(); value = value.ToLowerInvariant(); this.nodeStack.Peek().Entries[name] = value; } public void EndBlock() { this.nodeStack.Pop(); } } }
Make all strings in loaded TdfNodes lowercase
Make all strings in loaded TdfNodes lowercase This fixes aliasing issues in TDFs since TDF authors don't follow consistent case style.
C#
mit
MHeasell/TAUtil,MHeasell/TAUtil
dcbf91a8ca18886c9a651327079c2a995a484a5f
Views/ChatView.cshtml
Views/ChatView.cshtml
@model ChatApp.Controllers.ChatMessagesViewModel @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" @using ChatApp.Models <!DOCTYPE html> <html> <head> <title>ChatApp</title> </head> <body> <table> @foreach (Message msg in Model.OldMessages) { <tr> <td class="author">@msg.Author</td> <td class="text">@msg.Text</td> <td class="timestamp">@msg.Timestamp</td> </tr> } </table> <form asp-action="SendNewMessage" method="post"> <input asp-for="NewMessage.Author"/> <input asp-for="NewMessage.Text"/> <input type="submit" value="Send"/> </form> </body> </html>
@model ChatApp.Controllers.ChatMessagesViewModel @addTagHelper "*, Microsoft.AspNetCore.Mvc.TagHelpers" @using ChatApp.Models <!DOCTYPE html> <html> <head> <title>ChatApp</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css" async> </head> <body> <table class="w3-table w3-striped"> @foreach (Message msg in Model.OldMessages) { <tr> <td name="author" class="w3-right-align" style="width: 10em;">@msg.Author:</td> <td name="text">@msg.Text</td> <td name="timestamp" class="w3-right-align">@msg.Timestamp</td> </tr> } </table> <form asp-action="SendNewMessage" method="post" class="w3-row"> <input asp-for="NewMessage.Author" class="w3-input w3-border w3-col m2" placeholder="Name"/> <input asp-for="NewMessage.Text" class="w3-input w3-border w3-col m8" placeholder="Message"/> <input type="submit" value="Send" class="w3-btn w3-blue w3-col w3-large m2"/> </form> </body> </html>
Update UI look and feel
Update UI look and feel
C#
mit
RubenLaube-Pohto/asp.net-project
1dfc18cb9a20df554ecf55cd59c1114e568d22f9
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCopyright(XsdDocMetadata.Copyright)] [assembly: AssemblyCompany("Immo Landwerth")] [assembly: AssemblyProduct("XML Schema Documenter")] [assembly: CLSCompliant(false)] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion(XsdDocMetadata.Version)] [assembly: AssemblyFileVersion(XsdDocMetadata.Version)] internal static class XsdDocMetadata { public const string Version = "15.10.10.0"; public const string Copyright = "Copyright 2009-2015 Immo Landwerth"; }
using System; using System.Reflection; using System.Reflection.Emit; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyCopyright(XsdDocMetadata.Copyright)] [assembly: AssemblyCompany("Immo Landwerth")] [assembly: AssemblyProduct("XML Schema Documenter")] [assembly: CLSCompliant(false)] [assembly: ComVisible(false)] [assembly: NeutralResourcesLanguage("en-US")] [assembly: AssemblyVersion(XsdDocMetadata.Version)] [assembly: AssemblyFileVersion(XsdDocMetadata.Version)] internal static class XsdDocMetadata { public const string Version = "16.9.17.0"; public const string Copyright = "Copyright 2009-2015 Immo Landwerth"; }
Align XSD Doc version number with SHFB
Align XSD Doc version number with SHFB
C#
mit
terrajobst/xsddoc
8118ef4d218ba9b90ee2aa127861735c0af35f3d
src/CommonAssemblyInfo.cs
src/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("© Yevgeniy Shunevych 2018")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")]
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyCompany("Yevgeniy Shunevych")] [assembly: AssemblyProduct("Atata Framework")] [assembly: AssemblyCopyright("© Yevgeniy Shunevych 2019")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0")] [assembly: AssemblyFileVersion("1.0.0")]
Increment copyright year of projects to 2019
Increment copyright year of projects to 2019
C#
apache-2.0
atata-framework/atata-sample-app-tests
b2196b8cfed91c67738bd39d068c551c77e683b8
src/SimpleStack.Orm.PostgreSQL/PostgreSQLExpressionVisitor.cs
src/SimpleStack.Orm.PostgreSQL/PostgreSQLExpressionVisitor.cs
using SimpleStack.Orm.Expressions; namespace SimpleStack.Orm.PostgreSQL { /// <summary>A postgre SQL expression visitor.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T> { public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider) { } /// <summary>Gets the limit expression.</summary> /// <value>The limit expression.</value> public override string LimitExpression{ get{ if(!Rows.HasValue) return ""; string offset; if(Skip.HasValue){ offset= string.Format(" OFFSET {0}", Skip.Value ); } else{ offset=string.Empty; } return string.Format("LIMIT {0}{1}", Rows.Value, offset); } } } }
using System.Linq.Expressions; using SimpleStack.Orm.Expressions; namespace SimpleStack.Orm.PostgreSQL { /// <summary>A postgre SQL expression visitor.</summary> /// <typeparam name="T">Generic type parameter.</typeparam> public class PostgreSQLExpressionVisitor<T>:SqlExpressionVisitor<T> { public PostgreSQLExpressionVisitor(IDialectProvider dialectProvider) : base(dialectProvider) { } protected override string BindOperant(ExpressionType e) { switch (e) { case ExpressionType.ExclusiveOr: return "#"; } return base.BindOperant(e); } /// <summary>Gets the limit expression.</summary> /// <value>The limit expression.</value> public override string LimitExpression{ get{ if(!Rows.HasValue) return ""; string offset; if(Skip.HasValue){ offset= string.Format(" OFFSET {0}", Skip.Value ); } else{ offset=string.Empty; } return string.Format("LIMIT {0}{1}", Rows.Value, offset); } } } }
Add support for XOR in PostgreSQL
Add support for XOR in PostgreSQL
C#
bsd-3-clause
SimpleStack/simplestack.orm,SimpleStack/simplestack.orm
4fad711221e30aa4a0f0702b99ade16795f1ceb0
Conditional-Statements-Homework/CheckPlayCard/CheckPlayCard.cs
Conditional-Statements-Homework/CheckPlayCard/CheckPlayCard.cs
/*Problem 3. Check for a Play Card Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A. Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples: character Valid card sign? 5 yes 1 no Q yes q no P no 10 yes 500 no */ using System; class CheckPlayCard { static void Main() { Console.Title = "Check for a Play Card"; //Changing the title of the console. Console.Write("Please, enter a play card sign to check if it is valid: "); string cardSign = Console.ReadLine(); switch (cardSign) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10": case "J": case "Q": case "K": case "A": Console.WriteLine("\nValid card sign?\nyes"); break; default: Console.WriteLine("\nValid card sign?\nno"); break; } Console.ReadKey(); // Keeping the console opened. } }
/*Problem 3. Check for a Play Card Classical play cards use the following signs to designate the card face: `2, 3, 4, 5, 6, 7, 8, 9, 10, J, Q, K and A. Write a program that enters a string and prints “yes” if it is a valid card sign or “no” otherwise. Examples: character Valid card sign? 5 yes 1 no Q yes q no P no 10 yes 500 no */ using System; class CheckPlayCard { static void Main() { Console.Title = "Check for a Play Card"; //Changing the title of the console. Console.Write("Please, enter a play card sign to check if it is valid: "); string cardSign = Console.ReadLine(); switch (cardSign) { case "2": case "3": case "4": case "5": case "6": case "7": case "8": case "9": case "10": case "J": case "Q": case "K": case "A": Console.WriteLine("\r\nValid card sign?\r\nyes"); break; default: Console.WriteLine("\r\nValid card sign?\r\nno"); break; } Console.ReadKey(); // Keeping the console opened. } }
Update to Problem 3. Check for a Play Card
Update to Problem 3. Check for a Play Card
C#
mit
SimoPrG/CSharpPart1Homework
3fcc0fa2a1fe52bdc0d668e340ea7afa680e1262
src/CSharpClient/Bit.CSharpClient.Rest/ViewModel/Implementations/BitHttpClientHandler.cs
src/CSharpClient/Bit.CSharpClient.Rest/ViewModel/Implementations/BitHttpClientHandler.cs
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; namespace Bit.ViewModel.Implementations { public class BitHttpClientHandler : HttpClientHandler { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // ToDo: // Current-Time-Zone // Desired-Time-Zone // Client-App-Version // Client-Culture // Client-Route // Client-Theme // Client-Debug-Mode // System-Language // Client-Sys-Language // Client-Platform // ToDo: Use IDeviceService & IDateTimeProvider request.Headers.Add("Client-Type", "Xamarin"); if (Device.Idiom != TargetIdiom.Unsupported) request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet"); request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o")); request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString()); request.Headers.Add("Bit-Client-Type", "CS-Client"); return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } } }
using System; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Xamarin.Forms; namespace Bit.ViewModel.Implementations { public class BitHttpClientHandler : #if Android Xamarin.Android.Net.AndroidClientHandler #elif iOS NSUrlSessionHandler #else HttpClientHandler #endif { protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // ToDo: // Current-Time-Zone // Desired-Time-Zone // Client-App-Version // Client-Culture // Client-Route // Client-Theme // Client-Debug-Mode // System-Language // Client-Sys-Language // Client-Platform // ToDo: Use IDeviceService & IDateTimeProvider request.Headers.Add("Client-Type", "Xamarin"); if (Device.Idiom != TargetIdiom.Unsupported) request.Headers.Add("Client-Screen-Size", Device.Idiom == TargetIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet"); request.Headers.Add("Client-Date-Time", DefaultDateTimeProvider.Current.GetCurrentUtcDateTime().UtcDateTime.ToString("o")); request.Headers.Add("X-CorrelationId", Guid.NewGuid().ToString()); request.Headers.Add("Bit-Client-Type", "CS-Client"); return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } } }
Use AndroidClientHandler for android & NSUrlSessionHandler for iOS by default in bit cs client
Use AndroidClientHandler for android & NSUrlSessionHandler for iOS by default in bit cs client
C#
mit
bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework,bit-foundation/bit-framework
f6aa3efa928cbcc18f5fc7d03bc86842b543fded
Csla20Test/Csla.Test/DataBinding/DataBindingApp/ListObject.cs
Csla20Test/Csla.Test/DataBinding/DataBindingApp/ListObject.cs
using System; using System.Collections.Generic; using System.Text; using Csla.Core; using Csla; namespace DataBindingApp { [Serializable()] public class ListObject : BusinessListBase<ListObject, ListObject.DataObject> { [Serializable()] public class DataObject : BusinessBase<DataObject> { private int _ID; private string _data; private int _number; public int Number { get { return _number; } set { _number = value; } } public string Data { get { return _data; } set { _data = value; } } public int ID { get { return _ID; } set { _ID = value; } } protected override object GetIdValue() { return _ID; } public DataObject(string data, int number) { this.MarkAsChild(); _data = data; _number = number; this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged); } public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { Console.WriteLine("Property has changed"); } } private ListObject() { } public static ListObject GetList() { ListObject list = new ListObject(); for (int i = 0; i < 5; i++) { list.Add(new DataObject("element" + i, i)); } return list; } } }
using System; using System.Collections.Generic; using System.Text; using Csla.Core; using Csla; namespace DataBindingApp { [Serializable()] public class ListObject : BusinessListBase<ListObject, ListObject.DataObject> { [Serializable()] public class DataObject : BusinessBase<DataObject> { private int _ID; private string _data; private int _number; public int Number { get { return _number; } set { _number = value; } } public string Data { get { return _data; } set { _data = value; } } public int ID { get { return _ID; } set { _ID = value; } } protected override object GetIdValue() { return _number; } public DataObject(string data, int number) { this.MarkAsChild(); _data = data; _number = number; this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(DataObject_PropertyChanged); } public void DataObject_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) { Console.WriteLine("Property has changed"); } } private ListObject() { } public static ListObject GetList() { ListObject list = new ListObject(); for (int i = 0; i < 5; i++) { list.Add(new DataObject("element" + i, i)); } return list; } } }
Make sure GetIdValue returns a unique value per object.
Make sure GetIdValue returns a unique value per object.
C#
mit
ronnymgm/csla-light,ronnymgm/csla-light,BrettJaner/csla,jonnybee/csla,JasonBock/csla,MarimerLLC/csla,rockfordlhotka/csla,JasonBock/csla,MarimerLLC/csla,rockfordlhotka/csla,BrettJaner/csla,jonnybee/csla,rockfordlhotka/csla,JasonBock/csla,ronnymgm/csla-light,jonnybee/csla,MarimerLLC/csla,BrettJaner/csla
9f88c4875ae34786ebe17a88f2117e632f5fd852
src/ConsoleApp/Table.cs
src/ConsoleApp/Table.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.WriteLine(@")] public class Vaca : Migration { public override void Up() {"); writer.Write($" Create.Table(\"{tableName}\")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() {"); writer.Write($" Delete.Table(\"{tableName}\");"); writer.WriteLine(@" } } }"); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ConsoleApp { public class Table { private readonly string tableName; private readonly IEnumerable<Column> columns; public Table(string tableName, IEnumerable<Column> columns) { this.tableName = tableName; this.columns = columns; } public void OutputMigrationCode(TextWriter writer) { const string format = "yyyyMMddHHmmss"; writer.WriteLine(@"namespace Migrations {"); writer.WriteLine($" [Migration(\"{DateTime.Now.ToString(format)}\")]"); writer.Write($" public class {tableName}Migration : Migration"); writer.WriteLine(@" { public override void Up() {"); writer.Write($" Create.Table(\"{tableName}\")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.WriteLine(@"; } public override void Down() {"); writer.Write($" Delete.Table(\"{tableName}\");"); writer.WriteLine(@" } } }"); } } }
Fix namespace & class name
Fix namespace & class name
C#
mit
TeamnetGroup/schema2fm
7e492c36cd98a82140a70fb5712f60b05552a6db
ExRam.Gremlinq.Providers.CosmosDb.Tests/GroovySerializationTest.cs
ExRam.Gremlinq.Providers.CosmosDb.Tests/GroovySerializationTest.cs
using System; using System.Linq; using ExRam.Gremlinq.Core.Tests; using FluentAssertions; using Xunit; using static ExRam.Gremlinq.Core.GremlinQuerySource; namespace ExRam.Gremlinq.Providers.CosmosDb.Tests { public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor> { [Fact] public void Limit_overflow() { g .V() .Limit((long)int.MaxValue + 1) .Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x)) .Should() .Throw<ArgumentOutOfRangeException>(); } [Fact] public void Where_property_array_intersects_empty_array2() { g .V<User>() .Where(t => t.PhoneNumbers.Intersect(new string[0]).Any()) .Should() .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())") .WithParameters("User"); } } }
using System; using System.Linq; using ExRam.Gremlinq.Core.Tests; using FluentAssertions; using Xunit; using static ExRam.Gremlinq.Core.GremlinQuerySource; namespace ExRam.Gremlinq.Providers.CosmosDb.Tests { public class GroovySerializationTest : GroovySerializationTest<CosmosDbGroovyGremlinQueryElementVisitor> { [Fact] public void Limit_overflow() { g .V() .Limit((long)int.MaxValue + 1) .Invoking(x => new CosmosDbGroovyGremlinQueryElementVisitor().Visit(x)) .Should() .Throw<ArgumentOutOfRangeException>(); } [Fact] public void Where_property_array_intersects_empty_array() { g .V<User>() .Where(t => t.PhoneNumbers.Intersect(new string[0]).Any()) .Should() .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())") .WithParameters("User"); } [Fact] public void Where_property_is_contained_in_empty_enumerable() { var enumerable = Enumerable.Empty<int>(); g .V<User>() .Where(t => enumerable.Contains(t.Age)) .Should() .SerializeToGroovy<CosmosDbGroovyGremlinQueryElementVisitor>("g.V().hasLabel(_a).not(__.identity())") .WithParameters("User"); } } }
Bring back integration test for CosmosDb.
Bring back integration test for CosmosDb.
C#
mit
ExRam/ExRam.Gremlinq
93fb70e0c8bcb4c2d37aef5ef6701aee7709b779
Octokit/Helpers/EnumExtensions.cs
Octokit/Helpers/EnumExtensions.cs
using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using Octokit.Internal; namespace Octokit { static class EnumExtensions { [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] internal static string ToParameter(this Enum prop) { if (prop == null) return null; var propString = prop.ToString(); var member = prop.GetType().GetMember(propString).FirstOrDefault(); if (member == null) return null; var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false) .Cast<ParameterAttribute>() .FirstOrDefault(); return attribute != null ? attribute.Value : propString.ToLowerInvariant(); } } }
using System; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using Octokit.Internal; namespace Octokit { static class EnumExtensions { [SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase")] internal static string ToParameter(this Enum prop) { if (prop == null) return null; var propString = prop.ToString(); var member = prop.GetType().GetMember(propString).FirstOrDefault(); if (member == null) return null; var attribute = member.GetCustomAttributes(typeof(ParameterAttribute), false) .Cast<ParameterAttribute>() .FirstOrDefault(); return attribute != null ? attribute.Value : propString.ToLowerInvariant(); } } }
Add back in the reflection namespace
Add back in the reflection namespace
C#
mit
shiftkey-tester-org-blah-blah/octokit.net,hitesh97/octokit.net,daukantas/octokit.net,naveensrinivasan/octokit.net,gdziadkiewicz/octokit.net,thedillonb/octokit.net,editor-tools/octokit.net,shana/octokit.net,shiftkey-tester/octokit.net,mminns/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,ivandrofly/octokit.net,Sarmad93/octokit.net,ivandrofly/octokit.net,SamTheDev/octokit.net,bslliw/octokit.net,chunkychode/octokit.net,cH40z-Lord/octokit.net,editor-tools/octokit.net,gdziadkiewicz/octokit.net,dampir/octokit.net,brramos/octokit.net,Sarmad93/octokit.net,M-Zuber/octokit.net,shiftkey-tester/octokit.net,gabrielweyer/octokit.net,octokit-net-test-org/octokit.net,SamTheDev/octokit.net,gabrielweyer/octokit.net,devkhan/octokit.net,eriawan/octokit.net,geek0r/octokit.net,octokit/octokit.net,shiftkey/octokit.net,adamralph/octokit.net,fake-organization/octokit.net,khellang/octokit.net,nsnnnnrn/octokit.net,alfhenrik/octokit.net,hahmed/octokit.net,TattsGroup/octokit.net,khellang/octokit.net,TattsGroup/octokit.net,M-Zuber/octokit.net,dampir/octokit.net,rlugojr/octokit.net,takumikub/octokit.net,thedillonb/octokit.net,rlugojr/octokit.net,SmithAndr/octokit.net,octokit/octokit.net,shiftkey/octokit.net,chunkychode/octokit.net,shana/octokit.net,nsrnnnnn/octokit.net,SmithAndr/octokit.net,devkhan/octokit.net,mminns/octokit.net,hahmed/octokit.net,octokit-net-test-org/octokit.net,alfhenrik/octokit.net,eriawan/octokit.net
ccb2341434475dced47eddeaff849ab89eeeb5ba
MailChimp.Net.Api/PostHelpers.cs
MailChimp.Net.Api/PostHelpers.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace MailChimp.Net.Api { class PostHelpers { public static string PostJson(string url, string data) { var bytes = Encoding.Default.GetBytes(data); using (var client = new WebClient()) { client.Headers.Add("Content-Type", "application/json"); var response = client.UploadData(url, "POST", bytes); return Encoding.Default.GetString(response); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace MailChimp.Net.Api { class PostHelpers { public static string PostJson(string url, string data) { var bytes = Encoding.UTF8.GetBytes(data); using (var client = new WebClient()) { client.Headers.Add("Content-Type", "application/json"); var response = client.UploadData(url, "POST", bytes); return Encoding.Default.GetString(response); } } } }
Update default encoding to utf8 for supporting non-us symbols
Update default encoding to utf8 for supporting non-us symbols
C#
mit
sdesyllas/MailChimp.Net
fc96711b3464fb46050eb34e04532cc3f4ebd540
Modix/Modules/CodePasteModule.cs
Modix/Modules/CodePasteModule.cs
using Discord.Commands; using Modix.Services.AutoCodePaste; using System.Threading.Tasks; namespace Modix.Modules { [Name("Code Paste"), Summary("Paste some code to the internet.")] public class CodePasteModule : ModuleBase { private CodePasteService _service; public CodePasteModule(CodePasteService service) { _service = service; } [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")] public async Task Run([Remainder] string code) { string url = await _service.UploadCode(Context.Message, code); var embed = _service.BuildEmbed(Context.User, code, url); await ReplyAsync(Context.User.Mention, false, embed); await Context.Message.DeleteAsync(); } } }
using Discord.Commands; using Modix.Services.AutoCodePaste; using System.Net; using System.Threading.Tasks; namespace Modix.Modules { [Name("Code Paste"), Summary("Paste some code to the internet.")] public class CodePasteModule : ModuleBase { private CodePasteService _service; public CodePasteModule(CodePasteService service) { _service = service; } [Command("paste"), Summary("Paste the rest of your message to the internet, and return the URL.")] public async Task Run([Remainder] string code) { string url = null; string error = null; try { url = await _service.UploadCode(Context.Message, code); } catch (WebException ex) { url = null; error = ex.Message; } if (url != null) { var embed = _service.BuildEmbed(Context.User, code, url); await ReplyAsync(Context.User.Mention, false, embed); await Context.Message.DeleteAsync(); } else { await ReplyAsync(error); } } } }
Handle hastebin failure in the CodePaste module
Handle hastebin failure in the CodePaste module
C#
mit
mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX
4e20847855444cb0b559e2672ee603ffd562dceb
UnitTestProject1/UnitTest1.cs
UnitTestProject1/UnitTest1.cs
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5); Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6); } [TestMethod] public void ShouldFail() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), ClassLibrary1.Class1.ReturnSix()); } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class UnitTest1 { [TestMethod] public void TestMethod1() { Assert.AreEqual(ClassLibrary1.Class1.ReturnFive(), 5); Assert.AreEqual(ClassLibrary1.Class1.ReturnSix(), 6); } } }
Fix failing test ... by removing it
Fix failing test ... by removing it
C#
unlicense
PhilboBaggins/ci-experiments-dotnetcore,PhilboBaggins/ci-experiments-dotnetcore
2a76d81f27dcbfb27667de4c4239e7c46000dde6
src/ReverseMarkdown/Converters/P.cs
src/ReverseMarkdown/Converters/P.cs
using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine + Environment.NewLine; } } }
using System; using System.Linq; using HtmlAgilityPack; namespace ReverseMarkdown.Converters { public class P : ConverterBase { public P(Converter converter) : base(converter) { Converter.Register("p", this); } public override string Convert(HtmlNode node) { var indentation = IndentationFor(node); return $"{indentation}{TreatChildren(node).Trim()}{Environment.NewLine}"; } private static string IndentationFor(HtmlNode node) { var length = node.Ancestors("ol").Count() + node.Ancestors("ul").Count(); return node.ParentNode.Name.ToLowerInvariant() == "li" && node.ParentNode.FirstChild != node ? new string(' ', length * 4) : Environment.NewLine; } } }
Fix to convert paragraph tag with single carriage return
Fix to convert paragraph tag with single carriage return
C#
mit
mysticmind/reversemarkdown-net
c5bdf02db3149a62e55e59715ff76488c3aabfad
Test/ConfigurationTests.cs
Test/ConfigurationTests.cs
using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.TeamFoundation.Authentication.Test { /// <summary> /// A class to test <see cref="Configuration"/>. /// </summary> [TestClass] public class ConfigurationTests { [TestMethod] public void ParseGitConfig_Simple() { const string input = @" [core] autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } [TestMethod] public void ParseGitConfig_OverwritesValues() { // http://thedailywtf.com/articles/What_Is_Truth_0x3f_ const string input = @" [core] autocrlf = true autocrlf = FileNotFound autocrlf = false "; var values = TestParseGitConfig(input); Assert.AreEqual("false", values["core.autocrlf"]); } private static Dictionary<string, string> TestParseGitConfig(string input) { var values = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); using (var sr = new StringReader(input)) { Configuration.ParseGitConfig(sr, values); } return values; } } }
Add test to verify overwriting of values.
Add test to verify overwriting of values.
C#
mit
Alan-Lun/git-p3
21f5514fe11f4ee4c02661134bffbf700e24170d
src/EditorFeatures/TestUtilities/TestExtensionErrorHandler.cs
src/EditorFeatures/TestUtilities/TestExtensionErrorHandler.cs
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(TestExtensionErrorHandler))] [Export(typeof(IExtensionErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler { private List<Exception> _exceptions = new List<Exception>(); public void HandleError(object sender, Exception exception) { if (exception is ArgumentOutOfRangeException && ((ArgumentOutOfRangeException)exception).ParamName == "span") { // TODO: this is known bug 655591, fixed by Jack in changeset 931906 // Remove this workaround once the fix reaches the DP branch and we all move over. return; } _exceptions.Add(exception); } public ICollection<Exception> GetExceptions() { // We'll clear off our list, so that way we don't report this for other tests var newExceptions = _exceptions; _exceptions = new List<Exception>(); return newExceptions; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.UnitTests { [Export(typeof(TestExtensionErrorHandler))] [Export(typeof(IExtensionErrorHandler))] internal class TestExtensionErrorHandler : IExtensionErrorHandler { private List<Exception> _exceptions = new List<Exception>(); public void HandleError(object sender, Exception exception) { _exceptions.Add(exception); } public ICollection<Exception> GetExceptions() { // We'll clear off our list, so that way we don't report this for other tests var newExceptions = _exceptions; _exceptions = new List<Exception>(); return newExceptions; } } }
Delete workaround for a long-fixed editor bug
Delete workaround for a long-fixed editor bug
C#
mit
MichalStrehovsky/roslyn,orthoxerox/roslyn,wvdd007/roslyn,davkean/roslyn,cston/roslyn,AnthonyDGreen/roslyn,weltkante/roslyn,tvand7093/roslyn,gafter/roslyn,eriawan/roslyn,robinsedlaczek/roslyn,weltkante/roslyn,bartdesmet/roslyn,kelltrick/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,bartdesmet/roslyn,wvdd007/roslyn,AmadeusW/roslyn,dotnet/roslyn,jamesqo/roslyn,Giftednewt/roslyn,diryboy/roslyn,lorcanmooney/roslyn,agocke/roslyn,jkotas/roslyn,MattWindsor91/roslyn,tmeschter/roslyn,kelltrick/roslyn,genlu/roslyn,Hosch250/roslyn,eriawan/roslyn,abock/roslyn,agocke/roslyn,OmarTawfik/roslyn,tmat/roslyn,KirillOsenkov/roslyn,stephentoub/roslyn,genlu/roslyn,lorcanmooney/roslyn,bartdesmet/roslyn,agocke/roslyn,bkoelman/roslyn,TyOverby/roslyn,dpoeschl/roslyn,cston/roslyn,jasonmalinowski/roslyn,diryboy/roslyn,jkotas/roslyn,CaptainHayashi/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,srivatsn/roslyn,brettfo/roslyn,mattscheffer/roslyn,CaptainHayashi/roslyn,bkoelman/roslyn,tvand7093/roslyn,tannergooding/roslyn,aelij/roslyn,tmeschter/roslyn,khyperia/roslyn,gafter/roslyn,pdelvo/roslyn,dpoeschl/roslyn,jmarolf/roslyn,mavasani/roslyn,jkotas/roslyn,physhi/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,mattscheffer/roslyn,tmat/roslyn,shyamnamboodiripad/roslyn,khyperia/roslyn,mattscheffer/roslyn,tmeschter/roslyn,jcouv/roslyn,panopticoncentral/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,DustinCampbell/roslyn,pdelvo/roslyn,kelltrick/roslyn,AlekseyTs/roslyn,CaptainHayashi/roslyn,orthoxerox/roslyn,mmitche/roslyn,VSadov/roslyn,xasx/roslyn,Hosch250/roslyn,reaction1989/roslyn,AmadeusW/roslyn,TyOverby/roslyn,diryboy/roslyn,robinsedlaczek/roslyn,AlekseyTs/roslyn,shyamnamboodiripad/roslyn,AlekseyTs/roslyn,MattWindsor91/roslyn,abock/roslyn,pdelvo/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,jamesqo/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,mgoertz-msft/roslyn,KevinRansom/roslyn,OmarTawfik/roslyn,weltkante/roslyn,Giftednewt/roslyn,orthoxerox/roslyn,nguerrera/roslyn,jcouv/roslyn,Hosch250/roslyn,xasx/roslyn,AmadeusW/roslyn,dotnet/roslyn,VSadov/roslyn,genlu/roslyn,cston/roslyn,tvand7093/roslyn,AnthonyDGreen/roslyn,ErikSchierboom/roslyn,MattWindsor91/roslyn,panopticoncentral/roslyn,davkean/roslyn,Giftednewt/roslyn,jasonmalinowski/roslyn,DustinCampbell/roslyn,swaroop-sridhar/roslyn,MichalStrehovsky/roslyn,KirillOsenkov/roslyn,eriawan/roslyn,dpoeschl/roslyn,ErikSchierboom/roslyn,paulvanbrenk/roslyn,abock/roslyn,OmarTawfik/roslyn,mmitche/roslyn,tannergooding/roslyn,mavasani/roslyn,stephentoub/roslyn,reaction1989/roslyn,sharwell/roslyn,khyperia/roslyn,swaroop-sridhar/roslyn,lorcanmooney/roslyn,jmarolf/roslyn,MattWindsor91/roslyn,reaction1989/roslyn,nguerrera/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,wvdd007/roslyn,KirillOsenkov/roslyn,heejaechang/roslyn,nguerrera/roslyn,paulvanbrenk/roslyn,KevinRansom/roslyn,heejaechang/roslyn,tannergooding/roslyn,davkean/roslyn,mgoertz-msft/roslyn,robinsedlaczek/roslyn,dotnet/roslyn,gafter/roslyn,tmat/roslyn,mmitche/roslyn,mavasani/roslyn,srivatsn/roslyn,KevinRansom/roslyn,DustinCampbell/roslyn,sharwell/roslyn,stephentoub/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,jamesqo/roslyn,aelij/roslyn,xasx/roslyn,bkoelman/roslyn,heejaechang/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,shyamnamboodiripad/roslyn,paulvanbrenk/roslyn,physhi/roslyn,AnthonyDGreen/roslyn,jmarolf/roslyn,srivatsn/roslyn,aelij/roslyn,ErikSchierboom/roslyn,TyOverby/roslyn,brettfo/roslyn
a4d52ab0963b29d62d4d5374fc05cd58e1211260
src/keypay-dotnet/ApiFunctions/V2/PayRunDeductionFunction.cs
src/keypay-dotnet/ApiFunctions/V2/PayRunDeductionFunction.cs
using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }
using KeyPay.DomainModels.V2.PayRun; using RestSharp; namespace KeyPay.ApiFunctions.V2 { public class PayRunDeductionFunction : BaseFunction { public PayRunDeductionFunction(ApiRequestExecutor api) : base(api) { } public DeductionsResponse List(int businessId, int payRunId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions"); } public DeductionsResponse List(int businessId, int payRunId, int employeeId) { return ApiRequest<DeductionsResponse>("/business/" + businessId + "/payrun/" + payRunId + "/deductions/" + employeeId); } public DeductionModel Submit(int businessId, SubmitDeductionsRequest deductions) { return ApiRequest<DeductionModel, SubmitDeductionsRequest>("/business/" + businessId + "/payrun/" + deductions.PayRunId + "/deductions", deductions, Method.POST); } } }
Add function to get deductions from a payrun for a specific employee
Add function to get deductions from a payrun for a specific employee
C#
mit
KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet,KeyPay/keypay-dotnet
d4badac60f14148750d47f361a6fd831020b5375
ClubChallengeBeta/App_Start/BundleConfig.cs
ClubChallengeBeta/App_Start/BundleConfig.cs
using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.js", "~/Scripts/respond.js", "~/Scripts/blueimp-gallery.js", "~/Scripts/bootstrap-image-gallery.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.css", "~/Content/blueimp-gallery.css", "~/Content/bootstrap-image-gallery.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.css", "~/Content/site.css")); } } }
using System.Web; using System.Web.Optimization; namespace ClubChallengeBeta { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.min.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( "~/Scripts/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( "~/Scripts/modernizr-*")); //blueimp.github.io/Gallery/js/jquery.blueimp-gallery.min.js bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( "~/Scripts/bootstrap.min.js", "~/Scripts/respond.min.js", "~/Scripts/blueimp-gallery.min.js", "~/Scripts/bootstrap-image-gallery.min.js")); bundles.Add(new StyleBundle("~/Content/css").Include( "~/Content/bootstrap.min.css", "~/Content/blueimp-gallery.min.css", "~/Content/bootstrap-image-gallery.min.css", "~/Content/bootstrap-social.css", "~/Content/font-awesome.css", "~/Content/ionicons.min.css", "~/Content/site.css")); } } }
Change app to use minified files
Change app to use minified files
C#
mit
yyankov/club-challange,yyankov/club-challange,yyankov/club-challange
aa1997e5e8c4fcbe16fb2fceb351563b58f126dc
NBi.Core/Scalar/Resolver/IScalarResolver.cs
NBi.Core/Scalar/Resolver/IScalarResolver.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Scalar.Resolver { public interface IScalarResolver { object Execute(); } public interface IScalarResolver<T> : IScalarResolver { T Execute(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NBi.Core.Scalar.Resolver { public interface IScalarResolver { object Execute(); } public interface IScalarResolver<T> : IScalarResolver { new T Execute(); } }
Remove warning about hidden versus new
Remove warning about hidden versus new
C#
apache-2.0
Seddryck/NBi,Seddryck/NBi
26591b838aa62eafc225d96fb3fe598e40f7d6c0
src/Tgstation.Server.Host.Watchdog/WindowsActiveAssemblyDeleter.cs
src/Tgstation.Server.Host.Watchdog/WindowsActiveAssemblyDeleter.cs
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file //Also append the long path prefix just in case we're running on .NET framework var tmpLocation = String.Concat(@"\\?\", assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } }
using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; namespace Tgstation.Server.Host.Watchdog { /// <summary> /// See <see cref="IActiveAssemblyDeleter"/> for Windows systems /// </summary> sealed class WindowsActiveAssemblyDeleter : IActiveAssemblyDeleter { /// <summary> /// Set a file located at <paramref name="path"/> to be deleted on reboot /// </summary> /// <param name="path">The file to delete on reboot</param> [ExcludeFromCodeCoverage] static void DeleteFileOnReboot(string path) { if (!NativeMethods.MoveFileEx(path, null, NativeMethods.MoveFileFlags.DelayUntilReboot)) throw new Win32Exception(Marshal.GetLastWin32Error()); } /// <inheritdoc /> public void DeleteActiveAssembly(string assemblyPath) { if (assemblyPath == null) throw new ArgumentNullException(nameof(assemblyPath)); //Can't use Path.GetTempFileName() because it may cross drives, which won't actually rename the file var tmpLocation = String.Concat(assemblyPath, Guid.NewGuid()); File.Move(assemblyPath, tmpLocation); DeleteFileOnReboot(tmpLocation); } } }
Remove windows long filename prefix
Remove windows long filename prefix
C#
agpl-3.0
Cyberboss/tgstation-server,tgstation/tgstation-server-tools,tgstation/tgstation-server,tgstation/tgstation-server,Cyberboss/tgstation-server
a20806d3a8fa68155caef9ad7bb0d488270c667c
MarcelloDB.uwp/Platform.cs
MarcelloDB.uwp/Platform.cs
using MarcelloDB.Collections; using MarcelloDB.Platform; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public Storage.IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } }
using MarcelloDB.Collections; using MarcelloDB.Platform; using MarcelloDB.Storage; using MarcelloDB.uwp.Storage; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Storage; namespace MarcelloDB.uwp { public class Platform : IPlatform { public IStorageStreamProvider CreateStorageStreamProvider(string rootPath) { return new FileStorageStreamProvider(GetFolderForPath(rootPath)); } StorageFolder GetFolderForPath(string path) { var getFolderTask = StorageFolder.GetFolderFromPathAsync(path).AsTask(); getFolderTask.ConfigureAwait(false); getFolderTask.Wait(); return getFolderTask.Result; } } }
Fix namespace issue in uwp
Fix namespace issue in uwp
C#
mit
markmeeus/MarcelloDB
b0bbcf51a2a44e515f563e6075cf0fa99207f66f
BankFileParsers/Classes/BaiDetail.cs
BankFileParsers/Classes/BaiDetail.cs
using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } } }
using System.Collections.Generic; namespace BankFileParsers { public class BaiDetail { public string TransactionDetail { get; private set; } public List<string> DetailContinuation { get; internal set; } public BaiDetail(string line) { TransactionDetail = line; DetailContinuation = new List<string>(); } /// <summary> /// Overwrite the TransactionDetail line with a new string /// </summary> /// <param name="line">New string to overwrite with</param> public void SetTransactionDetail(string line) { TransactionDetail = line; } } }
Add new method to overwrite TransactionDetail line with a new string.
Add new method to overwrite TransactionDetail line with a new string.
C#
mit
kenwilcox/BankFileParsers
81c3c2274f736cbe86ccf258e9a85254368c3d7e
Assets/Scripts/Enemy/Action_Patrol.cs
Assets/Scripts/Enemy/Action_Patrol.cs
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.Resume (); if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }
using UnityEngine; [CreateAssetMenu (menuName = "AI/Actions/Enemy_Patrol")] public class Action_Patrol : Action { public override void Act(StateController controller) { Act(controller as Enemy_StateController); } public void Act(Enemy_StateController controller) { Patrol(controller); } private void Patrol(Enemy_StateController controller) { controller.navMeshAgent.destination = controller.movementVariables.wayPointList [controller.movementVariables.nextWayPoint].position; controller.navMeshAgent.isStopped = false; if (controller.navMeshAgent.remainingDistance <= controller.navMeshAgent.stoppingDistance && !controller.navMeshAgent.pathPending) { controller.movementVariables.nextWayPoint = (controller.movementVariables.nextWayPoint + 1) % controller.movementVariables.wayPointList.Count; } } }
Replace obsolete NavMeshAgent interface fot he newer one
Replace obsolete NavMeshAgent interface fot he newer one
C#
apache-2.0
allmonty/BrokenShield,allmonty/BrokenShield
703bd707cf3aeeb06010f2b6df9ab5ff846d5856
Properties/AssemblyInfo.cs
Properties/AssemblyInfo.cs
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")] [assembly: AssemblyDescription("")]
using System.Reflection; [assembly: AssemblyTitle("Autofac.Extras.Tests.AggregateService")]
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
Build script now writes the package name and version into the AssemblyDescription attibute. This allows the package information to be seen in Visual Studio avoiding confusion with the assembly version that remains at the major.
C#
mit
autofac/Autofac.Extras.AggregateService
22e96843046c670e1263fc5146c9e3dbc577e982
src/Atata.WebDriverExtras/Extensions/IWebElementExtensions.cs
src/Atata.WebDriverExtras/Extensions/IWebElementExtensions.cs
using OpenQA.Selenium; using System; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } }
using System; using System.Linq; using OpenQA.Selenium; namespace Atata { // TODO: Review IWebElementExtensions class. Remove unused methods. public static class IWebElementExtensions { public static WebElementExtendedSearchContext Try(this IWebElement element) { return new WebElementExtendedSearchContext(element); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout) { return new WebElementExtendedSearchContext(element, timeout); } public static WebElementExtendedSearchContext Try(this IWebElement element, TimeSpan timeout, TimeSpan retryInterval) { return new WebElementExtendedSearchContext(element, timeout, retryInterval); } public static bool HasContent(this IWebElement element, string content) { return element.Text.Contains(content); } public static bool HasClass(this IWebElement element, string className) { return element.GetAttribute("class").Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Contains(className); } public static string GetValue(this IWebElement element) { return element.GetAttribute("value"); } public static IWebElement FillInWith(this IWebElement element, string text) { element.Clear(); if (!string.IsNullOrEmpty(text)) element.SendKeys(text); return element; } } }
Add HasClass extension method for IWebElement
Add HasClass extension method for IWebElement
C#
apache-2.0
atata-framework/atata,YevgeniyShunevych/Atata,atata-framework/atata,YevgeniyShunevych/Atata
09b1a40f3cce0d9c31bb7d06e4743bf5eaae2019
XamarinTest/XamarinTest.cs
XamarinTest/XamarinTest.cs
using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
using System; using Xamarin.Forms; namespace XamarinTest { public class App : Application { public App () { // The root page of your application MainPage = new ContentPage { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { new Label { XAlign = TextAlignment.Center, Text = "Welcome to Xamarin Forms!" } } } }; } protected override void OnStart () { TelemetryManager.TrackEvent ("My Shared Event"); ApplicationInsights.RenewSessionWithId ("MySession"); ApplicationInsights.SetUserId ("Christoph"); TelemetryManager.TrackMetric ("My custom metric", 2.2); } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
Use public interface in test app
Use public interface in test app
C#
mit
Microsoft/ApplicationInsights-Xamarin
fd4b49e0d5ab086d24225ce69b1a2a267ab4a4d5
Torch.Server/Managers/RemoteAPIManager.cs
Torch.Server/Managers/RemoteAPIManager.cs
using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { if (MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } base.Attach(); } } }
using NLog; using Sandbox; using Torch.API; using Torch.Managers; using VRage.Dedicated.RemoteAPI; namespace Torch.Server.Managers { public class RemoteAPIManager : Manager { /// <inheritdoc /> public RemoteAPIManager(ITorchBase torchInstance) : base(torchInstance) { } /// <inheritdoc /> public override void Attach() { Torch.GameStateChanged += TorchOnGameStateChanged; base.Attach(); } /// <inheritdoc /> public override void Detach() { Torch.GameStateChanged -= TorchOnGameStateChanged; base.Detach(); } private void TorchOnGameStateChanged(MySandboxGame game, TorchGameState newstate) { if (newstate == TorchGameState.Loading && MySandboxGame.ConfigDedicated.RemoteApiEnabled && !string.IsNullOrEmpty(MySandboxGame.ConfigDedicated.RemoteSecurityKey)) { var myRemoteServer = new MyRemoteServer(MySandboxGame.ConfigDedicated.RemoteApiPort, MySandboxGame.ConfigDedicated.RemoteSecurityKey); LogManager.GetCurrentClassLogger().Info($"Remote API started on port {myRemoteServer.Port}"); } } } }
Fix remote API load order
Fix remote API load order
C#
apache-2.0
TorchAPI/Torch
f09c2c6ab2134813b4161e743abca3da648a36a0
src/System.Private.ServiceModel/tools/test/SelfHostWcfService/TestResources/BasicAuthResource.cs
src/System.Private.ServiceModel/tools/test/SelfHostWcfService/TestResources/BasicAuthResource.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; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using WcfTestBridgeCommon; namespace WcfService.TestResources { internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService> { protected override string Address { get { return "https-basic"; } } protected override string Protocol { get { return BaseAddressResource.Https; } } protected override int GetPort(ResourceRequestContext context) { return context.BridgeConfiguration.BridgeHttpsPort; } protected override Binding GetBinding() { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private ServiceCredentials GetServiceCredentials() { var serviceCredentials = new ServiceCredentials(); serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); return serviceCredentials; } protected override void ModifyBehaviors(ServiceDescription desc) { base.ModifyBehaviors(desc); desc.Behaviors.Remove<ServiceCredentials>(); desc.Behaviors.Add(GetServiceCredentials()); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ServiceModel; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Security; using WcfService.CertificateResources; using WcfTestBridgeCommon; namespace WcfService.TestResources { internal class BasicAuthResource : EndpointResource<WcfUserNameService, IWcfCustomUserNameService> { protected override string Address { get { return "https-basic"; } } protected override string Protocol { get { return BaseAddressResource.Https; } } protected override int GetPort(ResourceRequestContext context) { return context.BridgeConfiguration.BridgeHttpsPort; } protected override Binding GetBinding() { var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; return binding; } private ServiceCredentials GetServiceCredentials() { var serviceCredentials = new ServiceCredentials(); serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom; serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = new CustomUserNameValidator(); return serviceCredentials; } protected override void ModifyBehaviors(ServiceDescription desc) { base.ModifyBehaviors(desc); desc.Behaviors.Remove<ServiceCredentials>(); desc.Behaviors.Add(GetServiceCredentials()); } protected override void ModifyHost(ServiceHost serviceHost, ResourceRequestContext context) { // Ensure the https certificate is installed before this endpoint resource is used CertificateResourceHelpers.EnsureSslPortCertificateInstalled(context.BridgeConfiguration); base.ModifyHost(serviceHost, context); } } }
Fix test failure when BasicAuth tests were first to run
Fix test failure when BasicAuth tests were first to run The Https BasicAuthentication tests failed were they were the first scenario tests run after a fresh start of the Bridge. But they succeeded when other scenario tests ran first. Root cause was that the BasicAuthResource was not explicitly ensuring the SSL port certificate was installed. It passed if another scenario test did that first. The fix was to duplicate what the other Https test resources do and explicitly ensure the SSL port certificate is installed. Fixes #788
C#
mit
iamjasonp/wcf,imcarolwang/wcf,ericstj/wcf,imcarolwang/wcf,MattGal/wcf,dotnet/wcf,dotnet/wcf,mconnew/wcf,iamjasonp/wcf,StephenBonikowsky/wcf,khdang/wcf,shmao/wcf,imcarolwang/wcf,MattGal/wcf,mconnew/wcf,shmao/wcf,ElJerry/wcf,khdang/wcf,ElJerry/wcf,hongdai/wcf,KKhurin/wcf,hongdai/wcf,StephenBonikowsky/wcf,zhenlan/wcf,mconnew/wcf,zhenlan/wcf,dotnet/wcf,ericstj/wcf,KKhurin/wcf
5285c807f70cdc9b17a08df8891f60ca6d7d4258
Src/FluentAssertions/Common/Guard.cs
Src/FluentAssertions/Common/Guard.cs
using System; namespace FluentAssertions.Common { internal static class Guard { public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName) { if (obj is null) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message) { if (obj is null) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName, message); } } /// <summary> /// Workaround to make dotnet_code_quality.null_check_validation_methods work /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] private sealed class ValidatedNotNullAttribute : Attribute { } } }
using System; namespace FluentAssertions.Common { internal static class Guard { public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName) { if (obj is null) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNull<T>([ValidatedNotNull] T obj, string paramName, string message) { if (obj is null) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName); } } public static void ThrowIfArgumentIsNullOrEmpty([ValidatedNotNull] string str, string paramName, string message) { if (string.IsNullOrEmpty(str)) { throw new ArgumentNullException(paramName, message); } } public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName) where T : Enum { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(paramName); } } public static void ThrowIfArgumentIsOutOfRange<T>([ValidatedNotNull] T value, string paramName, string message) where T : Enum { if (!Enum.IsDefined(typeof(T), value)) { throw new ArgumentOutOfRangeException(paramName, message); } } /// <summary> /// Workaround to make dotnet_code_quality.null_check_validation_methods work /// https://github.com/dotnet/roslyn-analyzers/issues/3451#issuecomment-606690452 /// </summary> [AttributeUsage(AttributeTargets.Parameter)] private sealed class ValidatedNotNullAttribute : Attribute { } } }
Add guard methods for Enum Argument OutOfRange check
Add guard methods for Enum Argument OutOfRange check
C#
apache-2.0
jnyrup/fluentassertions,jnyrup/fluentassertions,dennisdoomen/fluentassertions,fluentassertions/fluentassertions,fluentassertions/fluentassertions,dennisdoomen/fluentassertions
a952a2b3cfb17f38f506109b95bd3177eda09e47
RightpointLabs.Pourcast.Web/Areas/Admin/Views/Tap/Index.cshtml
RightpointLabs.Pourcast.Web/Areas/Admin/Views/Tap/Index.cshtml
@model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel> @{ ViewBag.Title = "Index"; } <h2>Taps</h2> @foreach (var tap in Model) { <div class="col-lg-6"> <h3>@tap.Name</h3> @if (null == tap.Keg) { <h4>No Keg On Tap</h4> <hr /> } else { <h4>@tap.Keg.BeerName</h4> <p> Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining <br /> Percent Left: @tap.Keg.PercentRemaining <br /> </p> } <p> @Html.ActionLink("Edit", "Edit", new {id = tap.Id}) </p> </div> } <p> | @Html.ActionLink("Back to List", "Index") </p>
@model IEnumerable<RightpointLabs.Pourcast.Web.Areas.Admin.Models.TapModel> @{ ViewBag.Title = "Index"; } <h2>Taps</h2> @foreach (var tap in Model) { <div class="col-lg-6"> <h3>@tap.Name</h3> @if (null == tap.Keg) { <h4>No Keg On Tap</h4> <hr /> } else { <h4>@tap.Keg.BeerName</h4> <p> Amount of Beer Remaining: @tap.Keg.AmountOfBeerRemaining <br /> Percent Left: @tap.Keg.PercentRemaining <br /> </p> } <p> @Html.ActionLink("Edit", "Edit", new {id = tap.Id}, new { @class = "btn"}) @if (null != tap.Keg) { <a class="btn btn-pour" data-tap-id="@tap.Id" href="#">Pour</a> } </p> </div> } <p> | @Html.ActionLink("Back to List", "Index") </p> @section scripts { <script type="text/javascript"> $(function () { $(".btn-pour").each(function() { var $t = $(this); var tapId = $t.attr("data-tap-id"); var timer = null; var start = null; $t.mousedown(function () { $.getJSON("/api/tap/" + tapId + "/StartPour"); start = new Date().getTime(); timer = setInterval(function () { $.getJSON("/api/tap/" + tapId + "/Pouring?volume=" + ((new Date().getTime() - start) / 500)); }, 250); }); $t.mouseup(function () { clearInterval(timer); $.getJSON("/api/tap/" + tapId + "/StopPour?volume=" + ((new Date().getTime() - start) / 500)); }); }); }); </script> }
Add fake pour buttons in admin
Add fake pour buttons in admin They follow the same API as the Netduino will: 1 StartPour when pressed, 0-N Pouring while button held down, 1 StopPour when button released.
C#
mit
RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast,RightpointLabs/Pourcast
294e744002660ef99b99de95ea81a81d99d78629
Homunculus/MarekMotykaBot/ExtensionsMethods/StringExtensions.cs
Homunculus/MarekMotykaBot/ExtensionsMethods/StringExtensions.cs
using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-\']+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }
using System.Text.RegularExpressions; namespace MarekMotykaBot.ExtensionsMethods { public static class StringExtensions { public static string RemoveRepeatingChars(this string inputString) { string newString = string.Empty; char[] charArray = inputString.ToCharArray(); for (int i = 0; i < charArray.Length; i++) { if (string.IsNullOrEmpty(newString)) newString += charArray[i].ToString(); else if (newString[newString.Length - 1] != charArray[i]) newString += charArray[i].ToString(); } return newString; } public static string RemoveEmojis(this string inputString) { return Regex.Replace(inputString, @"[^a-zA-Z0-9żźćńółęąśŻŹĆĄŚĘŁÓŃ\s\?\.\,\!\-]+", "", RegexOptions.Compiled); } public static string RemoveEmotes(this string inputString) { return Regex.Replace(inputString, "(<:.+>)+", "", RegexOptions.Compiled); } public static string RemoveEmojisAndEmotes(this string inputString) { return inputString.RemoveEmotes().RemoveEmojis(); } } }
Fix regex pattern in removing emotes.
Fix regex pattern in removing emotes.
C#
mit
Ervie/Homunculus
325c3ebc780bd48dbd3997c5acbadce15c389d6a
api/CommaDelimitedArrayModelBinder.cs
api/CommaDelimitedArrayModelBinder.cs
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } }
using System; using System.ComponentModel; using System.Linq; using System.Reflection; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace api { public class CommaDelimitedArrayModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { if (bindingContext.ModelMetadata.IsEnumerableType) { var key = bindingContext.ModelName; var value = bindingContext.ValueProvider.GetValue(key).ToString(); if (!string.IsNullOrWhiteSpace(value)) { var elementType = bindingContext.ModelType.GetTypeInfo().GenericTypeArguments[0]; var converter = TypeDescriptor.GetConverter(elementType); var values = value.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries) .Select(x => converter.ConvertFromString(x.Trim())) .ToArray(); var typedValues = Array.CreateInstance(elementType, values.Length); values.CopyTo(typedValues, 0); bindingContext.Result = ModelBindingResult.Success(typedValues); } else { Console.WriteLine("string was empty"); // change this line to null if you prefer nulls to empty arrays bindingContext.Result = ModelBindingResult.Success(Array.CreateInstance(bindingContext.ModelType.GetGenericArguments()[0], 0)); } return Task.CompletedTask; } Console.WriteLine("Not enumerable"); return Task.CompletedTask; } } }
Add input binder to allow for comma-separated list inputs for API routes
Add input binder to allow for comma-separated list inputs for API routes Signed-off-by: Max Cairney-Leeming <d90f0d0190ac210d40c0e06a2594c771efeb4f5b@gmail.com>
C#
mit
mtcairneyleeming/latin
08f3c8f246b6472cf05bd6728962e56e28b41f8c
Tests/TroubleshootingTests.cs
Tests/TroubleshootingTests.cs
using Core; using StructureMap; using System.Diagnostics; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); Trace.Write(whatDoIHave); } } }
using Core; using StructureMap; using Xunit; namespace Tests { public class TroubleshootingTests { [Fact] public void ShowBuildPlan() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var buildPlan = container.Model.For<IService>() .Default .DescribeBuildPlan(); var expectedBuildPlan = @"PluginType: Core.IService Lifecycle: Transient new Service() "; Assert.Equal(expectedBuildPlan, buildPlan); } [Fact] public void WhatDoIHave() { var container = new Container(x => { x.For<IService>().Use<Service>(); }); var whatDoIHave = container.WhatDoIHave(); var expectedWhatDoIHave = @" =================================================================================================== PluginType Namespace Lifecycle Description Name --------------------------------------------------------------------------------------------------- Func<TResult> System Transient Open Generic Template for Func<> (Default) --------------------------------------------------------------------------------------------------- Func<T, TResult> System Transient Open Generic Template for Func<,> (Default) --------------------------------------------------------------------------------------------------- IContainer StructureMap Singleton Object: StructureMap.Container (Default) --------------------------------------------------------------------------------------------------- IService Core Transient Core.Service (Default) --------------------------------------------------------------------------------------------------- Lazy<T> System Transient Open Generic Template for Func<> (Default) ==================================================================================================="; Assert.Equal(expectedWhatDoIHave, whatDoIHave); } } }
Modify WhatDoIHave to show expected result
Modify WhatDoIHave to show expected result
C#
mit
kendaleiv/di-servicelocation-structuremap,kendaleiv/di-servicelocation-structuremap,kendaleiv/di-servicelocation-structuremap
bf40e69c95280ad374c094a51b62040d1a58220a
Mollie.Api/Models/Payment/PaymentMethod.cs
Mollie.Api/Models/Payment/PaymentMethod.cs
namespace Mollie.Api.Models.Payment { public static class PaymentMethod { public const string Bancontact = "bancontact"; public const string BankTransfer = "banktransfer"; public const string Belfius = "belfius"; public const string CreditCard = "creditcard"; public const string DirectDebit = "directdebit"; public const string Eps = "eps"; public const string GiftCard = "giftcard"; public const string Giropay = "giropay"; public const string Ideal = "ideal"; public const string IngHomePay = "inghomepay"; public const string Kbc = "kbc"; public const string PayPal = "paypal"; public const string PaySafeCard = "paysafecard"; public const string Sofort = "sofort"; public const string Refund = "refund"; public const string KlarnaPayLater = "klarnapaylater"; public const string KlarnaSliceIt = "klarnasliceit"; public const string Przelewy24 = "przelewy24"; public const string ApplePay = "applepay"; public const string MealVoucher = "mealvoucher"; } }
namespace Mollie.Api.Models.Payment { public static class PaymentMethod { public const string Bancontact = "bancontact"; public const string BankTransfer = "banktransfer"; public const string Belfius = "belfius"; public const string CreditCard = "creditcard"; public const string DirectDebit = "directdebit"; public const string Eps = "eps"; public const string GiftCard = "giftcard"; public const string Giropay = "giropay"; public const string Ideal = "ideal"; public const string IngHomePay = "inghomepay"; public const string Kbc = "kbc"; public const string PayPal = "paypal"; public const string PaySafeCard = "paysafecard"; public const string Sofort = "sofort"; public const string Refund = "refund"; public const string KlarnaPayLater = "klarnapaylater"; public const string KlarnaSliceIt = "klarnasliceit"; public const string Przelewy24 = "przelewy24"; public const string ApplePay = "applepay"; public const string MealVoucher = "mealvoucher"; public const string In3 = "in3"; } }
Add support for the new upcoming in3 payment method
Add support for the new upcoming in3 payment method
C#
mit
Viincenttt/MollieApi,Viincenttt/MollieApi
00fa7f0837ddfbae4bfd933b96b8f7da6fe68afd
src/Rescuer/Rescuer.Management/Controller/RescuerController.cs
src/Rescuer/Rescuer.Management/Controller/RescuerController.cs
using Rescuer.Management.Rescuers; namespace Rescuer.Management.Controller { public class RescuerController : IRescuerController { private readonly IRescuerFactory _factory; public RescuerController(IRescuerFactory factory) { _factory = factory; } public IRescuer[] IntializeRescuers(string[] monitoredEntities) { var rescuers = new IRescuer[monitoredEntities.Length]; for (int i = 0; i < rescuers.Length; i++) { rescuers[i] = _factory.Create(); rescuers[i].Connect(monitoredEntities[i]); } return rescuers; } public void DoWork(IRescuer[] rescuers) { for (int i = 0; i < rescuers.Length; i++) { rescuers[i].MonitorAndRescue(); } } } }
using System; using System.Text; using Rescuer.Management.Rescuers; namespace Rescuer.Management.Controller { public class RescuerController : IRescuerController { private readonly IRescuerFactory _factory; public RescuerController(IRescuerFactory factory) { _factory = factory; } public IRescuer[] IntializeRescuers(string[] monitoredEntities) { var rescuers = new IRescuer[monitoredEntities.Length]; for (int i = 0; i < rescuers.Length; i++) { if (String.IsNullOrWhiteSpace(monitoredEntities[i])) { var entitiesString = ToFlatString(monitoredEntities); throw new ArgumentException($"monitored entity name can't be null or empty! FailedIndex: {i} Array: [{entitiesString}]"); } rescuers[i] = _factory.Create(); rescuers[i].Connect(monitoredEntities[i]); } return rescuers; } public void DoWork(IRescuer[] rescuers) { for (int i = 0; i < rescuers.Length; i++) { rescuers[i].MonitorAndRescue(); } } private static string ToFlatString(string[] array) { var builder = new StringBuilder(); foreach (var entity in array) { builder.Append(entity); builder.Append(","); } var str = builder.ToString(); return str.Remove(str.Length - 1, 1); } } }
Handle empty entity name in rescuer
Handle empty entity name in rescuer
C#
mit
jarzynam/continuous,jarzynam/rescuer
58fe66b729be7cb6debd1e2dabd5d258b2fb1713
query/test/ReamQuery.Test/Helpers.cs
query/test/ReamQuery.Test/Helpers.cs
namespace ReamQuery.Test { using System; using Xunit; using ReamQuery.Helpers; using Microsoft.CodeAnalysis.Text; public class Helpers { [Fact] public void String_InsertTextAt() { var inp = "\r\n text\r\n"; var exp = "\r\n new text\r\n"; var output = inp.InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines_And_InsertTextAt() { var inp = "\r\n text\n"; var exp = "\r\n new text\r\n"; var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " text" + Environment.NewLine; var output = inp.NormalizeNewlines(); Assert.Equal(exp, output); } [Fact] public void String_ReplaceToken() { var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine; var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine; LinePosition pos; var output = inp.ReplaceToken("token", string.Empty, out pos); Assert.Equal(new LinePosition(2, 1), pos); Assert.Equal(exp, output); } } }
namespace ReamQuery.Test { using System; using Xunit; using ReamQuery.Helpers; using Microsoft.CodeAnalysis.Text; public class Helpers { [Fact] public void String_InsertTextAt() { var inp = Environment.NewLine + " text" + Environment.NewLine; var exp = Environment.NewLine + " new text" + Environment.NewLine; var output = inp.InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines_And_InsertTextAt() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " new text" + Environment.NewLine; var output = inp.NormalizeNewlines().InsertTextAt("new", 1, 1); Assert.Equal(exp, output); } [Fact] public void String_NormalizeNewlines() { var inp = "\r\n text\n"; var exp = Environment.NewLine + " text" + Environment.NewLine; var output = inp.NormalizeNewlines(); Assert.Equal(exp, output); } [Fact] public void String_ReplaceToken() { var inp = Environment.NewLine + Environment.NewLine + " token " + Environment.NewLine; var exp = Environment.NewLine + Environment.NewLine + " " + Environment.NewLine; LinePosition pos; var output = inp.ReplaceToken("token", string.Empty, out pos); Assert.Equal(new LinePosition(2, 1), pos); Assert.Equal(exp, output); } } }
Fix string test for ubuntu
Fix string test for ubuntu
C#
mit
stofte/ream-query
1b2bfd45da8f2ebc5e4110482ada8c311e10728a
src/Core/Messaging/MessageBusBase.cs
src/Core/Messaging/MessageBusBase.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Utility; namespace Foundatio.Messaging { public abstract class MessageBusBase : IMessagePublisher, IDisposable { private readonly CancellationTokenSource _queueDisposedCancellationTokenSource; private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>(); public MessageBusBase() { _queueDisposedCancellationTokenSource = new CancellationTokenSource(); TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100)); } private Task DoMaintenance() { Trace.WriteLine("Doing maintenance..."); foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) { _delayedMessages.Remove(message); Publish(message.MessageType, message.Message); } return TaskHelper.Completed(); } public abstract void Publish(Type messageType, object message, TimeSpan? delay = null); protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) { if (message == null) throw new ArgumentNullException("message"); _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) }); } protected class DelayedMessage { public DateTime SendTime { get; set; } public Type MessageType { get; set; } public object Message { get; set; } } public virtual void Dispose() { _queueDisposedCancellationTokenSource.Cancel(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Foundatio.Extensions; using Foundatio.Utility; namespace Foundatio.Messaging { public abstract class MessageBusBase : IMessagePublisher, IDisposable { private readonly CancellationTokenSource _queueDisposedCancellationTokenSource; private readonly List<DelayedMessage> _delayedMessages = new List<DelayedMessage>(); public MessageBusBase() { _queueDisposedCancellationTokenSource = new CancellationTokenSource(); //TaskHelper.RunPeriodic(DoMaintenance, TimeSpan.FromMilliseconds(500), _queueDisposedCancellationTokenSource.Token, TimeSpan.FromMilliseconds(100)); } private Task DoMaintenance() { Trace.WriteLine("Doing maintenance..."); foreach (var message in _delayedMessages.Where(m => m.SendTime <= DateTime.Now).ToList()) { _delayedMessages.Remove(message); Publish(message.MessageType, message.Message); } return TaskHelper.Completed(); } public abstract void Publish(Type messageType, object message, TimeSpan? delay = null); protected void AddDelayedMessage(Type messageType, object message, TimeSpan delay) { if (message == null) throw new ArgumentNullException("message"); _delayedMessages.Add(new DelayedMessage { Message = message, MessageType = messageType, SendTime = DateTime.Now.Add(delay) }); } protected class DelayedMessage { public DateTime SendTime { get; set; } public Type MessageType { get; set; } public object Message { get; set; } } public virtual void Dispose() { _queueDisposedCancellationTokenSource.Cancel(); } } }
Disable delayed messages to see what effect it has on tests.
Disable delayed messages to see what effect it has on tests.
C#
apache-2.0
FoundatioFx/Foundatio,Bartmax/Foundatio,vebin/Foundatio,exceptionless/Foundatio,wgraham17/Foundatio
58a67b69a949f5e0e5349573a66a9d663f98268c
src/Cake.Figlet.Tests/FigletTests.cs
src/Cake.Figlet.Tests/FigletTests.cs
using System; using Shouldly; using Xunit; namespace Cake.Figlet.Tests { public class FigletTests { [Fact] public void Figlet_can_render() { const string expected = @" _ _ _ _ __ __ _ _ | | | | ___ | || | ___ \ \ / / ___ _ __ | | __| | | |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` | | _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| | |_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_| |/ "; FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected); } } public static class ShouldlyAsciiExtensions { /// <summary> /// Helper to allow the expected ASCII art to be on it's own line when declaring /// the expected value in the source code /// </summary> /// <param name="input">The input.</param> /// <param name="expected">The expected.</param> public static void ShouldBeWithLeadingLineBreak(this string input, string expected) { (Environment.NewLine + input).ShouldBe(expected, StringCompareShould.IgnoreLineEndings); } } }
using System; using Shouldly; using Xunit; namespace Cake.Figlet.Tests { public class FigletTests { [Fact] public void Figlet_can_render() { const string expected = @" _ _ _ _ __ __ _ _ | | | | ___ | || | ___ \ \ / / ___ _ __ | | __| | | |_| | / _ \| || | / _ \ \ \ /\ / / / _ \ | '__|| | / _` | | _ || __/| || || (_) | _ \ V V / | (_) || | | || (_| | |_| |_| \___||_||_| \___/ ( ) \_/\_/ \___/ |_| |_| \__,_| |/ "; FigletAliases.Figlet(null, "Hello, World").ShouldBeWithLeadingLineBreak(expected); } } public static class ShouldlyAsciiExtensions { /// <summary> /// Helper to allow the expected ASCII art to be on it's own line when declaring /// the expected value in the source code /// </summary> /// <param name="input">The input.</param> /// <param name="expected">The expected.</param> public static void ShouldBeWithLeadingLineBreak(this string input, string expected) { (Environment.NewLine + input).ShouldBe(expected); } } }
Revert "(GH-36) Fix broken test"
Revert "(GH-36) Fix broken test" This reverts commit e8c0d4bc3a9fcb459096b05b189fd83f5883f1e2.
C#
mit
enkafan/Cake.Figlet
1d637d94f69702122f04fd3d33a1d3798055671a
src/ForEachAsyncCanceledException.cs
src/ForEachAsyncCanceledException.cs
namespace System.Collections.Async { /// <summary> /// This exception is thrown when you call <see cref="AsyncEnumerable{T}.Break"/>. /// </summary> public sealed class ForEachAsyncCanceledException : OperationCanceledException { } }
namespace System.Collections.Async { /// <summary> /// This exception is thrown when you call <see cref="ForEachAsyncExtensions.Break"/>. /// </summary> public sealed class ForEachAsyncCanceledException : OperationCanceledException { } }
Fix xml comment cref compiler warning
Fix xml comment cref compiler warning
C#
mit
tyrotoxin/AsyncEnumerable
ec226cc8b17e04500e4c8559a097dc71695b306b
src/MotleyFlash.AspNetCore.MessageProviders/SessionMessageProvider.cs
src/MotleyFlash.AspNetCore.MessageProviders/SessionMessageProvider.cs
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text; namespace MotleyFlash.AspNetCore.MessageProviders { public class SessionMessageProvider : IMessageProvider { public SessionMessageProvider(ISession session) { this.session = session; } private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; private readonly ISession session; private const string sessionKey = "motleyflash-session-message-provider"; public object Get() { byte[] value; object messages = null; if (session.TryGetValue(sessionKey, out value)) { if (value != null) { messages = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(value, 0, value.Length), jsonSerializerSettings); } } return messages; } public void Set(object messages) { session.Set( sessionKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( messages, jsonSerializerSettings))); session.CommitAsync(); } } }
using Microsoft.AspNetCore.Http; using Newtonsoft.Json; using System.Text; namespace MotleyFlash.AspNetCore.MessageProviders { public class SessionMessageProvider : IMessageProvider { public SessionMessageProvider(ISession session) { this.session = session; } private static JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.All }; private readonly ISession session; private const string sessionKey = "motleyflash-session-message-provider"; public object Get() { byte[] value; object messages = null; if (session.TryGetValue(sessionKey, out value)) { if (value != null) { messages = JsonConvert.DeserializeObject( Encoding.UTF8.GetString(value, 0, value.Length), jsonSerializerSettings); } } return messages; } public void Set(object messages) { session.Set( sessionKey, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject( messages, jsonSerializerSettings))); } } }
Remove session-commit statement that is not needed and already handled by middleware
Remove session-commit statement that is not needed and already handled by middleware Ref. https://github.com/aspnet/Session/blob/dabd28a5d9ac7837afbfce7c8dfa2805a9559857/src/Microsoft.AspNetCore.Session/SessionMiddleware.cs\#L116.
C#
mit
billboga/motleyflash,billboga/motleyflash
ed5810aa6f0cfb7121626ac3ce4c2b9bf883adc4
cslatest/Csla.Test/Silverlight/Server/DataPortal/TestableDataPortal.cs
cslatest/Csla.Test/Silverlight/Server/DataPortal/TestableDataPortal.cs
using System; using Csla.Server; namespace Csla.Testing.Business.DataPortal { /// <summary> /// Basically this test class exposes protected DataPortal constructor overloads to the /// Unit Testing System, allowing for a more fine-grained Unit Tests /// </summary> public class TestableDataPortal : Csla.Server.DataPortal { public TestableDataPortal() : base(){} public TestableDataPortal(string cslaAuthorizationProviderAppSettingName): base(cslaAuthorizationProviderAppSettingName) { } public TestableDataPortal(Type authProviderType):base(authProviderType) { } public static void Setup() { _authorizer = null; } public Type AuthProviderType { get { return _authorizer.GetType(); } } public IAuthorizeDataPortal AuthProvider { get { return _authorizer; } } public bool NullAuthorizerUsed { get { return AuthProviderType == typeof (NullAuthorizer); } } } }
using System; using Csla.Server; namespace Csla.Testing.Business.DataPortal { /// <summary> /// Basically this test class exposes protected DataPortal constructor overloads to the /// Unit Testing System, allowing for a more fine-grained Unit Tests /// </summary> public class TestableDataPortal : Csla.Server.DataPortal { public TestableDataPortal() : base(){} public TestableDataPortal(string cslaAuthorizationProviderAppSettingName): base(cslaAuthorizationProviderAppSettingName) { } public TestableDataPortal(Type authProviderType):base(authProviderType) { } public static void Setup() { Authorizer = null; } public Type AuthProviderType { get { return Authorizer.GetType(); } } public IAuthorizeDataPortal AuthProvider { get { return Authorizer; } } public bool NullAuthorizerUsed { get { return AuthProviderType == typeof (NullAuthorizer); } } } }
Update to use property, not field. bugid: 146
Update to use property, not field. bugid: 146
C#
mit
jonnybee/csla,MarimerLLC/csla,rockfordlhotka/csla,MarimerLLC/csla,JasonBock/csla,BrettJaner/csla,ronnymgm/csla-light,BrettJaner/csla,JasonBock/csla,jonnybee/csla,BrettJaner/csla,rockfordlhotka/csla,MarimerLLC/csla,ronnymgm/csla-light,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,ronnymgm/csla-light
151173d7d9e6f0de39c831ee3ee96cf3c0febbda
src/ReactiveUI.Routing.UWP/PagePresenter.cs
src/ReactiveUI.Routing.UWP/PagePresenter.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using ReactiveUI.Routing.Presentation; using Splat; namespace ReactiveUI.Routing.UWP { public class PagePresenter : Presenter<PagePresenterRequest> { private readonly Frame host; private readonly IViewLocator locator; public PagePresenter(Frame host, IViewLocator locator = null) { this.host = host ?? throw new ArgumentNullException(nameof(host)); this.locator = locator ?? Locator.Current.GetService<IViewLocator>(); } protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request) { return Observable.Create<PresenterResponse>(o => { try { var view = locator.ResolveView(request.ViewModel); view.ViewModel = request.ViewModel; host.Navigate(view.GetType()); o.OnNext(new PresenterResponse(view)); o.OnCompleted(); } catch (Exception ex) { o.OnError(ex); } return new CompositeDisposable(); }); } public static IDisposable RegisterHost(Frame control) { var resolver = Locator.Current.GetService<IMutablePresenterResolver>(); return resolver.Register(new PagePresenter(control)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Core; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; using ReactiveUI.Routing.Presentation; using Splat; namespace ReactiveUI.Routing.UWP { public class PagePresenter : Presenter<PagePresenterRequest> { private readonly ContentControl host; private readonly IViewLocator locator; public PagePresenter(ContentControl host, IViewLocator locator = null) { this.host = host ?? throw new ArgumentNullException(nameof(host)); this.locator = locator ?? Locator.Current.GetService<IViewLocator>(); } protected override IObservable<PresenterResponse> PresentCore(PagePresenterRequest request) { return Observable.Create<PresenterResponse>(o => { try { var view = locator.ResolveView(request.ViewModel); var disposable = view.WhenActivated(d => { o.OnNext(new PresenterResponse(view)); o.OnCompleted(); }); view.ViewModel = request.ViewModel; host.Content = view; return disposable; } catch (Exception ex) { o.OnError(ex); throw; } }); } public static IDisposable RegisterHost(ContentControl control) { var resolver = Locator.Current.GetService<IMutablePresenterResolver>(); return resolver.Register(new PagePresenter(control)); } } }
Make the UWP page presenter us a common content control
Make the UWP page presenter us a common content control
C#
mit
KallynGowdy/ReactiveUI.Routing
12253be382bfdaf4eccca281b47f49070bf5e082
LibGit2Sharp.Shared/SecureUsernamePasswordCredentials.cs
LibGit2Sharp.Shared/SecureUsernamePasswordCredentials.cs
using System; using System.Runtime.InteropServices; using System.Security; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. /// </summary> public sealed class SecureUsernamePasswordCredentials : Credentials { /// <summary> /// Callback to acquire a credential object. /// </summary> /// <param name="cred">The newly created credential object.</param> /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns> protected internal override int GitCredentialHandler(out IntPtr cred) { if (Username == null || Password == null) { throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); } IntPtr passwordPtr = IntPtr.Zero; try { passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); } finally { Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); } } /// <summary> /// Username for username/password authentication (as in HTTP basic auth). /// </summary> public string Username { get; set; } /// <summary> /// Password for username/password authentication (as in HTTP basic auth). /// </summary> public SecureString Password { get; set; } } }
using System; using System.Runtime.InteropServices; using System.Security; using LibGit2Sharp.Core; namespace LibGit2Sharp { /// <summary> /// Class that uses <see cref="SecureString"/> to hold username and password credentials for remote repository access. /// </summary> public sealed class SecureUsernamePasswordCredentials : Credentials { /// <summary> /// Callback to acquire a credential object. /// </summary> /// <param name="cred">The newly created credential object.</param> /// <returns>0 for success, &lt; 0 to indicate an error, &gt; 0 to indicate no credential was acquired.</returns> protected internal override int GitCredentialHandler(out IntPtr cred) { if (Username == null || Password == null) { throw new InvalidOperationException("UsernamePasswordCredentials contains a null Username or Password."); } IntPtr passwordPtr = IntPtr.Zero; try { #if NET40 passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(Password); #else passwordPtr = SecureStringMarshal.SecureStringToCoTaskMemUnicode(Password); #endif return NativeMethods.git_cred_userpass_plaintext_new(out cred, Username, Marshal.PtrToStringUni(passwordPtr)); } finally { #if NET40 Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr); #else SecureStringMarshal.ZeroFreeCoTaskMemUnicode(passwordPtr); #endif } } /// <summary> /// Username for username/password authentication (as in HTTP basic auth). /// </summary> public string Username { get; set; } /// <summary> /// Password for username/password authentication (as in HTTP basic auth). /// </summary> public SecureString Password { get; set; } } }
Fix compile error around exporting SecureString
Fix compile error around exporting SecureString
C#
mit
Zoxive/libgit2sharp,Zoxive/libgit2sharp,PKRoma/libgit2sharp,libgit2/libgit2sharp
d81639e0dbefaad73dd36aed4ab153ed45ac656d
src/nuclei.build/Properties/AssemblyInfo.cs
src/nuclei.build/Properties/AssemblyInfo.cs
//----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Nuclei.Build; [assembly: AssemblyCulture("")] // Resources [assembly: NeutralResourcesLanguage("en-US")] // 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: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Indicate that the assembly is CLS compliant. [assembly: CLSCompliant(true)] // The time the assembly was build [assembly: AssemblyBuildTime(buildTime: "1900-01-01T00:00:00.0000000+00:00")] // The version from which the assembly was build [module: SuppressMessage( "Microsoft.Usage", "CA2243:AttributeStringLiteralsShouldParseCorrectly", Justification = "It's a VCS revision, not a version")] [assembly: AssemblyBuildInformation(buildNumber: 0, versionControlInformation: "1234567890123456789012345678901234567890")]
//----------------------------------------------------------------------- // <copyright company="TheNucleus"> // Copyright (c) TheNucleus. All rights reserved. // Licensed under the Apache License, Version 2.0 license. See LICENCE.md file in the project root for full license information. // </copyright> //----------------------------------------------------------------------- using System; using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using Nuclei.Build; [assembly: AssemblyCulture("")] // Resources [assembly: NeutralResourcesLanguage("en-US")] // 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: AssemblyTrademark("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Indicate that the assembly is CLS compliant. [assembly: CLSCompliant(true)]
Remove the build attributes because they'll be generated with a full namespace
Remove the build attributes because they'll be generated with a full namespace references #7
C#
apache-2.0
thenucleus/nuclei.build
43c9d19b125bdeaf9d631a3aa55290c6658c9d95
plugin-common-cs/Constants.cs
plugin-common-cs/Constants.cs
using System; using System.Text.RegularExpressions; namespace Floobits.Common { public class Constants { static public string baseDir = FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "floobits"); static public string shareDir = FilenameUtils.concat(baseDir, "share"); static public string version = "0.11"; static public string pluginVersion = "0.01"; static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com"; static public int OUTBOUND_FILTER_PROXY_PORT = 443; static public string floobitsDomain = "floobits.com"; static public string defaultHost = "floobits.com"; static public int defaultPort = 3448; static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled); static public int TOO_MANY_BIG_DIRS = 50; } }
using System; using System.Text.RegularExpressions; namespace Floobits.Common { public class Constants { static public string baseDir = baseDirInit(); static public string shareDir = FilenameUtils.concat(baseDir, "share"); static public string version = "0.11"; static public string pluginVersion = "0.01"; static public string OUTBOUND_FILTER_PROXY_HOST = "proxy.floobits.com"; static public int OUTBOUND_FILTER_PROXY_PORT = 443; static public string floobitsDomain = "floobits.com"; static public string defaultHost = "floobits.com"; static public int defaultPort = 3448; static public Regex NEW_LINE = new Regex("\\r\\n?", RegexOptions.Compiled); static public int TOO_MANY_BIG_DIRS = 50; static public string baseDirInit() { return FilenameUtils.concat(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "floobits"); } } }
Use the same folder as the JAVA implementation
Use the same folder as the JAVA implementation
C#
apache-2.0
Floobits/floobits-vsp
46a9833e1ff7bed7d9c17c147ec5c5a32e94e6ce
BmpListener.ConsoleExample/Program.cs
BmpListener.ConsoleExample/Program.cs
using System; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace BmpListener.ConsoleExample { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new StringEnumConverter()); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }
using System; using BmpListener.Bmp; using BmpListener.JSON; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Serialization; namespace BmpListener.ConsoleExample { internal class Program { private static void Main() { JsonConvert.DefaultSettings = () => { var settings = new JsonSerializerSettings(); settings.Converters.Add(new IPAddressConverter()); settings.Converters.Add(new StringEnumConverter()); settings.ContractResolver = new CamelCasePropertyNamesContractResolver(); return settings; }; var bmpListener = new BmpListener(); bmpListener.Start(WriteJson).Wait(); } private static void WriteJson(BmpMessage msg) { var json = JsonConvert.SerializeObject(msg); Console.WriteLine(json); } } }
Change default JSON serialization to CamelCase
Change default JSON serialization to CamelCase
C#
mit
mstrother/BmpListener
a4fc7e91b171516806ce740a905ca1999be96c62
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenerator { class Program { static void Main(string[] args) { var gen = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]); for (int i = 0; i < 25; i++) { Console.WriteLine(gen.Generate()); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Reactive.Linq; using System.Text; using System.Threading.Tasks; namespace DataGenerator { class Program { static void Main(string[] args) { var data = new Fare.Xeger(ConfigurationSettings.AppSettings["pattern"]); var tick = TimeSpan.Parse(ConfigurationSettings.AppSettings["timespan"]); Observable .Timer(TimeSpan.Zero, tick) .Subscribe( t => { Console.WriteLine(data.Generate()); } ); Console.ReadLine(); } } }
Use Timer based Observable to generate data
Use Timer based Observable to generate data
C#
mit
WillemRB/DataGenerator
10058bed7e1b9277fd7cc89a943cde24d201c320
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
using System.Collections.Generic; using Promact.Trappist.DomainModel.Models.Question; using System.Linq; using Promact.Trappist.DomainModel.DbContext; namespace Promact.Trappist.Repository.Questions { public class QuestionRepository : IQuestionRespository { private readonly TrappistDbContext _dbContext; public QuestionRepository(TrappistDbContext dbContext) { _dbContext = dbContext; } /// <summary> /// Get all questions /// </summary> /// <returns>Question list</returns> public List<SingleMultipleAnswerQuestion> GetAllQuestions() { var question = _dbContext.SingleMultipleAnswerQuestion.ToList(); return question; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleAnswerQuestion"></param> /// <param name="singleMultipleAnswerQuestionOption"></param> public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption) { _dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion); foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption) { singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id; _dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement); } _dbContext.SaveChanges(); } } }
Update server side API for single multiple answer question
Update server side API for single multiple answer question
C#
mit
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
b5bedf07b507746e27db21f3411cc28dc81160e1
Mappy/Models/IMapViewSettingsModel.cs
Mappy/Models/IMapViewSettingsModel.cs
namespace Mappy.Models { using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using Mappy.Data; using Mappy.Database; public interface IMapViewSettingsModel { IObservable<bool> GridVisible { get; } IObservable<Color> GridColor { get; } IObservable<Size> GridSize { get; } IObservable<bool> HeightmapVisible { get; } IObservable<bool> FeaturesVisible { get; } IObservable<IFeatureDatabase> FeatureRecords { get; } IObservable<IMainModel> Map { get; } IObservable<int> ViewportWidth { get; set; } IObservable<int> ViewportHeight { get; set; } void SetViewportSize(Size size); void SetViewportLocation(Point pos); void OpenFromDragDrop(string filename); void DragDropData(IDataObject data, Point loc); } }
namespace Mappy.Models { using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using Mappy.Data; using Mappy.Database; public interface IMapViewSettingsModel { IObservable<bool> GridVisible { get; } IObservable<Color> GridColor { get; } IObservable<Size> GridSize { get; } IObservable<bool> HeightmapVisible { get; } IObservable<bool> FeaturesVisible { get; } IObservable<IFeatureDatabase> FeatureRecords { get; } IObservable<IMainModel> Map { get; } IObservable<int> ViewportWidth { get; } IObservable<int> ViewportHeight { get; } void SetViewportSize(Size size); void SetViewportLocation(Point pos); void OpenFromDragDrop(string filename); void DragDropData(IDataObject data, Point loc); } }
Remove setters from IObservable properties
Remove setters from IObservable properties
C#
mit
MHeasell/Mappy,MHeasell/Mappy
d87dca0262705b54e0ffeecf71b93b0843f7ecac
OpeningsMoeWpfClient/FfmpegMovieConverter.cs
OpeningsMoeWpfClient/FfmpegMovieConverter.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpeningsMoeWpfClient { class FfmpegMovieConverter : IMovieConverter { private string ffmpegPath; public Task<string> ConvertMovie(string sourcePath, string targetPath) { var tcs = new TaskCompletionSource<string>(); var process = new Process { StartInfo = { UseShellExecute = false, FileName = ffmpegPath, Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""", CreateNoWindow = true }, EnableRaisingEvents = true }; process.Exited += (sender, args) => { if(process.ExitCode == 0) tcs.SetResult(targetPath); else tcs.SetException(new InvalidOperationException("SOMETHING WENT WRONG")); process.Dispose(); }; process.Start(); process.PriorityClass = ProcessPriorityClass.BelowNormal; return tcs.Task; } public FfmpegMovieConverter(string ffmpegPath) { this.ffmpegPath = ffmpegPath; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OpeningsMoeWpfClient { class FfmpegMovieConverter : IMovieConverter { private string ffmpegPath; private Task<int> LaunchProcess(Func<Process> factory, Action<Process> postLaunchConfiguration) { var tcs = new TaskCompletionSource<int>(); var process = factory(); process.Exited += (sender, args) => { tcs.SetResult(process.ExitCode); process.Dispose(); }; process.Start(); postLaunchConfiguration(process); return tcs.Task; } public async Task<string> ConvertMovie(string sourcePath, string targetPath) { int exitCode = await LaunchProcess(() => new Process { StartInfo = { UseShellExecute = false, FileName = ffmpegPath, Arguments = $@"-i ""{sourcePath}"" -vcodec msmpeg4v2 -acodec libmp3lame -strict -2 ""{targetPath}""", CreateNoWindow = true }, EnableRaisingEvents = true }, process => { process.PriorityClass = ProcessPriorityClass.BelowNormal; }); if(exitCode == 0) return targetPath; throw new InvalidOperationException("SOMETHING WENT WRONG"); } public FfmpegMovieConverter(string ffmpegPath) { this.ffmpegPath = ffmpegPath; } } }
Split responsibility of ConvertMovie() method
Split responsibility of ConvertMovie() method
C#
mit
milleniumbug/OpeningsMoeDesktop
8f77f22794b96d768c76726cb9b15a801c658614
Templates/ParenthesizedExpressionTemplate.cs
Templates/ParenthesizedExpressionTemplate.cs
using System.Linq; using JetBrains.Annotations; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.PostfixTemplates.LookupItems; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace JetBrains.ReSharper.PostfixTemplates.Templates { // todo: (Bar) foo.par - available in auto? [PostfixTemplate( templateName: "par", description: "Parenthesizes current expression", example: "(expr)")] public class ParenthesizedExpressionTemplate : IPostfixTemplate { public ILookupItem CreateItem(PostfixTemplateContext context) { if (context.IsAutoCompletion) return null; PrefixExpressionContext bestContext = null; foreach (var expressionContext in context.Expressions.Reverse()) { if (CommonUtils.IsNiceExpression(expressionContext.Expression)) { bestContext = expressionContext; break; } } return new ParenthesesItem(bestContext ?? context.OuterExpression); } private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression> { public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { } protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { return factory.CreateExpression("($0)", expression); } } } }
using System.Linq; using JetBrains.Annotations; using JetBrains.ReSharper.Feature.Services.Lookup; using JetBrains.ReSharper.PostfixTemplates.LookupItems; using JetBrains.ReSharper.Psi.CSharp; using JetBrains.ReSharper.Psi.CSharp.Tree; namespace JetBrains.ReSharper.PostfixTemplates.Templates { [PostfixTemplate( templateName: "par", description: "Parenthesizes current expression", example: "(expr)")] public class ParenthesizedExpressionTemplate : IPostfixTemplate { public ILookupItem CreateItem(PostfixTemplateContext context) { PrefixExpressionContext bestContext = null; foreach (var expressionContext in context.Expressions.Reverse()) { if (CommonUtils.IsNiceExpression(expressionContext.Expression)) { bestContext = expressionContext; break; } } // available in auto over cast expressions var targetContext = bestContext ?? context.OuterExpression; var insideCastExpression = CastExpressionNavigator.GetByOp(targetContext.Expression) != null; if (!insideCastExpression && context.IsAutoCompletion) return null; return new ParenthesesItem(targetContext); } private sealed class ParenthesesItem : ExpressionPostfixLookupItem<ICSharpExpression> { public ParenthesesItem([NotNull] PrefixExpressionContext context) : base("par", context) { } protected override ICSharpExpression CreateExpression(CSharpElementFactory factory, ICSharpExpression expression) { return factory.CreateExpression("($0)", expression); } } } }
Allow .par in auto in case of '(T) expr.par'
Allow .par in auto in case of '(T) expr.par'
C#
mit
controlflow/resharper-postfix
e01daa9ba4a10cdcd34267fcec9bac8d92481b2b
src/Orchard.Web/Modules/LETS/Views/Fields/AgileUploader-Photos.cshtml
src/Orchard.Web/Modules/LETS/Views/Fields/AgileUploader-Photos.cshtml
@using So.ImageResizer.Helpers @{ Style.Include("slimbox2.css"); Script.Require("jQuery").AtFoot(); Script.Include("slimbox2.js").AtFoot(); } @if (!string.IsNullOrEmpty(Model.ContentField.FileNames)) { <div class="stripGallery"> @foreach (var fileName in Model.ContentField.FileNames.Split(';')) { <a href="@fileName" rel="lightbox-gallery"> @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; } <img width="100" height="80" src='@string.Format("/resizedImage?url={0}&width=100&height=80&maxWidth=100&maxheight=80&cropMode={1}&scale={2}&stretchMode={3}", fileName, ResizeSettingType.CropMode.Auto, ResizeSettingType.ScaleMode.DownscaleOnly, ResizeSettingType.StretchMode.Proportionally)' alt="@alternateText"/> </a> } </div> }
@{ Style.Include("slimbox2.css"); Script.Require("jQuery").AtFoot(); Script.Include("slimbox2.js").AtFoot(); } @if (!string.IsNullOrEmpty(Model.ContentField.FileNames)) { <div class="stripGallery"> @foreach (var fileName in Model.ContentField.FileNames.Split(';')) { <a href="@fileName" rel="lightbox-gallery"> @{ var alternateText = string.IsNullOrEmpty(Model.ContentField.AlternateText) ? Path.GetFileNameWithoutExtension(fileName) : Model.ContentField.AlternateText; } <img alt="@alternateText" src='@Display.ResizeMediaUrl(Width: 250, Path: fileName)' /> </a> } </div> }
Fix AgileUploader (remove SO image resizer)
Fix AgileUploader (remove SO image resizer)
C#
bsd-3-clause
planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS,planetClaire/Orchard-LETS
b26af61a4caa73af4473eaeed1aace5532db39fa
cmn-tools/suice/suice/SingletonProvider.cs
cmn-tools/suice/suice/SingletonProvider.cs
using System; namespace CmnTools.Suice { /// <summary> /// @author DisTurBinG /// </summary> public class SingletonProvider : AbstractProvider { internal object Instance; public SingletonProvider (Type providedType) : base(providedType) { } internal virtual void CreateSingletonInstance() { SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies)); } internal void SetInstance (object instance) { DependencyProxy dependencyProxy = Instance as DependencyProxy; if (dependencyProxy == null) { Instance = instance; } else { dependencyProxy.SetInstance(instance); } } protected override object ProvideObject() { return Instance ?? (Instance = new DependencyProxy (ProvidedType)); } } }
using System; namespace CmnTools.Suice { /// <summary> /// @author DisTurBinG /// </summary> public class SingletonProvider : AbstractProvider { internal object Instance; public SingletonProvider (Type providedType) : base(providedType) { } internal virtual void CreateSingletonInstance() { if (Instance == null) { SetInstance(Activator.CreateInstance(ProvidedType, ConstructorDependencies)); } } internal void SetInstance (object instance) { DependencyProxy dependencyProxy = Instance as DependencyProxy; if (dependencyProxy == null) { Instance = instance; } else { dependencyProxy.SetInstance(instance); } } protected override object ProvideObject() { return Instance ?? (Instance = new DependencyProxy (ProvidedType)); } } }
Fix for Binding singleton to instance.
Fix for Binding singleton to instance.
C#
mit
Disturbing/suice
8585b96efef0bd80e9d798c5443929154adf1ec9
src/Twilio.Mvc/TwiMLResult.cs
src/Twilio.Mvc/TwiMLResult.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Xml.Linq; namespace Twilio.TwiML.Mvc { public class TwiMLResult : ActionResult { XDocument data; public TwiMLResult() { } public TwiMLResult(string twiml) { data = XDocument.Parse(twiml); } public TwiMLResult(XDocument twiml) { data = twiml; } public TwiMLResult(TwilioResponse response) { data = response.ToXDocument(); } public override void ExecuteResult(ControllerContext controllerContext) { var context = controllerContext.RequestContext.HttpContext; context.Response.ContentType = "application/xml"; if (data == null) { data = new XDocument(new XElement("Response")); } data.Save(context.Response.Output); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Xml.Linq; namespace Twilio.TwiML.Mvc { public class TwiMLResult : ActionResult { XDocument data; public TwiMLResult() { } public TwiMLResult(string twiml) { data = XDocument.Parse(twiml); } public TwiMLResult(XDocument twiml) { data = twiml; } public TwiMLResult(TwilioResponse response) { if (response != null) data = response.ToXDocument(); } public override void ExecuteResult(ControllerContext controllerContext) { var context = controllerContext.RequestContext.HttpContext; context.Response.ContentType = "application/xml"; if (data == null) { data = new XDocument(new XElement("Response")); } data.Save(context.Response.Output); } } }
Fix NullReference when using T4MVC
Fix NullReference when using T4MVC T4MVC tries using the TwilioResponse constructor for the TwiMLResult object when generating the URL using URL.Action which causes a Runtime Exception. More details can be found at https://t4mvc.codeplex.com/workitem/22
C#
mit
IRlyDontKnow/twilio-csharp,mplacona/twilio-csharp,twilio/twilio-csharp
38e539c926fd4eb236602435af24d529c064d5cb
Inscribe/Text/TweetTextCounter.cs
Inscribe/Text/TweetTextCounter.cs
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 19 Chars. int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength; } totalCount += input.Length - prevIndex; return totalCount; } } }
using System.Linq; using System.Text.RegularExpressions; namespace Inscribe.Text { public static class TweetTextCounter { public static int Count(string input) { // URL is MAX 20 Chars (if URL has HTTPS scheme, URL is MAX 21 Chars) int prevIndex = 0; int totalCount = 0; foreach (var m in RegularExpressions.UrlRegex.Matches(input).OfType<Match>()) { totalCount += m.Index - prevIndex; prevIndex = m.Index + m.Groups[0].Value.Length; bool isHasHttpsScheme = m.Groups[0].Value.Contains("https"); if (m.Groups[0].Value.Length < TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0)) totalCount += m.Groups[0].Value.Length; else totalCount += TwitterDefine.UrlMaxLength + ((isHasHttpsScheme) ? 1 : 0); } totalCount += input.Length - prevIndex; return totalCount; } } }
Fix a bug of wrong counting characters with HTTPS URL
Fix a bug of wrong counting characters with HTTPS URL refs karno/Mystique#38
C#
mit
fin-alice/Mystique,azyobuzin/Mystique
e2c0681287b096e25e0e428c3bf39ca7613230b4
RtdArrayTest/TestFunctions.cs
RtdArrayTest/TestFunctions.cs
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ExcelDna.Integration; namespace RtdArrayTest { public static class TestFunctions { public static object RtdArrayTest(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using ExcelDna.Integration; namespace RtdArrayTest { public static class TestFunctions { public static object RtdArrayTest(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } // NOTE: This is that problem case discussed in https://groups.google.com/d/topic/exceldna/62cgmRMVtfQ/discussion // It seems that the DisconnectData will not be called on updates triggered by parameters from the sheet // for RTD functions that are marked IsMacroType=true. [ExcelFunction(IsMacroType=true)] public static object RtdArrayTestMT(string prefix) { object rtdValue = XlCall.RTD("RtdArrayTest.TestRtdServer", null, "X" + prefix); var resultString = rtdValue as string; if (resultString == null) return rtdValue; // We have a string value, parse and return as an 2x1 array var parts = resultString.Split(';'); Debug.Assert(parts.Length == 2); var result = new object[2, 1]; result[0, 0] = parts[0]; result[1, 0] = parts[1]; return result; } } }
Add problem function (with IsMacroType=true)
Add problem function (with IsMacroType=true)
C#
mit
Excel-DNA/Samples
02ea0fa5667c4b84e8a32da72bae0507ce953745
Assets/Tests/Narrative/PortraitFlipTest.cs
Assets/Tests/Narrative/PortraitFlipTest.cs
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; public class PortraitFlipTest : MonoBehaviour { void Update () { Transform t = gameObject.transform.FindChild("Canvas/JohnCharacter"); if (t == null) { return; } if (t.transform.localScale.x != -1f) { IntegrationTest.Fail("Character object not flipped horizontally"); } } }
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; using System.Collections; public class PortraitFlipTest : MonoBehaviour { void Update () { Transform t = gameObject.transform.Find("Canvas/JohnCharacter"); if (t == null) { return; } if (t.transform.localScale.x != -1f) { IntegrationTest.Fail("Character object not flipped horizontally"); } } }
Use transform.Find instead of deprecated transform.FindChild
Use transform.Find instead of deprecated transform.FindChild
C#
mit
lealeelu/Fungus,snozbot/fungus,inarizushi/Fungus,FungusGames/Fungus
53ed864513ca058343d7d49a7b5ed200c5a2240a
Testing/Editor/InitialInstanceTests.cs
Testing/Editor/InitialInstanceTests.cs
using NUnit.Framework; namespace FullSerializer.Tests.InitialInstance { public class SimpleModel { public int A; } public class InitialInstanceTests { [Test] public void TestInitialInstance() { SimpleModel model1 = new SimpleModel { A = 3 }; fsData data; var serializer = new fsSerializer(); Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded); model1.A = 1; SimpleModel model2 = model1; Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded); Assert.AreEqual(model1.A, 3); Assert.AreEqual(model2.A, 3); Assert.IsTrue(ReferenceEquals(model1, model2)); } } }
using NUnit.Framework; namespace FullSerializer.Tests.InitialInstance { public class SimpleModel { public int A; } public class InitialInstanceTests { [Test] public void TestPopulateObject() { // This test verifies that when we pass in an existing object // instance that same instance is used to deserialize into, ie, // we can do the equivalent of Json.NET's PopulateObject SimpleModel model1 = new SimpleModel { A = 3 }; fsData data; var serializer = new fsSerializer(); Assert.IsTrue(serializer.TrySerialize(model1, out data).Succeeded); model1.A = 1; SimpleModel model2 = model1; Assert.AreEqual(1, model1.A); Assert.AreEqual(1, model2.A); Assert.IsTrue(serializer.TryDeserialize(data, ref model2).Succeeded); Assert.AreEqual(3, model1.A); Assert.AreEqual(3, model2.A); Assert.IsTrue(ReferenceEquals(model1, model2)); } } }
Add test description and fix param order in Assert call
Add test description and fix param order in Assert call
C#
mit
jacobdufault/fullserializer,zodsoft/fullserializer,nuverian/fullserializer,Ksubaka/fullserializer,lazlo-bonin/fullserializer,caiguihou/myprj_02,jacobdufault/fullserializer,karlgluck/fullserializer,shadowmint/fullserializer,jagt/fullserializer,shadowmint/fullserializer,jacobdufault/fullserializer,darress/fullserializer,jagt/fullserializer,Ksubaka/fullserializer,Ksubaka/fullserializer,shadowmint/fullserializer,jagt/fullserializer
4e1b2c87d7c0975406bf0692ebbbcb9200feb2f2
Zermelo.API/Properties/AssemblyInfo.cs
Zermelo.API/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("Zermelo.API")] [assembly: AssemblyDescription("Connect to Zermelo from your .NET app")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")] [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("2.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")]
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("Zermelo.API")] [assembly: AssemblyDescription("Connect to Zermelo from your .NET app")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Zermelo.API")] [assembly: AssemblyCopyright("Copyright 2016 Arthur Rump")] [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("2.0.*")] [assembly: AssemblyFileVersion("1.0.0.0")] // Make internal classes and functions available for testing [assembly: InternalsVisibleTo("Zermelo.API.Tests")]
Change assembly version from 2.0.0.0 to 2.0.*
Change assembly version from 2.0.0.0 to 2.0.*
C#
mit
arthurrump/Zermelo.API
9fe0ccf79deb3a78318ad8814ea6344b01020703
src/Analyser/KeywordExtractor.cs
src/Analyser/KeywordExtractor.cs
using System.Collections.Generic; using System.IO; namespace JiebaNet.Analyser { public abstract class KeywordExtractor { protected static readonly List<string> DefaultStopWords = new List<string>() { "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are", "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it", "this", "then", "at", "have", "all", "not", "one", "has", "or", "that" }; protected virtual ISet<string> StopWords { get; set; } public void SetStopWords(string stopWordsFile) { var path = Path.GetFullPath(stopWordsFile); if (File.Exists(path)) { var lines = File.ReadAllLines(path); StopWords = new HashSet<string>(); foreach (var line in lines) { StopWords.Add(line.Trim()); } } } public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null); public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null); } }
using System.Collections.Generic; using System.IO; namespace JiebaNet.Analyser { public abstract class KeywordExtractor { protected static readonly List<string> DefaultStopWords = new List<string>() { "the", "of", "is", "and", "to", "in", "that", "we", "for", "an", "are", "by", "be", "as", "on", "with", "can", "if", "from", "which", "you", "it", "this", "then", "at", "have", "all", "not", "one", "has", "or", "that" }; protected virtual ISet<string> StopWords { get; set; } public void SetStopWords(string stopWordsFile) { StopWords = new HashSet<string>(); var path = Path.GetFullPath(stopWordsFile); if (File.Exists(path)) { var lines = File.ReadAllLines(path); foreach (var line in lines) { StopWords.Add(line.Trim()); } } } public abstract IEnumerable<string> ExtractTags(string text, int count = 20, IEnumerable<string> allowPos = null); public abstract IEnumerable<WordWeightPair> ExtractTagsWithWeight(string text, int count = 20, IEnumerable<string> allowPos = null); } }
Use empty stopwords set when the default stopwords file is missing.
Use empty stopwords set when the default stopwords file is missing.
C#
mit
anderscui/jieba.NET
8e21f1cd345f0ffbcfcd5e7c22f30beb0f2f452a
SolutionInfo.cs
SolutionInfo.cs
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion(SolutionInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SolutionInfo.Version)] [assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Octokit")] [assembly: AssemblyCopyright("Copyright GitHub 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Octokit.Tests")] [assembly: InternalsVisibleTo("OctokitRT.Tests")] [assembly: CLSCompliant(false)] class SolutionInfo { public const string Version = "0.1.0"; }
using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion(SolutionInfo.Version + ".0")] [assembly: AssemblyInformationalVersion(SolutionInfo.Version)] [assembly: AssemblyFileVersion(SolutionInfo.Version + ".0")] [assembly: ComVisible(false)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("GitHub")] [assembly: AssemblyProduct("Octokit")] [assembly: AssemblyCopyright("Copyright GitHub 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: InternalsVisibleTo("Octokit.Tests")] [assembly: InternalsVisibleTo("Octokit.Tests-NetCore45")] [assembly: CLSCompliant(false)] class SolutionInfo { public const string Version = "0.1.0"; }
Fix up InternalsVisibleTo to new name
Fix up InternalsVisibleTo to new name
C#
mit
octokit/octokit.net,cH40z-Lord/octokit.net,Sarmad93/octokit.net,SLdragon1989/octokit.net,thedillonb/octokit.net,editor-tools/octokit.net,octokit-net-test-org/octokit.net,kdolan/octokit.net,shiftkey/octokit.net,rlugojr/octokit.net,TattsGroup/octokit.net,shiftkey-tester/octokit.net,thedillonb/octokit.net,M-Zuber/octokit.net,khellang/octokit.net,daukantas/octokit.net,dampir/octokit.net,shana/octokit.net,adamralph/octokit.net,shiftkey-tester/octokit.net,Red-Folder/octokit.net,octokit-net-test-org/octokit.net,alfhenrik/octokit.net,fffej/octokit.net,dampir/octokit.net,nsrnnnnn/octokit.net,michaKFromParis/octokit.net,dlsteuer/octokit.net,SamTheDev/octokit.net,magoswiat/octokit.net,kolbasov/octokit.net,editor-tools/octokit.net,SmithAndr/octokit.net,SamTheDev/octokit.net,brramos/octokit.net,khellang/octokit.net,gdziadkiewicz/octokit.net,yonglehou/octokit.net,M-Zuber/octokit.net,hitesh97/octokit.net,mminns/octokit.net,chunkychode/octokit.net,naveensrinivasan/octokit.net,Sarmad93/octokit.net,TattsGroup/octokit.net,ivandrofly/octokit.net,nsnnnnrn/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,ivandrofly/octokit.net,gabrielweyer/octokit.net,eriawan/octokit.net,darrelmiller/octokit.net,bslliw/octokit.net,geek0r/octokit.net,octokit/octokit.net,mminns/octokit.net,yonglehou/octokit.net,octokit-net-test/octokit.net,shiftkey/octokit.net,fake-organization/octokit.net,hahmed/octokit.net,gdziadkiewicz/octokit.net,devkhan/octokit.net,devkhan/octokit.net,gabrielweyer/octokit.net,takumikub/octokit.net,rlugojr/octokit.net,forki/octokit.net,alfhenrik/octokit.net,shana/octokit.net,hahmed/octokit.net,shiftkey-tester-org-blah-blah/octokit.net,chunkychode/octokit.net,eriawan/octokit.net,ChrisMissal/octokit.net,SmithAndr/octokit.net
76a98fe28bcf3db056401040b962b666f64de96f
EndlessClient/UIControls/PictureBox.cs
EndlessClient/UIControls/PictureBox.cs
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EOLib; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XNAControls; namespace EndlessClient.UIControls { public class PictureBox : XNAControl { protected Texture2D _displayPicture; public Optional<Rectangle> SourceRectangle { get; set; } public PictureBox(Texture2D displayPicture, XNAControl parent = null) : base(null, null, parent) { SetNewPicture(displayPicture); if (parent == null) Game.Components.Add(this); SourceRectangle = new Optional<Rectangle>(); } public void SetNewPicture(Texture2D displayPicture) { _displayPicture = displayPicture; _setSize(displayPicture.Width, displayPicture.Height); } public override void Draw(GameTime gameTime) { SpriteBatch.Begin(); SpriteBatch.Draw( _displayPicture, DrawAreaWithOffset, SourceRectangle.HasValue ? SourceRectangle : null, Color.White); SpriteBatch.End(); base.Draw(gameTime); } } }
// Original Work Copyright (c) Ethan Moffat 2014-2016 // This file is subject to the GPL v2 License // For additional details, see the LICENSE file using EOLib; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using XNAControls; namespace EndlessClient.UIControls { public class PictureBox : XNAControl { protected Texture2D _displayPicture; public Optional<Rectangle?> SourceRectangle { get; set; } public PictureBox(Texture2D displayPicture, XNAControl parent = null) : base(null, null, parent) { SetNewPicture(displayPicture); if (parent == null) Game.Components.Add(this); SourceRectangle = new Optional<Rectangle?>(); } public void SetNewPicture(Texture2D displayPicture) { _displayPicture = displayPicture; _setSize(displayPicture.Width, displayPicture.Height); } public override void Draw(GameTime gameTime) { SpriteBatch.Begin(); SpriteBatch.Draw( _displayPicture, DrawAreaWithOffset, SourceRectangle.HasValue ? SourceRectangle.Value : null, Color.White); SpriteBatch.End(); base.Draw(gameTime); } } }
Make SourceRectangle nullable so it doesn't crash.
Make SourceRectangle nullable so it doesn't crash.
C#
mit
ethanmoffat/EndlessClient
461ccf361322156e9587d88422bf2a64120a46a6
Phoebe/Data/ForeignKeyJsonConverter.cs
Phoebe/Data/ForeignKeyJsonConverter.cs
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
using System; using Newtonsoft.Json; namespace Toggl.Phoebe.Data { public class ForeignKeyJsonConverter : JsonConverter { public override void WriteJson (JsonWriter writer, object value, JsonSerializer serializer) { var model = (Model)value; if (model == null) { writer.WriteNull (); return; } writer.WriteValue (model.RemoteId); } public override object ReadJson (JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType == JsonToken.Null) { return null; } var remoteId = Convert.ToInt64 (reader.Value); lock (Model.SyncRoot) { var model = Model.Manager.GetByRemoteId (objectType, remoteId); if (model == null) { model = (Model)Activator.CreateInstance (objectType); model.RemoteId = remoteId; model.ModifiedAt = new DateTime (); model = Model.Update (model); } return model; } } public override bool CanConvert (Type objectType) { return objectType.IsSubclassOf (typeof(Model)); } } }
Make foreign key converter thread-safe.
Make foreign key converter thread-safe.
C#
bsd-3-clause
ZhangLeiCharles/mobile,eatskolnikov/mobile,eatskolnikov/mobile,masterrr/mobile,peeedge/mobile,ZhangLeiCharles/mobile,masterrr/mobile,peeedge/mobile,eatskolnikov/mobile
7059310993543eadf31a94b6178d9790fa466de0
OutlookMatters.Core/Mattermost/v4/RestService.cs
OutlookMatters.Core/Mattermost/v4/RestService.cs
using System; using System.Collections.Generic; using Newtonsoft.Json; using OutlookMatters.Core.Http; using OutlookMatters.Core.Mattermost.v4.Interface; namespace OutlookMatters.Core.Mattermost.v4 { public class RestService : IRestService { private readonly IHttpClient _httpClient; public RestService(IHttpClient httpClient) { _httpClient = httpClient; } public void Login(Uri baseUri, Login login, out string token) { var loginUrl = new Uri(baseUri, "api/v4/users/login"); using (var response = _httpClient.Request(loginUrl) .WithContentType("text/json") .Post(JsonConvert.SerializeObject(login))) { token = response.GetHeaderValue("Token"); } } public IEnumerable<Team> GetTeams(Uri baseUri, string token) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using OutlookMatters.Core.Http; using OutlookMatters.Core.Mattermost.v4.Interface; namespace OutlookMatters.Core.Mattermost.v4 { public class RestService : IRestService { private readonly IHttpClient _httpClient; public RestService(IHttpClient httpClient) { _httpClient = httpClient; } public void Login(Uri baseUri, Login login, out string token) { var loginUrl = new Uri(baseUri, "api/v4/users/login"); using (var response = _httpClient.Request(loginUrl) .WithContentType("application/json") .Post(JsonConvert.SerializeObject(login))) { token = response.GetHeaderValue("Token"); } } public IEnumerable<Team> GetTeams(Uri baseUri, string token) { var teamsUrl = new Uri(baseUri, "api/v4/teams"); using (var response = _httpClient.Request(teamsUrl) .WithHeader("Authorization", "Bearer " + token) .Get()) { var payload = response.GetPayload(); return JsonConvert.DeserializeObject<IEnumerable<Team>>(payload); } } } }
Implement rest call to get teams.
Implement rest call to get teams.
C#
mit
makmu/outlook-matters,makmu/outlook-matters
2959a622fbca88acb7c2df638c43bea4ecf372ad
Demo/Program.cs
Demo/Program.cs
using System; using System.Collections.Generic; using Demo.Endpoints; using Distributor; namespace Demo { internal class Program { private static void Main(string[] args) { var distributables = new List<DistributableFile> { new DistributableFile { Id = Guid.NewGuid(), ProfileName = "TestProfile", Name = "test.pdf", Contents = null } }; //Configure the distributor var distributor = new Distributor<DistributableFile>(); distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService()); distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService()); //Run the Distributor distributor.Distribute(distributables); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using Demo.Endpoints.FileSystem; using Demo.Endpoints.Sharepoint; using Distributor; namespace Demo { internal class Program { private static void Main(string[] args) { var distributables = new List<DistributableFile> { new DistributableFile { Id = Guid.NewGuid(), ProfileName = "TestProfile", Name = "test.pdf", Contents = null } }; //Configure the distributor var distributor = new Distributor<DistributableFile>(); distributor.EndpointDeliveryServices.Add(new SharepointDeliveryService()); distributor.EndpointDeliveryServices.Add(new FileSystemDeliveryService()); //Run the Distributor distributor.Distribute(distributables); Console.ReadLine(); } } }
Fix import error in demo.
Fix import error in demo.
C#
mit
justinjstark/Verdeler,justinjstark/Delivered
3284266192461ae5a55c1079ae131f302fb26535
Assets/Scripts/UserInput.cs
Assets/Scripts/UserInput.cs
using UnityEngine; using UnityEngine.EventSystems; using System.Collections; public class UserInput : MonoBehaviour, IPointerClickHandler { // void Start(){} // void Update(){} // Mutually exclusive for now, priority is in the following order: // Left click for human, // Right for zombie, // Middle for corpse public void OnPointerClick(PointerEventData e) { if(e.button == PointerEventData.InputButton.Left) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Right) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Middle) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position)); } } }
using UnityEngine; using UnityEngine.EventSystems; using System.Collections; public class UserInput : MonoBehaviour, IPointerClickHandler { // void Start(){} // void Update(){} // Mutually exclusive for now, priority is in the following order: // Left click for human, // Right for zombie, // Middle for corpse public void OnPointerClick(PointerEventData e) { if(e.button == PointerEventData.InputButton.Left) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.ZOMBIE, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Right) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.HUMAN, Camera.main.ScreenToWorldPoint(e.position)); } else if(e.button == PointerEventData.InputButton.Middle) { FindObjectOfType<AgentDirector>().spawnAgent(Agent.AgentType.CORPSE, Camera.main.ScreenToWorldPoint(e.position)); } } }
Swap human/zombie spawn input so you can spawn zombies on touch screens
Swap human/zombie spawn input so you can spawn zombies on touch screens
C#
mit
futurechris/zombai
ed6c3e80233af477dedfd65f7a167f4252133a7d
Mappy/UI/Drawables/DrawableBandbox.cs
Mappy/UI/Drawables/DrawableBandbox.cs
namespace Mappy.UI.Drawables { using System; using System.Drawing; public class DrawableBandbox : IDrawable, IDisposable { private readonly Brush fillBrush; private readonly Pen borderPen; public DrawableBandbox(Brush fillBrush, Pen borderPen, Size size) { this.fillBrush = fillBrush; this.borderPen = borderPen; this.Size = size; } public Size Size { get; private set; } public int Width { get { return this.Size.Width; } } public int Height { get { return this.Size.Height; } } public static DrawableBandbox CreateSimple( Size size, Color color, Color borderColor, int borderWidth = 1) { return new DrawableBandbox( new SolidBrush(color), new Pen(borderColor, borderWidth), size); } public void Draw(Graphics graphics, Rectangle clipRectangle) { graphics.FillRectangle(this.fillBrush, 0, 0, this.Width - 1, this.Height - 1); graphics.DrawRectangle(this.borderPen, 0, 0, this.Width - 1, this.Height - 1); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.fillBrush.Dispose(); this.borderPen.Dispose(); } } } }
namespace Mappy.UI.Drawables { using System; using System.Drawing; public class DrawableBandbox : IDrawable, IDisposable { private readonly Brush fillBrush; private readonly Pen borderPen; public DrawableBandbox(Brush fillBrush, Pen borderPen, Size size) { this.fillBrush = fillBrush; this.borderPen = borderPen; this.Size = size; } public Size Size { get; private set; } public int Width { get { return this.Size.Width; } } public int Height { get { return this.Size.Height; } } public static DrawableBandbox CreateSimple(Size size, Color color, Color borderColor) { return CreateSimple(size, color, borderColor, 1); } public static DrawableBandbox CreateSimple( Size size, Color color, Color borderColor, int borderWidth) { return new DrawableBandbox( new SolidBrush(color), new Pen(borderColor, borderWidth), size); } public void Draw(Graphics graphics, Rectangle clipRectangle) { graphics.FillRectangle(this.fillBrush, 0, 0, this.Width - 1, this.Height - 1); graphics.DrawRectangle(this.borderPen, 0, 0, this.Width - 1, this.Height - 1); } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { this.fillBrush.Dispose(); this.borderPen.Dispose(); } } } }
Replace default parameter with overload
Replace default parameter with overload
C#
mit
MHeasell/Mappy,MHeasell/Mappy
5c3b92bcae05111479950478d1173ae92c37d749
MonJobs/Properties/AssemblyInfo.cs
MonJobs/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonJobs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonJobs")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")] // 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.8.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("MonJobs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MonJobs")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("763b7fef-ff24-407d-8dce-5313e6129941")] // 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.9.0.0")]
Increase version to 1.9 to reflect the new AdhocQuery capability change.
Increase version to 1.9 to reflect the new AdhocQuery capability change.
C#
mit
G3N7/MonJobs
08e5a6c5f8db6ff7c66ccdd9eea0b37c32419620
McIP/Program.cs
McIP/Program.cs
namespace McIP { using System; using System.Diagnostics; using System.IO; public static class Program { public static void Main() { var si = new ProcessStartInfo("ipconfig", "/all") { RedirectStandardOutput = true, UseShellExecute = false }; var p = Process.Start(si); StreamReader reader = p.StandardOutput; string heading = string.Empty; string line; while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrEmpty(line) && !line.StartsWith(" ", StringComparison.Ordinal)) { heading = line; } if (line.Contains("IP Address")) { Console.WriteLine(heading); Console.WriteLine(line); Console.WriteLine(); } } } } }
namespace McIP { using System; using System.Diagnostics; using System.IO; public static class Program { public static void Main() { var si = new ProcessStartInfo("ipconfig", "/all") { RedirectStandardOutput = true, UseShellExecute = false }; var p = Process.Start(si); StreamReader reader = p.StandardOutput; string heading = string.Empty; bool headingPrinted = false; string line; while ((line = reader.ReadLine()) != null) { if (!string.IsNullOrEmpty(line) && !line.StartsWith(" ", StringComparison.Ordinal)) { heading = line; headingPrinted = false; } if (line.ContainsAny("IP Address", "IPv4 Address", "IPv6 Address")) { if (!headingPrinted) { Console.WriteLine(); Console.WriteLine(heading); headingPrinted = true; } Console.WriteLine(line); } } } private static bool ContainsAny(this string target, params string[] values) { if (values == null) { throw new ArgumentNullException("values"); } foreach (var value in values) { if (target.Contains(value)) { return true; } } return false; } } }
Handle IPv4 Address and IPv6 Address
Handle IPv4 Address and IPv6 Address
C#
mit
PatrickMcDonald/McIP
e351af781dec7e9d1ed768ea35bef744f5f1d273
Trappist/src/Promact.Trappist.Core/Controllers/QuestionController.cs
Trappist/src/Promact.Trappist.Core/Controllers/QuestionController.cs
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.ApplicationClasses; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleQuestion"></param> /// <returns></returns> [Route("singlemultiplequestion")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion([FromBody]SingleMultipleQuestion singleMultipleQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleQuestion.singleMultipleAnswerQuestion,singleMultipleQuestion.singleMultipleAnswerQuestionOption); return Ok(singleMultipleQuestion); } } }
using Microsoft.AspNetCore.Mvc; using Promact.Trappist.DomainModel.ApplicationClasses; using Promact.Trappist.Repository.Questions; using System; namespace Promact.Trappist.Core.Controllers { [Route("api")] public class QuestionController : Controller { private readonly IQuestionRepository _questionsRepository; public QuestionsController(IQuestionRepository questionsRepository) { _questionsRepository = questionsRepository; } /// <summary> /// Add single multiple answer question into model /// </summary> /// <param name="singleMultipleQuestion"></param> /// <returns></returns> [Route("singlemultiplequestion")] [HttpPost] public IActionResult AddSingleMultipleAnswerQuestion([FromBody]SingleMultipleQuestion singleMultipleQuestion) { _questionsRepository.AddSingleMultipleAnswerQuestion(singleMultipleQuestion.singleMultipleAnswerQuestion,singleMultipleQuestion.singleMultipleAnswerQuestionOption); return Ok(singleMultipleQuestion); } } }
Create server side API for single multiple answer question
Create server side API for single multiple answer question
C#
mit
Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist
659e0bb2007c14d9493468c8bb2631895b7d86c7
source/Nuke.Common/CI/TeamCity/Configuration/TeamCityScheduledTrigger.cs
source/Nuke.Common/CI/TeamCity/Configuration/TeamCityScheduledTrigger.cs
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityScheduledTrigger : TeamCityTrigger { public string BranchFilter { get; set; } public string TriggerRules { get; set; } public bool TriggerBuildAlways { get; set; } //TODO: check public bool WithPendingChangesOnly { get; set; } public bool EnableQueueOptimization { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock("schedule")) { using (writer.WriteBlock("schedulingPolicy = daily")) { writer.WriteLine("hour = 3"); writer.WriteLine("timezone = \"Europe/Berlin\""); } writer.WriteLine($"branchFilter = {BranchFilter.DoubleQuote()}"); writer.WriteLine($"triggerRules = {TriggerRules.DoubleQuote()}"); writer.WriteLine("triggerBuild = always()"); writer.WriteLine("withPendingChangesOnly = false"); writer.WriteLine($"enableQueueOptimization = {EnableQueueOptimization.ToString().ToLowerInvariant()}"); writer.WriteLine("param(\"cronExpression_min\", \"3\")"); } } } }
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Linq; using Nuke.Common.Utilities; namespace Nuke.Common.CI.TeamCity.Configuration { public class TeamCityScheduledTrigger : TeamCityTrigger { public string BranchFilter { get; set; } public string TriggerRules { get; set; } public bool TriggerBuildAlways { get; set; } //TODO: check public bool WithPendingChangesOnly { get; set; } public bool EnableQueueOptimization { get; set; } public override void Write(CustomFileWriter writer) { using (writer.WriteBlock("schedule")) { using (writer.WriteBlock("schedulingPolicy = daily")) { writer.WriteLine("hour = 3"); } writer.WriteLine($"branchFilter = {BranchFilter.DoubleQuote()}"); writer.WriteLine($"triggerRules = {TriggerRules.DoubleQuote()}"); writer.WriteLine("triggerBuild = always()"); writer.WriteLine("withPendingChangesOnly = false"); writer.WriteLine($"enableQueueOptimization = {EnableQueueOptimization.ToString().ToLowerInvariant()}"); writer.WriteLine("param(\"cronExpression_min\", \"3\")"); } } } }
Remove timezone specification for scheduled triggers to use server timezone
Remove timezone specification for scheduled triggers to use server timezone
C#
mit
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
e4f78544f7414b6656229ac4de236e3035cb72ae
TAUtil/Gaf/Structures/GafFrameData.cs
TAUtil/Gaf/Structures/GafFrameData.cs
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public char Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadChar(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
namespace TAUtil.Gaf.Structures { using System.IO; public struct GafFrameData { public ushort Width; public ushort Height; public ushort XPos; public ushort YPos; public byte Unknown1; public bool Compressed; public ushort FramePointers; public uint Unknown2; public uint PtrFrameData; public uint Unknown3; public static void Read(Stream f, ref GafFrameData e) { BinaryReader b = new BinaryReader(f); e.Width = b.ReadUInt16(); e.Height = b.ReadUInt16(); e.XPos = b.ReadUInt16(); e.YPos = b.ReadUInt16(); e.Unknown1 = b.ReadByte(); e.Compressed = b.ReadBoolean(); e.FramePointers = b.ReadUInt16(); e.Unknown2 = b.ReadUInt32(); e.PtrFrameData = b.ReadUInt32(); e.Unknown3 = b.ReadUInt32(); } } }
Change char to byte in gaf frame header
Change char to byte in gaf frame header
C#
mit
MHeasell/TAUtil,MHeasell/TAUtil
6cc98764d3dbbd69dc10dc9485890ade24463de8
Palaso/Extensions/StringExtensions.cs
Palaso/Extensions/StringExtensions.cs
using System.Collections.Generic; namespace Palaso.Extensions { public static class StringExtensions { public static List<string> SplitTrimmed(this string s, char seperator) { var x = s.Split(seperator); var r = new List<string>(); foreach (var part in x) { r.Add(part.Trim()); } return r; } } }
using System.Collections.Generic; namespace Palaso.Extensions { public static class StringExtensions { public static List<string> SplitTrimmed(this string s, char seperator) { if(s.Trim() == string.Empty) return new List<string>(); var x = s.Split(seperator); var r = new List<string>(); foreach (var part in x) { r.Add(part.Trim()); } return r; } } }
Make SplitTrimmed give empty list when given white-space-only string
Make SplitTrimmed give empty list when given white-space-only string
C#
mit
mccarthyrb/libpalaso,hatton/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,ermshiperete/libpalaso,andrew-polk/libpalaso,ddaspit/libpalaso,glasseyes/libpalaso,glasseyes/libpalaso,tombogle/libpalaso,tombogle/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,chrisvire/libpalaso,ermshiperete/libpalaso,darcywong00/libpalaso,marksvc/libpalaso,marksvc/libpalaso,darcywong00/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,sillsdev/libpalaso,darcywong00/libpalaso,gtryus/libpalaso,glasseyes/libpalaso,mccarthyrb/libpalaso,ermshiperete/libpalaso,hatton/libpalaso,chrisvire/libpalaso,ddaspit/libpalaso,hatton/libpalaso,ddaspit/libpalaso,JohnThomson/libpalaso,glasseyes/libpalaso,gmartin7/libpalaso,gmartin7/libpalaso,mccarthyrb/libpalaso,JohnThomson/libpalaso,andrew-polk/libpalaso,tombogle/libpalaso,JohnThomson/libpalaso,ddaspit/libpalaso,chrisvire/libpalaso,gmartin7/libpalaso,gtryus/libpalaso,mccarthyrb/libpalaso,hatton/libpalaso,sillsdev/libpalaso,sillsdev/libpalaso,andrew-polk/libpalaso,marksvc/libpalaso,tombogle/libpalaso,gtryus/libpalaso,sillsdev/libpalaso
1885cefbd0ebb06d65ed0eb2b0bea014dae8295c
Snittlistan.Test/SerializationTest.cs
Snittlistan.Test/SerializationTest.cs
namespace Snittlistan.Test { using System.IO; using System.Text; using Models; using Raven.Imports.Newtonsoft.Json; using Xunit; public class SerializationTest : DbTest { [Fact] public void CanSerialize8x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create8x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match8x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.AwayTeam); } [Fact] public void CanSerialize4x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create4x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match4x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.HomeTeam); } } }
namespace Snittlistan.Test { using System.IO; using System.Text; using Models; using Raven.Imports.Newtonsoft.Json; using Xunit; public class SerializationTest : DbTest { [Fact] public void CanSerialize8x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create8x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match8x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.AwayTeam); } [Fact] public void CanSerialize4x4Match() { // Arrange var serializer = Store.Conventions.CreateSerializer(); var builder = new StringBuilder(); // Act serializer.Serialize(new StringWriter(builder), DbSeed.Create4x4Match()); string text = builder.ToString(); var match = serializer.Deserialize<Match4x4>(new JsonTextReader(new StringReader(text))); // Assert TestData.VerifyTeam(match.HomeTeam); } [Fact] public void CanSerializeUser() { // Arrange var user = new User("firstName", "lastName", "e@d.com", "some-pass"); // Act using (var session = Store.OpenSession()) { session.Store(user); session.SaveChanges(); } // Assert using (var session = Store.OpenSession()) { var loadedUser = session.Load<User>(user.Id); Assert.True(loadedUser.ValidatePassword("some-pass"), "Password validation failed"); } } } }
Make sure password validation works after saving
Make sure password validation works after saving
C#
mit
dlidstrom/Snittlistan,dlidstrom/Snittlistan,dlidstrom/Snittlistan
1f37516455774ebbccae9db8f65a1091b04b690a
NuPack.Dialog/PackageManagerUI/Converters/StringCollectionsToStringConverter.cs
NuPack.Dialog/PackageManagerUI/Converters/StringCollectionsToStringConverter.cs
using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Windows.Data; namespace NuPack.Dialog.PackageManagerUI { public class StringCollectionsToStringConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (targetType == typeof(string)) { string stringValue = value as string; if (stringValue != null) { return stringValue; } else { IEnumerable<string> parts = (IEnumerable<string>)value; return String.Join(", ", parts); } } return value; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }
Fix bug in the StringCollection converter when DataServicePackage.Authors is a simple string.
Fix bug in the StringCollection converter when DataServicePackage.Authors is a simple string.
C#
apache-2.0
pratikkagda/nuget,oliver-feng/nuget,antiufo/NuGet2,ctaggart/nuget,rikoe/nuget,mrward/NuGet.V2,GearedToWar/NuGet2,mono/nuget,alluran/node.net,pratikkagda/nuget,indsoft/NuGet2,jholovacs/NuGet,dolkensp/node.net,alluran/node.net,xoofx/NuGet,OneGet/nuget,zskullz/nuget,atheken/nuget,indsoft/NuGet2,ctaggart/nuget,dolkensp/node.net,zskullz/nuget,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,jholovacs/NuGet,rikoe/nuget,RichiCoder1/nuget-chocolatey,mrward/nuget,chocolatey/nuget-chocolatey,oliver-feng/nuget,GearedToWar/NuGet2,anurse/NuGet,indsoft/NuGet2,chocolatey/nuget-chocolatey,pratikkagda/nuget,antiufo/NuGet2,zskullz/nuget,GearedToWar/NuGet2,mono/nuget,rikoe/nuget,mrward/nuget,zskullz/nuget,ctaggart/nuget,akrisiun/NuGet,xoofx/NuGet,RichiCoder1/nuget-chocolatey,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,antiufo/NuGet2,chester89/nugetApi,xoofx/NuGet,mrward/NuGet.V2,pratikkagda/nuget,GearedToWar/NuGet2,themotleyfool/NuGet,mrward/NuGet.V2,antiufo/NuGet2,antiufo/NuGet2,GearedToWar/NuGet2,jmezach/NuGet2,akrisiun/NuGet,jholovacs/NuGet,dolkensp/node.net,themotleyfool/NuGet,RichiCoder1/nuget-chocolatey,RichiCoder1/nuget-chocolatey,mrward/NuGet.V2,alluran/node.net,xoofx/NuGet,indsoft/NuGet2,mrward/nuget,dolkensp/node.net,antiufo/NuGet2,ctaggart/nuget,rikoe/nuget,chocolatey/nuget-chocolatey,oliver-feng/nuget,oliver-feng/nuget,jholovacs/NuGet,xoofx/NuGet,mono/nuget,pratikkagda/nuget,kumavis/NuGet,alluran/node.net,chocolatey/nuget-chocolatey,jholovacs/NuGet,mrward/nuget,xero-github/Nuget,OneGet/nuget,OneGet/nuget,oliver-feng/nuget,jmezach/NuGet2,themotleyfool/NuGet,xoofx/NuGet,atheken/nuget,jmezach/NuGet2,mrward/NuGet.V2,indsoft/NuGet2,anurse/NuGet,chester89/nugetApi,oliver-feng/nuget,jmezach/NuGet2,jmezach/NuGet2,GearedToWar/NuGet2,OneGet/nuget,indsoft/NuGet2,jmezach/NuGet2,jholovacs/NuGet,mono/nuget,mrward/nuget,kumavis/NuGet,pratikkagda/nuget,mrward/nuget
84a1f76a9890e5ddbb3d6bf5b5b701fd1e17489b
Properties/VersionAssemblyInfo.cs
Properties/VersionAssemblyInfo.cs
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34003 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-10-23 22:48")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Wcf 3.0.0")]
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.18051 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("3.0.0.0")] [assembly: AssemblyFileVersion("3.0.0.0")] [assembly: AssemblyConfiguration("Release built on 2013-12-03 10:23")] [assembly: AssemblyCopyright("Copyright © 2013 Autofac Contributors")] [assembly: AssemblyDescription("Autofac.Wcf 3.0.0")]
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
Split WCF functionality out of Autofac.Extras.Multitenant into a separate assembly/package, Autofac.Extras.Multitenant.Wcf. Both packages are versioned 3.1.0.
C#
mit
caioproiete/Autofac.Wcf,autofac/Autofac.Wcf
752d16e816feec77d01256fbf6a5f79e5bbeb09f
Entitas.Unity/Assets/Entitas/Unity/VisualDebugging/GameObjectDestroyExtension.cs
Entitas.Unity/Assets/Entitas/Unity/VisualDebugging/GameObjectDestroyExtension.cs
using UnityEngine; namespace Entitas.Unity.VisualDebugging { public static class GameObjectDestroyExtension { public static void DestroyGameObject(this GameObject gameObject) { #if (UNITY_EDITOR) if (Application.isPlaying) { Object.Destroy(gameObject); } else { Object.DestroyImmediate(gameObject); } #else Destroy(gameObject); #endif } } }
using UnityEngine; namespace Entitas.Unity.VisualDebugging { public static class GameObjectDestroyExtension { public static void DestroyGameObject(this GameObject gameObject) { #if (UNITY_EDITOR) if (Application.isPlaying) { Object.Destroy(gameObject); } else { Object.DestroyImmediate(gameObject); } #else Object.Destroy(gameObject); #endif } } }
Fix Destroy compile time error
Fix Destroy compile time error Project refused to build post upgrade to 0.30.0. Error: error CS0103: The name `Destroy' does not exist in the current context
C#
mit
sschmid/Entitas-CSharp,sschmid/Entitas-CSharp,vkuskov/Entitas-CSharp,vkuskov/Entitas-CSharp