commit
stringlengths
40
40
subject
stringlengths
4
1.73k
repos
stringlengths
5
127k
old_file
stringlengths
2
751
new_file
stringlengths
2
751
new_contents
stringlengths
1
8.98k
old_contents
stringlengths
0
6.59k
license
stringclasses
13 values
lang
stringclasses
23 values
d9f7fe5c43cb340a9e061c79e94ad66b93ccaafb
Refactor baseconfig.
Joshua-Ashton/TheGuin2
src/ConfigSchema/BaseConfig.cs
src/ConfigSchema/BaseConfig.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace TheGuin2 { public class ConfigDefault { public string DefaultDir; } public class DefaultConfigDefault : ConfigDefault { public DefaultConfigDefault() { DefaultDir = "{\n}"; } } public class BaseConfig<Schema> : BaseConfig<Schema, ConfigDefault> { } public class BaseConfig<Schema, DefaultDir> where DefaultDir : ConfigDefault, new() { public static void Set(Schema newSchema, BaseServer server = null) { MakeDefault(server); Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, GetRelativePath(server)); } public static void Delete(BaseServer server = null) { string path = GetAbsolutePath(server); try { if (File.Exists(path)) File.Delete(path); } catch (Exception e) { Console.WriteLine(e.Message); } } public static string GetRelativePath(BaseServer server = null) { if (server != null) return String.Format("{0}/{1}{2}", server.GetConfigDir(), typeof(Schema).Name, ".json"); else return String.Format("{0}{1}", typeof(Schema).Name, ".json"); } private static string GetAbsolutePath(BaseServer server = null) { return String.Format("{0}/{1}", StaticConfig.Paths.ConfigPath, GetRelativePath(server)); } private static void MakeDefault(BaseServer server = null) { string path = GetAbsolutePath(server); try { if (!File.Exists(path)) File.WriteAllText(path, new DefaultDir().DefaultDir); } catch (Exception e) { Console.WriteLine(e.Message); } } public static Schema Get(BaseServer server = null) { MakeDefault(server); return Globals.GetConfigSystem().DeserialiseFile<Schema>(GetRelativePath(server)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace TheGuin2 { public class ConfigDefault { public string DefaultDir; } public class DefaultConfigDefault : ConfigDefault { public DefaultConfigDefault() { DefaultDir = "{\n}"; } } public class BaseConfig<Schema> : BaseConfig<Schema, ConfigDefault> { } public class BaseConfig<Schema, DefaultDir> where DefaultDir : ConfigDefault, new() { public static void Set(Schema newSchema, BaseServer server = null) { MakeDir(server); if (server != null) Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, server.GetConfigDir() + "/" + typeof(Schema).Name + ".json"); else Globals.GetConfigSystem().SerialiseToFile<Schema>(newSchema, typeof(Schema).Name + ".json"); } public static void Delete(BaseServer server = null) { try { string path = ""; if (server != null) path = StaticConfig.Paths.ConfigPath + "/" + server.GetConfigDir() + "/" + typeof(Schema).Name + ".json"; else path = StaticConfig.Paths.ConfigPath + "/" + typeof(Schema).Name + ".json"; File.Delete(path); } catch { } } private static void MakeDir(BaseServer server = null) { string path = ""; if (server != null) path = StaticConfig.Paths.ConfigPath + "/" + server.GetConfigDir() + "/" + typeof(Schema).Name + ".json"; else path = StaticConfig.Paths.ConfigPath + "/" + typeof(Schema).Name + ".json"; try { if (!File.Exists(path)) File.WriteAllText(path, new DefaultDir().DefaultDir); } catch (Exception e) { Console.WriteLine(e.Message); } } public static Schema Get(BaseServer server = null) { MakeDir(server); if (server != null) return Globals.GetConfigSystem().DeserialiseFile<Schema>(server.GetConfigDir() + "/" + typeof(Schema).Name + ".json"); else return Globals.GetConfigSystem().DeserialiseFile<Schema>(typeof(Schema).Name + ".json"); } } }
mit
C#
48430df3fb919be45a557e247614c78253a2b9e7
Create filter when -* is not included
michaelsync/Giles,michaelsync/Giles,codereflection/Giles,michaelsync/Giles,codereflection/Giles,michaelsync/Giles,codereflection/Giles
src/Giles.Core/Configuration/Filter.cs
src/Giles.Core/Configuration/Filter.cs
using System.Collections.Generic; using System.Linq; namespace Giles.Core.Configuration { public class Filter { public Filter() { } public Filter(string convertToFilter) { foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key))) { Type = entry.Value; Name = convertToFilter.Replace(entry.Key, string.Empty); break; } if (!string.IsNullOrWhiteSpace(Name)) return; Name = convertToFilter; Type = FilterType.Inclusive; } public string Name { get; set; } public FilterType Type { get; set; } public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType> { {"-i", FilterType.Inclusive}, {"-e", FilterType.Exclusive} }; } public enum FilterType { Inclusive, Exclusive } }
using System.Collections.Generic; using System.Linq; namespace Giles.Core.Configuration { public class Filter { public Filter() { } public Filter(string convertToFilter) { foreach (var entry in FilterLookUp.Where(entry => convertToFilter.Contains(entry.Key))) { Type = entry.Value; Name = convertToFilter.Replace(entry.Key, string.Empty); break; } } public string Name { get; set; } public FilterType Type { get; set; } public static readonly IDictionary<string, FilterType> FilterLookUp = new Dictionary<string, FilterType> { {"-i", FilterType.Inclusive}, {"-e", FilterType.Exclusive} }; } public enum FilterType { Inclusive, Exclusive } }
mit
C#
32761126f2a3dcec12eb63bf48454b0045671154
Fix message on project schedule not configured
leotsarev/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net,joinrpg/joinrpg-net,leotsarev/joinrpg-net
src/JoinRpg.WebPortal.Models/Schedules/ScheduleConfigProblemsViewModel.cs
src/JoinRpg.WebPortal.Models/Schedules/ScheduleConfigProblemsViewModel.cs
using System.ComponentModel; namespace JoinRpg.Web.Models.Schedules { public enum ScheduleConfigProblemsViewModel { [Description("Расписание не настроено для этого проекта. Вам необходимо добавить поля для помещения и расписания.")] FieldsNotSet, [Description("У полей, привязанных к расписанию, разная видимость. Измените настройки видимости полей (публичные/игрокам/мастерам) на одинаковые.")] InconsistentVisibility, [Description("У вас нет доступа к расписанию данного проекта")] NoAccess, [Description("Не настроено ни одного помещения")] NoRooms, [Description("Не настроено ни одного тайм-слота")] NoTimeSlots, } }
using System.ComponentModel; namespace JoinRpg.Web.Models.Schedules { public enum ScheduleConfigProblemsViewModel { //TODO поменять сообщение, когда сделаем настроечный экран [Description("Расписание не настроено для этого проекта, обратитесь в техподдержку")] FieldsNotSet, [Description("У полей, привязанных к расписанию, разная видимость. Измените настройки видимости полей (публичные/игрокам/мастерам) на одинаковые")] InconsistentVisibility, [Description("У вас нет доступа к расписанию данного проекта")] NoAccess, [Description("Не настроено ни одного помещения")] NoRooms, [Description("Не настроено ни одного тайм-слота")] NoTimeSlots, } }
mit
C#
6125643c3f8086b0f44973b76556eef58bb0ae66
Bump copyright year
tcmorris/Umbraco-CMS,mattbrailsford/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,leekelleher/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,bjarnef/Umbraco-CMS,abryukhov/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,robertjf/Umbraco-CMS,rasmuseeg/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,bjarnef/Umbraco-CMS,arknu/Umbraco-CMS,bjarnef/Umbraco-CMS,leekelleher/Umbraco-CMS,KevinJump/Umbraco-CMS,madsoulswe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,hfloyd/Umbraco-CMS,marcemarc/Umbraco-CMS,NikRimington/Umbraco-CMS,abjerner/Umbraco-CMS,NikRimington/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,tcmorris/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,rasmuseeg/Umbraco-CMS,dawoe/Umbraco-CMS,umbraco/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,umbraco/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,bjarnef/Umbraco-CMS,rasmuseeg/Umbraco-CMS,abryukhov/Umbraco-CMS,madsoulswe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,leekelleher/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,umbraco/Umbraco-CMS,arknu/Umbraco-CMS,abjerner/Umbraco-CMS
src/SolutionInfo.cs
src/SolutionInfo.cs
using System.Reflection; using System.Resources; [assembly: AssemblyCompany("Umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] // versions // read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin // note: do NOT change anything here manually, use the build scripts // this is the ONLY ONE the CLR cares about for compatibility // should change ONLY when "hard" breaking compatibility (manual change) [assembly: AssemblyVersion("8.0.0")] // these are FYI and changed automatically [assembly: AssemblyFileVersion("8.0.0")] [assembly: AssemblyInformationalVersion("8.0.0-alpha.58")]
using System.Reflection; using System.Resources; [assembly: AssemblyCompany("Umbraco")] [assembly: AssemblyCopyright("Copyright © Umbraco 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] // versions // read https://stackoverflow.com/questions/64602/what-are-differences-between-assemblyversion-assemblyfileversion-and-assemblyin // note: do NOT change anything here manually, use the build scripts // this is the ONLY ONE the CLR cares about for compatibility // should change ONLY when "hard" breaking compatibility (manual change) [assembly: AssemblyVersion("8.0.0")] // these are FYI and changed automatically [assembly: AssemblyFileVersion("8.0.0")] [assembly: AssemblyInformationalVersion("8.0.0-alpha.58")]
mit
C#
dbad62688e8309b4f42eb7827e6be8a16f045553
Clean up Qt 4.7.1 thirdparty module constructor
markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation,markfinal/BuildAMation
packages/Qt/4.7.1/Qt.cs
packages/Qt/4.7.1/Qt.cs
// <copyright file="Qt.cs" company="Mark Final"> // Opus package // </copyright> // <summary>Qt package</summary> // <author>Mark Final</author> [assembly:Opus.Core.RegisterToolset("Qt", typeof(Qt.Toolset))] namespace Qt { public sealed class Qt : QtCommon.QtCommon { public Qt(Opus.Core.Target target) { // The target here will have a null IToolset because this module is a Thirdparty // module, which has no need for a tool, so no toolset is configured // However, we do need to know where Qt was installed, which is in the Toolset // so just grab the instance Opus.Core.IToolset toolset = Opus.Core.ToolsetFactory.GetInstance(typeof(Toolset)); string installPath = toolset.InstallPath((Opus.Core.BaseTarget)target); if (Opus.Core.OSUtilities.IsOSXHosting) { this.BinPath = installPath; } else { this.BinPath = System.IO.Path.Combine(installPath, "bin"); } this.LibPath = System.IO.Path.Combine(installPath, "lib"); this.includePaths.Add(System.IO.Path.Combine(installPath, "include")); } } }
// <copyright file="Qt.cs" company="Mark Final"> // Opus package // </copyright> // <summary>Qt package</summary> // <author>Mark Final</author> [assembly:Opus.Core.RegisterToolset("Qt", typeof(Qt.Toolset))] namespace Qt { public sealed class Qt : QtCommon.QtCommon { public Qt(Opus.Core.Target target) { // NEW STYLE #if true // TODO: investigate this - Qt is a ThirdpartyModule, with no toolset // what is the best course of action? string installPath = Opus.Core.ToolsetFactory.GetInstance(typeof(Toolset)).InstallPath((Opus.Core.BaseTarget)target); //string installPath = target.Toolset.InstallPath((Opus.Core.BaseTarget)target); if (Opus.Core.OSUtilities.IsOSXHosting) { this.BinPath = installPath; } else { this.BinPath = System.IO.Path.Combine(installPath, "bin"); } #else if (Opus.Core.OSUtilities.IsOSXHosting) { this.BinPath = installPath; } else { this.BinPath = System.IO.Path.Combine(installPath, "bin"); } #endif this.LibPath = System.IO.Path.Combine(installPath, "lib"); this.includePaths.Add(System.IO.Path.Combine(installPath, "include")); } } }
bsd-3-clause
C#
530404962ff67eadb57109eda7c2cb4441fd263e
Update version numbers for BlazorExtension
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
tooling/Microsoft.VisualStudio.BlazorExtension/Properties/AssemblyInfo.cs
tooling/Microsoft.VisualStudio.BlazorExtension/Properties/AssemblyInfo.cs
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; // Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show // up in the Load context, which means that we can use ServiceHub and other nice things. // // The versions here need to match what the build is producing. If you change the version numbers // for the Blazor assemblies, this needs to change as well. [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.AngleSharp", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.9.9.0", NewVersion = "0.9.9.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.1.0.0", NewVersion = "0.1.0.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.1.0.0", NewVersion = "0.1.0.0")]
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.VisualStudio.Shell; // Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show // up in the Load context, which means that we can use ServiceHub and other nice things. // // The versions here need to match what the build is producing. If you change the version numbers // for the Blazor assemblies, this needs to change as well. [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.AngleSharp", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.9.9.0", NewVersion = "0.9.9.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.0.5.0", NewVersion = "0.0.5.0")] [assembly: ProvideBindingRedirection( AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor", GenerateCodeBase = true, PublicKeyToken = "", OldVersionLowerBound = "0.0.0.0", OldVersionUpperBound = "0.0.5.0", NewVersion = "0.0.5.0")]
apache-2.0
C#
118274da2309c8b7110dfc0f14a7ea17108ec50a
Fix antiraid/antispam migration
ShadowNoire/NadekoBot
NadekoBot.Core/Migrations/20210422130207_antiraid-antispam-time-addrole.cs
NadekoBot.Core/Migrations/20210422130207_antiraid-antispam-time-addrole.cs
using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { public partial class antiraidantispamtimeaddrole : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<ulong>( name: "RoleId", table: "AntiSpamSetting", nullable: true); migrationBuilder.AddColumn<int>( name: "PunishDuration", table: "AntiRaidSetting", nullable: false, defaultValue: 0); migrationBuilder.Sql("DELETE FROM AntiSpamIgnore WHERE AntiSpamSettingId in (SELECT ID FROM AntiSpamSetting WHERE MuteTime < 60 AND MuteTime <> 0)"); migrationBuilder.Sql("DELETE FROM AntiSpamSetting WHERE MuteTime < 60 AND MuteTime <> 0;"); migrationBuilder.Sql("UPDATE AntiSpamSetting SET MuteTime=MuteTime / 60;"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "RoleId", table: "AntiSpamSetting"); migrationBuilder.DropColumn( name: "PunishDuration", table: "AntiRaidSetting"); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace NadekoBot.Migrations { public partial class antiraidantispamtimeaddrole : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<ulong>( name: "RoleId", table: "AntiSpamSetting", nullable: true); migrationBuilder.AddColumn<int>( name: "PunishDuration", table: "AntiRaidSetting", nullable: false, defaultValue: 0); migrationBuilder.Sql("DELETE FROM AntiSpamSetting WHERE MuteTime < 60;"); migrationBuilder.Sql("UPDATE AntiSpamSetting SET MuteTime=MuteTime / 60;"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "RoleId", table: "AntiSpamSetting"); migrationBuilder.DropColumn( name: "PunishDuration", table: "AntiRaidSetting"); } } }
mit
C#
9aca7c060868c64137303b860427fc38955ecc07
Fix throw exception by \text{∅}
ForNeVeR/wpf-math
src/WpfMath/Boxes/CharBox.cs
src/WpfMath/Boxes/CharBox.cs
using System.Linq; using System.Windows; using System.Windows.Media; using WpfMath.Exceptions; using WpfMath.Rendering; namespace WpfMath.Boxes { // Box representing single character. internal class CharBox : Box { public CharBox(TexEnvironment environment, CharInfo charInfo) : base(environment) { this.Character = charInfo; this.Width = charInfo.Metrics.Width; this.Height = charInfo.Metrics.Height; this.Depth = charInfo.Metrics.Depth; this.Italic = charInfo.Metrics.Italic; } public CharInfo Character { get; private set; } internal GlyphRun GetGlyphRun(double scale, double x, double y) { var typeface = this.Character.Font; var characterInt = (int)this.Character.Character; if (!typeface.CharacterToGlyphMap.TryGetValue(characterInt, out var glyphIndex)) { var fontName = typeface.FamilyNames.Values.First(); var characterHex = characterInt.ToString("X4"); throw new TexCharacterMappingNotFoundException( $"The {fontName} font does not support '{this.Character.Character}' (U+{characterHex}) character."); } var glyphRun = new GlyphRun(typeface, 0, false, this.Character.Size * scale, new ushort[] { glyphIndex }, new Point(x * scale, y * scale), new double[] { typeface.AdvanceWidths[glyphIndex] }, null, null, null, null, null, null); return glyphRun; } public override void RenderTo(IElementRenderer renderer, double x, double y) { var color = this.Foreground ?? Brushes.Black; renderer.RenderGlyphRun(scale => this.GetGlyphRun(scale, x, y), x, y, color); } public override int GetLastFontId() { return this.Character.FontId; } } }
using System.Windows; using System.Windows.Media; using WpfMath.Rendering; namespace WpfMath.Boxes { // Box representing single character. internal class CharBox : Box { public CharBox(TexEnvironment environment, CharInfo charInfo) : base(environment) { this.Character = charInfo; this.Width = charInfo.Metrics.Width; this.Height = charInfo.Metrics.Height; this.Depth = charInfo.Metrics.Depth; this.Italic = charInfo.Metrics.Italic; } public CharInfo Character { get; private set; } internal GlyphRun GetGlyphRun(double scale, double x, double y) { var typeface = this.Character.Font; var glyphIndex = typeface.CharacterToGlyphMap[this.Character.Character]; var glyphRun = new GlyphRun(typeface, 0, false, this.Character.Size * scale, new ushort[] { glyphIndex }, new Point(x * scale, y * scale), new double[] { typeface.AdvanceWidths[glyphIndex] }, null, null, null, null, null, null); return glyphRun; } public override void RenderTo(IElementRenderer renderer, double x, double y) { var color = this.Foreground ?? Brushes.Black; renderer.RenderGlyphRun(scale => this.GetGlyphRun(scale, x, y), x, y, color); } public override int GetLastFontId() { return this.Character.FontId; } } }
mit
C#
5d04e79cfca64917c56885aa4e3b68157c80a532
standardize an IAM tag
GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples,GoogleCloudPlatform/dotnet-docs-samples
iam/api/Access/AddMember.cs
iam/api/Access/AddMember.cs
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START iam_modify_policy_add_member] // [START iam_modify_policy_member] using System.Linq; using Google.Apis.CloudResourceManager.v1.Data; public partial class AccessManager { public static Policy AddMember(Policy policy, string role, string member) { var binding = policy.Bindings.First(x => x.Role == role); binding.Members.Add(member); return policy; } } // [END iam_modify_policy_member] // [END iam_modify_policy_add_member]
// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // [START iam_modify_policy_member] using System.Linq; using Google.Apis.CloudResourceManager.v1.Data; public partial class AccessManager { public static Policy AddMember(Policy policy, string role, string member) { var binding = policy.Bindings.First(x => x.Role == role); binding.Members.Add(member); return policy; } } // [END iam_modify_policy_member]
apache-2.0
C#
47634c90cf001c7440708ff2afab083a8b2a40b2
change home page for placeholder
nikkh/xekina,nikkh/xekina
XekinaSample/XekinaWebApp/Views/Home/Index.cshtml
XekinaSample/XekinaWebApp/Views/Home/Index.cshtml
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>#Name_Placeholder# Sample Web Application</h1> <p class="lead">This web application has been automatically generated and deployed by Xekina.</p> <p><a href="https://www.xekina.com" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p> ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development. </p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div>
@{ ViewBag.Title = "Home Page"; } <div class="jumbotron"> <h1>Xekina Sample Web Application</h1> <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p> <p><a href="https://asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p> </div> <div class="row"> <div class="col-md-4"> <h2>Getting started</h2> <p> ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that enables a clean separation of concerns and gives you full control over markup for enjoyable, agile development. </p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301865">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Get more libraries</h2> <p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301866">Learn more &raquo;</a></p> </div> <div class="col-md-4"> <h2>Web Hosting</h2> <p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p> <p><a class="btn btn-default" href="https://go.microsoft.com/fwlink/?LinkId=301867">Learn more &raquo;</a></p> </div> </div>
unlicense
C#
7659808df11a5f8e44e72c5c3dd340ac64fa5f4e
Add manual test case for reproducing issue
ppy/osu-framework,ZLima12/osu-framework,peppy/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,peppy/osu-framework
osu.Framework.Tests/Visual/Testing/TestSceneManualInputManagerTestScene.cs
osu.Framework.Tests/Visual/Testing/TestSceneManualInputManagerTestScene.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; using osuTK; using osuTK.Input; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneManualInputManagerTestScene : ManualInputManagerTestScene { protected override Vector2 InitialMousePosition => new Vector2(10f); [Test] public void TestResetInput() { AddStep("move mouse", () => InputManager.MoveMouseTo(Vector2.Zero)); AddStep("press mouse", () => InputManager.PressButton(MouseButton.Left)); AddStep("press key", () => InputManager.PressKey(Key.Z)); AddStep("press joystick", () => InputManager.PressJoystickButton(JoystickButton.Button1)); AddStep("reset input", ResetInput); AddAssert("mouse position reset", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); AddAssert("all input states released", () => !InputManager.CurrentState.Mouse.Buttons.HasAnyButtonPressed && !InputManager.CurrentState.Keyboard.Keys.HasAnyButtonPressed && !InputManager.CurrentState.Joystick.Buttons.HasAnyButtonPressed); } /// <summary> /// Added to allow manual testing of the test cursor visuals. /// </summary> [Test] public void TestHoldLeftFromMaskedPosition() { AddStep("move mouse to screen zero", () => InputManager.MoveMouseTo(Vector2.Zero)); AddStep("hold mouse left", () => InputManager.PressButton(MouseButton.Left)); AddStep("move mouse to content center", () => InputManager.MoveMouseTo(Content.ScreenSpaceDrawQuad.Centre)); } [Test] public void TestMousePositionSetToInitial() => AddAssert("mouse position set to initial", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using NUnit.Framework; using osu.Framework.Input; using osu.Framework.Testing; using osuTK; using osuTK.Input; namespace osu.Framework.Tests.Visual.Testing { public class TestSceneManualInputManagerTestScene : ManualInputManagerTestScene { protected override Vector2 InitialMousePosition => new Vector2(10f); [Test] public void TestResetInput() { AddStep("move mouse", () => InputManager.MoveMouseTo(Vector2.Zero)); AddStep("press mouse", () => InputManager.PressButton(MouseButton.Left)); AddStep("press key", () => InputManager.PressKey(Key.Z)); AddStep("press joystick", () => InputManager.PressJoystickButton(JoystickButton.Button1)); AddStep("reset input", ResetInput); AddAssert("mouse position reset", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); AddAssert("all input states released", () => !InputManager.CurrentState.Mouse.Buttons.HasAnyButtonPressed && !InputManager.CurrentState.Keyboard.Keys.HasAnyButtonPressed && !InputManager.CurrentState.Joystick.Buttons.HasAnyButtonPressed); } [Test] public void TestMousePositionSetToInitial() => AddAssert("mouse position set to initial", () => InputManager.CurrentState.Mouse.Position == InitialMousePosition); } }
mit
C#
d33e70a11b70460c050e7f2cc85eaba11ee1bc79
Mask ClientSecret in Settings admin
OShop/OShop.PayPal,OShop/OShop.PayPal
Views/Admin/Settings.cshtml
Views/Admin/Settings.cshtml
@model OShop.PayPal.Models.PaypalSettings @{ Layout.Title = T("PayPal Settings"); } @using (Html.BeginFormAntiForgeryPost()) { @Html.ValidationSummary() <fieldset> <legend>@T("PayPal Account")</legend> <div> @Html.LabelFor(m => m.ClientId, T("Client ID")) @Html.TextBoxFor(m => m.ClientId, new { @class = "text medium" }) @Html.ValidationMessageFor(m => m.ClientId, "*") </div> <div> @Html.LabelFor(m => m.ClientSecret, T("Client secret")) @Html.TextBoxFor(m => m.ClientSecret, new { type = "password", @class = "text medium" }) @Html.ValidationMessageFor(m => m.ClientSecret, "*") </div> </fieldset> <fieldset> <legend>@T("Test mode")</legend> <div> @Html.CheckBoxFor(m => m.UseSandbox) @Html.LabelFor(m => m.UseSandbox, T("Use sandbox").Text, new { @class = "forcheckbox" }) <span class="hint">@T("For testing purpose only.")</span> @Html.ValidationMessageFor(m => m.UseSandbox, "*") </div> </fieldset> <div> <button type="submit" name="submit.Validate" value="validate">@T("Validate credentials")</button> <button type="submit" name="submit.Save" value="create">@T("Save")</button> </div> }
@model OShop.PayPal.Models.PaypalSettings @{ Layout.Title = T("PayPal Settings"); } @using (Html.BeginFormAntiForgeryPost()) { @Html.ValidationSummary() <fieldset> <legend>@T("PayPal Account")</legend> <div> @Html.LabelFor(m => m.ClientId, T("Client ID")) @Html.TextBoxFor(m => m.ClientId, new { @class = "text medium" }) @Html.ValidationMessageFor(m => m.ClientId, "*") </div> <div> @Html.LabelFor(m => m.ClientSecret, T("Client secret")) @Html.TextBoxFor(m => m.ClientSecret, new { @class = "text medium" }) @Html.ValidationMessageFor(m => m.ClientSecret, "*") </div> </fieldset> <fieldset> <legend>@T("Test mode")</legend> <div> @Html.CheckBoxFor(m => m.UseSandbox) @Html.LabelFor(m => m.UseSandbox, T("Use sandbox").Text, new { @class = "forcheckbox" }) <span class="hint">@T("For testing purpose only.")</span> @Html.ValidationMessageFor(m => m.UseSandbox, "*") </div> </fieldset> <div> <button type="submit" name="submit.Validate" value="validate">@T("Validate credentials")</button> <button type="submit" name="submit.Save" value="create">@T("Save")</button> </div> }
mit
C#
35420d1aa556a130a62e1c3e4052ce2e8154f33c
Test cleanup
bsimser/GeoJSON.NET
src/BilSimser.GeoJson.Tests/when_converting.cs
src/BilSimser.GeoJson.Tests/when_converting.cs
using System.IO; using System.Xml; using NUnit.Framework; namespace BilSimser.GeoJson.Tests { [TestFixture] public class when_converting { [Test] public void minimal_kml_result_is_not_blank() { const string fileName = "borabora.kml"; var path = Path.Combine(Path.GetTempPath(), fileName); TestServices.CreateTextFile("BilSimser.GeoJson.Tests.Data.borabora.kml", fileName); var input = TestServices.ReadFile(fileName); var result = GeoJsonConvert.Convert(input); Assert.IsNotEmpty(result); TestServices.DeleteFile(fileName); } [Test] public void blank_document_throws_xml_exception() { Assert.Throws<XmlException>(() => GeoJsonConvert.Convert(string.Empty)); } [Test] public void partial_document_throws_xml_exception() { Assert.Throws<XmlException>(delegate { const string partial = "<kml><Placemark><name>Bora-Bora Airport</name></Point></Placemark></kml>"; GeoJsonConvert.Convert(partial); }); } [Test] public void invalid_xml_throws_xml_exception() { Assert.Throws<XmlException>(delegate { const string partial = "<kml><Placemark>"; GeoJsonConvert.Convert(partial); }); } } }
using System.IO; using System.Xml; using NUnit.Framework; namespace BilSimser.GeoJson.Tests { [TestFixture] public class when_converting { [Test] public void minimal_kml_result_is_not_blank() { const string fileName = "borabora.kml"; var path = Path.Combine(Path.GetTempPath(), fileName); TestServices.CreateTextFile("BilSimser.GeoJson.Tests.Data.borabora.kml", fileName); var input = TestServices.ReadFile(fileName); var result = GeoJsonConvert.Convert(input); Assert.IsNotEmpty(result); TestServices.DeleteFile(fileName); } [Test] public void blank_document_throws_xml_exception() { Assert.Throws<XmlException>(delegate { GeoJsonConvert.Convert(string.Empty); }); } [Test] public void partial_document_throws_xml_exception() { Assert.Throws<XmlException>(delegate { const string partial = "<kml><Placemark><name>Bora-Bora Airport</name></Point></Placemark></kml>"; GeoJsonConvert.Convert(partial); }); } [Test] public void invalid_xml_throws_xml_exception() { Assert.Throws<XmlException>(delegate { const string partial = "<kml><Placemark>"; GeoJsonConvert.Convert(partial); }); } } }
mit
C#
2f1cd7f457b54f1b88b8e6e1881c6b1227d5a094
Update src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Program.cs
aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore
src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Program.cs
src/ProjectTemplates/Web.ProjectTemplates/content/Worker-CSharp/Program.cs
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Company.Application1; IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); await host.RunAsync();
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Company.Application1; using IHost host = Host.CreateDefaultBuilder(args) .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); await host.RunAsync();
apache-2.0
C#
4ce3a7806690b7672080253bc13caaf7e9fe3813
Update Pattern.cs
NeoAdonis/osu,NeoAdonis/osu,EVAST9919/osu,ZLima12/osu,Drezi126/osu,DrabWeb/osu,ZLima12/osu,ppy/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,tacchinotacchi/osu,smoogipoo/osu,Nabile-Rahmani/osu,peppy/osu-new,naoey/osu,smoogipooo/osu,UselessToucan/osu,osu-RP/osu-RP,Damnae/osu,DrabWeb/osu,smoogipoo/osu,naoey/osu,Frontear/osuKyzer,peppy/osu,johnneijzen/osu,johnneijzen/osu,naoey/osu,2yangk23/osu,NeoAdonis/osu,ppy/osu,EVAST9919/osu,peppy/osu,peppy/osu
osu.Game.Rulesets.Mania/Beatmaps/Patterns/Pattern.cs
osu.Game.Rulesets.Mania/Beatmaps/Patterns/Pattern.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Game.Rulesets.Mania.Objects; namespace osu.Game.Rulesets.Mania.Beatmaps.Patterns { /// <summary> /// Creates a pattern containing hit objects. /// </summary> internal class Pattern { private readonly List<ManiaHitObject> hitObjects = new List<ManiaHitObject>(); /// <summary> /// All the hit objects contained in this pattern. /// </summary> public IEnumerable<ManiaHitObject> HitObjects => hitObjects; /// <summary> /// Check whether a column of this patterns contains a hit object. /// </summary> /// <param name="column">The column index.</param> /// <returns>Whether the column with index <paramref name="column"/> contains a hit object.</returns> public bool ColumnHasObject(int column) => hitObjects.Exists(h => h.Column == column); /// <summary> /// Amount of columns taken up by hit objects in this pattern. /// </summary> public int ColumnWithObjects => HitObjects.GroupBy(h => h.Column).Count(); /// <summary> /// Adds a hit object to this pattern. /// </summary> /// <param name="hitObject">The hit object to add.</param> public void Add(ManiaHitObject hitObject) => hitObjects.Add(hitObject); /// <summary> /// Copies hit object from another pattern to this one. /// </summary> /// <param name="other">The other pattern.</param> public void Add(Pattern other) => hitObjects.AddRange(other.HitObjects); /// <summary> /// Clears this pattern, removing all hit objects. /// </summary> public void Clear() => hitObjects.Clear(); /// <summary> /// Removes a hit object from this pattern. /// </summary> /// <param name="hitObject">The hit object to remove.</param> public bool Remove(ManiaHitObject hitObject) => hitObjects.Remove(hitObject); } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System.Collections.Generic; using System.Linq; using osu.Framework.Extensions.IEnumerableExtensions; using osu.Game.Rulesets.Mania.Objects; namespace osu.Game.Rulesets.Mania.Beatmaps.Patterns { /// <summary> /// Creates a pattern containing hit objects. /// </summary> internal class Pattern { private readonly List<ManiaHitObject> hitObjects = new List<ManiaHitObject>(); /// <summary> /// All the hit objects contained in this pattern. /// </summary> public IEnumerable<ManiaHitObject> HitObjects => hitObjects; /// <summary> /// Check whether a column of this patterns contains a hit object. /// </summary> /// <param name="column">The column index.</param> /// <returns>Whether the column with index <paramref name="column"/> contains a hit object.</returns> public bool ColumnHasObject(int column) => hitObjects.Exists(h => h.Column == column); /// <summary> /// Amount of columns taken up by hit objects in this pattern. /// </summary> public int ColumnWithObjects => HitObjects.GroupBy(h => h.Column).Count(); /// <summary> /// Adds a hit object to this pattern. /// </summary> /// <param name="hitObject">The hit object to add.</param> public void Add(ManiaHitObject hitObject) => hitObjects.Add(hitObject); /// <summary> /// Copies hit object from another pattern to this one. /// </summary> /// <param name="other">The other pattern.</param> public void Add(Pattern other) => hitObjects.AddRange(other.HitObjects); /// <summary> /// Clears this pattern, removing all hit objects. /// </summary> public void Clear() => hitObjects.Clear(); /// <summary> /// Removes a hit object from this pattern. /// </summary> /// <param name="hitObject">The hit object to remove.</param> public bool Remove(ManiaHitObject hitObject) => hitObjects.Remove(hitObject); } }
mit
C#
5da7cb5397867b99d671d21c81dd395ee270b284
Make comment ID public for test
peppy/osu,ppy/osu,peppy/osu,ppy/osu,peppy/osu,ppy/osu
osu.Game/Online/API/Requests/CommentDeleteRequest.cs
osu.Game/Online/API/Requests/CommentDeleteRequest.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class CommentDeleteRequest : APIRequest<CommentBundle> { public readonly long ID; public CommentDeleteRequest(long id) { this.ID = id; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Delete; return req; } protected override string Target => $@"comments/{ID}"; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Net.Http; using osu.Framework.IO.Network; using osu.Game.Online.API.Requests.Responses; namespace osu.Game.Online.API.Requests { public class CommentDeleteRequest : APIRequest<CommentBundle> { private readonly long id; public CommentDeleteRequest(long id) { this.id = id; } protected override WebRequest CreateWebRequest() { var req = base.CreateWebRequest(); req.Method = HttpMethod.Delete; return req; } protected override string Target => $@"comments/{id}"; } }
mit
C#
383249bd6194f57a14ce4a5345b3556648f777fc
test ci
dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing,dotnet-architecture/eShopModernizing
eShopModernizedMVCSolution/src/eShopModernizedMVC/Views/Shared/_Layout.cshtml
eShopModernizedMVCSolution/src/eShopModernizedMVC/Views/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Catalog manager (MVC)</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <header class="navbar navbar-light navbar-static-top"> <div class="esh-header-brand"> <a href="@Url.Action("index", "catalog")"> <img src="~/images/brand.png" /> </a> </div> </header> <section class="esh-app-hero"> <div class="container esh-header"> <h1 class="esh-header-title" >Catalog manager <span>(MVC)</span></h1> </div> </section> @RenderBody() <footer class="esh-app-footer"> <div class="container"> <article class="row"> <section class="col-sm-6"> <img class="esh-app-footer-brand" src="~/images/brand_dark.png" /> </section> <section class="col-sm-6"> <img class="esh-app-footer-text hidden-xs" src="~/images/main_footer_text.png" width="335" height="26" alt="footer text image" /> </section> </article> </div> </footer> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>@ViewBag.Title - Catalog manager (MVC)</title> @Styles.Render("~/Content/css") @Scripts.Render("~/bundles/modernizr") </head> <body> <header class="navbar navbar-light navbar-static-top"> <div class="esh-header-brand"> <a href="@Url.Action("index", "catalog")"> <img src="~/images/brand.png" /> </a> </div> </header> <section class="esh-app-hero"> <div class="container esh-header"> <h1 class="esh-header-title" >Catalog Manager <span>(MVC)</span></h1> </div> </section> @RenderBody() <footer class="esh-app-footer"> <div class="container"> <article class="row"> <section class="col-sm-6"> <img class="esh-app-footer-brand" src="~/images/brand_dark.png" /> </section> <section class="col-sm-6"> <img class="esh-app-footer-text hidden-xs" src="~/images/main_footer_text.png" width="335" height="26" alt="footer text image" /> </section> </article> </div> </footer> @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/bootstrap") @RenderSection("scripts", required: false) </body> </html>
mit
C#
14fb21e8601316c410bef455afaaeae5a16fed48
add comment
zhouyongtao/my_aspnetmvc_learning,zhouyongtao/my_aspnetmvc_learning
my_aspnetmvc_learning/Controllers/ImageController.cs
my_aspnetmvc_learning/Controllers/ImageController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using NLog; namespace my_aspnetmvc_learning.Controllers { public class ImageController : Controller { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); // GET: Upload public ActionResult Index() { return View(); } /// <summary> /// 文件上传 /// </summary> /// <returns></returns> public ActionResult Upload() { for (var i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null) { logger.Info("FileName : " + file.FileName); file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName); } } return Json(new { success = true }, JsonRequestBehavior.AllowGet); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using NLog; namespace my_aspnetmvc_learning.Controllers { public class ImageController : Controller { private static readonly Logger logger = LogManager.GetCurrentClassLogger(); // GET: Upload public ActionResult Index() { return View(); } public ActionResult Upload() { for (var i = 0; i < Request.Files.Count; i++) { var file = Request.Files[i]; if (file != null) { logger.Info("FileName : " + file.FileName); file.SaveAs(AppDomain.CurrentDomain.BaseDirectory + "upload/" + file.FileName); } } return Json(new { success = true }, JsonRequestBehavior.AllowGet); } } }
mit
C#
3a2e44331276ecb9642a595a5cf4d0c640549d70
add FA5 classes to fix missing icons on leaflet maps pages (#31)
smbc-digital/iag-webapp,smbc-digital/iag-webapp,smbc-digital/iag-webapp
src/StockportWebapp/Views/Shared/SocialMediaLinks.cshtml
src/StockportWebapp/Views/Shared/SocialMediaLinks.cshtml
@model IEnumerable<StockportWebapp.Models.SocialMediaLink> @inject StockportWebapp.Config.BusinessId BusinessId <div class="footer-social-links"> @{ var nameOfSite = ""; } @if (BusinessId.ToString() == "stockportgov") { nameOfSite = "stockport council"; } else if (BusinessId.ToString() == "healthystockport") { nameOfSite = "healthy stockport "; } @foreach (var socialMediaLink in Model) { string socialMediaCSS = socialMediaLink.Icon.Replace("fa-", "icon-"); <a href="@socialMediaLink.Url"> <span class="visuallyhidden">link to @nameOfSite @socialMediaLink.Title </span> <div class="icon-bordered icon-bordered-fixed icon-container icon-twitter @socialMediaCSS"> <span class="fa fab fa-2x @socialMediaLink.Icon" aria-hidden="true"></span> </div> </a> } </div>
@model IEnumerable<StockportWebapp.Models.SocialMediaLink> @inject StockportWebapp.Config.BusinessId BusinessId <div class="footer-social-links"> @{ var nameOfSite = ""; } @if (BusinessId.ToString() == "stockportgov") { nameOfSite = "stockport council"; } else if (BusinessId.ToString() == "healthystockport") { nameOfSite = "healthy stockport "; } @foreach (var socialMediaLink in Model) { string socialMediaCSS = socialMediaLink.Icon.Replace("fa-", "icon-"); <a href="@socialMediaLink.Url"> <span class="visuallyhidden">link to @nameOfSite @socialMediaLink.Title </span> <div class="icon-bordered icon-bordered-fixed icon-container icon-twitter @socialMediaCSS"> <span class="fa fa-2x @socialMediaLink.Icon" aria-hidden="true"></span> </div> </a> } </div>
mit
C#
a90fa89fd87c079fdfc5cbd763e8c5cb395ca87c
Fix type mismatch forinterface IEtl and EtlXml
Seddryck/NBi,Seddryck/NBi
NBi.Xml/Items/EtlXml.cs
NBi.Xml/Items/EtlXml.cs
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; namespace NBi.Xml.Items { public class EtlXml: ExecutableXml, IEtl { [XmlAttribute("server")] public string Server { get; set; } [XmlAttribute("path")] public string Path { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("username")] public string UserName { get; set; } [XmlAttribute("password")] public string Password { get; set; } [XmlAttribute("catalog")] public string Catalog { get; set; } [XmlAttribute("folder")] public string Folder { get; set; } [XmlAttribute("project")] public string Project { get; set; } [XmlAttribute("bits-32")] public bool Is32Bits { get; set; } [XmlAttribute("timeout")] public int Timeout { get; set; } [XmlIgnore] public List<EtlParameter> Parameters { get { return InternalParameters.ToList<EtlParameter>(); } set { throw new NotImplementedException(); } } [XmlElement("parameter")] public List<EtlParameterXml> InternalParameters { get; set; } public EtlXml() { InternalParameters = new List<EtlParameterXml>(); } //public override string GetQuery() //{ // throw new NotImplementedException(); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; using NBi.Core.Etl; namespace NBi.Xml.Items { public class EtlXml: ExecutableXml, IEtl { [XmlAttribute("server")] public string Server { get; set; } [XmlAttribute("path")] public string Path { get; set; } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("username")] public string UserName { get; set; } [XmlAttribute("password")] public string Password { get; set; } [XmlAttribute("catalog")] public string Catalog { get; set; } [XmlAttribute("folder")] public string Folder { get; set; } [XmlAttribute("project")] public string Project { get; set; } [XmlAttribute("bits-32")] public bool Is32Bits { get; set; } [XmlAttribute("timeout")] public bool Timeout { get; set; } [XmlIgnore] public List<EtlParameter> Parameters { get { return InternalParameters.ToList<EtlParameter>(); } set { throw new NotImplementedException(); } } [XmlElement("parameter")] public List<EtlParameterXml> InternalParameters { get; set; } public EtlXml() { InternalParameters = new List<EtlParameterXml>(); } //public override string GetQuery() //{ // throw new NotImplementedException(); //} } }
apache-2.0
C#
b6ae2e8af6f270f6966db803822fe2ba7f766e22
Fix window scaling
DMagic1/KSP_Contract_Window
Source/ContractsWindow.Unity/Unity/CW_Scale.cs
Source/ContractsWindow.Unity/Unity/CW_Scale.cs
using System; using System.Collections.Generic; using ContractsWindow.Unity.Interfaces; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Unity { [RequireComponent(typeof(CanvasGroup), typeof(RectTransform))] public class CW_Scale : CW_Popup { [SerializeField] private Slider SliderScale = null; [SerializeField] private Toggle FontToggle = null; [SerializeField] private Toggle ScaleToggle = null; [SerializeField] private Text SliderValue = null; bool loaded; public void setScalar() { if (SliderScale == null || FontToggle == null || ScaleToggle == null || SliderValue == null) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; FontToggle.isOn = CW_Window.Window.Interface.LargeFont; ScaleToggle.isOn = CW_Window.Window.Interface.IgnoreScale; SliderValue.text = CW_Window.Window.Interface.Scale.ToString("P0"); SliderScale.value = CW_Window.Window.Interface.Scale * 10; FadeIn(); loaded = true; } public void SetLargeFont(bool isOn) { if (!loaded) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; CW_Window.Window.Interface.LargeFont = isOn; CW_Window.Window.UpdateFontSize(CW_Window.Window.gameObject, isOn ? 1 : -1); } public void IgnoreScale(bool isOn) { if (!loaded) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; CW_Window.Window.Interface.IgnoreScale = isOn; if (isOn) CW_Window.Window.transform.localScale /= CW_Window.Window.Interface.MasterScale; else CW_Window.Window.transform.localScale *= CW_Window.Window.Interface.MasterScale; } public void SliderValueChange(float value) { if (!loaded) return; float f = value / 10; if (SliderValue != null) SliderValue.text = f.ToString("P0"); } public void ApplyScale() { if (SliderScale == null) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; float f = SliderScale.value / 10; print(string.Format("[CW_UI] Local Scale: X = {0:N3} Y = {1:N3} Z = {2:N3}", CW_Window.Window.transform.localScale.x, CW_Window.Window.transform.localScale.y, CW_Window.Window.transform.localScale.z)); CW_Window.Window.Interface.Scale = f; Vector3 scale = new Vector3(1, 1, 1); if (CW_Window.Window.Interface.IgnoreScale) scale /= CW_Window.Window.Interface.MasterScale; CW_Window.Window.transform.localScale = scale * f; } public void Close() { if (CW_Window.Window == null) return; CW_Window.Window.FadePopup(this); } public override void ClosePopup() { gameObject.SetActive(false); Destroy(gameObject); } } }
using System; using System.Collections.Generic; using ContractsWindow.Unity.Interfaces; using UnityEngine; using UnityEngine.UI; namespace ContractsWindow.Unity.Unity { public class CW_Scale : CW_Popup { [SerializeField] private Slider SliderScale = null; [SerializeField] private Toggle FontToggle = null; [SerializeField] private Toggle ScaleToggle = null; [SerializeField] private Text SliderValue = null; bool loaded; public void setScalar() { if (SliderScale == null || FontToggle == null || ScaleToggle == null || SliderValue == null) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; FontToggle.isOn = CW_Window.Window.Interface.LargeFont; ScaleToggle.isOn = CW_Window.Window.Interface.IgnoreScale; SliderValue.text = CW_Window.Window.Interface.Scale.ToString("P0"); SliderScale.value = CW_Window.Window.Interface.Scale * 10; loaded = true; } public void SetLargeFont(bool isOn) { if (!loaded) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; CW_Window.Window.Interface.LargeFont = isOn; CW_Window.Window.UpdateFontSize(CW_Window.Window.gameObject, isOn ? 1 : -1); } public void IgnoreScale(bool isOn) { if (!loaded) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; CW_Window.Window.Interface.IgnoreScale = isOn; if (isOn) CW_Window.Window.transform.localScale /= CW_Window.Window.Interface.MasterScale; else CW_Window.Window.transform.localScale *= CW_Window.Window.Interface.MasterScale; } public void SliderValueChange(float value) { if (!loaded) return; if (CW_Window.Window == null) return; if (CW_Window.Window.Interface == null) return; float f = value / 10; if (SliderValue != null) SliderValue.text = f.ToString("P0"); CW_Window.Window.Interface.Scale = f; CW_Window.Window.transform.localScale *= f; } public void Close() { if (CW_Window.Window == null) return; CW_Window.Window.DestroyChild(gameObject); } } }
mit
C#
f1073f87ececdd90f8a0a11230a97dbca0ee5de4
optimize china provider
tinohager/Nager.Date,tinohager/Nager.Date,tinohager/Nager.Date
Src/Nager.Date/PublicHolidays/ChinaProvider.cs
Src/Nager.Date/PublicHolidays/ChinaProvider.cs
using Nager.Date.Contract; using Nager.Date.Model; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Nager.Date.PublicHolidays { public class ChinaProvider : IPublicHolidayProvider { public IEnumerable<PublicHoliday> Get(int year) { //TODO: Provider incomplete //Tomb-Sweeping-Day is invalid (5th solar term) //China //https://en.wikipedia.org/wiki/Public_holidays_in_China var countryCode = CountryCode.CN; var items = new List<PublicHoliday>(); var chineseCalendar = new ChineseLunisolarCalendar(); var leapMonth = chineseCalendar.GetLeapMonth(year); var springFestival = chineseCalendar.ToDateTime(year, this.MoveMonth(1, leapMonth), 1, 0, 0, 0, 0); var dragonBoatFestival = chineseCalendar.ToDateTime(year, this.MoveMonth(5, leapMonth), 5, 0, 0, 0, 0); var midAutumnFestival = chineseCalendar.ToDateTime(year, this.MoveMonth(8, leapMonth), 15, 0, 0, 0, 0); items.Add(new PublicHoliday(year, 1, 1, "元旦", "New Year's Day", countryCode)); items.Add(new PublicHoliday(springFestival, "春节", "Chinese New Year (Spring Festival)", countryCode)); items.Add(new PublicHoliday(year, 4, 5, "清明节", "Qingming Festival (Tomb-Sweeping Day)", countryCode)); //TODO: Date is not fixed, calculate from 5th solar term items.Add(new PublicHoliday(year, 5, 1, "劳动节", "Labour Day", countryCode)); items.Add(new PublicHoliday(dragonBoatFestival, "端午节", "Dragon Boat Festival", countryCode)); items.Add(new PublicHoliday(midAutumnFestival, "中秋节", "Mid-Autumn Festival", countryCode)); items.Add(new PublicHoliday(year, 10, 1, "国庆节", "National Day", countryCode)); return items.OrderBy(o => o.Date); } private int MoveMonth(int month, int leapMonth) { if (leapMonth == 0) { return month; } if (leapMonth < month) { return ++month; } return month; } } }
using Nager.Date.Contract; using Nager.Date.Model; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Nager.Date.PublicHolidays { public class ChinaProvider : IPublicHolidayProvider { public IEnumerable<PublicHoliday> Get(int year) { //TODO: Provider incomplete //Tomb-Sweeping-Day is invalid (5th solar term) //China //https://en.wikipedia.org/wiki/Public_holidays_in_China var countryCode = CountryCode.CN; var items = new List<PublicHoliday>(); var chineseCalendar = new ChineseLunisolarCalendar(); var leapMonth = chineseCalendar.GetLeapMonth(year); var springFestival = chineseCalendar.ToDateTime(year, this.MoveMonth(1, leapMonth), 1, 0, 0, 0, 0); var tombSweepimgDay = chineseCalendar.ToDateTime(year, this.MoveMonth(4, leapMonth), 5, 0, 0, 0, 0); var dragonBoatFestival = chineseCalendar.ToDateTime(year, this.MoveMonth(5, leapMonth), 5, 0, 0, 0, 0); var midAutumnFestival = chineseCalendar.ToDateTime(year, this.MoveMonth(8, leapMonth), 15, 0, 0, 0, 0); items.Add(new PublicHoliday(year, 1, 1, "元旦", "New Year's Day", countryCode)); items.Add(new PublicHoliday(springFestival, "春节", "Chinese New Year (Spring Festival)", countryCode)); items.Add(new PublicHoliday(tombSweepimgDay, "清明节", "Qingming Festival (Tomb-Sweeping Day)", countryCode)); items.Add(new PublicHoliday(year, 5, 1, "劳动节", "Labour Day", countryCode)); items.Add(new PublicHoliday(dragonBoatFestival, "端午节", "Dragon Boat Festival", countryCode)); items.Add(new PublicHoliday(midAutumnFestival, "中秋节", "Mid-Autumn Festival", countryCode)); items.Add(new PublicHoliday(year, 10, 1, "国庆节", "National Day", countryCode)); return items.OrderBy(o => o.Date); } private int MoveMonth(int month, int leapMonth) { if (leapMonth == 0) { return month; } if (leapMonth < month) { return ++month; } return month; } } }
mit
C#
6c871602664695637d26b93c62d315264d630b3a
add UpdateLayoutEx()
TakeAsh/cs-WpfUtility
WpfUtility/FrameworkElementExtensionMethods.cs
WpfUtility/FrameworkElementExtensionMethods.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Threading; using TakeAshUtility; namespace WpfUtility { public static class FrameworkElementExtensionMethods { public static T SafeTryFindResource<T>( this FrameworkElement element, object key, T defaultValue = default(T) ) { return element == null ? defaultValue : element.TryFindResource(key) .SafeToObject(defaultValue); } public static T SafeGetTag<T>( this FrameworkElement element, T defaultValue = default(T) ) { return element == null || element.Tag == null || !(element.Tag is T) ? defaultValue : (T)element.Tag; } /// <summary> /// Update the layout of the element according to its Width and Height. /// </summary> /// <param name="element">the FrameworkElement to be updated.</param> public static void UpdateLayoutEx(this FrameworkElement element) { element.Dispatcher.Invoke( DispatcherPriority.Render, new Action(() => { if (element == null || double.IsNaN(element.Width) || double.IsNaN(element.Height) || double.IsInfinity(element.Width) || double.IsInfinity(element.Height)) { return; } element.Measure(new Size(element.Width, element.Height)); element.Arrange(new Rect(0, 0, element.Width, element.Height)); element.UpdateLayout(); }) ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using TakeAshUtility; namespace WpfUtility { public static class FrameworkElementExtensionMethods { public static T SafeTryFindResource<T>( this FrameworkElement element, object key, T defaultValue = default(T) ) { return element == null ? defaultValue : element.TryFindResource(key) .SafeToObject(defaultValue); } public static T SafeGetTag<T>( this FrameworkElement element, T defaultValue = default(T) ) { return element == null || element.Tag == null || !(element.Tag is T) ? defaultValue : (T)element.Tag; } } }
mit
C#
ea4fe85ca2c3abe4b7b99335b71c56a7c344a9e0
Add several BigInteger before ulong.MaxValue
fredatgithub/PrimeSearch,fredatgithub/PrimeSearch,fredatgithub/PrimeSearch
PrimeSearch/Program.cs
PrimeSearch/Program.cs
using System; namespace PrimeSearch { using System.Numerics; internal class Program { private static void Main() { for (ulong i = 2; i < 50001; i++) { if (IsPrime(i)) { Console.WriteLine(i); } } BigInteger number = new BigInteger(ulong.MaxValue); if (IsPrime(number)) { Console.WriteLine(number + " est premier"); } else { Console.WriteLine(number + " n'est pas premier"); } for (BigInteger i = number - 50 ; i < number; i++) { if (IsPrime(i)) { Console.WriteLine(i + " est premier"); } else { Console.WriteLine(i + " n'est pas premier"); } } Console.WriteLine("Press a key to exit"); Console.ReadKey(); } private static bool IsPrime(ulong number) { if (number <= 1) { return false; } if (number == 2 || number == 3 || number == 5) { return true; } if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0) { return false; } for (ulong i = 6; i < Math.Sqrt(number); i = i + 2) { if (number % i == 0) { return false; } } return true; } private static bool IsPrime(BigInteger number) { if (number.IsEven) { return false; } if (number.Sign == 0 || number.Sign == -1) { return false; } if (number == 2 || number == 3 || number == 5) { return true; } if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0) { return false; } var tmpSqr = Math.Exp(BigInteger.Log(number) / 2); for (ulong i = 6; i < tmpSqr; i = i + 2) { if (number % i == 0) { return false; } } return true; } } }
using System; namespace PrimeSearch { using System.Data.SqlTypes; using System.Numerics; internal class Program { private static void Main() { for (ulong i = 2; i < 50001; i++) { if (IsPrime(i)) { Console.WriteLine(i); } } BigInteger number = new BigInteger(ulong.MaxValue); if (IsPrime(number)) { Console.WriteLine(number + " est premier"); } else { Console.WriteLine(number + " n'est pas premier"); } Console.WriteLine("Press a key to exit"); Console.ReadKey(); } private static bool IsPrime(ulong number) { if (number <= 1) { return false; } if (number == 2 || number == 3 || number == 5) { return true; } if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0) { return false; } for (ulong i = 6; i < Math.Sqrt(number); i = i + 2) { if (number % i == 0) { return false; } } return true; } private static bool IsPrime(BigInteger number) { if (number.IsEven) { return false; } if (number.Sign == 0 || number.Sign == -1) { return false; } if (number == 2 || number == 3 || number == 5) { return true; } if (number % 2 == 0 || number % 3 == 0 || number % 5 == 0) { return false; } var tmpSqr = Math.Exp(BigInteger.Log(number) / 2); for (ulong i = 6; i < tmpSqr; i = i + 2) { if (number % i == 0) { return false; } } return true; } } }
mit
C#
9a470c3638d470e346a39a0147f802268bcedd76
Fix bug in PMs where incoming PM would cause a crash
ethanmoffat/EndlessClient
EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs
EOLib/PacketHandlers/Chat/PrivateMessageHandler.cs
using System; using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Net; namespace EOLib.PacketHandlers.Chat { [AutoMappedType] public class PrivateMessageHandler : PlayerChatByNameBase { private readonly IChatRepository _chatRepository; public override PacketAction Action => PacketAction.Tell; public PrivateMessageHandler(IPlayerInfoProvider playerInfoProvider, IChatRepository chatRepository) : base(playerInfoProvider) { _chatRepository = chatRepository; } protected override void PostChat(string name, string message) { var localData = new ChatData(name, message, ChatIcon.Note, ChatColor.PM); var pmData = new ChatData(name, message, ChatIcon.Note); ChatTab whichPmTab; if (_chatRepository.PMTarget1 == null && _chatRepository.PMTarget2 == null) whichPmTab = ChatTab.Local; else whichPmTab = _chatRepository.PMTarget1.Equals(name, StringComparison.InvariantCultureIgnoreCase) ? ChatTab.Private1 : _chatRepository.PMTarget2.Equals(name, StringComparison.InvariantCultureIgnoreCase) ? ChatTab.Private2 : ChatTab.Local; _chatRepository.AllChat[ChatTab.Local].Add(localData); if (whichPmTab != ChatTab.Local) _chatRepository.AllChat[whichPmTab].Add(pmData); } } }
using System; using AutomaticTypeMapper; using EOLib.Domain.Chat; using EOLib.Domain.Login; using EOLib.Net; namespace EOLib.PacketHandlers.Chat { [AutoMappedType] public class PrivateMessageHandler : PlayerChatByNameBase { private readonly IChatRepository _chatRepository; public override PacketAction Action => PacketAction.Tell; public PrivateMessageHandler(IPlayerInfoProvider playerInfoProvider, IChatRepository chatRepository) : base(playerInfoProvider) { _chatRepository = chatRepository; } protected override void PostChat(string name, string message) { var localData = new ChatData(name, message, ChatIcon.Note, ChatColor.PM); var pmData = new ChatData(name, message, ChatIcon.Note); var whichPMTab = _chatRepository.PMTarget1.Equals(name, StringComparison.InvariantCultureIgnoreCase) ? ChatTab.Private1 : _chatRepository.PMTarget2.Equals(name, StringComparison.InvariantCultureIgnoreCase) ? ChatTab.Private2 : ChatTab.Local; _chatRepository.AllChat[ChatTab.Local].Add(localData); if (whichPMTab != ChatTab.Local) _chatRepository.AllChat[whichPMTab].Add(pmData); } } }
mit
C#
24459579a61677f1d7f2238dcbef9e2e5e8f5e7f
Clean up LightDevice example
NZSmartie/OICNet
samples/OICNet.Server.Example/Devices/LightDevice.cs
samples/OICNet.Server.Example/Devices/LightDevice.cs
using System; using OICNet.ResourceTypes; using System.ComponentModel; using Microsoft.Extensions.Logging; namespace OICNet.Server.Example.Devices { public class LightDevice : OicDevice { private readonly ILogger<LightDevice> _logger; [OicResource(OicResourcePolicies.Discoverable | OicResourcePolicies.Secure)] public LightBrightness Brightness { get; } = new LightBrightness { RelativeUri = "/light/brightness", }; [OicResource(OicResourcePolicies.Discoverable | OicResourcePolicies.Secure)] public SwitchBinary Switch { get; } = new SwitchBinary { RelativeUri = "/light/switch", }; public LightDevice(ILogger<LightDevice> logger) : base("oic.d.light") { _logger = logger; Brightness.PropertyChanged += OnResourceChanged; Switch.PropertyChanged += OnResourceChanged; } private void OnResourceChanged(object sender, PropertyChangedEventArgs e) { if(sender == Switch && e.PropertyName == nameof(Switch.Value)) _logger.LogInformation($"Switch changed to {Switch.Value}"); if (sender == Brightness && e.PropertyName == nameof(Brightness.Brightness)) _logger.LogInformation($"Brightness changed to {Brightness.Brightness}"); } } }
using System; using OICNet.ResourceTypes; using System.ComponentModel; using Microsoft.Extensions.Logging; namespace OICNet.Server.Example.Devices { public class LightDevice : OicDevice { private readonly ILogger<LightDevice> _logger; [OicResource(OicResourcePolicies.Discoverable | OicResourcePolicies.Secure)] public LightBrightness Brightness { get; } = new LightBrightness { RelativeUri = "/light/brightness", }; [OicResource(OicResourcePolicies.Discoverable | OicResourcePolicies.Secure)] public SwitchBinary Switch { get; } = new SwitchBinary { RelativeUri = "/light/switch", }; public LightDevice(ILogger<LightDevice> logger) : base("oic.d.light") { _logger = logger; Brightness.PropertyChanged += OnResourceChanged; Switch.PropertyChanged += OnResourceChanged; } private void OnResourceChanged(object sender, PropertyChangedEventArgs e) { if(sender == Switch && e.PropertyName == nameof(Switch.Value)) { _logger.LogInformation($"Switch changed to {Switch.Value}"); } else if (sender == Brightness && e.PropertyName == nameof(Brightness.Brightness)) { _logger.LogInformation($"Brightness changed to {Brightness.Brightness}"); } } } }
apache-2.0
C#
7e3a710a9e96133e7521d58b673387b8522dd44d
Update `LogJsonConfigPathEventHandler` to handle `AtataContextInitCompletedEvent`
atata-framework/atata-configuration-json
src/Atata.Configuration.Json/EventHandlers/LogJsonConfigPathEventHandler.cs
src/Atata.Configuration.Json/EventHandlers/LogJsonConfigPathEventHandler.cs
namespace Atata.Configuration.Json { internal sealed class LogJsonConfigPathEventHandler : IEventHandler<AtataContextInitCompletedEvent> { private readonly string _configPath; internal LogJsonConfigPathEventHandler(string configPath) { _configPath = configPath; } public void Handle(AtataContextInitCompletedEvent eventData, AtataContext context) => context.Log.Trace($"Use: \"{_configPath}\" config"); } }
namespace Atata.Configuration.Json { internal sealed class LogJsonConfigPathEventHandler : IEventHandler<AtataContextInitEvent> { private readonly string _configPath; internal LogJsonConfigPathEventHandler(string configPath) { _configPath = configPath; } public void Handle(AtataContextInitEvent eventData, AtataContext context) => context.Log.Trace($"Use: \"{_configPath}\" config"); } }
apache-2.0
C#
11414602dbf1795021e8d9a84603e52b19d083ba
Add "partial" to MarshalAsAttribute (dotnet/coreclr#24014)
wtgodbe/corefx,wtgodbe/corefx,wtgodbe/corefx,ViktorHofer/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,ViktorHofer/corefx,ViktorHofer/corefx,shimingsg/corefx,ericstj/corefx,wtgodbe/corefx,wtgodbe/corefx,shimingsg/corefx,shimingsg/corefx,wtgodbe/corefx,ericstj/corefx,BrennanConroy/corefx,ViktorHofer/corefx,shimingsg/corefx,BrennanConroy/corefx,shimingsg/corefx,ericstj/corefx,ericstj/corefx,ViktorHofer/corefx,BrennanConroy/corefx
src/Common/src/CoreLib/System/Runtime/InteropServices/MarshalAsAttribute.cs
src/Common/src/CoreLib/System/Runtime/InteropServices/MarshalAsAttribute.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)] public sealed partial class MarshalAsAttribute : Attribute { public MarshalAsAttribute(UnmanagedType unmanagedType) { Value = unmanagedType; } public MarshalAsAttribute(short unmanagedType) { Value = (UnmanagedType)unmanagedType; } public UnmanagedType Value { get; } // Fields used with SubType = SafeArray. public VarEnum SafeArraySubType; public Type SafeArrayUserDefinedSubType; // Field used with iid_is attribute (interface pointers). public int IidParameterIndex; // Fields used with SubType = ByValArray and LPArray. // Array size = parameter(PI) * PM + C public UnmanagedType ArraySubType; public short SizeParamIndex; // param index PI public int SizeConst; // constant C // Fields used with SubType = CustomMarshaler public string MarshalType; // Name of marshaler class public Type MarshalTypeRef; // Type of marshaler class public string MarshalCookie; // cookie to pass to marshaler } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Runtime.InteropServices { [AttributeUsage(AttributeTargets.Parameter | AttributeTargets.Field | AttributeTargets.ReturnValue, Inherited = false)] public sealed class MarshalAsAttribute : Attribute { public MarshalAsAttribute(UnmanagedType unmanagedType) { Value = unmanagedType; } public MarshalAsAttribute(short unmanagedType) { Value = (UnmanagedType)unmanagedType; } public UnmanagedType Value { get; } // Fields used with SubType = SafeArray. public VarEnum SafeArraySubType; public Type SafeArrayUserDefinedSubType; // Field used with iid_is attribute (interface pointers). public int IidParameterIndex; // Fields used with SubType = ByValArray and LPArray. // Array size = parameter(PI) * PM + C public UnmanagedType ArraySubType; public short SizeParamIndex; // param index PI public int SizeConst; // constant C // Fields used with SubType = CustomMarshaler public string MarshalType; // Name of marshaler class public Type MarshalTypeRef; // Type of marshaler class public string MarshalCookie; // cookie to pass to marshaler } }
mit
C#
2e818be9f93014eed59e23a3014524c4a2c90038
Fix initialize test
genlu/roslyn,KevinRansom/roslyn,stephentoub/roslyn,tmat/roslyn,tannergooding/roslyn,KirillOsenkov/roslyn,weltkante/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,reaction1989/roslyn,jmarolf/roslyn,abock/roslyn,heejaechang/roslyn,eriawan/roslyn,sharwell/roslyn,heejaechang/roslyn,davkean/roslyn,panopticoncentral/roslyn,abock/roslyn,wvdd007/roslyn,reaction1989/roslyn,diryboy/roslyn,CyrusNajmabadi/roslyn,eriawan/roslyn,physhi/roslyn,brettfo/roslyn,diryboy/roslyn,mavasani/roslyn,jmarolf/roslyn,dotnet/roslyn,diryboy/roslyn,jmarolf/roslyn,reaction1989/roslyn,davkean/roslyn,genlu/roslyn,eriawan/roslyn,AlekseyTs/roslyn,KevinRansom/roslyn,mavasani/roslyn,davkean/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,physhi/roslyn,weltkante/roslyn,KevinRansom/roslyn,wvdd007/roslyn,AmadeusW/roslyn,genlu/roslyn,mgoertz-msft/roslyn,gafter/roslyn,agocke/roslyn,stephentoub/roslyn,aelij/roslyn,tmat/roslyn,gafter/roslyn,KirillOsenkov/roslyn,tannergooding/roslyn,heejaechang/roslyn,abock/roslyn,shyamnamboodiripad/roslyn,tannergooding/roslyn,jasonmalinowski/roslyn,physhi/roslyn,dotnet/roslyn,tmat/roslyn,jasonmalinowski/roslyn,panopticoncentral/roslyn,aelij/roslyn,mgoertz-msft/roslyn,KirillOsenkov/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,sharwell/roslyn,sharwell/roslyn,agocke/roslyn,shyamnamboodiripad/roslyn,panopticoncentral/roslyn,aelij/roslyn,brettfo/roslyn,weltkante/roslyn,wvdd007/roslyn,agocke/roslyn,bartdesmet/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,stephentoub/roslyn,brettfo/roslyn,gafter/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,mgoertz-msft/roslyn,bartdesmet/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn
src/Features/LanguageServer/ProtocolUnitTests/Initialize/InitializeTests.cs
src/Features/LanguageServer/ProtocolUnitTests/Initialize/InitializeTests.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.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Initialize { public class InitializeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestInitializeAsync() { var (solution, _) = CreateTestSolution(string.Empty); var results = await RunInitializeAsync(solution, new LSP.InitializeParams()); AssertServerCapabilities(results.Capabilities); } private static async Task<LSP.InitializeResult> RunInitializeAsync(Solution solution, LSP.InitializeParams request) => await GetLanguageServer(solution).InitializeAsync(solution, request, new LSP.ClientCapabilities(), CancellationToken.None); private static void AssertServerCapabilities(LSP.ServerCapabilities actual) { Assert.True(actual.DefinitionProvider); Assert.True(actual.ImplementationProvider); Assert.True(actual.HoverProvider); Assert.True(actual.DocumentSymbolProvider); Assert.True(actual.WorkspaceSymbolProvider); Assert.True(actual.DocumentFormattingProvider); Assert.True(actual.DocumentRangeFormattingProvider); Assert.True(actual.DocumentHighlightProvider); Assert.True(actual.CompletionProvider.ResolveProvider); Assert.Equal(new[] { "." }, actual.CompletionProvider.TriggerCharacters); Assert.Equal(new[] { "(", "," }, actual.SignatureHelpProvider.TriggerCharacters); Assert.Equal("}", actual.DocumentOnTypeFormattingProvider.FirstTriggerCharacter); Assert.Equal(new[] { ";", "\n" }, actual.DocumentOnTypeFormattingProvider.MoreTriggerCharacter); } } }
// 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.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Initialize { public class InitializeTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestInitializeAsync() { var (solution, _) = CreateTestSolution(string.Empty); var results = await RunInitializeAsync(solution, new LSP.InitializeParams()); AssertServerCapabilities(results.Capabilities); } private static async Task<LSP.InitializeResult> RunInitializeAsync(Solution solution, LSP.InitializeParams request) => await GetLanguageServer(solution).InitializeAsync(solution, request, new LSP.ClientCapabilities(), CancellationToken.None); private static void AssertServerCapabilities(LSP.ServerCapabilities actual) { Assert.True(actual.DefinitionProvider); Assert.True(actual.ReferencesProvider); Assert.True(actual.ImplementationProvider); Assert.True(actual.HoverProvider); Assert.True(actual.CodeActionProvider); Assert.True(actual.DocumentSymbolProvider); Assert.True(actual.WorkspaceSymbolProvider); Assert.True(actual.DocumentFormattingProvider); Assert.True(actual.DocumentRangeFormattingProvider); Assert.True(actual.DocumentHighlightProvider); Assert.True(actual.RenameProvider); Assert.True(actual.CompletionProvider.ResolveProvider); Assert.Equal(new[] { "." }, actual.CompletionProvider.TriggerCharacters); Assert.Equal(new[] { "(", "," }, actual.SignatureHelpProvider.TriggerCharacters); Assert.Equal("}", actual.DocumentOnTypeFormattingProvider.FirstTriggerCharacter); Assert.Equal(new[] { ";", "\n" }, actual.DocumentOnTypeFormattingProvider.MoreTriggerCharacter); Assert.NotNull(actual.ExecuteCommandProvider); } } }
mit
C#
f7afa80cb4eda9a2f7ce5644fe8dffe25df589ab
Remove unused imports
crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin,crdschurch/crds-signin-checkin
SignInCheckIn/SignInCheckIn/Util/HttpAuthResult.cs
SignInCheckIn/SignInCheckIn/Util/HttpAuthResult.cs
using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SignInCheckIn.Util { public class HttpAuthResult : IHttpActionResult { private readonly string _token; private readonly string _refreshToken; private readonly IHttpActionResult _result; public const string AuthorizationTokenHeaderName = "Authorization"; public const string RefreshTokenHeaderName = "RefreshToken"; public HttpAuthResult(IHttpActionResult result, string token, string refreshToken) { _result = result; _token = token; _refreshToken = refreshToken; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { return Task.Run(() => { var response = _result.ExecuteAsync(cancellationToken).Result; response.Headers.Add("Access-Control-Expose-Headers", new [] { AuthorizationTokenHeaderName , RefreshTokenHeaderName }); response.Headers.Add(AuthorizationTokenHeaderName, _token); response.Headers.Add(RefreshTokenHeaderName, _refreshToken); return response; }, cancellationToken); } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace SignInCheckIn.Util { public class HttpAuthResult : IHttpActionResult { private readonly string _token; private readonly string _refreshToken; private readonly IHttpActionResult _result; public const string AuthorizationTokenHeaderName = "Authorization"; public const string RefreshTokenHeaderName = "RefreshToken"; public HttpAuthResult(IHttpActionResult result, string token, string refreshToken) { _result = result; _token = token; _refreshToken = refreshToken; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { return Task.Run(() => { var response = _result.ExecuteAsync(cancellationToken).Result; response.Headers.Add("Access-Control-Expose-Headers", new [] { AuthorizationTokenHeaderName , RefreshTokenHeaderName }); response.Headers.Add(AuthorizationTokenHeaderName, _token); response.Headers.Add(RefreshTokenHeaderName, _refreshToken); return response; }, cancellationToken); } } }
bsd-2-clause
C#
7a68546be08a9db10a287be00d01ded31f1961dd
Make Megavoice output number files for each book from 001
sillsdev/hearthis,sillsdev/hearthis,sillsdev/hearthis
src/HearThis/Publishing/MegaVoicePublishingMethod.cs
src/HearThis/Publishing/MegaVoicePublishingMethod.cs
using System.Collections.Generic; using System.IO; using HearThis.Script; using Palaso.Progress; namespace HearThis.Publishing { /// <summary> /// From the nscribe manual: /// All audio content that you wish to use with the nScribe software must be in the form of mono, 16 bit, 44.1 khz, WAV (.wav) files. /// If you plan to use Auto-Arrange Nested function (see next section), make sure to give the audio tag file the same name as the tier folder name and add the three-letter prefix TAG. For example, for a tier named Luke create an audio tag named TAGLuke.wav. See Appendix B for more information. /// </summary> public class MegaVoicePublishingMethod : IPublishingMethod { private BibleStats _statistics; private IAudioEncoder _encoder; Dictionary<string, int> filesOutput = new Dictionary<string, int>(); public MegaVoicePublishingMethod() { _statistics = new BibleStats(); _encoder = new WavEncoder(); } public string GetFilePathWithoutExtension(string rootFolderPath, string bookName, int chapterNumber) { // Megavoice requires files numbered sequentially from 001 for each book. int fileNumber; filesOutput.TryGetValue(bookName, out fileNumber); // if not found it will be zero. fileNumber++; filesOutput[bookName] = fileNumber; string bookIndex = (1 + _statistics.GetBookNumber(bookName)).ToString("000"); string chapterIndex = fileNumber.ToString("000"); string fileName = string.Format("{0}-{1}", bookName, chapterIndex); var dir = CreateDirectoryIfNeeded(rootFolderPath, GetFolderName(bookName, bookIndex)); return Path.Combine(dir, fileName); } private string GetFolderName(string bookName, string bookIndex) { return string.Format("{0}-{1}", bookName, bookIndex); } public virtual string GetRootDirectoryName() { return "MegaVoice"; } public void PublishChapter(string rootPath, string bookName, int chapterNumber, string pathToIncomingChapterWav, IProgress progress) { var outputPath = GetFilePathWithoutExtension(rootPath, bookName, chapterNumber); _encoder.Encode(pathToIncomingChapterWav, outputPath, progress); } private string CreateDirectoryIfNeeded(string parent, string child) { var path = Path.Combine(parent, child); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } } }
using System.IO; using HearThis.Script; using Palaso.Progress; namespace HearThis.Publishing { /// <summary> /// From the nscribe manual: /// All audio content that you wish to use with the nScribe software must be in the form of mono, 16 bit, 44.1 khz, WAV (.wav) files. /// If you plan to use Auto-Arrange Nested function (see next section), make sure to give the audio tag file the same name as the tier folder name and add the three-letter prefix TAG. For example, for a tier named Luke create an audio tag named TAGLuke.wav. See Appendix B for more information. /// </summary> public class MegaVoicePublishingMethod : IPublishingMethod { private BibleStats _statistics; private IAudioEncoder _encoder; public MegaVoicePublishingMethod() { _statistics = new BibleStats(); _encoder = new WavEncoder(); } public string GetFilePathWithoutExtension(string rootFolderPath, string bookName, int chapterNumber) { string bookIndex = (1 + _statistics.GetBookNumber(bookName)).ToString("000"); string chapterIndex = chapterNumber.ToString("000"); string fileName = string.Format("{0}-{1}", bookName, chapterIndex); var dir = CreateDirectoryIfNeeded(rootFolderPath, GetFolderName(bookName, bookIndex)); return Path.Combine(dir, fileName); } private string GetFolderName(string bookName, string bookIndex) { return string.Format("{0}-{1}", bookName, bookIndex); } public virtual string GetRootDirectoryName() { return "MegaVoice"; } public void PublishChapter(string rootPath, string bookName, int chapterNumber, string pathToIncomingChapterWav, IProgress progress) { var outputPath = GetFilePathWithoutExtension(rootPath, bookName, chapterNumber); _encoder.Encode(pathToIncomingChapterWav, outputPath, progress); } private string CreateDirectoryIfNeeded(string parent, string child) { var path = Path.Combine(parent, child); if (!Directory.Exists(path)) Directory.CreateDirectory(path); return path; } } }
mit
C#
15aff34ff88bb821734c6518607c7ef35b28487d
Scrub id_token_hint from EndSession request log (#2917)
IdentityServer/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4,IdentityServer/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,MienDev/IdentityServer4,IdentityServer/IdentityServer4
src/Logging/Models/EndSessionRequestValidationLog.cs
src/Logging/Models/EndSessionRequestValidationLog.cs
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; using IdentityModel; using IdentityServer4.Extensions; using IdentityServer4.Validation; namespace IdentityServer4.Logging.Models { internal class EndSessionRequestValidationLog { public string ClientId { get; set; } public string ClientName { get; set; } public string SubjectId { get; set; } public string PostLogOutUri { get; set; } public string State { get; set; } public Dictionary<string, string> Raw { get; set; } public EndSessionRequestValidationLog(ValidatedEndSessionRequest request) { Raw = request.Raw.ToScrubbedDictionary(OidcConstants.EndSessionRequest.IdTokenHint); SubjectId = "unknown"; if (request.Subject != null) { var subjectClaim = request.Subject.FindFirst(JwtClaimTypes.Subject); if (subjectClaim != null) { SubjectId = subjectClaim.Value; } } if (request.Client != null) { ClientId = request.Client.ClientId; ClientName = request.Client.ClientName; } PostLogOutUri = request.PostLogOutUri; State = request.State; } public override string ToString() { return LogSerializer.Serialize(this); } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System.Collections.Generic; using IdentityModel; using IdentityServer4.Extensions; using IdentityServer4.Validation; namespace IdentityServer4.Logging.Models { internal class EndSessionRequestValidationLog { public string ClientId { get; set; } public string ClientName { get; set; } public string SubjectId { get; set; } public string PostLogOutUri { get; set; } public string State { get; set; } public Dictionary<string, string> Raw { get; set; } public EndSessionRequestValidationLog(ValidatedEndSessionRequest request) { Raw = request.Raw.ToDictionary(); SubjectId = "unknown"; if (request.Subject != null) { var subjectClaim = request.Subject.FindFirst(JwtClaimTypes.Subject); if (subjectClaim != null) { SubjectId = subjectClaim.Value; } } if (request.Client != null) { ClientId = request.Client.ClientId; ClientName = request.Client.ClientName; } PostLogOutUri = request.PostLogOutUri; State = request.State; } public override string ToString() { return LogSerializer.Serialize(this); } } }
apache-2.0
C#
835935201e081fef38131589411993a963c8afd2
Change main to use test003
ilovepi/Compiler,ilovepi/Compiler
compiler/Program/Program.cs
compiler/Program/Program.cs
using System; using compiler.frontend; namespace Program { class Program { //TODO: adjust main to use the parser when it is complete static void Main(string[] args) { // using (Lexer l = new Lexer(@"../../testdata/big.txt")) // { // Token t; // do // { // t = l.GetNextToken(); // Console.WriteLine(TokenHelper.PrintToken(t)); // // } while (t != Token.EOF); // // // necessary when testing on windows with visual studio // //Console.WriteLine("Press 'enter' to exit ...."); // //Console.ReadLine(); // } using (Parser p = new Parser(@"../../testdata/test003.txt")) { p.Parse(); p.FlowCfg.GenerateDOTOutput(); using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt")) { file.WriteLine( p.FlowCfg.DOTOutput); } } } } }
using System; using compiler.frontend; namespace Program { class Program { //TODO: adjust main to use the parser when it is complete static void Main(string[] args) { // using (Lexer l = new Lexer(@"../../testdata/big.txt")) // { // Token t; // do // { // t = l.GetNextToken(); // Console.WriteLine(TokenHelper.PrintToken(t)); // // } while (t != Token.EOF); // // // necessary when testing on windows with visual studio // //Console.WriteLine("Press 'enter' to exit ...."); // //Console.ReadLine(); // } using (Parser p = new Parser(@"../../testdata/test002.txt")) { p.Parse(); p.FlowCfg.GenerateDOTOutput(); using (System.IO.StreamWriter file = new System.IO.StreamWriter("graph.txt")) { file.WriteLine( p.FlowCfg.DOTOutput); } } } } }
mit
C#
8bf602d960752fd61d7dafbddd2bffa062331797
add link to area
OdeToCode/AddFeatureFolders
sample/WebApplication/Features/Shared/_Layout.cshtml
sample/WebApplication/Features/Shared/_Layout.cshtml
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> @await Component.InvokeAsync("MainMenu") @RenderBody() <footer> Footer rendered by _Layout<br /> <a href="/">Home</a><br/> <a href="/Foo/Home">Feature: Foo</a><br/> <a href="/Bar/Home">Feature: Bar</a><br /> <a href="/Administration/Overview">Area Administration: Overview</a> </footer> </body> </html>
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> @await Component.InvokeAsync("MainMenu") @RenderBody() <footer> Footer rendered by _Layout<br /> <a href="/">Home</a><br/> <a href="/Foo/Home">Feature: Foo</a><br/> <a href="/Bar/Home">Feature: Bar</a> </footer> </body> </html>
mit
C#
0d6679a468852b955a01fec2d43b3980f1157503
Fix GeocodingService URI selection
ericnewton76/gmaps-api-net
src/Google.Maps/Geocoding/GeocodingService.cs
src/Google.Maps/Geocoding/GeocodingService.cs
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Globalization; namespace Google.Maps.Geocoding { /// <summary> /// Provides a direct way to access a geocoder via an HTTP request. /// Additionally, the service allows you to perform the converse operation /// (turning coordinates into addresses); this process is known as /// "reverse geocoding." /// </summary> public class GeocodingService { #region Http/Https Uris and Constructors public static readonly Uri HttpsUri = new Uri("https://maps.google.com/maps/api/geocode/"); public static readonly Uri HttpUri = new Uri("http://maps.google.com/maps/api/geocode/"); public Uri BaseUri { get; set; } public GeocodingService() : this(HttpsUri) { } public GeocodingService(Uri baseUri) { this.BaseUri = baseUri; } #endregion /// <summary> /// Sends the specified request to the Google Maps Geocoding web /// service and parses the response as an GeocodingResponse /// object. /// </summary> /// <param name="request"></param> /// <returns></returns> public GeocodeResponse GetResponse(GeocodingRequest request) { var url = new Uri(this.BaseUri, request.ToUri()); return Internal.Http.Get(url).As<GeocodeResponse>(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Text; using System.Globalization; namespace Google.Maps.Geocoding { /// <summary> /// Provides a direct way to access a geocoder via an HTTP request. /// Additionally, the service allows you to perform the converse operation /// (turning coordinates into addresses); this process is known as /// "reverse geocoding." /// </summary> public class GeocodingService { #region Http/Https Uris and Constructors public static readonly Uri HttpsUri = new Uri("https://maps.google.com/maps/api/geocode/"); public static readonly Uri HttpUri = new Uri("http://maps.google.com/maps/api/geocode/"); public Uri BaseUri { get; set; } public GeocodingService() : this(HttpUri) { } public GeocodingService(Uri baseUri) { this.BaseUri = HttpsUri; } #endregion /// <summary> /// Sends the specified request to the Google Maps Geocoding web /// service and parses the response as an GeocodingResponse /// object. /// </summary> /// <param name="request"></param> /// <returns></returns> public GeocodeResponse GetResponse(GeocodingRequest request) { var url = new Uri(this.BaseUri, request.ToUri()); return Internal.Http.Get(url).As<GeocodeResponse>(); } } }
apache-2.0
C#
feaa26744c6d4e3fe68092c5a4288c6851676226
Update MvxFormsApp.cs
Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins,Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins
FormsPresenters/Core/MvxFormsApp.cs
FormsPresenters/Core/MvxFormsApp.cs
// MvxFormsApp.cs // 2015 (c) Copyright Cheesebaron. http://ostebaronen.dk // Cheesebaron.MvxPlugins.FormsPresenters is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Tomasz Cielecki, @cheesebaron, mvxplugins@ostebaronen.dk  using System; using Xamarin.Forms; namespace Cheesebaron.MvxPlugins.FormsPresenters.Core { public class MvxFormsApp : Application { public event EventHandler Start; public event EventHandler Sleep; public event EventHandler Resume; protected override void OnStart() { var handler = Start; if (handler != null) handler(this, EventArgs.Empty); } protected override void OnSleep() { var handler = Sleep; if (handler != null) handler(this, EventArgs.Empty); } protected override void OnResume() { var handler = Resume; if (handler != null) handler(this, EventArgs.Empty); } } }
// MvxFormsApp.cs // 2015 (c) Copyright Cheesebaron. http://ostebaronen.dk // Cheesebaron.MvxPlugins.FormsPresenters is licensed using Microsoft Public License (Ms-PL) // Contributions and inspirations noted in readme.md and license.txt // // Project Lead - Tomasz Cielecii, @cheesebaron, mvxplugins@ostebaronen.dk  using System; using Xamarin.Forms; namespace Cheesebaron.MvxPlugins.FormsPresenters.Core { public class MvxFormsApp : Application { public event EventHandler Start; public event EventHandler Sleep; public event EventHandler Resume; protected override void OnStart() { var handler = Start; if (handler != null) handler(this, EventArgs.Empty); } protected override void OnSleep() { var handler = Sleep; if (handler != null) handler(this, EventArgs.Empty); } protected override void OnResume() { var handler = Resume; if (handler != null) handler(this, EventArgs.Empty); } } }
apache-2.0
C#
fb9a54be2f7913fac00903f1063e69148a44c59c
Update to use the new API.
jmptrader/manos,jacksonh/manos,jacksonh/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,jmptrader/manos,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos
sample/mango-project/MangoProject.cs
sample/mango-project/MangoProject.cs
using Mango; using Mango.Templates.Minge; namespace MangoProject { // // A mango application is made of MangoModules and MangoApps // There really isn't any difference between a Module and an App // except that the server will load the MangoApp first. A mango // application can only have one MangoApp, but as many MangoModules // as you want. // public class MangoProject : MangoApp { // // This method is called when the server first starts, // public override void OnStartup () { // // Routing can be done by using the Get/Head/Post/Put/Delete/Trace // methods. They take a regular expression and either a method // or another module to hand off processing to. // // The regular expressions come after the method/module, because // Mango uses params to allow you to easily register multiple // regexs to the same handler // Get (Home, "Home"); // // The Route method will hand off all HTTP methods to the supplied // method or module // // Route (new AdminModule (), "Admin/"); } // // Handlers can be registered with attributes too // [Get ("About")] public static void About (MangoContext ctx) { // // Templates use property lookup, so you can pass in // a strongly typed object, or you can use an anonymous // type. // RenderTemplate (ctx, "about.html", new { Title = "About", Message = "Hey, I am the about page.", }); } public static void Home (MangoContext ctx) { RenderTemplate (ctx, "home.html", new { Title = "Home", Message = "Welcome to the Mango-Project." }); } } // // Normally a different module would be in a different file, but for // demo porpoises we'll do it here. // public class AdminModule : MangoModule { public override void OnStartup () { } /// blah, blah, blah } }
using Mango; using Mango.Templates.Minge; namespace MangoProject { // // A mango application is made of MangoModules and MangoApps // There really isn't any difference between a Module and an App // except that the server will load the MangoApp first. A mango // application can only have one MangoApp, but as many MangoModules // as you want. // public class MangoProject : MangoApp { // // This method is called when the server first starts, // public override void OnStartup () { // // Routing can be done by using the Get/Head/Post/Put/Delete/Trace // methods. They take a regular expression and either a method // or another module to hand off processing to. // // The regular expressions come after the method/module, because // Mango uses params to allow you to easily register multiple // regexs to the same handler // Get ("Home", Home); // // The Route method will hand off all HTTP methods to the supplied // method or module // // Route (new AdminModule (), "Admin/"); } // // Handlers can be registered with attributes too // [Get ("About")] public static void About (MangoContext ctx) { // // Templates use property lookup, so you can pass in // a strongly typed object, or you can use an anonymous // type. // RenderTemplate (ctx, "about.html", new { Title = "About", Message = "Hey, I am the about page.", }); } public static void Home (MangoContext ctx) { RenderTemplate (ctx, "home.html", new { Title = "Home", Message = "Welcome to the Mango-Project." }); } } // // Normally a different module would be in a different file, but for // demo porpoises we'll do it here. // public class AdminModule : MangoModule { public override void OnStartup () { } /// blah, blah, blah } }
mit
C#
a9660a5fe7290174378834a203e93204de0baa06
fix ProcessExecutionExtensions
signumsoftware/framework,AlejandroCano/extensions,signumsoftware/extensions,MehdyKarimpour/extensions,MehdyKarimpour/extensions,signumsoftware/framework,AlejandroCano/extensions,signumsoftware/extensions
Signum.Windows.Extensions.UIAutomation/Proxies/ProcessExecutionExtensions.cs
Signum.Windows.Extensions.UIAutomation/Proxies/ProcessExecutionExtensions.cs
using Signum.Entities; using Signum.Entities.Basics; using Signum.Entities.Processes; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Signum.Windows.UIAutomation { public static class ProcessExecutionExtensions { static int DefaultTimeout = 20 * 1000; public static void PlayAndWait(this NormalWindowProxy<ProcessDN> pe, Func<string> actionDescription = null, int? timeout = null) { using (pe) { pe.Execute(ProcessOperation.Execute); pe.Element.Wait(() => pe.ValueLineValue(pe2 => pe2.State) == ProcessState.Finished, () => "{0}, result state is {1}".Formato((actionDescription != null ? actionDescription() : "Waiting for process to finish"), pe.ValueLineValue(pe2 => pe2.State)), timeout ?? DefaultTimeout); } } public static void ConstructProcessAndPlay<T>(this NormalWindowProxy<T> normalWnindow, Enum processOperation, int? timeout = null) where T : ModifiableEntity { var pe = normalWnindow.ConstructFrom<ProcessDN>(processOperation); pe.PlayAndWait(() => "Waiting for process after {0} to finish".Formato(OperationDN.UniqueKey(processOperation))); } } }
using Signum.Entities; using Signum.Entities.Basics; using Signum.Entities.Processes; using Signum.Utilities; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Signum.Windows.UIAutomation { public static class ProcessExecutionExtensions { static int DefaultTimeout = 20 * 1000; public static void PlayAndWait(this NormalWindowProxy<ProcessExecutionDN> pe, Func<string> actionDescription = null, int? timeout = null) { using (pe) { pe.Execute(ProcessOperation.Execute); pe.Element.Wait(() => pe.ValueLineValue(pe2 => pe2.State) == ProcessState.Finished, () => "{0}, result state is {1}".Formato((actionDescription != null ? actionDescription() : "Waiting for process to finish"), pe.ValueLineValue(pe2 => pe2.State)), timeout ?? DefaultTimeout); } } public static void ConstructProcessAndPlay<T>(this NormalWindowProxy<T> normalWnindow, Enum processOperation, int? timeout = null) where T : ModifiableEntity { var pe = normalWnindow.ConstructFrom<ProcessExecutionDN>(processOperation); pe.PlayAndWait(() => "Waiting for process after {0} to finish".Formato(OperationDN.UniqueKey(processOperation))); } } }
mit
C#
b2b988b3e7a97f892420dffe61c4f919a2b4a3d8
Move GetByIdIndexer to centralized GetKeyParameters implementation
tonycrider/Vipr,ysanghi/Vipr,tonycrider/Vipr,Microsoft/Vipr,v-am/Vipr,MSOpenTech/Vipr
src/Writers/CSharpWriter/CollectionGetByIdIndexer.cs
src/Writers/CSharpWriter/CollectionGetByIdIndexer.cs
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Vipr.Core; using Vipr.Core.CodeModel; namespace CSharpWriter { public class CollectionGetByIdIndexer : Indexer { public Dictionary<Parameter, OdcmProperty> ParameterToPropertyMap { get; private set; } public CollectionGetByIdIndexer(OdcmEntityClass odcmClass) { Parameters = global::CSharpWriter.Parameters.GetKeyParameters(odcmClass); ReturnType = new Type(NamesService.GetFetcherInterfaceName(odcmClass)); OdcmClass = odcmClass; IsSettable = false; IsGettable = true; } public OdcmClass OdcmClass { get; private set; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Linq; using Vipr.Core; using Vipr.Core.CodeModel; namespace CSharpWriter { public class CollectionGetByIdIndexer : Indexer { public Dictionary<Parameter, OdcmProperty> ParameterToPropertyMap { get; private set; } public CollectionGetByIdIndexer(OdcmEntityClass odcmClass) { var keyProperties = odcmClass.Key; ParameterToPropertyMap = keyProperties.ToDictionary(Parameter.FromProperty, p => p); Parameters = ParameterToPropertyMap.Keys; ReturnType = new Type(NamesService.GetFetcherInterfaceName(odcmClass)); OdcmClass = odcmClass; IsSettable = false; IsGettable = true; } public OdcmClass OdcmClass { get; private set; } } }
mit
C#
b611180647171f232fe317cbc1d27c3126136e17
Change list to array in payload
BoomaNation/Booma.Payloads,BoomaNation/Booma.Payloads
src/Booma.Payloads.ServerSelection/Payloads/GameServerListResponsePayload.cs
src/Booma.Payloads.ServerSelection/Payloads/GameServerListResponsePayload.cs
using Booma.Payloads.Common; using GladNet.Payload; using GladNet.Serializer; using System; using System.Collections.Generic; using System.Linq; namespace Booma.Payloads.ServerSelection { //TODO: Debate on authorized request [GladNetSerializationContract] [GladLivePayload(BoomaPayloadMessageType.GetGameServerListResponse)] public class GameServerListResponsePayload : PacketPayload, IResponseStatus<GameServerListResponseCode> { /// <summary> /// Indicates the status of the response. /// </summary> [GladNetMember(GladNetDataIndex.Index1)] public GameServerListResponseCode ResponseCode { get; private set; } //private and hidden. For serializer. [GladNetMember(GladNetDataIndex.Index2)] private SimpleGameServerDetailsModel[] gameServerDetails; /// <summary> /// Collection of available gameservers. /// </summary> public IEnumerable<SimpleGameServerDetailsModel> GameServerDetails { get { return gameServerDetails; } } /// <summary> /// Creates a new gameserver list response with only a response code. /// </summary> /// <param name="code">response code.</param> public GameServerListResponsePayload(GameServerListResponseCode code) { ResponseCode = code; } /// <summary> /// Creates a new gameserver list response with the server list. /// </summary> /// <param name="code">Response code.</param> /// <param name="details">Details collection.</param> public GameServerListResponsePayload(GameServerListResponseCode code, IEnumerable<SimpleGameServerDetailsModel> details) { ResponseCode = code; //set to internal field gameServerDetails = details.ToArray(); } /// <summary> /// Creates a new payload for the <see cref="BoomaPayloadMessageType.GetGameServerListResponse"/> packet. /// </summary> public GameServerListResponsePayload() { } } }
using Booma.Payloads.Common; using GladNet.Payload; using GladNet.Serializer; using System; using System.Collections.Generic; using System.Linq; namespace Booma.Payloads.ServerSelection { //TODO: Debate on authorized request [GladNetSerializationContract] [GladLivePayload(BoomaPayloadMessageType.GetGameServerListResponse)] public class GameServerListResponsePayload : PacketPayload, IResponseStatus<GameServerListResponseCode> { /// <summary> /// Indicates the status of the response. /// </summary> [GladNetMember(GladNetDataIndex.Index1)] public GameServerListResponseCode ResponseCode { get; private set; } //private and hidden. For serializer. [GladNetMember(GladNetDataIndex.Index2)] private List<SimpleGameServerDetailsModel> gameServerDetails; /// <summary> /// Collection of available gameservers. /// </summary> public IEnumerable<SimpleGameServerDetailsModel> GameServerDetails { get { return gameServerDetails; } } /// <summary> /// Creates a new gameserver list response with only a response code. /// </summary> /// <param name="code">response code.</param> public GameServerListResponsePayload(GameServerListResponseCode code) { ResponseCode = code; } /// <summary> /// Creates a new gameserver list response with the server list. /// </summary> /// <param name="code">Response code.</param> /// <param name="details">Details collection.</param> public GameServerListResponsePayload(GameServerListResponseCode code, IEnumerable<SimpleGameServerDetailsModel> details) { ResponseCode = code; //set to internal field gameServerDetails = details.ToList(); } /// <summary> /// Creates a new payload for the <see cref="BoomaPayloadMessageType.GetGameServerListResponse"/> packet. /// </summary> public GameServerListResponsePayload() { } } }
mit
C#
9a90a757f1c5be22ae088c501f74e06a115c777a
add include_depth
PKRoma/libgit2sharp,libgit2/libgit2sharp
LibGit2Sharp/Core/GitConfigEntry.cs
LibGit2Sharp/Core/GitConfigEntry.cs
using System; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] internal unsafe struct GitConfigEntry { public char* namePtr; public char* valuePtr; public uint include_depth; public uint level; public void* freePtr; public void* payloadPtr; } }
using System; using System.Runtime.InteropServices; namespace LibGit2Sharp.Core { [StructLayout(LayoutKind.Sequential)] internal unsafe struct GitConfigEntry { public char* namePtr; public char* valuePtr; public uint level; public void* freePtr; public void* payloadPtr; } }
mit
C#
c579e701c4bba3f5a52322da1cbed0b8ef808b76
Hide external process windows.
trondr/NMultiTool,trondr/NMultiTool
src/NMultiTool.Library/Module/Commands/ConvertAllSvgToIco/ProcessProvider.cs
src/NMultiTool.Library/Module/Commands/ConvertAllSvgToIco/ProcessProvider.cs
using System.Diagnostics; using Common.Logging; using NMultiTool.Library.Module.Commands.ConvertSvgToIco; namespace NMultiTool.Library.Module.Commands.ConvertAllSvgToIco { public class ProcessProvider : IProcessProvider { private readonly ILog _logger; public ProcessProvider(ILog logger) { _logger = logger; } public int StartProcess(string exe, string arguments) { _logger.DebugFormat("\"{0}\" {1}", exe, arguments); var startInfo = new ProcessStartInfo() { FileName = exe, Arguments = arguments, CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }; var process = Process.Start(startInfo); if (process == null) throw new NMultiToolException("Failed to start: " + exe); process.WaitForExit(); var exitCode = process.ExitCode; if (exitCode == 0) { _logger.DebugFormat("ExitCode: " + exitCode); } else { _logger.Warn("ExitCode: " + exitCode); } return process.ExitCode; } } }
using System.Diagnostics; using Common.Logging; using NMultiTool.Library.Module.Commands.ConvertSvgToIco; namespace NMultiTool.Library.Module.Commands.ConvertAllSvgToIco { public class ProcessProvider : IProcessProvider { private readonly ILog _logger; public ProcessProvider(ILog logger) { _logger = logger; } public int StartProcess(string exe, string arguments) { _logger.DebugFormat("\"{0}\" {1}", exe, arguments); var process = Process.Start(exe, arguments); if (process == null) throw new NMultiToolException("Failed to start: " + exe); process.WaitForExit(); var exitCode = process.ExitCode; if (exitCode == 0) { _logger.DebugFormat("ExitCode: " + exitCode); } else { _logger.Warn("ExitCode: " + exitCode); } return process.ExitCode; } } }
bsd-3-clause
C#
6c13258fddf02d0090be3f0a4d572ced83472515
Update loading logging
AndMu/Wikiled.Sentiment
src/Sentiment/Wikiled.Sentiment.Text/Configuration/ExtendedLexiconFactory.cs
src/Sentiment/Wikiled.Sentiment.Text/Configuration/ExtendedLexiconFactory.cs
using System; using System.IO; using NLog; using Wikiled.Common.Arguments; using Wikiled.Sentiment.Text.Parser; using Wikiled.Sentiment.Text.Resources; using Wikiled.Text.Analysis.Dictionary; namespace Wikiled.Sentiment.Text.Configuration { public class ExtendedLexiconFactory : IExtendedLexiconFactory { private static readonly Logger log = LogManager.GetCurrentClassLogger(); private Lazy<IWordsHandler> wordsHandler; public ExtendedLexiconFactory(IConfigurationHandler configuration) { Guard.NotNull(() => configuration, configuration); var path = configuration.ResolvePath("Resources"); ResourcesPath = Path.Combine(path, configuration.SafeGetConfiguration("Lexicon", @"Library\Standard")); } public bool CanBeConstructed { get { if (!Directory.Exists(ResourcesPath)) { log.Error("Path doesn't exist: {0}", ResourcesPath); return false; } return true; } } public bool CanConstruct => !IsConstructed && CanBeConstructed; public bool IsConstructed { get; private set; } public string ResourcesPath { get; } public IWordsHandler WordsHandler => wordsHandler.Value; public void Construct() { if (!CanBeConstructed) { throw new InvalidOperationException("Lexicon can't be constructed"); } wordsHandler = new Lazy<IWordsHandler>( () => { var handler = new WordsDataLoader(ResourcesPath, new BasicEnglishDictionary()); handler.Load(); return handler; }); log.Debug("Construct lexicon using path: {0}", ResourcesPath); IsConstructed = true; } } }
using System; using System.IO; using NLog; using Wikiled.Common.Arguments; using Wikiled.Sentiment.Text.Parser; using Wikiled.Sentiment.Text.Resources; using Wikiled.Text.Analysis.Dictionary; namespace Wikiled.Sentiment.Text.Configuration { public class ExtendedLexiconFactory : IExtendedLexiconFactory { private static readonly Logger log = LogManager.GetCurrentClassLogger(); private Lazy<IWordsHandler> wordsHandler; public ExtendedLexiconFactory(IConfigurationHandler configuration) { Guard.NotNull(() => configuration, configuration); var path = configuration.ResolvePath("Resources"); ResourcesPath = Path.Combine(path, configuration.SafeGetConfiguration("Lexicon", @"Library\Standard")); } public bool CanBeConstructed { get { if (!Directory.Exists(ResourcesPath)) { log.Debug("Path doesn't exist: {0}", ResourcesPath); return false; } return true; } } public bool CanConstruct => !IsConstructed && CanBeConstructed; public bool IsConstructed { get; private set; } public string ResourcesPath { get; } public IWordsHandler WordsHandler => wordsHandler.Value; public void Construct() { if (!CanBeConstructed) { throw new InvalidOperationException("Lexicon can't be constructed"); } wordsHandler = new Lazy<IWordsHandler>( () => { var handler = new WordsDataLoader(ResourcesPath, new BasicEnglishDictionary()); handler.Load(); return handler; }); log.Debug("Construct lexicon using path: {0}", ResourcesPath); IsConstructed = true; } } }
apache-2.0
C#
6c1cd102af524163b85e1bf4116d08abadd3bfde
fix for activation function
jobeland/NeuralNetwork
NeuralNetwork/NeuralNetwork/ActivationFunctions/AbsoluteXActivationFunction.cs
NeuralNetwork/NeuralNetwork/ActivationFunctions/AbsoluteXActivationFunction.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork.ActivationFunctions { public class AbsoluteXActivationFunction : IActivationFunction { public double Calculate(double sumOfInputsAndBias) { return Math.Abs(sumOfInputsAndBias); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ArtificialNeuralNetwork.ActivationFunctions { public class AbsoluteXActivationFunction : IActivationFunction { double Calculate(double sumOfInputsAndBias) { return Math.Abs(sumOfInputsAndBias); } } }
mit
C#
b914bc8f47987d57f37aef1098b44640dc3e6121
Refactor ExtendedStringFormatter
YevgeniyShunevych/Atata,atata-framework/atata,atata-framework/atata,YevgeniyShunevych/Atata
src/Atata/ExtendedStringFormatter.cs
src/Atata/ExtendedStringFormatter.cs
using System; using System.Globalization; namespace Atata { public class ExtendedStringFormatter : IFormatProvider, ICustomFormatter { private const string InnerFormatValueIndicator = "*"; public static ExtendedStringFormatter Default { get; } = new ExtendedStringFormatter(); public object GetFormat(Type formatType) { return formatType == typeof(ICustomFormatter) ? this : null; } public string Format(string format, object arg, IFormatProvider formatProvider) { if (!Equals(formatProvider)) return null; if (arg == null) return string.Empty; if (arg is string argString && !string.IsNullOrWhiteSpace(format)) return FormatInnerString(format, argString); else if (arg is IFormattable argFormattable) return argFormattable.ToString(format, CultureInfo.CurrentCulture); else return arg.ToString(); } private static string FormatInnerString(string format, string argument) { string normalizedFormat = format. Replace(InnerFormatValueIndicator, "{0}"). Replace("{0}{0}", InnerFormatValueIndicator); return string.Format(normalizedFormat, argument); } } }
using System; using System.Globalization; namespace Atata { public class ExtendedStringFormatter : IFormatProvider, ICustomFormatter { private const string InnerFormatValueIndicator = "*"; public static ExtendedStringFormatter Default { get; } = new ExtendedStringFormatter(); public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return this; else return null; } public string Format(string format, object arg, IFormatProvider formatProvider) { if (!Equals(formatProvider)) return null; if (arg == null) return string.Empty; if (arg is string argString && !string.IsNullOrWhiteSpace(format)) return FormatInnerString(format, argString); else if (arg is IFormattable argFormattable) return argFormattable.ToString(format, CultureInfo.CurrentCulture); else return arg.ToString(); } private static string FormatInnerString(string format, string argument) { string normalizedFormat = format. Replace(InnerFormatValueIndicator, "{0}"). Replace("{0}{0}", InnerFormatValueIndicator); return string.Format(normalizedFormat, argument); } } }
apache-2.0
C#
4fe69dbc896d77fd1efea4c469254fdbb3563fe0
Fix context menu sub-menu display
johnneijzen/osu,UselessToucan/osu,ppy/osu,peppy/osu-new,peppy/osu,EVAST9919/osu,peppy/osu,johnneijzen/osu,NeoAdonis/osu,ppy/osu,ppy/osu,UselessToucan/osu,2yangk23/osu,UselessToucan/osu,smoogipoo/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,smoogipoo/osu,EVAST9919/osu,peppy/osu
osu.Game/Graphics/UserInterface/OsuContextMenu.cs
osu.Game/Graphics/UserInterface/OsuContextMenu.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Effects; using osu.Framework.Graphics.UserInterface; namespace osu.Game.Graphics.UserInterface { public class OsuContextMenu : OsuMenu { private const int fade_duration = 250; public OsuContextMenu() : base(Direction.Vertical) { MaskingContainer.CornerRadius = 5; MaskingContainer.EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(0.1f), Radius = 4, }; ItemsContainer.Padding = new MarginPadding { Vertical = DrawableOsuMenuItem.MARGIN_VERTICAL }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.ContextMenuGray; } protected override void AnimateOpen() => this.FadeIn(fade_duration, Easing.OutQuint); protected override void AnimateClose() => this.FadeOut(fade_duration, Easing.OutQuint); protected override Menu CreateSubMenu() => new OsuContextMenu(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osuTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Effects; namespace osu.Game.Graphics.UserInterface { public class OsuContextMenu : OsuMenu { private const int fade_duration = 250; public OsuContextMenu() : base(Direction.Vertical) { MaskingContainer.CornerRadius = 5; MaskingContainer.EdgeEffect = new EdgeEffectParameters { Type = EdgeEffectType.Shadow, Colour = Color4.Black.Opacity(0.1f), Radius = 4, }; ItemsContainer.Padding = new MarginPadding { Vertical = DrawableOsuMenuItem.MARGIN_VERTICAL }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { BackgroundColour = colours.ContextMenuGray; } protected override void AnimateOpen() => this.FadeIn(fade_duration, Easing.OutQuint); protected override void AnimateClose() => this.FadeOut(fade_duration, Easing.OutQuint); } }
mit
C#
d4443775646dd64837094cf4193e9621c7f9445f
Add example
fredatgithub/AtlasReloaded
UsageConsole/Program.cs
UsageConsole/Program.cs
using System; using Ritter.Atlas; namespace UsageConsole { class Program { static void Main() { Action<string> Display = s => Console.WriteLine(s); var zipcode = new ZipCode { Id = "17011" }; var zipcode2 = new ZipCode { Id = "90210" }; var zipcode3 = new ZipCode { Id = "75017" }; var zipcode4 = new ZipCode { Id = "75020" }; var zipcode5 = new ZipCode { Id = "12345" }; Console.ReadKey(); } } }
using System; using Ritter.Atlas; namespace UsageConsole { class Program { static void Main() { Action<string> Display = s => Console.WriteLine(s); var zipcode = new ZipCode { Id = "17011" }; var zipcode2 = new ZipCode { Id = "90210" }; var zipcode3 = new ZipCode { Id = "75017" }; var zipcode4 = new ZipCode { Id = "75020" }; Console.ReadKey(); } } }
mit
C#
9a06a1ca74520351af40acae471f868d3f97d06d
Swap bytecodes WIP
ajlopez/BlockchainSharp
Src/BlockchainSharp/Vm/Bytecodes.cs
Src/BlockchainSharp/Vm/Bytecodes.cs
namespace BlockchainSharp.Vm { public enum Bytecodes { Push1 = 0x60, Push2 = 0x61, Push3 = 0x62, Push4 = 0x63, Push5 = 0x64, Push6 = 0x65, Push7 = 0x66, Push8 = 0x67, Push9 = 0x68, Push10 = 0x69, Push11 = 0x6a, Push12 = 0x6b, Push13 = 0x6c, Push14 = 0x6d, Push15 = 0x6e, Push16 = 0x6f, Push17 = 0x70, Push18 = 0x71, Push19 = 0x72, Push20 = 0x73, Push21 = 0x74, Push22 = 0x75, Push23 = 0x76, Push24 = 0x77, Push25 = 0x78, Push26 = 0x79, Push27 = 0x7a, Push28 = 0x7b, Push29 = 0x7c, Push30 = 0x7d, Push31 = 0x7e, Push32 = 0x7f, Dup1 = 0x80, Dup2 = 0x81, Dup3 = 0x82, Dup4 = 0x83, Dup5 = 0x84, Dup6 = 0x85, Dup7 = 0x86, Dup8 = 0x87, Dup9 = 0x88, Dup10 = 0x89, Dup11 = 0x8a, Dup12 = 0x8b, Dup13 = 0x8c, Dup14 = 0x8d, Dup15 = 0x8e, Dup16 = 0x8f, Swap1 = 0x90, Swap2 = 0x091, Swap3 = 0x092, Swap4 = 0x093, Swap5 = 0x094, Swap6 = 0x095, Swap7 = 0x096, Swap8 = 0x097, Swap9 = 0x098, Swap10 = 0x099, Swap11 = 0x09a, Swap12 = 0x09b, Swap13 = 0x09c, Swap14 = 0x09d, Swap15 = 0x09e, Swap16 = 0x09f } }
namespace BlockchainSharp.Vm { public enum Bytecodes { Push1 = 0x60, Push2 = 0x61, Push3 = 0x62, Push4 = 0x63, Push5 = 0x64, Push6 = 0x65, Push7 = 0x66, Push8 = 0x67, Push9 = 0x68, Push10 = 0x69, Push11 = 0x6a, Push12 = 0x6b, Push13 = 0x6c, Push14 = 0x6d, Push15 = 0x6e, Push16 = 0x6f, Push17 = 0x70, Push18 = 0x71, Push19 = 0x72, Push20 = 0x73, Push21 = 0x74, Push22 = 0x75, Push23 = 0x76, Push24 = 0x77, Push25 = 0x78, Push26 = 0x79, Push27 = 0x7a, Push28 = 0x7b, Push29 = 0x7c, Push30 = 0x7d, Push31 = 0x7e, Push32 = 0x7f, Dup1 = 0x80, Dup2 = 0x81, Dup3 = 0x82, Dup4 = 0x83, Dup5 = 0x84, Dup6 = 0x85, Dup7 = 0x86, Dup8 = 0x87, Dup9 = 0x88, Dup10 = 0x89, Dup11 = 0x8a, Dup12 = 0x8b, Dup13 = 0x8c, Dup14 = 0x8d, Dup15 = 0x8e, Dup16 = 0x8f } }
mit
C#
9ce82c35185db2827338aeab5125384e402bae9a
Fix e2e faild because api change
LianwMS/WebApi,scz2011/WebApi,lewischeng-ms/WebApi,yonglehou/WebApi,lungisam/WebApi,congysu/WebApi,lewischeng-ms/WebApi,lungisam/WebApi,LianwMS/WebApi,scz2011/WebApi,congysu/WebApi,yonglehou/WebApi
OData/test/E2ETest/WebStack.QA.Test.OData/SxS2/ODataV3/ODataV3WebApiConfig.cs
OData/test/E2ETest/WebStack.QA.Test.OData/SxS2/ODataV3/ODataV3WebApiConfig.cs
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.OData.Extensions; using WebStack.QA.Test.OData.SxS2.ODataV3.Extensions; namespace WebStack.QA.Test.OData.SxS2.ODataV3 { public static class ODataV3WebApiConfig { public static void Register(HttpConfiguration config) { config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; var odataRoute = config.Routes.MapODataServiceRoute( routeName: "SxSODataV3", routePrefix: "SxSOData", model: WebStack.QA.Test.OData.SxS2.ODataV3.Models.ModelBuilder.GetEdmModel()); var contraint = new ODataVersionRouteConstraint(new List<string>() { "OData-Version" }); odataRoute.Constraints.Add("VersionContraintV1", contraint); } } }
using System.Collections.Generic; using System.Web.Http; using System.Web.Http.OData.Extensions; using WebStack.QA.Test.OData.SxS2.ODataV3.Extensions; namespace WebStack.QA.Test.OData.SxS2.ODataV3 { public static class ODataV3WebApiConfig { public static void Register(HttpConfiguration config) { config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; var odataRoute = config.Routes.MapODataServiceRoute( routeName: "SxSODataV3", routePrefix: "SxSOData", model: WebStack.QA.Test.OData.SxS2.ODataV3.Models.ModelBuilder.GetEdmModel()) .SetODataVersionConstraint(true); var contraint = new ODataVersionRouteConstraint(new List<string>() { "OData-Version" }); odataRoute.Constraints.Add("VersionContraintV1", contraint); } } }
mit
C#
4e6a155744dd59829a14468c753ef7581b9a4d84
Modify primitive driver to send x, y, and z linear effort values.
WisconsinRobotics/BadgerControlSystem
BadgerControlModule/Utils/RemotePrimitiveDriverService.cs
BadgerControlModule/Utils/RemotePrimitiveDriverService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BadgerJaus.Services.Core; using BadgerJaus.Messages.PrimitiveDriver; using BadgerJaus.Util; using BadgerControlModule.Models; namespace BadgerControlModule.Utils { class RemotePrimitiveDriverService : RemoteDriverService { BadgerControlSubsystem badgerControlSubsystem; public RemotePrimitiveDriverService(BadgerControlSubsystem badgerControlSubsystem) { this.badgerControlSubsystem = badgerControlSubsystem; } public void SendDriveCommand(long xJoystickValue, long yJoystickValue, long zJoystickValue, Component parentComponent) { SetWrenchEffort setWrenchEffort = new SetWrenchEffort(); setWrenchEffort.SetSource(badgerControlSubsystem.LocalAddress); setWrenchEffort.SetDestination(parentComponent.JausAddress); // This is intentional, do not attempt to swap the X and Y values. setWrenchEffort.SetPropulsiveLinearEffortX(yJoystickValue); setWrenchEffort.SetPropulsiveLinearEffortY(xJoystickValue); setWrenchEffort.SetPropulsiveLinearEffortZ(zJoystickValue); Transport.SendMessage(setWrenchEffort); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BadgerJaus.Services.Core; using BadgerJaus.Messages.PrimitiveDriver; using BadgerJaus.Util; using BadgerControlModule.Models; namespace BadgerControlModule.Utils { class RemotePrimitiveDriverService : RemoteDriverService { BadgerControlSubsystem badgerControlSubsystem; public RemotePrimitiveDriverService(BadgerControlSubsystem badgerControlSubsystem) { this.badgerControlSubsystem = badgerControlSubsystem; } public void SendDriveCommand(long xJoystickValue, long yJoystickValue, long zJoystickValue, Component parentComponent) { SetWrenchEffort setWrenchEffort = new SetWrenchEffort(); setWrenchEffort.SetSource(badgerControlSubsystem.LocalAddress); setWrenchEffort.SetDestination(parentComponent.JausAddress); setWrenchEffort.SetPropulsiveLinearEffortX(yJoystickValue); Transport.SendMessage(setWrenchEffort); } } }
bsd-3-clause
C#
f93f316cf7c47a79a8e398ceff866b4632ea0169
Fix constructor visibility for plugin
pleonex/NitroDebugger,pleonex/NitroDebugger,pleonex/NitroDebugger
NitroDebugger/Plugin.cs
NitroDebugger/Plugin.cs
// // Plugin.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Addins; namespace NitroDebugger { [TypeExtensionPoint] public abstract class Plugin : IDisposable { static List<Plugin> instances = new List<Plugin>(); protected Plugin() { instances.Add(this); } ~Plugin() { this.Dispose(false); } public static ReadOnlyCollection<Plugin> Instances { get { return new ReadOnlyCollection<Plugin>(instances); } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool freeManagedResourcesAlso) { instances.Remove(this); } } }
// // Plugin.cs // // Author: // Benito Palacios Sánchez <benito356@gmail.com> // // Copyright (c) 2015 Benito Palacios Sánchez // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using Mono.Addins; namespace NitroDebugger { [TypeExtensionPoint] public abstract class Plugin : IDisposable { static List<Plugin> instances = new List<Plugin>(); public Plugin() { instances.Add(this); } ~Plugin() { this.Dispose(false); } public static ReadOnlyCollection<Plugin> Instances { get { return new ReadOnlyCollection<Plugin>(instances); } } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool freeManagedResourcesAlso) { instances.Remove(this); } } }
mit
C#
ea594a3248236374abe17c0a60af47876296c867
Fix demo plugin
martin211/aimp_dotnet,martin211/aimp_dotnet,martin211/aimp_dotnet,martin211/aimp_dotnet,martin211/aimp_dotnet
Plugins/Demo/Program.cs
Plugins/Demo/Program.cs
using System.Windows.Forms; namespace TestPlugin { using AIMP.SDK; using AIMP.SDK.MenuManager; using AIMP.SDK.Options; using AIMP.SDK.UI.ActionItem; using AIMP.SDK.UI.MenuItem; [AimpPlugin("dotNetInteropTest", "Evgeniy Bogdan", "1", AimpPluginType = AimpPluginType.Addons)] public class Program : AimpPlugin { private Form1 _demoForm; private IAimpOptionsDialogFrame _optionsFrame; public override void Initialize() { Player.Core.CoreMessage += (param1, param2) => { System.Diagnostics.Debug.WriteLine("Demo plugin: Player.Core.CoreMessage"); }; _demoForm = new Form1(Player); var menuItem = new StandartMenuItem("Demo plugin"); menuItem.BeforeShow += (sender, args) => { }; menuItem.Click += (sender, args) => { var m = Player.MenuManager.GetBuiltIn(ParentMenuType.AIMP_MENUID_PLAYER_MAIN_FUNCTIONS); _demoForm.Show(); }; Player.MenuManager.Add(ParentMenuType.AIMP_MENUID_COMMON_UTILITIES, menuItem); var action = new AimpActionItem("Teset action", "test Group"); Player.ActionManager.Add(action); //_optionsFrame = new OptionsFrame(Player); Player.Core.RegisterExtension(_optionsFrame); } public override void Dispose() { System.Diagnostics.Debug.WriteLine("Dispose"); } } }
using System.Windows.Forms; namespace TestPlugin { using AIMP.SDK; using AIMP.SDK.MenuManager; using AIMP.SDK.Options; using AIMP.SDK.UI.ActionItem; using AIMP.SDK.UI.MenuItem; [AimpPlugin("dotNetInteropTest", "Evgeniy Bogdan", "1", AimpPluginType = AimpPluginType.Addons)] public class Program : AimpPlugin { private Form1 _demoForm; private IAimpOptionsDialogFrame _optionsFrame; public override void ShowSettingDialog(IWin32Window ParentWnd) { } public override void Initialize() { Player.Core.CoreMessage += (param1, param2) => { System.Diagnostics.Debug.WriteLine("Demo plugin: Player.Core.CoreMessage"); }; _demoForm = new Form1(Player); var menuItem = new StandartMenuItem("Demo plugin"); menuItem.BeforeShow += (sender, args) => { }; menuItem.Click += (sender, args) => { var m = Player.MenuManager.GetBuiltIn(ParentMenuType.AIMP_MENUID_PLAYER_MAIN_FUNCTIONS); _demoForm.Show(); }; Player.MenuManager.Add(ParentMenuType.AIMP_MENUID_COMMON_UTILITIES, menuItem); var action = new AimpActionItem("Teset action", "test Group"); Player.ActionManager.Add(action); //_optionsFrame = new OptionsFrame(Player); Player.Core.RegisterExtension(_optionsFrame); } public override void Dispose() { System.Diagnostics.Debug.WriteLine("Dispose"); } public override bool HasSettingDialog { get { return false; } } } }
apache-2.0
C#
add56d8197811e151407ed9a0a171e1e9cddf0c6
add revese-proxy support
MCeddy/IoT-core
IoT-Core/Startup.cs
IoT-Core/Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using IoT_Core.Models; using IoT_Core.Middelware; using Microsoft.AspNetCore.HttpOverrides; namespace IoT_Core { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkSqlite() .AddDbContext<SensorValueContext>(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); // for reverse-proxy support app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); if (env.IsProduction()) { app.UseSecretAuthentication(); } app.UseMvc(); // create database using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { var sensorValueContext = serviceScope.ServiceProvider.GetRequiredService<SensorValueContext>(); sensorValueContext.Database.EnsureCreated(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using IoT_Core.Models; using IoT_Core.Middelware; namespace IoT_Core { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddEntityFrameworkSqlite() .AddDbContext<SensorValueContext>(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsProduction()) { app.UseSecretAuthentication(); } app.UseMvc(); // create database using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope()) { var sensorValueContext = serviceScope.ServiceProvider.GetRequiredService<SensorValueContext>(); sensorValueContext.Database.EnsureCreated(); } } } }
mit
C#
55a43451bd487b7435945322f15e795c0ee87902
Add Category property to Item
Azure-Samples/documentdb-dotnet-todo-app,Azure-Samples/documentdb-dotnet-todo-app,Azure-Samples/documentdb-dotnet-todo-app
src/Models/Item.cs
src/Models/Item.cs
namespace todo.Models { using Microsoft.Azure.Documents; using Newtonsoft.Json; public class Item { [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "description")] public string Description { get; set; } [JsonProperty(PropertyName = "isComplete")] public bool Completed { get; set; } [JsonProperty(PropertyName = "category")] public string Category { get; set; } } }
namespace todo.Models { using Microsoft.Azure.Documents; using Newtonsoft.Json; public class Item { [JsonProperty(PropertyName = "id")] public string Id { get; set; } [JsonProperty(PropertyName = "name")] public string Name { get; set; } [JsonProperty(PropertyName = "description")] public string Description { get; set; } [JsonProperty(PropertyName = "isComplete")] public bool Completed { get; set; } } }
mit
C#
5bef498993a2f080a39a21b1ab7fcf2a844d8e79
Fix source analysis
ajlopez/BScript
Src/BScript/Machine.cs
Src/BScript/Machine.cs
namespace BScript { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BScript.Commands; using BScript.Compiler; using BScript.Language; public class Machine { private Context context; private TextWriter outWriter; public Machine() { this.outWriter = System.Console.Out; this.context = new Context(); this.context.SetValue("machine", this); this.context.SetValue("print", new Print(this)); } public Context RootContext { get { return this.context; } } public TextWriter Out { get { return this.outWriter; } set { this.outWriter = value; } } public static void Execute(string code, Context context) { Parser parser = new Parser(code); ICommand cmd = parser.ParseCommands(); cmd.Execute(context); } public static void ExecuteFile(string filename, Context context) { var code = File.ReadAllText(filename); Execute(code, context); } public void Execute(string code) { Execute(code, this.context); } public void ExecuteFile(string filename) { ExecuteFile(filename, this.context); } } }
namespace BScript { using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using BScript.Commands; using BScript.Compiler; using BScript.Language; public class Machine { private Context context; private TextWriter outWriter; public Machine() { this.outWriter = System.Console.Out; this.context = new Context(); this.context.SetValue("machine", this); this.context.SetValue("print", new Print(this)); } public Context RootContext { get { return this.context; } } public TextWriter Out { get { return this.outWriter; } set { this.outWriter = value; } } public void Execute(string code) { Execute(code, this.context); } public static void Execute(string code, Context context) { Parser parser = new Parser(code); ICommand cmd = parser.ParseCommands(); cmd.Execute(context); } public void ExecuteFile(string filename) { ExecuteFile(filename, this.context); } public static void ExecuteFile(string filename, Context context) { var code = File.ReadAllText(filename); Execute(code, context); } } }
mit
C#
aac13df34a97feacb0381924980d4d7fa398f1c3
add SF app version back
aloneguid/logmagic
src/LogMagic.Microsoft.Azure.ServiceFabric/Enrichers/ServiceFabricEnricher.cs
src/LogMagic.Microsoft.Azure.ServiceFabric/Enrichers/ServiceFabricEnricher.cs
using LogMagic.Enrichers; using System.Fabric; namespace LogMagic.Microsoft.Azure.ServiceFabric.Enrichers { class ServiceFabricEnricher : IEnricher { private readonly ServiceContext _context; public ServiceFabricEnricher(ServiceContext context) { _context = context ?? throw new System.ArgumentNullException(nameof(context)); } public void Enrich(LogEvent e, out string propertyName, out object propertyValue) { propertyName = null; propertyValue = null; e.AddProperty(KnownFabricProperty.ServiceName, _context.ServiceName); e.AddProperty(KnownFabricProperty.ServiceTypeName, _context.ServiceTypeName); e.AddProperty(KnownFabricProperty.PartitionId, _context.PartitionId); e.AddProperty(KnownFabricProperty.ApplicationName, _context.CodePackageActivationContext.ApplicationName); e.AddProperty(KnownFabricProperty.ApplicationTypeName, _context.CodePackageActivationContext.ApplicationTypeName); e.AddProperty(KnownFabricProperty.NodeName, _context.NodeContext.NodeName); e.AddProperty(KnownProperty.Version, _context.CodePackageActivationContext.CodePackageVersion); if (_context is StatelessServiceContext) { e.AddProperty(KnownFabricProperty.InstanceId, _context.ReplicaOrInstanceId); } if(_context is StatefulServiceContext) { e.AddProperty(KnownFabricProperty.ReplicaId, _context.ReplicaOrInstanceId); } } } }
using LogMagic.Enrichers; using System.Fabric; namespace LogMagic.Microsoft.Azure.ServiceFabric.Enrichers { class ServiceFabricEnricher : IEnricher { private readonly ServiceContext _context; public ServiceFabricEnricher(ServiceContext context) { _context = context ?? throw new System.ArgumentNullException(nameof(context)); } public void Enrich(LogEvent e, out string propertyName, out object propertyValue) { propertyName = null; propertyValue = null; e.AddProperty(KnownFabricProperty.ServiceName, _context.ServiceName); e.AddProperty(KnownFabricProperty.ServiceTypeName, _context.ServiceTypeName); e.AddProperty(KnownFabricProperty.PartitionId, _context.PartitionId); e.AddProperty(KnownFabricProperty.ApplicationName, _context.CodePackageActivationContext.ApplicationName); e.AddProperty(KnownFabricProperty.ApplicationTypeName, _context.CodePackageActivationContext.ApplicationTypeName); e.AddProperty(KnownFabricProperty.NodeName, _context.NodeContext.NodeName); if(_context is StatelessServiceContext) { e.AddProperty(KnownFabricProperty.InstanceId, _context.ReplicaOrInstanceId); } if(_context is StatefulServiceContext) { e.AddProperty(KnownFabricProperty.ReplicaId, _context.ReplicaOrInstanceId); } } } }
mit
C#
46ea59cc36b826b5db00e124488a694fd4c23002
Fix typo in Acquire return value doc
morelinq/MoreLINQ,fsateler/MoreLINQ,ddpruitt/morelinq,ddpruitt/morelinq,morelinq/MoreLINQ,fsateler/MoreLINQ
MoreLinq/Acquire.cs
MoreLinq/Acquire.cs
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2012 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Ensures that a source sequence of <see cref="IDisposable"/> /// objects are all acquired successfully. If the acquisition of any /// one <see cref="IDisposable"/> fails then those successfully /// acquired till that point are disposed. /// </summary> /// <typeparam name="TSource">Type of elements in <paramref name="source"/> sequence.</typeparam> /// <param name="source">Source sequence of <see cref="IDisposable"/> objects.</param> /// <returns> /// Returns an array of all the acquired <see cref="IDisposable"/> /// objects in source order. /// </returns> /// <remarks> /// This operator executes immediately. /// </remarks> public static TSource[] Acquire<TSource>(this IEnumerable<TSource> source) where TSource : IDisposable { if (source == null) throw new ArgumentNullException(nameof(source)); var disposables = new List<TSource>(); try { disposables.AddRange(source); return disposables.ToArray(); } catch { foreach (var disposable in disposables) disposable.Dispose(); throw; } } } }
#region License and Terms // MoreLINQ - Extensions to LINQ to Objects // Copyright (c) 2012 Atif Aziz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion namespace MoreLinq { using System; using System.Collections.Generic; static partial class MoreEnumerable { /// <summary> /// Ensures that a source sequence of <see cref="IDisposable"/> /// objects are all acquired successfully. If the acquisition of any /// one <see cref="IDisposable"/> fails then those successfully /// acquired till that point are disposed. /// </summary> /// <typeparam name="TSource">Type of elements in <paramref name="source"/> sequence.</typeparam> /// <param name="source">Source sequence of <see cref="IDisposable"/> objects.</param> /// <returns> /// Returns an array of all the acquired <see cref="IDisposable"/> /// object and in source order. /// </returns> /// <remarks> /// This operator executes immediately. /// </remarks> public static TSource[] Acquire<TSource>(this IEnumerable<TSource> source) where TSource : IDisposable { if (source == null) throw new ArgumentNullException(nameof(source)); var disposables = new List<TSource>(); try { disposables.AddRange(source); return disposables.ToArray(); } catch { foreach (var disposable in disposables) disposable.Dispose(); throw; } } } }
apache-2.0
C#
92bcbd0b33e1ebca5088262225014112e30206b5
Fix #40
TheSharpieOne/LinqToQuerystring,TheSharpieOne/LinqToQuerystring,TheSharpieOne/LinqToQuerystring
LinqToQuerystring/TreeNodes/DataTypes/DateTimeNode.cs
LinqToQuerystring/TreeNodes/DataTypes/DateTimeNode.cs
namespace LinqToQuerystring.TreeNodes.DataTypes { using System; using System.Globalization; using System.Linq; using System.Linq.Expressions; using Antlr.Runtime; using LinqToQuerystring.TreeNodes.Base; public class DateTimeNode : TreeNode { public DateTimeNode(Type inputType, IToken payload, TreeNodeFactory treeNodeFactory) : base(inputType, payload, treeNodeFactory) { } public override Expression BuildLinqExpression(IQueryable query, Expression expression, Expression item = null) { var dateText = this.Text .Replace("datetime'", string.Empty) .Replace("'", string.Empty); return Expression.Constant(DateTime.Parse(dateText, null, DateTimeStyles.RoundtripKind)); } } }
namespace LinqToQuerystring.TreeNodes.DataTypes { using System; using System.Globalization; using System.Linq; using System.Linq.Expressions; using Antlr.Runtime; using LinqToQuerystring.TreeNodes.Base; public class DateTimeNode : TreeNode { public DateTimeNode(Type inputType, IToken payload, TreeNodeFactory treeNodeFactory) : base(inputType, payload, treeNodeFactory) { } public override Expression BuildLinqExpression(IQueryable query, Expression expression, Expression item = null) { var dateText = this.Text .Replace("datetime'", string.Empty) .Replace("'", string.Empty) .Replace(".", ":"); return Expression.Constant(DateTime.Parse(dateText, null, DateTimeStyles.RoundtripKind)); } } }
mit
C#
d4b4060e60430ac5719be2ac9576e85ecf7b9af2
Update src/EditorFeatures/Core.Wpf/IDebuggerTextView2.cs
diryboy/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,sharwell/roslyn,mgoertz-msft/roslyn,AmadeusW/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,AlekseyTs/roslyn,wvdd007/roslyn,tmat/roslyn,jasonmalinowski/roslyn,eriawan/roslyn,physhi/roslyn,shyamnamboodiripad/roslyn,bartdesmet/roslyn,tannergooding/roslyn,weltkante/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,mgoertz-msft/roslyn,AlekseyTs/roslyn,diryboy/roslyn,bartdesmet/roslyn,weltkante/roslyn,tmat/roslyn,AmadeusW/roslyn,physhi/roslyn,tannergooding/roslyn,mgoertz-msft/roslyn,dotnet/roslyn,weltkante/roslyn,tmat/roslyn,tannergooding/roslyn,wvdd007/roslyn,eriawan/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,eriawan/roslyn,KevinRansom/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,mavasani/roslyn,diryboy/roslyn,KevinRansom/roslyn
src/EditorFeatures/Core.Wpf/IDebuggerTextView2.cs
src/EditorFeatures/Core.Wpf/IDebuggerTextView2.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor { internal interface IDebuggerTextView2 : IDebuggerTextView { void HACK_StartCompletionSession(IIntellisenseSession? editorSession); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Microsoft.VisualStudio.Language.Intellisense; namespace Microsoft.CodeAnalysis.Editor { internal interface IDebuggerTextView2 : IDebuggerTextView { void HACK_StartCompletionSession(IIntellisenseSession editorSessionOpt); } }
mit
C#
e25e6babe566fdebc76f6cbdaa0e40d6c7256a3c
Bump version number.
codecutout/StringToExpression
src/StringToExpression/Properties/AssemblyInfo.cs
src/StringToExpression/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyTitle("StringToExpression")] [assembly: AssemblyDescription(@"StringToExpression supports the compiling a domain specific string into a .NET expression. Out of the box configuration is provided for parsing arithmetic expressions and for parsing OData filter strings. Although can be configured to parse string of any format")] [assembly: AssemblyCompany("Codecutout")] [assembly: AssemblyProduct("StringToExpression")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: ComVisible(false)] [assembly: Guid("b1b0a26f-04e2-40e5-b25c-12764e50befc")] [assembly: AssemblyVersion("0.9.1")] [assembly: AssemblyFileVersion("0.9.1")] [assembly: InternalsVisibleTo("StringToExpression.Test")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyTitle("StringToExpression")] [assembly: AssemblyDescription(@"StringToExpression supports the compiling a domain specific string into a .NET expression. Out of the box configuration is provided for parsing arithmetic expressions and for parsing OData filter strings. Although can be configured to parse string of any format")] [assembly: AssemblyCompany("Codecutout")] [assembly: AssemblyProduct("StringToExpression")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: ComVisible(false)] [assembly: Guid("b1b0a26f-04e2-40e5-b25c-12764e50befc")] [assembly: AssemblyVersion("0.1.0")] [assembly: AssemblyFileVersion("0.1.0")] [assembly: InternalsVisibleTo("StringToExpression.Test")]
mit
C#
0ce0f2a2d55a4298d9d06ea29d26a28f14373ea3
Add char.ToLower/Upper perf tests (#28765)
Jiayili1/corefx,ptoonen/corefx,ViktorHofer/corefx,wtgodbe/corefx,mmitche/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,ViktorHofer/corefx,ericstj/corefx,shimingsg/corefx,Jiayili1/corefx,shimingsg/corefx,ViktorHofer/corefx,Jiayili1/corefx,shimingsg/corefx,mmitche/corefx,ericstj/corefx,BrennanConroy/corefx,ptoonen/corefx,ericstj/corefx,shimingsg/corefx,wtgodbe/corefx,shimingsg/corefx,Jiayili1/corefx,mmitche/corefx,mmitche/corefx,shimingsg/corefx,Jiayili1/corefx,wtgodbe/corefx,ViktorHofer/corefx,Jiayili1/corefx,wtgodbe/corefx,ptoonen/corefx,ericstj/corefx,BrennanConroy/corefx,wtgodbe/corefx,ptoonen/corefx,BrennanConroy/corefx,ptoonen/corefx,ericstj/corefx,ViktorHofer/corefx,mmitche/corefx,wtgodbe/corefx,ptoonen/corefx,ViktorHofer/corefx,mmitche/corefx,Jiayili1/corefx,ViktorHofer/corefx,ptoonen/corefx,mmitche/corefx,ericstj/corefx
src/System.Runtime/tests/Performance/Perf.Char.cs
src/System.Runtime/tests/Performance/Perf.Char.cs
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Globalization; using Microsoft.Xunit.Performance; using Xunit; namespace System.Tests { public class Perf_Char { private const int InnerIterations = 1_000_000; public static IEnumerable<object[]> Char_ChangeCase_MemberData() { yield return new object[] { 'A', "en-US" }; // ASCII upper case yield return new object[] { 'a', "en-US" }; // ASCII lower case yield return new object[] { '\u0130', "en-US" }; // non-ASCII, English yield return new object[] { '\u4F60', "zh-Hans" }; // non-ASCII, Chinese } [Benchmark(InnerIterationCount = InnerIterations)] [MemberData(nameof(Char_ChangeCase_MemberData))] public static char Char_ToLower(char c, string cultureName) { char ret = default(char); CultureInfo culture = new CultureInfo(cultureName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < InnerIterations; i++) { ret = Char.ToLower(c, culture); } } } return ret; } [Benchmark(InnerIterationCount = InnerIterations)] [MemberData(nameof(Char_ChangeCase_MemberData))] public static char Char_ToUpper(char c, string cultureName) { char ret = default(char); CultureInfo culture = new CultureInfo(cultureName); foreach (var iteration in Benchmark.Iterations) { using (iteration.StartMeasurement()) { for (int i = 0; i < InnerIterations; i++) { ret = Char.ToUpper(c, culture); } } } return ret; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Xunit.Performance; namespace System.Tests { public class Perf_Char { [Benchmark] public static char Char_ToLower() { char ret = default(char); foreach (var iteration in Benchmark.Iterations) using (iteration.StartMeasurement()) ret = Char.ToLower('A'); return ret; } } }
mit
C#
66bc10eb2cbd02ad1290d3a37a7be8c87f660942
update 1.0.3
arichika/AspNet.Identity.Oracle,arichika/AspNet.Identity.Oracle,arichika/AspNet.Identity.Oracle
Src/AspNet.Identity.Oracle/Properties/AssemblyInfo.cs
Src/AspNet.Identity.Oracle/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("AspNet.Identity.Oracle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspNet.Identity.Oracle")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7403FCE0-1BCC-4DB6-8241-5D8A4FC0FDA1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.3.0")] [assembly: AssemblyFileVersion("1.0.3.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AspNet.Identity.Oracle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AspNet.Identity.Oracle")] [assembly: AssemblyCopyright("")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7403FCE0-1BCC-4DB6-8241-5D8A4FC0FDA1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
C#
d649e2eef58c8ba5dfda30172f77d78903325f5d
Fix all violations of SX1309S
tunnelvisionlabs/InheritanceMargin
Tvl.VisualStudio.InheritanceMargin/RoslynUtilities.cs
Tvl.VisualStudio.InheritanceMargin/RoslynUtilities.cs
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Microsoft Reciprocal License (MS-RL). See LICENSE in the project root for license information. namespace Tvl.VisualStudio.InheritanceMargin { using System; using Microsoft.VisualStudio.Shell.Interop; // Stolen from Microsoft.RestrictedUsage.CSharp.Utilities in Microsoft.VisualStudio.CSharp.Services.Language.dll internal static class RoslynUtilities { private static bool? _roslynInstalled; public static bool IsRoslynInstalled(IServiceProvider serviceProvider) { if (_roslynInstalled.HasValue) return _roslynInstalled.Value; _roslynInstalled = false; if (serviceProvider == null) return false; IVsShell vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell; if (vsShell == null) return false; Guid guid = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1"); int isInstalled; if (vsShell.IsPackageInstalled(ref guid, out isInstalled) == 0 && isInstalled != 0) _roslynInstalled = true; return _roslynInstalled.Value; } } }
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Microsoft Reciprocal License (MS-RL). See LICENSE in the project root for license information. namespace Tvl.VisualStudio.InheritanceMargin { using System; using Microsoft.VisualStudio.Shell.Interop; // Stolen from Microsoft.RestrictedUsage.CSharp.Utilities in Microsoft.VisualStudio.CSharp.Services.Language.dll internal static class RoslynUtilities { private static bool? roslynInstalled; public static bool IsRoslynInstalled(IServiceProvider serviceProvider) { if (roslynInstalled.HasValue) return roslynInstalled.Value; roslynInstalled = false; if (serviceProvider == null) return false; IVsShell vsShell = serviceProvider.GetService(typeof(SVsShell)) as IVsShell; if (vsShell == null) return false; Guid guid = new Guid("6cf2e545-6109-4730-8883-cf43d7aec3e1"); int isInstalled; if (vsShell.IsPackageInstalled(ref guid, out isInstalled) == 0 && isInstalled != 0) roslynInstalled = true; return roslynInstalled.Value; } } }
mit
C#
7a397306156b4cca31370eee6f40c0614763e38e
Update to Cake.Issues.Recipe 0.3.2
cake-contrib/Cake.Recipe,cake-contrib/Cake.Recipe
Cake.Recipe/Content/addins.cake
Cake.Recipe/Content/addins.cake
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.7.0 #addin nuget:?package=Cake.Coveralls&version=0.10.1 #addin nuget:?package=Cake.Coverlet&version=2.3.4 #addin nuget:?package=Cake.Email&version=0.9.1&loaddependencies=true // loading dependencies is important to ensure Cake.Email.Common is loaded as well #addin nuget:?package=Cake.Figlet&version=1.3.1 #addin nuget:?package=Cake.Gitter&version=0.11.1 #addin nuget:?package=Cake.Incubator&version=5.1.0 #addin nuget:?package=Cake.Kudu&version=0.10.1 #addin nuget:?package=Cake.MicrosoftTeams&version=0.9.0 #addin nuget:?package=Cake.ReSharperReports&version=0.11.1 #addin nuget:?package=Cake.Slack&version=0.13.0 #addin nuget:?package=Cake.Transifex&version=0.8.0 #addin nuget:?package=Cake.Twitter&version=0.10.1 #addin nuget:?package=Cake.Wyam&version=2.2.7 #load nuget:?package=Cake.Issues.Recipe&version=0.3.2 Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if (BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if (BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
/////////////////////////////////////////////////////////////////////////////// // ADDINS /////////////////////////////////////////////////////////////////////////////// #addin nuget:?package=Cake.Codecov&version=0.7.0 #addin nuget:?package=Cake.Coveralls&version=0.10.1 #addin nuget:?package=Cake.Coverlet&version=2.3.4 #addin nuget:?package=Cake.Email&version=0.9.1&loaddependencies=true // loading dependencies is important to ensure Cake.Email.Common is loaded as well #addin nuget:?package=Cake.Figlet&version=1.3.1 #addin nuget:?package=Cake.Gitter&version=0.11.1 #addin nuget:?package=Cake.Incubator&version=5.1.0 #addin nuget:?package=Cake.Kudu&version=0.10.1 #addin nuget:?package=Cake.MicrosoftTeams&version=0.9.0 #addin nuget:?package=Cake.ReSharperReports&version=0.11.1 #addin nuget:?package=Cake.Slack&version=0.13.0 #addin nuget:?package=Cake.Transifex&version=0.8.0 #addin nuget:?package=Cake.Twitter&version=0.10.1 #addin nuget:?package=Cake.Wyam&version=2.2.7 #load nuget:?package=Cake.Issues.Recipe&version=0.3.1 Action<string, IDictionary<string, string>> RequireAddin = (code, envVars) => { var script = MakeAbsolute(File(string.Format("./{0}.cake", Guid.NewGuid()))); try { System.IO.File.WriteAllText(script.FullPath, code); var arguments = new Dictionary<string, string>(); if (BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient") != null) { arguments.Add("nuget_useinprocessclient", BuildParameters.CakeConfiguration.GetValue("NuGet_UseInProcessClient")); } if (BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification") != null) { arguments.Add("settings_skipverification", BuildParameters.CakeConfiguration.GetValue("Settings_SkipVerification")); } CakeExecuteScript(script, new CakeSettings { EnvironmentVariables = envVars, Arguments = arguments }); } finally { if (FileExists(script)) { DeleteFile(script); } } };
mit
C#
470de0a629da75ed0ddd3e993b5858c1ff4a25f3
Fix the speed of the canvas width scaling by left/right arrow keys
setchi/NoteEditor,setchi/NotesEditor
Assets/Scripts/UI/CanvasWidthScalePresenter.cs
Assets/Scripts/UI/CanvasWidthScalePresenter.cs
using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class CanvasWidthScalePresenter : MonoBehaviour { [SerializeField] CanvasEvents canvasEvents; [SerializeField] Slider canvasWidthScaleController; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { model.CanvasWidth = canvasEvents.MouseScrollWheelObservable .Where(_ => KeyInput.CtrlKey()) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.05f)) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.05f)) .Select(delta => model.CanvasWidth.Value * (1 + delta)) .Select(x => x / (model.Audio.clip.samples / 100f)) .Select(x => Mathf.Clamp(x, 0.1f, 2f)) .Merge(canvasWidthScaleController.OnValueChangedAsObservable() .DistinctUntilChanged()) .Select(x => model.Audio.clip.samples / 100f * x) .ToReactiveProperty(); } }
using UniRx; using UniRx.Triggers; using UnityEngine; using UnityEngine.UI; public class CanvasWidthScalePresenter : MonoBehaviour { [SerializeField] CanvasEvents canvasEvents; [SerializeField] Slider canvasWidthScaleController; NotesEditorModel model; void Awake() { model = NotesEditorModel.Instance; model.OnLoadedMusicObservable.First().Subscribe(_ => Init()); } void Init() { model.CanvasWidth = canvasEvents.MouseScrollWheelObservable .Where(_ => KeyInput.CtrlKey()) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.UpArrow)).Select(_ => 0.1f)) .Merge(this.UpdateAsObservable().Where(_ => Input.GetKey(KeyCode.DownArrow)).Select(_ => -0.1f)) .Select(delta => model.CanvasWidth.Value * (1 + delta)) .Select(x => x / (model.Audio.clip.samples / 100f)) .Select(x => Mathf.Clamp(x, 0.1f, 2f)) .Merge(canvasWidthScaleController.OnValueChangedAsObservable() .DistinctUntilChanged()) .Select(x => model.Audio.clip.samples / 100f * x) .ToReactiveProperty(); } }
mit
C#
1b92ef07c6ebb88b2dae1f09ace6825a9c6a1824
Enhance EdgeDirection-enum.
ExRam/ExRam.Gremlinq
ExRam.Gremlinq/EdgeDirection.cs
ExRam.Gremlinq/EdgeDirection.cs
using System; namespace ExRam.Gremlinq { [Flags] public enum EdgeDirection { None = 0, Out = 1, In = 2, Both = 3 } }
namespace ExRam.Gremlinq { public enum EdgeDirection { Out, In } }
mit
C#
17fbe7cbabe21dc62fff08a1f57668a8b1af4c46
fix model binding
Adiqq/aurelia-docker-dotnet,Adiqq/aurelia-docker-dotnet,Adiqq/aurelia-docker-dotnet,Adiqq/aurelia-docker-dotnet
API/src/WebAPI/Controllers/CommentsController.cs
API/src/WebAPI/Controllers/CommentsController.cs
using Microsoft.AspNetCore.Mvc; using Application.Commands; using WebAPI.Services; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace WebAPI.Controllers { [Route("api/[controller]")] public class CommentsController : Controller { private readonly IPageService _pageService; public CommentsController(IPageService pageService) { _pageService = pageService; } // POST api/values [HttpPost] public void Post([FromBody]CreateCommentCommand command) { _pageService.AddComment(command); } } }
using Microsoft.AspNetCore.Mvc; using Application.Commands; using WebAPI.Services; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace WebAPI.Controllers { [Route("api/[controller]")] public class CommentsController : Controller { private readonly IPageService _pageService; public CommentsController(IPageService pageService) { _pageService = pageService; } // POST api/values [HttpPost] public void Post(CreateCommentCommand command) { _pageService.AddComment(command); } } }
apache-2.0
C#
9f8019c8881d5b0ba5317ce83f0daae786aef370
Update unity networking for NETWORK_PHOTON. Updates for iTunes 1.2 build update. Advertiser id to vendor id for game analytics and update textures/showing fireworks/camera sorting.
drawcode/game-lib-engine
Engine/Game/Controllers/ThirdPersonPushBodies.cs
Engine/Game/Controllers/ThirdPersonPushBodies.cs
using System.Collections; using Engine; using Engine.Data; using Engine.Networking; using Engine.Utility; using UnityEngine; namespace Engine.Game.Controllers { #if NETWORK_PHOTON [RequireComponent(typeof(ThirdPersonController))] public class ThirdPersonPushBodies : BaseEngineBehavior { public float pushPower = 0.5f; public LayerMask pushLayers = -1; private BaseThirdPersonController controller; private void Start() { controller = GetComponent<BaseThirdPersonController>(); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; // no rigidbody if (body == null || body.isKinematic) return; // Ignore pushing those rigidbodies int bodyLayerMask = 1 << body.gameObject.layer; if ((bodyLayerMask & pushLayers.value) == 0) return; // We dont want to push objects below us if (hit.moveDirection.y < -0.3) return; // Calculate push direction from move direction, we only push objects to the sides // never up and down Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z); // push with move speed but never more than walkspeed body.velocity = pushDir * pushPower * Mathf.Min(controller.GetSpeed(), controller.walkSpeed); } } #endif }
using System.Collections; using Engine; using Engine.Data; using Engine.Networking; using Engine.Utility; using UnityEngine; namespace Engine.Game.Controllers { [RequireComponent(typeof(ThirdPersonController))] public class ThirdPersonPushBodies : BaseEngineBehavior { public float pushPower = 0.5f; public LayerMask pushLayers = -1; private BaseThirdPersonController controller; private void Start() { controller = GetComponent<BaseThirdPersonController>(); } private void OnControllerColliderHit(ControllerColliderHit hit) { Rigidbody body = hit.collider.attachedRigidbody; // no rigidbody if (body == null || body.isKinematic) return; // Ignore pushing those rigidbodies int bodyLayerMask = 1 << body.gameObject.layer; if ((bodyLayerMask & pushLayers.value) == 0) return; // We dont want to push objects below us if (hit.moveDirection.y < -0.3) return; // Calculate push direction from move direction, we only push objects to the sides // never up and down Vector3 pushDir = new Vector3(hit.moveDirection.x, 0, hit.moveDirection.z); // push with move speed but never more than walkspeed body.velocity = pushDir * pushPower * Mathf.Min(controller.GetSpeed(), controller.walkSpeed); } } }
mit
C#
139cb2c9870d441f52399c32073fdfe7b9cbd06b
Switch to in memory key store
codeforamerica/denver-schedules-api,codeforamerica/denver-schedules-api,schlos/denver-schedules-api,schlos/denver-schedules-api
Schedules.API/CustomBootstrapper.cs
Schedules.API/CustomBootstrapper.cs
using Nancy; using Nancy.TinyIoc; using Nancy.Bootstrapper; using Newtonsoft.Json; using Schedules.API; using Nancy.Authentication.Token; using Nancy.Authentication.Token.Storage; namespace Schedules.API { public class CustomBootstrapper: DefaultNancyBootstrapper { protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(typeof(JsonSerializer), typeof(CustomJsonSerializer)); // TODO - Add something custom to the Tokenizer (commented example below shows passing cfg to constructor). container.Register<ITokenizer>(new Tokenizer( cfg => cfg.WithKeyCache(new InMemoryTokenKeyStore()) // cfg => cfg.AdditionalItems( // ctx => ctx.Request.Headers["X-Custom-Header"].FirstOrDefault(), // ctx => ctx.Request.Query.extraValue) )); } protected override void RequestStartup (TinyIoCContainer container, IPipelines pipelines, NancyContext context) { TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration (container.Resolve<ITokenizer>())); pipelines.BeforeRequest.AddItemToStartOfPipeline(c => { if (c.Request.Method != "OPTIONS") return null; return new Response { StatusCode = HttpStatusCode.NoContent } .WithHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE") .WithHeader("Access-Control-Allow-Headers", "Content-Type"); }); pipelines.AfterRequest.AddItemToEndOfPipeline(c => c.Response.WithHeader("Access-Control-Allow-Origin", "*") ); } protected override void ApplicationStartup (TinyIoCContainer container, IPipelines pipelines) { pipelines.OnError.AddItemToEndOfPipeline((context, exception) => { System.Console.Error.WriteLine(exception.ToString()); return null; }); } } }
using Nancy; using Nancy.TinyIoc; using Nancy.Bootstrapper; using Newtonsoft.Json; using Schedules.API; using Nancy.Authentication.Token; using System.Linq; namespace Schedules.API { public class CustomBootstrapper: DefaultNancyBootstrapper { protected override void ConfigureApplicationContainer(TinyIoCContainer container) { base.ConfigureApplicationContainer(container); container.Register(typeof(JsonSerializer), typeof(CustomJsonSerializer)); // TODO - Add something custom to the Tokenizer (commented example below shows passing cfg to constructor). container.Register<ITokenizer>(new Tokenizer() // ( // cfg => cfg.AdditionalItems( // ctx => ctx.Request.Headers["X-Custom-Header"].FirstOrDefault(), // ctx => ctx.Request.Query.extraValue) // ) ); } protected override void RequestStartup (TinyIoCContainer container, IPipelines pipelines, NancyContext context) { TokenAuthentication.Enable(pipelines, new TokenAuthenticationConfiguration (container.Resolve<ITokenizer>())); pipelines.BeforeRequest.AddItemToStartOfPipeline(c => { if (c.Request.Method != "OPTIONS") return null; return new Response { StatusCode = HttpStatusCode.NoContent } .WithHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, PUT, DELETE") .WithHeader("Access-Control-Allow-Headers", "Content-Type"); }); pipelines.AfterRequest.AddItemToEndOfPipeline(c => c.Response.WithHeader("Access-Control-Allow-Origin", "*") ); } protected override void ApplicationStartup (TinyIoCContainer container, IPipelines pipelines) { pipelines.OnError.AddItemToEndOfPipeline((context, exception) => { System.Console.Error.WriteLine(exception.ToString()); return null; }); } } }
mit
C#
b945af41375bfd4cd0bb793586d1af5053077189
Change IPublish component to use enumerable of AbsolutePath for package files
nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke
source/Nuke.Components/IPublish.cs
source/Nuke.Components/IPublish.cs
// Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Nuke.Common; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.Git.GitTasks; using static Nuke.Common.ValueInjection.ValueInjectionUtility; namespace Nuke.Components { [PublicAPI] public interface IPublish : IPack, ITest { [Parameter] string NuGetSource => TryGetValue(() => NuGetSource) ?? "https://api.nuget.org/v3/index.json"; [Parameter] [Secret] string NuGetApiKey => TryGetValue(() => NuGetApiKey); Target Publish => _ => _ .DependsOn(Test, Pack) .Requires(() => NuGetApiKey) // .Requires(() => GitHasCleanWorkingCopy()) .Executes(() => { DotNetNuGetPush(_ => _ .Apply(PushSettingsBase) .Apply(PushSettings) .CombineWith(PushPackageFiles, (_, v) => _ .SetTargetPath(v)) .Apply(PackagePushSettings), PushDegreeOfParallelism, PushCompleteOnFailure); }); sealed Configure<DotNetNuGetPushSettings> PushSettingsBase => _ => _ .SetSource(NuGetSource) .SetApiKey(NuGetApiKey); Configure<DotNetNuGetPushSettings> PushSettings => _ => _; Configure<DotNetNuGetPushSettings> PackagePushSettings => _ => _; IEnumerable<AbsolutePath> PushPackageFiles => PackagesDirectory.GlobFiles("*.nupkg"); bool PushCompleteOnFailure => true; int PushDegreeOfParallelism => 5; } }
// Copyright 2020 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.Linq; using JetBrains.Annotations; using Nuke.Common; using Nuke.Common.IO; using Nuke.Common.Tooling; using Nuke.Common.Tools.DotNet; using static Nuke.Common.Tools.DotNet.DotNetTasks; using static Nuke.Common.Tools.Git.GitTasks; using static Nuke.Common.ValueInjection.ValueInjectionUtility; namespace Nuke.Components { [PublicAPI] public interface IPublish : IPack, ITest { [Parameter] string NuGetSource => TryGetValue(() => NuGetSource) ?? "https://api.nuget.org/v3/index.json"; [Parameter] [Secret] string NuGetApiKey => TryGetValue(() => NuGetApiKey); Target Publish => _ => _ .DependsOn(Test, Pack) .Requires(() => NuGetApiKey) // .Requires(() => GitHasCleanWorkingCopy()) .Executes(() => { DotNetNuGetPush(_ => _ .Apply(PushSettingsBase) .Apply(PushSettings) .CombineWith(PushPackageFiles, (_, v) => _ .SetTargetPath(v)) .Apply(PackagePushSettings), PushDegreeOfParallelism, PushCompleteOnFailure); }); sealed Configure<DotNetNuGetPushSettings> PushSettingsBase => _ => _ .SetSource(NuGetSource) .SetApiKey(NuGetApiKey); Configure<DotNetNuGetPushSettings> PushSettings => _ => _; Configure<DotNetNuGetPushSettings> PackagePushSettings => _ => _; IEnumerable<string> PushPackageFiles => PackagesDirectory.GlobFiles("*.nupkg").Select(x => x.ToString()); bool PushCompleteOnFailure => true; int PushDegreeOfParallelism => 5; } }
mit
C#
0cabb64ca85cc963e347a6d56ba42ddf871c7d61
fix for combining absolute path
tudway/Qart,avao/Qart,mcraveiro/Qart
Src/Qart.Testing/ScopedDataStore.cs
Src/Qart.Testing/ScopedDataStore.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Qart.Testing { public class ScopedDataStore : IDataStore { private readonly IDataStore _dataStore; private readonly string _tag; public ScopedDataStore(IDataStore dataStore, string tag) { _dataStore = dataStore; _tag = tag; } public Stream GetReadStream(string id) { return _dataStore.GetReadStream(GetScopedId(id)); } public Stream GetWriteStream(string id) { return _dataStore.GetWriteStream(GetScopedId(id)); } public bool Contains(string id) { return _dataStore.Contains(GetScopedId(id)); } public IEnumerable<string> GetItemIds(string tag) { return _dataStore.GetItemIds(GetScopedId(tag)).Select(_ => _.Substring(_tag.Length + 1));//TODO mixing tags and ids } private string GetScopedId(string name) { if(!Path.IsPathRooted(name)) return Path.Combine(_tag, name); return name; } public IEnumerable<string> GetItemGroups(string group) { return _dataStore.GetItemGroups(GetScopedId(group)); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Qart.Testing { public class ScopedDataStore : IDataStore { private readonly IDataStore _dataStore; private readonly string _tag; public ScopedDataStore(IDataStore dataStore, string tag) { _dataStore = dataStore; _tag = tag; } public Stream GetReadStream(string id) { return _dataStore.GetReadStream(GetScopedId(id)); } public Stream GetWriteStream(string id) { return _dataStore.GetWriteStream(GetScopedId(id)); } public bool Contains(string id) { return _dataStore.Contains(GetScopedId(id)); } public IEnumerable<string> GetItemIds(string tag) { return _dataStore.GetItemIds(GetScopedId(tag)).Select(_ => _.Substring(_tag.Length + 1));//TODO mixing tags and ids } private string GetScopedId(string name) { return Path.Combine(_tag, name); } public IEnumerable<string> GetItemGroups(string group) { return _dataStore.GetItemGroups(GetScopedId(group)); } } }
apache-2.0
C#
91dbba13442ae93fd93acf79071f0c53529f912e
Fix broken test
Kantis/GitVersion,asbjornu/GitVersion,distantcam/GitVersion,alexhardwicke/GitVersion,MarkZuber/GitVersion,Kantis/GitVersion,anobleperson/GitVersion,DanielRose/GitVersion,GitTools/GitVersion,TomGillen/GitVersion,onovotny/GitVersion,anobleperson/GitVersion,openkas/GitVersion,dpurge/GitVersion,pascalberger/GitVersion,anobleperson/GitVersion,gep13/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,orjan/GitVersion,distantcam/GitVersion,orjan/GitVersion,Kantis/GitVersion,JakeGinnivan/GitVersion,pascalberger/GitVersion,Philo/GitVersion,RaphHaddad/GitVersion,alexhardwicke/GitVersion,gep13/GitVersion,FireHost/GitVersion,TomGillen/GitVersion,ermshiperete/GitVersion,dazinator/GitVersion,JakeGinnivan/GitVersion,onovotny/GitVersion,GeertvanHorrik/GitVersion,GitTools/GitVersion,GeertvanHorrik/GitVersion,DanielRose/GitVersion,ermshiperete/GitVersion,onovotny/GitVersion,MarkZuber/GitVersion,openkas/GitVersion,Philo/GitVersion,JakeGinnivan/GitVersion,dpurge/GitVersion,dpurge/GitVersion,pascalberger/GitVersion,FireHost/GitVersion,JakeGinnivan/GitVersion,RaphHaddad/GitVersion,DanielRose/GitVersion,ermshiperete/GitVersion,ParticularLabs/GitVersion,ParticularLabs/GitVersion,dpurge/GitVersion
Tests/BuildServers/TeamCityTests.cs
Tests/BuildServers/TeamCityTests.cs
using GitVersion; using NUnit.Framework; [TestFixture] public class TeamCityTests { [Test] public void Develop_branch() { var arguments = new Arguments(); var versionBuilder = new TeamCity(arguments); var tcVersion = versionBuilder.GenerateSetVersionMessage("0.0.0-Unstable4"); Assert.AreEqual("##teamcity[buildNumber '0.0.0-Unstable4']", tcVersion); } [Test] public void EscapeValues() { var arguments = new Arguments(); var versionBuilder = new TeamCity(arguments); var tcVersion = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##teamcity[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[0]); Assert.AreEqual("##teamcity[setParameter name='system.GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[1]); } }
using GitVersion; using NUnit.Framework; [TestFixture] public class TeamCityTests { [Test] public void Develop_branch() { var arguments = new Arguments(); var versionBuilder = new TeamCity(arguments); var tcVersion = versionBuilder.GenerateSetVersionMessage("0.0.0-Unstable4"); Assert.AreEqual("##teamcity[buildNumber '0.0.0-Unstable4']", tcVersion); } [Test] public void EscapeValues() { var arguments = new Arguments(); var versionBuilder = new TeamCity(arguments); var tcVersion = versionBuilder.GenerateSetParameterMessage("Foo", "0.8.0-unstable568 Branch:'develop' Sha:'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb'"); Assert.AreEqual("##teamcity[setParameter name='GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[1]); Assert.AreEqual("##teamcity[setParameter name='system.GitVersion.Foo' value='0.8.0-unstable568 Branch:|'develop|' Sha:|'ee69bff1087ebc95c6b43aa2124bd58f5722e0cb|'']", tcVersion[3]); } }
mit
C#
9ac701f46bbe8c820ad6236db4260f3eb99ffd9f
Use ExpectedConditions for element exists check
kendaleiv/ui-specflow-selenium,kendaleiv/ui-specflow-selenium,kendaleiv/ui-specflow-selenium
Web.UI.Tests/WebBrowserWaitSteps.cs
Web.UI.Tests/WebBrowserWaitSteps.cs
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using TechTalk.SpecFlow; using Xunit; namespace Web.UI.Tests { [Binding] public class WebBrowserWaitSteps : WebDriverStepsBase { [When("I wait for element with id (.*) to exist")] public void IWaitForElementWithIdToExist(string id) { var wait = new WebDriverWait(Driver, TimeSpan.FromMinutes(1)); wait.Until<IWebElement>(ExpectedConditions.ElementExists(By.Id(id))); } [Then(@"I expect that the element with id (.*) exists")] public void ThenIExpectThatTheElementWithIdExists(string id) { var element = Driver.FindElement(By.Id(id)); Assert.NotNull(element); } } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.UI; using System; using TechTalk.SpecFlow; using Xunit; namespace Web.UI.Tests { [Binding] public class WebBrowserWaitSteps : WebDriverStepsBase { [When("I wait for element with id (.*) to exist")] public void IWaitForElementWithIdToExist(string id) { var wait = new WebDriverWait(Driver, TimeSpan.FromMinutes(1)); wait.Until<IWebElement>(x => { return x.FindElement(By.Id(id)); }); } [Then(@"I expect that the element with id (.*) exists")] public void ThenIExpectThatTheElementWithIdExists(string id) { var element = Driver.FindElement(By.Id(id)); Assert.NotNull(element); } } }
mit
C#
74ec3451b3cb5abb85d277ba962fbc1a8319c7d6
Update AuthorizationDecider.cs
Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek,Soluto/tweek
Tweek.ApiService.NetCore/Security/AuthorizationDecider.cs
Tweek.ApiService.NetCore/Security/AuthorizationDecider.cs
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using Engine; using Engine.Core.Context; using Engine.DataTypes; using FSharpUtils.Newtonsoft; using LanguageExt.Trans; using LanguageExt.SomeHelp; using LanguageExt.Trans.Linq; using LanguageExt; using static LanguageExt.Prelude; namespace Tweek.ApiService.NetCore.Security { public delegate bool CheckReadConfigurationAccess(ClaimsPrincipal identity, string path, ICollection<Identity> tweekIdentities); public static class Authorization { public static CheckReadConfigurationAccess CreateAccessChecker(ITweek tweek) { return (identity, path, tweekIdentities) => { if (path == "@tweek/_" || path.StartsWith("@tweek/auth")) return false; return tweekIdentities.Select(tweekIdentity => { var identityType = tweekIdentity.Type; var key = $"@tweek/auth/{identityType}/read_configuration"; var result = tweek.CalculateWithLocalContext(key, new HashSet<Identity>(), type => type == "token" ? (GetContextValue)((string q) => Optional(identity.FindFirst(q)).Map(x=>x.Value).Map(JsonValue.NewString)) : (_) => None) .SingleKey(key) .Map(j => j.AsString()) .Match(x => match(x, with("allow", (_) => true), with("deny", (_) => false), (claim) => Optional(identity.FindFirst(claim)).Match(c=> c.Value.Equals(tweekIdentity.Id, StringComparison.OrdinalIgnoreCase), ()=>false)), () => true); return result; }).All(x => x); }; } } }
using System.Collections.Generic; using System.Linq; using System.Security.Claims; using Engine; using Engine.Core.Context; using Engine.DataTypes; using FSharpUtils.Newtonsoft; using LanguageExt.Trans; using LanguageExt.SomeHelp; using LanguageExt.Trans.Linq; using LanguageExt; using static LanguageExt.Prelude; namespace Tweek.ApiService.NetCore.Security { public delegate bool CheckReadConfigurationAccess(ClaimsPrincipal identity, string path, ICollection<Identity> tweekIdentities); public static class Authorization { public static CheckReadConfigurationAccess CreateAccessChecker(ITweek tweek) { return (identity, path, tweekIdentities) => { if (path == "@tweek/_" || path.StartsWith("@tweek/auth")) return false; return tweekIdentities.Select(tweekIdentity => { var identityType = tweekIdentity.Type; var key = $"@tweek/auth/{identityType}/read_configuration"; var result = tweek.CalculateWithLocalContext(key, new HashSet<Identity>(), type => type == "token" ? (GetContextValue)((string q) => Optional(identity.FindFirst(q)).Map(x=>x.Value).Map(JsonValue.NewString)) : (_) => None) .SingleKey(key) .Map(j => j.AsString()) .Match(x => match(x, with("allow", (_) => true), with("deny", (_) => false), (claim) => Optional(identity.FindFirst(claim)).Match(c=> c.Value == tweekIdentity.Id, ()=>false)), () => true); return result; }).All(x => x); }; } } }
mit
C#
36dc9e3e553a320c87693c744fe951b18d21719f
fix unnecessary override of property.
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi.Fluent/ViewModels/Wallets/WalletViewModel.cs
WalletWasabi.Fluent/ViewModels/Wallets/WalletViewModel.cs
using NBitcoin; using ReactiveUI; using Splat; using System; using System.Collections; using System.Collections.ObjectModel; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using WalletWasabi.Fluent.ViewModels.Wallets.Actions; using WalletWasabi.Fluent.ViewModels.Wallets.HardwareWallet; using WalletWasabi.Fluent.ViewModels.Wallets.WatchOnlyWallet; using WalletWasabi.Gui; using WalletWasabi.Logging; using WalletWasabi.Wallets; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent.ViewModels.Wallets { public partial class WalletViewModel : WalletViewModelBase { protected WalletViewModel(UiConfig uiConfig, Wallet wallet) : base(wallet) { Disposables = Disposables is null ? new CompositeDisposable() : throw new NotSupportedException($"Cannot open {GetType().Name} before closing it."); uiConfig = Locator.Current.GetService<Global>().UiConfig; Observable.Merge( Observable.FromEventPattern(Wallet.TransactionProcessor, nameof(Wallet.TransactionProcessor.WalletRelevantTransactionProcessed)).Select(_ => Unit.Default)) .Throttle(TimeSpan.FromSeconds(0.1)) .Merge(uiConfig.WhenAnyValue(x => x.PrivacyMode).Select(_ => Unit.Default)) .Merge(Wallet.Synchronizer.WhenAnyValue(x => x.UsdExchangeRate).Select(_ => Unit.Default)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe( _ => { try { var balance = Wallet.Coins.TotalAmount(); Title = $"{WalletName} ({(uiConfig.PrivacyMode ? "#########" : balance.ToString(false))} BTC)"; TitleTip = balance.ToUsdString(Wallet.Synchronizer.UsdExchangeRate, uiConfig.PrivacyMode); } catch (Exception ex) { Logger.LogError(ex); } }) .DisposeWith(Disposables); } private CompositeDisposable Disposables { get; set; } public override string IconName => "web_asset_regular"; public static WalletViewModel Create(UiConfig uiConfig, Wallet wallet) { return wallet.KeyManager.IsHardwareWallet ? new HardwareWalletViewModel(uiConfig, wallet) : wallet.KeyManager.IsWatchOnly ? new WatchOnlyWalletViewModel(uiConfig, wallet) : new WalletViewModel(uiConfig, wallet); } } }
using NBitcoin; using ReactiveUI; using Splat; using System; using System.Collections; using System.Collections.ObjectModel; using System.Reactive; using System.Reactive.Disposables; using System.Reactive.Linq; using WalletWasabi.Fluent.ViewModels.Wallets.Actions; using WalletWasabi.Fluent.ViewModels.Wallets.HardwareWallet; using WalletWasabi.Fluent.ViewModels.Wallets.WatchOnlyWallet; using WalletWasabi.Gui; using WalletWasabi.Logging; using WalletWasabi.Wallets; using WalletWasabi.Gui.ViewModels; namespace WalletWasabi.Fluent.ViewModels.Wallets { public partial class WalletViewModel : WalletViewModelBase { private string _title; protected WalletViewModel(UiConfig uiConfig, Wallet wallet) : base(wallet) { Disposables = Disposables is null ? new CompositeDisposable() : throw new NotSupportedException($"Cannot open {GetType().Name} before closing it."); uiConfig = Locator.Current.GetService<Global>().UiConfig; Observable.Merge( Observable.FromEventPattern(Wallet.TransactionProcessor, nameof(Wallet.TransactionProcessor.WalletRelevantTransactionProcessed)).Select(_ => Unit.Default)) .Throttle(TimeSpan.FromSeconds(0.1)) .Merge(uiConfig.WhenAnyValue(x => x.PrivacyMode).Select(_ => Unit.Default)) .Merge(Wallet.Synchronizer.WhenAnyValue(x => x.UsdExchangeRate).Select(_ => Unit.Default)) .ObserveOn(RxApp.MainThreadScheduler) .Subscribe( _ => { try { var balance = Wallet.Coins.TotalAmount(); Title = $"{WalletName} ({(uiConfig.PrivacyMode ? "#########" : balance.ToString(false))} BTC)"; TitleTip = balance.ToUsdString(Wallet.Synchronizer.UsdExchangeRate, uiConfig.PrivacyMode); } catch (Exception ex) { Logger.LogError(ex); } }) .DisposeWith(Disposables); } private CompositeDisposable Disposables { get; set; } public override string Title { get => _title; protected set => this.RaiseAndSetIfChanged(ref _title, value); } public override string IconName => "web_asset_regular"; public static WalletViewModel Create(UiConfig uiConfig, Wallet wallet) { return wallet.KeyManager.IsHardwareWallet ? new HardwareWalletViewModel(uiConfig, wallet) : wallet.KeyManager.IsWatchOnly ? new WatchOnlyWalletViewModel(uiConfig, wallet) : new WalletViewModel(uiConfig, wallet); } } }
mit
C#
1c62d3ff825fc9e13a02790aa377987475205aa0
add my Spotify playlist to blog sidebar
csyntax/BlogSystem
Source/BlogSystem.Web/Views/Sidebar/Index.cshtml
Source/BlogSystem.Web/Views/Sidebar/Index.cshtml
@model BlogSystem.Web.ViewModels.Sidebar.SidebarViewModel @if (Model.RecentPosts.Any()) { <div class="widget"> <h3 class="widgettitle">Recent Posts</h3> <ul> @foreach (var post in Model.RecentPosts) { <li> @Html.RouteLink(post.Title, "Post", new { id = post.Id }) </li> } </ul> </div> } @if (Model.Pages.Any()) { <div class="widget"> <h3 class="widgettitle">Pages</h3> <ul> @foreach (var page in Model.Pages) { <li> @Html.RouteLink(page.Title, "Page", new { permalink = page.Permalink }) </li> } </ul> </div> } <div class="widget"> <iframe src="https://embed.spotify.com/?uri=spotify%3Auser%3A11184122126%3Aplaylist%3A4PVXpMtbqsumofoOEOL7Pj" width="300" height="500" frameborder="0" allowtransparency="true"></iframe> </div>
@model BlogSystem.Web.ViewModels.Sidebar.SidebarViewModel @if (Model.RecentPosts.Any()) { <div class="widget"> <h3 class="widgettitle">Recent Posts</h3> <ul> @foreach (var post in Model.RecentPosts) { <li> @Html.RouteLink(post.Title, "Post", new { id = post.Id }) </li> } </ul> </div> } @if (Model.Pages.Any()) { <div class="widget"> <h3 class="widgettitle">Pages</h3> <ul> @foreach (var page in Model.Pages) { <li> @Html.RouteLink(page.Title, "Page", new { permalink = page.Permalink }) </li> } </ul> </div> }
mit
C#
789dc26ba94bcd9dfcd350187c2d32515b5675cd
bump version to 3.8
darrenstarr/ironmeta
Source/IronMeta/Properties/CommonAssemblyInfo.cs
Source/IronMeta/Properties/CommonAssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCopyright("Copyright © Gordon Tisher 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.8.*")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyCopyright("Copyright © Gordon Tisher 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: AssemblyVersion("3.7.*")]
bsd-3-clause
C#
c2f0376467e6859e569da84fa0e14a37b1a56d05
Use new price providers and degare SmartBit
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
WalletWasabi/WebClients/ExchangeRateProviders.cs
WalletWasabi/WebClients/ExchangeRateProviders.cs
using NBitcoin; using System; using System.Collections.Generic; using System.Threading.Tasks; using WalletWasabi.Backend.Models; using WalletWasabi.Interfaces; using WalletWasabi.Logging; using WalletWasabi.WebClients.BlockchainInfo; using WalletWasabi.WebClients.Coinbase; using WalletWasabi.WebClients.Gemini; using WalletWasabi.WebClients.ItBit; using WalletWasabi.WebClients.SmartBit; namespace WalletWasabi.WebClients { public class ExchangeRateProvider : IExchangeRateProvider { private readonly IExchangeRateProvider[] ExchangeRateProviders = { new BlockchainInfoExchangeRateProvider(), new CoinstampExchangeRateProvider(), new CoinGeckoExchangeRateProvider(), new CoinbaseExchangeRateProvider(), new GeminiExchangeRateProvider(), new ItBitExchangeRateProvider() new SmartBitExchangeRateProvider(new SmartBitClient(Network.Main)), }; public async Task<List<ExchangeRate>> GetExchangeRateAsync() { List<ExchangeRate> exchangeRates = null; foreach (var provider in ExchangeRateProviders) { try { exchangeRates = await provider.GetExchangeRateAsync(); break; } catch (Exception ex) { // Ignore it and try with the next one Logger.LogTrace(ex); } } return exchangeRates; } } }
using NBitcoin; using System; using System.Collections.Generic; using System.Threading.Tasks; using WalletWasabi.Backend.Models; using WalletWasabi.Interfaces; using WalletWasabi.Logging; using WalletWasabi.WebClients.BlockchainInfo; using WalletWasabi.WebClients.Coinbase; using WalletWasabi.WebClients.Gemini; using WalletWasabi.WebClients.ItBit; using WalletWasabi.WebClients.SmartBit; namespace WalletWasabi.WebClients { public class ExchangeRateProvider : IExchangeRateProvider { private readonly IExchangeRateProvider[] ExchangeRateProviders = { new SmartBitExchangeRateProvider(new SmartBitClient(Network.Main)), new BlockchainInfoExchangeRateProvider(), new CoinbaseExchangeRateProvider(), new GeminiExchangeRateProvider(), new ItBitExchangeRateProvider() }; public async Task<List<ExchangeRate>> GetExchangeRateAsync() { List<ExchangeRate> exchangeRates = null; foreach (var provider in ExchangeRateProviders) { try { exchangeRates = await provider.GetExchangeRateAsync(); break; } catch (Exception ex) { // Ignore it and try with the next one Logger.LogTrace(ex); } } return exchangeRates; } } }
mit
C#
dd6624c0aea8692b6d1a9b0baa1d801a92006250
Update Support's email address on contact page. Was breaking the world, so it had to be done.
jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox,jpfultonzm/trainingsandbox
ZirMed.TrainingSandbox/Views/Home/Contact.cshtml
ZirMed.TrainingSandbox/Views/Home/Contact.cshtml
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@wechangedthis.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> </address>
@{ ViewBag.Title = "Contact"; } <h2>@ViewBag.Title.</h2> <h3>@ViewBag.Message</h3> <address> One Microsoft Way<br /> Redmond, WA 98052-6399<br /> <abbr title="Phone">P:</abbr> 425.555.0100 </address> <address> <strong>Support:</strong> <a href="mailto:Support@example.com">Support@example.com</a><br /> <strong>Marketing:</strong> <a href="mailto:Marketing@example.com">Marketing@example.com</a> </address>
mit
C#
f124216accb91717d140e52400da9165303e5a8d
Change from address on PERSTAT, OCD
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
Battery-Commander.Web/Jobs/PERSTATReportJob.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static IList<Address> Recipients => new List<Address>(new Address[] { FROM // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address FROM => new Address { Name = "C-2-116 FA", EmailAddress = "C-2-116FA@redleg.app" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { foreach (var unit in UnitService.List(db).GetAwaiter().GetResult()) { // HACK - Configure the recipients and units that this is going to be wired up for emailSvc .To(Recipients) .SetFrom(FROM.EmailAddress, FROM.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using FluentEmail.Core; using FluentEmail.Core.Models; using FluentScheduler; using System.Collections.Generic; using System.IO; namespace BatteryCommander.Web.Jobs { public class PERSTATReportJob : IJob { private static IList<Address> Recipients => new List<Address>(new Address[] { Matt // new Address { Name = "2-116 FA BN TOC", EmailAddress = "ng.fl.flarng.list.ngfl-2-116-fa-bn-toc@mail.mil" } }); internal static Address Matt => new Address { Name = "1LT Wagner", EmailAddress = "MattGWagner@gmail.com" }; private readonly Database db; private readonly IFluentEmail emailSvc; public PERSTATReportJob(Database db, IFluentEmail emailSvc) { this.db = db; this.emailSvc = emailSvc; } public virtual void Execute() { foreach (var unit in UnitService.List(db).GetAwaiter().GetResult()) { // HACK - Configure the recipients and units that this is going to be wired up for emailSvc .To(Recipients) .SetFrom(Matt.EmailAddress, Matt.Name) .Subject($"{unit.Name} | RED 1 PERSTAT") .UsingTemplateFromFile($"{Directory.GetCurrentDirectory()}/Views/Reports/Red1_Perstat.cshtml", unit) .Send(); } } } }
mit
C#
9b4c877a50ef9b3b8f8e2cbee702bf061b5fecdc
Remove unused property getter
rover886/CefSharp,zhangjingpu/CefSharp,Octopus-ITSM/CefSharp,NumbersInternational/CefSharp,dga711/CefSharp,VioletLife/CefSharp,gregmartinhtc/CefSharp,Livit/CefSharp,ruisebastiao/CefSharp,jamespearce2006/CefSharp,ITGlobal/CefSharp,NumbersInternational/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,windygu/CefSharp,NumbersInternational/CefSharp,joshvera/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,ITGlobal/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,rover886/CefSharp,illfang/CefSharp,rlmcneary2/CefSharp,yoder/CefSharp,joshvera/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,VioletLife/CefSharp,battewr/CefSharp,wangzheng888520/CefSharp,joshvera/CefSharp,jamespearce2006/CefSharp,Octopus-ITSM/CefSharp,Haraguroicha/CefSharp,joshvera/CefSharp,AJDev77/CefSharp,rlmcneary2/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,gregmartinhtc/CefSharp,battewr/CefSharp,Livit/CefSharp,dga711/CefSharp,windygu/CefSharp,twxstar/CefSharp,Octopus-ITSM/CefSharp,dga711/CefSharp,ruisebastiao/CefSharp,gregmartinhtc/CefSharp,jamespearce2006/CefSharp,Octopus-ITSM/CefSharp,AJDev77/CefSharp,VioletLife/CefSharp,AJDev77/CefSharp,haozhouxu/CefSharp,yoder/CefSharp,haozhouxu/CefSharp,illfang/CefSharp,yoder/CefSharp,illfang/CefSharp,ITGlobal/CefSharp,Haraguroicha/CefSharp,twxstar/CefSharp,yoder/CefSharp,AJDev77/CefSharp,jamespearce2006/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,twxstar/CefSharp,twxstar/CefSharp,haozhouxu/CefSharp,rover886/CefSharp,Livit/CefSharp,ruisebastiao/CefSharp,rlmcneary2/CefSharp,haozhouxu/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,windygu/CefSharp,ruisebastiao/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,battewr/CefSharp,Haraguroicha/CefSharp,Livit/CefSharp,ITGlobal/CefSharp
CefSharp.BrowserSubprocess/CefRenderProcess.cs
CefSharp.BrowserSubprocess/CefRenderProcess.cs
using System; using System.Threading.Tasks; using CefSharp.Internals; using System.Collections.Generic; using System.ServiceModel; namespace CefSharp.BrowserSubprocess { public class CefRenderProcess : CefSubProcess, IRenderProcess { private DuplexChannelFactory<IBrowserProcess> channelFactory; private CefBrowserBase browser; public CefRenderProcess(IEnumerable<string> args) : base(args) { } protected override void DoDispose(bool isDisposing) { DisposeMember(ref browser); base.DoDispose(isDisposing); } public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper) { browser = cefBrowserWrapper; if (ParentProcessId == null) { return; } var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId); var binding = BrowserProcessServiceHost.CreateBinding(); channelFactory = new DuplexChannelFactory<IBrowserProcess>( this, binding, new EndpointAddress(serviceName) ); channelFactory.Open(); var proxy = CreateBrowserProxy(); var javascriptObject = proxy.GetRegisteredJavascriptObjects(); Bind(javascriptObject); } public Task<JavascriptResponse> EvaluateScript(long frameId, string script, TimeSpan timeout) { var task = browser.EvaluateScript(frameId, script, timeout); return task; } public override IBrowserProcess CreateBrowserProxy() { return channelFactory.CreateChannel(); } } }
using System; using System.Threading.Tasks; using CefSharp.Internals; using System.Collections.Generic; using System.ServiceModel; namespace CefSharp.BrowserSubprocess { public class CefRenderProcess : CefSubProcess, IRenderProcess { private DuplexChannelFactory<IBrowserProcess> channelFactory; private CefBrowserBase browser; public CefBrowserBase Browser { get { return browser; } } public CefRenderProcess(IEnumerable<string> args) : base(args) { } protected override void DoDispose(bool isDisposing) { DisposeMember(ref browser); base.DoDispose(isDisposing); } public override void OnBrowserCreated(CefBrowserBase cefBrowserWrapper) { browser = cefBrowserWrapper; if (ParentProcessId == null) { return; } var serviceName = RenderprocessClientFactory.GetServiceName(ParentProcessId.Value, cefBrowserWrapper.BrowserId); var binding = BrowserProcessServiceHost.CreateBinding(); channelFactory = new DuplexChannelFactory<IBrowserProcess>( this, binding, new EndpointAddress(serviceName) ); channelFactory.Open(); var proxy = CreateBrowserProxy(); var javascriptObject = proxy.GetRegisteredJavascriptObjects(); Bind(javascriptObject); } public Task<JavascriptResponse> EvaluateScript(long frameId, string script, TimeSpan timeout) { var task = Browser.EvaluateScript(frameId, script, timeout); return task; } public override IBrowserProcess CreateBrowserProxy() { return channelFactory.CreateChannel(); } } }
bsd-3-clause
C#
6295314874406a34916d808179eb6666653cdd96
Update File.cs
tiksn/TIKSN-Framework
TIKSN.Core/Data/File.cs
TIKSN.Core/Data/File.cs
using System; namespace TIKSN.Data { public class File : FileInfo, IFile { public File(string path, byte[] content) : base(path) => this.Content = content ?? throw new ArgumentNullException(nameof(content)); public byte[] Content { get; } } public class File<TIdentity> : FileInfo<TIdentity>, IFile<TIdentity> where TIdentity : IEquatable<TIdentity> { public File(TIdentity id, string path, byte[] content) : base(id, path) => this.Content = content ?? throw new ArgumentNullException(nameof(content)); public byte[] Content { get; } } public class File<TIdentity, TMetadata> : FileInfo<TIdentity, TMetadata>, IFile<TIdentity, TMetadata> where TIdentity : IEquatable<TIdentity> { public File(TIdentity id, string path, TMetadata metadata, byte[] content) : base(id, path, metadata) => this.Content = content ?? throw new ArgumentNullException(nameof(content)); public byte[] Content { get; } } }
using System; namespace TIKSN.Data { public class File : FileInfo, IFile { public File(string path, byte[] content) : base(path) { Content = content ?? throw new ArgumentNullException(nameof(content)); } public byte[] Content { get; } } public class File<TIdentity> : FileInfo<TIdentity>, IFile<TIdentity> where TIdentity : IEquatable<TIdentity> { public File(TIdentity id, string path, byte[] content) : base(id, path) { Content = content ?? throw new ArgumentNullException(nameof(content)); } public byte[] Content { get; } } public class File<TIdentity, TMetadata> : FileInfo<TIdentity, TMetadata>, IFile<TIdentity, TMetadata> where TIdentity : IEquatable<TIdentity> { public File(TIdentity id, string path, TMetadata metadata, byte[] content) : base(id, path, metadata) { Content = content ?? throw new ArgumentNullException(nameof(content)); } public byte[] Content { get; } } }
mit
C#
3ce353de7541c304f461d14f0bf04f6cf5059903
Add missing ;
TeamnetGroup/schema2fm
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.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.Write(@"; } public override void Down() { Delete.Table("""); writer.Write(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) { writer.Write(@"namespace Cucu { [Migration("); writer.Write(DateTime.Now.ToString("yyyyMMddHHmmss")); writer.Write(@")] public class Vaca : Migration { public override void Up() { Create.Table("""); writer.Write(tableName); writer.Write(@""")"); columns.ToList().ForEach(c => { writer.WriteLine(); writer.Write(c.FluentMigratorCode()); }); writer.Write(@"; } public override void Down() { Delete.Table("""); writer.Write(tableName); writer.WriteLine(@""") } } }"); } } }
mit
C#
63999c9c7cf80de5563c85fe30b93d32bede2c21
Use autogenerated prop for Random instance
mspons/DiceApi
src/DiceApi.Core/Die.cs
src/DiceApi.Core/Die.cs
using System; namespace DiceApi.Core { public class Die { /// <summary> /// Initializes a new instance of <see cref="Die" /> with a /// specified number of sides. /// </summary> /// <param name="sides">Number of sides on the die.</param> public Die(int sides) { if (sides < 1) { throw new ArgumentOutOfRangeException(nameof(sides)); } this.Sides = sides; this.RandomNumberGenerator = new Random(); } /// <summary> /// Gets the number of sides on the die. /// </summary> /// <returns></returns> public int Sides { get; } /// <summary> /// Gets an instance of Random that we instantiate with the Die /// constructor. This is used by Roll() to create a random value /// for the die roll. /// </summary> private Random RandomNumberGenerator { get; } /// <summary> /// Rolls the die, returning its value. /// </summary> /// <returns>Result of die roll.</returns> public int Roll() { // Range for Next() is inclusive on the minimum, exclusive on the maximum return this.RandomNumberGenerator.Next(1, this.Sides + 1); } } }
using System; namespace DiceApi.Core { public class Die { /// <summary> /// Instance of Random that we'll instantiate with the die /// and use within the Roll() method. /// </summary> private readonly Random rng; /// <summary> /// Initializes a new instance of <see cref="Die" /> with a /// specified number of sides. /// </summary> /// <param name="sides">Number of sides on the die.</param> public Die(int sides) { if (sides < 1) { throw new ArgumentOutOfRangeException(nameof(sides)); } this.Sides = sides; this.rng = new Random(); } /// <summary> /// Gets the number of sides on the die. /// </summary> /// <returns></returns> public int Sides { get; } /// <summary> /// Rolls the die, returning its value. /// </summary> /// <returns>Result of die roll.</returns> public int Roll() { // Range for Next() is inclusive on the minimum, exclusive on the maximum return rng.Next(1, this.Sides + 1); } } }
mit
C#
3a3f70136a99389c7f66a7123d57acc66172225b
Fix missing override
Redth/EggsToGo,Redth/EggsToGo
src/EggsToGo/Command.cs
src/EggsToGo/Command.cs
using System; namespace EggsToGo { public class SwipeUpCommand : Command { public override string Value { get { return "UP"; } } } public class SwipeDownCommand : Command { public override string Value { get { return "DOWN"; } } } public class SwipeLeftCommand : Command { public override string Value { get { return "LEFT"; } } } public class SwipeRightCommand : Command { public override string Value { get { return "RIGHT"; } } } public class TapCommand : Command { public override string Value { get { return "TAP"; } } } public class LongTapCommand : Command { public override string Value { get { return "LONGTAP"; } } } public class KeyboardCommand : Command { public KeyboardCommand(char key) { KeyboardKey = key; } public char KeyboardKey { get; set; } public override string Value { get { return KeyboardKey.ToString(); } } } public abstract class Command { public abstract string Value { get; } public override bool Equals (object obj) { var cmd = obj as Command; if (cmd == null) return false; return cmd.Value.Equals (this.Value); } public override int GetHashCode() { return base.GetHashCode(); } public static SwipeUpCommand SwipeUp() { return new SwipeUpCommand(); } public static SwipeDownCommand SwipeDown() { return new SwipeDownCommand(); } public static SwipeLeftCommand SwipeLeft() { return new SwipeLeftCommand(); } public static SwipeRightCommand SwipeRight() { return new SwipeRightCommand(); } public static TapCommand Tap() { return new TapCommand(); } public static LongTapCommand LongTap() { return new LongTapCommand(); } public static KeyboardCommand Keyboard(char key) { return new KeyboardCommand(key); } } }
using System; namespace EggsToGo { public class SwipeUpCommand : Command { public override string Value { get { return "UP"; } } } public class SwipeDownCommand : Command { public override string Value { get { return "DOWN"; } } } public class SwipeLeftCommand : Command { public override string Value { get { return "LEFT"; } } } public class SwipeRightCommand : Command { public override string Value { get { return "RIGHT"; } } } public class TapCommand : Command { public override string Value { get { return "TAP"; } } } public class LongTapCommand : Command { public override string Value { get { return "LONGTAP"; } } } public class KeyboardCommand : Command { public KeyboardCommand(char key) { KeyboardKey = key; } public char KeyboardKey { get; set; } public override string Value { get { return KeyboardKey.ToString(); } } } public abstract class Command { public abstract string Value { get; } public override bool Equals (object obj) { var cmd = obj as Command; if (cmd == null) return false; return cmd.Value.Equals (this.Value); } public static SwipeUpCommand SwipeUp() { return new SwipeUpCommand(); } public static SwipeDownCommand SwipeDown() { return new SwipeDownCommand(); } public static SwipeLeftCommand SwipeLeft() { return new SwipeLeftCommand(); } public static SwipeRightCommand SwipeRight() { return new SwipeRightCommand(); } public static TapCommand Tap() { return new TapCommand(); } public static LongTapCommand LongTap() { return new LongTapCommand(); } public static KeyboardCommand Keyboard(char key) { return new KeyboardCommand(key); } } }
mit
C#
ea61651bbce553d01f6774c2b0e018c7f2b262ce
Rename DLL
hey-red/Mime
src/Mime/MagicNative.cs
src/Mime/MagicNative.cs
using System; using System.Runtime.InteropServices; namespace HeyRed.Mime { internal static class MagicNative { private const string MAGIC_LIB_PATH = "libmagic-1"; [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_open(MagicOpenFlags flags); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern int magic_load(IntPtr magic_cookie, string filename); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern void magic_close(IntPtr magic_cookie); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_file(IntPtr magic_cookie, string filename); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_buffer(IntPtr magic_cookie, byte[] buffer, int length); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_error(IntPtr magic_cookie); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern int magic_version(); } }
using System; using System.Runtime.InteropServices; namespace HeyRed.Mime { internal static class MagicNative { private const string MAGIC_LIB_PATH = "libmagic1"; [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_open(MagicOpenFlags flags); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern int magic_load(IntPtr magic_cookie, string filename); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern void magic_close(IntPtr magic_cookie); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_file(IntPtr magic_cookie, string filename); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_buffer(IntPtr magic_cookie, byte[] buffer, int length); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern IntPtr magic_error(IntPtr magic_cookie); [DllImport(MAGIC_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] public static extern int magic_version(); } }
mit
C#
7accd5ba5c8db69c165839c440f58605600a8168
Change UserInfo of CCAnimationFrame to be object instead of PlistDictionary. User can put what they want in there instead of strongly typed.
TukekeSoft/CocosSharp,netonjm/CocosSharp,haithemaraissia/CocosSharp,MSylvia/CocosSharp,mono/CocosSharp,haithemaraissia/CocosSharp,mono/CocosSharp,TukekeSoft/CocosSharp,hig-ag/CocosSharp,hig-ag/CocosSharp,netonjm/CocosSharp,zmaruo/CocosSharp,MSylvia/CocosSharp,zmaruo/CocosSharp
src/sprite_nodes/CCAnimationFrame.cs
src/sprite_nodes/CCAnimationFrame.cs
namespace CocosSharp { public class CCAnimationFrame { public CCSpriteFrame SpriteFrame { get; private set; } public float DelayUnits { get; private set; } public object UserInfo { get; private set; } #region Constructors public CCAnimationFrame(CCSpriteFrame spriteFrame, float delayUnits, object userInfo) { SpriteFrame = spriteFrame; DelayUnits = delayUnits; UserInfo = userInfo; } protected CCAnimationFrame(CCAnimationFrame animFrame) { SpriteFrame = animFrame.SpriteFrame; DelayUnits = animFrame.DelayUnits; UserInfo = animFrame.UserInfo; } #endregion Constructors public CCAnimationFrame Copy() { return new CCAnimationFrame(this); } } }
namespace CocosSharp { public class CCAnimationFrame { public CCSpriteFrame SpriteFrame { get; private set; } public float DelayUnits { get; private set; } public PlistDictionary UserInfo { get; private set; } #region Constructors public CCAnimationFrame(CCSpriteFrame spriteFrame, float delayUnits, PlistDictionary userInfo) { SpriteFrame = spriteFrame; DelayUnits = delayUnits; UserInfo = userInfo; } protected CCAnimationFrame(CCAnimationFrame animFrame) { SpriteFrame = animFrame.SpriteFrame; DelayUnits = animFrame.DelayUnits; UserInfo = animFrame.UserInfo; } #endregion Constructors public CCAnimationFrame Copy() { return new CCAnimationFrame(this); } } }
mit
C#
2fd0038154082ec3d622aa3ddff0e25ee29684ad
Fix checkmark being hidden after clicking current waveform opacity setting
smoogipooo/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,peppy/osu,UselessToucan/osu
osu.Game/Screens/Edit/WaveformOpacityMenuItem.cs
osu.Game/Screens/Edit/WaveformOpacityMenuItem.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Bindables; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Screens.Edit { internal class WaveformOpacityMenuItem : MenuItem { private readonly Bindable<float> waveformOpacity; private readonly Dictionary<float, TernaryStateRadioMenuItem> menuItemLookup = new Dictionary<float, TernaryStateRadioMenuItem>(); public WaveformOpacityMenuItem(Bindable<float> waveformOpacity) : base("Waveform opacity") { Items = new[] { createMenuItem(0.25f), createMenuItem(0.5f), createMenuItem(0.75f), createMenuItem(1f), }; this.waveformOpacity = waveformOpacity; waveformOpacity.BindValueChanged(opacity => { foreach (var kvp in menuItemLookup) kvp.Value.State.Value = kvp.Key == opacity.NewValue ? TernaryState.True : TernaryState.False; }, true); } private TernaryStateRadioMenuItem createMenuItem(float opacity) { var item = new TernaryStateRadioMenuItem($"{opacity * 100}%", MenuItemType.Standard, _ => updateOpacity(opacity)); menuItemLookup[opacity] = item; return item; } private void updateOpacity(float opacity) => waveformOpacity.Value = opacity; } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.Collections.Generic; using osu.Framework.Bindables; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics.UserInterface; namespace osu.Game.Screens.Edit { internal class WaveformOpacityMenuItem : MenuItem { private readonly Bindable<float> waveformOpacity; private readonly Dictionary<float, ToggleMenuItem> menuItemLookup = new Dictionary<float, ToggleMenuItem>(); public WaveformOpacityMenuItem(Bindable<float> waveformOpacity) : base("Waveform opacity") { Items = new[] { createMenuItem(0.25f), createMenuItem(0.5f), createMenuItem(0.75f), createMenuItem(1f), }; this.waveformOpacity = waveformOpacity; waveformOpacity.BindValueChanged(opacity => { foreach (var kvp in menuItemLookup) kvp.Value.State.Value = kvp.Key == opacity.NewValue; }, true); } private ToggleMenuItem createMenuItem(float opacity) { var item = new ToggleMenuItem($"{opacity * 100}%", MenuItemType.Standard, _ => updateOpacity(opacity)); menuItemLookup[opacity] = item; return item; } private void updateOpacity(float opacity) => waveformOpacity.Value = opacity; } }
mit
C#
8329e936831917ce2bfe72b5494c1b698ef878e9
Remove permission check on custom settings recipe step (#6086)
stevetayloruk/Orchard2,stevetayloruk/Orchard2,OrchardCMS/Brochard,petedavis/Orchard2,petedavis/Orchard2,OrchardCMS/Brochard,stevetayloruk/Orchard2,stevetayloruk/Orchard2,petedavis/Orchard2,xkproject/Orchard2,stevetayloruk/Orchard2,xkproject/Orchard2,OrchardCMS/Brochard,xkproject/Orchard2,xkproject/Orchard2,petedavis/Orchard2,xkproject/Orchard2
src/OrchardCore.Modules/OrchardCore.CustomSettings/Recipes/CustomSettingsStep.cs
src/OrchardCore.Modules/OrchardCore.CustomSettings/Recipes/CustomSettingsStep.cs
using System; using System.Linq; using System.Threading.Tasks; using OrchardCore.CustomSettings.Services; using OrchardCore.Recipes.Models; using OrchardCore.Recipes.Services; using OrchardCore.Settings; namespace OrchardCore.CustomSettings.Recipes { /// <summary> /// This recipe step updates the site settings. /// </summary> public class CustomSettingsStep : IRecipeStepHandler { private readonly ISiteService _siteService; private readonly CustomSettingsService _customSettingsService; public CustomSettingsStep( ISiteService siteService, CustomSettingsService customSettingsService) { _siteService = siteService; _customSettingsService = customSettingsService; } public async Task ExecuteAsync(RecipeExecutionContext context) { if (!String.Equals(context.Name, "custom-settings", StringComparison.OrdinalIgnoreCase)) { return; } var model = context.Step; var customSettingsList = (from property in model.Properties() where property.Name != "name" select property).ToArray(); var siteSettings = await _siteService.LoadSiteSettingsAsync(); foreach (var customSettings in customSettingsList) { siteSettings.Properties[customSettings.Name] = customSettings.Value; } await _siteService.UpdateSiteSettingsAsync(siteSettings); } } }
using System; using System.Linq; using System.Threading.Tasks; using OrchardCore.CustomSettings.Services; using OrchardCore.Recipes.Models; using OrchardCore.Recipes.Services; using OrchardCore.Settings; namespace OrchardCore.CustomSettings.Recipes { /// <summary> /// This recipe step updates the site settings. /// </summary> public class CustomSettingsStep : IRecipeStepHandler { private readonly ISiteService _siteService; private readonly CustomSettingsService _customSettingsService; public CustomSettingsStep( ISiteService siteService, CustomSettingsService customSettingsService) { _siteService = siteService; _customSettingsService = customSettingsService; } public async Task ExecuteAsync(RecipeExecutionContext context) { if (!String.Equals(context.Name, "custom-settings", StringComparison.OrdinalIgnoreCase)) { return; } var model = context.Step; var customSettingsList = (from property in model.Properties() where property.Name != "name" select property).ToArray(); var customSettingsNames = (from customSettings in customSettingsList select customSettings.Name).ToArray(); var customSettingsTypes = _customSettingsService.GetSettingsTypes(customSettingsNames).ToArray(); foreach (var customSettingsType in customSettingsTypes) { if (!await _customSettingsService.CanUserCreateSettingsAsync(customSettingsType)) { return; } } var siteSettings = await _siteService.LoadSiteSettingsAsync(); foreach (var customSettings in customSettingsList) { siteSettings.Properties[customSettings.Name] = customSettings.Value; } await _siteService.UpdateSiteSettingsAsync(siteSettings); } } }
bsd-3-clause
C#
6308ee4f878257295ee1017b6d29c0ebe0c7cda4
Remove Checkpoints table
andlju/swetugg-tix,andlju/swetugg-tix,andlju/swetugg-tix
src/Swetugg.Tix.Activity.ViewBuilder/Migrations/00000000_0000_InitialDatabase.cs
src/Swetugg.Tix.Activity.ViewBuilder/Migrations/00000000_0000_InitialDatabase.cs
using FluentMigrator; namespace Swetugg.Tix.Activity.ViewBuilder.Migrations { [Migration(0)] public class InitialDatabase : Migration { public override void Up() { Create.Schema("ActivityViews"); Create.Table("ActivityOverview") .InSchema("ActivityViews") .WithColumn("ActivityId").AsGuid().PrimaryKey() .WithColumn("TicketTypes").AsInt32() .WithColumn("TotalSeats").AsInt32() .WithColumn("FreeSeats").AsInt32(); Create.Table("TicketType") .InSchema("ActivityViews") .WithColumn("ActivityId").AsGuid().NotNullable().NotNullable() .WithColumn("TicketTypeId").AsGuid().NotNullable() .WithColumn("Limit").AsInt32().Nullable() .WithColumn("Reserved").AsInt32().WithDefaultValue(0).NotNullable(); Create.PrimaryKey().OnTable("TicketType") .WithSchema("ActivityViews") .Columns("ActivityId", "TicketTypeId"); } public override void Down() { Delete.Table("ActivityOverview").InSchema("ActivityViews"); Delete.Table("TicketType").InSchema("ActivityViews"); Delete.Schema("ActivityViews"); } } }
using FluentMigrator; namespace Swetugg.Tix.Activity.ViewBuilder.Migrations { [Migration(0)] public class InitialDatabase : Migration { public override void Up() { Create.Table("Checkpoint") .WithColumn("Name").AsString(200).PrimaryKey() .WithColumn("LastCheckpoint").AsInt64(); Create.Schema("ActivityViews"); Create.Table("ActivityOverview") .InSchema("ActivityViews") .WithColumn("ActivityId").AsGuid().PrimaryKey() .WithColumn("TicketTypes").AsInt32() .WithColumn("TotalSeats").AsInt32() .WithColumn("FreeSeats").AsInt32(); Create.Table("TicketType") .InSchema("ActivityViews") .WithColumn("ActivityId").AsGuid().NotNullable().NotNullable() .WithColumn("TicketTypeId").AsGuid().NotNullable() .WithColumn("Limit").AsInt32().Nullable() .WithColumn("Reserved").AsInt32().WithDefaultValue(0).NotNullable(); Create.PrimaryKey().OnTable("TicketType") .WithSchema("ActivityViews") .Columns("ActivityId", "TicketTypeId"); } public override void Down() { Delete.Table("Checkpoints"); Delete.Table("ActivityOverview").InSchema("ActivityViews"); Delete.Table("TicketType").InSchema("ActivityViews"); Delete.Schema("ActivityViews"); } } }
mit
C#
843feb4e0879d98e852c4f780a5c17ff8d807aca
Add more xmldoc to ControllableOverlayHeader
peppy/osu-new,UselessToucan/osu,EVAST9919/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu,smoogipooo/osu,peppy/osu,smoogipoo/osu,EVAST9919/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu,NeoAdonis/osu,ppy/osu,ppy/osu,NeoAdonis/osu,2yangk23/osu,UselessToucan/osu
osu.Game/Overlays/ControllableOverlayHeader.cs
osu.Game/Overlays/ControllableOverlayHeader.cs
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Overlays { /// <summary> /// <see cref="OverlayHeader"/> which contains <see cref="TabControl{T}"/>. /// </summary> /// <typeparam name="T">The type of item to be represented by tabs in <see cref="TabControl{T}"/>.</typeparam> public abstract class ControllableOverlayHeader<T> : OverlayHeader { private readonly Box controlBackground; protected ControllableOverlayHeader(OverlayColourScheme colourScheme) : base(colourScheme) { HeaderInfo.Add(new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { controlBackground = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Gray, }, CreateTabControl().With(control => control.Margin = new MarginPadding { Left = UserProfileOverlay.CONTENT_X_MARGIN }) } }); } [BackgroundDependencyLoader] private void load(OsuColour colours) { controlBackground.Colour = colours.ForOverlayElement(ColourScheme, 0.2f, 0.2f); } protected abstract TabControl<T> CreateTabControl(); } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Allocation; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Graphics.UserInterface; using osu.Game.Graphics; using osuTK.Graphics; namespace osu.Game.Overlays { /// <typeparam name="T">The type of item to be represented by tabs in <see cref="TabControl{T}"/>.</typeparam> public abstract class ControllableOverlayHeader<T> : OverlayHeader { private readonly Box controlBackground; protected ControllableOverlayHeader(OverlayColourScheme colourScheme) : base(colourScheme) { HeaderInfo.Add(new Container { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { controlBackground = new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.Gray, }, CreateTabControl().With(control => control.Margin = new MarginPadding { Left = UserProfileOverlay.CONTENT_X_MARGIN }) } }); } [BackgroundDependencyLoader] private void load(OsuColour colours) { controlBackground.Colour = colours.ForOverlayElement(ColourScheme, 0.2f, 0.2f); } protected abstract TabControl<T> CreateTabControl(); } }
mit
C#
aabc1bdcd12141a29f8e6ff3e4b3eb72b7fbd89b
add path resolver to ElementEditor
reinterpretcat/utymap,reinterpretcat/utymap,reinterpretcat/utymap
unity/Assets/UtymapLib/Maps/Data/ElementEditor.cs
unity/Assets/UtymapLib/Maps/Data/ElementEditor.cs
using System; using Assets.UtymapLib.Core; using Assets.UtymapLib.Core.Models; using Assets.UtymapLib.Infrastructure.Dependencies; using Assets.UtymapLib.Infrastructure.IO; using Assets.UtymapLib.Infrastructure.Primitives; namespace Assets.UtymapLib.Maps.Data { /// <summary> Specifies behavior of element editor. </summary> public interface IElementEditor { /// <summary> Adds element. </summary> void Add(Element element, Range<int> levelOfDetails); /// <summary> Edits element. </summary> void Edit(Element element, Range<int> levelOfDetails); /// <summary> Marks element with given id. </summary> void Delete(long elementId, Range<int> levelOfDetails); } /// <summary> /// Default implementation of <see cref="IElementEditor"/> which /// works with in-memory store. /// </summary> internal class ElementEditor : IElementEditor { private readonly Stylesheet _stylesheet; private readonly IPathResolver _resolver; [Dependency] public ElementEditor(Stylesheet stylesheet, IPathResolver resolver) { _stylesheet = stylesheet; _resolver = resolver; } /// <inheritdoc /> public void Add(Element element, Range<int> levelOfDetails) { UtymapLib.AddElementToInMemoryStore(_resolver.Resolve(_stylesheet.Path), element, levelOfDetails, message => { if (!String.IsNullOrEmpty(message)) throw new MapDataException(message); }); } /// <inheritdoc /> public void Edit(Element element, Range<int> levelOfDetails) { throw new NotImplementedException(); } /// <inheritdoc /> public void Delete(long elementId, Range<int> levelOfDetails) { throw new NotImplementedException(); } } }
using System; using Assets.UtymapLib.Core; using Assets.UtymapLib.Core.Models; using Assets.UtymapLib.Infrastructure.Dependencies; using Assets.UtymapLib.Infrastructure.Primitives; namespace Assets.UtymapLib.Maps.Data { /// <summary> Specifies behavior of element editor. </summary> public interface IElementEditor { /// <summary> Adds element. </summary> void Add(Element element, Range<int> levelOfDetails); /// <summary> Edits element. </summary> void Edit(Element element, Range<int> levelOfDetails); /// <summary> Marks element with given id. </summary> void Delete(long elementId, Range<int> levelOfDetails); } /// <summary> /// Default implementation of <see cref="IElementEditor"/> which /// works with in-memory store. /// </summary> internal class ElementEditor : IElementEditor { private readonly Stylesheet _stylesheet; [Dependency] public ElementEditor(Stylesheet stylesheet) { _stylesheet = stylesheet; } /// <inheritdoc /> public void Add(Element element, Range<int> levelOfDetails) { UtymapLib.AddElementToInMemoryStore(_stylesheet.Path, element, levelOfDetails, message => { if (!String.IsNullOrEmpty(message)) throw new MapDataException(message); }); } /// <inheritdoc /> public void Edit(Element element, Range<int> levelOfDetails) { throw new NotImplementedException(); } /// <inheritdoc /> public void Delete(long elementId, Range<int> levelOfDetails) { throw new NotImplementedException(); } } }
apache-2.0
C#
54db274c35fc6128c462c12553e0be0ab01e7118
Update file version to 2.2.1.4
JKennedy24/Xamarin.Forms.GoogleMaps,amay077/Xamarin.Forms.GoogleMaps,JKennedy24/Xamarin.Forms.GoogleMaps
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
Xamarin.Forms.GoogleMaps/Xamarin.Forms.GoogleMaps/Internals/ProductInformation.cs
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.4"; } }
using System; namespace Xamarin.Forms.GoogleMaps.Internals { internal class ProductInformation { public const string Author = "amay077"; public const string Name = "Xamarin.Forms.GoogleMaps"; public const string Copyright = "Copyright © amay077. 2016 - 2017"; public const string Trademark = ""; public const string Version = "2.2.1.3"; } }
mit
C#
79270263df3373b7e334d63f6bf83a62561a4a9e
Fix stop of host
generik0/Rik.CodeCamp
Src/Hosts/Rik.CodeCamp.Host/CodeCampControl.cs
Src/Hosts/Rik.CodeCamp.Host/CodeCampControl.cs
using System; using System.IO; using System.Threading.Tasks; using GAIT.Utilities.Logging; using NLog; using Rik.CodeCamp.Core; using Topshelf; using static GAIT.Utilities.GeneralBootstrapper; namespace Rik.CodeCamp.Host { internal class CodeCampControl : ServiceControl { private Bootstrapper _bootstrapper; private readonly ILogger _logger; public CodeCampControl() { _logger = LoggingFactory.Create(GetType()); } public bool Start(HostControl hostControl) { try { _bootstrapper = new Bootstrapper(); var worker = _bootstrapper.Resolve<IWorker>(); return worker.Start(); } catch (Exception exception) { _logger.Fatal(exception, "Start failed!!! "); } return false; } public bool Stop(HostControl hostControl) { try { Task.Run(() => { if (File.Exists("C:\\RikCodeCampDb.db")) { File.Delete("C:\\RikCodeCampDb.db"); } }); _bootstrapper?.Dispose(); CancelAll.Cancel(); return true; } catch (Exception exception) { _logger.Fatal(exception, "Stop failed!!! "); } return false; } } }
using System; using GAIT.Utilities.Logging; using NLog; using Rik.CodeCamp.Core; using Topshelf; using static GAIT.Utilities.GeneralBootstrapper; namespace Rik.CodeCamp.Host { internal class CodeCampControl : ServiceControl { private Bootstrapper _bootstrapper; private readonly ILogger _logger; public CodeCampControl() { _logger = LoggingFactory.Create(GetType()); } public bool Start(HostControl hostControl) { try { _bootstrapper = new Bootstrapper(); var worker = _bootstrapper.Resolve<IWorker>(); return worker.Start(); } catch (Exception exception) { _logger.Fatal(exception, "Start failed!!! "); } return false; } public bool Stop(HostControl hostControl) { try { _bootstrapper?.Dispose(); CancelAll.Cancel(); } catch (Exception exception) { _logger.Fatal(exception, "Stop failed!!! "); } return false; } } }
mit
C#
c9b9720fb11f96194ad67b37b670d8cbc3959962
Improve code
sakapon/Samples-2016,sakapon/Samples-2016
Wpf3DSample/DiceRotationWpf/EventsExtension.cs
Wpf3DSample/DiceRotationWpf/EventsExtension.cs
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Windows; using System.Windows.Input; namespace DiceRotationWpf { public class EventsExtension<TElement> where TElement : UIElement { public TElement Target { get; } Point MouseDragLastPoint; public IObservable<Vector> MouseDragDelta { get; } public EventsExtension(TElement target) { Target = target; // Replaces events with IObservable objects. var mouseDown = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseDown)).Select(e => e.EventArgs); var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseMove)).Select(e => e.EventArgs); var mouseUp = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseUp)).Select(e => e.EventArgs); var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseLeave)).Select(e => e.EventArgs); var mouseDownEnd = mouseUp.Merge(mouseLeave); MouseDragDelta = mouseDown .Select(e => e.GetPosition(Target)) .Do(p => MouseDragLastPoint = p) .SelectMany(p0 => mouseMove .TakeUntil(mouseDownEnd) .Select(e => new { p1 = MouseDragLastPoint, p2 = e.GetPosition(Target) }) .Do(_ => MouseDragLastPoint = _.p2) .Select(_ => _.p2 - _.p1)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reactive.Linq; using System.Reactive.Subjects; using System.Windows; using System.Windows.Input; namespace DiceRotationWpf { public class EventsExtension<TElement> where TElement : UIElement { public TElement Target { get; } Point MouseDragLastPoint; Subject<Vector> _MouseDragDelta = new Subject<Vector>(); public IObservable<Vector> MouseDragDelta => _MouseDragDelta; public EventsExtension(TElement target) { Target = target; // Replaces events with IObservable objects. var mouseDown = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseDown)).Select(e => e.EventArgs); var mouseMove = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseMove)).Select(e => e.EventArgs); var mouseUp = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseUp)).Select(e => e.EventArgs); var mouseLeave = Observable.FromEventPattern<MouseEventArgs>(Target, nameof(UIElement.MouseLeave)).Select(e => e.EventArgs); var mouseDownEnd = mouseUp.Merge(mouseLeave); mouseDown .Select(e => e.GetPosition(Target)) .Do(p => MouseDragLastPoint = p) .Subscribe(p0 => mouseMove .TakeUntil(mouseDownEnd) .Select(e => new { p1 = MouseDragLastPoint, p2 = e.GetPosition(Target) }) .Do(_ => MouseDragLastPoint = _.p2) .Do(_ => _MouseDragDelta.OnNext(_.p2 - _.p1)) .Subscribe()); } } }
mit
C#
aa1213bbcea67cfe74848bedf0d8255f720f7030
Improve skipping
slek120/Unity-Touch-Smoothing-One-Euro-Filter
OneEuroSmoothing.cs
OneEuroSmoothing.cs
using UnityEngine; using System.Collections; public class OneEuroSmoothing : MonoBehaviour { //Lower value reduces jitter (fcmin or minimum cutoff frequency) //Keep above 0. Start at 1. Adjust until jitter is reasonable. //Recommended 1 public float jitterReduction; //Higher values reduce lag (beta or slope of velocity for cutoff frequency) //Keep above 0. Start at 0. Increase until no lag. //Recommended 1 public float lagReduction; private Vector2 currentPosition; private Vector2 currentVelocity; private Vector2 filteredPosition; private Vector2 filteredVelocity; void Start () { currentPosition = Camera.main.WorldToScreenPoint (transform.position); currentVelocity = Vector2.zero; filteredPosition = Camera.main.WorldToScreenPoint (transform.position); filteredVelocity = Vector2.zero; } void Update () { if (Input.touchCount > 0) { UnityEngine.Touch touch = Input.GetTouch (0); currentPosition = touch.position; } currentVelocity = (currentPosition - filteredPosition) / Time.deltaTime; OneEuroFilter (currentPosition, currentVelocity, Time.deltaTime); transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (filteredPosition.x, filteredPosition.y, 8)); } void OneEuroFilter (Vector2 currentPosition, Vector2 currentVelocity, float dt) { if (Mathf.Approximately ((currentVelocity - filteredVelocity).sqrMagnitude, 0)) { //Skip if filtering is unnecessary filteredVelocity = currentVelocity; } else { //Get a smooth velocity using exponential smoothing filteredVelocity = Filter (currentVelocity, filteredVelocity, Alpha (Vector2.one, dt)); } if (Mathf.Approximately ((currentPosition - filteredPosition).sqrMagnitude, 0)) { //Skip if filtering is unnecessary filteredPosition = currentPosition; } else { //Use velocity to get smoothing factor for position Vector2 cutoffFrequency; cutoffFrequency.x = jitterReduction + 0.01f * lagReduction * Mathf.Abs (filteredVelocity.x); cutoffFrequency.y = jitterReduction + 0.01f * lagReduction * Mathf.Abs (filteredVelocity.y); //Get a smooth position using exponential smoothing with smoothing factor from velocity filteredPosition = Filter (currentPosition, filteredPosition, Alpha (cutoffFrequency, dt)); } } Vector2 Alpha (Vector2 cutoff, float dt) { float tauX = 1 / (2 * Mathf.PI * cutoff.x); float tauY = 1 / (2 * Mathf.PI * cutoff.y); float alphaX = 1 / (1 + tauX / dt); float alphaY = 1 / (1 + tauY / dt); alphaX = Mathf.Clamp (alphaX, 0, 1); alphaY = Mathf.Clamp (alphaY, 0, 1); return new Vector2 (alphaX, alphaY); } Vector2 Filter (Vector2 current, Vector2 previous, Vector2 alpha) { float x = alpha.x * current.x + (1 - alpha.x) * previous.x; float y = alpha.y * current.y + (1 - alpha.y) * previous.y; return new Vector2 (x, y); } }
using UnityEngine; using System.Collections; public class OneEuroSmoothing : MonoBehaviour { //Lower value reduces jitter (fcmin or minimum cutoff frequency) //Keep above 0. Start at 1. Adjust until jitter is reasonable. //Recommended 1 public float jitterReduction; //Higher values reduce lag (beta or slope of velocity for cutoff frequency) //Keep above 0. Start at 0. Increase until no lag. //Recommended 1 public float lagReduction; private Vector2 currentPosition; private Vector2 currentVelocity; private Vector2 filteredPosition; private Vector2 filteredVelocity; void Start () { currentPosition = Camera.main.WorldToScreenPoint (transform.position); currentVelocity = Vector2.zero; filteredPosition = Camera.main.WorldToScreenPoint (transform.position); filteredVelocity = Vector2.zero; } void Update () { if (Input.touchCount > 0) { UnityEngine.Touch touch = Input.GetTouch (0); currentPosition = touch.position; } currentVelocity = (currentPosition - filteredPosition) / Time.deltaTime; OneEuroFilter (currentPosition, currentVelocity, Time.deltaTime); transform.position = Camera.main.ScreenToWorldPoint (new Vector3 (filteredPosition.x, filteredPosition.y, 8)); } void OneEuroFilter (Vector2 currentPosition, Vector2 currentVelocity, float dt) { if (Mathf.Approximately (currentVelocity.x, filteredVelocity.x) && Mathf.Approximately (currentVelocity.y, filteredVelocity.y)) { //Skip if filtering is unnecessary filteredVelocity = currentVelocity; } else { //Get a smooth velocity using exponential smoothing filteredVelocity = Filter (currentVelocity, filteredVelocity, Alpha (Vector2.one, dt)); } if (Mathf.Approximately (currentPosition.x, filteredPosition.x) && Mathf.Approximately (currentPosition.y, filteredPosition.y)) { //Skip if filtering is unnecessary filteredPosition = currentPosition; } else { //Use velocity to get smoothing factor for position Vector2 cutoffFrequency; cutoffFrequency.x = jitterReduction + 0.01f * lagReduction * Mathf.Abs (filteredVelocity.x); cutoffFrequency.y = jitterReduction + 0.01f * lagReduction * Mathf.Abs (filteredVelocity.y); //Get a smooth position using exponential smoothing with smoothing factor from velocity filteredPosition = Filter (currentPosition, filteredPosition, Alpha (cutoffFrequency, dt)); } } Vector2 Alpha (Vector2 cutoff, float dt) { float tauX = 1 / (2 * Mathf.PI * cutoff.x); float tauY = 1 / (2 * Mathf.PI * cutoff.y); float alphaX = 1 / (1 + tauX / dt); float alphaY = 1 / (1 + tauY / dt); alphaX = Mathf.Clamp (alphaX, 0, 1); alphaY = Mathf.Clamp (alphaY, 0, 1); return new Vector2 (alphaX, alphaY); } Vector2 Filter (Vector2 current, Vector2 previous, Vector2 alpha) { float x = alpha.x * current.x + (1 - alpha.x) * previous.x; float y = alpha.y * current.y + (1 - alpha.y) * previous.y; return new Vector2 (x, y); } }
unlicense
C#
11b0f2ce0bf15e77d1bbe50becb19bd753534cdc
fix position of image on the screen
NataliaDSmirnova/CGAdvanced2017
Assets/Scripts/RenderObject.cs
Assets/Scripts/RenderObject.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RenderObject : MonoBehaviour { // input objects public GameObject renderObject; public Camera mainCamera; // private objects private RenderTexture renderTexture; private RawImage image; void Start() { // get raw image from scene (see RTSprite) image = GetComponent<RawImage>(); // create temprorary texture of screen size renderTexture = RenderTexture.GetTemporary(Screen.width, Screen.height); } void Update() { // rescale raw image size depending on screen size float height = image.rectTransform.sizeDelta.y; float width = height * Screen.width / (float)Screen.height; image.rectTransform.sizeDelta = new Vector2(width, height); // fix position of image in left lower corner image.rectTransform.anchoredPosition = new Vector2((width - Screen.width) / 2, (height - Screen.height) / 2); } void OnRenderObject() { // set our temprorary texture as target for rendering Graphics.SetRenderTarget(renderTexture); // clear render texture GL.Clear(false, true, new Color(0f, 0f, 0f)); if (renderObject == null) { Debug.Log("Object for rendering is not set"); return; } // get mesh from input object Mesh objectMesh = renderObject.GetComponent<MeshFilter>().sharedMesh; if (objectMesh == null) { Debug.Log("Can't get mesh from input object"); return; } // get mesh renderer from input object var renderer = renderObject.GetComponent<MeshRenderer>(); if (renderer == null) { Debug.Log("Can't get mesh renderer from input object"); return; } // activate first shader pass for our renderer renderer.material.SetPass(0); // draw mesh of input object to render texture Graphics.DrawMeshNow(objectMesh, renderObject.transform.localToWorldMatrix * mainCamera.worldToCameraMatrix); // set texture of raw image equals to our render texture image.texture = renderTexture; // render again to backbuffer Graphics.SetRenderTarget(null); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RenderObject : MonoBehaviour { // input objects public GameObject renderObject; public Camera mainCamera; // private objects private RenderTexture renderTexture; private RawImage image; void Start () { // get raw image from scene (see RTSprite) image = GetComponent<RawImage>(); // create temprorary texture of screen size renderTexture = RenderTexture.GetTemporary(Screen.width, Screen.height); } void Update () { // rescale raw image size depending on screen size float width = image.rectTransform.sizeDelta.x; float height = image.rectTransform.sizeDelta.y; image.rectTransform.sizeDelta = new Vector2(height * Screen.width / (float) Screen.height, height); } void OnRenderObject () { // set our temprorary texture as target for rendering Graphics.SetRenderTarget(renderTexture); // clear render texture GL.Clear(false, true, new Color(0f, 0f, 0f)); if (renderObject == null) { Debug.Log("Object for rendering is not set"); return; } // get mesh from input object Mesh objectMesh = renderObject.GetComponent<MeshFilter>().sharedMesh; if (objectMesh == null) { Debug.Log("Can't get mesh from input object"); return; } // get mesh renderer from input object var renderer = renderObject.GetComponent<MeshRenderer>(); if (renderer == null) { Debug.Log("Can't get mesh renderer from input object"); return; } // activate first shader pass for our renderer renderer.material.SetPass(0); // draw mesh of input object to render texture Graphics.DrawMeshNow(objectMesh, renderObject.transform.localToWorldMatrix * mainCamera.worldToCameraMatrix); // set texture of raw image equals to our render texture image.texture = renderTexture; // render again to backbuffer Graphics.SetRenderTarget(null); } }
mit
C#
3c062ceffe15f17c6464147c93bdb2682a29c0e5
Fix sample navigation
gjulianm/AncoraMVVM
AncoraMVVM.Phone.Sample/Properties/AssemblyInfo.cs
AncoraMVVM.Phone.Sample/Properties/AssemblyInfo.cs
using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using AncoraMVVM.Base; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie los valores de estos atributos para modificar la información // asociada a un ensamblado. [assembly: AssemblyTitle("AncoraMVVM.Phone7.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AncoraMVVM.Phone7.Sample")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si ComVisible se establece en False, los componentes COM no verán los // tipos de este ensamblado. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible en True en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("ccdc6d5e-b773-4d15-af8a-ad013291d061")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y revisión // mediante el carácter '*', como se muestra a continuación: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("es-ES")] [assembly: RootNamespace("AncoraMVVM.Phone.Sample")]
using AncoraMVVM.Base; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie los valores de estos atributos para modificar la información // asociada a un ensamblado. [assembly: AssemblyTitle("AncoraMVVM.Phone7.Sample")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("AncoraMVVM.Phone7.Sample")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si ComVisible se establece en False, los componentes COM no verán los // tipos de este ensamblado. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible en True en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como identificador de typelib si este proyecto se expone a COM [assembly: Guid("ccdc6d5e-b773-4d15-af8a-ad013291d061")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y revisión // mediante el carácter '*', como se muestra a continuación: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("es-ES")] [assembly: RootNamespace("AncoraMVVM.Phone7.Sample")]
mpl-2.0
C#
28fd3f00cb3009cd5dbd7dd8669f5d857e35a624
Fix for search by rank
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Controllers/SSDController.cs
Battery-Commander.Web/Controllers/SSDController.cs
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class SSDController : Controller { private readonly Database db; public SSDController(Database db) { this.db = db; } public async Task<IActionResult> Index(SoldierSearchService.Query query) { if (query?.Ranks?.Any() == true) { // Cool, we're searching for one or more specific ranks } else { query.OnlyEnlisted = true; } return View("List", await SoldierSearchService.Filter(db, query)); } [HttpPost] public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion) { // Take the models and pull the updated data var soldier = await SoldiersController.Get(db, soldierId); soldier .SSDSnapshots .Add(new Soldier.SSDSnapshot { SSD = ssd, PerecentComplete = completion / 100 // Convert to decimal percentage }); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
using BatteryCommander.Web.Models; using BatteryCommander.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; namespace BatteryCommander.Web.Controllers { [Authorize, ApiExplorerSettings(IgnoreApi = true)] public class SSDController : Controller { private readonly Database db; public SSDController(Database db) { this.db = db; } public async Task<IActionResult> Index(SoldierSearchService.Query query) { // Ensure we're only displaying Soldiers we care about here if (!query.Ranks.Any()) query.OnlyEnlisted = true; return View("List", await SoldierSearchService.Filter(db, query)); } [HttpPost] public async Task<IActionResult> Update(int soldierId, SSD ssd, decimal completion) { // Take the models and pull the updated data var soldier = await SoldiersController.Get(db, soldierId); soldier .SSDSnapshots .Add(new Soldier.SSDSnapshot { SSD = ssd, PerecentComplete = completion / 100 // Convert to decimal percentage }); await db.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
mit
C#
657a7a79bf5c8f764f33b2a5043608ce3536170e
Add display_name field for UserProfile
Inumedia/SlackAPI
SlackAPI/UserProfile.cs
SlackAPI/UserProfile.cs
namespace SlackAPI { public class UserProfile : ProfileIcons { public string title; public string display_name; public string first_name; public string last_name; public string real_name; public string email; public string skype; public string status_emoji; public string status_text; public string phone; public override string ToString() { return real_name; } } }
namespace SlackAPI { public class UserProfile : ProfileIcons { public string title; public string first_name; public string last_name; public string real_name; public string email; public string skype; public string status_emoji; public string status_text; public string phone; public override string ToString() { return real_name; } } }
mit
C#