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 |
|---|---|---|---|---|---|---|---|---|
cfa1b2c99f2485a262c5564ec1fb432280d928b1 | Remove console write | i-e-b/SevenDigital.Messaging | src/SevenDigital.Messaging/Cooldown.cs | src/SevenDigital.Messaging/Cooldown.cs | using System;
using System.Threading;
using SignalHandling;
namespace SevenDigital.Messaging
{
public class Cooldown
{
static int calls;
public static void Activate()
{
if (Interlocked.CompareExchange(ref calls, 1, 0) == 0)
{
CrossPlatformSignalDispatch.Instance.TerminateEvent += Instance_TerminateEvent;
}
}
static void Instance_TerminateEvent(object sender, TerminateEventArgs args)
{
Console.WriteLine("Waiting for all handlers to exit");
new MessagingConfiguration().Shutdown();
Console.WriteLine("All handlers done. Exiting");
Environment.Exit(0);
}
}
}
| using System;
using System.Threading;
using SignalHandling;
namespace SevenDigital.Messaging
{
public class Cooldown
{
static int calls;
public static void Activate()
{
if (Interlocked.CompareExchange(ref calls, 1, 0) == 0)
{
Console.WriteLine("Activating cooldown capture");
CrossPlatformSignalDispatch.Instance.TerminateEvent += Instance_TerminateEvent;
}
}
static void Instance_TerminateEvent(object sender, TerminateEventArgs args)
{
Console.WriteLine("Waiting for all handlers to exit");
new MessagingConfiguration().Shutdown();
Console.WriteLine("All handlers done. Exiting");
Environment.Exit(0);
}
}
}
| bsd-3-clause | C# |
b4ceebb50a9329451ffd95b6ea2579a821d6a6fc | Update Envelope.cs | Narvalex/SimpleEmailSender,Narvalex/SimpleEmailSender | src/SimpleEmailSender.Core/Envelope.cs | src/SimpleEmailSender.Core/Envelope.cs | using System.Net.Mail;
namespace SimpleEmailSender
{
public class Envelope
{
public Envelope(
Contact from,
Contact[] to,
Contact[] carbonCopies,
Contact[] blindCarbonCopies,
Contact[] replyToList,
string subject,
string body,
bool isBodyHtml,
MailPriority priority,
Attachment[] attachments
)
{
this.From = from;
this.To = to;
this.CarbonCopies = carbonCopies;
this.BlindCarbonCopies = blindCarbonCopies;
this.ReplyToList = replyToList;
this.Subject = subject;
this.Body = body;
this.IsBodyHtml = isBodyHtml;
this.Attachments = attachments;
}
public Contact From { get; }
public Contact[] To { get; }
public Contact[] CarbonCopies { get; }
public Contact[] BlindCarbonCopies { get; }
public Contact[] ReplyToList { get; }
public string Subject { get; }
public string Body { get; }
public bool IsBodyHtml { get; }
public MailPriority Priority { get; }
public Attachment[] Attachments { get; }
}
}
| using System.Net.Mail;
namespace SimpleEmailSender
{
public class Envelope
{
public Envelope(
Contact from,
Contact[] to,
Contact[] carbonCopies,
Contact[] blindCarbonCopies,
Contact[] replyToList,
string subject,
string body,
bool isBodyHtml,
MailPriority priority)
{
this.From = from;
this.To = to;
this.CarbonCopies = carbonCopies;
this.BlindCarbonCopies = blindCarbonCopies;
this.ReplyToList = replyToList;
this.Subject = subject;
this.Body = body;
this.IsBodyHtml = isBodyHtml;
}
public Contact From { get; }
public Contact[] To { get; }
public Contact[] CarbonCopies { get; }
public Contact[] BlindCarbonCopies { get; }
public Contact[] ReplyToList { get; }
public string Subject { get; }
public string Body { get; }
public bool IsBodyHtml { get; }
public MailPriority Priority { get; }
}
}
| mit | C# |
0f414d839177d34317fb4d87d9b12332ab45a8dd | Fix unit tests. | SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,jkoritzinsky/Avalonia,akrisiun/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,wieslawsoltes/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,grokys/Perspex | src/Skia/Avalonia.Skia/SkiaPlatform.cs | src/Skia/Avalonia.Skia/SkiaPlatform.cs | // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Platform;
namespace Avalonia.Skia
{
/// <summary>
/// Skia platform initializer.
/// </summary>
public static class SkiaPlatform
{
/// <summary>
/// Initialize Skia platform.
/// </summary>
public static void Initialize(ICustomSkiaGpu customGpu = null)
{
var renderInterface = new PlatformRenderInterface(customGpu);
AvaloniaLocator.CurrentMutable
.Bind<IPlatformRenderInterface>().ToConstant(renderInterface);
}
/// <summary>
/// Default DPI.
/// </summary>
public static Vector DefaultDpi => new Vector(96.0f, 96.0f);
}
}
| // Copyright (c) The Avalonia Project. All rights reserved.
// Licensed under the MIT license. See licence.md file in the project root for full license information.
using Avalonia.Platform;
namespace Avalonia.Skia
{
/// <summary>
/// Skia platform initializer.
/// </summary>
public static class SkiaPlatform
{
/// <summary>
/// Initialize Skia platform.
/// </summary>
public static void Initialize(ICustomSkiaGpu customGpu)
{
var renderInterface = new PlatformRenderInterface(customGpu);
AvaloniaLocator.CurrentMutable
.Bind<IPlatformRenderInterface>().ToConstant(renderInterface);
}
/// <summary>
/// Default DPI.
/// </summary>
public static Vector DefaultDpi => new Vector(96.0f, 96.0f);
}
}
| mit | C# |
672f112f1db36f72794fd3194d26eb47e39b878a | fix it up a bit | tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web,tugberkugurlu/tugberk-web | src/Tugberk.Domain/StringExtensions.cs | src/Tugberk.Domain/StringExtensions.cs | using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Tugberk.Domain
{
public static class StringExtensions
{
/// <remarks>
/// Does not allow leading or trailing hypens or whitespace.
/// </remarks>
public static readonly Regex SlugRegex = new Regex(@"(^[a-z0-9])([a-z0-9_-]+)*([a-z0-9])$", RegexOptions.Compiled);
public static string ToSlug(this string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (SlugRegex.IsMatch(value))
{
return value;
}
return GenerateSlug(value);
}
/// <summary>
/// Credit for this method goes to http://stackoverflow.com/questions/2920744/url-slugify-alrogithm-in-cs and
/// https://github.com/benfoster/Fabrik.Common/blob/dev/src/Fabrik.Common/StringExtensions.cs.
/// </summary>
private static string GenerateSlug(string phrase)
{
string result = RemoveAccent(phrase).ToLowerInvariant();
result = result.Trim('-', '.');
result = result.Replace('.', '-');
result = result.Replace("#", "-sharp");
result = Regex.Replace(result, @"[^a-z0-9\s-]", string.Empty); // remove invalid characters
result = Regex.Replace(result, @"\s+", " ").Trim(); // convert multiple spaces into one space
return Regex.Replace(result, @"\s", "-"); // replace all spaces with hyphens
}
private static string RemoveAccent(string txt)
{
// broken on rc2, see: https://github.com/dotnet/corefx/issues/9158
// byte[] bytes = Encoding.GetEncoding("Cyrillic").GetBytes(txt);
byte[] bytes = Encoding.UTF8.GetBytes(txt);
return Encoding.ASCII.GetString(bytes);
}
}
}
| using System;
using System.Text;
using System.Text.RegularExpressions;
namespace Tugberk.Domain
{
public static class StringExtensions
{
/// <summary>
/// A regular expression for validating slugs.
/// Does not allow leading or trailing hypens or whitespace.
/// </summary>
public static readonly Regex SlugRegex = new Regex(@"(^[a-z0-9])([a-z0-9_-]+)*([a-z0-9])$", RegexOptions.Compiled);
/// <summary>
/// Slugifies a string
/// </summary>
/// <param name="value">The string value to slugify</param>
/// <param name="maxLength">An optional maximum length of the generated slug</param>
/// <returns>A URL safe slug representation of the input <paramref name="value"/>.</returns>
public static string ToSlug(this string value)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
if (SlugRegex.IsMatch(value))
{
return value;
}
return GenerateSlug(value);
}
/// <summary>
/// Credit for this method goes to http://stackoverflow.com/questions/2920744/url-slugify-alrogithm-in-cs and
/// https://github.com/benfoster/Fabrik.Common/blob/dev/src/Fabrik.Common/StringExtensions.cs.
/// </summary>
private static string GenerateSlug(string phrase)
{
string result = RemoveAccent(phrase).ToLowerInvariant();
result = result.Trim('-', '.');
result = result.Replace('.', '-');
result = result.Replace("#", "-sharp");
result = Regex.Replace(result, @"[^a-z0-9\s-]", string.Empty); // remove invalid characters
result = Regex.Replace(result, @"\s+", " ").Trim(); // convert multiple spaces into one space
return Regex.Replace(result, @"\s", "-"); // replace all spaces with hyphens
}
private static string RemoveAccent(string txt)
{
// broken on rc2, see: https://github.com/dotnet/corefx/issues/9158
// byte[] bytes = Encoding.GetEncoding("Cyrillic").GetBytes(txt);
byte[] bytes = Encoding.UTF8.GetBytes(txt);
return Encoding.ASCII.GetString(bytes);
}
}
}
| agpl-3.0 | C# |
6ef208bde9e86c1a1e296aebcff54274faf3d57b | Fix XLCFColorScaleConverter for indexed and theme colors | igitur/ClosedXML,ClosedXML/ClosedXML,b0bi79/ClosedXML | ClosedXML/Excel/ConditionalFormats/Save/XLCFColorScaleConverter.cs | ClosedXML/Excel/ConditionalFormats/Save/XLCFColorScaleConverter.cs | using System;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ClosedXML.Excel
{
internal class XLCFColorScaleConverter : IXLCFConverter
{
public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
{
var conditionalFormattingRule = XLCFBaseConverter.Convert(cf, priority);
var colorScale = new ColorScale();
for (Int32 i = 1; i <= cf.ContentTypes.Count; i++)
{
var type = cf.ContentTypes[i].ToOpenXml();
var val = (cf.Values.ContainsKey(i) && cf.Values[i] != null) ? cf.Values[i].Value : null;
var conditionalFormatValueObject = new ConditionalFormatValueObject { Type = type };
if (val != null)
conditionalFormatValueObject.Val = val;
colorScale.Append(conditionalFormatValueObject);
}
for (Int32 i = 1; i <= cf.Colors.Count; i++)
{
var xlColor = cf.Colors[i];
var color = new Color();
switch (xlColor.ColorType)
{
case XLColorType.Color:
color.Rgb = xlColor.Color.ToHex();
break;
case XLColorType.Theme:
color.Theme = System.Convert.ToUInt32(xlColor.ThemeColor);
break;
case XLColorType.Indexed:
color.Indexed = System.Convert.ToUInt32(xlColor.Indexed);
break;
}
colorScale.Append(color);
}
conditionalFormattingRule.Append(colorScale);
return conditionalFormattingRule;
}
}
}
| using System;
using DocumentFormat.OpenXml.Spreadsheet;
namespace ClosedXML.Excel
{
internal class XLCFColorScaleConverter : IXLCFConverter
{
public ConditionalFormattingRule Convert(IXLConditionalFormat cf, Int32 priority, XLWorkbook.SaveContext context)
{
var conditionalFormattingRule = XLCFBaseConverter.Convert(cf, priority);
var colorScale = new ColorScale();
for (Int32 i = 1; i <= cf.ContentTypes.Count; i++)
{
var type = cf.ContentTypes[i].ToOpenXml();
var val = (cf.Values.ContainsKey(i) && cf.Values[i] != null) ? cf.Values[i].Value : null;
var conditionalFormatValueObject = new ConditionalFormatValueObject { Type = type };
if (val != null)
conditionalFormatValueObject.Val = val;
colorScale.Append(conditionalFormatValueObject);
}
for (Int32 i = 1; i <= cf.Colors.Count; i++)
{
Color color = new Color { Rgb = cf.Colors[i].Color.ToHex() };
colorScale.Append(color);
}
conditionalFormattingRule.Append(colorScale);
return conditionalFormattingRule;
}
}
}
| mit | C# |
a0d47c5293a97a47a96f77e2f25d1b0fc733e564 | Increment version for new 'skip' querystring support | XeroAPI/XeroAPI.Net,MatthewSteeples/XeroAPI.Net,TDaphneB/XeroAPI.Net,jcvandan/XeroAPI.Net | source/XeroApi/Properties/AssemblyInfo.cs | source/XeroApi/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.0.9")]
[assembly: AssemblyFileVersion("1.1.0.9")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("XeroApi")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Xero")]
[assembly: AssemblyProduct("XeroApi")]
[assembly: AssemblyCopyright("Copyright © Xero 2011")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e18a84e7-ba04-4368-b4c9-0ea0cc78ddef")]
// 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.0.8")]
[assembly: AssemblyFileVersion("1.1.0.8")]
| mit | C# |
a66fe8e489568e15bd526a811186f771f12e5b31 | Fix PrinterChooserHonorsWhitelist test | unlimitedbacon/MatterControl,mmoening/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,mmoening/MatterControl,jlewin/MatterControl,jlewin/MatterControl,larsbrubaker/MatterControl,unlimitedbacon/MatterControl,mmoening/MatterControl,jlewin/MatterControl,jlewin/MatterControl,unlimitedbacon/MatterControl,larsbrubaker/MatterControl,larsbrubaker/MatterControl | Tests/MatterControl.Tests/MatterControl/PrinterChooserUnitTests.cs | Tests/MatterControl.Tests/MatterControl/PrinterChooserUnitTests.cs | using System.Collections.Generic;
using System.Linq;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.Agg.UI;
using MatterHackers.MatterControl;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.Tests.Automation;
using NUnit.Framework;
namespace MatterControl.Tests.MatterControl
{
class PrinterChooserUnitTests
{
[Test]
public void PrinterChooserHonorsWhitelist()
{
AggContext.StaticData = new FileSystemStaticData(TestContext.CurrentContext.ResolveProjectPath(4, "StaticData"));
MatterControlUtilities.OverrideAppDataLocation(TestContext.CurrentContext.ResolveProjectPath(4));
var manufacturers = new string[] { "3D Factory", "3D Stuffmaker", "Airwolf 3D", "BCN", "BeeVeryCreative", "Blue Eagle Labs", "Deezmaker", "FlashForge", "gCreate", "IRA3D", "JumpStart", "Leapfrog", "Lulzbot", "MAKEiT", "Maker's Tool Works", "MakerBot", "MakerGear", "Me3D", "OpenBeam", "Organic Thinking System", "Other", "Portabee", "Printrbot", "PrintSpace", "Revolution 3D Printers", "ROBO 3D", "SeeMeCNC", "Solidoodle", "Tosingraf", "Type A Machines", "Ultimaker", "Velleman", "Wanhao" };
var allManufacturers = manufacturers.Select(m => new KeyValuePair<string, string>(m, m)).ToList();
BoundDropList dropList;
var theme = new ThemeConfig()
{
Colors = ActiveTheme.Instance
};
// Whitelist on non-OEM builds should contain all printers
dropList = new BoundDropList("Test", theme);
dropList.ListSource = allManufacturers;
Assert.Greater(dropList.MenuItems.Count, 20);
var whitelist = new List<string> { "3D Stuffmaker" };
OemSettings.Instance.SetManufacturers(allManufacturers, whitelist);
dropList = new BoundDropList("Test", theme);
dropList.ListSource = OemSettings.Instance.AllOems;
Assert.AreEqual(1, dropList.MenuItems.Count);
whitelist.Add("Airwolf 3D");
OemSettings.Instance.SetManufacturers(allManufacturers, whitelist);
dropList = new BoundDropList("Test", theme);
dropList.ListSource = OemSettings.Instance.AllOems;
Assert.AreEqual(2, dropList.MenuItems.Count);
/*
* Disable Esagono tests
*
SetPrivatePrinterWhiteListMember(new List<string>() { "Esagono" });
var manufacturerNameMapping = new ManufacturerNameMapping();
manufacturerNameMapping.NameOnDisk = "Esagono";
manufacturerNameMapping.NameToDisplay = "Esagonò";
printChooser = new PrinterChooser();
string expectedItem = null;
foreach (var menuItem in printChooser.ManufacturerDropList.MenuItems)
{
if(menuItem.Text.StartsWith("Esa"))
{
expectedItem = menuItem.Text;
}
}
Assert.IsTrue(!string.IsNullOrEmpty(expectedItem) && expectedItem == "Esagonò");
*/
}
}
}
| using System.Collections.Generic;
using System.Linq;
using MatterHackers.Agg;
using MatterHackers.Agg.Platform;
using MatterHackers.MatterControl;
using MatterHackers.MatterControl.SettingsManagement;
using MatterHackers.MatterControl.Tests.Automation;
using NUnit.Framework;
namespace MatterControl.Tests.MatterControl
{
class PrinterChooserUnitTests
{
[Test]
public void PrinterChooserHonorsWhitelist()
{
AggContext.StaticData = new FileSystemStaticData(TestContext.CurrentContext.ResolveProjectPath(4, "StaticData"));
MatterControlUtilities.OverrideAppDataLocation(TestContext.CurrentContext.ResolveProjectPath(4));
var manufacturers = new string[] { "3D Factory", "3D Stuffmaker", "Airwolf 3D", "BCN", "BeeVeryCreative", "Blue Eagle Labs", "Deezmaker", "FlashForge", "gCreate", "IRA3D", "JumpStart", "Leapfrog", "Lulzbot", "MAKEiT", "Maker's Tool Works", "MakerBot", "MakerGear", "Me3D", "OpenBeam", "Organic Thinking System", "Other", "Portabee", "Printrbot", "PrintSpace", "Revolution 3D Printers", "ROBO 3D", "SeeMeCNC", "Solidoodle", "Tosingraf", "Type A Machines", "Ultimaker", "Velleman", "Wanhao" };
var allManufacturers = manufacturers.Select(m => new KeyValuePair<string, string>(m, m)).ToList();
BoundDropList dropList;
var theme = new ThemeConfig();
// Whitelist on non-OEM builds should contain all printers
dropList = new BoundDropList("Test", theme);
dropList.ListSource = allManufacturers;
Assert.Greater(dropList.MenuItems.Count, 20);
var whitelist = new List<string> { "3D Stuffmaker" };
OemSettings.Instance.SetManufacturers(allManufacturers, whitelist);
dropList = new BoundDropList("Test", theme);
dropList.ListSource = OemSettings.Instance.AllOems;
Assert.AreEqual(1, dropList.MenuItems.Count);
whitelist.Add("Airwolf 3D");
OemSettings.Instance.SetManufacturers(allManufacturers, whitelist);
dropList = new BoundDropList("Test", theme);
dropList.ListSource = OemSettings.Instance.AllOems;
Assert.AreEqual(2, dropList.MenuItems.Count);
/*
* Disable Esagono tests
*
SetPrivatePrinterWhiteListMember(new List<string>() { "Esagono" });
var manufacturerNameMapping = new ManufacturerNameMapping();
manufacturerNameMapping.NameOnDisk = "Esagono";
manufacturerNameMapping.NameToDisplay = "Esagonò";
printChooser = new PrinterChooser();
string expectedItem = null;
foreach (var menuItem in printChooser.ManufacturerDropList.MenuItems)
{
if(menuItem.Text.StartsWith("Esa"))
{
expectedItem = menuItem.Text;
}
}
Assert.IsTrue(!string.IsNullOrEmpty(expectedItem) && expectedItem == "Esagonò");
*/
}
}
}
| bsd-2-clause | C# |
a8ac88233788dfe9c925a60fa16082b11f367043 | make circle radius available | dev-zzo/Spritesse,dev-zzo/Spritesse | ThreeSheeps.Spritesse/Physics/PhysicalCircle.cs | ThreeSheeps.Spritesse/Physics/PhysicalCircle.cs | using Microsoft.Xna.Framework;
namespace ThreeSheeps.Spritesse.Physics
{
public sealed class PhysicalCircle : PhysicalShape
{
public new sealed class CreationInfo : PhysicalShape.CreationInfo
{
public float Radius;
}
public PhysicalCircle(ICollisionResolverService resolver, CreationInfo info)
: this(info)
{
this.resolver = resolver;
resolver.Insert(this);
}
private PhysicalCircle(CreationInfo info)
: base(info)
{
this.radius = info.Radius;
}
public override Vector2 HalfDimensions
{
get { return new Vector2(this.radius, this.radius); }
}
public float Radius
{
get { return this.radius; }
}
private float radius;
}
}
| using Microsoft.Xna.Framework;
namespace ThreeSheeps.Spritesse.Physics
{
public sealed class PhysicalCircle : PhysicalShape
{
public new sealed class CreationInfo : PhysicalShape.CreationInfo
{
public float Radius;
}
public PhysicalCircle(ICollisionResolverService resolver, CreationInfo info)
: this(info)
{
this.resolver = resolver;
resolver.Insert(this);
}
private PhysicalCircle(CreationInfo info)
: base(info)
{
this.radius = info.Radius;
}
public override Vector2 HalfDimensions
{
get { return new Vector2(this.radius, this.radius); }
}
private float radius;
}
}
| unlicense | C# |
d7ee85743e728139ba7cfbd9b40837520eb27344 | Change access of Write() to internal | turtle-box-games/leaf-csharp | Leaf/Leaf/Nodes/Node.cs | Leaf/Leaf/Nodes/Node.cs | using System.IO;
namespace Leaf.Nodes
{
/// <summary>
/// Base class for all node types.
/// </summary>
public abstract class Node
{
/// <summary>
/// Writes the data of the node to a stream.
/// </summary>
/// <param name="writer">Writer to use for putting data in the stream.</param>
internal abstract void Write(BinaryWriter writer);
}
}
| using System.IO;
namespace Leaf.Nodes
{
/// <summary>
/// Base class for all node types.
/// </summary>
public abstract class Node
{
/// <summary>
/// Writes the data of the node to a stream.
/// </summary>
/// <param name="writer">Writer to use for putting data in the stream.</param>
public abstract void Write(BinaryWriter writer);
}
}
| mit | C# |
45ea7b7a718fa6274ee0f993f2493c6a09a0e174 | Allow playing non-positioned sound & don't dispose sounds before they stop. | Zalewa/LostSoulSquasher | LostSoul/AudioSystem.cs | LostSoul/AudioSystem.cs | using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LostSoul
{
class SoundRequest
{
public SoundEffect Sound { get; set; }
public Vector2? Position { get; set; }
};
public class AudioSystem
{
private Random random = new Random();
private List<SoundRequest> soundRequests = new List<SoundRequest>();
private List<SoundEffectInstance> playingSounds = new List<SoundEffectInstance>();
public Vector2 ListenerPosition = Vector2.Zero;
public float PanDivisor = 1.0f;
public float PanClamp = 1.0f;
public AudioSystem()
{
}
public void PlaySound(SoundEffect sound)
{
var request = new SoundRequest();
request.Sound = sound;
request.Position = null;
soundRequests.Add(request);
}
public void PlaySound(SoundEffect sound, Vector2 position)
{
var request = new SoundRequest();
request.Sound = sound;
request.Position = position;
soundRequests.Add(request);
}
public void FireSounds()
{
soundRequests.ForEach(e => FireSound(e));
soundRequests.Clear();
ClearCompletedSounds();
}
private void FireSound(SoundRequest request)
{
SoundEffectInstance instance = request.Sound.CreateInstance();
if (request.Position != null)
{
Vector2 relative = (Vector2)request.Position - ListenerPosition;
instance.Pan = MathHelper.Clamp(relative.X / PanDivisor, -PanClamp, PanClamp);
}
instance.Pitch = 0.5f - (float)random.NextDouble();
instance.Play();
playingSounds.Add(instance);
}
private void ClearCompletedSounds()
{
for (int i = 0; i < playingSounds.Count; ++i)
{
if (playingSounds[i].State == SoundState.Stopped)
{
playingSounds[i].Dispose();
playingSounds.RemoveAt(i);
--i;
}
}
}
public void PlayMusic(Song song)
{
MediaPlayer.Play(song);
MediaPlayer.IsRepeating = true;
}
public void StopMusic()
{
MediaPlayer.Stop();
}
}
}
| using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Media;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LostSoul
{
class SoundRequest
{
public SoundEffect Sound { get; set; }
public Vector2 Position { get; set; }
};
public class AudioSystem
{
private Random random = new Random();
private List<SoundRequest> soundRequests = new List<SoundRequest>();
public Vector2 ListenerPosition = Vector2.Zero;
public float PanDivisor = 1.0f;
public float PanClamp = 1.0f;
public AudioSystem()
{
}
public void PlaySound(SoundEffect sound, Vector2 position)
{
var request = new SoundRequest();
request.Sound = sound;
request.Position = position;
soundRequests.Add(request);
}
public void FireSounds()
{
soundRequests.ForEach(e => FireSound(e));
soundRequests.Clear();
}
private void FireSound(SoundRequest request)
{
SoundEffectInstance instance = request.Sound.CreateInstance();
Vector2 relative = request.Position - ListenerPosition;
instance.Pan = MathHelper.Clamp(relative.X / PanDivisor, -PanClamp, PanClamp);
instance.Pitch = 0.5f - (float)random.NextDouble();
instance.Play();
}
public void PlayMusic(Song song)
{
MediaPlayer.Play(song);
MediaPlayer.IsRepeating = true;
}
public void StopMusic()
{
MediaPlayer.Stop();
}
}
}
| bsd-3-clause | C# |
1693a9458e148b5ccc8af4d7b866b61c3bf554a9 | Change accommodation ordering | ahmedmatem/vs-bgb,ahmedmatem/vs-bgb,ahmedmatem/vs-bgb | BGB.WebAPI/Controllers/AccommodationsController.cs | BGB.WebAPI/Controllers/AccommodationsController.cs | namespace BGB.WebAPI.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Data.Common.Repository;
using Models;
using ViewModels;
using System.Data.Entity;
using Data;
[RoutePrefix("api/accommodations")]
public class AccommodationsController : BaseController
{
// GET api/accommodations/id
public HttpResponseMessage Get(int id)
{
AccommodationAd result = context.AccommodationAds.Find(id);
if(result == null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, result);
}
// GET api/accommodations/all
[Route("All")]
public HttpResponseMessage GetAll()
{
var result = context.AccommodationAds
.OrderByDescending(x => x.PublishedDate)
.Select(a => a)
.ToList<AccommodationAd>();
if (result == null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, new { accommodations = result });
}
// POST api/accommodations/save
[Route("Save")]
public IHttpActionResult Post(AccViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var accomodationAd = new AccommodationAd()
{
Title = model.Title,
Author = model.Author,
Content = model.Content,
PublishedDate = DateTime.Now
};
context.AccommodationAds.Add(accomodationAd);
context.SaveChanges();
return Ok();
}
}
}
| namespace BGB.WebAPI.Controllers
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Data.Common.Repository;
using Models;
using ViewModels;
using System.Data.Entity;
using Data;
[RoutePrefix("api/accommodations")]
public class AccommodationsController : BaseController
{
// GET api/accommodations/id
public HttpResponseMessage Get(int id)
{
AccommodationAd result = context.AccommodationAds.Find(id);
if(result == null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, result);
}
// GET api/accommodations/all
[Route("All")]
public HttpResponseMessage GetAll()
{
var result = context.AccommodationAds
.OrderBy(x => x.PublishedDate)
.Select(a => a)
.ToList<AccommodationAd>();
if (result == null)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
return Request.CreateResponse(HttpStatusCode.OK, new { accommodations = result });
}
// POST api/accommodations/save
[Route("Save")]
public IHttpActionResult Post(AccViewModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var accomodationAd = new AccommodationAd()
{
Title = model.Title,
Author = model.Author,
Content = model.Content,
PublishedDate = DateTime.Now
};
context.AccommodationAds.Add(accomodationAd);
context.SaveChanges();
return Ok();
}
}
}
| mit | C# |
5bac954c2058fd33ed83b41701a78e85c651e21d | Update PrivacyAct.cshtml | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Views/Home/PrivacyAct.cshtml | Battery-Commander.Web/Views/Home/PrivacyAct.cshtml | <h1>Privacy Statement</h1>
<h2>Controlled Unclassified Information (CUI)</h2>
<p>By using this system, you have a responsibility to safeguard the information entrusted to you.</p>
<p>Be able to recognize PII and safeguard it.</p>
<p>Collect PII only when authorized.</p>
<p>Collect only necessary information.</p>
<p>Keep the PII accurate, relevant, timely and complete.</p>
<p>Keep PII confidential and protect it from misuse or loss or breach.</p>
<p>
Please view the Army's policy on Personally Identifiable Information (PII) at <a href="https://www.rmda.army.mil/privacy/PII/PII.html">https://www.rmda.army.mil/privacy/PII/PII.html</a>.
</p>
<div>
<a href="/" class="btn btn-success btn-xl">Click Here to Continue</a>
</div>
| <h1>Privacy Statement</h1>
<h2>For Official Use Only (FOUO)</h2>
<p>By using this system, you have a responsibility to safeguard the information entrusted to you.</p>
<p>Be able to recognize PII and safeguard it.</p>
<p>Collect PII only when authorized.</p>
<p>Collect only necessary information.</p>
<p>Keep the PII accurate, relevant, timely and complete.</p>
<p>Keep PII confidential and protect it from misuse or loss or breach.</p>
<p>
Please view the Army's policy on Personally Identifiable Information (PII) at <a href="https://www.rmda.army.mil/privacy/PII/PII.html">https://www.rmda.army.mil/privacy/PII/PII.html</a>.
</p>
<div>
<a href="/" class="btn btn-success btn-xl">Click Here to Continue</a>
</div> | mit | C# |
2bb269a934b4a84ef9cc3f6da9646f39aa099f09 | Update fb-usertoken grant to reuser Facebook id | ankodu/nether,navalev/nether,navalev/nether,stuartleeks/nether,stuartleeks/nether,navalev/nether,stuartleeks/nether,navalev/nether,MicrosoftDX/nether,vflorusso/nether,ankodu/nether,krist00fer/nether,stuartleeks/nether,stuartleeks/nether,vflorusso/nether,vflorusso/nether,oliviak/nether,ankodu/nether,ankodu/nether,vflorusso/nether,vflorusso/nether | src/Nether.Data/Identity/LoginProvider.cs | src/Nether.Data/Identity/LoginProvider.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nether.Data.Identity
{
public static class LoginProvider
{
public const string UserNamePassword = "password";
public const string FacebookUserAccessToken = "Facebook"; // use the same identifier as the implicit flow for facebook
}
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Nether.Data.Identity
{
public static class LoginProvider
{
public const string UserNamePassword = "password";
public const string FacebookUserAccessToken = "facebook-user-access-token";
}
}
| mit | C# |
dd864202b2a4b1a4512afa02ee50cb63f62f796a | Fix writing of shorter uints | haefele/PalmDB | src/PalmDB/Serialization/UintPalmValue.cs | src/PalmDB/Serialization/UintPalmValue.cs | using System;
using System.Threading.Tasks;
namespace PalmDB.Serialization
{
/// <summary>
/// Represents a <see cref="uint"/> value inside a palm database.
/// </summary>
internal class UIntPalmValue : IPalmValue<uint>
{
/// <summary>
/// Gets the length of this uint block.
/// </summary>
public int Length { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UIntPalmValue"/> class.
/// </summary>
/// <param name="length">The length of the uint block.</param>
public UIntPalmValue(int length)
{
Guard.NotNegative(length, nameof(length));
this.Length = length;
}
/// <summary>
/// Reads the <see cref="uint"/> using the specified <paramref name="reader"/>.
/// </summary>
/// <param name="reader">The reader.</param>
public async Task<uint> ReadValueAsync(AsyncBinaryReader reader)
{
Guard.NotNull(reader, nameof(reader));
var data = await reader.ReadAsync(this.Length);
Array.Reverse(data);
Array.Resize(ref data, 4);
return BitConverter.ToUInt32(data, 0);
}
/// <summary>
/// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="value">The value.</param>
public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value)
{
Guard.NotNull(writer, nameof(writer));
var data = BitConverter.GetBytes(value);
Array.Resize(ref data, this.Length);
Array.Reverse(data);
await writer.WriteAsync(data);
}
}
} | using System;
using System.Threading.Tasks;
namespace PalmDB.Serialization
{
/// <summary>
/// Represents a <see cref="uint"/> value inside a palm database.
/// </summary>
internal class UIntPalmValue : IPalmValue<uint>
{
/// <summary>
/// Gets the length of this uint block.
/// </summary>
public int Length { get; }
/// <summary>
/// Initializes a new instance of the <see cref="UIntPalmValue"/> class.
/// </summary>
/// <param name="length">The length of the uint block.</param>
public UIntPalmValue(int length)
{
Guard.NotNegative(length, nameof(length));
this.Length = length;
}
/// <summary>
/// Reads the <see cref="uint"/> using the specified <paramref name="reader"/>.
/// </summary>
/// <param name="reader">The reader.</param>
public async Task<uint> ReadValueAsync(AsyncBinaryReader reader)
{
Guard.NotNull(reader, nameof(reader));
var data = await reader.ReadAsync(this.Length);
Array.Reverse(data);
Array.Resize(ref data, 4);
return BitConverter.ToUInt32(data, 0);
}
/// <summary>
/// Writes the specified <paramref name="value"/> using the specified <paramref name="writer"/>.
/// </summary>
/// <param name="writer">The writer.</param>
/// <param name="value">The value.</param>
public async Task WriteValueAsync(AsyncBinaryWriter writer, uint value)
{
Guard.NotNull(writer, nameof(writer));
var data = BitConverter.GetBytes(value);
Array.Reverse(data);
Array.Resize(ref data, this.Length);
await writer.WriteAsync(data);
}
}
} | mit | C# |
b1ffd81bf6a0bc67a9c2dee87b5737ec8d391d0e | bump version | rabbit-link/rabbit-link,rabbit-link/rabbit-link | src/RabbitLink/Properties/AssemblyInfo.cs | src/RabbitLink/Properties/AssemblyInfo.cs | #region Usings
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("RabbitLink")]
[assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RabbitLink")]
[assembly: AssemblyCopyright("Copyright © Artur Kraev 2015")]
[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("b2148830-a507-44a5-bc99-efda7f36e21d")]
// 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.2.0")]
[assembly: AssemblyFileVersion("0.2.2.0")] | #region Usings
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// 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("RabbitLink")]
[assembly: AssemblyDescription("Advanced .Net API for RabbitMQ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RabbitLink")]
[assembly: AssemblyCopyright("Copyright © Artur Kraev 2015")]
[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("b2148830-a507-44a5-bc99-efda7f36e21d")]
// 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.1.0")]
[assembly: AssemblyFileVersion("0.2.1.0")] | mit | C# |
c1d2a5a8cbbb4333180986345dd34699964fe55a | add default parameters. | geffzhang/equeue,tangxuehua/equeue,Aaron-Liu/equeue,Aaron-Liu/equeue,geffzhang/equeue,tangxuehua/equeue,tangxuehua/equeue | src/EQueue/Broker/BrokerController.cs | src/EQueue/Broker/BrokerController.cs | using EQueue.Broker.LongPolling;
using EQueue.Broker.Processors;
using EQueue.Infrastructure.IoC;
using EQueue.Remoting;
namespace EQueue.Broker
{
public class BrokerController
{
private readonly IMessageService _messageService;
private readonly SocketRemotingServer _remotingServer;
public PullRequestHoldService PullRequestHoldService { get; private set; }
public BrokerController(string address = "127.0.0.1", int port = 5000, int backlog = 5000)
{
_messageService = ObjectContainer.Resolve<IMessageService>();
_remotingServer = new SocketRemotingServer(address, port, backlog);
PullRequestHoldService = new PullRequestHoldService();
}
public BrokerController Initialize()
{
_remotingServer.RegisterRequestProcessor((int)RequestCode.SendMessage, new SendMessageRequestProcessor());
_remotingServer.RegisterRequestProcessor((int)RequestCode.PullMessage, new PullMessageRequestProcessor(this));
return this;
}
public void Start()
{
_remotingServer.Start();
PullRequestHoldService.Start();
}
public void Shutdown()
{
}
}
}
| using EQueue.Broker.LongPolling;
using EQueue.Broker.Processors;
using EQueue.Infrastructure.IoC;
using EQueue.Remoting;
namespace EQueue.Broker
{
public class BrokerController
{
private readonly IMessageService _messageService;
private readonly SocketRemotingServer _remotingServer;
public PullRequestHoldService PullRequestHoldService { get; private set; }
public BrokerController()
{
_messageService = ObjectContainer.Resolve<IMessageService>();
_remotingServer = new SocketRemotingServer();
PullRequestHoldService = new PullRequestHoldService();
}
public BrokerController Initialize()
{
_remotingServer.RegisterRequestProcessor((int)RequestCode.SendMessage, new SendMessageRequestProcessor());
_remotingServer.RegisterRequestProcessor((int)RequestCode.PullMessage, new PullMessageRequestProcessor(this));
return this;
}
public void Start()
{
_remotingServer.Start();
PullRequestHoldService.Start();
}
public void Shutdown()
{
}
}
}
| mit | C# |
574fe631a40de988e988d8814b4287424873a929 | Add comment about how IDiscoverableCollection is treated | zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype | src/Glimpse.Common/GlimpseServices.cs | src/Glimpse.Common/GlimpseServices.cs | using Glimpse;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace Glimpse
{
public class GlimpseServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Discovery & Reflection.
//
yield return describe.Transient<ITypeActivator, DefaultTypeActivator>();
yield return describe.Transient<ITypeSelector, DefaultTypeSelector>();
yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>();
yield return describe.Transient<ITypeService, DefaultTypeService>();
yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>));
// TODO: consider making above singleton
//
// Messages.
//
yield return describe.Singleton<IMessageConverter, DefaultMessageConverter>();
//
// JSON.Net.
//
yield return describe.Singleton<JsonSerializer>(x => new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
}
}
} | using Glimpse;
using Microsoft.Framework.ConfigurationModel;
using Microsoft.Framework.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System.Collections.Generic;
using System;
using System.Reflection;
namespace Glimpse
{
public class GlimpseServices
{
public static IEnumerable<IServiceDescriptor> GetDefaultServices()
{
return GetDefaultServices(new Configuration());
}
public static IEnumerable<IServiceDescriptor> GetDefaultServices(IConfiguration configuration)
{
var describe = new ServiceDescriber(configuration);
//
// Discovery & Reflection.
//
yield return describe.Transient<ITypeActivator, DefaultTypeActivator>();
yield return describe.Transient<ITypeSelector, DefaultTypeSelector>();
yield return describe.Transient<IAssemblyProvider, DefaultAssemblyProvider>();
yield return describe.Transient<ITypeService, DefaultTypeService>();
yield return describe.Transient(typeof(IDiscoverableCollection<>), typeof(ReflectionDiscoverableCollection<>));
//
// Messages.
//
yield return describe.Singleton<IMessageConverter, DefaultMessageConverter>();
//
// JSON.Net.
//
yield return describe.Singleton<JsonSerializer>(x => new JsonSerializer
{
ContractResolver = new CamelCasePropertyNamesContractResolver()
});
}
}
} | mit | C# |
76dff8f0dc25fa768dd573a01865401698e6ce76 | revise functional test for min/max | kflu/kfl.utils | test/FunctionalTests.cs | test/FunctionalTests.cs | namespace test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using static Kfl.Utils.Functional.Functional;
public class FunctionalTests
{
[Xunit.Fact]
public void TestMinMax()
{
Assert.Equal(1, Min(1, 2));
Assert.Equal(2.0, Max(2.0, -1));
}
}
}
| namespace test
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using static Kfl.Utils.Functional.Functional;
public class FunctionalTests
{
[Xunit.Fact]
public void TestMinMax()
{
Func<int, int, int> min = Min<int>;
Func<double, double, double> max = Max<double>;
Assert.Equal(1, min(1, 2));
Assert.Equal(2.0, max(2.0, -1));
}
}
}
| mit | C# |
9efce73750172e0c48e9b2d7db3613b1e40b9972 | Create a temporary library file and rename it to reduce the chance of library corruption | punker76/Espera,flagbug/Espera | Espera/Espera.Core/Management/LibraryFileWriter.cs | Espera/Espera.Core/Management/LibraryFileWriter.cs | using Rareform.Validation;
using System;
using System.Collections.Generic;
using System.IO;
namespace Espera.Core.Management
{
public class LibraryFileWriter : ILibraryWriter
{
private readonly string targetPath;
public LibraryFileWriter(string targetPath)
{
if (targetPath == null)
Throw.ArgumentNullException(() => targetPath);
this.targetPath = targetPath;
}
public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath)
{
// Create a temporary file, write the library it, then delete the original library file
// and rename our new one. This ensures that there is a minimum possibility of things
// going wrong, for example if the process is killed mid-writing.
string tempFilePath = Path.Combine(Path.GetDirectoryName(this.targetPath), Guid.NewGuid().ToString());
using (FileStream targetStream = File.Create(tempFilePath))
{
LibraryWriter.Write(songs, playlists, songSourcePath, targetStream);
}
File.Delete(this.targetPath);
File.Move(tempFilePath, this.targetPath);
}
}
} | using Rareform.Validation;
using System.Collections.Generic;
using System.IO;
namespace Espera.Core.Management
{
public class LibraryFileWriter : ILibraryWriter
{
private readonly string targetPath;
public LibraryFileWriter(string targetPath)
{
if (targetPath == null)
Throw.ArgumentNullException(() => targetPath);
this.targetPath = targetPath;
}
public void Write(IEnumerable<LocalSong> songs, IEnumerable<Playlist> playlists, string songSourcePath)
{
using (FileStream targetStream = File.Create(this.targetPath))
{
LibraryWriter.Write(songs, playlists, songSourcePath, targetStream);
}
}
}
} | mit | C# |
2b8506a2bbe368fd740e2d682185175c26088df8 | Add TaskHelper.ToTask | WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common,WeihanLi/WeihanLi.Common | src/WeihanLi.Common/Helpers/TaskHelper.cs | src/WeihanLi.Common/Helpers/TaskHelper.cs | // Copyright (c) Weihan Li. All rights reserved.
// Licensed under the Apache license.
namespace WeihanLi.Common.Helpers;
public static class TaskHelper
{
#if ValueTaskSupport
/// <summary>
/// A cached completed value task
/// </summary>
public static ValueTask CompletedValueTask =>
#if NET6_0_OR_GREATER
ValueTask.CompletedTask
#else
default
#endif
;
public static ValueTask ToTask(object? object)
{
var task = object switch
{
ValueTask vt => vt,
Task t => new ValueTask(t),
_ => CompletedValueTask
};
return task;
}
#endif
}
| // Copyright (c) Weihan Li. All rights reserved.
// Licensed under the Apache license.
namespace WeihanLi.Common.Helpers;
public static class TaskHelper
{
#if ValueTaskSupport
/// <summary>
/// A cached completed value task
/// </summary>
public static ValueTask CompletedValueTask =>
#if NET6_0_OR_GREATER
ValueTask.CompletedTask
#else
default
#endif
;
#endif
}
| mit | C# |
da011a4a7a6456eb380be3b0db0e80793b267be6 | fix tests for NUnit | ppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,DrabWeb/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Tom94/osu-framework,Tom94/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,peppy/osu-framework,EVAST9919/osu-framework | osu.Framework.Tests/Visual/TestCaseFullscreen.cs | osu.Framework.Tests/Visual/TestCaseFullscreen.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.Drawing;
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Platform;
using osu.Framework.Testing;
namespace osu.Framework.Tests.Visual
{
public class TestCaseFullscreen : TestCase
{
private readonly SpriteText currentActualSize = new SpriteText();
private DesktopGameWindow window;
private readonly BindableSize sizeFullscreen = new BindableSize();
private readonly Bindable<WindowMode> windowMode = new Bindable<WindowMode>();
public TestCaseFullscreen()
{
var currentBindableSize = new SpriteText();
Child = new FillFlowContainer
{
Children = new[]
{
currentBindableSize,
currentActualSize,
},
};
sizeFullscreen.ValueChanged += newSize => currentBindableSize.Text = $"Fullscreen size: {newSize}";
}
private void testResolution(int w, int h)
{
AddStep($"{w}x{h}", () => sizeFullscreen.Value = new Size(w, h));
}
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager config, GameHost host)
{
window = (DesktopGameWindow)host.Window;
config.BindWith(FrameworkSetting.SizeFullscreen, sizeFullscreen);
config.BindWith(FrameworkSetting.WindowMode, windowMode);
// so the test case doesn't change fullscreen size just when you enter it
AddStep("nothing", () => { });
// I'll assume that most monitors are compatible with 1280x720, and this is just for testing anyways
AddStep("set to 1280x720", () => sizeFullscreen.Value = new Size(1280, 720));
AddStep("change to fullscreen", () => windowMode.Value = WindowMode.Fullscreen);
testResolution(1920, 1080);
testResolution(1280, 960);
AddStep("999x999 throws and restores", () => Assert.Throws(typeof(ArgumentException), () => sizeFullscreen.Value = new Size(999, 999)));
AddStep("go back to windowed", () => windowMode.Value = WindowMode.Windowed);
}
protected override void Update()
{
base.Update();
currentActualSize.Text = $"Window size: {window?.Bounds.Size}";
}
}
}
| // 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 osu.Framework.Allocation;
using osu.Framework.Configuration;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Platform;
using osu.Framework.Testing;
using System.Drawing;
namespace osu.Framework.Tests.Visual
{
public class TestCaseFullscreen : TestCase
{
private readonly SpriteText currentActualSize = new SpriteText();
private DesktopGameWindow window;
private readonly BindableSize sizeFullscreen = new BindableSize();
public TestCaseFullscreen()
{
var currentBindableSize = new SpriteText();
Child = new FillFlowContainer
{
Children = new[]
{
currentBindableSize,
currentActualSize,
},
};
sizeFullscreen.ValueChanged += newSize => currentBindableSize.Text = $"Fullscreen size: {newSize}";
}
private void testResolution(int w, int h)
{
AddStep($"{w}x{h}", () => sizeFullscreen.Value = new Size(w, h));
}
[BackgroundDependencyLoader]
private void load(FrameworkConfigManager config, GameHost host)
{
window = (DesktopGameWindow)host.Window;
config.BindWith(FrameworkSetting.SizeFullscreen, sizeFullscreen);
// so the test case doesn't change fullscreen size just when you enter it
AddStep("nothing", () => { });
testResolution(1920, 1080);
testResolution(1280, 720);
testResolution(1280, 960);
testResolution(999, 999);
}
protected override void Update()
{
base.Update();
currentActualSize.Text = $"Window size: {window.Bounds.Size}";
}
}
}
| mit | C# |
d5d696f9333b5ade0439ea7ba805272a20a72422 | Update in line with merge | ZLima12/osu-framework,ZLima12/osu-framework,peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,EVAST9919/osu-framework,ppy/osu-framework,ppy/osu-framework,EVAST9919/osu-framework | osu.Framework/IO/Stores/TimedExpiryGlyphStore.cs | osu.Framework/IO/Stores/TimedExpiryGlyphStore.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.
// 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.Textures;
namespace osu.Framework.IO.Stores
{
/// <summary>
/// A glyph store which caches font sprite sheets in memory temporary, to allow for more efficient retrieval.
/// </summary>
/// <remarks>
/// This store has a higher memory overhead than <see cref="RawCachingGlyphStore"/>, but better performance and zero disk footprint.
/// </remarks>
public class TimedExpiryGlyphStore : GlyphStore
{
private readonly TimedExpiryCache<int, TextureUpload> texturePages = new TimedExpiryCache<int, TextureUpload>();
public TimedExpiryGlyphStore(ResourceStore<byte[]> store, string assetName = null)
: base(store, assetName)
{
}
protected override TextureUpload GetPageImage(int page)
{
if (!texturePages.TryGetValue(page, out var image))
{
loadedPageCount++;
texturePages.Add(page, image = base.GetPageImage(page));
}
return image;
}
private int loadedPageCount;
public override string ToString() => $@"GlyphStore({AssetName}) LoadedPages:{loadedPageCount} LoadedGlyphs:{LoadedGlyphCount}";
protected override void Dispose(bool disposing)
{
texturePages.Dispose();
}
}
}
| // 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.
// 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 SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.IO.Stores
{
/// <summary>
/// A glyph store which caches font sprite sheets in memory temporary, to allow for more efficient retrieval.
/// </summary>
/// <remarks>
/// This store has a higher memory overhead than <see cref="RawCachingGlyphStore"/>, but better performance and zero disk footprint.
/// </remarks>
public class TimedExpiryGlyphStore : GlyphStore
{
private readonly TimedExpiryCache<int, Image<Rgba32>> texturePages = new TimedExpiryCache<int, Image<Rgba32>>();
public TimedExpiryGlyphStore(ResourceStore<byte[]> store, string assetName = null)
: base(store, assetName)
{
}
protected override Image<Rgba32> GetPageImage(int page)
{
if (!texturePages.TryGetValue(page, out var image))
{
loadedPageCount++;
texturePages.Add(page, image = base.GetPageImage(page));
}
return image;
}
private int loadedPageCount;
public override string ToString() => $@"GlyphStore({AssetName}) LoadedPages:{loadedPageCount} LoadedGlyphs:{LoadedGlyphCount}";
protected override void Dispose(bool disposing)
{
texturePages.Dispose();
}
}
}
| mit | C# |
165da3204454999cd8497d0f55987d871774b34c | Fix dropdown crash on collection name collisions | NeoAdonis/osu,NeoAdonis/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu,ppy/osu,peppy/osu,peppy/osu,smoogipoo/osu,UselessToucan/osu,UselessToucan/osu,peppy/osu,peppy/osu-new,smoogipoo/osu | osu.Game/Collections/CollectionFilterMenuItem.cs | osu.Game/Collections/CollectionFilterMenuItem.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 JetBrains.Annotations;
using osu.Framework.Bindables;
namespace osu.Game.Collections
{
/// <summary>
/// A <see cref="BeatmapCollection"/> filter.
/// </summary>
public class CollectionFilterMenuItem : IEquatable<CollectionFilterMenuItem>
{
/// <summary>
/// The collection to filter beatmaps from.
/// May be null to not filter by collection (include all beatmaps).
/// </summary>
[CanBeNull]
public readonly BeatmapCollection Collection;
/// <summary>
/// The name of the collection.
/// </summary>
[NotNull]
public readonly Bindable<string> CollectionName;
/// <summary>
/// Creates a new <see cref="CollectionFilterMenuItem"/>.
/// </summary>
/// <param name="collection">The collection to filter beatmaps from.</param>
public CollectionFilterMenuItem([CanBeNull] BeatmapCollection collection)
{
Collection = collection;
CollectionName = Collection?.Name.GetBoundCopy() ?? new Bindable<string>("All beatmaps");
}
public bool Equals(CollectionFilterMenuItem other)
{
if (other == null)
return false;
// collections may have the same name, so compare first on reference equality.
// this relies on the assumption that only one instance of the BeatmapCollection exists game-wide, managed by CollectionManager.
if (Collection != null)
return Collection == other.Collection;
// fallback to name-based comparison.
// this is required for special dropdown items which don't have a collection (all beatmaps / manage collections items below).
return CollectionName.Value == other.CollectionName.Value;
}
public override int GetHashCode() => CollectionName.Value.GetHashCode();
}
public class AllBeatmapsCollectionFilterMenuItem : CollectionFilterMenuItem
{
public AllBeatmapsCollectionFilterMenuItem()
: base(null)
{
}
}
public class ManageCollectionsFilterMenuItem : CollectionFilterMenuItem
{
public ManageCollectionsFilterMenuItem()
: base(null)
{
CollectionName.Value = "Manage collections...";
}
}
}
| // 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 JetBrains.Annotations;
using osu.Framework.Bindables;
namespace osu.Game.Collections
{
/// <summary>
/// A <see cref="BeatmapCollection"/> filter.
/// </summary>
public class CollectionFilterMenuItem : IEquatable<CollectionFilterMenuItem>
{
/// <summary>
/// The collection to filter beatmaps from.
/// May be null to not filter by collection (include all beatmaps).
/// </summary>
[CanBeNull]
public readonly BeatmapCollection Collection;
/// <summary>
/// The name of the collection.
/// </summary>
[NotNull]
public readonly Bindable<string> CollectionName;
/// <summary>
/// Creates a new <see cref="CollectionFilterMenuItem"/>.
/// </summary>
/// <param name="collection">The collection to filter beatmaps from.</param>
public CollectionFilterMenuItem([CanBeNull] BeatmapCollection collection)
{
Collection = collection;
CollectionName = Collection?.Name.GetBoundCopy() ?? new Bindable<string>("All beatmaps");
}
public bool Equals(CollectionFilterMenuItem other)
=> other != null && CollectionName.Value == other.CollectionName.Value;
public override int GetHashCode() => CollectionName.Value.GetHashCode();
}
public class AllBeatmapsCollectionFilterMenuItem : CollectionFilterMenuItem
{
public AllBeatmapsCollectionFilterMenuItem()
: base(null)
{
}
}
public class ManageCollectionsFilterMenuItem : CollectionFilterMenuItem
{
public ManageCollectionsFilterMenuItem()
: base(null)
{
CollectionName.Value = "Manage collections...";
}
}
}
| mit | C# |
ef3b19a2725a3dad30ddec626649ebd59d280d6b | Add missing copyright name | markembling/MarkEmbling.Utils,markembling/MarkEmbling.Utilities | MarkEmbling.Utils.Forms/Properties/AssemblyInfo.cs | MarkEmbling.Utils.Forms/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("MarkEmbling.Utils.Forms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.Utils.Forms")]
[assembly: AssemblyCopyright("Copyright © Mark Embling 2013")]
[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("1311bc7e-049c-4f38-9463-a136fec1fc5b")]
// 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.0.4")]
[assembly: AssemblyFileVersion("0.0.4")]
| 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("MarkEmbling.Utils.Forms")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Mark Embling")]
[assembly: AssemblyProduct("MarkEmbling.Utils.Forms")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[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("1311bc7e-049c-4f38-9463-a136fec1fc5b")]
// 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.0.4")]
[assembly: AssemblyFileVersion("0.0.4")]
| mit | C# |
159525feec67ef2de534ea3216827e84f8385827 | Add saftey around the Properties Dialog | Mataniko/IV-Play | Forms/Propertiesview.cs | Forms/Propertiesview.cs | #region
using IV_Play.Data;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
#endregion
namespace IV_Play
{
/// <summary>
/// Rom Properties view
/// </summary>
public partial class PropertiesView : Form
{
private Game _game;
public PropertiesView(Game game)
{
InitializeComponent();
try
{
_game = new XmlParser().ReadGameByName(game.Name);
}
catch
{
_game = game;
}
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
base.OnKeyUp(e);
}
private void PopulateForm()
{
_layoutPanel.BackgroundImage = SettingsManager.BackgroundImage;
Text = string.Format("IV/Play {0} Properties", _game.Description);
_txtDesc.Text = _game.Description;
_txtManu.Text = _game.Manufacturer;
_txtName.Text = _game.Name.Replace("fav_", "");
_txtYear.Text = _game.Year;
_txtColors.Text = _game.Colors;
_txtStatus.Text = _game.Driver;
_txtCPU.Text = _game.CPU;
_txtRoms.Text = _game.Roms;
_txtClone.Text = _game.CloneOf;
_txtSource.Text = _game.SourceFile;
_txtInput.Text = _game.Input;
_txtSound.Text = _game.Sound;
_txtScreen.Text = _game.Display;
}
private void PropertiesView_Load(object sender, EventArgs e)
{
PopulateForm();
}
private void _btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
} | #region
using IV_Play.Data;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
#endregion
namespace IV_Play
{
/// <summary>
/// Rom Properties view
/// </summary>
public partial class PropertiesView : Form
{
private Game _game;
public PropertiesView(Game game)
{
InitializeComponent();
_game = new XmlParser().ReadGameByName(game.Name);
}
protected override void OnKeyUp(KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
Close();
base.OnKeyUp(e);
}
private void PopulateForm()
{
_layoutPanel.BackgroundImage = SettingsManager.BackgroundImage;
Text = string.Format("IV/Play {0} Properties", _game.Description);
_txtDesc.Text = _game.Description;
_txtManu.Text = _game.Manufacturer;
_txtName.Text = _game.Name.Replace("fav_", "");
_txtYear.Text = _game.Year;
_txtColors.Text = _game.Colors;
_txtStatus.Text = _game.Driver;
_txtCPU.Text = _game.CPU;
_txtRoms.Text = _game.Roms;
_txtClone.Text = _game.CloneOf;
_txtSource.Text = _game.SourceFile;
_txtInput.Text = _game.Input;
_txtSound.Text = _game.Sound;
_txtScreen.Text = _game.Display;
}
private void PropertiesView_Load(object sender, EventArgs e)
{
PopulateForm();
}
private void _btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
} | mit | C# |
60da952d4b9215c6fe8b06d89184f7497d1fecb7 | Change Teamupdate time interval to 180s. | Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW,Midnight-Myth/Mitternacht-NEW | src/NadekoBot/Common/TimeConstants.cs | src/NadekoBot/Common/TimeConstants.cs | namespace Mitternacht.Common
{
public class TimeConstants
{
public const int WaitForForum = 500;
public const int TeamUpdate = 3 * 60 * 1000;
public const int Birthday = 60 * 1000;
}
}
| namespace Mitternacht.Common
{
public class TimeConstants
{
public const int WaitForForum = 500;
public const int TeamUpdate = 60 * 1000;
public const int Birthday = 60 * 1000;
}
}
| mit | C# |
fb60ccb9a72c337cfbc3316b7ca62c7d8c457f37 | Handle null jsonProperty.UnderlyingName values | Cussa/Swashbuckle,henning-krause/Swashbuckle,Driedas/Swashbuckle,kredinor/Swashbuckle,davetransom/Swashbuckle,gliljas/Swashbuckle,bdhess/Swashbuckle,tareq-s/Swashbuckle,gliljas/Swashbuckle,domaindrivendev/Swashbuckle,bigtlb/Swashbuckle,kredinor/Swashbuckle,gliljas/Swashbuckle,enkafan/Swashbuckle,Rolive0712/Swashbuckle,kienct89/Swashbuckle,xMarkos/Swashbuckle,fffej/Swashbuckle,svickers/Swashbuckle,bigtlb/Swashbuckle,Rolive0712/Swashbuckle,svickers/Swashbuckle,lostllama/Swashbuckle,replaysMike/Swashbuckle,lostllama/Swashbuckle,Driedas/Swashbuckle,enkafan/Swashbuckle,fffej/Swashbuckle,henning-krause/Swashbuckle,kienct89/Swashbuckle,jruckert/Swashbuckle,Atomosk/Swashbuckle,henning-krause/Swashbuckle,Cussa/Swashbuckle,Driedas/Swashbuckle,kredinor/Swashbuckle,svickers/Swashbuckle,partychen/Swashbuckle,replaysMike/Swashbuckle,martincostello/Swashbuckle,Colligo/Swashbuckle,VirtoCommerce/Swashbuckle,martincostello/Swashbuckle,fffej/Swashbuckle,gliljas/Swashbuckle,martincostello/Swashbuckle,xMarkos/Swashbuckle,xMarkos/Swashbuckle,yonglehou/Swashbuckle,domaindrivendev/Swashbuckle,davetransom/Swashbuckle,Colligo/Swashbuckle,lostllama/Swashbuckle,Rolive0712/Swashbuckle,Atomosk/Swashbuckle,tareq-s/Swashbuckle,VirtoCommerce/Swashbuckle,bdhess/Swashbuckle,svickers/Swashbuckle,Driedas/Swashbuckle,tareq-s/Swashbuckle,bdhess/Swashbuckle,lostllama/Swashbuckle,replaysMike/Swashbuckle,domaindrivendev/Swashbuckle,VirtoCommerce/Swashbuckle,bigtlb/Swashbuckle,martincostello/Swashbuckle,yonglehou/Swashbuckle,Atomosk/Swashbuckle,enkafan/Swashbuckle,tareq-s/Swashbuckle,Cussa/Swashbuckle,fffej/Swashbuckle,Colligo/Swashbuckle,bigtlb/Swashbuckle,kienct89/Swashbuckle,Cussa/Swashbuckle,Atomosk/Swashbuckle,partychen/Swashbuckle,yonglehou/Swashbuckle,jruckert/Swashbuckle,davetransom/Swashbuckle,henning-krause/Swashbuckle,kienct89/Swashbuckle,jruckert/Swashbuckle,yonglehou/Swashbuckle,kredinor/Swashbuckle,davetransom/Swashbuckle,partychen/Swashbuckle,bdhess/Swashbuckle,Colligo/Swashbuckle,replaysMike/Swashbuckle,Rolive0712/Swashbuckle,xMarkos/Swashbuckle,jruckert/Swashbuckle,partychen/Swashbuckle,VirtoCommerce/Swashbuckle,enkafan/Swashbuckle | Swashbuckle.Core/Swagger/JsonPropertyExtensions.cs | Swashbuckle.Core/Swagger/JsonPropertyExtensions.cs | using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.Swagger
{
public static class JsonPropertyExtensions
{
public static bool IsRequired(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<RequiredAttribute>();
}
public static bool IsObsolete(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<ObsoleteAttribute>();
}
public static bool HasAttribute<T>(this JsonProperty jsonProperty)
{
var propInfo = jsonProperty.PropertyInfo();
return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
}
public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
{
if(jsonProperty.UnderlyingName == null) return null;
return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
}
}
}
| using System;
using System.ComponentModel.DataAnnotations;
using System.Reflection;
using Newtonsoft.Json.Serialization;
namespace Swashbuckle.Swagger
{
public static class JsonPropertyExtensions
{
public static bool IsRequired(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<RequiredAttribute>();
}
public static bool IsObsolete(this JsonProperty jsonProperty)
{
return jsonProperty.HasAttribute<ObsoleteAttribute>();
}
public static bool HasAttribute<T>(this JsonProperty jsonProperty)
{
var propInfo = jsonProperty.PropertyInfo();
return propInfo != null && Attribute.IsDefined(propInfo, typeof (T));
}
public static PropertyInfo PropertyInfo(this JsonProperty jsonProperty)
{
return jsonProperty.DeclaringType.GetProperty(jsonProperty.UnderlyingName, jsonProperty.PropertyType);
}
}
}
| bsd-3-clause | C# |
1e2d8e764fbfbce35e8eb85a4b302e8547796092 | Call GetBaseException instead of manually unwrapping exception types. | mdavid/nuget,mdavid/nuget | src/Core/Utility/ExceptionUtility.cs | src/Core/Utility/ExceptionUtility.cs | using System;
using System.Reflection;
namespace NuGet {
public static class ExceptionUtility {
public static Exception Unwrap(Exception exception) {
if (exception == null) {
throw new ArgumentNullException("exception");
}
if (exception.InnerException == null) {
return exception;
}
// Always return the inner exception from a target invocation exception
if (exception is AggregateException ||
exception is TargetInvocationException) {
return exception.GetBaseException();
}
return exception;
}
}
}
| using System;
using System.Reflection;
namespace NuGet {
public static class ExceptionUtility {
public static Exception Unwrap(Exception exception) {
if (exception == null) {
throw new ArgumentNullException("exception");
}
if (exception.InnerException == null) {
return exception;
}
// Always return the inner exception from a target invocation exception
if (exception.GetType() == typeof(TargetInvocationException)) {
return exception.InnerException;
}
// Flatten the aggregate before getting the inner exception
if (exception.GetType() == typeof(AggregateException)) {
return ((AggregateException)exception).Flatten().InnerException;
}
return exception;
}
}
}
| apache-2.0 | C# |
21f4ced2c41b29752c00b3bcd0a754a69ea65caa | Remove a semicolon | riganti/dotvvm,riganti/dotvvm,riganti/dotvvm,riganti/dotvvm | src/DotVVM.Compiler/ProjectLoader.cs | src/DotVVM.Compiler/ProjectLoader.cs | using System;
using System.IO;
using System.Reflection;
namespace DotVVM.Compiler
{
public static class ProjectLoader
{
public static ICompilerExecutor GetExecutor(string assemblyPath)
{
#if NETCOREAPP3_1
var dependencyResolver = new System.Runtime.Loader.AssemblyDependencyResolver(assemblyPath);
System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += (c, n) =>
{
var path = dependencyResolver.ResolveAssemblyToPath(n);
return path is object
? c.LoadFromAssemblyPath(path)
: null;
};
_ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
return new DefaultCompilerExecutor();
#elif NET461
var setup = new AppDomainSetup
{
ApplicationBase = Path.GetDirectoryName(assemblyPath)
};
var configPath = assemblyPath + ".config";
if (File.Exists(configPath))
{
setup.ConfigurationFile = configPath;
}
var domain = AppDomain.CreateDomain("DotVVM.Compiler.AppDomain", null, setup);
return (ICompilerExecutor)domain.CreateInstanceFromAndUnwrap(
assemblyName: typeof(AppDomainCompilerExecutor).Assembly.Location,
typeName: typeof(AppDomainCompilerExecutor).FullName);
#else
#error Fix TargetFrameworks.
#endif
}
}
}
| using System;
using System.IO;
using System.Reflection;
namespace DotVVM.Compiler
{
public static class ProjectLoader
{
public static ICompilerExecutor GetExecutor(string assemblyPath)
{
#if NETCOREAPP3_1
var dependencyResolver = new System.Runtime.Loader.AssemblyDependencyResolver(assemblyPath);
System.Runtime.Loader.AssemblyLoadContext.Default.Resolving += (c, n) =>
{
var path = dependencyResolver.ResolveAssemblyToPath(n);
return path is object
? c.LoadFromAssemblyPath(path)
: null;
};
_ = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyPath);
return new DefaultCompilerExecutor();
#elif NET461
var setup = new AppDomainSetup
{
ApplicationBase = Path.GetDirectoryName(assemblyPath)
};
var configPath = assemblyPath + ".config";
if (File.Exists(configPath))
{
setup.ConfigurationFile = configPath;
}
var domain = AppDomain.CreateDomain("DotVVM.Compiler.AppDomain", null, setup);
return (ICompilerExecutor)domain.CreateInstanceFromAndUnwrap(
assemblyName: typeof(AppDomainCompilerExecutor).Assembly.Location,
typeName: typeof(AppDomainCompilerExecutor).FullName); ;
#else
#error Fix TargetFrameworks.
#endif
}
}
}
| apache-2.0 | C# |
6c37893afe6cdf6312eb45148d8d37f2ff17eb68 | Add Condition.And() that can operate over a collection of conjunctions | terrajobst/nquery-vnext | src/NQuery/Optimization/Condition.cs | src/NQuery/Optimization/Condition.cs | using System;
using System.Collections.Generic;
using System.Linq;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal static class Condition
{
public static BoundExpression And(BoundExpression left, BoundExpression right)
{
if (left == null)
return right;
if (right == null)
return left;
var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
return new BoundBinaryExpression(left, result, right);
}
public static BoundExpression And(IEnumerable<BoundExpression> conditions)
{
return conditions.Aggregate<BoundExpression, BoundExpression>(null, (c, n) => c == null ? n : And(c, n));
}
public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
{
var stack = new Stack<BoundExpression>();
stack.Push(expression);
while (stack.Count > 0)
{
var current = stack.Pop();
var binary = current as BoundBinaryExpression;
if (binary != null && binary.Result.Selected.Signature.Kind == BinaryOperatorKind.LogicalAnd)
{
stack.Push(binary.Left);
stack.Push(binary.Right);
}
else
{
yield return binary;
}
}
}
public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
{
var finder = new ValueSlotDependencyFinder();
finder.VisitExpression(expression);
return finder.ValueSlots.Overlaps(valueSlots);
}
}
} | using System;
using System.Collections.Generic;
using NQuery.Binding;
namespace NQuery.Optimization
{
internal static class Condition
{
public static BoundExpression And(BoundExpression left, BoundExpression right)
{
if (left == null)
return right;
if (right == null)
return left;
var result = BinaryOperator.Resolve(BinaryOperatorKind.LogicalAnd, left.Type, right.Type);
return new BoundBinaryExpression(left, result, right);
}
public static IEnumerable<BoundExpression> SplitConjunctions(BoundExpression expression)
{
var stack = new Stack<BoundExpression>();
stack.Push(expression);
while (stack.Count > 0)
{
var current = stack.Pop();
var binary = current as BoundBinaryExpression;
if (binary != null && binary.Result.Selected.Signature.Kind == BinaryOperatorKind.LogicalAnd)
{
stack.Push(binary.Left);
stack.Push(binary.Right);
}
else
{
yield return binary;
}
}
}
public static bool DependsOnAny(this BoundExpression expression, IEnumerable<ValueSlot> valueSlots)
{
var finder = new ValueSlotDependencyFinder();
finder.VisitExpression(expression);
return finder.ValueSlots.Overlaps(valueSlots);
}
}
} | mit | C# |
04b2cb63d2902b980f344849b95f2bdc355b25d7 | Remove obsolete comment about NestedLoops | fsateler/MoreLINQ,morelinq/MoreLINQ,ddpruitt/morelinq,morelinq/MoreLINQ,ddpruitt/morelinq,fsateler/MoreLINQ | MoreLinq/NestedLoops.cs | MoreLinq/NestedLoops.cs | #region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2010 Leopold Bushkin. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static partial class MoreEnumerable
{
// This extension method was developed (primarily) to support the
// implementation of the Permutations() extension methods.
/// <summary>
/// Produces a sequence from an action based on the dynamic generation of N nested loops
/// whose iteration counts are defined by a sequence of loop counts.
/// </summary>
/// <param name="action">Action delegate for which to produce a nested loop sequence</param>
/// <param name="loopCounts">A sequence of loop repetition counts</param>
/// <returns>A sequence of Action representing the expansion of a set of nested loops</returns>
static IEnumerable<Action> NestedLoops(this Action action, IEnumerable<int> loopCounts)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (loopCounts == null) throw new ArgumentNullException(nameof(loopCounts));
return _(); IEnumerable<Action> _()
{
var count = loopCounts.Assert(n => n >= 0,
n => new InvalidOperationException("Invalid loop count (must be greater than or equal to zero)."))
.DefaultIfEmpty()
.Aggregate((acc, x) => acc * x);
for (var i = 0; i < count; i++)
yield return action;
}
}
}
}
| #region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2010 Leopold Bushkin. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
namespace MoreLinq
{
using System;
using System.Collections.Generic;
using System.Linq;
public static partial class MoreEnumerable
{
// This extension method was developed (primarily) to support the
// implementation of the Permutations() extension methods. However,
// it is of sufficient generality and usefulness to be elevated to
// a public extension method in its own right.
/// <summary>
/// Produces a sequence from an action based on the dynamic generation of N nested loops
/// whose iteration counts are defined by a sequence of loop counts.
/// </summary>
/// <param name="action">Action delegate for which to produce a nested loop sequence</param>
/// <param name="loopCounts">A sequence of loop repetition counts</param>
/// <returns>A sequence of Action representing the expansion of a set of nested loops</returns>
static IEnumerable<Action> NestedLoops(this Action action, IEnumerable<int> loopCounts)
{
if (action == null) throw new ArgumentNullException(nameof(action));
if (loopCounts == null) throw new ArgumentNullException(nameof(loopCounts));
return _(); IEnumerable<Action> _()
{
var count = loopCounts.Assert(n => n >= 0,
n => new InvalidOperationException("Invalid loop count (must be greater than or equal to zero)."))
.DefaultIfEmpty()
.Aggregate((acc, x) => acc * x);
for (var i = 0; i < count; i++)
yield return action;
}
}
}
}
| apache-2.0 | C# |
341df045f24af59afaf5eab494e555df2408f9fb | Add Client.Read and Client.Send methods | ashfordl/netlib | NetLib/Client/Client.cs | NetLib/Client/Client.cs | // Client.cs
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace NetLib.Client
{
public class Client
{
private TcpClient tcp;
private NetworkStream stream;
private Thread readThread;
public Client(IPEndPoint ipep)
{
this.tcp = new TcpClient();
this.tcp.Connect(ipep);
this.stream = this.tcp.GetStream();
this.InitReadThread();
}
public Client(IPAddress ip, int port)
{
this.tcp = new TcpClient();
this.tcp.Connect(new IPEndPoint(ip, port));
this.stream = this.tcp.GetStream();
this.InitReadThread();
}
public Client(string hostname, int port)
{
this.tcp = new TcpClient(hostname, port);
this.stream = this.tcp.GetStream();
this.InitReadThread();
}
private void InitReadThread()
{
this.readThread = new Thread(this.Read);
readThread.Start();
}
private int ReadPayloadSize()
{
// Read the size of the message
byte[] sizeBuffer = new byte[4];
// Init message framing variables
int totalRead = 0, currentRead = 0;
// Read the size
do
{
currentRead = this.stream.Read(sizeBuffer, totalRead, sizeBuffer.Length - totalRead);
totalRead += currentRead;
}
while (totalRead < sizeBuffer.Length && currentRead > 0);
// Convert the size to an integer
return BitConverter.ToInt32(sizeBuffer, 0);
}
private byte[] ReadPayload(int size)
{
// Assign the payload buffer array
byte[] message = new byte[size];
// Asign message framing variables
int totalRead = 0, currentRead = 0;
// Read the payload
do
{
currentRead = this.stream.Read(message, totalRead, message.Length - totalRead);
totalRead += currentRead;
}
while (totalRead < message.Length && currentRead > 0);
return message;
}
private void Read()
{
while (true)
{
byte[] message;
try
{
// Convert the size to an integer
int size = this.ReadPayloadSize();
message = ReadPayload(size);
}
catch
{
break;
}
if (message.Length == 0)
{
// Client disconnected
break;
}
// Message received
string msg = Encoding.ASCII.GetString(message, 0, message.Length);
Console.WriteLine("Client: " + msg);
}
this.tcp.Close();
}
public void Send(string message)
{
this.Send(Encoding.ASCII.GetBytes(message));
}
public void Send(byte[] message)
{
// Encode message in bytes
byte[] lenBuffer = BitConverter.GetBytes(message.Length); // 4 bytes
// Concat two byte arrays
byte[] buffer = new byte[4 + message.Length];
lenBuffer.CopyTo(buffer, 0);
message.CopyTo(buffer, 4);
// Send the data
this.stream.Write(buffer, 0, buffer.Length);
Console.WriteLine("Client: Message sent");
}
}
}
| // Client.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace NetLib.Client
{
class Client
{
}
}
| mit | C# |
ccca5ee317f05e712d782e6f0a4a3f9420ff601e | Add Included property to Document model | huysentruitw/simple-json-api | src/SimpleJsonApi/Models/Document.cs | src/SimpleJsonApi/Models/Document.cs | using System.Collections.Generic;
using Newtonsoft.Json;
namespace SimpleJsonApi.Models
{
internal sealed class Document
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IDictionary<string, string> Links { get; set; }
/// <summary>
/// Data is either a <see cref="DocumentData"/> or <see cref="IEnumerable{DocumentData}"/> instance.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Include)]
public object Data { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<Error> Errors { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<DocumentData> Included { get; set; }
}
}
| using System.Collections.Generic;
using Newtonsoft.Json;
namespace SimpleJsonApi.Models
{
internal sealed class Document
{
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IDictionary<string, string> Links { get; set; }
/// <summary>
/// Data is either a <see cref="DocumentData"/> or <see cref="IEnumerable{DocumentData}"/> instance.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Include)]
public object Data { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public IEnumerable<Error> Errors { get; set; }
}
}
| apache-2.0 | C# |
26746c4034bbe76d1ef8eba06cf0ef1a68365991 | add parameter to map generator | rustamserg/mogate | mogate/Layers/MapGridLayer.cs | mogate/Layers/MapGridLayer.cs | using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace mogate
{
public class MapGridLayer: DrawableGameComponent
{
Texture2D m_wall;
Texture2D m_tile;
Texture2D m_ladder;
SpriteBatch m_spriteBatch;
public MapGridLayer (Game game) : base(game)
{
}
protected override void LoadContent ()
{
m_spriteBatch = new SpriteBatch(Game.GraphicsDevice);
m_tile = Game.Content.Load<Texture2D>("tile");
m_wall = Game.Content.Load<Texture2D>("wall");
m_ladder = Game.Content.Load<Texture2D>("ladder");
}
public override void Update (GameTime gameTime)
{
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
if (gameState.State == EState.LevelStarting) {
var mapGrid = (IMapGrid)Game.Services.GetService(typeof(IMapGrid));
MapGenerator.Generate(mapGrid, new MapGenerator.Params(mapGrid));
gameState.State = EState.MapGenerated;
}
}
public override void Draw (GameTime gameTime)
{
var mapGrid = (IMapGrid)Game.Services.GetService (typeof(IMapGrid));
m_spriteBatch.Begin ();
for (int x = 0; x < mapGrid.Width; x++) {
for (int y = 0; y < mapGrid.Height; y++) {
Vector2 dest = new Vector2(x * 32, y * 32);
m_spriteBatch.Draw (m_tile, dest, Color.White);
var id = mapGrid.GetID (x, y);
if (id == MapGridTypes.ID.Blocked)
m_spriteBatch.Draw (m_wall, dest, Color.White);
else if (id == MapGridTypes.ID.StairDown || id == MapGridTypes.ID.StairUp)
m_spriteBatch.Draw (m_ladder, dest, Color.White);
}
}
m_spriteBatch.End ();
base.Draw(gameTime);
}
}
}
| using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
namespace mogate
{
public class MapGridLayer: DrawableGameComponent
{
Texture2D m_wall;
Texture2D m_tile;
Texture2D m_ladder;
SpriteBatch m_spriteBatch;
public MapGridLayer (Game game) : base(game)
{
}
protected override void LoadContent ()
{
m_spriteBatch = new SpriteBatch(Game.GraphicsDevice);
m_tile = Game.Content.Load<Texture2D>("tile");
m_wall = Game.Content.Load<Texture2D>("wall");
m_ladder = Game.Content.Load<Texture2D>("ladder");
}
public override void Update (GameTime gameTime)
{
var gameState = (IGameState)Game.Services.GetService (typeof(IGameState));
if (gameState.State == EState.LevelStarting) {
var mapGrid = (IMapGrid)Game.Services.GetService(typeof(IMapGrid));
MapGenerator.Generate(mapGrid);
gameState.State = EState.MapGenerated;
}
}
public override void Draw (GameTime gameTime)
{
var mapGrid = (IMapGrid)Game.Services.GetService (typeof(IMapGrid));
m_spriteBatch.Begin ();
for (int x = 0; x < mapGrid.Width; x++) {
for (int y = 0; y < mapGrid.Height; y++) {
Vector2 dest = new Vector2(x * 32, y * 32);
m_spriteBatch.Draw (m_tile, dest, Color.White);
var id = mapGrid.GetID (x, y);
if (id == MapGridTypes.ID.Blocked)
m_spriteBatch.Draw (m_wall, dest, Color.White);
else if (id == MapGridTypes.ID.StairDown || id == MapGridTypes.ID.StairUp)
m_spriteBatch.Draw (m_ladder, dest, Color.White);
}
}
m_spriteBatch.End ();
base.Draw(gameTime);
}
}
}
| mit | C# |
e09570c31bf18af340d529fc59448b1b694db270 | Implement best-name-finding helper method | peppy/osu,peppy/osu,peppy/osu,ppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu | osu.Game/Utils/NamingUtils.cs | osu.Game/Utils/NamingUtils.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.Text.RegularExpressions;
namespace osu.Game.Utils
{
public static class NamingUtils
{
/// <summary>
/// Given a set of <paramref name="existingNames"/> and a target <paramref name="desiredName"/>,
/// finds a "best" name closest to <paramref name="desiredName"/> that is not in <paramref name="existingNames"/>.
/// </summary>
/// <remarks>
/// <para>
/// This helper is most useful in scenarios when creating new objects in a set
/// (such as adding new difficulties to a beatmap set, or creating a clone of an existing object that needs a unique name).
/// If <paramref name="desiredName"/> is already present in <paramref name="existingNames"/>,
/// this method will append the lowest possible number in brackets that doesn't conflict with <paramref name="existingNames"/>
/// to <paramref name="desiredName"/> and return that.
/// See <c>osu.Game.Tests.Utils.NamingUtilsTest</c> for concrete examples of behaviour.
/// </para>
/// <para>
/// <paramref name="desiredName"/> and <paramref name="existingNames"/> are compared in a case-insensitive manner,
/// so this method is safe to use for naming files in a platform-invariant manner.
/// </para>
/// </remarks>
public static string GetNextBestName(IEnumerable<string> existingNames, string desiredName)
{
string pattern = $@"^(?i){Regex.Escape(desiredName)}(?-i)( \((?<copyNumber>[1-9][0-9]*)\))?$";
var regex = new Regex(pattern, RegexOptions.Compiled);
var takenNumbers = new HashSet<int>();
foreach (string name in existingNames)
{
var match = regex.Match(name);
if (!match.Success)
continue;
string copyNumberString = match.Groups[@"copyNumber"].Value;
if (string.IsNullOrEmpty(copyNumberString))
{
takenNumbers.Add(0);
continue;
}
takenNumbers.Add(int.Parse(copyNumberString));
}
int bestNumber = 0;
while (takenNumbers.Contains(bestNumber))
bestNumber += 1;
return bestNumber == 0
? desiredName
: $"{desiredName} ({bestNumber})";
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
namespace osu.Game.Utils
{
public static class NamingUtils
{
public static string GetNextBestName(IEnumerable<string> existingNames, string desiredName)
{
return null;
}
}
}
| mit | C# |
f7f09736d35dd4bda4a3e5387b067cf2f15bc5d8 | Update Recents.cs | wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,Core2D/Core2D,wieslawsoltes/Core2D | src/Core2D.Editor/Recent/Recents.cs | src/Core2D.Editor/Recent/Recents.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 System.Collections.Immutable;
namespace Core2D.Editor.Recent
{
/// <summary>
/// Recent files.
/// </summary>
public class Recents : ObservableObject
{
private ImmutableArray<RecentFile> _files = ImmutableArray.Create<RecentFile>();
private RecentFile _current = default(RecentFile);
/// <summary>
/// Gets or sets recent file entries.
/// </summary>
public ImmutableArray<RecentFile> Files
{
get => _files;
set => Update(ref _files, value);
}
/// <summary>
/// Gets or sets current recent file.
/// </summary>
public RecentFile Current
{
get => _current;
set => Update(ref _current, value);
}
/// <summary>
/// Creates a new <see cref="Recents"/> instance.
/// </summary>
/// <param name="files">The recent files.</param>
/// <param name="current">The current recent file.</param>
/// <returns>The new instance of the <see cref="Recents"/> class.</returns>
public static Recents Create(ImmutableArray<RecentFile> files, RecentFile current)
{
return new Recents()
{
Files = files,
Current = current
};
}
}
}
| // Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Core2D.Editor.Recent
{
/// <summary>
/// Recent file.
/// </summary>
public class RecentFile : ObservableObject
{
private string _name;
private string _path;
/// <summary>
/// Gets or sets recent file name.
/// </summary>
public string Name
{
get => _name;
set => Update(ref _name, value);
}
/// <summary>
/// Gets or sets recent file path.
/// </summary>
public string Path
{
get => _path;
set => Update(ref _path, value);
}
/// <summary>
/// Creates a new <see cref="RecentFile"/> instance.
/// </summary>
/// <param name="name">The recent file name.</param>
/// <param name="path">The recent file path.</param>
/// <returns>The new instance of the <see cref="RecentFile"/> class.</returns>
public static RecentFile Create(string name, string path)
{
return new RecentFile()
{
Name = name,
Path = path
};
}
}
}
| mit | C# |
5bf58a08e9664c63bf153c09b8f3f1b7dd7d5e33 | Remove redundant AddOptions which is now a default hosting service | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | src/Microsoft.AspNet.Cors/CorsServiceCollectionExtensions.cs | src/Microsoft.AspNet.Cors/CorsServiceCollectionExtensions.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Cors.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// The <see cref="IServiceCollection"/> extensions for enabling CORS support.
/// </summary>
public static class CorsServiceCollectionExtensions
{
/// <summary>
/// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection to which CORS services are added.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCors(this IServiceCollection serviceCollection)
{
if (serviceCollection == null)
{
throw new ArgumentNullException(nameof(serviceCollection));
}
serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsService, CorsService>());
serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsPolicyProvider, DefaultCorsPolicyProvider>());
return serviceCollection;
}
/// <summary>
/// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection to which CORS services are added.</param>
/// <param name="configure">A delegate which is run to configure the services.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCors(
this IServiceCollection serviceCollection,
Action<CorsOptions> configure)
{
if (serviceCollection == null)
{
throw new ArgumentNullException(nameof(serviceCollection));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
serviceCollection.Configure(configure);
return serviceCollection.AddCors();
}
}
} | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using Microsoft.AspNet.Cors.Infrastructure;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Microsoft.Extensions.DependencyInjection
{
/// <summary>
/// The <see cref="IServiceCollection"/> extensions for enabling CORS support.
/// </summary>
public static class CorsServiceCollectionExtensions
{
/// <summary>
/// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection to which CORS services are added.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCors(this IServiceCollection serviceCollection)
{
if (serviceCollection == null)
{
throw new ArgumentNullException(nameof(serviceCollection));
}
serviceCollection.AddOptions();
serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsService, CorsService>());
serviceCollection.TryAdd(ServiceDescriptor.Transient<ICorsPolicyProvider, DefaultCorsPolicyProvider>());
return serviceCollection;
}
/// <summary>
/// Add services needed to support CORS to the given <paramref name="serviceCollection"/>.
/// </summary>
/// <param name="serviceCollection">The service collection to which CORS services are added.</param>
/// <param name="configure">A delegate which is run to configure the services.</param>
/// <returns>The updated <see cref="IServiceCollection"/>.</returns>
public static IServiceCollection AddCors(
this IServiceCollection serviceCollection,
Action<CorsOptions> configure)
{
if (serviceCollection == null)
{
throw new ArgumentNullException(nameof(serviceCollection));
}
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
serviceCollection.Configure(configure);
return serviceCollection.AddCors();
}
}
} | apache-2.0 | C# |
b2d8d42793eedc21eb02d1e50d5d6a30bc5d62c0 | Patch support added. | nseckinoral/xomni-sdk-dotnet | src/XOMNI.SDK.Private/Passbook/PassbookTemplateManagement.cs | src/XOMNI.SDK.Private/Passbook/PassbookTemplateManagement.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XOMNI.SDK.Core.ApiAccess;
using XOMNI.SDK.Core.Management;
using XOMNI.SDK.Core.Providers;
namespace XOMNI.SDK.Private.Passbook
{
public class PassbookTemplate : ApiAccessBase
{
private XOMNI.SDK.Private.ApiAccess.Passbook.PassbookTemplate passbookTemplateApi;
protected override string SingleOperationBaseUrl
{
get { return "/private/passbook/templates"; }
}
protected override string ListOperationBaseUrl
{
get { throw new NotImplementedException(); }
}
public Task<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate> AddAsync(XOMNI.SDK.Model.Private.Passbook.PassbookTemplateRequest passbookTemplate, ApiBasicCredential credential)
{
return HttpProvider.PostAsync<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>(GenerateUrl(SingleOperationBaseUrl), passbookTemplate, credential);
}
public Task<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate> UpdateAsync(XOMNI.SDK.Model.Private.Passbook.PassbookTemplateRequest passbookTemplate, ApiBasicCredential credential)
{
return HttpProvider.PutAsync<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>(GenerateUrl(SingleOperationBaseUrl), passbookTemplate, credential);
}
public Task<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate> PatchAsync(dynamic passbookTemplate, ApiBasicCredential credential)
{
return HttpProvider.PatchAsync<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>(GenerateUrl(SingleOperationBaseUrl), passbookTemplate, credential);
}
public Task DeleteAsync(int templateId, ApiBasicCredential credential)
{
Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
additionalParameters.Add("templateId", templateId.ToString());
return HttpProvider.DeleteAsync(GenerateUrl(SingleOperationBaseUrl, additionalParameters), credential);
}
public Task<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate> GetAsync(int templateId, ApiBasicCredential credential)
{
Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
additionalParameters.Add("templateId", templateId.ToString());
return HttpProvider.GetAsync<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>(GenerateUrl(SingleOperationBaseUrl, additionalParameters), credential);
}
public Task<XOMNI.SDK.Model.CountedCollectionContainer<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>> GetAllAsync(int skip, int take, ApiBasicCredential credential)
{
Dictionary<string, string> additionalParameters = new Dictionary<string, string>();
additionalParameters.Add("skip", skip.ToString());
additionalParameters.Add("take", take.ToString());
return HttpProvider.GetAsync<XOMNI.SDK.Model.CountedCollectionContainer<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>>(GenerateUrl(ListOperationBaseUrl, additionalParameters), credential);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using XOMNI.SDK.Core.Management;
namespace XOMNI.SDK.Private.Passbook
{
public class PassbookTemplateManagement : BaseCRUDPSkipTakeManagement<XOMNI.SDK.Model.Private.Passbook.PassbookTemplate>
{
private XOMNI.SDK.Private.ApiAccess.Passbook.PassbookTemplate passbookTemplateApi;
protected override Core.ApiAccess.CRUDPApiAccessBase<Model.Private.Passbook.PassbookTemplate> CRUDPApiAccess
{
get
{
if (passbookTemplateApi == null)
{
passbookTemplateApi = new ApiAccess.Passbook.PassbookTemplate();
}
return passbookTemplateApi;
}
}
}
}
| mit | C# |
9c98000b4151088411fcd0f20d0556d95fb05425 | Add comment to demo teamcity | JakeGinnivan/fixie,Duohong/fixie,EliotJones/fixie,fixie/fixie,KevM/fixie,bardoloi/fixie,bardoloi/fixie | src/Fixie/Behaviors/CaseBehavior.cs | src/Fixie/Behaviors/CaseBehavior.cs | namespace Fixie.Behaviors
{
public interface CaseBehavior
{
void Execute(Case @case, object instance); //comment to demo teamcity
}
}
| namespace Fixie.Behaviors
{
public interface CaseBehavior
{
void Execute(Case @case, object instance);
}
} | mit | C# |
741d258fab2165edb09721a4fe5b0910e8938bb4 | remove WhenTerminated.Wait | InventoryLab/lighthouse,InventoryLab/lighthouse | src/Lighthouse/LighthouseService.cs | src/Lighthouse/LighthouseService.cs | // Copyright 2014-2015 Aaron Stannard, Petabridge LLC
//
// 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.Threading.Tasks;
using Akka.Actor;
using Petabridge.Cmd.Host;
using Petabridge.Cmd.Cluster;
namespace Lighthouse
{
public class LighthouseService
{
private readonly string _ipAddress;
private readonly int? _port;
private ActorSystem _lighthouseSystem;
public LighthouseService() : this(null, null) { }
public LighthouseService(string ipAddress, int? port)
{
_ipAddress = ipAddress;
_port = port;
}
public void Start()
{
_lighthouseSystem = LighthouseHostFactory.LaunchLighthouse(_ipAddress, _port);
var cmd = PetabridgeCmd.Get(_lighthouseSystem);
cmd.RegisterCommandPalette(ClusterCommands.Instance);
cmd.Start();
}
public async Task StopAsync()
{
await _lighthouseSystem.Terminate();
}
}
}
| // Copyright 2014-2015 Aaron Stannard, Petabridge LLC
//
// 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.Threading.Tasks;
using Akka.Actor;
using Petabridge.Cmd.Host;
using Petabridge.Cmd.Cluster;
namespace Lighthouse
{
public class LighthouseService
{
private readonly string _ipAddress;
private readonly int? _port;
private ActorSystem _lighthouseSystem;
public LighthouseService() : this(null, null) { }
public LighthouseService(string ipAddress, int? port)
{
_ipAddress = ipAddress;
_port = port;
}
public void Start()
{
_lighthouseSystem = LighthouseHostFactory.LaunchLighthouse(_ipAddress, _port);
var cmd = PetabridgeCmd.Get(_lighthouseSystem);
cmd.RegisterCommandPalette(ClusterCommands.Instance);
cmd.Start();
_lighthouseSystem.WhenTerminated.Wait();
}
public async Task StopAsync()
{
await _lighthouseSystem.Terminate();
}
}
}
| apache-2.0 | C# |
fdc290a6a927d5603d612c13039e1fef587ebfb9 | call commit after adding a document to lucene | mvbalaw/MvbaCore | src/MvbaCore/Lucene/LuceneWriter.cs | src/MvbaCore/Lucene/LuceneWriter.cs | // * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.IO;
using System.Linq;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Directory = System.IO.Directory;
using Version = Lucene.Net.Util.Version;
namespace MvbaCore.Lucene
{
public interface ILuceneWriter
{
void AddDocument(Document document);
void Close();
void Commit();
void DeleteDocuments(Term term);
}
public class LuceneWriter : ILuceneWriter, IDisposable
{
private readonly ILuceneFileSystem _luceneFileSystem;
private IndexWriter _writer;
public LuceneWriter(ILuceneFileSystem luceneFileSystem)
{
_luceneFileSystem = luceneFileSystem;
}
public void Dispose()
{
Close();
}
public void Close()
{
if (_writer != null)
{
_writer.Commit();
_writer.Close();
_writer = null;
}
}
public void DeleteDocuments(Term term)
{
Open();
_writer.DeleteDocuments(term);
Commit();
}
public void Commit()
{
if (_writer == null)
{
return;
}
_writer.Commit();
}
public void AddDocument(Document document)
{
Open();
_writer.AddDocument(document);
Commit();
}
private void Open()
{
if (_writer != null)
{
return;
}
var analyzer = new StandardAnalyzer(Version.LUCENE_29);
string luceneDirectory = _luceneFileSystem.GetLuceneDirectory();
var fsDirectory = FSDirectory.Open(new DirectoryInfo(luceneDirectory));
bool create = !Directory.GetFiles(luceneDirectory).Any();
_writer = new IndexWriter(fsDirectory, analyzer, create, new IndexWriter.MaxFieldLength(1000));
}
}
} | // * **************************************************************************
// * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C.
// * This source code is subject to terms and conditions of the MIT License.
// * A copy of the license can be found in the License.txt file
// * at the root of this distribution.
// * By using this source code in any fashion, you are agreeing to be bound by
// * the terms of the MIT License.
// * You must not remove this notice from this software.
// * **************************************************************************
using System;
using System.IO;
using System.Linq;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Directory = System.IO.Directory;
using Version = Lucene.Net.Util.Version;
namespace MvbaCore.Lucene
{
public interface ILuceneWriter
{
void AddDocument(Document document);
void Close();
void Commit();
void DeleteDocuments(Term term);
}
public class LuceneWriter : ILuceneWriter, IDisposable
{
private readonly ILuceneFileSystem _luceneFileSystem;
private IndexWriter _writer;
public LuceneWriter(ILuceneFileSystem luceneFileSystem)
{
_luceneFileSystem = luceneFileSystem;
}
public void Dispose()
{
Close();
}
public void Close()
{
if (_writer != null)
{
_writer.Commit();
_writer.Close();
_writer = null;
}
}
public void DeleteDocuments(Term term)
{
Open();
_writer.DeleteDocuments(term);
Commit();
}
public void Commit()
{
if (_writer == null)
{
return;
}
_writer.Commit();
}
public void AddDocument(Document document)
{
Open();
_writer.AddDocument(document);
}
private void Open()
{
if (_writer != null)
{
return;
}
var analyzer = new StandardAnalyzer(Version.LUCENE_29);
string luceneDirectory = _luceneFileSystem.GetLuceneDirectory();
var fsDirectory = FSDirectory.Open(new DirectoryInfo(luceneDirectory));
bool create = !Directory.GetFiles(luceneDirectory).Any();
_writer = new IndexWriter(fsDirectory, analyzer, create, new IndexWriter.MaxFieldLength(1000));
}
}
} | mit | C# |
9ae6bb92ba0062065b27281cabdb39820b412221 | Rename DefaultComputerCharacteristics to WindowsComputerCharacteristics | JanDotNet/ThinkSharp.Licensing | ThinkSharp.Licensing/Licensing/DefaultComputerCharacteristics.cs | ThinkSharp.Licensing/Licensing/DefaultComputerCharacteristics.cs | // Copyright (c) Jan-Niklas Schäfer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Runtime.Versioning;
using System.Text;
namespace ThinkSharp.Licensing.Licensing
{
internal class WindowsComputerCharacteristics : IComputerCharacteristics
{
public IEnumerable<string> GetCharacteristicsForCurrentComputer()
{
yield return GetValue("ProcessorID", "Win32_Processor");
yield return GetValue("SerialNumber", "Win32_BIOS");
yield return GetValue("SerialNumber", "Win32_BaseBoard");
yield return GetValue("SerialNumber", "Win32_PhysicalMedia");
}
private static string GetValue(string property, string type)
{
var sb = new StringBuilder();
try
{
var searcher = new ManagementObjectSearcher($"select {property} from {type}");
foreach (var share in searcher.Get())
foreach (PropertyData pc in share.Properties)
sb.Append(pc.Value);
}
catch
{
sb.Append(property).Append(type);
}
return sb.ToString();
}
}
}
| // Copyright (c) Jan-Niklas Schäfer. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
namespace ThinkSharp.Licensing.Licensing
{
internal class DefaultComputerCharacteristics : IComputerCharacteristics
{
public IEnumerable<string> GetCharacteristicsForCurrentComputer()
{
yield return GetValue("ProcessorID", "Win32_Processor");
yield return GetValue("SerialNumber", "Win32_BIOS");
yield return GetValue("SerialNumber", "Win32_BaseBoard");
yield return GetValue("SerialNumber", "Win32_PhysicalMedia");
}
private static string GetValue(string property, string type)
{
var sb = new StringBuilder();
try
{
var searcher = new ManagementObjectSearcher($"select {property} from {type}");
foreach (var share in searcher.Get())
foreach (PropertyData pc in share.Properties)
sb.Append(pc.Value);
}
catch
{
sb.Append(property).Append(type);
}
return sb.ToString();
}
}
}
| mit | C# |
9df4ff13577d2a7aa64864bdf51f5d679bc1c12e | Allow web query from https://babelmark.github.io and http://johnmacfarlane.net | babelmark/babelmark-proxy | src/BabelMark/Startup.cs | src/BabelMark/Startup.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace BabelMark
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(
Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(builder =>
{
builder.WithOrigins("http://babelmark.github.io", "https://babelmark.github.io", "http://johnmacfarlane.net").WithMethods("get").AllowCredentials();
});
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMiddleware<RequestThrottlingMiddleware>();
app.UseMvc();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace BabelMark
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
if (env.IsEnvironment("Development"))
{
// This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
builder.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfigurationRoot Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(
Configuration);
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseCors(builder =>
{
builder.WithOrigins("http://babelmark.github.io").WithMethods("get").AllowCredentials();
});
app.UseApplicationInsightsRequestTelemetry();
app.UseApplicationInsightsExceptionTelemetry();
app.UseMiddleware<RequestThrottlingMiddleware>();
app.UseMvc();
}
}
}
| bsd-2-clause | C# |
4b41becb8affbe9270034e9a0291ec5226f41b14 | transform component use degrees | bitzhuwei/CSharpGL,bitzhuwei/CSharpGL,bitzhuwei/CSharpGL | CSharpGL/Scenes/TransformComponent.cs | CSharpGL/Scenes/TransformComponent.cs | using System;
namespace CSharpGL
{
/// <summary>
/// Description of TransformComponent.
/// </summary>
public partial class TransformComponent : Component
{
public vec3 Position { get; set; }
public vec3 Rotation { get; set; }
public vec3 Scale { get; set; }
public TransformComponent(SceneObject bindingObject = null)
: base(bindingObject)
{
this.Scale = new vec3(1, 1, 1);
}
static readonly vec3 xAxis = new vec3(1, 0, 0);
static readonly vec3 yAxis = new vec3(0, 1, 0);
static readonly vec3 zAxis = new vec3(0, 0, 1);
/// <summary>
/// Get model matrix.
/// </summary>
/// <returns></returns>
public mat4 GetMatrix()
{
mat4 matrix;
matrix = glm.rotate((float)(this.Rotation.x * Math.PI / 180.0), xAxis);
matrix = glm.rotate((float)(this.Rotation.y * Math.PI / 180.0), yAxis);
matrix = glm.rotate((float)(this.Rotation.z * Math.PI / 180.0), zAxis);
matrix = glm.scale(matrix, this.Scale);
matrix = glm.translate(matrix, this.Position);
return matrix;
}
}
}
| using System;
namespace CSharpGL
{
/// <summary>
/// Description of TransformComponent.
/// </summary>
public partial class TransformComponent : Component
{
public vec3 Position { get; set; }
public vec3 Rotation { get; set; }
public vec3 Scale { get; set; }
public TransformComponent(SceneObject bindingObject = null)
: base(bindingObject)
{
this.Scale = new vec3(1, 1, 1);
}
static readonly vec3 xAxis = new vec3(1, 0, 0);
static readonly vec3 yAxis = new vec3(0, 1, 0);
static readonly vec3 zAxis = new vec3(0, 0, 1);
/// <summary>
/// Get model matrix.
/// </summary>
/// <returns></returns>
public mat4 GetMatrix()
{
mat4 matrix;
matrix = glm.rotate(this.Rotation.x, xAxis);
matrix = glm.rotate(this.Rotation.y, yAxis);
matrix = glm.rotate(this.Rotation.z, zAxis);
matrix = glm.scale(matrix, this.Scale);
matrix = glm.translate(matrix, this.Position);
return matrix;
}
}
}
| mit | C# |
633e9efb9b3847a0692cbd7193ffcaec7153ef9d | Increase the base timeout for TaskTest | PKRoma/kafka-net,martijnhoekstra/kafka-net,EranOfer/KafkaNetClient,BDeus/KafkaNetClient,nightkid1027/kafka-net,geffzhang/kafka-net,Jroland/kafka-net,CenturyLinkCloud/kafka-net,aNutForAJarOfTuna/kafka-net,bridgewell/kafka-net,gigya/KafkaNetClient | src/kafka-tests/Helpers/TaskTest.cs | src/kafka-tests/Helpers/TaskTest.cs | using System;
using System.Diagnostics;
using System.Threading;
namespace kafka_tests.Helpers
{
public static class TaskTest
{
public static bool WaitFor(Func<bool> predicate, int milliSeconds = 3000)
{
var sw = Stopwatch.StartNew();
while (predicate() != true)
{
if (sw.ElapsedMilliseconds > milliSeconds)
return false;
Thread.Sleep(500);
}
return true;
}
}
}
| using System;
using System.Diagnostics;
using System.Threading;
namespace kafka_tests.Helpers
{
public static class TaskTest
{
public static bool WaitFor(Func<bool> predicate, int milliSeconds = 1000)
{
var sw = Stopwatch.StartNew();
while (predicate() != true)
{
if (sw.ElapsedMilliseconds > milliSeconds)
return false;
Thread.Sleep(500);
}
return true;
}
}
}
| apache-2.0 | C# |
5cdc131ab4d1391fa5069d65c39b8a272ac945e8 | Add comments. | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | bootstrapping/Build.cs | bootstrapping/Build.cs | using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;
class Build : NukeBuild
{
// Auto-injection fields:
// - [GitVersion] must have 'GitVersion.CommandLine' referenced
// - [GitRepository] parses the origin from git config
// - [Parameter] retrieves its value from command-line arguments or environment variables
//
//[GitVersion] readonly GitVersion GitVersion;
//[GitRepository] readonly GitRepository GitRepository;
//[Parameter] readonly string MyGetApiKey;
// This is the application entry point for the build.
// It also defines the default target to execute.
public static int Main () => Execute<Build>(x => x.Compile);
Target Clean => _ => _
// Disabled for safety.
.OnlyWhen(() => false)
.Executes(() => DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj")))
.Executes(() => EnsureCleanDirectory(OutputDirectory));
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
// Remove tasks as needed. They exist for compatibility.
DotNetRestore(SolutionDirectory);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
NuGetRestore(SolutionFile);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// When having xproj-based projects, using VS2015 is necessary.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion?);
}
| using System;
using System.Linq;
using Nuke.Common;
using Nuke.Common.Git;
using Nuke.Common.Tools.GitVersion;
using Nuke.Common.Tools.MSBuild;
using Nuke.Core;
using static Nuke.Common.Tools.DotNet.DotNetTasks;
using static Nuke.Common.Tools.MSBuild.MSBuildTasks;
using static Nuke.Common.Tools.NuGet.NuGetTasks;
using static Nuke.Core.IO.FileSystemTasks;
using static Nuke.Core.IO.PathConstruction;
using static Nuke.Core.EnvironmentInfo;
class Build : NukeBuild
{
//[GitVersion] readonly GitVersion GitVersion;
//[GitRepository] readonly GitRepository GitRepository;
// This is the application entry point for the build.
// It also defines the default target to execute.
public static int Main () => Execute<Build>(x => x.Compile);
Target Clean => _ => _
// Disabled for safety.
.OnlyWhen(() => false)
.Executes(() => DeleteDirectories(GlobDirectories(SourceDirectory, "**/bin", "**/obj")))
.Executes(() => EnsureCleanDirectory(OutputDirectory));
Target Restore => _ => _
.DependsOn(Clean)
.Executes(() =>
{
// Remove tasks as needed. They exist for compatibility.
DotNetRestore(SolutionDirectory);
if (MSBuildVersion == Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017)
MSBuild(s => DefaultSettings.MSBuildRestore);
NuGetRestore(SolutionFile);
});
Target Compile => _ => _
.DependsOn(Restore)
.Executes(() => MSBuild(s => DefaultSettings.MSBuildCompile
.SetMSBuildVersion(MSBuildVersion)));
// When having xproj-based projects, using VS2015 is necessary.
MSBuildVersion? MSBuildVersion =>
!IsUnix
? GlobFiles(SolutionDirectory, "*.xproj").Any()
? Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2015
: Nuke.Common.Tools.MSBuild.MSBuildVersion.VS2017
: default(MSBuildVersion?);
}
| mit | C# |
36853547007f2cfe5079f1660c4453edf1513efd | Add line breaks. | CyrusNajmabadi/roslyn,aelij/roslyn,wvdd007/roslyn,tmeschter/roslyn,reaction1989/roslyn,swaroop-sridhar/roslyn,genlu/roslyn,nguerrera/roslyn,xasx/roslyn,dpoeschl/roslyn,physhi/roslyn,VSadov/roslyn,mavasani/roslyn,panopticoncentral/roslyn,mavasani/roslyn,bkoelman/roslyn,jcouv/roslyn,KirillOsenkov/roslyn,bartdesmet/roslyn,jasonmalinowski/roslyn,jmarolf/roslyn,diryboy/roslyn,MichalStrehovsky/roslyn,cston/roslyn,KevinRansom/roslyn,weltkante/roslyn,AlekseyTs/roslyn,agocke/roslyn,wvdd007/roslyn,jamesqo/roslyn,aelij/roslyn,jamesqo/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,tannergooding/roslyn,ErikSchierboom/roslyn,AmadeusW/roslyn,jmarolf/roslyn,DustinCampbell/roslyn,OmarTawfik/roslyn,gafter/roslyn,tmat/roslyn,genlu/roslyn,gafter/roslyn,VSadov/roslyn,swaroop-sridhar/roslyn,OmarTawfik/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,dotnet/roslyn,mgoertz-msft/roslyn,weltkante/roslyn,KirillOsenkov/roslyn,VSadov/roslyn,bkoelman/roslyn,dpoeschl/roslyn,CyrusNajmabadi/roslyn,sharwell/roslyn,ErikSchierboom/roslyn,tmat/roslyn,stephentoub/roslyn,panopticoncentral/roslyn,wvdd007/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,brettfo/roslyn,abock/roslyn,mgoertz-msft/roslyn,jasonmalinowski/roslyn,MichalStrehovsky/roslyn,mgoertz-msft/roslyn,KevinRansom/roslyn,DustinCampbell/roslyn,KevinRansom/roslyn,davkean/roslyn,physhi/roslyn,stephentoub/roslyn,dotnet/roslyn,ErikSchierboom/roslyn,paulvanbrenk/roslyn,AmadeusW/roslyn,AmadeusW/roslyn,DustinCampbell/roslyn,tmeschter/roslyn,mavasani/roslyn,sharwell/roslyn,jmarolf/roslyn,dotnet/roslyn,weltkante/roslyn,reaction1989/roslyn,paulvanbrenk/roslyn,eriawan/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,abock/roslyn,MichalStrehovsky/roslyn,paulvanbrenk/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,davkean/roslyn,stephentoub/roslyn,physhi/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,reaction1989/roslyn,heejaechang/roslyn,diryboy/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,dpoeschl/roslyn,heejaechang/roslyn,agocke/roslyn,davkean/roslyn,cston/roslyn,jcouv/roslyn,aelij/roslyn,bartdesmet/roslyn,gafter/roslyn,heejaechang/roslyn,jcouv/roslyn,KirillOsenkov/roslyn,OmarTawfik/roslyn,swaroop-sridhar/roslyn,cston/roslyn,AlekseyTs/roslyn,diryboy/roslyn,xasx/roslyn,abock/roslyn,bkoelman/roslyn,xasx/roslyn,nguerrera/roslyn,brettfo/roslyn,bartdesmet/roslyn,genlu/roslyn,nguerrera/roslyn,tmeschter/roslyn,jamesqo/roslyn,tannergooding/roslyn,eriawan/roslyn,AlekseyTs/roslyn,jasonmalinowski/roslyn,tannergooding/roslyn | src/Workspaces/Core/Portable/EmbeddedLanguages/Json/JsonHelpers.cs | src/Workspaces/Core/Portable/EmbeddedLanguages/Json/JsonHelpers.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Json
{
using JsonToken = EmbeddedSyntaxToken<JsonKind>;
using JsonTrivia = EmbeddedSyntaxTrivia<JsonKind>;
internal static class JsonHelpers
{
public static JsonToken CreateToken(
JsonKind kind, ImmutableArray<JsonTrivia> leadingTrivia,
ImmutableArray<VirtualChar> virtualChars, ImmutableArray<JsonTrivia> trailingTrivia)
=> CreateToken(kind, leadingTrivia, virtualChars, trailingTrivia, ImmutableArray<EmbeddedDiagnostic>.Empty);
public static JsonToken CreateToken(JsonKind kind,
ImmutableArray<JsonTrivia> leadingTrivia, ImmutableArray<VirtualChar> virtualChars,
ImmutableArray<JsonTrivia> trailingTrivia, ImmutableArray<EmbeddedDiagnostic> diagnostics)
=> new JsonToken(kind, leadingTrivia, virtualChars, trailingTrivia, diagnostics, value: null);
public static JsonToken CreateMissingToken(JsonKind kind)
=> CreateToken(kind, ImmutableArray<JsonTrivia>.Empty, ImmutableArray<VirtualChar>.Empty, ImmutableArray<JsonTrivia>.Empty);
public static JsonTrivia CreateTrivia(JsonKind kind, ImmutableArray<VirtualChar> virtualChars)
=> CreateTrivia(kind, virtualChars, ImmutableArray<EmbeddedDiagnostic>.Empty);
public static JsonTrivia CreateTrivia(JsonKind kind, ImmutableArray<VirtualChar> virtualChars, ImmutableArray<EmbeddedDiagnostic> diagnostics)
=> new JsonTrivia(kind, virtualChars, diagnostics);
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
using Microsoft.CodeAnalysis.EmbeddedLanguages.Common;
using Microsoft.CodeAnalysis.EmbeddedLanguages.VirtualChars;
namespace Microsoft.CodeAnalysis.EmbeddedLanguages.Json
{
using JsonToken = EmbeddedSyntaxToken<JsonKind>;
using JsonTrivia = EmbeddedSyntaxTrivia<JsonKind>;
internal static class JsonHelpers
{
public static JsonToken CreateToken(JsonKind kind, ImmutableArray<JsonTrivia> leadingTrivia, ImmutableArray<VirtualChar> virtualChars, ImmutableArray<JsonTrivia> trailingTrivia)
=> CreateToken(kind, leadingTrivia, virtualChars, trailingTrivia, ImmutableArray<EmbeddedDiagnostic>.Empty);
public static JsonToken CreateToken(JsonKind kind,
ImmutableArray<JsonTrivia> leadingTrivia, ImmutableArray<VirtualChar> virtualChars,
ImmutableArray<JsonTrivia> trailingTrivia, ImmutableArray<EmbeddedDiagnostic> diagnostics)
=> new JsonToken(kind, leadingTrivia, virtualChars, trailingTrivia, diagnostics, value: null);
public static JsonToken CreateMissingToken(JsonKind kind)
=> CreateToken(kind, ImmutableArray<JsonTrivia>.Empty, ImmutableArray<VirtualChar>.Empty, ImmutableArray<JsonTrivia>.Empty);
public static JsonTrivia CreateTrivia(JsonKind kind, ImmutableArray<VirtualChar> virtualChars)
=> CreateTrivia(kind, virtualChars, ImmutableArray<EmbeddedDiagnostic>.Empty);
public static JsonTrivia CreateTrivia(JsonKind kind, ImmutableArray<VirtualChar> virtualChars, ImmutableArray<EmbeddedDiagnostic> diagnostics)
=> new JsonTrivia(kind, virtualChars, diagnostics);
}
}
| mit | C# |
4c59750e00e2ca780483d6a8ca964c9716d9d9c9 | Make default value of SignedPetitions as array. | enarod/enarod-web-api,enarod/enarod-web-api,enarod/enarod-web-api | Infopulse.EDemocracy.Model/BusinessEntities/UserDetailInfo.cs | Infopulse.EDemocracy.Model/BusinessEntities/UserDetailInfo.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Infopulse.EDemocracy.Model.BusinessEntities
{
public class UserDetailInfo : BaseEntity
{
[JsonIgnore]
public int UserID { get; set; }
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
public string ZipCode { get; set; }
[Required]
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[Required]
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
[JsonIgnore]
public string CreatedBy { get; set; }
[JsonIgnore]
public DateTime CreatedDate { get; set; }
[JsonIgnore]
public string ModifiedBy { get; set; }
[JsonIgnore]
public DateTime? ModifiedDate { get; set; }
public User User { get; set; }
public List<Petition> CreatedPetitions { get; set; }
public List<Petition> SignedPetitions { get; set; }
public UserDetailInfo()
{
this.CreatedPetitions = new List<Petition>();
this.SignedPetitions = new List<Petition>();
}
}
}
| using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace Infopulse.EDemocracy.Model.BusinessEntities
{
public class UserDetailInfo : BaseEntity
{
[JsonIgnore]
public int UserID { get; set; }
[Required]
public string FirstName { get; set; }
public string MiddleName { get; set; }
[Required]
public string LastName { get; set; }
public string ZipCode { get; set; }
[Required]
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
[Required]
public string City { get; set; }
public string Region { get; set; }
public string Country { get; set; }
[JsonIgnore]
public string CreatedBy { get; set; }
[JsonIgnore]
public DateTime CreatedDate { get; set; }
[JsonIgnore]
public string ModifiedBy { get; set; }
[JsonIgnore]
public DateTime? ModifiedDate { get; set; }
public User User { get; set; }
public List<Petition> CreatedPetitions { get; set; }
public List<Petition> SignedPetitions { get; set; }
public UserDetailInfo()
{
this.CreatedPetitions = new List<Petition>();
}
}
}
| cc0-1.0 | C# |
8dd2b259ee42d40338f8fc8669ce0cd0ca398531 | Add missing error categories | libgit2/libgit2sharp,red-gate/libgit2sharp,AMSadek/libgit2sharp,red-gate/libgit2sharp,AMSadek/libgit2sharp,Zoxive/libgit2sharp,Zoxive/libgit2sharp,PKRoma/libgit2sharp | LibGit2Sharp/Core/GitErrorCategory.cs | LibGit2Sharp/Core/GitErrorCategory.cs | namespace LibGit2Sharp.Core
{
internal enum GitErrorCategory
{
Unknown = -1,
None,
NoMemory,
Os,
Invalid,
Reference,
Zlib,
Repository,
Config,
Regex,
Odb,
Index,
Object,
Net,
Tag,
Tree,
Indexer,
Ssl,
Submodule,
Thread,
Stash,
Checkout,
FetchHead,
Merge,
Ssh,
Filter,
Revert,
Callback,
CherryPick,
Describe,
Rebase,
Filesystem,
}
}
| namespace LibGit2Sharp.Core
{
internal enum GitErrorCategory
{
Unknown = -1,
None,
NoMemory,
Os,
Invalid,
Reference,
Zlib,
Repository,
Config,
Regex,
Odb,
Index,
Object,
Net,
Tag,
Tree,
Indexer,
Ssl,
Submodule,
Thread,
Stash,
Checkout,
FetchHead,
Merge,
Ssh,
Filter,
Revert,
Callback,
}
}
| mit | C# |
1f6acc6d5197ecc3a9b0195e4f9237ea71d596f4 | Update assembly informational version | roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon,roman-yagodin/R7.Epsilon | R7.Epsilon/Properties/AssemblyInfo.cs | R7.Epsilon/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("R7.Epsilon")]
[assembly: AssemblyDescription ("Responsive skin for DNN Platform")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("R7.Labs")]
[assembly: AssemblyProduct ("R7.Epsilon")]
[assembly: AssemblyCopyright ("")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.14.0.*")]
[assembly: AssemblyInformationalVersion ("1.14")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("R7.Epsilon")]
[assembly: AssemblyDescription ("Responsive skin for DNN Platform")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("R7.Labs")]
[assembly: AssemblyProduct ("R7.Epsilon")]
[assembly: AssemblyCopyright ("")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("1.14.0.*")]
[assembly: AssemblyInformationalVersion ("1.14.0-rc.1")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| agpl-3.0 | C# |
ef5b6b8d4c98e9bb154a8b237d6d232e5d558d0e | Write out the r4mvc.generated.cs file when running on coreclr | T4MVC/R4MVC,wwwlicious/R4MVC,artiomchi/R4MVC,wwwlicious/R4MVC,artiomchi/R4MVC,wwwlicious/R4MVC | src/R4Mvc/R4MVCCompilerModule.cs | src/R4Mvc/R4MVCCompilerModule.cs | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime;
using Microsoft.Framework.Runtime.Roslyn;
using R4Mvc.Extensions;
using R4Mvc.Ioc;
using R4Mvc.Locators;
namespace R4Mvc
{
public class R4MVCCompilerModule : ICompileModule
{
private readonly IServiceProvider _serviceProvider;
public ICollection<IViewLocator> ViewLocators { get; }
public ICollection<IStaticFileLocator> StaticFileLocators { get; }
public static bool filesGenerated;
private readonly DefaultRazorViewLocator _defaultRazorViewLocator = new DefaultRazorViewLocator();
private readonly DefaultStaticFileLocator _defaultStaticFileLocator = new DefaultStaticFileLocator();
public R4MVCCompilerModule(IServiceProvider serviceProvider)
{
ViewLocators = new Collection<IViewLocator>();
StaticFileLocators = new Collection<IStaticFileLocator>();
RegisterDefaultLocators();
RegisterCustomLocators();
_serviceProvider = IocConfig.RegisterServices(ViewLocators, StaticFileLocators);
}
public void BeforeCompile(IBeforeCompileContext context)
{
if (filesGenerated) return; // prevents generation running twice after compilation is modified the first time
//Debugger.Launch();
var project = ((CompilationContext)(context)).Project;
// HACK to make project available to default view
_defaultRazorViewLocator.ProjectDelegate = () => project;
_defaultStaticFileLocator.ProjectDelegate = () => project;
// generate r4mvc syntaxtree
var generator = _serviceProvider.GetService<R4MvcGenerator>();
var generatedNode = generator.Generate((CompilationContext)context);
// out to file
var generatedFilePath = Path.Combine(project.ProjectDirectory, R4MvcGenerator.R4MvcFileName);
generatedNode.WriteFile(generatedFilePath);
// update compilation
context.CSharpCompilation.AddSyntaxTrees(generatedNode.SyntaxTree);
filesGenerated = true;
}
public void AfterCompile(IAfterCompileContext context)
{
}
public virtual void RegisterCustomLocators() { }
private void RegisterDefaultLocators()
{
ViewLocators.Add(_defaultRazorViewLocator);
StaticFileLocators.Add(_defaultStaticFileLocator);
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.Runtime;
using Microsoft.Framework.Runtime.Roslyn;
using R4Mvc.Extensions;
using R4Mvc.Ioc;
using R4Mvc.Locators;
namespace R4Mvc
{
public class R4MVCCompilerModule : ICompileModule
{
private readonly IServiceProvider _serviceProvider;
public ICollection<IViewLocator> ViewLocators { get; }
public ICollection<IStaticFileLocator> StaticFileLocators { get; }
public static bool filesGenerated;
private readonly DefaultRazorViewLocator _defaultRazorViewLocator = new DefaultRazorViewLocator();
private readonly DefaultStaticFileLocator _defaultStaticFileLocator = new DefaultStaticFileLocator();
public R4MVCCompilerModule(IServiceProvider serviceProvider)
{
ViewLocators = new Collection<IViewLocator>();
StaticFileLocators = new Collection<IStaticFileLocator>();
RegisterDefaultLocators();
RegisterCustomLocators();
_serviceProvider = IocConfig.RegisterServices(ViewLocators, StaticFileLocators);
}
public void BeforeCompile(IBeforeCompileContext context)
{
#if !ASPNETCORE50
if (filesGenerated) return; // prevents generation running twice after compilation is modified the first time
//Debugger.Launch();
var project = ((CompilationContext)(context)).Project;
// HACK to make project available to default view
_defaultRazorViewLocator.ProjectDelegate = () => project;
_defaultStaticFileLocator.ProjectDelegate = () => project;
// generate r4mvc syntaxtree
var generator = _serviceProvider.GetService<R4MvcGenerator>();
var generatedNode = generator.Generate((CompilationContext)context);
// out to file
var generatedFilePath = Path.Combine(project.ProjectDirectory, R4MvcGenerator.R4MvcFileName);
generatedNode.WriteFile(generatedFilePath);
// update compilation
context.CSharpCompilation.AddSyntaxTrees(generatedNode.SyntaxTree);
filesGenerated = true;
#endif
}
public void AfterCompile(IAfterCompileContext context)
{
}
public virtual void RegisterCustomLocators() { }
private void RegisterDefaultLocators()
{
ViewLocators.Add(_defaultRazorViewLocator);
StaticFileLocators.Add(_defaultStaticFileLocator);
}
}
} | apache-2.0 | C# |
93d84484046548a6c76006f83fb8552ed285ec51 | Update CubicNoise_Unity.cs | jobtalle/CubicNoise,jobtalle/CubicNoise,jobtalle/CubicNoise,jobtalle/CubicNoise,jobtalle/CubicNoise,jobtalle/CubicNoise | c#/CubicNoise_Unity.cs | c#/CubicNoise_Unity.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public sealed class CubicNoise
{
private static readonly int RND_A = 134775813;
private static readonly int RND_B = 1103515245;
private int seed;
private int octave;
private int periodx = int.MaxValue;
private int periody = int.MaxValue;
public CubicNoise(int seed, int octave, int periodx, int periody)
{
this.seed = seed;
this.octave = octave;
this.periodx = periodx;
this.periody = periody;
}
public CubicNoise(int seed, int octave)
{
this.seed = seed;
this.octave = octave;
}
public float sample(float x)
{
int xi = (int)Mathf.Floor(x / octave);
float lerp = x / octave - xi;
return interpolate(
randomize(seed, tile(xi - 1, periodx), 0),
randomize(seed, tile(xi, periodx), 0),
randomize(seed, tile(xi + 1, periodx), 0),
randomize(seed, tile(xi + 2, periodx), 0),
lerp) * 0.666666f + 0.166666f;
}
public float sample(float x, float y)
{
int xi = (int)Mathf.Floor(x / octave);
float lerpx = x / octave - xi;
int yi = (int)Mathf.Floor(y / octave);
float lerpy = y / octave - yi;
float[] xSamples = new float[4];
for (int i = 0; i < 4; ++i)
xSamples[i] = interpolate(
randomize(seed, tile(xi - 1, periodx), tile(yi - 1 + i, periody)),
randomize(seed, tile(xi, periodx), tile(yi - 1 + i, periody)),
randomize(seed, tile(xi + 1, periodx), tile(yi - 1 + i, periody)),
randomize(seed, tile(xi + 2, periodx), tile(yi - 1 + i, periody)),
lerpx);
return interpolate(xSamples[0], xSamples[1], xSamples[2], xSamples[3], lerpy) * 0.5f + 0.25f;
}
private static float randomize(int seed, int x, int y)
{
return (float)((((x ^ y) * RND_A) ^ (seed + x)) * (((RND_B * x) << 16) ^ (RND_B * y) - RND_A)) / int.MaxValue;
}
private static int tile(int coordinate, int period)
{
return coordinate % period;
}
private static float interpolate(float a, float b, float c, float d, float x)
{
float p = (d - c) - (a - b);
return x * (x * (x * p + ((a - b) - p)) + (c - a)) + b;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public sealed class CubicNoise
{
private static readonly int RND_A = 134775813;
private static readonly int RND_B = 1103515245;
private int seed;
private int octave;
private int periodx = int.MaxValue;
private int periody = int.MaxValue;
public CubicNoise(int seed, int octave, int periodx, int periody)
{
this.seed = seed;
this.octave = octave;
this.periodx = periodx;
this.periody = periody;
}
public CubicNoise(int seed, int octave)
{
this.seed = seed;
this.octave = octave;
}
public float sample(float x)
{
int xi = (int)Mathf.Floor(x / octave);
float lerp = x / octave - xi;
return interpolate(
randomize(seed, tile(xi - 1, periodx), 0),
randomize(seed, tile(xi, periodx), 0),
randomize(seed, tile(xi + 1, periodx), 0),
randomize(seed, tile(xi + 2, periodx), 0),
lerp) * 0.5f + 0.25f;
}
public float sample(float x, float y)
{
int xi = (int)Mathf.Floor(x / octave);
float lerpx = x / octave - xi;
int yi = (int)Mathf.Floor(y / octave);
float lerpy = y / octave - yi;
float[] xSamples = new float[4];
for (int i = 0; i < 4; ++i)
xSamples[i] = interpolate(
randomize(seed, tile(xi - 1, periodx), tile(yi - 1 + i, periody)),
randomize(seed, tile(xi, periodx), tile(yi - 1 + i, periody)),
randomize(seed, tile(xi + 1, periodx), tile(yi - 1 + i, periody)),
randomize(seed, tile(xi + 2, periodx), tile(yi - 1 + i, periody)),
lerpx);
return interpolate(xSamples[0], xSamples[1], xSamples[2], xSamples[3], lerpy) * 0.5f + 0.25f;
}
private static float randomize(int seed, int x, int y)
{
return (float)((((x ^ y) * RND_A) ^ (seed + x)) * (((RND_B * x) << 16) ^ (RND_B * y) - RND_A)) / int.MaxValue;
}
private static int tile(int coordinate, int period)
{
return coordinate % period;
}
private static float interpolate(float a, float b, float c, float d, float x)
{
float p = (d - c) - (a - b);
return x * (x * (x * p + ((a - b) - p)) + (c - a)) + b;
}
}
| unlicense | C# |
93f9d1549e6d3f7c854b23530f4063c019ed0e8b | Revert "Bump version" | o11c/WebMConverter,Yuisbean/WebMConverter,nixxquality/WebMConverter | Properties/AssemblyInfo.cs | 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.7.2")]
| 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("WebM for Retards")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebM for Retards")]
[assembly: AssemblyCopyright("Copyright © 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("88d1c5f0-e3e0-445a-8e11-a02441ab6ca8")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.7.3")]
| mit | C# |
c5b2e78112efabb67facc5cfaf5695c8a118ee37 | fix paren | ucdavis/Namster,ucdavis/Namster,ucdavis/Namster | src/Namster/Services/SearchService.cs | src/Namster/Services/SearchService.cs | using System;
using System.Threading.Tasks;
using Microsoft.Azure;
using Namster.Models;
using Nest;
namespace Namster.Services
{
public interface ISearchService
{
Task<ISearchResponse<DataNam>> FindByMatchAsync(string term, int size);
}
public class SearchService : ISearchService
{
private static readonly Uri ConnectionString = new Uri(CloudConfigurationManager.GetSetting("ElasticSearchUrl"));
private static readonly string IndexName = CloudConfigurationManager.GetSetting("SearchIndexName");
private readonly ElasticClient _client;
private readonly Action<HighlightDescriptor<DataNam>> _highlightDescription =
h =>
h.OnFields(
f => f.OnField(x => x.Building).PreTags("<mark>").PostTags("</mark>"),
f => f.OnField(x => x.Room).PreTags("<mark>").PostTags("</mark>"),
f => f.OnField(x => x.Department).PreTags("<mark>").PostTags("</mark>"),
f => f.OnField(x => x.Division).PreTags("<mark>").PostTags("</mark>"));
public SearchService()
{
var settings = new ConnectionSettings(ConnectionString, IndexName);
_client = new ElasticClient(settings);
}
public async Task<ISearchResponse<DataNam>> FindByMatchAsync(string term, int size)
{
var baseSearch =
Query<DataNam>.MultiMatch(
m =>
m.OnFields(f => f.NamNumber, f => f.Building, f => f.Room,
f => f.Department, f => f.Division).Query(term));
return
await
_client.SearchAsync<DataNam>(
s =>
s.Size(size)
.Query(baseSearch)
.Highlight(_highlightDescription));
}
}
}
| using System;
using System.Threading.Tasks;
using Microsoft.Azure;
using Namster.Models;
using Nest;
namespace Namster.Services
{
public interface ISearchService
{
Task<ISearchResponse<DataNam>> FindByMatchAsync(string term, int size);
}
public class SearchService : ISearchService
{
private static readonly Uri ConnectionString = new Uri(CloudConfigurationManager.GetSetting("ElasticSearchUrl");
private static readonly string IndexName = CloudConfigurationManager.GetSetting("SearchIndexName");
private readonly ElasticClient _client;
private readonly Action<HighlightDescriptor<DataNam>> _highlightDescription =
h =>
h.OnFields(
f => f.OnField(x => x.Building).PreTags("<mark>").PostTags("</mark>"),
f => f.OnField(x => x.Room).PreTags("<mark>").PostTags("</mark>"),
f => f.OnField(x => x.Department).PreTags("<mark>").PostTags("</mark>"),
f => f.OnField(x => x.Division).PreTags("<mark>").PostTags("</mark>"));
public SearchService()
{
var settings = new ConnectionSettings(ConnectionString, IndexName);
_client = new ElasticClient(settings);
}
public async Task<ISearchResponse<DataNam>> FindByMatchAsync(string term, int size)
{
var baseSearch =
Query<DataNam>.MultiMatch(
m =>
m.OnFields(f => f.NamNumber, f => f.Building, f => f.Room,
f => f.Department, f => f.Division).Query(term));
return
await
_client.SearchAsync<DataNam>(
s =>
s.Size(size)
.Query(baseSearch)
.Highlight(_highlightDescription));
}
}
}
| mit | C# |
77d81624a1ac60e3881fb3a5561468ef01264718 | fix consts | timiles/DependencyMap,timiles/DependencyMap,timiles/DependencyMap | Sample/WebView.DataUpdater/Program.cs | Sample/WebView.DataUpdater/Program.cs | using System.Diagnostics;
using System.IO;
using System.Linq;
using DependencyMap.Analysis;
using DependencyMap.Scanning;
using DependencyMap.SourceRepositories;
using Newtonsoft.Json;
namespace WebView.DataUpdater
{
class Program
{
static void Main(string[] args)
{
const string webViewDir = "../../../WebView/";
const string outputPath = webViewDir + "data.js";
const string sourceDir = "../../../DummySourceRepository/";
var repository = new FileSystemSourceRepository("packages.config", new [] { sourceDir });
var packageConfigs = repository.GetDependencyFiles();
var scanner = new NuGetPackageConfigScanner();
var serviceDependencies = scanner.GetAllServiceDependencies(packageConfigs);
// filter our dependencies if we like
var nonTestServiceDependencies = serviceDependencies.Where(x => !x.DependencyFilePath.Contains(".Tests"));
var analyser = new ServiceDependenciesAnalyser(nonTestServiceDependencies.ToList());
var dependencies = SerializeObjectToJson(analyser.GetAllDependencies());
var services = SerializeObjectToJson(analyser.GetAllServices());
File.WriteAllText(outputPath, $"g_dependencies = {dependencies};\r\ng_services = {services};");
Process.Start("chrome", webViewDir + "dependencies.html");
Process.Start("chrome", webViewDir + "services.html");
}
private static string SerializeObjectToJson(object value)
{
return JsonConvert.SerializeObject(value, Formatting.Indented, new SemanticVersionConverter());
}
}
}
| using System.Diagnostics;
using System.IO;
using System.Linq;
using DependencyMap.Analysis;
using DependencyMap.Scanning;
using DependencyMap.SourceRepositories;
using Newtonsoft.Json;
namespace WebView.DataUpdater
{
class Program
{
static void Main(string[] args)
{
var sourceDir = "../../../DummySourceRepository/";
var webViewDir = "../../../WebView/";
var outputPath = webViewDir + "data.js";
var repository = new FileSystemSourceRepository("packages.config", new [] { sourceDir });
var packageConfigs = repository.GetDependencyFiles();
var scanner = new NuGetPackageConfigScanner();
var serviceDependencies = scanner.GetAllServiceDependencies(packageConfigs);
// filter our dependencies if we like
var nonTestServiceDependencies = serviceDependencies.Where(x => !x.DependencyFilePath.Contains(".Tests"));
var analyser = new ServiceDependenciesAnalyser(nonTestServiceDependencies.ToList());
var dependencies = SerializeObjectToJson(analyser.GetAllDependencies());
var services = SerializeObjectToJson(analyser.GetAllServices());
File.WriteAllText(outputPath, $"g_dependencies = {dependencies};\r\ng_services = {services};");
Process.Start("chrome", webViewDir + "dependencies.html");
Process.Start("chrome", webViewDir + "services.html");
}
private static string SerializeObjectToJson(object value)
{
return JsonConvert.SerializeObject(value, Formatting.Indented, new SemanticVersionConverter());
}
}
}
| mit | C# |
e2d27083415d2e30ac25bec1ae1440c7d3ac666e | Update tests with new specifications of Mapping | rcdmk/EntityFramework.Extended | Source/Samples/net45/Tracker.SqlServer.Test/MappingObjectContext.cs | Source/Samples/net45/Tracker.SqlServer.Test/MappingObjectContext.cs | using System;
using EntityFramework.Mapping;
using Xunit;
using Tracker.SqlServer.CodeFirst;
using Tracker.SqlServer.CodeFirst.Entities;
using Tracker.SqlServer.Entities;
using EntityFramework.Extensions;
using Task = Tracker.SqlServer.Entities.Task;
namespace Tracker.SqlServer.Test
{
/// <summary>
/// Summary description for MappingObjectContext
/// </summary>
public class MappingObjectContext
{
[Fact]
public void GetEntityMapTask()
{
//var db = new TrackerEntities();
//var metadata = db.MetadataWorkspace;
//var map = db.Tasks.GetEntityMap<Task>();
//Assert.Equal("[dbo].[Task]", map.TableName);
}
[Fact]
public void GetEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(AuditData), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("Audit", map.TableName);
Assert.Equal("dbo", map.SchemaName);
}
[Fact]
public void GetInheritedEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(CodeFirst.Entities.Task), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("Task", map.TableName);
Assert.Equal("dbo", map.SchemaName);
}
}
}
| using System;
using EntityFramework.Mapping;
using Xunit;
using Tracker.SqlServer.CodeFirst;
using Tracker.SqlServer.CodeFirst.Entities;
using Tracker.SqlServer.Entities;
using EntityFramework.Extensions;
using Task = Tracker.SqlServer.Entities.Task;
namespace Tracker.SqlServer.Test
{
/// <summary>
/// Summary description for MappingObjectContext
/// </summary>
public class MappingObjectContext
{
[Fact]
public void GetEntityMapTask()
{
//var db = new TrackerEntities();
//var metadata = db.MetadataWorkspace;
//var map = db.Tasks.GetEntityMap<Task>();
//Assert.Equal("[dbo].[Task]", map.TableName);
}
[Fact]
public void GetEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(AuditData), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("[dbo].[Audit]", map.TableName);
}
[Fact]
public void GetInheritedEntityMapAuditData()
{
var db = new TrackerContext();
var resolver = new MetadataMappingProvider();
var map = resolver.GetEntityMap(typeof(CodeFirst.Entities.Task), db);
//var map = db.Audits.ToObjectQuery().GetEntityMap<AuditData>();
Assert.Equal("[dbo].[Task]", map.TableName);
}
}
}
| bsd-3-clause | C# |
769eaed104584b3c5793188cf6494dcca3b21b5a | remove 'info' config fields (expanded info added to readme). | Pathoschild/StardewMods | TractorMod/Framework/TractorConfig.cs | TractorMod/Framework/TractorConfig.cs | using Microsoft.Xna.Framework.Input;
namespace TractorMod.Framework
{
/// <summary>The mod configuration model.</summary>
internal class TractorConfig
{
/*********
** Accessors
*********/
/// <summary>The enabled tools.</summary>
public ToolConfig[] Tool { get; set; } = {
new ToolConfig("Scythe", 0, 2),
new ToolConfig("Hoe"),
new ToolConfig("Watering Can")
};
/// <summary>The number of tiles on each side of the tractor to affect (in addition to the tile under it).</summary>
public int ItemRadius { get; set; } = 1;
/// <summary>The button which summons the tractor to your position.</summary>
public Keys TractorKey { get; set; } = Keys.B;
/// <summary>The speed modifier when riding the tractor.</summary>
public int TractorSpeed { get; set; } = -2;
/// <summary>The button which calls to buy a tractor garage.</summary>
public Keys PhoneKey { get; set; } = Keys.N;
/// <summary>The gold price to buy a tractor garage.</summary>
public int TractorHousePrice { get; set; } = 150000;
/// <summary>The button which reloads the mod configuration.</summary>
public Keys UpdateConfig { get; set; } = Keys.P;
}
}
| using Microsoft.Xna.Framework.Input;
namespace TractorMod.Framework
{
/// <summary>The mod configuration model.</summary>
internal class TractorConfig
{
/*********
** Accessors
*********/
public string Info1 = "Add tool with exact name you would like to use with Tractor Mode.";
public string Info2 = "Also custom minLevel and effective radius for each tool.";
public string Info3 = "Ingame tools included: Pickaxe, Axe, Hoe, Watering Can.";
public string Info4 = "I haven't tried tools like Shears or Milk Pail but you can :)";
public string Info5 = "Delete Scythe entry if you don't want to harvest stuff.";
/// <summary>The enabled tools.</summary>
public ToolConfig[] Tool { get; set; } = {
new ToolConfig("Scythe", 0, 2, 1),
new ToolConfig("Hoe"),
new ToolConfig("Watering Can")
};
/// <summary>The number of tiles on each side of the tractor to affect (in addition to the tile under it).</summary>
public int ItemRadius { get; set; } = 1;
/// <summary>The button which summons the tractor to your position.</summary>
public Keys TractorKey { get; set; } = Keys.B;
/// <summary>The speed modifier when riding the tractor.</summary>
public int TractorSpeed { get; set; } = -2;
/// <summary>The button which calls to buy a tractor garage.</summary>
public Keys PhoneKey { get; set; } = Keys.N;
/// <summary>The gold price to buy a tractor garage.</summary>
public int TractorHousePrice { get; set; } = 150000;
/// <summary>The button which reloads the mod configuration.</summary>
public Keys UpdateConfig { get; set; } = Keys.P;
}
}
| mit | C# |
bbd7c483681587696df8f3d4c986825c9c8bd068 | Fix a comment | DotNetKit/DotNetKit.Wpf.Printing | DotNetKit.Wpf.Printing/Windows/Documents/Paginators/IPaginator.cs | DotNetKit.Wpf.Printing/Windows/Documents/Paginators/IPaginator.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace DotNetKit.Windows.Documents
{
/// <summary>
/// Represents a function to paginate a printable.
/// </summary>
public interface IPaginator<in TPrintable>
{
/// <summary>
/// Paginates the printable into pages.
/// </summary>
IEnumerable Paginate(TPrintable printable, Size pageSize);
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
namespace DotNetKit.Windows.Documents
{
/// <summary>
/// Provides <see cref="Paginate(Size)"/>.
/// </summary>
public interface IPaginator<in TPrintable>
{
/// <summary>
/// Paginates the printable into pages.
/// </summary>
IEnumerable Paginate(TPrintable printable, Size pageSize);
}
}
| mit | C# |
ed9fe0ad317f17c09c04a136543bdf01e63fd221 | Remove in-code resharper disable statement | NeerajW/HoloToolkit-Unity,paseb/MixedRealityToolkit-Unity,out-of-pixel/HoloToolkit-Unity,HattMarris1/HoloToolkit-Unity,paseb/HoloToolkit-Unity,willcong/HoloToolkit-Unity,ForrestTrepte/HoloToolkit-Unity | Assets/HoloToolkit/Utilities/Scripts/CameraCache.cs | Assets/HoloToolkit/Utilities/Scripts/CameraCache.cs | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main
/// executes a FindByTag on the scene, which will get worse and worse with more tagged objects.
/// </summary>
public static class CameraCache
{
private static Camera cachedCamera;
/// <summary>
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
/// </summary>
public static Camera Main
{
get
{
if (cachedCamera == null)
{
return Refresh(Camera.main);
}
return cachedCamera;
}
}
/// <summary>
/// Set the cached camera to a new reference and return it
/// </summary>
/// <param name="newMain">New main camera to cache</param>
public static Camera Refresh(Camera newMain)
{
return cachedCamera = newMain;
}
}
}
| // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEngine;
namespace HoloToolkit.Unity
{
/// <summary>
/// The purpose of this class is to provide a cached reference to the main camera. Calling Camera.main
/// executes a FindByTag on the scene, which will get worse and worse with more tagged objects.
/// </summary>
public static class CameraCache
{
private static Camera cachedCamera;
/// <summary>
/// Returns a cached reference to the main camera and uses Camera.main if it hasn't been cached yet.
/// </summary>
public static Camera Main
{
get
{
// ReSharper disable once ConvertIfStatementToReturnStatement
if (cachedCamera == null)
{
return Refresh(Camera.main);
}
return cachedCamera;
}
}
/// <summary>
/// Set the cached camera to a new reference and return it
/// </summary>
/// <param name="newMain">New main camera to cache</param>
public static Camera Refresh(Camera newMain)
{
return cachedCamera = newMain;
}
}
}
| mit | C# |
0090efd702e5eee71a9509316d42edf09db10311 | remove UWP extension method | MeilCli/CrossFormattedText | Source/Plugin.CrossFormattedText.UWP/SpannableStringExtensions.cs | Source/Plugin.CrossFormattedText.UWP/SpannableStringExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Plugin.CrossFormattedText.Abstractions;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
namespace Plugin.CrossFormattedText {
public static class SpannableStringExtensions {
public static List<Inline> Span(this ISpannableString spannableString) {
if(spannableString is SpannableString) {
return (spannableString as SpannableString).Text;
}
throw new NotSupportedException();
}
public static void SetTo(this ISpannableString spannableString,TextBlock textBlock) {
textBlock.Inlines.Clear();
foreach(var span in spannableString.Span()) {
textBlock.Inlines.Add(span);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Plugin.CrossFormattedText.Abstractions;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Documents;
namespace Plugin.CrossFormattedText {
public static class SpannableStringExtensions {
public static List<Inline> Span(this ISpannableString spannableString) {
if(spannableString is SpannableString) {
return (spannableString as SpannableString).Text;
}
throw new NotSupportedException();
}
public static void SetTo(this ISpannableString spannableString,TextBlock textBlock) {
textBlock.Inlines.Clear();
foreach(var span in spannableString.Span()) {
textBlock.Inlines.Add(span);
}
}
public static void SetTo(this ISpannableString spannableString,Paragraph paragraph) {
paragraph.Inlines.Clear();
foreach(var span in spannableString.Span()) {
paragraph.Inlines.Add(span);
}
}
}
}
| mit | C# |
1dae2b3f588d05a4cf13d05bff1f74c4693db32d | Change Jit_GenericsMethod benchmark to reproduce on x64 both Legacy & RuyJit | Ky7m/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,redknightlois/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,ig-sinicyn/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,Ky7m/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,alinasmirnova/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet,Teknikaali/BenchmarkDotNet,redknightlois/BenchmarkDotNet,redknightlois/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,adamsitnik/BenchmarkDotNet,Ky7m/BenchmarkDotNet,Ky7m/BenchmarkDotNet,PerfDotNet/BenchmarkDotNet | BenchmarkDotNet.Samples/JIT/Jit_GenericsMethod.cs | BenchmarkDotNet.Samples/JIT/Jit_GenericsMethod.cs | using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Tasks;
namespace BenchmarkDotNet.Samples.JIT
{
// See: https://alexandrnikitin.github.io/blog/dotnet-generics-under-the-hood/
[BenchmarkTask(platform: BenchmarkPlatform.X86, jitVersion: BenchmarkJitVersion.LegacyJit)]
[BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.LegacyJit)]
[BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)]
public class Jit_GenericsMethod
{
private class BaseClass<T>
{
private List<T> list = new List<T>();
public BaseClass()
{
foreach (var _ in list) { }
}
public void Run()
{
for (var i = 0; i < 11; i++)
if (list.Any(_ => true))
return;
}
}
private class DerivedClass : BaseClass<object>
{
}
private BaseClass<object> baseClass = new BaseClass<object>();
private BaseClass<object> derivedClass = new DerivedClass();
[Benchmark]
public void Base()
{
baseClass.Run();
}
[Benchmark]
public void Derived()
{
derivedClass.Run();
}
}
} | using System.Collections.Generic;
using System.Linq;
using BenchmarkDotNet.Tasks;
namespace BenchmarkDotNet.Samples.JIT
{
// See: https://alexandrnikitin.github.io/blog/dotnet-generics-under-the-hood/
[BenchmarkTask(platform: BenchmarkPlatform.X86, jitVersion: BenchmarkJitVersion.LegacyJit)]
[BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.LegacyJit)]
[BenchmarkTask(platform: BenchmarkPlatform.X64, jitVersion: BenchmarkJitVersion.RyuJit)]
public class Jit_GenericsMethod
{
private class BaseClass<T>
{
private List<T> list = new List<T>();
public BaseClass()
{
Enumerable.Empty<T>();
}
public void Run()
{
for (var i = 0; i < 11; i++)
if (list.Any())
return;
}
}
private class DerivedClass : BaseClass<object>
{
}
private BaseClass<object> baseClass = new BaseClass<object>();
private BaseClass<object> derivedClass = new DerivedClass();
[Benchmark]
public void Base()
{
baseClass.Run();
}
[Benchmark]
public void Derived()
{
derivedClass.Run();
}
}
} | mit | C# |
20f9e5e4611cc5b38505def9d532553f1f9753af | Fix warning. | JohanLarsson/Gu.Wpf.ToolTips | Gu.Wpf.ToolTips.UiTests/Images/ScriptAttribute.cs | Gu.Wpf.ToolTips.UiTests/Images/ScriptAttribute.cs | namespace Gu.Wpf.ToolTips.UiTests
{
using NUnit.Framework;
[System.Diagnostics.Conditional("DEBUG")]
public sealed class ScriptAttribute : TestAttribute
{
}
}
| namespace Gu.Wpf.ToolTips.UiTests
{
using NUnit.Framework;
[System.Diagnostics.Conditional("DEBUG")]
public class ScriptAttribute : TestAttribute
{
}
}
| mit | C# |
7e3878deae3f86e905b7a244981bb371abc2dca7 | Increment versions | SnapMD/connectedcare-sdk,dhawalharsora/connectedcare-sdk | SnapMD.ConnectedCare.Sdk/Properties/AssemblyInfo.cs | SnapMD.ConnectedCare.Sdk/Properties/AssemblyInfo.cs | // Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SnapMD.ConnectedCare.Sdk")]
[assembly: AssemblyDescription("Open-source wrapper for the REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SnapMD")]
[assembly: AssemblyProduct("Connected Care")]
[assembly: AssemblyCopyright("Copyright © 2015 SnapMD, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fc089857-9e43-41eb-b5e3-e397174f7f00")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.10.3")]
[assembly: AssemblyFileVersion("1.0.0.0")] | // Copyright 2015 SnapMD, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SnapMD.ConnectedCare.Sdk")]
[assembly: AssemblyDescription("Open-source wrapper for the REST API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("SnapMD")]
[assembly: AssemblyProduct("Connected Care")]
[assembly: AssemblyCopyright("Copyright © 2015 SnapMD, Inc.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("fc089857-9e43-41eb-b5e3-e397174f7f00")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.10.2")]
[assembly: AssemblyFileVersion("1.0.0.0")] | apache-2.0 | C# |
d245cf7a1c3aaf83059b1ac126e5546d9fbdf9dd | Implement king movement logic in NormalKingMovement.cs | totkov/ChessGameEngine | Source/Chess.Source/Movements/NormalKingMovement.cs | Source/Chess.Source/Movements/NormalKingMovement.cs | namespace Chess.Source.Movements
{
using System;
using Chess.Source.Board.Contracts;
using Chess.Source.Common;
using Chess.Source.Figures.Contracts;
using Chess.Source.Movements.Contracts;
public class NormalKingMovement : IMovement
{
public void VlidateMove(IFigure figure, IBoard board, Move move)
{
Position from = move.From;
Position to = move.To;
bool condition = (
((from.Col + 1) == to.Col) ||
((from.Col - 1) == to.Col) ||
((from.Row + 1) == to.Row) ||
((from.Row - 1) == to.Row) ||
(((from.Row + 1) == to.Row) && ((from.Col + 1) == to.Col)) ||
(((from.Row - 1) == to.Row) && ((from.Col + 1) == to.Col)) ||
(((from.Row - 1) == to.Row) && ((from.Col - 1) == to.Col)) ||
(((from.Row + 1) == to.Row) && ((from.Col - 1) == to.Col))
);
if (condition)
{
return;
}
else
{
throw new InvalidOperationException("King cannot move this way!");
}
}
}
}
| namespace Chess.Source.Movements
{
using Chess.Source.Board.Contracts;
using Chess.Source.Common;
using Chess.Source.Figures.Contracts;
using Chess.Source.Movements.Contracts;
public class NormalKingMovement : IMovement
{
public void VlidateMove(IFigure figure, IBoard board, Move move)
{
throw new System.NotImplementedException();
}
}
}
| mit | C# |
a56906b83f14787cbfdc967b3fa787433e9ea453 | Adjust collection editor to list by milestone | NitorInc/NitoriWare,Barleytree/NitoriWare,Barleytree/NitoriWare,NitorInc/NitoriWare | Assets/Editor/MicrogameCollectionEditor.cs | Assets/Editor/MicrogameCollectionEditor.cs | using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
MicrogameCollection collection;
private List<MicrogameList> microgames;
private class MicrogameList
{
public string milestoneName;
public bool show = false;
public List<string> idList;
public MicrogameList()
{
idList = new List<string>();
}
}
private void OnEnable()
{
collection = (MicrogameCollection)target;
setMicrogames();
}
void setMicrogames()
{
microgames = new List<MicrogameList>();
var collectionMicrogames = collection.microgames;
var milestoneNames = Enum.GetNames(typeof(MicrogameTraits.Milestone));
for (int i = milestoneNames.Length - 1; i >= 0; i--)
{
var milestoneMicrogames = collectionMicrogames.Where(a => (int)a.difficultyTraits[0].milestone == i);
var newList = new MicrogameList();
newList.milestoneName = milestoneNames[i];
foreach (var milestoneMicrogame in milestoneMicrogames)
{
newList.idList.Add(milestoneMicrogame.microgameId);
}
microgames.Add(newList);
}
}
public override void OnInspectorGUI()
{
if (GUILayout.Button("Update Microgames"))
{
collection.updateMicrogames();
setMicrogames();
EditorUtility.SetDirty(collection);
}
if (GUILayout.Button("Update Build Path"))
{
collection.updateBuildPath();
EditorUtility.SetDirty(collection);
}
GUILayout.Label("Indexed Microgames:");
var names = Enum.GetNames(typeof(MicrogameTraits.Milestone));
foreach (var microgameList in microgames)
{
microgameList.show = EditorGUILayout.Foldout(microgameList.show, microgameList.milestoneName);
if (microgameList.show)
{
foreach (var microgameId in microgameList.idList)
{
EditorGUILayout.LabelField(" " + microgameId);
}
}
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(MicrogameCollection))]
public class MicrogameCollectionEditor : Editor
{
public override void OnInspectorGUI()
{
MicrogameCollection collection = (MicrogameCollection)target;
if (GUILayout.Button("Update Microgames"))
{
collection.updateMicrogames();
EditorUtility.SetDirty(collection);
}
if (GUILayout.Button("Update Build Path"))
{
collection.updateBuildPath();
EditorUtility.SetDirty(collection);
}
DrawDefaultInspector();
}
}
| mit | C# |
1b44f870097bf51b378c61c3442c0e139b8babbd | fix standalone | soulgame/slua,luzexi/slua-3rd-lib,jiangzhhhh/slua,luzexi/slua-3rd-lib,soulgame/slua,soulgame/slua,yaukeywang/slua,haolly/slua_source_note,jiangzhhhh/slua,yaukeywang/slua,yaukeywang/slua,haolly/slua_source_note,soulgame/slua,haolly/slua_source_note,yaukeywang/slua,soulgame/slua,yaukeywang/slua,luzexi/slua-3rd,jiangzhhhh/slua,pangweiwei/slua,luzexi/slua-3rd,luzexi/slua-3rd-lib,pangweiwei/slua,jiangzhhhh/slua,luzexi/slua-3rd,luzexi/slua-3rd,mr-kelly/slua,Roland0511/slua,mr-kelly/slua,jiangzhhhh/slua,Roland0511/slua,haolly/slua_source_note,shrimpz/slua,luzexi/slua-3rd,luzexi/slua-3rd-lib,luzexi/slua-3rd-lib,mr-kelly/slua,shrimpz/slua,mr-kelly/slua,yaukeywang/slua,luzexi/slua-3rd,soulgame/slua,Roland0511/slua,pangweiwei/slua,haolly/slua_source_note,jiangzhhhh/slua,haolly/slua_source_note,Roland0511/slua,mr-kelly/slua,Roland0511/slua,pangweiwei/slua,mr-kelly/slua,luzexi/slua-3rd-lib,Roland0511/slua,pangweiwei/slua | Assets/Plugins/Slua_Managed/SLuaSetting.cs | Assets/Plugins/Slua_Managed/SLuaSetting.cs | // The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// 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.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if !SLUA_STANDALONE
using UnityEngine;
#endif
namespace SLua{
public enum EOL{
Native,
CRLF,
CR,
LF,
}
public class SLuaSetting
#if !SLUA_STANDALONE
: ScriptableObject
#endif
{
public EOL eol = EOL.Native;
public bool exportExtensionMethod = true;
public string UnityEngineGeneratePath = "Assets/Slua/LuaObject/";
public int debugPort=10240;
public string debugIP="0.0.0.0";
private static SLuaSetting _instance=null;
public static SLuaSetting Instance{
get{
#if !SLUA_STANDALONE
if(_instance == null){
_instance = Resources.Load<SLuaSetting>("setting");
#if UNITY_EDITOR
if(_instance == null){
_instance = SLuaSetting.CreateInstance<SLuaSetting>();
AssetDatabase.CreateAsset(_instance,"Assets/Slua/Resources/setting.asset");
}
#endif
}
#endif
return _instance;
}
}
#if UNITY_EDITOR && !SLUA_STANDALONE
[MenuItem("SLua/Setting")]
public static void Open(){
Selection.activeObject = Instance;
}
#endif
}
}
| // The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// 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.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if !SLUA_STANDALONE
using UnityEngine;
#endif
namespace SLua{
public enum EOL{
Native,
CRLF,
CR,
LF,
}
public class SLuaSetting
#if !SLUA_STANDALONE
: ScriptableObject
#endif
{
public EOL eol = EOL.Native;
public bool exportExtensionMethod = true;
public string UnityEngineGeneratePath = "Assets/Slua/LuaObject/";
public int debugPort=10240;
public string debugIP="0.0.0.0";
private static SLuaSetting _instance;
public static SLuaSetting Instance{
get{
#if !SLUA_STANDALONE
if(_instance == null){
_instance = Resources.Load<SLuaSetting>("setting");
#if UNITY_EDITOR
if(_instance == null){
_instance = SLuaSetting.CreateInstance<SLuaSetting>();
AssetDatabase.CreateAsset(_instance,"Assets/Slua/Resources/setting.asset");
}
#endif
}
#endif
return _instance;
}
}
#if UNITY_EDITOR
[MenuItem("SLua/Setting")]
public static void Open(){
Selection.activeObject = Instance;
}
#endif
}
}
| mit | C# |
d88d08532ee7259edd65d77659180430ab340da3 | fix Quit menu option. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Gui/Shell/Commands/SystemCommands.cs | WalletWasabi.Gui/Shell/Commands/SystemCommands.cs | using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using AvalonStudio.Commands;
using ReactiveUI;
using System;
using System.Composition;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class SystemCommands
{
public Global Global { get; }
[DefaultKeyGesture("ALT+F4", osxKeyGesture: "CMD+Q")]
[ExportCommandDefinition("File.Exit")]
public CommandDefinition ExitCommand { get; }
[ImportingConstructor]
public SystemCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = Guard.NotNull(nameof(Global), global.Global);
var exit = ReactiveCommand.Create(OnExit);
exit.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex));
ExitCommand = new CommandDefinition(
"Quit Wasabi Wallet",
commandIconService.GetCompletionKindImage("Exit"),
exit);
}
private void OnExit()
{
(Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow.Close();
}
}
}
| using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using AvalonStudio.Commands;
using ReactiveUI;
using System;
using System.Composition;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
namespace WalletWasabi.Gui.Shell.Commands
{
internal class SystemCommands
{
public Global Global { get; }
[DefaultKeyGesture("ALT+F4", osxKeyGesture: "CMD+Q")]
[ExportCommandDefinition("File.Exit")]
public CommandDefinition ExitCommand { get; }
[ImportingConstructor]
public SystemCommands(CommandIconService commandIconService, AvaloniaGlobalComponent global)
{
Global = Guard.NotNull(nameof(Global), global.Global);
var exit = ReactiveCommand.Create(OnExit);
exit.ThrownExceptions.Subscribe(ex => Logger.LogWarning(ex));
ExitCommand = new CommandDefinition(
"Quit WasabiWallet",
commandIconService.GetCompletionKindImage("Exit"),
exit);
}
private void OnExit()
{
(Application.Current.ApplicationLifetime as IClassicDesktopStyleApplicationLifetime).MainWindow.Close();
}
}
}
| mit | C# |
e4004e80beea1d0a38ba93083a5685203886e12f | Use coroutine for recharge | ne1ro/desperation | Assets/Scripts/Shot.cs | Assets/Scripts/Shot.cs | using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Shot : MonoBehaviour {
public float fireRate = 1.5f; // Battle fire rate is 40 per minute for single shots
public int cartridgeCount = 30;
public float chargeInterval = 3.5f;
public int distance = 1500; // Penetration distance, use 3000 for non-lethal
public AudioClip shotSound;
public AudioClip chargeSound;
public Text roundCountText;
private float nextFire;
private int roundCount;
void Start() {
nextFire = 0.0f;
roundCount = 5;
roundCountText.text = roundCount.ToString();
}
void Update() {
// Shot
if (Input.GetButton("Fire1") && Time.time > nextFire && roundCount > 0) {
nextFire = Time.time + fireRate;
roundCount --;
roundCountText.text = roundCount.ToString();
GetComponent<AudioSource>().PlayOneShot(shotSound);
if (roundCount <= 0) StartCoroutine(Recharge());
}
}
// Recharge weapon
private IEnumerator Recharge() {
GetComponent<AudioSource>().PlayOneShot(chargeSound);
yield return new WaitForSeconds(chargeInterval);
roundCount = cartridgeCount;
}
}
| using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class Shot : MonoBehaviour {
public float fireRate = 1.5f; // Battle fire rate is 40 per minute for single shots
public int cartridgeCount = 30;
public float chargeInterval = 3.5f;
public int distance = 1500; // Penetration distance, use 3000 for non-lethal
public AudioClip shotSound;
public AudioClip chargeSound;
public Text roundCountText;
private float nextFire;
private int roundCount;
void Start() {
nextFire = 0.0f;
roundCount = 5;
roundCountText.text = roundCount.ToString();
}
void Update() {
bool isCharged = roundCount > 0;
// Shot
if (Input.GetButton("Fire1") && Time.time > nextFire && isCharged) {
nextFire = Time.time + fireRate;
roundCount --;
roundCountText.text = roundCount.ToString();
GetComponent<AudioSource>().PlayOneShot(shotSound);
}
// Recharge
if (roundCount <= 0) {
roundCount = cartridgeCount;
}
}
}
| mit | C# |
daed20f1acba30d1a4603f6ed4b1528187b283eb | Update version string to 4.4.1 | NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity,NIFTYCloud-mbaas/ncmb_unity | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | ncmb_unity/Assets/NCMB/Script/CommonConstant.cs | /*******
Copyright 2017-2021 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.4.1"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| /*******
Copyright 2017-2021 FUJITSU CLOUD TECHNOLOGIES LIMITED All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
**********/
using System.Collections;
namespace NCMB.Internal
{
//通信種別
internal enum ConnectType
{
//GET通信
GET,
//POST通信
POST,
//PUT通信
PUT,
//DELETE通信
DELETE
}
/// <summary>
/// 定数を定義する共通用のクラスです
/// </summary>
internal static class CommonConstant
{
//service
public static readonly string DOMAIN = "mbaas.api.nifcloud.com";//ドメイン
public static readonly string DOMAIN_URL = "https://mbaas.api.nifcloud.com";//ドメインのURL
public static readonly string API_VERSION = "2013-09-01";//APIバージョン
public static readonly string SDK_VERSION = "4.5.0"; //SDKバージョン
//DEBUG LOG Setting: NCMBDebugにてdefine設定をしてください
}
}
| apache-2.0 | C# |
fef2581d4d854bfd0f4a232fc25e1c31fe64e3ae | Change password view reimplementation | SpaceTrafficDevelopers/SpaceTraffic,SpaceTrafficDevelopers/SpaceTraffic,SpaceTrafficDevelopers/SpaceTraffic,SpaceTrafficDevelopers/SpaceTraffic | GameUi/Views/Account/ChangePassword.cshtml | GameUi/Views/Account/ChangePassword.cshtml | @model SpaceTraffic.GameUi.Models.ChangePasswordModel
@{
ViewBag.Title = "Změna hesla";
}
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<div class="ajax" data-related-element-id="tabsContent">
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="settings_form">
<section>
<h1>Změna hesla</h1>
<p>
@Html.PasswordFor(m => m.OldPassword, new { required = "", placeholder = "Původní heslo", maxlength = "100", autofocus = "" })
@Html.ValidationMessageFor(m => m.OldPassword)
</p>
<p>
@Html.PasswordFor(m => m.NewPassword, new { required = "", placeholder = "Nové heslo", maxlength = "100" })
@Html.ValidationMessageFor(m => m.NewPassword)
</p>
<p>
@Html.PasswordFor(m => m.ConfirmPassword, new { required = "", placeholder = "Potvrdit nové heslo", maxlength = "100" })
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</p>
@Html.ValidationSummary(true)
</section>
<p class="clear">
<a href="@Url.Action("Settings", "Profile", new { Area = "Game" })" class="ajax cancel" data-related-element-id="tabsContent">Zrušit</a>
<input type="submit" value="Změnit heslo" class="ok"/>
</p>
</div>
}
</div> | @model SpaceTraffic.GameUi.Models.ChangePasswordModel
@{
ViewBag.Title = "Change Password";
}
<h2>Change Password</h2>
<p>
Use the form below to change your password.
</p>
<p>
New passwords are required to be a minimum of @Membership.MinRequiredPasswordLength characters in length.
</p>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm()) {
@Html.ValidationSummary(true, "Password change was unsuccessful. Please correct the errors and try again.")
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
@Html.LabelFor(m => m.OldPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.OldPassword)
@Html.ValidationMessageFor(m => m.OldPassword)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.NewPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.NewPassword)
@Html.ValidationMessageFor(m => m.NewPassword)
</div>
<div class="editor-label">
@Html.LabelFor(m => m.ConfirmPassword)
</div>
<div class="editor-field">
@Html.PasswordFor(m => m.ConfirmPassword)
@Html.ValidationMessageFor(m => m.ConfirmPassword)
</div>
<p>
<input type="submit" value="Change Password" />
</p>
</fieldset>
</div>
}
| apache-2.0 | C# |
99280db69487c1f0b8542031c8d6037fe875084e | Add note about AlwaysPresent requirement | peppy/osu,UselessToucan/osu,UselessToucan/osu,NeoAdonis/osu,EVAST9919/osu,smoogipoo/osu,peppy/osu-new,ppy/osu,peppy/osu,ppy/osu,2yangk23/osu,EVAST9919/osu,NeoAdonis/osu,2yangk23/osu,smoogipoo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,smoogipooo/osu,johnneijzen/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu | osu.Game/Rulesets/Mods/ModCinema.cs | osu.Game/Rulesets/Mods/ModCinema.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.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T>
where T : HitObject
{
public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset)
{
drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap));
// AlwaysPresent required for hitsounds
drawableRuleset.Playfield.AlwaysPresent = true;
drawableRuleset.Playfield.Hide();
}
}
public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer
{
public override string Name => "Cinema";
public override string Acronym => "CN";
public override IconUsage Icon => OsuIcon.ModCinema;
public override string Description => "Watch the video without visual distractions.";
public void ApplyToHUD(HUDOverlay overlay)
{
overlay.ShowHud.Value = false;
overlay.ShowHud.Disabled = true;
}
public void ApplyToPlayer(Player player)
{
player.Background.EnableUserDim.Value = false;
player.DimmableVideo.IgnoreUserSettings.Value = true;
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
}
}
}
| // 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.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Objects;
using osu.Game.Rulesets.UI;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModCinema<T> : ModCinema, IApplicableToDrawableRuleset<T>
where T : HitObject
{
public virtual void ApplyToDrawableRuleset(DrawableRuleset<T> drawableRuleset)
{
drawableRuleset.SetReplayScore(CreateReplayScore(drawableRuleset.Beatmap));
drawableRuleset.Playfield.AlwaysPresent = true;
drawableRuleset.Playfield.Hide();
}
}
public class ModCinema : ModAutoplay, IApplicableToHUD, IApplicableToPlayer
{
public override string Name => "Cinema";
public override string Acronym => "CN";
public override IconUsage Icon => OsuIcon.ModCinema;
public override string Description => "Watch the video without visual distractions.";
public void ApplyToHUD(HUDOverlay overlay)
{
overlay.ShowHud.Value = false;
overlay.ShowHud.Disabled = true;
}
public void ApplyToPlayer(Player player)
{
player.Background.EnableUserDim.Value = false;
player.DimmableVideo.IgnoreUserSettings.Value = true;
player.DimmableStoryboard.IgnoreUserSettings.Value = true;
}
}
}
| mit | C# |
497f20d818ab28b5a3d49d22c1a5666760bbdca6 | Fix bug in default nav for shared folders link | brondavies/wwwplatform.net,brondavies/wwwplatform.net,brondavies/wwwplatform.net | src/web/Views/Shared/_Nav.cshtml | src/web/Views/Shared/_Nav.cshtml | @{
var pages = Pages;
}
<ul class="nav navbar-nav navbar-right">
@foreach (var p in pages)
{
@Html.Partial("_PageNavigation", p)
}
@if (Settings.ShowSharedFoldersInMenus && SharedFoldersLinkIsAvailable())
{
<li>
@SharedFoldersLink()
</li>
}
</ul> | @{
var pages = Pages;
}
<ul class="nav navbar-nav navbar-right">
@foreach (var p in pages)
{
@Html.Partial("_PageNavigation", p)
}
@if (Settings.ShowSharedFoldersInMenus)
{
<li>
@SharedFoldersLink()
</li>
}
</ul> | apache-2.0 | C# |
8aad8a5d64670f3390034ae4177e9257c40c88d1 | Simplify MethodReplacer and keep backwards compatibility | pardeike/Harmony | Harmony/Transpilers.cs | Harmony/Transpilers.cs | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = to.IsConstructor ? OpCodes.Newobj : OpCodes.Call;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
} | using System;
using System.Collections.Generic;
using System.Reflection;
using System.Reflection.Emit;
namespace Harmony
{
public static class Transpilers
{
private static IEnumerable<CodeInstruction> Replacer(IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to, OpCode opcode)
{
if (from == null)
throw new ArgumentException("Unexpected null argument", nameof(from));
if (to == null)
throw new ArgumentException("Unexpected null argument", nameof(to));
foreach (var instruction in instructions)
{
var method = instruction.operand as MethodBase;
if (method == from)
{
instruction.opcode = opcode;
instruction.operand = to;
}
yield return instruction;
}
}
public static IEnumerable<CodeInstruction> MethodReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
return Replacer(instructions, from, to, OpCodes.Call);
}
public static IEnumerable<CodeInstruction> ConstructorReplacer(this IEnumerable<CodeInstruction> instructions, MethodBase from, MethodBase to)
{
return Replacer(instructions, from, to, OpCodes.Newobj);
}
public static IEnumerable<CodeInstruction> DebugLogger(this IEnumerable<CodeInstruction> instructions, string text)
{
yield return new CodeInstruction(OpCodes.Ldstr, text);
yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(FileLog), nameof(FileLog.Log)));
foreach (var instruction in instructions) yield return instruction;
}
// more added soon
}
} | mit | C# |
ab6ff87a73b9d707176de8f15d5cd81cf2f5a70c | Fix spacing. | AvaloniaUI/Avalonia,wieslawsoltes/Perspex,Perspex/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Perspex,wieslawsoltes/Perspex,grokys/Perspex,SuperJMN/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,SuperJMN/Avalonia,Perspex/Perspex,wieslawsoltes/Perspex,jkoritzinsky/Avalonia,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,SuperJMN/Avalonia,SuperJMN/Avalonia,wieslawsoltes/Perspex,grokys/Perspex,AvaloniaUI/Avalonia,jkoritzinsky/Avalonia,wieslawsoltes/Perspex,akrisiun/Perspex,SuperJMN/Avalonia | src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ResourceInclude.cs | src/Markup/Avalonia.Markup.Xaml/MarkupExtensions/ResourceInclude.cs | using System;
using System.ComponentModel;
using Avalonia.Controls;
#nullable enable
namespace Avalonia.Markup.Xaml.MarkupExtensions
{
/// <summary>
/// Loads a resource dictionary from a specified URL.
/// </summary>
public class ResourceInclude : IResourceProvider
{
private Uri? _baseUri;
private IResourceDictionary? _loaded;
private bool _isLoading;
/// <summary>
/// Gets the loaded resource dictionary.
/// </summary>
public IResourceDictionary Loaded
{
get
{
if (_loaded == null)
{
_isLoading = true;
var loader = new AvaloniaXamlLoader();
_loaded = (IResourceDictionary)loader.Load(Source, _baseUri);
_isLoading = false;
}
return _loaded;
}
}
public IResourceHost? Owner => Loaded.Owner;
/// <summary>
/// Gets or sets the source URL.
/// </summary>
public Uri? Source { get; set; }
bool IResourceNode.HasResources => Loaded.HasResources;
public event EventHandler OwnerChanged
{
add => Loaded.OwnerChanged += value;
remove => Loaded.OwnerChanged -= value;
}
bool IResourceNode.TryGetResource(object key, out object? value)
{
if (!_isLoading)
{
return Loaded.TryGetResource(key, out value);
}
value = null;
return false;
}
void IResourceProvider.AddOwner(IResourceHost owner) => Loaded.AddOwner(owner);
void IResourceProvider.RemoveOwner(IResourceHost owner) => Loaded.RemoveOwner(owner);
public ResourceInclude ProvideValue(IServiceProvider serviceProvider)
{
var tdc = (ITypeDescriptorContext)serviceProvider;
_baseUri = tdc?.GetContextBaseUri();
return this;
}
}
}
| using System;
using System.ComponentModel;
using Avalonia.Controls;
#nullable enable
namespace Avalonia.Markup.Xaml.MarkupExtensions
{
/// <summary>
/// Loads a resource dictionary from a specified URL.
/// </summary>
public class ResourceInclude : IResourceProvider
{
private Uri? _baseUri;
private IResourceDictionary? _loaded;
private bool _isLoading;
/// <summary>
/// Gets the loaded resource dictionary.
/// </summary>
public IResourceDictionary Loaded
{
get
{
if (_loaded == null)
{
_isLoading = true;
var loader = new AvaloniaXamlLoader();
_loaded = (IResourceDictionary)loader.Load(Source, _baseUri);
_isLoading = false;
}
return _loaded;
}
}
public IResourceHost? Owner => Loaded.Owner;
/// <summary>
/// Gets or sets the source URL.
/// </summary>
public Uri? Source { get; set; }
bool IResourceNode.HasResources => Loaded.HasResources;
public event EventHandler OwnerChanged
{
add => Loaded.OwnerChanged += value;
remove => Loaded.OwnerChanged -= value;
}
bool IResourceNode.TryGetResource(object key, out object? value)
{
if(!_isLoading)
{
return Loaded.TryGetResource(key, out value);
}
value = null;
return false;
}
void IResourceProvider.AddOwner(IResourceHost owner) => Loaded.AddOwner(owner);
void IResourceProvider.RemoveOwner(IResourceHost owner) => Loaded.RemoveOwner(owner);
public ResourceInclude ProvideValue(IServiceProvider serviceProvider)
{
var tdc = (ITypeDescriptorContext)serviceProvider;
_baseUri = tdc?.GetContextBaseUri();
return this;
}
}
}
| mit | C# |
cef2837c49d163a49641d8cf7df722b9433aa29c | Check for int.MaxValue when incrementing retry counter | michael-wolfenden/Polly | src/Polly.Shared/Retry/RetryPolicyStateWithSleepDurationProvider.cs | src/Polly.Shared/Retry/RetryPolicyStateWithSleepDurationProvider.cs | using System;
using Polly.Utilities;
namespace Polly.Retry
{
internal partial class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState
{
private int _errorCount;
private readonly Func<int, TimeSpan> _sleepDurationProvider;
private readonly Action<Exception, TimeSpan, Context> _onRetry;
private readonly Context _context;
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context)
{
this._sleepDurationProvider = sleepDurationProvider;
_onRetry = onRetry;
_context = context;
}
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry) :
this(sleepDurationProvider, (exception, timespan, context) => onRetry(exception, timespan), null)
{
}
public bool CanRetry(Exception ex)
{
if (_errorCount < int.MaxValue)
{
_errorCount += 1;
}
var currentTimeSpan = _sleepDurationProvider(_errorCount);
_onRetry(ex, currentTimeSpan, _context);
SystemClock.Sleep(currentTimeSpan);
return true;
}
}
}
| using System;
using Polly.Utilities;
namespace Polly.Retry
{
internal partial class RetryPolicyStateWithSleepDurationProvider : IRetryPolicyState
{
private int _errorCount;
private readonly Func<int, TimeSpan> _sleepDurationProvider;
private readonly Action<Exception, TimeSpan, Context> _onRetry;
private readonly Context _context;
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan, Context> onRetry, Context context)
{
this._sleepDurationProvider = sleepDurationProvider;
_onRetry = onRetry;
_context = context;
}
public RetryPolicyStateWithSleepDurationProvider(Func<int, TimeSpan> sleepDurationProvider, Action<Exception, TimeSpan> onRetry) :
this(sleepDurationProvider, (exception, timespan, context) => onRetry(exception, timespan), null)
{
}
public bool CanRetry(Exception ex)
{
if (_errorCount < int.MaxValue)
{
_errorCount += 1;
}
else
{
}
var currentTimeSpan = _sleepDurationProvider(_errorCount);
_onRetry(ex, currentTimeSpan, _context);
SystemClock.Sleep(currentTimeSpan);
return true;
}
}
}
| bsd-3-clause | C# |
3189ce75ae8a990912729aaa8296670a2bddff77 | throw exception if duplicate content app aliases are found | WebCentrum/Umbraco-CMS,arknu/Umbraco-CMS,rasmuseeg/Umbraco-CMS,umbraco/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,dawoe/Umbraco-CMS,dawoe/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,arknu/Umbraco-CMS,tompipe/Umbraco-CMS,umbraco/Umbraco-CMS,hfloyd/Umbraco-CMS,hfloyd/Umbraco-CMS,umbraco/Umbraco-CMS,mattbrailsford/Umbraco-CMS,marcemarc/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,WebCentrum/Umbraco-CMS,rasmuseeg/Umbraco-CMS,NikRimington/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,abryukhov/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,abjerner/Umbraco-CMS,leekelleher/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tompipe/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,mattbrailsford/Umbraco-CMS,lars-erik/Umbraco-CMS,tompipe/Umbraco-CMS,marcemarc/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,tcmorris/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,hfloyd/Umbraco-CMS,tcmorris/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,abjerner/Umbraco-CMS,KevinJump/Umbraco-CMS,bjarnef/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,robertjf/Umbraco-CMS,robertjf/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,hfloyd/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,rasmuseeg/Umbraco-CMS,madsoulswe/Umbraco-CMS,KevinJump/Umbraco-CMS,NikRimington/Umbraco-CMS,KevinJump/Umbraco-CMS,tcmorris/Umbraco-CMS,lars-erik/Umbraco-CMS,hfloyd/Umbraco-CMS,dawoe/Umbraco-CMS,bjarnef/Umbraco-CMS,madsoulswe/Umbraco-CMS,arknu/Umbraco-CMS,WebCentrum/Umbraco-CMS,umbraco/Umbraco-CMS | src/Umbraco.Web/ContentApps/ContentAppDefinitionCollection.cs | src/Umbraco.Web/ContentApps/ContentAppDefinitionCollection.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Models.ContentEditing;
using Umbraco.Core.Logging;
namespace Umbraco.Web.ContentApps
{
public class ContentAppDefinitionCollection : BuilderCollectionBase<IContentAppDefinition>
{
//private readonly ILogger _logger;
public ContentAppDefinitionCollection(IEnumerable<IContentAppDefinition> items)
: base(items)
{
//_logger = logger;
}
public IEnumerable<ContentApp> GetContentAppsFor(object o)
{
var apps = this.Select(x => x.GetContentAppFor(o)).WhereNotNull().OrderBy(x => x.Weight);
//apps must have unique aliases, we will remove any duplicates and log problems
var resultApps = new Dictionary<string, ContentApp>();
List<string> dups = null;
foreach(var a in apps)
{
if (resultApps.TryGetValue(a.Alias, out var count))
(dups ?? (dups = new List<string>())).Add(a.Alias);
else
resultApps[a.Alias] = a;
}
if (dups != null)
{
throw new InvalidOperationException($"Duplicate content app aliases found: {string.Join(",", dups)}");
//_logger.Warn<ContentAppDefinitionCollection>($"Duplicate content app aliases found: {string.Join(",", dups)}");
}
return resultApps.Values;
}
}
}
| using System.Collections.Generic;
using System.Linq;
using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Models.ContentEditing;
namespace Umbraco.Web.ContentApps
{
public class ContentAppDefinitionCollection : BuilderCollectionBase<IContentAppDefinition>
{
public ContentAppDefinitionCollection(IEnumerable<IContentAppDefinition> items)
: base(items)
{ }
public IEnumerable<ContentApp> GetContentAppsFor(object o)
{
return this.Select(x => x.GetContentAppFor(o)).WhereNotNull().OrderBy(x => x.Weight);
}
}
}
| mit | C# |
25e16943815859cd2a8228605646523b2ffcf16c | move to version 2.1 | puco/WebApiContrib.Formatting.Jsonp,WebApiContrib/WebApiContrib.Formatting.Jsonp,puco/WebApiContrib.Formatting.Jsonp,WebApiContrib/WebApiContrib.Formatting.Jsonp | src/WebApiContrib.Formatting.Jsonp/Properties/AssemblyInfo.cs | src/WebApiContrib.Formatting.Jsonp/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("WebApiContrib.Formatting.Jsonp")]
[assembly: AssemblyDescription("Provides a JSONP MediaTypeFormatter implementation for ASP.NET Web API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("WebApiContrib")]
[assembly: AssemblyProduct("WebApiContrib.Formatting.Jsonp")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("ea85f1dd-2454-4b75-9953-f3291e9336f8")]
// 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("2.1.0")]
[assembly: AssemblyFileVersion("2.1.0")]
[assembly: InternalsVisibleTo("WebApiContrib.Formatting.Jsonp.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("WebApiContrib.Formatting.Jsonp")]
[assembly: AssemblyDescription("Provides a JSONP MediaTypeFormatter implementation for ASP.NET Web API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("WebApiContrib")]
[assembly: AssemblyProduct("WebApiContrib.Formatting.Jsonp")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[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("ea85f1dd-2454-4b75-9953-f3291e9336f8")]
// 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("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0")]
[assembly: InternalsVisibleTo("WebApiContrib.Formatting.Jsonp.Tests")]
| mit | C# |
80b237aa2dc634e09db15d10f4163d3c84451173 | Fix bad conflict resolution which caused mulitple entries | sharwell/roslyn,weltkante/roslyn,bartdesmet/roslyn,sharwell/roslyn,KevinRansom/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,dotnet/roslyn,KevinRansom/roslyn,dotnet/roslyn,bartdesmet/roslyn,bartdesmet/roslyn,shyamnamboodiripad/roslyn,KevinRansom/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,mavasani/roslyn,weltkante/roslyn,mavasani/roslyn,CyrusNajmabadi/roslyn,jasonmalinowski/roslyn,jasonmalinowski/roslyn,dotnet/roslyn,diryboy/roslyn,diryboy/roslyn,shyamnamboodiripad/roslyn,weltkante/roslyn,CyrusNajmabadi/roslyn | src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs | src/Workspaces/Core/Portable/Experiments/IExperimentationService.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
void EnableExperiment(string experimentName, bool value);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
public void EnableExperiment(string experimentName, bool value) { }
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string OOPCoreClr = "Roslyn.OOPCoreClr";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
public const string AsynchronousQuickActions = "Roslyn.AsynchronousQuickActions";
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Composition;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
namespace Microsoft.CodeAnalysis.Experiments
{
internal interface IExperimentationService : IWorkspaceService
{
bool IsExperimentEnabled(string experimentName);
void EnableExperiment(string experimentName, bool value);
}
[ExportWorkspaceService(typeof(IExperimentationService)), Shared]
internal class DefaultExperimentationService : IExperimentationService
{
[ImportingConstructor]
[Obsolete(MefConstruction.ImportingConstructorMessage, error: true)]
public DefaultExperimentationService()
{
}
public bool IsExperimentEnabled(string experimentName) => false;
public void EnableExperiment(string experimentName, bool value) { }
}
internal static class WellKnownExperimentNames
{
public const string PartialLoadMode = "Roslyn.PartialLoadMode";
public const string TypeImportCompletion = "Roslyn.TypeImportCompletion";
public const string InsertFullMethodCall = "Roslyn.InsertFullMethodCall";
public const string TargetTypedCompletionFilter = "Roslyn.TargetTypedCompletionFilter";
public const string OOPServerGC = "Roslyn.OOPServerGC";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string ImportsOnPasteDefaultEnabled = "Roslyn.ImportsOnPasteDefaultEnabled";
public const string LspTextSyncEnabled = "Roslyn.LspTextSyncEnabled";
public const string SourceGeneratorsEnableOpeningInWorkspace = "Roslyn.SourceGeneratorsEnableOpeningInWorkspace";
public const string RemoveUnusedReferences = "Roslyn.RemoveUnusedReferences";
public const string LSPCompletion = "Roslyn.LSP.Completion";
public const string CloudCache = "Roslyn.CloudCache";
public const string UnnamedSymbolCompletionDisabled = "Roslyn.UnnamedSymbolCompletionDisabled";
public const string InheritanceMargin = "Roslyn.InheritanceMargin";
public const string RazorLspEditorFeatureFlag = "Razor.LSP.Editor";
public const string LspPullDiagnosticsFeatureFlag = "Lsp.PullDiagnostics";
public const string OOPCoreClr = "Roslyn.OOPCoreClr";
public const string ProgressionForceLegacySearch = "Roslyn.ProgressionForceLegacySearch";
public const string AsynchronousQuickActions = "Roslyn.AsynchronousQuickActions";
}
}
| mit | C# |
6bff072cd8ab31060073e5cd71e57427f02ef0fa | change JsonError to RawBody in BizwebSharpException | vinhch/BizwebSharp | src/BizwebSharp/Infrastructure/Exceptions/BizwebSharpException.cs | src/BizwebSharp/Infrastructure/Exceptions/BizwebSharpException.cs | using System;
using System.Collections.Generic;
using System.Net;
namespace BizwebSharp.Infrastructure
{
public class BizwebSharpException : Exception
{
public BizwebSharpException(string message) : base(message)
{
}
public BizwebSharpException(string message, Exception innerException) : base(message, innerException)
{
}
public BizwebSharpException(HttpStatusCode httpStatusCode, Dictionary<string, IEnumerable<string>> errors,
string message, string rawBody, RequestSimpleInfo requestInfo = null) : base(message)
{
HttpStatusCode = httpStatusCode;
Errors = errors;
RawBody = rawBody;
RequestInfo = requestInfo;
}
public HttpStatusCode HttpStatusCode { get; set; }
public Dictionary<string, IEnumerable<string>> Errors { get; set; } =
new Dictionary<string, IEnumerable<string>>();
public string RawBody { get; set; }
public RequestSimpleInfo RequestInfo { get; set; }
}
} | using System;
using System.Collections.Generic;
using System.Net;
namespace BizwebSharp.Infrastructure
{
public class BizwebSharpException : Exception
{
public BizwebSharpException(string message) : base(message)
{
}
public BizwebSharpException(string message, Exception innerException) : base(message, innerException)
{
}
public BizwebSharpException(HttpStatusCode httpStatusCode, Dictionary<string, IEnumerable<string>> errors,
string message, string jsonError, RequestSimpleInfo requestInfo = null) : base(message)
{
HttpStatusCode = httpStatusCode;
Errors = errors;
JsonError = jsonError;
RequestInfo = requestInfo;
}
public HttpStatusCode HttpStatusCode { get; set; }
public Dictionary<string, IEnumerable<string>> Errors { get; set; } =
new Dictionary<string, IEnumerable<string>>();
public string JsonError { get; set; }
public RequestSimpleInfo RequestInfo { get; set; }
}
} | mit | C# |
d54396302896821dc2de4518bd13b98a386cefd5 | Remove the reading of the response... extra overhead not needed | mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Agent.Channel.Server.Http/Broker/HttpChannelSender.cs | src/Glimpse.Agent.Channel.Server.Http/Broker/HttpChannelSender.cs | using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public class HttpChannelSender : IChannelSender, IDisposable
{
private readonly HttpClient _httpClient;
private readonly HttpClientHandler _httpHandler;
public HttpChannelSender()
{
_httpHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpHandler);
}
public async void PublishMessage(IMessage message)
{
// TODO: Needs error handelling
// TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync
try
{
var response = await _httpClient.PostAsJsonAsync("http://localhost:5210/Glimpse/Agent", message);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
}
catch (Exception e)
{
// TODO: Bad thing happened
}
}
public void Dispose()
{
_httpClient.Dispose();
_httpHandler.Dispose();
}
}
} | using System;
using System.Net.Http;
using System.Threading.Tasks;
namespace Glimpse.Agent
{
public class HttpChannelSender : IChannelSender, IDisposable
{
private readonly HttpClient _httpClient;
private readonly HttpClientHandler _httpHandler;
public HttpChannelSender()
{
_httpHandler = new HttpClientHandler();
_httpClient = new HttpClient(_httpHandler);
}
public async void PublishMessage(IMessage message)
{
// TODO: Needs error handelling
// TODO: Find out what happened to System.Net.Http.Formmating - PostAsJsonAsync
try
{
var response = await _httpClient.PostAsJsonAsync("http://localhost:5210/Glimpse/Agent", message);
// Check that response was successful or throw exception
response.EnsureSuccessStatusCode();
// Read response asynchronously as JsonValue and write out top facts for each country
var result = await response.Content.ReadAsStringAsync();
}
catch (Exception e)
{
// TODO: Bad thing happened
}
}
public void Dispose()
{
_httpClient.Dispose();
_httpHandler.Dispose();
}
}
} | mit | C# |
31d2080b54ea52ef09078bcd23e7b7c3dea3db2b | Order apps by name | appharbor/appharbor-cli | src/AppHarbor/Commands/AppCommand.cs | src/AppHarbor/Commands/AppCommand.cs | using System.IO;
using System.Linq;
namespace AppHarbor.Commands
{
[CommandHelp("List your applications")]
public class AppCommand : ICommand
{
private readonly IAppHarborClient _client;
private readonly TextWriter _writer;
public AppCommand(IAppHarborClient appharborClient, TextWriter writer)
{
_client = appharborClient;
_writer = writer;
}
public void Execute(string[] arguments)
{
var applications = _client.GetApplications();
foreach (var application in applications.OrderBy(x => x.Slug))
{
_writer.WriteLine(application.Slug);
}
}
}
}
| using System.IO;
namespace AppHarbor.Commands
{
[CommandHelp("List your applications")]
public class AppCommand : ICommand
{
private readonly IAppHarborClient _client;
private readonly TextWriter _writer;
public AppCommand(IAppHarborClient appharborClient, TextWriter writer)
{
_client = appharborClient;
_writer = writer;
}
public void Execute(string[] arguments)
{
var applications = _client.GetApplications();
foreach (var application in applications)
{
_writer.WriteLine(application.Slug);
}
}
}
}
| mit | C# |
f74a71cf904a830ab4587dc1864cf71c0227959e | Fix spelling | ewilde/crane,ewilde/crane | src/crane.core.tests/Configuration/Modules/CommandModulesTests.cs | src/crane.core.tests/Configuration/Modules/CommandModulesTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Autofac;
using crane.console.Configuration.Modules;
using crane.core.Commands;
using crane.core.tests.TestExtensions;
using FluentAssertions;
using Xbehave;
using Xunit;
namespace crane.core.tests.Configuration.Modules
{
public class CommandModulesTests
{
[Scenario]
public void command_module_registration(IContainer container, CommandModule module)
{
"Given we have a command module"
._(() => module = new CommandModule());
"When I build the module"
._(() => container = module.BuildContainerWithModule());
"Then it should resolve the help command"
._(() => container.Resolve<IEnumerable<ICraneCommand>>().Any(item => item is ShowHelp).Should().BeTrue());
"And it should be a singleton instance" // Is there a better way to verify lifecycle in Autofac?
._(
() =>
ReferenceEquals(container.Resolve<IEnumerable<ICraneCommand>>().First(item => item is ShowHelp),
container.Resolve<IEnumerable<ICraneCommand>>().First(item => item is ShowHelp))
.Should().BeTrue());
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Input;
using Autofac;
using crane.console.Configuration.Modules;
using crane.core.Commands;
using crane.core.tests.TestExtensions;
using FluentAssertions;
using Xbehave;
using Xunit;
namespace crane.core.tests.Configuration.Modules
{
public class CommandModulesTests
{
[Scenario]
public void command_module_registration(IContainer container, CommandModule module)
{
"Given we have a command modlue"
._(() => module = new CommandModule());
"When I build the module"
._(() => container = module.BuildContainerWithModule());
"Then it should resolve the help command"
._(() => container.Resolve<IEnumerable<ICraneCommand>>().Any(item => item is ShowHelp).Should().BeTrue());
"And it should be a singleton instance" // Is there a better way to verify lifecycle in Autofac?
._(
() =>
ReferenceEquals(container.Resolve<IEnumerable<ICraneCommand>>().First(item => item is ShowHelp),
container.Resolve<IEnumerable<ICraneCommand>>().First(item => item is ShowHelp))
.Should().BeTrue());
}
}
} | apache-2.0 | C# |
c892ab4cc5fcf68b6eb80cace69b659e000f0b5d | Refactor sim.exe | sergeyshushlyapin/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager,Brad-Christie/Sitecore-Instance-Manager,dsolovay/Sitecore-Instance-Manager | src/SIM.Core/Commands/StopCommand.cs | src/SIM.Core/Commands/StopCommand.cs | namespace SIM.Core.Commands
{
using System;
using System.Linq;
using Sitecore.Diagnostics.Base;
using SIM.Core.Common;
using SIM.Instances;
public class StopCommand : AbstractInstanceActionCommand<Exception>
{
public virtual bool? Force { get; set; }
protected override void DoExecute(CommandResult<Exception> result)
{
Assert.ArgumentNotNull(result, "result");
var force = this.Force;
var name = this.Name;
Ensure.IsNotNullOrEmpty(name, "Name is not specified");
InstanceManager.Initialize();
var instance = InstanceManager.Instances.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
Ensure.IsNotNull(instance, "instance is not found");
Ensure.IsTrue(instance.State != InstanceState.Disabled, "instance is disabled");
Ensure.IsTrue(instance.State != InstanceState.Stopped, "instance is already stopped");
instance.Stop(force);
}
}
} | namespace SIM.Core.Commands
{
using System;
using System.Linq;
using Sitecore.Diagnostics.Base;
using SIM.Core.Common;
using SIM.Instances;
public class StopCommand : AbstractInstanceActionCommand<Exception>
{
public virtual bool? Force { get; set; }
protected override void DoExecute(CommandResult<Exception> result)
{
Assert.ArgumentNotNull(result, "result");
var force = this.Force;
var name = this.Name;
Ensure.IsNotNullOrEmpty(name, "Name is not specified");
InstanceManager.Initialize();
var instance = InstanceManager.Instances.FirstOrDefault(x => x.Name.Equals(name, StringComparison.OrdinalIgnoreCase));
Ensure.IsNotNull(instance, "instance is not found");
Ensure.IsTrue(instance.State != InstanceState.Disabled, "instance is disabled");
Ensure.IsTrue(instance.State != InstanceState.Stopped, "instance is already stopped");
Exception exception = null;
try
{
instance.Stop(force);
}
catch (Exception ex)
{
exception = ex;
}
result.Success = exception == null;
result.Message = exception.With(x => x.Message) ?? "done";
result.Data = exception;
}
}
} | mit | C# |
66d153a57a097cbe9463f29c7f0385ff1faef8da | fix hashCode for Instructions | ilovepi/Compiler,ilovepi/Compiler | compiler/middleend/ir/Instruction.cs | compiler/middleend/ir/Instruction.cs | using System;
namespace compiler.middleend.ir
{
public class Instruction : IEquatable<Instruction>
{
/// <summary>
/// The Instruction number
/// </summary>
/// <value>The number.</value>
public int Num { get; set; }
/// <summary>
/// The op/op code
/// </summary>
/// <value>The op.</value>
public IrOps Op { get; set; }
/// <summary>
/// The First Argument in the Instruction
/// </summary>
/// <value>The arg1.</value>
public Operand Arg1 { get; set; }
/// <summary>
/// The Second Argument in the instruction
/// </summary>
/// <value>The arg2.</value>
public Operand Arg2 { get; set; }
/// <summary>
/// Linked list pointer to the previous instruction
/// </summary>
Instruction Prev { get; set; }
/// <summary>
/// Linked list pointer to the next instruction
/// </summary>
Instruction Next { get; set; }
/// <summary>
/// Pointer to the next Instruction of the same type (op)
/// </summary>
public Instruction Search { set; get; }
public static int InstructionCounter = 0;
public Instruction(IrOps pOp, Operand pArg1, Operand pArg2)
{
Num = InstructionCounter;
InstructionCounter++;
Op = pOp;
Arg1 = pArg1;
Arg2 = pArg2;
Prev = null;
Next = null;
Search = null;
}
public bool Equals(Instruction other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Op == other.Op && Equals(Arg1, other.Arg1) && Equals(Arg2, other.Arg2);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Instruction) obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = (int)Op;
hashCode = (hashCode * 397) ^ (Arg1?.GetHashCode() ?? 0);
hashCode = (hashCode * 397) ^ (Arg2?.GetHashCode() ?? 0);
return hashCode;
}
}
public static bool operator ==(Instruction left, Instruction right)
{
return Equals(left, right);
}
public static bool operator !=(Instruction left, Instruction right)
{
return !Equals(left, right);
}
}
}
| using System;
namespace compiler.middleend.ir
{
public class Instruction : IEquatable<Instruction>
{
/// <summary>
/// The Instruction number
/// </summary>
/// <value>The number.</value>
public int Num { get; set; }
/// <summary>
/// The op/op code
/// </summary>
/// <value>The op.</value>
public IrOps Op { get; set; }
/// <summary>
/// The First Argument in the Instruction
/// </summary>
/// <value>The arg1.</value>
public Operand Arg1 { get; set; }
/// <summary>
/// The Second Argument in the instruction
/// </summary>
/// <value>The arg2.</value>
public Operand Arg2 { get; set; }
/// <summary>
/// Linked list pointer to the previous instruction
/// </summary>
Instruction Prev { get; set; }
/// <summary>
/// Linked list pointer to the next instruction
/// </summary>
Instruction Next { get; set; }
/// <summary>
/// Pointer to the next Instruction of the same type (op)
/// </summary>
public Instruction Search { set; get; }
public static int InstructionCounter = 0;
public Instruction(IrOps pOp, Operand pArg1, Operand pArg2)
{
Num = InstructionCounter;
InstructionCounter++;
Op = pOp;
Arg1 = pArg1;
Arg2 = pArg2;
Prev = null;
Next = null;
Search = null;
}
public bool Equals(Instruction other)
{
if (ReferenceEquals(null, other)) return false;
if (ReferenceEquals(this, other)) return true;
return Op == other.Op && Equals(Arg1, other.Arg1) && Equals(Arg2, other.Arg2);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
if (ReferenceEquals(this, obj)) return true;
if (obj.GetType() != this.GetType()) return false;
return Equals((Instruction) obj);
}
/*
public override int GetHashCode()
{
unchecked
{
var hashCode = Op;
hashCode = (hashCode * 397) ^ (Arg1 != null ? Arg1.GetHashCode() : 0);
hashCode = (hashCode * 397) ^ (Arg2 != null ? Arg2.GetHashCode() : 0);
return hashCode;
}
}
*/
public static bool operator ==(Instruction left, Instruction right)
{
return Equals(left, right);
}
public static bool operator !=(Instruction left, Instruction right)
{
return !Equals(left, right);
}
}
}
| mit | C# |
2c638035ad6c9a2ffcf40a2a34a87c1fb267feaa | Add warning to /tools if JavaScript disabled | martincostello/website,martincostello/website,martincostello/website,martincostello/website | src/Website/Views/Tools/Index.cshtml | src/Website/Views/Tools/Index.cshtml | @inject BowerVersions Bower
@inject SiteOptions Options
@{
ViewBag.Title = ".NET Development Tools";
ViewBag.MetaDescription = ".NET Development Tools for generating GUIDs, machine keys and hashing text.";
var clipboardVersion = Bower["clipboard"];
var toolsUri = Options.ExternalLinks.Api.AbsoluteUri + "tools";
}
@section meta {
<link rel="api-guid" href="@toolsUri/guid" />
<link rel="api-hash" href="@toolsUri/hash" />
<link rel="api-machine-key" href="@toolsUri/machinekey" />
}
@section scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/@clipboardVersion/clipboard.min.js" integrity="sha256-COWXDc7n7PAqsE3y1r4CVopxWU9JI0kenz6K4zBqhT8=" crossorigin="anonymous"
asp-fallback-src="~/lib/clipboard/dist/clipboard.min.js"
asp-fallback-test="window.Clipboard">
</script>
}
<h1>@ViewBag.Title</h1>
<div class="panel panel-default">
<div class="panel-body">This page contains tools and links to common development tools.</div>
</div>
<noscript>
<div class="alert alert-warning" role="alert">JavaScript must be enabled in your browser to use these tools.</div>
</noscript>
<div>
@await Html.PartialAsync("_GenerateGuid")
</div>
<div>
@await Html.PartialAsync("_GenerateHash")
</div>
<div>
@await Html.PartialAsync("_GenerateMachineKey")
</div>
| @inject BowerVersions Bower
@inject SiteOptions Options
@{
ViewBag.Title = ".NET Development Tools";
ViewBag.MetaDescription = ".NET Development Tools for generating GUIDs, machine keys and hashing text.";
var clipboardVersion = Bower["clipboard"];
var toolsUri = Options.ExternalLinks.Api.AbsoluteUri + "tools";
}
@section meta {
<link rel="api-guid" href="@toolsUri/guid" />
<link rel="api-hash" href="@toolsUri/hash" />
<link rel="api-machine-key" href="@toolsUri/machinekey" />
}
@section scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/clipboard.js/@clipboardVersion/clipboard.min.js" integrity="sha256-COWXDc7n7PAqsE3y1r4CVopxWU9JI0kenz6K4zBqhT8=" crossorigin="anonymous"
asp-fallback-src="~/lib/clipboard/dist/clipboard.min.js"
asp-fallback-test="window.Clipboard">
</script>
}
<h1>@ViewBag.Title</h1>
<div class="panel panel-default">
<div class="panel-body">This page contains tools and links to common development tools.</div>
</div>
<div>
@await Html.PartialAsync("_GenerateGuid")
</div>
<div>
@await Html.PartialAsync("_GenerateHash")
</div>
<div>
@await Html.PartialAsync("_GenerateMachineKey")
</div>
| apache-2.0 | C# |
a8e404599a1272bc9803f94ba7b3542d3d707d39 | Update Program.cs | codebude/QRCoder | QRCoderDemo/Program.cs | QRCoderDemo/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace QRCoderDemo
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Application.Run(new Form1());
Application.Run(new Multigenerator());
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace QRCoderDemo
{
static class Program
{
/// <summary>
/// Der Haupteinstiegspunkt für die Anwendung.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| mit | C# |
ae4ea833d110aefb5bcac6bb7b4c611a1b5c3305 | Fix Portal Bug | bunashibu/kikan | Assets/Scripts/Player/PlayerPortal.cs | Assets/Scripts/Player/PlayerPortal.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Bunashibu.Kikan {
public class PlayerPortal : MonoBehaviour {
void OnTriggerStay2D(Collider2D collider) {
if (!_player.PhotonView.isMine)
return;
GameObject target = collider.gameObject;
if (target.layer == LayerMask.NameToLayer(_portalLayerName)) {
if (Input.GetKey(KeyCode.UpArrow)) {
target.GetComponent<Portal>().Enter(_player);
}
}
}
[SerializeField] private string _portalLayerName;
[SerializeField] private BattlePlayer _player;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Bunashibu.Kikan {
public class PlayerPortal : MonoBehaviour {
void OnTriggerStay2D(Collider2D collider) {
GameObject target = collider.gameObject;
if (target.layer == LayerMask.NameToLayer(_portalLayerName)) {
if (Input.GetKey(KeyCode.UpArrow)) {
target.GetComponent<Portal>().Enter(_player);
}
}
}
[SerializeField] private string _portalLayerName;
[SerializeField] private BattlePlayer _player;
}
}
| mit | C# |
6b49486bac8df5f3ba219b508438d34df85c3e53 | update 后退时候保持前一个页面的状态 | MarcusTzaen/CNodeUwp | src/CNodeUwp/MainPage.xaml.cs | src/CNodeUwp/MainPage.xaml.cs | using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace CNodeUwp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
NavigationCacheMode = NavigationCacheMode.Enabled;
}
}
}
| using Windows.UI.Xaml.Controls;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace CNodeUwp
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
}
}
| mit | C# |
30dd30276a1d43e466b43b83661eb1483f888761 | Hide a defintion for internal use | DotNetKit/DotNetKit.Wpf.AutoCompleteComboBox | DotNetKit.Wpf.AutoCompleteComboBox/Windows/Media/VisualTreeModule.cs | DotNetKit.Wpf.AutoCompleteComboBox/Windows/Media/VisualTreeModule.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace DotNetKit.Windows.Media
{
static class VisualTreeModule
{
public static FrameworkElement FindChild(DependencyObject obj, string childName)
{
if (obj == null) return null;
var queue = new Queue<DependencyObject>();
queue.Enqueue(obj);
while (queue.Count > 0)
{
obj = queue.Dequeue();
var childCount = VisualTreeHelper.GetChildrenCount(obj);
for (var i = 0; i < childCount; i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
var fe = child as FrameworkElement;
if (fe != null && fe.Name == childName)
{
return fe;
}
queue.Enqueue(child);
}
}
return null;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
namespace DotNetKit.Windows.Media
{
public static class VisualTreeModule
{
public static FrameworkElement FindChild(DependencyObject obj, string childName)
{
if (obj == null) return null;
var queue = new Queue<DependencyObject>();
queue.Enqueue(obj);
while (queue.Count > 0)
{
obj = queue.Dequeue();
var childCount = VisualTreeHelper.GetChildrenCount(obj);
for (var i = 0; i < childCount; i++)
{
var child = VisualTreeHelper.GetChild(obj, i);
var fe = child as FrameworkElement;
if (fe != null && fe.Name == childName)
{
return fe;
}
queue.Enqueue(child);
}
}
return null;
}
}
}
| mit | C# |
4b748c88944e8f24fe17adea9170c225c64b596a | Update InsertingAColumn.cs | aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/RowsColumns/InsertingAndDeleting/InsertingAColumn.cs | Examples/CSharp/RowsColumns/InsertingAndDeleting/InsertingAColumn.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.InsertingAndDeleting
{
public class InsertingAColumn
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Inserting a column into the worksheet at 2nd position
worksheet.Cells.InsertColumn(1);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.RowsColumns.InsertingAndDeleting
{
public class InsertingAColumn
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
//Creating a file stream containing the Excel file to be opened
FileStream fstream = new FileStream(dataDir + "book1.xls", FileMode.Open);
//Instantiating a Workbook object
//Opening the Excel file through the file stream
Workbook workbook = new Workbook(fstream);
//Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.Worksheets[0];
//Inserting a column into the worksheet at 2nd position
worksheet.Cells.InsertColumn(1);
//Saving the modified Excel file
workbook.Save(dataDir + "output.out.xls");
//Closing the file stream to free all resources
fstream.Close();
//End:1
}
}
}
| mit | C# |
7693a58270bf1a9d60d97ed260c51de72011f776 | Update DeviceSet | ChillyFlashER/OpenInput | src/Mallos.Input/DeviceSet.cs | src/Mallos.Input/DeviceSet.cs | namespace Mallos.Input
{
using Mallos.Input.Trackers;
/// <summary>
/// DeviceSet is a set of all devices that allows for easier usage of the library.
/// </summary>
public class DeviceSet<TKeyboard, TMouse, TGamePad> : IDeviceSet
where TKeyboard : IKeyboard
where TMouse : IMouse
where TGamePad : IGamePad
{
public DeviceSet(
string name,
TKeyboard keyboard,
TMouse mouse,
TGamePad[] gamePads)
{
this.Name = name;
this.GKeyboard = keyboard;
this.GMouse = mouse;
// FIXME: Figure out how to handle new gamepad connect
this.TGamePads = gamePads;
this.KeyboardTracker = this.GKeyboard?.CreateTracker();
this.MouseTracker = this.GMouse?.CreateTracker();
}
/// <inheritdoc />
public string Name { get; }
/// <inheritdoc />
public IKeyboard Keyboard => this.GKeyboard;
/// <inheritdoc />
public IMouse Mouse => this.GMouse;
/// <inheritdoc />
public IGamePad[] GamePads => this.TGamePads as IGamePad[];
/// <inheritdoc />
public IKeyboardTracker KeyboardTracker { get; }
/// <inheritdoc />
public IMouseTracker MouseTracker { get; }
protected TKeyboard GKeyboard { get; }
protected TMouse GMouse { get; }
protected TGamePad[] TGamePads { get; }
/// <inheritdoc />
public void Update(float elapsedTime)
{
KeyboardTracker?.Update(elapsedTime);
MouseTracker?.Update(elapsedTime);
}
}
}
| namespace Mallos.Input
{
using Mallos.Input.Trackers;
/// <summary>
/// DeviceSet is a set of all devices that allows for easier usage of the library.
/// </summary>
public class DeviceSet<TKeyboard, TMouse, TGamePad> : IDeviceSet
where TKeyboard : IKeyboard
where TMouse : IMouse
where TGamePad : IGamePad
{
public DeviceSet(
string name,
TKeyboard keyboard,
TMouse mouse,
TGamePad[] gamePads)
{
this.Name = name;
this.GKeyboard = keyboard;
this.GMouse = mouse;
// FIXME: Figure out how to handle new gamepad connect
this.TGamePads = gamePads;
this.KeyboardTracker = this.GKeyboard?.CreateTracker();
this.MouseTracker = this.GMouse?.CreateTracker();
}
/// <inheritdoc />
public string Name { get; }
/// <inheritdoc />
IKeyboard Keyboard => this.GKeyboard;
/// <inheritdoc />
IMouse Mouse => this.GMouse;
/// <inheritdoc />
IGamePad[] GamePads => this.TGamePads as IGamePad[];
/// <inheritdoc />
public IKeyboardTracker KeyboardTracker { get; }
/// <inheritdoc />
public IMouseTracker MouseTracker { get; }
protected TKeyboard GKeyboard { get; }
protected TMouse GMouse { get; }
protected TGamePad[] TGamePads { get; }
/// <inheritdoc />
public void Update(float elapsedTime)
{
KeyboardTracker?.Update(elapsedTime);
MouseTracker?.Update(elapsedTime);
}
}
}
| mit | C# |
2e0241c71b789a5a86941cb943df3492757d1014 | Remove trailing whitespace in AssemblyInfo.cs | sharwell/StyleCop.Analyzers.Status,sharwell/StyleCop.Analyzers.Status,pdelvo/StyleCop.Analyzers.Status,sharwell/StyleCop.Analyzers.Status,DotNetAnalyzers/StyleCopAnalyzers,pdelvo/StyleCop.Analyzers.Status,pdelvo/StyleCop.Analyzers.Status | StyleCop.Analyzers.Status.Generator/Properties/AssemblyInfo.cs | StyleCop.Analyzers.Status.Generator/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("StyleCop.Analyzers.Status.Generator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StyleCop.Analyzers.Status.Generator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("9bf22a9e-9708-4ae4-a5c7-7a00ae4c8885")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.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("StyleCop.Analyzers.Status.Generator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("StyleCop.Analyzers.Status.Generator")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[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("9bf22a9e-9708-4ae4-a5c7-7a00ae4c8885")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
f888126d566d0b121edac14f56f206fc8409b30a | Switch over ExecutionMessage to use TimerResultMessage instead of MessageBase | dudzon/Glimpse,Glimpse/Glimpse,elkingtonmcb/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,dudzon/Glimpse,flcdrg/Glimpse,codevlabs/Glimpse,dudzon/Glimpse,gabrielweyer/Glimpse,sorenhl/Glimpse,rho24/Glimpse,rho24/Glimpse,SusanaL/Glimpse,rho24/Glimpse,SusanaL/Glimpse,flcdrg/Glimpse,paynecrl97/Glimpse,paynecrl97/Glimpse,Glimpse/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,SusanaL/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,sorenhl/Glimpse,elkingtonmcb/Glimpse,Glimpse/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,gabrielweyer/Glimpse,codevlabs/Glimpse | source/Glimpse.Mvc3/Message/ExecutionMessage.cs | source/Glimpse.Mvc3/Message/ExecutionMessage.cs | using System;
using System.Reflection;
using System.Web.Mvc;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Message;
namespace Glimpse.Mvc.Message
{
public class ExecutionMessage : TimerResultMessage, IExecutionMessage
{
public ExecutionMessage(FilterCategory? filterCategory, Type filterType, MethodInfo method, TimerResult timerResult, ControllerBase controllerBase)
: base(timerResult, Simplify(method.Name), "Filter")
{
// IsChildAction is false if ControllerContext is null
IsChildAction = controllerBase.ControllerContext != null && controllerBase.ControllerContext.IsChildAction;
Category = filterCategory;
ExecutedType = filterType;
ExecutedMethod = method;
}
public bool IsChildAction { get; private set; }
public FilterCategory? Category { get; private set; }
public Type ExecutedType { get; private set; }
public MethodInfo ExecutedMethod { get; private set; }
private static string Simplify(string methodName)
{
var nameParts = methodName.Split('.');
return nameParts[nameParts.Length - 1];
}
}
} | using System;
using System.Reflection;
using System.Web.Mvc;
using Glimpse.Core.Extensibility;
using Glimpse.Core.Message;
namespace Glimpse.Mvc.Message
{
public class ExecutionMessage : MessageBase, IExecutionMessage, ITimerResultMessage
{
public ExecutionMessage(FilterCategory? filterCategory, Type filterType, MethodInfo method, TimerResult timerResult, ControllerBase controllerBase)
{
// IsChildAction is false if ControllerContext is null
IsChildAction = controllerBase.ControllerContext != null && controllerBase.ControllerContext.IsChildAction;
Category = filterCategory;
ExecutedType = filterType;
ExecutedMethod = method;
Duration = timerResult.Duration;
Offset = timerResult.Offset;
EventName = Simplify(method.Name);
EventCategory = filterCategory + "Filter";
}
public bool IsChildAction { get; private set; }
public FilterCategory? Category { get; private set; }
public Type ExecutedType { get; private set; }
public MethodInfo ExecutedMethod { get; private set; }
public string EventName { get; private set; }
public string EventCategory { get; private set; }
public long Offset { get; private set; }
public TimeSpan Duration { get; private set; }
private string Simplify(string methodName)
{
var nameParts = methodName.Split('.');
return nameParts[nameParts.Length - 1];
}
}
} | apache-2.0 | C# |
318086ff6d1323eb064916bf13a21b01a522bec9 | Put AMEE Ribbon Panel under Analyze tab | AMEE/revit | src/AMEE-in-Revit.Addin/AMEEPanel.cs | src/AMEE-in-Revit.Addin/AMEEPanel.cs | using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using Autodesk.Revit.UI;
namespace AMEE_in_Revit.Addin
{
public class AMEEPanel : IExternalApplication
{
// ExternalCommands assembly path
static string AddInPath = typeof(AMEEPanel).Assembly.Location;
// Button icons directory
static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath);
// uiApplication
static UIApplication uiApplication = null;
public Result OnStartup(UIControlledApplication application)
{
try
{
var panel = application.CreateRibbonPanel(Tab.Analyze, "AMEE");
AddAMEEConnectButton(panel);
panel.AddSeparator();
return Result.Succeeded;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "AMEE-in-Revit error");
return Result.Failed;
}
}
private void AddAMEEConnectButton(RibbonPanel panel)
{
var pushButton = panel.AddItem(new PushButtonData("launchAMEEConnect", "AMEE Connect", AddInPath, "AMEE_in_Revit.Addin.LaunchAMEEConnectCommand")) as PushButton;
pushButton.ToolTip = "Say Hello World";
// Set the large image shown on button
pushButton.LargeImage = new BitmapImage(new Uri(ButtonIconsFolder+ @"\AMEE.ico"));
}
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
}
}
| using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Media.Imaging;
using Autodesk.Revit.UI;
namespace AMEE_in_Revit.Addin
{
public class AMEEPanel : IExternalApplication
{
// ExternalCommands assembly path
static string AddInPath = typeof(AMEEPanel).Assembly.Location;
// Button icons directory
static string ButtonIconsFolder = Path.GetDirectoryName(AddInPath);
// uiApplication
static UIApplication uiApplication = null;
public Result OnStartup(UIControlledApplication application)
{
try
{
var panel = application.CreateRibbonPanel("AMEE");
AddAMEEConnectButton(panel);
panel.AddSeparator();
return Result.Succeeded;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "AMEE-in-Revit error");
return Result.Failed;
}
}
private void AddAMEEConnectButton(RibbonPanel panel)
{
var pushButton = panel.AddItem(new PushButtonData("launchAMEEConnect", "AMEE Connect", AddInPath, "AMEE_in_Revit.Addin.LaunchAMEEConnectCommand")) as PushButton;
pushButton.ToolTip = "Say Hello World";
// Set the large image shown on button
pushButton.LargeImage = new BitmapImage(new Uri(ButtonIconsFolder+ @"\AMEE.ico"));
}
public Result OnShutdown(UIControlledApplication application)
{
return Result.Succeeded;
}
}
}
| bsd-3-clause | C# |
dc7e762f9ea894b6e0ca1da513673e70feb15b29 | Format Signature | carbon/Amazon | src/Amazon.Core/Helpers/Signature.cs | src/Amazon.Core/Helpers/Signature.cs | #nullable enable
using System;
using System.Security.Cryptography;
using System.Text;
using Amazon.Helpers;
namespace Amazon
{
internal readonly struct Signature
{
public Signature(byte[] data)
{
Data = data;
}
public byte[] Data { get; }
public readonly string ToBase64String() => Convert.ToBase64String(Data);
public readonly string ToHexString() => HexString.FromBytes(Data);
public static Signature ComputeHmacSha256(string key, string data)
{
return ComputeHmacSha256(
key : Encoding.UTF8.GetBytes(key),
data : Encoding.UTF8.GetBytes(data)
);
}
public static Signature ComputeHmacSha256(byte[] key, byte[] data)
{
using HMACSHA256 algorithm = new HMACSHA256(key);
byte[] hash = algorithm.ComputeHash(data);
return new Signature(hash);
}
}
} | using System;
using System.Security.Cryptography;
using System.Text;
namespace Amazon
{
using Helpers;
internal readonly struct Signature
{
public Signature(byte[] data)
{
Data = data ?? throw new ArgumentNullException(nameof(data));
}
public byte[] Data { get; }
public string ToBase64String() => Convert.ToBase64String(Data);
public string ToHexString() => HexString.FromBytes(Data);
public static Signature ComputeHmacSha256(string key, string data)
{
return ComputeHmacSha256(
key : Encoding.UTF8.GetBytes(key),
data : Encoding.UTF8.GetBytes(data)
);
}
public static Signature ComputeHmacSha256(byte[] key, byte[] data)
{
if (key is null)
throw new ArgumentNullException(nameof(key));
if (data is null)
throw new ArgumentNullException(nameof(data));
using (var algorithm = new HMACSHA256(key))
{
byte[] hash = algorithm.ComputeHash(data);
return new Signature(hash);
}
}
}
} | mit | C# |
c1a72ecb068bb9b39278b5c705b8b5c0d45dea39 | Update Info for Dan Rigby (#152) | planetxamarin/planetxamarin,planetxamarin/planetxamarin,MabroukENG/planetxamarin,MabroukENG/planetxamarin,MabroukENG/planetxamarin,planetxamarin/planetxamarin,planetxamarin/planetxamarin | src/Firehose.Web/Authors/DanRigby.cs | src/Firehose.Web/Authors/DanRigby.cs | using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class DanRigby : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Dan";
public string LastName => "Rigby";
public string ShortBioOrTagLine => "is a Xamarin Technical Solutions Professional at Microsoft.";
public string StateOrRegion => "Raleigh, North Carolina";
public string EmailAddress => "Dan.Rigby@Xamarin.com";
public string TwitterHandle => "DanRigby";
public string GitHubHandle => "DanRigby";
public string GravatarHash => "f025f772418fbcfd3a1e15a74bf0f8a4";
public GeoPosition Position => new GeoPosition(35.7795900,-78.6381790);
public Uri WebSite => new Uri("http://danrigby.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://feeds.feedburner.com/DanRigby"); }
}
}
}
| using System;
using System.Collections.Generic;
using Firehose.Web.Infrastructure;
namespace Firehose.Web.Authors
{
public class DanRigby : IWorkAtXamarinOrMicrosoft
{
public string FirstName => "Dan";
public string LastName => "Rigby";
public string ShortBioOrTagLine => string.Empty;
public string StateOrRegion => "North Carolina";
public string EmailAddress => "dan.rigby@xamarin.com";
public string TwitterHandle => "DanRigby";
public Uri WebSite => new Uri("http://danrigby.com/");
public IEnumerable<Uri> FeedUris
{
get { yield return new Uri("https://feeds.feedburner.com/DanRigby"); }
}
public string GravatarHash => "f025f772418fbcfd3a1e15a74bf0f8a4";
public string GitHubHandle => string.Empty;
public GeoPosition Position => new GeoPosition(35.7595730, -79.0193000);
}
} | mit | C# |
bac654e3aa91077c4fd81e66ea21fff1e5c1d40b | Update on hourglass script. Still not in action | brunopagno/abandon-gds | Assets/Scripts/Controls/Hourglass.cs | Assets/Scripts/Controls/Hourglass.cs | using UnityEngine;
using System.Collections;
public class Hourglass : Trigger {
public GameObject cutsceneObject;
public Animator cutScene;
void Start() {
//cutScene = cutsceneObject.GetComponent<Animator>();
}
public override void Activate() {
UtilControls.Freeze();
cutScene.Play("cutscene");
GameObject.FindGameObjectWithTag("ThingsController").GetComponent<ThingsController>().ClearCurrentMemory();
}
public override void Deactivate() { /* nothing */ }
public override void Interact() { /* nothing */ }
}
| using UnityEngine;
using System.Collections;
public class Hourglass : Trigger {
public Animator cutScene;
public override void Activate() {
UtilControls.Freeze();
cutScene.Play("cutscene");
GameObject.FindGameObjectWithTag("ThingsController").GetComponent<ThingsController>().ClearCurrentMemory();
}
public override void Deactivate() { /* nothing */ }
public override void Interact() { /* nothing */ }
}
| mit | C# |
61e7b1c6bbf5cae0fdb339490725da22cebc4f2d | Fix automation name (for narrator) of the project combo box entries in the add environment dialog. (#5101) | zooba/PTVS,int19h/PTVS,huguesv/PTVS,Microsoft/PTVS,huguesv/PTVS,huguesv/PTVS,int19h/PTVS,zooba/PTVS,zooba/PTVS,int19h/PTVS,Microsoft/PTVS,zooba/PTVS,int19h/PTVS,Microsoft/PTVS,int19h/PTVS,Microsoft/PTVS,int19h/PTVS,huguesv/PTVS,zooba/PTVS,Microsoft/PTVS,zooba/PTVS,huguesv/PTVS,huguesv/PTVS,Microsoft/PTVS | Python/Product/PythonTools/PythonTools/Environments/ProjectView.cs | Python/Product/PythonTools/PythonTools/Environments/ProjectView.cs | // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Linq;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
namespace Microsoft.PythonTools.Environments {
sealed class ProjectView {
public PythonProjectNode Node { get; }
public IPythonWorkspaceContext Workspace { get; }
public string Name { get; set; }
public string HomeFolder { get; set; }
public string[] InterpreterIds { get; set; }
public string ActiveInterpreterId { get; set; }
public string RequirementsTxtPath { get; set; }
public string EnvironmentYmlPath { get; set; }
public string MissingCondaEnvName { get; set; }
public ProjectView(PythonProjectNode node) {
Node = node ?? throw new ArgumentNullException(nameof(node));
Name = node.Name;
HomeFolder = node.ProjectHome;
InterpreterIds = node.InterpreterIds.ToArray();
ActiveInterpreterId = node.ActiveInterpreter.Configuration.Id;
RequirementsTxtPath = node.GetRequirementsTxtPath();
EnvironmentYmlPath = node.GetEnvironmentYmlPath();
}
public ProjectView(IPythonWorkspaceContext workspace) {
Workspace = workspace ?? throw new ArgumentNullException(nameof(workspace));
Name = workspace.WorkspaceName;
HomeFolder = workspace.Location;
if (workspace.CurrentFactory != null) {
var id = workspace.CurrentFactory.Configuration.Id;
InterpreterIds = new string[] { id };
ActiveInterpreterId = id;
} else {
InterpreterIds = new string[0];
ActiveInterpreterId = string.Empty;
}
RequirementsTxtPath = workspace.GetRequirementsTxtPath();
EnvironmentYmlPath = workspace.GetEnvironmentYmlPath();
}
public override string ToString() => Name;
}
}
| // Python Tools for Visual Studio
// Copyright(c) Microsoft Corporation
// All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the License); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS
// OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY
// IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABILITY OR NON-INFRINGEMENT.
//
// See the Apache Version 2.0 License for specific language governing
// permissions and limitations under the License.
using System;
using System.Linq;
using Microsoft.PythonTools.Interpreter;
using Microsoft.PythonTools.Project;
namespace Microsoft.PythonTools.Environments {
sealed class ProjectView {
public PythonProjectNode Node { get; }
public IPythonWorkspaceContext Workspace { get; }
public string Name { get; set; }
public string HomeFolder { get; set; }
public string[] InterpreterIds { get; set; }
public string ActiveInterpreterId { get; set; }
public string RequirementsTxtPath { get; set; }
public string EnvironmentYmlPath { get; set; }
public string MissingCondaEnvName { get; set; }
public ProjectView(PythonProjectNode node) {
Node = node ?? throw new ArgumentNullException(nameof(node));
Name = node.Name;
HomeFolder = node.ProjectHome;
InterpreterIds = node.InterpreterIds.ToArray();
ActiveInterpreterId = node.ActiveInterpreter.Configuration.Id;
RequirementsTxtPath = node.GetRequirementsTxtPath();
EnvironmentYmlPath = node.GetEnvironmentYmlPath();
}
public ProjectView(IPythonWorkspaceContext workspace) {
Workspace = workspace ?? throw new ArgumentNullException(nameof(workspace));
Name = workspace.WorkspaceName;
HomeFolder = workspace.Location;
if (workspace.CurrentFactory != null) {
var id = workspace.CurrentFactory.Configuration.Id;
InterpreterIds = new string[] { id };
ActiveInterpreterId = id;
} else {
InterpreterIds = new string[0];
ActiveInterpreterId = string.Empty;
}
RequirementsTxtPath = workspace.GetRequirementsTxtPath();
EnvironmentYmlPath = workspace.GetEnvironmentYmlPath();
}
}
}
| apache-2.0 | C# |
941cc16250e325dc0fc2c8b1dd2c6423df309af9 | Save files as UTF-8 for consistency. | fixie/fixie | src/Fixie.Execution/Listeners/ReportListener.cs | src/Fixie.Execution/Listeners/ReportListener.cs | namespace Fixie.Execution.Listeners
{
using System;
using System.IO;
using System.Xml.Linq;
public class ReportListener<TXmlFormat> :
Handler<AssemblyStarted>,
Handler<ClassStarted>,
Handler<CaseCompleted>,
Handler<ClassCompleted>,
Handler<AssemblyCompleted>
where TXmlFormat : XmlFormat, new()
{
Report report;
ClassReport currentClass;
readonly Action<Report> save;
public ReportListener(Action<Report> save)
{
this.save = save;
}
public ReportListener()
: this(Save)
{
}
public void Handle(AssemblyStarted message)
{
report = new Report(message.Assembly);
}
public void Handle(ClassStarted message)
{
currentClass = new ClassReport(message.Class);
report.Add(currentClass);
}
public void Handle(CaseCompleted message)
{
currentClass.Add(message);
}
public void Handle(ClassCompleted message)
{
currentClass = null;
}
public void Handle(AssemblyCompleted message)
{
save(report);
report = null;
}
static void Save(Report report)
{
var format = new TXmlFormat();
var xDocument = format.Transform(report);
var filePath = Path.GetFullPath(report.Assembly.Location) + ".xml";
using (var stream = new FileStream(filePath, FileMode.Create))
using (var writer = new StreamWriter(stream))
xDocument.Save(writer, SaveOptions.None);
}
}
} | namespace Fixie.Execution.Listeners
{
using System;
using System.IO;
using System.Xml.Linq;
public class ReportListener<TXmlFormat> :
Handler<AssemblyStarted>,
Handler<ClassStarted>,
Handler<CaseCompleted>,
Handler<ClassCompleted>,
Handler<AssemblyCompleted>
where TXmlFormat : XmlFormat, new()
{
Report report;
ClassReport currentClass;
readonly Action<Report> save;
public ReportListener(Action<Report> save)
{
this.save = save;
}
public ReportListener()
: this(Save)
{
}
public void Handle(AssemblyStarted message)
{
report = new Report(message.Assembly);
}
public void Handle(ClassStarted message)
{
currentClass = new ClassReport(message.Class);
report.Add(currentClass);
}
public void Handle(CaseCompleted message)
{
currentClass.Add(message);
}
public void Handle(ClassCompleted message)
{
currentClass = null;
}
public void Handle(AssemblyCompleted message)
{
save(report);
report = null;
}
static void Save(Report report)
{
var format = new TXmlFormat();
var xDocument = format.Transform(report);
var filePath = Path.GetFullPath(report.Assembly.Location) + ".xml";
using (var stream = new FileStream(filePath, FileMode.Create))
using (var writer = new StreamWriter(stream))
xDocument.Save(writer, SaveOptions.None);
}
}
} | mit | C# |
8205c253834d7b49d80590ffb4b84b736f6d9d60 | Increment the Standalone Assembly Version | etodd/Steamworks.NET,rlabrecque/Steamworks.NET,itamargreen/Steamworks.NET,rlabrecque/Steamworks.NET,rlabrecque/Steamworks.NET,GoeGaming/Steamworks.NET,Gert-Jan/Steamworks.NET,Yukinii/Async-Await-Steamworks.NET,rlabrecque/Steamworks.NET | Standalone/Properties/AssemblyInfo.cs | Standalone/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("Steamworks.NET")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Riley Labrecque")]
[assembly: AssemblyProduct("Steamworks.NET")]
[assembly: AssemblyCopyright("Copyright © Riley Labrecque 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("316ab144-2a2a-4847-857b-63317c980dda")]
// 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.0")]
[assembly: AssemblyFileVersion("3.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("Steamworks.NET")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Riley Labrecque")]
[assembly: AssemblyProduct("Steamworks.NET")]
[assembly: AssemblyCopyright("Copyright © Riley Labrecque 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("316ab144-2a2a-4847-857b-63317c980dda")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.0.0")]
[assembly: AssemblyFileVersion("2.0.0")]
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.