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 |
|---|---|---|---|---|---|---|---|---|
a52f7aaca22e692aa93de0aaf142b422592e7ae4 | Make log4net appender render the log event (as zero log is rendering it, the comparison wouldn't be fair otherwise) | Abc-Arbitrage/ZeroLog | src/ZeroLog.Benchmarks/Tools/Log4NetTestAppender.cs | src/ZeroLog.Benchmarks/Tools/Log4NetTestAppender.cs | using System.Collections.Generic;
using System.Threading;
using log4net.Appender;
using log4net.Core;
namespace ZeroLog.Benchmarks
{
internal class Log4NetTestAppender : AppenderSkeleton
{
private readonly bool _captureLoggedMessages;
private int _messageCount;
private ManualResetEventSlim _signal;
private int _messageCountTarget;
public List<string> LoggedMessages { get; } = new List<string>();
public Log4NetTestAppender(bool captureLoggedMessages)
{
_captureLoggedMessages = captureLoggedMessages;
}
public ManualResetEventSlim SetMessageCountTarget(int expectedMessageCount)
{
_signal = new ManualResetEventSlim(false);
_messageCount = 0;
_messageCountTarget = expectedMessageCount;
return _signal;
}
protected override void Append(LoggingEvent loggingEvent)
{
var formatted = loggingEvent.RenderedMessage;
if (_captureLoggedMessages)
LoggedMessages.Add(loggingEvent.ToString());
if (++_messageCount == _messageCountTarget)
_signal.Set();
}
}
} | using System.Collections.Generic;
using System.Threading;
using log4net.Appender;
using log4net.Core;
namespace ZeroLog.Benchmarks
{
internal class Log4NetTestAppender : AppenderSkeleton
{
private readonly bool _captureLoggedMessages;
private int _messageCount;
private ManualResetEventSlim _signal;
private int _messageCountTarget;
public List<string> LoggedMessages { get; } = new List<string>();
public Log4NetTestAppender(bool captureLoggedMessages)
{
_captureLoggedMessages = captureLoggedMessages;
}
public ManualResetEventSlim SetMessageCountTarget(int expectedMessageCount)
{
_signal = new ManualResetEventSlim(false);
_messageCount = 0;
_messageCountTarget = expectedMessageCount;
return _signal;
}
protected override void Append(LoggingEvent loggingEvent)
{
if (_captureLoggedMessages)
LoggedMessages.Add(loggingEvent.ToString());
if (++_messageCount == _messageCountTarget)
_signal.Set();
}
}
} | mit | C# |
ab3addd520e51ec2ed3faf2acc67662f2ab5cd4e | Simplify Register | DimensionDataCBUSydney/jab | jab/jab/Test/ApiBestPracticeTestBase.cs | jab/jab/Test/ApiBestPracticeTestBase.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using jab.Interfaces;
using NSwag;
using NUnit.Framework;
namespace jab.Test
{
public partial class ApiBestPracticeTestBase
{
/// <summary>
/// Default constructor
/// </summary>
static ApiBestPracticeTestBase()
{
string swaggerFile;
using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("jab.Fixtures.swagger.json"))
using (StreamReader stringReader = new StreamReader(resourceStream))
{
swaggerFile = stringReader.ReadToEnd();
}
Configuration = new JabTestConfiguration(swaggerFile, null);
}
/// <summary>
/// Operations using the DELETE HTTP verb.
/// </summary>
protected static IEnumerable<TestCaseData> DeleteOperations =>
SwaggerTestHelpers.GetOperations(
Configuration,
jabApiOperation => jabApiOperation.Method == SwaggerOperationMethod.Delete);
/// <summary>
/// Operations.
/// </summary>
protected static IEnumerable<TestCaseData> Operations => SwaggerTestHelpers.GetOperations(Configuration);
/// <summary>
/// Services.
/// </summary>
protected static IEnumerable<TestCaseData> Services => SwaggerTestHelpers.GetServices(Configuration);
/// <summary>
/// The container used to pass configuration to the test class.
/// </summary>
public static IJabTestConfiguration Configuration { get; set; }
/// <summary>
/// Register components.
/// </summary>
/// <param name="swaggerFile">
/// The contents of the swagger file. This cannot be null, empty or whitespace.
/// </param>
/// <param name="baseUrl">
/// The optional base URL to use for testing the web service.
/// </param>
public static void Register(string swaggerFile, Uri baseUrl = null)
{
if (string.IsNullOrWhiteSpace(swaggerFile))
{
throw new ArgumentNullException(nameof(swaggerFile));
}
Configuration = new JabTestConfiguration(swaggerFile, baseUrl);
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using jab.Interfaces;
using NSwag;
using NUnit.Framework;
namespace jab.Test
{
public partial class ApiBestPracticeTestBase
{
/// <summary>
/// Default constructor
/// </summary>
static ApiBestPracticeTestBase()
{
string swaggerFile;
using (Stream resourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("jab.Fixtures.swagger.json"))
using (StreamReader stringReader = new StreamReader(resourceStream))
{
swaggerFile = stringReader.ReadToEnd();
}
Configuration = new JabTestConfiguration(swaggerFile, null);
}
/// <summary>
/// Operations using the DELETE HTTP verb.
/// </summary>
protected static IEnumerable<TestCaseData> DeleteOperations =>
SwaggerTestHelpers.GetOperations(
Configuration,
jabApiOperation => jabApiOperation.Method == SwaggerOperationMethod.Delete);
/// <summary>
/// Operations.
/// </summary>
protected static IEnumerable<TestCaseData> Operations => SwaggerTestHelpers.GetOperations(Configuration);
/// <summary>
/// Services.
/// </summary>
protected static IEnumerable<TestCaseData> Services => SwaggerTestHelpers.GetServices(Configuration);
/// <summary>
/// The container used to pass configuration to the test class.
/// </summary>
public static IJabTestConfiguration Configuration { get; set; }
/// <summary>
/// Register components.
/// </summary>
/// <param name="swaggerFile">
/// The contents of the swagger file. This cannot be null, empty or whitespace.
/// </param>
/// <param name="baseUrl">
/// The optional base URL to use for testing the web service.
/// </param>
public static void Register(string swaggerFile, Uri baseUrl = null)
{
if (string.IsNullOrWhiteSpace(swaggerFile))
{
throw new ArgumentNullException(nameof(swaggerFile));
}
Test.ApiBestPracticeTestBase.Configuration = new JabTestConfiguration(swaggerFile, baseUrl);
}
}
}
| apache-2.0 | C# |
18e50815232534bc456429b064ae3e71bc320a01 | Fix test failures | smoogipoo/osu,NeoAdonis/osu,peppy/osu-new,UselessToucan/osu,ppy/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,peppy/osu,smoogipooo/osu,ppy/osu,peppy/osu,UselessToucan/osu | osu.Game/Tests/Visual/Multiplayer/MultiplayerTestScene.cs | osu.Game/Tests/Visual/Multiplayer/MultiplayerTestScene.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Testing;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay;
using osu.Game.Screens.OnlinePlay.Lounge.Components;
namespace osu.Game.Tests.Visual.Multiplayer
{
public abstract class MultiplayerTestScene : RoomTestScene
{
[Cached(typeof(StatefulMultiplayerClient))]
public TestMultiplayerClient Client { get; }
[Cached(typeof(IRoomManager))]
public TestMultiplayerRoomManager RoomManager { get; }
[Cached]
public Bindable<FilterCriteria> Filter { get; }
[Cached]
public OngoingOperationTracker OngoingOperationTracker { get; }
protected override Container<Drawable> Content => content;
private readonly TestMultiplayerRoomContainer content;
private readonly bool joinRoom;
protected MultiplayerTestScene(bool joinRoom = true)
{
this.joinRoom = joinRoom;
base.Content.Add(content = new TestMultiplayerRoomContainer { RelativeSizeAxes = Axes.Both });
Client = content.Client;
RoomManager = content.RoomManager;
Filter = content.Filter;
OngoingOperationTracker = content.OngoingOperationTracker;
}
[SetUp]
public new void Setup() => Schedule(() =>
{
RoomManager.Schedule(() => RoomManager.PartRoom());
if (joinRoom)
RoomManager.Schedule(() => RoomManager.CreateRoom(Room));
});
public override void SetUpSteps()
{
base.SetUpSteps();
if (joinRoom)
AddUntilStep("wait for room join", () => Client.Room != null);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Online.Multiplayer;
using osu.Game.Screens.OnlinePlay;
using osu.Game.Screens.OnlinePlay.Lounge.Components;
namespace osu.Game.Tests.Visual.Multiplayer
{
public abstract class MultiplayerTestScene : RoomTestScene
{
[Cached(typeof(StatefulMultiplayerClient))]
public TestMultiplayerClient Client { get; }
[Cached(typeof(IRoomManager))]
public TestMultiplayerRoomManager RoomManager { get; }
[Cached]
public Bindable<FilterCriteria> Filter { get; }
[Cached]
public OngoingOperationTracker OngoingOperationTracker { get; }
protected override Container<Drawable> Content => content;
private readonly TestMultiplayerRoomContainer content;
private readonly bool joinRoom;
protected MultiplayerTestScene(bool joinRoom = true)
{
this.joinRoom = joinRoom;
base.Content.Add(content = new TestMultiplayerRoomContainer { RelativeSizeAxes = Axes.Both });
Client = content.Client;
RoomManager = content.RoomManager;
Filter = content.Filter;
OngoingOperationTracker = content.OngoingOperationTracker;
}
[SetUp]
public new void Setup() => Schedule(() =>
{
RoomManager.Schedule(() => RoomManager.PartRoom());
if (joinRoom)
RoomManager.Schedule(() => RoomManager.CreateRoom(Room));
});
}
}
| mit | C# |
86645f87ce6a6b2b8c2d81721f616f5e1fabf34e | Bump version to 1.0.0. | FacilityApi/Facility | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| using System.Reflection;
[assembly: AssemblyVersion("0.6.0.0")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyCopyright("Copyright 2016-2017 Ed Ball")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
| mit | C# |
507de36dd809a1b6690df24b1f7541867b896be8 | remove unneeded comments | mschray/CalendarHelper | OfficeHoursTopics/run.csx | OfficeHoursTopics/run.csx | using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
string[] Topics = new string[] {"Node.js","Azure Functions", "Azure App Services"};
return Topics == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, Topics);
} | using System.Net;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");
// parse query parameter
//string name = req.GetQueryNameValuePairs()
// .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
// .Value;
// Get request body
//dynamic data = await req.Content.ReadAsAsync<object>();
// Set name to query string or body data
//name = name ?? data?.name;
string[] Topics = new string[] {"Node.js","Azure Functions", "Azure App Services"};
return Topics == null
? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
: req.CreateResponse(HttpStatusCode.OK, Topics);
} | mit | C# |
0fed25acd36bb30a3af8b11e0913a1b24f41dba3 | send some sample Sensu checks for machine health | sepehr-laal/OpenRoC | OpenRoC/SensuInterface.cs | OpenRoC/SensuInterface.cs | namespace oroc
{
using liboroc;
using System;
using System.Text;
using System.Net.Sockets;
public class SensuInterface : IDisposable
{
private readonly ProcessManager Manager;
private UdpClient sensuClientSocket;
public SensuInterface(ProcessManager manager)
{
Manager = manager;
try
{
sensuClientSocket = new UdpClient(
Settings.Instance.SensuInterfaceHost,
(int)Settings.Instance.SensuInterfacePort);
}
catch(Exception ex)
{
Log.e("Failed to construct Sensu client socket: {0}", ex.Message);
sensuClientSocket = null;
}
}
public void SendChecks()
{
if (sensuClientSocket == null)
return;
byte[] data = null;
Manager.ProcessRunnerList.ForEach(runner =>
{
data = runner.ToSensuCheck();
sensuClientSocket.Send(data, data.Length);
});
data = Encoding.Default.GetBytes(new
{
name = string.Format("{0}", Environment.MachineName),
output = string.Format("Uptime: {0}", TimeSpan.FromTicks(Environment.TickCount)),
status = 1
}
.ToJson());
sensuClientSocket.Send(data, data.Length);
}
#region IDisposable Support
public bool IsDisposed { get; private set; } = false;
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
IsDisposed = true;
if (disposing)
{
sensuClientSocket?.Close();
}
sensuClientSocket = null;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| namespace oroc
{
using liboroc;
using System;
using System.Net.Sockets;
public class SensuInterface : IDisposable
{
private readonly ProcessManager Manager;
private UdpClient sensuClientSocket;
public SensuInterface(ProcessManager manager)
{
Manager = manager;
try
{
sensuClientSocket = new UdpClient(
Settings.Instance.SensuInterfaceHost,
(int)Settings.Instance.SensuInterfacePort);
}
catch(Exception ex)
{
Log.e("Failed to construct Sensu client socket: {0}", ex.Message);
sensuClientSocket = null;
}
}
public void SendChecks()
{
if (sensuClientSocket == null)
return;
Manager.ProcessRunnerList.ForEach(runner =>
{
byte[] data = runner.ToSensuCheck();
sensuClientSocket.Send(data, data.Length);
});
}
#region IDisposable Support
public bool IsDisposed { get; private set; } = false;
protected virtual void Dispose(bool disposing)
{
if (!IsDisposed)
{
IsDisposed = true;
if (disposing)
{
sensuClientSocket?.Close();
}
sensuClientSocket = null;
}
}
public void Dispose()
{
Dispose(true);
}
#endregion
}
}
| mit | C# |
9554bd6b8512d68202d442829c6527252206b6c6 | Update Structure Data | Slazanger/SMT | EVEData/Structure.cs | EVEData/Structure.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMT.EVEData
{
class Structure
{
public enum StructureType
{
// citadel
Astrahus,
Fortizar,
FactionFortizar,
Keepstar,
// engineering
Raitaru,
Azbel,
Sotiyo,
// refineries
Athanor,
Tatara,
NPC_Station,
// Ansiblex
JumpGate,
CynoBecon,
CynoJammer
}
public enum PowerState
{
Normal,
LowPower,
Shield,
Armor,
}
public string ID { get; set; }
public string Name { get; set; }
public string System { get; set; }
public DateTime LastUpdate { get; set; }
public PowerState State { get; set; }
public StructureType Type { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SMT.EVEData
{
class Structure
{
public enum UpwellType
{
// citadel
Astrahus,
Fortizar,
FactionFortizar,
Keepstar,
// engineering
Raitaru,
Azbel,
Sotiyo,
// refineries
Athanor,
Tatara,
NPC_Station,
}
public enum PowerState
{
Normal,
LowPower,
Shield,
Armor,
}
public string ID { get; set; }
public string Name { get; set; }
public string System { get; set; }
public DateTime LastUpdate { get; set; }
public PowerState State { get; set; }
public UpwellType Type { get; set; }
}
}
| mit | C# |
dc3239fcc50bf52216181e2ad74fd975609a8ff9 | Increment version | hivepeople/FluentAssertionsEx | FluentAssertionsEx/Properties/AssemblyInfo.cs | FluentAssertionsEx/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("FluentAssertionsEx")]
[assembly: AssemblyDescription("Extensions for FluentAssertions")]
[assembly: AssemblyCompany("HivePeople ApS")]
[assembly: AssemblyProduct("FluentAssertionsEx")]
[assembly: AssemblyCopyright("Copyright © HivePeople 2016")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.7")]
// This is needed for specifying NuGet package version since AssemblyVersion does
// not support semantic versioning.
[assembly: AssemblyInformationalVersion("1.0.0-alpha7")]
| 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("FluentAssertionsEx")]
[assembly: AssemblyDescription("Extensions for FluentAssertions")]
[assembly: AssemblyCompany("HivePeople ApS")]
[assembly: AssemblyProduct("FluentAssertionsEx")]
[assembly: AssemblyCopyright("Copyright © HivePeople 2016")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.0.6")]
// This is needed for specifying NuGet package version since AssemblyVersion does
// not support semantic versioning.
[assembly: AssemblyInformationalVersion("1.0.0-alpha6")]
| apache-2.0 | C# |
19fd3c0dc9adb8ff6ce74a6df7d6294e82c9c97c | Change seeding of topic categories | SkoodleNinjas/Skoodle,SkoodleNinjas/Skoodle | Skoodle/App_Start/CustomInitializer.cs | Skoodle/App_Start/CustomInitializer.cs | using Skoodle.Models;
using System.Data.Entity;
namespace Skoodle.App_Start
{
public class CustomInitializer: DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
Cathegory Category1 = new Cathegory { CathegoryName = "Category1" };
Cathegory Category2 = new Cathegory { CathegoryName = "Category2" };
Cathegory Category3 = new Cathegory { CathegoryName = "Category3" };
context.Topics.Add(new Topic { Name = "Topic1", Category = Category1 });
context.Topics.Add(new Topic { Name = "Topic2", Category = Category1 });
context.Topics.Add(new Topic { Name = "Topic3", Category = Category2 });
context.Topics.Add(new Topic { Name = "Topic4", Category = Category2 });
context.Topics.Add(new Topic { Name = "Topic5", Category = Category3 });
context.SaveChanges();
}
}
} | using Skoodle.Models;
using System.Data.Entity;
namespace Skoodle.App_Start
{
public class CustomInitializer: DropCreateDatabaseAlways<ApplicationDbContext>
{
protected override void Seed(ApplicationDbContext context)
{
context.Topics.Add(new Topic { Name = "Topic1", Category = "Category1" });
context.Topics.Add(new Topic { Name = "Topic2", Category = "Category1" });
context.Topics.Add(new Topic { Name = "Topic3", Category = "Category2" });
context.Topics.Add(new Topic { Name = "Topic4", Category = "Category2" });
context.Topics.Add(new Topic { Name = "Topic5", Category = "Category3" });
context.SaveChanges();
}
}
} | mit | C# |
90430aef9bbbfdd887d0ea47b7c28788ee86aa9a | fix missing save | yuxuac/docs.particular.net,eclaus/docs.particular.net,WojcikMike/docs.particular.net,pashute/docs.particular.net,pedroreys/docs.particular.net,SzymonPobiega/docs.particular.net | Snippets/Snippets_5/ContainerCustom.cs | Snippets/Snippets_5/ContainerCustom.cs | using System;
using System.Collections.Generic;
using NServiceBus;
using NServiceBus.Container;
using NServiceBus.ObjectBuilder.Common;
using NServiceBus.Settings;
public class ContainerCustom
{
// startcode CustomContainersV5
public void CustomContainerExtensionUsage()
{
Configure.With(b => b.UseContainer<MyContainer>());
}
public class MyContainer : ContainerDefinition
{
public override IContainer CreateContainer(ReadOnlySettings settings)
{
return new MyObjectBuilder();
}
}
public class MyObjectBuilder : IContainer
{
// endcode
public void Dispose()
{
throw new NotImplementedException();
}
public object Build(Type typeToBuild)
{
throw new NotImplementedException();
}
public IContainer BuildChildContainer()
{
throw new NotImplementedException();
}
public IEnumerable<object> BuildAll(Type typeToBuild)
{
throw new NotImplementedException();
}
public void Configure(Type component, DependencyLifecycle dependencyLifecycle)
{
throw new NotImplementedException();
}
public void Configure<T>(Func<T> component, DependencyLifecycle dependencyLifecycle)
{
throw new NotImplementedException();
}
public void ConfigureProperty(Type component, string property, object value)
{
throw new NotImplementedException();
}
public void RegisterSingleton(Type lookupType, object instance)
{
throw new NotImplementedException();
}
public bool HasComponent(Type componentType)
{
throw new NotImplementedException();
}
public void Release(object instance)
{
throw new NotImplementedException();
}
}
}
| using System;
using System.Collections.Generic;
using NServiceBus;
using NServiceBus.Container;
using NServiceBus.ObjectBuilder.Common;
using NServiceBus.Settings;
public class ContainerCustom
{
#region CustomContainersV5
public void CustomContainerExtensionUsage()
{
Configure.With(b => b.UseContainer<MyContainer>());
}
public class MyContainer : ContainerDefinition
{
public override IContainer CreateContainer(ReadOnlySettings settings)
{
return new MyObjectBuilder();
}
}
#endregion
}
public class MyObjectBuilder : IContainer
{
public void Dispose()
{
throw new NotImplementedException();
}
public object Build(Type typeToBuild)
{
throw new NotImplementedException();
}
public IContainer BuildChildContainer()
{
throw new NotImplementedException();
}
public IEnumerable<object> BuildAll(Type typeToBuild)
{
throw new NotImplementedException();
}
public void Configure(Type component, DependencyLifecycle dependencyLifecycle)
{
throw new NotImplementedException();
}
public void Configure<T>(Func<T> component, DependencyLifecycle dependencyLifecycle)
{
throw new NotImplementedException();
}
public void ConfigureProperty(Type component, string property, object value)
{
throw new NotImplementedException();
}
public void RegisterSingleton(Type lookupType, object instance)
{
throw new NotImplementedException();
}
public bool HasComponent(Type componentType)
{
throw new NotImplementedException();
}
public void Release(object instance)
{
throw new NotImplementedException();
}
} | apache-2.0 | C# |
671f5166cb0bc50ca00853acf03fc0bc66bb0166 | Add OrchardCore.DynamicCache as module dependency | Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module,Lombiq/Orchard-Training-Demo-Module | Manifest.cs | Manifest.cs | using OrchardCore.Modules.Manifest;
[assembly: Module(
// Name of the module to be displayed on the Modules page of the Dashboard.
Name = "Orchard Core Training Demo",
// Your name, company or any name that identifies the developers working on the project.
Author = "Lombiq",
// Optionally you can add a website URL (e.g. your company's website, GitHub repository URL).
Website = "https://github.com/Lombiq/Orchard-Training-Demo-Module",
// Version of the module.
Version = "2.0.0-alpha1",
// Short description of the module. It will be displayed on the Dashboard.
Description = "Orchard Core training demo module for teaching Orchard Core fundamentals primarily by going " +
"through its source code.",
// Modules are categorized on the Dashboard so it's a good idea to put similar modules together into a separate
// section.
Category = "Training",
// Modules can have dependencies which are other module names (name of the project) or if these modules have
// subfeatures then the name of the feature. If you use any service, taghelper etc. coming from an Orchard Core
// feature then you need to include them in this list. Orchard Core will make sure to enable all dependent modules
// when you enable a module that has dependencies. Without this some features would not work even if the assembly
// is referenced in the project.
Dependencies = new[]
{
"Lombiq.VueJs",
"OrchardCore.BackgroundTasks",
"OrchardCore.Contents",
"OrchardCore.ContentTypes",
"OrchardCore.ContentFields",
"OrchardCore.DynamicCache",
"OrchardCore.Media",
"OrchardCore.Navigation"
}
)]
// END OF TRAINING SECTION: Manifest
// NEXT STATION: Controllers/YourFirstOrchardCoreController.cs | using OrchardCore.Modules.Manifest;
[assembly: Module(
// Name of the module to be displayed on the Modules page of the Dashboard.
Name = "Orchard Core Training Demo",
// Your name, company or any name that identifies the developers working on the project.
Author = "Lombiq",
// Optionally you can add a website URL (e.g. your company's website, GitHub repository URL).
Website = "https://github.com/Lombiq/Orchard-Training-Demo-Module",
// Version of the module.
Version = "2.0.0-alpha1",
// Short description of the module. It will be displayed on the Dashboard.
Description = "Orchard Core training demo module for teaching Orchard Core fundamentals primarily by going " +
"through its source code.",
// Modules are categorized on the Dashboard so it's a good idea to put similar modules together into a separate
// section.
Category = "Training",
// Modules can have dependencies which are other module names (name of the project) or if these modules have
// subfeatures then the name of the feature. If you use any service, taghelper etc. coming from an Orchard Core
// feature then you need to include them in this list. Orchard Core will make sure to enable all dependent modules
// when you enable a module that has dependencies. Without this some features would not work even if the assembly
// is referenced in the project.
Dependencies = new[]
{
"Lombiq.VueJs",
"OrchardCore.BackgroundTasks",
"OrchardCore.Contents",
"OrchardCore.ContentTypes",
"OrchardCore.ContentFields",
"OrchardCore.Media",
"OrchardCore.Navigation"
}
)]
// END OF TRAINING SECTION: Manifest
// NEXT STATION: Controllers/YourFirstOrchardCoreController.cs | bsd-3-clause | C# |
9b565f643b4d38d0266046b4b352ce4cf70b0efc | debug CI | Fody/Fody,GeertvanHorrik/Fody | Tests/Fody/AddinFinderTest/AddinFinderTest.cs | Tests/Fody/AddinFinderTest/AddinFinderTest.cs | using System;
using System.IO;
using System.Linq;
using Xunit;
using ObjectApproval;
public class AddinFinderTest : TestBase
{
[Fact]
public void WithNuGetPackageRoot()
{
var combine = Path.GetFullPath(Path.Combine(AssemblyLocation.CurrentDirectory, "../../../Fody/FakeNuGetPackageRoot"));
var nuGetPackageRoot = Path.GetFullPath(combine);
var result = AddinFinder.ScanDirectoryForPackages(nuGetPackageRoot)
.Select(s => s.Replace(@"\\", @"\").Replace(combine, ""))
.ToList();
ObjectApprover.VerifyWithJson(result);
}
[Fact]
public void Integration_OldNugetStructure()
{
var combine = Path.GetFullPath(Path.Combine(AssemblyLocation.CurrentDirectory, "Fody/AddinFinderTest/OldNugetStructure"));
Verify(combine);
}
[Fact]
public void Integration_NewNugetStructure()
{
var combine = Path.GetFullPath(Path.Combine(AssemblyLocation.CurrentDirectory, "Fody/AddinFinderTest/NewNugetStructure"));
Verify(combine);
}
static void Verify(string combine)
{
var addinFinder = new AddinFinder(
log: s => { },
solutionDirectory: Path.Combine(combine, "Solution"),
msBuildTaskDirectory: Path.Combine(combine, "MsBuildDirectory/1/2/3"),
nuGetPackageRoot: Path.Combine(combine, "NuGetPackageRoot"),
packageDefinitions: null);
addinFinder.FindAddinDirectories();
throw new Exception(ObjectApprover.AsFormattedJson(addinFinder.FodyFiles.Select(x => x.Replace(combine, ""))));
ObjectApprover.VerifyWithJson(addinFinder.FodyFiles.Select(x => x.Replace(combine, "")));
}
} | using System.IO;
using System.Linq;
using Xunit;
using ObjectApproval;
public class AddinFinderTest : TestBase
{
[Fact]
public void WithNuGetPackageRoot()
{
var combine = Path.GetFullPath(Path.Combine(AssemblyLocation.CurrentDirectory, "../../../Fody/FakeNuGetPackageRoot"));
var nuGetPackageRoot = Path.GetFullPath(combine);
var result = AddinFinder.ScanDirectoryForPackages(nuGetPackageRoot)
.Select(s => s.Replace(@"\\", @"\").Replace(combine, ""))
.ToList();
ObjectApprover.VerifyWithJson(result);
}
[Fact]
public void Integration_OldNugetStructure()
{
var combine = Path.GetFullPath(Path.Combine(AssemblyLocation.CurrentDirectory, "Fody/AddinFinderTest/OldNugetStructure"));
Verify(combine);
}
[Fact]
public void Integration_NewNugetStructure()
{
var combine = Path.GetFullPath(Path.Combine(AssemblyLocation.CurrentDirectory, "Fody/AddinFinderTest/NewNugetStructure"));
Verify(combine);
}
static void Verify(string combine)
{
var addinFinder = new AddinFinder(
log: (s) => { },
solutionDirectory: Path.Combine(combine, "Solution"),
msBuildTaskDirectory: Path.Combine(combine, "MsBuildDirectory/1/2/3"),
nuGetPackageRoot: Path.Combine(combine, "NuGetPackageRoot"),
packageDefinitions: null);
addinFinder.FindAddinDirectories();
ObjectApprover.VerifyWithJson(addinFinder.FodyFiles.Select(x => x.Replace(combine, "")));
}
} | mit | C# |
83b6018f2d5b7d6345e26007bc28edc7e14ed582 | Update Console Program with a Condition - Rename GetRoleMessageTest to GetRoleMessageForAdminTest so it is more specific | penblade/Training.CSharpWorkshop | Training.CSharpWorkshop.Tests/ProgramTests.cs | Training.CSharpWorkshop.Tests/ProgramTests.cs | using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Training.CSharpWorkshop.Tests
{
[TestClass]
public class ProgramTests
{
[Ignore]
[TestMethod]
public void IgnoreTest()
{
Assert.Fail();
}
[TestMethod()]
public void GetRoleMessageForAdminTest()
{
// Arrange
var userName = "Andrew";
var expected = "Role: Admin.";
// Act
var actual = Program.GetRoleMessage(userName);
// Assert
Assert.AreEqual(expected, actual);
}
}
}
| using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Training.CSharpWorkshop.Tests
{
[TestClass]
public class ProgramTests
{
[Ignore]
[TestMethod]
public void IgnoreTest()
{
Assert.Fail();
}
[TestMethod()]
public void GetRoleMessageTest()
{
// Arrange
var userName = "Andrew";
var expected = "Role: Admin.";
// Act
var actual = Program.GetRoleMessage(userName);
// Assert
Assert.AreEqual(expected, actual);
}
}
}
| mit | C# |
929be74947ce49ffbee575d42f29c4d66925e3ab | Initialize rotation path | bartlomiejwolk/AnimationPathAnimator | PathData.cs | PathData.cs | using UnityEngine;
using System.Collections;
namespace ATP.AnimationPathTools {
public class PathData : ScriptableObject {
[SerializeField]
private AnimationPath animatedObjectPath;
[SerializeField]
private AnimationPath rotationPath;
[SerializeField]
private AnimationCurve easeCurve;
[SerializeField]
private AnimationCurve tiltingCurve;
private void OnEnable() {
InstantiateReferenceTypes();
AssignDefaultValues();
}
private void AssignDefaultValues() {
InitializeAnimatedObjectPath();
InitializeRotationPath();
}
private void InitializeRotationPath() {
var firstNodePos = new Vector3(0, 0, 0);
rotationPath.CreateNewNode(0, firstNodePos);
var lastNodePos = new Vector3(1, 0, 1);
rotationPath.CreateNewNode(1, lastNodePos);
}
private void InitializeAnimatedObjectPath() {
var firstNodePos = new Vector3(0, 0, 0);
animatedObjectPath.CreateNewNode(0, firstNodePos);
var lastNodePos = new Vector3(1, 0, 1);
animatedObjectPath.CreateNewNode(1, lastNodePos);
}
private void InstantiateReferenceTypes() {
animatedObjectPath =
ScriptableObject.CreateInstance<AnimationPath>();
rotationPath =
ScriptableObject.CreateInstance<AnimationPath>();
easeCurve = new AnimationCurve();
tiltingCurve = new AnimationCurve();
}
}
}
| using UnityEngine;
using System.Collections;
namespace ATP.AnimationPathTools {
public class PathData : ScriptableObject {
[SerializeField]
private AnimationPath animatedObjectPath;
[SerializeField]
private AnimationPath rotationPath;
[SerializeField]
private AnimationCurve easeCurve;
[SerializeField]
private AnimationCurve tiltingCurve;
private void OnEnable() {
InstantiateReferenceTypes();
AssignDefaultValues();
}
private void AssignDefaultValues() {
InitializeAnimatedObjectPath();
}
private void InitializeAnimatedObjectPath() {
var firstNodePos = new Vector3(0, 0, 0);
animatedObjectPath.CreateNewNode(0, firstNodePos);
var lastNodePos = new Vector3(1, 0, 1);
animatedObjectPath.CreateNewNode(1, lastNodePos);
}
private void InstantiateReferenceTypes() {
animatedObjectPath =
ScriptableObject.CreateInstance<AnimationPath>();
rotationPath =
ScriptableObject.CreateInstance<AnimationPath>();
easeCurve = new AnimationCurve();
tiltingCurve = new AnimationCurve();
}
}
}
| mit | C# |
0aa701f00896fc5d77f0bf5fa0907d6dff7c694f | Bump version | CSIS/EnrollmentStation | EnrollmentStation/Properties/AssemblyInfo.cs | EnrollmentStation/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("EnrollmentStation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnrollmentStation")]
[assembly: AssemblyCopyright("Copyright © Ian Qvist, Michael Bisbjerg 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("80874570-42c0-4473-8dc5-bea5af3e110e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.4.2")]
[assembly: AssemblyFileVersion("0.3.4.2")]
| 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("EnrollmentStation")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("EnrollmentStation")]
[assembly: AssemblyCopyright("Copyright © Ian Qvist, Michael Bisbjerg 2016")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("80874570-42c0-4473-8dc5-bea5af3e110e")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.3.4.1")]
[assembly: AssemblyFileVersion("0.3.4.1")]
| mit | C# |
ac612493abd6a203647ca282435d59fc207a5bac | Fix demo code - never use Clock.Now in a test, even for a demo :) | malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime,jskeet/nodatime,nodatime/nodatime,malcolmr/nodatime,zaccharles/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,nodatime/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime | src/NodaTime.Demo/TimeZoneDemo.cs | src/NodaTime.Demo/TimeZoneDemo.cs | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2010 Jon Skeet
//
// 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
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Demo
{
[TestFixture]
public class TimeZoneDemo
{
[Test]
public void EarlyParis()
{
DateTimeZone paris = DateTimeZones.ForId("Europe/Paris");
Offset offset = paris.GetOffsetFromUtc(Instant.FromUtc(1900, 1, 1, 0, 0));
Assert.AreEqual("+0:09:21", offset.ToString());
}
[Test]
public void BritishDoubleSummerTime()
{
DateTimeZone london = DateTimeZones.ForId("Europe/London");
Offset offset = london.GetOffsetFromUtc(Instant.FromUtc(1942, 7, 1, 0, 0));
Assert.AreEqual("+2", offset.ToString());
}
[Test]
public void ZoneInterval()
{
DateTimeZone london = DateTimeZones.ForId("Europe/London");
ZoneInterval interval = london.GetZoneInterval(Instant.FromUtc(2010, 6, 19, 0, 0));
Assert.AreEqual("BST", interval.Name);
Assert.AreEqual(Instant.FromUtc(2010, 3, 28, 1, 0), interval.Start);
Assert.AreEqual(Instant.FromUtc(2010, 10, 31, 1, 0), interval.End);
Assert.AreEqual(Offset.ForHours(1), interval.Offset);
Assert.AreEqual(Offset.ForHours(1), interval.Savings);
}
}
} | #region Copyright and license information
// Copyright 2001-2009 Stephen Colebourne
// Copyright 2009-2010 Jon Skeet
//
// 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
using NodaTime.TimeZones;
using NUnit.Framework;
namespace NodaTime.Demo
{
[TestFixture]
public class TimeZoneDemo
{
[Test]
public void EarlyParis()
{
DateTimeZone paris = DateTimeZones.ForId("Europe/Paris");
Offset offset = paris.GetOffsetFromUtc(Instant.FromUtc(1900, 1, 1, 0, 0));
Assert.AreEqual("+0:09:21", offset.ToString());
}
[Test]
public void BritishDoubleSummerTime()
{
DateTimeZone london = DateTimeZones.ForId("Europe/London");
Offset offset = london.GetOffsetFromUtc(Instant.FromUtc(1942, 7, 1, 0, 0));
Assert.AreEqual("+2", offset.ToString());
}
[Test]
public void ZoneInterval()
{
DateTimeZone london = DateTimeZones.ForId("Europe/London");
ZoneInterval interval = london.GetZoneInterval(Clock.Now);
Assert.AreEqual("BST", interval.Name);
Assert.AreEqual(Instant.FromUtc(2010, 3, 28, 1, 0), interval.Start);
Assert.AreEqual(Instant.FromUtc(2010, 10, 31, 1, 0), interval.End);
Assert.AreEqual(Offset.ForHours(1), interval.Offset);
Assert.AreEqual(Offset.ForHours(1), interval.Savings);
}
}
} | apache-2.0 | C# |
616aeba156d617c98955e437f3283ae66206c2ba | Use chrome instead of chromium on Ubuntu | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | test/Kestrel.Transport.FunctionalTests/ChromeConstants.cs | test/Kestrel.Transport.FunctionalTests/ChromeConstants.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 System.IO;
using System.Runtime.InteropServices;
namespace Interop.FunctionalTests
{
public static class ChromeConstants
{
public static string ExecutablePath { get; } = ResolveChromeExecutablePath();
private static string ResolveChromeExecutablePath()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Google", "Chrome", "Application", "chrome.exe");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return Path.Combine("/usr", "bin", "google-chrome");
}
throw new PlatformNotSupportedException();
}
}
}
| // 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 System.IO;
using System.Runtime.InteropServices;
namespace Interop.FunctionalTests
{
public static class ChromeConstants
{
public static string ExecutablePath { get; } = ResolveChromeExecutablePath();
private static string ResolveChromeExecutablePath()
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Google", "Chrome", "Application", "chrome.exe");
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
return Path.Combine("/usr", "bin", "chromium-browser");
}
throw new PlatformNotSupportedException();
}
}
}
| apache-2.0 | C# |
4dee01e9cd595a9be31046c26f60c742e26a49f3 | Complete the WebApi work, needs tests | csf-dev/agiil,csf-dev/agiil,csf-dev/agiil,csf-dev/agiil | Agiil.Web/ApiControllers/TicketController.cs | Agiil.Web/ApiControllers/TicketController.cs | using System;
using System.Net;
using System.Threading;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Agiil.Domain.Tickets;
using Agiil.Web.Models;
using Agiil.Web.Services.Tickets;
using CSF.Entities;
namespace Agiil.Web.ApiControllers
{
public class TicketController : ApiController
{
readonly Lazy<ITicketCreator> ticketCreator;
readonly Lazy<ITicketEditor> ticketEditor;
readonly Lazy<ITicketDetailService> ticketDetailService;
readonly TicketDetailMapper mapper;
public NewTicketResponse Put(NewTicketSpecification ticket)
{
if(ticket == null)
{
throw new ArgumentNullException(nameof(ticket));
}
var request = new CreateTicketRequest
{
Title = ticket.Title,
Description = ticket.Description,
};
var response = ticketCreator.Value.Create(request);
return new NewTicketResponse
{
TitleIsInvalid = response.TitleIsInvalid,
DescriptionIsInvalid = response.DescriptionIsInvalid,
TicketIdentity = response.Ticket?.GetIdentity()?.Value,
};
}
public Models.EditTicketTitleAndDescriptionResponse Post(EditTicketTitleAndDescriptionSpecification ticket)
{
if(ticket == null)
{
throw new ArgumentNullException(nameof(ticket));
}
var request = new EditTicketTitleAndDescriptionRequest
{
Identity = ticket.Identity,
Title = ticket.Title,
Description = ticket.Description,
};
var response = ticketEditor.Value.Edit(request);
if(response.IdentityIsInvalid)
throw new HttpResponseException(HttpStatusCode.NotFound);
return new Models.EditTicketTitleAndDescriptionResponse
{
Success = response.IsSuccess,
TitleIsInvalid = response.TitleIsInvalid,
DescriptionIsInvalid = response.DescriptionIsInvalid,
};
}
public TicketDetailDto Get(IIdentity<Ticket> id)
{
var ticket = ticketDetailService.Value.GetTicket(id);
if(ReferenceEquals(ticket, null))
throw new HttpResponseException(HttpStatusCode.NotFound);
return mapper.Map(ticket);
}
public TicketController(Lazy<ITicketCreator> ticketCreator,
Lazy<ITicketDetailService> ticketDetailService,
Lazy<ITicketEditor> ticketEditor,
TicketDetailMapper mapper)
{
if(ticketCreator == null)
throw new ArgumentNullException(nameof(ticketCreator));
if(mapper == null)
throw new ArgumentNullException(nameof(mapper));
if(ticketDetailService == null)
throw new ArgumentNullException(nameof(ticketDetailService));
this.ticketDetailService = ticketDetailService;
this.mapper = mapper;
this.ticketCreator = ticketCreator;
this.ticketEditor = ticketEditor;
}
}
}
| using System;
using System.Net;
using System.Threading;
using System.Web.Http;
using System.Web.Http.ModelBinding;
using Agiil.Domain.Tickets;
using Agiil.Web.Models;
using Agiil.Web.Services.Tickets;
using CSF.Entities;
namespace Agiil.Web.ApiControllers
{
public class TicketController : ApiController
{
readonly ITicketCreator ticketCreator;
readonly ITicketDetailService ticketDetailService;
readonly TicketDetailMapper mapper;
public NewTicketResponse Put(NewTicketSpecification ticket)
{
if(ticket == null)
{
throw new ArgumentNullException(nameof(ticket));
}
var request = new CreateTicketRequest
{
Title = ticket.Title,
Description = ticket.Description,
};
var response = ticketCreator.Create(request);
return new NewTicketResponse
{
TitleIsInvalid = response.TitleIsInvalid,
DescriptionIsInvalid = response.DescriptionIsInvalid,
TicketIdentity = response.Ticket?.GetIdentity()?.Value,
};
}
public TicketDetailDto Get(IIdentity<Ticket> id)
{
var ticket = ticketDetailService.GetTicket(id);
if(ReferenceEquals(ticket, null))
throw new HttpResponseException(HttpStatusCode.NotFound);
return mapper.Map(ticket);
}
public TicketController(ITicketCreator ticketCreator,
ITicketDetailService ticketDetailService,
TicketDetailMapper mapper)
{
if(ticketCreator == null)
throw new ArgumentNullException(nameof(ticketCreator));
if(mapper == null)
throw new ArgumentNullException(nameof(mapper));
if(ticketDetailService == null)
throw new ArgumentNullException(nameof(ticketDetailService));
this.ticketDetailService = ticketDetailService;
this.mapper = mapper;
this.ticketCreator = ticketCreator;
}
}
}
| mit | C# |
1b1562016125189f7d15ba3cc4f36a07bdca82c4 | mark the client assembly to be CLS Compliant; generated some CLS compliance errors that will need to be cleaned up | mlittle/avaya-moagent-client | AvayaMoagentClient/Properties/AssemblyInfo.cs | AvayaMoagentClient/Properties/AssemblyInfo.cs | //Copyright (c) 2010 - 2012, Matthew J Little and contributors.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted
//provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
//IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
using System;
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("AvayaMoagentClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AvayaMoagentClient")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: CLSCompliant(true)]
// 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("2860eacf-b5a4-4de1-9c4b-52ebf02e369a")]
// 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.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
| //Copyright (c) 2010 - 2012, Matthew J Little and contributors.
//All rights reserved.
//
//Redistribution and use in source and binary forms, with or without modification, are permitted
//provided that the following conditions are met:
//
// Redistributions of source code must retain the above copyright notice, this list of conditions
// and the following disclaimer.
//
// Redistributions in binary form must reproduce the above copyright notice, this list of
// conditions and the following disclaimer in the documentation and/or other materials provided
// with the distribution.
//
//THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
//IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
//FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
//CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
//DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
//DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
//WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
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("AvayaMoagentClient")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("AvayaMoagentClient")]
[assembly: AssemblyCopyright("Copyright © 2010")]
[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("2860eacf-b5a4-4de1-9c4b-52ebf02e369a")]
// 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.1.0")]
[assembly: AssemblyFileVersion("1.0.1.0")]
| bsd-2-clause | C# |
cd14bcb3046892f5c99c11231c7da66bf0a49d87 | Add constructors with custom message | mkropat/BetterWin32Errors | BetterWin32Errors/Win32Exception.cs | BetterWin32Errors/Win32Exception.cs | using System;
using System.Runtime.InteropServices;
namespace BetterWin32Errors
{
/// <summary>
/// Exception that represents a <see cref="Win32Error"/>.
/// </summary>
public class Win32Exception : Exception
{
/// <summary>
/// Returns the last <see cref="Win32Error"/>. Note: make sure to set SetLastError=true on <see cref="DllImportAttribute"/>.
/// </summary>
/// <returns></returns>
public static Win32Error GetLastWin32Error()
{
return (Win32Error)Marshal.GetLastWin32Error();
}
/// <summary>
/// The <see cref="Win32Error"/> that the exception represents.
/// </summary>
public Win32Error Error { get; private set; }
/// <summary>
/// A human readable message associated with the <see cref="Win32Error"/>.
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// Custom message which can be utilized in logic code.
/// </summary>
public string CustomMessage { get; private set; }
/// <summary>
/// Create a new exception using the value from <see cref="GetLastWin32Error"/>. Note: make sure to set SetLastError=true on <see cref="DllImportAttribute"/>.
/// </summary>
public Win32Exception()
: this(GetLastWin32Error())
{
}
/// <summary>
/// Create a new exception with given error code.
/// </summary>
public Win32Exception(Win32Error error)
: base($"{error}: {GetMessage(error)}")
{
Error = error;
ErrorMessage = GetMessage(error);
}
/// <summary>
/// Create a new exception using the value from <see cref="GetLastWin32Error"/> and custom message. Note: make sure to set SetLastError=true on <see cref="DllImportAttribute"/>.
/// </summary>
public Win32Exception(string customMessage)
: this(GetLastWin32Error())
{
CustomMessage = customMessage;
}
/// <summary>
/// Create a new exception with given error code and custom message
/// </summary>
public Win32Exception(Win32Error error, string customMessage)
: base($"{error}: {GetMessage(error)}")
{
Error = error;
ErrorMessage = GetMessage(error);
CustomMessage = customMessage;
}
static string GetMessage(Win32Error error)
{
var builtinException = new System.ComponentModel.Win32Exception((int)error);
return builtinException.Message;
}
}
}
| using System;
using System.Runtime.InteropServices;
namespace BetterWin32Errors
{
/// <summary>
/// Exception that represents a <see cref="Win32Error"/>.
/// </summary>
public class Win32Exception : Exception
{
/// <summary>
/// Returns the last <see cref="Win32Error"/>. Note: make sure to set SetLastError=true on <see cref="DllImportAttribute"/>.
/// </summary>
/// <returns></returns>
public static Win32Error GetLastWin32Error()
{
return (Win32Error)Marshal.GetLastWin32Error();
}
/// <summary>
/// The <see cref="Win32Error"/> that the exception represents.
/// </summary>
public Win32Error Error { get; private set; }
/// <summary>
/// A human readable message associated with the <see cref="Win32Error"/>.
/// </summary>
public string ErrorMessage { get; private set; }
/// <summary>
/// Create a new exception using the value from <see cref="GetLastWin32Error"/>. Note: make sure to set SetLastError=true on <see cref="DllImportAttribute"/>.
/// </summary>
public Win32Exception()
: this(GetLastWin32Error())
{
}
/// <summary>
/// </summary>
public Win32Exception(Win32Error error)
: base($"{error}: {GetMessage(error)}")
{
Error = error;
ErrorMessage = GetMessage(error);
}
static string GetMessage(Win32Error error)
{
var builtinException = new System.ComponentModel.Win32Exception((int)error);
return builtinException.Message;
}
}
}
| mit | C# |
9705838bb8aa37e1c95fffdd2eadd3587c15f420 | Add GetProperty | yanyiyun/LockstepFramework,erebuswolf/LockstepFramework,SnpM/Lockstep-Framework | Core/Utility/Serialization/Editor/Injector.cs | Core/Utility/Serialization/Editor/Injector.cs | using UnityEngine;
using System.Collections;
using UnityEditor;
namespace Lockstep
{
public static class Injector
{
public static void SetTarget (UnityEngine.Object target) {
Target = target;
}
public static Object Target{ get; private set;}
public static SerializedProperty GetProperty (string name) {
SerializedObject so = new SerializedObject (Target);
SerializedProperty prop = so.FindProperty(name);
return prop;
}
public static void SetField (string name, float value, FieldType fieldType) {
SerializedProperty prop = GetProperty (name);
switch (fieldType) {
case FieldType.FixedNumber:
prop.longValue = FixedMath.Create(value);
break;
case FieldType.Interval:
prop.intValue = Mathf.RoundToInt(value * LockstepManager.FrameRate);
break;
case FieldType.Rate:
prop.intValue = Mathf.RoundToInt((1 / value) * LockstepManager.FrameRate);
break;
}
}
public static float GetField (string name, FieldType fieldType) {
SerializedProperty prop = GetProperty (name);
switch (fieldType) {
case FieldType.FixedNumber:
return prop.longValue.ToFloat();
break;
case FieldType.Interval:
return prop.intValue / (float) LockstepManager.FrameRate;
break;
case FieldType.Rate:
return 1 / (prop.intValue / (float)LockstepManager.FrameRate);
break;
}
return 0;
}
}
public enum FieldType {
FixedNumber,
Interval,
Rate,
}
} | using UnityEngine;
using System.Collections;
using UnityEditor;
namespace Lockstep
{
public static class Injector
{
public static void SetTarget (UnityEngine.Object target) {
Target = target;
}
public static Object Target{ get; private set;}
public static void SetField (string name, float value, FieldType fieldType) {
SerializedObject so = new SerializedObject (Target);
SerializedProperty prop = so.FindProperty(name);
switch (fieldType) {
case FieldType.FixedNumber:
prop.longValue = FixedMath.Create(value);
break;
case FieldType.Interval:
prop.intValue = Mathf.RoundToInt(value * LockstepManager.FrameRate);
break;
case FieldType.Rate:
prop.intValue = Mathf.RoundToInt((1 / value) * LockstepManager.FrameRate);
break;
}
}
public static float GetField (string name, FieldType fieldType) {
SerializedObject so = new SerializedObject (Target);
SerializedProperty prop = so.FindProperty(name);
switch (fieldType) {
case FieldType.FixedNumber:
return prop.longValue.ToFloat();
break;
case FieldType.Interval:
return prop.intValue / (float) LockstepManager.FrameRate;
break;
case FieldType.Rate:
return 1 / (prop.intValue / (float)LockstepManager.FrameRate);
break;
}
return 0;
}
}
public enum FieldType {
FixedNumber,
Interval,
Rate,
}
} | mit | C# |
b327a362b153faf5e4fa856b3cf911b14100aaa0 | Add WebInvoke to demonstrate how to post. | tlaothong/lab-swp-ws-kiatnakin,tlaothong/lab-swp-ws-kiatnakin,tlaothong/lab-swp-ws-kiatnakin | LabWsKiatnakin/DemoWcfRest/DemoService.svc.cs | LabWsKiatnakin/DemoWcfRest/DemoService.svc.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace DemoWcfRest
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "hi/{name}")]
public string Hello(string name)
{
return string.Format("Hello, {0}", name);
}
// Add more operations here and mark them with [OperationContract]
[OperationContract]
[WebInvoke(Method = "POST")]
public void PostSample(string postBody)
{
// DO NOTHING
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;
namespace DemoWcfRest
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class DemoService
{
// To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
// To create an operation that returns XML,
// add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
// and include the following line in the operation body:
// WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
[OperationContract]
[WebGet(UriTemplate = "hi/{name}")]
public string Hello(string name)
{
return string.Format("Hello, {0}", name);
}
// Add more operations here and mark them with [OperationContract]
}
}
| mit | C# |
aec6129c8bcd775bb77d700407e729e9285707d8 | Add 7 | Pesh2003/MyFirstDemoInGitHub | HelloSharp/ThisTimeHello/Program.cs | HelloSharp/ThisTimeHello/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThisTimeHello
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Helo Melo :)");
Console.WriteLine("Add another feature to the club :))");
Console.WriteLine("1234567");
Console.WriteLine("This is third ");
Console.WriteLine("67567");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ThisTimeHello
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Helo Melo :)");
Console.WriteLine("Add another feature to the club :))");
Console.WriteLine("1234567");
Console.WriteLine("This is third "); }
}
}
| mit | C# |
c48a1b45e52d5015466f5a526540b417919b2b5d | Remove GetVersion requirement from IScriptLink | rcskids/ScriptLinkStandard | ScriptLinkStandard/Interfaces/IScriptLink.cs | ScriptLinkStandard/Interfaces/IScriptLink.cs | using ScriptLinkStandard.Objects;
namespace ScriptLinkStandard.Interfaces
{
public interface IScriptLink
{
OptionObject ProcessScript(IOptionObject optionObject, string parameter);
OptionObject2 ProcessScript(IOptionObject2 optionObject, string parameter);
OptionObject2015 ProcessScript(IOptionObject2015 optionObject, string parameter);
}
} | using ScriptLinkStandard.Objects;
namespace ScriptLinkStandard.Interfaces
{
public interface IScriptLink
{
string GetVersion();
OptionObject ProcessScript(IOptionObject optionObject, string parameter);
OptionObject2 ProcessScript(IOptionObject2 optionObject, string parameter);
OptionObject2015 ProcessScript(IOptionObject2015 optionObject, string parameter);
}
} | mit | C# |
0b7059bea287abbcbbcf1b7bbbe557de78c90017 | remove redundant conditional compilation | config-r/config-r | src/ConfigR/Sdk/AppDomainSetupExtensions.cs | src/ConfigR/Sdk/AppDomainSetupExtensions.cs | // <copyright file="AppDomainSetupExtensions.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
namespace ConfigR.Sdk
{
using System;
using System.IO;
public static class AppDomainSetupExtensions
{
private static readonly string visualStudioHostSuffix = ".vshost";
private static readonly int visualStudioHostSuffixLength = ".vshost".Length;
public static string VSHostingAgnosticConfigurationFile(this AppDomainSetup setup)
{
var path = setup?.ConfigurationFile;
if (path == null)
{
return null;
}
var fileNameWithoutConfigExtension = Path.GetFileNameWithoutExtension(path);
var fileNameWithoutAssemblyTypeExtension = Path.GetFileNameWithoutExtension(fileNameWithoutConfigExtension);
if (fileNameWithoutAssemblyTypeExtension.EndsWith(visualStudioHostSuffix, StringComparison.OrdinalIgnoreCase))
{
var fileNameWithoutHostSuffix = string.Concat(
fileNameWithoutAssemblyTypeExtension.Substring(
0, fileNameWithoutAssemblyTypeExtension.Length - visualStudioHostSuffixLength),
Path.GetExtension(fileNameWithoutConfigExtension),
Path.GetExtension(path));
return Path.Combine(Path.GetDirectoryName(path) ?? string.Empty, fileNameWithoutHostSuffix);
}
return path;
}
}
}
| // <copyright file="AppDomainSetupExtensions.cs" company="ConfigR contributors">
// Copyright (c) ConfigR contributors. (configr.net@gmail.com)
// </copyright>
#if TESTS_ACCEPTANCE_ROSLYN_CSHARP
namespace ConfigR.Tests.Acceptance.Roslyn.CSharp.Support
#else
namespace ConfigR.Sdk
#endif
{
using System;
using System.IO;
public static class AppDomainSetupExtensions
{
private static readonly string visualStudioHostSuffix = ".vshost";
private static readonly int visualStudioHostSuffixLength = ".vshost".Length;
public static string VSHostingAgnosticConfigurationFile(this AppDomainSetup setup)
{
var path = setup?.ConfigurationFile;
if (path == null)
{
return null;
}
var fileNameWithoutConfigExtension = Path.GetFileNameWithoutExtension(path);
var fileNameWithoutAssemblyTypeExtension = Path.GetFileNameWithoutExtension(fileNameWithoutConfigExtension);
if (fileNameWithoutAssemblyTypeExtension.EndsWith(visualStudioHostSuffix, StringComparison.OrdinalIgnoreCase))
{
var fileNameWithoutHostSuffix = string.Concat(
fileNameWithoutAssemblyTypeExtension.Substring(
0, fileNameWithoutAssemblyTypeExtension.Length - visualStudioHostSuffixLength),
Path.GetExtension(fileNameWithoutConfigExtension),
Path.GetExtension(path));
return Path.Combine(Path.GetDirectoryName(path) ?? string.Empty, fileNameWithoutHostSuffix);
}
return path;
}
}
}
| mit | C# |
2f6b95da39129c6bfcfa74b34a69ec9611bcf43c | Add descriptions for the remaining settings | peppy/osu,NeoAdonis/osu,smoogipoo/osu,peppy/osu,ppy/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu-new,smoogipoo/osu,ppy/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipooo/osu | osu.Game/Screens/Edit/Setup/DesignSection.cs | osu.Game/Screens/Edit/Setup/DesignSection.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Setup
{
internal class DesignSection : SetupSection
{
private LabelledSwitchButton widescreenSupport;
private LabelledSwitchButton epilepsyWarning;
private LabelledSwitchButton letterboxDuringBreaks;
public override LocalisableString Title => "Design";
[BackgroundDependencyLoader]
private void load()
{
Children = new[]
{
widescreenSupport = new LabelledSwitchButton
{
Label = "Widescreen support",
Description = "Allows storyboards to use the full screen space, rather than be confined to a 4:3 area.",
Current = { Value = Beatmap.BeatmapInfo.WidescreenStoryboard }
},
epilepsyWarning = new LabelledSwitchButton
{
Label = "Epilepsy warning",
Description = "Recommended if the storyboard or video contain scenes with rapidly flashing colours.",
Current = { Value = Beatmap.BeatmapInfo.EpilepsyWarning }
},
letterboxDuringBreaks = new LabelledSwitchButton
{
Label = "Letterbox during breaks",
Description = "Adds horizontal letterboxing to give a cinematic look during breaks.",
Current = { Value = Beatmap.BeatmapInfo.LetterboxInBreaks }
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
widescreenSupport.Current.BindValueChanged(_ => updateBeatmap());
epilepsyWarning.Current.BindValueChanged(_ => updateBeatmap());
letterboxDuringBreaks.Current.BindValueChanged(_ => updateBeatmap());
}
private void updateBeatmap()
{
Beatmap.BeatmapInfo.WidescreenStoryboard = widescreenSupport.Current.Value;
Beatmap.BeatmapInfo.EpilepsyWarning = epilepsyWarning.Current.Value;
Beatmap.BeatmapInfo.LetterboxInBreaks = letterboxDuringBreaks.Current.Value;
}
}
}
| // 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.Localisation;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Setup
{
internal class DesignSection : SetupSection
{
private LabelledSwitchButton widescreenSupport;
private LabelledSwitchButton epilepsyWarning;
private LabelledSwitchButton letterboxDuringBreaks;
public override LocalisableString Title => "Design";
[BackgroundDependencyLoader]
private void load()
{
Children = new[]
{
widescreenSupport = new LabelledSwitchButton
{
Label = "Widescreen support",
Current = { Value = Beatmap.BeatmapInfo.WidescreenStoryboard }
},
epilepsyWarning = new LabelledSwitchButton
{
Label = "Epilepsy warning",
Description = "Recommended if the storyboard or video contain scenes with rapidly flashing colours.",
Current = { Value = Beatmap.BeatmapInfo.EpilepsyWarning }
},
letterboxDuringBreaks = new LabelledSwitchButton
{
Label = "Letterbox during breaks",
Current = { Value = Beatmap.BeatmapInfo.LetterboxInBreaks }
}
};
}
protected override void LoadComplete()
{
base.LoadComplete();
widescreenSupport.Current.BindValueChanged(_ => updateBeatmap());
epilepsyWarning.Current.BindValueChanged(_ => updateBeatmap());
letterboxDuringBreaks.Current.BindValueChanged(_ => updateBeatmap());
}
private void updateBeatmap()
{
Beatmap.BeatmapInfo.WidescreenStoryboard = widescreenSupport.Current.Value;
Beatmap.BeatmapInfo.EpilepsyWarning = epilepsyWarning.Current.Value;
Beatmap.BeatmapInfo.LetterboxInBreaks = letterboxDuringBreaks.Current.Value;
}
}
}
| mit | C# |
be04186ed79d2d6a656e05273df98d9321bba771 | Update ResolutionFailedException.cs | z4kn4fein/stashbox | src/Exceptions/ResolutionFailedException.cs | src/Exceptions/ResolutionFailedException.cs | using Stashbox.Utils;
using System;
using System.Runtime.Serialization;
namespace Stashbox.Exceptions
{
/// <summary>
/// Represents the exception the container throws when a service resolution is failed.
/// </summary>
[Serializable]
public class ResolutionFailedException : Exception
{
/// <summary>
/// The type the container is currently resolving.
/// </summary>
public Type Type { get; }
/// <summary>
/// Constructs a <see cref="ResolutionFailedException"/>.
/// </summary>
/// <param name="type">The type of the service.</param>
/// <param name="name">The name of the service.</param>
/// <param name="message">The exception message.</param>
/// <param name="innerException">The inner exception.</param>
public ResolutionFailedException(Type type,
object name = null,
string message = "Service is not registered properly or unresolvable type requested.",
Exception innerException = null)
: base($"Unable to resolve type {type.FullName}{(name != null ? " with the name \'" + name + "\'" : "")}.{Environment.NewLine}{message}", innerException)
{
this.Type = type;
}
/// <inheritdoc />
protected ResolutionFailedException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.Type = (Type)info.GetValue("Type", typeof(Type));
}
/// <inheritdoc />
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
Shield.EnsureNotNull(info, "info");
info.AddValue("Type", this.Type, typeof(Type));
base.GetObjectData(info, context);
}
}
} | using System;
using System.Runtime.Serialization;
namespace Stashbox.Exceptions
{
/// <summary>
/// Represents the exception the container throws when a service resolution is failed.
/// </summary>
[Serializable]
public class ResolutionFailedException : Exception
{
/// <summary>
/// The type the container is currently resolving.
/// </summary>
public Type Type { get; }
/// <summary>
/// Constructs a <see cref="ResolutionFailedException"/>.
/// </summary>
/// <param name="type">The type of the service.</param>
/// <param name="name">The name of the service.</param>
/// <param name="message">The exception message.</param>
/// <param name="innerException">The inner exception.</param>
public ResolutionFailedException(Type type,
object name = null,
string message = "Service is not registered properly or unresolvable type requested.",
Exception innerException = null)
: base($"Unable to resolve type {type.FullName}{(name != null ? " with the name \'" + name + "\'" : "")}.{Environment.NewLine}{message}", innerException)
{
this.Type = type;
}
/// <inheritdoc />
protected ServiceAlreadyRegisteredException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
this.Type = (Type)info.GetValue("Type", typeof(Type));
}
/// <inheritdoc />
public override void GetObjectData(SerializationInfo info, StreamingContext context)
{
Shield.EnsureNotNull(info, "info");
info.AddValue("Type", this.Type, typeof(Type));
base.GetObjectData(info, context);
}
}
} | mit | C# |
dc072d5aa6d2dc0c4825fdde9b37e908429e5208 | remove link property from incident | lurch83/RfsForChromeService | src/RfsForChrome.Service/Models/Incident.cs | src/RfsForChrome.Service/Models/Incident.cs | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace RfsForChrome.Service.Models
{
public class Incident
{
public string Title { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public Category Category { get; set; }
public DateTime LastUpdated { get; set; }
public string CouncilArea { get; set; }
public string Status { get; set; }
public string Size { get; set; }
public string Type { get; set; }
public string Location { get; set; }
}
} | using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace RfsForChrome.Service.Models
{
public class Incident
{
public string Title { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public Category Category { get; set; }
public string Link { get; set; }
public DateTime LastUpdated { get; set; }
public string CouncilArea { get; set; }
public string Status { get; set; }
public string Size { get; set; }
public string Type { get; set; }
public string Location { get; set; }
}
} | mit | C# |
59da22a80e9549e5ee7e7307a70e1fbc964fbc5e | Print MOTD in the screen only | DaggerES/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer,gavazquez/LunaMultiPlayer | LmpClient/Systems/Motd/MotdMessageHandler.cs | LmpClient/Systems/Motd/MotdMessageHandler.cs | using LmpClient.Base;
using LmpClient.Base.Interface;
using LmpCommon.Message.Data.Motd;
using LmpCommon.Message.Interface;
using System.Collections.Concurrent;
namespace LmpClient.Systems.Motd
{
public class MotdMessageHandler : SubSystem<MotdSystem>, IMessageHandler
{
public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>();
public void HandleMessage(IServerMessageBase msg)
{
if (!(msg.Data is MotdReplyMsgData msgData)) return;
if (!string.IsNullOrEmpty(msgData.MessageOfTheDay))
{
LunaScreenMsg.PostScreenMessage(msgData.MessageOfTheDay, 30f, ScreenMessageStyle.UPPER_CENTER);
}
}
}
}
| using System.Collections.Concurrent;
using LmpClient.Base;
using LmpClient.Base.Interface;
using LmpClient.Systems.Chat;
using LmpCommon.Message.Data.Motd;
using LmpCommon.Message.Interface;
namespace LmpClient.Systems.Motd
{
public class MotdMessageHandler : SubSystem<MotdSystem>, IMessageHandler
{
public ConcurrentQueue<IServerMessageBase> IncomingMessages { get; set; } = new ConcurrentQueue<IServerMessageBase>();
public void HandleMessage(IServerMessageBase msg)
{
if (!(msg.Data is MotdReplyMsgData msgData)) return;
if (!string.IsNullOrEmpty(msgData.MessageOfTheDay))
{
ChatSystem.Singleton.PrintToChat(msgData.MessageOfTheDay);
LunaScreenMsg.PostScreenMessage(msgData.MessageOfTheDay, 30f, ScreenMessageStyle.UPPER_CENTER);
}
}
}
}
| mit | C# |
b883671d9e361431d5aa68388d94b7626d704bc1 | Fix index header fail | BenJenkinson/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,nodatime/nodatime,malcolmr/nodatime,malcolmr/nodatime,malcolmr/nodatime,jskeet/nodatime,nodatime/nodatime,jskeet/nodatime | src/NodaTime.Web/Controllers/TzdbController.cs | src/NodaTime.Web/Controllers/TzdbController.cs | using Microsoft.AspNetCore.Mvc;
using NodaTime.Helpers;
using NodaTime.Web.Models;
using System.Linq;
namespace NodaTime.Web.Controllers
{
[AddHeader("X-Robots-Tag", "noindex")]
public class TzdbController : Controller
{
private const string ContentType = "application/octet-stream";
private readonly ITzdbRepository tzdbRepository;
public TzdbController(ITzdbRepository tzdbRepository)
{
this.tzdbRepository = tzdbRepository;
}
[Route(@"/tzdb/{id:regex(^.*\.nzd$)}")]
public IActionResult Get(string id)
{
var release = tzdbRepository.GetRelease(id);
if (release == null)
{
return NotFound();
}
return File(release.GetContent(), ContentType, release.Name);
}
[Route("/tzdb/latest.txt")]
public IActionResult Latest() =>
new ContentResult
{
ContentType = "text/plain",
Content = tzdbRepository.GetReleases().Last().NodaTimeOrgUrl,
StatusCode = 200
};
[Route("/tzdb/index.txt")]
public IActionResult Index()
{
var releases = tzdbRepository.GetReleases();
var releaseUrls = releases.Select(r => r.NodaTimeOrgUrl);
return new ContentResult
{
ContentType = "text/plain",
Content = string.Join("\r\n", releaseUrls),
StatusCode = 200
};
}
}
}
| using Microsoft.AspNetCore.Mvc;
using NodaTime.Helpers;
using NodaTime.Web.Models;
using System.Linq;
namespace NodaTime.Web.Controllers
{
[AddHeader("X-Robots-Tag", "noindex")]
public class TzdbController : Controller
{
private const string ContentType = "application/octet-stream";
private readonly ITzdbRepository tzdbRepository;
public TzdbController(ITzdbRepository tzdbRepository)
{
this.tzdbRepository = tzdbRepository;
}
[Route(@"/tzdb/{id:regex(^.*\.nzd$)}")]
public IActionResult Get(string id)
{
var release = tzdbRepository.GetRelease(id);
if (release == null)
{
return NotFound();
}
Response.Headers.Add("X-Robots-Tag", "noindex");
return File(release.GetContent(), ContentType, release.Name);
}
[Route("/tzdb/latest.txt")]
public IActionResult Latest() =>
new ContentResult
{
ContentType = "text/plain",
Content = tzdbRepository.GetReleases().Last().NodaTimeOrgUrl,
StatusCode = 200
};
[Route("/tzdb/index.txt")]
public IActionResult Index()
{
var releases = tzdbRepository.GetReleases();
var releaseUrls = releases.Select(r => r.NodaTimeOrgUrl);
return new ContentResult
{
ContentType = "text/plain",
Content = string.Join("\r\n", releaseUrls),
StatusCode = 200
};
}
}
}
| apache-2.0 | C# |
fe4a6bb6e98ddc4550d474542d2f39001d13b678 | Remove null label for ElementId | jeremytammik/RevitLookup | RevitLookup/Core/RevitTypes/ElementIdData.cs | RevitLookup/Core/RevitTypes/ElementIdData.cs | // Copyright 2003-2022 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
using Autodesk.Revit.DB;
using RevitLookup.Views;
using Form = System.Windows.Forms.Form;
namespace RevitLookup.Core.RevitTypes;
/// <summary>
/// Snoop.Data class to hold and format an ElementId value.
/// </summary>
public class ElementIdData : Data
{
private readonly Element _element;
private readonly ElementId _value;
public ElementIdData(string label, ElementId val, Document doc) : base(label)
{
_value = val;
_element = doc.GetElement(val);
}
public override bool HasDrillDown => _element is not null;
public override string AsValueString()
{
return _element is not null ? Utils.GetLabel(_element) : _value.ToString();
}
public override Form DrillDown()
{
if (_element is null) return null;
var form = new ObjectsView(_element);
return form;
}
} | // Copyright 2003-2022 by Autodesk, Inc.
//
// Permission to use, copy, modify, and distribute this software in
// object code form for any purpose and without fee is hereby granted,
// provided that the above copyright notice appears in all copies and
// that both that copyright notice and the limited warranty and
// restricted rights notice below appear in all supporting
// documentation.
//
// AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS.
// AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF
// MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC.
// DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE
// UNINTERRUPTED OR ERROR FREE.
//
// Use, duplication, or disclosure by the U.S. Government is subject to
// restrictions set forth in FAR 52.227-19 (Commercial Computer
// Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii)
// (Rights in Technical Data and Computer Software), as applicable.
using Autodesk.Revit.DB;
using RevitLookup.Views;
using Form = System.Windows.Forms.Form;
namespace RevitLookup.Core.RevitTypes;
/// <summary>
/// Snoop.Data class to hold and format an ElementId value.
/// </summary>
public class ElementIdData : Data
{
private readonly Element _element;
private readonly ElementId _value;
public ElementIdData(string label, ElementId val, Document doc) : base(label)
{
_value = val;
_element = doc.GetElement(val);
}
public override bool HasDrillDown => _element is not null;
public override string AsValueString()
{
if (_element is not null) return Utils.GetLabel(_element);
return _value != ElementId.InvalidElementId ? _value.ToString() : Utils.GetLabel(null);
}
public override Form DrillDown()
{
if (_element is null) return null;
var form = new ObjectsView(_element);
return form;
}
} | mit | C# |
61c9ab08f562cb1bb8a28826fa536d6088a27bb0 | Update MonsterType.cs (#337) | Shidesu/RiotSharp,Oucema90/RiotSharp,frederickrogan/RiotSharp,JanOuborny/RiotSharp,florinciubotariu/RiotSharp,Challengermode/RiotSharp,BenFradet/RiotSharp,oisindoherty/RiotSharp,jono-90/RiotSharp | RiotSharp/MatchEndpoint/Enums/MonsterType.cs | RiotSharp/MatchEndpoint/Enums/MonsterType.cs | using Newtonsoft.Json;
using RiotSharp.MatchEndpoint.Enums.Converters;
namespace RiotSharp.MatchEndpoint.Enums
{
/// <summary>
/// Type of monster (Match API).
/// </summary>
[JsonConverter(typeof(MonsterTypeConverter))]
public enum MonsterType
{
/// <summary>
/// Corresponds to the baron Nashor.
/// </summary>
BaronNashor,
/// <summary>
/// Corresponds to the blue golem.
/// </summary>
BlueGolem,
/// <summary>
/// Corresponds to the dragon.
/// </summary>
Dragon,
/// <summary>
/// Corresponds to the red lizard.
/// </summary>
RedLizard,
/// <summary>
/// Corresponds to Vilemaw (on the 3vs3 map).
/// </summary>
Vilemaw,
/// <summary>
/// Corresponds to Rift Herald.
/// </summary>
RiftHerald
}
static class MonsterTypeExtension
{
public static string ToCustomString(this MonsterType monsterType)
{
switch (monsterType)
{
case MonsterType.BaronNashor:
return "BARON_NASHOR";
case MonsterType.BlueGolem:
return "BLUE_GOLEM";
case MonsterType.Dragon:
return "DRAGON";
case MonsterType.RedLizard:
return "RED_LIZARD";
case MonsterType.Vilemaw:
return "VILEMAW";
case MonsterType.RiftHerald:
return "RIFTHERALD";
default:
return string.Empty;
}
}
}
}
| using Newtonsoft.Json;
using RiotSharp.MatchEndpoint.Enums.Converters;
namespace RiotSharp.MatchEndpoint.Enums
{
/// <summary>
/// Type of monster (Match API).
/// </summary>
[JsonConverter(typeof(MonsterTypeConverter))]
public enum MonsterType
{
/// <summary>
/// Corresponds to the baron Nashor.
/// </summary>
BaronNashor,
/// <summary>
/// Corresponds to the blue golem.
/// </summary>
BlueGolem,
/// <summary>
/// Corresponds to the dragon.
/// </summary>
Dragon,
/// <summary>
/// Corresponds to the red lizard.
/// </summary>
RedLizard,
/// <summary>
/// Corresponds to Vilemaw (on the 3vs3 map).
/// </summary>
Vilemaw
}
static class MonsterTypeExtension
{
public static string ToCustomString(this MonsterType monsterType)
{
switch (monsterType)
{
case MonsterType.BaronNashor:
return "BARON_NASHOR";
case MonsterType.BlueGolem:
return "BLUE_GOLEM";
case MonsterType.Dragon:
return "DRAGON";
case MonsterType.RedLizard:
return "RED_LIZARD";
case MonsterType.Vilemaw:
return "VILEMAW";
default:
return string.Empty;
}
}
}
}
| mit | C# |
72aedf32a280b88aff715e1ee819f09de9ff310c | Make planet update dependent components. | dirty-casuals/LD38-A-Small-World | Assets/Scripts/Planet.cs | Assets/Scripts/Planet.cs | using UnityEngine;
[ExecuteInEditMode]
public class Planet : MonoBehaviour {
[SerializeField]
private float _radius;
public float Radius {
get { return _radius; }
set { _radius = value; }
}
public float Permieter {
get { return 2 * Mathf.PI * Radius; }
}
public float Volume {
get { return 4 / 3 * Mathf.PI * Radius * Radius * Radius; }
}
public void SampleOrbit2D( float angle,
float distance,
out Vector3 position,
out Vector3 normal ) {
// Polar to cartesian coordinates
float x = Mathf.Cos( angle ) * distance;
float y = Mathf.Sin( angle ) * distance;
Vector3 dispalcement = new Vector3( x, 0, y );
Vector3 center = transform.position;
position = center + dispalcement;
normal = dispalcement.normalized;
}
#if UNITY_EDITOR
private void Update() {
if( Application.isPlaying ) {
return;
}
var sphereColider = GetComponent<SphereCollider>();
if( sphereColider ) {
sphereColider.radius = Radius;
}
var model = transform.FindChild( "Model" );
if( model ) {
model.localScale = Vector3.one * Radius * 2;
}
}
#endif
}
| using UnityEngine;
public class Planet : MonoBehaviour {
[SerializeField]
private float _radius;
public float Radius {
get { return _radius; }
set { _radius = value; }
}
public float Permieter {
get { return 2 * Mathf.PI * Radius; }
}
public float Volume {
get { return 4 / 3 * Mathf.PI * Radius * Radius * Radius; }
}
public void SampleOrbit2D( float angle,
float distance,
out Vector3 position,
out Vector3 normal ) {
// Polar to cartesian coordinates
float x = Mathf.Cos( angle ) * distance;
float y = Mathf.Sin( angle ) * distance;
Vector3 dispalcement = new Vector3( x, 0, y );
Vector3 center = transform.position;
position = center + dispalcement;
normal = dispalcement.normalized;
}
}
| mit | C# |
ff32d633404171ddc7006b3c912bf80f5559d717 | Update BaseAction.cs | Anatid/XML-Documentation-for-the-KSP-API | src/BaseAction.cs | src/BaseAction.cs | using System;
using System.Collections.Generic;
/// <summary>
/// A BaseAction object is the basic action object.
/// There is one of these automatically created for each 'KSPAction' field in a partModule
/// </summary>
[Serializable]
public class BaseAction
{
/// <summary>
/// Unconfirmed: The action groups this action is currently assigned to.
/// </summary>
public KSPActionGroup actionGroup;
/// <summary>
/// Is this action available? Setting this false disables the action so it will not show in the available actions list.
/// </summary>
public bool active;
/// <summary>
///Unconfirmed: Assign this action to action groups upon creation ('Gear' group for landing legs)
/// </summary>
public KSPActionGroup defaultActionGroup;
/// <summary>
/// Name shown in editor action groups panel
/// </summary>
public string guiName;
/// <summary>
/// Information about what the action is attached to.
/// listParent.module = partModule this action is a memeber of
/// listParent.part = part this action is a member of
/// </summary>
public BaseActionList listParent;
/// <summary>
/// Name of the action group as seen in code where the KSPAction field exists
/// </summary>
public string name;
public extern BaseAction(BaseActionList listParent, string name, BaseActionDelegate onEvent, KSPAction actionAttr);
public static extern int ActionGroupsLength { get; }
protected extern BaseActionDelegate onEvent { get; }
public static extern bool ContainsNonDefaultActions(Part p);
public static extern List<BaseAction> CreateActionList(List<Part> parts, KSPActionGroup group, bool include);
public static extern List<BaseAction> CreateActionList(Part p, KSPActionGroup group, bool include);
public static extern List<bool> CreateGroupList(List<Part> parts);
public static extern List<bool> CreateGroupList(Part p);
public static extern void FireAction(List<Part> parts, KSPActionGroup group, KSPActionType type);
public static extern int GetGroupIndex(KSPActionGroup group);
/// <summary>
/// Activate this action. Note that there is no toggle activation, you must check state yourself in code
/// and activate or deactivate as appropriate
///
/// **Example code start to activate an action: KSP version 0.24.2**
///
/// <code>
/// KSPActionParam actParam = new KSPActionParam(KSPActionGroup.None, KSPActionType.Activate); //okay to create this new just before invoking
/// exampleAction.Invoke(actParam); //action defined as a KSPAction in a partModule
/// </code>
///
/// **Example code start to deactivate an action: KSP version 0.24.2**
///
/// <code>
/// KSPActionParam actParam = new KSPActionParam(KSPActionGroup.None, KSPActionType.Deactivate); //okay to create this new just before invoking
/// exampleAction.Invoke(actParam); //action defined as a KSPAction in a partModule
/// </code>
/// </summary>
public extern void Invoke(KSPActionParam param);
public extern void OnLoad(ConfigNode node);
public extern void OnSave(ConfigNode node);
}
| using System;
using System.Collections.Generic;
/// <summary>
/// A BaseAction object is the basic action object.
/// There is one of these automatically created for each 'KSPAction' field in a partModule
/// </summary>
[Serializable]
public class BaseAction
{
/// <summary>
/// Unconfirmed: The action groups this action is currently assigned to.
/// </summary>
public KSPActionGroup actionGroup;
/// <summary>
/// Is this action activated?
/// </summary>
public bool active;
/// <summary>
///Unconfirmed: Assign this action to action groups upon creation ('Gear' group for landing legs)
/// </summary>
public KSPActionGroup defaultActionGroup;
/// <summary>
/// Name shown in editor action groups panel
/// </summary>
public string guiName;
/// <summary>
/// Information about what the action is attached to.
/// listParent.module = partModule this action is a memeber of
/// listParent.part = part this action is a member of
/// </summary>
public BaseActionList listParent;
/// <summary>
/// Name of the action group as seen in code where the KSPAction field exists
/// </summary>
public string name;
public extern BaseAction(BaseActionList listParent, string name, BaseActionDelegate onEvent, KSPAction actionAttr);
public static extern int ActionGroupsLength { get; }
protected extern BaseActionDelegate onEvent { get; }
public static extern bool ContainsNonDefaultActions(Part p);
public static extern List<BaseAction> CreateActionList(List<Part> parts, KSPActionGroup group, bool include);
public static extern List<BaseAction> CreateActionList(Part p, KSPActionGroup group, bool include);
public static extern List<bool> CreateGroupList(List<Part> parts);
public static extern List<bool> CreateGroupList(Part p);
public static extern void FireAction(List<Part> parts, KSPActionGroup group, KSPActionType type);
public static extern int GetGroupIndex(KSPActionGroup group);
/// <summary>
/// Activate this action. Note that there is no toggle activation, you must check state yourself in code
/// and activate or deactivate as appropriate
///
/// **Example code start to activate an action: KSP version 0.24.2**
///
/// <code>
/// KSPActionParam actParam = new KSPActionParam(KSPActionGroup.None, KSPActionType.Activate); //okay to create this new just before invoking
/// exampleAction.Invoke(actParam); //action defined as a KSPAction in a partModule
/// </code>
///
/// **Example code start to deactivate an action: KSP version 0.24.2**
///
/// <code>
/// KSPActionParam actParam = new KSPActionParam(KSPActionGroup.None, KSPActionType.Deactivate); //okay to create this new just before invoking
/// exampleAction.Invoke(actParam); //action defined as a KSPAction in a partModule
/// </code>
/// </summary>
public extern void Invoke(KSPActionParam param);
public extern void OnLoad(ConfigNode node);
public extern void OnSave(ConfigNode node);
}
| unlicense | C# |
7bdaec074443d54c305d0010677dd966a409aa54 | add xml docs for the public interface | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EAS.Portal.Client/IPortalClient.cs | src/SFA.DAS.EAS.Portal.Client/IPortalClient.cs | using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.EAS.Portal.Client.Types;
namespace SFA.DAS.EAS.Portal.Client
{
public interface IPortalClient
{
/// <summary>
/// Get the account details required to render the homepage.
/// </summary>
/// <param name="hashedAccountId">The (non-public) hashed account id.</param>
/// <param name="accountState">The current state of the account. Set all flags that apply.</param>
/// <param name="cancellationToken">An optional cancellation token.</param>
/// <returns></returns>
Task<Account> GetAccount(string hashedAccountId, AccountState accountState,
CancellationToken cancellationToken = default);
}
} | using System.Threading;
using System.Threading.Tasks;
using SFA.DAS.EAS.Portal.Client.Types;
namespace SFA.DAS.EAS.Portal.Client
{
public interface IPortalClient
{
Task<Account> GetAccount(string hashedAccountId, AccountState accountState,
CancellationToken cancellationToken = default);
}
} | mit | C# |
9ff1f078b146eea230eff8159eddbd410320ad91 | return Directory as GlassLabel. | dkoeb/f-spot,Yetangitu/f-spot,mans0954/f-spot,GNOME/f-spot,GNOME/f-spot,GNOME/f-spot,dkoeb/f-spot,Sanva/f-spot,dkoeb/f-spot,dkoeb/f-spot,Sanva/f-spot,Yetangitu/f-spot,mans0954/f-spot,GNOME/f-spot,mans0954/f-spot,mans0954/f-spot,Sanva/f-spot,Yetangitu/f-spot,mono/f-spot,mono/f-spot,dkoeb/f-spot,mono/f-spot,NguyenMatthieu/f-spot,mono/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,nathansamson/F-Spot-Album-Exporter,NguyenMatthieu/f-spot,NguyenMatthieu/f-spot,mono/f-spot,NguyenMatthieu/f-spot,nathansamson/F-Spot-Album-Exporter,Sanva/f-spot,mans0954/f-spot,GNOME/f-spot,NguyenMatthieu/f-spot,mono/f-spot,mans0954/f-spot,dkoeb/f-spot,Yetangitu/f-spot,nathansamson/F-Spot-Album-Exporter,Yetangitu/f-spot | src/DirectoryAdaptor.cs | src/DirectoryAdaptor.cs | using System;
using System.Collections;
namespace FSpot {
public class DirectoryAdaptor : GroupAdaptor {
public PhotoQuery query;
public ArrayList dirs = new ArrayList ();
struct DirInfo {
public string Path;
public int Count;
}
public override void SetLimits (int min, int max)
{
Console.WriteLine ("There are no limits");
}
public override event GlassSetHandler GlassSet;
public override void SetGlass (int group)
{
Console.WriteLine ("Selected Path {0}", ((DirInfo)dirs [group]).Path);
int item = 0;
int i = 0;
while (i < group) {
item += ((DirInfo)dirs [i++]).Count;
}
GlassSet (this, item);
}
public override int Count ()
{
return dirs.Count;
}
public override string GlassLabel (int item)
{
DirInfo info = (DirInfo)dirs[item];
return dirs [item] as string;
}
public override string TickLabel (int item)
{
return null;
}
public override int Value (int item)
{
DirInfo info = (DirInfo)dirs[item];
return info.Count;
}
public void Load () {
dirs.Clear ();
Photo [] photos = query.Store.Query (null, null);
Array.Sort (photos, new Photo.CompareDirectory ());
Array.Sort (query.Photos, new Photo.CompareDirectory ());
DirInfo info = new DirInfo ();
foreach (Photo p in photos) {
string dir = p.DirectoryPath;
if (dir != info.Path) {
if (info.Path != null)
dirs.Add (info);
info.Path = dir;
info.Count = 0;
}
info.Count += 1;
}
}
public DirectoryAdaptor (PhotoQuery query) {
this.query = query;
Load ();
}
}
}
| using System;
using System.Collections;
namespace FSpot {
public class DirectoryAdaptor : GroupAdaptor {
public PhotoQuery query;
public ArrayList dirs = new ArrayList ();
struct DirInfo {
public string Path;
public int Count;
}
public override void SetLimits (int min, int max)
{
Console.WriteLine ("There are no limits");
}
public override event GlassSetHandler GlassSet;
public override void SetGlass (int group)
{
Console.WriteLine ("Selected Path {0}", ((DirInfo)dirs [group]).Path);
int item = 0;
int i = 0;
while (i < group) {
item += ((DirInfo)dirs [i++]).Count;
}
GlassSet (this, item);
}
public override int Count ()
{
return dirs.Count;
}
public override string Label (int item)
{
DirInfo info = (DirInfo)dirs[item];
return dirs [item] as string;
}
public override int Value (int item)
{
DirInfo info = (DirInfo)dirs[item];
return info.Count;
}
public void Load () {
dirs.Clear ();
Photo [] photos = query.Store.Query (null, null);
Array.Sort (photos, new Photo.CompareDirectory ());
Array.Sort (query.Photos, new Photo.CompareDirectory ());
DirInfo info = new DirInfo ();
foreach (Photo p in photos) {
string dir = p.DirectoryPath;
if (dir != info.Path) {
if (info.Path != null)
dirs.Add (info);
info.Path = dir;
info.Count = 0;
}
info.Count += 1;
}
}
public DirectoryAdaptor (PhotoQuery query) {
this.query = query;
Load ();
}
}
}
| mit | C# |
5f79d7bfa51c38b6f8c8431836538baa48a57580 | change average fps calc method | oggy83/TinyOculusSharpDxDemo | TinyOculusSharpDxDemo/Framework/FpsCounter.cs | TinyOculusSharpDxDemo/Framework/FpsCounter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace TinyOculusSharpDxDemo
{
public class FpsCounter
{
private const double AverageDeltaTimeUpdateInterval = 1.0;
public FpsCounter()
{
m_sw = new Stopwatch();
m_lastDeltaTick = 0;
m_sumDeltaTick = 0;
m_deltaTickCount = 0;
m_averageDeltaTimeUpdateTimer = 0;
m_lastAverageDeltaTime = 0;
m_sw.Start();
}
public void BeginFrame()
{
m_sw.Restart();
}
public void EndFrame()
{
if (m_sw.IsRunning)
{
m_sw.Stop();
// update delta time
m_lastDeltaTick = m_sw.ElapsedTicks;
m_averageDeltaTimeUpdateTimer -= GetDeltaTime();
m_sumDeltaTick += m_lastDeltaTick;
m_deltaTickCount++;
if (m_averageDeltaTimeUpdateTimer < 0.0f)
{
// update average delta time
double avgTickCount = (double)m_sumDeltaTick / m_deltaTickCount;
m_lastAverageDeltaTime = avgTickCount / Stopwatch.Frequency;
m_sumDeltaTick = 0;
m_deltaTickCount = 0;
m_averageDeltaTimeUpdateTimer = AverageDeltaTimeUpdateInterval;
}
}
}
/// <summary>
/// get delta time in sec
/// </summary>
/// <returns></returns>
public double GetDeltaTime()
{
return (double)m_lastDeltaTick / Stopwatch.Frequency;
}
/// <summary>
/// get average delta time in sec
/// </summary>
/// <returns></returns>
public double GetAverageDeltaTime()
{
return m_lastAverageDeltaTime;
}
#region private members
private Stopwatch m_sw = null;
/// <summary>
/// next delta tick count
/// </summary>
private long m_lastDeltaTick;
/// <summary>
/// the sum of delta time since last update of average delta time
/// </summary>
private long m_sumDeltaTick;
/// <summary>
/// counter for m_sumDeltaTime
/// </summary>
private int m_deltaTickCount;
/// <summary>
/// timer for update average delta time
/// </summary>
private double m_averageDeltaTimeUpdateTimer = 0;
/// <summary>
/// value for GetAverageDeltaTime()
/// </summary>
private double m_lastAverageDeltaTime = 0;
#endregion // private members
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace TinyOculusSharpDxDemo
{
public class FpsCounter
{
private const int MaxDeltaTimeQueueCount = 100;
public FpsCounter()
{
m_sw = new Stopwatch();
m_deltaTick = 0;
m_deltaTickQueue = new Queue<long>();
m_sw.Start();
}
public void BeginFrame()
{
m_sw.Restart();
}
public void EndFrame()
{
if (m_sw.IsRunning)
{
m_sw.Stop();
// update delta time
m_deltaTick = m_sw.ElapsedTicks;
if (m_deltaTickQueue.Count == MaxDeltaTimeQueueCount)
{
m_deltaTickQueue.Dequeue();
}
m_deltaTickQueue.Enqueue(m_deltaTick);
}
}
/// <summary>
/// get delta time in sec
/// </summary>
/// <returns></returns>
public double GetDeltaTime()
{
return (double)m_deltaTick / Stopwatch.Frequency;
}
/// <summary>
/// get average delta time in sec
/// </summary>
/// <returns></returns>
public double GetAverageDeltaTime()
{
double avgTickCount = (m_deltaTickQueue.Count == 0) ? 0 : m_deltaTickQueue.Average();
return avgTickCount / Stopwatch.Frequency;
}
#region private members
private Stopwatch m_sw = null;
/// <summary>
/// next delta tick count
/// </summary>
private long m_deltaTick;
/// <summary>
/// delta tick count queue
/// </summary>
private Queue<long> m_deltaTickQueue;
#endregion // private members
}
}
| mit | C# |
819439edad3497839f8c3b396725609310d91391 | Remove logs link, never worked right | mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander | Battery-Commander.Web/Controllers/AdminController.cs | Battery-Commander.Web/Controllers/AdminController.cs | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
namespace BatteryCommander.Web.Controllers
{
[Authorize, ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
// Admin Tasks:
// Add/Remove Users
// Backup SQLite Db
// Scrub Soldier Data
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
}
} | using BatteryCommander.Web.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.IO;
namespace BatteryCommander.Web.Controllers
{
[Authorize, ApiExplorerSettings(IgnoreApi = true)]
public class AdminController : Controller
{
// Admin Tasks:
// Add/Remove Users
// Backup SQLite Db
// Scrub Soldier Data
private readonly Database db;
public AdminController(Database db)
{
this.db = db;
}
public IActionResult Index()
{
return View();
}
public IActionResult Backup()
{
var data = System.IO.File.ReadAllBytes("Data.db");
var mimeType = "application/octet-stream";
return File(data, mimeType);
}
public IActionResult Logs()
{
byte[] data;
using (var stream = new FileStream($@"logs\{DateTime.Today:yyyyMMdd}.log", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var reader = new StreamReader(stream))
{
data = System.Text.Encoding.Default.GetBytes(reader.ReadToEnd());
}
return File(data, "text/plain");
}
}
} | mit | C# |
50e7dab00b3a295c7541919e1a4b0b7e65fdffbf | Fix incorrect wording | Zyrio/ictus,Zyrio/ictus | src/Yio/Views/Shared/_AboutPanelPartial.cshtml | src/Yio/Views/Shared/_AboutPanelPartial.cshtml | @{
var version = "";
var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString();
if(Yio.Data.Constants.VersionConstant.Patch == 0) {
version = Yio.Data.Constants.VersionConstant.Release.ToString();
} else {
version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." +
Yio.Data.Constants.VersionConstant.Patch.ToString();
}
}
<div class="panel" id="about-panel">
<div class="panel-inner">
<div class="panel-close">
<a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a>
</div>
<h1>About</h1>
<p>
<strong>Curl your paw round your dick, and get clicking!</strong>
</p>
<p>
Filled with furry (and more) porn, stripped from many sources — tumblr, e621, 4chan, 8chan, etc. — Yiff.co is the never-ending full-width stream of NSFW images.
</p>
<p>
Built by <a href="https://zyr.io">Zyrio</a>. Licensed under the MIT license, with code available on <a href="https://git.zyr.io/zyrio/yio">Zyrio Git</a>. All copyrights belong to their respectful owner, and Yiff.co does not claim ownership over any of them, nor does Yiff.co generate any money.
</p>
<p>
If you want something removed<s>, or would like to send dick pics</s>, email the developer at <a href="mailto:ducky.vexton@outlook.com"><i class="fa fa-envelope"></i> ducky.vexton@outlook.com</a>, or visit his site at <a href="https://ducky.ws"><i class="fa fa-globe"></i> ducky.ws</i></a>.
</p>
<p>
Running on version <strong>@version '@(versionName)'</strong>
</p>
</div>
</div> | @{
var version = "";
var versionName = Yio.Data.Constants.VersionConstant.Codename.ToString();
if(Yio.Data.Constants.VersionConstant.Patch == 0) {
version = Yio.Data.Constants.VersionConstant.Release.ToString();
} else {
version = Yio.Data.Constants.VersionConstant.Release.ToString() + "." +
Yio.Data.Constants.VersionConstant.Patch.ToString();
}
}
<div class="panel" id="about-panel">
<div class="panel-inner">
<div class="panel-close">
<a href="#" id="about-panel-close"><i class="fa fa-fw fa-times"></i></a>
</div>
<h1>About</h1>
<p>
<strong>Curl your paw round your dick, and get clicking!</strong>
</p>
<p>
Filled with furry (and more) porn, stripped from many sources — tumblr, e621, 4chan, 8chan, etc. — Yiff.co is the never-ending full-width stream of NSFW images.
</p>
<p>
Built by <a href="https://zyr.io">Zyrio</a>. Licensed under the MIT license, with code available on <a href="https://git.zyr.io/zyrio/yio">Zyrio Git</a>. All copyrights belong to their respectful owner, and Yiff.co does not claim ownership over any of them, nor does Yiff.co generate any money.
</p>
<p>
If you want something removed<s>, or would like to send dick pics to the developer</s>, email him at <a href="mailto:ducky.vexton@outlook.com"><i class="fa fa-envelope"></i> ducky.vexton@outlook.com</a>, or visit his site at <a href="https://ducky.ws"><i class="fa fa-globe"></i> ducky.ws</i></a>.
</p>
<p>
Running on version <strong>@version '@(versionName)'</strong>
</p>
</div>
</div> | mit | C# |
114df1b6df6f072ac28b724ff027981b9853b60e | Reword comment | ZLima12/osu-framework,ZLima12/osu-framework,ppy/osu-framework,EVAST9919/osu-framework,smoogipooo/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,peppy/osu-framework,DrabWeb/osu-framework,EVAST9919/osu-framework,DrabWeb/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,peppy/osu-framework,DrabWeb/osu-framework | osu.Framework/Input/UserInputManager.cs | osu.Framework/Input/UserInputManager.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework.Input
{
public class UserInputManager : PassThroughInputManager
{
protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;
protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;
protected internal override bool ShouldBeAlive => true;
protected internal UserInputManager()
{
// UserInputManager is at the very top of the draw hierarchy, so it has no parnt updating its IsAlive state
IsAlive = true;
UseParentInput = false;
}
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
switch (inputStateChange)
{
case MousePositionChangeEvent mousePositionChange:
var mouse = mousePositionChange.State.Mouse;
// confine cursor
if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined))
mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
break;
case MouseScrollChangeEvent _:
if (Host.Window != null && !Host.Window.CursorInWindow)
return;
break;
}
base.HandleInputStateChange(inputStateChange);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Input.Handlers;
using osu.Framework.Input.StateChanges.Events;
using osu.Framework.Platform;
using osuTK;
namespace osu.Framework.Input
{
public class UserInputManager : PassThroughInputManager
{
protected override IEnumerable<InputHandler> InputHandlers => Host.AvailableInputHandlers;
protected override bool HandleHoverEvents => Host.Window?.CursorInWindow ?? true;
protected internal override bool ShouldBeAlive => true;
protected internal UserInputManager()
{
// IsAlive is being forced to true here as UserInputManager is at the very top of the Draw Hierarchy, which means it never becomes alive normally.
IsAlive = true;
UseParentInput = false;
}
public override void HandleInputStateChange(InputStateChangeEvent inputStateChange)
{
switch (inputStateChange)
{
case MousePositionChangeEvent mousePositionChange:
var mouse = mousePositionChange.State.Mouse;
// confine cursor
if (Host.Window != null && Host.Window.CursorState.HasFlag(CursorState.Confined))
mouse.Position = Vector2.Clamp(mouse.Position, Vector2.Zero, new Vector2(Host.Window.Width, Host.Window.Height));
break;
case MouseScrollChangeEvent _:
if (Host.Window != null && !Host.Window.CursorInWindow)
return;
break;
}
base.HandleInputStateChange(inputStateChange);
}
}
}
| mit | C# |
d1fe2286b3976e551bda4de78a2f121b7317f1c5 | update assembly version | Geta/Geta.EPi.Imageshop,Geta/Geta.EPi.Imageshop,Geta/Geta.EPi.Imageshop | src/Properties/AssemblyInfo.cs | src/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("Geta.EPi.Imageshop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Geta")]
[assembly: AssemblyProduct("Geta.EPi.Imageshop")]
[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("c54433d8-eb2f-4bac-9b88-a54c84858a5d")]
// 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.6.0.0")]
[assembly: AssemblyFileVersion("1.6.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("Geta.EPi.Imageshop")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Geta")]
[assembly: AssemblyProduct("Geta.EPi.Imageshop")]
[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("c54433d8-eb2f-4bac-9b88-a54c84858a5d")]
// 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.5.0.1")]
[assembly: AssemblyFileVersion("1.5.0.1")]
| apache-2.0 | C# |
10d7164bac8e1b23730d8afdb2b1d3a441963054 | mark as CLS compliant | keith-hall/reactive-animation | src/Properties/AssemblyInfo.cs | src/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("ReactiveAnimation")]
[assembly: AssemblyDescription("Simple Animation framework built on Reactive Extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Keith Hall")]
[assembly: AssemblyProduct("ReactiveAnimation")]
[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("ead15993-b604-461c-9897-9ff19feb1041")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: System.CLSCompliant(true)]
| 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("ReactiveAnimation")]
[assembly: AssemblyDescription("Simple Animation framework built on Reactive Extensions")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Keith Hall")]
[assembly: AssemblyProduct("ReactiveAnimation")]
[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("ead15993-b604-461c-9897-9ff19feb1041")]
// 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")]
| apache-2.0 | C# |
f63f5a56868c85cd9deb43d0845334705a55c46e | Update copyright date | dpuleri/WRW | WinRedditWallpaper/Properties/AssemblyInfo.cs | WinRedditWallpaper/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("WpfApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WpfApplication1")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 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("WpfApplication1")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WpfApplication1")]
[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)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// 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")]
| apache-2.0 | C# |
580c16557ab16e86e39d412be443252d60d2a515 | Add console-based trace listener | maxwellb/csharp-driver,maxwellb/csharp-driver,datastax/csharp-driver,mintsoft/csharp-driver,datastax/csharp-driver | src/Cassandra.IntegrationTests/CommonFixtureSetup.cs | src/Cassandra.IntegrationTests/CommonFixtureSetup.cs | using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using NUnit.Framework;
namespace Cassandra.IntegrationTests
{
[SetUpFixture]
public class CommonFixtureSetup
{
[OneTimeSetUp]
public void SetupTestSuite()
{
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;
if (Environment.GetEnvironmentVariable("TEST_TRACE")?.ToUpper() == "ON")
{
Trace.Listeners.Add(new TextWriterTraceListener(Console.Out));
}
Trace.TraceInformation("Starting Test Run ...");
}
[OneTimeTearDown]
public void TearDownTestSuite()
{
// this method is executed once after all the fixtures have completed execution
TestClusterManager.TryRemove();
}
}
}
| using System.Diagnostics;
using System.Globalization;
using System.Threading;
using Cassandra.IntegrationTests.TestBase;
using Cassandra.IntegrationTests.TestClusterManagement;
using NUnit.Framework;
namespace Cassandra.IntegrationTests
{
[SetUpFixture]
public class CommonFixtureSetup
{
[OneTimeSetUp]
public void SetupTestSuite()
{
Diagnostics.CassandraTraceSwitch.Level = TraceLevel.Info;
Trace.TraceInformation("TestBase Setup Complete. Starting Test Run ...");
}
[OneTimeTearDown]
public void TearDownTestSuite()
{
// this method is executed once after all the fixtures have completed execution
TestClusterManager.TryRemove();
}
}
}
| apache-2.0 | C# |
221a726701503a5f34ecceed9eadff00229ec1f7 | Change exception message format | lecaillon/Evolve | src/Evolve/Exception/EvolveConfigurationException.cs | src/Evolve/Exception/EvolveConfigurationException.cs | using System;
namespace Evolve
{
public class EvolveConfigurationException : EvolveException
{
public EvolveConfigurationException(string message) : base(message) { }
public EvolveConfigurationException(string message, Exception innerException) : base(message, innerException) { }
}
}
| using System;
namespace Evolve
{
public class EvolveConfigurationException : EvolveException
{
private const string EvolveConfigurationError = "Evolve configuration error: ";
public EvolveConfigurationException(string message) : base(EvolveConfigurationError + FirstLetterToLower(message)) { }
public EvolveConfigurationException(string message, Exception innerException) : base(EvolveConfigurationError + FirstLetterToLower(message), innerException) { }
private static string FirstLetterToLower(string str)
{
if (str == null)
{
return "";
}
if (str.Length > 1)
{
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
return str.ToLowerInvariant();
}
}
}
| mit | C# |
ec5cd2d5828e51ebc4db1b6996e650630f8da965 | Fix for tests added in previous commit (r5368). Failing on TeamCity due to inability to locate embedded image resource. | ngbrown/nhibernate-core,RogerKratz/nhibernate-core,alobakov/nhibernate-core,nkreipke/nhibernate-core,livioc/nhibernate-core,alobakov/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,nkreipke/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,ngbrown/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,gliljas/nhibernate-core,nkreipke/nhibernate-core,hazzik/nhibernate-core,nhibernate/nhibernate-core,hazzik/nhibernate-core,hazzik/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,ManufacturingIntelligence/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,RogerKratz/nhibernate-core,nhibernate/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,livioc/nhibernate-core | src/NHibernate.Test/NHSpecificTest/NH2484/Fixture.cs | src/NHibernate.Test/NHSpecificTest/NH2484/Fixture.cs | using System;
using System.Drawing;
using System.Reflection;
using NUnit.Framework;
using NHibernate.Type;
using NHibernate.SqlTypes;
namespace NHibernate.Test.NHSpecificTest.NH2484
{
[TestFixture]
public class Fixture : BugTestCase
{
protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect)
{
return (dialect is Dialect.MsSql2008Dialect);
}
[Test]
public void TestPersistenceOfClassWithUnknownSerializableType()
{
Assembly assembly = Assembly.Load(MappingsAssembly);
var stream = assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg");
var image = Bitmap.FromStream(stream);
var model = new ClassWithImage() { Image = image };
var imageSize = model.Image.Size;
int id = -1;
using (ISession session = OpenSession())
{
session.SaveOrUpdate(model);
session.Flush();
id = model.Id;
Assert.That(id, Is.GreaterThan(-1));
}
using (ISession session = OpenSession())
{
model = session.Get<ClassWithImage>(id);
Assert.That(model.Image.Size, Is.EqualTo(imageSize)); // Ensure type is not truncated
}
using (ISession session = OpenSession())
{
session.CreateQuery("delete from ClassWithImage").ExecuteUpdate();
session.Flush();
}
stream.Dispose();
}
[Test]
public void TestPersistenceOfClassWithSerializableType()
{
Assembly assembly = Assembly.Load(MappingsAssembly);
var stream = assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg");
var image = Bitmap.FromStream(stream);
var model = new ClassWithSerializableType() { Image = image };
var imageSize = ((Image)model.Image).Size;
int id = -1;
using (ISession session = OpenSession())
{
session.SaveOrUpdate(model);
session.Flush();
id = model.Id;
Assert.That(id, Is.GreaterThan(-1));
}
using (ISession session = OpenSession())
{
model = session.Get<ClassWithSerializableType>(id);
Assert.That(((Image)model.Image).Size, Is.EqualTo(imageSize)); // Ensure type is not truncated
}
using (ISession session = OpenSession())
{
session.CreateQuery("delete from ClassWithSerializableType").ExecuteUpdate();
session.Flush();
}
stream.Dispose();
}
}
} | using System;
using System.Drawing;
using NUnit.Framework;
using NHibernate.Type;
using NHibernate.SqlTypes;
namespace NHibernate.Test.NHSpecificTest.NH2484
{
[TestFixture]
public class Fixture : BugTestCase
{
protected override bool AppliesTo(NHibernate.Dialect.Dialect dialect)
{
return (dialect is Dialect.MsSql2008Dialect);
}
[Test]
public void TestPersistenceOfClassWithUnknownSerializableType()
{
var stream = this.GetType().Assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg");
var image = Bitmap.FromStream(stream);
var model = new ClassWithImage() { Image = image };
var imageSize = model.Image.Size;
int id = -1;
using (ISession session = OpenSession())
{
session.SaveOrUpdate(model);
session.Flush();
id = model.Id;
Assert.That(id, Is.GreaterThan(-1));
}
using (ISession session = OpenSession())
{
model = session.Get<ClassWithImage>(id);
Assert.That(model.Image.Size, Is.EqualTo(imageSize)); // Ensure type is not truncated
}
using (ISession session = OpenSession())
{
session.CreateQuery("delete from ClassWithImage").ExecuteUpdate();
session.Flush();
}
stream.Dispose();
}
[Test]
public void TestPersistenceOfClassWithSerializableType()
{
var stream = this.GetType().Assembly.GetManifestResourceStream("NHibernate.Test.NHSpecificTest.NH2484.food-photo.jpg");
var image = Bitmap.FromStream(stream);
var model = new ClassWithSerializableType() { Image = image };
var imageSize = ((Image)model.Image).Size;
int id = -1;
using (ISession session = OpenSession())
{
session.SaveOrUpdate(model);
session.Flush();
id = model.Id;
Assert.That(id, Is.GreaterThan(-1));
}
using (ISession session = OpenSession())
{
model = session.Get<ClassWithSerializableType>(id);
Assert.That(((Image)model.Image).Size, Is.EqualTo(imageSize)); // Ensure type is not truncated
}
using (ISession session = OpenSession())
{
session.CreateQuery("delete from ClassWithSerializableType").ExecuteUpdate();
session.Flush();
}
stream.Dispose();
}
}
} | lgpl-2.1 | C# |
409abaded9ce0377f0a87879b1e78b6708842852 | fix identation | takenet/elephant | src/Take.Elephant.Kafka/KafkaPartitionSenderQueue.cs | src/Take.Elephant.Kafka/KafkaPartitionSenderQueue.cs | using System;
using System.Threading;
using System.Threading.Tasks;
using Confluent.Kafka;
namespace Take.Elephant.Kafka
{
public class KafkaPartitionSenderQueue<T> : IPartitionSenderQueue<T>, IDisposable
{
private readonly IEventStreamPublisher<string, string> _producer;
private readonly ISerializer<T> _serializer;
public KafkaPartitionSenderQueue(string bootstrapServers, string topic, ISerializer<T> serializer)
: this(new ProducerConfig() { BootstrapServers = bootstrapServers }, topic, serializer) { }
public KafkaPartitionSenderQueue(
string bootstrapServers,
string topic,
ISerializer<T> serializer,
Confluent.Kafka.ISerializer<string> kafkaSerializer)
: this(new ProducerConfig() { BootstrapServers = bootstrapServers }, topic, serializer, kafkaSerializer) { }
public KafkaPartitionSenderQueue(
ProducerConfig producerConfig,
string topic,
ISerializer<T> serializer)
: this(producerConfig, topic, serializer, null) { }
public KafkaPartitionSenderQueue(
ProducerConfig producerConfig,
string topic,
ISerializer<T> serializer,
Confluent.Kafka.ISerializer<string> kafkaSerializer)
{
Topic = topic;
_serializer = serializer;
_producer = new KafkaEventStreamPublisher<string, string>(producerConfig, topic, kafkaSerializer ?? new StringSerializer());
}
public KafkaPartitionSenderQueue(
IProducer<string, string> producer,
ISerializer<T> serializer,
string topic)
{
Topic = topic;
_serializer = serializer;
_producer = new KafkaEventStreamPublisher<string, string>(producer, topic);
}
public string Topic { get; }
public virtual Task EnqueueAsync(T item, string key, CancellationToken cancellationToken = default)
{
var stringItem = _serializer.Serialize(item);
return _producer.PublishAsync(key, stringItem, cancellationToken);
}
public void Dispose() => (_producer as IDisposable)?.Dispose();
}
}
| using System;
using System.Threading;
using System.Threading.Tasks;
using Confluent.Kafka;
namespace Take.Elephant.Kafka
{
public class KafkaPartitionSenderQueue<T> : IPartitionSenderQueue<T>, IDisposable
{
private readonly IEventStreamPublisher<string, string> _producer;
private readonly ISerializer<T> _serializer;
public KafkaPartitionSenderQueue(string bootstrapServers, string topic, ISerializer<T> serializer)
: this(new ProducerConfig() { BootstrapServers = bootstrapServers }, topic, serializer)
{
}
public KafkaPartitionSenderQueue(
string bootstrapServers,
string topic,
ISerializer<T> serializer,
Confluent.Kafka.ISerializer<string> kafkaSerializer)
: this(new ProducerConfig() { BootstrapServers = bootstrapServers }, topic, serializer, kafkaSerializer) { }
public KafkaPartitionSenderQueue(
ProducerConfig producerConfig,
string topic,
ISerializer<T> serializer)
: this(producerConfig, topic, serializer, null) { }
public KafkaPartitionSenderQueue(
ProducerConfig producerConfig,
string topic,
ISerializer<T> serializer,
Confluent.Kafka.ISerializer<string> kafkaSerializer)
{
Topic = topic;
_serializer = serializer;
_producer = new KafkaEventStreamPublisher<string, string>(producerConfig, topic, kafkaSerializer ?? new StringSerializer());
}
public KafkaPartitionSenderQueue(
IProducer<string, string> producer,
ISerializer<T> serializer,
string topic)
{
Topic = topic;
_serializer = serializer;
_producer = new KafkaEventStreamPublisher<string, string>(producer, topic);
}
public string Topic { get; }
public virtual Task EnqueueAsync(T item, string key, CancellationToken cancellationToken = default)
{
var stringItem = _serializer.Serialize(item);
return _producer.PublishAsync(key, stringItem, cancellationToken);
}
public void Dispose() => (_producer as IDisposable)?.Dispose();
}
}
| apache-2.0 | C# |
fccd8e8ee7e6699520d82def971efb3e445576bd | Fix incorrect formatting of time stamps | filipetoscano/Zinc | src/Zinc.WebServices.Swashbuckle/ZincSchemaFilter.cs | src/Zinc.WebServices.Swashbuckle/ZincSchemaFilter.cs | using Newtonsoft.Json;
using Swashbuckle.Swagger;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Zinc.Json;
namespace Zinc.WebServices
{
/// <summary />
public class ZincSchemaFilter : ISchemaFilter
{
/// <summary />
public void Apply( Schema schema, SchemaRegistry schemaRegistry, Type type )
{
#region Validations
if ( schema == null )
throw new ArgumentNullException( nameof( schema ) );
if ( type == null )
throw new ArgumentNullException( nameof( type ) );
#endregion
var properties = type.GetProperties()
.Where( prop => prop.PropertyType == typeof( DateTime )
&& prop.GetCustomAttribute<JsonConverterAttribute>() != null );
foreach ( var prop in properties )
{
var conv = prop.GetCustomAttribute<JsonConverterAttribute>();
var propSchema = schema.properties[ prop.Name ];
if ( conv.ConverterType == typeof( DateConverter ) || conv.ConverterType == typeof( NullableDateConverter ) )
{
propSchema.format = "date";
propSchema.example = DateTime.UtcNow.ToString( "yyyy-MM-dd", CultureInfo.InvariantCulture );
}
if ( conv.ConverterType == typeof( TimeConverter ) || conv.ConverterType == typeof( NullableTimeConverter ) )
{
propSchema.format = "time";
propSchema.example = DateTime.UtcNow.ToString( "HH:mm:ss", CultureInfo.InvariantCulture );
}
}
}
}
}
| using Newtonsoft.Json;
using Swashbuckle.Swagger;
using System;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Zinc.Json;
namespace Zinc.WebServices
{
/// <summary />
public class ZincSchemaFilter : ISchemaFilter
{
/// <summary />
public void Apply( Schema schema, SchemaRegistry schemaRegistry, Type type )
{
#region Validations
if ( schema == null )
throw new ArgumentNullException( nameof( schema ) );
if ( type == null )
throw new ArgumentNullException( nameof( type ) );
#endregion
var properties = type.GetProperties()
.Where( prop => prop.PropertyType == typeof( DateTime )
&& prop.GetCustomAttribute<JsonConverterAttribute>() != null );
foreach ( var prop in properties )
{
var conv = prop.GetCustomAttribute<JsonConverterAttribute>();
var propSchema = schema.properties[ prop.Name ];
if ( conv.ConverterType == typeof( DateConverter ) || conv.ConverterType == typeof( NullableDateConverter ) )
{
propSchema.format = "date";
propSchema.example = DateTime.UtcNow.ToString( "yyyy-MM-dd", CultureInfo.InvariantCulture );
}
if ( conv.ConverterType == typeof( TimeConverter ) || conv.ConverterType == typeof( NullableTimeConverter ) )
{
propSchema.format = "time";
propSchema.example = DateTime.UtcNow.ToString( "hh:mm:ss", CultureInfo.InvariantCulture );
}
}
}
}
}
| bsd-3-clause | C# |
878213887fc72ec4aaaf211fbd028bcd9e5e576c | Change Russian to Русский for the language selector | qianlifeng/Wox,Wox-launcher/Wox,Wox-launcher/Wox,lances101/Wox,lances101/Wox,qianlifeng/Wox,qianlifeng/Wox | Wox.Core/i18n/AvailableLanguages.cs | Wox.Core/i18n/AvailableLanguages.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Wox.Core.i18n
{
internal static class AvailableLanguages
{
public static Language English = new Language("en", "English");
public static Language Chinese = new Language("zh-cn", "中文");
public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)");
public static Language Russian = new Language("ru", "Русский");
public static List<Language> GetAvailableLanguages()
{
List<Language> languages = new List<Language>
{
English,
Chinese,
Chinese_TW,
Russian,
};
return languages;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Wox.Core.i18n
{
internal static class AvailableLanguages
{
public static Language English = new Language("en", "English");
public static Language Chinese = new Language("zh-cn", "中文");
public static Language Chinese_TW = new Language("zh-tw", "中文(繁体)");
public static Language Russian = new Language("ru", "Russian");
public static List<Language> GetAvailableLanguages()
{
List<Language> languages = new List<Language>
{
English,
Chinese,
Chinese_TW,
Russian,
};
return languages;
}
}
} | mit | C# |
5ff47467a3e9a1c618e1bde53a95b174be1f7d99 | Fix potential thread safety issue in viewmodelbase.cs | Sankra/NDC2015,Hammerstad/NDC2015 | NDC2015/ViewModelBase.cs | NDC2015/ViewModelBase.cs | using System.ComponentModel;
using System.Runtime.CompilerServices;
using NDC2015.Annotations;
namespace NDC2015
{
public class ViewModelBase : INotifyPropertyChanged
{
protected void Set<T>(ref T member, T value, [CallerMemberName] string propertyName = null)
{
member = value;
OnPropertyChanged(propertyName);
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var propertyChanged = PropertyChanged;
if (propertyChanged != null)
{
propertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
} | using System.ComponentModel;
using System.Runtime.CompilerServices;
using NDC2015.Annotations;
namespace NDC2015
{
public class ViewModelBase : INotifyPropertyChanged
{
protected void Set<T>(ref T member, T value, [CallerMemberName] string propertyName = null)
{
member = value;
OnPropertyChanged(propertyName);
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
} | mit | C# |
a9ef42c8891a7d06425de4a2627c21658b948cac | Rename params to match convention | Livit/CefSharp,Haraguroicha/CefSharp,dga711/CefSharp,gregmartinhtc/CefSharp,ruisebastiao/CefSharp,yoder/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,ruisebastiao/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,NumbersInternational/CefSharp,illfang/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,joshvera/CefSharp,illfang/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,windygu/CefSharp,dga711/CefSharp,wangzheng888520/CefSharp,gregmartinhtc/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,zhangjingpu/CefSharp,zhangjingpu/CefSharp,twxstar/CefSharp,Octopus-ITSM/CefSharp,ruisebastiao/CefSharp,AJDev77/CefSharp,yoder/CefSharp,ITGlobal/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,rlmcneary2/CefSharp,rlmcneary2/CefSharp,gregmartinhtc/CefSharp,yoder/CefSharp,Octopus-ITSM/CefSharp,haozhouxu/CefSharp,VioletLife/CefSharp,wangzheng888520/CefSharp,twxstar/CefSharp,ruisebastiao/CefSharp,battewr/CefSharp,ITGlobal/CefSharp,windygu/CefSharp,joshvera/CefSharp,dga711/CefSharp,joshvera/CefSharp,Octopus-ITSM/CefSharp,Livit/CefSharp,rover886/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,haozhouxu/CefSharp,ITGlobal/CefSharp,Octopus-ITSM/CefSharp,illfang/CefSharp,battewr/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,battewr/CefSharp,yoder/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,twxstar/CefSharp,illfang/CefSharp,Haraguroicha/CefSharp,Haraguroicha/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,windygu/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,NumbersInternational/CefSharp,jamespearce2006/CefSharp,rlmcneary2/CefSharp,VioletLife/CefSharp,joshvera/CefSharp,Livit/CefSharp,haozhouxu/CefSharp,AJDev77/CefSharp,battewr/CefSharp,AJDev77/CefSharp | CefSharp/IDialogHandler.cs | CefSharp/IDialogHandler.cs | using System.Collections.Generic;
namespace CefSharp
{
public interface IDialogHandler
{
bool OnOpenFile(IWebBrowser browser, string title, string defaultFileName, List<string> acceptTypes, out List<string> result);
}
}
| using System.Collections.Generic;
namespace CefSharp
{
public interface IDialogHandler
{
bool OnOpenFile(IWebBrowser browser, string title, string default_file_name, List<string> accept_types, out List<string> result);
}
}
| bsd-3-clause | C# |
b69861f142e6aaaf627d091cacc08d73ec96e299 | Update HealthScanner.cs | fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,Necromunger/unitystation,fomalsd/unitystation,Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation | UnityProject/Assets/Scripts/Medical/HealthScanner.cs | UnityProject/Assets/Scripts/Medical/HealthScanner.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthScanner : PickUpTrigger
{
public void PlayerFound(GameObject Player) {
PlayerHealth Playerhealth = Player.GetComponent<PlayerHealth>();
string ToShow = (Player.name + " is " + Playerhealth.ConsciousState.ToString() + "\n"
+"OverallHealth = " + Playerhealth.OverallHealth.ToString() + " Blood level = " + Playerhealth.bloodSystem.BloodLevel.ToString() + "\n"
+ "Blood oxygen level = " + Playerhealth.bloodSystem.OxygenLevel.ToString() + "\n"
+ "Body Part, Brut, Burn \n");
foreach (BodyPartBehaviour BodyPart in Playerhealth.BodyParts) {
ToShow += BodyPart.Type.ToString() + "\t";
ToShow += BodyPart.BruteDamage.ToString() + "\t";
ToShow += BodyPart.BurnDamage.ToString();
ToShow += "\n";
}
PostToChatMessage.Send(ToShow,ChatChannel.System);
//Logger.Log(ToShow);
}
public override bool Interact(GameObject originator, Vector3 position, string hand)
{
if (gameObject == UIManager.Hands.CurrentSlot.Item)
{
Vector3 tposition = Camera.main.ScreenToWorldPoint(UnityEngine.Input.mousePosition);
tposition.z = 0f;
List<GameObject> objects = UITileList.GetItemsAtPosition(tposition);
foreach (GameObject theObject in objects) {
PlayerHealth thething = theObject.GetComponentInChildren<PlayerHealth>();
if (thething != null) {
PlayerFound(theObject);
}
}
return base.Interact(originator, position, hand);;
}
else
{
return base.Interact(originator, position, hand);
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthScanner : PickUpTrigger
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void PlayerFound(GameObject Player) {
PlayerHealth Playerhealth = Player.GetComponent<PlayerHealth>();
string ToShow = (Player.name + " is " + Playerhealth.ConsciousState.ToString() + "\n"
+"OverallHealth = " + Playerhealth.OverallHealth.ToString() + " Blood level = " + Playerhealth.bloodSystem.BloodLevel.ToString() + "\n"
+ "Blood oxygen level = " + Playerhealth.bloodSystem.OxygenLevel.ToString() + "\n"
+ "Body Part, Brut, Burn \n");
foreach (BodyPartBehaviour BodyPart in Playerhealth.BodyParts) {
ToShow += BodyPart.Type.ToString() + "\t";
ToShow += BodyPart.BruteDamage.ToString() + "\t";
ToShow += BodyPart.BurnDamage.ToString();
ToShow += "\n";
}
PostToChatMessage.Send(ToShow,ChatChannel.System);
Logger.Log(ToShow);
}
/// <summary>
/// Occurs when shooting by clicking on empty space
/// </summary>
public override bool Interact(GameObject originator, Vector3 position, string hand)
{
//shoot gun interation if its in hand
if (gameObject == UIManager.Hands.CurrentSlot.Item)
{
Vector3 tposition = Camera.main.ScreenToWorldPoint(UnityEngine.Input.mousePosition);
tposition.z = 0f;
List<GameObject> objects = UITileList.GetItemsAtPosition(tposition);
foreach (GameObject theObject in objects) {
PlayerHealth thething = theObject.GetComponentInChildren<PlayerHealth>();
if (thething != null) {
PlayerFound(theObject);
}
}
Logger.Log("yo");
//
return base.Interact(originator, position, hand);;
}
else
{
return base.Interact(originator, position, hand);
}
}
}
| agpl-3.0 | C# |
f20d1c2f30b9544e2bb29ca2ace2f2223ce5cc84 | improve import scenario workflow > first cancel works | accu-rate/SumoVizUnity,accu-rate/SumoVizUnity | Assets/Editor/ScenarioImporter.cs | Assets/Editor/ScenarioImporter.cs | using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.IO;
using System.Collections;
public class ScenarioImporter {
[MenuItem("Assets/Import accu:rate output")]
static void importAccurateOutput() {
if (!EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo ())
return;
bool continueOk = true;
if (EditorSceneManager.GetActiveScene().name == "Base")
continueOk = !EditorUtility.DisplayDialog("duplicate scene", "It is recommend that you first duplicate the Scene (select it in the Scenes folder and use Edit > Duplicate), rename it optionally and doubleclick the new scene.", "ok, let me duplicate", "continue");
if (continueOk) {
var path = EditorUtility.OpenFilePanel ("", Application.dataPath + "/Resources/Data", "xml"); //Path.GetFileName(path))
if (path == "") // = cancel was clicked in open file dialog
return;
new GameObject("World");
new GameObject ("Pedestrians");
RuntimeInitializer ri = GameObject.Find("RuntimeInitializer").GetComponent<RuntimeInitializer>();
ri.geometryLoader = GameObject.Find("GeometryLoader").GetComponent<GeometryLoader>();
ri.geometryLoader.setTheme (new EvaktischThemingMode ());
ScenarioLoader sl = new ScenarioLoader (path);
sl.loadScenario ();
ri.relativeTrajFilePath = sl.getRelativeTrajFilePath ();
}
}
[MenuItem("Assets/dev")]
static void dev() {
/* this is the name the app gets on an android smartphone */
//PlayerSettings.productName = "app_name";
//Debug.Log (PlayerSettings.productName);
/* to undo the texture-stretching on a cube that stretching the cube caused */
//ReCalcCubeTexture script = GameObject.Find("Cube").GetComponent<ReCalcCubeTexture>();
//script.reCalcCubeTexture ();
/*
string dir = "Assets/Resources/Data/_ignore/out_***REMOVED***/";
FileInfo fi = new FileInfo (dir + "floor-0.csv");
StreamReader reader = fi.OpenText ();
StreamWriter writer = new StreamWriter(dir + "floor-0_reduced.csv", false);
using (reader) {
string line;
int i = 0;
while((line = reader.ReadLine()) != null && i++ < 100000) {
writer.WriteLine (line);
}
reader.Close ();
writer.Close();
}
Debug.Log ("DONE");
*/
}
}
| using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
using System.IO;
using System.Collections;
public class ScenarioImporter {
[MenuItem("Assets/Import accu:rate output")]
static void importAccurateOutput() {
var ret = EditorSceneManager.SaveCurrentModifiedScenesIfUserWantsTo ();
//TODO Debug.Log (ret.ToString ());
var continueOk = true;
if (EditorSceneManager.GetActiveScene().name == "Base")
continueOk = !EditorUtility.DisplayDialog("duplicate scene", "It is recommend that you first duplicate the Scene (select it in the Scenes folder and use Edit > Duplicate), rename it optionally and doubleclick the new scene.", "ok, let me duplicate", "continue");
if (continueOk) {
var path = EditorUtility.OpenFilePanel ("", Application.dataPath + "/Resources/Data", "xml"); //Path.GetFileName(path))
if (path == "") // = cancel was clicked in open file dialog
return;
new GameObject("World");
new GameObject ("Pedestrians");
RuntimeInitializer ri = GameObject.Find("RuntimeInitializer").GetComponent<RuntimeInitializer>();
ri.geometryLoader = GameObject.Find("GeometryLoader").GetComponent<GeometryLoader>();
ri.geometryLoader.setTheme (new EvaktischThemingMode ());
ScenarioLoader sl = new ScenarioLoader (path);
sl.loadScenario ();
ri.relativeTrajFilePath = sl.getRelativeTrajFilePath ();
}
}
[MenuItem("Assets/dev")]
static void dev() {
/* this is the name the app gets on an android smartphone */
//PlayerSettings.productName = "app_name";
//Debug.Log (PlayerSettings.productName);
/* to undo the texture-stretching on a cube that stretching the cube caused */
//ReCalcCubeTexture script = GameObject.Find("Cube").GetComponent<ReCalcCubeTexture>();
//script.reCalcCubeTexture ();
/*
string dir = "Assets/Resources/Data/_ignore/out_***REMOVED***/";
FileInfo fi = new FileInfo (dir + "floor-0.csv");
StreamReader reader = fi.OpenText ();
StreamWriter writer = new StreamWriter(dir + "floor-0_reduced.csv", false);
using (reader) {
string line;
int i = 0;
while((line = reader.ReadLine()) != null && i++ < 100000) {
writer.WriteLine (line);
}
reader.Close ();
writer.Close();
}
Debug.Log ("DONE");
*/
}
}
| mit | C# |
50693ce25cd8f0f450bb795492d6e0851af5be3a | Revert the previous change | EasyPost/easypost-csharp,EasyPost/easypost-csharp | EasyPost/Client.cs | EasyPost/Client.cs | using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
namespace EasyPost {
public class Client {
public string version;
internal RestClient client;
internal ClientConfiguration configuration;
public Client(ClientConfiguration clientConfiguration) {
System.Net.ServicePointManager.SecurityProtocol = Security.GetProtocol();
if (clientConfiguration == null) throw new ArgumentNullException("clientConfiguration");
configuration = clientConfiguration;
client = new RestClient(clientConfiguration.ApiBase);
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
version = info.FileVersion;
}
public IRestResponse Execute(Request request) {
return client.Execute(PrepareRequest(request));
}
public T Execute<T>(Request request) where T : new() {
RestResponse<T> response = (RestResponse<T>)client.Execute<T>(PrepareRequest(request));
int StatusCode = Convert.ToInt32(response.StatusCode);
if (StatusCode > 399) {
try {
Dictionary<string, Dictionary<string, object>> Body = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(response.Content);
throw new HttpException(StatusCode, (string)Body["error"]["message"], (string)Body["error"]["code"]);
} catch {
throw new HttpException(StatusCode, "RESPONSE.PARSE_ERROR", response.Content);
}
}
return response.Data;
}
internal RestRequest PrepareRequest(Request request) {
RestRequest restRequest = (RestRequest)request;
restRequest.AddHeader("user_agent", string.Concat("EasyPost/v2 CSharp/", version));
restRequest.AddHeader("authorization", "Bearer " + this.configuration.ApiKey);
restRequest.AddHeader("content_type", "application/x-www-form-urlencoded");
return restRequest;
}
}
}
| using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading;
namespace EasyPost {
public class Client {
public string version;
internal RestClient client;
internal ClientConfiguration configuration;
public Client(ClientConfiguration clientConfiguration) {
System.Net.ServicePointManager.SecurityProtocol = Security.GetProtocol();
if (clientConfiguration == null) throw new ArgumentNullException("clientConfiguration");
configuration = clientConfiguration;
client = new RestClient(clientConfiguration.ApiBase);
Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo info = FileVersionInfo.GetVersionInfo(assembly.Location);
version = info.FileVersion;
}
public IRestResponse Execute(Request request) {
return client.Execute(PrepareRequest(request));
}
public T Execute<T>(Request request) where T : new() {
RestResponse<T> response = (RestResponse<T>)client.Execute<T>(PrepareRequest(request));
int StatusCode = Convert.ToInt32(response.StatusCode);
if (StatusCode > 399) {
try {
Dictionary<string, Dictionary<string, object>> Body = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, object>>>(response.Content);
throw new HttpException(StatusCode, (string)Body["error"]["message"], (string)Body["error"]["code"]);
} catch {
throw new HttpException(StatusCode, "RESPONSE.PARSE_ERROR", response.Content);
}
}
return response.Data;
}
internal RestRequest PrepareRequest(Request request) {
RestRequest restRequest = (RestRequest)request;
restRequest.AddHeader("user_agent", string.Concat("EasyPost/v2 CSharp/", version));
restRequest.AddHeader("authorization", "Bearer " + this.configuration.ApiKey);
restRequest.AddHeader("content_type", "application/x-www-form-urlencoded");
return restRequest;
}
}
}
| mit | C# |
c0e863a222c8779e68602f51de4a10053e8c8e41 | Change version to 0.10.1 | Seddryck/Lookum | GlobalAssemblyInfo.cs | GlobalAssemblyInfo.cs | using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Lookum Team - Cédric L. Charlier")]
[assembly: AssemblyProduct("Lookum")]
[assembly: AssemblyCopyright("Copyright © 2014-2015 - Cédric L. Charlier")]
[assembly: AssemblyDescription("Lookum is a framework dedicated to the support of etl features available from C# applications")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
//Reference the testing class to ensure access to internal members
[assembly: InternalsVisibleTo("Lookum.Framework.Testing")]
[assembly: AssemblyVersion("0.10.0.*")]
[assembly: AssemblyFileVersion("0.10.1")]
[assembly: AssemblyInformationalVersion("0.10.1-BETA")]
| using System.Resources;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyCompany("Lookum Team - Cédric L. Charlier")]
[assembly: AssemblyProduct("Lookum")]
[assembly: AssemblyCopyright("Copyright © 2014-2015 - Cédric L. Charlier")]
[assembly: AssemblyDescription("Lookum is a framework dedicated to the support of etl features available from C# applications")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
//Reference the testing class to ensure access to internal members
[assembly: InternalsVisibleTo("Lookum.Framework.Testing")]
[assembly: AssemblyVersion("0.10.0.*")]
[assembly: AssemblyFileVersion("0.10.0")]
[assembly: AssemblyInformationalVersion("0.10.0-BETA")]
| apache-2.0 | C# |
dd9e57efa22f9086c8805943dd949653e85affa7 | Fix stupid typo | mmbot/mmbot.scripts | scripts/Fun/Swearjar.csx | scripts/Fun/Swearjar.csx | /**
* <description>
* Monitors for swearing
* </description>
*
* <configuration>
*
* </configuration>
*
* <commands>
* mmbot swearjar - shows the swear stats of users
* </commands>
*
* <author>
* dkarzon
* </author>
*/
var robot = Require<Robot>();
robot.Respond("swearjar", msg =>
{
var swearBrain = robot.Brain.Get<List<SwearUser>>("swearbot").Result ?? new List<SwearUser>();
foreach (var s in swearBrain.OrderByDescending(s => (s.Swears ?? new List<SwearStat>()).Count))
{
if (s.Swears == null) continue;
msg.Send(string.Format("{0} has sworn {1} times!", s.User, s.Swears.Count));
}
});
robot.Hear(@".*\b(fuck|shit|cock|crap|bitch|cunt|asshole|dick)(s)?(ed)?(ing)?(\b|\s|$)", (msg) =>
{
//Someone said a swear!
var theSwear = msg.Match[1];
var userName = msg.Message.User.Name;
//load the swears from the Brain
var swearBrain = robot.Brain.Get<List<SwearUser>>("swearbot").Result ?? new List<SwearUser>();
var swearUser = swearBrain.FirstOrDefault(s => s.User == userName);
if (swearUser == null)
{
swearUser = new SwearUser { User = userName };
swearBrain.Add(swearUser);
}
if (swearUser.Swears == null)
{
swearUser.Swears = new List<SwearStat>();
}
swearUser.Swears.Add(new SwearStat{Swear = theSwear, Date = DateTime.Now});
robot.Brain.Set("swearbot", swearBrain);
msg.Send("SWEAR JAR!");
});
public class SwearStat
{
public string Swear { get; set; }
public DateTime Date { get; set; }
}
public class SwearUser
{
public string User { get; set; }
public List<SwearStat> Swears { get; set; }
}
| /**
* <description>
* Monitors for swearing
* </description>
*
* <configuration>
*
* </configuration>
*
* <commands>
* mmbot swearjar - shows the swear stats of users
* </commands>
*
* <author>
* dkarzon
* </author>
*/
var robot = Require<Robot>();
robot.Respond("swearjar", msg =>
{
var swearBrain = robot.Brain.Get<List<SwearUser>>("swearbot").Result ?? new List<SwearUser>();
foreach (var s in swearBrain..OrderByDescending(s => (s.Swears ?? new List<SwearStat>()).Count))
{
if (s.Swears == null) continue;
msg.Send(string.Format("{0} has sworn {1} times!", s.User, s.Swears.Count));
}
});
robot.Hear(@".*\b(fuck|shit|cock|crap|bitch|cunt|asshole|dick)(s)?(ed)?(ing)?(\b|\s|$)", (msg) =>
{
//Someone said a swear!
var theSwear = msg.Match[1];
var userName = msg.Message.User.Name;
//load the swears from the Brain
var swearBrain = robot.Brain.Get<List<SwearUser>>("swearbot").Result ?? new List<SwearUser>();
var swearUser = swearBrain.FirstOrDefault(s => s.User == userName);
if (swearUser == null)
{
swearUser = new SwearUser { User = userName };
swearBrain.Add(swearUser);
}
if (swearUser.Swears == null)
{
swearUser.Swears = new List<SwearStat>();
}
swearUser.Swears.Add(new SwearStat{Swear = theSwear, Date = DateTime.Now});
robot.Brain.Set("swearbot", swearBrain);
msg.Send("SWEAR JAR!");
});
public class SwearStat
{
public string Swear { get; set; }
public DateTime Date { get; set; }
}
public class SwearUser
{
public string User { get; set; }
public List<SwearStat> Swears { get; set; }
}
| apache-2.0 | C# |
437cc7d9f053f001bfcb21ba0038906c6b0faf91 | Fix typo in HtmlParseMode.cs | AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp,AngleSharp/AngleSharp | src/AngleSharp/Html/Parser/HtmlParseMode.cs | src/AngleSharp/Html/Parser/HtmlParseMode.cs | namespace AngleSharp.Html.Parser
{
/// <summary>
/// Defines the different tokenization content models.
/// </summary>
enum HtmlParseMode : byte
{
/// <summary>
/// Initial state: Parsed Character Data (characters will be parsed).
/// </summary>
PCData,
/// <summary>
/// Optional state: Raw character data (characters will be parsed from a special table).
/// </summary>
RCData,
/// <summary>
/// Optional state: Just plain text data (characters will be parsed matching the given ones).
/// </summary>
Plaintext,
/// <summary>
/// Optional state: Rawtext data (characters will not be parsed).
/// </summary>
Rawtext,
/// <summary>
/// Optional state: Script data.
/// </summary>
Script
}
}
| namespace AngleSharp.Html.Parser
{
/// <summary>
/// Defines the different tokenization content models.
/// </summary>
enum HtmlParseMode : byte
{
/// <summary>
/// Initial state: Parsed Character Data (characters will be parsed).
/// </summary>
PCData,
/// <summary>
/// Optional state: Raw character data (characters will be parsed from a special table).
/// </summary>
RCData,
/// <summary>
/// Optional state: Just plain text data (chracters will be parsed matching the given ones).
/// </summary>
Plaintext,
/// <summary>
/// Optional state: Rawtext data (characters will not be parsed).
/// </summary>
Rawtext,
/// <summary>
/// Optional state: Script data.
/// </summary>
Script
}
}
| mit | C# |
a0ed0631ed33d52e12aa199754353c6a7b7ab545 | Add DEMON_HUNTER_INITIATE to wild | HearthSim/HearthDb | HearthDb/Helper.cs | HearthDb/Helper.cs | using HearthDb.Enums;
using System.Text.RegularExpressions;
namespace HearthDb
{
public static class Helper
{
public static Regex AtCounterRegex = new Regex(@"\|4\(([^,)]+),\s*([^,)]+)\)");
public static Regex ProgressRegex = new Regex(@"\(@\/\d+\)");
public static CardSet[] WildSets =
{
CardSet.BRM, CardSet.LOE, CardSet.TGT, CardSet.HOF,
CardSet.FP1, CardSet.PE1, CardSet.PROMO,
CardSet.KARA, CardSet.OG, CardSet.GANGS,
CardSet.UNGORO, CardSet.ICECROWN, CardSet.LOOTAPALOOZA,
CardSet.GILNEAS, CardSet.BOOMSDAY, CardSet.TROLL,
CardSet.DEMON_HUNTER_INITIATE,
};
public static CardSet[] ClassicSets = { CardSet.VANILLA };
public static string[] SpellstoneStrings =
{
CardIds.Collectible.Druid.LesserJasperSpellstone,
CardIds.Collectible.Mage.LesserRubySpellstone,
CardIds.Collectible.Paladin.LesserPearlSpellstone,
CardIds.Collectible.Priest.LesserDiamondSpellstone,
CardIds.Collectible.Rogue.LesserOnyxSpellstone,
CardIds.Collectible.Shaman.LesserSapphireSpellstone,
CardIds.Collectible.Warlock.LesserAmethystSpellstone,
CardIds.NonCollectible.Neutral.TheDarkness_TheDarkness
};
}
}
| using HearthDb.Enums;
using System.Text.RegularExpressions;
namespace HearthDb
{
public static class Helper
{
public static Regex AtCounterRegex = new Regex(@"\|4\(([^,)]+),\s*([^,)]+)\)");
public static Regex ProgressRegex = new Regex(@"\(@\/\d+\)");
public static CardSet[] WildSets =
{
CardSet.BRM, CardSet.LOE, CardSet.TGT, CardSet.HOF,
CardSet.FP1, CardSet.PE1, CardSet.PROMO,
CardSet.KARA, CardSet.OG, CardSet.GANGS,
CardSet.UNGORO, CardSet.ICECROWN, CardSet.LOOTAPALOOZA,
CardSet.GILNEAS, CardSet.BOOMSDAY, CardSet.TROLL,
};
public static CardSet[] ClassicSets = { CardSet.VANILLA };
public static string[] SpellstoneStrings =
{
CardIds.Collectible.Druid.LesserJasperSpellstone,
CardIds.Collectible.Mage.LesserRubySpellstone,
CardIds.Collectible.Paladin.LesserPearlSpellstone,
CardIds.Collectible.Priest.LesserDiamondSpellstone,
CardIds.Collectible.Rogue.LesserOnyxSpellstone,
CardIds.Collectible.Shaman.LesserSapphireSpellstone,
CardIds.Collectible.Warlock.LesserAmethystSpellstone,
CardIds.NonCollectible.Neutral.TheDarkness_TheDarkness
};
}
}
| mit | C# |
d4d6f6388d3f0c44d36b7269ccc6516cbb9fc2cd | include a public domain license statement on the one code file (tracewriter) which was just derived from the hockeyapp sdk. | tpurtell/AndroidHockeyApp | Additions/TraceWriter.cs | Additions/TraceWriter.cs | // public domain ... derived from https://github.com/bitstadium/HockeySDK-Android/blob/db7fff12beecea715f2894cb69ba358ea324ad17/src/main/java/net/hockeyapp/android/internal/ExceptionHandler.java
using System;
using System.IO;
using Java.Lang;
using Java.Util;
using Exception = System.Exception;
using Process = Android.OS.Process;
namespace Net.Hockeyapp.Android
{
public static class TraceWriter
{
public static void WriteTrace(object exception)
{
DateTime date = DateTime.UtcNow;
// Create filename from a random uuid
string filename = UUID.RandomUUID().ToString();
string path = Path.Combine(Constants.FilesPath, filename + ".stacktrace");
Console.WriteLine("Writing unhandled exception to: {0}", path);
try
{
using (var f = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
using (var sw = new StreamWriter(f))
{
// Write the stacktrace to disk
sw.WriteLine("Package: {0}", Constants.AppPackage);
sw.WriteLine("Version: {0}", Constants.AppVersion);
sw.WriteLine("Android: {0}", Constants.AndroidVersion);
sw.WriteLine("Manufacturer: {0}", Constants.PhoneManufacturer);
sw.WriteLine("Model: {0}", Constants.PhoneModel);
sw.WriteLine("Date: {0}", date);
sw.WriteLine();
sw.WriteLine(exception);
}
}
catch (Exception another)
{
Console.WriteLine("Error saving exception stacktrace! {0}", another);
}
Process.KillProcess(Process.MyPid());
JavaSystem.Exit(10);
Environment.Exit(10);
}
}
} | using System;
using System.IO;
using Java.Lang;
using Java.Util;
using Exception = System.Exception;
using Process = Android.OS.Process;
namespace Net.Hockeyapp.Android
{
public static class TraceWriter
{
public static void WriteTrace(object exception)
{
DateTime date = DateTime.UtcNow;
// Create filename from a random uuid
string filename = UUID.RandomUUID().ToString();
string path = Path.Combine(Constants.FilesPath, filename + ".stacktrace");
Console.WriteLine("Writing unhandled exception to: {0}", path);
try
{
using (var f = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
using (var sw = new StreamWriter(f))
{
// Write the stacktrace to disk
sw.WriteLine("Package: {0}", Constants.AppPackage);
sw.WriteLine("Version: {0}", Constants.AppVersion);
sw.WriteLine("Android: {0}", Constants.AndroidVersion);
sw.WriteLine("Manufacturer: {0}", Constants.PhoneManufacturer);
sw.WriteLine("Model: {0}", Constants.PhoneModel);
sw.WriteLine("Date: {0}", date);
sw.WriteLine();
sw.WriteLine(exception);
}
}
catch (Exception another)
{
Console.WriteLine("Error saving exception stacktrace! {0}", another);
}
Process.KillProcess(Process.MyPid());
JavaSystem.Exit(10);
Environment.Exit(10);
}
}
} | mit | C# |
95ca5ddbc0165a6fa928c570961621a490f20227 | Add datetime prefix to dumped file name if texture didn't have name | earalov/Skylines-ModTools | Debugger/Utils/FileUtil.cs | Debugger/Utils/FileUtil.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using ColossalFramework.Plugins;
using ICities;
namespace ModTools
{
public static class FileUtil
{
public static List<string> ListFilesInDirectory(string path, List<string> _filesMustBeNull = null)
{
_filesMustBeNull = _filesMustBeNull ?? new List<string>();
foreach (string file in Directory.GetFiles(path))
{
_filesMustBeNull.Add(file);
}
return _filesMustBeNull;
}
public static string FindPluginPath(Type type)
{
var pluginManager = PluginManager.instance;
var plugins = pluginManager.GetPluginsInfo();
foreach (var item in plugins)
{
var instances = item.GetInstances<IUserMod>();
var instance = instances.FirstOrDefault();
if (instance != null && instance.GetType() != type)
{
continue;
}
foreach (var file in Directory.GetFiles(item.modPath))
{
if (Path.GetExtension(file) == ".dll")
{
return file;
}
}
}
throw new Exception("Failed to find assembly!");
}
public static string LegalizeFileName(this string illegal)
{
if (string.IsNullOrEmpty(illegal))
{
return DateTime.Now.ToString("yyyyMMddhhmmss");
}
var regexSearch = new string(Path.GetInvalidFileNameChars()/* + new string(Path.GetInvalidPathChars()*/);
var r = new Regex($"[{Regex.Escape(regexSearch)}]");
return r.Replace(illegal, "_");
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using ColossalFramework.Plugins;
using ICities;
namespace ModTools
{
public static class FileUtil
{
public static List<string> ListFilesInDirectory(string path, List<string> _filesMustBeNull = null)
{
_filesMustBeNull = _filesMustBeNull ?? new List<string>();
foreach (string file in Directory.GetFiles(path))
{
_filesMustBeNull.Add(file);
}
return _filesMustBeNull;
}
public static string FindPluginPath(Type type)
{
var pluginManager = PluginManager.instance;
var plugins = pluginManager.GetPluginsInfo();
foreach (var item in plugins)
{
var instances = item.GetInstances<IUserMod>();
var instance = instances.FirstOrDefault();
if (instance != null && instance.GetType() != type)
{
continue;
}
foreach (var file in Directory.GetFiles(item.modPath))
{
if (Path.GetExtension(file) == ".dll")
{
return file;
}
}
}
throw new Exception("Failed to find assembly!");
}
public static string LegalizeFileName(this string illegal)
{
var regexSearch = new string(Path.GetInvalidFileNameChars()/* + new string(Path.GetInvalidPathChars()*/);
var r = new Regex($"[{Regex.Escape(regexSearch)}]");
return r.Replace(illegal, "_");
}
}
}
| mit | C# |
7f923d9a044d0773d2801b4e81bc82d5879606fd | remove ugly hack | martinlindhe/Punku | punku/Strings/Shift.cs | punku/Strings/Shift.cs | using System;
// TODO: upper case!
// TODO: unit test for non-2-shifts
// FIXME: vad är skillnaden mellan Rot13? är det metoden...?
namespace Punku.Strings
{
/**
* Transform english text to a shifted form (a = a + shift)
*/
public class Shift
{
public char[] Table = new char[char.MaxValue];
public Shift (int shift)
{
for (int i = 0; i < char.MaxValue; i++)
Table [i] = (char)i;
for (int i = 'a'; i <= 'z'; i++) {
if (i + shift <= 'z')
Table [i] = (char)(i + shift);
else
Table [i] = (char)(i + shift - 'z' + 'a' - 1);
}
}
public string ShiftString (string s)
{
char[] arr = s.ToCharArray ();
for (int i = 0; i < arr.Length; i++)
arr [i] = Table [arr [i]];
return new string (arr);
}
public static string ShiftString (string s, int shift)
{
var x = new Shift (shift);
return x.ShiftString (s);
}
}
}
| using System;
// TODO: upper case!
// FIXME: vad är skillnaden mellan Rotate? är det metoden...?
namespace Punku.Strings
{
/**
* Transform english text to a shifted form (a = a + shift)
*/
public class Shift
{
public char[] Table = new char[char.MaxValue];
public Shift (int shift)
{
for (int i = 0; i < char.MaxValue; i++)
Table [i] = (char)i;
for (int i = 'a'; i <= 'z'; i++) {
if (i + shift <= 'z')
Table [i] = (char)(i + shift);
else {
// XXX ugly hack. respect SHIFT and do this dynamically
if (i == 'y')
Table [i] = 'a';
if (i == 'z')
Table [i] = 'b';
}
}
}
public string ShiftString (string s)
{
char[] arr = s.ToCharArray ();
for (int i = 0; i < arr.Length; i++)
arr [i] = Table [arr [i]];
return new string (arr);
}
public static string ShiftString (string s, int shift)
{
var x = new Shift (shift);
return x.ShiftString (s);
}
}
}
| mit | C# |
39af8e204eb9b7589f3c92ad92ed729fb9fbc68e | Use InternalException | LouisMT/TeleBotDotNet,Naxiz/TeleBotDotNet | Json/JsonException.cs | Json/JsonException.cs | using System;
namespace TeleBotDotNet.Json
{
internal class JsonException : Exception
{
internal JsonException(string input, Exception innerException)
: base(GetExceptionMessage(input), innerException)
{
}
private static string GetExceptionMessage(string input)
{
return $"The received JSON is invalid:{Environment.NewLine}{Environment.NewLine}{input}";
}
}
}
| using System;
namespace TeleBotDotNet.Json
{
internal class JsonException : Exception
{
public Exception UnderlyingException { get; }
internal JsonException(string input, Exception underlyingException)
: base(GetExceptionMessage(input))
{
UnderlyingException = underlyingException;
}
private static string GetExceptionMessage(string input)
{
return $"The received JSON is invalid:{Environment.NewLine}{Environment.NewLine}{input}";
}
}
}
| mit | C# |
33700826cbb5dfe953ce879be212e1c0a041a5b4 | Fix area id. | UCASoft/DynamicControls,UCASoft/DynamicControls | DynamicControls.Site/Views/Home/Index.cshtml | DynamicControls.Site/Views/Home/Index.cshtml | @using System.Web.Compilation
@using DynamicControls
@model dynamic
@functions {
private DynamicDataSource DataSourceDelegate(string name, Dictionary<string, string> additionalParameters)
{
DynamicDataSource result = new DynamicDataSource();
if (name.Equals("select-field"))
{
result.Add("0", "Day");
result.Add("1", "Week");
result.Add("2", "Month");
result.Add("3", "Year");
result.Add(additionalParameters.First().Key, additionalParameters.First().Value);
}
else if (name.Equals("radio-list"))
{
result.Add("0", "New");
result.Add("1", "Old");
}
return result;
}
private Type GetTypeDelegate(string type)
{
return BuildManager.GetType(String.Format("DynamicControls.Site.Dynamic.{0}Control", type), true);
}
}
@{
ViewBag.Title = "Dynamic Controls";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section style
{
@Styles.Render("~/Content/kendo")
}
<h2>Dynamic Controls</h2>
@(Html.DynamicControls(File.ReadAllText(@"controls.json")).RegisterDataSourceDelegate(DataSourceDelegate, "dataSource").RegisterGetTypeDelegate(GetTypeDelegate))
<button onclick="getDynamicData();">Get data</button>
@section script
{
@Scripts.Render("~/bundles/dynamic")
@Scripts.Render("~/bundles/dynamic-bootstrap")
@Scripts.Render("~/bundles/kendo")
@Scripts.Render("~/bundles/dynamic-kendo")
<script type="text/javascript">
function getDynamicData() {
var data = getAreaData("data-form");
alert(JSON.stringify(data));
}
</script>
}
| @using System.Web.Compilation
@using DynamicControls
@model dynamic
@functions {
private DynamicDataSource DataSourceDelegate(string name, Dictionary<string, string> additionalParameters)
{
DynamicDataSource result = new DynamicDataSource();
if (name.Equals("select-field"))
{
result.Add("0", "Day");
result.Add("1", "Week");
result.Add("2", "Month");
result.Add("3", "Year");
result.Add(additionalParameters.First().Key, additionalParameters.First().Value);
}
else if (name.Equals("radio-list"))
{
result.Add("0", "New");
result.Add("1", "Old");
}
return result;
}
private Type GetTypeDelegate(string type)
{
return BuildManager.GetType(String.Format("DynamicControls.Site.Dynamic.{0}Control", type), true);
}
}
@{
ViewBag.Title = "Dynamic Controls";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@section style
{
@Styles.Render("~/Content/kendo")
}
<h2>Dynamic Controls</h2>
@(Html.DynamicControls(File.ReadAllText(@"controls.json")).RegisterDataSourceDelegate(DataSourceDelegate, "dataSource").RegisterGetTypeDelegate(GetTypeDelegate))
<button onclick="getDynamicData();">Get data</button>
@section script
{
@Scripts.Render("~/bundles/dynamic")
@Scripts.Render("~/bundles/dynamic-bootstrap")
@Scripts.Render("~/bundles/kendo")
@Scripts.Render("~/bundles/dynamic-kendo")
<script type="text/javascript">
function getDynamicData() {
var data = getAreaData("arm-demand");
alert(JSON.stringify(data));
}
</script>
}
| mit | C# |
e743c418d314d055249e9f1d8c051cc1ae5a2f14 | Add type restriction to `BuilderFor<T>()`. | alastairs/BobTheBuilder,fffej/BobTheBuilder | BobTheBuilder/Builder.cs | BobTheBuilder/Builder.cs | using System;
using System.Dynamic;
namespace BobTheBuilder
{
public class DynamicBuilder : DynamicObject
{
private readonly Type _destinationType;
internal DynamicBuilder(Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
_destinationType = destinationType;
}
public object Build()
{
return Activator.CreateInstance(_destinationType);
}
}
public class A
{
public static DynamicBuilder BuilderFor<T>() where T: class
{
return new DynamicBuilder(typeof(T));
}
}
} | using System;
using System.Dynamic;
namespace BobTheBuilder
{
public class DynamicBuilder : DynamicObject
{
private readonly Type _destinationType;
internal DynamicBuilder(Type destinationType)
{
if (destinationType == null)
{
throw new ArgumentNullException("destinationType");
}
_destinationType = destinationType;
}
public object Build()
{
return Activator.CreateInstance(_destinationType);
}
}
public class A
{
public static DynamicBuilder BuilderFor<T>()
{
return new DynamicBuilder(typeof(T));
}
}
} | apache-2.0 | C# |
74be8c8edf811d568c613880b73fdf065682dc80 | Remove SuppressOpen enum value to line up with CEF (#1942) | Livit/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,Livit/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp,jamespearce2006/CefSharp | CefSharp/WindowOpenDisposition.cs | CefSharp/WindowOpenDisposition.cs | // Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp
{
/// <summary>
/// The manner in which a link click should be opened.
/// </summary>
public enum WindowOpenDisposition
{
Unknown,
CurrentTab,
SingletonTab,
NewForegroundTab,
NewBackgroundTab,
NewPopup,
NewWindow,
SaveToDisk,
OffTheRecord,
IgnoreAction
}
}
| // Copyright © 2010-2016 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
namespace CefSharp
{
/// <summary>
/// The manner in which a link click should be opened.
/// </summary>
public enum WindowOpenDisposition
{
Unknown,
SuppressOpen,
CurrentTab,
SingletonTab,
NewForegroundTab,
NewBackgroundTab,
NewPopup,
NewWindow,
SaveToDisk,
OffTheRecord,
IgnoreAction
}
}
| bsd-3-clause | C# |
258a4dc282e776f6dda264240c0980981b9273a0 | Set svn:eol-style. | ft-/opensim-optimizations-wip-tests,allquixotic/opensim-autobackup,N3X15/VoxelSim,intari/OpenSimMirror,TomDataworks/opensim,allquixotic/opensim-autobackup,QuillLittlefeather/opensim-1,OpenSimian/opensimulator,QuillLittlefeather/opensim-1,RavenB/opensim,bravelittlescientist/opensim-performance,BogusCurry/arribasim-dev,N3X15/VoxelSim,AlphaStaxLLC/taiga,OpenSimian/opensimulator,rryk/omp-server,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,M-O-S-E-S/opensim,AlphaStaxLLC/taiga,AlexRa/opensim-mods-Alex,AlexRa/opensim-mods-Alex,cdbean/CySim,N3X15/VoxelSim,M-O-S-E-S/opensim,RavenB/opensim,zekizeki/agentservice,TomDataworks/opensim,bravelittlescientist/opensim-performance,AlphaStaxLLC/taiga,OpenSimian/opensimulator,justinccdev/opensim,RavenB/opensim,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip,Michelle-Argus/ArribasimExtract,zekizeki/agentservice,AlexRa/opensim-mods-Alex,justinccdev/opensim,rryk/omp-server,justinccdev/opensim,AlexRa/opensim-mods-Alex,allquixotic/opensim-autobackup,allquixotic/opensim-autobackup,bravelittlescientist/opensim-performance,N3X15/VoxelSim,ft-/arribasim-dev-extras,OpenSimian/opensimulator,AlphaStaxLLC/taiga,rryk/omp-server,M-O-S-E-S/opensim,rryk/omp-server,QuillLittlefeather/opensim-1,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,ft-/opensim-optimizations-wip-tests,allquixotic/opensim-autobackup,RavenB/opensim,AlphaStaxLLC/taiga,M-O-S-E-S/opensim,AlexRa/opensim-mods-Alex,bravelittlescientist/opensim-performance,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,intari/OpenSimMirror,OpenSimian/opensimulator,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,BogusCurry/arribasim-dev,ft-/arribasim-dev-extras,cdbean/CySim,TechplexEngineer/Aurora-Sim,N3X15/VoxelSim,Michelle-Argus/ArribasimExtract,AlphaStaxLLC/taiga,ft-/arribasim-dev-tests,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,Michelle-Argus/ArribasimExtract,ft-/opensim-optimizations-wip,N3X15/VoxelSim,zekizeki/agentservice,BogusCurry/arribasim-dev,ft-/arribasim-dev-tests,justinccdev/opensim,TechplexEngineer/Aurora-Sim,TomDataworks/opensim,ft-/arribasim-dev-tests,QuillLittlefeather/opensim-1,QuillLittlefeather/opensim-1,ft-/arribasim-dev-tests,allquixotic/opensim-autobackup,cdbean/CySim,ft-/opensim-optimizations-wip-tests,QuillLittlefeather/opensim-1,intari/OpenSimMirror,zekizeki/agentservice,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-tests,AlphaStaxLLC/taiga,BogusCurry/arribasim-dev,OpenSimian/opensimulator,intari/OpenSimMirror,ft-/opensim-optimizations-wip,TomDataworks/opensim,ft-/opensim-optimizations-wip-extras,N3X15/VoxelSim,Michelle-Argus/ArribasimExtract,ft-/arribasim-dev-extras,ft-/arribasim-dev-extras,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,AlphaStaxLLC/taiga,justinccdev/opensim,BogusCurry/arribasim-dev,intari/OpenSimMirror,RavenB/opensim,rryk/omp-server,ft-/opensim-optimizations-wip-extras,ft-/opensim-optimizations-wip,bravelittlescientist/opensim-performance,TomDataworks/opensim,BogusCurry/arribasim-dev,M-O-S-E-S/opensim,TomDataworks/opensim,M-O-S-E-S/opensim,ft-/opensim-optimizations-wip-extras,AlexRa/opensim-mods-Alex,justinccdev/opensim,ft-/opensim-optimizations-wip-tests,Michelle-Argus/ArribasimExtract,rryk/omp-server,cdbean/CySim,QuillLittlefeather/opensim-1,N3X15/VoxelSim,zekizeki/agentservice,cdbean/CySim,ft-/arribasim-dev-extras,intari/OpenSimMirror,TechplexEngineer/Aurora-Sim,ft-/opensim-optimizations-wip-extras,ft-/arribasim-dev-tests,bravelittlescientist/opensim-performance,zekizeki/agentservice,OpenSimian/opensimulator,TechplexEngineer/Aurora-Sim,ft-/arribasim-dev-extras,M-O-S-E-S/opensim,RavenB/opensim,cdbean/CySim,ft-/opensim-optimizations-wip-tests | OpenSim/Framework/Data/OpenSimTableMapper.cs | OpenSim/Framework/Data/OpenSimTableMapper.cs | using System.Data;
using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data
{
public abstract class OpenSimTableMapper<TRowMapper, TPrimaryKey> : BaseTableMapper<TRowMapper, TPrimaryKey>
{
public OpenSimTableMapper(BaseDatabaseConnector database, string tableName) : base(database, tableName)
{
}
protected override DataReader CreateReader(IDataReader reader)
{
return new OpenSimDataReader(reader);
}
}
}
| using System.Data;
using TribalMedia.Framework.Data;
namespace OpenSim.Framework.Data
{
public abstract class OpenSimTableMapper<TRowMapper, TPrimaryKey> : BaseTableMapper<TRowMapper, TPrimaryKey>
{
public OpenSimTableMapper(BaseDatabaseConnector database, string tableName) : base(database, tableName)
{
}
protected override DataReader CreateReader(IDataReader reader)
{
return new OpenSimDataReader(reader);
}
}
}
| bsd-3-clause | C# |
f29ecfea06e4761f1d7f21184326d6a90a21d936 | change build script to exclude client projects | roflkins/IdentityModel.OidcClient2,roflkins/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient,IdentityModel/IdentityModel.OidcClient2,IdentityModel/IdentityModel.OidcClient,IdentityModel/IdentityModel.OidcClient2 | build.cake | build.cake | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var packPath = Directory("./src/IdentityModel.OidcClient");
var sourcePath = Directory("./src");
var clientsPath = Directory("./clients");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
// build sources
var projects = GetFiles("./src/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
// build tests
projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Pack")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = buildArtifacts,
};
// add build suffix for CI builds
if(!isLocalBuild)
{
settings.VersionSuffix = AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
DotNetCorePack(packPath, settings);
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore(sourcePath, settings);
DotNetCoreRestore(testsPath, settings);
DotNetCoreRestore(clientsPath, settings);
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("RunTests")
.IsDependentOn("Pack");
RunTarget(target); | var target = Argument("target", "Default");
var configuration = Argument<string>("configuration", "Release");
///////////////////////////////////////////////////////////////////////////////
// GLOBAL VARIABLES
///////////////////////////////////////////////////////////////////////////////
var isLocalBuild = !AppVeyor.IsRunningOnAppVeyor;
var packPath = Directory("./src/IdentityModel.OidcClient");
var sourcePath = Directory("./src");
var clientsPath = Directory("./clients");
var testsPath = Directory("test");
var buildArtifacts = Directory("./artifacts/packages");
Task("Build")
.IsDependentOn("Clean")
.IsDependentOn("Restore")
.Does(() =>
{
var projects = GetFiles("./**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreBuildSettings
{
Configuration = configuration
};
DotNetCoreBuild(project.GetDirectory().FullPath, settings);
}
});
Task("RunTests")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var projects = GetFiles("./test/**/project.json");
foreach(var project in projects)
{
var settings = new DotNetCoreTestSettings
{
Configuration = configuration
};
DotNetCoreTest(project.GetDirectory().FullPath, settings);
}
});
Task("Pack")
.IsDependentOn("Restore")
.IsDependentOn("Clean")
.Does(() =>
{
var settings = new DotNetCorePackSettings
{
Configuration = configuration,
OutputDirectory = buildArtifacts,
};
// add build suffix for CI builds
if(!isLocalBuild)
{
settings.VersionSuffix = AppVeyor.Environment.Build.Number.ToString().PadLeft(4,'0');
}
DotNetCorePack(packPath, settings);
});
Task("Clean")
.Does(() =>
{
CleanDirectories(new DirectoryPath[] { buildArtifacts });
});
Task("Restore")
.Does(() =>
{
var settings = new DotNetCoreRestoreSettings
{
Sources = new [] { "https://api.nuget.org/v3/index.json" }
};
DotNetCoreRestore(sourcePath, settings);
DotNetCoreRestore(testsPath, settings);
DotNetCoreRestore(clientsPath, settings);
});
Task("Default")
.IsDependentOn("Build")
.IsDependentOn("RunTests")
.IsDependentOn("Pack");
RunTarget(target); | apache-2.0 | C# |
2958d59522a0256404ea48344b0317e36fa85373 | add support for guid.native to MySQL5Dialect | alobakov/nhibernate-core,alobakov/nhibernate-core,hazzik/nhibernate-core,lnu/nhibernate-core,lnu/nhibernate-core,ManufacturingIntelligence/nhibernate-core,fredericDelaporte/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,nhibernate/nhibernate-core,nhibernate/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core,RogerKratz/nhibernate-core,nkreipke/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,RogerKratz/nhibernate-core,livioc/nhibernate-core,ngbrown/nhibernate-core,hazzik/nhibernate-core,livioc/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,ManufacturingIntelligence/nhibernate-core,ManufacturingIntelligence/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,fredericDelaporte/nhibernate-core,hazzik/nhibernate-core,nkreipke/nhibernate-core,alobakov/nhibernate-core,nhibernate/nhibernate-core,gliljas/nhibernate-core,lnu/nhibernate-core,fredericDelaporte/nhibernate-core,ngbrown/nhibernate-core,gliljas/nhibernate-core | src/NHibernate/Dialect/MySQL5Dialect.cs | src/NHibernate/Dialect/MySQL5Dialect.cs | using NHibernate.SqlCommand;
namespace NHibernate.Dialect
{
public class MySQL5Dialect : MySQLDialect
{
//Reference 5.x
//Numeric:
//http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
//Date and time:
//http://dev.mysql.com/doc/refman/5.0/en/date-and-time-type-overview.html
//String:
//http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html
//default:
//http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
public override bool SupportsVariableLimit
{
get
{
//note: why false?
return false;
}
}
public override bool SupportsSubSelects
{
get
{
//subquery in mysql? yes! From 4.1!
//http://dev.mysql.com/doc/refman/5.1/en/subqueries.html
return true;
}
}
public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit)
{
var pagingBuilder = new SqlStringBuilder();
pagingBuilder.Add(querySqlString);
pagingBuilder.Add(" limit ");
if (offset > 0)
{
pagingBuilder.Add(offset.ToString());
pagingBuilder.Add(", ");
}
pagingBuilder.Add(limit.ToString());
return pagingBuilder.ToSqlString();
}
public override string SelectGUIDString
{
get
{
return "select uuid()";
}
}
}
} | using NHibernate.SqlCommand;
namespace NHibernate.Dialect
{
public class MySQL5Dialect : MySQLDialect
{
//Reference 5.x
//Numeric:
//http://dev.mysql.com/doc/refman/5.0/en/numeric-type-overview.html
//Date and time:
//http://dev.mysql.com/doc/refman/5.0/en/date-and-time-type-overview.html
//String:
//http://dev.mysql.com/doc/refman/5.0/en/string-type-overview.html
//default:
//http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html
public override bool SupportsVariableLimit
{
get
{
//note: why false?
return false;
}
}
public override bool SupportsSubSelects
{
get
{
//subquery in mysql? yes! From 4.1!
//http://dev.mysql.com/doc/refman/5.1/en/subqueries.html
return true;
}
}
public override SqlString GetLimitString(SqlString querySqlString, int offset, int limit)
{
var pagingBuilder = new SqlStringBuilder();
pagingBuilder.Add(querySqlString);
pagingBuilder.Add(" limit ");
if (offset > 0)
{
pagingBuilder.Add(offset.ToString());
pagingBuilder.Add(", ");
}
pagingBuilder.Add(limit.ToString());
return pagingBuilder.ToSqlString();
}
}
} | lgpl-2.1 | C# |
8448d3b4420540133c8c51d800aaf435d0794645 | add Session cookies to RootPath | ZocDoc/ServiceStack,NServiceKit/NServiceKit,timba/NServiceKit,nataren/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,NServiceKit/NServiceKit,ZocDoc/ServiceStack,timba/NServiceKit,MindTouch/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,nataren/NServiceKit,nataren/NServiceKit,ZocDoc/ServiceStack,meebey/ServiceStack,ZocDoc/ServiceStack,meebey/ServiceStack,timba/NServiceKit,NServiceKit/NServiceKit,MindTouch/NServiceKit,timba/NServiceKit | src/ServiceStack/ServiceHost/Cookies.cs | src/ServiceStack/ServiceHost/Cookies.cs | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using System.Web;
using ServiceStack.Common.Web;
namespace ServiceStack.ServiceHost
{
public class Cookies : ICookies
{
readonly IHttpResponse httpRes;
public Dictionary<string, List<Cookie>> PathCookies;
private static readonly DateTime Session = DateTime.MinValue;
private static readonly DateTime Permanaent = DateTime.UtcNow.AddYears(20);
private const string RootPath = "/";
public Cookies(IHttpResponse httpRes)
{
this.httpRes = httpRes;
}
/// <summary>
/// Sets a persistent cookie which never expires
/// </summary>
public void AddPermanentCookie(string cookieName, string cookieValue)
{
AddCookie(new Cookie(cookieName, cookieValue, RootPath) {
Expires = Permanaent,
});
}
/// <summary>
/// Sets a session cookie which expires after the browser session closes
/// </summary>
public void AddSessionCookie(string cookieName, string cookieValue)
{
AddCookie(new Cookie(cookieName, cookieValue, RootPath));
}
/// <summary>
/// Deletes a specified cookie by setting its value to empty and expiration to -1 days
/// </summary>
public void DeleteCookie(string cookieName)
{
var cookie = String.Format("{0}=;expires={1};path=/",
cookieName, DateTime.UtcNow.AddDays(-1).ToString("R"));
httpRes.AddHeader(HttpHeaders.SetCookie, cookie);
}
public HttpCookie ToHttpCookie(Cookie cookie)
{
return new HttpCookie(cookie.Name, cookie.Value) {
Path = cookie.Path,
Expires = cookie.Expires,
Domain = cookie.Domain,
};
}
public string GetHeaderValue(Cookie cookie)
{
return cookie.Expires == Session
? String.Format("{0}={1};path=/", cookie.Name, cookie.Value)
: String.Format("{0}={1};expires={2};path={3}",
cookie.Name, cookie.Value, cookie.Expires.ToString("R"), cookie.Path ?? "/");
}
/// <summary>
/// Sets a persistent cookie which expires after the given time
/// </summary>
public void AddCookie(Cookie cookie)
{
var aspNet = this.httpRes.OriginalResponse as HttpResponse;
if (aspNet != null)
{
var httpCookie = ToHttpCookie(cookie);
aspNet.SetCookie(httpCookie);
return;
}
var httpListener = this.httpRes.OriginalResponse as HttpListenerResponse;
if (httpListener != null)
{
var cookieStr = GetHeaderValue(cookie);
httpListener.Headers.Add(HttpHeaders.SetCookie, cookieStr);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Globalization;
using System.Net;
using System.Text;
using System.Web;
using ServiceStack.Common.Web;
namespace ServiceStack.ServiceHost
{
public class Cookies : ICookies
{
readonly IHttpResponse httpRes;
public Dictionary<string, List<Cookie>> PathCookies;
private static readonly DateTime Session = DateTime.MinValue;
private static readonly DateTime Permanaent = DateTime.UtcNow.AddYears(20);
private const string RootPath = "/";
public Cookies(IHttpResponse httpRes)
{
this.httpRes = httpRes;
}
/// <summary>
/// Sets a persistent cookie which never expires
/// </summary>
public void AddPermanentCookie(string cookieName, string cookieValue)
{
AddCookie(new Cookie(cookieName, cookieValue, RootPath) {
Expires = Permanaent,
});
}
/// <summary>
/// Sets a session cookie which expires after the browser session closes
/// </summary>
public void AddSessionCookie(string cookieName, string cookieValue)
{
AddCookie(new Cookie(cookieName, cookieValue));
}
/// <summary>
/// Deletes a specified cookie by setting its value to empty and expiration to -1 days
/// </summary>
public void DeleteCookie(string cookieName)
{
var cookie = String.Format("{0}=;expires={1};path=/",
cookieName, DateTime.UtcNow.AddDays(-1).ToString("R"));
httpRes.AddHeader(HttpHeaders.SetCookie, cookie);
}
public HttpCookie ToHttpCookie(Cookie cookie)
{
return new HttpCookie(cookie.Name, cookie.Value) {
Path = cookie.Path,
Expires = cookie.Expires,
Domain = cookie.Domain,
};
}
public string GetHeaderValue(Cookie cookie)
{
return cookie.Expires == Session
? String.Format("{0}={1};path=/", cookie.Name, cookie.Value)
: String.Format("{0}={1};expires={2};path={3}",
cookie.Name, cookie.Value, cookie.Expires.ToString("R"), cookie.Path ?? "/");
}
/// <summary>
/// Sets a persistent cookie which expires after the given time
/// </summary>
public void AddCookie(Cookie cookie)
{
var aspNet = this.httpRes.OriginalResponse as HttpResponse;
if (aspNet != null)
{
var httpCookie = ToHttpCookie(cookie);
aspNet.SetCookie(httpCookie);
return;
}
var httpListener = this.httpRes.OriginalResponse as HttpListenerResponse;
if (httpListener != null)
{
var cookieStr = GetHeaderValue(cookie);
httpListener.Headers.Add(HttpHeaders.SetCookie, cookieStr);
}
}
}
} | bsd-3-clause | C# |
74ab5cd8d1f77eefa64540a71719bf892e6c7cda | Add a diagnostic tool for myself. | MrJoy/UnityGit | ShellHelpers.cs | ShellHelpers.cs | #define DEBUG_COMMANDS
//using UnityEditor;
//using UnityEngine;
//using System.Collections;
using System.Diagnostics;
public class ShellHelpers {
public static Process StartProcess(string filename, string arguments) {
#if DEBUG_COMMANDS
UnityEngine.Debug.Log("Running: " + filename + " " + arguments);
#endif
Process p = new Process();
p.StartInfo.Arguments = arguments;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = filename;
p.Start();
return p;
}
public static string OutputFromCommand(string filename, string arguments) {
var p = StartProcess(filename, arguments);
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if(output.EndsWith("\n"))
output = output.Substring(0, output.Length - 1);
return output;
}
}
| //using UnityEditor;
//using UnityEngine;
//using System.Collections;
using System.Diagnostics;
public class ShellHelpers {
public static Process StartProcess(string filename, string arguments) {
Process p = new Process();
p.StartInfo.Arguments = arguments;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = filename;
p.Start();
return p;
}
public static string OutputFromCommand(string filename, string arguments) {
var p = StartProcess(filename, arguments);
var output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
if(output.EndsWith("\n"))
output = output.Substring(0, output.Length - 1);
return output;
}
}
| mit | C# |
96316203d632034203b63f9cf6ed421a29d3fbc3 | Add `OptionExtensions.BindNone` | Weingartner/SolidworksAddinFramework | SolidworksAddinFramework/OptionExtensions.cs | SolidworksAddinFramework/OptionExtensions.cs | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using LanguageExt;
using Weingartner.Exceptional;
using static LanguageExt.Prelude;
namespace SolidworksAddinFramework
{
public static class OptionExtensions
{
/// <summary>
/// Get the value from an option. If it is none
/// then a null reference exception will be raised.
/// Don't use this in production please.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="option"></param>
/// <returns></returns>
public static T __Value__<T>(this Option<T> option)
{
return option.Match
(v => v ,
() =>
{
throw new NullReferenceException();
});
}
public static Option<ImmutableList<T>> Sequence<T>(this IEnumerable<Option<T>> p)
{
return p.Fold(
Prelude.Optional(ImmutableList<T>.Empty),
(state, itemOpt) =>
from item in itemOpt
from list in state
select list.Add(item));
}
/// <summary>
/// Invokes the action if it is there.
/// </summary>
/// <param name="a"></param>
public static void Invoke(this Option<Action> a)
{
a.IfSome(fn => fn());
}
/// <summary>
/// Fluent version Optional
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static Option<T> ToOption<T>(this T obj)
{
return Optional(obj);
}
public static Option<T> ToOption<T>(this IExceptional<T> obj)
{
return obj.Match(Some, _ => None);
}
public static Option<T> BindNone<T>(this Option<T> o, Func<Option<T>> fn)
{
return o.Match(Some, fn);
}
}
} | using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using LanguageExt;
using Weingartner.Exceptional;
using static LanguageExt.Prelude;
namespace SolidworksAddinFramework
{
public static class OptionExtensions
{
/// <summary>
/// Get the value from an option. If it is none
/// then a null reference exception will be raised.
/// Don't use this in production please.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="option"></param>
/// <returns></returns>
public static T __Value__<T>(this Option<T> option)
{
return option.Match
(v => v ,
() =>
{
throw new NullReferenceException();
});
}
public static Option<ImmutableList<T>> Sequence<T>(this IEnumerable<Option<T>> p)
{
return p.Fold(
Prelude.Optional(ImmutableList<T>.Empty),
(state, itemOpt) =>
from item in itemOpt
from list in state
select list.Add(item));
}
/// <summary>
/// Invokes the action if it is there.
/// </summary>
/// <param name="a"></param>
public static void Invoke(this Option<Action> a)
{
a.IfSome(fn => fn());
}
/// <summary>
/// Fluent version Optional
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static Option<T> ToOption<T>(this T obj)
{
return Optional(obj);
}
public static Option<T> ToOption<T>(this IExceptional<T> obj)
{
return obj.Match(Some, _ => None);
}
}
} | mit | C# |
3bd46dc23552669228154e22c6a3f4a1eebb0200 | Update default.aspx.cs | subodhtirkey/Gmail-Feed | Gmailfeed2/default.aspx.cs | Gmailfeed2/default.aspx.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Data;
namespace Gmailfeed2
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
/*Gmail Username and Password Section*/
string username = "/*______Replace With Your Gmail Username__________*/";
string password = "/*______Replace with your Gmail Password__________*/";
string url = (@"https://gmail.google.com/gmail/feed/atom");
var request = (HttpWebRequest)WebRequest.Create(url);
var encoded = TextToBase64(username + ":" + password);
var myWebRequest = HttpWebRequest.Create(url);
myWebRequest.Method = "POST";
myWebRequest.ContentLength = 0;
myWebRequest.Headers.Add("Authorization", "Basic " + encoded);
var response = myWebRequest.GetResponse();
var stream = response.GetResponseStream();
DataSet dt = new DataSet();
dt.ReadXml(stream);
DataTable DT = dt.Tables[3];
// DT.Merge(dt.Tables[1]);
DT.Merge(dt.Tables[2]);
feedGrid.DataSource = DT;
DataBind();
}
public static string TextToBase64(string sAscii)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] bytes = encoding.GetBytes(sAscii);
return System.Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.IO;
using System.Xml;
using System.Data;
namespace Gmailfeed2
{
public partial class _default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string username = "/*______Replace With Your Gmail Username__________*/";
string password = "/*______Replace with your Gmail Password__________*/";
string url = (@"https://gmail.google.com/gmail/feed/atom");
var request = (HttpWebRequest)WebRequest.Create(url);
var encoded = TextToBase64(username + ":" + password);
var myWebRequest = HttpWebRequest.Create(url);
myWebRequest.Method = "POST";
myWebRequest.ContentLength = 0;
myWebRequest.Headers.Add("Authorization", "Basic " + encoded);
var response = myWebRequest.GetResponse();
var stream = response.GetResponseStream();
DataSet dt = new DataSet();
dt.ReadXml(stream);
DataTable DT = dt.Tables[3];
// DT.Merge(dt.Tables[1]);
DT.Merge(dt.Tables[2]);
feedGrid.DataSource = DT;
DataBind();
}
public static string TextToBase64(string sAscii)
{
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] bytes = encoding.GetBytes(sAscii);
return System.Convert.ToBase64String(bytes, 0, bytes.Length);
}
}
}
| apache-2.0 | C# |
210c360fca85268c4697c4c4669af904f0e298af | Throw an exception when creating a Color with an invalid float value | AntiTcb/Discord.Net,LassieME/Discord.Net,Confruggy/Discord.Net,RogueException/Discord.Net | src/Discord.Net.Core/Entities/Roles/Color.cs | src/Discord.Net.Core/Entities/Roles/Color.cs | using System;
using System.Diagnostics;
namespace Discord
{
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct Color
{
/// <summary> Gets the default user color value. </summary>
public static readonly Color Default = new Color(0);
/// <summary> Gets the encoded value for this color. </summary>
public uint RawValue { get; }
/// <summary> Gets the red component for this color. </summary>
public byte R => (byte)(RawValue >> 16);
/// <summary> Gets the green component for this color. </summary>
public byte G => (byte)(RawValue >> 8);
/// <summary> Gets the blue component for this color. </summary>
public byte B => (byte)(RawValue);
public Color(uint rawValue)
{
RawValue = rawValue;
}
public Color(byte r, byte g, byte b)
{
RawValue =
((uint)r << 16) |
((uint)g << 8) |
b;
}
public Color(float r, float g, float b)
{
if (r <= 0.0f && r >= 1.0f)
throw new ArgumentOutOfRangeException(nameof(r), "A float value must be within [0,1]");
if (g <= 0.0f || g >= 1.0f)
throw new ArgumentOutOfRangeException(nameof(g), "A float value must be within [0,1]");
if (b <= 0.0f || b >= 1.0f)
throw new ArgumentOutOfRangeException(nameof(b), "A float value must be within [0,1]");
RawValue =
((uint)(r * 255.0f) << 16) |
((uint)(g * 255.0f) << 8) |
(uint)(b * 255.0f);
}
public override string ToString() =>
$"#{Convert.ToString(RawValue, 16)}";
private string DebuggerDisplay =>
$"#{Convert.ToString(RawValue, 16)} ({RawValue})";
}
}
| using System;
using System.Diagnostics;
namespace Discord
{
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public struct Color
{
/// <summary> Gets the default user color value. </summary>
public static readonly Color Default = new Color(0);
/// <summary> Gets the encoded value for this color. </summary>
public uint RawValue { get; }
/// <summary> Gets the red component for this color. </summary>
public byte R => (byte)(RawValue >> 16);
/// <summary> Gets the green component for this color. </summary>
public byte G => (byte)(RawValue >> 8);
/// <summary> Gets the blue component for this color. </summary>
public byte B => (byte)(RawValue);
public Color(uint rawValue)
{
RawValue = rawValue;
}
public Color(byte r, byte g, byte b)
{
RawValue =
((uint)r << 16) |
((uint)g << 8) |
b;
}
public Color(float r, float g, float b)
{
RawValue =
((uint)(r * 255.0f) << 16) |
((uint)(g * 255.0f) << 8) |
(uint)(b * 255.0f);
}
public override string ToString() =>
$"#{Convert.ToString(RawValue, 16)}";
private string DebuggerDisplay =>
$"#{Convert.ToString(RawValue, 16)} ({RawValue})";
}
}
| mit | C# |
0e90812a617ea0a90a893727d0ef5051958c88af | Update JsonDeserializer.cs | tiksn/TIKSN-Framework | TIKSN.Core/Serialization/JsonDeserializer.cs | TIKSN.Core/Serialization/JsonDeserializer.cs | using Newtonsoft.Json;
namespace TIKSN.Serialization
{
public class JsonDeserializer : DeserializerBase<string>
{
protected override T DeserializeInternal<T>(string serial) => JsonConvert.DeserializeObject<T>(serial);
}
}
| using Newtonsoft.Json;
namespace TIKSN.Serialization
{
public class JsonDeserializer : DeserializerBase<string>
{
protected override T DeserializeInternal<T>(string serial)
{
return JsonConvert.DeserializeObject<T>(serial);
}
}
} | mit | C# |
51000bfc2227c143d9e52d1a41edb79cbdff0b52 | Add constructor with FileInfo param | clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch,clarkcb/xsearch | csharp/CsSearch/CsSearch/SearchFile.cs | csharp/CsSearch/CsSearch/SearchFile.cs | using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CsSearch
{
public class SearchFile
{
public static string ContainerSeparator = "!";
public IList<string> Containers { get; private set; }
public string FilePath { get; private set; }
public string FileName { get; private set; }
public FileType Type { get; private set; }
public string FullName => ToString();
public string PathAndName => FileUtil.JoinPath(FilePath, FileName);
public SearchFile(FileInfo fileInfo, FileType type) :
this(new List<string>(), fileInfo.DirectoryName, fileInfo.Name, type) {}
public SearchFile(string path, string fileName, FileType type) :
this(new List<string>(), path, fileName, type) {}
public SearchFile(IList<string> containers, string path,
string fileName, FileType type)
{
Containers = containers;
FilePath = path;
FileName = fileName;
Type = type;
}
public void AddContainer(string container)
{
Containers.Add(container);
}
public FileInfo ToFileInfo()
{
return new FileInfo(PathAndName);
}
public override string ToString()
{
var sb = new StringBuilder();
if (Containers.Count > 0)
{
for (var i = 0; i < Containers.Count; i++)
{
if (i > 0) sb.Append(ContainerSeparator);
sb.Append(Containers[i]);
}
sb.Append(ContainerSeparator);
}
sb.Append(PathAndName);
return sb.ToString();
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Text;
namespace CsSearch
{
public class SearchFile
{
public static string ContainerSeparator = "!";
public IList<string> Containers { get; private set; }
public string FilePath { get; private set; }
public string FileName { get; private set; }
public FileType Type { get; private set; }
public string FullName => ToString();
public string PathAndName => FileUtil.JoinPath(FilePath, FileName);
public SearchFile(string path, string fileName, FileType type) : this(new List<string>(), path, fileName, type) {}
public SearchFile(IList<string> containers, string path,
string fileName, FileType type)
{
Containers = containers;
FilePath = path;
FileName = fileName;
Type = type;
}
public void AddContainer(string container)
{
Containers.Add(container);
}
public FileInfo ToFileInfo()
{
return new FileInfo(PathAndName);
}
public override string ToString()
{
var sb = new StringBuilder();
if (Containers.Count > 0)
{
for (var i = 0; i < Containers.Count; i++)
{
if (i > 0) sb.Append(ContainerSeparator);
sb.Append(Containers[i]);
}
sb.Append(ContainerSeparator);
}
sb.Append(PathAndName);
return sb.ToString();
}
}
}
| mit | C# |
466487589acff3118a9f9475428c625bc31a4075 | Make the "type" attribute available from GenerateScript | mrahhal/MR.AspNet.Deps,mrahhal/MR.AspNet.Deps | src/MR.AspNet.Deps/OutputHelper.cs | src/MR.AspNet.Deps/OutputHelper.cs | using System.Collections.Generic;
namespace MR.AspNet.Deps
{
public class OutputHelper
{
private List<Element> _elements = new List<Element>();
public void Add(Element element)
{
_elements.Add(element);
}
public void Add(List<Element> elements)
{
_elements.AddRange(elements);
}
public List<Element> Elements { get { return _elements; } }
}
public static class OutputHelperExtensions
{
/// <summary>
/// Generates a <link > tag.
/// </summary>
public static void GenerateLink(this OutputHelper @this, string href)
{
var e = new Element("link", ClosingTagKind.None);
e.Attributes.Add(new ElementAttribute("rel", "stylesheet"));
e.Attributes.Add(new ElementAttribute("href", href));
@this.Add(e);
}
/// <summary>
/// Generates a <script></script> tag.
/// </summary>
public static void GenerateScript(this OutputHelper @this, string src, string type = null)
{
var e = new Element("script", ClosingTagKind.Normal);
e.Attributes.Add(new ElementAttribute("src", src));
if (type != null)
{
e.Attributes.Add(new ElementAttribute("type", type));
}
@this.Add(e);
}
}
}
| using System.Collections.Generic;
namespace MR.AspNet.Deps
{
public class OutputHelper
{
private List<Element> _elements = new List<Element>();
public void Add(Element element)
{
_elements.Add(element);
}
public void Add(List<Element> elements)
{
_elements.AddRange(elements);
}
public List<Element> Elements { get { return _elements; } }
}
public static class OutputHelperExtensions
{
public static void GenerateLink(this OutputHelper @this, string href)
{
var e = new Element("link", ClosingTagKind.None);
e.Attributes.Add(new ElementAttribute("rel", "stylesheet"));
e.Attributes.Add(new ElementAttribute("href", href));
@this.Add(e);
}
public static void GenerateScript(this OutputHelper @this, string src)
{
var e = new Element("script", ClosingTagKind.Normal);
e.Attributes.Add(new ElementAttribute("src", src));
@this.Add(e);
}
}
}
| mit | C# |
386715c0c247f03db33870dab3474148a5e5b851 | Rename parameter | picklesdoc/pickles,magicmonty/pickles,dirkrombauts/pickles,picklesdoc/pickles,picklesdoc/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,blorgbeard/pickles,irfanah/pickles,ludwigjossieaux/pickles,irfanah/pickles,magicmonty/pickles,blorgbeard/pickles,magicmonty/pickles,blorgbeard/pickles,magicmonty/pickles,dirkrombauts/pickles,irfanah/pickles,dirkrombauts/pickles,picklesdoc/pickles,blorgbeard/pickles,irfanah/pickles,dirkrombauts/pickles | src/Pickles/Pickles.Test/AssertExtensions.cs | src/Pickles/Pickles.Test/AssertExtensions.cs | using System;
using System.Linq;
using System.Xml.Linq;
using NFluent;
using NFluent.Extensibility;
using NUnit.Framework;
using PicklesDoc.Pickles.Test.Extensions;
namespace PicklesDoc.Pickles.Test
{
public static class AssertExtensions
{
public static void HasAttribute(this ICheck<XElement> check, string name, string value)
{
var actual = ExtensibilityHelper.ExtractChecker(check).Value;
ShouldHaveAttribute(actual, name, value);
}
private static void ShouldHaveAttribute(this XElement element, string name, string value)
{
XAttribute xAttribute = element.Attributes().FirstOrDefault(attribute => attribute.Name.LocalName == name);
Check.That(xAttribute).IsNotNull();
// ReSharper disable once PossibleNullReferenceException
Check.That(xAttribute.Value).IsEqualTo(value);
}
public static void HasElement(this ICheck<XElement> check, string name)
{
var actual = ExtensibilityHelper.ExtractChecker(check).Value;
ShouldHaveElement(actual, name);
}
private static void ShouldHaveElement(this XElement element, string name)
{
Check.That(element.HasElement(name)).IsTrue();
}
public static void IsInNamespace(this ICheck<XElement> check, string nameOfNamespace)
{
var actual = ExtensibilityHelper.ExtractChecker(check).Value;
ShouldBeInNamespace(actual, nameOfNamespace);
}
private static void ShouldBeInNamespace(this XElement element, string nameOfNamespace)
{
Check.That(element.Name.NamespaceName).IsEqualTo(nameOfNamespace);
}
public static void ShouldBeNamed(this XElement element, string name)
{
Check.That(element.Name.LocalName).IsEqualTo(name);
}
public static void ShouldDeepEquals(this XElement element, XElement other)
{
Assert.IsTrue(
XNode.DeepEquals(element, other),
"Expected:\r\n{0}\r\nActual:\r\n{1}\r\n",
element,
other);
}
}
} | using System;
using System.Linq;
using System.Xml.Linq;
using NFluent;
using NFluent.Extensibility;
using NUnit.Framework;
using PicklesDoc.Pickles.Test.Extensions;
namespace PicklesDoc.Pickles.Test
{
public static class AssertExtensions
{
public static void HasAttribute(this ICheck<XElement> check, string name, string value)
{
var actual = ExtensibilityHelper.ExtractChecker(check).Value;
ShouldHaveAttribute(actual, name, value);
}
private static void ShouldHaveAttribute(this XElement element, string name, string value)
{
XAttribute xAttribute = element.Attributes().FirstOrDefault(attribute => attribute.Name.LocalName == name);
Check.That(xAttribute).IsNotNull();
// ReSharper disable once PossibleNullReferenceException
Check.That(xAttribute.Value).IsEqualTo(value);
}
public static void HasElement(this ICheck<XElement> check, string name)
{
var actual = ExtensibilityHelper.ExtractChecker(check).Value;
ShouldHaveElement(actual, name);
}
private static void ShouldHaveElement(this XElement element, string name)
{
Check.That(element.HasElement(name)).IsTrue();
}
public static void IsInNamespace(this ICheck<XElement> element, string nameOfNamespace)
{
var actual = ExtensibilityHelper.ExtractChecker(element).Value;
ShouldBeInNamespace(actual, nameOfNamespace);
}
private static void ShouldBeInNamespace(this XElement element, string nameOfNamespace)
{
Check.That(element.Name.NamespaceName).IsEqualTo(nameOfNamespace);
}
public static void ShouldBeNamed(this XElement element, string name)
{
Check.That(element.Name.LocalName).IsEqualTo(name);
}
public static void ShouldDeepEquals(this XElement element, XElement other)
{
Assert.IsTrue(
XNode.DeepEquals(element, other),
"Expected:\r\n{0}\r\nActual:\r\n{1}\r\n",
element,
other);
}
}
} | apache-2.0 | C# |
e8efb58d80ca87b1c14cc08ba9d3fcafe048d4dc | use config setup form service base | aruss/ServiceBase,aruss/ServiceBase | src/ServiceBase/Config/ConfigurationSetup.cs | src/ServiceBase/Config/ConfigurationSetup.cs | using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace ServiceBase.Config
{
public static class ConfigurationSetup
{
public static IConfigurationRoot Configure(IHostingEnvironment environment)
{
var builder = new ConfigurationBuilder()
.SetBasePath(environment.ContentRootPath)
.AddJsonFile(Path.Combine("Config", "config.json"), optional: false, reloadOnChange: true)
.AddJsonFile(Path.Combine("Config", $"config.{environment.EnvironmentName}.json"), optional: true, reloadOnChange: true);
if (environment.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
return builder.Build();
}
}
}
| using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
namespace ServiceBase.Config
{
public static class ConfigurationSetup
{
public static IConfigurationRoot Configure(IHostingEnvironment hostEnv)
{
var builder = new ConfigurationBuilder()
.SetBasePath(hostEnv.ContentRootPath)
.AddJsonFile(Path.Combine("Config", "config.json"), optional: false, reloadOnChange: true)
.AddJsonFile(Path.Combine("Config", $"config.{hostEnv.EnvironmentName}.json"), optional: true, reloadOnChange: true);
if (hostEnv.IsDevelopment())
{
// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709
builder.AddUserSecrets();
}
builder.AddEnvironmentVariables();
return builder.Build();
}
}
}
| apache-2.0 | C# |
36d24f4663343543650f4e6220ec3949be0da0c4 | move ChatChannel enum to TCC.Utils | Foglio1024/Tera-custom-cooldowns,Foglio1024/Tera-custom-cooldowns | TCC.Utils/Enums.cs | TCC.Utils/Enums.cs | namespace TCC.Utils
{
public enum NotificationType
{
Normal = 0,
Success,
Warning,
Error
}
public enum NotificationTemplate
{
Default,
Progress,
Confirm
}
}
namespace TCC.Data
{
public enum ChatChannel
{
Say = 0,
Party = 1,
Guild = 2,
Area = 3,
Trade = 4,
Greet = 9,
Angler = 10,
Private1 = 11,
Private2 = 12,
Private3 = 13,
Private4 = 14,
Private5 = 15,
Private6 = 16,
Private7 = 17,
Private8 = 18,
PartyNotice = 21,
TeamAlert = 22,
SystemDefault = 24,
RaidNotice = 25,
Emote = 26,
Global = 27,
Raid = 32,
Notify = 201, //enchant, broker msgs, Discovered:, etc..
Event = 202, //guild bam, civil unrest,
Error = 203,
Group = 204,
GuildNotice = 205,
Deathmatch = 206,
ContractAlert = 207,
GroupAlerts = 208,
Loot = 209,
Exp = 210,
Money = 211,
Megaphone = 213,
GuildAdvertising = 214,
// custom--
SentWhisper = 300,
ReceivedWhisper = 301,
System = 302, //missing in db
TradeRedirect = 303,
//Enchant12 = 304,
//Enchant15 = 305,
RaidLeader = 306,
Bargain = 307,
Apply = 308,
Death = 309,
Ress = 310,
Quest = 311,
Friend = 312,
//Enchant7 = 313,
//Enchant8 = 314,
//Enchant9 = 315,
WorldBoss = 316,
Laurel = 317,
Damage = 318,
Guardian = 319,
Enchant = 320,
LFG = 321, // not sure if old /u is still here
TCC = 1000,
Twitch = 1001
// --custom
}
}
| namespace TCC.Utils
{
public enum NotificationType
{
Normal = 0,
Success,
Warning,
Error
}
public enum NotificationTemplate
{
Default,
Progress,
Confirm
}
}
| mit | C# |
902438467f2d7cf339b32011e3f1af3356cf88be | support multi PrefsKvsPathCustom | fuqunaga/PrefsGUI | Packages/PrefsGUI/Runtime/Kvs/PrefsKvsPathSelector.cs | Packages/PrefsGUI/Runtime/Kvs/PrefsKvsPathSelector.cs | using System.Linq;
using UnityEngine;
namespace PrefsGUI.Kvs
{
public interface IPrefsKvsPath
{
string path { get; }
}
public static class PrefsKvsPathSelector
{
static bool _first = true;
static string _path;
public static string path
{
get
{
if (_first)
{
_first = false;
_path = Resources
.FindObjectsOfTypeAll<MonoBehaviour>()
.Select(b => b.GetComponent<IPrefsKvsPath>()?.path)
.FirstOrDefault(str => str != null);
}
return _path ?? Application.persistentDataPath;
}
}
}
} | using System.Linq;
using UnityEngine;
namespace PrefsGUI.Kvs
{
public interface IPrefsKvsPath
{
string path { get; }
}
public static class PrefsKvsPathSelector
{
static bool first = true;
static IPrefsKvsPath _path;
public static string path
{
get
{
if (first)
{
first = false;
_path = Resources
.FindObjectsOfTypeAll<MonoBehaviour>()
.Select(b => b.GetComponent<IPrefsKvsPath>())
.FirstOrDefault(o => o != null);
}
return _path?.path ?? Application.persistentDataPath;
}
}
}
} | mit | C# |
66e87f0c746494f74a363e2179aa2da02a0a5403 | Add a FindByPrefix(string) overload | thefactory/datastore,thefactory/datastore,thefactory/datastore,thefactory/datastore | csharp/TheFactory.Datastore/src/IDatabase.cs | csharp/TheFactory.Datastore/src/IDatabase.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TheFactory.Datastore {
public interface IDatabase : IDisposable {
void PushTablet(string filename);
void PopTablet();
IEnumerable<IKeyValuePair> Find(Slice term);
void PushTabletStream(Stream stream, Action<IEnumerable<IKeyValuePair>> callback);
Slice Get(Slice key);
void Put(Slice key, Slice val);
void Delete(Slice key);
void Close();
}
public static class IDatabaseExtensions {
public static IEnumerable<IKeyValuePair> Find(this IDatabase db) {
return db.Find(null);
}
public static IEnumerable<IKeyValuePair> FindByPrefix(this IDatabase db, Slice term) {
foreach (var kv in db.Find(term)) {
if (!Slice.IsPrefix(kv.Key, term)) {
break;
}
yield return kv;
}
yield break;
}
public static IEnumerable<IKeyValuePair> FindByPrefix(this IDatabase db, string term) {
return db.FindByPrefix((Slice)Encoding.UTF8.GetBytes(term));
}
public static Slice Get(this IDatabase db, string key) {
return db.Get((Slice)Encoding.UTF8.GetBytes(key));
}
public static void Put(this IDatabase db, string key, Slice val) {
db.Put((Slice)Encoding.UTF8.GetBytes(key), val);
}
public static void Put(this IDatabase db, string key, string val) {
db.Put((Slice)Encoding.UTF8.GetBytes(key), (Slice)Encoding.UTF8.GetBytes(val));
}
public static void Delete(this IDatabase db, string key) {
db.Delete((Slice)Encoding.UTF8.GetBytes(key));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace TheFactory.Datastore {
public interface IDatabase : IDisposable {
void PushTablet(string filename);
void PopTablet();
IEnumerable<IKeyValuePair> Find(Slice term);
void PushTabletStream(Stream stream, Action<IEnumerable<IKeyValuePair>> callback);
Slice Get(Slice key);
void Put(Slice key, Slice val);
void Delete(Slice key);
void Close();
}
public static class IDatabaseExtensions {
public static IEnumerable<IKeyValuePair> Find(this IDatabase db) {
return db.Find(null);
}
public static IEnumerable<IKeyValuePair> FindByPrefix(this IDatabase db, Slice term) {
foreach (var kv in db.Find(term)) {
if (!Slice.IsPrefix(kv.Key, term)) {
break;
}
yield return kv;
}
yield break;
}
public static Slice Get(this IDatabase db, string key) {
return db.Get((Slice)Encoding.UTF8.GetBytes(key));
}
public static void Put(this IDatabase db, string key, Slice val) {
db.Put((Slice)Encoding.UTF8.GetBytes(key), val);
}
public static void Put(this IDatabase db, string key, string val) {
db.Put((Slice)Encoding.UTF8.GetBytes(key), (Slice)Encoding.UTF8.GetBytes(val));
}
public static void Delete(this IDatabase db, string key) {
db.Delete((Slice)Encoding.UTF8.GetBytes(key));
}
}
}
| mit | C# |
bc171d244d66592f61e91ad5fc1b5abf6b97a804 | Revert "Add OptimizationCount to UserData." | nfleet/.net-sdk | NFleetSDK/Data/UserData.cs | NFleetSDK/Data/UserData.cs | using System.Collections.Generic;
using System.Runtime.Serialization;
namespace NFleet.Data
{
[DataContract]
public class UserData : IResponseData
{
[IgnoreDataMember]
public int VersionNumber { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public int ProblemLimit { get; set; }
[DataMember]
public int VehicleLimit { get; set; }
[DataMember]
public int TaskLimit { get; set; }
[DataMember]
public int OptimizationQueueLimit { get; set; }
#region Implementation of IResponseData
[DataMember]
public List<Link> Meta { get; set; }
#endregion
}
}
| using System.Collections.Generic;
using System.Runtime.Serialization;
namespace NFleet.Data
{
[DataContract]
public class UserData : IResponseData
{
[IgnoreDataMember]
public int VersionNumber { get; set; }
[DataMember]
public int Id { get; set; }
[DataMember]
public int ProblemLimit { get; set; }
[DataMember]
public int VehicleLimit { get; set; }
[DataMember]
public int TaskLimit { get; set; }
[DataMember]
public int OptimizationQueueLimit { get; set; }
[DataMember]
public int OptimizationCount { get; set; }
#region Implementation of IResponseData
[DataMember]
public List<Link> Meta { get; set; }
#endregion
}
}
| mit | C# |
ea49fa2f15568fe1b0d2ebdb5b7a42c9c12caf49 | Fix bumping algorithm | monoman/NugetCracker,monoman/NugetCracker | NugetCracker/Extensions.cs | NugetCracker/Extensions.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NugetCracker
{
public enum VersionPart { Major, Minor, Revision, Build }
public static class Extensions
{
public static string GetMetaProjectFilePath(this IEnumerable<string> args)
{
var dir = GetFirstDirPath(args);
return args.FirstOrDefaultPath(
arg => arg.ToLowerInvariant().EndsWith(".nugetcracker"),
Path.Combine(dir, "MetaProject.NugetCracker"));
}
public static string FirstOrDefaultPath(this IEnumerable<string> args, Func<string, bool> filter, string defaultfilePath)
{
return Path.GetFullPath(args.FirstOrDefault(filter) ?? defaultfilePath);
}
public static string GetFirstDirPath(this IEnumerable<string> args)
{
return args.FirstOrDefaultPath(arg => Directory.Exists(arg), ".");
}
public static Version Bump(this Version oldVersion, VersionPart partToBump)
{
switch (partToBump) {
case VersionPart.Major:
return new Version(oldVersion.Major + 1, 0, 0, 0);
case VersionPart.Minor:
return new Version(oldVersion.Major, oldVersion.Minor + 1, 0, 0);
case VersionPart.Build:
return new Version(oldVersion.Major, oldVersion.Minor, oldVersion.Build + 1, 0);
}
return new Version(oldVersion.Major, oldVersion.Minor, oldVersion.Build, oldVersion.Revision + 1);
}
public static string ToShort(this Version version)
{
if (version.Revision == 0)
if (version.Build == 0)
return version.ToString(2);
else
return version.ToString(3);
return version.ToString();
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace NugetCracker
{
public enum VersionPart { Major, Minor, Revision, Build }
public static class Extensions
{
public static string GetMetaProjectFilePath(this IEnumerable<string> args)
{
var dir = GetFirstDirPath(args);
return args.FirstOrDefaultPath(
arg => arg.ToLowerInvariant().EndsWith(".nugetcracker"),
Path.Combine(dir, "MetaProject.NugetCracker"));
}
public static string FirstOrDefaultPath(this IEnumerable<string> args, Func<string, bool> filter, string defaultfilePath)
{
return Path.GetFullPath(args.FirstOrDefault(filter) ?? defaultfilePath);
}
public static string GetFirstDirPath(this IEnumerable<string> args)
{
return args.FirstOrDefaultPath(arg => Directory.Exists(arg), ".");
}
public static Version Bump(this Version oldVersion, VersionPart partToBump)
{
switch (partToBump) {
case VersionPart.Major:
return new Version(oldVersion.Major + 1, oldVersion.Minor, oldVersion.Build, oldVersion.Revision);
case VersionPart.Minor:
return new Version(oldVersion.Major, oldVersion.Minor + 1, oldVersion.Build, oldVersion.Revision);
case VersionPart.Build:
return new Version(oldVersion.Major, oldVersion.Minor, oldVersion.Build + 1, oldVersion.Revision);
}
return new Version(oldVersion.Major, oldVersion.Minor, oldVersion.Build, oldVersion.Revision + 1);
}
public static string ToShort(this Version version)
{
if (version.Revision == 0)
if (version.Build == 0)
return version.ToString(2);
else
return version.ToString(3);
return version.ToString();
}
}
}
| apache-2.0 | C# |
9a08c25609cef05db7b375403a0b1e289e9fd638 | Update resource to handle message strings | mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype | src/Glimpse.Server.Web/Resources/MessageHistoryResource.cs | src/Glimpse.Server.Web/Resources/MessageHistoryResource.cs | using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Net.Http.Headers;
namespace Glimpse.Server.Web
{
public class MessageHistoryResource : IResource
{
private readonly InMemoryStorage _store;
public MessageHistoryResource(IStorage storage)
{
// TODO: Really shouldn't be here
_store = (InMemoryStorage)storage;
}
public async Task Invoke(HttpContext context, IDictionary<string, string> parameters)
{
var response = context.Response;
response.Headers[HeaderNames.ContentType] = "application/json";
var list = await _store.Query(null);
var sb = new StringBuilder("[");
sb.Append(string.Join(",", list));
sb.Append("]");
var output = sb.ToString();
await response.WriteAsync(output);
}
public string Name => "MessageHistory";
public ResourceParameters Parameters => null;
}
} | using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNet.Http;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
namespace Glimpse.Server.Web
{
public class MessageHistoryResource : IResource
{
private readonly InMemoryStorage _store;
private readonly JsonSerializer _jsonSerializer;
public MessageHistoryResource(IStorage storage, JsonSerializer jsonSerializer)
{
// TODO: This hack is needed to get around signalr problem
jsonSerializer.ContractResolver = new CamelCasePropertyNamesContractResolver();
// TODO: Really shouldn't be here
_store = (InMemoryStorage)storage;
_jsonSerializer = jsonSerializer;
}
public async Task Invoke(HttpContext context, IDictionary<string, string> parameters)
{
var response = context.Response;
response.Headers[HeaderNames.ContentType] = "application/json";
var list = _store.Query(null);
var output = _jsonSerializer.Serialize(list);
await response.WriteAsync(output);
}
public string Name => "MessageHistory";
public ResourceParameters Parameters => null;
}
} | mit | C# |
5fe44dddfa1e2afdc9d458c3d8f92a90e0a574b3 | Update 20170714.cs | twilightspike/cuddly-disco,twilightspike/cuddly-disco | main/20170714.cs | main/20170714.cs | public struct AABB{
}
| int aaa;
int bbb;
int ccc;
| mit | C# |
e1a9d66a39db422fe5542e1092537e20ff509a74 | Update ArrayEx.ToList | DaveSenn/Extend | PortableExtensions/System.Array/Array.ToList.cs | PortableExtensions/System.Array/Array.ToList.cs | #region Using
using System;
using System.Collections.Generic;
using System.Linq;
#endregion
namespace PortableExtensions
{
/// <summary>
/// Class containing some extension methods for <see cref="Array" />.
/// </summary>
public static partial class ArrayEx
{
/// <summary>
/// Converts the given array to a list using the specified selector.
/// </summary>
/// <param name="items">The array containing the items.</param>
/// <param name="selector">The selector.</param>
/// <typeparam name="T">The type of the items in the list.</typeparam>
/// <returns>The items of the array as list.</returns>
public static List<T> ToList<T>( this Array items, Func<Object, T> selector )
{
items.ThrowIfNull( () => items );
selector.ThrowIfNull( () => selector );
return (from object item in items select selector(item)).ToList();
}
}
} | #region Using
using System;
using System.Collections.Generic;
#endregion
namespace PortableExtensions
{
/// <summary>
/// Class containing some extension methods for <see cref="Array" />.
/// </summary>
public static partial class ArrayEx
{
/// <summary>
/// Converts the given array to a list using the specified selector.
/// </summary>
/// <param name="items">The array containing the items.</param>
/// <param name="selector">The selector.</param>
/// <typeparam name="T">The type of the items in the list.</typeparam>
/// <returns>The items of the array as list.</returns>
public static List<T> ToList<T>( this Array items, Func<Object, T> selector )
{
items.ThrowIfNull( () => items );
selector.ThrowIfNull( () => selector );
var list = new List<T>();
foreach ( var item in items )
list.Add( selector( item ) );
return list;
}
}
} | mit | C# |
d1f919d0caa5734dbb9a1610dd0402d716bf7c85 | Add unit test for Internet detection methods | fredatgithub/UsefulFunctions | UnitTestUsefullFunctions/UnitTestFunctionsInternet.cs | UnitTestUsefullFunctions/UnitTestFunctionsInternet.cs | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Globalization;
using MathFunc = FonctionsUtiles.Fred.Csharp.FunctionsMath;
using StringFunc = FonctionsUtiles.Fred.Csharp.FunctionsString;
using DateFunc = FonctionsUtiles.Fred.Csharp.FunctionsDateTime;
using InternetFunc = FonctionsUtiles.Fred.Csharp.FunctionsInternet;
using FonctionsUtiles.Fred.Csharp;
namespace UnitTestUsefullFunctions
{
[TestClass]
public class UnitTestFunctionsInternet
{
#region IsInternetConnected
//**********************IsInternetConnected***************
[TestMethod]
public void TestMethod_IsInternetConnected_true()
{
const bool expected = true;
bool result = InternetFunc.IsInternetConnected();
Assert.AreEqual(result, expected);
}
#endregion IsInternetConnected
#region IsNetworkLikelyAvailable
//**********************IsNetworkLikelyAvailable***************
[TestMethod]
public void TestMethod_IsNetworkLikelyAvailable_true()
{
const bool expected = true;
bool result = InternetFunc.IsNetworkLikelyAvailable();
Assert.AreEqual(result, expected);
}
#endregion IsNetworkLikelyAvailable
#region IsNetworkLikelyAvailable
//**********************IsOnenNetworkCardAvailable***************
[TestMethod]
public void TestMethod_IsOnenNetworkCardAvailable_true()
{
const bool expected = true;
bool result = InternetFunc.IsOnenNetworkCardAvailable();
Assert.AreEqual(result, expected);
}
#endregion IsOnenNetworkCardAvailable
}
} | /*
The MIT License(MIT)
Copyright(c) 2015 Freddy Juhel
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 Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Globalization;
using MathFunc = FonctionsUtiles.Fred.Csharp.FunctionsMath;
using StringFunc = FonctionsUtiles.Fred.Csharp.FunctionsString;
using DateFunc = FonctionsUtiles.Fred.Csharp.FunctionsDateTime;
using InternetFunc = FonctionsUtiles.Fred.Csharp.FunctionsInternet;
using FonctionsUtiles.Fred.Csharp;
namespace UnitTestUsefullFunctions
{
[TestClass]
public class UnitTestFunctionsInternet
{
#region IsInternetConnected
//**********************IsInternetConnected***************
[TestMethod]
public void TestMethod_IsInternetConnected_true()
{
const bool expected = true;
bool result = InternetFunc.IsInternetConnected();
Assert.AreEqual(result, expected);
}
#endregion IsInternetConnected
}
} | mit | C# |
1387c69a39766f02f213fc4e1fae5305447c4fcc | Write TSV. | ethankennerly/UnityToykit | Journal.cs | Journal.cs | using System.Collections.Generic/*<List>*/;
using UnityEngine/*<Mathf>*/;
namespace Finegamedesign.Utils
{
// Record and playback real-time actions.
public sealed class Journal
{
public string action = null;
public int milliseconds = 0;
public float seconds = 0.0f;
public bool isPlayback = false;
public int playbackIndex = 0;
public List<int> playbackDelays = new List<int>();
public List<string> playbackActions = new List<string>();
public string commandNow = null;
// Example: TestAnagramJournal.cs
public void Update(float deltaSeconds)
{
seconds += deltaSeconds;
milliseconds = (int)(Mathf.Round(seconds * 1000.0f));
if (isPlayback)
{
commandNow = UpdatePlayback();
}
}
private string UpdatePlayback()
{
string command = null;
if (playbackIndex < DataUtil.Length(playbackDelays))
{
int delay = playbackDelays[playbackIndex];
if (delay <= milliseconds)
{
command = playbackActions[playbackIndex];
playbackIndex++;
}
}
return command;
}
// Example: TestAnagramJournal.cs
public void Record(string act)
{
action = act;
if (!isPlayback)
{
playbackActions.Add(act);
playbackDelays.Add(milliseconds);
}
seconds = 0.0f;
}
// Example: TestAnagramJournal.cs
public void Read(string historyTsv)
{
string[][] table = Toolkit.ParseCsv(historyTsv, "\t");
DataUtil.Clear(playbackDelays);
DataUtil.Clear(playbackActions);
if ("delay" != table[0][0] || "action" != table[0][1])
{
throw new System.InvalidOperationException("Expected delay and action as headers."
+ " Got " + table[0][0] + ", " + table[0][1]);
}
for (int rowIndex = 1; rowIndex < DataUtil.Length(table); rowIndex++)
{
string[] row = table[rowIndex];
int delay = Toolkit.ParseInt(row[0]);
playbackDelays.Add(delay);
string action = row[1];
playbackActions.Add(action);
}
}
// Example: TestAnagramJournal.cs
public string Write()
{
string historyTsv = "delay\taction";
for (int index = 0; index < DataUtil.Length(playbackDelays); index++)
{
historyTsv += "\n" + playbackDelays[index].ToString();
historyTsv += "\t" + playbackActions[index];
}
return historyTsv;
}
public void StartPlayback()
{
playbackIndex = 0;
isPlayback = true;
}
}
}
| using System.Collections.Generic/*<List>*/;
using UnityEngine/*<Mathf>*/;
namespace Finegamedesign.Utils
{
public sealed class Journal
{
public string action = null;
public int milliseconds = 0;
public float seconds = 0.0f;
public bool isPlayback = false;
public int playbackIndex = 0;
public List<int> playbackDelays = new List<int>();
public List<string> playbackActions = new List<string>();
public string commandNow = null;
public void Update(float deltaSeconds)
{
seconds += deltaSeconds;
milliseconds = (int)(Mathf.Round(seconds * 1000.0f));
if (isPlayback)
{
commandNow = UpdatePlayback();
}
}
private string UpdatePlayback()
{
string command = null;
if (playbackIndex < DataUtil.Length(playbackDelays))
{
int delay = playbackDelays[playbackIndex];
if (delay <= milliseconds)
{
command = playbackActions[playbackIndex];
playbackIndex++;
}
}
return command;
}
public void Record(string act)
{
action = act;
if (!isPlayback)
{
playbackActions.Add(act);
playbackDelays.Add(milliseconds);
}
seconds = 0.0f;
}
public void Read(string historyTsv)
{
string[][] table = Toolkit.ParseCsv(historyTsv, "\t");
DataUtil.Clear(playbackDelays);
DataUtil.Clear(playbackActions);
if ("delay" != table[0][0] || "action" != table[0][1])
{
throw new System.InvalidOperationException("Expected delay and action as headers."
+ " Got " + table[0][0] + ", " + table[0][1]);
}
for (int rowIndex = 1; rowIndex < DataUtil.Length(table); rowIndex++)
{
string[] row = table[rowIndex];
int delay = Toolkit.ParseInt(row[0]);
playbackDelays.Add(delay);
string action = row[1];
playbackActions.Add(action);
}
}
public void StartPlayback()
{
playbackIndex = 0;
isPlayback = true;
}
}
}
| mit | C# |
4dbbd0d765efd016d02d5b570f15eca5efa856c9 | Convert to NFluent | blorgbeard/pickles,magicmonty/pickles,irfanah/pickles,blorgbeard/pickles,ludwigjossieaux/pickles,picklesdoc/pickles,irfanah/pickles,irfanah/pickles,blorgbeard/pickles,magicmonty/pickles,ludwigjossieaux/pickles,ludwigjossieaux/pickles,magicmonty/pickles,blorgbeard/pickles,dirkrombauts/pickles,irfanah/pickles,dirkrombauts/pickles,magicmonty/pickles,dirkrombauts/pickles,picklesdoc/pickles,picklesdoc/pickles,picklesdoc/pickles,dirkrombauts/pickles | src/Pickles/Pickles.Test/Extensions/PathExtensionsTests.cs | src/Pickles/Pickles.Test/Extensions/PathExtensionsTests.cs | using System;
using System.IO.Abstractions.TestingHelpers;
using NUnit.Framework;
using PicklesDoc.Pickles.Extensions;
using NFluent;
namespace PicklesDoc.Pickles.Test.Extensions
{
[TestFixture]
internal class PathExtensionsTests : BaseFixture
{
[Test]
public void Get_A_Relative_Path_When_Location_Is_Deeper_Than_Root()
{
MockFileSystem fileSystem = FileSystem;
fileSystem.AddFile(@"c:\test\deep\blah.feature", "Feature:"); // adding a file automatically adds all parent directories
string actual = PathExtensions.MakeRelativePath(@"c:\test", @"c:\test\deep\blah.feature", fileSystem);
Check.That(actual).IsEqualTo(@"deep\blah.feature");
}
[Test]
public void Get_A_Relative_Path_When_Location_Is_Deeper_Than_Root_Even_When_Root_Contains_End_Slash()
{
MockFileSystem fileSystem = FileSystem;
fileSystem.AddFile(@"c:\test\deep\blah.feature", "Feature:"); // adding a file automatically adds all parent directories
string actual = PathExtensions.MakeRelativePath(@"c:\test\", @"c:\test\deep\blah.feature", fileSystem);
Check.That(actual).IsEqualTo(@"deep\blah.feature");
}
}
} | using System;
using System.IO.Abstractions.TestingHelpers;
using NUnit.Framework;
using PicklesDoc.Pickles.Extensions;
using Should;
namespace PicklesDoc.Pickles.Test.Extensions
{
[TestFixture]
internal class PathExtensionsTests : BaseFixture
{
[Test]
public void Get_A_Relative_Path_When_Location_Is_Deeper_Than_Root()
{
MockFileSystem fileSystem = FileSystem;
fileSystem.AddFile(@"c:\test\deep\blah.feature", "Feature:"); // adding a file automatically adds all parent directories
string actual = PathExtensions.MakeRelativePath(@"c:\test", @"c:\test\deep\blah.feature", fileSystem);
actual.ShouldEqual(@"deep\blah.feature");
}
[Test]
public void Get_A_Relative_Path_When_Location_Is_Deeper_Than_Root_Even_When_Root_Contains_End_Slash()
{
MockFileSystem fileSystem = FileSystem;
fileSystem.AddFile(@"c:\test\deep\blah.feature", "Feature:"); // adding a file automatically adds all parent directories
string actual = PathExtensions.MakeRelativePath(@"c:\test\", @"c:\test\deep\blah.feature", fileSystem);
actual.ShouldEqual(@"deep\blah.feature");
}
}
} | apache-2.0 | C# |
971cc8687b756e2b714c60c98ef0fd4e28c5a046 | Bump version | InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET,InEngine-NET/InEngine.NET | configuration/SharedAssemblyInfo.cs | configuration/SharedAssemblyInfo.cs | using System.Reflection;
// Assembly Info that is shared across the product
[assembly: AssemblyProduct("InEngine.NET")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0-alpha5")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ethan Hann")]
[assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
| using System.Reflection;
// Assembly Info that is shared across the product
[assembly: AssemblyProduct("InEngine.NET")]
[assembly: AssemblyVersion("2.0.0.*")]
[assembly: AssemblyInformationalVersion("2.0.0-alpha4")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Ethan Hann")]
[assembly: AssemblyCopyright("Copyright © Ethan Hann 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyDescription("")]
| mit | C# |
5913e07fa2c78f58525aec30df0897eac61aede9 | Fix connection bug to PGSQL | ctigeek/InvokeQueryPowershellModule | InvokePostgreSqlQuery.cs | InvokePostgreSqlQuery.cs | using Npgsql;
using System.Data.Common;
using System.Management.Automation;
namespace InvokeQuery
{
[Cmdlet("Invoke", "PostgreSqlQuery", SupportsTransactions = true, SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)]
public class InvokePostgreSqlQuery : InvokeQueryBase
{
protected override DbProviderFactory GetProviderFactory()
{
return NpgsqlFactory.Instance;
}
protected override void ConfigureConnectionString()
{
if (!string.IsNullOrEmpty(ConnectionString)) return;
var connString = new NpgsqlConnectionStringBuilder();
connString.Host = Server;
if (!string.IsNullOrEmpty(Database))
{
connString.Database = Database;
}
if (Credential != PSCredential.Empty)
{
connString.Username = Credential.UserName;
connString.Password = Credential.Password.ConvertToUnsecureString();
}
if (ConnectionTimeout > 0)
{
connString.Timeout = ConnectionTimeout;
}
ConnectionString = connString.ToString();
}
}
}
| using System.Data.Common;
using System.Management.Automation;
using Npgsql;
namespace InvokeQuery
{
[Cmdlet("Invoke", "PostgreSqlQuery", SupportsTransactions = true, SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)]
public class InvokePostgreSqlQuery : InvokeQueryBase
{
protected override DbProviderFactory GetProviderFactory()
{
return NpgsqlFactory.Instance;
}
}
}
| mit | C# |
6f835338acd28fb784b9b5de7c3e26905da4b040 | use essential review support | prozum/solitude | Solitude.Server/Controllers/ReviewController.cs | Solitude.Server/Controllers/ReviewController.cs | using System.Web.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Model;
using System;
namespace Solitude.Server
{
public class ReviewController : SolitudeController
{
public async Task<IHttpActionResult> Get(Guid id)
{
var events = await DB.GetReviews(id);
return Ok(events);
}
public async Task<IHttpActionResult> Post(Review review)
{
review.UserId = new Guid(User.Identity.GetUserId());
await DB.AddReview(review);
return Ok();
}
}
}
| using System.Web.Http;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Model;
using System;
namespace Solitude.Server
{
public class ReviewController : SolitudeController
{
public async Task<IHttpActionResult> Post(Review review)
{
review.UserId = new Guid(User.Identity.GetUserId());
await DB.AddReview(review);
return Ok();
}
}
}
| mit | C# |
07a546da9928d8502675bcbff0c40f89809ca835 | Fix `BassAmplitudeProcessor` allocating unnecessary array | peppy/osu-framework,peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ZLima12/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework,ppy/osu-framework | osu.Framework/Audio/BassAmplitudeProcessor.cs | osu.Framework/Audio/BassAmplitudeProcessor.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.
#nullable enable
using ManagedBass;
using osu.Framework.Audio.Mixing.Bass;
using osu.Framework.Audio.Track;
namespace osu.Framework.Audio
{
/// <summary>
/// Computes and caches amplitudes for a bass channel.
/// </summary>
internal class BassAmplitudeProcessor
{
/// <summary>
/// The most recent amplitude data. Note that this is updated on an ongoing basis and there is no guarantee it is in a consistent (single sample) state.
/// If you need consistent data, make a copy of FrequencyAmplitudes while on the audio thread.
/// </summary>
public ChannelAmplitudes CurrentAmplitudes { get; private set; } = ChannelAmplitudes.Empty;
private readonly IBassAudioChannel channel;
public BassAmplitudeProcessor(IBassAudioChannel channel)
{
this.channel = channel;
}
private float[]? frequencyData;
private readonly float[] channelLevels = new float[2];
public void Update()
{
if (channel.Handle == 0)
return;
bool active = channel.Mixer.ChannelIsActive(channel) == PlaybackState.Playing;
channel.Mixer.ChannelGetLevel(channel, channelLevels, 1 / 60f, LevelRetrievalFlags.Stereo);
var leftChannel = active ? channelLevels[0] : -1;
var rightChannel = active ? channelLevels[1] : -1;
if (leftChannel >= 0 && rightChannel >= 0)
{
frequencyData ??= new float[ChannelAmplitudes.AMPLITUDES_SIZE];
channel.Mixer.ChannelGetData(channel, frequencyData, (int)DataFlags.FFT512);
CurrentAmplitudes = new ChannelAmplitudes(leftChannel, rightChannel, frequencyData);
}
else
CurrentAmplitudes = ChannelAmplitudes.Empty;
}
}
}
| // 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.
#nullable enable
using ManagedBass;
using osu.Framework.Audio.Mixing.Bass;
using osu.Framework.Audio.Track;
namespace osu.Framework.Audio
{
/// <summary>
/// Computes and caches amplitudes for a bass channel.
/// </summary>
internal class BassAmplitudeProcessor
{
/// <summary>
/// The most recent amplitude data. Note that this is updated on an ongoing basis and there is no guarantee it is in a consistent (single sample) state.
/// If you need consistent data, make a copy of FrequencyAmplitudes while on the audio thread.
/// </summary>
public ChannelAmplitudes CurrentAmplitudes { get; private set; } = ChannelAmplitudes.Empty;
private readonly IBassAudioChannel channel;
public BassAmplitudeProcessor(IBassAudioChannel channel)
{
this.channel = channel;
}
private float[]? frequencyData;
public void Update()
{
if (channel.Handle == 0)
return;
bool active = channel.Mixer.ChannelIsActive(channel) == PlaybackState.Playing;
float[] channelLevels = new float[2];
channel.Mixer.ChannelGetLevel(channel, channelLevels, 1 / 60f, LevelRetrievalFlags.Stereo);
var leftChannel = active ? channelLevels[0] : -1;
var rightChannel = active ? channelLevels[1] : -1;
if (leftChannel >= 0 && rightChannel >= 0)
{
frequencyData ??= new float[ChannelAmplitudes.AMPLITUDES_SIZE];
channel.Mixer.ChannelGetData(channel, frequencyData, (int)DataFlags.FFT512);
CurrentAmplitudes = new ChannelAmplitudes(leftChannel, rightChannel, frequencyData);
}
else
CurrentAmplitudes = ChannelAmplitudes.Empty;
}
}
}
| mit | C# |
afe311cd046837cdd725f30048654c749c83dd6a | fix using wrong id, this one is blank at this point | Pondidum/Ledger,Pondidum/Ledger | Ledger/AggregateStore.cs | Ledger/AggregateStore.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Ledger.Infrastructure;
namespace Ledger
{
public class AggregateStore<TKey>
{
private readonly IEventStore _eventStore;
public int DefaultSnapshotInterval { get; set; }
public AggregateStore(IEventStore eventStore)
{
_eventStore = eventStore;
DefaultSnapshotInterval = 10;
}
public void Save<TAggregate>(TAggregate aggregate)
where TAggregate : AggregateRoot<TKey>
{
var lastStoredSequence = _eventStore.GetLatestSequenceFor(aggregate.ID);
if (lastStoredSequence.HasValue && lastStoredSequence != aggregate.SequenceID)
{
throw new Exception();
}
var changes = aggregate
.GetUncommittedEvents()
.Apply((e, i) => e.SequenceID = aggregate.SequenceID + i)
.ToList();
if (changes.None())
{
return;
}
if (ImplementsSnapshottable(aggregate) && NeedsSnapshot(aggregate, changes))
{
var methodName = TypeInfo.GetMethodName<ISnapshotable<ISequenced>>(x => x.CreateSnapshot());
var createSnapshot = aggregate
.GetType()
.GetMethod(methodName);
var snapshot = (ISequenced)createSnapshot.Invoke(aggregate, new object[] { });
snapshot.SequenceID = changes.Last().SequenceID;
_eventStore.SaveSnapshot(aggregate.ID, snapshot);
}
_eventStore.SaveEvents(aggregate.ID, changes);
aggregate.MarkEventsCommitted();
}
private bool NeedsSnapshot<TAggregate>(TAggregate aggregate, IReadOnlyCollection<DomainEvent> changes)
where TAggregate : AggregateRoot<TKey>
{
var control = aggregate as ISnapshotControl;
var interval = control != null
? control.SnapshotInterval
: DefaultSnapshotInterval;
if (changes.Count >= interval)
{
return true;
}
var snapshotID = _eventStore.GetLatestSnapshotSequenceFor(aggregate.ID);
return snapshotID.HasValue && changes.Last().SequenceID >= snapshotID.Value + interval;
}
public TAggregate Load<TAggregate>(TKey aggregateID, Func<TAggregate> createNew)
where TAggregate : AggregateRoot<TKey>
{
var aggregate = createNew();
if (ImplementsSnapshottable(aggregate))
{
var snapshot = _eventStore.GetLatestSnapshotFor(aggregateID);
var events = _eventStore.LoadEventsSince(aggregateID, snapshot.SequenceID);
aggregate.LoadFromSnapshot(snapshot, events);
}
else
{
var events = _eventStore.LoadEvents(aggregateID);
aggregate.LoadFromEvents(events);
}
return aggregate;
}
private static bool ImplementsSnapshottable(AggregateRoot<TKey> aggregate)
{
return aggregate
.GetType()
.GetInterfaces()
.Any(i => i.GetGenericTypeDefinition() == typeof(ISnapshotable<>));
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Ledger.Infrastructure;
namespace Ledger
{
public class AggregateStore<TKey>
{
private readonly IEventStore _eventStore;
public int DefaultSnapshotInterval { get; set; }
public AggregateStore(IEventStore eventStore)
{
_eventStore = eventStore;
DefaultSnapshotInterval = 10;
}
public void Save<TAggregate>(TAggregate aggregate)
where TAggregate : AggregateRoot<TKey>
{
var lastStoredSequence = _eventStore.GetLatestSequenceFor(aggregate.ID);
if (lastStoredSequence.HasValue && lastStoredSequence != aggregate.SequenceID)
{
throw new Exception();
}
var changes = aggregate
.GetUncommittedEvents()
.Apply((e, i) => e.SequenceID = aggregate.SequenceID + i)
.ToList();
if (changes.None())
{
return;
}
if (ImplementsSnapshottable(aggregate) && NeedsSnapshot(aggregate, changes))
{
var methodName = TypeInfo.GetMethodName<ISnapshotable<ISequenced>>(x => x.CreateSnapshot());
var createSnapshot = aggregate
.GetType()
.GetMethod(methodName);
var snapshot = (ISequenced)createSnapshot.Invoke(aggregate, new object[] { });
snapshot.SequenceID = changes.Last().SequenceID;
_eventStore.SaveSnapshot(aggregate.ID, snapshot);
}
_eventStore.SaveEvents(aggregate.ID, changes);
aggregate.MarkEventsCommitted();
}
private bool NeedsSnapshot<TAggregate>(TAggregate aggregate, IReadOnlyCollection<DomainEvent> changes)
where TAggregate : AggregateRoot<TKey>
{
var control = aggregate as ISnapshotControl;
var interval = control != null
? control.SnapshotInterval
: DefaultSnapshotInterval;
if (changes.Count >= interval)
{
return true;
}
var snapshotID = _eventStore.GetLatestSnapshotSequenceFor(aggregate.ID);
return snapshotID.HasValue && changes.Last().SequenceID >= snapshotID.Value + interval;
}
public TAggregate Load<TAggregate>(TKey aggregateID, Func<TAggregate> createNew)
where TAggregate : AggregateRoot<TKey>
{
var aggregate = createNew();
if (ImplementsSnapshottable(aggregate))
{
var snapshot = _eventStore.GetLatestSnapshotFor(aggregate.ID);
var events = _eventStore.LoadEventsSince(aggregateID, snapshot.SequenceID);
aggregate.LoadFromSnapshot(snapshot, events);
}
else
{
var events = _eventStore.LoadEvents(aggregateID);
aggregate.LoadFromEvents(events);
}
return aggregate;
}
private static bool ImplementsSnapshottable(AggregateRoot<TKey> aggregate)
{
return aggregate
.GetType()
.GetInterfaces()
.Any(i => i.GetGenericTypeDefinition() == typeof(ISnapshotable<>));
}
}
}
| lgpl-2.1 | C# |
76c84fa9bbe9342274453fe18b7790191959aceb | Update App.xaml.cs | wieslawsoltes/Draw2D,wieslawsoltes/Draw2D,wieslawsoltes/Draw2D | src/PathDemo/App.xaml.cs | src/PathDemo/App.xaml.cs | using System.Windows;
using PathDemo.Views;
namespace PathDemo
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var window = new MainView();
window.ShowDialog();
}
}
}
| using System.Windows;
namespace PathDemo
{
public partial class App : Application
{
}
}
| mit | C# |
996511a82e5365a97fb7185ab21e3e4242fca189 | Update version info | Abc-Arbitrage/Zebus,biarne-a/Zebus,rbouallou/Zebus,AtwooTM/Zebus | src/SharedVersionInfo.cs | src/SharedVersionInfo.cs | using System.Reflection;
[assembly: AssemblyVersion("1.2.11")]
[assembly: AssemblyFileVersion("1.2.11")]
[assembly: AssemblyInformationalVersion("1.2.11")]
| using System.Reflection;
[assembly: AssemblyVersion("1.2.10")]
[assembly: AssemblyFileVersion("1.2.10")]
[assembly: AssemblyInformationalVersion("1.2.10")]
| mit | C# |
0e90793a0b7968cbe6f144fa8d22b39e802edcf0 | Update ModuleInitializer.cs | SimonCropp/CaptureSnippets | Tests/ModuleInitializer.cs | Tests/ModuleInitializer.cs | using ObjectApproval;
public static class ModuleInitializer
{
public static void Initialize()
{
SerializerBuilder.ExtraSettings = settings =>
{
var converters = settings.Converters;
converters.Add(new VersionRangeConverter());
converters.Add(new ProcessResultConverter());
converters.Add(new SnippetConverter());
};
}
} | using ObjectApproval;
public static class ModuleInitializer
{
public static void Initialize()
{
var converters = ObjectApprover.JsonSerializer.Converters;
converters.Add(new VersionRangeConverter());
converters.Add(new ProcessResultConverter());
converters.Add(new SnippetConverter());
}
} | mit | C# |
15a0777a2e4bf5e0e4d4ea0315fdeff2360fd845 | Update FirstReverse.cs | michaeljwebb/Algorithm-Practice | Coderbyte/FirstReverse.cs | Coderbyte/FirstReverse.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
class FirstReverse
{
static void Main(string[] args)
{
Console.WriteLine(First_Reverse(Console.ReadLine()));
}
public static string First_Reverse(string str)
{
char[] cArray = str.ToCharArray();
string result = "";
for (int i = cArray.Length - 1; i >= 0; i--)
{
result += cArray[i];
str = result;
}
return str;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Coderbyte
{
class FirstReverse
{
static void Main(string[] args)
{
Console.WriteLine(First_Reverse(Console.ReadLine()));
}
public static string First_Reverse(string str)
{
char[] cArray = str.ToCharArray();
string result = "";
for (int i = cArray.Length - 1; i >= 0; i--)
{
result += cArray[i];
str = result;
}
return str;
}
}
}
| mit | C# |
46b6e0a67fc615f2ef0b264ced88fb7c5f27757d | Write new progress bar on top of the old one | appharbor/appharbor-cli | src/AppHarbor/CompressionExtensions.cs | src/AppHarbor/CompressionExtensions.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName))
.ToList();
var entriesCount = entries.Count();
for (var i = 0; i < entriesCount; i++)
{
archive.WriteEntry(entries[i], true);
ConsoleProgressBar.Render(i * 100 / (double)entriesCount, ConsoleColor.Green,
string.Format("Packing files ({0} of {1})", i + 1, entriesCount));
}
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => !excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using ICSharpCode.SharpZipLib.Tar;
namespace AppHarbor
{
public static class CompressionExtensions
{
public static void ToTar(this DirectoryInfo sourceDirectory, Stream output, string[] excludedDirectoryNames)
{
var archive = TarArchive.CreateOutputTarArchive(output);
archive.RootPath = sourceDirectory.FullName.Replace(Path.DirectorySeparatorChar, '/').TrimEnd('/');
var entries = GetFiles(sourceDirectory, excludedDirectoryNames)
.Select(x => TarEntry.CreateEntryFromFile(x.FullName))
.ToList();
var entriesCount = entries.Count();
for (var i = 0; i < entriesCount; i++)
{
archive.WriteEntry(entries[i], true);
ConsoleProgressBar.Render(i * 100 / (double)entriesCount, ConsoleColor.Green,
string.Format("Packing files ({0} of {1})", i + 1, entriesCount));
}
Console.CursorTop++;
Console.WriteLine();
archive.Close();
}
private static IEnumerable<FileInfo> GetFiles(DirectoryInfo directory, string[] excludedDirectories)
{
return directory.GetFiles("*", SearchOption.TopDirectoryOnly)
.Concat(directory.GetDirectories()
.Where(x => !excludedDirectories.Contains(x.Name))
.SelectMany(x => GetFiles(x, excludedDirectories)));
}
}
}
| mit | C# |
a3ebd246f7f6a2a0895fe7fa997f578ae82ceba5 | Clear console before game starts | 12joan/hangman | Program.cs | Program.cs | using System;
using System.IO;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
var wordGenerator = new RandomWord();
var word = wordGenerator.Word();
var game = new Game(word);
var width = Math.Min(81, Console.WindowWidth);
string titleText;
int spacing;
if (width >= 81) {
titleText = File.ReadAllText("title_long.txt");
spacing = 2;
} else if (width >= 48) {
titleText = File.ReadAllText("title_short.txt");
spacing = 1;
} else {
titleText = "Hangman";
spacing = 1;
}
while (game.IsPlaying()) {
var table = HangmanTable.Build(
word,
titleText,
game,
width,
spacing
);
var tableOutput = table.Draw();
Console.Clear();
Console.WriteLine(tableOutput);
char key = Console.ReadKey(true).KeyChar;
game.GuessLetter(Char.ToUpper(key));
}
// After the game
Console.Clear();
Console.WriteLine(game.Status);
Console.WriteLine("The word was \"{0}\".", word);
}
}
}
| using System;
using System.IO;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
var wordGenerator = new RandomWord();
var word = wordGenerator.Word();
var game = new Game(word);
var width = Math.Min(81, Console.WindowWidth);
string titleText;
int spacing;
if (width >= 81) {
titleText = File.ReadAllText("title_long.txt");
spacing = 2;
} else if (width >= 48) {
titleText = File.ReadAllText("title_short.txt");
spacing = 1;
} else {
titleText = "Hangman";
spacing = 1;
}
while (game.IsPlaying()) {
var table = HangmanTable.Build(
word,
titleText,
game,
width,
spacing
);
var tableOutput = table.Draw();
Console.WriteLine(tableOutput);
char key = Console.ReadKey(true).KeyChar;
game.GuessLetter(Char.ToUpper(key));
Console.Clear();
}
// After the game
Console.WriteLine(game.Status);
Console.WriteLine("The word was \"{0}\".", word);
}
}
}
| unlicense | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.