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
265560062f3b134b0f0eb77e56ec400918858e4b
add current and next build to view data
half-ogre/qed,Haacked/qed
RequestHandlers/GetHome.cs
RequestHandlers/GetHome.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using fn = qed.Functions; namespace qed { public static partial class Handlers { public static Task GetHome( IDictionary<string, object> environment, Func<IDictionary<string, object>, Task> next) { var buildConfigurations = fn.GetBuildConfigurations(); var configuredRepos = buildConfigurations .Select(bc => new { owner = bc.Owner, name = bc.Name, lastBuild = fn.GetLastFinishedBuild(bc.Owner, bc.Name).To(build => new { id = build.Id, description = fn.GetBuildDescription(build), status = GetBuildStatus(build) }), currentBuild = fn.GetCurrentBuild(bc.Owner, bc.Name).To(build => new { id = build.Id, description = fn.GetBuildDescription(build), status = GetBuildStatus(build) }), nextBuild = fn.GetNextBuild(bc.Owner, bc.Name).To(build => new { id = build.Id, description = fn.GetBuildDescription(build), status = GetBuildStatus(build) }) }) .ToList(); return environment.Render("home", new { configuredRepos }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using fn = qed.Functions; namespace qed { public static partial class Handlers { public static Task GetHome( IDictionary<string, object> environment, Func<IDictionary<string, object>, Task> next) { var buildConfigurations = fn.GetBuildConfigurations(); var configuredRepos = buildConfigurations .Select(bc => new { owner = bc.Owner, name = bc.Name, lastBuild = fn.GetLastFinishedBuild(bc.Owner, bc.Name).To(build => new { id = build.Id, description = fn.GetBuildDescription(build), status = GetBuildStatus(build) }) }) .ToList(); return environment.Render("home", new { configuredRepos }); } } }
mit
C#
496212916aa5d32359566866402f71866002d11f
update MI_Record with 0.2 features
nerai/CMenu
src/ExampleMenu/MI_Record.cs
src/ExampleMenu/MI_Record.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using ConsoleMenu; namespace ExampleMenu { public class MI_Record : CMenu { private List<string> _Lines; private string _EndRecordCommand = "endrecord"; public string EndRecordCommand { get { return _EndRecordCommand; } set { this[_EndRecordCommand].Selector = value; _EndRecordCommand = value; } } public MI_Record () : base ("record") { HelpText = "" + Selector + " name\n" + "Records all subsequent commands to the specified file name.\n" + "Recording can be stopped by the command \"" + EndRecordCommand + "\"\n" + "Stored records can be played via the \"replay\" command.\n" + "\n" + "Nested recording is not supported."; Add (EndRecordCommand, s => MenuResult.Quit, "Finishes recording."); Add (null, s => _Lines.Add (s)); } public override MenuResult Execute (string arg) { if (string.IsNullOrWhiteSpace (arg)) { Console.WriteLine ("You must enter a name to identify this command group."); return MenuResult.Normal; } _Lines = new List<string> (); Run (); Directory.CreateDirectory (".\\Records\\"); File.WriteAllLines (".\\Records\\" + arg + ".txt", _Lines); return MenuResult.Normal; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using ConsoleMenu; namespace ExampleMenu { public class MI_Record : CMenuItem { public string EndrecordCommand = "endrecord"; public MI_Record () : base ("record") { HelpText = "" + "record name\n" + "Records all subsequent commands to the specified file name.\n" + "Recording can be stopped by the command \"" + EndrecordCommand + "\"\n" + "Stored records can be played via the \"replay\" command.\n" + "\n" + "Nested recording is not supported."; } public override MenuResult Execute (string arg) { if (string.IsNullOrWhiteSpace (arg)) { Console.WriteLine ("You must enter a name to identify this command group."); return MenuResult.Normal; } var lines = new List<string> (); for (; ; ) { var line = Console.ReadLine (); if (EndrecordCommand.Equals (line)) { break; } lines.Add (line); } Directory.CreateDirectory (".\\Records\\"); File.WriteAllLines (".\\Records\\" + arg + ".txt", lines); return MenuResult.Normal; } } }
mit
C#
bdafa4de1fc7b2a064547a475027d1ab3fe8b3f5
Update location
planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell,planetpowershell/planetpowershell
src/Firehose.Web/Authors/KevinMarquette.cs
src/Firehose.Web/Authors/KevinMarquette.cs
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class KevinMarquette : IAmAMicrosoftMVP { public string FirstName => "Kevin"; public string LastName => "Marquette"; public string ShortBioOrTagLine => "Principal DevOps Engineer, Microsoft MVP, 2018 PowerShell Community Hero, and SoCal PowerShell UserGroup Organizer."; public string StateOrRegion => "Irvine, CA, USA"; public string EmailAddress => "kevmar@gmail.com"; public string TwitterHandle => "kevinmarquette"; public string GitHubHandle => "kevinmarquette"; public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142"; public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000); public Uri WebSite => new Uri("https://PowerShellExplained.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershellexplained.com/feed.xml"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.ServiceModel.Syndication; using System.Web; using Firehose.Web.Infrastructure; namespace Firehose.Web.Authors { public class KevinMarquette : IAmAMicrosoftMVP { public string FirstName => "Kevin"; public string LastName => "Marquette"; public string ShortBioOrTagLine => "Principal DevOps Engineer, Microsoft MVP, 2018 PowerShell Community Hero, and SoCal PowerShell UserGroup Organizer."; public string StateOrRegion => "Orange County, USA"; public string EmailAddress => "kevmar@gmail.com"; public string TwitterHandle => "kevinmarquette"; public string GitHubHandle => "kevinmarquette"; public string GravatarHash => "d7d29e9573b5da44d9886df24fcc6142"; public GeoPosition Position => new GeoPosition(33.6800000,-117.7900000); public Uri WebSite => new Uri("https://PowerShellExplained.com"); public IEnumerable<Uri> FeedUris { get { yield return new Uri("https://powershellexplained.com/feed.xml"); } } } }
mit
C#
a875c2ca22437cc352d79108158bf527caf54c6a
Handle a European apostrophe in escaped characters
nunit/teamcity-event-listener,nunit/teamcity-event-listener
src/extension/ServiceMessageWriter.cs
src/extension/ServiceMessageWriter.cs
namespace NUnit.Engine.Listeners { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; [SuppressMessage("ReSharper", "UseNameofExpression")] internal class ServiceMessageWriter { private const string Header = "##teamcity["; private const string Footer = "]"; public void Write(TextWriter writer, ServiceMessage serviceMessage) { if (writer == null) throw new ArgumentNullException("writer"); writer.Write(Header); writer.Write(serviceMessage.Name); foreach (var attribute in serviceMessage.Attributes) { writer.Write(' '); Write(writer, attribute); } writer.Write(Footer); } private void Write(TextWriter writer, ServiceMessageAttr attribute) { writer.Write(attribute.Name); writer.Write("='"); writer.Write(EscapeString(attribute.Value)); writer.Write('\''); } private static string EscapeString(string value) { return value != null ? value.Replace("|", "||") .Replace("'", "|'") .Replace("’", "|’") .Replace("\n", "|n") .Replace("\r", "|r") .Replace(char.ConvertFromUtf32(int.Parse("0086", NumberStyles.HexNumber)), "|x") .Replace(char.ConvertFromUtf32(int.Parse("2028", NumberStyles.HexNumber)), "|l") .Replace(char.ConvertFromUtf32(int.Parse("2029", NumberStyles.HexNumber)), "|p") .Replace("[", "|[") .Replace("]", "|]") : null; } } }
namespace NUnit.Engine.Listeners { using System; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; [SuppressMessage("ReSharper", "UseNameofExpression")] internal class ServiceMessageWriter { private const string Header = "##teamcity["; private const string Footer = "]"; public void Write(TextWriter writer, ServiceMessage serviceMessage) { if (writer == null) throw new ArgumentNullException("writer"); writer.Write(Header); writer.Write(serviceMessage.Name); foreach (var attribute in serviceMessage.Attributes) { writer.Write(' '); Write(writer, attribute); } writer.Write(Footer); } private void Write(TextWriter writer, ServiceMessageAttr attribute) { writer.Write(attribute.Name); writer.Write("='"); writer.Write(EscapeString(attribute.Value)); writer.Write('\''); } private static string EscapeString(string value) { return value != null ? value.Replace("|", "||") .Replace("'", "|'") .Replace("\n", "|n") .Replace("\r", "|r") .Replace(char.ConvertFromUtf32(int.Parse("0086", NumberStyles.HexNumber)), "|x") .Replace(char.ConvertFromUtf32(int.Parse("2028", NumberStyles.HexNumber)), "|l") .Replace(char.ConvertFromUtf32(int.Parse("2029", NumberStyles.HexNumber)), "|p") .Replace("[", "|[") .Replace("]", "|]") : null; } } }
mit
C#
e37ba75632810ad02adc43bc45fcff465dcacdd5
Update MemUtil.cs
FacticiusVir/SharpVk
SharpVk/SharpVk/MemUtil.cs
SharpVk/SharpVk/MemUtil.cs
using System; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SharpVk { /// <summary> /// /// </summary> public static class MemUtil { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static uint SizeOf<T>() { return SizeOfCache<T>.SizeOf; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> private static class SizeOfCache<T> { public static readonly uint SizeOf; static SizeOfCache() { SizeOf = (uint)Marshal.SizeOf(typeof(T)); } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dest"></param> /// <param name="value"></param> /// <param name="startIndex"></param> /// <param name="count"></param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void WriteToPtr<T>(IntPtr dest, T[] value, int startIndex, int count) where T : struct { if (count > 0) { int elementSize = (int)SizeOf<T>(); int transferSize = elementSize * count; int startOffset = elementSize * startIndex; byte* pointer = (byte*)dest.ToPointer(); pointer += startOffset; var handle = GCHandle.Alloc(value, GCHandleType.Pinned); byte* handlePointer = (byte*)handle.AddrOfPinnedObject().ToPointer(); //HACK Replace with by-platform optimisations for (int index = 0; index < transferSize; index++) { pointer[index] = handlePointer[index]; } handle.Free(); } } } }
using System; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace SharpVk { /// <summary> /// /// </summary> public static class MemUtil { /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static uint SizeOf<T>() { return SizeOfCache<T>.SizeOf; } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> private static class SizeOfCache<T> { public static readonly uint SizeOf; static SizeOfCache() { SizeOf = (uint)Marshal.SizeOf(typeof(T)); } } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dest"></param> /// <param name="value"></param> /// <param name="startIndex"></param> /// <param name="count"></param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public unsafe static void WriteToPtr<T>(IntPtr dest, T[] value, int startIndex, int count) where T : struct { if (count > 0) { int elementSize = (int)SizeOf<T>(); int transferSize = elementSize * count; byte* pointer = (byte*)dest.ToPointer(); var handle = GCHandle.Alloc(value, GCHandleType.Pinned); byte* handlePointer = (byte*)handle.AddrOfPinnedObject().ToPointer(); //HACK Replace with by-platform optimisations for (int index = 0; index < transferSize; index++) { pointer[index] = handlePointer[index]; } handle.Free(); } } } }
mit
C#
1d453e1c3f2e6e41c8f3b9964caa969471d6ac14
Update version from 0.2.0 to 0.3.0
IxMilia/Dxf,IxMilia/Dxf
src/IxMilia.Dxf/Properties/AssemblyInfo.cs
src/IxMilia.Dxf/Properties/AssemblyInfo.cs
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Runtime.CompilerServices; // 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("IxMilia.Dxf")] [assembly: AssemblyDescription("A portable .NET library for reading and writing DXF files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("IxMilia")] [assembly: AssemblyProduct("IxMilia.Dxf")] [assembly: AssemblyCopyright("Copyright © IxMilia 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.3.0.0")] [assembly: AssemblyFileVersion("0.3.0.0")] [assembly: InternalsVisibleTo("IxMilia.Dxf.Test")]
// Copyright (c) IxMilia. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Reflection; using System.Runtime.CompilerServices; // 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("IxMilia.Dxf")] [assembly: AssemblyDescription("A portable .NET library for reading and writing DXF files.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("IxMilia")] [assembly: AssemblyProduct("IxMilia.Dxf")] [assembly: AssemblyCopyright("Copyright © IxMilia 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: InternalsVisibleTo("IxMilia.Dxf.Test")]
apache-2.0
C#
efe1a1b826d404eb075f3124916c03ffe631d7ef
Change vehicle type enum
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Vehicle.cs
Battery-Commander.Web/Models/Vehicle.cs
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BatteryCommander.Web.Models { public class Vehicle { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int UnitId { get; set; } public virtual Unit Unit { get; set; } // Notes, What's broken about it? [Required] public VehicleStatus Status { get; set; } = VehicleStatus.FMC; [Required, StringLength(10)] public String Bumper { get; set; } [Required] public VehicleType Type { get; set; } = VehicleType.HMMWV; // public String Registration { get; set; } // public String Serial { get; set; } [Required] public int Seats { get; set; } = 2; // TroopCapacity? // Chalk Order? // LIN? // Fuel Card? Towbar? Water Buffalo? // Fuel Level? // Driver, A-Driver, Passengers, Assigned Section? public enum VehicleType : byte { HMMWV = 0, MTV = 1 } public enum VehicleStatus : byte { Unknown = 0, FMC = 1, NMC = byte.MaxValue } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BatteryCommander.Web.Models { public class Vehicle { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int UnitId { get; set; } public virtual Unit Unit { get; set; } // Notes, What's broken about it? [Required] public VehicleStatus Status { get; set; } = VehicleStatus.FMC; [Required, StringLength(10)] public String Bumper { get; set; } [Required] public VehicleType Type { get; set; } = VehicleType.HMMWV; // public String Registration { get; set; } // public String Serial { get; set; } [Required] public int Seats { get; set; } = 2; // TroopCapacity? // Chalk Order? // LIN? // Fuel Card? Towbar? Water Buffalo? // Fuel Level? // Driver, A-Driver, Passengers, Assigned Section? public enum VehicleType : byte { HMMWV = 0, LMTV = 1 } public enum VehicleStatus : byte { Unknown = 0, FMC = 1, NMC = byte.MaxValue } } }
mit
C#
a359e6abaf4f44c4b5da6385acd651e2630ce588
Fix display foe fuelcard/towbar header
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Models/Vehicle.cs
Battery-Commander.Web/Models/Vehicle.cs
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BatteryCommander.Web.Models { public class Vehicle { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int UnitId { get; set; } public virtual Unit Unit { get; set; } [Required] public VehicleStatus Status { get; set; } = VehicleStatus.FMC; [Required] public VehicleType Type { get; set; } = VehicleType.HMMWV; // Bumper, Registration, and Serial should be UNIQUE -- configured in Database.OnModelCreating [Required, StringLength(10)] public String Bumper { get; set; } [StringLength(10)] public String Registration { get; set; } [StringLength(50)] public String Serial { get; set; } [StringLength(20)] public String Nomenclature { get; set; } [StringLength(10)] public String LIN { get; set; } [Required] public int Seats { get; set; } = 2; // TroopCapacity? // Chalk Order? [Display(Name = "Fuel Card")] public Boolean HasFuelCard { get; set; } [Display(Name = "Tow Bar")] public Boolean HasTowBar { get; set; } // Fuel Level? // Has JBC-P? // Location? public Soldier Driver { get; set; } public int? DriverId { get; set; } [Display(Name = "A-Driver")] public Soldier A_Driver { get; set; } public int? A_DriverId { get; set; } // Passengers public String Notes { get; set; } public enum VehicleType : byte { HMMWV = 0, MTV = 1 } public enum VehicleStatus : byte { Unknown = 0, FMC = 1, NMC = byte.MaxValue } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BatteryCommander.Web.Models { public class Vehicle { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public int Id { get; set; } [Required] public int UnitId { get; set; } public virtual Unit Unit { get; set; } [Required] public VehicleStatus Status { get; set; } = VehicleStatus.FMC; [Required] public VehicleType Type { get; set; } = VehicleType.HMMWV; // Bumper, Registration, and Serial should be UNIQUE -- configured in Database.OnModelCreating [Required, StringLength(10)] public String Bumper { get; set; } [StringLength(10)] public String Registration { get; set; } [StringLength(50)] public String Serial { get; set; } [StringLength(20)] public String Nomenclature { get; set; } [StringLength(10)] public String LIN { get; set; } [Required] public int Seats { get; set; } = 2; // TroopCapacity? // Chalk Order? public Boolean HasFuelCard { get; set; } public Boolean HasTowBar { get; set; } // Fuel Level? // Has JBC-P? // Location? public Soldier Driver { get; set; } public int? DriverId { get; set; } [Display(Name = "A-Driver")] public Soldier A_Driver { get; set; } public int? A_DriverId { get; set; } // Passengers public String Notes { get; set; } public enum VehicleType : byte { HMMWV = 0, MTV = 1 } public enum VehicleStatus : byte { Unknown = 0, FMC = 1, NMC = byte.MaxValue } } }
mit
C#
8e4f815a0ebbbdb8adaf7787e3704654d0ea48b6
Bump version to 0.5.0.0
Ronald2/empleo-dot-net,Ronald2/empleo-dot-net,Ronald2/empleo-dot-net
EmpleoDotNet/Properties/AssemblyInfo.cs
EmpleoDotNet/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("EmpleoDotNet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EmpleoDotNet")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5042df17-bd29-4bd4-8c7c-4097bcb5e60e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.5.0.0")] [assembly: AssemblyFileVersion("0.5.0.0")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("EmpleoDotNet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EmpleoDotNet")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("5042df17-bd29-4bd4-8c7c-4097bcb5e60e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("0.4.0.0")] [assembly: AssemblyFileVersion("0.4.0.0")]
unlicense
C#
9fe6e1096ab9d9264f97f52ba8ed7ae504983d0b
Remove cruft from `SkinnableHealthDisplay`
NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,smoogipoo/osu,smoogipooo/osu,smoogipoo/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,ppy/osu,smoogipoo/osu,peppy/osu
osu.Game/Screens/Play/HUD/SkinnableHealthDisplay.cs
osu.Game/Screens/Play/HUD/SkinnableHealthDisplay.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.Game.Skinning; namespace osu.Game.Screens.Play.HUD { public class SkinnableHealthDisplay : SkinnableDrawable { public SkinnableHealthDisplay() : base(new HUDSkinComponent(HUDSkinComponents.HealthDisplay), _ => new DefaultHealthDisplay()) { CentreComponent = false; } } }
// 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; using osu.Framework.Bindables; using osu.Game.Rulesets.Scoring; using osu.Game.Skinning; namespace osu.Game.Screens.Play.HUD { public class SkinnableHealthDisplay : SkinnableDrawable { public Bindable<double> Current { get; } = new BindableDouble(1) { MinValue = 0, MaxValue = 1 }; private HealthProcessor processor; public void BindHealthProcessor(HealthProcessor processor) { if (this.processor != null) throw new InvalidOperationException("Can't bind to a processor more than once"); this.processor = processor; Current.BindTo(processor.Health); } public SkinnableHealthDisplay() : base(new HUDSkinComponent(HUDSkinComponents.HealthDisplay), _ => new DefaultHealthDisplay()) { CentreComponent = false; } } }
mit
C#
d666a4263c580b21c7221a972ee34aab65c86c6a
Update comment
AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Perspex,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,SuperJMN/Avalonia,grokys/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,Perspex/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,Perspex/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia
src/Avalonia.Controls/Diagnostics/ToolTipDiagnostics.cs
src/Avalonia.Controls/Diagnostics/ToolTipDiagnostics.cs
#nullable enable namespace Avalonia.Controls.Diagnostics { /// <summary> /// Helper class to provide diagnostics information for <see cref="ToolTip"/>. /// </summary> public static class ToolTipDiagnostics { public static AvaloniaProperty<ToolTip?> ToolTipProperty = ToolTip.ToolTipProperty; } }
#nullable enable namespace Avalonia.Controls.Diagnostics { /// <summary> /// Helper class to provide some diagnostics insides into <see cref="ToolTip"/>. /// </summary> public static class ToolTipDiagnostics { public static AvaloniaProperty<ToolTip?> ToolTipProperty = ToolTip.ToolTipProperty; } }
mit
C#
72b49d199ab5e4e615530a19c18807b2d818be58
Add more detail in documentation comment.
bfriesen/Rock.Core,peteraritchie/Rock.Core,RockFramework/Rock.Core
Rock.Core/AppSettingsApplicationInfo.cs
Rock.Core/AppSettingsApplicationInfo.cs
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rock { /// <summary> /// An implementation of <see cref="IApplicationInfo"/> that uses a config /// file's appSettings section. /// </summary> public class AppSettingsApplicationInfo : IApplicationInfo { private const string DefaultApplicationIdKey = "Rock.ApplicationId.Current"; private readonly string _applicationIdKey; /// <summary> /// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class. /// The key of the application ID setting will be "Rock.ApplicationId.Current". /// </summary> public AppSettingsApplicationInfo() : this(DefaultApplicationIdKey) { } /// <summary> /// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class. /// </summary> /// <param name="applicationIdKey">The key of the application ID setting.</param> public AppSettingsApplicationInfo(string applicationIdKey) { _applicationIdKey = applicationIdKey; } /// <summary> /// Gets the ID of the current application. /// </summary> public string ApplicationId { get { return ConfigurationManager.AppSettings[_applicationIdKey]; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Rock { /// <summary> /// An implementation of <see cref="IApplicationInfo"/> that uses a config /// file's appSettings section. /// </summary> public class AppSettingsApplicationInfo : IApplicationInfo { private const string DefaultApplicationIdKey = "Rock.ApplicationId.Current"; private readonly string _applicationIdKey; /// <summary> /// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class. /// </summary> public AppSettingsApplicationInfo() : this(DefaultApplicationIdKey) { } /// <summary> /// Initializes a new instance of the <see cref="AppSettingsApplicationInfo"/> class. /// </summary> /// <param name="applicationIdKey">The key of the application ID setting.</param> public AppSettingsApplicationInfo(string applicationIdKey) { _applicationIdKey = applicationIdKey; } /// <summary> /// Gets the ID of the current application. /// </summary> public string ApplicationId { get { return ConfigurationManager.AppSettings[_applicationIdKey]; } } } }
mit
C#
14d6b0258852dd7354bc349d7566dc5337905ac9
Fix ProjectN regression in `ByReference<T>` (dotnet/corert#6713)
wtgodbe/coreclr,mmitche/coreclr,cshung/coreclr,wtgodbe/coreclr,mmitche/coreclr,krk/coreclr,poizan42/coreclr,wtgodbe/coreclr,cshung/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr,mmitche/coreclr,wtgodbe/coreclr,krk/coreclr,cshung/coreclr,mmitche/coreclr,poizan42/coreclr,krk/coreclr,cshung/coreclr,mmitche/coreclr,krk/coreclr,poizan42/coreclr,krk/coreclr,wtgodbe/coreclr,poizan42/coreclr,poizan42/coreclr
src/System.Private.CoreLib/shared/System/ByReference.cs
src/System.Private.CoreLib/shared/System/ByReference.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.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { // ByReference<T> is meant to be used to represent "ref T" fields. It is working // around lack of first class support for byref fields in C# and IL. The JIT and // type loader has special handling for it that turns it into a thin wrapper around ref T. [NonVersionable] internal #if !PROJECTN // readonly breaks codegen contract and asserts UTC readonly #endif ref struct ByReference<T> { // CS0169: The private field '{blah}' is never used #pragma warning disable 169 private readonly IntPtr _value; #pragma warning restore [Intrinsic] public ByReference(ref T value) { // Implemented as a JIT intrinsic - This default implementation is for // completeness and to provide a concrete error if called via reflection // or if intrinsic is missed. throw new PlatformNotSupportedException(); } public ref T Value { [Intrinsic] get { // Implemented as a JIT intrinsic - This default implementation is for // completeness and to provide a concrete error if called via reflection // or if the intrinsic is missed. throw new PlatformNotSupportedException(); } } } }
// 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.Runtime.CompilerServices; using System.Runtime.Versioning; namespace System { // ByReference<T> is meant to be used to represent "ref T" fields. It is working // around lack of first class support for byref fields in C# and IL. The JIT and // type loader has special handling for it that turns it into a thin wrapper around ref T. [NonVersionable] internal readonly ref struct ByReference<T> { // CS0169: The private field '{blah}' is never used #pragma warning disable 169 private readonly IntPtr _value; #pragma warning restore [Intrinsic] public ByReference(ref T value) { // Implemented as a JIT intrinsic - This default implementation is for // completeness and to provide a concrete error if called via reflection // or if intrinsic is missed. throw new PlatformNotSupportedException(); } public ref T Value { [Intrinsic] get { // Implemented as a JIT intrinsic - This default implementation is for // completeness and to provide a concrete error if called via reflection // or if the intrinsic is missed. throw new PlatformNotSupportedException(); } } } }
mit
C#
dfc3e56eb79965117c4ebfb489d9e71779878b39
Check if we're in debug and set IncludeErrorPolicy accordingly
marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,KevinJump/Umbraco-CMS,marcemarc/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,KevinJump/Umbraco-CMS,arknu/Umbraco-CMS,umbraco/Umbraco-CMS,abryukhov/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,abryukhov/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,robertjf/Umbraco-CMS,arknu/Umbraco-CMS,robertjf/Umbraco-CMS,umbraco/Umbraco-CMS,umbraco/Umbraco-CMS,dawoe/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abjerner/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,mattbrailsford/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,abryukhov/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,arknu/Umbraco-CMS,abryukhov/Umbraco-CMS,umbraco/Umbraco-CMS,abjerner/Umbraco-CMS,dawoe/Umbraco-CMS
src/Umbraco.Web/WebApi/EnableDetailedErrorsAttribute.cs
src/Umbraco.Web/WebApi/EnableDetailedErrorsAttribute.cs
using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace Umbraco.Web.WebApi { /// <summary> /// Ensures controllers have detailed error messages even when debug mode is off /// </summary> public class EnableDetailedErrorsAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { actionContext.ControllerContext.Configuration.IncludeErrorDetailPolicy = HttpContext.Current.IsDebuggingEnabled ? IncludeErrorDetailPolicy.Always : IncludeErrorDetailPolicy.Default; } } }
using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; namespace Umbraco.Web.WebApi { /// <summary> /// Ensures controllers have detailed error messages even when debug mode is off /// </summary> public class EnableDetailedErrorsAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext actionContext) { actionContext.ControllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; } } }
mit
C#
3941ff5f84f68547e74fef7dd3c5d7309d1abff2
change version number
HeddaZ/ServiceOnset
ServiceOnset/Properties/AssemblyInfo.cs
ServiceOnset/Properties/AssemblyInfo.cs
using ServiceOnset; 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(AppHelper.AppTitle)] [assembly: AssemblyDescription(AppHelper.AppDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("+ii")] [assembly: AssemblyProduct("ServiceOnset")] [assembly: AssemblyCopyright("Copyright © +ii 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a7dc7161-b6aa-47d6-ba87-246289b305dc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.*")] [assembly: AssemblyFileVersion("1.2.0.0")]
using ServiceOnset; 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(AppHelper.AppTitle)] [assembly: AssemblyDescription(AppHelper.AppDescription)] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("+ii")] [assembly: AssemblyProduct("ServiceOnset")] [assembly: AssemblyCopyright("Copyright © +ii 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("a7dc7161-b6aa-47d6-ba87-246289b305dc")] // 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.1.*")] [assembly: AssemblyFileVersion("1.1.0.0")]
apache-2.0
C#
6e6c9e220e9805c01a7f16e222d64eb26a16074d
Fix html-style validation
brondavies/wwwplatform.net,brondavies/wwwplatform.net,brondavies/wwwplatform.net
src/web/Views/SharedFolders/Podcast.cshtml
src/web/Views/SharedFolders/Podcast.cshtml
<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet type="text/xsl" href="/Content/xsl/rss/display.xsl" ?> <?xml-stylesheet type="text/css" href="/Content/xsl/rss/display.css" ?> @using wwwplatform.Models; @model SharedFolder @helper Link (string url) { WriteLiteral("<link>"); WriteLiteral(url); WriteLiteral("</link>"); } <rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xml:lang="en-US"> <channel> <title>@Model.Name</title> @Link(Request.Url.OriginalString.ToLower()) <atom:link href="@Request.Url.OriginalString.ToLower()" rel="self" type="application/rss+xml" /> <description>@Model.Description</description> <itunes:owner> <itunes:name>@Settings.SiteOwner</itunes:name> <itunes:email>@Settings.EmailDefaultFrom</itunes:email> </itunes:owner> <itunes:author>@Model.UpdatedBy</itunes:author> <itunes:explicit>no</itunes:explicit> <itunes:category text="@Model.PodcastCategory"> <itunes:category text="@Model.PodcastSubCategory" /> </itunes:category> <copyright>Copyright @(DateTime.Now.Year) @(Settings.SiteOwner). All rights reserved.</copyright> <itunes:image href="@(Model.Poster?.GetUrl(Settings))" /> @foreach (var file in Model.Files.Where(f => f.GetFileType() == FileType.Audio).OrderByDescending(f => f.DisplayDate ?? f.UpdatedAt)) { <item> <title>@file.Name</title> <itunes:author /> <itunes:summary>@file.Description</itunes:summary> <itunes:image href="@file.GetPreviewUrl(Settings)" /> <itunes:keywords /> @Link(file.GetUrl(Settings)) <enclosure url="@file.GetUrl(Settings)" type="@file.GetMimeType()" length="@file.Size" /> <guid isPermaLink="true">@file.GetUrl(Settings)</guid> <pubDate>@((file.DisplayDate ?? file.UpdatedAt).ToUniversalTime().ToString("R"))</pubDate> </item> } </channel> </rss>
<?xml version="1.0" encoding="utf-8" ?> <?xml-stylesheet type="text/xsl" href="/Content/xsl/rss/display.xsl" ?> <?xml-stylesheet type="text/css" href="/Content/xsl/rss/display.css" ?> @using wwwplatform.Models; @model SharedFolder @helper Link (string url) { WriteLiteral("<link>"); WriteLiteral(url); WriteLiteral("</link>"); } <rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xml:lang="en-US"> <channel> <title>@Model.Name</title> <link>@Request.Url.OriginalString.ToLower()</link> <atom:link href="@Request.Url.OriginalString.ToLower()" rel="self" type="application/rss+xml" /> <description>@Model.Description</description> <itunes:owner> <itunes:name>@Settings.SiteOwner</itunes:name> <itunes:email>@Settings.EmailDefaultFrom</itunes:email> </itunes:owner> <itunes:author>@Model.UpdatedBy</itunes:author> <itunes:explicit>no</itunes:explicit> <itunes:category text="@Model.PodcastCategory"> <itunes:category text="@Model.PodcastSubCategory" /> </itunes:category> <copyright>Copyright @(DateTime.Now.Year) @(Settings.SiteOwner). All rights reserved.</copyright> <itunes:image href="@(Model.Poster?.GetUrl(Settings))" /> @foreach (var file in Model.Files.Where(f => f.GetFileType() == FileType.Audio).OrderByDescending(f => f.DisplayDate ?? f.UpdatedAt)) { <item> <title>@file.Name</title> <itunes:author /> <itunes:summary>@file.Description</itunes:summary> <itunes:image href="@file.GetPreviewUrl(Settings)" /> <itunes:keywords /> @Link(file.GetUrl(Settings)) <enclosure url="@file.GetUrl(Settings)" type="@file.GetMimeType()" length="@file.Size" /> <guid isPermaLink="true">@file.GetUrl(Settings)</guid> <pubDate>@((file.DisplayDate ?? file.UpdatedAt).ToUniversalTime().ToString("R"))</pubDate> </item> } </channel> </rss>
apache-2.0
C#
ddf62eb3c17e2fced1cc93702ce5fc1b8b066749
Fix namespace collision
ziyasal/Autofac.Extras.NLog
src/Autofac.Extras.NLog/NLogModule.cs
src/Autofac.Extras.NLog/NLogModule.cs
using System.Linq; using System.Reflection; using Autofac.Core; using NLog; // ReSharper disable RedundantUsingDirective using Module = Autofac.Module; // ReSharper restore RedundantUsingDirective namespace Autofac.Extras.NLog { public class NLogModule : Module { private static void InjectLoggerProperties(object instance) { var instanceType = instance.GetType(); // Get all the injectable properties to set. // If you wanted to ensure the properties were only UNSET properties, // here's where you'd do it. var properties = instanceType .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.PropertyType == typeof(ILogger) && p.CanWrite && p.GetIndexParameters().Length == 0); // Set the properties located. foreach (var propToSet in properties) { propToSet.SetValue(instance, new NLogger(LogManager.GetLogger(instanceType.FullName)), null); } } private static void OnComponentPreparing(object sender, PreparingEventArgs e) { var t = e.Component.Activator.LimitType; e.Parameters = e.Parameters.Union( new[] { new ResolvedParameter((p, i) => p.ParameterType == typeof (ILogger), (p, i) => new NLogger(LogManager.GetLogger(t.FullName))) }); } protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { // Handle constructor parameters. registration.Preparing += OnComponentPreparing; // Handle properties. registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance); } } }
using System.Linq; using System.Reflection; using Autofac.Core; using NLog; namespace Autofac.Extras.NLog { public class NLogModule : Module { private static void InjectLoggerProperties(object instance) { var instanceType = instance.GetType(); // Get all the injectable properties to set. // If you wanted to ensure the properties were only UNSET properties, // here's where you'd do it. var properties = instanceType .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.PropertyType == typeof(ILogger) && p.CanWrite && p.GetIndexParameters().Length == 0); // Set the properties located. foreach (var propToSet in properties) { propToSet.SetValue(instance, new NLogger(LogManager.GetLogger(instanceType.FullName)), null); } } private static void OnComponentPreparing(object sender, PreparingEventArgs e) { var t = e.Component.Activator.LimitType; e.Parameters = e.Parameters.Union( new[] { new ResolvedParameter((p, i) => p.ParameterType == typeof (ILogger), (p, i) => new NLogger(LogManager.GetLogger(t.FullName))) }); } protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration) { // Handle constructor parameters. registration.Preparing += OnComponentPreparing; // Handle properties. registration.Activated += (sender, e) => InjectLoggerProperties(e.Instance); } } }
mit
C#
8ede41ebb6a4d435f8f782507bad91ab2f97a142
Improve car handling
xorver/race-game
Assets/Scripts/Player.cs
Assets/Scripts/Player.cs
using UnityEngine; using UnityEngine.UI; using System.Collections; using System; public class Player : MonoBehaviour { public Text scoreText; public Text winText; public float movementSpeed = 15; public float turningSpeed = 60; public float cityMapWidth = 100f; public int pickUpsCount; private int score; private float time = 0f; private float accelerationTime; private float maxAccelerationTime; private float verticalAcceleration; void Start () { maxAccelerationTime = 3; accelerationTime = 0; Reset (); } void Update () { time -= Time.deltaTime; if (Input.GetAxis ("Vertical") > 0) { accelerationTime += accelerationTime < 0 ? Time.deltaTime * 4 : Time.deltaTime; accelerationTime = Math.Min (accelerationTime, maxAccelerationTime); } else if (Input.GetAxis ("Vertical") < 0) { accelerationTime -= accelerationTime > 0 ? Time.deltaTime * 4 : Time.deltaTime * 2; accelerationTime = Math.Max (accelerationTime, maxAccelerationTime * -1); } else { if (accelerationTime < 0) { accelerationTime += Time.deltaTime * 4; accelerationTime = Math.Min (accelerationTime, 0.0f); } else { accelerationTime -= Time.deltaTime * 2; accelerationTime = Math.Max (accelerationTime, 0.0f); } } float turningSpeedMod = 1.0f; verticalAcceleration = accelerationTime / maxAccelerationTime; if (verticalAcceleration < 0) { verticalAcceleration /= 2; turningSpeedMod *= 3; } float horizontal = Input.GetAxis ("Horizontal") * turningSpeed * Time.deltaTime * verticalAcceleration * turningSpeedMod; transform.RotateAround (transform.position, Vector3.up, horizontal); float vertical = verticalAcceleration * movementSpeed * Time.deltaTime; transform.Translate (0, 0, vertical); SetScoreText (); } void OnTriggerEnter (Collider other) { if (other.gameObject.CompareTag ("Pick Up")) { other.gameObject.SetActive (false); score += 1; SetScoreText (); } else if (other.gameObject.CompareTag ("Human") && Math.Abs(verticalAcceleration) > 0.05f) { Human human = other.GetComponent<Human>(); if (human.isAlive ()) time -= 20; human.kill (); } } public void Reset () { score = 0; time = 3 * 60f; SetScoreText (); SetWinText (""); transform.position = new Vector3 (cityMapWidth / 2, 1f, -10f); transform.rotation = Quaternion.identity; } private void SetScoreText() { scoreText.text = "Time: " + time.ToString("0.00") + "\nScore: " + score.ToString (); if (score >= pickUpsCount && time > 0) { SetWinText ("You Win!\nTime: " + time.ToString("0.00")); } if (time < 0) { SetWinText ("You Lose!\nScore: " + score.ToString("0")); } } private void SetWinText(string text) { winText.text = text; } }
using UnityEngine; using UnityEngine.UI; using System.Collections; using System; public class Player : MonoBehaviour { public Text scoreText; public Text winText; public float movementSpeed = 10; public float turningSpeed = 60; public float cityMapWidth = 100f; public int pickUpsCount; private int score; private float time = 0f; void Start () { Reset (); } void Update () { time -= Time.deltaTime; float horizontal = Input.GetAxis ("Horizontal") * turningSpeed * Time.deltaTime; transform.RotateAround (transform.position, Vector3.up, horizontal); float vertical = Input.GetAxis ("Vertical") * movementSpeed * Time.deltaTime; transform.Translate (0, 0, vertical); SetScoreText (); } void OnTriggerEnter (Collider other) { if (other.gameObject.CompareTag ("Pick Up")) { other.gameObject.SetActive (false); score += 1; SetScoreText (); } else if (other.gameObject.CompareTag ("Human") && Input.GetAxis ("Vertical") > 0.0f) { Human human = other.GetComponent<Human>(); if (human.isAlive ()) time -= 20; human.kill (); } } public void Reset () { score = 0; time = 3 * 60f; SetScoreText (); SetWinText (""); transform.position = new Vector3 (cityMapWidth / 2, 1f, -10f); transform.rotation = Quaternion.identity; } private void SetScoreText() { scoreText.text = "Time: " + time.ToString("0.00") + "\nScore: " + score.ToString (); if (score >= pickUpsCount && time > 0) { SetWinText ("You Win!\nTime: " + time.ToString("0.00")); } if (time < 0) { SetWinText ("You Lose!\nScore: " + score.ToString("0")); } } private void SetWinText(string text) { winText.text = text; } }
mit
C#
40806ec2ac052835601c67d214189cb4370f1e9c
Update index.cshtml
Aleksandrovskaya/apmathclouddif
site/index.cshtml
site/index.cshtml
@{ double t_0 = 0; double t_end = 150; double step = 0.1; int N = Convert.ToInt32((t_end-t_0)/step) + 1; String data = ""; bool show_chart = false; if (IsPost){ show_chart = true; var number = Request["text1"]; double xd = number.AsInt(); double t = 0; double x1 = 0; double x2 = 0; double x3 = 0; double currentx1 = 0; double currentx2 = 0; double currentx3 = 0; for (int i=0; i < N; ++i){ t = t_0 + step * i; currentx1 = x1 + step* (-0.1252*x1 + -0.004637*x2+-0.002198*x3); currentx2 = x2 + step*x1 ; currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd)); x1 = currentx1; x2 = currentx2; x3 = currentx3; data += "[" +t+"," + x2+"]"; if( i < N - 1){ data += ","; } } } } <html> <head> <meta charset="utf-8"> <title>MathBox</title> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Time', 'Height'], @data ]); var options = { title: 'pitch', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <form action="" method="post"> <p><label for="text1">Input Height</label><br> <input type="text" name="text1" /></p> <p><input type="submit" value=" Show " /></p> </form> @if (show_сhart) { <div id="curve_chart" style="width: 900px; height: 500px"></div> } else { <p></p> } </body> </html>
@{ double t_0 = 0; double t_end = 150; double step = 0.1; int N = Convert.ToInt32((t_end-t_0)/step) + 1; String data = ""; bool show_chart = false; if (IsPost){ show_chart = true; var number = Request["text1"]; double xd = number.AsInt(); double t = 0; double x1 = 0; double x2 = 0; double x3 = 0; double currentx1 = 0; double currentx2 = 0; double currentx3 = 0; for (int i=0; i < N; ++i){ t = t_0 + step * i; currentx1 = x1 + step* (-0.1252*x1 + -0.004637*x2+-0.002198*x3); currentx2 = x2 + step*x1 ; currentx3= x3 + step*(10*x1 + -0.2*x3 +1*(x2-xd)); x1 = currentx1; x2 = currentx2; x3 = currentx3; data += "[" +t+"," + x2+"]"; if( i < N - 1){ data += ","; } } } } <html> <head> <meta charset="utf-8"> <title>MathBox</title> <script type="text/javascript" src="https://www.google.com/jsapi?autoload={ 'modules':[{ 'name':'visualization', 'version':'1', 'packages':['corechart'] }] }"></script> <script type="text/javascript"> google.setOnLoadCallback(drawChart); function drawChart() { var data = google.visualization.arrayToDataTable([ ['Time', 'Height'], @data ]); var options = { title: 'pitch', curveType: 'function', legend: { position: 'bottom' } }; var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> </head> <body> <form action="" method="post"> <p><label for="text1">Input Height</label><br> <input type="text" name="text1" /></p> <p><input type="submit" value=" Show " /></p> </form> @if (showChart) { <div id="curve_chart" style="width: 900px; height: 500px"></div> } else { <p></p> } </body> </html>
mit
C#
43ea1f5d59be11669c6c08c86ee6ecea48796096
Change the HttpUtility.UrlEncode to Uri.EscapeDataString method.
exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless,exceptionless/Exceptionless
src/Exceptionless.Core/Extensions/UriExtensions.cs
src/Exceptionless.Core/Extensions/UriExtensions.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace Exceptionless.Core.Extensions { public static class UriExtensions { public static string ToQueryString(this NameValueCollection collection) { return collection.AsKeyValuePairs().ToQueryString(); } public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) { return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={Uri.EscapeDataString(pair.Value)}", "&"); } /// <summary> /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence. /// </summary> private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) { return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key))); } public static string GetBaseUrl(this Uri uri) { return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath; } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; namespace Exceptionless.Core.Extensions { public static class UriExtensions { public static string ToQueryString(this NameValueCollection collection) { return collection.AsKeyValuePairs().ToQueryString(); } public static string ToQueryString(this IEnumerable<KeyValuePair<string, string>> collection) { return collection.ToConcatenatedString(pair => pair.Key == null ? pair.Value : $"{pair.Key}={System.Web.HttpUtility.UrlEncode(pair.Value)}", "&"); } /// <summary> /// Converts the legacy NameValueCollection into a strongly-typed KeyValuePair sequence. /// </summary> private static IEnumerable<KeyValuePair<string, string>> AsKeyValuePairs(this NameValueCollection collection) { return collection.AllKeys.Select(key => new KeyValuePair<string, string>(key, collection.Get(key))); } public static string GetBaseUrl(this Uri uri) { return uri.Scheme + "://" + uri.Authority + uri.AbsolutePath; } } }
apache-2.0
C#
6fbe39b84509f4db86113b7af2710455bcbc0159
Fix request creation post/delete in personalization
GetStream/stream-net,GetStream/stream-net,GetStream/stream-net
src/stream-net/Personalization.cs
src/stream-net/Personalization.cs
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Stream.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Stream { public class Personalization { readonly StreamClient _client; internal Personalization(StreamClient client) { _client = client; } public async Task<IDictionary<string, object>> Get(string endpoint, IDictionary<string, object> data) { var request = this._client.BuildPersonalizationRequest(endpoint + "/", HttpMethod.GET); foreach (KeyValuePair<string, object> entry in data) { request.AddQueryParameter(entry.Key, Convert.ToString(entry.Value)); } var response = await this._client.MakeRequest(request); if ((int)response.StatusCode < 300) return JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content); throw StreamException.FromResponse(response); } public async Task<IDictionary<string, object>> Post(string endpoint, IDictionary<string, object> data) { var request = this._client.BuildPersonalizationRequest(endpoint + "/", HttpMethod.POST); request.SetJsonBody(JsonConvert.SerializeObject(data)); var response = await this._client.MakeRequest(request); if ((int)response.StatusCode < 300) return JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content); throw StreamException.FromResponse(response); } public async Task Delete(string endpoint, IDictionary<string, object> data) { var request = this._client.BuildPersonalizationRequest(endpoint + "/", HttpMethod.DELETE); foreach (KeyValuePair<string, object> entry in data) { request.AddQueryParameter(entry.Key, Convert.ToString(entry.Value)); } var response = await this._client.MakeRequest(request); if ((int)response.StatusCode >= 300) throw StreamException.FromResponse(response); } }; }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Stream.Rest; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Stream { public class Personalization { readonly StreamClient _client; internal Personalization(StreamClient client) { _client = client; } public async Task<IDictionary<string, object>> Get(string endpoint, IDictionary<string, object> data) { var request = this._client.BuildPersonalizationRequest(endpoint + "/", HttpMethod.GET); foreach(KeyValuePair<string, object> entry in data) { request.AddQueryParameter(entry.Key, Convert.ToString(entry.Value)); } var response = await this._client.MakeRequest(request); if ((int)response.StatusCode < 300) return JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content); throw StreamException.FromResponse(response); } public async Task<IDictionary<string, object>> Post(string endpoint, IDictionary<string, object> data) { var request = this._client.BuildJWTAppRequest(endpoint + "/", HttpMethod.POST); request.SetJsonBody(JsonConvert.SerializeObject(data)); var response = await this._client.MakeRequest(request); if ((int)response.StatusCode < 300) return JsonConvert.DeserializeObject<Dictionary<string, object>>(response.Content); throw StreamException.FromResponse(response); } public async Task Delete(string endpoint, IDictionary<string, object> data) { var request = this._client.BuildJWTAppRequest(endpoint + "/", HttpMethod.DELETE); foreach(KeyValuePair<string, object> entry in data) { request.AddQueryParameter(entry.Key, Convert.ToString(entry.Value)); } var response = await this._client.MakeRequest(request); if ((int)response.StatusCode >= 300) throw StreamException.FromResponse(response); } }; }
bsd-3-clause
C#
9a5846ee9d95b35b703679a67e7de524169d39a2
Make invoke method private
SnowflakePowered/snowflake,RonnChyran/snowflake,faint32/snowflake-1,faint32/snowflake-1,faint32/snowflake-1,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,RonnChyran/snowflake
Snowflake.API/Core/EventDelegate/JsonRPCEventDelegate.cs
Snowflake.API/Core/EventDelegate/JsonRPCEventDelegate.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Collections.Specialized; using Newtonsoft.Json; using System.IO; namespace Snowflake.Core.EventDelegate { public class JsonRPCEventDelegate { private string RPCUrl; public JsonRPCEventDelegate(int port) { this.RPCUrl = "http://localhost:" + port.ToString() + @"/"; } private WebResponse InvokeMethod(string method, string methodParams, string id) { WebRequest request = WebRequest.Create(this.RPCUrl); request.ContentType = "application/json-rpc"; request.Method = "POST"; var values = new Dictionary<string, dynamic>(){ {"method", method}, {"params", methodParams}, {"id", id} }; var data = JsonConvert.SerializeObject(values); byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Flush(); dataStream.Close(); return request.GetResponse(); } public void Notify(string eventName, dynamic eventData) { var response = this.InvokeMethod( "notify", JsonConvert.SerializeObject( new Dictionary<string, dynamic>(){ {"eventData", eventData}, {"eventName", eventName} }), "null" ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Collections.Specialized; using Newtonsoft.Json; using System.IO; namespace Snowflake.Core.EventDelegate { public class JsonRPCEventDelegate { private string RPCUrl; public JsonRPCEventDelegate(int port) { this.RPCUrl = "http://localhost:" + port.ToString() + @"/"; } public WebResponse InvokeMethod(string method, string methodParams, string id) { WebRequest request = WebRequest.Create(this.RPCUrl); request.ContentType = "application/json-rpc"; request.Method = "POST"; var values = new Dictionary<string, dynamic>(){ {"method", method}, {"params", methodParams}, {"id", id} }; var data = JsonConvert.SerializeObject(values); byte[] byteArray = Encoding.UTF8.GetBytes(data); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Flush(); dataStream.Close(); return request.GetResponse(); } public void Notify(string eventName, dynamic eventData) { var response = this.InvokeMethod( "notify", JsonConvert.SerializeObject( new Dictionary<string, dynamic>(){ {"eventData", eventData}, {"eventName", eventName} }), "null" ); } } }
mpl-2.0
C#
d9e86ff97a08467c721955ca71a8ee2fda5ca9cd
Fix issue with API header binding when running under a subdirectory
KuduApps/NuGetGallery,projectkudu/SiteExtensionGallery,projectkudu/SiteExtensionGallery,ScottShingler/NuGetGallery,ScottShingler/NuGetGallery,projectkudu/SiteExtensionGallery,mtian/SiteExtensionGallery,JetBrains/ReSharperGallery,KuduApps/NuGetGallery,mtian/SiteExtensionGallery,skbkontur/NuGetGallery,skbkontur/NuGetGallery,KuduApps/NuGetGallery,skbkontur/NuGetGallery,grenade/NuGetGallery_download-count-patch,grenade/NuGetGallery_download-count-patch,grenade/NuGetGallery_download-count-patch,KuduApps/NuGetGallery,ScottShingler/NuGetGallery,KuduApps/NuGetGallery,JetBrains/ReSharperGallery,JetBrains/ReSharperGallery,mtian/SiteExtensionGallery
Website/Infrastructure/HttpHeaderValueProviderFactory.cs
Website/Infrastructure/HttpHeaderValueProviderFactory.cs
using System; using System.Web.Mvc; namespace NuGetGallery { public class HttpHeaderValueProviderFactory : ValueProviderFactory { public override IValueProvider GetValueProvider(ControllerContext controllerContext) { var request = controllerContext.RequestContext.HttpContext.Request; // Use this value provider only if a route is located under "API" if (request.Path.Contains("/api/")) return new HttpHeaderValueProvider(request, "ApiKey"); return null; } } }
using System; using System.Web.Mvc; namespace NuGetGallery { public class HttpHeaderValueProviderFactory : ValueProviderFactory { public override IValueProvider GetValueProvider(ControllerContext controllerContext) { var request = controllerContext.RequestContext.HttpContext.Request; // Use this value provider only if a route is located under "API" if (request.Path.TrimStart('/').StartsWith("api", StringComparison.OrdinalIgnoreCase)) return new HttpHeaderValueProvider(request, "ApiKey"); return null; } } }
apache-2.0
C#
0756841dee8b08fe1f4b252f3584a07bc8c7c412
Update Location.cs
ADAPT/ADAPT
source/ADAPT/Logistics/Location.cs
source/ADAPT/Logistics/Location.cs
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Tarak Reddy, Tim Shearouse - initial API and implementation * Kathleen Oneal - added GpsSource * R. Andres Ferreyra - added nullable ParentFacilityId for PAIL compatibility. *******************************************************************************/ using System.Collections.Generic; using AgGateway.ADAPT.ApplicationDataModel.Common; using AgGateway.ADAPT.ApplicationDataModel.Shapes; namespace AgGateway.ADAPT.ApplicationDataModel.Logistics { public class Location { public Location() { ContextItems = new List<ContextItem>(); } public Point Position { get; set; } public List<ContextItem> ContextItems { get; set; } public GpsSource GpsSource { get; set; } public int? ParentFacilityId { get; set; } // Locations in PAIL have Ids; they don't in ADAPT. This provides a way to // enable using ADAPT facilities to stand in for Locations (by reference) when needed. } }
/******************************************************************************* * Copyright (C) 2015 AgGateway and ADAPT Contributors * Copyright (C) 2015 Deere and Company * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html <http://www.eclipse.org/legal/epl-v10.html> * * Contributors: * Tarak Reddy, Tim Shearouse - initial API and implementation * Kathleen Oneal - added GpsSource *******************************************************************************/ using System.Collections.Generic; using AgGateway.ADAPT.ApplicationDataModel.Common; using AgGateway.ADAPT.ApplicationDataModel.Shapes; namespace AgGateway.ADAPT.ApplicationDataModel.Logistics { public class Location { public Location() { ContextItems = new List<ContextItem>(); } public Point Position { get; set; } public List<ContextItem> ContextItems { get; set; } public GpsSource GpsSource { get; set; } } }
epl-1.0
C#
84747bc6e5ae5dc507ef64941403ad9631572946
Clean scaffolded program source
peterblazejewicz/mongodb-mva-vnext
CSharpEnd/Program.cs
CSharpEnd/Program.cs
using System; namespace MongoSample { public class Program { public static void Main(string[] args) { } } }
using System; namespace ConsoleApp1 { public class Program { public static void Main(string[] args) { Console.WriteLine("Hello World"); Console.ReadLine(); } } }
mit
C#
4fcab3cdff13b89fdfcb326b07e0527a0fc62503
Remove unused import
MHeasell/Mappy,MHeasell/Mappy
Mappy/Models/MapModel.cs
Mappy/Models/MapModel.cs
namespace Mappy.Models { using System.Collections.Generic; using System.Drawing; using Data; using Mappy.Collections; public class MapModel : IMapModel { public MapModel(int width, int height) : this(width, height, new MapAttributes()) { } public MapModel(int width, int height, MapAttributes attrs) : this(new MapTile(width, height), attrs) { } public MapModel(MapTile tile) : this(tile, new MapAttributes()) { } public MapModel(MapTile tile, MapAttributes attrs) { this.Tile = tile; this.Attributes = attrs; this.FloatingTiles = new List<Positioned<IMapTile>>(); this.Features = new SparseGrid<Feature>(this.Tile.HeightGrid.Width, this.Tile.HeightGrid.Height); this.Voids = new SparseGrid<bool>(this.Tile.HeightGrid.Width, this.Tile.HeightGrid.Height); this.Minimap = new Bitmap(252, 252); } public MapAttributes Attributes { get; private set; } public IMapTile Tile { get; private set; } public IList<Positioned<IMapTile>> FloatingTiles { get; private set; } public ISparseGrid<Feature> Features { get; private set; } public ISparseGrid<bool> Voids { get; private set; } public int SeaLevel { get; set; } public Bitmap Minimap { get; set; } } }
namespace Mappy.Models { using System.Collections.Generic; using System.Drawing; using System.Linq; using Data; using Mappy.Collections; public class MapModel : IMapModel { public MapModel(int width, int height) : this(width, height, new MapAttributes()) { } public MapModel(int width, int height, MapAttributes attrs) : this(new MapTile(width, height), attrs) { } public MapModel(MapTile tile) : this(tile, new MapAttributes()) { } public MapModel(MapTile tile, MapAttributes attrs) { this.Tile = tile; this.Attributes = attrs; this.FloatingTiles = new List<Positioned<IMapTile>>(); this.Features = new SparseGrid<Feature>(this.Tile.HeightGrid.Width, this.Tile.HeightGrid.Height); this.Voids = new SparseGrid<bool>(this.Tile.HeightGrid.Width, this.Tile.HeightGrid.Height); this.Minimap = new Bitmap(252, 252); } public MapAttributes Attributes { get; private set; } public IMapTile Tile { get; private set; } public IList<Positioned<IMapTile>> FloatingTiles { get; private set; } public ISparseGrid<Feature> Features { get; private set; } public ISparseGrid<bool> Voids { get; private set; } public int SeaLevel { get; set; } public Bitmap Minimap { get; set; } } }
mit
C#
74ee2848fd83438e1a1f86a8dd742092b28f172c
Make necrophage require Look faculty
futurechris/zombai
Assets/Scripts/Behaviors/NecrophageBehavior.cs
Assets/Scripts/Behaviors/NecrophageBehavior.cs
using UnityEngine; using System.Collections; using System.Collections.Generic; public class NecrophageBehavior : AgentBehavior { // "pursue" nearest corpse public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits) { Action newMoveAction; Action newLookAction; Agent tempAgent; bool found = findNearestAgent(percepts, AgentPercept.LivingState.DEAD, out tempAgent); if(found && !myself.getMoveInUse() && !myself.getLookInUse()) { newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS); newMoveAction.setTargetPoint(tempAgent.getLocation()); newLookAction = new Action(Action.ActionType.TURN_TOWARDS); newLookAction.setTargetPoint(tempAgent.getLocation()); currentPlans.Clear(); this.currentPlans.Add(newMoveAction); this.currentPlans.Add(newLookAction); return true; } return false; } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class NecrophageBehavior : AgentBehavior { // "pursue" nearest corpse public override bool updatePlan(List<AgentPercept> percepts, int allottedWorkUnits) { Action newMoveAction; Action newLookAction; Agent tempAgent; bool found = findNearestAgent(percepts, AgentPercept.LivingState.DEAD, out tempAgent); if(found && !myself.getMoveInUse()) { newMoveAction = new Action(Action.ActionType.MOVE_TOWARDS); newMoveAction.setTargetPoint(tempAgent.getLocation()); newLookAction = new Action(Action.ActionType.TURN_TOWARDS); newLookAction.setTargetPoint(tempAgent.getLocation()); currentPlans.Clear(); this.currentPlans.Add(newMoveAction); this.currentPlans.Add(newLookAction); return true; } return false; } }
mit
C#
b58a820659caa1e690638043f2f694b5d1940746
Update version to 0.9.6-beta
logjam2/logjam,logjam2/logjam
build/Version.cs
build/Version.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Version.cs"> // Copyright (c) 2011-2014 logjam.codeplex.com. // </copyright> // Licensed under the <a href="http://logjam.codeplex.com/license">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("LogJam Contributors")] [assembly: AssemblyProduct("LogJam")] [assembly: AssemblyCopyright("Copyright 2011-2015")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")] // Semantic version (http://semver.org). Assembly version changes less than the semver; semver must increment for every release. [assembly: AssemblyInformationalVersion("0.9.6-beta")]
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Version.cs"> // Copyright (c) 2011-2014 logjam.codeplex.com. // </copyright> // Licensed under the <a href="http://logjam.codeplex.com/license">Apache License, Version 2.0</a>; // you may not use this file except in compliance with the License. // -------------------------------------------------------------------------------------------------------------------- using System; using System.Reflection; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. #if DEBUG [assembly: AssemblyConfiguration("Debug")] #else [assembly: AssemblyConfiguration("Release")] #endif [assembly: AssemblyCompany("logjam.codeplex.com")] [assembly: AssemblyProduct("LogJam")] [assembly: AssemblyCopyright("Copyright 2011-2015")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.0.0")] [assembly: AssemblyFileVersion("0.9.0.0")] // Semantic version (http://semver.org). Assembly version changes less than the semver; semver must increment for every release. [assembly: AssemblyInformationalVersion("0.9.5-beta")]
apache-2.0
C#
45e1aa2ba93ccb50869887c4dc461cd7f4e4d10a
convert params to objects
maul-esel/CobaltAHK,maul-esel/CobaltAHK
CobaltAHK/ExpressionTree/FunctionCallBinder.cs
CobaltAHK/ExpressionTree/FunctionCallBinder.cs
using System; using System.Dynamic; using System.Linq; using System.Linq.Expressions; namespace CobaltAHK.ExpressionTree { public class FunctionCallBinder : InvokeBinder { public FunctionCallBinder(CallInfo info, Scope scp) : base(info) { scope = scp; } private readonly Scope scope; public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { if (!target.HasValue || args.Any(a => !a.HasValue)) { return Defer(target, args); } var func = (string)target.Value; if (!scope.IsFunctionDefined(func)) { // todo: defer when !HasValue ? return Defer(target, args); } var lambda = scope.ResolveFunction(func); var prms = args.Select(arg => Converter.ConvertToObject(arg.Expression)); return new DynamicMetaObject( Expression.Invoke(lambda, prms), BindingRestrictions.GetInstanceRestriction(target.Expression, func) // todo ); } } }
using System; using System.Dynamic; using System.Linq; using System.Linq.Expressions; namespace CobaltAHK.ExpressionTree { public class FunctionCallBinder : InvokeBinder { public FunctionCallBinder(CallInfo info, Scope scp) : base(info) { scope = scp; } private readonly Scope scope; public override DynamicMetaObject FallbackInvoke(DynamicMetaObject target, DynamicMetaObject[] args, DynamicMetaObject errorSuggestion) { if (!target.HasValue || args.Any(a => !a.HasValue)) { return Defer(target, args); } var func = (string)target.Value; if (!scope.IsFunctionDefined(func)) { // todo: defer when !HasValue ? return Defer(target, args); } var lambda = scope.ResolveFunction(func); var prms = args.Select(arg => arg.Expression); return new DynamicMetaObject( Expression.Invoke(lambda, prms), BindingRestrictions.GetInstanceRestriction(target.Expression, func) // todo ); } } }
mit
C#
109bd1e754630e2d1a490cd44561fc698d536914
Add a couple binary generator tests.
numinit/open-waveform-format,numinit/open-waveform-format,numinit/open-waveform-format
c-sharp/OWF-test/Serializers/BinaryTests.cs
c-sharp/OWF-test/Serializers/BinaryTests.cs
using System; using System.Web; using Microsoft.VisualStudio.TestTools.UnitTesting; using OWF.Serializers; using OWF.DTO; using System.Collections.Generic; namespace OWF_test.Serializers { [TestClass] public class BinaryTests { [TestMethod] public void GeneratesCorrectEmptyObject() { var p = new Package(new List<Channel>()); byte[] buffer = BinarySerializer.convert(p); byte[] expected = new byte[] {0x4f, 0x57, 0x46, 0x31, /**/ 0, 0, 0, 0}; CollectionAssert.AreEqual(buffer, expected, "Incorrect empty object"); } [TestMethod] public void GeneratesCorrectEmptyChannelObject() { var c = new Channel("TEST_CHANNEL", new List<Namespace>()); var p = new Package(new List<Channel>(new Channel[] { c })); byte[] buffer = BinarySerializer.convert(p); byte[] expected = { 0x4f, 0x57, 0x46, 0x31, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x10, 0x54, 0x45, 0x53, 0x54, 0x5f, 0x43, 0x48, 0x41, 0x4e, 0x4e, 0x45, 0x4c, 0x00, 0x00, 0x00, 0x00 }; CollectionAssert.AreEqual(buffer, expected, "Incorrect empty channel"); } [TestMethod] public void GeneratesCorrectEmptyNamespaceObject() { var t0 = new DateTime(2015, 6, 8, 5, 30, 22); var dt = new TimeSpan(1,2,3); var n = new Namespace("TEST_NAMESPACE", t0, dt, new List<Signal>(), new List<Event>(), new List<Alarm>()); var c = new Channel("TEST_CHANNEL", new List<Namespace>(new Namespace[] { n })); var p = new Package(new List<Channel>(new Channel[] { c })); byte[] buffer = BinarySerializer.convert(p); byte[] expected = { 0x4f, 0x57, 0x46, 0x31, 0x00, 0x00, 0x00, 0x4c, 0x00, 0x00, 0x00, 0x48, 0x00, 0x00, 0x00, 0x10, 0x54, 0x45, 0x53, 0x54, 0x5f, 0x43, 0x48, 0x41, 0x4e, 0x4e, 0x45, 0x4c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x32, 0xef, 0xcd, 0x61, 0x94, 0xab, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x38, 0xce, 0xf8, 0x00, 0x00, 0x00, 0x10, 0x54, 0x45, 0x53, 0x54, 0x5f, 0x4e, 0x41, 0x4d, 0x45, 0x53, 0x50, 0x41, 0x43, 0x45, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; CollectionAssert.AreEqual(buffer, expected, "Incorrect empty namespace"); } } }
using System; using System.Web; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace OWF_test.Serializers { [TestClass] public class BinaryTests { [TestMethod] public void GeneratesCorrectEmptyObject() { } } }
apache-2.0
C#
284b87d676aba1726879a1505cf5514d319af050
Update XValue.cs
wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D
src/Core2D/Data/Database/XValue.cs
src/Core2D/Data/Database/XValue.cs
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Attributes; namespace Core2D.Data.Database { /// <summary> /// Record value. /// </summary> public class XValue : ObservableObject { private string _content; /// <summary> /// Gets or sets value content. /// </summary> [Content] public string Content { get => _content; set => Update(ref _content, value); } /// <summary> /// Creates a new <see cref="XValue"/> instance. /// </summary> /// <param name="content">The value content.</param> /// <returns>The new instance of the <see cref="XValue"/> class.</returns> public static XValue Create(string content) => new XValue() { Content = content }; /// <summary> /// Check whether the <see cref="Content"/> property has changed from its default value. /// </summary> /// <returns>Returns true if the property has changed; otherwise, returns false.</returns> public bool ShouldSerializeContent() => !String.IsNullOrWhiteSpace(_content); } }
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Core2D.Attributes; namespace Core2D.Data.Database { /// <summary> /// Record value. /// </summary> public class XValue : ObservableObject { private string _content; /// <summary> /// Gets or sets value content. /// </summary> [Content] public string Content { get => _content; set => Update(ref _content, value); } /// <summary> /// Creates a new <see cref="XValue"/> instance. /// </summary> /// <param name="content">The value content.</param> /// <returns>The new instance of the <see cref="XValue"/> class.</returns> public static XValue Create(string content) => new XValue() { Content = content }; } }
mit
C#
8f70c3cd7f8d2dca39c3a2153ad8701ff4c67f55
Return after printing wasm-dump usage
jonathanvdc/cs-wasm,jonathanvdc/cs-wasm
wasm-dump/Program.cs
wasm-dump/Program.cs
using System; using System.IO; using Wasm.Binary; namespace Wasm.Dump { public static class Program { public static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("usage: wasm-dump file.wasm"); return; } WasmFile file; using (var fileStream = File.OpenRead(args[0])) { using (var reader = new BinaryReader(fileStream)) { // Create a WebAssembly reader and read the file. var wasmReader = new BinaryWasmReader(reader); file = wasmReader.ReadFile(); } } DumpFile(file); } public static void DumpFile(WasmFile ParsedFile) { foreach (var section in ParsedFile.Sections) { section.Dump(Console.Out); Console.WriteLine(); } } } }
using System; using System.IO; using Wasm.Binary; namespace Wasm.Dump { public static class Program { public static void Main(string[] args) { if (args.Length != 1) Console.WriteLine("usage: wasm-dump file.wasm"); WasmFile file; using (var fileStream = File.OpenRead(args[0])) { using (var reader = new BinaryReader(fileStream)) { // Create a WebAssembly reader and read the file. var wasmReader = new BinaryWasmReader(reader); file = wasmReader.ReadFile(); } } DumpFile(file); } public static void DumpFile(WasmFile ParsedFile) { foreach (var section in ParsedFile.Sections) { section.Dump(Console.Out); Console.WriteLine(); } } } }
mit
C#
bf4946e42fc9048e9e3ec30b957c9c60bb322996
change logic
degarashi0913/FAManagementStudio
FAManagementStudio/Common/Messenger.cs
FAManagementStudio/Common/Messenger.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace FAManagementStudio.Common { public class Messenger { private static readonly Messenger _instance = new Messenger(); public static Messenger Instance { get { return _instance; } } private Dictionary<Type, List<MessageAction>> _actions = new Dictionary<Type, List<MessageAction>>(); public void Register<TMessage>(object recipient, Action<TMessage> action) { var type = typeof(TMessage); if (!_actions.ContainsKey(type)) { _actions.Add(type, new List<MessageAction>()); } var list = _actions[type]; list.Add(new MessageAction(recipient, action)); } public void Send<TMessage>(TMessage message) { var actions = _actions[typeof(TMessage)].ToList(); foreach (var item in actions) { item.Execute(message); } } public void Unregister<TMessage>(object recipient) { var items = _actions[typeof(TMessage)].Where(x => x.Target == recipient); foreach (var item in items) { _actions[typeof(TMessage)].Remove(item); } } } public class MessageAction { private object _target; private Delegate _action; public object Target { get { return _target; } } public MessageAction(object target, Delegate action) { _target = target; _action = action; } public void Execute<T>(T param) { _action.Method.Invoke(_target, new object[] { param }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace FAManagementStudio.Common { public class Messenger { private static readonly Messenger _instance = new Messenger(); public static Messenger Instance { get { return _instance; } } private Dictionary<Type, List<Delegate>> _actions = new Dictionary<Type, List<Delegate>>(); public void Register<TMessage>(object recipient, Action<TMessage> action) { var type = typeof(TMessage); if (!_actions.ContainsKey(type)) { _actions.Add(type, new List<Delegate>()); } var list = _actions[type]; list.Add(action); } public void Send<TMessage>(TMessage message) { var actions = _actions[typeof(TMessage)].ToList(); foreach (Action<TMessage> item in actions) { item(message); } } public void Unregister<TMessage>(object recipient) { _actions[typeof(TMessage)].Clear(); } } }
mit
C#
e0f3121cea7f76188c35b5ff3287b635ea0f2654
Update Media.cs
ysinjab/InstagramCSharp
src/InstgramCSharp/Models/Media.cs
src/InstgramCSharp/Models/Media.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InstgramCSharp.Models { public class Media { public string Type { get; set; } public Location Location { get; set; } public Comments Comments { get; set; } public Likes Likes { get; set; } public string Filter { get; set; } public long Created_Time { get; set; } public string Link { get; set; } public Images Images { get; set; } public Videos Videos { get; set; } public List<UserInPhoto> Users_In_Photo { get; set; } public Caption Caption { get; set; } public bool User_Has_Liked { get; set; } public string Id { get; set; } public User User { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InstgramCSharp.Models { public class Media { public string Type { get; set; } public Location Location { get; set; } public Comments Comments { get; set; } public Likes Likes { get; set; } public string Filter { get; set; } public long Created_Time { get; set; } public string Link { get; set; } public Images images { get; set; } public Videos videos { get; set; } public List<UserInPhoto> users_in_photo { get; set; } public Caption Caption { get; set; } public bool User_Has_Liked { get; set; } public string id { get; set; } public User user { get; set; } } }
mit
C#
4f303719ef535822dbd7dc41f410faa3851e6a45
Fix Event Map HP Checker
kyoryo/test
Grabacr07.KanColleWrapper/EventMapHPChecker.cs
Grabacr07.KanColleWrapper/EventMapHPChecker.cs
using Grabacr07.KanColleWrapper.Models.Raw; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Grabacr07.KanColleWrapper.Models { public class EventMapHPChecker { public bool EnableEventMapInfo { get; set; } public List<Maplists> Lists = new List<Maplists>(); private StringBuilder SeaList= new StringBuilder(); //public delegate void MapListEventHandler(); //public event MapListEventHandler EventMapEnable; public EventMapHPChecker(KanColleProxy proxy) { proxy.api_get_member_mapinfo.TryParse<kcsapi_mapinfo[]>().Subscribe(x => this.EventMapList(x.Data)); } private void EventMapList(kcsapi_mapinfo[] list) { if (!KanColleClient.Current.EventMapHPChecker.EnableEventMapInfo) return; int j = 1; for (int i = 0; i < list.Length; i++) { if (list[i].api_eventmap != null) { Maplists t = new Maplists(); t.MaxHp = list[i].api_eventmap.api_max_maphp; t.NowHp = list[i].api_eventmap.api_now_maphp; t.Num = j; this.Lists.Add(t); j++; } } if (this.Lists.Count >= 1) { for (int i = 0; i < Lists.Count; i++) { if (((double)Lists[i].NowHp / (double)Lists[i].MaxHp)>0) SeaList.Append("E-" + Lists[i].Num.ToString() + "해역 HP:" + Lists[i].NowHp.ToString() + "/" + Lists[i].MaxHp.ToString() + "\r"); } if(SeaList.Length!=0)MessageBox.Show(SeaList.ToString(),"이벤트 해역정보"); if (SeaList.Length == 0) KanColleClient.Current.EventMapHPChecker.EnableEventMapInfo=false; } Lists.Clear(); SeaList.Clear(); } } }
using Grabacr07.KanColleWrapper.Models.Raw; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Grabacr07.KanColleWrapper.Models { public class EventMapHPChecker { public bool EnableEventMapInfo { get; set; } public List<Maplists> Lists = new List<Maplists>(); private StringBuilder SeaList= new StringBuilder(); //public delegate void MapListEventHandler(); //public event MapListEventHandler EventMapEnable; public EventMapHPChecker(KanColleProxy proxy) { proxy.api_get_member_mapinfo.TryParse<kcsapi_mapinfo[]>().Subscribe(x => this.EventMapList(x.Data)); } private void EventMapList(kcsapi_mapinfo[] list) { if (!KanColleClient.Current.EventMapHPChecker.EnableEventMapInfo) return; int j = 1; for (int i = 0; i < list.Length; i++) { if (list[i].api_eventmap != null) { Maplists t = new Maplists(); t.MaxHp = list[i].api_eventmap.api_max_maphp; t.NowHp = list[i].api_eventmap.api_now_maphp; t.Num = j; this.Lists.Add(t); j++; } } if (this.Lists.Count >= 1) { for (int i = 0; i < Lists.Count; i++) { SeaList.Append("E-" + Lists[i].Num.ToString() + "해역 HP:" + Lists[i].NowHp.ToString() + "/" + Lists[i].MaxHp.ToString()+"\r"); } MessageBox.Show(SeaList.ToString(),"이벤트 해역정보"); } Lists.Clear(); SeaList.Clear(); } } }
mit
C#
b5bf6244b62b76cecb8621991dc6253ed8fce5bd
fix for throwing notSupported even once creation has happened
Pondidum/Ledger.Stores.Postgres,Pondidum/Ledger.Stores.Postgres
Ledger.Stores.Postgres/TableBuilder.cs
Ledger.Stores.Postgres/TableBuilder.cs
using System; using System.Collections.Generic; using System.Linq; using Npgsql; namespace Ledger.Stores.Postgres { public class TableBuilder { private readonly Dictionary<Type, Action<string>> _creators; public TableBuilder(NpgsqlConnection connection) { _creators = new Dictionary<Type, Action<string>> { {typeof (Guid), stream => new CreateGuidAggregateTablesCommand(connection).Execute(stream)}, {typeof (int), stream => new CreateIntAggregateTablesCommand(connection).Execute(stream)} }; } public void CreateTable(Type keyType, string stream) { Action<string> create; if (_creators.TryGetValue(keyType, out create) == false) { var supported = string.Join(", ", _creators.Keys.Select(k => k.Name)); throw new NotSupportedException($"Cannot create a '{keyType.Name}' aggregate keyed table, only '{supported}' are supported."); } create(stream); } public static string EventsName(string stream) { return stream + "_events"; } public static string SnapshotsName(string stream) { return stream + "_snapshots"; } } }
using System; using System.Collections.Generic; using System.Linq; using Npgsql; namespace Ledger.Stores.Postgres { public class TableBuilder { private readonly Dictionary<Type, Action<string>> _creators; public TableBuilder(NpgsqlConnection connection) { _creators = new Dictionary<Type, Action<string>> { {typeof (Guid), stream => new CreateGuidAggregateTablesCommand(connection).Execute(stream)}, {typeof (int), stream => new CreateIntAggregateTablesCommand(connection).Execute(stream)} }; } public void CreateTable(Type keyType, string stream) { Action<string> create; if (_creators.TryGetValue(keyType, out create)) { create(stream); } throw new NotSupportedException(string.Format( "Cannot create a '{0}' aggregate keyed table, only '{1}' are supported.", keyType.Name, string.Join(", ", _creators.Keys.Select(k => k.Name)))); } public static string EventsName(string stream) { return stream + "_events"; } public static string SnapshotsName(string stream) { return stream + "_snapshots"; } } }
lgpl-2.1
C#
29032b0cf98fbc6500125f11e8253f868cb46ac6
Correct TIFF file extension and add Bitmap support. Closes #43
SteamDatabase/ValveResourceFormat
GUI/Forms/Texture.cs
GUI/Forms/Texture.cs
using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace GUI.Forms { public partial class Texture : UserControl { public string name { get; private set; } public Texture() { InitializeComponent(); } public void SetImage(Bitmap image, string name, int w, int h) { this.pictureBox1.Image = image; this.name = name; this.pictureBox1.MaximumSize = new Size(w, h); } private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Name != "saveAsToolStripMenuItem") { return; } var menuStrip = sender as ContextMenuStrip; menuStrip.Visible = false; //Hide it as we have pressed the button now! var saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PNG Image|*.png|JPG Image|*.jpg|Tiff Image|*.tiff|Bitmap Image|*.bmp"; saveFileDialog.Title = "Save an Image File"; saveFileDialog.FileName = this.name; saveFileDialog.ShowDialog(this); if (saveFileDialog.FileName != "") { ImageFormat format = ImageFormat.Png; switch (saveFileDialog.FilterIndex) { case 2: format = ImageFormat.Jpeg; break; case 3: format = ImageFormat.Tiff; break; case 4: format = ImageFormat.Bmp; break; } using (var fs = (FileStream)saveFileDialog.OpenFile()) { this.pictureBox1.Image.Save(fs, format); } } } } }
using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Windows.Forms; namespace GUI.Forms { public partial class Texture : UserControl { public string name { get; private set; } public Texture() { InitializeComponent(); } public void SetImage(Bitmap image, string name, int w, int h) { this.pictureBox1.Image = image; this.name = name; this.pictureBox1.MaximumSize = new Size(w, h); } private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { if (e.ClickedItem.Name != "saveAsToolStripMenuItem") { return; } var menuStrip = sender as ContextMenuStrip; menuStrip.Visible = false; //Hide it as we have pressed the button now! var saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "PNG Image|*.png|JPG Image|*.jpg|Tiff Image|*.tga"; saveFileDialog.Title = "Save an Image File"; saveFileDialog.FileName = this.name; saveFileDialog.ShowDialog(this); if (saveFileDialog.FileName != "") { ImageFormat format = ImageFormat.Png; switch (saveFileDialog.FilterIndex) { case 2: format = ImageFormat.Jpeg; break; case 3: format = ImageFormat.Tiff; break; } using (var fs = (FileStream)saveFileDialog.OpenFile()) { this.pictureBox1.Image.Save(fs, format); } } } } }
mit
C#
2627724efad1f3d880c19ab116d46ba7832a8850
implement ExistsIn(sequence)
miraimann/Knuth-Morris-Pratt
KnuthMorrisPratt/KnuthMorrisPratt/Finder.cs
KnuthMorrisPratt/KnuthMorrisPratt/Finder.cs
using System; using System.Collections.Generic; using System.Linq; namespace KnuthMorrisPratt { internal class Finder<T> : IFinder<T> { private readonly int[,] _dfa; private readonly Dictionary<T, int> _abc; private readonly int _finalState; public Finder(IEnumerable<T> word) { var pattern = word as T[] ?? word.ToArray(); _finalState = pattern.Length; _abc = pattern.Distinct() .Select((v, i) => new { v, i }) .ToDictionary(o => o.v, o => o.i); _dfa = new int[_abc.Count, pattern.Length]; _dfa[0, 0] = 1; for (int i = 0, j = 1; j < pattern.Length; i = _dfa[_abc[pattern[j++]], i]) { for (int c = 0; c < _abc.Count; c++) _dfa[c, j] = _dfa[c, i]; _dfa[_abc[pattern[j]], j] = j + 1; } } public int FindIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public int FindLastIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public IEnumerable<int> FindAllIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public bool ExistsIn(IEnumerable<T> sequence) { using (var e = sequence.Select(c => _abc[c]) .GetEnumerator()) { int state = 0; while (e.MoveNext()) { state = _dfa[e.Current, state]; if (state == _finalState) return true; } return false; } } } }
using System; using System.Collections.Generic; using System.Linq; namespace KnuthMorrisPratt { internal class Finder<T> : IFinder<T> { private readonly int[,] _dfa; private readonly Dictionary<T, int> _abc; private readonly int _finalState; public Finder(IEnumerable<T> word) { var pattern = word as T[] ?? word.ToArray(); _finalState = pattern.Length; _abc = pattern.Distinct() .Select((v, i) => new { v, i }) .ToDictionary(o => o.v, o => o.i); _dfa = new int[_abc.Count, pattern.Length]; _dfa[0, 0] = 1; for (int i = 0, j = 1; j < pattern.Length; i = _dfa[_abc[pattern[j++]], i]) { for (int c = 0; c < _abc.Count; c++) _dfa[c, j] = _dfa[c, i]; _dfa[_abc[pattern[j]], j] = j + 1; } } public int FindIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public int FindLastIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public IEnumerable<int> FindAllIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } public bool ExistsIn(IEnumerable<T> sequence) { throw new NotImplementedException(); } } }
mit
C#
89780b8b3e6c2dc9b01efe3e4f847275d81ba082
Add Form Processing Header
zptec/Liq_UI
Liq_UI/Translation/TranslationProcessing.cs
Liq_UI/Translation/TranslationProcessing.cs
using System; using System.Collections.Generic; using Liq_UI.Analysis; namespace Liq_UI.Translation { internal class TranslationProcessing { //Analysis Result private AnalysisBase analysisResult; //Translation Base Info private TranslationBase translationBase; public TranslationProcessing(AnalysisBase analysisResult) { this.analysisResult = analysisResult; } public TranslationProcessing(TranslationBase translationBase) { this.translationBase = translationBase; } internal List<TranslationSegment> GenerateCode() { List<TranslationSegment> segments = new List<TranslationSegment>(); //Add each form processing implementation TranslationSegment segmentProcessing = new TranslationSegment("Processing_FormImpl", TranslationSegmentType.DBFetching); foreach (AnalysisFormImpl abapFormImpl in analysisResult.FormImpl) { //Add Form Header segmentProcessing.CodeLines.Add("*&---------------------------------------------------------------------*"); segmentProcessing.CodeLines.Add("*& Form " + abapFormImpl.FormName); segmentProcessing.CodeLines.Add("*&---------------------------------------------------------------------*"); segmentProcessing.CodeLines.Add("* " + abapFormImpl.FormDesc); segmentProcessing.CodeLines.Add("*&---------------------------------------------------------------------*"); segmentProcessing.CodeLines.Add("* --> p1 text"); segmentProcessing.CodeLines.Add("* <-- p2 text"); segmentProcessing.CodeLines.Add("*&---------------------------------------------------------------------*"); segmentProcessing.CodeLines.Add("FORM " + abapFormImpl.FormName + " ."); segmentProcessing.CodeLines.Add(""); } segments.Add(segmentProcessing); return segments; } } }
using System; using System.Collections.Generic; using Liq_UI.Analysis; namespace Liq_UI.Translation { internal class TranslationProcessing { //Analysis Result private AnalysisBase analysisResult; //Translation Base Info private TranslationBase translationBase; public TranslationProcessing(AnalysisBase analysisResult) { this.analysisResult = analysisResult; } public TranslationProcessing(TranslationBase translationBase) { this.translationBase = translationBase; } internal List<TranslationSegment> GenerateCode() { List<TranslationSegment> segments = new List<TranslationSegment>(); //Add each form processing implementation TranslationSegment segmentProcessing = new TranslationSegment("Processing__FormImpl", TranslationSegmentType.DBFetching); segments.Add(segmentProcessing); return segments; } } }
mit
C#
eadba462fdc4659b2025b0d64aecfe8c7acd65b4
Add check for microgames when forced in Practice
Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare,NitorInc/NitoriWare
Assets/Scripts/Stage/MicrogameStage.cs
Assets/Scripts/Stage/MicrogameStage.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MicrogameStage : Stage { public static string microgameId; [SerializeField] private string forceMicrogame; public override void onStageStart() { //Update collection if microgame is forced, in case it's in the project but hasn't been added to the collection if (!string.IsNullOrEmpty(forceMicrogame)) GameController.instance.microgameCollection.updateMicrogames(); } public override Microgame getMicrogame(int num) { Microgame microgame = new Microgame(microgameId); microgame.microgameId = !string.IsNullOrEmpty(forceMicrogame) ? forceMicrogame : microgameId; return microgame; } public override int getMicrogameDifficulty(Microgame microgame, int num) { return (num % 3) + 1; } public override Interruption[] getInterruptions(int num) { if (num == 0 || num % 3 > 0) return new Interruption[0]; return new Interruption[0].add(new Interruption(Interruption.SpeedChange.SpeedUp)); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MicrogameStage : Stage { public static string microgameId; [SerializeField] private string forceMicrogame; public override Microgame getMicrogame(int num) { Microgame microgame = new Microgame(microgameId); microgame.microgameId = !string.IsNullOrEmpty(forceMicrogame) ? forceMicrogame : microgameId; return microgame; } public override int getMicrogameDifficulty(Microgame microgame, int num) { return (num % 3) + 1; } public override Interruption[] getInterruptions(int num) { if (num == 0 || num % 3 > 0) return new Interruption[0]; return new Interruption[0].add(new Interruption(Interruption.SpeedChange.SpeedUp)); } }
mit
C#
5d736397e3c89e5ddfca3fb553023528cf32494a
Remove Serializable attribute to achieve parity with the VB code.
rockfordlhotka/csla,ronnymgm/csla-light,ronnymgm/csla-light,MarimerLLC/csla,jonnybee/csla,JasonBock/csla,JasonBock/csla,jonnybee/csla,rockfordlhotka/csla,BrettJaner/csla,rockfordlhotka/csla,jonnybee/csla,MarimerLLC/csla,BrettJaner/csla,BrettJaner/csla,JasonBock/csla,MarimerLLC/csla,ronnymgm/csla-light
csla20cs/Csla/Core/RemovingItemEventArgs.cs
csla20cs/Csla/Core/RemovingItemEventArgs.cs
using System; using System.Collections.Generic; using System.Text; namespace Csla.Core { /// <summary> /// Contains event data for the RemovingItem /// event. /// </summary> public class RemovingItemEventArgs : EventArgs { private object _removingItem; /// <summary> /// Gets a reference to the item that was /// removed from the list. /// </summary> public object RemovingItem { get { return _removingItem; } } /// <summary> /// Create an instance of the object. /// </summary> /// <param name="removingItem"> /// A reference to the item that was /// removed from the list. /// </param> public RemovingItemEventArgs(object removingItem) { _removingItem = removingItem; } } }
using System; using System.Collections.Generic; using System.Text; namespace Csla.Core { /// <summary> /// Contains event data for the RemovingItem /// event. /// </summary> [Serializable] public class RemovingItemEventArgs : EventArgs { private object _removingItem; /// <summary> /// Gets a reference to the item that was /// removed from the list. /// </summary> public object RemovingItem { get { return _removingItem; } } /// <summary> /// Create an instance of the object. /// </summary> /// <param name="removingItem"> /// A reference to the item that was /// removed from the list. /// </param> public RemovingItemEventArgs(object removingItem) { _removingItem = removingItem; } } }
mit
C#
1f7995f93c22bf4ce64461b626dcf1589178e371
Bump version to 0.2.0
mwijnands/SimpleCache
SimpleCache/Properties/AssemblyInfo.cs
SimpleCache/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("XperiCode.SimpleCache")] [assembly: AssemblyDescription("Extension methods for System.Runtime.Caching.ObjectCache / MemoryCache with locking mechanism.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("XperiCode")] [assembly: AssemblyProduct("SimpleCache")] [assembly: AssemblyCopyright("Copyright © Marcel Wijnands 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9c702e23-7ce3-49e4-bbf0-8ae461adf938")] // 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("0.2.0.0")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0")] [assembly: InternalsVisibleTo("XperiCode.SimpleCache.Tests")]
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("XperiCode.SimpleCache")] [assembly: AssemblyDescription("Extension methods for System.Runtime.Caching.ObjectCache / MemoryCache with locking mechanism.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("XperiCode")] [assembly: AssemblyProduct("SimpleCache")] [assembly: AssemblyCopyright("Copyright © Marcel Wijnands 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9c702e23-7ce3-49e4-bbf0-8ae461adf938")] // 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("0.1.1.0")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: AssemblyInformationalVersion("0.1.1")] [assembly: InternalsVisibleTo("XperiCode.SimpleCache.Tests")]
mit
C#
908bd43f78fbf324af2916638d90e704e03da688
fix comment
Fody/PropertyChanged,user1568891/PropertyChanged,0x53A/PropertyChanged
PropertyChanged/ImplementPropertyChangedAttribute.cs
PropertyChanged/ImplementPropertyChangedAttribute.cs
using System; namespace PropertyChanged { /// <summary> /// Include a <see cref="Type"/> for notification. /// The INotifyPropertyChanged interface is added to the type. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ImplementPropertyChangedAttribute : Attribute { } }
using System; using System.ComponentModel; namespace PropertyChanged { /// <summary> /// Include a <see cref="Type"/> for notification. /// The <see cref="INotifyPropertyChanged"/> interface is added to the type. /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)] public class ImplementPropertyChangedAttribute : Attribute { } }
mit
C#
00704939ccc55c4ae3438f882dd007bbe22abe73
Add status field
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
Battery-Commander.Web/Views/Evaluations/List.cshtml
Battery-Commander.Web/Views/Evaluations/List.cshtml
@model IEnumerable<Evaluation> <h2>Evaluations @Html.ActionLink("Add New", "New", "Evaluations", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().ThruDate)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Status)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Delinquency)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastUpdated)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rater)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().SeniorRater)</th> <th></th> </tr> </thead> <tbody> @foreach (var evaluation in Model) { <tr> <td>@Html.DisplayFor(_ => evaluation.Ratee)</td> <td>@Html.DisplayFor(_ => evaluation.ThruDate)</td> <td>@Html.DisplayFor(_ => evaluation.Status)</td> <td>@Html.DisplayFor(_ => evaluation.Delinquency)</td> <td>@Html.DisplayFor(_ => evaluation.LastUpdated)</td> <td>@Html.DisplayFor(_ => evaluation.Type)</td> <td>@Html.DisplayFor(_ => evaluation.Rater)</td> <td>@Html.DisplayFor(_ => evaluation.SeniorRater)</td> <td>@Html.ActionLink("Details", "Details", new { evaluation.Id })</td> </tr> } </tbody> </table>
@model IEnumerable<Evaluation> <h2>Evaluations @Html.ActionLink("Add New", "New", "Evaluations", null, new { @class = "btn btn-default" })</h2> <table class="table table-striped"> <thead> <tr> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Ratee)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().ThruDate)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Delinquency)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().LastUpdated)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Type)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Rater)</th> <th>@Html.DisplayNameFor(_ => _.FirstOrDefault().SeniorRater)</th> <th></th> </tr> </thead> <tbody> @foreach (var evaluation in Model) { <tr> <td>@Html.DisplayFor(_ => evaluation.Ratee)</td> <td>@Html.DisplayFor(_ => evaluation.ThruDate)</td> <td>@Html.DisplayFor(_ => evaluation.Delinquency)</td> <td>@Html.DisplayFor(_ => evaluation.LastUpdated)</td> <td>@Html.DisplayFor(_ => evaluation.Type)</td> <td>@Html.DisplayFor(_ => evaluation.Rater)</td> <td>@Html.DisplayFor(_ => evaluation.SeniorRater)</td> <td>@Html.ActionLink("Details", "Details", new { evaluation.Id })</td> </tr> } </tbody> </table>
mit
C#
12ec8a26aa92ae5a4c5aeff3de2356de8ba9e1f1
Update AssemblyInfo.cs
bradyholt/cron-expression-descriptor,sadedil/cron-expression-descriptor,sadedil/cron-expression-descriptor,bradyholt/cron-expression-descriptor
CronExpressionDescriptor/Properties/AssemblyInfo.cs
CronExpressionDescriptor/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("Cron Expression Descriptor")] [assembly: AssemblyDescription("A library that converts cron expressions into human readable strings.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Brady Holt, Renato Lima, Ivan Santos")] [assembly: AssemblyProduct("CronExpressionDescriptor")] [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("3df2e79f-e253-4cb0-ab32-c73710d8278d")] // 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.7.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("Cron Expression Descriptor")] [assembly: AssemblyDescription("A C# library that converts cron expressions into human readable strings.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Brady Holt, Renato Lima, Ivan Santos")] [assembly: AssemblyProduct("CronExpressionDescriptor")] [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("3df2e79f-e253-4cb0-ab32-c73710d8278d")] // 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.7.0")]
mit
C#
2c79d9e4aa31d7fcf8ba391920b73bd5c2ea45cd
Comment out debug spam
Goat-Improvement-Suite/The-Chinese-Room
Assets/Scripts/ConvayerOutItemInteraction.cs
Assets/Scripts/ConvayerOutItemInteraction.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConvayerOutItemInteraction : Interaction { public GameColor color; private ItemInteraction holding; [SerializeField] public GameObject endPoint; [SerializeField] public GameObject startPoint; void Start() { } public override void Highlight(GameObject player) { } public override void Unhighlight(GameObject player) { } void Update() { if (holding) { if ((holding.transform.position - endPoint.transform.position).magnitude > 0.5f) holding.transform.position = Vector3.Lerp(holding.transform.position, endPoint.transform.position, 0.1f); } } public override bool CanInteractWith(CharacterItemInteraction player, ItemInteraction item) { //Debug.LogWarning(player.color == color); //Debug.LogWarning(item == null); //Debug.LogWarning(player != null); //Debug.LogWarning(holding != null); //Debug.LogWarning("==================="); return (holding != null && player != null && player.color == color && item == null); } public bool GiveItem(CharacterItemInteraction playerItemInteraction, ItemInteraction itemInteraction) { if (holding && playerItemInteraction.ReceiveItem(null, holding)) { holding = null; return true; } return false; } public bool isReady() { return holding == null; } public bool ReceiveItem(ItemInteraction itemInteraction) { Debug.LogWarning("atempting to grab"); if (!holding) { Debug.LogWarning("grabbed"); holding = itemInteraction; holding.MarkAsHeldBy(gameObject); holding.transform.parent = transform; holding.transform.position = startPoint.transform.position; return true; } return false; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ConvayerOutItemInteraction : Interaction { public GameColor color; private ItemInteraction holding; [SerializeField] public GameObject endPoint; [SerializeField] public GameObject startPoint; void Start() { } public override void Highlight(GameObject player) { } public override void Unhighlight(GameObject player) { } void Update() { if (holding) { if ((holding.transform.position - endPoint.transform.position).magnitude > 0.5f) holding.transform.position = Vector3.Lerp(holding.transform.position, endPoint.transform.position, 0.1f); } } public override bool CanInteractWith(CharacterItemInteraction player, ItemInteraction item) { Debug.LogWarning(player.color == color); Debug.LogWarning(item == null); Debug.LogWarning(player != null); Debug.LogWarning(holding != null); Debug.LogWarning("==================="); return (holding != null && player != null && player.color == color && item == null); } public bool GiveItem(CharacterItemInteraction playerItemInteraction, ItemInteraction itemInteraction) { if (holding && playerItemInteraction.ReceiveItem(null, holding)) { holding = null; return true; } return false; } public bool isReady() { return holding == null; } public bool ReceiveItem(ItemInteraction itemInteraction) { Debug.LogWarning("atempting to grab"); if (!holding) { Debug.LogWarning("grabbed"); holding = itemInteraction; holding.MarkAsHeldBy(gameObject); holding.transform.parent = transform; holding.transform.position = startPoint.transform.position; return true; } return false; } }
mit
C#
411cb4750726b5e8d63ba1abdeb3a483cd7d42d1
Comment fix.
dlemstra/line-bot-sdk-dotnet,dlemstra/line-bot-sdk-dotnet
src/LineBot/ILineBot.cs
src/LineBot/ILineBot.cs
// Copyright 2017 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet) // // Dirk Lemstra 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: // // https://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.Threading.Tasks; namespace Line { /// <summary> /// Encapsulates the interface for the bot that can be used to communicatie with the Line API. /// </summary> public interface ILineBot { /// <summary> /// Returns the content of the specified message. /// </summary> /// <param name="messageId">The id of the message</param> /// <returns>The content of the specified message.</returns> Task<byte[]> GetContent(string messageId); /// <summary> /// Returns the profile of the specified user. /// </summary> /// <param name="userId">The id of the user.</param> /// <returns>The profile of the specified user.</returns> Task<IUserProfile> GetProfile(string userId); /// <summary> /// Returns the profile of the specified user. /// </summary> /// <param name="user">The user.</param> /// <returns>The profile of the specified user.</returns> Task<IUserProfile> GetProfile(IUser user); /// <summary> /// Leave the specified group. /// </summary> /// <param name="groupId">The id of the group.</param> /// <returns>.</returns> Task LeaveGroup(string groupId); /// <summary> /// Leave the specified group. /// </summary> /// <param name="group">The group.</param> /// <returns>.</returns> Task LeaveGroup(IGroup group); /// <summary> /// Leave the specified room. /// </summary> /// <param name="roomId">The id of the room.</param> /// <returns>.</returns> Task LeaveRoom(string roomId); /// <summary> /// Leave the specified room. /// </summary> /// <param name="room">The room.</param> /// <returns>.</returns> Task LeaveRoom(IRoom room); } }
// Copyright 2017 Dirk Lemstra (https://github.com/dlemstra/line-bot-sdk-dotnet) // // Dirk Lemstra 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: // // https://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.Threading.Tasks; namespace Line { /// <summary> /// Encapsulates the interface for the bot that can be used to communicatie with the Line API. /// </summary> public interface ILineBot { /// <summary> /// Returns the content of the specified message. /// </summary> /// <param name="messageId">The id of the message</param> /// <returns>The content of the specified message.</returns> Task<byte[]> GetContent(string messageId); /// <summary> /// Returns the profile of the specified user. /// </summary> /// <param name="userId">The id of the user.</param> /// <returns>The profile of the specified user.</returns> Task<IUserProfile> GetProfile(string userId); /// <summary> /// Returns the profile of the specified user. /// </summary> /// <param name="user">The user.</param> /// <returns>The profile of the specified user.</returns> Task<IUserProfile> GetProfile(IUser user); /// <summary> /// Leave the specified group. /// </summary> /// <param name="groupId">The id of the group.</param> /// <returns>.</returns> Task LeaveGroup(string groupId); /// <summary> /// Leave the specified group. /// </summary> /// <param name="group">The group.</param> /// <returns>.</returns> Task LeaveGroup(IGroup group); /// <summary> /// Leave the specified room. /// </summary> /// <param name="roomId">The id of the room.</param> /// <returns>.</returns> Task LeaveRoom(string roomId); /// <summary> /// Leave the specified room. /// </summary> /// <param name="roomId">The room.</param> /// <returns>.</returns> Task LeaveRoom(IRoom room); } }
apache-2.0
C#
99e3d2d74edd54e4746f158e4d0b1d5b663c373b
update assembly version to 3.0.2.0
rainmattertech/dotnetkiteconnect
KiteConnect/Properties/AssemblyInfo.cs
KiteConnect/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("KiteConnect")] [assembly: AssemblyDescription("Official .Net client library for Kite Connect APIs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Zerodha Technology Pvt. Ltd.")] [assembly: AssemblyProduct("KiteConnect")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("f5f75ad6-e72f-44da-8d3f-1360b000c684")] // 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("3.0.2.0")] [assembly: AssemblyFileVersion("3.0.2.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("KiteConnect")] [assembly: AssemblyDescription("Official .Net client library for Kite Connect APIs")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Zerodha Technology Pvt. Ltd.")] [assembly: AssemblyProduct("KiteConnect")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("f5f75ad6-e72f-44da-8d3f-1360b000c684")] // 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("3.0.1.0")] [assembly: AssemblyFileVersion("3.0.1.0")]
mit
C#
8a76eb51158caac8dd9ba505c0f82565a2568d86
add method to interface
BenPhegan/NuGet.Extensions
NuGet.Extensions/MSBuild/IVsProject.cs
NuGet.Extensions/MSBuild/IVsProject.cs
using System.Collections.Generic; using System.IO; namespace NuGet.Extensions.MSBuild { public interface IVsProject { IEnumerable<IReference> GetBinaryReferences(); string AssemblyName { get; } string ProjectName { get; } DirectoryInfo ProjectDirectory { get; } void Save(); void AddFile(string filename); IEnumerable<IReference> GetProjectReferences(); } }
using System.Collections.Generic; using System.IO; namespace NuGet.Extensions.MSBuild { public interface IVsProject { IEnumerable<IReference> GetBinaryReferences(); string AssemblyName { get; } string ProjectName { get; } DirectoryInfo ProjectDirectory { get; } void Save(); void AddFile(string filename); } }
mit
C#
5a2de19b13d9b894f761eb21cf8444eca98054bf
update minor version number to 1.2.*
ParagonTruss/UnitClassLibrary
UnitClassLibrary/Properties/AssemblyInfo.cs
UnitClassLibrary/Properties/AssemblyInfo.cs
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("Unit Class Library")] [assembly: AssemblyDescription("A class library that gives many operations for almost every measurable unit.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Clearspan Components Inc")] [assembly: AssemblyProduct("Unit Class Library")] [assembly: AssemblyCopyright("Copyright © Clearspan Components Inc 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. // The following GUID is for the ID of the typelib if this project is exposed to COM // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.2.*")] [assembly: AssemblyFileVersion("1.2.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("Unit Class Library")] [assembly: AssemblyDescription("A class library that gives many operations for almost every measurable unit.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Clearspan Components Inc")] [assembly: AssemblyProduct("Unit Class Library")] [assembly: AssemblyCopyright("Copyright © Clearspan Components Inc 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. // The following GUID is for the ID of the typelib if this project is exposed to COM // 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.1.*")] [assembly: AssemblyFileVersion("1.1.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
lgpl-2.1
C#
2358527f5012569d0fd0f10705a60a045ef9192e
fix template
takenet/messaginghub-client-csharp
src/Template/Program.cs
src/Template/Program.cs
using System; using System.Threading.Tasks; using Lime.Protocol; using Takenet.MessagingHub.Client; using Takenet.MessagingHub.Client.Receivers; namespace Template { internal static class Program { public static void Main(string[] args) { Init().Wait(); } private class MessageReceiver : MessageReceiverBase { public override async Task ReceiveAsync(Message message) { // Text messages sent to your application will be received here await MessageSender.SendMessageAsync("It works!", message.From); } } private static async Task Init() { // Go to http://console.messaginghub.io to register your application and get your access key const string login = "yourApplicationName"; const string accessKey = "yourAccessKey"; // Instantiates a MessageHubClient using its fluent API // Since host name and domain name are not informed, the default value, 'msging.net', will be used for both parameters var client = new MessagingHubClient() .UsingAccessKey(login, accessKey) .AddMessageReceiver(new MessageReceiver(), MediaTypes.PlainText); // Starts the client await client.StartAsync(); Console.WriteLine("Press any key to stop"); Console.ReadKey(); // Stop the client await client.StopAsync(); } } }
using System; using System.Threading.Tasks; using Lime.Protocol; using Takenet.MessagingHub.Client; using Takenet.MessagingHub.Client.Receivers; namespace Template { internal static class Program { public static void Main(string[] args) { Init().Wait(); } private class MessageReceiver : MessageReceiverBase { public override async Task ReceiveAsync(Message message) { // Text messages sent to your application will be received here await MessageSender.SendMessageAsync("It works!", message.From); } } private static async Task Init() { const string login = "yourApplicationName"; const string accessKey = "yourAccessKey"; // Instantiates a MessageHubClient using its fluent API // Since host name and domain name are not informed, the default value, 'msging.net', will be used for both parameters var client = new MessagingHubClient() .UsingAccessKey(login, accessKey) .AddMessageReceiver(new MessageReceiver(), MediaTypes.PlainText); // Starts the client await client.StartAsync(); Console.WriteLine("Press any key to stop"); Console.ReadKey(); // Stop the client await client.StopAsync(); } } }
apache-2.0
C#
9bd65323db51a995b10206a960720d65fb286ebd
Refactor the Venue level cost centre to inherit from the Account level cost centre to allow sharing of data structures.
ivvycode/ivvy-sdk-net
src/Venue/CostCenter.cs
src/Venue/CostCenter.cs
using Newtonsoft.Json; namespace Ivvy.API.Venue { public class CostCenter : Account.CostCenter { [JsonProperty("parentId")] public int? ParentId { get; set; } } }
using Newtonsoft.Json; namespace Ivvy.API.Venue { public class CostCenter { public enum DefaultTypes { Other = 1, VenueFood = 2, VenueBeverage = 3, VenueAudioVisual = 4, VenueRoomHire = 5, VenueAccommodation = 6, } [JsonProperty("id")] public int? Id { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("code")] public string Code { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("defaultType")] public DefaultTypes? DefaultType { get; set; } [JsonProperty("parentId")] public int? ParentId { get; set; } } }
mit
C#
97a69dffb62677c885021b0fb596b2d45c5e36ee
Fix using regression
ppy/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework
osu.Framework.Tests/Visual/Sprites/TestCaseScreenshot.cs
osu.Framework.Tests/Visual/Sprites/TestCaseScreenshot.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.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Platform; using osu.Framework.Testing; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Sprites { public class TestCaseScreenshot : TestCase { [Resolved] private GameHost host { get; set; } private Sprite display; [BackgroundDependencyLoader] private void load() { Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Masking = true, BorderColour = Color4.Green, BorderThickness = 2, Child = display = new Sprite { RelativeSizeAxes = Axes.Both } }; AddStep("take screenshot", takeScreenshot); } private void takeScreenshot() { if (host.Window == null) return; host.TakeScreenshotAsync().ContinueWith(t => Schedule(() => { var image = t.Result; var tex = new Texture(image.Width, image.Height); tex.SetData(new TextureUpload(image)); display.Texture = tex; })); } } }
// 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.Textures; using osu.Framework.Platform; using osu.Framework.Testing; using osuTK; using osuTK.Graphics; namespace osu.Framework.Tests.Visual.Sprites { public class TestCaseScreenshot : TestCase { [Resolved] private GameHost host { get; set; } private Graphics.Sprites.Sprite display; [BackgroundDependencyLoader] private void load() { Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f), Masking = true, BorderColour = Color4.Green, BorderThickness = 2, Child = display = new Graphics.Sprites.Sprite { RelativeSizeAxes = Axes.Both } }; AddStep("take screenshot", takeScreenshot); } private void takeScreenshot() { if (host.Window == null) return; host.TakeScreenshotAsync().ContinueWith(t => Schedule(() => { var image = t.Result; var tex = new Texture(image.Width, image.Height); tex.SetData(new TextureUpload(image)); display.Texture = tex; })); } } }
mit
C#
88d55b796b6c2dd99301031d5ed7d343bfc035d8
Add Maximum/Average aggregate functions for amplitudes
peppy/osu-framework,ZLima12/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,naoey/osu-framework,ZLima12/osu-framework,ppy/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,default0/osu-framework,default0/osu-framework,paparony03/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,peppy/osu-framework,Tom94/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,Nabile-Rahmani/osu-framework,naoey/osu-framework,EVAST9919/osu-framework
osu.Framework/Audio/Track/TrackAmplitudes.cs
osu.Framework/Audio/Track/TrackAmplitudes.cs
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; namespace osu.Framework.Audio.Track { public struct TrackAmplitudes { public float LeftChannel; public float RightChannel; public float Maximum => Math.Max(LeftChannel, RightChannel); public float Average => (LeftChannel + RightChannel) / 2; } }
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE namespace osu.Framework.Audio.Track { public struct TrackAmplitudes { public float LeftChannel; public float RightChannel; } }
mit
C#
0e20c3ca88825bf27c1f8a38d79d6fa3331a1972
Add source documentation for configuration class.
henrikfroehling/TraktApiSharp
Source/Lib/TraktApiSharp/Core/TraktConfiguration.cs
Source/Lib/TraktApiSharp/Core/TraktConfiguration.cs
namespace TraktApiSharp.Core { using System.Net.Http; /// <summary>Provides global client settings.</summary> public class TraktConfiguration { internal TraktConfiguration() { ApiVersion = 2; UseStagingUrl = false; } internal static HttpClient HTTP_CLIENT = null; /// <summary> /// Gets or sets the Trakt API version. /// <para> /// See <a href="http://docs.trakt.apiary.io/#introduction/api-url">"Trakt API Doc - API URL"</a> for more information. /// </para> /// </summary> public int ApiVersion { get; set; } /// <summary> /// Gets or sets, whether the Trakt API staging environment should be used. By default disabled. /// <para> /// See <a href="http://docs.trakt.apiary.io/#introduction/api-url">"Trakt API Doc - API URL"</a> for more information. /// </para> /// </summary> public bool UseStagingUrl { get; set; } /// <summary>Returns the Trakt API base URL based on, whether <see cref="UseStagingUrl" /> is false or true.</summary> public string BaseUrl => UseStagingUrl ? "https://api-staging.trakt.tv/" : $"https://api-v{ApiVersion}launch.trakt.tv/"; } }
namespace TraktApiSharp.Core { using System.Net.Http; public class TraktConfiguration { internal TraktConfiguration() { ApiVersion = 2; UseStagingUrl = false; } internal static HttpClient HTTP_CLIENT = null; public int ApiVersion { get; set; } public bool UseStagingUrl { get; set; } public string BaseUrl => UseStagingUrl ? "https://api-staging.trakt.tv/" : $"https://api-v{ApiVersion}launch.trakt.tv/"; } }
mit
C#
5d04ff79915d1acd301313acebfe53629ec96e7a
Add info to addin description about uninstalling old addin
mrward/monodevelop-dnx-addin
src/MonoDevelop.Dnx/Properties/AddinInfo.cs
src/MonoDevelop.Dnx/Properties/AddinInfo.cs
using Mono.Addins; [assembly:Addin ("Dnx", Namespace = "MonoDevelop", Version = "0.5", Category = "IDE extensions")] [assembly:AddinName ("DNX")] [assembly:AddinDescription ("Adds .NET Core and ASP.NET Core support.\n\nPlease uninstall any older version of the addin and restart the application before installing this new version.")] [assembly:AddinDependency ("Core", "6.0")] [assembly:AddinDependency ("Ide", "6.0")] [assembly:AddinDependency ("DesignerSupport", "6.0")] [assembly:AddinDependency ("Debugger", "6.0")] [assembly:AddinDependency ("Debugger.Soft", "6.0")] [assembly:AddinDependency ("SourceEditor2", "6.0")] [assembly:AddinDependency ("UnitTesting", "6.0")]
using Mono.Addins; [assembly:Addin ("Dnx", Namespace = "MonoDevelop", Version = "0.5", Category = "IDE extensions")] [assembly:AddinName ("DNX")] [assembly:AddinDescription ("Adds .NET Core and ASP.NET Core support.")] [assembly:AddinDependency ("Core", "6.0")] [assembly:AddinDependency ("Ide", "6.0")] [assembly:AddinDependency ("DesignerSupport", "6.0")] [assembly:AddinDependency ("Debugger", "6.0")] [assembly:AddinDependency ("Debugger.Soft", "6.0")] [assembly:AddinDependency ("SourceEditor2", "6.0")] [assembly:AddinDependency ("UnitTesting", "6.0")]
mit
C#
6983e660370aae362292022de028f0be2959ee02
Fix preprocessor condition
adamhathcock/sharpcompress,adamhathcock/sharpcompress,adamhathcock/sharpcompress
src/SharpCompress/Common/ArchiveEncoding.cs
src/SharpCompress/Common/ArchiveEncoding.cs
using System; using System.Text; namespace SharpCompress.Common { public class ArchiveEncoding { /// <summary> /// Default encoding to use when archive format doesn't specify one. /// </summary> public Encoding Default { get; set; } /// <summary> /// ArchiveEncoding used by encryption schemes which don't comply with RFC 2898. /// </summary> public Encoding Password { get; set; } /// <summary> /// Set this encoding when you want to force it for all encoding operations. /// </summary> public Encoding? Forced { get; set; } /// <summary> /// Set this when you want to use a custom method for all decoding operations. /// </summary> /// <returns>string Func(bytes, index, length)</returns> public Func<byte[], int, int, string>? CustomDecoder { get; set; } public ArchiveEncoding() : this(Encoding.Default, Encoding.Default) { } public ArchiveEncoding(Encoding def, Encoding password) { Default = def; Password = password; } #if !NETFRAMEWORK static ArchiveEncoding() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } #endif public string Decode(byte[] bytes) { return Decode(bytes, 0, bytes.Length); } public string Decode(byte[] bytes, int start, int length) { return GetDecoder().Invoke(bytes, start, length); } public string DecodeUTF8(byte[] bytes) { return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } public byte[] Encode(string str) { return GetEncoding().GetBytes(str); } public Encoding GetEncoding() { return Forced ?? Default ?? Encoding.UTF8; } public Func<byte[], int, int, string> GetDecoder() { return CustomDecoder ?? ((bytes, index, count) => GetEncoding().GetString(bytes, index, count)); } } }
using System; using System.Text; namespace SharpCompress.Common { public class ArchiveEncoding { /// <summary> /// Default encoding to use when archive format doesn't specify one. /// </summary> public Encoding Default { get; set; } /// <summary> /// ArchiveEncoding used by encryption schemes which don't comply with RFC 2898. /// </summary> public Encoding Password { get; set; } /// <summary> /// Set this encoding when you want to force it for all encoding operations. /// </summary> public Encoding? Forced { get; set; } /// <summary> /// Set this when you want to use a custom method for all decoding operations. /// </summary> /// <returns>string Func(bytes, index, length)</returns> public Func<byte[], int, int, string>? CustomDecoder { get; set; } public ArchiveEncoding() : this(Encoding.Default, Encoding.Default) { } public ArchiveEncoding(Encoding def, Encoding password) { Default = def; Password = password; } static ArchiveEncoding() { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } public string Decode(byte[] bytes) { return Decode(bytes, 0, bytes.Length); } public string Decode(byte[] bytes, int start, int length) { return GetDecoder().Invoke(bytes, start, length); } public string DecodeUTF8(byte[] bytes) { return Encoding.UTF8.GetString(bytes, 0, bytes.Length); } public byte[] Encode(string str) { return GetEncoding().GetBytes(str); } public Encoding GetEncoding() { return Forced ?? Default ?? Encoding.UTF8; } public Func<byte[], int, int, string> GetDecoder() { return CustomDecoder ?? ((bytes, index, count) => GetEncoding().GetString(bytes, index, count)); } } }
mit
C#
b280fad64f11dffd027e8165a54bb30f1fae19be
Fix IndexOutOfRangeException when using get-desc with SetupProcess
mono/mono-addins,mono/mono-addins
Mono.Addins.SetupProcess/SetupProcessTool.cs
Mono.Addins.SetupProcess/SetupProcessTool.cs
// // SetupProcessTool.cs // // Author: // Marius Ungureanu <maungu@microsoft.com> // // Copyright (c) 2019 Microsoft Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Mono.Addins.Database; namespace Mono.Addins.SetupProcess { class SetupProcessTool { public static int Main (string [] args) { ProcessProgressStatus monitor = new ProcessProgressStatus (int.Parse (args [0])); try { string registryPath = Console.In.ReadLine (); string startupDir = Console.In.ReadLine (); string addinsDir = Console.In.ReadLine (); string databaseDir = Console.In.ReadLine (); AddinDatabase.RunningSetupProcess = true; AddinRegistry reg = new AddinRegistry (registryPath, startupDir, addinsDir, databaseDir); switch (args [1]) { case "scan": { string folder = args.Length > 2 ? args [2] : null; if (folder.Length == 0) folder = null; var context = new ScanOptions (); context.Read (Console.In); reg.ScanFolders (monitor, folder, context); break; } case "pre-scan": { string folder = args.Length > 2 ? args [2] : null; if (folder.Length == 0) folder = null; var recursive = bool.Parse (Console.In.ReadLine ()); reg.GenerateScanDataFilesInProcess (monitor, folder, recursive); break; } case "get-desc": var outFile = Console.In.ReadLine (); reg.ParseAddin (monitor, args [2], outFile); break; } } catch (Exception ex) { monitor.ReportError ("Unexpected error in setup process", ex); return 1; } return 0; } } }
// // SetupProcessTool.cs // // Author: // Marius Ungureanu <maungu@microsoft.com> // // Copyright (c) 2019 Microsoft Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Mono.Addins.Database; namespace Mono.Addins.SetupProcess { class SetupProcessTool { public static int Main (string [] args) { ProcessProgressStatus monitor = new ProcessProgressStatus (int.Parse (args [0])); try { string registryPath = Console.In.ReadLine (); string startupDir = Console.In.ReadLine (); string addinsDir = Console.In.ReadLine (); string databaseDir = Console.In.ReadLine (); AddinDatabase.RunningSetupProcess = true; AddinRegistry reg = new AddinRegistry (registryPath, startupDir, addinsDir, databaseDir); switch (args [1]) { case "scan": { string folder = args.Length > 2 ? args [2] : null; if (folder.Length == 0) folder = null; var context = new ScanOptions (); context.Read (Console.In); reg.ScanFolders (monitor, folder, context); break; } case "pre-scan": { string folder = args.Length > 2 ? args [2] : null; if (folder.Length == 0) folder = null; var recursive = bool.Parse (Console.In.ReadLine ()); reg.GenerateScanDataFilesInProcess (monitor, folder, recursive); break; } case "get-desc": var outFile = Console.In.ReadLine (); reg.ParseAddin (monitor, args [2], args [3]); break; } } catch (Exception ex) { monitor.ReportError ("Unexpected error in setup process", ex); return 1; } return 0; } } }
mit
C#
2671e2993d559da4d2bc13f5deeb0b3b89d22637
Adjust project to AppVeyor builds
tomaszkiewicz/rsb
RSB.Diagnostics.Tests/BusDiagnosticsTests.cs
RSB.Diagnostics.Tests/BusDiagnosticsTests.cs
using System.Threading; using System.Threading.Tasks; using NUnit.Framework; using RSB.Interfaces; using RSB.Transports.RabbitMQ; namespace RSB.Diagnostics.Tests { [TestFixture] public class BusDiagnosticsTests { private IBus _busServer1; private IBus _busServer2; private IBus _busClient; private volatile bool _busServer1Subsystem1Health = true; private volatile bool _busServer1Subsystem2Health = true; private volatile bool _busServer2Subsystem1Health = true; private volatile bool _busServer2Subsystem2Health = true; private BusDiscoveryClient _discoveryClient; [SetUp] public void Init() { _busServer1 = new Bus(RabbitMqTransport.FromConfigurationFile()); _busServer1.UseBusDiagnostics("Module1", "Instance1", diagnostics1 => { diagnostics1.RegisterSubsystemHealthChecker("subsystem1", () => _busServer1Subsystem1Health); diagnostics1.RegisterSubsystemHealthChecker("subsystem2", () => _busServer1Subsystem2Health); }); _busServer2 = new Bus(RabbitMqTransport.FromConfigurationFile()); _busServer2.UseBusDiagnostics("Module2", "Instance2", diagnostics2 => { diagnostics2.RegisterSubsystemHealthChecker("subsystem1", () => _busServer2Subsystem1Health); diagnostics2.RegisterSubsystemHealthChecker("subsystem2", () => _busServer2Subsystem2Health); }); _busClient = new Bus(RabbitMqTransport.FromConfigurationFile()); _discoveryClient = new BusDiscoveryClient(_busClient); Thread.Sleep(3000); } [TearDown] public void Deinit() { _busServer1.Shutdown(); _busServer2.Shutdown(); _busClient.Shutdown(); } [Test] public async Task TestDiscovery() { await _discoveryClient.DiscoverComponents(5); } } }
using System.Threading; using NUnit.Framework; using RSB.Interfaces; using RSB.Transports.RabbitMQ; namespace RSB.Diagnostics.Tests { [TestFixture] public class BusDiagnosticsTests { private IBus _busServer1; private IBus _busServer2; private IBus _busClient; private volatile bool _busServer1Subsystem1Health = true; private volatile bool _busServer1Subsystem2Health = true; private volatile bool _busServer2Subsystem1Health = true; private volatile bool _busServer2Subsystem2Health = true; private BusDiscoveryClient _discoveryClient; [SetUp] public void Init() { _busServer1 = new Bus(RabbitMqTransport.FromConfigurationFile()); _busServer1.UseBusDiagnostics("Module1", "Instance1", diagnostics1 => { diagnostics1.RegisterSubsystemHealthChecker("subsystem1", () => _busServer1Subsystem1Health); diagnostics1.RegisterSubsystemHealthChecker("subsystem2", () => _busServer1Subsystem2Health); }); _busServer2 = new Bus(RabbitMqTransport.FromConfigurationFile()); _busServer2.UseBusDiagnostics("Module2", "Instance2", diagnostics2 => { diagnostics2.RegisterSubsystemHealthChecker("subsystem1", () => _busServer2Subsystem1Health); diagnostics2.RegisterSubsystemHealthChecker("subsystem2", () => _busServer2Subsystem2Health); }); _busClient = new Bus(RabbitMqTransport.FromConfigurationFile()); _discoveryClient = new BusDiscoveryClient(_busClient); Thread.Sleep(3000); } [TearDown] public void Deinit() { _busServer1.Shutdown(); _busServer2.Shutdown(); _busClient.Shutdown(); } [Test] public async void TestDiscovery() { await _discoveryClient.DiscoverComponents(5); } } }
bsd-3-clause
C#
ceb7982c7b98022d629c8f48f34c64400107d09d
Fix bug caused by missing initialization
jdno/AIChallengeFramework
Map/Map.cs
Map/Map.cs
// // Copyright 2014 jdno // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; namespace AIChallengeFramework { /// <summary> /// A map is the top-level organizational unit of the gaming board. It contains /// of several continents. /// </summary> public class Map { /// <summary> /// A map consists of several continents. /// </summary> /// <value>The continents.</value> public List<Continent> Continents { get; private set; } /// <summary> /// Lookup regions on this map using their ID. /// </summary> /// <value>The regions.</value> public Dictionary<int, Region> Regions { get; private set; } public Map () { Continents = new List<Continent> (); Regions = new Dictionary<int, Region> (); } /// <summary> /// Adds the continent to the map. /// </summary> /// <param name="continent">Continent.</param> public void AddContinent (Continent continent) { if (!Continents.Contains (continent)) { Continents.Add (continent); } } /// <summary> /// Adds the region to the map. /// </summary> /// <param name="region">Region.</param> public void AddRegion (Region region) { Regions.Add (region.Id, region); } /// <summary> /// Return the continent with the given identifier. /// </summary> /// <returns>The continent with the given identifier.</returns> /// <param name="id">Identifier.</param> public Continent ContinentForId (int id) { foreach (Continent c in Continents) { if (c.Id == id) { return c; } } return null; } } }
// // Copyright 2014 jdno // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; namespace AIChallengeFramework { /// <summary> /// A map is the top-level organizational unit of the gaming board. It contains /// of several continents. /// </summary> public class Map { /// <summary> /// A map consists of several continents. /// </summary> /// <value>The continents.</value> public List<Continent> Continents { get; private set; } /// <summary> /// Lookup regions on this map using their ID. /// </summary> /// <value>The regions.</value> public Dictionary<int, Region> Regions { get; private set; } public Map () { Continents = new List<Continent> (); } /// <summary> /// Adds the continent to the map. /// </summary> /// <param name="continent">Continent.</param> public void AddContinent (Continent continent) { if (!Continents.Contains (continent)) { Continents.Add (continent); } } /// <summary> /// Adds the region to the map. /// </summary> /// <param name="region">Region.</param> public void AddRegion (Region region) { Regions.Add (region.Id, region); } /// <summary> /// Return the continent with the given identifier. /// </summary> /// <returns>The continent with the given identifier.</returns> /// <param name="id">Identifier.</param> public Continent ContinentForId (int id) { foreach (Continent c in Continents) { if (c.Id == id) { return c; } } return null; } } }
apache-2.0
C#
da7c30657df7cc6235399da266fe5e6671e729d4
Update Timber to 4.4.0
xamarin/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,xamarin/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents,bholmes/XamarinComponents
Android/Timber/build.cake
Android/Timber/build.cake
#load "../../common.cake" var TARGET = Argument ("t", Argument ("target", "Default")); var ANDROID_VERSION = "4.4.0"; var ANDROID_NUGET_VERSION = "4.4.0"; var ANDROID_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/jakewharton/timber/timber/{0}/timber-{0}.aar", ANDROID_VERSION); var ANDROID_FILE = "jakewharton.timber.aar"; var buildSpec = new BuildSpec () { Libs = new ISolutionBuilder [] { new DefaultSolutionBuilder { SolutionPath = "./source/Timber.sln", OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/Timber/bin/Release/Timber.dll", } } } }, Samples = new ISolutionBuilder [] { new DefaultSolutionBuilder { SolutionPath = "./samples/TimberSample.sln" }, }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.JakeWharton.Timber.nuspec", Version = ANDROID_NUGET_VERSION }, }, }; Task ("externals") .Does (() => { if (!DirectoryExists ("./externals/")) CreateDirectory ("./externals/"); DownloadFile (ANDROID_URL, "./externals/" + ANDROID_FILE); }); Task ("clean").IsDependentOn ("clean-base").Does (() => { DeleteFiles ("./externals/*.aar"); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
#load "../../common.cake" var TARGET = Argument ("t", Argument ("target", "Default")); var ANDROID_VERSION = "4.3.1"; var ANDROID_NUGET_VERSION = "4.3.1.1"; var ANDROID_URL = string.Format ("http://search.maven.org/remotecontent?filepath=com/jakewharton/timber/timber/{0}/timber-{0}.aar", ANDROID_VERSION); var ANDROID_FILE = "jakewharton.timber.aar"; var buildSpec = new BuildSpec () { Libs = new ISolutionBuilder [] { new DefaultSolutionBuilder { SolutionPath = "./source/Timber.sln", OutputFiles = new [] { new OutputFileCopy { FromFile = "./source/Timber/bin/Release/Timber.dll", } } } }, Samples = new ISolutionBuilder [] { new DefaultSolutionBuilder { SolutionPath = "./samples/TimberSample.sln" }, }, NuGets = new [] { new NuGetInfo { NuSpec = "./nuget/Xamarin.JakeWharton.Timber.nuspec", Version = ANDROID_NUGET_VERSION }, }, }; Task ("externals") .Does (() => { if (!DirectoryExists ("./externals/")) CreateDirectory ("./externals/"); DownloadFile (ANDROID_URL, "./externals/" + ANDROID_FILE); }); Task ("clean").IsDependentOn ("clean-base").Does (() => { DeleteFiles ("./externals/*.aar"); }); SetupXamarinBuildTasks (buildSpec, Tasks, Task); RunTarget (TARGET);
mit
C#
35940a6701b90de703255fcf4b96a2b9583a5f8e
Add terminal velocity
wqferr/GMTK-GameJam
Assets/Scripts/PlayerController.cs
Assets/Scripts/PlayerController.cs
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public Rigidbody2D rb; public bool goingUp; public bool goingDown; public bool airborne; public float timeJumping; public float jumpDuration; public float timeFalling; public float fallDuration; public float fallingSpeed; public float fallGravity; public float maxFallSpeed; public float groundHeight; // jumping public float initialHeight; public float targetHeight; public float jumpPeak; public float airJumpHeight; // Use this for initialization void Start () { groundHeight = transform.position.y; } // Update is called once per frame void Update () { if (Input.GetButtonDown ("Fire1") && !airborne) { JumpTo(jumpPeak, 0.8f); } } void FixedUpdate() { if (airborne) { if (goingUp) { timeJumping += Time.fixedDeltaTime; if (Mathf.Abs (transform.position.y - targetHeight) < 0.1f) { transform.position = new Vector3 ( transform.position.x, targetHeight, transform.position.z ); StartFalling (); } else { float t = timeJumping / jumpDuration - 1; float dh = targetHeight - initialHeight; transform.position = new Vector3 ( transform.position.x, dh * (t*t*t*t*t + 1) + initialHeight, transform.position.z ); } } else if (goingDown) { if (Mathf.Abs (transform.position.y - groundHeight) < 0.1f) { airborne = false; goingDown = false; } else { fallingSpeed -= fallGravity * fallGravity * Time.fixedDeltaTime; if (fallingSpeed < maxFallSpeed) fallingSpeed = maxFallSpeed; transform.Translate (new Vector3 (0.0f, fallingSpeed, 0.0f) * Time.fixedDeltaTime); } } } } void JumpTo(float peak, float duration) { targetHeight = peak; initialHeight = transform.position.y; timeJumping = 0; jumpDuration = duration; airborne = true; goingUp = true; } void StartFalling() { goingUp = false; goingDown = true; timeFalling = 0; fallingSpeed = 0; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public Rigidbody2D rb; public bool goingUp; public bool goingDown; public bool airborne; public float timeJumping; public float jumpDuration; public float timeFalling; public float fallDuration; public float fallingSpeed; public float fallGravity; public float maxFallSpeed; public float groundHeight; // jumping public float initialHeight; public float targetHeight; public float jumpPeak; public float airJumpHeight; // Use this for initialization void Start () { groundHeight = transform.position.y; } // Update is called once per frame void Update () { if (Input.GetButtonDown ("Fire1") && !airborne) { JumpTo(jumpPeak, 0.8f); } } void FixedUpdate() { if (airborne) { if (goingUp) { timeJumping += Time.fixedDeltaTime; if (Mathf.Abs (transform.position.y - targetHeight) < 0.1f) { transform.position = new Vector3 ( transform.position.x, targetHeight, transform.position.z ); StartFalling (); } else { float t = timeJumping / jumpDuration - 1; float dh = targetHeight - initialHeight; transform.position = new Vector3 ( transform.position.x, dh * (t*t*t*t*t + 1) + initialHeight, transform.position.z ); } } else if (goingDown) { if (Mathf.Abs (transform.position.y - groundHeight) < 0.1f) { airborne = false; goingDown = false; } else { fallingSpeed -= fallGravity * fallGravity * Time.fixedDeltaTime; transform.Translate (new Vector3 (0.0f, fallingSpeed, 0.0f) * Time.fixedDeltaTime); } } } } void JumpTo(float peak, float duration) { targetHeight = peak; initialHeight = transform.position.y; timeJumping = 0; jumpDuration = duration; airborne = true; goingUp = true; } void StartFalling() { goingUp = false; goingDown = true; timeFalling = 0; fallingSpeed = 0; } }
mit
C#
6aff0d75c7436f55e576cfaf5480b5bc7cba0c6c
Add Comments to RPGStat Class
jkpenner/RPGStatTutorial
Assets/Scripts/RPGStat.cs
Assets/Scripts/RPGStat.cs
using UnityEngine; using System.Collections; public class RPGStat { /// <summary> /// The Name of the RPGStat. Used mostly for UI purposes /// </summary> private string _statName; /// <summary> /// The Base value of the stat /// </summary> private int _statBaseValue; /// <summary> /// Initializes a new instance of the RPGStat class /// </summary> public RPGStat() { _statName = string.Empty; _statBaseValue = 0; } /// <summary> /// Gets or sets the _statName /// </summary> public string StatName { get { return _statName; } set { _statName = value; } } /// <summary> /// [Overridable] Gets or sets the _statBaseValue /// </summary> public virtual int StatBaseValue { get { return _statBaseValue; } set { _statBaseValue = value; } } /// <summary> /// [Overridable] Gets the stat's value. /// </summary> public virtual int StatValue { get { return StatBaseValue; } } }
using UnityEngine; using System.Collections; public class RPGStat { private string _statName; private int _statBaseValue; public RPGStat() { _statName = string.Empty; _statBaseValue = 0; } public string StatName { get { return _statName; } set { _statName = value; } } public virtual int StatBaseValue { get { return _statBaseValue; } set { _statBaseValue = value; } } public virtual int StatValue { get { return StatBaseValue; } } }
mit
C#
e45d961337438ba46c85fc67650397be44582b29
Resolve Issue #22: disable console listener by default.
GibraltarSoftware/Loupe.Agent.Core,GibraltarSoftware/Loupe.Agent.Core,GibraltarSoftware/Loupe.Agent.Core
src/Extensibility/Configuration/ListenerConfiguration.cs
src/Extensibility/Configuration/ListenerConfiguration.cs
namespace Loupe.Configuration { /// <summary> /// Configuration information for the trace listener. /// </summary> public sealed class ListenerConfiguration { /// <summary> /// Initialize from application configuration section /// </summary> public ListenerConfiguration() { AutoTraceRegistration = true; EnableConsole = false; //this is nearly always duplicate information in .NET Core. EnableNetworkEvents = true; EndSessionOnTraceClose = true; } /// <summary> /// Configures whether Loupe should automatically make sure it is registered as a Trace Listener. /// </summary> /// <remarks>This is true by default to enable easy drop-in configuration (e.g. using the LiveLogViewer /// control on a form). Normally, it should not be necessary to disable this feature even when adding /// Loupe as a Trace Listener in an app.config or by code. But this setting can be configured /// to false if it is desirable to prevent Loupe from receiving Trace events directly, such as /// if the application is processing Trace events into the Loupe API itself.</remarks> public bool AutoTraceRegistration { get; set; } /// <summary> /// When true, anything written to the console out will be appended to the log. /// </summary> /// <remarks>Disabled by default as ASP.NET Core applications send significant duplicate data to the console.</remarks> public bool EnableConsole { get; set; } /// <summary> /// When true, network events (such as reconfiguration and disconnection) will be logged automatically. /// </summary> public bool EnableNetworkEvents { get; set; } /// <summary> /// When true, the Loupe LogListener will end the Loupe log session when Trace.Close() is called. /// </summary> /// <remarks>This setting has no effect if the trace listener is not enabled. Unless disabled by setting /// this configuration value to false, a call to Trace.Close() to shutdown Trace logging will also be /// translated into a call to Gibraltar.Agent.Log.EndSession().</remarks> public bool EndSessionOnTraceClose { get; set; } } }
namespace Loupe.Configuration { /// <summary> /// Configuration information for the trace listener. /// </summary> public sealed class ListenerConfiguration { /// <summary> /// Initialize from application configuration section /// </summary> public ListenerConfiguration() { AutoTraceRegistration = true; EnableConsole = true; EnableNetworkEvents = true; EndSessionOnTraceClose = true; } /// <summary> /// Configures whether Loupe should automatically make sure it is registered as a Trace Listener. /// </summary> /// <remarks>This is true by default to enable easy drop-in configuration (e.g. using the LiveLogViewer /// control on a form). Normally, it should not be necessary to disable this feature even when adding /// Loupe as a Trace Listener in an app.config or by code. But this setting can be configured /// to false if it is desirable to prevent Loupe from receiving Trace events directly, such as /// if the application is processing Trace events into the Loupe API itself.</remarks> public bool AutoTraceRegistration { get; set; } /// <summary> /// When true, anything written to the console out will be appended to the log. /// </summary> /// <remarks>This setting has no effect if the trace listener is not enabled.</remarks> public bool EnableConsole { get; set; } /// <summary> /// When true, network events (such as reconfiguration and disconnection) will be logged automatically. /// </summary> public bool EnableNetworkEvents { get; set; } /// <summary> /// When true, the Loupe LogListener will end the Loupe log session when Trace.Close() is called. /// </summary> /// <remarks>This setting has no effect if the trace listener is not enabled. Unless disabled by setting /// this configuration value to false, a call to Trace.Close() to shutdown Trace logging will also be /// translated into a call to Gibraltar.Agent.Log.EndSession().</remarks> public bool EndSessionOnTraceClose { get; set; } } }
mit
C#
2b61837967913f885e0cc1e1c88b278e044771f6
Add accounts-specific NameType removed from CodeFirstWebFramework.
nikkilocke/AccountServer,nikkilocke/AccountServer
Program.cs
Program.cs
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Configuration; using System.Globalization; using System.Threading; using CodeFirstWebFramework; namespace AccountServer { static class Program { static void Main(string[] args) { Config.Load(args); bool windows = false; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: windows = true; break; } // Default to UK culture and time (specify empty culture and/or tz to use machine values) if (Config.CommandLineFlags["culture"] != "") { CultureInfo c = new CultureInfo(Config.CommandLineFlags["culture"] ?? "en-GB"); Thread.CurrentThread.CurrentCulture = c; CultureInfo.DefaultThreadCurrentCulture = c; CultureInfo.DefaultThreadCurrentUICulture = c; } if (!string.IsNullOrEmpty(Config.CommandLineFlags["tz"])) Utils._tz = TimeZoneInfo.FindSystemTimeZoneById(Config.CommandLineFlags["tz"] ?? (windows ? "GMT Standard Time" : "GB")); if (windows) { string startPage = ""; if (Config.CommandLineFlags["url"] != null) startPage = Config.CommandLineFlags["url"]; if (Config.CommandLineFlags["nolaunch"] == null) System.Diagnostics.Process.Start("http://" + Config.Default.DefaultServer.ServerName + ":" + Config.Default.Port + "/" + startPage); } new WebServer().Start(); } /// <summary> /// Translate NameType letter to human-readable form /// </summary> public static string NameType(this string type) { switch (type) { case "C": return "Customer"; case "S": return "Supplier"; case "O": return "Other Name"; case "M": return "Member"; case "": case null: return "Unknown"; default: return "Type " + type; } } } }
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Configuration; using System.Globalization; using System.Threading; using CodeFirstWebFramework; namespace AccountServer { class Program { static void Main(string[] args) { Config.Load(args); bool windows = false; switch (Environment.OSVersion.Platform) { case PlatformID.Win32NT: case PlatformID.Win32S: case PlatformID.Win32Windows: windows = true; break; } // Default to UK culture and time (specify empty culture and/or tz to use machine values) if (Config.CommandLineFlags["culture"] != "") { CultureInfo c = new CultureInfo(Config.CommandLineFlags["culture"] ?? "en-GB"); Thread.CurrentThread.CurrentCulture = c; CultureInfo.DefaultThreadCurrentCulture = c; CultureInfo.DefaultThreadCurrentUICulture = c; } if (!string.IsNullOrEmpty(Config.CommandLineFlags["tz"])) Utils._tz = TimeZoneInfo.FindSystemTimeZoneById(Config.CommandLineFlags["tz"] ?? (windows ? "GMT Standard Time" : "GB")); if (windows) { string startPage = ""; if (Config.CommandLineFlags["url"] != null) startPage = Config.CommandLineFlags["url"]; if (Config.CommandLineFlags["nolaunch"] == null) System.Diagnostics.Process.Start("http://" + Config.Default.DefaultServer.ServerName + ":" + Config.Default.Port + "/" + startPage); } new WebServer().Start(); } } }
apache-2.0
C#
2e2871c9f21874b6c5f0aeda4ebe0fb146c3a0ac
add ifdef
technicat/LearnUnity,technicat/LearnUnity
chapter17/unityproject/Assets/CSharp/Splash.cs
chapter17/unityproject/Assets/CSharp/Splash.cs
/* Copyright (c) 2013 Technicat, LLC. All Rights Reserved. MIT License. http://learnunity4.com/ */ using UnityEngine; using System.Collections; namespace Fugu { public class Splash : MonoBehaviour { public float waitTime=2; // in seconds public string level=""; // scene name to load // Use this for initialization void Start () { UnityEngine.Object.DontDestroyOnLoad(gameObject); // retain this object through a level load #if UNITY_IOS Handheld.SetActivityIndicatorStyle(UnityEngine.iOS.ActivityIndicatorStyle.Gray); #endif #if UNITY_ANDROID Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.InversedLarge); #endif #if UNITY_IOS || UNITY_ANDROID Handheld.StartActivityIndicator(); #endif StartCoroutine (WaitAndLoad ()); } IEnumerator WaitAndLoad() { yield return new WaitForSeconds(waitTime); Application.LoadLevel(level); UnityEngine.SceneManagement.SceneManager.LoadScene(level); } } }
/* Copyright (c) 2013 Technicat, LLC. All Rights Reserved. MIT License. http://learnunity4.com/ */ using UnityEngine; using System.Collections; namespace Fugu { public class Splash : MonoBehaviour { public float waitTime=2; // in seconds public string level=""; // scene name to load // Use this for initialization void Start () { UnityEngine.Object.DontDestroyOnLoad(gameObject); // retain this object through a level load #if UNITY_IOS Handheld.SetActivityIndicatorStyle(UnityEngine.iOS.ActivityIndicatorStyle.Gray); #endif #if UNITY_ANDROID Handheld.SetActivityIndicatorStyle(AndroidActivityIndicatorStyle.InversedLarge); #endif Handheld.StartActivityIndicator(); StartCoroutine (WaitAndLoad ()); } IEnumerator WaitAndLoad() { yield return new WaitForSeconds(waitTime); Application.LoadLevel(level); UnityEngine.SceneManagement.SceneManager.LoadScene(level); } } }
mit
C#
55c77f968e7eafbf4ccd0c20fc0afb4f727ee290
Edit in vs
mtsuker/GitTest1
ConsoleApp1/ConsoleApp1/Program.cs
ConsoleApp1/ConsoleApp1/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //github change + edit // edit in VS } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { //github change + edit } } }
mit
C#
1ec24d7916b3421a9f74d5bff1268ff72b71b28a
Update WpfMinesweeperButton.cs
Minesweeper-6-Team-Project-Telerik/Minesweeper-6
src2/WpfMinesweeper/WpfMinesweeperButton.cs
src2/WpfMinesweeper/WpfMinesweeperButton.cs
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WpfMinesweeperButton.cs" company="Telerik Academy"> // Teamwork Project "Minesweeper-6" // </copyright> // <summary> // The wpf minesweeper button. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System.Windows.Controls; /// <summary> /// The wpf minesweeper button. /// </summary> public class WpfMinesweeperButton : Button { /// <summary> /// Gets or sets the row. /// </summary> public int Row { get; set; } /// <summary> /// Gets or sets the col. /// </summary> public int Col { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="WpfMinesweeperButton.cs" company=""> // // </copyright> // <summary> // The wpf minesweeper button. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace WpfMinesweeper { using System.Windows.Controls; /// <summary> /// The wpf minesweeper button. /// </summary> public class WpfMinesweeperButton : Button { /// <summary> /// Gets or sets the row. /// </summary> public int Row { get; set; } /// <summary> /// Gets or sets the col. /// </summary> public int Col { get; set; } } }
mit
C#
7a00fd84f86bcddaec8e01c9af8d12d6f1e39bab
Add more shell unit test
falahati/LiteDB,89sos98/LiteDB,89sos98/LiteDB,falahati/LiteDB,mbdavid/LiteDB
LiteDB.Tests/Engine/Shell_Tests.cs
LiteDB.Tests/Engine/Shell_Tests.cs
using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LiteDB.Tests.Engine { [TestClass] public class Shell_Tests { [TestMethod] public void Shell_Commands() { using (var db = new LiteEngine(new MemoryStream())) { db.Run("db.col1.insert {a: 1}"); db.Run("db.col1.insert {a: 2}"); db.Run("db.col1.insert {a: 3}"); db.Run("db.col1.ensureIndex a"); Assert.AreEqual(1, db.Run("db.col1.find a = 1").First().AsDocument["a"].AsInt32); db.Run("db.col1.update a = $.a + 10, b = 2 where a = 1"); Assert.AreEqual(11, db.Run("db.col1.find a = 11").First().AsDocument["a"].AsInt32); Assert.AreEqual(3, db.Count("col1")); // insert new data db.Run("db.data.insert {Text: \"Anything\", Number: 10} id:int"); db.Run("db.data.ensureIndex Text"); var doc = db.Run("db.data.find Text like \"A\"").First() as BsonDocument; Assert.AreEqual(1, doc["_id"].AsInt32); Assert.AreEqual("Anything", doc["Text"].AsString); Assert.AreEqual(10, doc["Number"].AsInt32); } } } }
using System.IO; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace LiteDB.Tests.Engine { [TestClass] public class Shell_Tests { [TestMethod] public void Shell_Commands() { using (var db = new LiteEngine(new MemoryStream())) { db.Run("db.col1.insert {a: 1}"); db.Run("db.col1.insert {a: 2}"); db.Run("db.col1.insert {a: 3}"); db.Run("db.col1.ensureIndex a"); Assert.AreEqual(1, db.Run("db.col1.find a = 1").First().AsDocument["a"].AsInt32); db.Run("db.col1.update a = $.a + 10, b = 2 where a = 1"); Assert.AreEqual(11, db.Run("db.col1.find a = 11").First().AsDocument["a"].AsInt32); Assert.AreEqual(3, db.Count("col1")); } } } }
mit
C#
10d67b6655a31b89e9bb30aa03f2ea2220822d4d
Change Instruction#Destination's type
lury-lang/lury-ir
LuryIR/Compiling/IR/Instruction.cs
LuryIR/Compiling/IR/Instruction.cs
// // Instruction.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2015 Tomona Nanase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; namespace Lury.Compiling.IR { public class Instruction { #region -- Public Fields -- public const int NoAssign = -1; #endregion #region -- Public Properties -- public int Destination { get; private set; } public Operation Operation { get; private set; } public IReadOnlyList<Parameter> Parameters { get; private set; } #endregion #region -- Constructors -- public Instruction(int destination, Operation operation, params Parameter[] parameters) { if (!Enum.IsDefined(typeof(Operation), operation)) throw new ArgumentOutOfRangeException("operation"); this.Destination = destination; this.Operation = operation; this.Parameters = parameters ?? new Parameter[0]; } public Instruction(int destination, Operation operation) : this(destination, operation, null) { } public Instruction(Operation operation, params Parameter[] parameters) : this(NoAssign, operation, parameters) { } public Instruction(Operation operation) : this(NoAssign, operation, null) { } #endregion } }
// // Instruction.cs // // Author: // Tomona Nanase <nanase@users.noreply.github.com> // // The MIT License (MIT) // // Copyright (c) 2015 Tomona Nanase // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; namespace Lury.Compiling.IR { public class Instruction { #region -- Public Fields -- public const int NoAssign = -1; #endregion #region -- Public Properties -- public string Destination { get; private set; } public Operation Operation { get; private set; } public IReadOnlyList<Parameter> Parameters { get; private set; } #endregion #region -- Constructors -- public Instruction(string destination, Operation operation, params Parameter[] parameters) { if (!Enum.IsDefined(typeof(Operation), operation)) throw new ArgumentOutOfRangeException("operation"); this.Destination = destination; this.Operation = operation; this.Parameters = parameters ?? new Parameter[0]; } public Instruction(string destination, Operation operation) : this(destination, operation, null) { } public Instruction(Operation operation, params Parameter[] parameters) : this(null, operation, parameters) { } public Instruction(Operation operation) : this(null, operation, null) { } #endregion } }
mit
C#
266a07c108b5895a8c18a6ff4075ffc02f39cd13
comment typo
viktorbalog/Maileon
Maileon/Contacts/InvalidContact.cs
Maileon/Contacts/InvalidContact.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Maileon.Contacts { /// <summary> /// A class representing an invalid contact /// </summary> public class InvalidContact : Contact { /// <summary> /// The SynchronizationError that makes this contact invalid /// </summary> [XmlElement("error")] public SynchronizationError Error { get; set; } public InvalidContact() { } public InvalidContact(SynchronizationError error) { this.Error = error; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Maileon.Contacts { /// <summary> /// A calss representing an invalid contact /// </summary> public class InvalidContact : Contact { /// <summary> /// The SynchronizationError that makes this contact invalid /// </summary> [XmlElement("error")] public SynchronizationError Error { get; set; } public InvalidContact() { } public InvalidContact(SynchronizationError error) { this.Error = error; } } }
mit
C#
585bd541f319ce316c8c4eef80aeb4247449b232
Add missing parentheses to RPM calculation
NeoAdonis/osu,ppy/osu,peppy/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu
osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs
osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.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; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Utils; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSpunOut : Mod, IApplicableToDrawableHitObject { public override string Name => "Spun Out"; public override string Acronym => "SO"; public override IconUsage? Icon => OsuIcon.ModSpunOut; public override ModType Type => ModType.Automation; public override string Description => @"Spinners will be automatically completed."; public override double ScoreMultiplier => 0.9; public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) }; public void ApplyToDrawableHitObject(DrawableHitObject hitObject) { if (hitObject is DrawableSpinner spinner) { spinner.HandleUserInput = false; spinner.OnUpdate += onSpinnerUpdate; } } private void onSpinnerUpdate(Drawable drawable) { var spinner = (DrawableSpinner)drawable; spinner.RotationTracker.Tracking = true; // early-return if we were paused to avoid division-by-zero in the subsequent calculations. if (Precision.AlmostEquals(spinner.Clock.Rate, 0)) return; // because the spinner is under the gameplay clock, it is affected by rate adjustments on the track; // for that reason using ElapsedFrameTime directly leads to fewer SPM with Half Time and more SPM with Double Time. // for spinners we want the real (wall clock) elapsed time; to achieve that, unapply the clock rate locally here. double rateIndependentElapsedTime = spinner.Clock.ElapsedFrameTime / spinner.Clock.Rate; float rotationSpeed = (float)(spinner.HitObject.SpinsRequired / (spinner.HitObject.Duration / 1.01)); spinner.RotationTracker.AddRotation(MathUtils.RadiansToDegrees((float)rateIndependentElapsedTime * rotationSpeed * MathF.PI * 2.0f)); } } }
// 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; using osu.Framework.Graphics; using osu.Framework.Graphics.Sprites; using osu.Framework.Utils; using osu.Game.Graphics; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Osu.Objects.Drawables; namespace osu.Game.Rulesets.Osu.Mods { public class OsuModSpunOut : Mod, IApplicableToDrawableHitObject { public override string Name => "Spun Out"; public override string Acronym => "SO"; public override IconUsage? Icon => OsuIcon.ModSpunOut; public override ModType Type => ModType.Automation; public override string Description => @"Spinners will be automatically completed."; public override double ScoreMultiplier => 0.9; public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) }; public void ApplyToDrawableHitObject(DrawableHitObject hitObject) { if (hitObject is DrawableSpinner spinner) { spinner.HandleUserInput = false; spinner.OnUpdate += onSpinnerUpdate; } } private void onSpinnerUpdate(Drawable drawable) { var spinner = (DrawableSpinner)drawable; spinner.RotationTracker.Tracking = true; // early-return if we were paused to avoid division-by-zero in the subsequent calculations. if (Precision.AlmostEquals(spinner.Clock.Rate, 0)) return; // because the spinner is under the gameplay clock, it is affected by rate adjustments on the track; // for that reason using ElapsedFrameTime directly leads to fewer SPM with Half Time and more SPM with Double Time. // for spinners we want the real (wall clock) elapsed time; to achieve that, unapply the clock rate locally here. double rateIndependentElapsedTime = spinner.Clock.ElapsedFrameTime / spinner.Clock.Rate; float rotationSpeed = (float)(spinner.HitObject.SpinsRequired / spinner.HitObject.Duration / 1.01); spinner.RotationTracker.AddRotation(MathUtils.RadiansToDegrees((float)rateIndependentElapsedTime * rotationSpeed * MathF.PI * 2.0f)); } } }
mit
C#
36ae4dd2715f911d0d649c7e133ae7392b0f6558
Fix osu! playfield (was using inheriting sizemode when it shouldn't).
naoey/osu,ppy/osu,Frontear/osuKyzer,DrabWeb/osu,ppy/osu,UselessToucan/osu,johnneijzen/osu,peppy/osu-new,nyaamara/osu,peppy/osu,NeoAdonis/osu,theguii/osu,NeoAdonis/osu,smoogipooo/osu,NotKyon/lolisu,Damnae/osu,2yangk23/osu,RedNesto/osu,osu-RP/osu-RP,DrabWeb/osu,smoogipoo/osu,naoey/osu,EVAST9919/osu,tacchinotacchi/osu,Nabile-Rahmani/osu,smoogipoo/osu,EVAST9919/osu,2yangk23/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,DrabWeb/osu,UselessToucan/osu,default0/osu,ppy/osu,ZLima12/osu,Drezi126/osu,peppy/osu,johnneijzen/osu,smoogipoo/osu,naoey/osu,ZLima12/osu
osu.Game/GameModes/Play/Osu/OsuPlayfield.cs
osu.Game/GameModes/Play/Osu/OsuPlayfield.cs
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Drawables; using OpenTK; namespace osu.Game.GameModes.Play.Osu { public class OsuPlayfield : Playfield { public OsuPlayfield() { SizeMode = InheritMode.None; Size = new Vector2(512, 384); Anchor = Anchor.Centre; Origin = Anchor.Centre; } public override void Load() { base.Load(); Add(new Box() { Anchor = Anchor.Centre, Origin = Anchor.Centre, SizeMode = InheritMode.XY, Alpha = 0.5f }); } } }
//Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>. //Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Drawables; using OpenTK; namespace osu.Game.GameModes.Play.Osu { public class OsuPlayfield : Playfield { public OsuPlayfield() { Size = new Vector2(512, 384); Anchor = Anchor.Centre; Origin = Anchor.Centre; } public override void Load() { base.Load(); Add(new Box() { Anchor = Anchor.Centre, Origin = Anchor.Centre, SizeMode = InheritMode.XY, Size = new Vector2(1.3f, 1.3f), Alpha = 0.5f }); } } }
mit
C#
d55e27bf171e338e88c868c301a39cb163750ab8
Remove logging dependency from GitContextPackage
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.VisualStudio/GitContextPackage.cs
src/GitHub.VisualStudio/GitContextPackage.cs
using System; using System.Threading; using System.Runtime.InteropServices; using GitHub.Exports; using GitHub.Services; using Microsoft.VisualStudio.Shell; using Task = System.Threading.Tasks.Task; namespace GitHub.VisualStudio { /// <summary> /// This package creates a custom UIContext <see cref="Guids.UIContext_Git"/> that is activated when a /// repository is active in <see cref="IVSGitExt"/>. /// </summary> [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(Guids.UIContext_Git)] // this is the Git service GUID, so we load whenever it loads [ProvideAutoLoad(Guids.GitSccProviderId, PackageAutoLoadFlags.BackgroundLoad)] public class GitContextPackage : AsyncPackage { protected async override Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { if (!ExportForVisualStudioProcessAttribute.IsVisualStudioProcess()) { // Don't activate 'UIContext_Git' for non-Visual Studio process return; } var gitExt = (IVSGitExt)await GetServiceAsync(typeof(IVSGitExt)); var context = UIContext.FromUIContextGuid(new Guid(Guids.UIContext_Git)); RefreshContext(context, gitExt); gitExt.ActiveRepositoriesChanged += () => { RefreshContext(context, gitExt); }; } static void RefreshContext(UIContext context, IVSGitExt gitExt) { context.IsActive = gitExt.ActiveRepositories.Count > 0; } } }
using System; using System.Threading; using System.Runtime.InteropServices; using GitHub.Exports; using GitHub.Logging; using GitHub.Services; using Microsoft.VisualStudio.Shell; using Serilog; using Task = System.Threading.Tasks.Task; namespace GitHub.VisualStudio { /// <summary> /// This package creates a custom UIContext <see cref="Guids.UIContext_Git"/> that is activated when a /// repository is active in <see cref="IVSGitExt"/>. /// </summary> [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [Guid(Guids.UIContext_Git)] // this is the Git service GUID, so we load whenever it loads [ProvideAutoLoad(Guids.GitSccProviderId, PackageAutoLoadFlags.BackgroundLoad)] public class GitContextPackage : AsyncPackage { static readonly ILogger log = LogManager.ForContext<GitContextPackage>(); protected async override Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { if (!ExportForVisualStudioProcessAttribute.IsVisualStudioProcess()) { log.Warning("Don't activate 'UIContext_Git' for non-Visual Studio process"); return; } var gitExt = (IVSGitExt)await GetServiceAsync(typeof(IVSGitExt)); var context = UIContext.FromUIContextGuid(new Guid(Guids.UIContext_Git)); RefreshContext(context, gitExt); gitExt.ActiveRepositoriesChanged += () => { RefreshContext(context, gitExt); }; } static void RefreshContext(UIContext context, IVSGitExt gitExt) { context.IsActive = gitExt.ActiveRepositories.Count > 0; } } }
mit
C#
fbf780526721f7db4d48cf783e807829e465b874
add attachment option
elerch/SAML2,alexrster/SAML2
src/Owin.Security.Saml/SamlMetadataWriter.cs
src/Owin.Security.Saml/SamlMetadataWriter.cs
using System; using System.Threading.Tasks; using Microsoft.Owin; using SAML2.Config; using System.Text; using SAML2.Logging; using SAML2; using SAML2.Utils; namespace Owin { internal class SamlMetadataWriter { private Saml2Configuration configuration; private readonly IInternalLogger logger; public SamlMetadataWriter(Saml2Configuration configuration) { this.configuration = configuration; logger = LoggerProvider.LoggerFor(typeof(Saml2Configuration)); } internal Task WriteMetadataDocument(IOwinContext context) { var encoding = Encoding.UTF8; string encodingStr = null; try { encodingStr = context.Request.Query.Get("encoding"); if (!string.IsNullOrEmpty(encodingStr)) { encoding = Encoding.GetEncoding(encodingStr); context.Response.Headers["Content-Encoding"] = encoding.ToString(); } } catch (ArgumentException ex) { logger.ErrorFormat(ErrorMessages.UnknownEncoding, encodingStr); throw new ArgumentException(string.Format(ErrorMessages.UnknownEncoding, encodingStr), ex); } var sign = true; var param = context.Request.Query.Get("sign"); if (!string.IsNullOrEmpty(param)) { if (!bool.TryParse(param, out sign)) { throw new ArgumentException(ErrorMessages.MetadataSignQueryParameterInvalid); } } context.Response.ContentType = "text/xml"; //Saml20Constants.MetadataMimetype; - that will prompt a download var filename = context.Request.Query.Get("file"); if (!string.IsNullOrWhiteSpace(filename)) context.Response.Headers["Content-Disposition"] = string.Format("attachment; filename=\"{0}\"", filename); var metautil = new MetadataUtils(configuration, logger); return context.Response.WriteAsync(metautil.CreateMetadataDocument(encoding, sign)); } } }
using System; using System.Threading.Tasks; using Microsoft.Owin; using SAML2.Config; using System.Text; using SAML2.Logging; using SAML2; using SAML2.Utils; namespace Owin { internal class SamlMetadataWriter { private Saml2Configuration configuration; private readonly IInternalLogger logger; public SamlMetadataWriter(Saml2Configuration configuration) { this.configuration = configuration; logger = LoggerProvider.LoggerFor(typeof(Saml2Configuration)); } internal Task WriteMetadataDocument(IOwinContext context) { var encoding = Encoding.UTF8; string encodingStr = null; try { encodingStr = context.Request.Query.Get("encoding"); if (!string.IsNullOrEmpty(encodingStr)) { encoding = Encoding.GetEncoding(encodingStr); context.Response.Headers["Content-Encoding"] = encoding.ToString(); } } catch (ArgumentException ex) { logger.ErrorFormat(ErrorMessages.UnknownEncoding, encodingStr); throw new ArgumentException(string.Format(ErrorMessages.UnknownEncoding, encodingStr), ex); } var sign = true; var param = context.Request.Query.Get("sign"); if (!string.IsNullOrEmpty(param)) { if (!bool.TryParse(param, out sign)) { throw new ArgumentException(ErrorMessages.MetadataSignQueryParameterInvalid); } } context.Response.ContentType = "text/xml"; //Saml20Constants.MetadataMimetype; - that will prompt a download //context.Response.Headers["Content-Disposition"] = "attachment; filename=\"metadata.xml\""; var metautil = new MetadataUtils(configuration, logger); return context.Response.WriteAsync(metautil.CreateMetadataDocument(encoding, sign)); } } }
mpl-2.0
C#
1b264f73b4b8e0b6949097bf82dad6f177268899
Fix test settings.
github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql,github/codeql
csharp/ql/test/library-tests/csharp8/AsyncStreams.cs
csharp/ql/test/library-tests/csharp8/AsyncStreams.cs
// semmle-extractor-options: /r:System.Threading.Tasks.dll /r:System.Threading.Tasks.Extensions.dll /r:netstandard.dll /langversion:preview using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class AsyncStreams { async IAsyncEnumerable<int> Items() { yield return 1; yield return 2; await Task.Delay(1000); yield return 3; } async void F() { await foreach(var item in Items()) Console.WriteLine(item); } } namespace System { interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } namespace System.Collections.Generic { interface IAsyncEnumerable<out T> { public System.Collections.Generic.IAsyncEnumerator<T> GetAsyncEnumerator (System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } interface IAsyncEnumerator<out T> : IAsyncDisposable { T Current { get; } System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); } }
// semmle-extractor-options: /r:System.Threading.Tasks.dll /r:System.Threading.Tasks.Extensions.dll /r:netstandard.dll using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; class AsyncStreams { async IAsyncEnumerable<int> Items() { yield return 1; yield return 2; await Task.Delay(1000); yield return 3; } async void F() { await foreach(var item in Items()) Console.WriteLine(item); } } namespace System { interface IAsyncDisposable { System.Threading.Tasks.ValueTask DisposeAsync(); } } namespace System.Collections.Generic { interface IAsyncEnumerable<out T> { public System.Collections.Generic.IAsyncEnumerator<T> GetAsyncEnumerator (System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } interface IAsyncEnumerator<out T> : IAsyncDisposable { T Current { get; } System.Threading.Tasks.ValueTask<bool> MoveNextAsync(); } }
mit
C#
fd8b268873a0908977b2e5c3239c63b2b5e45644
change some tests
andremarcondesteixeira/currency
test/AndreMarcondesTeixeira/CurrencyTest.cs
test/AndreMarcondesTeixeira/CurrencyTest.cs
using System; using Xunit; namespace AndreMarcondesTeixeira { public class CurrencyTest { [Fact] public void Currency_Is_A_Value_Type_And_All_Factory_Methods_Return_New_Instances() { Assert.False(Object.ReferenceEquals(Currency.XXX, Currency.XXX)); Assert.False(Object.ReferenceEquals(Currency.GetByLetterCode("XXX"), Currency.GetByLetterCode("XXX"))); Assert.False(Object.ReferenceEquals(Currency.GetByNumericCode("999"), Currency.GetByNumericCode("999"))); } [Fact] public void Currency_Instances_Can_Be_Created_By_Three_Ways() { Assert.IsType(typeof(Currency), Currency.XXX); Assert.IsType(typeof(Currency), Currency.GetByLetterCode("XXX")); Assert.IsType(typeof(Currency), Currency.GetByNumericCode("999")); } [Fact] public void Currency_Getter_Methods_Throws_Exception_For_Nonexistent_Currencies() { Assert.Throws<ArgumentException>(() => Currency.GetByLetterCode("Nonexistent")); Assert.Throws<ArgumentException>(() => Currency.GetByNumericCode("Nonexistent")); } [Fact] public void Currency_Instances_Are_Compared_Through_Their_Whole_Set_Of_Properties() { Assert.False(Currency.XXX == Currency.XTS); Assert.True(Currency.XTS != Currency.XXX); } } }
using System; using Xunit; namespace AndreMarcondesTeixeira { public class CurrencyTest { [Fact] public void Currency_Is_A_Value_Type_And_All_Factory_Methods_Return_New_Instances() { Assert.False(Object.ReferenceEquals(Currency.XXX, Currency.XXX)); Assert.False(Object.ReferenceEquals(Currency.GetByLetterCode("XXX"), Currency.GetByLetterCode("XXX"))); Assert.False(Object.ReferenceEquals(Currency.GetByNumericCode("999"), Currency.GetByNumericCode("999"))); } [Fact] public void Currency_Instances_Can_Be_Created_By_Four_Ways() { Assert.IsType(typeof(Currency), Currency.XXX); Assert.IsType(typeof(Currency), new Currency("ZZZ", "000", 0, "Test")); Assert.IsType(typeof(Currency), Currency.GetByLetterCode("XXX")); Assert.IsType(typeof(Currency), Currency.GetByNumericCode("999")); } [Fact] public void Currency_Instances_Are_Compared_Through_Their_Whole_Set_Of_Properties() { var customCurrency = new Currency("ZZ", "000", 2, "Test"); var differentLetterCode = new Currency("ZZZ", "000", 2, "Test"); var differentNumberCode = new Currency("ZZ", "00", 2, "Test"); var differentMinorUnits = new Currency("ZZ", "000", 1, "Test"); var differentName = new Currency("ZZ", "000", 2, "Different Name"); var equivalentCurrency = new Currency("ZZ", "000", 2, "Test"); Assert.True(customCurrency != differentLetterCode); Assert.True(customCurrency != differentNumberCode); Assert.True(customCurrency != differentMinorUnits); Assert.True(customCurrency != differentName); Assert.True(customCurrency == equivalentCurrency); Assert.False(customCurrency != equivalentCurrency); Assert.False(Currency.XXX == Currency.XTS); Assert.True(Currency.XTS != Currency.XXX); } } }
mit
C#
bd2fdb26a3b1cf612ce6fc63462ce3a8742f806b
Add a sample inline data to AzureStoragePartitionKeyTest
studio-nine/Nine.Storage,yufeih/Nine.Storage
test/Server/AzureStoragePartitionKeyTest.cs
test/Server/AzureStoragePartitionKeyTest.cs
namespace Nine.Storage { using System.Diagnostics; using Xunit; public class AzureStoragePartitionKeyTest { [Theory] [InlineData("abcdefg", 32, 4, 26)] public void batch_storage_key_to_partition_key(string key, int partitionCount, int partitionKeyLength, int expectedPartition) { var partition = BatchedTableStorage<TestStorageObject>.GetPartitionKey(key, partitionCount, partitionKeyLength); Trace.WriteLine($"{ key } => { partition }"); Assert.Equal(expectedPartition, partition); } } }
namespace Nine.Storage { using System.Diagnostics; using Xunit; public class AzureStoragePartitionKeyTest { [Theory] public void batch_storage_key_to_partition_key(string key, int partitionCount, int partitionKeyLength) { var partition = BatchedTableStorage<TestStorageObject>.GetPartitionKey(key, partitionCount, partitionKeyLength); Trace.WriteLine($"{ key } => { partition }"); } } }
mit
C#
9ff6a3111dd3bab44a059ed6454a22d3bf1dce28
Remove dependency on CupCake.dll, fixes #21
Yonom/CupCake
CupCake/Host/CupCakeClient.cs
CupCake/Host/CupCakeClient.cs
using System; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Reflection; using CupCake.Core; using MuffinFramework; using PlayerIOClient; namespace CupCake.Host { /// <summary> /// Class CupCakeClient. /// Use this client to host CupCake in your own application. /// </summary> public class CupCakeClient : MuffinClient { private Connection _connection; /// <summary> /// Initializes a new instance of the <see cref="CupCakeClient"/> class. /// Automatically adds the current assembly and every assembly with the format "CupCake.*.dll". /// </summary> /// <param name="catalog">The ComposablePartCatalog array that contains zero or more items to add to the catalog.</param> public CupCakeClient(params ComposablePartCatalog[] catalog) : base(catalog) { this.AggregateCatalog.Catalogs.Add(new DirectoryCatalog(Environment.CurrentDirectory, "CupCake.*.dll")); this.PlatformLoader.EnableComplete += this.PlatformLoader_EnableComplete; } /// <summary> /// Starts CupCake and sets the connection to the given one. /// </summary> /// <param name="connection">The connection.</param> /// <exception cref="System.ArgumentNullException">connection</exception> public void Start(Connection connection) { if (connection == null) throw new ArgumentNullException("connection"); this._connection = connection; base.Start(); } /// <summary> /// Starts the client. /// Obsolete. Use the overload with Connection parameter. /// </summary> /// <exception cref="System.NotSupportedException">Please provide the connection parameter</exception> [Obsolete("Use the overload with Connection parameter.", true)] #pragma warning disable 809 public override void Start() #pragma warning restore 809 { throw new NotSupportedException("Please provide the connection parameter"); } private void PlatformLoader_EnableComplete(object sender, EventArgs e) { this.PlatformLoader.Get<ConnectionPlatform>().Connection = this._connection; } } }
using System; using System.ComponentModel.Composition.Hosting; using System.ComponentModel.Composition.Primitives; using System.Reflection; using CupCake.Core; using MuffinFramework; using PlayerIOClient; namespace CupCake.Host { /// <summary> /// Class CupCakeClient. /// Use this client to host CupCake in your own application. /// </summary> public class CupCakeClient : MuffinClient { private Connection _connection; /// <summary> /// Initializes a new instance of the <see cref="CupCakeClient"/> class. /// Automatically adds the current assembly and every assembly with the format "CupCake.*.dll". /// </summary> /// <param name="catalog">The ComposablePartCatalog array that contains zero or more items to add to the catalog.</param> public CupCakeClient(params ComposablePartCatalog[] catalog) : base(catalog) { this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly())); this.AggregateCatalog.Catalogs.Add(new DirectoryCatalog(Environment.CurrentDirectory, "CupCake.*.dll")); this.PlatformLoader.EnableComplete += this.PlatformLoader_EnableComplete; } /// <summary> /// Starts CupCake and sets the connection to the given one. /// </summary> /// <param name="connection">The connection.</param> /// <exception cref="System.ArgumentNullException">connection</exception> public void Start(Connection connection) { if (connection == null) throw new ArgumentNullException("connection"); this._connection = connection; base.Start(); } /// <summary> /// Starts the client. /// Obsolete. Use the overload with Connection parameter. /// </summary> /// <exception cref="System.NotSupportedException">Please provide the connection parameter</exception> [Obsolete("Use the overload with Connection parameter.", true)] #pragma warning disable 809 public override void Start() #pragma warning restore 809 { throw new NotSupportedException("Please provide the connection parameter"); } private void PlatformLoader_EnableComplete(object sender, EventArgs e) { this.PlatformLoader.Get<ConnectionPlatform>().Connection = this._connection; } } }
mit
C#
8e406643e21cacb81703ee62bb108b558fa7288a
set useGUILayout = false for StageEngine.
fairygui/FairyGUI-unity
Source/Scripts/Core/StageEngine.cs
Source/Scripts/Core/StageEngine.cs
using System; using UnityEngine; namespace FairyGUI { /// <summary> /// /// </summary> public class StageEngine : MonoBehaviour { public int ObjectsOnStage; public int GraphicsOnStage; public static bool beingQuit; void Start() { useGUILayout = false; } void LateUpdate() { Stage.inst.InternalUpdate(); ObjectsOnStage = Stats.ObjectCount; GraphicsOnStage = Stats.GraphicsCount; } void OnGUI() { Stage.inst.HandleGUIEvents(Event.current); } #if !UNITY_5_4_OR_NEWER void OnLevelWasLoaded() { StageCamera.CheckMainCamera(); } #endif void OnApplicationQuit() { beingQuit = true; if (Application.isEditor) UIPackage.RemoveAllPackages(true); } } }
using System; using UnityEngine; namespace FairyGUI { /// <summary> /// /// </summary> public class StageEngine : MonoBehaviour { public int ObjectsOnStage; public int GraphicsOnStage; public static bool beingQuit; void LateUpdate() { Stage.inst.InternalUpdate(); ObjectsOnStage = Stats.ObjectCount; GraphicsOnStage = Stats.GraphicsCount; } void OnGUI() { Stage.inst.HandleGUIEvents(Event.current); } #if !UNITY_5_4_OR_NEWER void OnLevelWasLoaded() { StageCamera.CheckMainCamera(); } #endif void OnApplicationQuit() { beingQuit = true; if (Application.isEditor) UIPackage.RemoveAllPackages(true); } } }
mit
C#
a39c091a9f66d48c64dbad1dc8ec8502b435e3f7
expand to container
darrenkopp/SassyStudio
SassyStudio.2012/Intellisense/CompletionContextBuilder.cs
SassyStudio.2012/Intellisense/CompletionContextBuilder.cs
using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using SassyStudio.Compiler.Parsing; using SassyStudio.Editor; namespace SassyStudio.Intellisense { interface ICompletionContextBuilder { SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document); } [Export(typeof(ICompletionContextBuilder))] class CompletionContextBuilder : ICompletionContextBuilder { public SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document) { var tree = document.Tree; var text = new SnapshotTextProvider(tree.SourceText); var position = span.GetStartPoint(tree.SourceText).Position; var current = tree.Items.FindItemContainingPosition(position); if (current != null && current is TokenItem) current = current.Parent; var path = CreateTraversalPath(current); return new SassCompletionContext(tree.SourceText, span, current, path); } static IEnumerable<ComplexItem> CreateTraversalPath(ParseItem item) { var path = new LinkedList<ComplexItem>(); if (item == null) return path; Logger.Log(string.Format("Current Type: {0}", item.GetType().Name)); var current = (item as ComplexItem) ?? item.Parent; while (current != null) { path.AddLast(current); current = current.Parent; } return path; } } }
using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using SassyStudio.Compiler.Parsing; using SassyStudio.Editor; namespace SassyStudio.Intellisense { interface ICompletionContextBuilder { SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document); } [Export(typeof(ICompletionContextBuilder))] class CompletionContextBuilder : ICompletionContextBuilder { public SassCompletionContext Create(ITrackingSpan span, SassEditorDocument document) { var tree = document.Tree; var text = new SnapshotTextProvider(tree.SourceText); var position = span.GetStartPoint(tree.SourceText).Position; var current = tree.Items.FindItemContainingPosition(position); var path = CreateTraversalPath(current); return new SassCompletionContext(tree.SourceText, span, current, path); } static IEnumerable<ComplexItem> CreateTraversalPath(ParseItem item) { var path = new LinkedList<ComplexItem>(); if (item == null) return path; Logger.Log(string.Format("Current Type: {0}", item.GetType().Name)); var current = (item as ComplexItem) ?? item.Parent; while (current != null) { path.AddLast(current); current = current.Parent; } return path; } } }
mit
C#
5b9c5d9dc67d52226980aa6f5d12d2564a63082f
remove BOM
greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d,greggman/hft-unity3d
HappyFunTimes/HFTConstants.cs
HappyFunTimes/HFTConstants.cs
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace HappyFunTimes { public class HFTConstants { public const string kExeKey = "HappyFunTimesExecutable"; }; } // namespace HappyFunTimes
/* * Copyright 2014, Gregg Tavares. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Gregg Tavares. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace HappyFunTimes { public class HFTConstants { public const string kExeKey = "HappyFunTimesExecutable"; }; } // namespace HappyFunTimes
bsd-3-clause
C#
bdf506766a8a1c3a67658005494a01b5796f3bef
Fix silent failure when using metamethods on an object without an attached state
Rohansi/Mond,Rohansi/Mond,Rohansi/Mond,SirTony/Mond,SirTony/Mond,SirTony/Mond
Mond/VirtualMachine/Object.cs
Mond/VirtualMachine/Object.cs
using System.Collections.Generic; namespace Mond.VirtualMachine { class Object { public readonly Dictionary<MondValue, MondValue> Values; public bool Locked; public MondValue Prototype; public object UserData; private MondState _dispatcherState; public MondState State { set { if (_dispatcherState == null) _dispatcherState = value; } } public Object() { Values = new Dictionary<MondValue, MondValue>(); Locked = false; Prototype = null; UserData = null; } public bool TryDispatch(string name, out MondValue result, params MondValue[] args) { MondState state = null; MondValue callable; var current = this; while (true) { if (current.Values.TryGetValue(name, out callable)) { // we need to use the state from the metamethod's object state = current._dispatcherState; break; } var currentValue = current.Prototype; if (currentValue == null || currentValue.Type != MondValueType.Object) break; current = currentValue.ObjectValue; } if (callable == null) { result = MondValue.Undefined; return false; } if (state == null) throw new MondRuntimeException("MondValue must have an attached state to use metamethods"); result = state.Call(callable, args); return true; } } }
using System.Collections.Generic; namespace Mond.VirtualMachine { class Object { public readonly Dictionary<MondValue, MondValue> Values; public bool Locked; public MondValue Prototype; public object UserData; private MondState _dispatcherState; public MondState State { set { if (_dispatcherState == null) _dispatcherState = value; } } public Object() { Values = new Dictionary<MondValue, MondValue>(); Locked = false; Prototype = null; UserData = null; } public bool TryDispatch(string name, out MondValue result, params MondValue[] args) { if (_dispatcherState == null) { result = MondValue.Undefined; return false; } MondState state = null; MondValue callable; if (!Values.TryGetValue(name, out callable)) { var current = Prototype; while (current != null && current.Type == MondValueType.Object) { if (current.ObjectValue.Values.TryGetValue(name, out callable)) { // we should use the state from the metamethod's object state = current.ObjectValue._dispatcherState; break; } current = current.Prototype; } } if (callable == null) { result = MondValue.Undefined; return false; } state = state ?? _dispatcherState; if (state == null) throw new MondRuntimeException("MondValue must have an attached state to use metamethods"); result = state.Call(callable, args); return true; } } }
mit
C#
55eca45ec45a89548fb30584ddca8c8760fa751d
check for exactly one parameter in Cmd
strotz/pustota,strotz/pustota,strotz/pustota
src/Pustota.Maven.Cmd/Program.cs
src/Pustota.Maven.Cmd/Program.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Pustota.Maven.Base.Serialization; namespace Pustota.Maven.Cmd { class Program { static void Main(string[] args) { try { if (args.Length != 1) { Console.WriteLine("Need top folder location"); return; } string topFolder = args[0]; var entryPoint = new RepositoryEntryPoint(topFolder); var serializer = new ProjectSerializer(); var loader = new ProjectTreeLoader(entryPoint, serializer, new FileSystemAccess()); var projects = loader.LoadProjects().ToList(); Console.WriteLine(projects.Count + " projects loaded"); } catch (Exception ex) { Console.WriteLine(ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Pustota.Maven.Base.Serialization; namespace Pustota.Maven.Cmd { class Program { static void Main(string[] args) { try { string topFolder = args[0]; var entryPoint = new RepositoryEntryPoint(topFolder); var serializer = new ProjectSerializer(); var loader = new ProjectTreeLoader(entryPoint, serializer, new FileSystemAccess()); var projects = loader.LoadProjects().ToList(); Console.WriteLine(projects.Count + " projects loaded"); } catch (Exception ex) { Console.WriteLine(ex); } } } }
mit
C#
12ace15c002cb46f133c877e9941d6646c5030e1
Add HomeController example code
datalust/seq-extensions-logging,datalust/seq-extensions-logging,datalust/seq-extensions-logging
example/WebApplication/Controllers/HomeController.cs
example/WebApplication/Controllers/HomeController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace WebApplication.Controllers { public class HomeController : Controller { readonly ILogger<HomeController> _log; public HomeController(ILogger<HomeController> log) { _log = log; } public IActionResult Index() { _log.LogInformation("Hello, world!"); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace WebApplication.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Error() { return View(); } } }
apache-2.0
C#
fdfe00a793507551ce4a2eecc222a0ce62768b8c
Fix some comments.
Yttrmin/CSharpTo2600,Yttrmin/CSharpTo2600,Yttrmin/CSharpTo2600
VCSCompilerCLI/Program.cs
VCSCompilerCLI/Program.cs
#nullable enable using System; using System.Linq; using System.Text; using VCSCompiler.V2; namespace VCSCompilerCLI { class Program { /// <summary> /// A compiler that compiles C# source code into a VCS (Atari 2600) binary. /// </summary> /// <param name="arguments">A list of C# source files to compile.</param> /// <param name="outputPath">The path to save the compiled binary to. The same path with a different extension will be used for related files. /// If a path is not provided, no files will be saved.</param> /// <param name="emulatorPath">Path of the emulator executable. /// If provided, it will be launched with the path to the output binary passed as an argument.</param> /// <param name="textEditorPath">Path of the text editor executable. /// If provided, it will be launched with the path to the output ASM file passed as an argument.</param> /// <param name="disableOptimizations">True to disable optimizations. Main use is to observe output of primitive /// VIL macros and stack operations. Unoptimized code generally will not run correctly due to excessive cycles consumed.</param> /// <param name="sourceAnnotations">Whether to include C#, CIL, neither, or both source lines as comments /// above the VIL macros that they were compiled to.</param> static int Main( string[] arguments, string? outputPath = null, string? emulatorPath = null, string? textEditorPath = null, bool disableOptimizations = false, SourceAnnotation sourceAnnotations = SourceAnnotation.CSharp ) { var options = new CompilerOptions { OutputPath = outputPath, EmulatorPath = emulatorPath, TextEditorPath = textEditorPath, DisableOptimizations = disableOptimizations, SourceAnnotations = sourceAnnotations }; var file = arguments.SingleOrDefault() ?? throw new ArgumentException("Missing file"); var result = Compiler.CompileFromFile(file, options); var builder = new StringBuilder(); builder.AppendLine($" {nameof(RomInfo.IsSuccessful)}: {result.IsSuccessful}"); builder.AppendLine($" {nameof(RomInfo.RomPath)}: {result.RomPath}"); builder.AppendLine($" {nameof(RomInfo.ListPath)}: {result.ListPath}"); builder.AppendLine($" {nameof(RomInfo.AssemblyPath)}: {result.AssemblyPath}"); Console.WriteLine("Result:"); Console.WriteLine(builder.ToString()); return result.IsSuccessful ? 0 : 1; } } }
#nullable enable using System; using System.Linq; using System.Text; using VCSCompiler.V2; namespace VCSCompilerCLI { class Program { /// <summary> /// /// </summary> /// /// <param name="arguments">A list of C# source files to compile.</param> /// <param name="outputPath">The path to save the compiled binary to. The same path with a different extension will be used for related files. /// If a path is not provided, no files will be saved.</param> /// <param name="frameworkPath">The path to the VCSFramework DLL to compile against. /// Defaults to looking in the same directory as this EXE.</param> /// <param name="emulatorPath">Path of the emulator executable. /// If provided, it will be launched with the path to the output binary passed as an argument.</param> /// <param name="textEditorPath">Path of the text edit executable. /// If provided, it will be launched with the path to the output ASM file passed as an argument.</param> /// <param name="sourceAnnotations">Whether to include C#, CIL, neither, or both source lines as comments /// above the macros that they were compiled to.</param> /// <param name="disableOptimizations">True to disable optimizations. Main use is to observe output of primitive /// VIL macros and stack operations. Unoptimized code generally will not run correctly due to excessive cycles consumed.</param> static int Main( string[] arguments, string? outputPath = null, string? emulatorPath = null, string? textEditorPath = null, bool disableOptimizations = false, SourceAnnotation sourceAnnotations = SourceAnnotation.CSharp ) { var options = new CompilerOptions { OutputPath = outputPath, EmulatorPath = emulatorPath, TextEditorPath = textEditorPath, DisableOptimizations = disableOptimizations, SourceAnnotations = sourceAnnotations }; var file = arguments.SingleOrDefault() ?? throw new ArgumentException("Missing file"); var result = Compiler.CompileFromFile(file, options); var builder = new StringBuilder(); builder.AppendLine($" {nameof(RomInfo.IsSuccessful)}: {result.IsSuccessful}"); builder.AppendLine($" {nameof(RomInfo.RomPath)}: {result.RomPath}"); builder.AppendLine($" {nameof(RomInfo.ListPath)}: {result.ListPath}"); builder.AppendLine($" {nameof(RomInfo.AssemblyPath)}: {result.AssemblyPath}"); Console.WriteLine("Result:"); Console.WriteLine(builder.ToString()); return result.IsSuccessful ? 0 : 1; } } }
mit
C#
d46375c3445722847cbca50006616368666296fb
Clean up BranchName
michael-reichenauer/GitMind
GitMind/Git/BranchName.cs
GitMind/Git/BranchName.cs
using System; using GitMind.Utils; namespace GitMind.Git { /// <summary> /// Branch name type, which handles branch names as case insensitive strings. /// </summary> public class BranchName : Equatable<BranchName>, IComparable { public static BranchName Master = new BranchName("master"); public static BranchName OriginHead = new BranchName("origin/HEAD"); public static BranchName Head = new BranchName("HEAD"); private readonly string name; private readonly string caseInsensitiveName; private readonly int hashCode; public BranchName(string name) { this.name = name; caseInsensitiveName = name?.ToLower(); hashCode = caseInsensitiveName?.GetHashCode() ?? 0; } protected override int GetHash() => hashCode; protected override bool IsEqual(BranchName other) => caseInsensitiveName == other.caseInsensitiveName; public bool IsEqual(string other) => 0 == string.Compare(caseInsensitiveName, other, StringComparison.OrdinalIgnoreCase); public bool StartsWith(string prefix) => caseInsensitiveName?.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) ?? false; public BranchName Substring(int startIndex) => new BranchName(name.Substring(startIndex)); public static implicit operator string(BranchName branchName) => branchName?.name; public static implicit operator BranchName(string branchName) => branchName != null ? new BranchName(branchName) : null; public int CompareTo(object obj) { if (obj == null) return 1; BranchName other = obj as BranchName; if (other != null) { return string.Compare( caseInsensitiveName, other.caseInsensitiveName, StringComparison.Ordinal); } else { throw new ArgumentException("Object is not a BranchName"); } } public override string ToString() => name; } }
using System; using GitMind.Utils; namespace GitMind.Git { public class BranchName : Equatable<BranchName>, IComparable { private readonly string name; private readonly string id; private readonly int hashCode; public static BranchName Master = new BranchName("master"); public static BranchName OriginHead = new BranchName("origin/HEAD"); public static BranchName Head = new BranchName("HEAD"); public BranchName(string name) { this.name = name; id = name.ToLower(); hashCode = id.GetHashCode(); } protected override int GetHash() => hashCode; protected override bool IsEqual(BranchName other) => id == other.id; public bool IsEqual(string other) => 0 == string.Compare(id, other, StringComparison.OrdinalIgnoreCase); public bool StartsWith(string prefix) => id.StartsWith(prefix, StringComparison.OrdinalIgnoreCase); public BranchName Substring(int length) => new BranchName(name.Substring(length)); public static implicit operator string(BranchName branchName) => branchName?.name; public static implicit operator BranchName(string branchName) => branchName != null ? new BranchName(branchName) : null; public int CompareTo(object obj) { if (obj == null) return 1; BranchName otherTemperature = obj as BranchName; if (otherTemperature != null) { return string.Compare(id, otherTemperature.id, StringComparison.Ordinal); } else { throw new ArgumentException("Object is not a BranchName"); } } public override string ToString() => name; } }
mit
C#
674539c8422d0327f2b91ce97649a0f672cd99ca
Split IService into smaller interfaces
ahanusa/Peasy.NET,ahanusa/facile.net,peasy/Peasy.NET
Peasy/IService.cs
Peasy/IService.cs
using System.Collections.Generic; namespace Peasy { public interface IService<T, TKey> : ISupportGetAllCommand<T>, ISupportGetByIDCommand<T, TKey>, ISupportInsertCommand<T>, ISupportUpdateCommand<T>, ISupportDeleteCommand<TKey> { } public interface ISupportGetAllCommand<T> { ICommand<IEnumerable<T>> GetAllCommand(); } public interface ISupportGetByIDCommand<T, TKey> { ICommand<T> GetByIDCommand(TKey id); } public interface ISupportInsertCommand<T> { ICommand<T> InsertCommand(T entity); } public interface ISupportUpdateCommand<T> { ICommand<T> UpdateCommand(T entity); } public interface ISupportDeleteCommand<TKey> { ICommand DeleteCommand(TKey id); } }
using System.Collections.Generic; namespace Peasy { public interface IService<T, TKey> { ICommand<IEnumerable<T>> GetAllCommand(); ICommand<T> GetByIDCommand(TKey id); ICommand<T> InsertCommand(T entity); ICommand<T> UpdateCommand(T entity); ICommand DeleteCommand(TKey id); } }
mit
C#
05b6d44a8803f68cee66770efe65d3f578631fde
Remove LogLevel.Verbose, change missing library logging to Error
peppy/osu-framework,peppy/osu-framework,Tom94/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,Tom94/osu-framework,DrabWeb/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework
osu.Framework/Platform/Linux/Native/Library.cs
osu.Framework/Platform/Linux/Native/Library.cs
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; using osu.Framework.Logging; namespace osu.Framework.Platform.Linux.Native { public static class Library { [Flags] public enum Flags { RTLD_LAZY = 0x00001, RTLD_NOW = 0x00002, RTLD_BINDING_MASK = 0x00003, RTLD_NOLOAD = 0x00004, RTLD_DEEPBIND = 0x00008, RTLD_GLOBAL = 0x00100, RTLD_LOCAL = 0x00000, RTLD_NODELETE = 0x01000 } [DllImport("libdl.so", EntryPoint = "dlopen")] private static extern IntPtr dlopen(string library, Flags flags); /// <summary> /// Loads a library with an enum of flags to use with dlopen. Uses <see cref="Flags"/> for the flags /// <para/>See 'man dlopen' for more information about the flags. /// <para/>See 'man ld.so' for more information about how the libraries are loaded. /// </summary> public static void Load(string library, Flags flags) => dlopen(library, flags); /// <summary> /// Check that bass and bass_fx has been loaded, log the versions. /// </summary> public static void LogVersion(string libraryName, Func<Version> version) { try { Logger.Log(libraryName + " version = " + version(), LoggingTarget.Runtime); } catch (Exception e) { Logger.Log("Failed to load " + libraryName + ", trace: \n" + e, LoggingTarget.Runtime, LogLevel.Error); } } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using System.Runtime.InteropServices; using osu.Framework.Logging; namespace osu.Framework.Platform.Linux.Native { public static class Library { [Flags] public enum Flags { RTLD_LAZY = 0x00001, RTLD_NOW = 0x00002, RTLD_BINDING_MASK = 0x00003, RTLD_NOLOAD = 0x00004, RTLD_DEEPBIND = 0x00008, RTLD_GLOBAL = 0x00100, RTLD_LOCAL = 0x00000, RTLD_NODELETE = 0x01000 } [DllImport("libdl.so", EntryPoint = "dlopen")] private static extern IntPtr dlopen(string library, Flags flags); /// <summary> /// Loads a library with an enum of flags to use with dlopen. Uses <see cref="Flags"/> for the flags /// <para/>See 'man dlopen' for more information about the flags. /// <para/>See 'man ld.so' for more information about how the libraries are loaded. /// </summary> public static void Load(string library, Flags flags) => dlopen(library, flags); /// <summary> /// Check that bass and bass_fx has been loaded, log the versions. /// </summary> public static void LogVersion(string libraryName, Func<Version> version) { try { Logger.Log(libraryName + " version = " + version(), LoggingTarget.Runtime, LogLevel.Verbose); } catch (Exception e) { Logger.Log("Failed to load " + libraryName + ", trace: \n" + e, LoggingTarget.Runtime, LogLevel.Important); } } } }
mit
C#
525958e122875c96ed4c88f8c538acac36a9734d
Add missing error code
henrik1235/Kugelmatik,henrik1235/Kugelmatik,henrik1235/Kugelmatik
KugelmatikLibrary/ErrorCode.cs
KugelmatikLibrary/ErrorCode.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KugelmatikLibrary { public enum ErrorCode { None = 0, TooShort = 1, InvalidX = 2, InvalidY = 3, InvalidMagic = 4, BufferOverflow = 5, UnkownPacket = 6, NotRunningBusy = 7, InvalidConfigValue = 8, InvalidHeight = 9, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KugelmatikLibrary { public enum ErrorCode { None = 0, TooShort = 1, InvalidX = 2, InvalidY = 3, InvalidMagic = 4, BufferOverflow = 5, UnkownPacket = 6, NotRunningBusy = 7, InvalidConfigValue = 8, } }
mit
C#
d211472e706e1dc1c409a61acd3f38c364359578
Fix RTVS e-mail address
karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,karthiknadig/RTVS,AlexanderSher/RTVS,karthiknadig/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,MikhailArkhipov/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,AlexanderSher/RTVS,MikhailArkhipov/RTVS,karthiknadig/RTVS
src/Package/Impl/Feedback/SendMailCommand.cs
src/Package/Impl/Feedback/SendMailCommand.cs
using System; using System.Diagnostics; using System.Globalization; using System.IO; using Microsoft.Office.Interop.Outlook; using Microsoft.VisualStudio.R.Package.Commands; namespace Microsoft.VisualStudio.R.Package.Feedback { internal class SendMailCommand : PackageCommand { public SendMailCommand(Guid group, int id) : base(group, id) { } protected static void SendMail(string body, string subject, string attachmentFile) { Application outlookApp = null; try { outlookApp = new Application(); } catch (System.Exception) { } if (outlookApp == null) { if (attachmentFile != null) { body = @"Please attach RTVSLogs.zip file that can be found in your user TEMP folder and briefly describe what you were doing that led to the issue if applicable. Please be aware that the data contained in the attached logs contain your command history as well as all output displayed in the R Interactive Window"; } ProcessStartInfo psi = new ProcessStartInfo(); psi.UseShellExecute = true; psi.FileName = string.Format(CultureInfo.InvariantCulture, "mailto://rtvsuserfeedback@microsoft.com?subject={0}&body={1}", subject, body); Process.Start(psi); if (attachmentFile != null) { Process.Start(Path.GetTempPath()); } } else { MailItem mail = outlookApp.CreateItem(OlItemType.olMailItem) as MailItem; mail.Subject = subject; mail.Body = body; AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry; if (currentUser.Type == "EX") { mail.To = "rtvsuserfeedback@microsoft.com"; mail.Recipients.ResolveAll(); if (!string.IsNullOrEmpty(attachmentFile)) { mail.Attachments.Add(attachmentFile, OlAttachmentType.olByValue); } mail.Display(Modal: false); } } } } }
using System; using System.Diagnostics; using System.Globalization; using System.IO; using Microsoft.Office.Interop.Outlook; using Microsoft.VisualStudio.R.Package.Commands; namespace Microsoft.VisualStudio.R.Package.Feedback { internal class SendMailCommand : PackageCommand { public SendMailCommand(Guid group, int id) : base(group, id) { } protected static void SendMail(string body, string subject, string attachmentFile) { Application outlookApp = null; try { outlookApp = new Application(); } catch (System.Exception) { } if (outlookApp == null) { if (attachmentFile != null) { body = @"Please attach RTVSLogs.zip file that can be found in your user TEMP folder and briefly describe what you were doing that led to the issue if applicable. Please be aware that the data contained in the attached logs contain your command history as well as all output displayed in the R Interactive Window"; } ProcessStartInfo psi = new ProcessStartInfo(); psi.UseShellExecute = true; psi.FileName = string.Format(CultureInfo.InvariantCulture, "mailto://rtvsuserfeedback@microsoft.com?subject={0}&body={1}", subject, body); Process.Start(psi); if (attachmentFile != null) { Process.Start(Path.GetTempPath()); } } else { MailItem mail = outlookApp.CreateItem(OlItemType.olMailItem) as MailItem; mail.Subject = subject; mail.Body = body; AddressEntry currentUser = outlookApp.Session.CurrentUser.AddressEntry; if (currentUser.Type == "EX") { mail.To = "rtvsuserfeedback"; mail.Recipients.ResolveAll(); if (!string.IsNullOrEmpty(attachmentFile)) { mail.Attachments.Add(attachmentFile, OlAttachmentType.olByValue); } mail.Display(Modal: false); } } } } }
mit
C#
d5d0423b0ab587cb67253812a9355c85361096e4
Add comments to StandardMemberRenamer
lunet-io/scriban,textamina/scriban
src/Scriban/Runtime/StandardMemberRenamer.cs
src/Scriban/Runtime/StandardMemberRenamer.cs
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System.Text; namespace Scriban.Runtime { /// <summary> /// The standard rename make a camel/pascalcase name changed by `_` and lowercase. e.g `ThisIsAnExample` becomes `this_is_an_example`. /// </summary> public sealed class StandardMemberRenamer { public static readonly MemberRenamerDelegate Default = Rename; /// <summary> /// Renames a camel/pascalcase member to a lowercase and `_` name. e.g `ThisIsAnExample` becomes `this_is_an_example`. /// </summary> /// <param name="member">The member name to rename</param> /// <returns>The member name renamed</returns> public static string Rename(string member) { var builder = new StringBuilder(); bool previousUpper = false; for (int i = 0; i < member.Length; i++) { var c = member[i]; if (char.IsUpper(c)) { if (i > 0 && !previousUpper) { builder.Append("_"); } builder.Append(char.ToLowerInvariant(c)); previousUpper = true; } else { builder.Append(c); previousUpper = false; } } return builder.ToString(); } } }
// Copyright (c) Alexandre Mutel. All rights reserved. // Licensed under the BSD-Clause 2 license. // See license.txt file in the project root for full license information. using System.Text; namespace Scriban.Runtime { public sealed class StandardMemberRenamer { public static readonly MemberRenamerDelegate Default = Rename; public static string Rename(string member) { var builder = new StringBuilder(); bool previousUpper = false; for (int i = 0; i < member.Length; i++) { var c = member[i]; if (char.IsUpper(c)) { if (i > 0 && !previousUpper) { builder.Append("_"); } builder.Append(char.ToLowerInvariant(c)); previousUpper = true; } else { builder.Append(c); previousUpper = false; } } return builder.ToString(); } } }
bsd-2-clause
C#
6c4c02289c236a5a9eab38e602eff164530f93dd
Create doc store or embedded doc
half-ogre/qed,Haacked/qed
qed/Functions/CreateRavenStore.cs
qed/Functions/CreateRavenStore.cs
using Raven.Client; using Raven.Client.Document; using Raven.Client.Embedded; using fn = qed.Functions; namespace qed { public static partial class Functions { public static IDocumentStore GetRavenStore() { var ravenStore = GetConfiguration<IDocumentStore>(Constants.Configuration.RavenStoreKey); if (ravenStore != null) return ravenStore; if (string.IsNullOrEmpty(GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey))) ravenStore = new EmbeddableDocumentStore { DataDirectory = GetConfiguration<string>(Constants.Configuration.RavenDataDirectoryKey) }; else ravenStore = new DocumentStore { Url = GetConfiguration<string>(Constants.Configuration.RavenConnectionStringKey) }; ravenStore.Initialize(); SetConfiguration(Constants.Configuration.RavenStoreKey, ravenStore); return ravenStore; } } }
using Raven.Client; using Raven.Client.Embedded; using fn = qed.Functions; namespace qed { public static partial class Functions { public static IDocumentStore GetRavenStore() { var ravenStore = GetConfiguration<IDocumentStore>(Constants.Configuration.RavenStoreKey); if (ravenStore != null) return ravenStore; ravenStore = new EmbeddableDocumentStore { DataDirectory = GetConfiguration<string>(Constants.Configuration.RavenDataDirectoryKey) }; ravenStore.Initialize(); SetConfiguration(Constants.Configuration.RavenStoreKey, ravenStore); return ravenStore; } } }
mit
C#
f643faf56958f18cafe659f585a69bd3594eb442
Fix issue #9
themehrdad/NetTelebot,vertigra/NetTelebot-2.0
NetTelebot/ForceReplyMarkup.cs
NetTelebot/ForceReplyMarkup.cs
using System.Text; namespace NetTelebot { /// <summary> /// Upon receiving a message with this object, Telegram clients will display a reply interface to the user /// (act as if the user has selected the bot‘s message and tapped ’Reply'). /// </summary> public class ForceReplyMarkup : IReplyMarkup { public ForceReplyMarkup() { ForceReply = true; } /// <summary> /// Shows reply interface to the user, as if they manually selected the bot‘s message and tapped ’Reply' /// </summary> public bool ForceReply { get; private set; } /// <summary> /// Optional. Use this parameter if you want to force reply from specific users only. /// Targets: /// 1) users that are @mentioned in the text of the Message object; /// 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. /// </summary> public bool? Selective { get; set; } public string GetJson() { StringBuilder builder = new StringBuilder(); builder.Append("{ \"force_reply\" : true "); if (Selective.HasValue) { builder.AppendFormat(", \"selective\" : {0} ", Selective.Value.ToString().ToLower()); } builder.Append("}"); return builder.ToString(); } } }
using System.Text; namespace NetTelebot { /// <summary> /// Upon receiving a message with this object, Telegram clients will display a reply interface to the user (act as if the user has selected the bot‘s message and tapped ’Reply'). /// </summary> public class ForceReplyMarkup : IReplyMarkup { public ForceReplyMarkup() { ForceReply = true; } /// <summary> /// Shows reply interface to the user, as if they manually selected the bot‘s message and tapped ’Reply' /// </summary> public bool ForceReply { get; private set; } /// <summary> /// Optional. Use this parameter if you want to force reply from specific users only. Targets: 1) users that are @mentioned in the text of the Message object; 2) if the bot's message is a reply (has reply_to_message_id), sender of the original message. /// </summary> public bool? Selective { get; set; } public string GetJson() { StringBuilder builder = new StringBuilder(); builder.Append("{ \"force_reply\" : true "); if (Selective.HasValue) { builder.AppendFormat(", \"selective\" : {0} ", Selective.Value.ToString().ToLower()); } builder.Append("}"); return builder.ToString(); } } }
mit
C#
7925750e5a58575e77e825d3ef33711e2a2733d7
Extend NetworkingProxy to support listener socket endpoints besides "any".
the-dargon-project/ItzWarty.Proxies.Api,ItzWarty/ItzWarty.Proxies.Api
Networking/INetworkingProxy.cs
Networking/INetworkingProxy.cs
using System.IO; using System.Net.Sockets; namespace ItzWarty.Networking { public interface INetworkingProxy { IConnectedSocket CreateConnectedSocket(string host, int port); IConnectedSocket CreateConnectedSocket(ITcpEndPoint endpoint); IListenerSocket CreateListenerSocket(int port); IListenerSocket CreateListenerSocket(ITcpEndPoint endpoint); IConnectedSocket Accept(IListenerSocket listenerSocket); NetworkStream CreateNetworkStream(IConnectedSocket connectedSocket, bool ownsSocket = true); ITcpEndPoint CreateLoopbackEndPoint(int port); ITcpEndPoint CreateAnyEndPoint(int port); ITcpEndPoint CreateEndPoint(string host, int port); } }
using System.IO; using System.Net.Sockets; namespace ItzWarty.Networking { public interface INetworkingProxy { IConnectedSocket CreateConnectedSocket(string host, int port); IConnectedSocket CreateConnectedSocket(ITcpEndPoint endpoint); IListenerSocket CreateListenerSocket(int port); IConnectedSocket Accept(IListenerSocket listenerSocket); NetworkStream CreateNetworkStream(IConnectedSocket connectedSocket, bool ownsSocket = true); ITcpEndPoint CreateLoopbackEndPoint(int port); ITcpEndPoint CreateEndPoint(string host, int port); } }
bsd-2-clause
C#
e14672eac4f80683aaa1255a0e5eb8c75320bd20
Print ffplay output to the console in debug builds
o11c/WebMConverter,Yuisbean/WebMConverter,nixxquality/WebMConverter
Components/FFplay.cs
Components/FFplay.cs
using System; using System.Diagnostics; using System.IO; namespace WebMConverter { class FFplay : Process { public string FFplayPath = Path.Combine(Environment.CurrentDirectory, "Binaries", "Win32", "ffplay.exe"); public FFplay(string argument) { this.StartInfo.FileName = FFplayPath; this.StartInfo.Arguments = argument; this.StartInfo.RedirectStandardInput = true; this.StartInfo.RedirectStandardOutput = true; this.StartInfo.RedirectStandardError = true; this.StartInfo.UseShellExecute = false; //Required to redirect IO streams this.StartInfo.CreateNoWindow = true; //Hide console this.EnableRaisingEvents = true; #if DEBUG OutputDataReceived += (sender, args) => Console.WriteLine(args.Data); ErrorDataReceived += (sender, args) => Console.WriteLine(args.Data); #endif } new public void Start() { base.Start(); this.BeginErrorReadLine(); this.BeginOutputReadLine(); } } }
using System; using System.Diagnostics; using System.IO; namespace WebMConverter { class FFplay : Process { public string FFplayPath = Path.Combine(Environment.CurrentDirectory, "Binaries", "Win32", "ffplay.exe"); public FFplay(string argument) { this.StartInfo.FileName = FFplayPath; this.StartInfo.Arguments = argument; this.StartInfo.RedirectStandardInput = true; this.StartInfo.RedirectStandardOutput = true; this.StartInfo.RedirectStandardError = true; this.StartInfo.UseShellExecute = false; //Required to redirect IO streams this.StartInfo.CreateNoWindow = true; //Hide console this.EnableRaisingEvents = true; } new public void Start() { base.Start(); this.BeginErrorReadLine(); this.BeginOutputReadLine(); } } }
mit
C#
04452ef8bd08fb5075845f17477ca34c2fdc629f
Format xmldoc comments
github/VisualStudio,github/VisualStudio,github/VisualStudio
src/GitHub.Exports/Services/ITeamExplorerContext.cs
src/GitHub.Exports/Services/ITeamExplorerContext.cs
using System; using System.ComponentModel; using GitHub.Models; namespace GitHub.Services { /// <summary> /// Responsible for watching the active repository in Team Explorer. /// </summary> /// <remarks> /// A <see cref="PropertyChanged"/> event is fired when moving to a new repository. /// A <see cref="StatusChanged"/> event is fired when the CurrentBranch or HeadSha changes. /// </remarks> public interface ITeamExplorerContext : INotifyPropertyChanged { /// <summary> /// The active Git repository in Team Explorer. /// This will be null if no repository is active. /// </summary> ILocalRepositoryModel ActiveRepository { get; } /// <summary> /// Fired when the CurrentBranch or HeadSha changes. /// </summary> event EventHandler StatusChanged; } }
using System; using System.ComponentModel; using GitHub.Models; namespace GitHub.Services { /// <summary> /// Responsible for watching the active repository in Team Explorer. /// A PropertyChanged event is fired when moving to a new repository. /// A StatusChanged event is fired when the CurrentBranch or HeadSha changes. /// </summary> public interface ITeamExplorerContext : INotifyPropertyChanged { /// <summary> /// The active Git repository in Team Explorer. /// This will be null if no repository is active. /// </summary> ILocalRepositoryModel ActiveRepository { get; } /// <summary> /// Fired when the CurrentBranch or HeadSha changes. /// </summary> event EventHandler StatusChanged; } }
mit
C#
11a5927f6bcd926a5314dae3644f1d9927a68a3e
Update IBotCardsFarmerInfo.cs
JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm,JustArchi/ArchiSteamFarm
ArchiSteamFarm/Plugins/IBotCardsFarmerInfo.cs
ArchiSteamFarm/Plugins/IBotCardsFarmerInfo.cs
// _ _ _ ____ _ _____ // / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ // / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ // / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | // /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| // | // Copyright 2015-2019 Łukasz "JustArchi" Domeradzki // Contact: JustArchi@JustArchi.net // | // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // | // http://www.apache.org/licenses/LICENSE-2.0 // | // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using JetBrains.Annotations; namespace ArchiSteamFarm.Plugins { [PublicAPI] public interface IBotCardsFarmerInfo : IPlugin { /// <summary> /// ASF will call this method when cards farming module is finished on given bot instance. This method will also be called when there is nothing to idle or idling is unavailable, you can use provided boolean value for determining that. /// </summary> /// <param name="bot">Bot object related to this callback.</param> /// <param name="farmedSomething">Bool value indicating whether the module has finished successfully, so when there was at least one card to drop, and nothing has interrupted us in the meantime.</param> void OnBotFarmingFinished(Bot bot, bool farmedSomething); /// <summary> /// ASF will call this method when cards farming module is started on given bot instance. The module is started only when there are valid cards to drop, so this method won't be called when there is nothing to idle. /// </summary> /// <param name="bot">Bot object related to this callback.</param> void OnBotFarmingStarted(Bot bot); /// <summary> /// ASF will call this method when cards farming module is stopped on given bot instance. The stop could be a result of a natural finish, or other situations (e.g. Steam networking issues, user commands). /// </summary> /// <param name="bot">Bot object related to this callback.</param> void OnBotFarmingStopped(Bot bot); } }
// _ _ _ ____ _ _____ // / \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___ // / _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \ // / ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | | // /_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_| // | // Copyright 2015-2019 Łukasz "JustArchi" Domeradzki // Contact: JustArchi@JustArchi.net // | // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // | // http://www.apache.org/licenses/LICENSE-2.0 // | // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using JetBrains.Annotations; namespace ArchiSteamFarm.Plugins { [PublicAPI] public interface IBotCardsFarmerInfo : IPlugin { /// <summary> /// ASF will call this method when cards farming module is finished on given bot instance. This method will also be called when there is nothing to idle or idling is unavailable, you can use provided boolean value for determining that. /// </summary> /// <param name="bot">Bot object related to this callback.</param> /// <param name="farmedSomething">Bool value indicating whether the module has confirmed to drop at least one card during the process.</param> void OnBotFarmingFinished(Bot bot, bool farmedSomething); /// <summary> /// ASF will call this method when cards farming module is started on given bot instance. The module is started only when there are valid cards to drop, so this method won't be called when there is nothing to idle. /// </summary> /// <param name="bot">Bot object related to this callback.</param> void OnBotFarmingStarted(Bot bot); /// <summary> /// ASF will call this method when cards farming module is stopped on given bot instance. The stop could be a result of a natural finish, or other situations (e.g. Steam networking issues, user commands). /// </summary> /// <param name="bot">Bot object related to this callback.</param> void OnBotFarmingStopped(Bot bot); } }
apache-2.0
C#
6d396400f8cfa0f79a6b51ff2ff4ab0ed94d3b40
create help attribute
mykeels/CommandLineParser
CommandLineParser/Attributes/HelpAttribute.cs
CommandLineParser/Attributes/HelpAttribute.cs
using System; namespace CommandLineParser.Attributes { [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, Inherited = false, AllowMultiple = false)] public sealed class HelpAttribute : Attribute { private readonly string usageText; public HelpAttribute(string usageText) { this.usageText = usageText; } public string Usage { get { return usageText; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CommandLineParser.Attributes { [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] public sealed class HelpAttribute : Attribute { readonly string usageText; // This is a positional argument public HelpAttribute(string usageText) { this.usageText = usageText; } public string Usage { get { return usageText; } } } }
mit
C#
9ed9888f86e1806309d253bdac1e334207a0516f
Update DiseaseTest (#9639)
space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14,space-wizards/space-station-14
Content.IntegrationTests/Tests/DiseaseTest.cs
Content.IntegrationTests/Tests/DiseaseTest.cs
using System.Threading.Tasks; using Content.Shared.Disease; using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests; [TestFixture] public sealed class DiseaseTest { /// <summary> /// Asserts that a disease prototype has valid stages for its effects and cures. /// </summary> [Test] public async Task Stages() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency<IPrototypeManager>(); await server.WaitAssertion(() => { foreach (var proto in protoManager.EnumeratePrototypes<DiseasePrototype>()) { var stagesLength = proto.Stages.Count; foreach (var effect in proto.Effects) { for (var i = 0; i < effect.Stages.Length; i++) { Assert.That(i >= 0 && i < stagesLength, $"Disease {proto.ID} has an effect with an incorrect stage, {i}!"); } } foreach (var cure in proto.Cures) { for (var i = 0; i < cure.Stages.Length; i++) { Assert.That(i >= 0 && i < stagesLength, $"Disease {proto.ID} has a cure with an incorrect stage, {i}!"); } } } }); await pairTracker.CleanReturnAsync(); } }
using System.Threading.Tasks; using Content.Shared.Disease; using NUnit.Framework; using Robust.Shared.Prototypes; namespace Content.IntegrationTests.Tests; [TestFixture] public sealed class DiseaseTest { /// <summary> /// Asserts that a disease prototype has valid stages for its effects and cures. /// </summary> [Test] public async Task Stages() { await using var pairTracker = await PoolManager.GetServerClient(new PoolSettings{NoClient = true}); var server = pairTracker.Pair.Server; var protoManager = server.ResolveDependency<IPrototypeManager>(); await server.WaitAssertion(() => { foreach (var proto in protoManager.EnumeratePrototypes<DiseasePrototype>()) { var stages = proto.Stages; foreach (var effect in proto.Effects) { for (var i = 0; i < effect.Stages.Length; i++) { Assert.That(stages.Contains(i), $"Disease {proto.ID} has an effect with an incorrect stage, {i}!"); } } foreach (var cure in proto.Cures) { for (var i = 0; i < cure.Stages.Length; i++) { Assert.That(stages.Contains(i), $"Disease {proto.ID} has a cure with an incorrect stage, {i}!"); } } } }); await pairTracker.CleanReturnAsync(); } }
mit
C#