doc_id stringlengths 36 36 | metadata dict | input stringlengths 28 4.3k | output stringlengths 11 5.45k |
|---|---|---|---|
05aa3d77-a843-41e2-b937-0d66d9b3eba8 | {
"language": "C#"
} | ```c#
using System;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseHttpSys();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
```
Add missing call to set content root on WebHostBuilder | ```c#
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Server.HttpSys;
using Microsoft.Extensions.Configuration;
namespace MusicStore
{
public static class Program
{
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.AddCommandLine(args)
.AddEnvironmentVariables(prefix: "ASPNETCORE_")
.Build();
var builder = new WebHostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseConfiguration(config)
.UseIISIntegration()
.UseStartup("MusicStore");
if (string.Equals(builder.GetSetting("server"), "Microsoft.AspNetCore.Server.HttpSys", System.StringComparison.Ordinal))
{
var environment = builder.GetSetting("environment") ??
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (string.Equals(environment, "NtlmAuthentication", System.StringComparison.Ordinal))
{
// Set up NTLM authentication for WebListener like below.
// For IIS and IISExpress: Use inetmgr to setup NTLM authentication on the application vDir or
// modify the applicationHost.config to enable NTLM.
builder.UseHttpSys(options =>
{
options.Authentication.Schemes = AuthenticationSchemes.NTLM;
options.Authentication.AllowAnonymous = false;
});
}
else
{
builder.UseHttpSys();
}
}
else
{
builder.UseKestrel();
}
var host = builder.Build();
host.Run();
}
}
}
``` |
595cf47c-a7f7-4696-8c6e-904dce04ed61 | {
"language": "C#"
} | ```c#
namespace Alexa.NET.Request.Type
{
public class DefaultRequestTypeConverter : IRequestTypeConverter
{
public bool CanConvert(string requestType)
{
return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest";
}
public Request Convert(string requestType)
{
switch (requestType)
{
case "IntentRequest":
return new IntentRequest();
case "LaunchRequest":
return new LaunchRequest();
case "SessionEndedRequest":
return new SessionEndedRequest();
case "System.ExceptionEncountered":
return new SystemExceptionRequest();
}
return null;
}
}
}```
Update default converter to handle exception type | ```c#
namespace Alexa.NET.Request.Type
{
public class DefaultRequestTypeConverter : IRequestTypeConverter
{
public bool CanConvert(string requestType)
{
return requestType == "IntentRequest" || requestType == "LaunchRequest" || requestType == "SessionEndedRequest" || requestType == "System.ExceptionEncountered";
}
public Request Convert(string requestType)
{
switch (requestType)
{
case "IntentRequest":
return new IntentRequest();
case "LaunchRequest":
return new LaunchRequest();
case "SessionEndedRequest":
return new SessionEndedRequest();
case "System.ExceptionEncountered":
return new SystemExceptionRequest();
}
return null;
}
}
}
``` |
da010d9b-0a52-4198-8c82-d2ee630fb2c5 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Treehopper.Demos.SoftPwm
{
class Program
{
static void Main(string[] args)
{
Run();
}
static TreehopperUsb board;
static async void Run()
{
int pinNumber = 10;
Console.Write("Looking for board...");
board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Board found.");
Console.WriteLine(String.Format("Connecting to {0} and starting SoftPwm on Pin{1}", board, pinNumber));
await board.ConnectAsync();
board[pinNumber].SoftPwm.Enabled = true;
int step = 10;
int rate = 25;
while (true)
{
for (int i = 0; i < 256; i = i + step)
{
board[pinNumber].SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
for (int i = 255; i > 0; i = i - step)
{
board[pinNumber].SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
}
}
}
}
```
Use Pins, not ints. We ain't Arduino! | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Treehopper.Demos.SoftPwm
{
class Program
{
static void Main(string[] args)
{
Run();
}
static TreehopperUsb board;
static async void Run()
{
Console.Write("Looking for board...");
board = await ConnectionService.Instance.GetFirstDeviceAsync();
Console.WriteLine("Board found.");
await board.ConnectAsync();
var pin = board[1];
pin.SoftPwm.Enabled = true;
pin.SoftPwm.DutyCycle = 0.8;
int step = 10;
int rate = 25;
while (true)
{
for (int i = 0; i < 256; i = i + step)
{
pin.SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
for (int i = 255; i > 0; i = i - step)
{
pin.SoftPwm.DutyCycle = i / 255.0;
await Task.Delay(rate);
}
}
}
}
}
``` |
88292eca-895e-4dd3-b5ca-78b1c14b8f8b | {
"language": "C#"
} | ```c#
using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.Common.Web;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS",
Summary = "Get status information about the server.")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = conn.Scalar<int>("SELECT COUNT(*) FROM DBUser");
s.TotalNumberOfNotes = conn.Scalar<int>("SELECT COUNT(*) FROM DBNote");
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
}```
Use ORM instead of open-coded SQL | ```c#
using ServiceStack.ServiceHost;
using Rainy.Db;
using ServiceStack.OrmLite;
using System;
using ServiceStack.Common.Web;
using Tomboy.Db;
namespace Rainy.WebService.Admin
{
[Route("/api/admin/status/","GET, OPTIONS",
Summary = "Get status information about the server.")]
[AdminPasswordRequired]
public class StatusRequest : IReturn<Status>
{
}
public class StatusService : ServiceBase {
public StatusService (IDbConnectionFactory fac) : base (fac)
{
}
public Status Get (StatusRequest req)
{
var s = new Status ();
s.Uptime = MainClass.Uptime;
s.NumberOfRequests = MainClass.ServedRequests;
// determine number of users
using (var conn = connFactory.OpenDbConnection ()) {
s.NumberOfUser = (int)conn.Count<DBUser> ();
s.TotalNumberOfNotes = (int)conn.Count<DBNote> ();
if (s.NumberOfUser > 0)
s.AverageNotesPerUser = (float)s.TotalNumberOfNotes / (float)s.NumberOfUser;
};
return s;
}
}
public class Status
{
public DateTime Uptime { get; set; }
public int NumberOfUser { get; set; }
public long NumberOfRequests { get; set; }
public int TotalNumberOfNotes { get; set; }
public float AverageNotesPerUser { get; set; }
}
}``` |
b4abfc36-7ab2-4a4c-b1b7-8370eaa5052b | {
"language": "C#"
} | ```c#
using System;
using System.Net;
using System.Net.Sockets;
namespace Abc.Zebus.Util
{
internal static class TcpUtil
{
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
public static bool IsPortUnused(int port)
{
var listener = new TcpListener(IPAddress.Any, port);
try
{
listener.Start();
}
catch (Exception)
{
return false;
}
listener.Stop();
return true;
}
}
}```
Change IsPortUnused() implementation because of SO_REUSEPORT on Linux | ```c#
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
namespace Abc.Zebus.Util
{
internal static class TcpUtil
{
public static int GetRandomUnusedPort()
{
var listener = new TcpListener(IPAddress.Any, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
public static bool IsPortUnused(int port)
{
var ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
var activeTcpListeners = ipGlobalProperties.GetActiveTcpListeners();
return activeTcpListeners.All(endpoint => endpoint.Port != port);
}
}
}
``` |
499a558a-9757-40cc-91c5-6c313d1b4cae | {
"language": "C#"
} | ```c#
using CommentEverythingCryptography.Encryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace CEComms.Communications.Twilio.User {
public class Usage {
public double GetUsageThisMonth() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth");
UsageRecord record = totalPrice.UsageRecords[0];
return record.Usage;
}
public double GetSMSCountToday() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalSent = twilio.ListUsage("sms", "Today");
UsageRecord record = totalSent.UsageRecords[0];
return record.Usage;
}
}
}
```
Return int or decimal for usage stats | ```c#
using CommentEverythingCryptography.Encryption;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Twilio;
namespace CEComms.Communications.Twilio.User {
public class Usage {
public decimal GetUsageThisMonth() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalPrice = twilio.ListUsage("totalprice", "ThisMonth");
UsageRecord record = totalPrice.UsageRecords[0];
return (decimal) record.Usage;
}
public int GetSMSCountToday() {
IEncryptionProvider decryptor = EncryptionProviderFactory.CreateInstance(EncryptionProviderFactory.CryptographyMethod.AES);
TwilioRestClient twilio = new TwilioRestClient(decryptor.Decrypt(UserProfile.ACCOUNT_SID_CIPHER), decryptor.Decrypt(UserProfile.AUTH_TOKEN_CIPHER));
UsageResult totalSent = twilio.ListUsage("sms", "Today");
UsageRecord record = totalSent.UsageRecords[0];
return (int) Math.Round(record.Usage);
}
}
}
``` |
f5ffdf74-763d-4719-afa1-a8bee540aa3e | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace osu.Game.Rulesets.Mods
{
public interface IApplicableToAudio : IApplicableToTrack, IApplicableToSample
{
}
}
```
Add missing license header and remove unused usings | ```c#
// 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.
namespace osu.Game.Rulesets.Mods
{
public interface IApplicableToAudio : IApplicableToTrack, IApplicableToSample
{
}
}
``` |
4e972862-56d1-42a4-b1f7-646d89e5fe07 | {
"language": "C#"
} | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
namespace Glimpse
{
public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T>
{
private readonly ITypeService _typeService;
public ReflectionDiscoverableCollection(ITypeService typeService)
{
_typeService = typeService;
CoreLibarary = "Glimpse";
}
public string CoreLibarary { get; set; }
public void Discover()
{
var instances = _typeService.Resolve<T>(CoreLibarary);
AddRange(instances);
}
}
}```
Update root lib to Glimpse.Common | ```c#
using System;
using System.Collections;
using System.Collections.Generic;
namespace Glimpse
{
public class ReflectionDiscoverableCollection<T> : List<T>, IDiscoverableCollection<T>
{
private readonly ITypeService _typeService;
public ReflectionDiscoverableCollection(ITypeService typeService)
{
_typeService = typeService;
CoreLibarary = "Glimpse.Common";
}
public string CoreLibarary { get; set; }
public void Discover()
{
var instances = _typeService.Resolve<T>(CoreLibarary);
AddRange(instances);
}
}
}``` |
d71a0ff9-e793-4aa8-bbd0-12e86b65c77b | {
"language": "C#"
} | ```c#
using System;
namespace NFig
{
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class DefaultSettingValueAttribute : Attribute
{
public object DefaultValue { get; protected set; }
public object SubApp { get; protected set; }
public object Tier { get; protected set; }
public object DataCenter { get; protected set; }
public bool AllowOverrides { get; protected set; } = true;
}
}```
Add XML docs for DefaultSettingValueAttribute | ```c#
using System;
namespace NFig
{
/// <summary>
/// This is the base class for all NFig attributes which specify default values, except for the <see cref="SettingAttribute"/> itself. This attribute is
/// abstract because you should provide the attributes which make sense for your individual setup. The subApp/tier/dataCenter parameters in inheriting
/// attributes should be strongly typed (rather than using "object"), and match the generic parameters used for the NFigStore and Settings object.
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public abstract class DefaultSettingValueAttribute : Attribute
{
/// <summary>
/// The value of the default being applied. This must be either a convertable string, or a literal value whose type matches that of the setting. For
/// encrypted settings, a default value must always be an encrypted string.
/// </summary>
public object DefaultValue { get; protected set; }
/// <summary>
/// The sub-app which the default is applicable to. If null or the zero-value, it is considered applicable to the "Global" app, as well as any sub-app
/// which does not have another default applied. If your application only uses the Global app (no sub-apps), then you should not include this parameter
/// in inheriting attributes.
/// </summary>
public object SubApp { get; protected set; }
/// <summary>
/// The deployment tier (e.g. local/dev/prod) which the default is applicable to. If null or the zero-value, the default is applicable to any tier.
/// </summary>
public object Tier { get; protected set; }
/// <summary>
/// The data center which the default is applicable to. If null or the zero-value, the default is applicable to any data center.
/// </summary>
public object DataCenter { get; protected set; }
/// <summary>
/// Specifies whether NFig should accept runtime overrides for this default. Note that this only applies to environments where this particular default
/// is the active default. For example, if you set an default for Tier=Prod/DataCenter=Any which DOES NOT allow defaults, and another default for
/// Tier=Prod/DataCenter=East which DOES allow overrides, then you will be able to set overrides in Prod/East, but you won't be able to set overrides
/// in any other data center.
/// </summary>
public bool AllowOverrides { get; protected set; } = true;
}
}``` |
98efba93-8594-43a4-aa12-c430a2f879be | {
"language": "C#"
} | ```c#
using System;
namespace SteamShutdown
{
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public int State { get; set; }
/// <summary>
/// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
/// </summary>
public bool IsDownloading
{
get { return CheckDownloading(State); }
}
/// <summary>
/// Returns a value indicating whether the game is being downloaded. Includes games in queue for download.
/// </summary>
/// <param name="appState"></param>
/// <returns></returns>
public static bool CheckDownloading(int appState)
{
// 6: In queue for update
// 1026: In queue
// 1042: download running
return appState == 6 || appState == 1026 || appState == 1042 || appState == 1062 || appState == 1030;
}
public override string ToString()
{
return Name;
}
}
}
```
Check for specific bit now to check if a game is downloaded at the moment | ```c#
namespace SteamShutdown
{
public class App
{
public int ID { get; set; }
public string Name { get; set; }
public int State { get; set; }
/// <summary>
/// Returns a value indicating whether the game is being downloaded.
/// </summary>
public bool IsDownloading => CheckDownloading(State);
/// <summary>
/// Returns a value indicating whether the game is being downloaded.
/// </summary>
public static bool CheckDownloading(int appState)
{
// The second bit defines if anything for the app needs to be downloaded
// Doesn't matter if queued, download running and so on
return IsBitSet(appState, 1);
}
public override string ToString()
{
return Name;
}
private static bool IsBitSet(int b, int pos)
{
return (b & (1 << pos)) != 0;
}
}
}
``` |
5ac67f14-645f-4121-aa48-cfb49ffa1aa9 | {
"language": "C#"
} | ```c#
using System.Diagnostics;
using System.IO;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.ProjectImportArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
if (build == null)
{
build = new Build() { Succeeded = false };
build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
}
var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
if (sourceArchive == null && File.Exists(projectImportsZip))
{
sourceArchive = File.ReadAllBytes(projectImportsZip);
}
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
```
Fix a bug where it didn't read .binlog files correctly. | ```c#
using System.Diagnostics;
using System.IO;
namespace Microsoft.Build.Logging.StructuredLogger
{
public class BinaryLog
{
public static Build ReadBuild(string filePath)
{
var eventSource = new BinaryLogReplayEventSource();
byte[] sourceArchive = null;
eventSource.OnBlobRead += (kind, bytes) =>
{
if (kind == BinaryLogRecordKind.ProjectImportArchive)
{
sourceArchive = bytes;
}
};
StructuredLogger.SaveLogToDisk = false;
StructuredLogger.CurrentBuild = null;
var structuredLogger = new StructuredLogger();
structuredLogger.Parameters = "build.buildlog";
structuredLogger.Initialize(eventSource);
var sw = Stopwatch.StartNew();
eventSource.Replay(filePath);
var elapsed = sw.Elapsed;
structuredLogger.Shutdown();
var build = StructuredLogger.CurrentBuild;
StructuredLogger.CurrentBuild = null;
if (build == null)
{
build = new Build() { Succeeded = false };
build.AddChild(new Error() { Text = "Error when opening the file: " + filePath });
}
var projectImportsZip = Path.ChangeExtension(filePath, ".ProjectImports.zip");
if (sourceArchive == null && File.Exists(projectImportsZip))
{
sourceArchive = File.ReadAllBytes(projectImportsZip);
}
build.SourceFilesArchive = sourceArchive;
// build.AddChildAtBeginning(new Message { Text = "Elapsed: " + elapsed.ToString() });
return build;
}
}
}
``` |
25355a78-bd59-4f43-adff-6ce7e53a9420 | {
"language": "C#"
} | ```c#
/* Copyright 2014 Jonathan Holland.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Wave.Defaults;
namespace Wave.ServiceHosting.IIS
{
/// <summary>
/// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
/// </summary>
public class IISQueueNameResolver : DefaultQueueNameResolver
{
public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }
public override string GetPrimaryQueueName()
{
return String.Format("{0}_{1}",
base.GetPrimaryQueueName(),
Environment.MachineName);
}
}
}
```
Append IIS queues with worker PID. | ```c#
/* Copyright 2014 Jonathan Holland.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Diagnostics;
using Wave.Defaults;
namespace Wave.ServiceHosting.IIS
{
/// <summary>
/// This queue resolver tags queue names with the machine name (TEMP REMOVED UNTIL CLEANUP STRATEGY IN PLACE: and worker process Id) listening on this queue.
/// </summary>
public class IISQueueNameResolver : DefaultQueueNameResolver
{
public IISQueueNameResolver(IAssemblyLocator assemblyLocator) : base(assemblyLocator) { }
public override string GetPrimaryQueueName()
{
return String.Format("{0}_{1}_{2}",
base.GetPrimaryQueueName(),
Environment.MachineName,
Process.GetCurrentProcess().Id
);
}
}
}
``` |
8b87a64c-0b34-4e0a-8492-1f5df0b10efc | {
"language": "C#"
} | ```c#
namespace JustCli.Commands
{
public class CommandLineHelpCommand : ICommand
{
public ICommandRepository CommandRepository { get; set; }
public IOutput Output { get; set; }
public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
{
CommandRepository = commandRepository;
Output = output;
}
public bool Execute()
{
var commandsInfo = CommandRepository.GetCommandsInfo();
Output.WriteInfo("Command list:");
foreach (var commandInfo in commandsInfo)
{
Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
}
return true;
}
}
}```
Add "There are no commands". | ```c#
namespace JustCli.Commands
{
public class CommandLineHelpCommand : ICommand
{
public ICommandRepository CommandRepository { get; set; }
public IOutput Output { get; set; }
public CommandLineHelpCommand(ICommandRepository commandRepository, IOutput output)
{
CommandRepository = commandRepository;
Output = output;
}
public bool Execute()
{
var commandsInfo = CommandRepository.GetCommandsInfo();
if (commandsInfo.Count == 0)
{
Output.WriteInfo("There are no commands.");
return true;
}
Output.WriteInfo("Command list:");
foreach (var commandInfo in commandsInfo)
{
Output.WriteInfo(string.Format("{0} - {1}", commandInfo.Name, commandInfo.Description));
}
return true;
}
}
}``` |
d4586b6a-7102-46c3-a4a1-f8435097b945 | {
"language": "C#"
} | ```c#
using System;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Utils
{
public static class JTokens
{
public static JToken Null = JToken.Parse("null");
public static JToken True = JToken.Parse("true");
public static JToken False = JToken.Parse("false");
public static bool IsFalse(JToken token)
{
// A false value corresponds to any of the following conditions:
// Empty list: ``[]``
// Empty object: ``{}``
// Empty string: ``""``
// False boolean: ``false``
// Null value: ``null``
var array = token as JArray;
if (array != null && array.Count == 0)
return true;
var @object = token as JObject;
if (@object != null && @object.Count == 0)
return true;
var value = token as JValue;
if (value != null)
{
switch (token.Type)
{
case JTokenType.Bytes:
case JTokenType.Date:
case JTokenType.Guid:
case JTokenType.String:
return token.Value<String>() == "";
case JTokenType.Boolean:
return token.Value<Boolean>() == false;
case JTokenType.Null:
return true;
}
}
return false;
}
}
}```
Fix - Included some missing cases for JSON string types. | ```c#
using System;
using Newtonsoft.Json.Linq;
namespace DevLab.JmesPath.Utils
{
public static class JTokens
{
public static JToken Null = JToken.Parse("null");
public static JToken True = JToken.Parse("true");
public static JToken False = JToken.Parse("false");
public static bool IsFalse(JToken token)
{
// A false value corresponds to any of the following conditions:
// Empty list: ``[]``
// Empty object: ``{}``
// Empty string: ``""``
// False boolean: ``false``
// Null value: ``null``
var array = token as JArray;
if (array != null && array.Count == 0)
return true;
var @object = token as JObject;
if (@object != null && @object.Count == 0)
return true;
var value = token as JValue;
if (value != null)
{
switch (token.Type)
{
case JTokenType.Bytes:
case JTokenType.Date:
case JTokenType.Guid:
case JTokenType.String:
case JTokenType.TimeSpan:
case JTokenType.Uri:
return token.Value<String>() == "";
case JTokenType.Boolean:
return token.Value<Boolean>() == false;
case JTokenType.Null:
return true;
}
}
return false;
}
}
}``` |
20e9bb6b-53e3-4627-9ff3-55bfbadf94e3 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;
namespace Hadouken.Plugins.Torrents.Rpc
{
public class TorrentsServices : IJsonRpcService
{
private readonly IBitTorrentEngine _torrentEngine;
public TorrentsServices(IBitTorrentEngine torrentEngine)
{
_torrentEngine = torrentEngine;
}
[JsonRpcMethod("torrents.start")]
public bool Start(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Start();
return true;
}
[JsonRpcMethod("torrents.stop")]
public bool Stop(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Stop();
return true;
}
[JsonRpcMethod("torrents.list")]
public object List()
{
var torrents = _torrentEngine.TorrentManagers;
return (from t in torrents
select new
{
t.Torrent.Name,
t.Torrent.Size
}).ToList();
}
[JsonRpcMethod("torrents.addFile")]
public object AddFile(byte[] data, string savePath, string label)
{
var torrent = _torrentEngine.Add(data, savePath, label);
return torrent;
}
}
}
```
Return simple object representing the torrent. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Hadouken.Framework.Rpc;
using Hadouken.Plugins.Torrents.BitTorrent;
namespace Hadouken.Plugins.Torrents.Rpc
{
public class TorrentsServices : IJsonRpcService
{
private readonly IBitTorrentEngine _torrentEngine;
public TorrentsServices(IBitTorrentEngine torrentEngine)
{
_torrentEngine = torrentEngine;
}
[JsonRpcMethod("torrents.start")]
public bool Start(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Start();
return true;
}
[JsonRpcMethod("torrents.stop")]
public bool Stop(string infoHash)
{
var manager = _torrentEngine.Get(infoHash);
if (manager == null)
return false;
manager.Stop();
return true;
}
[JsonRpcMethod("torrents.list")]
public object List()
{
var torrents = _torrentEngine.TorrentManagers;
return (from t in torrents
select new
{
t.Torrent.Name,
t.Torrent.Size
}).ToList();
}
[JsonRpcMethod("torrents.addFile")]
public object AddFile(byte[] data, string savePath, string label)
{
var manager = _torrentEngine.Add(data, savePath, label);
return new
{
manager.Torrent.Name,
manager.Torrent.Size
};
}
}
}
``` |
6c04e7af-fb06-4512-9b51-c086a3efd483 | {
"language": "C#"
} | ```c#
namespace NuGet.VisualStudio {
public class PowerShellScripts {
public static readonly string Install = "install.ps1";
public static readonly string Uninstall = "uninstall.ps1";
public static readonly string Init = "init.ps1";
}
}
```
Make PowerShellScripts class static per review. | ```c#
namespace NuGet.VisualStudio {
public static class PowerShellScripts {
public static readonly string Install = "install.ps1";
public static readonly string Uninstall = "uninstall.ps1";
public static readonly string Init = "init.ps1";
}
}
``` |
163bfb2f-3b1a-4669-9d93-eed83cbebdd9 | {
"language": "C#"
} | ```c#
// Copyright(c) 2015 Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
namespace GoogleCloudSamples
{
public class Startup
{
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
```
Add a regionTag for document inclusion. | ```c#
// Copyright(c) 2015 Google Inc.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
// [START sample]
using Microsoft.AspNet.Builder;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNet.Http;
namespace GoogleCloudSamples
{
public class Startup
{
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app)
{
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
// Entry point for the application.
public static void Main(string[] args) =>
WebApplication.Run<Startup>(args);
}
}
// [END sample]``` |
783f2775-5eba-4743-9a8c-6eab4896f951 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
namespace Discord.Commands
{
public abstract class ModuleBase
{
public CommandContext Context { get; internal set; }
protected virtual async Task ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
{
await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
}
}
}
```
Update ReplyAsync Task to return the sent message. | ```c#
using System.Threading.Tasks;
namespace Discord.Commands
{
public abstract class ModuleBase
{
public CommandContext Context { get; internal set; }
protected virtual async Task<IUserMessage> ReplyAsync(string message, bool isTTS = false, RequestOptions options = null)
{
return await Context.Channel.SendMessageAsync(message, isTTS, options).ConfigureAwait(false);
}
}
}
``` |
e327a79d-9958-4f41-aa74-d3a5bfe32394 | {
"language": "C#"
} | ```c#
using UnityEngine;
using UnityEngine.UI;
public class SceneSelector : MonoBehaviour
{
[SerializeField] private Text _levelName;
[SerializeField] private string[] _levels;
[SerializeField] private Button _leftArrow;
[SerializeField] private Button _rightArrow;
private int pos = 0;
private LeaderboardUI _leaderboardUI;
private void Start()
{
_leaderboardUI = FindObjectOfType<LeaderboardUI>();
_levelName.text = _levels[pos];
_leftArrow.gameObject.SetActive(false);
if (_levels.Length <= 1) _rightArrow.gameObject.SetActive(false);
}
public void LeftArrowClick()
{
_levelName.text = _levels[--pos];
if (pos == 0) _leftArrow.gameObject.SetActive(false);
if (_levels.Length > 1) _rightArrow.gameObject.SetActive(true);
_leaderboardUI.LoadScene(_levels[pos]);
}
public void RightArrowClick()
{
_levelName.text = _levels[++pos];
if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
_leftArrow.gameObject.SetActive(true);
_leaderboardUI.LoadScene(_levels[pos]);
}
}
```
Update the level selector input at the bottom of the leaderboard | ```c#
using System;
using UnityEngine;
using UnityEngine.UI;
public class SceneSelector : MonoBehaviour
{
[SerializeField] private Text _levelName;
[SerializeField] private string[] _levels;
[SerializeField] private Button _leftArrow;
[SerializeField] private Button _rightArrow;
private int pos = 0;
private LeaderboardUI _leaderboardUI;
private void Start()
{
_leaderboardUI = FindObjectOfType<LeaderboardUI>();
var levelShown = FindObjectOfType<LevelToLoad>().GetLevelToLoad();
pos = GetPosOfLevelShown(levelShown);
_levelName.text = _levels[pos];
UpdateArrows();
}
private int GetPosOfLevelShown(string levelShown)
{
for (var i = 0; i < _levels.Length; ++i)
{
var level = _levels[i];
if (level.IndexOf(levelShown, StringComparison.InvariantCultureIgnoreCase) > -1)
return i;
}
//Defaults at loading the first entry if nothing found
return 0;
}
public void LeftArrowClick()
{
_levelName.text = _levels[--pos];
_leaderboardUI.LoadScene(_levels[pos]);
UpdateArrows();
}
public void RightArrowClick()
{
_levelName.text = _levels[++pos];
_leaderboardUI.LoadScene(_levels[pos]);
UpdateArrows();
}
private void UpdateArrows()
{
_leftArrow.gameObject.SetActive(true);
_rightArrow.gameObject.SetActive(true);
if (pos == 0) _leftArrow.gameObject.SetActive(false);
if (_levels.Length <= pos + 1)_rightArrow.gameObject.SetActive(false);
}
}
``` |
6b5930c0-7eee-4a3d-8862-3d9c66729a8d | {
"language": "C#"
} | ```c#
namespace AngleSharp
{
using System.Collections.Generic;
using System.Threading.Tasks;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
```
Use official namespace (better for fallback) | ```c#
namespace System.Threading.Tasks
{
using System.Collections.Generic;
/// <summary>
/// Simple wrapper for static methods of Task, which are missing in older
/// versions of the .NET-Framework.
/// </summary>
static class TaskEx
{
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(params Task[] tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.WhenAll, but also works with .NET 4 and SL due to
/// same naming as TaskEx in BCL.Async.
/// </summary>
public static Task WhenAll(IEnumerable<Task> tasks)
{
return Task.WhenAll(tasks);
}
/// <summary>
/// Wrapper for Task.FromResult, but also works with .NET 4 and SL due
/// to same naming as TaskEx in BCL.Async.
/// </summary>
public static Task<TResult> FromResult<TResult>(TResult result)
{
return Task.FromResult(result);
}
}
}
``` |
955326a2-958e-4ee7-bdd1-d3dfc7b92d67 | {
"language": "C#"
} | ```c#
using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class UnitService
{
public static async Task<Unit> Get(Database db, int unitId)
{
return (await List(db, includeIgnored: true)).Single(unit => unit.Id == unitId);
}
public static async Task<IEnumerable<Unit>> List(Database db, Boolean includeIgnored = false)
{
return
await db
.Units
.Include(unit => unit.Vehicles)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.ABCPs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.APFTs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.SSDSnapshots)
.Where(unit => includeIgnored || !unit.IgnoreForReports)
.OrderBy(unit => unit.Name)
.ToListAsync();
}
}
}```
Remove unit service reference to ignore for reporting | ```c#
using BatteryCommander.Web.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace BatteryCommander.Web.Services
{
public class UnitService
{
public static async Task<Unit> Get(Database db, int unitId)
{
return (await List(db)).Single(unit => unit.Id == unitId);
}
public static async Task<IEnumerable<Unit>> List(Database db)
{
return
await db
.Units
.Include(unit => unit.Vehicles)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.ABCPs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.APFTs)
.Include(unit => unit.Soldiers)
.ThenInclude(soldier => soldier.SSDSnapshots)
.OrderBy(unit => unit.Name)
.ToListAsync();
}
}
}``` |
e38af311-1aa7-48e4-bd0b-ff487499d6da | {
"language": "C#"
} | ```c#
using System;
using System.Windows.Controls;
namespace PackageExplorer {
public class PublishUrlValidationRule : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
string stringValue = (string)value;
Uri url;
if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase)) {
return ValidationResult.ValidResult;
}
else {
return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
}
}
else {
return new ValidationResult(false, "Invalid publish url.");
}
}
}
}
```
Fix binding validation which disallow publishing to HTTPS addresses. | ```c#
using System;
using System.Windows.Controls;
namespace PackageExplorer {
public class PublishUrlValidationRule : ValidationRule {
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) {
string stringValue = (string)value;
Uri url;
if (Uri.TryCreate(stringValue, UriKind.Absolute, out url)) {
if (url.Scheme.Equals(Uri.UriSchemeHttp, StringComparison.OrdinalIgnoreCase) ||
url.Scheme.Equals(Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)) {
return ValidationResult.ValidResult;
}
else {
return new ValidationResult(false, "Publish url must be an HTTP or HTTPS address.");
}
}
else {
return new ValidationResult(false, "Invalid publish url.");
}
}
}
}``` |
183c73ff-3ac5-4945-a8cb-6d1b3feddf19 | {
"language": "C#"
} | ```c#
using System;
namespace DDSReader.Console
{
class Program
{
static void Main(string[] args)
{
var dds = new DDSImage(args[0]);
dds.Save(args[1]);
}
}
}
```
Add exception handling to console | ```c#
using System;
using System.IO;
namespace DDSReader.Console
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 2)
{
System.Console.WriteLine("ERROR: input and output file required\n");
Environment.Exit(1);
}
var input = args[0];
var output = args[1];
if (!File.Exists(input))
{
System.Console.WriteLine("ERROR: input file does not exist\n");
Environment.Exit(1);
}
try
{
var dds = new DDSImage(input);
dds.Save(output);
}
catch (Exception e)
{
System.Console.WriteLine("ERROR: failed to convert DDS file\n");
System.Console.WriteLine(e);
Environment.Exit(1);
}
if (File.Exists(output))
{
System.Console.WriteLine("Successfully created " + output);
}
else
{
System.Console.WriteLine("ERROR: something went wrong!\n");
Environment.Exit(1);
}
}
}
}
``` |
eab764bb-9433-477f-809b-bed8c96aaf17 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using CIV.Common;
namespace CIV.Ccs
{
class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
protected override IEnumerable<Transition> EnumerateTransitions()
{
return new List<Transition>{
new Transition{
Label = Label,
Process = Inner
}
};
}
protected override string BuildRepr()
{
return $"{Label}{Const.prefix}{Inner}";
}
}
}
```
Use “yield” instead of List for GetTransitions | ```c#
using System;
using System.Collections.Generic;
using CIV.Common;
namespace CIV.Ccs
{
class PrefixProcess : CcsProcess
{
public String Label { get; set; }
public CcsProcess Inner { get; set; }
protected override IEnumerable<Transition> EnumerateTransitions()
{
yield return new Transition
{
Label = Label,
Process = Inner
};
}
protected override string BuildRepr()
{
return $"{Label}{Const.prefix}{Inner}";
}
}
}
``` |
e16095f6-f90e-4da7-a52e-5c296bbe331f | {
"language": "C#"
} | ```c#
using System.Net.Http;
using System.Threading.Tasks;
namespace FluentMetacritic.Net
{
public class HttpClientWrapper : IHttpClient
{
private static readonly HttpClient Client = new HttpClient();
public async Task<string> GetContentAsync(string address)
{
return await Client.GetStringAsync(address);
}
}
}```
Set UserAgent on HTTP Client. | ```c#
using System.Net.Http;
using System.Threading.Tasks;
namespace FluentMetacritic.Net
{
public class HttpClientWrapper : IHttpClient
{
private static readonly HttpClient Client;
static HttpClientWrapper()
{
Client = new HttpClient();
Client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.11 Safari/537.36");
}
public async Task<string> GetContentAsync(string address)
{
return await Client.GetStringAsync(address);
}
}
}``` |
481b6d5b-8f57-4289-82d7-0456ffa30545 | {
"language": "C#"
} | ```c#
namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System.Linq.Expressions;
using DataSources;
using Extensions;
using Members;
internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
{
public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();
public IDataSource Create(IMemberMappingData mappingData)
=> mappingData.MapperData.TargetMember.IsReadable
? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
: DefaultValueDataSourceFactory.Instance.Create(mappingData);
private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
{
public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
: base(mapperData.SourceMember, GetValue(mapperData), mapperData)
{
}
private static Expression GetValue(IMemberMapperData mapperData)
{
var existingValue = mapperData.GetTargetMemberAccess();
if (!mapperData.TargetMember.IsEnumerable)
{
return existingValue;
}
var existingValueNotNull = existingValue.GetIsNotDefaultComparison();
var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();
return Expression.Condition(
existingValueNotNull,
existingValue,
emptyEnumerable,
existingValue.Type);
}
}
}
}```
Revert "Using ternary instead of coalesce in fallback enumerable value selection" | ```c#
namespace AgileObjects.AgileMapper.ObjectPopulation
{
using System.Linq.Expressions;
using DataSources;
using Members;
internal class ExistingOrDefaultValueDataSourceFactory : IDataSourceFactory
{
public static readonly IDataSourceFactory Instance = new ExistingOrDefaultValueDataSourceFactory();
public IDataSource Create(IMemberMappingData mappingData)
=> mappingData.MapperData.TargetMember.IsReadable
? new ExistingMemberValueOrEmptyDataSource(mappingData.MapperData)
: DefaultValueDataSourceFactory.Instance.Create(mappingData);
private class ExistingMemberValueOrEmptyDataSource : DataSourceBase
{
public ExistingMemberValueOrEmptyDataSource(IMemberMapperData mapperData)
: base(mapperData.SourceMember, GetValue(mapperData), mapperData)
{
}
private static Expression GetValue(IMemberMapperData mapperData)
{
var existingValue = mapperData.GetTargetMemberAccess();
if (!mapperData.TargetMember.IsEnumerable)
{
return existingValue;
}
var emptyEnumerable = mapperData.TargetMember.GetEmptyInstanceCreation();
return Expression.Coalesce(existingValue, emptyEnumerable);
}
}
}
}``` |
6f88636f-3242-4481-8dde-dd2808761dd5 | {
"language": "C#"
} | ```c#
using BeekmanLabs.UnitTesting;
using IntegrationEngine.JobProcessor;
using NUnit.Framework;
using Moq;
using System;
using System.Threading;
namespace IntegrationEngine.Tests.JobProcessor
{
public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager>
{
public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; }
[SetUp]
public void Setup()
{
MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>();
MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener())
.Returns<IMessageQueueListener>(null);
Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object;
}
[Test]
public void ShouldStartListener()
{
Subject.ListenerTaskCount = 1;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once);
}
[Test]
public void ShouldStartMultipleListeners()
{
var listenerTaskCount = 3;
Subject.ListenerTaskCount = listenerTaskCount;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(),
Times.Exactly(listenerTaskCount));
}
[Test]
public void ShouldSetCancellationTokenOnDispose()
{
Subject.CancellationTokenSource = new CancellationTokenSource();
Subject.Dispose();
Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True);
}
}
}
```
Test launching 10 listeners in CI | ```c#
using BeekmanLabs.UnitTesting;
using IntegrationEngine.JobProcessor;
using NUnit.Framework;
using Moq;
using System;
using System.Threading;
namespace IntegrationEngine.Tests.JobProcessor
{
public class MessageQueueListenerManagerTest : TestBase<MessageQueueListenerManager>
{
public Mock<MessageQueueListenerFactory> MockMessageQueueListenerFactory { get; set; }
[SetUp]
public void Setup()
{
MockMessageQueueListenerFactory = new Mock<MessageQueueListenerFactory>();
MockMessageQueueListenerFactory.Setup(x => x.CreateRabbitMQListener())
.Returns<IMessageQueueListener>(null);
Subject.MessageQueueListenerFactory = MockMessageQueueListenerFactory.Object;
}
[Test]
public void ShouldStartListener()
{
Subject.ListenerTaskCount = 1;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(), Times.Once);
}
[Test]
public void ShouldStartMultipleListeners()
{
var listenerTaskCount = 10;
Subject.ListenerTaskCount = listenerTaskCount;
Subject.StartListener();
MockMessageQueueListenerFactory.Verify(x => x.CreateRabbitMQListener(),
Times.Exactly(listenerTaskCount));
}
[Test]
public void ShouldSetCancellationTokenOnDispose()
{
Subject.CancellationTokenSource = new CancellationTokenSource();
Subject.Dispose();
Assert.That(Subject.CancellationTokenSource.IsCancellationRequested, Is.True);
}
}
}
``` |
da82f734-4a35-473b-8042-ec6afb84da59 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Basic;
using Newtonsoft.Json;
/// <summary>
/// A collection of images for a Trakt season.
/// </summary>
public class TraktSeasonImages
{
/// <summary>
/// A poster image set for various sizes.
/// </summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>
/// A thumbnail image.
/// </summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
```
Add get best id method for season images. | ```c#
namespace TraktApiSharp.Objects.Get.Shows.Seasons
{
using Basic;
using Newtonsoft.Json;
/// <summary>A collection of images and image sets for a Trakt season.</summary>
public class TraktSeasonImages
{
/// <summary>Gets or sets the screenshot image set.</summary>
[JsonProperty(PropertyName = "poster")]
public TraktImageSet Poster { get; set; }
/// <summary>Gets or sets the thumb image.</summary>
[JsonProperty(PropertyName = "thumb")]
public TraktImage Thumb { get; set; }
}
}
``` |
4a564c13-e926-408b-814e-ecc04384cc5e | {
"language": "C#"
} | ```c#
using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ZoneDefinition]
public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone>
{
}
[SetUpFixture]
public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone>
{
}
}
```
Fix test data path when building in Unity plugin | ```c#
using JetBrains.Application.BuildScript.Application.Zones;
using JetBrains.ReSharper.TestFramework;
using JetBrains.TestFramework;
using JetBrains.TestFramework.Application.Zones;
using NUnit.Framework;
[assembly: RequiresSTA]
// This attribute is marked obsolete but is still supported. Use is discouraged in preference to convention, but the
// convention doesn't work for us. That convention is to walk up the tree from the executing assembly and look for a
// relative path called "test/data". This doesn't work because our common "build" folder is one level above our
// "test/data" folder, so it doesn't get found. We want to keep the common "build" folder, but allow multiple "modules"
// with separate "test/data" folders. E.g. "resharper-unity" and "resharper-yaml"
// TODO: This makes things work when building as part of the Unity project, but breaks standalone
// Maybe it should be using product/subplatform markers?
#pragma warning disable 618
[assembly: TestDataPathBase("resharper-yaml/test/data")]
#pragma warning restore 618
namespace JetBrains.ReSharper.Plugins.Yaml.Tests
{
[ZoneDefinition]
public interface IYamlTestZone : ITestsEnvZone, IRequire<PsiFeatureTestZone>
{
}
[SetUpFixture]
public class TestEnvironment : ExtensionTestEnvironmentAssembly<IYamlTestZone>
{
}
}
``` |
196f0b52-e29d-4f7d-b09e-7ac6b5374a4a | {
"language": "C#"
} | ```c#
using Newtonsoft.Json;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class ResponseAnswer
{
public long? ChoiceId { get; set; }
public long? RowId { get; set; }
public long? ColId { get; set; }
public long? OtherId { get; set; }
public string Text { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public string SimpleText { get; set; }
[JsonIgnore]
internal object TagData { get; set; }
public ChoiceMetadata ChoiceMetadata { get; set; }
}
}```
Add download_url and content_type for file upload questions | ```c#
using Newtonsoft.Json;
namespace SurveyMonkey.Containers
{
[JsonConverter(typeof(TolerantJsonConverter))]
public class ResponseAnswer
{
public long? ChoiceId { get; set; }
public long? RowId { get; set; }
public long? ColId { get; set; }
public long? OtherId { get; set; }
public string Text { get; set; }
public bool? IsCorrect { get; set; }
public int? Score { get; set; }
public string DownloadUrl { get; set; }
public string ContentType { get; set; }
public string SimpleText { get; set; }
[JsonIgnore]
internal object TagData { get; set; }
public ChoiceMetadata ChoiceMetadata { get; set; }
}
}``` |
3af1b7c7-d7ee-40c6-abb9-44098bf089c9 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPAppStudio.Services.Interfaces;
namespace WPAppStudio.Services
{
public class WordWrapService
{
private readonly ITextMeasurementService _tms;
public WordWrapService(ITextMeasurementService textMeasurementService)
{
_tms = textMeasurementService;
}
public string GetWords(string text, int wordCount)
{
StringBuilder result = new StringBuilder();
for (int word = 0; word < wordCount; word++)
{
int space = text.IndexOf(' ', 1);
//return text.Substring(0, space);
if (space == -1)
{
result.Append(text);
return result.ToString();
}
result.Append(text.Substring(0, space));
text = text.Substring(space);
}
return result.ToString();
}
public string GetLine(string text, int lineLength)
{
for (int wordCount = 10; wordCount > 0; wordCount--)
{
string line = GetWords(text, wordCount);
int width = _tms.GetTextWidth(line);
if (width <= lineLength)
{
return line;
}
}
return GetWords(text, 1);
}
}
}
```
Revert "And we have the medium line working!" | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WPAppStudio.Services.Interfaces;
namespace WPAppStudio.Services
{
public class WordWrapService
{
private readonly ITextMeasurementService _tms;
public WordWrapService(ITextMeasurementService textMeasurementService)
{
_tms = textMeasurementService;
}
public string GetWords(string text, int wordCount)
{
StringBuilder result = new StringBuilder();
for (int word = 0; word < wordCount; word++)
{
int space = text.IndexOf(' ', 1);
//return text.Substring(0, space);
if (space == -1)
{
result.Append(text);
return result.ToString();
}
result.Append(text.Substring(0, space));
text = text.Substring(space);
}
return result.ToString();
}
public string GetLine(string text, int lineLength)
{
string line = GetWords(text, 3);
int width = _tms.GetTextWidth(line);
if (width <= lineLength)
{
return line;
}
return GetWords(text, 1);
}
}
}
``` |
257d15f7-0adb-4084-8345-2eee90343275 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotal<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
```
Revert "Removing 'zzz' from method name" | ```c#
using System;
using System.Linq;
namespace Smartrak.Collections.Paging
{
public static class PagingHelpers
{
/// <summary>
/// Gets a paged list of entities with the total appended to each row in the resultset. This is a faster way of doing things than using 2 seperate queries
/// </summary>
/// <typeparam name="T">The type of the entity, can be inferred by the type of queryable you pass</typeparam>
/// <param name="entities">A queryable of entities</param>
/// <param name="page">the 1 indexed page number you are interested in, cannot be zero or negative</param>
/// <param name="pageSize">the size of the page you want, cannot be zero or negative</param>
/// <returns>A queryable of the page of entities with counts appended.</returns>
public static IQueryable<EntityWithCount<T>> GetPageWithTotalzzz<T>(this IQueryable<T> entities, int page, int pageSize) where T : class
{
if (entities == null)
{
throw new ArgumentNullException("entities");
}
if (page < 1)
{
throw new ArgumentException("Must be positive", "page");
}
if (pageSize < 1)
{
throw new ArgumentException("Must be positive", "pageSize");
}
return entities
.Select(e => new EntityWithCount<T> { Entity = e, Count = entities.Count() })
.Skip(page - 1 * pageSize)
.Take(pageSize);
}
}
}
``` |
5306f397-f65f-4c6b-8bae-862a8444a962 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace ProcessRelauncher
{
public class ProcessMonitor : IDisposable
{
private Timer _timer;
private readonly int _monitoringPollingIntervalMs;
private readonly ProcessStartInfo _processStartInfo;
private readonly string _processName;
public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs)
{
_processStartInfo = launcher;
_processName = processName.ToLower();
_monitoringPollingIntervalMs = monitoringPollingIntervalMs;
}
public void Monitor(object o)
{
Process[] processlist = Process.GetProcesses();
foreach(var p in processlist)
{
if (p.ProcessName.ToLower().Equals(_processName)) return;
}
Process.Start(_processStartInfo);
GC.Collect();
}
public void Start()
{
if (_timer != null) return;
_timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs);
}
public void Dispose()
{
_timer.Dispose();
}
}
}```
Enable the GC to clean up the process list immediately. Fixed potential null reference when disposing before starting. | ```c#
using System;
using System.Diagnostics;
using System.Threading;
namespace ProcessRelauncher
{
public class ProcessMonitor : IDisposable
{
private Timer _timer;
private readonly int _monitoringPollingIntervalMs;
private readonly ProcessStartInfo _processStartInfo;
private readonly string _processName;
public ProcessMonitor(string processName, ProcessStartInfo launcher, int monitoringPollingIntervalMs)
{
_processStartInfo = launcher;
_processName = processName.ToLower();
_monitoringPollingIntervalMs = monitoringPollingIntervalMs;
}
public void Monitor(object o)
{
Process[] processlist = Process.GetProcesses();
foreach (var p in processlist)
{
if (p.ProcessName.ToLower().Equals(_processName)) return;
}
Process.Start(_processStartInfo);
processlist = null;
GC.Collect();
}
public void Start()
{
if (_timer != null) return;
_timer = new Timer(this.Monitor, null, 0, _monitoringPollingIntervalMs);
}
public void Dispose()
{
if (_timer == null) return;
_timer.Dispose();
}
}
}``` |
4381353f-e70d-4dee-a433-8cce843eeb5c | {
"language": "C#"
} | ```c#
using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
Table table = new Table(2, 3);
string output = table.Draw();
Console.WriteLine(output);
}
}
}
```
Comment out the code in Hangman that uses Table | ```c#
using System;
namespace Hangman {
public class Hangman {
public static void Main(string[] args) {
// Table table = new Table(2, 3);
// string output = table.Draw();
// Console.WriteLine(output);
}
}
}
``` |
1a26ebde-fa5e-491f-af93-f8fe4bd37028 | {
"language": "C#"
} | ```c#
namespace BaiduHiCrawler
{
using System;
static class Constants
{
public const string CommentRetrivalUrlPattern =
"http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog";
public const string LocalArchiveFolder = @".\Archive\";
public const string LogsFolder = @".\Logs\";
public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login");
public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home");
public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
public static readonly LogLevel LogLevel = LogLevel.Verbose;
}
}
```
Set LogLevel in master branch to Warning | ```c#
namespace BaiduHiCrawler
{
using System;
static class Constants
{
public const string CommentRetrivalUrlPattern =
"http://hi.baidu.com/qcmt/data/cmtlist?qing_request_source=new_request&thread_id_enc={0}&start={1}&count={2}&orderby_type=0&favor=2&type=smblog";
public const string LocalArchiveFolder = @".\Archive\";
public const string LogsFolder = @".\Logs\";
public static readonly Uri LoginUri = new Uri("http://hi.baidu.com/go/login");
public static readonly Uri HomeUri = new Uri("http://hi.baidu.com/home");
public static readonly DateTime CommentBaseDateTime = new DateTime(1970, 1, 1, 0, 0, 0);
public static readonly LogLevel LogLevel = LogLevel.Warning;
}
}
``` |
0f3c9caf-de65-41b4-9c89-de1a027bfe55 | {
"language": "C#"
} | ```c#
using System.Collections.Generic;
using Rocket.API;
using RocketRegions.Model;
namespace RocketRegions
{
public class RegionsConfiguration : IRocketPluginConfiguration
{
public int UpdateFrameCount;
public List<Region> Regions;
public string UrlOpenMessage;
public void LoadDefaults()
{
Regions = new List<Region>();
UpdateFrameCount = 1;
UrlOpenMessage = "Visit webpage";
}
}
}
```
Set default <UpdateFrameCount> to 10 | ```c#
using System.Collections.Generic;
using Rocket.API;
using RocketRegions.Model;
namespace RocketRegions
{
public class RegionsConfiguration : IRocketPluginConfiguration
{
public int UpdateFrameCount;
public List<Region> Regions;
public string UrlOpenMessage;
public void LoadDefaults()
{
Regions = new List<Region>();
UpdateFrameCount = 10;
UrlOpenMessage = "Visit webpage";
}
}
}
``` |
506b077c-af1e-48fc-860d-1c5433c70cb5 | {
"language": "C#"
} | ```c#
using System.ComponentModel;
using System.Windows;
namespace DesktopWidgets.Actions
{
internal class PopupAction : ActionBase
{
[DisplayName("Text")]
public string Text { get; set; } = "";
[DisplayName("Title")]
public string Title { get; set; } = "";
[DisplayName("Image")]
public MessageBoxImage Image { get; set; }
protected override void ExecuteAction()
{
base.ExecuteAction();
MessageBox.Show(Text, Title, MessageBoxButton.OK, Image);
}
}
}```
Add "Input Mode", "File" options to "Popup" action | ```c#
using System.ComponentModel;
using System.IO;
using System.Windows;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Actions
{
internal class PopupAction : ActionBase
{
public FilePath FilePath { get; set; } = new FilePath();
[DisplayName("Text")]
public string Text { get; set; } = "";
[DisplayName("Input Mode")]
public InputMode InputMode { get; set; } = InputMode.Text;
[DisplayName("Title")]
public string Title { get; set; } = "";
[DisplayName("Image")]
public MessageBoxImage Image { get; set; }
protected override void ExecuteAction()
{
base.ExecuteAction();
var input = string.Empty;
switch (InputMode)
{
case InputMode.Clipboard:
input = Clipboard.GetText();
break;
case InputMode.File:
input = File.ReadAllText(FilePath.Path);
break;
case InputMode.Text:
input = Text;
break;
}
MessageBox.Show(input, Title, MessageBoxButton.OK, Image);
}
}
}``` |
c0c4ccc5-e1f2-46d2-a7f3-7e3554648696 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace GarrysMod.AddonCreator
{
public class AddonJson
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; }
[JsonProperty("ignore")]
public List<string> Ignores { get; set; }
public void CheckForErrors()
{
if (string.IsNullOrEmpty(Title))
{
throw new MissingFieldException("Title is empty or not specified.");
}
if (!string.IsNullOrEmpty(Description) && Description.Contains('\0'))
{
throw new InvalidDataException("Description contains NULL character.");
}
if (string.IsNullOrEmpty(Type))
{
throw new MissingFieldException("Type is empty or not specified.");
}
}
public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files)
{
foreach (var key in files.Keys.ToArray())
// ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts
{
if (Ignores.Any(w => w.WildcardRegex().IsMatch(key)))
files.Remove(key);
}
}
}
}
```
Add version field and make CheckForErrors less accessible from outside. | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace GarrysMod.AddonCreator
{
public class AddonJson
{
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("tags")]
public List<string> Tags { get; set; }
[JsonProperty("ignore")]
public List<string> Ignores { get; set; }
[JsonProperty("version")]
public int Version { get; set; }
internal void CheckForErrors()
{
if (string.IsNullOrEmpty(Title))
{
throw new MissingFieldException("Title is empty or not specified.");
}
if (!string.IsNullOrEmpty(Description) && Description.Contains('\0'))
{
throw new InvalidDataException("Description contains NULL character.");
}
if (string.IsNullOrEmpty(Type))
{
throw new MissingFieldException("Type is empty or not specified.");
}
}
public void RemoveIgnoredFiles(ref Dictionary<string, AddonFileInfo> files)
{
foreach (var key in files.Keys.ToArray())
// ToArray makes a shadow copy of Keys to avoid "mid-loop-removal" conflicts
{
if (Ignores.Any(w => w.WildcardRegex().IsMatch(key)))
files.Remove(key);
}
}
}
}
``` |
d6ebcb63-f7f6-4fb4-8991-1a6c5db9ad27 | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using Xamarin.Forms;
using InteractApp;
namespace InteractApp
{
public class EventListPageBase : ViewPage<EventListPageViewModel>
{
}
public partial class EventListPage : EventListPageBase
{
public EventListPage ()
{
InitializeComponent ();
this.Title = "Events";
Padding = new Thickness (0, 0, 0, 0);
ToolbarItems.Add (new ToolbarItem {
Text = "My Info",
Order = ToolbarItemOrder.Primary,
Command = new Command (this.ShowMyInfoPage),
});
ToolbarItems.Add (new ToolbarItem {
Text = "My Events",
Order = ToolbarItemOrder.Primary,
});
//To hide iOS list seperator
EventList.SeparatorVisibility = SeparatorVisibility.None;
ViewModel.LoadEventsCommand.Execute (null);
EventList.ItemTapped += async (sender, e) => {
Event evt = (Event)e.Item;
Debug.WriteLine ("Tapped: " + (evt.Name));
var page = new EventInfoPage (evt);
((ListView)sender).SelectedItem = null;
await Navigation.PushAsync (page);
};
}
private void ShowMyInfoPage ()
{
Navigation.PushAsync (new MyInfoPage ());
}
}
}
```
Remove unused Toolbar options until we actually make use of them | ```c#
using System;
using System.Diagnostics;
using Xamarin.Forms;
using InteractApp;
namespace InteractApp
{
public class EventListPageBase : ViewPage<EventListPageViewModel>
{
}
public partial class EventListPage : EventListPageBase
{
public EventListPage ()
{
InitializeComponent ();
this.Title = "Events";
Padding = new Thickness (0, 0, 0, 0);
// ToolbarItems.Add (new ToolbarItem {
// Text = "My Info",
// Order = ToolbarItemOrder.Primary,
// Command = new Command (this.ShowMyInfoPage),
// });
// ToolbarItems.Add (new ToolbarItem {
// Text = "My Events",
// Order = ToolbarItemOrder.Primary,
// });
//To hide iOS list seperator
EventList.SeparatorVisibility = SeparatorVisibility.None;
ViewModel.LoadEventsCommand.Execute (null);
EventList.ItemTapped += async (sender, e) => {
Event evt = (Event)e.Item;
Debug.WriteLine ("Tapped: " + (evt.Name));
var page = new EventInfoPage (evt);
((ListView)sender).SelectedItem = null;
await Navigation.PushAsync (page);
};
}
private void ShowMyInfoPage ()
{
Navigation.PushAsync (new MyInfoPage ());
}
}
}
``` |
51d48ead-eace-4797-8499-cc04fe7833de | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PolarisServer.Packets;
namespace PolarisServer.Models
{
public class PSOObject
{
public struct PSOObjectThing
{
public UInt32 data;
}
public EntityHeader Header { get; set; }
public MysteryPositions Position { get; set; }
public string Name { get; set; }
public UInt32 ThingFlag { get; set; }
public PSOObjectThing[] things { get; set; }
public byte[] GenerateSpawnBlob()
{
PacketWriter writer = new PacketWriter();
writer.WriteStruct(Header);
writer.WriteStruct(Position);
writer.Seek(2, SeekOrigin.Current); // Padding I guess...
writer.WriteFixedLengthASCII(Name, 0x34);
writer.Write(ThingFlag);
writer.Write(things.Length);
foreach (PSOObjectThing thing in things)
{
writer.WriteStruct(thing);
}
return writer.ToArray();
}
}
}
```
Write Position using the Position Writer Function | ```c#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using PolarisServer.Packets;
namespace PolarisServer.Models
{
public class PSOObject
{
public struct PSOObjectThing
{
public UInt32 data;
}
public EntityHeader Header { get; set; }
public MysteryPositions Position { get; set; }
public string Name { get; set; }
public UInt32 ThingFlag { get; set; }
public PSOObjectThing[] things { get; set; }
public byte[] GenerateSpawnBlob()
{
PacketWriter writer = new PacketWriter();
writer.WriteStruct(Header);
writer.Write(Position);
writer.Seek(2, SeekOrigin.Current); // Padding I guess...
writer.WriteFixedLengthASCII(Name, 0x34);
writer.Write(ThingFlag);
writer.Write(things.Length);
foreach (PSOObjectThing thing in things)
{
writer.WriteStruct(thing);
}
return writer.ToArray();
}
}
}
``` |
95daf8ad-59ba-4afd-b5b2-bbe4851182d0 | {
"language": "C#"
} | ```c#
using System;
using System.IO;
using System.Linq;
using Villermen.RuneScapeCacheTools.Audio.Vorbis;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
public class VorbisTests : IDisposable
{
private ITestOutputHelper Output { get; }
private VorbisReader Reader1 { get; }
private VorbisReader Reader2 { get; }
private VorbisWriter Writer { get; }
public VorbisTests(ITestOutputHelper output)
{
Output = output;
Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg"));
Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg"));
Writer = new VorbisWriter(File.OpenWrite("out.ogg"));
}
[Fact]
public void TestReadComments()
{
Reader1.ReadPacket();
var commentPacket = Reader1.ReadPacket();
Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}");
Assert.IsType<VorbisCommentHeader>(commentPacket);
var commentHeader = (VorbisCommentHeader)commentPacket;
Output.WriteLine("Comments in header:");
foreach (var userComment in commentHeader.UserComments)
{
Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}");
}
Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("genre", "Soundtrack")));
}
public void Dispose()
{
Reader1?.Dispose();
Reader2?.Dispose();
Writer?.Dispose();
}
}
}```
Change comment test to reflect changed samples | ```c#
using System;
using System.IO;
using System.Linq;
using Villermen.RuneScapeCacheTools.Audio.Vorbis;
using Xunit;
using Xunit.Abstractions;
namespace RuneScapeCacheToolsTests
{
public class VorbisTests : IDisposable
{
private ITestOutputHelper Output { get; }
private VorbisReader Reader1 { get; }
private VorbisReader Reader2 { get; }
private VorbisWriter Writer { get; }
public VorbisTests(ITestOutputHelper output)
{
Output = output;
Reader1 = new VorbisReader(File.OpenRead("testdata/sample1.ogg"));
Reader2 = new VorbisReader(File.OpenRead("testdata/sample2.ogg"));
Writer = new VorbisWriter(File.OpenWrite("out.ogg"));
}
[Fact]
public void TestReadComments()
{
Reader1.ReadPacket();
var commentPacket = Reader1.ReadPacket();
Output.WriteLine($"Type of packet: {commentPacket.GetType().FullName}");
Assert.IsType<VorbisCommentHeader>(commentPacket);
var commentHeader = (VorbisCommentHeader)commentPacket;
Output.WriteLine("Comments in header:");
foreach (var userComment in commentHeader.UserComments)
{
Output.WriteLine($" - {userComment.Item1}: {userComment.Item2}");
}
Assert.True(commentHeader.UserComments.Contains(new Tuple<string, string>("DATE", "2012")));
}
public void Dispose()
{
Reader1?.Dispose();
Reader2?.Dispose();
Writer?.Dispose();
}
}
}``` |
1454f84f-b7fa-49f7-b6b8-e76644de4139 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using DAQ.Environment;
namespace DAQ.HAL
{
public class Agilent53131A : FrequencyCounter
{
public Agilent53131A(String visaAddress) : base(visaAddress)
{}
public override double Frequency
{
get
{
if (!Environs.Debug)
{
Write(":FUNC 'FREQ 1'");
Write(":FREQ:ARM:STAR:SOUR IMM");
Write(":FREQ:ARM:STOP:SOUR TIM");
Write(":FREQ:ARM:STOP:TIM 1.0");
Write("READ:FREQ?");
string fr = Read();
return Double.Parse(fr);
}
else
{
return 170.730 + (new Random()).NextDouble();
}
}
}
public override double Amplitude
{
get { throw new Exception("The method or operation is not implemented."); }
}
}
}
```
Fix a little bug with the new counter. The rf frequency measurement is now tested and works. | ```c#
using System;
using System.Collections.Generic;
using System.Text;
using DAQ.Environment;
namespace DAQ.HAL
{
public class Agilent53131A : FrequencyCounter
{
public Agilent53131A(String visaAddress) : base(visaAddress)
{}
public override double Frequency
{
get
{
if (!Environs.Debug)
{
Connect();
Write(":FUNC 'FREQ 1'");
Write(":FREQ:ARM:STAR:SOUR IMM");
Write(":FREQ:ARM:STOP:SOUR TIM");
Write(":FREQ:ARM:STOP:TIM 1.0");
Write("READ:FREQ?");
string fr = Read();
Disconnect();
return Double.Parse(fr);
}
else
{
return 170.730 + (new Random()).NextDouble();
}
}
}
public override double Amplitude
{
get { throw new Exception("The method or operation is not implemented."); }
}
}
}
``` |
b8fe2462-cbf3-4760-bbca-442712f82ffe | {
"language": "C#"
} | ```c#
@model Vaskelista.Models.Household
@{
ViewBag.Title = "Create";
}
<h2>Velkommen til vaskelista</h2>
<p>Her kan du velge hva vaskelisten din skal hete:</p>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-12"><label>@Request.Url.ToString()</label></div>
<div class="col-md-12">
<ul class="form-option-list">
@foreach (string randomUrl in ViewBag.RandomUrls)
{
<li>
@using (Html.BeginForm("Create", "Household", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Token, new { Value = randomUrl })
<input type="submit" value="@randomUrl" class="btn btn-default" />
}
</li>
}
</ul>
</div>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
```
Decrease bootstrap column sizes to improve mobile experience | ```c#
@model Vaskelista.Models.Household
@{
ViewBag.Title = "Create";
}
<h2>Velkommen til vaskelista</h2>
<p>Her kan du velge hva vaskelisten din skal hete:</p>
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-2"><label>@Request.Url.ToString()</label></div>
<div class="col-md-4">
<ul class="form-option-list">
@foreach (string randomUrl in ViewBag.RandomUrls)
{
<li>
@using (Html.BeginForm("Create", "Household", FormMethod.Post))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(model => model.Token, new { Value = randomUrl })
<input type="submit" value="@randomUrl" class="btn btn-default" />
}
</li>
}
</ul>
</div>
</div>
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
``` |
f47f4a53-f9a4-4e11-b32b-fcc31fb6a936 | {
"language": "C#"
} | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte Unknown1;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.Unknown1 = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
```
Rename previously unknown GAF field | ```c#
namespace TAUtil.Gaf.Structures
{
using System.IO;
public struct GafFrameData
{
public ushort Width;
public ushort Height;
public ushort XPos;
public ushort YPos;
public byte TransparencyIndex;
public bool Compressed;
public ushort FramePointers;
public uint Unknown2;
public uint PtrFrameData;
public uint Unknown3;
public static void Read(BinaryReader b, ref GafFrameData e)
{
e.Width = b.ReadUInt16();
e.Height = b.ReadUInt16();
e.XPos = b.ReadUInt16();
e.YPos = b.ReadUInt16();
e.TransparencyIndex = b.ReadByte();
e.Compressed = b.ReadBoolean();
e.FramePointers = b.ReadUInt16();
e.Unknown2 = b.ReadUInt32();
e.PtrFrameData = b.ReadUInt32();
e.Unknown3 = b.ReadUInt32();
}
}
}
``` |
636ec65b-d8c8-4561-961a-4e8f6e6899e1 | {
"language": "C#"
} | ```c#
// 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.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Timing
{
internal class SampleSection : Section<SampleControlPoint>
{
private LabelledTextBox bank;
private SliderWithTextBoxInput<int> volume;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new Drawable[]
{
bank = new LabelledTextBox
{
Label = "Bank Name",
},
volume = new SliderWithTextBoxInput<int>("Volume")
{
Current = new SampleControlPoint().SampleVolumeBindable,
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point)
{
if (point.NewValue != null)
{
bank.Current = point.NewValue.SampleBankBindable;
volume.Current = point.NewValue.SampleVolumeBindable;
}
}
protected override SampleControlPoint CreatePoint()
{
var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time);
return new SampleControlPoint
{
SampleBank = reference.SampleBank,
SampleVolume = reference.SampleVolume,
};
}
}
}
```
Add change handling for sample section | ```c#
// 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.Bindables;
using osu.Framework.Graphics;
using osu.Game.Beatmaps.ControlPoints;
using osu.Game.Graphics.UserInterfaceV2;
namespace osu.Game.Screens.Edit.Timing
{
internal class SampleSection : Section<SampleControlPoint>
{
private LabelledTextBox bank;
private SliderWithTextBoxInput<int> volume;
[BackgroundDependencyLoader]
private void load()
{
Flow.AddRange(new Drawable[]
{
bank = new LabelledTextBox
{
Label = "Bank Name",
},
volume = new SliderWithTextBoxInput<int>("Volume")
{
Current = new SampleControlPoint().SampleVolumeBindable,
}
});
}
protected override void OnControlPointChanged(ValueChangedEvent<SampleControlPoint> point)
{
if (point.NewValue != null)
{
bank.Current = point.NewValue.SampleBankBindable;
bank.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
volume.Current = point.NewValue.SampleVolumeBindable;
volume.Current.BindValueChanged(_ => ChangeHandler?.SaveState());
}
}
protected override SampleControlPoint CreatePoint()
{
var reference = Beatmap.Value.Beatmap.ControlPointInfo.SamplePointAt(SelectedGroup.Value.Time);
return new SampleControlPoint
{
SampleBank = reference.SampleBank,
SampleVolume = reference.SampleVolume,
};
}
}
}
``` |
3aa374ad-f819-4c8e-aeef-fe8e153702b8 | {
"language": "C#"
} | ```c#
using System;
using NServiceBus;
using SFA.DAS.AutoConfiguration;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.Notifications.Messages.Commands;
using SFA.DAS.NServiceBus.Configuration.AzureServiceBus;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.Extensions
{
public static class EndpointConfigurationExtensions
{
public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container)
{
var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL);
if (isDevelopment)
{
var transport = config.UseTransport<LearningTransport>();
transport.Transactions(TransportTransactionMode.ReceiveOnly);
ConfigureRouting(transport.Routing());
}
else
{
config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting);
}
return config;
}
private static void ConfigureRouting(RoutingSettings routing)
{
routing.RouteToEndpoint(
typeof(ImportLevyDeclarationsCommand).Assembly,
typeof(ImportLevyDeclarationsCommand).Namespace,
"SFA.DAS.EmployerFinance.MessageHandlers"
);
routing.RouteToEndpoint(
typeof(SendEmailCommand).Assembly,
typeof(SendEmailCommand).Namespace,
"SFA.DAS.Notifications.MessageHandlers"
);
}
}
}```
Tweak conventions for nservicebus messages to work in unobtrusive and normal mode | ```c#
using System;
using NServiceBus;
using SFA.DAS.AutoConfiguration;
using SFA.DAS.EmployerFinance.Messages.Commands;
using SFA.DAS.Notifications.Messages.Commands;
using SFA.DAS.NServiceBus.Configuration.AzureServiceBus;
using StructureMap;
namespace SFA.DAS.EmployerAccounts.Extensions
{
public static class EndpointConfigurationExtensions
{
public static EndpointConfiguration UseAzureServiceBusTransport(this EndpointConfiguration config, Func<string> connectionStringBuilder, IContainer container)
{
var isDevelopment = container.GetInstance<IEnvironmentService>().IsCurrent(DasEnv.LOCAL);
if (isDevelopment)
{
var transport = config.UseTransport<LearningTransport>();
transport.Transactions(TransportTransactionMode.ReceiveOnly);
ConfigureRouting(transport.Routing());
}
else
{
config.UseAzureServiceBusTransport(connectionStringBuilder(), ConfigureRouting);
var conventions = config.Conventions();
conventions.DefiningCommandsAs(type =>
{
return type.Namespace == typeof(SendEmailCommand).Namespace || type.Namespace == typeof(ImportLevyDeclarationsCommand).Namespace;
});
}
return config;
}
private static void ConfigureRouting(RoutingSettings routing)
{
routing.RouteToEndpoint(
typeof(ImportLevyDeclarationsCommand).Assembly,
typeof(ImportLevyDeclarationsCommand).Namespace,
"SFA.DAS.EmployerFinance.MessageHandlers"
);
routing.RouteToEndpoint(
typeof(SendEmailCommand).Assembly,
typeof(SendEmailCommand).Namespace,
"SFA.DAS.Notifications.MessageHandlers"
);
}
}
}``` |
7f0d8016-f7aa-4a6b-bef2-dc35dce8f13b | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using Flood.Editor.Server;
namespace Flood.Editor
{
public class ServerManager
{
public EditorServer Server { get; private set; }
private ManualResetEventSlim serverCreatedEvent;
private void RunBuiltinServer()
{
serverCreatedEvent.Set();
Server.Serve();
}
public void CreateBuiltinServer()
{
Console.WriteLine("Initializing the built-in editor server...");
serverCreatedEvent = new ManualResetEventSlim();
Server = new EditorServer();
System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
serverCreatedEvent.Wait();
}
}
}```
Use the logger for writing to the console. | ```c#
using System;
using System.Threading;
using Flood.Editor.Server;
namespace Flood.Editor
{
public class ServerManager
{
public EditorServer Server { get; private set; }
private ManualResetEventSlim serverCreatedEvent;
private void RunBuiltinServer()
{
serverCreatedEvent.Set();
Server.Serve();
}
public void CreateBuiltinServer()
{
Log.Info("Initializing the built-in editor server...");
serverCreatedEvent = new ManualResetEventSlim();
Server = new EditorServer();
System.Threading.Tasks.Task.Run((Action)RunBuiltinServer);
serverCreatedEvent.Wait();
}
}
}``` |
5da5e280-9de5-4071-906f-6bf709829087 | {
"language": "C#"
} | ```c#
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Imaging;
namespace WPFConverters
{
public class BitmapImageConverter : BaseConverter
{
protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string)
return new BitmapImage(new Uri((string)value, UriKind.RelativeOrAbsolute));
if (value is Uri)
return new BitmapImage((Uri)value);
return DependencyProperty.UnsetValue;
}
}
}```
Make bitmap loading cache the image | ```c#
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Media.Imaging;
namespace WPFConverters
{
public class BitmapImageConverter : BaseConverter
{
protected override object OnConvert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is string)
return LoadImage(new Uri((string)value, UriKind.RelativeOrAbsolute));
if (value is Uri)
return LoadImage((Uri)value);
return DependencyProperty.UnsetValue;
}
private BitmapImage LoadImage(Uri uri)
{
var image = new BitmapImage();
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.UriSource = uri;
image.EndInit();
return image;
}
}
}``` |
ae00883a-00db-4864-b51c-005c15285546 | {
"language": "C#"
} | ```c#
using System.Linq;
using Geocoding.Google;
using Xunit;
using Xunit.Extensions;
namespace Geocoding.Tests
{
public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
{
GoogleGeocoder geoCoder;
protected override IAsyncGeocoder CreateAsyncGeocoder()
{
geoCoder = new GoogleGeocoder();
return geoCoder;
}
[Theory]
[InlineData("United States", GoogleAddressType.Country)]
[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
[InlineData("New York, New York", GoogleAddressType.Locality)]
[InlineData("90210, US", GoogleAddressType.PostalCode)]
[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)]
public void CanParseAddressTypes(string address, GoogleAddressType type)
{
geoCoder.GeocodeAsync(address).ContinueWith(task =>
{
GoogleAddress[] addresses = task.Result.ToArray();
Assert.Equal(type, addresses[0].Type);
});
}
}
}
```
Use google API key in async test. | ```c#
using System.Configuration;
using System.Linq;
using Geocoding.Google;
using Xunit;
using Xunit.Extensions;
namespace Geocoding.Tests
{
public class GoogleAsyncGeocoderTest : AsyncGeocoderTest
{
GoogleGeocoder geoCoder;
protected override IAsyncGeocoder CreateAsyncGeocoder()
{
geoCoder = new GoogleGeocoder
{
ApiKey = ConfigurationManager.AppSettings["googleApiKey"]
};
return geoCoder;
}
[Theory]
[InlineData("United States", GoogleAddressType.Country)]
[InlineData("Illinois, US", GoogleAddressType.AdministrativeAreaLevel1)]
[InlineData("New York, New York", GoogleAddressType.Locality)]
[InlineData("90210, US", GoogleAddressType.PostalCode)]
[InlineData("1600 pennsylvania ave washington dc", GoogleAddressType.StreetAddress)]
public void CanParseAddressTypes(string address, GoogleAddressType type)
{
geoCoder.GeocodeAsync(address).ContinueWith(task =>
{
GoogleAddress[] addresses = task.Result.ToArray();
Assert.Equal(type, addresses[0].Type);
});
}
}
}
``` |
188d602b-5dda-4c23-9dd4-1deafaef0b6e | {
"language": "C#"
} | ```c#
using System.Configuration;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
/// <summary>
/// Configuration Element Collection for <see cref="RedisHost"/>
/// </summary>
public class RedisHostCollection : ConfigurationElementCollection
{
/// <summary>
/// Gets or sets the <see cref="RedisHost"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="RedisHost"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns></returns>
public RedisHost this[int index]
{
get
{
return BaseGet(index) as RedisHost;
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
/// <summary>
/// Creates the new element.
/// </summary>
/// <returns></returns>
protected override ConfigurationElement CreateNewElement()
{
return new RedisHost();
}
/// <summary>
/// Gets the element key.
/// </summary>
/// <param name="element">The element.</param>
/// <returns></returns>
protected override object GetElementKey(ConfigurationElement element)
{
return ((RedisHost)element).Host;
}
}
}```
Allow for multiple instances of redis running on the same server but different ports. | ```c#
using System.Configuration;
namespace StackExchange.Redis.Extensions.Core.Configuration
{
/// <summary>
/// Configuration Element Collection for <see cref="RedisHost"/>
/// </summary>
public class RedisHostCollection : ConfigurationElementCollection
{
/// <summary>
/// Gets or sets the <see cref="RedisHost"/> at the specified index.
/// </summary>
/// <value>
/// The <see cref="RedisHost"/>.
/// </value>
/// <param name="index">The index.</param>
/// <returns></returns>
public RedisHost this[int index]
{
get
{
return BaseGet(index) as RedisHost;
}
set
{
if (BaseGet(index) != null)
{
BaseRemoveAt(index);
}
BaseAdd(index, value);
}
}
/// <summary>
/// Creates the new element.
/// </summary>
/// <returns></returns>
protected override ConfigurationElement CreateNewElement()
{
return new RedisHost();
}
/// <summary>
/// Gets the element key.
/// </summary>
/// <param name="element">The element.</param>
/// <returns></returns>
protected override object GetElementKey(ConfigurationElement element)
{
return string.Format("{0}:{1}", ((RedisHost)element).Host, ((RedisHost)element).CachePort);
}
}
}``` |
54194c13-9cd1-411b-bffb-0703779e861e | {
"language": "C#"
} | ```c#
using System;
using System.Diagnostics;
using System.Linq.Expressions;
using LINQToTTreeLib.Expressions;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace LINQToTTreeLib.Tests.ResultOperators
{
[TestClass]
[PexClass(typeof(SubExpressionReplacement))]
public partial class SubExpressionReplacementTest
{
[TestInitialize]
public void TestInit()
{
TestUtils.ResetLINQLibrary();
}
[TestCleanup]
public void TestDone()
{
MEFUtilities.MyClassDone();
}
[PexMethod, PexAllowedException(typeof(ArgumentNullException))]
public Expression TestReplacement(Expression source, Expression pattern, Expression replacement)
{
return source.ReplaceSubExpression(pattern, replacement);
}
[TestMethod]
public void TestSimpleReplacement()
{
var arr = Expression.Parameter(typeof(int[]), "myarr");
var param = Expression.Parameter(typeof(int), "dude");
var expr = Expression.ArrayIndex(arr, param);
var rep = Expression.Parameter(typeof(int), "fork");
var result = expr.ReplaceSubExpression(param, rep);
Debg.WriteLine("Expression: " + result.ToString());
Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable");
}
}
}
```
Fix up badly spelled test | ```c#
using LINQToTTreeLib.Expressions;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Diagnostics;
using System.Linq.Expressions;
namespace LINQToTTreeLib.Tests.ResultOperators
{
[TestClass]
[PexClass(typeof(SubExpressionReplacement))]
public partial class SubExpressionReplacementTest
{
[TestInitialize]
public void TestInit()
{
TestUtils.ResetLINQLibrary();
}
[TestCleanup]
public void TestDone()
{
MEFUtilities.MyClassDone();
}
[PexMethod, PexAllowedException(typeof(ArgumentNullException))]
public Expression TestReplacement(Expression source, Expression pattern, Expression replacement)
{
return source.ReplaceSubExpression(pattern, replacement);
}
[TestMethod]
public void TestSimpleReplacement()
{
var arr = Expression.Parameter(typeof(int[]), "myarr");
var param = Expression.Parameter(typeof(int), "dude");
var expr = Expression.ArrayIndex(arr, param);
var rep = Expression.Parameter(typeof(int), "fork");
var result = expr.ReplaceSubExpression(param, rep);
Debug.WriteLine("Expression: " + result.ToString());
Assert.IsFalse(result.ToString().Contains("dude"), "Contains the dude variable");
}
}
}
``` |
ec5d0d11-ba22-4b2b-a54a-b00647047d19 | {
"language": "C#"
} | ```c#
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta04")]```
Increase nuget package version to 1.0.0-beta05 | ```c#
using System.Reflection;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("CakeMail.RestClient")]
[assembly: AssemblyDescription("CakeMail.RestClient is a .NET wrapper for the CakeMail API")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jeremie Desautels")]
[assembly: AssemblyProduct("CakeMail.RestClient")]
[assembly: AssemblyCopyright("Copyright Jeremie Desautels © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0-beta05")]``` |
3f2f7e43-f3fa-48f3-8e35-6cb8e4d3bedc | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MediaCentreServer.Controllers
{
// Controller for running an application.
public class RunController : ApiController
{
// POST /api/run?path=...
public void Post(string path)
{
var startInfo = new ProcessStartInfo(path);
startInfo.UseShellExecute = false;
Process.Start(startInfo);
}
}
}
```
Use shell execute for run action. | ```c#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace MediaCentreServer.Controllers
{
// Controller for running an application.
public class RunController : ApiController
{
// POST /api/run?path=...
public HttpResponseMessage Post(string path)
{
var startInfo = new ProcessStartInfo(path);
try
{
Process.Start(startInfo);
return Request.CreateResponse(HttpStatusCode.NoContent);
}
catch (Exception)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Failed to launch process");
}
}
}
}
``` |
be33ee59-5f09-44ab-b41b-2324116fc7c1 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
/// <summary>
/// A trail of the catcher.
/// It also represents a hyper dash afterimage.
/// </summary>
// TODO: Trails shouldn't be animated when the skin has an animated catcher.
// The animation should be frozen at the animation frame at the time of the trail generation.
public class CatcherTrail : PoolableDrawable
{
public CatcherAnimationState AnimationState
{
set => body.AnimationState.Value = value;
}
private readonly SkinnableCatcher body;
public CatcherTrail()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
Origin = Anchor.TopCentre;
Blending = BlendingParameters.Additive;
InternalChild = body = new SkinnableCatcher();
}
protected override void FreeAfterUse()
{
ClearTransforms();
base.FreeAfterUse();
}
}
}
```
Use a frozen clock for catcher trails | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Timing;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
/// <summary>
/// A trail of the catcher.
/// It also represents a hyper dash afterimage.
/// </summary>
public class CatcherTrail : PoolableDrawable
{
public CatcherAnimationState AnimationState
{
set => body.AnimationState.Value = value;
}
private readonly SkinnableCatcher body;
public CatcherTrail()
{
Size = new Vector2(CatcherArea.CATCHER_SIZE);
Origin = Anchor.TopCentre;
Blending = BlendingParameters.Additive;
InternalChild = body = new SkinnableCatcher
{
// Using a frozen clock because trails should not be animated when the skin has an animated catcher.
// TODO: The animation should be frozen at the animation frame at the time of the trail generation.
Clock = new FramedClock(new ManualClock()),
};
}
protected override void FreeAfterUse()
{
ClearTransforms();
base.FreeAfterUse();
}
}
}
``` |
ac7dc100-3245-43ff-bfed-1459d1e50114 | {
"language": "C#"
} | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using EndlessClient.HUD;
using EndlessClient.Rendering;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1);
}
protected override void OnUpdateControl(GameTime gameTime)
{
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
base.OnUpdateControl(gameTime);
}
}
}
```
Fix status label updating (update method not called if control is not visible) | ```c#
// Original Work Copyright (c) Ethan Moffat 2014-2016
// This file is subject to the GPL v2 License
// For additional details, see the LICENSE file
using System;
using EndlessClient.HUD;
using EndlessClient.Rendering;
using EOLib;
using Microsoft.Xna.Framework;
using XNAControls;
namespace EndlessClient.UIControls
{
public class StatusBarLabel : XNALabel
{
private const int STATUS_LABEL_DISPLAY_TIME_MS = 3000;
private readonly IStatusLabelTextProvider _statusLabelTextProvider;
public StatusBarLabel(IClientWindowSizeProvider clientWindowSizeProvider,
IStatusLabelTextProvider statusLabelTextProvider)
: base(Constants.FontSize07)
{
_statusLabelTextProvider = statusLabelTextProvider;
DrawArea = new Rectangle(97, clientWindowSizeProvider.Height - 24, 1, 1);
}
protected override bool ShouldUpdate()
{
if (Text != _statusLabelTextProvider.StatusText)
{
Text = _statusLabelTextProvider.StatusText;
Visible = true;
}
if ((DateTime.Now - _statusLabelTextProvider.SetTime).TotalMilliseconds > STATUS_LABEL_DISPLAY_TIME_MS)
Visible = false;
return base.ShouldUpdate();
}
}
}
``` |
0f5ab736-be24-438c-a7e1-f2c11723f99e | {
"language": "C#"
} | ```c#
using System.Drawing;
namespace DanTup.DaNES.Emulation
{
class Ppu
{
public Memory Ram { get; }
public Bitmap Screen { get; }
public Ppu(Memory ram, Bitmap screen)
{
Ram = ram;
Screen = screen;
for (var x = 0; x < 256; x++)
{
for (var y = 0; y < 240; y++)
{
Screen.SetPixel(x, y, Color.FromArgb(x, y, 128));
}
}
}
public void Step()
{
}
}
}
```
Add fields for PPU registers. | ```c#
using System.Drawing;
namespace DanTup.DaNES.Emulation
{
class Ppu
{
public Memory Ram { get; }
public Bitmap Screen { get; }
// PPU Control
bool NmiEnable;
bool PpuMasterSlave;
bool SpriteHeight;
bool BackgroundTileSelect;
bool SpriteTileSelect;
bool IncrementMode;
bool NameTableSelect1;
bool NameTableSelect0;
// PPU Mask
bool TintBlue;
bool TintGreen;
bool TintRed;
bool ShowSprites;
bool ShowBackground;
bool ShowLeftSprites;
bool ShowLeftBackground;
bool Greyscale;
// PPU Status
bool VBlank;
bool Sprite0Hit;
bool SpriteOverflow;
byte OamAddress { get; }
byte OamData { get; }
byte PpuScroll { get; }
byte PpuAddr { get; }
byte PpuData { get; }
byte OamDma { get; }
public Ppu(Memory ram, Bitmap screen)
{
Ram = ram;
Screen = screen;
for (var x = 0; x < 256; x++)
{
for (var y = 0; y < 240; y++)
{
Screen.SetPixel(x, y, Color.FromArgb(x, y, 128));
}
}
}
public void Step()
{
}
}
}
``` |
9ebf78d2-a596-42fb-821a-c0a7572dca85 | {
"language": "C#"
} | ```c#
// 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 Newtonsoft.Json;
namespace osu.Game.IO.Serialization
{
public interface IJsonSerializable
{
}
public static class JsonSerializableExtensions
{
public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings());
public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings());
public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings());
/// <summary>
/// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s.
/// </summary>
/// <returns></returns>
public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented,
ObjectCreationHandling = ObjectCreationHandling.Replace,
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
ContractResolver = new KeyContractResolver()
};
}
}
```
Add back the default json converter locally to ensure it's actually used | ```c#
// 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 Newtonsoft.Json;
using osu.Framework.IO.Serialization;
namespace osu.Game.IO.Serialization
{
public interface IJsonSerializable
{
}
public static class JsonSerializableExtensions
{
public static string Serialize(this IJsonSerializable obj) => JsonConvert.SerializeObject(obj, CreateGlobalSettings());
public static T Deserialize<T>(this string objString) => JsonConvert.DeserializeObject<T>(objString, CreateGlobalSettings());
public static void DeserializeInto<T>(this string objString, T target) => JsonConvert.PopulateObject(objString, target, CreateGlobalSettings());
/// <summary>
/// Creates the default <see cref="JsonSerializerSettings"/> that should be used for all <see cref="IJsonSerializable"/>s.
/// </summary>
/// <returns></returns>
public static JsonSerializerSettings CreateGlobalSettings() => new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
Formatting = Formatting.Indented,
ObjectCreationHandling = ObjectCreationHandling.Replace,
DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate,
Converters = new List<JsonConverter> { new Vector2Converter() },
ContractResolver = new KeyContractResolver()
};
}
}
``` |
994ab4bb-e995-4eee-a9ad-14a0d007f6df | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NetBotsHostProject.Models
{
public static class Secrets
{
private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>()
{
{"gitHubClientIdDev", "placeholder"},
{"gitHubClientSecretDev", "placeholder"}
};
public static string GetSecret(string key)
{
if (_secrets.ContainsKey(key))
{
return _secrets[key];
}
return null;
}
}
}```
Set Secret.cs so it will not be modified by default. This means we can put sensitive information in it, and it won't go into source control | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NetBotsHostProject.Models
{
public static class Secrets
{
private static readonly Dictionary<string,string> _secrets = new Dictionary<string, string>()
{
{"gitHubClientIdDev", "placeHolder"},
{"gitHubClientSecretDev", "placeHolder"}
};
public static string GetSecret(string key)
{
if (_secrets.ContainsKey(key))
{
return _secrets[key];
}
return null;
}
}
}``` |
375247dd-b491-413c-82dc-421da40f8460 | {
"language": "C#"
} | ```c#
using UnityEngine;
using System.Reflection;
[assembly: AssemblyVersion("1.1.0.*")]
public class Loader : MonoBehaviour
{
/// <summary>
/// DebugUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _debugUI;
/// <summary>
/// ModalDialog prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _modalDialog;
/// <summary>
/// MainMenu prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _mainMenu;
/// <summary>
/// InGameUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _inGameUI;
/// <summary>
/// SoundManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _soundManager;
/// <summary>
/// GameManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _gameManager;
protected void Awake()
{
// Check if the instances have already been assigned to static variables or they are still null.
if (DebugUI.Instance == null)
{
Instantiate(_debugUI);
}
if (ModalDialog.Instance == null)
{
Instantiate(_modalDialog);
}
if (MainMenu.Instance == null)
{
Instantiate(_mainMenu);
}
if (InGameUI.Instance == null)
{
Instantiate(_inGameUI);
}
if (SoundManager.Instance == null)
{
Instantiate(_soundManager);
}
if (GameManager.Instance == null)
{
Instantiate(_gameManager);
}
}
}
```
Change version up to 1.1.1 | ```c#
using UnityEngine;
using System.Reflection;
[assembly: AssemblyVersion("1.1.1.*")]
public class Loader : MonoBehaviour
{
/// <summary>
/// DebugUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _debugUI;
/// <summary>
/// ModalDialog prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _modalDialog;
/// <summary>
/// MainMenu prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _mainMenu;
/// <summary>
/// InGameUI prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _inGameUI;
/// <summary>
/// SoundManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _soundManager;
/// <summary>
/// GameManager prefab to instantiate.
/// </summary>
[SerializeField]
private GameObject _gameManager;
protected void Awake()
{
// Check if the instances have already been assigned to static variables or they are still null.
if (DebugUI.Instance == null)
{
Instantiate(_debugUI);
}
if (ModalDialog.Instance == null)
{
Instantiate(_modalDialog);
}
if (MainMenu.Instance == null)
{
Instantiate(_mainMenu);
}
if (InGameUI.Instance == null)
{
Instantiate(_inGameUI);
}
if (SoundManager.Instance == null)
{
Instantiate(_soundManager);
}
if (GameManager.Instance == null)
{
Instantiate(_gameManager);
}
}
}
``` |
ce8f55b8-058f-4908-a81b-b65b2ff7b8e0 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Grobid.PdfToXml;
namespace Grobid.NET
{
public class PdfBlockExtractor<T>
{
private readonly BlockStateFactory factory;
public PdfBlockExtractor()
{
this.factory = new BlockStateFactory();
}
public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform)
{
foreach (var block in blocks)
{
foreach (var textBlock in block.TextBlocks)
{
var tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize());
foreach (var tokenBlock in tokenBlocks)
{
var blockState = this.factory.Create(block, textBlock, tokenBlock);
yield return transform(blockState);
}
}
}
}
}
}
```
Simplify foreach'es to a LINQ expression | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using Grobid.PdfToXml;
namespace Grobid.NET
{
public class PdfBlockExtractor<T>
{
private readonly BlockStateFactory factory;
public PdfBlockExtractor()
{
this.factory = new BlockStateFactory();
}
public IEnumerable<T> Extract(IEnumerable<Block> blocks, Func<BlockState, T> transform)
{
return from block in blocks
from textBlock in block.TextBlocks
let tokenBlocks = textBlock.TokenBlocks.SelectMany(x => x.Tokenize())
from tokenBlock in tokenBlocks
select this.factory.Create(block, textBlock, tokenBlock)
into blockState
select transform(blockState);
}
}
}
``` |
b0cb184e-2d44-408a-910e-b3fd31ab2649 | {
"language": "C#"
} | ```c#
using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(String twilioAccountSid, String twilioAuthToken, String twilioSourceNumber)
{
this._twilioAccountSId = twilioAccountSid;
this._twilioAuthToken = twilioAuthToken;
this._twilioSourceNumber = twilioSourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync"))
{
Log.Info("Sending SMSNotification {@Notification}", notification);
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
}
}```
Add timer for email sending | ```c#
using CertiPay.Common.Logging;
using System;
using System.Threading.Tasks;
using Twilio;
namespace CertiPay.Common.Notifications
{
/// <summary>
/// Send an SMS message to the given recipient.
/// </summary>
/// <remarks>
/// Implementation may be sent into background processing.
/// </remarks>
public interface ISMSService : INotificationSender<SMSNotification>
{
// Task SendAsync(T notification);
}
public class SmsService : ISMSService
{
private static readonly ILog Log = LogManager.GetLogger<ISMSService>();
private readonly String _twilioAccountSId;
private readonly String _twilioAuthToken;
private readonly String _twilioSourceNumber;
public SmsService(TwilioConfig config)
{
this._twilioAccountSId = config.AccountSid;
this._twilioAuthToken = config.AuthToken;
this._twilioSourceNumber = config.SourceNumber;
}
public Task SendAsync(SMSNotification notification)
{
using (Log.Timer("SMSNotification.SendAsync"))
{
Log.Info("Sending SMSNotification {@Notification}", notification);
// TODO Add error handling
var client = new TwilioRestClient(_twilioAccountSId, _twilioAuthToken);
foreach (var recipient in notification.Recipients)
{
client.SendSmsMessage(_twilioSourceNumber, recipient, notification.Content);
}
return Task.FromResult(0);
}
}
public class TwilioConfig
{
public String AccountSid { get; set; }
public String AuthToken { get; set; }
public String SourceNumber { get; set; }
}
}
}``` |
758770b7-6fb7-4974-a644-484c06e69204 | {
"language": "C#"
} | ```c#
using Windows.System.Profile;
using Windows.UI.ViewManagement;
namespace DigiTransit10.Helpers
{
public static class DeviceTypeHelper
{
public static DeviceFormFactorType GetDeviceFormFactorType()
{
switch (AnalyticsInfo.VersionInfo.DeviceFamily)
{
case "Windows.Mobile":
return DeviceFormFactorType.Phone;
case "Windows.Desktop":
return UIViewSettings.GetForCurrentView().UserInteractionMode == UserInteractionMode.Mouse
? DeviceFormFactorType.Desktop
: DeviceFormFactorType.Tablet;
case "Windows.Universal":
return DeviceFormFactorType.IoT;
case "Windows.Team":
return DeviceFormFactorType.SurfaceHub;
default:
return DeviceFormFactorType.Other;
}
}
}
public enum DeviceFormFactorType
{
Phone,
Desktop,
Tablet,
IoT,
SurfaceHub,
Other
}
}
```
Make Tablet and Desktop device types report as Desktop | ```c#
using Windows.System.Profile;
using Windows.UI.ViewManagement;
namespace DigiTransit10.Helpers
{
public static class DeviceTypeHelper
{
public static DeviceFormFactorType GetDeviceFormFactorType()
{
switch (AnalyticsInfo.VersionInfo.DeviceFamily)
{
case "Windows.Mobile":
return DeviceFormFactorType.Phone;
case "Windows.Desktop":
return DeviceFormFactorType.Desktop;
case "Windows.Universal":
return DeviceFormFactorType.IoT;
case "Windows.Team":
return DeviceFormFactorType.SurfaceHub;
default:
return DeviceFormFactorType.Other;
}
}
}
public enum DeviceFormFactorType
{
Phone,
Desktop,
Tablet,
IoT,
SurfaceHub,
Other
}
}
``` |
bb30286d-aa76-4b52-a196-a1f1da436919 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection;
using MusicStore.Models;
using Xunit;
namespace MusicStore.Components
{
public class GenreMenuComponentTest
{
private readonly IServiceProvider _serviceProvider;
public GenreMenuComponentTest()
{
var services = new ServiceCollection();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase());
_serviceProvider = services.BuildServiceProvider();
}
[Fact]
public async Task GenreMenuComponent_Returns_NineGenres()
{
// Arrange
var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
var genreMenuComponent = new GenreMenuComponent(dbContext);
PopulateData(dbContext);
// Act
var result = await genreMenuComponent.InvokeAsync();
// Assert
Assert.NotNull(result);
var viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.Null(viewResult.ViewName);
var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model);
Assert.Equal(9, genreResult.Count);
}
private static void PopulateData(MusicStoreContext context)
{
var genres = Enumerable.Range(1, 10).Select(n => new Genre());
context.AddRange(genres);
context.SaveChanges();
}
}
}
```
Fix bug in test where key value was not being set. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Mvc.ViewComponents;
using Microsoft.Data.Entity;
using Microsoft.Extensions.DependencyInjection;
using MusicStore.Models;
using Xunit;
namespace MusicStore.Components
{
public class GenreMenuComponentTest
{
private readonly IServiceProvider _serviceProvider;
public GenreMenuComponentTest()
{
var services = new ServiceCollection();
services.AddEntityFramework()
.AddInMemoryDatabase()
.AddDbContext<MusicStoreContext>(options => options.UseInMemoryDatabase());
_serviceProvider = services.BuildServiceProvider();
}
[Fact]
public async Task GenreMenuComponent_Returns_NineGenres()
{
// Arrange
var dbContext = _serviceProvider.GetRequiredService<MusicStoreContext>();
var genreMenuComponent = new GenreMenuComponent(dbContext);
PopulateData(dbContext);
// Act
var result = await genreMenuComponent.InvokeAsync();
// Assert
Assert.NotNull(result);
var viewResult = Assert.IsType<ViewViewComponentResult>(result);
Assert.Null(viewResult.ViewName);
var genreResult = Assert.IsType<List<Genre>>(viewResult.ViewData.Model);
Assert.Equal(9, genreResult.Count);
}
private static void PopulateData(MusicStoreContext context)
{
var genres = Enumerable.Range(1, 10).Select(n => new Genre { GenreId = n });
context.AddRange(genres);
context.SaveChanges();
}
}
}
``` |
50f54d80-5b76-45c3-a52d-b555f8a51358 | {
"language": "C#"
} | ```c#
using System.Linq;
using EPiServer.Core;
using EPiServer.Find;
using EPiServer.Find.Framework;
using EPiServer.ServiceLocation;
using Vro.FindExportImport.Models;
namespace Vro.FindExportImport.Stores
{
public interface ISearchService
{
ContentReference FindMatchingContent(BestBetEntity bestBetEntity);
}
[ServiceConfiguration(typeof(ISearchService))]
public class SearchService : ISearchService
{
public ContentReference FindMatchingContent(BestBetEntity bestBetEntity)
{
var searchQuery = SearchClient.Instance
.Search<IContent>()
.Filter(x => x.Name.Match(bestBetEntity.TargetName));
if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector))
{
searchQuery = searchQuery.Filter(x => !x.ContentLink.ProviderName.Exists());
}
else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector))
{
searchQuery = searchQuery.Filter(x => x.ContentLink.ProviderName.Match("CatalogContent"));
}
var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult();
return searchResults.Hits.FirstOrDefault()?.Document;
}
}
}```
Use type filtering when searching matching content for BestBets | ```c#
using System;
using System.Linq;
using EPiServer;
using EPiServer.Core;
using EPiServer.Find;
using EPiServer.Find.Framework;
using EPiServer.ServiceLocation;
using Vro.FindExportImport.Models;
namespace Vro.FindExportImport.Stores
{
public interface ISearchService
{
ContentReference FindMatchingContent(BestBetEntity bestBetEntity);
}
[ServiceConfiguration(typeof(ISearchService))]
public class SearchService : ISearchService
{
public ContentReference FindMatchingContent(BestBetEntity bestBetEntity)
{
var searchQuery = SearchClient.Instance
.Search<IContent>()
.Filter(x => x.Name.Match(bestBetEntity.TargetName));
if (bestBetEntity.TargetType.Equals(Helpers.PageBestBetSelector))
{
searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(typeof(PageData)));
}
else if (bestBetEntity.TargetType.Equals(Helpers.CommerceBestBetSelector))
{
// resolving type from string to avoid referencing Commerce assemblies
var commerceCatalogEntryType =
Type.GetType("EPiServer.Commerce.Catalog.ContentTypes.EntryContentBase, EPiServer.Business.Commerce");
searchQuery = searchQuery.Filter(x => x.MatchTypeHierarchy(commerceCatalogEntryType));
}
var searchResults = searchQuery.Select(c => c.ContentLink).Take(1).GetResult();
return searchResults.Hits.FirstOrDefault()?.Document;
}
}
}``` |
c9988c2b-68a3-4bd1-9f3e-9064b6ebc435 | {
"language": "C#"
} | ```c#
namespace TrackTv.Updater
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TrackTv.Data;
public class ApiResultRepository
{
public ApiResultRepository(IDbService dbService)
{
this.DbService = dbService;
}
private IDbService DbService { get; }
public Task SaveApiResult(object jsonObj, ApiChangeType type, int thetvdbid)
{
int apiResponseID = this.DbService.ApiResponses
.Where(poco =>
poco.ApiResponseShowThetvdbid == thetvdbid || poco.ApiResponseEpisodeThetvdbid == thetvdbid)
.Select(poco => poco.ApiResponseID)
.FirstOrDefault();
var result = new ApiResponsePoco
{
ApiResponseID = apiResponseID,
ApiResponseBody = JsonConvert.SerializeObject(jsonObj),
ApiResponseLastUpdated = DateTime.UtcNow,
};
switch (type)
{
case ApiChangeType.Show :
result.ApiResponseShowThetvdbid = thetvdbid;
break;
case ApiChangeType.Episode :
result.ApiResponseEpisodeThetvdbid = thetvdbid;
break;
default :
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
return this.DbService.Save(result);
}
}
}```
Fix for the api_results FK collision. | ```c#
namespace TrackTv.Updater
{
using System;
using System.Linq;
using System.Threading.Tasks;
using Newtonsoft.Json;
using TrackTv.Data;
public class ApiResultRepository
{
public ApiResultRepository(IDbService dbService)
{
this.DbService = dbService;
}
private IDbService DbService { get; }
public Task SaveApiResult(object jsonObj, ApiChangeType type, int thetvdbid)
{
int apiResponseID = this.DbService.ApiResponses
.Where(poco =>
(type == ApiChangeType.Show && poco.ApiResponseShowThetvdbid == thetvdbid) ||
(type == ApiChangeType.Episode && poco.ApiResponseEpisodeThetvdbid == thetvdbid))
.Select(poco => poco.ApiResponseID)
.FirstOrDefault();
var result = new ApiResponsePoco
{
ApiResponseID = apiResponseID,
ApiResponseBody = JsonConvert.SerializeObject(jsonObj),
ApiResponseLastUpdated = DateTime.UtcNow,
};
switch (type)
{
case ApiChangeType.Show :
result.ApiResponseShowThetvdbid = thetvdbid;
break;
case ApiChangeType.Episode :
result.ApiResponseEpisodeThetvdbid = thetvdbid;
break;
default :
throw new ArgumentOutOfRangeException(nameof(type), type, null);
}
return this.DbService.Save(result);
}
}
}``` |
60a4c977-dcdf-4bd2-8034-7cba553495a3 | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Screens.Testing;
namespace osu.Framework.VisualTests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
}
}
```
Set cursor invisible in visual test game | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Cursor;
using osu.Framework.Platform;
using osu.Framework.Screens.Testing;
namespace osu.Framework.VisualTests
{
internal class VisualTestGame : Game
{
[BackgroundDependencyLoader]
private void load()
{
Children = new Drawable[]
{
new TestBrowser(),
new CursorContainer(),
};
}
protected override void LoadComplete()
{
base.LoadComplete();
Host.Window.CursorState = CursorState.Hidden;
}
}
}
``` |
2dc26693-b705-4cf3-ae66-1daf79056496 | {
"language": "C#"
} | ```c#
using System.Text;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Mvc.Rendering;
namespace Glimpse.Web.Common
{
[TargetElement("body")]
public class ScriptInjector : TagHelper
{
public override int Order => int.MaxValue;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var js = new StringBuilder();
js.AppendLine("var link = document.createElement('a');");
js.AppendLine("link.setAttribute('href', '/glimpseui/index.html');");
js.AppendLine("link.setAttribute('target', '_blank');");
js.AppendLine("link.text = 'Open Glimpse';");
js.AppendLine("document.body.appendChild(link);");
var tag = new TagBuilder("script")
{
InnerHtml = new HtmlString(js.ToString()),
};
output.PostContent.Append(tag.ToHtmlContent(TagRenderMode.Normal));
}
}
}
```
Update tag helper usage from upstream breaking change | ```c#
using System.Text;
using Microsoft.AspNet.Razor.Runtime.TagHelpers;
using Microsoft.AspNet.Mvc.Rendering;
namespace Glimpse.Web.Common
{
[TargetElement("body")]
public class ScriptInjector : TagHelper
{
public override int Order => int.MaxValue;
public override void Process(TagHelperContext context, TagHelperOutput output)
{
var js = new StringBuilder();
js.AppendLine("var link = document.createElement('a');");
js.AppendLine("link.setAttribute('href', '/glimpseui/index.html');");
js.AppendLine("link.setAttribute('target', '_blank');");
js.AppendLine("link.text = 'Open Glimpse';");
js.AppendLine("document.body.appendChild(link);");
var tag = new TagBuilder("script")
{
InnerHtml = new HtmlString(js.ToString()),
};
output.PostContent.Append(tag);
}
}
}
``` |
a923d9b7-9f58-4457-9f7e-ce88b2c44672 | {
"language": "C#"
} | ```c#
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CertiPay.Payroll.Common
{
[ComplexType]
public class Address
{
// Warning: This is marked as a complex type, and used in several projects, so any changes will trickle down into EF changes...
[StringLength(75)]
public String Address1 { get; set; }
[StringLength(75)]
public String Address2 { get; set; }
[StringLength(75)]
public String Address3 { get; set; }
[StringLength(50)]
public String City { get; set; }
public StateOrProvince State { get; set; }
[DataType(DataType.PostalCode)]
[StringLength(15)]
[Display(Name = "Postal Code")]
public String PostalCode { get; set; }
// TODO: international fields
public Address()
{
this.State = StateOrProvince.FL;
}
}
}```
Add API comments for address | ```c#
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace CertiPay.Payroll.Common
{
/// <summary>
/// Represents a basic address format for the United States
/// </summary>
[ComplexType]
public class Address
{
// Warning: This is marked as a complex type, and used in several projects, so any changes will trickle down into EF changes...
/// <summary>
/// The first line of the address
/// </summary>
[StringLength(75)]
public String Address1 { get; set; }
/// <summary>
/// The second line of the address
/// </summary>
[StringLength(75)]
public String Address2 { get; set; }
/// <summary>
/// The third line of the address
/// </summary>
[StringLength(75)]
public String Address3 { get; set; }
/// <summary>
/// The city the address is located in
/// </summary>
[StringLength(50)]
public String City { get; set; }
/// <summary>
/// The state the address is located in
/// </summary>
public StateOrProvince State { get; set; }
/// <summary>
/// The postal "zip" code for the address, could include the additional four digits
/// </summary>
[DataType(DataType.PostalCode)]
[StringLength(15)]
[Display(Name = "Postal Code")]
public String PostalCode { get; set; }
public Address()
{
this.State = StateOrProvince.FL;
}
}
}``` |
4a5ccee4-b957-4e2f-abc3-34aba9bf0120 | {
"language": "C#"
} | ```c#
@model alert_roster.web.Models.Message
@{
ViewBag.Title = "Post New Message";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("New", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true)
<div class="alert alert-info">
Please limit messages to < 160 characters.
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { rows = "3", cols = "80" })
@Html.ValidationMessageFor(model => model.Content)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Post" class="btn btn-default" />
</div>
</div>
</div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
}
```
Add warning about no edit/delete | ```c#
@model alert_roster.web.Models.Message
@{
ViewBag.Title = "Post New Message";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm("New", "Home", FormMethod.Post))
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
@Html.ValidationSummary(true)
<div class="alert alert-info">
Please limit messages to < 160 characters. Note that, due to notifications being sent,
editing or deleting a post is currently unavailable.
</div>
<div class="form-group">
@Html.LabelFor(model => model.Content, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextAreaFor(model => model.Content, new { rows = "3", cols = "80" })
@Html.ValidationMessageFor(model => model.Content)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Post" class="btn btn-default" />
</div>
</div>
</div>
<div>
@Html.ActionLink("Back to List", "Index")
</div>
}
``` |
dbb359f7-6331-41d3-b498-3f5da6d94bd4 | {
"language": "C#"
} | ```c#
using System.Threading.Tasks;
using EE.FutureProof;
using JetBrains.Annotations;
using PlayerIOClient;
namespace BotBits
{
public class FutureProofLoginClient : LoginClient
{
private const int CurrentVersion = 218;
public FutureProofLoginClient([NotNull] ConnectionManager connectionManager, [NotNull] Client client) : base(connectionManager, client)
{
}
protected override Task Attach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int? version)
{
var versionLoader = version.HasValue
? TaskHelper.FromResult(version.Value)
: LoginUtils.GetVersionAsync(this.Client);
return versionLoader.Then(v =>
{
connectionManager.AttachConnection(connection.FutureProof(CurrentVersion, v.Result), args);
});
}
}
}
```
Optimize FutureProof to not load when the version is up to date | ```c#
using System.Threading.Tasks;
using EE.FutureProof;
using JetBrains.Annotations;
using PlayerIOClient;
namespace BotBits
{
public class FutureProofLoginClient : LoginClient
{
private const int CurrentVersion = 218;
public FutureProofLoginClient([NotNull] ConnectionManager connectionManager, [NotNull] Client client) : base(connectionManager, client)
{
}
protected override Task Attach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int? version)
{
var versionLoader = version.HasValue
? TaskHelper.FromResult(version.Value)
: LoginUtils.GetVersionAsync(this.Client);
return versionLoader.Then(v =>
{
if (v.Result == CurrentVersion)
{
base.Attach(connectionManager, connection, args, v.Result);
}
else
{
this.FutureProofAttach(connectionManager, connection, args, v.Result);
}
});
}
// This line is separated into a function to prevent uncessarily loading FutureProof into memory.
private void FutureProofAttach(ConnectionManager connectionManager, Connection connection, ConnectionArgs args, int version)
{
connectionManager.AttachConnection(connection.FutureProof(CurrentVersion, version), args);
}
}
}
``` |
a9b891eb-30d5-4f04-b378-48ec4d613b07 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;
namespace CasualMeter.Common.Formatters
{
public class DamageTrackerFormatter : Formatter
{
public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
{
var placeHolders = new List<KeyValuePair<string, object>>();
placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name));
placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));
Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
FormatProvider = formatHelpers.CultureInfo;
}
}
}
```
Fix not pasting stats with no boss name available. | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CasualMeter.Common.Helpers;
using Tera.DamageMeter;
namespace CasualMeter.Common.Formatters
{
public class DamageTrackerFormatter : Formatter
{
public DamageTrackerFormatter(DamageTracker damageTracker, FormatHelpers formatHelpers)
{
var placeHolders = new List<KeyValuePair<string, object>>();
placeHolders.Add(new KeyValuePair<string, object>("Boss", damageTracker.Name??string.Empty));
placeHolders.Add(new KeyValuePair<string, object>("Time", formatHelpers.FormatTimeSpan(damageTracker.Duration)));
Placeholders = placeHolders.ToDictionary(x => x.Key, y => y.Value);
FormatProvider = formatHelpers.CultureInfo;
}
}
}
``` |
cdc0c9c1-3ca3-4263-a7d6-7af318f2f919 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Okanshi.Dashboard.Models;
namespace Okanshi.Dashboard
{
public interface IGetMetrics
{
IEnumerable<Metric> Execute(string instanceName);
}
public class GetMetrics : IGetMetrics
{
private readonly IStorage _storage;
public GetMetrics(IStorage storage)
{
_storage = storage;
}
public IEnumerable<Metric> Execute(string instanceName)
{
var webClient = new WebClient();
var response = webClient.DownloadString(_storage.GetAll().Single(x => x.Name.Equals(instanceName, StringComparison.OrdinalIgnoreCase)).Url);
var jObject = JObject.Parse(response);
JToken versionToken;
jObject.TryGetValue("version", out versionToken);
var version = "0";
if (versionToken != null && versionToken.HasValues)
{
version = versionToken.Value<string>();
}
if (version.Equals("0", StringComparison.OrdinalIgnoreCase))
{
var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response);
return deserializeObject
.Select(x => new Metric
{
Name = x.Key,
Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(),
WindowSize = x.Value.windowSize.ToObject<float>()
});
}
return Enumerable.Empty<Metric>();
}
}
}```
Throw exception on unsupported exception | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Okanshi.Dashboard.Models;
namespace Okanshi.Dashboard
{
public interface IGetMetrics
{
IEnumerable<Metric> Execute(string instanceName);
}
public class GetMetrics : IGetMetrics
{
private readonly IStorage _storage;
public GetMetrics(IStorage storage)
{
_storage = storage;
}
public IEnumerable<Metric> Execute(string instanceName)
{
var webClient = new WebClient();
var response = webClient.DownloadString(_storage.GetAll().Single(x => x.Name.Equals(instanceName, StringComparison.OrdinalIgnoreCase)).Url);
var jObject = JObject.Parse(response);
JToken versionToken;
jObject.TryGetValue("version", out versionToken);
var version = "0";
if (versionToken != null && versionToken.HasValues)
{
version = versionToken.Value<string>();
}
if (version.Equals("0", StringComparison.OrdinalIgnoreCase))
{
var deserializeObject = JsonConvert.DeserializeObject<IDictionary<string, dynamic>>(response);
return deserializeObject
.Select(x => new Metric
{
Name = x.Key,
Measurements = x.Value.measurements.ToObject<IEnumerable<Measurement>>(),
WindowSize = x.Value.windowSize.ToObject<float>()
});
}
throw new InvalidOperationException("Not supported version");
}
}
}``` |
0a212f57-9e45-461a-bac8-163d5336a659 | {
"language": "C#"
} | ```c#
using Basic.Azure.Storage.Communications.Core;
using Basic.Azure.Storage.Communications.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Basic.Azure.Storage.Communications.QueueService.MessageOperations
{
/// <summary>
/// Deletes the specified queue item from the queue
/// http://msdn.microsoft.com/en-us/library/azure/dd179347.aspx
/// </summary>
public class ClearMessageRequest : RequestBase<EmptyResponsePayload>
{
private string _queueName;
public ClearMessageRequest(StorageAccountSettings settings, string queueName)
: base(settings)
{
//TODO: add Guard statements against invalid values, short circuit so we don't have the latency roundtrip to the server
_queueName = queueName;
}
protected override string HttpMethod { get { return "DELETE"; } }
protected override StorageServiceType ServiceType { get { return StorageServiceType.QueueService; } }
protected override RequestUriBuilder GetUriBase()
{
var builder = new RequestUriBuilder(Settings.QueueEndpoint);
builder.AddSegment(_queueName);
builder.AddSegment("messages");
return builder;
}
}
}
```
Update comment for ClearMessages request | ```c#
using Basic.Azure.Storage.Communications.Core;
using Basic.Azure.Storage.Communications.Core.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Basic.Azure.Storage.Communications.QueueService.MessageOperations
{
/// <summary>
/// Clears the specified queue
/// http://msdn.microsoft.com/en-us/library/azure/dd179454.aspx
/// </summary>
public class ClearMessageRequest : RequestBase<EmptyResponsePayload>
{
private string _queueName;
public ClearMessageRequest(StorageAccountSettings settings, string queueName)
: base(settings)
{
//TODO: add Guard statements against invalid values, short circuit so we don't have the latency roundtrip to the server
_queueName = queueName;
}
protected override string HttpMethod { get { return "DELETE"; } }
protected override StorageServiceType ServiceType { get { return StorageServiceType.QueueService; } }
protected override RequestUriBuilder GetUriBase()
{
var builder = new RequestUriBuilder(Settings.QueueEndpoint);
builder.AddSegment(_queueName);
builder.AddSegment("messages");
return builder;
}
}
}
``` |
3243601b-4421-4d43-83d4-8c00340805a5 | {
"language": "C#"
} | ```c#
using System;
using System.Linq;
using System.Runtime.InteropServices;
using Windows.Security.Credentials;
using TimesheetParser.Business.Services;
namespace TimesheetParser.Win10.Services
{
internal class PasswordService : IPasswordService
{
private readonly string pluginName;
private readonly PasswordVault vault = new PasswordVault();
public PasswordService(string pluginName)
{
this.pluginName = pluginName;
}
public string Login { get; set; }
public string Password { get; set; }
public void LoadCredential()
{
try
{
var credential = vault.FindAllByResource(GetResource()).FirstOrDefault();
if (credential != null)
{
Login = credential.UserName;
Password = credential.Password;
}
}
catch (COMException)
{
// No passwords are saved for this resource.
}
}
public void SaveCredential()
{
vault.Add(new PasswordCredential(GetResource(), Login, Password));
}
public void DeleteCredential()
{
vault.Remove(vault.Retrieve(GetResource(), Login));
}
private string GetResource()
{
return $"TimesheetParser/{pluginName}";
}
}
}```
Fix exception handling on .NET Native. | ```c#
using System;
using System.Linq;
using Windows.Security.Credentials;
using TimesheetParser.Business.Services;
namespace TimesheetParser.Win10.Services
{
internal class PasswordService : IPasswordService
{
private readonly string pluginName;
private readonly PasswordVault vault = new PasswordVault();
public PasswordService(string pluginName)
{
this.pluginName = pluginName;
}
public string Login { get; set; }
public string Password { get; set; }
public void LoadCredential()
{
try
{
var credential = vault.FindAllByResource(GetResource()).FirstOrDefault();
if (credential != null)
{
Login = credential.UserName;
Password = credential.Password;
}
}
catch (Exception)
{
// No passwords are saved for this resource.
}
}
public void SaveCredential()
{
vault.Add(new PasswordCredential(GetResource(), Login, Password));
}
public void DeleteCredential()
{
vault.Remove(vault.Retrieve(GetResource(), Login));
}
private string GetResource()
{
return $"TimesheetParser/{pluginName}";
}
}
}``` |
f14e4cd8-a5ac-40e5-96d8-a8ce83dba044 | {
"language": "C#"
} | ```c#
using UnityEngine;
namespace LiteNetLibManager
{
[System.Serializable]
public class LiteNetLibScene
{
[SerializeField]
public Object sceneAsset;
[SerializeField]
public string sceneName = string.Empty;
public string SceneName
{
get { return sceneName; }
set { sceneName = value; }
}
public static implicit operator string(LiteNetLibScene unityScene)
{
return unityScene.SceneName;
}
public bool IsSet()
{
return !string.IsNullOrEmpty(sceneName);
}
}
}
```
Make scene asset / scene name deprecated | ```c#
using UnityEngine;
namespace LiteNetLibManager
{
[System.Serializable]
public class LiteNetLibScene
{
[SerializeField]
private Object sceneAsset;
[SerializeField]
private string sceneName = string.Empty;
public string SceneName
{
get { return sceneName; }
set { sceneName = value; }
}
public static implicit operator string(LiteNetLibScene unityScene)
{
return unityScene.SceneName;
}
public bool IsSet()
{
return !string.IsNullOrEmpty(sceneName);
}
}
}
``` |
0e725bab-4fcc-4c5d-9397-518254857542 | {
"language": "C#"
} | ```c#
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Avalonia.FreeDesktop
{
internal static class NativeMethods
{
[DllImport("libc", SetLastError = true)]
private static extern long readlink([MarshalAs(UnmanagedType.LPArray)] byte[] filename,
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,
long len);
public static string ReadLink(string path)
{
var symlinkMaxSize = Encoding.ASCII.GetMaxByteCount(path.Length);
var bufferSize = 4097; // PATH_MAX is (usually?) 4096, but we need to know if the result was truncated
var symlink = ArrayPool<byte>.Shared.Rent(symlinkMaxSize + 1);
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
var symlinkSize = Encoding.UTF8.GetBytes(path, 0, path.Length, symlink, 0);
symlink[symlinkSize] = 0;
var size = readlink(symlink, buffer, bufferSize);
Debug.Assert(size < bufferSize); // if this fails, we need to increase the buffer size (dynamically?)
return Encoding.UTF8.GetString(buffer, 0, (int)size);
}
finally
{
ArrayPool<byte>.Shared.Return(symlink);
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
}
```
Use the correct size for the symlink path buffer | ```c#
using System.Buffers;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Avalonia.FreeDesktop
{
internal static class NativeMethods
{
[DllImport("libc", SetLastError = true)]
private static extern long readlink([MarshalAs(UnmanagedType.LPArray)] byte[] filename,
[MarshalAs(UnmanagedType.LPArray)] byte[] buffer,
long len);
public static string ReadLink(string path)
{
var symlinkSize = Encoding.UTF8.GetByteCount(path);
var bufferSize = 4097; // PATH_MAX is (usually?) 4096, but we need to know if the result was truncated
var symlink = ArrayPool<byte>.Shared.Rent(symlinkSize + 1);
var buffer = ArrayPool<byte>.Shared.Rent(bufferSize);
try
{
Encoding.UTF8.GetBytes(path, 0, path.Length, symlink, 0);
symlink[symlinkSize] = 0;
var size = readlink(symlink, buffer, bufferSize);
Debug.Assert(size < bufferSize); // if this fails, we need to increase the buffer size (dynamically?)
return Encoding.UTF8.GetString(buffer, 0, (int)size);
}
finally
{
ArrayPool<byte>.Shared.Return(symlink);
ArrayPool<byte>.Shared.Return(buffer);
}
}
}
}
``` |
4bf3954f-23df-43fc-9ef7-77566bc9df57 | {
"language": "C#"
} | ```c#
using Hyena;
using TagLib;
using System;
using GLib;
namespace FSpot.Utils
{
public static class Metadata
{
public static TagLib.Image.File Parse (SafeUri uri)
{
// Detect mime-type
var gfile = FileFactory.NewForUri (uri);
var info = gfile.QueryInfo ("standard::content-type", FileQueryInfoFlags.None, null);
var mime = info.ContentType;
// Parse file
var res = new GIOTagLibFileAbstraction () { Uri = uri };
var sidecar_uri = uri.ReplaceExtension (".xmp");
var sidecar_res = new GIOTagLibFileAbstraction () { Uri = sidecar_uri };
TagLib.Image.File file = null;
try {
file = TagLib.File.Create (res, mime, ReadStyle.Average) as TagLib.Image.File;
} catch (Exception e) {
Hyena.Log.Exception (String.Format ("Loading of Metadata failed for file: {0}", uri.ToString ()), e);
return null;
}
// Load XMP sidecar
var sidecar_file = GLib.FileFactory.NewForUri (sidecar_uri);
if (sidecar_file.Exists) {
file.ParseXmpSidecar (sidecar_res);
}
return file;
}
}
}
```
Work around broken mime-type detection. | ```c#
using Hyena;
using TagLib;
using System;
using GLib;
namespace FSpot.Utils
{
public static class Metadata
{
public static TagLib.Image.File Parse (SafeUri uri)
{
// Detect mime-type
var gfile = FileFactory.NewForUri (uri);
var info = gfile.QueryInfo ("standard::content-type", FileQueryInfoFlags.None, null);
var mime = info.ContentType;
if (mime.StartsWith ("application/x-extension-")) {
// Works around broken metadata detection - https://bugzilla.gnome.org/show_bug.cgi?id=624781
mime = String.Format ("taglib/{0}", mime.Substring (24));
}
// Parse file
var res = new GIOTagLibFileAbstraction () { Uri = uri };
var sidecar_uri = uri.ReplaceExtension (".xmp");
var sidecar_res = new GIOTagLibFileAbstraction () { Uri = sidecar_uri };
TagLib.Image.File file = null;
try {
file = TagLib.File.Create (res, mime, ReadStyle.Average) as TagLib.Image.File;
} catch (Exception e) {
Hyena.Log.Exception (String.Format ("Loading of Metadata failed for file: {0}", uri.ToString ()), e);
return null;
}
// Load XMP sidecar
var sidecar_file = GLib.FileFactory.NewForUri (sidecar_uri);
if (sidecar_file.Exists) {
file.ParseXmpSidecar (sidecar_res);
}
return file;
}
}
}
``` |
977d1330-34e5-405b-8d9f-4630ddcad9bd | {
"language": "C#"
} | ```c#
using Content.Server.Administration;
using Content.Server.Atmos.Components;
using Content.Shared.Administration;
using Robust.Shared.Console;
namespace Content.Server.Atmos.Commands
{
[AdminCommand(AdminFlags.Debug)]
public sealed class AddAtmosCommand : IConsoleCommand
{
[Dependency] private readonly IEntityManager _entities = default!;
public string Command => "addatmos";
public string Description => "Adds atmos support to a grid.";
public string Help => $"{Command} <GridId>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 1)
{
shell.WriteLine(Help);
return;
}
var entMan = IoCManager.Resolve<IEntityManager>();
if(EntityUid.TryParse(args[0], out var euid))
{
shell.WriteError($"Failed to parse euid '{args[0]}'.");
return;
}
if (!entMan.HasComponent<IMapGridComponent>(euid))
{
shell.WriteError($"Euid '{euid}' does not exist or is not a grid.");
return;
}
if (_entities.HasComponent<IAtmosphereComponent>(euid))
{
shell.WriteLine("Grid already has an atmosphere.");
return;
}
_entities.AddComponent<GridAtmosphereComponent>(euid);
shell.WriteLine($"Added atmosphere to grid {euid}.");
}
}
}
```
Fix addatmos from griduid artifact | ```c#
using Content.Server.Administration;
using Content.Server.Atmos.Components;
using Content.Shared.Administration;
using Robust.Shared.Console;
namespace Content.Server.Atmos.Commands
{
[AdminCommand(AdminFlags.Debug)]
public sealed class AddAtmosCommand : IConsoleCommand
{
[Dependency] private readonly IEntityManager _entities = default!;
public string Command => "addatmos";
public string Description => "Adds atmos support to a grid.";
public string Help => $"{Command} <GridId>";
public void Execute(IConsoleShell shell, string argStr, string[] args)
{
if (args.Length < 1)
{
shell.WriteLine(Help);
return;
}
var entMan = IoCManager.Resolve<IEntityManager>();
if (!EntityUid.TryParse(args[0], out var euid))
{
shell.WriteError($"Failed to parse euid '{args[0]}'.");
return;
}
if (!entMan.HasComponent<IMapGridComponent>(euid))
{
shell.WriteError($"Euid '{euid}' does not exist or is not a grid.");
return;
}
if (_entities.HasComponent<IAtmosphereComponent>(euid))
{
shell.WriteLine("Grid already has an atmosphere.");
return;
}
_entities.AddComponent<GridAtmosphereComponent>(euid);
shell.WriteLine($"Added atmosphere to grid {euid}.");
}
}
}
``` |
64d3c01a-e511-4b1d-90d1-a148791d0f09 | {
"language": "C#"
} | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Sender;
using System.Diagnostics;
using FaqTemplate.Core.Services;
using FaqTemplate.Core.Domain;
namespace FaqTemplate.Bot
{
public class PlainTextMessageReceiver : IMessageReceiver
{
private readonly IFaqService<string> _faqService;
private readonly IMessagingHubSender _sender;
private readonly Settings _settings;
public PlainTextMessageReceiver(IMessagingHubSender sender, IFaqService<string> faqService, Settings settings)
{
_sender = sender;
_faqService = faqService;
_settings = settings;
}
public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
{
Trace.TraceInformation($"From: {message.From} \tContent: {message.Content}");
var request = new FaqRequest { Ask = message.Content.ToString() };
var result = await _faqService.AskThenIAnswer(request);
await _sender.SendMessageAsync($"{result.Score}: {result.Answer}", message.From, cancellationToken);
}
}
}
```
Add multiple response handling for diferente score levels | ```c#
using System;
using System.Threading;
using System.Threading.Tasks;
using Lime.Protocol;
using Takenet.MessagingHub.Client;
using Takenet.MessagingHub.Client.Listener;
using Takenet.MessagingHub.Client.Sender;
using System.Diagnostics;
using FaqTemplate.Core.Services;
using FaqTemplate.Core.Domain;
namespace FaqTemplate.Bot
{
public class PlainTextMessageReceiver : IMessageReceiver
{
private readonly IFaqService<string> _faqService;
private readonly IMessagingHubSender _sender;
private readonly Settings _settings;
public PlainTextMessageReceiver(IMessagingHubSender sender, IFaqService<string> faqService, Settings settings)
{
_sender = sender;
_faqService = faqService;
_settings = settings;
}
public async Task ReceiveAsync(Message message, CancellationToken cancellationToken)
{
Trace.TraceInformation($"From: {message.From} \tContent: {message.Content}");
var request = new FaqRequest { Ask = message.Content.ToString() };
var response = await _faqService.AskThenIAnswer(request);
if (response.Score >= 0.8)
{
await _sender.SendMessageAsync($"{response.Answer}", message.From, cancellationToken);
}
else if(response.Score >= 0.5)
{
await _sender.SendMessageAsync($"Eu acho que a resposta para o que voc precisa :", message.From, cancellationToken);
cancellationToken.WaitHandle.WaitOne(TimeSpan.FromSeconds(1));
await _sender.SendMessageAsync($"{response.Answer}", message.From, cancellationToken);
}
else
{
await _sender.SendMessageAsync($"Infelizmente eu ainda no sei isso! Mas vou me aprimorar, prometo!", message.From, cancellationToken);
}
await _sender.SendMessageAsync($"{response.Score}: {response.Answer}", message.From, cancellationToken);
}
}
}
``` |
ef2418f9-a706-4115-9286-c24774658c44 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace SimpleWAWS.Models
{
public class WebsiteTemplate : BaseTemplate
{
[JsonProperty(PropertyName="fileName")]
public string FileName { get; set; }
[JsonProperty(PropertyName="language")]
public string Language { get; set; }
public static WebsiteTemplate EmptySiteTemplate
{
get { return new WebsiteTemplate() { Name = "Empty Site", Language = "Empty Site", SpriteName = "sprite-Large" }; }
}
}
}```
Move 'Empty Website' template to Default language | ```c#
using System;
using System.Collections.Generic;
using System.EnterpriseServices.Internal;
using System.Linq;
using System.Runtime.Serialization;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace SimpleWAWS.Models
{
public class WebsiteTemplate : BaseTemplate
{
[JsonProperty(PropertyName="fileName")]
public string FileName { get; set; }
[JsonProperty(PropertyName="language")]
public string Language { get; set; }
public static WebsiteTemplate EmptySiteTemplate
{
get { return new WebsiteTemplate() { Name = "Empty Site", Language = "Default", SpriteName = "sprite-Large" }; }
}
}
}``` |
a8435d08-7f70-4e36-bd23-b6c364e6fe69 | {
"language": "C#"
} | ```c#
using System;
namespace Telegram.Bot.Helpers
{
/// <summary>
/// Extension Methods
/// </summary>
public static class Extensions
{
private static readonly DateTime UnixStart = new DateTime(1970, 1, 1);
/// <summary>
/// Convert a long into a DateTime
/// </summary>
public static DateTime FromUnixTime(this long dateTime)
=> UnixStart.AddSeconds(dateTime).ToLocalTime();
/// <summary>
/// Convert a DateTime into a long
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="OverflowException"></exception>
public static long ToUnixTime(this DateTime dateTime)
{
var utcDateTime = dateTime.ToUniversalTime();
if (utcDateTime == DateTime.MinValue)
return 0;
var delta = dateTime - UnixStart;
if (delta.TotalSeconds < 0)
throw new ArgumentOutOfRangeException(nameof(dateTime), "Unix epoch starts January 1st, 1970");
return Convert.ToInt64(delta.TotalSeconds);
}
}
}
```
Fix minor issue with unix time calculation. | ```c#
using System;
namespace Telegram.Bot.Helpers
{
/// <summary>
/// Extension Methods
/// </summary>
public static class Extensions
{
private static readonly DateTime UnixStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Convert a long into a DateTime
/// </summary>
public static DateTime FromUnixTime(this long unixTime)
=> UnixStart.AddSeconds(unixTime).ToLocalTime();
/// <summary>
/// Convert a DateTime into a long
/// </summary>
/// <exception cref="ArgumentOutOfRangeException"></exception>
/// <exception cref="OverflowException"></exception>
public static long ToUnixTime(this DateTime dateTime)
{
if (dateTime == DateTime.MinValue)
return 0;
var utcDateTime = dateTime.ToUniversalTime();
var delta = (utcDateTime - UnixStart).TotalSeconds;
if (delta < 0)
throw new ArgumentOutOfRangeException(nameof(dateTime), "Unix epoch starts January 1st, 1970");
return Convert.ToInt64(delta);
}
}
}
``` |
8e203241-e355-4802-8113-88fece31a108 | {
"language": "C#"
} | ```c#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Linq;
namespace osu.Game.Online.API.Requests
{
public class GetUsersRequest : APIRequest<GetUsersResponse>
{
private readonly int[] userIds;
private const int max_ids_per_request = 50;
public GetUsersRequest(int[] userIds)
{
if (userIds.Length > max_ids_per_request)
throw new ArgumentException($"{nameof(GetUsersRequest)} calls only support up to {max_ids_per_request} IDs at once");
this.userIds = userIds;
}
protected override string Target => $@"users/?{userIds.Select(u => $"ids[]={u}&").Aggregate((a, b) => a + b)}";
}
}
```
Refactor request string logic to avoid linq usage | ```c#
// 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;
namespace osu.Game.Online.API.Requests
{
public class GetUsersRequest : APIRequest<GetUsersResponse>
{
private readonly int[] userIds;
private const int max_ids_per_request = 50;
public GetUsersRequest(int[] userIds)
{
if (userIds.Length > max_ids_per_request)
throw new ArgumentException($"{nameof(GetUsersRequest)} calls only support up to {max_ids_per_request} IDs at once");
this.userIds = userIds;
}
protected override string Target => "users/?ids[]=" + string.Join("&ids[]=", userIds);
}
}
``` |
090edcdc-ab51-47c3-ae56-e5d6e26d23e6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
public static string RoleProvider { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
RoleProvider = ConfigurationManager.AppSettings["RoleProvider"];
}
}
}```
Remove unused RoleProvider setting from authentication configuration | ```c#
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
namespace Bonobo.Git.Server.Configuration
{
public class AuthenticationSettings
{
public static string MembershipService { get; private set; }
static AuthenticationSettings()
{
MembershipService = ConfigurationManager.AppSettings["MembershipService"];
}
}
}``` |
df64149a-69c8-4e21-84ef-cbec79bacb19 | {
"language": "C#"
} | ```c#
using System.Net;
using FluentAssertions;
using NUnit.Framework;
namespace Durwella.UrlShortening.Tests
{
public class WebClientUrlUnwrapperTest
{
[Test]
public void ShouldGetResourceLocation()
{
var wrappedUrl = "http://goo.gl/mSkqOi";
var subject = new WebClientUrlUnwrapper();
var directUrl = subject.GetDirectUrl(wrappedUrl);
directUrl.Should().Be("http://example.com/");
}
[Test]
public void ShouldReturnGivenLocationIfAuthenticationRequired()
{
var givenUrl = "http://durwella.com/testing/does-not-exist";
var subject = new WebClientUrlUnwrapper
{
IgnoreErrorCodes = new[] { HttpStatusCode.NotFound }
};
var directUrl = subject.GetDirectUrl(givenUrl);
directUrl.Should().Be(givenUrl);
}
}
}
```
Update tests for new url resolution behavior | ```c#
using System.Net;
using FluentAssertions;
using NUnit.Framework;
namespace Durwella.UrlShortening.Tests
{
public class WebClientUrlUnwrapperTest
{
[Test]
public void ShouldGetResourceLocation()
{
var wrappedUrl = "http://goo.gl/mSkqOi";
var subject = new WebClientUrlUnwrapper();
WebClientUrlUnwrapper.ResolveUrls = true;
var directUrl = subject.GetDirectUrl(wrappedUrl);
directUrl.Should().Be("http://example.com/");
WebClientUrlUnwrapper.ResolveUrls = false;
}
[Test]
public void ShouldReturnGivenLocationIfAuthenticationRequired()
{
var givenUrl = "http://durwella.com/testing/does-not-exist";
var subject = new WebClientUrlUnwrapper
{
IgnoreErrorCodes = new[] { HttpStatusCode.NotFound }
};
WebClientUrlUnwrapper.ResolveUrls = true;
var directUrl = subject.GetDirectUrl(givenUrl);
directUrl.Should().Be(givenUrl);
WebClientUrlUnwrapper.ResolveUrls = false;
}
}
}
``` |
dfbc0f2a-c3d4-4a43-b59f-6ca30d650b25 | {
"language": "C#"
} | ```c#
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
using Workstation.ServiceModel.Ua;
using Xunit;
namespace Workstation.UaClient.UnitTests
{
public class UaApplicationOptionsTests
{
[Fact]
public void UaTcpTransportChannelOptionsDefaults()
{
var lowestBufferSize = 1024u;
var options = new UaTcpTransportChannelOptions();
options.LocalMaxChunkCount
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalMaxMessageSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalReceiveBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalSendBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
}
[Fact]
public void UaTcpSecureChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSecureChannelOptions();
TimeSpan.FromMilliseconds(options.TimeoutHint)
.Should().BeGreaterOrEqualTo(shortestTimespan);
options.DiagnosticsHint
.Should().Be(0);
}
[Fact]
public void UaTcpSessionChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSessionChannelOptions();
TimeSpan.FromMilliseconds(options.SessionTimeout)
.Should().BeGreaterOrEqualTo(shortestTimespan);
}
}
}
```
Use 8192u as lowestBufferSize; Remove tests for LocalMaxChunkCount and MaxMessageSize | ```c#
using FluentAssertions;
using System;
using System.Collections.Generic;
using System.Text;
using Workstation.ServiceModel.Ua;
using Xunit;
namespace Workstation.UaClient.UnitTests
{
public class UaApplicationOptionsTests
{
[Fact]
public void UaTcpTransportChannelOptionsDefaults()
{
var lowestBufferSize = 8192u;
var options = new UaTcpTransportChannelOptions();
options.LocalReceiveBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
options.LocalSendBufferSize
.Should().BeGreaterOrEqualTo(lowestBufferSize);
}
[Fact]
public void UaTcpSecureChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSecureChannelOptions();
TimeSpan.FromMilliseconds(options.TimeoutHint)
.Should().BeGreaterOrEqualTo(shortestTimespan);
options.DiagnosticsHint
.Should().Be(0);
}
[Fact]
public void UaTcpSessionChannelOptionsDefaults()
{
var shortestTimespan = TimeSpan.FromMilliseconds(100);
var options = new UaTcpSessionChannelOptions();
TimeSpan.FromMilliseconds(options.SessionTimeout)
.Should().BeGreaterOrEqualTo(shortestTimespan);
}
}
}
``` |
f5b3bbb2-3041-45a5-9bd5-5f2586194484 | {
"language": "C#"
} | ```c#
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Helpers
{
internal static class FullScreenHelper
{
private static bool DoesMonitorHaveFullscreenApp(Screen screen) => Win32Helper.GetForegroundApp()
.IsFullScreen(screen);
private static bool DoesMonitorHaveFullscreenApp(Screen screen, Win32App ignoreApp)
{
var foregroundApp = Win32Helper.GetForegroundApp();
return foregroundApp.Hwnd != ignoreApp.Hwnd && foregroundApp.IsFullScreen(screen);
}
public static bool DoesMonitorHaveFullscreenApp(Rect bounds)
=> DoesMonitorHaveFullscreenApp(ScreenHelper.GetScreen(bounds));
public static bool DoesMonitorHaveFullscreenApp(Rect bounds, Win32App ignoreApp)
=> DoesMonitorHaveFullscreenApp(ScreenHelper.GetScreen(bounds), ignoreApp);
public static bool DoesAnyMonitorHaveFullscreenApp() => Screen.AllScreens.Any(DoesMonitorHaveFullscreenApp);
}
}```
Fix potential fullscreen checking error | ```c#
using System.Linq;
using System.Windows;
using System.Windows.Forms;
using DesktopWidgets.Classes;
namespace DesktopWidgets.Helpers
{
internal static class FullScreenHelper
{
private static bool DoesMonitorHaveFullscreenApp(Screen screen) => Win32Helper.GetForegroundApp()
.IsFullScreen(screen);
private static bool DoesMonitorHaveFullscreenApp(Screen screen, Win32App ignoreApp)
{
var foregroundApp = Win32Helper.GetForegroundApp();
return foregroundApp.Hwnd != ignoreApp?.Hwnd && foregroundApp.IsFullScreen(screen);
}
public static bool DoesMonitorHaveFullscreenApp(Rect bounds)
=> DoesMonitorHaveFullscreenApp(ScreenHelper.GetScreen(bounds));
public static bool DoesMonitorHaveFullscreenApp(Rect bounds, Win32App ignoreApp)
=> DoesMonitorHaveFullscreenApp(ScreenHelper.GetScreen(bounds), ignoreApp);
public static bool DoesAnyMonitorHaveFullscreenApp() => Screen.AllScreens.Any(DoesMonitorHaveFullscreenApp);
}
}``` |
71b5591a-932f-46b0-bd3c-41e2c04b70f2 | {
"language": "C#"
} | ```c#
using System;
namespace SharpHaven.Resources
{
public struct ResourceRef
{
public ResourceRef(string name, ushort version)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
this.Name = name;
this.Version = version;
}
public string Name { get; }
public ushort Version { get; }
public override int GetHashCode()
{
return Name.GetHashCode() ^ Version.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ResourceRef))
return false;
var other = (ResourceRef)obj;
return string.Equals(Name, other.Name) && Version == other.Version;
}
}
}
```
Revert "Fix mono compilation error" | ```c#
using System;
namespace SharpHaven.Resources
{
public struct ResourceRef
{
public ResourceRef(string name, ushort version)
{
if (name == null)
throw new ArgumentNullException(nameof(name));
Name = name;
Version = version;
}
public string Name { get; }
public ushort Version { get; }
public override int GetHashCode()
{
return Name.GetHashCode() ^ Version.GetHashCode();
}
public override bool Equals(object obj)
{
if (!(obj is ResourceRef))
return false;
var other = (ResourceRef)obj;
return string.Equals(Name, other.Name) && Version == other.Version;
}
}
}
``` |
55a69496-61ab-4d52-a12d-9d7713b46d3e | {
"language": "C#"
} | ```c#
namespace Gu.Wpf.Geometry.Tests
{
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Markup;
using NUnit.Framework;
public class NamespacesTests
{
private const string Uri = "http://gu.se/Geometry";
private readonly Assembly assembly;
public NamespacesTests()
{
this.assembly = typeof(GradientPath).Assembly;
}
[Test]
public void XmlnsDefinitions()
{
string[] skip = { ".Annotations", ".Properties", "XamlGeneratedNamespace" };
var strings = this.assembly.GetTypes()
.Select(x => x.Namespace)
.Distinct()
.Where(x => x != null && !skip.Any(x.EndsWith))
.OrderBy(x => x)
.ToArray();
var attributes = this.assembly.CustomAttributes.Where(x => x.AttributeType == typeof(XmlnsDefinitionAttribute))
.ToArray();
var actuals = attributes.Select(a => a.ConstructorArguments[1].Value)
.OrderBy(x => x);
foreach (var s in strings)
{
Console.WriteLine(@"[assembly: XmlnsDefinition(""{0}"", ""{1}"")]", Uri, s);
}
Assert.AreEqual(strings, actuals);
foreach (var attribute in attributes)
{
Assert.AreEqual(Uri, attribute.ConstructorArguments[0].Value);
}
}
[Test]
public void XmlnsPrefix()
{
var attributes = this.assembly.CustomAttributes.Where(x => x.AttributeType == typeof(XmlnsPrefixAttribute));
foreach (var attribute in attributes)
{
Assert.AreEqual(Uri, attribute.ConstructorArguments[0].Value);
}
}
}
}
```
Remove test that is checked by analyzer. | ```c#
namespace Gu.Wpf.Geometry.Tests
{
using System;
using System.Linq;
using System.Reflection;
using System.Windows.Markup;
using NUnit.Framework;
public class NamespacesTests
{
private const string Uri = "http://gu.se/Geometry";
private readonly Assembly assembly;
public NamespacesTests()
{
this.assembly = typeof(GradientPath).Assembly;
}
[Test]
public void XmlnsPrefix()
{
var attributes = this.assembly.CustomAttributes.Where(x => x.AttributeType == typeof(XmlnsPrefixAttribute));
foreach (var attribute in attributes)
{
Assert.AreEqual(Uri, attribute.ConstructorArguments[0].Value);
}
}
}
}
``` |
d62d9b88-b2f5-4560-b8c1-40b121e60cf6 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OMF
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string baseDir = System.AppDomain.CurrentDomain.BaseDirectory;
string file = System.IO.Path.Combine(baseDir, "..\\..\\test.omf");
if (System.IO.File.Exists(file) == false)
{
Console.WriteLine(string.Format("File '{0}' does not exist.", file));
Console.ReadLine();
return;
}
OMF torun = new OMF();
torun.Execute(file);
}
}
}
```
Make test file path OS-agnostic | ```c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace OMF
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
string baseDir = System.AppDomain.CurrentDomain.BaseDirectory;
string file = System.IO.Path.Combine(baseDir, "..", "..", "test.omf");
if (System.IO.File.Exists(file) == false)
{
Console.WriteLine(string.Format("File '{0}' does not exist.", file));
Console.ReadLine();
return;
}
OMF torun = new OMF();
torun.Execute(file);
}
}
}
``` |
045514b7-52b2-4cfa-8acc-181a548a7f4c | {
"language": "C#"
} | ```c#
namespace PS.Mothership.Core.Common.SignalRConnectionHandling
{
public interface IClientsCollection
{
ISignalRUser Get(string machineName, string username);
ISignalRUser GetOrAdd(string machineName, string username);
void AddOrReplace(ISignalRUser inputUser);
}
}
```
Remove machine name from method calls since it is no longer needed after refactoring implementation | ```c#
namespace PS.Mothership.Core.Common.SignalRConnectionHandling
{
public interface IClientsCollection
{
ISignalRUser Get(string username);
ISignalRUser GetOrAdd(string username);
void AddOrReplace(ISignalRUser inputUser);
}
}
``` |
c844faac-5b0d-4b8a-9538-aaf14eb2f5c3 | {
"language": "C#"
} | ```c#
namespace AjErl.Console
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjErl.Compiler;
using AjErl.Expressions;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("AjErl alfa 0.0.1");
Lexer lexer = new Lexer(Console.In);
Parser parser = new Parser(lexer);
Machine machine = new Machine();
while (true)
try
{
ProcessExpression(parser, machine.RootContext);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
Console.Error.WriteLine(ex.StackTrace);
}
}
private static void ProcessExpression(Parser parser, Context context)
{
IExpression expression = parser.ParseExpression();
object result = expression.Evaluate(context);
if (result == null)
return;
Console.Write("> ");
Console.WriteLine(result);
}
}
}
```
Expand delayed calls in console interpreter | ```c#
namespace AjErl.Console
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AjErl.Compiler;
using AjErl.Expressions;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("AjErl alfa 0.0.1");
Lexer lexer = new Lexer(Console.In);
Parser parser = new Parser(lexer);
Machine machine = new Machine();
while (true)
try
{
ProcessExpression(parser, machine.RootContext);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
Console.Error.WriteLine(ex.StackTrace);
}
}
private static void ProcessExpression(Parser parser, Context context)
{
IExpression expression = parser.ParseExpression();
object result = Machine.ExpandDelayedCall(expression.Evaluate(context));
if (result == null)
return;
Console.Write("> ");
Console.WriteLine(result);
}
}
}
``` |
9d96a69b-962e-4125-b21c-4b0c8488f52b | {
"language": "C#"
} | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Graphics;
using osu.Game.Overlays.Dialog;
namespace osu.Game.Screens.Select
{
public class ImportFromStablePopup : PopupDialog
{
public ImportFromStablePopup(Action importFromStable)
{
HeaderText = @"You have no beatmaps!";
BodyText = "An existing copy of osu! was found, though.\nWould you like to import your beatmaps?";
Icon = FontAwesome.fa_trash_o;
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Yes please!",
Action = importFromStable
},
new PopupDialogCancelButton
{
Text = @"No, I'd like to start from scratch",
},
};
}
}
}
```
Use a more suiting (?) icon for import dialog | ```c#
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using System;
using osu.Game.Graphics;
using osu.Game.Overlays.Dialog;
namespace osu.Game.Screens.Select
{
public class ImportFromStablePopup : PopupDialog
{
public ImportFromStablePopup(Action importFromStable)
{
HeaderText = @"You have no beatmaps!";
BodyText = "An existing copy of osu! was found, though.\nWould you like to import your beatmaps?";
Icon = FontAwesome.fa_plane;
Buttons = new PopupDialogButton[]
{
new PopupDialogOkButton
{
Text = @"Yes please!",
Action = importFromStable
},
new PopupDialogCancelButton
{
Text = @"No, I'd like to start from scratch",
},
};
}
}
}
``` |
1bd08109-efe9-4a61-bb3a-84dcc9aa3a17 | {
"language": "C#"
} | ```c#
using System.Reflection;
// common assembly attributes
[assembly: AssemblyDescription("Lean Engine is an open-source, plataform agnostic C# and Python algorithmic trading engine. " +
"Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")]
[assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")]
[assembly: AssemblyCompany("QuantConnect Corporation")]
[assembly: AssemblyVersion("2.4")]
// Configuration used to build the assembly is by defaulting 'Debug'.
// To create a package using a Release configuration, -properties Configuration=Release on the command line must be use.
// source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens```
Fix typo in assembly description | ```c#
using System.Reflection;
// common assembly attributes
[assembly: AssemblyDescription("Lean Engine is an open-source, platform agnostic C# and Python algorithmic trading engine. " +
"Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")]
[assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")]
[assembly: AssemblyCompany("QuantConnect Corporation")]
[assembly: AssemblyVersion("2.4")]
// Configuration used to build the assembly is by defaulting 'Debug'.
// To create a package using a Release configuration, -properties Configuration=Release on the command line must be use.
// source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens``` |
7461acec-afe6-477e-ae3e-4b79164bfed0 | {
"language": "C#"
} | ```c#
namespace OmniSharp
{
internal static class Configuration
{
public static bool ZeroBasedIndices = false;
public const string RoslynVersion = "2.1.0.0";
public const string RoslynPublicKeyToken = "31bf3856ad364e35";
public readonly static string RoslynFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Features");
public readonly static string RoslynCSharpFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.CSharp.Features");
public readonly static string RoslynWorkspaces = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Workspaces");
private static string GetRoslynAssemblyFullName(string name)
{
return $"{name}, Version={RoslynVersion}, Culture=neutral, PublicKeyToken={RoslynPublicKeyToken}";
}
}
}
```
Update Roslyn version number for assembly loading | ```c#
namespace OmniSharp
{
internal static class Configuration
{
public static bool ZeroBasedIndices = false;
public const string RoslynVersion = "2.3.0.0";
public const string RoslynPublicKeyToken = "31bf3856ad364e35";
public readonly static string RoslynFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Features");
public readonly static string RoslynCSharpFeatures = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.CSharp.Features");
public readonly static string RoslynWorkspaces = GetRoslynAssemblyFullName("Microsoft.CodeAnalysis.Workspaces");
private static string GetRoslynAssemblyFullName(string name)
{
return $"{name}, Version={RoslynVersion}, Culture=neutral, PublicKeyToken={RoslynPublicKeyToken}";
}
}
}
``` |
b018ab84-a108-4f8d-a3ec-a1eb84be9b42 | {
"language": "C#"
} | ```c#
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace ProcessSample
{
using System;
using System.Diagnostics;
using System.Threading;
internal sealed class Program
{
private static void Main(string[] args)
{
int exitCode;
DateTime exitTime;
using (Process process = Process.Start("notepad.exe"))
using (ProcessExitWatcher watcher = new ProcessExitWatcher(new ProcessExit(process)))
{
Console.WriteLine("Waiting for Notepad to exit...");
watcher.WaitForExitAsync(CancellationToken.None).Wait();
exitCode = watcher.Status.ExitCode;
exitTime = watcher.Status.ExitTime;
}
Console.WriteLine("Done, exited with code {0} at {1}.", exitCode, exitTime);
}
}
}
```
Use async method in main program | ```c#
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="Brian Rogers">
// Copyright (c) Brian Rogers. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace ProcessSample
{
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
internal sealed class Program
{
private static void Main(string[] args)
{
using (CancellationTokenSource cts = new CancellationTokenSource())
{
Task task = StartAndWaitForProcessAsync(cts.Token);
Console.WriteLine("Press ENTER to quit.");
Console.ReadLine();
cts.Cancel();
try
{
task.Wait();
}
catch (AggregateException ae)
{
ae.Handle(e => e is OperationCanceledException);
Console.WriteLine("(Canceled.)");
}
}
}
private static async Task StartAndWaitForProcessAsync(CancellationToken token)
{
int exitCode;
DateTime exitTime;
using (Process process = await Task.Factory.StartNew(() => Process.Start("notepad.exe")))
using (ProcessExitWatcher watcher = new ProcessExitWatcher(new ProcessExit(process)))
{
Console.WriteLine("Waiting for Notepad to exit...");
await watcher.WaitForExitAsync(token);
exitCode = watcher.Status.ExitCode;
exitTime = watcher.Status.ExitTime;
}
Console.WriteLine("Done, exited with code {0} at {1}.", exitCode, exitTime);
}
}
}
``` |
f20dec8b-841a-4c39-b643-06ae747ff3af | {
"language": "C#"
} | ```c#
@{
ViewData["Title"] = "Home Page";
}
.<div class="row">
<div class="col-xs-12">
<div bs-progress-min="1"
bs-progress-max="5"
bs-progress-value="4">
</div>
</div>
</div>
```
Use updated TagHelper on home page | ```c#
@{
ViewData["Title"] = "Home Page";
}
<div class="row">
<div class="col-xs-6 col-md-4">
<div href="#" class="thumbnail">
<h3>Progress Bar Default</h3>
<p>
<code>progress-bar</code>
</p>
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="45">
</div>
<pre class="pre-scrollable">
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="45">
</div></pre>
</div>
</div>
<div class="col-xs-6 col-md-4">
<div href="#" class="thumbnail">
<h3>Progress Bar Animated</h3>
<p>
<code>progress-bar progress-bar-success progress-bar-striped active</code>
</p>
<div bs-progress-style="success"
bs-progress-min="1"
bs-progress-max="5"
bs-progress-value="4"
bs-progress-active="true">
</div>
<pre class="pre-scrollable">
<div bs-progress-style="success"
bs-progress-min="1"
bs-progress-max="5"
bs-progress-value="4"
bs-progress-active="true">
</div></pre>
</div>
</div>
<div class="col-xs-6 col-md-4">
<div href="#" class="thumbnail">
<h3>Progress Bar Striped</h3>
<p>
<code>progress-bar progress-bar-danger progress-bar-striped</code>
</p>
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="80"
bs-progress-style="danger"
bs-progress-striped="true"
bs-progress-label-visible="false">
</div>
<pre class="pre-scrollable">
<div bs-progress-min="1"
bs-progress-max="100"
bs-progress-value="80"
bs-progress-style="danger"
bs-progress-striped="true"
bs-progress-label-visible="false">
</div></pre>
</div>
</div>
</div>
``` |
00002c4a-fcd3-4aef-a481-6ec27b365477 | {
"language": "C#"
} | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace Hangman {
public class Game {
public string Word;
private List<char> GuessedLetters;
private string StatusMessage;
public Game(string word) {
Word = word;
GuessedLetters = new List<char>();
StatusMessage = "Press any letter to guess!";
}
public string ShownWord() {
var obscuredWord = new StringBuilder();
foreach (char letter in Word) {
obscuredWord.Append(ShownLetterFor(letter));
}
return obscuredWord.ToString();
}
public string Status() {
return StatusMessage;
}
public bool GuessLetter(char letter) {
GuessedLetters.Add(letter);
return LetterIsCorrect(letter);
}
private char ShownLetterFor(char originalLetter) {
if (LetterWasGuessed(originalLetter) || originalLetter == ' ') {
return originalLetter;
} else {
return '_';
}
}
private bool LetterWasGuessed(char letter) {
return GuessedLetters.Contains(letter);
}
private bool LetterIsCorrect(char letter) {
return Word.Contains(letter.ToString());
}
}
}
```
Update status message for last guess | ```c#
using System;
using System.Collections.Generic;
using System.Text;
namespace Hangman {
public class Game {
public string Word;
private List<char> GuessedLetters;
private string StatusMessage;
public Game(string word) {
Word = word;
GuessedLetters = new List<char>();
StatusMessage = "Press any letter to guess!";
}
public string ShownWord() {
var obscuredWord = new StringBuilder();
foreach (char letter in Word) {
obscuredWord.Append(ShownLetterFor(letter));
}
return obscuredWord.ToString();
}
public string Status() {
return StatusMessage;
}
public bool GuessLetter(char letter) {
GuessedLetters.Add(letter);
bool correct = LetterIsCorrect(letter);
if (correct) {
StatusMessage = "Correct! Guess again!";
} else {
StatusMessage = "Incorrect! Try again!";
}
// CheckGameOver();
return correct;
}
private char ShownLetterFor(char originalLetter) {
if (LetterWasGuessed(originalLetter) || originalLetter == ' ') {
return originalLetter;
} else {
return '_';
}
}
private bool LetterWasGuessed(char letter) {
return GuessedLetters.Contains(letter);
}
private bool LetterIsCorrect(char letter) {
return Word.Contains(letter.ToString());
}
}
}
``` |
1e3c7e2f-98da-40cf-919b-2efe79c00ab1 | {
"language": "C#"
} | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users.Lists;
using TraktApiSharp.Objects.Post.Users;
[TestClass]
public class TraktUserCustomListAddRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsNotAbstract()
{
typeof(TraktUserCustomListAddRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSealed()
{
typeof(TraktUserCustomListAddRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSubclassOfATraktSingleItemPostRequest()
{
typeof(TraktUserCustomListAddRequest).IsSubclassOf(typeof(ATraktSingleItemPostRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
}
}
}
```
Add test for authorization requirement in TraktUserCustomListAddRequest | ```c#
namespace TraktApiSharp.Tests.Experimental.Requests.Users.OAuth
{
using FluentAssertions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TraktApiSharp.Experimental.Requests.Base.Post;
using TraktApiSharp.Experimental.Requests.Users.OAuth;
using TraktApiSharp.Objects.Get.Users.Lists;
using TraktApiSharp.Objects.Post.Users;
using TraktApiSharp.Requests;
[TestClass]
public class TraktUserCustomListAddRequestTests
{
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsNotAbstract()
{
typeof(TraktUserCustomListAddRequest).IsAbstract.Should().BeFalse();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSealed()
{
typeof(TraktUserCustomListAddRequest).IsSealed.Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestIsSubclassOfATraktSingleItemPostRequest()
{
typeof(TraktUserCustomListAddRequest).IsSubclassOf(typeof(ATraktSingleItemPostRequest<TraktList, TraktUserCustomListPost>)).Should().BeTrue();
}
[TestMethod, TestCategory("Requests"), TestCategory("Users")]
public void TestTraktUserCustomListAddRequestHasAuthorizationRequired()
{
var request = new TraktUserCustomListAddRequest(null);
request.AuthorizationRequirement.Should().Be(TraktAuthorizationRequirement.Required);
}
}
}
``` |
1939462c-2a30-43b5-829c-771e43e500cb | {
"language": "C#"
} | ```c#
using System.Linq;
using NUnit.Framework;
using Shouldly;
using StructureMap;
namespace JustSaying.IntegrationTests.WhenRegisteringHandlersViaResolver
{
public class WhenRegisteringABlockingHandlerViaContainer : GivenAPublisher
{
private BlockingOrderProcessor _resolvedHandler;
protected override void Given()
{
var container = new Container(x => x.AddRegistry(new BlockingHandlerRegistry()));
var handlerResolver = new StructureMapHandlerResolver(container);
var handlers = handlerResolver.ResolveHandlers<OrderPlaced>().ToList();
Assert.That(handlers.Count, Is.EqualTo(1));
_resolvedHandler = (BlockingOrderProcessor)handlers[0];
DoneSignal = _resolvedHandler.DoneSignal.Task;
var subscriber = CreateMeABus.InRegion("eu-west-1")
.WithSqsTopicSubscriber()
.IntoQueue("container-test")
.WithMessageHandler<OrderPlaced>(handlerResolver);
subscriber.StartListening();
}
[Test]
public void ThenHandlerWillReceiveTheMessage()
{
_resolvedHandler.ReceivedMessageCount.ShouldBeGreaterThan(0);
}
}
}```
Fix to dodgy cast in test | ```c#
using System.Linq;
using JustSaying.Messaging.MessageHandling;
using NUnit.Framework;
using Shouldly;
using StructureMap;
namespace JustSaying.IntegrationTests.WhenRegisteringHandlersViaResolver
{
public class WhenRegisteringABlockingHandlerViaContainer : GivenAPublisher
{
private BlockingOrderProcessor _resolvedHandler;
protected override void Given()
{
var container = new Container(x => x.AddRegistry(new BlockingHandlerRegistry()));
var handlerResolver = new StructureMapHandlerResolver(container);
var handlers = handlerResolver.ResolveHandlers<OrderPlaced>().ToList();
Assert.That(handlers.Count, Is.EqualTo(1));
var blockingHandler = (BlockingHandler<OrderPlaced>)handlers[0];
_resolvedHandler = (BlockingOrderProcessor)blockingHandler.Inner;
DoneSignal = _resolvedHandler.DoneSignal.Task;
var subscriber = CreateMeABus.InRegion("eu-west-1")
.WithSqsTopicSubscriber()
.IntoQueue("container-test")
.WithMessageHandler<OrderPlaced>(handlerResolver);
subscriber.StartListening();
}
[Test]
public void ThenHandlerWillReceiveTheMessage()
{
_resolvedHandler.ReceivedMessageCount.ShouldBeGreaterThan(0);
}
}
}``` |
e95a036c-07b0-4415-a698-b9d8f047393a | {
"language": "C#"
} | ```c#
using System;
namespace ReadLine
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
static ReadLine()
{
_keyHandler = new KeyHandler();
}
public static string Read()
{
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
return _keyHandler.Text;
}
}
}
```
Create new instance of KeyHandler on every call to Read method | ```c#
using System;
namespace ReadLine
{
public static class ReadLine
{
private static KeyHandler _keyHandler;
public static string Read()
{
_keyHandler = new KeyHandler();
ConsoleKeyInfo keyInfo = Console.ReadKey(true);
while (keyInfo.Key != ConsoleKey.Enter)
{
_keyHandler.Handle(keyInfo);
keyInfo = Console.ReadKey(true);
}
return _keyHandler.Text;
}
}
}
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.