commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13 values | lang stringclasses 23 values |
|---|---|---|---|---|---|---|---|---|
e538150ffe9c1db0c918c11ce2a58b536a44de76 | Update (simplify) padding | IvionSauce/MeidoBot | NyaaSpam/OutputTools.cs | NyaaSpam/OutputTools.cs | using System;
using System.Collections.Generic;
static class OutputTools
{
public static IEnumerable<string> TwoColumns(string[] patterns)
{
var half = (int)Math.Ceiling(patterns.Length / 2d);
int longestLength = 0;
for (int i = 0; i < half; i++)
{
if (patterns[i].Length > longestLength)
longestLength = patterns[i].Length;
}
int j;
for (int i = 0; i < half; i++)
{
j = i + half;
if (j < patterns.Length)
{
var patternLeft = Pad(patterns[i], longestLength);
var patternRight = patterns[j];
yield return string.Format("[{0}] {1} [{2}] {3}", i, patternLeft, j, patternRight);
}
else
yield return string.Format("[{0}] {1}", i, patterns[i]);
}
}
static string Pad(string s, int totalLength)
{
int padding = totalLength - s.Length;
// Padoru, padoru.
if (padding > 0)
return s + new string(' ', padding);
else
return s;
}
} | using System;
using System.Text;
using System.Collections.Generic;
static class OutputTools
{
public static IEnumerable<string> TwoColumns(string[] patterns)
{
var half = (int)Math.Ceiling(patterns.Length / 2d);
int longestLength = 0;
for (int i = 0; i < half; i++)
{
if (patterns[i].Length > longestLength)
longestLength = patterns[i].Length;
}
int j;
for (int i = 0; i < half; i++)
{
j = i + half;
if (j < patterns.Length)
{
var patternLeft = Pad(patterns[i], longestLength);
var patternRight = patterns[j];
yield return string.Format("[{0}] {1} [{2}] {3}", i, patternLeft, j, patternRight);
}
else
yield return string.Format("[{0}] {1}", i, patterns[i]);
}
}
static string Pad(string s, int totalLength)
{
string padded;
// Padoru, padoru.
if (s.Length < totalLength)
{
var builder = new StringBuilder(s, totalLength);
while (builder.Length < totalLength)
{
builder.Append(' ');
}
padded = builder.ToString();
}
// No padoru necessary.
else
padded = s;
return padded;
}
} | bsd-2-clause | C# |
ca20a5062d186cc43ec16bd7f5d888459c863e46 | set background border to be applied logically | Willster419/RelicModManager,Willster419/RelhaxModpack,Willster419/RelhaxModpack | RelhaxModpack/RelhaxModpack/UIComponents/ClassThemeDefinitions/BorderClassThemeDefinition.cs | RelhaxModpack/RelhaxModpack/UIComponents/ClassThemeDefinitions/BorderClassThemeDefinition.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace RelhaxModpack.UIComponents.ClassThemeDefinitions
{
public class BorderClassThemeDefinition : IClassThemeDefinition
{
public Type ClassType { get; } = typeof(Border);
//background
public bool BackgroundAllowed { get; } = true;
public string BackgroundBoundName { get; } = string.Empty;
public bool BackgroundAppliedLocal { get; } = true;
public DependencyProperty BackgroundDependencyProperty { get; } = Border.BackgroundProperty;
//foreground
public bool ForegroundAllowed { get; } = false;
public string ForegroundBoundName { get; } = string.Empty;
public bool ForegroundAppliedLocal { get; } = false;
public DependencyProperty ForegroundDependencyProperty { get; } = null;
//highlight
public bool HighlightAllowed { get; } = false;
public string HighlightBoundName { get; } = string.Empty;
//select
public bool SelectAllowed { get; } = false;
public string SelectBoundName { get; } = string.Empty;
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace RelhaxModpack.UIComponents.ClassThemeDefinitions
{
public class BorderClassThemeDefinition : IClassThemeDefinition
{
public Type ClassType { get; } = typeof(Border);
//background
public bool BackgroundAllowed { get; } = true;
public string BackgroundBoundName { get; } = string.Empty;
public bool BackgroundAppliedLocal { get; } = false;
public DependencyProperty BackgroundDependencyProperty { get; } = Border.BackgroundProperty;
//foreground
public bool ForegroundAllowed { get; } = false;
public string ForegroundBoundName { get; } = string.Empty;
public bool ForegroundAppliedLocal { get; } = false;
public DependencyProperty ForegroundDependencyProperty { get; } = null;
//highlight
public bool HighlightAllowed { get; } = false;
public string HighlightBoundName { get; } = string.Empty;
//select
public bool SelectAllowed { get; } = false;
public string SelectBoundName { get; } = string.Empty;
}
}
| apache-2.0 | C# |
d18e8b04b3df0023519fae781421df695761037d | Enable error traces for Razor. | eidolonic/plating,eidolonic/plating | Plating/Bootstrapper.cs | Plating/Bootstrapper.cs | using Nancy;
namespace Plating
{
public class Bootstrapper : DefaultNancyBootstrapper
{
public Bootstrapper()
{
StaticConfiguration.DisableErrorTraces = false;
Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true;
}
}
} | using Nancy;
namespace Plating
{
public class Bootstrapper : DefaultNancyBootstrapper
{
public Bootstrapper()
{
Cassette.Nancy.CassetteNancyStartup.OptimizeOutput = true;
}
}
} | mit | C# |
7a26d0ea7b75dbe6b3aee3f30633048c889dcba2 | Change class name to OrderingTypes. | LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform,LykkeCity/CompetitionPlatform | src/CompetitionPlatform/Helpers/StreamsConstants.cs | src/CompetitionPlatform/Helpers/StreamsConstants.cs | namespace CompetitionPlatform.Helpers
{
public static class StreamsRoles
{
public const string Admin = "ADMIN";
}
public static class ResultVoteTypes
{
public const string Admin = "ADMIN";
public const string Author = "AUTHOR";
}
public static class OrderingTypes
{
public const string All = "All";
public const string Ascending = "Ascending";
public const string Descending = "Descending";
}
public static class LykkeEmailDomains
{
public const string LykkeCom = "lykke.com";
public const string LykkexCom = "lykkex.com";
}
}
| namespace CompetitionPlatform.Helpers
{
public static class StreamsRoles
{
public const string Admin = "ADMIN";
}
public static class ResultVoteTypes
{
public const string Admin = "ADMIN";
public const string Author = "AUTHOR";
}
public static class OrderingConstants
{
public const string All = "All";
public const string Ascending = "Ascending";
public const string Descending = "Descending";
}
public static class LykkeEmailDomains
{
public const string LykkeCom = "lykke.com";
public const string LykkexCom = "lykkex.com";
}
}
| mit | C# |
d2b7e0d11a449b2ad0143ed11fd271d1b3a21e60 | Order of properties is important | phatboyg/Stact,phatboyg/Stact,phatboyg/Stact,phatboyg/Stact | src/Magnum.Common.Tests/Reflection/InterOp_Specs.cs | src/Magnum.Common.Tests/Reflection/InterOp_Specs.cs | namespace Magnum.Common.Tests.Reflection
{
using NUnit.Framework;
[TestFixture]
public class InterOp_Specs :
SerializationSpecificationBase
{
private readonly Bob _bob = new Bob { Name = "Dru" };
private readonly Order1 _order = new Order1{FirstName = "Chris", LastName = "Patterson"};
[Test]
public void Shouldnt_care_about_namespaces()
{
byte[] bytes;
bytes = Serialize(_bob);
var output = Deserialize<Different.Bob>(bytes);
Assert.AreEqual(_bob.Name, output.Name);
}
[Test]
public void Shouldnt_care_about_class_names()
{
byte[] bytes;
bytes = Serialize(_bob);
var output = Deserialize<Bill>(bytes);
Assert.AreEqual(_bob.Name, output.Name);
}
[Test]
public void Shouldnt_care_about_casing()
{
byte[] bytes;
bytes = Serialize(_bob);
var output = Deserialize<Jack>(bytes);
Assert.AreEqual(_bob.Name, output.name);
}
[Test]
public void Shouldnt_care_about_order()
{
byte[] bytes;
bytes = Serialize(_order);
var output = Deserialize<Order2>(bytes);
Assert.AreEqual(_order.FirstName, output.FirstName);
Assert.AreEqual(_order.LastName, output.LastName);
}
public class Bob
{
public string Name { get; set; }
}
public class Bill
{
public string Name { get; set; }
}
public class Jack
{
public string name { get; set; }
}
public class Order1
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Order2
{
public string LastName { get; set; }
public string FirstName { get; set; }
}
}
namespace Different
{
public class Bob
{
public string Name { get; set; }
}
}
} | namespace Magnum.Common.Tests.Reflection
{
using System.Diagnostics;
using NUnit.Framework;
[TestFixture]
public class InterOp_Specs :
SerializationSpecificationBase
{
private readonly Bob bob = new Bob{Name="Dru"};
[Test]
public void Shouldnt_care_about_namespaces()
{
byte[] bytes;
bytes = Serialize(bob);
var output = Deserialize<Different.Bob>(bytes);
Assert.AreEqual(bob.Name, output.Name);
}
[Test]
public void Shouldnt_care_about_class_names()
{
byte[] bytes;
bytes = Serialize(bob);
var output = Deserialize<Bill>(bytes);
Assert.AreEqual(bob.Name, output.Name);
}
[Test]
public void Shouldnt_care_about_casing()
{
byte[] bytes;
bytes = Serialize(bob);
var output = Deserialize<Jack>(bytes);
Assert.AreEqual(bob.Name, output.name);
}
}
public class Bob
{
public string Name { get; set; }
}
public class Bill
{
public string Name { get; set; }
}
public class Jack
{
public string name { get; set; }
}
namespace Different
{
public class Bob
{
public string Name { get; set; }
}
}
} | apache-2.0 | C# |
85df77d57eba1dbe41f7829e3fbb80418291b200 | Fix sonarqube issue | coenm/PlaygroundCoreDotNet,coenm/PlaygroundCoreDotNet | src/Playground.Calculator/SystemDateTimeProvider.cs | src/Playground.Calculator/SystemDateTimeProvider.cs | using System;
namespace Playground.Calculator
{
public class SystemDateTimeProvider : IDateTimeProvider
{
public static SystemDateTimeProvider Instance { get; } = new SystemDateTimeProvider();
private SystemDateTimeProvider()
{
}
public DateTime Now => DateTime.Now;
}
} | using System;
namespace Playground.Calculator
{
public class SystemDateTimeProvider : IDateTimeProvider
{
public static SystemDateTimeProvider Instance = new SystemDateTimeProvider();
private SystemDateTimeProvider()
{
}
public DateTime Now => DateTime.Now;
}
} | mit | C# |
8f9c1a92539b14733a4c2246e010222b023dc87e | Update Program.cs | medhajoshi27/GitTest1 | ConsoleApplication1/ConsoleApplication1/Program.cs | ConsoleApplication1/ConsoleApplication1/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//hello
Console.WriteLine("HELLO");
Console.WriteLine("World");
//medha
//in vs
Console.WriteLine("Medha");
//in github
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//hello
Console.WriteLine("HELLO");
Console.WriteLine("World");
//medha
//in vs
Console.WriteLine("Medha");
}
}
}
| mit | C# |
2b29f235e608a82619ed7dccb916e54ee00a14ca | comment the code | chjwilliams/DreamTeam | DreamTeam/Assets/Scripts/NPC/BasicNPCController.cs | DreamTeam/Assets/Scripts/NPC/BasicNPCController.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/*--------------------------------------------------------------------------------------*/
/* */
/* BasicNPCController: Handles baisc npc behavior */
/* Functions: */
/* public: */
/* startGestureAnimation() */
/* OnTriggerEnter() */
/* OnTriggerStay() */
/* OnTriggerStay() */
/* OnTriggerExit() */
/*--------------------------------------------------------------------------------------*/
public class BasicNPCController : MonoBehaviour {
public bool gestureAnimationDone; //whether we have done the gesture animation
public HartoTuningController HARTO; //Game object HARTO
public float myFrequency; //
public float range;
public bool acknowledgePlayer;
// Use this for initialization
void Start () {
HARTO = GameObject.FindGameObjectWithTag ("HARTO").GetComponent<HartoTuningController> (); //get the HARTO thourgh find the tag of HARTO
myFrequency = 60; //the frequency you can talk to me
range = 2.5f; // the range of the frequency you can talk to me
acknowledgePlayer = false; //I am not talking with the player
gestureAnimationDone = false; //at the start, gesture animation has not shown yet
}
// Update is called once per frame
void Update () {
}
//the function we start play the animation
public void startGestureAnimation() {
gestureAnimationDone = true; //set this bool to true after we played the animation
GetComponent<MeshRenderer> ().material.color = new Color (0.0f, 0.0f, 0.0f); // change the color of the object after we played the animation
}
//the function we call when the other collider enter this collision
void OnTriggerEnter(Collider other) {
if (other.gameObject.CompareTag ("Astrid")) { //if the other collider has the tag of "Astrid" , do the stuff
if (!acknowledgePlayer) { //whether the player is talking with other game object? if not, do the stuff
transform.Translate (Vector3.up); //lift me up if I am talking to player. That's why I am shaking.
acknowledgePlayer = true; //Other script will know I am talking to player
}
}
}
//the function we call when the trigger hang there
void OnTriggerStay(Collider other) {
if (other.gameObject.CompareTag ("Astrid")) { //if the other collider has the tag of "Astrid" , do the stuff
Vector3 delta = new Vector3(other.gameObject.transform.position.x - transform.position.x, 0.0f, other.gameObject.transform.position.z - transform.position.z); //get the position of the collider who enter
Quaternion rotation = Quaternion.LookRotation(delta); //rotation in that direction?
transform.rotation = rotation; //make the rotation to the enter's rotation?
//if you are in the right frequency, change the color, to let player know they got it right.
if (HARTO.currentfrequency > myFrequency - range && HARTO.currentfrequency < myFrequency + range) {
GetComponent<MeshRenderer> ().material.color = new Color (0.0f, 0.0f, 1.0f);
}
//else if the animation has not shown yet, change the color
else if (!gestureAnimationDone){
GetComponent<MeshRenderer> ().material.color = new Color (1.0f, 0.0f, 0.0f);
}
}
}
//if the collider leave me, stop talking to the player, and also let other game object know that.
void OnTriggerExit(Collider other) {
acknowledgePlayer = false;
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BasicNPCController : MonoBehaviour {
public bool gestureAnimationDone;
public HartoTuningController HARTO;
public float myFrequency;
public float range;
public bool acknowledgePlayer;
// Use this for initialization
void Start () {
HARTO = GameObject.FindGameObjectWithTag ("HARTO").GetComponent<HartoTuningController> ();
myFrequency = 60;
range = 2.5f;
acknowledgePlayer = false;
gestureAnimationDone = false;
}
// Update is called once per frame
void Update () {
}
public void startGestureAnimation() {
gestureAnimationDone = true;
GetComponent<MeshRenderer> ().material.color = new Color (0.0f, 0.0f, 0.0f);
}
void OnTriggerEnter(Collider other) {
if (other.gameObject.CompareTag ("Astrid")) {
if (!acknowledgePlayer) {
transform.Translate (Vector3.up);
acknowledgePlayer = true;
}
}
}
void OnTriggerStay(Collider other) {
if (other.gameObject.CompareTag ("Astrid")) {
Vector3 delta = new Vector3(other.gameObject.transform.position.x - transform.position.x, 0.0f, other.gameObject.transform.position.z - transform.position.z);
Quaternion rotation = Quaternion.LookRotation(delta);
transform.rotation = rotation;
if (HARTO.currentfrequency > myFrequency - range && HARTO.currentfrequency < myFrequency + range) {
GetComponent<MeshRenderer> ().material.color = new Color (0.0f, 0.0f, 1.0f);
}
else if (!gestureAnimationDone){
GetComponent<MeshRenderer> ().material.color = new Color (1.0f, 0.0f, 0.0f);
}
}
}
void OnTriggerExit(Collider other) {
acknowledgePlayer = false;
}
}
| unlicense | C# |
18b8d9ebb1a26ca6f62ac9172d72e71a86808a69 | Fix DesktopUrhoInitializer.cs for D3D mode. | florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho,florin-chelaru/urho | Bindings/Desktop/DesktopUrhoInitializer.cs | Bindings/Desktop/DesktopUrhoInitializer.cs | using System;
using System.IO;
using System.Reflection;
namespace Urho.Desktop
{
public static class DesktopUrhoInitializer
{
static string assetsDirectory;
/// <summary>
/// Path to a folder containing "Data" folder. CurrentDirectory if null
/// </summary>
public static string AssetsDirectory
{
get { return assetsDirectory; }
set
{
assetsDirectory = value;
if (!string.IsNullOrEmpty(assetsDirectory))
{
if (!Directory.Exists(assetsDirectory))
{
throw new InvalidDataException($"Directory {assetsDirectory} not found");
}
const string coreDataFile = "CoreData.pak";
System.IO.File.Copy(
sourceFileName: Path.Combine(Environment.CurrentDirectory, coreDataFile),
destFileName: Path.Combine(assetsDirectory, coreDataFile),
overwrite: true);
Environment.CurrentDirectory = assetsDirectory;
}
}
}
internal static void OnInited()
{
var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
//unlike the OS X, windows doesn't support FAT binaries
if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
!Environment.Is64BitProcess &&
Is64Bit(Path.Combine(currentPath, Consts.NativeImport + ".dll")))
{
throw new NotSupportedException("mono-urho.dll is 64bit, but current process is x86 (change target platform from Any CPU/x86 to x64)");
}
}
public static void CopyEmbeddedCoreDataTo(string destinationFolder)
{
using (Stream input = typeof(SimpleApplication).Assembly.GetManifestResourceStream("Urho.CoreData.pak"))
using (Stream output = File.Create(Path.Combine(destinationFolder, "CoreData.pak")))
input.CopyTo(output);
}
static bool Is64Bit(string dllPath)
{
using (var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read))
using (var br = new BinaryReader(fs))
{
fs.Seek(0x3c, SeekOrigin.Begin);
var peOffset = br.ReadInt32();
fs.Seek(peOffset, SeekOrigin.Begin);
var value = br.ReadUInt16();
const ushort IMAGE_FILE_MACHINE_AMD64 = 0x8664;
const ushort IMAGE_FILE_MACHINE_IA64 = 0x200;
return value == IMAGE_FILE_MACHINE_AMD64 ||
value == IMAGE_FILE_MACHINE_IA64;
}
}
}
}
| using System;
using System.IO;
using System.Reflection;
namespace Urho.Desktop
{
public static class DesktopUrhoInitializer
{
static string assetsDirectory;
/// <summary>
/// Path to a folder containing "Data" folder. CurrentDirectory if null
/// </summary>
public static string AssetsDirectory
{
get { return assetsDirectory; }
set
{
assetsDirectory = value;
if (!string.IsNullOrEmpty(assetsDirectory))
{
if (!Directory.Exists(assetsDirectory))
{
throw new InvalidDataException($"Directory {assetsDirectory} not found");
}
const string coreDataFile = "CoreData.pak";
System.IO.File.Copy(
sourceFileName: Path.Combine(Environment.CurrentDirectory, coreDataFile),
destFileName: Path.Combine(assetsDirectory, coreDataFile),
overwrite: true);
Environment.CurrentDirectory = assetsDirectory;
}
}
}
internal static void OnInited()
{
var currentPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
//unlike the OS X, windows doesn't support FAT binaries
if (Environment.OSVersion.Platform == PlatformID.Win32NT &&
!Environment.Is64BitProcess &&
Is64Bit(Path.Combine(currentPath, "mono-urho.dll")))
{
throw new NotSupportedException("mono-urho.dll is 64bit, but current process is x86 (change target platform from Any CPU/x86 to x64)");
}
}
public static void CopyEmbeddedCoreDataTo(string destinationFolder)
{
using (Stream input = typeof(SimpleApplication).Assembly.GetManifestResourceStream("Urho.CoreData.pak"))
using (Stream output = File.Create(Path.Combine(destinationFolder, "CoreData.pak")))
input.CopyTo(output);
}
static bool Is64Bit(string dllPath)
{
using (var fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read))
using (var br = new BinaryReader(fs))
{
fs.Seek(0x3c, SeekOrigin.Begin);
var peOffset = br.ReadInt32();
fs.Seek(peOffset, SeekOrigin.Begin);
var value = br.ReadUInt16();
const ushort IMAGE_FILE_MACHINE_AMD64 = 0x8664;
const ushort IMAGE_FILE_MACHINE_IA64 = 0x200;
return value == IMAGE_FILE_MACHINE_AMD64 ||
value == IMAGE_FILE_MACHINE_IA64;
}
}
}
}
| mit | C# |
46d0c31003264c409fbe2161cee3811e55eff2f4 | Remove variável desncessária | CristianoRC/DotCEP | DotCEP/DotCEP.Localidades/BancosDeDados.cs | DotCEP/DotCEP.Localidades/BancosDeDados.cs | using System;
using Microsoft.Data.Sqlite;
namespace DotCEP.Localidades
{
internal class BancosDeDados
{
internal BancosDeDados()
{
Conexao = new SqliteConnection($@"Data Source={AppDomain.CurrentDomain.BaseDirectory}Lugares.db");
}
internal SqliteConnection Conexao { get; }
}
} | using System;
using Microsoft.Data.Sqlite;
namespace DotCEP.Localidades
{
internal class BancosDeDados
{
internal BancosDeDados()
{
var asd = $"{AppDomain.CurrentDomain.BaseDirectory}Lugares.db";
Conexao = new SqliteConnection($@"Data Source={AppDomain.CurrentDomain.BaseDirectory}Lugares.db");
}
internal SqliteConnection Conexao { get; }
}
} | mit | C# |
d5d6f626845c30f5c00b799468bfd5a58933f68b | Add BoolParameter and IntParameter to enum | faint32/snowflake-1,RonnChyran/snowflake,SnowflakePowered/snowflake,SnowflakePowered/snowflake,RonnChyran/snowflake,SnowflakePowered/snowflake,faint32/snowflake-1,faint32/snowflake-1,RonnChyran/snowflake | Snowflake.API/Ajax/AjaxMethodParameterAttribute.cs | Snowflake.API/Ajax/AjaxMethodParameterAttribute.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Ajax
{
/// <summary>
/// A metadata attribute to indicate parameter methods
/// Does not affect execution.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class AjaxMethodParameterAttribute : Attribute
{
public string ParameterName { get; set; }
public AjaxMethodParameterType ParameterType { get; set; }
}
public enum AjaxMethodParameterType
{
StringParameter,
ObjectParameter,
ArrayParameter,
BoolParameter,
IntParameter
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Snowflake.Ajax
{
/// <summary>
/// A metadata attribute to indicate parameter methods
/// Does not affect execution.
/// </summary>
[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public class AjaxMethodParameterAttribute : Attribute
{
public string ParameterName { get; set; }
public AjaxMethodParameterType ParameterType { get; set; }
}
public enum AjaxMethodParameterType
{
StringParameter,
ObjectParameter,
ArrayParameter
}
}
| mpl-2.0 | C# |
cee289864b2385f2e13c6f5872fe5e5f8f3bfea9 | Update AssemblyVersion | tmds/Tmds.DBus | AssemblyInfo.cs | AssemblyInfo.cs | // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("0.4.0")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
| // Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
using System.Reflection;
using System.Runtime.CompilerServices;
//[assembly: AssemblyVersion("0.0.0.*")]
[assembly: AssemblyTitle ("NDesk.DBus")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker")]
[assembly: AssemblyCompany ("NDesk")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("NDesk.DBus.GLib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
| mit | C# |
5899d056c2cd3fb52dcd3d32a29cbbc35fc43e43 | Update email address. | huin/kerbcam2 | kerbcam2/Properties/AssemblyInfo.cs | kerbcam2/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("kerbcam2")]
[assembly: AssemblyDescription("KSP camera sequencing tool")]
[assembly: AssemblyProduct("kerbcam2")]
[assembly: AssemblyCopyright("Copyright © John Beisley <johnbeisleyuk@gmail.com> 2014")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("16dbc4f2-2c20-4b80-a343-dbde02e084b7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("kerbcam2")]
[assembly: AssemblyDescription("KSP camera sequencing tool")]
[assembly: AssemblyProduct("kerbcam2")]
[assembly: AssemblyCopyright("Copyright © John Beisley <greatred@gmail.com> 2014")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("16dbc4f2-2c20-4b80-a343-dbde02e084b7")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("0.1.*")]
| bsd-3-clause | C# |
cb4094418bace2604579f80126fc86332dcad783 | rename bool arg. | edwinj85/ezDoom | ezDoom/Code/GameProcessHandler.cs | ezDoom/Code/GameProcessHandler.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace ezDoom.Code
{
/// <summary>
/// This class handles launching the doom engine with chosen settings.
/// </summary>
public static class GameProcessHandler
{
/// <summary>
/// This method launches the doom engine with chosen settings.
/// </summary>
public static void RunGame(string IWADPath, IEnumerable<GamePackage> mods, bool useSoftwareRendering)
{
//use a string builder to take all the chosen mods and turn them into a string we can pass as an argument.
StringBuilder sb = new StringBuilder();
foreach (GamePackage item in mods)
{
sb.Append($"\"../{ConstStrings.ModsFolderName}/{item.FullName}\" ");
}
string chosenPackages = sb.ToString();
//create process to launch the game.
var details = new ProcessStartInfo(Path.Combine(ConstStrings.EngineFolderName, ConstStrings.GzDoomExeName));
details.UseShellExecute = false; //we need to set UseShellExecute to false to make the exe run from the local folder.
//Store game saves in the user's saved games folder.
var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var savesDirectoryRaw = Path.Combine(userDirectory, ConstStrings.GameSaveFolderName);
var savesDirectory = $"\"{savesDirectoryRaw}\"".Replace(@"\", "/");
var renderingOptions = useSoftwareRendering ? "+set vid_renderer 0" : "+set vid_renderer 1";
//launch GZDoom with the correct args.
details.Arguments = $"-iwad ../iwads/\"{IWADPath}\" -file {chosenPackages} -savedir {savesDirectory} {renderingOptions}";
//we wrap the process in a using statement to make sure the handle is always disposed after use.
using (Process process = Process.Start(details)) { };
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
namespace ezDoom.Code
{
/// <summary>
/// This class handles launching the doom engine with chosen settings.
/// </summary>
public static class GameProcessHandler
{
/// <summary>
/// This method launches the doom engine with chosen settings.
/// </summary>
public static void RunGame(string IWADPath, IEnumerable<GamePackage> mods, bool softwareRendering)
{
//use a string builder to take all the chosen mods and turn them into a string we can pass as an argument.
StringBuilder sb = new StringBuilder();
foreach (GamePackage item in mods)
{
sb.Append($"\"../{ConstStrings.ModsFolderName}/{item.FullName}\" ");
}
string chosenPackages = sb.ToString();
//create process to launch the game.
var details = new ProcessStartInfo(Path.Combine(ConstStrings.EngineFolderName, ConstStrings.GzDoomExeName));
details.UseShellExecute = false; //we need to set UseShellExecute to false to make the exe run from the local folder.
//Store game saves in the user's saved games folder.
var userDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var savesDirectoryRaw = Path.Combine(userDirectory, ConstStrings.GameSaveFolderName);
var savesDirectory = $"\"{savesDirectoryRaw}\"".Replace(@"\", "/");
var renderingOptions = softwareRendering ? "+set vid_renderer 0" : "+set vid_renderer 1";
//launch GZDoom with the correct args.
details.Arguments = $"-iwad ../iwads/\"{IWADPath}\" -file {chosenPackages} -savedir {savesDirectory} {renderingOptions}";
//we wrap the process in a using statement to make sure the handle is always disposed after use.
using (Process process = Process.Start(details)) { };
}
}
}
| apache-2.0 | C# |
6ccf7c5999497ed96f58e6d49d6a724aab06a95a | fix spacing | fabianPas/TradeRouteMarketeer,fabianPas/TradeRouteMarketeer | TradeRouteMarketeer/Models/Market/Trade.cs | TradeRouteMarketeer/Models/Market/Trade.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TradeRouteMarketeer.Models.Market
{
public class Trade
{
public string Commodity { get; set; }
public string Outlet { get; set; }
public int TradePrice { get; set; }
public int Amount { get; set; }
public Trade(string commodity, string outlet, int tradePrice, int amount)
{
Commodity = commodity;
Outlet = outlet;
TradePrice = tradePrice;
Amount = amount;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace TradeRouteMarketeer.Models.Market
{
public class Trade
{
public string Commodity { get; set; }
public string Outlet { get; set; }
public int TradePrice { get; set; }
public int Amount { get; set; }
public Trade(string commodity, string outlet, int tradePrice, int amount)
{
Commodity = commodity;
Outlet = outlet;
TradePrice = tradePrice;
Amount = amount;
}
}
}
| apache-2.0 | C# |
c1a8ac00efd76a80bc4db0df515aa3a66eacbc70 | fix retry | LykkeCity/bitcoinservice,LykkeCity/bitcoinservice | src/LkeServices/Helpers/Retry.cs | src/LkeServices/Helpers/Retry.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common.Log;
namespace LkeServices.Helpers
{
public class Retry
{
public static async Task<T> Try<T>(Func<Task<T>> action, Func<Exception, bool> exceptionFilter, int tryCount, ILog logger)
{
int @try = 0;
while (true)
{
try
{
return await action();
}
catch (Exception ex)
{
@try++;
if (!exceptionFilter(ex) || @try >= tryCount)
throw;
await logger.WriteErrorAsync("Retry", "Try", null, ex);
}
}
}
public static async Task Try(Func<Task> action, Func<Exception, bool> exceptionFilter, int tryCount, ILog logger)
{
int @try = 0;
while (true)
{
try
{
await action();
return;
}
catch (Exception ex)
{
@try++;
if (!exceptionFilter(ex) || @try >= tryCount)
throw;
await logger.WriteErrorAsync("Retry", "Try", null, ex);
}
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Common.Log;
namespace LkeServices.Helpers
{
public class Retry
{
public static async Task<T> Try<T>(Func<Task<T>> action, Func<Exception, bool> exceptionFilter, int tryCount, ILog logger)
{
int @try = 0;
while (true)
{
try
{
return await action();
}
catch (Exception ex)
{
@try++;
if (!exceptionFilter(ex) || @try >= tryCount)
throw;
await logger.WriteErrorAsync("Retry", "Try", null, ex);
}
}
}
public static async Task Try(Func<Task> action, Func<Exception, bool> exceptionFilter, int tryCount, ILog logger)
{
int @try = 0;
while (true)
{
try
{
await action();
}
catch (Exception ex)
{
@try++;
if (!exceptionFilter(ex) || @try >= tryCount)
throw;
await logger.WriteErrorAsync("Retry", "Try", null, ex);
}
}
}
}
}
| mit | C# |
57f3eba0d75924d3e48436c35b0b89f5ecd50790 | Make BotBitsClient inherit IDisposable | Yonom/BotBits | BotBits/Client/BotBitsClient.cs | BotBits/Client/BotBitsClient.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using BotBits.Events;
using JetBrains.Annotations;
namespace BotBits
{
public class BotBitsClient : IDisposable
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly PackageLoader _packageLoader;
private int _disposed;
public BotBitsClient() : this(BotServices.GetScheduler())
{
}
internal BotBitsClient(ISchedulerHandle handle)
{
this._packageLoader = new PackageLoader(this);
this.Extensions = new List<Type>();
DefaultExtension.LoadInto(this, handle);
Scheduler.Of(this).InitScheduler(false);
}
[UsedImplicitly]
internal PackageLoader Packages => this._packageLoader;
internal List<Type> Extensions { get; }
public void Dispose()
{
if (Interlocked.Exchange(ref this._disposed, 1) == 0)
{
new DisposingEvent().RaiseIn(this);
this._packageLoader.Dispose();
new DisposedEvent().RaiseIn(this);
}
}
}
} | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using BotBits.Events;
using JetBrains.Annotations;
namespace BotBits
{
public class BotBitsClient
{
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly PackageLoader _packageLoader;
private int _disposed;
public BotBitsClient() : this(BotServices.GetScheduler())
{
}
internal BotBitsClient(ISchedulerHandle handle)
{
this._packageLoader = new PackageLoader(this);
this.Extensions = new List<Type>();
DefaultExtension.LoadInto(this, handle);
Scheduler.Of(this).InitScheduler(false);
}
[UsedImplicitly]
internal PackageLoader Packages => this._packageLoader;
internal List<Type> Extensions { get; }
public void Dispose()
{
if (Interlocked.Exchange(ref this._disposed, 1) == 0)
{
new DisposingEvent().RaiseIn(this);
this._packageLoader.Dispose();
new DisposedEvent().RaiseIn(this);
}
}
}
} | mit | C# |
c3bee8d15f3cde2ca9cf17d895b484105b2a2578 | Update INumbers.cs | aliostad/RandomGen,aliostad/RandomGen | src/RandomGen/Fluent/INumbers.cs | src/RandomGen/Fluent/INumbers.cs | using System;
using System.Collections.Generic;
namespace RandomGen.Fluent
{
public interface INumbers : IFluentInterface
{
Func<byte> Bytes(byte min = byte.MinValue, byte max = byte.MaxValue);
Func<int> Integers(int min = 0, int max = 100);
Func<IEnumerable<int>> IntegersDrawNoPlacement(int min = 0, int max = 100, int take = 1);
Func<uint> UnsignedIntegers(uint min = 0, uint max = 100);
Func<long> Longs(long min = 0, long max = 100);
IDouble Doubles();
Func<double> Doubles(double min, double max);
Func<decimal> Decimals(decimal min = 0, decimal max = 1);
Func<bool> Booleans();
}
}
| using System;
using System.Collections.Generic;
namespace RandomGen.Fluent
{
public interface INumbers : IFluentInterface
{
Func<byte> Bytes(byte min = byte.MinValue, byte max = byte.MaxValue);
Func<int> Integers(int min = 0, int max = 100);
Func<uint> UnsignedIntegers(uint min = 0, uint max = 100);
Func<long> Longs(long min = 0, long max = 100);
IDouble Doubles();
Func<double> Doubles(double min, double max);
Func<decimal> Decimals(decimal min = 0, decimal max = 1);
Func<bool> Booleans();
Func<IEnumerable<int>> IntegersDrawNoPlacement(int min = 0, int max = 100, int take_number = 1);
}
}
| mit | C# |
072b447518f95b2795aa200343cd4ecdde92dfaa | Delete dead code | sean-gilliam/msbuild,AndyGerlicher/msbuild,rainersigwald/msbuild,AndyGerlicher/msbuild,rainersigwald/msbuild,sean-gilliam/msbuild,rainersigwald/msbuild,AndyGerlicher/msbuild,rainersigwald/msbuild,sean-gilliam/msbuild,AndyGerlicher/msbuild,sean-gilliam/msbuild | src/Build/BackEnd/Node/ServerNamedMutex.cs | src/Build/BackEnd/Node/ServerNamedMutex.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
namespace Microsoft.Build.Execution
{
internal sealed class ServerNamedMutex : IDisposable
{
private readonly Mutex _serverMutex;
public bool IsDisposed { get; private set; }
public bool IsLocked { get; private set; }
public ServerNamedMutex(string mutexName, out bool createdNew)
{
_serverMutex = new Mutex(
initiallyOwned: true,
name: mutexName,
createdNew: out createdNew);
if (createdNew)
{
IsLocked = true;
}
}
internal static ServerNamedMutex OpenOrCreateMutex(string name, out bool createdNew)
{
return new ServerNamedMutex(name, out createdNew);
}
public static bool WasOpen(string mutexName)
{
bool result = Mutex.TryOpenExisting(mutexName, out Mutex? mutex);
mutex?.Dispose();
return result;
}
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
try
{
if (IsLocked)
{
_serverMutex.ReleaseMutex();
}
}
finally
{
_serverMutex.Dispose();
IsLocked = false;
}
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Threading;
namespace Microsoft.Build.Execution
{
internal sealed class ServerNamedMutex : IDisposable
{
private readonly Mutex _serverMutex;
public bool IsDisposed { get; private set; }
public bool IsLocked { get; private set; }
public ServerNamedMutex(string mutexName, out bool createdNew)
{
_serverMutex = new Mutex(
initiallyOwned: true,
name: mutexName,
createdNew: out createdNew);
if (createdNew)
{
IsLocked = true;
}
}
internal static ServerNamedMutex OpenOrCreateMutex(string name, out bool createdNew)
{
return new ServerNamedMutex(name, out createdNew);
}
public static bool WasOpen(string mutexName)
{
bool result = Mutex.TryOpenExisting(mutexName, out Mutex? mutex);
mutex?.Dispose();
return result;
}
public bool TryLock(int timeoutMs)
{
if (IsDisposed)
{
throw new ObjectDisposedException(nameof(ServerNamedMutex));
}
if (IsLocked)
{
throw new InvalidOperationException("Lock already held");
}
return IsLocked = _serverMutex.WaitOne(timeoutMs);
}
public void Dispose()
{
if (IsDisposed)
{
return;
}
IsDisposed = true;
try
{
if (IsLocked)
{
_serverMutex.ReleaseMutex();
}
}
finally
{
_serverMutex.Dispose();
IsLocked = false;
}
}
}
}
| mit | C# |
2626f6d934e382ef8ed3cc850afa303f3963cff1 | add null checks | ericBG/AnyfinCalculator | AnyfinCalculator/AnyfinCalculator/GraveyardHelper.cs | AnyfinCalculator/AnyfinCalculator/GraveyardHelper.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Hearthstone_Deck_Tracker.Hearthstone;
using Hearthstone_Deck_Tracker.API;
namespace AnyfinCalculator
{
public class GraveyardHelper
{
private readonly Predicate<Card> _shouldBeTracked;
private List<Card> _checkedMinions = new List<Card>();
public GraveyardHelper(Predicate<Card> shouldBeTracked = null)
{
_shouldBeTracked = shouldBeTracked;
}
public IEnumerable<Card> TrackedMinions
=> (Core.Game.Player.Graveyard ?? Enumerable.Empty<CardEntity>()).Select(ce => ce.Entity.Card)
.Concat((Core.Game.Opponent.Graveyard ?? Enumerable.Empty<CardEntity>()).Select(ce => ce.Entity.Card))
.Where(thisShouldBeAPredicate => _shouldBeTracked(thisShouldBeAPredicate));
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using Hearthstone_Deck_Tracker.Hearthstone;
using Hearthstone_Deck_Tracker.API;
namespace AnyfinCalculator
{
public class GraveyardHelper
{
private readonly Predicate<Card> _shouldBeTracked;
private List<Card> _checkedMinions = new List<Card>();
public GraveyardHelper(Predicate<Card> shouldBeTracked = null)
{
_shouldBeTracked = shouldBeTracked;
}
public IEnumerable<Card> TrackedMinions => Core.Game.Player.Graveyard.Select(ce => ce.Entity.Card)
.Concat(Core.Game.Opponent.Graveyard.Select(ce => ce.Entity.Card))
.Where(thisShouldBeAPredicate =>_shouldBeTracked(thisShouldBeAPredicate));
}
} | mit | C# |
87c72109424c7b7b3453d7b60e4367ebdae01b05 | Update StackExchangeService - remove redundant string interpolation, update to follow naming conventions | mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX,mariocatch/MODiX | Modix.Services/StackExchange/StackExchangeService.cs | Modix.Services/StackExchange/StackExchangeService.cs | using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Modix.Services.StackExchange
{
public class StackExchangeService
{
private static HttpClient HttpClient => new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
});
private string _apiReferenceUrl =
"http://api.stackexchange.com/2.2/search/advanced" +
"?key={0}" +
"&order=desc" +
"&sort=votes" +
"&filter=default";
public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
{
_apiReferenceUrl = string.Format(_apiReferenceUrl, token);
phrase = Uri.EscapeDataString(phrase);
site = Uri.EscapeDataString(site);
tags = Uri.EscapeDataString(tags);
var query = _apiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";
var response = await HttpClient.GetAsync(query);
if (!response.IsSuccessStatusCode)
{
throw new WebException("Something failed while querying the Stack Exchange API.");
}
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<StackExchangeResponse>(jsonResponse);
}
}
}
| using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace Modix.Services.StackExchange
{
public class StackExchangeService
{
private static HttpClient HttpClient => new HttpClient(new HttpClientHandler
{
AutomaticDecompression = DecompressionMethods.GZip
});
private string _ApiReferenceUrl =
$"http://api.stackexchange.com/2.2/search/advanced" +
"?key={0}" +
$"&order=desc" +
$"&sort=votes" +
$"&filter=default";
public async Task<StackExchangeResponse> GetStackExchangeResultsAsync(string token, string phrase, string site, string tags)
{
_ApiReferenceUrl = string.Format(_ApiReferenceUrl, token);
phrase = Uri.EscapeDataString(phrase);
site = Uri.EscapeDataString(site);
tags = Uri.EscapeDataString(tags);
var query = _ApiReferenceUrl += $"&site={site}&tags={tags}&q={phrase}";
var response = await HttpClient.GetAsync(query);
if (!response.IsSuccessStatusCode)
{
throw new WebException("Something failed while querying the Stack Exchange API.");
}
var jsonResponse = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<StackExchangeResponse>(jsonResponse);
}
}
}
| mit | C# |
b5f5400e069bcc8cb720391eccea385a45bfe7b5 | Add Refresh() Method to ISerachModule to allow forcing a sim to resend it's search data | EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,TomDataworks/opensim,TomDataworks/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,RavenB/opensim,RavenB/opensim,RavenB/opensim,RavenB/opensim,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC,EriHoss/OpenSim_0.8.2.0_Dev_LibLSLCC | OpenSim/Region/Framework/Interfaces/ISearchModule.cs | OpenSim/Region/Framework/Interfaces/ISearchModule.cs | /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
namespace OpenSim.Framework
{
public interface ISearchModule
{
void Refresh();
}
}
| /*
* Copyright (c) Contributors, http://opensimulator.org/
* See CONTRIBUTORS.TXT for a full list of copyright holders.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the OpenSimulator Project nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using OpenMetaverse;
namespace OpenSim.Framework
{
public interface ISearchModule
{
}
}
| bsd-3-clause | C# |
b46bcce9effb225cc453e037d461b655f4eaf412 | fix typo | endjin/Endjin.Licensing | Solutions/Endjin.Licensing.Demo.ServerApp/Program.cs | Solutions/Endjin.Licensing.Demo.ServerApp/Program.cs | namespace Endjin.Licensing.Demo.ServerApp
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.IO;
using Endjin.Licensing.Domain;
using Endjin.Licensing.Extensions;
using Endjin.Licensing.Infrastructure.Crypto;
using Endjin.Licensing.Infrastructure.Generators;
#endregion
public class Program
{
public static void Main(string[] args)
{
var dataDirectory = @"..\..\..\..\LicenseData".ResolveBaseDirectory();
var publicKeyPath = @"..\..\..\..\LicenseData\PublicKey.xml".ResolveBaseDirectory();
var licensePath = @"..\..\..\..\LicenseData\License.xml".ResolveBaseDirectory();
if (!Directory.Exists(dataDirectory))
{
Directory.CreateDirectory(dataDirectory);
}
var licenseCriteria = new LicenseCriteria
{
ExpirationDate = DateTimeOffset.UtcNow.LastDayOfMonth().EndOfDay(),
IssueDate = DateTimeOffset.UtcNow,
Id = Guid.NewGuid(),
MetaData = new Dictionary<string, string> { { "LicensedCores", "2" } },
Type = "Subscription"
};
var privateKey = new RsaPrivateKeyProvider().Create();
var serverLicense = new ServerLicenseGenerator().Generate(privateKey, licenseCriteria);
var clientLicense = serverLicense.ToClientLicense();
// In a real implementation, you would embed the public key into the assembly, via a resource file
File.WriteAllText(publicKeyPath, privateKey.ExtractPublicKey().Contents);
// In a real implementation you would implement ILicenseRepository
File.WriteAllText(licensePath, clientLicense.Content.InnerXml);
Console.WriteLine(Messsages.LicenseGenerated, dataDirectory);
Console.WriteLine(Messsages.PressAnyKey);
Console.ReadKey();
}
}
} | namespace Endjin.Licensing.Demo.ServerApp
{
#region Using Directives
using System;
using System.Collections.Generic;
using System.IO;
using Endjin.Licensing.Domain;
using Endjin.Licensing.Extensions;
using Endjin.Licensing.Infrastructure.Crypto;
using Endjin.Licensing.Infrastructure.Generators;
#endregion
public class Program
{
public static void Main(string[] args)
{
var dataDirectory = @"..\..\..\..\LicenseData".ResolveBaseDirectory();
var publicKeyPath = @"..\..\..\..\LicenseData\PublicKey.xml".ResolveBaseDirectory();
var licensePath = @"..\..\..\..\LicenseData\License.xml".ResolveBaseDirectory();
if (!Directory.Exists(dataDirectory))
{
Directory.CreateDirectory(dataDirectory);
}
var licenseCriteria = new LicenseCriteria
{
ExpirationDate = DateTimeOffset.UtcNow.LastDayOfMonth().EndOfDay(),
IssueDate = DateTimeOffset.UtcNow,
Id = Guid.NewGuid(),
MetaData = new Dictionary<string, string> { { "LicensedCores", "2" } },
Type = "Subscription"
};
var privateKey = new RsaPrivateKeyProvider().Create();
var serverLicense = new ServerLicenseGenerator().Generate(privateKey, licenseCriteria);
var clientLicense = serverLicense.ToClientLicense();
// In a real implementation, you would embedd the public key into the assembly, via a resource file
File.WriteAllText(publicKeyPath, privateKey.ExtractPublicKey().Contents);
// In a real implementation you would implement ILicenseRepository
File.WriteAllText(licensePath, clientLicense.Content.InnerXml);
Console.WriteLine(Messsages.LicenseGenerated, dataDirectory);
Console.WriteLine(Messsages.PressAnyKey);
Console.ReadKey();
}
}
} | mit | C# |
967add91ef218595b8e61a898ee9c9341b904b56 | Add a constructor to TransferStatus to make unit testing of progress handlers possible. | Azure/azure-storage-net-data-movement | lib/TransferStatus.cs | lib/TransferStatus.cs | //-----------------------------------------------------------------------------
// <copyright file="TransferStatus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//-----------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
using System;
/// <summary>
/// Transfer status
/// </summary>
public sealed class TransferStatus
{
/// <summary>
/// Initializes a new instance of the <see cref="TransferStatus"/> class.
/// </summary>
public TransferStatus()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TransferStatus"/> class.
/// </summary>
/// <param name="bytesTransferred">Number of bytes that have been transferred.</param>
/// <param name="numberOfFilesTransferred">Number of files that have been transferred.</param>
/// <param name="numberOfFilesSkipped">Number of files that are skipped to be transferred.</param>
/// <param name="numberOfFilesFailed">Number of files that are failed to be transferred.</param>
public TransferStatus(long bytesTransferred, long numberOfFilesTransferred, long numberOfFilesSkipped, long numberOfFilesFailed)
{
if (bytesTransferred < 0)
{
throw new ArgumentOutOfRangeException(nameof(bytesTransferred));
}
if (numberOfFilesTransferred < 0)
{
throw new ArgumentOutOfRangeException(nameof(numberOfFilesTransferred));
}
if (numberOfFilesSkipped < 0)
{
throw new ArgumentOutOfRangeException(nameof(numberOfFilesSkipped));
}
if (numberOfFilesFailed < 0)
{
throw new ArgumentOutOfRangeException(nameof(numberOfFilesFailed));
}
this.BytesTransferred = bytesTransferred;
this.NumberOfFilesTransferred = numberOfFilesTransferred;
this.NumberOfFilesSkipped = numberOfFilesSkipped;
this.NumberOfFilesFailed = numberOfFilesFailed;
}
/// <summary>
/// Gets the number of bytes that have been transferred.
/// </summary>
public long BytesTransferred
{
get;
internal set;
}
/// <summary>
/// Gets the number of files that have been transferred.
/// </summary>
public long NumberOfFilesTransferred
{
get;
internal set;
}
/// <summary>
/// Gets the number of files that are skipped to be transferred.
/// </summary>
public long NumberOfFilesSkipped
{
get;
internal set;
}
/// <summary>
/// Gets the number of files that are failed to be transferred.
/// </summary>
public long NumberOfFilesFailed
{
get;
internal set;
}
}
}
| //-----------------------------------------------------------------------------
// <copyright file="TransferStatus.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation
// </copyright>
//-----------------------------------------------------------------------------
namespace Microsoft.WindowsAzure.Storage.DataMovement
{
/// <summary>
/// Transfer status
/// </summary>
public sealed class TransferStatus
{
/// <summary>
/// Gets the number of bytes that have been transferred.
/// </summary>
public long BytesTransferred
{
get;
internal set;
}
/// <summary>
/// Gets the number of files that have been transferred.
/// </summary>
public long NumberOfFilesTransferred
{
get;
internal set;
}
/// <summary>
/// Gets the number of files that are skipped to be transferred.
/// </summary>
public long NumberOfFilesSkipped
{
get;
internal set;
}
/// <summary>
/// Gets the number of files that are failed to be transferred.
/// </summary>
public long NumberOfFilesFailed
{
get;
internal set;
}
}
}
| mit | C# |
9ead2ba0d2eb7ee9da2ad8b4aeaab2ce7e1820fb | Debug info + Default cleanup on failed conditions | alvivar/React | React.cs | React.cs |
// Andrés Villalobos | andresalvivar@gmail.com | @matnesis
// 2015/06/17 01:44:37 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class React : MonoBehaviour
{
[Header("Info")]
public string currentReaction = "";
public string lastReactionExecuted = "";
[Header("ReactBase Queue")]
public List<ReactBase> linear;
public List<ReactBase> untilCondition;
[Header("Config")]
public bool autoStart = true;
public float tick = 0.1f;
private Coroutine coLinearExecution;
private Coroutine coUntilConditionExecution;
void Start()
{
if (autoStart)
Play();
}
public void Play()
{
Stop();
coLinearExecution = StartCoroutine(ExecuteLinear());
coUntilConditionExecution = StartCoroutine(ExecuteUntilCondition());
}
public void Stop()
{
if (coLinearExecution != null)
StopCoroutine(coLinearExecution);
if (coUntilConditionExecution != null)
StopCoroutine(coUntilConditionExecution);
}
IEnumerator ExecuteLinear()
{
foreach (ReactBase r in linear)
{
yield return new WaitForSeconds(tick);
if (r.Condition())
yield return StartCoroutine(r.Action());
}
yield return null;
StartCoroutine(ExecuteLinear());
}
IEnumerator ExecuteUntilCondition()
{
bool stopTheRest = false;
foreach (ReactBase r in untilCondition)
{
// +Info
currentReaction = r.GetType().Name;
// Stop all reactions only
if (stopTheRest)
{
r.Stop();
continue;
}
// Evaluation
if (r.Condition())
{
// +Info
lastReactionExecuted = r.GetType().Name;
// Execution
yield return StartCoroutine(r.Action());
// No more evaluations until the next execution
stopTheRest = true;
}
else
{
// To avoid leftovers when the last action executed is the
// current else condition #experimental
r.Stop();
}
// Tick
yield return new WaitForSeconds(tick);
}
// Wait and retry
yield return new WaitForEndOfFrame();
StartCoroutine(ExecuteUntilCondition());
}
}
|
// Andrés Villalobos | andresalvivar@gmail.com | @matnesis
// 2015/06/17 01:44:37 PM
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class React : MonoBehaviour
{
[Header("ReactBase Queue")]
public List<ReactBase> linear;
public List<ReactBase> untilCondition;
[Header("Config")]
public bool autoStart = true;
public float tick = 0.1f;
private Coroutine coLinearExecution;
private Coroutine coUntilConditionExecution;
void Start()
{
if (autoStart)
Play();
}
public void Play()
{
Stop();
coLinearExecution = StartCoroutine(ExecuteLinear());
coUntilConditionExecution = StartCoroutine(ExecuteUntilCondition());
}
public void Stop()
{
if (coLinearExecution != null)
StopCoroutine(coLinearExecution);
if (coUntilConditionExecution != null)
StopCoroutine(coUntilConditionExecution);
}
IEnumerator ExecuteLinear()
{
foreach (ReactBase r in linear)
{
yield return new WaitForSeconds(tick);
if (r.Condition())
yield return StartCoroutine(r.Action());
}
yield return null;
StartCoroutine(ExecuteLinear());
}
IEnumerator ExecuteUntilCondition()
{
bool stopTheRest = false;
foreach (ReactBase r in untilCondition)
{
// Stop all reactions only
if (stopTheRest)
{
r.Stop();
continue;
}
// Evaluation
if (r.Condition())
{
// Execution
yield return StartCoroutine(r.Action());
// No more evaluations until the next execution
stopTheRest = true;
}
// Tick
yield return new WaitForSeconds(tick);
}
// Wait and retry
yield return new WaitForEndOfFrame();
StartCoroutine(ExecuteUntilCondition());
}
}
| mit | C# |
f574aacc469d40834783ae7824da4f6f389725db | index users projection required events fixed | msbahrul/EventStore,msbahrul/EventStore,ianbattersby/EventStore,msbahrul/EventStore,msbahrul/EventStore,msbahrul/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,ianbattersby/EventStore,msbahrul/EventStore | src/EventStore/EventStore.Web/Users/IndexUsersProjectionHandler.cs | src/EventStore/EventStore.Web/Users/IndexUsersProjectionHandler.cs | // Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using EventStore.Projections.Core.Services;
using EventStore.Projections.Core.Services.Processing;
namespace EventStore.Web.Users
{
public sealed class IndexUsersProjectionHandler : IProjectionStateHandler
{
public IndexUsersProjectionHandler(string query, Action<string> logger)
{
}
public void Dispose()
{
}
public void ConfigureSourceProcessingStrategy(QuerySourceProcessingStrategyBuilder builder)
{
builder.FromAll();
builder.IncludeEvent("$user-created");
}
public void Load(string state)
{
}
public void Initialize()
{
}
public string GetStatePartition(
CheckpointTag eventPosition, string streamId, string eventType, string category, Guid eventid,
int sequenceNumber, string metadata, string data)
{
throw new NotImplementedException();
}
public bool ProcessEvent(
string partition, CheckpointTag eventPosition, string category, ResolvedEvent data, out string newState,
out EmittedEvent[] emittedEvents)
{
throw new NotImplementedException();
}
public string TransformStateToResult()
{
throw new NotImplementedException();
}
}
}
| // Copyright (c) 2012, Event Store LLP
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the Event Store LLP nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
using System;
using EventStore.Projections.Core.Services;
using EventStore.Projections.Core.Services.Processing;
namespace EventStore.Web.Users
{
public sealed class IndexUsersProjectionHandler : IProjectionStateHandler
{
public IndexUsersProjectionHandler(string query, Action<string> logger)
{
}
public void Dispose()
{
}
public void ConfigureSourceProcessingStrategy(QuerySourceProcessingStrategyBuilder builder)
{
builder.FromAll();
builder.IncludeEvent("$user-created");
builder.IncludeEvent("$user-updated");
}
public void Load(string state)
{
}
public void Initialize()
{
}
public string GetStatePartition(
CheckpointTag eventPosition, string streamId, string eventType, string category, Guid eventid,
int sequenceNumber, string metadata, string data)
{
throw new NotImplementedException();
}
public bool ProcessEvent(
string partition, CheckpointTag eventPosition, string category, ResolvedEvent data, out string newState,
out EmittedEvent[] emittedEvents)
{
throw new NotImplementedException();
}
public string TransformStateToResult()
{
throw new NotImplementedException();
}
}
}
| bsd-3-clause | C# |
b6000bdfa38652c5bba6a6c0427d7d5cb9bdb498 | Update sln info | onovotny/fluentassertions | SolutionInfo.cs | SolutionInfo.cs | using System.Reflection;
[assembly: AssemblyCompany("www.dennisdoomen.net")]
[assembly: AssemblyCopyright("Copyright Dennis Doomen 2010-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("3.0.1")]
[assembly: AssemblyFileVersion("3.0.1")]
| using System.Reflection;
[assembly: AssemblyCompany("www.dennisdoomen.net")]
[assembly: AssemblyCopyright("Copyright Dennis Doomen 2010-2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: AssemblyVersion("3.0.9999")]
[assembly: AssemblyFileVersion("3.0.9999")]
| apache-2.0 | C# |
fdd7af14b8c2bb05e605740f28aa975ec3ca0eb8 | Update Timeseries.cs | marmind/MailChimp.NET-APIv2,danesparza/MailChimp.NET | MailChimp/Reports/Timeseries.cs | MailChimp/Reports/Timeseries.cs | using System.Runtime.Serialization;
namespace MailChimp.Reports
{
/// <summary>
/// optional - various extra options based on the campaign type
/// </summary>
[DataContract]
public class Timeseries
{
/// <summary>
///The timestemp in Y-m-d H:00:00 format
/// </summary>
[DataMember(Name = "timestamp")]
public string Timestamp { get; set; }
/// <summary>
///the total emails sent during the hour
/// </summary>
[DataMember(Name = "emails_sent")]
public int EmailsSent { get; set; }
/// <summary>
///unique opens seen during the hour
/// </summary>
[DataMember(Name = "unique_opens")]
public int UniqueOpens { get; set; }
/// <summary>
///unique clicks seen during the hour
/// </summary>
[DataMember(Name = "recipients_click")]
public int RecipientsClick { get; set; }
}
}
| using System.Runtime.Serialization;
namespace MailChimp.Reports
{
/// <summary>
/// optional - various extra options based on the campaign type
/// </summary>
[DataContract]
public class Industry
{
/// <summary>
///the selected industry
/// </summary>
[DataMember(Name = "type")]
public string Type { get; set; }
/// <summary>
///industry open rate
/// </summary>
[DataMember(Name = "open_rate")]
public float OpenRate { get; set; }
/// <summary>
///industry click rate
/// </summary>
[DataMember(Name = "click_rate")]
public float ClickRate { get; set; }
/// <summary>
///industry bounce rate
/// </summary>
[DataMember(Name = "bounce_rate")]
public float BounceRate { get; set; }
/// <summary>
///industry unopen rate
/// </summary>
[DataMember(Name = "unopen_rate")]
public float UnopenRate { get; set; }
/// <summary>
///industry unsub rate
/// </summary>
[DataMember(Name = "unsub_rate")]
public float UnsubRate { get; set; }
/// <summary>
///industry abuse rate
/// </summary>
[DataMember(Name = "abuse_rate")]
public float AbuseRate { get; set; }
}
}
| mit | C# |
acb5607a6d142cb978e8529fdb4d8b199088a7b9 | check CI build v2 | Orbmu2k/nvidiaProfileInspector,Orbmu2k/nvidiaProfileInspector | nspector/Properties/AssemblyInfo.cs | nspector/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("nvidiaProfileInspector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NVIDIA Profile Inspector")]
[assembly: AssemblyCopyright("©2022 by Orbmu2k")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2fe2861-54c5-4d63-968e-30472019bed3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.0.1")]
[assembly: AssemblyFileVersion("2.4.0.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("nvidiaProfileInspector")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("NVIDIA Profile Inspector")]
[assembly: AssemblyCopyright("©2022 by Orbmu2k")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c2fe2861-54c5-4d63-968e-30472019bed3")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.4.0.0")]
[assembly: AssemblyFileVersion("2.4.0.0")]
| mit | C# |
417d93dde0b0223b5c30969c87a0c02c538cf2e3 | Make default material 1 | MatterHackers/agg-sharp,larsbrubaker/agg-sharp,mmoening/agg-sharp,LayoutFarm/PixelFarm,mmoening/agg-sharp,jlewin/agg-sharp,mmoening/agg-sharp | PolygonMesh/MeshMaterialData.cs | PolygonMesh/MeshMaterialData.cs | /*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Text;
using MatterHackers.VectorMath;
namespace MatterHackers.PolygonMesh
{
public class MeshMaterialData
{
public int MaterialIndex = 1;
private MeshMaterialData()
{
}
private static ConditionalWeakTable<Mesh, MeshMaterialData> meshsWithMaterialData = new ConditionalWeakTable<Mesh, MeshMaterialData>();
static public MeshMaterialData Get(Mesh meshToGetMaterialDataFor)
{
MeshMaterialData plugin;
meshsWithMaterialData.TryGetValue(meshToGetMaterialDataFor, out plugin);
if (plugin == null)
{
MeshMaterialData newPlugin = new MeshMaterialData();
meshsWithMaterialData.Add(meshToGetMaterialDataFor, newPlugin);
return newPlugin;
}
return plugin;
}
}
}
| /*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Text;
using MatterHackers.VectorMath;
namespace MatterHackers.PolygonMesh
{
public class MeshMaterialData
{
public int MaterialIndex = -1;
private MeshMaterialData()
{
}
private static ConditionalWeakTable<Mesh, MeshMaterialData> meshsWithMaterialData = new ConditionalWeakTable<Mesh, MeshMaterialData>();
static public MeshMaterialData Get(Mesh meshToGetMaterialDataFor)
{
MeshMaterialData plugin;
meshsWithMaterialData.TryGetValue(meshToGetMaterialDataFor, out plugin);
if (plugin == null)
{
MeshMaterialData newPlugin = new MeshMaterialData();
meshsWithMaterialData.Add(meshToGetMaterialDataFor, newPlugin);
return newPlugin;
}
return plugin;
}
}
}
| bsd-2-clause | C# |
c387e04c09a70de3a3f8935bbf7766ff204f31c9 | Reorganize Logger.cs | Joe4evr/Discord.Net,Confruggy/Discord.Net,RogueException/Discord.Net,AntiTcb/Discord.Net,LassieME/Discord.Net | src/Discord.Net/Logging/Logger.cs | src/Discord.Net/Logging/Logger.cs | using System;
namespace Discord.Logging
{
public class Logger : ILogger
{
private readonly LogManager _manager;
public string Name { get; }
public LogSeverity Level => _manager.Level;
internal Logger(LogManager manager, string name)
{
_manager = manager;
Name = name;
}
public void Log(LogSeverity severity, string message, Exception exception = null)
=> _manager.Log(severity, Name, message, exception);
public void Error(string message, Exception exception = null)
=> _manager.Error(Name, message, exception);
public void Error(Exception exception)
=> _manager.Error(Name, exception);
public void Warning(string message, Exception exception = null)
=> _manager.Warning(Name, message, exception);
public void Warning(Exception exception)
=> _manager.Warning(Name, exception);
public void Info(string message, Exception exception = null)
=> _manager.Info(Name, message, exception);
public void Info(Exception exception)
=> _manager.Info(Name, exception);
public void Verbose(string message, Exception exception = null)
=> _manager.Verbose(Name, message, exception);
public void Verbose(Exception exception)
=> _manager.Verbose(Name, exception);
public void Debug(string message, Exception exception = null)
=> _manager.Debug(Name, message, exception);
public void Debug(Exception exception)
=> _manager.Debug(Name, exception);
#if DOTNET5_4
public void Log(LogSeverity severity, FormattableString message, Exception exception = null)
=> _manager.Log(severity, Name, message, exception);
public void Error(FormattableString message, Exception exception = null)
=> _manager.Error(Name, message, exception);
public void Warning(FormattableString message, Exception exception = null)
=> _manager.Warning(Name, message, exception);
public void Info(FormattableString message, Exception exception = null)
=> _manager.Info(Name, message, exception);
public void Verbose(FormattableString message, Exception exception = null)
=> _manager.Verbose(Name, message, exception);
public void Debug(FormattableString message, Exception exception = null)
=> _manager.Debug(Name, message, exception);
#endif
}
}
| using System;
namespace Discord.Logging
{
public class Logger : ILogger
{
private readonly LogManager _manager;
public string Name { get; }
public LogSeverity Level => _manager.Level;
internal Logger(LogManager manager, string name)
{
_manager = manager;
Name = name;
}
public void Log(LogSeverity severity, string message, Exception exception = null)
=> _manager.Log(severity, Name, message, exception);
#if DOTNET5_4
public void Log(LogSeverity severity, FormattableString message, Exception exception = null)
=> _manager.Log(severity, Name, message, exception);
#endif
public void Error(string message, Exception exception = null)
=> _manager.Error(Name, message, exception);
#if DOTNET5_4
public void Error(FormattableString message, Exception exception = null)
=> _manager.Error(Name, message, exception);
#endif
public void Error(Exception exception)
=> _manager.Error(Name, exception);
public void Warning(string message, Exception exception = null)
=> _manager.Warning(Name, message, exception);
#if DOTNET5_4
public void Warning(FormattableString message, Exception exception = null)
=> _manager.Warning(Name, message, exception);
#endif
public void Warning(Exception exception)
=> _manager.Warning(Name, exception);
public void Info(string message, Exception exception = null)
=> _manager.Info(Name, message, exception);
#if DOTNET5_4
public void Info(FormattableString message, Exception exception = null)
=> _manager.Info(Name, message, exception);
#endif
public void Info(Exception exception)
=> _manager.Info(Name, exception);
public void Verbose(string message, Exception exception = null)
=> _manager.Verbose(Name, message, exception);
#if DOTNET5_4
public void Verbose(FormattableString message, Exception exception = null)
=> _manager.Verbose(Name, message, exception);
#endif
public void Verbose(Exception exception)
=> _manager.Verbose(Name, exception);
public void Debug(string message, Exception exception = null)
=> _manager.Debug(Name, message, exception);
#if DOTNET5_4
public void Debug(FormattableString message, Exception exception = null)
=> _manager.Debug(Name, message, exception);
#endif
public void Debug(Exception exception)
=> _manager.Debug(Name, exception);
}
}
| mit | C# |
67785de2c9d1032bc3e9617789dbb90ee254a926 | Remove redundant IResourceResolver mapping. | jammycakes/dolstagis.web,jammycakes/dolstagis.web,jammycakes/dolstagis.web | src/Dolstagis.Web/CoreServices.cs | src/Dolstagis.Web/CoreServices.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dolstagis.Web.Http;
using Dolstagis.Web.Lifecycle;
using Dolstagis.Web.Routing;
using Dolstagis.Web.Sessions;
using Dolstagis.Web.Static;
using Dolstagis.Web.Views;
using StructureMap.Configuration.DSL;
namespace Dolstagis.Web
{
internal class CoreServices : Registry
{
public CoreServices()
{
For<RouteTable>().Singleton().Use<RouteTable>();
For<IMimeTypes>().Singleton().Use<MimeTypes>();
For<IRequestContextBuilder>().Use<RequestContextBuilder>();
For<IRequestProcessor>().Use<RequestProcessor>();
For<IExceptionHandler>().Use<ExceptionHandler>();
For<ISessionCookieBuilder>().Singleton().Use<SessionCookieBuilder>();
For<IResultProcessor>().Singleton().Add<StaticResultProcessor>()
.Ctor<IResourceResolver>().Is(ctx => new ResourceResolver
("StaticFiles", ctx.GetAllInstances<ResourceLocation>())
);
For<IResultProcessor>().Singleton().Add<ViewResultProcessor>();
For<IResultProcessor>().Singleton().Add<JsonResultProcessor>();
For<IResultProcessor>().Singleton().Add<ContentResultProcessor>();
For<ViewRegistry>().Singleton().Use<ViewRegistry>()
.Ctor<IResourceResolver>().Is(ctx => new ResourceResolver
("Views", ctx.GetAllInstances<ResourceLocation>())
);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dolstagis.Web.Http;
using Dolstagis.Web.Lifecycle;
using Dolstagis.Web.Routing;
using Dolstagis.Web.Sessions;
using Dolstagis.Web.Static;
using Dolstagis.Web.Views;
using StructureMap.Configuration.DSL;
namespace Dolstagis.Web
{
internal class CoreServices : Registry
{
public CoreServices()
{
For<RouteTable>().Singleton().Use<RouteTable>();
For<IMimeTypes>().Singleton().Use<MimeTypes>();
For<IRequestContextBuilder>().Use<RequestContextBuilder>();
For<IRequestProcessor>().Use<RequestProcessor>();
For<IExceptionHandler>().Use<ExceptionHandler>();
For<IResourceResolver>().Singleton().Use<ResourceResolver>();
For<ISessionCookieBuilder>().Singleton().Use<SessionCookieBuilder>();
For<IResultProcessor>().Singleton().Add<StaticResultProcessor>()
.Ctor<IResourceResolver>().Is(ctx => new ResourceResolver
("StaticFiles", ctx.GetAllInstances<ResourceLocation>())
);
For<IResultProcessor>().Singleton().Add<ViewResultProcessor>();
For<IResultProcessor>().Singleton().Add<JsonResultProcessor>();
For<IResultProcessor>().Singleton().Add<ContentResultProcessor>();
For<ViewRegistry>().Singleton().Use<ViewRegistry>()
.Ctor<IResourceResolver>().Is(ctx => new ResourceResolver
("Views", ctx.GetAllInstances<ResourceLocation>())
);
}
}
}
| mit | C# |
0c30c87f50a560e823667ff016caa9c92ce850ef | Use new return value of Guard.ExpectNode to refine casting... | rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,rytmis/dotless,dotless/dotless,dotless/dotless,rytmis/dotless | src/dotless.Core/Parser/Functions/RgbaFunction.cs | src/dotless.Core/Parser/Functions/RgbaFunction.cs | namespace dotless.Core.Parser.Functions
{
using System.Linq;
using Infrastructure;
using Infrastructure.Nodes;
using Tree;
using Utils;
public class RgbaFunction : Function
{
protected override Node Evaluate(Env env)
{
if (Arguments.Count == 2)
{
var color = Guard.ExpectNode<Color>(Arguments[0], this, Location);
var alpha = Guard.ExpectNode<Number>(Arguments[1], this, Location);
return new Color(color.RGB, alpha.Value);
}
Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
Guard.ExpectAllNodes<Number>(Arguments, this, Location);
var args = Arguments.Cast<Number>();
var rgb = args.Take(3);
return new Color(rgb, args.ElementAt(3));
}
}
} | namespace dotless.Core.Parser.Functions
{
using System.Linq;
using Infrastructure;
using Infrastructure.Nodes;
using Tree;
using Utils;
public class RgbaFunction : Function
{
protected override Node Evaluate(Env env)
{
if (Arguments.Count == 2)
{
Guard.ExpectNode<Color>(Arguments[0], this, Location);
Guard.ExpectNode<Number>(Arguments[1], this, Location);
return new Color(((Color) Arguments[0]).RGB, ((Number) Arguments[1]).Value);
}
Guard.ExpectNumArguments(4, Arguments.Count, this, Location);
Guard.ExpectAllNodes<Number>(Arguments, this, Location);
var args = Arguments.Cast<Number>();
var rgb = args.Take(3);
return new Color(rgb, args.ElementAt(3));
}
}
} | apache-2.0 | C# |
e0a748b4a3c61972fe8ef0d3c8c9039af3848b22 | Fix iOS themes | rafaelbarrelo/Xamarin-Prism-Starter | src/iOS/AppDelegate.cs | src/iOS/AppDelegate.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace XamarinPrismStarter.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
var x = typeof(Xamarin.Forms.Themes.DarkThemeResources);
x = typeof(Xamarin.Forms.Themes.LightThemeResources);
x = typeof(Xamarin.Forms.Themes.iOS.UnderlineEffect);
return base.FinishedLaunching(app, options);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace XamarinPrismStarter.iOS
{
[Register("AppDelegate")]
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
var x = typeof(Xamarin.Forms.Themes.DarkThemeResources);
x = typeof(Xamarin.Forms.Themes.LightThemeResources);
x = typeof(Xamarin.Forms.Themes.iOS.UnderlineEffect);
}
}
}
| mit | C# |
73b98b8f7072848626a7cb594b1e5be777ade4cd | Make VideoTextureUpload's constructor internal | peppy/osu-framework,smoogipooo/osu-framework,ZLima12/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,peppy/osu-framework,ppy/osu-framework,ZLima12/osu-framework,smoogipooo/osu-framework | osu.Framework/Graphics/Video/VideoTextureUpload.cs | osu.Framework/Graphics/Video/VideoTextureUpload.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Textures;
using osuTK.Graphics.ES30;
using FFmpeg.AutoGen;
using osu.Framework.Graphics.Primitives;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Video
{
public unsafe class VideoTextureUpload : ITextureUpload
{
public readonly AVFrame* Frame;
private readonly FFmpegFuncs.AvFrameFreeDelegate freeFrameDelegate;
public ReadOnlySpan<Rgba32> Data => ReadOnlySpan<Rgba32>.Empty;
public int Level => 0;
public RectangleI Bounds { get; set; }
public PixelFormat Format => PixelFormat.Red;
/// <summary>
/// Sets the frame containing the data to be uploaded.
/// </summary>
/// <param name="frame">The frame to upload.</param>
/// <param name="freeFrameDelegate">A function to free the frame on disposal.</param>
internal VideoTextureUpload(AVFrame* frame, FFmpegFuncs.AvFrameFreeDelegate freeFrameDelegate)
{
Frame = frame;
this.freeFrameDelegate = freeFrameDelegate;
}
#region IDisposable Support
public void Dispose()
{
fixed (AVFrame** ptr = &Frame)
freeFrameDelegate(ptr);
}
#endregion
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics.Textures;
using osuTK.Graphics.ES30;
using FFmpeg.AutoGen;
using osu.Framework.Graphics.Primitives;
using SixLabors.ImageSharp.PixelFormats;
namespace osu.Framework.Graphics.Video
{
public unsafe class VideoTextureUpload : ITextureUpload
{
public readonly AVFrame* Frame;
private readonly FFmpegFuncs.AvFrameFreeDelegate freeFrameDelegate;
public ReadOnlySpan<Rgba32> Data => ReadOnlySpan<Rgba32>.Empty;
public int Level => 0;
public RectangleI Bounds { get; set; }
public PixelFormat Format => PixelFormat.Red;
/// <summary>
/// Sets the frame containing the data to be uploaded.
/// </summary>
/// <param name="frame">The frame to upload.</param>
/// <param name="freeFrameDelegate">A function to free the frame on disposal.</param>
public VideoTextureUpload(AVFrame* frame, FFmpegFuncs.AvFrameFreeDelegate freeFrameDelegate)
{
Frame = frame;
this.freeFrameDelegate = freeFrameDelegate;
}
#region IDisposable Support
public void Dispose()
{
fixed (AVFrame** ptr = &Frame)
freeFrameDelegate(ptr);
}
#endregion
}
}
| mit | C# |
f4ab1323d908ca990f5a5ba3bfe0ea6d0678c304 | Expand the raft around the support and wipe tower. | jlewin/MatterSlice | raft.cs | raft.cs | /*
Copyright (C) 2013 David Braam
Copyright (c) 2014, Lars Brubaker
This file is part of MatterSlice.
MatterSlice is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MatterSlice is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MatterSlice. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ClipperLib;
namespace MatterHackers.MatterSlice
{
public static class Raft
{
public static void generateRaft(SliceDataStorage storage, int distance)
{
for (int volumeIdx = 0; volumeIdx < storage.volumes.Count; volumeIdx++)
{
if (storage.volumes[volumeIdx].layers.Count < 1)
{
continue;
}
SliceLayer layer = storage.volumes[volumeIdx].layers[0];
for (int i = 0; i < layer.parts.Count; i++)
{
storage.raftOutline = storage.raftOutline.CreateUnion(layer.parts[i].outline.Offset(distance));
}
}
SupportPolyGenerator supportGenerator = new SupportPolyGenerator(storage.support, 0);
storage.raftOutline = storage.raftOutline.CreateUnion(storage.wipeTower.Offset(distance));
storage.raftOutline = storage.raftOutline.CreateUnion(supportGenerator.polygons.Offset(distance));
}
}
} | /*
Copyright (C) 2013 David Braam
Copyright (c) 2014, Lars Brubaker
This file is part of MatterSlice.
MatterSlice is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MatterSlice is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with MatterSlice. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using ClipperLib;
namespace MatterHackers.MatterSlice
{
public static class Raft
{
public static void generateRaft(SliceDataStorage storage, int distance)
{
for (int volumeIdx = 0; volumeIdx < storage.volumes.Count; volumeIdx++)
{
if (storage.volumes[volumeIdx].layers.Count < 1) continue;
SliceLayer layer = storage.volumes[volumeIdx].layers[0];
for (int i = 0; i < layer.parts.Count; i++)
{
storage.raftOutline = storage.raftOutline.CreateUnion(layer.parts[i].outline.Offset(distance));
storage.raftOutline = storage.raftOutline.CreateUnion(storage.wipeTower);
}
}
SupportPolyGenerator supportGenerator = new SupportPolyGenerator(storage.support, 0);
storage.raftOutline = storage.raftOutline.CreateUnion(supportGenerator.polygons);
}
}
} | agpl-3.0 | C# |
b1fc21481da7b32f042c30d52ff77d6314ee2f2f | remove Thing.Description. (Something else will have this name soon.) | leafi/lo-novo | Thing.cs | Thing.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lo_novo
{
public abstract class Thing : FalseIObey, ITick, INoun
{
public abstract string Name { get; }
public string Preposition = "a";
private string inRoomDescription = null;
public string InRoomDescription
{
get { return inRoomDescription ?? "A " + Name + " lies on the floor."; }
set { inRoomDescription = value; }
}
private string furtherInRoomDescription = null;
public string FurtherInRoomDescription
{
get { return furtherInRoomDescription ?? InRoomDescription; }
set { furtherInRoomDescription = value; }
}
public List<string> AliasesRegex = new List<string>();
public bool Heavy = true;
public bool CanTake = false;
/// <summary>
/// Should we tell the user about this object when describing the room?
/// </summary>
public bool Important = true;
public void AddAliases(params string[] aliasesRegex)
{
AliasesRegex.AddRange(aliasesRegex);
}
public void Tick() { }
public override string ToString()
{
return Preposition + " " + Name;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lo_novo
{
public abstract class Thing : FalseIObey, ITick, INoun
{
public abstract string Name { get; }
public string Preposition = "a";
private string description = null;
public string Description
{
get { return description ?? "Truly, a " + Name + " remarkable only in how unremarkable it is."; }
set { description = value; }
}
private string inRoomDescription = null;
public string InRoomDescription
{
get { return inRoomDescription ?? "A " + Name + " lies on the floor."; }
set { inRoomDescription = value; }
}
private string furtherInRoomDescription = null;
public string FurtherInRoomDescription
{
get { return furtherInRoomDescription ?? InRoomDescription; }
set { furtherInRoomDescription = value; }
}
public List<string> AliasesRegex = new List<string>();
public bool Heavy = true;
public bool CanTake = false;
/// <summary>
/// Should we tell the user about this object when describing the room?
/// </summary>
public bool Important = true;
public void AddAliases(params string[] aliasesRegex)
{
AliasesRegex.AddRange(aliasesRegex);
}
public void Tick() { }
public override string ToString()
{
return Preposition + " " + Name;
}
}
}
| mit | C# |
f1b6a7451877005707b7a16e7ef1db0893bba02e | Support for configuration | RagingBool/RagingBool.Carcosa | projects/RagingBool.Carcosa.Core_cs/Control/KeyboardControlActor.cs | projects/RagingBool.Carcosa.Core_cs/Control/KeyboardControlActor.cs | // [[[[INFO>
// Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool)
//
// 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.
//
// For more information check https://github.com/RagingBool/RagingBool.Carcosa
// ]]]]
using Epicycle.Input.Keyboard;
using RagingBool.Carcosa.Commons.Control;
using RagingBool.Carcosa.Commons.Control.Akka;
using System.Collections.Generic;
namespace RagingBool.Carcosa.Core.Control
{
internal sealed class KeyboardControlActor<TKeyId, TAdditionalKeyEventData> : ControlActor<IKeyboard<TKeyId, TAdditionalKeyEventData>>
{
protected override IEnumerable<ControlPortConfiguration> CreateInputsConfiguration()
{
return null;
}
protected override IEnumerable<ControlPortConfiguration> CreateOutputsConfiguration()
{
return new ControlPortConfiguration[]
{
new ControlPortConfiguration("keyEvents", typeof(KeyEventArgs<TKeyId, TAdditionalKeyEventData>))
};
}
protected override void Configure(IKeyboard<TKeyId, TAdditionalKeyEventData> keyboard)
{
// TODO
}
}
}
| // [[[[INFO>
// Copyright 2015 Raging Bool (http://ragingbool.org, https://github.com/RagingBool)
//
// 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.
//
// For more information check https://github.com/RagingBool/RagingBool.Carcosa
// ]]]]
using Epicycle.Input.Keyboard;
using RagingBool.Carcosa.Commons.Control;
using RagingBool.Carcosa.Commons.Control.Akka;
using System.Collections.Generic;
namespace RagingBool.Carcosa.Core.Control
{
internal sealed class KeyboardControlActor<TKeyId, TAdditionalKeyEventData> : ControlActor
{
protected override IEnumerable<ControlPortConfiguration> CreateInputsConfiguration()
{
return null;
}
protected override IEnumerable<ControlPortConfiguration> CreateOutputsConfiguration()
{
return new ControlPortConfiguration[]
{
new ControlPortConfiguration("keyEvents", typeof(KeyEventArgs<TKeyId, TAdditionalKeyEventData>))
};
}
}
}
| apache-2.0 | C# |
94792535512270a9bdf17e7c21e36aed9f9d7740 | Add visual MessageBox when an unhandled crash is encountered | jehy/unBand,nachmore/unBand | src/unBand/App.xaml.cs | src/unBand/App.xaml.cs | using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace unBand
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Exit(object sender, ExitEventArgs e)
{
unBand.Properties.Settings.Default.Save();
}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
Telemetry.Client.TrackException(e.Exception);
MessageBox.Show("An unhandled exception occurred - sorry about that, we're going to have to crash now :(\n\nYou can open a bug with a copy of this crash: hit Ctrl + C right now and then paste into a new bug at https://github.com/nachmore/unBand/issues.\n\n" + e.Exception.ToString(),
"Imminent Crash", MessageBoxButton.OK, MessageBoxImage.Exclamation);
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace unBand
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void Application_Exit(object sender, ExitEventArgs e)
{
unBand.Properties.Settings.Default.Save();
}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
Telemetry.Client.TrackException(e.Exception);
}
}
}
| mit | C# |
778cf1888bfbd620544e132565951b0b838a75e4 | Update AutoFitRowsMergedCells.cs | maria-shahid-aspose/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET,aspose-cells/Aspose.Cells-for-.NET,maria-shahid-aspose/Aspose.Cells-for-.NET,asposecells/Aspose_Cells_NET,aspose-cells/Aspose.Cells-for-.NET | Examples/CSharp/Articles/AutoFitRowsMergedCells.cs | Examples/CSharp/Articles/AutoFitRowsMergedCells.cs | using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class AutoFitRowsMergedCells
{
public static void Main(string[] args)
{
//ExStart:1
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook
Workbook wb = new Workbook();
//Get the first (default) worksheet
Worksheet _worksheet = wb.Worksheets[0];
//Create a range A1:B1
Range range = _worksheet.Cells.CreateRange(0, 0, 1, 2);
//Merge the cells
range.Merge();
//Insert value to the merged cell A1
_worksheet.Cells[0, 0].Value = "A quick brown fox jumps over the lazy dog. A quick brown fox jumps over the lazy dog....end";
//Create a style object
Aspose.Cells.Style style = _worksheet.Cells[0, 0].GetStyle();
//Set wrapping text on
style.IsTextWrapped = true;
//Apply the style to the cell
_worksheet.Cells[0, 0].SetStyle(style);
//Create an object for AutoFitterOptions
AutoFitterOptions options = new AutoFitterOptions();
//Set auto-fit for merged cells
options.AutoFitMergedCells = true;
//Autofit rows in the sheet(including the merged cells)
_worksheet.AutoFitRows(options);
//Save the Excel file
wb.Save(dataDir+ "AutoFitMergedCells.out.xlsx");
//ExEnd:1
}
}
}
| using System.IO;
using Aspose.Cells;
namespace Aspose.Cells.Examples.Articles
{
public class AutoFitRowsMergedCells
{
public static void Main(string[] args)
{
// The path to the documents directory.
string dataDir = Aspose.Cells.Examples.Utils.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// Create directory if it is not already present.
bool IsExists = System.IO.Directory.Exists(dataDir);
if (!IsExists)
System.IO.Directory.CreateDirectory(dataDir);
//Instantiate a new Workbook
Workbook wb = new Workbook();
//Get the first (default) worksheet
Worksheet _worksheet = wb.Worksheets[0];
//Create a range A1:B1
Range range = _worksheet.Cells.CreateRange(0, 0, 1, 2);
//Merge the cells
range.Merge();
//Insert value to the merged cell A1
_worksheet.Cells[0, 0].Value = "A quick brown fox jumps over the lazy dog. A quick brown fox jumps over the lazy dog....end";
//Create a style object
Aspose.Cells.Style style = _worksheet.Cells[0, 0].GetStyle();
//Set wrapping text on
style.IsTextWrapped = true;
//Apply the style to the cell
_worksheet.Cells[0, 0].SetStyle(style);
//Create an object for AutoFitterOptions
AutoFitterOptions options = new AutoFitterOptions();
//Set auto-fit for merged cells
options.AutoFitMergedCells = true;
//Autofit rows in the sheet(including the merged cells)
_worksheet.AutoFitRows(options);
//Save the Excel file
wb.Save(dataDir+ "AutoFitMergedCells.out.xlsx");
}
}
} | mit | C# |
dfb923271c39178575b8b887e3abd4b7d430b1d3 | add zh-TW to ResourceService | stu43005/KanColleViewer | Grabacr07.KanColleViewer/Models/ResourceService.cs | Grabacr07.KanColleViewer/Models/ResourceService.cs | using Grabacr07.KanColleViewer.Properties;
using Livet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grabacr07.KanColleViewer.Models
{
/// <summary>
/// リソースを提供します。
/// </summary>
public class ResourceService : NotificationObject
{
#region static members
private static readonly ResourceService current = new ResourceService();
public static ResourceService Current
{
get { return current; }
}
#endregion
/// <summary>
/// サポートされているカルチャの名前。
/// </summary>
private readonly string[] supportedCultureNames =
{
"en-US",
"ja-JP",
"zh-CN",
"zh-TW"
};
private readonly Resources _Resources = new Resources();
private readonly IReadOnlyCollection<CultureInfo> _SupportedCultures;
/// <summary>
/// リソースを取得します。
/// </summary>
public Resources Resources
{
get { return this._Resources; }
}
/// <summary>
/// サポートされているカルチャを取得します。
/// </summary>
public IReadOnlyCollection<CultureInfo> SupportedCultures
{
get { return this._SupportedCultures; }
}
private ResourceService()
{
this._SupportedCultures = this.supportedCultureNames
.Select(x =>
{
try
{
return CultureInfo.GetCultureInfo(x);
}
catch (CultureNotFoundException)
{
return null;
}
})
.Where(x => x != null)
.ToList();
}
/// <summary>
/// 指定されたカルチャ名を使用して、リソースのカルチャを変更します。
/// </summary>
/// <param name="name">カルチャの名前。</param>
public void ChangeCulture(string name)
{
Resources.Culture = this.SupportedCultures.SingleOrDefault(x => x.Name == name);
// リソースの変更を受けて設定に適切な値を適用します。
Settings.Current.Culture = Resources.Culture != null
? Resources.Culture.Name
: null;
this.RaisePropertyChanged("Resources");
}
}
}
| using Grabacr07.KanColleViewer.Properties;
using Livet;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grabacr07.KanColleViewer.Models
{
/// <summary>
/// リソースを提供します。
/// </summary>
public class ResourceService : NotificationObject
{
#region static members
private static readonly ResourceService current = new ResourceService();
public static ResourceService Current
{
get { return current; }
}
#endregion
/// <summary>
/// サポートされているカルチャの名前。
/// </summary>
private readonly string[] supportedCultureNames =
{
"en-US",
"ja-JP",
"zh-CN"
};
private readonly Resources _Resources = new Resources();
private readonly IReadOnlyCollection<CultureInfo> _SupportedCultures;
/// <summary>
/// リソースを取得します。
/// </summary>
public Resources Resources
{
get { return this._Resources; }
}
/// <summary>
/// サポートされているカルチャを取得します。
/// </summary>
public IReadOnlyCollection<CultureInfo> SupportedCultures
{
get { return this._SupportedCultures; }
}
private ResourceService()
{
this._SupportedCultures = this.supportedCultureNames
.Select(x =>
{
try
{
return CultureInfo.GetCultureInfo(x);
}
catch (CultureNotFoundException)
{
return null;
}
})
.Where(x => x != null)
.ToList();
}
/// <summary>
/// 指定されたカルチャ名を使用して、リソースのカルチャを変更します。
/// </summary>
/// <param name="name">カルチャの名前。</param>
public void ChangeCulture(string name)
{
Resources.Culture = this.SupportedCultures.SingleOrDefault(x => x.Name == name);
// リソースの変更を受けて設定に適切な値を適用します。
Settings.Current.Culture = Resources.Culture != null
? Resources.Culture.Name
: null;
this.RaisePropertyChanged("Resources");
}
}
}
| mit | C# |
49151e3b53887d092ce3f6d2c272e924d490a12c | fix .net core sample | FantasticFiasco/mvvm-dialogs | samples/net-core/Demo.ActivateNonModalDialog/MainWindowViewModel.cs | samples/net-core/Demo.ActivateNonModalDialog/MainWindowViewModel.cs | using System.ComponentModel;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmDialogs;
namespace Demo.ActivateNonModalDialog
{
public class MainWindowViewModel : ViewModelBase
{
private readonly IDialogService dialogService;
private INotifyPropertyChanged dialogViewModel;
public MainWindowViewModel(IDialogService dialogService)
{
this.dialogService = dialogService;
ShowCommand = new RelayCommand(Show, CanShow);
ActivateCommand = new RelayCommand(Activate, CanActivate);
}
public RelayCommand ShowCommand { get; }
public RelayCommand ActivateCommand { get; }
private void Show()
{
dialogViewModel = new CurrentTimeDialogViewModel();
dialogService.Show(this, dialogViewModel);
ShowCommand.RaiseCanExecuteChanged();
ActivateCommand.RaiseCanExecuteChanged();
}
private bool CanShow()
{
return dialogViewModel == null;
}
private void Activate()
{
dialogService.Activate(dialogViewModel);
}
private bool CanActivate()
{
return dialogViewModel != null;
}
}
}
| using System.ComponentModel;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using MvvmDialogs;
namespace Demo.ActivateNonModalDialog
{
public class MainWindowViewModel : ViewModelBase
{
private readonly IDialogService dialogService;
private INotifyPropertyChanged dialogViewModel;
public MainWindowViewModel(IDialogService dialogService)
{
this.dialogService = dialogService;
ShowCommand = new RelayCommand(Show, CanShow);
ActivateCommand = new RelayCommand(Activate, CanActivate);
}
public ICommand ShowCommand { get; }
public ICommand ActivateCommand { get; }
private void Show()
{
dialogViewModel = new CurrentTimeDialogViewModel();
dialogService.Show(this, dialogViewModel);
}
private bool CanShow()
{
return dialogViewModel == null;
}
private void Activate()
{
dialogService.Activate(dialogViewModel);
}
private bool CanActivate()
{
return dialogViewModel != null;
}
}
}
| apache-2.0 | C# |
c29f0e7625fea119ba17b53d3f26418a39e03d99 | Add newline. | nguerrera/roslyn,gafter/roslyn,tmeschter/roslyn,AmadeusW/roslyn,jasonmalinowski/roslyn,brettfo/roslyn,CyrusNajmabadi/roslyn,jcouv/roslyn,dotnet/roslyn,sharwell/roslyn,abock/roslyn,VSadov/roslyn,physhi/roslyn,abock/roslyn,bkoelman/roslyn,xasx/roslyn,DustinCampbell/roslyn,ErikSchierboom/roslyn,heejaechang/roslyn,KirillOsenkov/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,reaction1989/roslyn,brettfo/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,panopticoncentral/roslyn,heejaechang/roslyn,cston/roslyn,agocke/roslyn,sharwell/roslyn,tannergooding/roslyn,tmat/roslyn,dpoeschl/roslyn,davkean/roslyn,agocke/roslyn,KirillOsenkov/roslyn,jamesqo/roslyn,jmarolf/roslyn,VSadov/roslyn,tannergooding/roslyn,tannergooding/roslyn,KevinRansom/roslyn,dotnet/roslyn,abock/roslyn,CyrusNajmabadi/roslyn,gafter/roslyn,panopticoncentral/roslyn,jamesqo/roslyn,xasx/roslyn,wvdd007/roslyn,ErikSchierboom/roslyn,KirillOsenkov/roslyn,jmarolf/roslyn,gafter/roslyn,nguerrera/roslyn,jcouv/roslyn,bartdesmet/roslyn,MichalStrehovsky/roslyn,ErikSchierboom/roslyn,weltkante/roslyn,diryboy/roslyn,cston/roslyn,bkoelman/roslyn,dpoeschl/roslyn,bkoelman/roslyn,shyamnamboodiripad/roslyn,jamesqo/roslyn,stephentoub/roslyn,dotnet/roslyn,physhi/roslyn,KevinRansom/roslyn,genlu/roslyn,shyamnamboodiripad/roslyn,eriawan/roslyn,jasonmalinowski/roslyn,KevinRansom/roslyn,eriawan/roslyn,AlekseyTs/roslyn,OmarTawfik/roslyn,aelij/roslyn,physhi/roslyn,reaction1989/roslyn,mavasani/roslyn,jcouv/roslyn,mgoertz-msft/roslyn,stephentoub/roslyn,mgoertz-msft/roslyn,tmat/roslyn,jasonmalinowski/roslyn,aelij/roslyn,mavasani/roslyn,weltkante/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,MichalStrehovsky/roslyn,eriawan/roslyn,wvdd007/roslyn,tmeschter/roslyn,xasx/roslyn,swaroop-sridhar/roslyn,swaroop-sridhar/roslyn,jmarolf/roslyn,stephentoub/roslyn,weltkante/roslyn,diryboy/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,cston/roslyn,paulvanbrenk/roslyn,dpoeschl/roslyn,reaction1989/roslyn,brettfo/roslyn,MichalStrehovsky/roslyn,shyamnamboodiripad/roslyn,tmeschter/roslyn,paulvanbrenk/roslyn,OmarTawfik/roslyn,mavasani/roslyn,sharwell/roslyn,genlu/roslyn,paulvanbrenk/roslyn,davkean/roslyn,VSadov/roslyn,CyrusNajmabadi/roslyn,DustinCampbell/roslyn,aelij/roslyn,davkean/roslyn,heejaechang/roslyn,AlekseyTs/roslyn,AmadeusW/roslyn,OmarTawfik/roslyn,nguerrera/roslyn,AmadeusW/roslyn,swaroop-sridhar/roslyn,tmat/roslyn,AlekseyTs/roslyn,genlu/roslyn,diryboy/roslyn,DustinCampbell/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,wvdd007/roslyn | src/Features/Core/Portable/AbstractParenthesesDiagnosticAnalyzer.cs | src/Features/Core/Portable/AbstractParenthesesDiagnosticAnalyzer.cs | // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
{
internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractCodeStyleDiagnosticAnalyzer
{
protected AbstractParenthesesDiagnosticAnalyzer(
string descriptorId, LocalizableString title, LocalizableString message)
: base(descriptorId, title, message)
{
}
protected PerLanguageOption<CodeStyleOption<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind)
{
switch (precedenceKind)
{
case PrecedenceKind.Arithmetic:
case PrecedenceKind.Shift:
case PrecedenceKind.Bitwise:
return CodeStyleOptions.ArithmeticBinaryParentheses;
case PrecedenceKind.Relational:
case PrecedenceKind.Equality:
case PrecedenceKind.Logical:
case PrecedenceKind.Coalesce:
return CodeStyleOptions.OtherBinaryParentheses;
case PrecedenceKind.Other:
return CodeStyleOptions.OtherParentheses;
}
throw ExceptionUtilities.UnexpectedValue(precedenceKind);
}
}
}
| // Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.Options;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.RemoveUnnecessaryParentheses
{
internal abstract class AbstractParenthesesDiagnosticAnalyzer : AbstractCodeStyleDiagnosticAnalyzer
{
protected AbstractParenthesesDiagnosticAnalyzer(
string descriptorId, LocalizableString title, LocalizableString message)
: base(descriptorId, title, message)
{
}
protected PerLanguageOption<CodeStyleOption<ParenthesesPreference>> GetLanguageOption(PrecedenceKind precedenceKind)
{
switch (precedenceKind)
{
case PrecedenceKind.Arithmetic:
case PrecedenceKind.Shift:
case PrecedenceKind.Bitwise:
return CodeStyleOptions.ArithmeticBinaryParentheses;
case PrecedenceKind.Relational:
case PrecedenceKind.Equality:
case PrecedenceKind.Logical:
case PrecedenceKind.Coalesce:
return CodeStyleOptions.OtherBinaryParentheses;
case PrecedenceKind.Other: return CodeStyleOptions.OtherParentheses;
}
throw ExceptionUtilities.UnexpectedValue(precedenceKind);
}
}
}
| mit | C# |
40fe27db061942d5bb0919f76b33acf363adbd45 | Fix issue with trailing whitespace. | danielwertheim/mycouch,danielwertheim/mycouch | src/Projects/MyCouch/Responses/Factories/DocumentResponseFactory.cs | src/Projects/MyCouch/Responses/Factories/DocumentResponseFactory.cs | using System.IO;
using System.Net.Http;
using System.Text;
using MyCouch.Extensions;
using MyCouch.Serialization;
namespace MyCouch.Responses.Factories
{
public class DocumentResponseFactory : ResponseFactoryBase
{
public DocumentResponseFactory(SerializationConfiguration serializationConfiguration)
: base(serializationConfiguration) { }
public virtual DocumentResponse Create(HttpResponseMessage httpResponse)
{
return Materialize(new DocumentResponse(), httpResponse, OnSuccessfulResponse, OnFailedResponse);
}
protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse)
{
using (var content = httpResponse.Content.ReadAsStream())
{
if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage))
PopulateDocumentHeaderFromResponseStream(response, content);
else
{
PopulateMissingIdFromRequestUri(response, httpResponse);
PopulateMissingRevFromRequestHeaders(response, httpResponse);
}
content.Position = 0;
var sb = new StringBuilder();
using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding))
{
while (!reader.EndOfStream)
{
sb.Append(reader.ReadLine());
}
}
response.Content = sb.ToString();
sb.Clear();
}
}
}
} | using System.IO;
using System.Net.Http;
using MyCouch.Extensions;
using MyCouch.Serialization;
namespace MyCouch.Responses.Factories
{
public class DocumentResponseFactory : ResponseFactoryBase
{
public DocumentResponseFactory(SerializationConfiguration serializationConfiguration)
: base(serializationConfiguration) { }
public virtual DocumentResponse Create(HttpResponseMessage httpResponse)
{
return Materialize(new DocumentResponse(), httpResponse, OnSuccessfulResponse, OnFailedResponse);
}
protected virtual void OnSuccessfulResponse(DocumentResponse response, HttpResponseMessage httpResponse)
{
using (var content = httpResponse.Content.ReadAsStream())
{
if (ContentShouldHaveIdAndRev(httpResponse.RequestMessage))
PopulateDocumentHeaderFromResponseStream(response, content);
else
{
PopulateMissingIdFromRequestUri(response, httpResponse);
PopulateMissingRevFromRequestHeaders(response, httpResponse);
}
content.Position = 0;
using (var reader = new StreamReader(content, MyCouchRuntime.DefaultEncoding))
{
response.Content = reader.ReadToEnd();
}
}
}
}
} | mit | C# |
f8f12bffe264e97efea9f84894d0b4f27301dd9e | Return of signin; with updated content as per ticket. | SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice,SkillsFundingAgency/das-employerapprenticeshipsservice | src/SFA.DAS.EmployerAccounts.Web/Views/Home/ServiceStartPage.cshtml | src/SFA.DAS.EmployerAccounts.Web/Views/Home/ServiceStartPage.cshtml | @{ViewBag.PageID = "page-service-start"; }
@{ViewBag.Title = "Manage apprenticeships"; }
@{ViewBag.MetaDesc = "Manage your funding for apprenticeships in England"; }
@{ViewBag.HideNav = "true"; }
@{
ViewBag.GaData.Vpv = "/page-service-start";
}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">
@ViewBag.Title
</h1>
<p class="lede">This service is for organisations that want to take on apprentices.</p>
<p>Use this service to:</p>
<ul class="list list-bullet">
<li>set up and manage apprenticeship training</li>
<li>pay for apprenticeship training</li>
</ul>
<p>
You must register for a manage apprenticeships account in order to get government funding for training your apprentices.
<strong><a href="@Url.Action("SignIn", "Home")">sign in</a> if you already have an account.</strong>
</p>
<p><a class="button button-start" id="service-start" href="@Url.Action("UsedServiceBefore", "Home")">Start</a></p>
<h2 class="heading-medium">Before you start</h2>
<ul class="list list-bullet">
<li>Find out more about <a target="_blank" rel="external" href="https://www.gov.uk/take-on-an-apprentice">employing apprentices</a></li>
<li>Find out <a target="_blank" rel="external" href="https://www.gov.uk/guidance/manage-apprenticeship-funds">how you can use</a> your apprenticeship account</li>
<li>Find out about the <a target="_blank" rel="external" href="https://www.gov.uk/government/publications/apprenticeship-levy-how-it-will-work/apprenticeship-levy-how-it-will-work">apprenticeship levy</a></li>
</ul>
</div>
</div> | @{ViewBag.PageID = "page-service-start"; }
@{ViewBag.Title = "Manage apprenticeships"; }
@{ViewBag.MetaDesc = "Manage your funding for apprenticeships in England"; }
@{ViewBag.HideNav = "true"; }
@{
ViewBag.GaData.Vpv = "/page-service-start";
}
<div class="grid-row">
<div class="column-two-thirds">
<h1 class="heading-xlarge">
@ViewBag.Title
</h1>
<p class="lede">This service is for organisations that want to take on apprentices.</p>
<p>Use this service to:</p>
<ul class="list list-bullet">
<li>set up and manage apprenticeship training</li>
<li>pay for apprenticeship training</li>
</ul>
<p><a class="button button-start" id="service-start" href="@Url.Action("UsedServiceBefore", "Home")">Start</a></p>
<h2 class="heading-medium">Before you start</h2>
<ul class="list list-bullet">
<li>Find out more about <a target="_blank" rel="external" href="https://www.gov.uk/take-on-an-apprentice">employing apprentices</a></li>
<li>Find out <a target="_blank" rel="external" href="https://www.gov.uk/guidance/manage-apprenticeship-funds">how you can use</a> your apprenticeship account</li>
<li>Find out about the <a target="_blank" rel="external" href="https://www.gov.uk/government/publications/apprenticeship-levy-how-it-will-work/apprenticeship-levy-how-it-will-work">apprenticeship levy</a></li>
</ul>
</div>
</div> | mit | C# |
5a6bf5ac3dfabbc578f973e0c09c2e2d3a494b46 | clean MigrationEntity | AlejandroCano/extensions,signumsoftware/extensions,signumsoftware/framework,MehdyKarimpour/extensions,signumsoftware/extensions,AlejandroCano/extensions,MehdyKarimpour/extensions,signumsoftware/framework | Signum.Entities.Extensions/Migrations/Migration.cs | Signum.Entities.Extensions/Migrations/Migration.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Signum.Utilities;
namespace Signum.Entities.Migrations
{
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional), TicksColumn(false)]
public class MigrationEntity : Entity
{
string versionNumber;
public string VersionNumber
{
get { return versionNumber; }
set { Set(ref versionNumber, value); }
}
DateTime executionDate;
public DateTime ExecutionDate
{
get { return executionDate; }
set { SetToStr(ref executionDate, value); }
}
static Expression<Func<MigrationEntity, string>> ToStringExpression = e => e.VersionNumber;
public override string ToString()
{
return ToStringExpression.Evaluate(this);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using Signum.Utilities;
namespace Signum.Entities.Migrations
{
[Serializable, EntityKind(EntityKind.System, EntityData.Transactional)]
public class MigrationEntity : Entity
{
string versionNumber;
public string VersionNumber
{
get { return versionNumber; }
set { Set(ref versionNumber, value); }
}
DateTime executionDate;
public DateTime ExecutionDate
{
get { return executionDate; }
set { SetToStr(ref executionDate, value); }
}
}
}
| mit | C# |
8c537c45180c38aaea06131d5bb52b3531bd9261 | Refactor and tidy-up | DanielLarsenNZ/examples,DanielLarsenNZ/examples | functions-hi-connections/HiConnections/GetSecrets.cs | functions-hi-connections/HiConnections/GetSecrets.cs | using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Threading.Tasks;
using static Microsoft.Azure.KeyVault.KeyVaultClient;
namespace HiConnections
{
public class GetSecrets : Secrets
{
public GetSecrets(TelemetryConfiguration telemetryConfiguration) : base(telemetryConfiguration)
{
}
/// <summary>
/// This version news up a KeyVaultClient for every decryption
/// </summary>
[FunctionName("GetSecrets")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation(nameof(GetSecrets));
return await GetSecrets();
}
protected override KeyVaultCrypto GetCrypto()
{
return new KeyVaultCrypto(new KeyVaultClient(
new AuthenticationCallback(new AzureServiceTokenProvider().KeyVaultTokenCallback)),
Environment.GetEnvironmentVariable("KeyId"));
}
}
}
| using Microsoft.ApplicationInsights.Extensibility;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.KeyVault;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Threading.Tasks;
using static Microsoft.Azure.KeyVault.KeyVaultClient;
namespace HiConnections
{
public class GetSecrets : Secrets
{
private readonly KeyVaultCrypto _crypto;
private static HttpClient _http = new HttpClient();
private static readonly KeyVaultClient _keyVaultClient =
new KeyVaultClient(new AuthenticationCallback(
new AzureServiceTokenProvider().KeyVaultTokenCallback),
_http);
public GetSecrets(TelemetryConfiguration telemetryConfiguration) : base(telemetryConfiguration)
{
}
/// <summary>
/// This version news up a KeyVaultClient for every decryption
/// </summary>
[FunctionName("GetSecrets")]
public async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation(nameof(GetSecrets));
return await GetSecrets();
}
protected override KeyVaultCrypto GetCrypto()
{
var keyVaultClient = new KeyVaultClient(
new AuthenticationCallback(new AzureServiceTokenProvider().KeyVaultTokenCallback));
return new KeyVaultCrypto(keyVaultClient, "https://helloase-aue-kv.vault.azure.net/keys/key1");
}
}
}
| mit | C# |
32327caac615f033dfc66f86c5b17053cc831649 | add first implementation of h-dependency | hylasoft-usa/h-dependency,hylasoft-usa/h-dependency | h-dependency/HDependency.cs | h-dependency/HDependency.cs | using System;
using System.Collections.Generic;
namespace hylasoft.dependency
{
/// <summary>
/// Simple dependency mechanism provider to achieve loose coupling and easy mocking.
/// It's a not a pure dependency injection provider, but it offers more flexibility in terms of where it can be used and initialized.
/// It doesn't offer dependency resolution mechanism.
/// </summary>
public class HDependency
{
#region static methods
/// <summary>
/// Initialize the provider. This method should be called during the bootstrapping of the application.
/// </summary>
/// <param name="test">If set to true, the provider can be reinitialized (default to false). It's useful when the provider needs to be used in unit tests, so it can be reinitialized</param>
/// <exception cref="InvalidOperationException">This exception is thrown when the provider can't be instantiated, because it has already been instantiated in debug mode</exception>
public static void Initialize(bool test = false)
{
if (!_canBeInitialized)
throw new InvalidOperationException("The dependency Initializer cannot be started twice if it's not initialized in test mode.");
//set a new dependency injector.
Provider = new HDependency { _services = new Dictionary<Type, object>() };
_canBeInitialized = test;
}
public static HDependency Provider { get; private set; }
private static bool _canBeInitialized = true;
#endregion
/// <summary>
/// default constructor made private
/// </summary>
internal HDependency() { }
/// <summary>
/// Dictornary containing all the registered service classes
/// </summary>
private IDictionary<Type, object> _services;
/// <summary>
/// Register an instance in the provider
/// </summary>
/// <typeparam name="T">The type used to register the service. To retrieve the service, this instance must be used</typeparam>
/// <param name="instance">The instance to be registered</param>
/// <exception cref="ArgumentException">Thrown when the instance object is not an instance of type T</exception>
/// <exception cref="InvalidOperationException">Thrown when a service registered with the same type already exists</exception>
public void Register<T>(object instance) where T : class
{
if ((instance as T) == null)
throw new ArgumentException("The instance has to be of the same class of the Type passed.");
var type = typeof(T);
if (_services.ContainsKey(type))
throw new InvalidOperationException("The type has an already specified instance in the provider.");
_services.Add(type, instance);
}
/// <summary>
/// Get a service that is registered in the provider with the requested type
/// </summary>
/// <typeparam name="T">the type that the passed service is registered with</typeparam>
/// <returns>The service that implements the requested type</returns>
/// <exception cref="ArgumentException">Thrown when the provider doesn't contain a service for the type T</exception>
public T Get<T>() where T : class
{
object val;
if (!_services.TryGetValue(typeof (T), out val))
throw new ArgumentException("Unable to find " + typeof(T).Name + ". It appears is not registered.");
return val as T;
}
}
} | namespace hylasoft.dependency
{
/// <summary>
/// Simple dependency mechanism to loose coupling and easy mocking
/// </summary>
public class HDependency
{
}
}
| mit | C# |
70a3823da39f688593848e539f82ec748bc418d6 | Remove virtual from overloads in AlternateType | dudzon/Glimpse,SusanaL/Glimpse,gabrielweyer/Glimpse,rho24/Glimpse,rho24/Glimpse,gabrielweyer/Glimpse,paynecrl97/Glimpse,codevlabs/Glimpse,elkingtonmcb/Glimpse,sorenhl/Glimpse,gabrielweyer/Glimpse,sorenhl/Glimpse,paynecrl97/Glimpse,flcdrg/Glimpse,codevlabs/Glimpse,paynecrl97/Glimpse,dudzon/Glimpse,elkingtonmcb/Glimpse,SusanaL/Glimpse,Glimpse/Glimpse,flcdrg/Glimpse,rho24/Glimpse,paynecrl97/Glimpse,codevlabs/Glimpse,SusanaL/Glimpse,elkingtonmcb/Glimpse,flcdrg/Glimpse,sorenhl/Glimpse,Glimpse/Glimpse,rho24/Glimpse,Glimpse/Glimpse,dudzon/Glimpse | source/Glimpse.Core/Extensibility/AlternateType.cs | source/Glimpse.Core/Extensibility/AlternateType.cs | using System;
using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Core.Extensibility
{
public abstract class AlternateType<T> : IAlternateType<T> where T : class
{
protected AlternateType(IProxyFactory proxyFactory)
{
if (proxyFactory == null)
{
throw new ArgumentNullException("proxyFactory");
}
ProxyFactory = proxyFactory;
}
public IProxyFactory ProxyFactory { get; set; }
public abstract IEnumerable<IAlternateMethod> AllMethods { get; }
public bool TryCreate(T originalObj, out T newObj)
{
return TryCreate(originalObj, out newObj, null, null);
}
public bool TryCreate(T originalObj, out T newObj, IEnumerable<object> mixins)
{
return TryCreate(originalObj, out newObj, mixins, null);
}
public virtual bool TryCreate(T originalObj, out T newObj, IEnumerable<object> mixins, object[] constructorArguments)
{
var allMethods = AllMethods;
if (mixins == null)
{
mixins = Enumerable.Empty<object>();
}
if (ProxyFactory.IsWrapInterfaceEligible<T>(typeof(T)))
{
newObj = ProxyFactory.WrapInterface(originalObj, allMethods, mixins);
return true;
}
if (ProxyFactory.IsWrapClassEligible(typeof(T)))
{
try
{
newObj = ProxyFactory.WrapClass(originalObj, allMethods, mixins, constructorArguments);
return true;
}
catch
{
newObj = null;
return false;
}
}
newObj = null;
return false;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
namespace Glimpse.Core.Extensibility
{
public abstract class AlternateType<T> : IAlternateType<T> where T : class
{
protected AlternateType(IProxyFactory proxyFactory)
{
if (proxyFactory == null)
{
throw new ArgumentNullException("proxyFactory");
}
ProxyFactory = proxyFactory;
}
public IProxyFactory ProxyFactory { get; set; }
public abstract IEnumerable<IAlternateMethod> AllMethods { get; }
public virtual bool TryCreate(T originalObj, out T newObj)
{
return TryCreate(originalObj, out newObj, null, null);
}
public virtual bool TryCreate(T originalObj, out T newObj, IEnumerable<object> mixins)
{
return TryCreate(originalObj, out newObj, mixins, null);
}
public virtual bool TryCreate(T originalObj, out T newObj, IEnumerable<object> mixins, object[] constructorArguments)
{
var allMethods = AllMethods;
if (mixins == null)
{
mixins = Enumerable.Empty<object>();
}
if (ProxyFactory.IsWrapInterfaceEligible<T>(typeof(T)))
{
newObj = ProxyFactory.WrapInterface(originalObj, allMethods, mixins);
return true;
}
if (ProxyFactory.IsWrapClassEligible(typeof(T)))
{
try
{
newObj = ProxyFactory.WrapClass(originalObj, allMethods, mixins, constructorArguments);
return true;
}
catch
{
newObj = null;
return false;
}
}
newObj = null;
return false;
}
}
}
| apache-2.0 | C# |
ba693939964e80718dbf68afa5f610ac54b825c8 | Change modify Portuguese Ordinalizer | ErikSchierboom/Humanizer,hazzik/Humanizer,MehdiK/Humanizer,schalpat/Humanizer,jaxx-rep/Humanizer,aloisdg/Humanizer,Flatlineato/Humanizer,ErikSchierboom/Humanizer,Flatlineato/Humanizer,schalpat/Humanizer | src/Humanizer/Configuration/OrdinalizerRegistry.cs | src/Humanizer/Configuration/OrdinalizerRegistry.cs | using Humanizer.Localisation.Ordinalizers;
namespace Humanizer.Configuration
{
internal class OrdinalizerRegistry : LocaliserRegistry<IOrdinalizer>
{
public OrdinalizerRegistry() : base(new DefaultOrdinalizer())
{
Register("de", new GermanOrdinalizer());
Register("en", new EnglishOrdinalizer());
Register("es", new SpanishOrdinalizer());
Register("it", new ItalianOrdinalizer());
Register("pt", new PortugueseOrdinalizer());
Register("ru", new RussianOrdinalizer());
Register("tr", new TurkishOrdinalizer());
}
}
}
| using Humanizer.Localisation.Ordinalizers;
namespace Humanizer.Configuration
{
internal class OrdinalizerRegistry : LocaliserRegistry<IOrdinalizer>
{
public OrdinalizerRegistry() : base(new DefaultOrdinalizer())
{
Register("de", new GermanOrdinalizer());
Register("en", new EnglishOrdinalizer());
Register("es", new SpanishOrdinalizer());
Register("it", new ItalianOrdinalizer());
Register("pt-BR", new BrazilianPortugueseOrdinalizer());
Register("ru", new RussianOrdinalizer());
Register("tr", new TurkishOrdinalizer());
}
}
} | mit | C# |
0f70773f1af31ddde4de4ccd044eace090f460a4 | switch Nancy status module to async | lvermeulen/Nanophone | src/Nanophone.RegistryTenant.Nancy/StatusModule.cs | src/Nanophone.RegistryTenant.Nancy/StatusModule.cs | using System.Threading.Tasks;
using Nancy;
using Nanophone.RegistryTenant.Nancy.Logging;
namespace Nanophone.RegistryTenant.Nancy
{
public class StatusModule : NancyModule
{
private static readonly ILog s_log = LogProvider.For<StatusModule>();
public StatusModule()
{
Get("/status", async parameters =>
{
s_log.Info("Status: OK");
return await Task.FromResult("OK");
});
}
}
}
| using System.Threading.Tasks;
using Nancy;
using Nanophone.RegistryTenant.Nancy.Logging;
namespace Nanophone.RegistryTenant.Nancy
{
public class StatusModule : NancyModule
{
private static readonly ILog s_log = LogProvider.For<StatusModule>();
public StatusModule()
{
Get("/status", parameters =>
{
s_log.Info("Status: OK");
return Task.FromResult("OK");
});
}
}
}
| mit | C# |
126ed9d6321bf444ff97a19fe6842fe116286f77 | Fix crash in ApplicationWindowState.Dispose | canton7/SyncTrayzor,canton7/SyncTrayzor,canton7/SyncTrayzor | src/SyncTrayzor/Services/ApplicationWindowState.cs | src/SyncTrayzor/Services/ApplicationWindowState.cs | using Stylet;
using SyncTrayzor.Pages;
using System;
namespace SyncTrayzor.Services
{
public interface IApplicationWindowState : IDisposable
{
event EventHandler<ActivationEventArgs> RootWindowActivated;
event EventHandler<DeactivationEventArgs> RootWindowDeactivated;
event EventHandler<CloseEventArgs> RootWindowClosed;
ScreenState ScreenState { get; }
void Setup(ShellViewModel rootViewModel);
void CloseToTray();
void EnsureInForeground();
}
public class ApplicationWindowState : IApplicationWindowState
{
private ShellViewModel rootViewModel;
public void Setup(ShellViewModel rootViewModel)
{
this.rootViewModel = rootViewModel;
this.rootViewModel.Activated += this.OnRootWindowActivated;
this.rootViewModel.Deactivated += this.OnRootWindowDeactivated;
this.rootViewModel.Closed += this.OnRootWindowClosed;
}
public event EventHandler<ActivationEventArgs> RootWindowActivated;
public event EventHandler<DeactivationEventArgs> RootWindowDeactivated;
public event EventHandler<CloseEventArgs> RootWindowClosed;
private void OnRootWindowActivated(object sender, ActivationEventArgs e)
{
this.RootWindowActivated?.Invoke(this, e);
}
private void OnRootWindowDeactivated(object sender, DeactivationEventArgs e)
{
this.RootWindowDeactivated?.Invoke(this, e);
}
private void OnRootWindowClosed(object sender, CloseEventArgs e)
{
this.RootWindowClosed?.Invoke(this, e);
}
public ScreenState ScreenState => this.rootViewModel.ScreenState;
public void CloseToTray()
{
this.rootViewModel.CloseToTray();
}
public void EnsureInForeground()
{
this.rootViewModel.EnsureInForeground();
}
public void Dispose()
{
if (this.rootViewModel != null)
{
this.rootViewModel.Activated -= this.OnRootWindowActivated;
this.rootViewModel.Deactivated -= this.OnRootWindowDeactivated;
this.rootViewModel.Closed -= this.OnRootWindowClosed;
}
}
}
}
| using Stylet;
using SyncTrayzor.Pages;
using System;
namespace SyncTrayzor.Services
{
public interface IApplicationWindowState : IDisposable
{
event EventHandler<ActivationEventArgs> RootWindowActivated;
event EventHandler<DeactivationEventArgs> RootWindowDeactivated;
event EventHandler<CloseEventArgs> RootWindowClosed;
ScreenState ScreenState { get; }
void Setup(ShellViewModel rootViewModel);
void CloseToTray();
void EnsureInForeground();
}
public class ApplicationWindowState : IApplicationWindowState
{
private ShellViewModel rootViewModel;
public void Setup(ShellViewModel rootViewModel)
{
this.rootViewModel = rootViewModel;
this.rootViewModel.Activated += this.OnRootWindowActivated;
this.rootViewModel.Deactivated += this.OnRootWindowDeactivated;
this.rootViewModel.Closed += this.OnRootWindowClosed;
}
public event EventHandler<ActivationEventArgs> RootWindowActivated;
public event EventHandler<DeactivationEventArgs> RootWindowDeactivated;
public event EventHandler<CloseEventArgs> RootWindowClosed;
private void OnRootWindowActivated(object sender, ActivationEventArgs e)
{
this.RootWindowActivated?.Invoke(this, e);
}
private void OnRootWindowDeactivated(object sender, DeactivationEventArgs e)
{
this.RootWindowDeactivated?.Invoke(this, e);
}
private void OnRootWindowClosed(object sender, CloseEventArgs e)
{
this.RootWindowClosed?.Invoke(this, e);
}
public ScreenState ScreenState => this.rootViewModel.ScreenState;
public void CloseToTray()
{
this.rootViewModel.CloseToTray();
}
public void EnsureInForeground()
{
this.rootViewModel.EnsureInForeground();
}
public void Dispose()
{
this.rootViewModel.Activated -= this.OnRootWindowActivated;
this.rootViewModel.Deactivated -= this.OnRootWindowDeactivated;
this.rootViewModel.Closed -= this.OnRootWindowClosed;
}
}
}
| mit | C# |
cdeb404b224680724eb3085e9771728c638bd9c0 | Update WalletWasabi.Tests/UnitTests/ListExtensionTests.cs | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Tests/UnitTests/ListExtensionTests.cs | WalletWasabi.Tests/UnitTests/ListExtensionTests.cs | using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ListExtensionTests
{
[Fact]
public void InsertSorted_Orders_Items_Correctly()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void InsertSorted_Orders_Items_Correctly_Allowing_Duplicates()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(5, false);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void BinarySearch_Uses_CompareTo()
{
var actual = new List<ReverseComparable>();
actual.InsertSorted(new ReverseComparable(0));
actual.InsertSorted(new ReverseComparable(1));
actual.InsertSorted(new ReverseComparable(2));
actual.InsertSorted(new ReverseComparable(3));
actual.InsertSorted(new ReverseComparable(4));
var expected = new List<ReverseComparable>
{
new ReverseComparable(4),
new ReverseComparable(3),
new ReverseComparable(2),
new ReverseComparable(1),
new ReverseComparable(0)
};
Assert.Equal(expected, actual);
}
private class ReverseComparable : IComparable<ReverseComparable>
{
public ReverseComparable(int value)
{
Value = value;
}
public int Value { get; }
public int CompareTo([AllowNull] ReverseComparable other)
{
return other.Value.CompareTo(Value);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using Xunit;
namespace WalletWasabi.Tests.UnitTests
{
public class ListExtensionTests
{
[Fact]
public void InsertSorted_Orders_Items_Correctly()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void InsertSorted_Orders_Items_Correctly_Allowing_Duplicates()
{
var actual = new List<int>();
actual.InsertSorted(5);
actual.InsertSorted(4);
actual.InsertSorted(3);
actual.InsertSorted(2);
actual.InsertSorted(5, false);
actual.InsertSorted(1);
actual.InsertSorted(0);
var expected = new List<int> { 0, 1, 2, 3, 4, 5, 5 };
Assert.Equal(expected, actual);
}
[Fact]
public void BinarySearch_Uses_CompareTo()
{
var actual = new List<ReverseComparable>();
actual.InsertSorted(new ReverseComparable(0));
actual.InsertSorted(new ReverseComparable(1));
actual.InsertSorted(new ReverseComparable(2));
actual.InsertSorted(new ReverseComparable(3));
actual.InsertSorted(new ReverseComparable(4));
var expected = new List<ReverseComparable>
{
new ReverseComparable(4),
new ReverseComparable(3),
new ReverseComparable(2),
new ReverseComparable(1),
new ReverseComparable(0)
};
Assert.Equal(expected, actual);
}
private class ReverseComparable : IComparable<ReverseComparable>
{
public ReverseComparable(int value)
{
Value = value;
}
public int Value { get; }
public int CompareTo([AllowNull] ReverseComparable other)
{
return other.Value.CompareTo(Value);
}
}
}
}
| mit | C# |
2c3a9fb947152f5ca8b60f6d5e8c69986e1aa97d | Remove leftover EnsureCreated() call | martincostello/sqllocaldb | samples/TodoApp/Data/TodoContext.cs | samples/TodoApp/Data/TodoContext.cs | // Copyright (c) Martin Costello, 2012-2018. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using Microsoft.EntityFrameworkCore;
namespace TodoApp.Data
{
/// <summary>
/// A class representing the database context for TodoApp.
/// </summary>
public class TodoContext : DbContext
{
/// <summary>
/// Initializes a new instance of the <see cref="TodoContext"/> class.
/// </summary>
/// <param name="options">The options for this context.</param>
public TodoContext(DbContextOptions<TodoContext> options)
: base(options)
{
}
/// <summary>
/// Gets or sets the database set containing the Todo items.
/// </summary>
public DbSet<TodoItem> Items { get; set; }
}
}
| // Copyright (c) Martin Costello, 2012-2018. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
using Microsoft.EntityFrameworkCore;
namespace TodoApp.Data
{
/// <summary>
/// A class representing the database context for TodoApp.
/// </summary>
public class TodoContext : DbContext
{
/// <summary>
/// Initializes a new instance of the <see cref="TodoContext"/> class.
/// </summary>
/// <param name="options">The options for this context.</param>
public TodoContext(DbContextOptions<TodoContext> options)
: base(options)
{
Database.EnsureCreated();
}
/// <summary>
/// Gets or sets the database set containing the Todo items.
/// </summary>
public DbSet<TodoItem> Items { get; set; }
}
}
| apache-2.0 | C# |
1f4f6a3f7d22ecb76dfdf8712f307375a7253d64 | add thread utils | oelite/RESTme | OElite.Restme.Utils/ThreadUtils.cs | OElite.Restme.Utils/ThreadUtils.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace OElite
{
public static class ThreadUtils
{
public static void RunInBackgroundAndForget(this Task task)
{
}
public static void RunInBackgroundAndForget(Action action)
{
Task.Run(action).RunInBackgroundAndForget();
}
public static T WaitAndGetResult<T>(this Task<T> task, int timeoutMiliseconds = -1)
{
if (task == null) return default(T);
if (timeoutMiliseconds > 0)
{
task.Wait(timeoutMiliseconds);
}
else
task.Wait();
return task.Result;
}
public static void WaitTillAvailableToProcess<TA>(List<TA> processingObjects, TA newObject)
{
if (processingObjects?.Count >= 0)
{
#region This code can be better improved using queue mechanism
var executionWaitRequired = true;
while (executionWaitRequired)
{
lock (processingObjects)
{
executionWaitRequired = processingObjects.FirstOrDefault() != null;
if (executionWaitRequired)
Thread.Sleep(1);
else
{
processingObjects.Add(newObject);
}
}
if (executionWaitRequired)
Thread.Sleep(100);
}
#endregion
}
}
public static void ClearProcessingObject<TA>(List<TA> processingObjects, TA singleObjectToRemove = default,
bool throwExceptionIfObjectNotFound = true)
{
if (processingObjects?.Count > 0)
{
lock (processingObjects)
{
if (singleObjectToRemove != null)
{
var indexOfObject = processingObjects.IndexOf(singleObjectToRemove);
if (indexOfObject >= 0)
{
processingObjects.Remove(singleObjectToRemove);
}
else if (throwExceptionIfObjectNotFound)
{
throw new OEliteException("Object to remove is no longer in the processing queue");
}
}
else
{
processingObjects.Clear();
}
}
}
}
}
} | using System;
using System.Threading.Tasks;
namespace OElite
{
public static class ThreadUtils
{
public static void RunInBackgroundAndForget(this Task task)
{
}
public static void RunInBackgroundAndForget(Action action)
{
Task.Run(action).RunInBackgroundAndForget();
}
public static T WaitAndGetResult<T>(this Task<T> task, int timeoutMiliseconds = -1)
{
if (task == null) return default(T);
if (timeoutMiliseconds > 0)
{
task.Wait(timeoutMiliseconds);
}
else
task.Wait();
return task.Result;
}
}
} | mit | C# |
293aa45a55fdabc7f44736f3b473601d4de99cc8 | Format Input code | sandermvanvliet/kata-nethack,nrjohnstone/kata-nethack | KataNetHack.Console/Input/Input.cs | KataNetHack.Console/Input/Input.cs | using System;
namespace KataNetHack.Console.Input
{
public class Input
{
public Func<ConsoleKeyInfo> ReadKey = () => System.Console.ReadKey(intercept:true);
public event Action<InputResult> InputReceived;
public void PollForInput()
{
InputResult inputReceived;
var key = ReadKey();
switch(key.Key)
{
case ConsoleKey.W:
inputReceived = InputResult.Up;
break;
case ConsoleKey.A:
inputReceived = InputResult.Left;
break;
case ConsoleKey.S:
inputReceived = InputResult.Down;
break;
case ConsoleKey.D:
inputReceived = InputResult.Right;
break;
default:
inputReceived = InputResult.Invalid;
break;
}
if(inputReceived != InputResult.Invalid)
InputReceived?.Invoke(inputReceived);
}
}
} | using System;
namespace KataNetHack.Console.Input
{
public class Input
{
public Func<ConsoleKeyInfo> ReadKey = () => System.Console.ReadKey(intercept:true);
public event Action<InputResult> InputReceived;
public void PollForInput()
{
InputResult inputReceived;
var key = ReadKey();
switch (key.Key)
{
case ConsoleKey.W:
inputReceived = InputResult.Up;
break;
case ConsoleKey.A:
inputReceived = InputResult.Left;
break;
case ConsoleKey.S:
inputReceived = InputResult.Down;
break;
case ConsoleKey.D:
inputReceived = InputResult.Right;
break;
default:
inputReceived = InputResult.Invalid;
break;
}
if (inputReceived != InputResult.Invalid)
InputReceived?.Invoke(inputReceived);
}
}
} | mit | C# |
e520200fd897c4f93552852938813be8373f94ee | Update DialogIOS.cs | asus4/UnityNativeDialogPlugin,asus4/UnityNativeDialogPlugin | Packages/com.github.asus4.nativedialog/Runtime/Internal/DialogIOS.cs | Packages/com.github.asus4.nativedialog/Runtime/Internal/DialogIOS.cs | #if UNITY_IOS
using System.Runtime.InteropServices;
namespace NativeDialog
{
internal sealed class DialogIOS : IDialog
{
public void Dispose()
{
}
public void SetLabel(string decide, string cancel, string close)
{
_setLabel(decide, cancel, close);
}
public int ShowSelect(string message)
{
return _showSelectDialog(message);
}
public int ShowSelect(string title, string message)
{
return _showSelectTitleDialog(title, message);
}
public int ShowSubmit(string message)
{
return _showSubmitDialog(message);
}
public int ShowSubmit(string title, string message)
{
return _showSubmitTitleDialog(title, message);
}
public void Dissmiss(int id)
{
_dissmissDialog(id);
}
[DllImport("__Internal")]
private static extern int _showSelectDialog(string msg);
[DllImport("__Internal")]
private static extern int _showSelectTitleDialog(string title, string msg);
[DllImport("__Internal")]
private static extern int _showSubmitDialog(string msg);
[DllImport("__Internal")]
private static extern int _showSubmitTitleDialog(string title, string msg);
[DllImport("__Internal")]
private static extern void _dissmissDialog(int id);
[DllImport("__Internal")]
private static extern void _setLabel(string decide, string cancel, string close);
}
}
#endif // UNITY_IOS | #if UNITY_IOS
using System.Runtime.InteropServices;
namespace NativeDialog
{
internal sealed class DialogIOS : IDialog
{
public void Dispose()
{
}
public void SetLabel(string decide, string cancel, string close)
{
_setLabel(decide, cancel, close);
}
public int ShowSelect(string message)
{
return _showSelectDialog(message);
}
public int ShowSelect(string title, string message)
{
return _showSelectTitleDialog(title, message);
}
public int ShowSubmit(string message)
{
return _showSubmitDialog(message);
}
public int ShowSubmit(string title, string message)
{
return _showSelectTitleDialog(title, message);
}
public void Dissmiss(int id)
{
_dissmissDialog(id);
}
[DllImport("__Internal")]
private static extern int _showSelectDialog(string msg);
[DllImport("__Internal")]
private static extern int _showSelectTitleDialog(string title, string msg);
[DllImport("__Internal")]
private static extern int _showSubmitDialog(string msg);
[DllImport("__Internal")]
private static extern int _showSubmitTitleDialog(string title, string msg);
[DllImport("__Internal")]
private static extern void _dissmissDialog(int id);
[DllImport("__Internal")]
private static extern void _setLabel(string decide, string cancel, string close);
}
}
#endif // UNITY_IOS | mit | C# |
7bd1bcba2f3f3ccb311620ddd97a368e768c7f6e | Update version number to 1.1 | mephraim/ghostscriptsharp | GhostScriptSharp/Properties/AssemblyInfo.cs | GhostScriptSharp/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GhostscriptSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("GhostscriptSharp")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("56ecd9b7-8386-481f-8603-3215c77c2eb6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.1")]
[assembly: AssemblyFileVersion("1.1")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GhostscriptSharp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("GhostscriptSharp")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("56ecd9b7-8386-481f-8603-3215c77c2eb6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyFileVersion("1.0")]
| mit | C# |
484ff6b4c00d0d7b9dc1efd51a53513ec087a45d | Move 'is active?' logic into overridable function | Gibe/Gibe.Navigation | Gibe.Navigation/DefaultNavigationService.cs | Gibe.Navigation/DefaultNavigationService.cs | using System;
using System.Collections.Generic;
using System.Linq;
using Gibe.Caching.Interfaces;
using Gibe.Navigation.Models;
namespace Gibe.Navigation
{
public class DefaultNavigationService<T> : INavigationService<T> where T : INavigationElement
{
private readonly ICache _cache;
private readonly IEnumerable<INavigationProvider<T>> _providers;
private readonly string _cacheKey;
public DefaultNavigationService(ICache cache, IEnumerable<INavigationProvider<T>> providers, string cacheKey = "navigation")
{
_cache = cache;
_providers = providers;
_cacheKey = cacheKey;
}
public Navigation<T> GetNavigation()
{
return GetNavigation(null);
}
public Navigation<T> GetNavigation(string currentUrl)
{
List<T> navElements;
if (_cache.Exists(_cacheKey))
{
navElements = Clone(_cache.Get<List<T>>(_cacheKey)).ToList();
}
else
{
navElements = _providers.OrderBy(p => p.Priority).SelectMany(p => p.GetNavigationElements()).ToList();
_cache.Add(_cacheKey, navElements, new TimeSpan(0, 10, 0));
}
SelectActiveTree(navElements, currentUrl);
return new Models.Navigation<T>
{
Items = Visible(navElements)
};
}
public SubNavigationModel<T> GetSubNavigation(string url)
{
var matchingSideNavigation = _providers
.OrderBy(x => x.Priority)
.Select(x => x.GetSubNavigation(url))
.SingleOrDefault(x => x != null);
if (matchingSideNavigation == null) return null;
SelectActiveTree(matchingSideNavigation.NavigationElements.ToList(), url);
return new SubNavigationModel<T>
{
SectionParent = matchingSideNavigation.SectionParent,
NavigationElements = Visible(matchingSideNavigation.NavigationElements.ToList())
};
}
private bool SelectActiveTree(List<T> elements, string currentUrl)
{
if (currentUrl != null)
{
foreach (var navigationElement in elements)
{
if (navigationElement.IsConcrete && (IsActive(currentUrl, navigationElement)))
{
navigationElement.IsActive = true;
return true;
}
navigationElement.IsActive = SelectActiveTree(navigationElement.Items.Select(i => (T)i).ToList(), currentUrl);
if (navigationElement.IsActive)
{
return true;
}
}
}
return elements.Any(n => n.IsActive);
}
protected bool IsActive(string currentUrl, T navigationElement) =>
navigationElement.Url.TrimEnd('/') == currentUrl.TrimEnd('/');
private IEnumerable<T> Clone(IEnumerable<T> elements)
=> elements.Select(e => (T)e.Clone()).ToList();
private IEnumerable<T> Visible(List<T> elements)
=> elements.Where(e => e.IsVisible).Select(e => (T)e.Clone());
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using Gibe.Caching.Interfaces;
using Gibe.Navigation.Models;
namespace Gibe.Navigation
{
public class DefaultNavigationService<T> : INavigationService<T> where T : INavigationElement
{
private readonly ICache _cache;
private readonly IEnumerable<INavigationProvider<T>> _providers;
private readonly string _cacheKey;
public DefaultNavigationService(ICache cache, IEnumerable<INavigationProvider<T>> providers, string cacheKey = "navigation")
{
_cache = cache;
_providers = providers;
_cacheKey = cacheKey;
}
public Navigation<T> GetNavigation()
{
return GetNavigation(null);
}
public Navigation<T> GetNavigation(string currentUrl)
{
List<T> navElements;
if (_cache.Exists(_cacheKey))
{
navElements = Clone(_cache.Get<List<T>>(_cacheKey)).ToList();
}
else
{
navElements = _providers.OrderBy(p => p.Priority).SelectMany(p => p.GetNavigationElements()).ToList();
_cache.Add(_cacheKey, navElements, new TimeSpan(0, 10, 0));
}
SelectActiveTree(navElements, currentUrl);
return new Models.Navigation<T>
{
Items = Visible(navElements)
};
}
public SubNavigationModel<T> GetSubNavigation(string url)
{
var matchingSideNavigation = _providers
.OrderBy(x => x.Priority)
.Select(x => x.GetSubNavigation(url))
.SingleOrDefault(x => x != null);
if (matchingSideNavigation == null) return null;
SelectActiveTree(matchingSideNavigation.NavigationElements.ToList(), url);
return new SubNavigationModel<T>
{
SectionParent = matchingSideNavigation.SectionParent,
NavigationElements = Visible(matchingSideNavigation.NavigationElements.ToList())
};
}
private bool SelectActiveTree(List<T> elements, string currentUrl)
{
if (currentUrl != null)
{
foreach (var navigationElement in elements)
{
if (navigationElement.IsConcrete && (navigationElement.Url.TrimEnd('/') == currentUrl.TrimEnd('/')))
{
navigationElement.IsActive = true;
return true;
}
navigationElement.IsActive = SelectActiveTree(navigationElement.Items.Select(i => (T)i).ToList(), currentUrl);
if (navigationElement.IsActive)
{
return true;
}
}
}
return elements.Any(n => n.IsActive);
}
private IEnumerable<T> Clone(IEnumerable<T> elements)
=> elements.Select(e => (T)e.Clone()).ToList();
private IEnumerable<T> Visible(List<T> elements)
=> elements.Where(e => e.IsVisible).Select(e => (T)e.Clone());
}
}
| mit | C# |
e443718dbbc2fb88e84cd09f06edc78d4c98e99c | Update assembly description | andyshao/Hangfire.Ninject,HangfireIO/Hangfire.Ninject | HangFire.Ninject/Properties/AssemblyInfo.cs | HangFire.Ninject/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HangFire.Ninject")]
[assembly: AssemblyDescription("Ninject IoC Container support for HangFire (background job system for ASP.NET applications).")]
[assembly: AssemblyProduct("HangFire")]
[assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91f25a4e-65e7-4d9c-886e-33a6c82b14c4")]
[assembly: AssemblyVersion("0.1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HangFire.Ninject")]
[assembly: AssemblyDescription("HangFire job activator based on Ninject IoC Container")]
[assembly: AssemblyProduct("HangFire")]
[assembly: AssemblyCopyright("Copyright © 2014 Sergey Odinokov")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("91f25a4e-65e7-4d9c-886e-33a6c82b14c4")]
[assembly: AssemblyVersion("0.1")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit | C# |
06a31d32f5b451bc392609fc54af10c98a934ce0 | add gunShot Audio edit | LNWPOR/HamsterRushVR-Client | Assets/Scripts/GameManager.cs | Assets/Scripts/GameManager.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public string URL = "http://localhost:8000";
public PlayerData playerData;
public int characterType;
private static GameManager _instance;
public static GameManager Instance
{
get
{
if (_instance == null)
{
_instance = new GameObject("GameManager").AddComponent<GameManager>();
}
return _instance;
}
}
void Awake()
{
playerData = new PlayerData("58e28708a8730c1ed41dd793", "LNWPOR", 0, 0);
characterType = 0;
DontDestroyOnLoad(gameObject);
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour {
public string URL = "http://localhost:8000";
public PlayerData playerData;
public int characterType;
private static GameManager _instance;
public static GameManager Instance
{
get
{
if (_instance == null)
{
_instance = new GameObject("GameManager").AddComponent<GameManager>();
}
return _instance;
}
}
void Awake()
{
playerData = new PlayerData("58e28708a8730c1ed41dd793", "LNWPOR", 0, 0);
characterType = 2;
DontDestroyOnLoad(gameObject);
}
}
| mit | C# |
6e71632dcf034bc9a4672ab7fc26d520f8d9dbe8 | Use the user-specific appdata path for the repository cache | awaescher/RepoZ,awaescher/RepoZ | RepoZ.Api.Win/Git/WindowsRepositoryCache.cs | RepoZ.Api.Win/Git/WindowsRepositoryCache.cs | using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepoZ.Api.Common;
using RepoZ.Api.Common.Git;
using RepoZ.Api.Git;
namespace RepoZ.Api.Win.Git
{
public class WindowsRepositoryCache : FileRepositoryCache
{
public WindowsRepositoryCache(IErrorHandler errorHandler)
: base(errorHandler)
{
}
public override string GetFileName() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "RepoZ\\Repositories.cache");
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepoZ.Api.Common;
using RepoZ.Api.Common.Git;
using RepoZ.Api.Git;
namespace RepoZ.Api.Win.Git
{
public class WindowsRepositoryCache : FileRepositoryCache
{
public WindowsRepositoryCache(IErrorHandler errorHandler)
: base(errorHandler)
{
}
public override string GetFileName() => Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "RepoZ\\Repositories.cache");
}
}
| mit | C# |
a4c228d38b0359565e445d8c8db30e0a6b5d4970 | Remove magic string for fake controller | kjac/FormEditor,kjac/FormEditor,kjac/FormEditor | Source/Solution/FormEditor/EmailRenderer.cs | Source/Solution/FormEditor/EmailRenderer.cs | using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core.Models;
namespace FormEditor
{
public class EmailRenderer
{
private const string EmailViewPath = "~/views/partials/formeditor/email/";
private class FakeController : Controller
{
}
public static string Render(string viewName, FormModel model, IPublishedContent currentContent)
{
var viewPath = Path.Combine(EmailViewPath, viewName);
var viewFile = new FileInfo(HostingEnvironment.MapPath(viewPath));
if (viewFile.Exists == false)
{
return null;
}
var writer = new StringWriter();
var context = new HttpContextWrapper(HttpContext.Current);
var routeData = new RouteData();
routeData.Values["controller"] = nameof(FakeController);
var controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController());
var razor = new RazorView(controllerContext, viewPath, null, false, null);
var viewData = new ViewDataDictionary(model);
// pass the current content to the email template, because Umbraco.AssignedContentItem doesn't work out of Umbraco context
viewData["currentContent"] = currentContent;
razor.Render(new ViewContext(controllerContext, razor, viewData, new TempDataDictionary(), writer), writer);
return writer.ToString();
}
public static IEnumerable<string> GetAllEmailTemplates()
{
var directory = new DirectoryInfo(HostingEnvironment.MapPath(EmailViewPath));
if (directory.Exists == false)
{
return new string[] { };
}
return directory.GetFiles("*.cshtml").Select(f => f.Name);
}
}
}
| using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;
using Umbraco.Core.Models;
namespace FormEditor
{
public class EmailRenderer
{
private const string EmailViewPath = "~/views/partials/formeditor/email/";
private class FakeController : Controller
{
}
public static string Render(string viewName, FormModel model, IPublishedContent currentContent)
{
var viewPath = Path.Combine(EmailViewPath, viewName);
var viewFile = new FileInfo(HostingEnvironment.MapPath(viewPath));
if (viewFile.Exists == false)
{
return null;
}
var writer = new StringWriter();
var context = new HttpContextWrapper(HttpContext.Current);
var routeData = new RouteData();
routeData.Values["controller"] = "FakeController";
var controllerContext = new ControllerContext(new RequestContext(context, routeData), new FakeController());
var razor = new RazorView(controllerContext, viewPath, null, false, null);
var viewData = new ViewDataDictionary(model);
// pass the current content to the email template, because Umbraco.AssignedContentItem doesn't work out of Umbraco context
viewData["currentContent"] = currentContent;
razor.Render(new ViewContext(controllerContext, razor, viewData, new TempDataDictionary(), writer), writer);
return writer.ToString();
}
public static IEnumerable<string> GetAllEmailTemplates()
{
var directory = new DirectoryInfo(HostingEnvironment.MapPath(EmailViewPath));
if (directory.Exists == false)
{
return new string[] { };
}
return directory.GetFiles("*.cshtml").Select(f => f.Name);
}
}
}
| mit | C# |
12043802d0ff177499cc884bbbb714ece34dc1fa | Remove html escaping for sermons. | razsilev/Sv_Naum,razsilev/Sv_Naum,razsilev/Sv_Naum | Source/SvNaum.Web/Views/Home/Sermons.cshtml | Source/SvNaum.Web/Views/Home/Sermons.cshtml | @model IEnumerable<SvNaum.Models.Sermon>
@{
ViewBag.Title = "Проповеди";
}
<h2>Проповеди!</h2>
<br />
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Create Sermon", "SermonAdd", "Admin")
<br />
<br />
}
@if (Model != null && Model.Count() > 0)
{
foreach (var item in Model)
{
<div>
@Html.LabelFor(m => item.Theme)
@Html.DisplayFor(m => item.Theme)
<br />
@Html.LabelFor(m => item.Title)
@Html.DisplayFor(m => item.Title)
<br />
@Html.LabelFor(m => item.Author)
@Html.DisplayFor(m => item.Author)
<br />
@Html.LabelFor(m => item.Text)
<p>
@Html.Raw(item.Text)
</p>
<br />
@Html.LabelFor(m => item.Date)
@Html.DisplayFor(m => item.Date.ToLocalTime().GetDateTimeFormats()[1])
<br />
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Delete", "SermonDelete", "Admin", new { id = item.Id }, null)
<br />
@Html.ActionLink("Edit", "SermonEdit", "Admin", new { id = item.Id }, null)
}
</div>
<p>-----------------------------------------</p>
}
}
else
{
<h3>There is no sermons!</h3>
}
| @model IEnumerable<SvNaum.Models.Sermon>
@{
ViewBag.Title = "Проповеди";
}
<h2>Проповеди!</h2>
<br />
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Create Sermon", "SermonAdd", "Admin")
<br />
<br />
}
@if (Model != null && Model.Count() > 0)
{
foreach (var item in Model)
{
<div>
@Html.LabelFor(m => item.Theme)
@Html.DisplayFor(m => item.Theme)
<br />
@Html.LabelFor(m => item.Title)
@Html.DisplayFor(m => item.Title)
<br />
@Html.LabelFor(m => item.Author)
@Html.DisplayFor(m => item.Author)
<br />
@Html.LabelFor(m => item.Text)
<p>
@Html.DisplayFor(m => item.Text)
</p>
<br />
@Html.LabelFor(m => item.Date)
@Html.DisplayFor(m => item.Date.ToLocalTime().GetDateTimeFormats()[1])
<br />
@if (this.User.Identity.IsAuthenticated)
{
@Html.ActionLink("Delete", "SermonDelete", "Admin", new { id = item.Id }, null)
<br />
@Html.ActionLink("Edit", "SermonEdit", "Admin", new { id = item.Id }, null)
}
</div>
<p>-----------------------------------------</p>
}
}
else
{
<h3>There is no sermons!</h3>
}
| mit | C# |
1a0d2f5a6028fbf0d1da718d7e4f61c52091e463 | fix draft url | boyarincev/boyarincev.net,boyarincev/boyarincev.net | Snow/themes/snowbyte/drafts.cshtml | Snow/themes/snowbyte/drafts.cshtml | @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Snow.ViewModels.ContentViewModel>
@using System.Collections.Generic
@{
Layout = "default.cshtml";
}
<header>
<div class="head-inner">
<h1>Drafts</h1>
</div>
</header>
<ul class="category-list fancy-container darkishblue">
@foreach(var draft in Model.Drafts){
<li><a href="/drafts/@draft.Url" title="@draft.Title">@draft.Title</a></li>
}
</ul>
| @inherits Nancy.ViewEngines.Razor.NancyRazorViewBase<Snow.ViewModels.ContentViewModel>
@using System.Collections.Generic
@{
Layout = "default.cshtml";
}
<header>
<div class="head-inner">
<h1>Drafts</h1>
</div>
</header>
<ul class="category-list fancy-container darkishblue">
@foreach(var draft in Model.Drafts){
<li><a href="/drafts@draft.Url" title="@draft.Title">@draft.Title</a></li>
}
</ul>
| mit | C# |
9b8865836e2064875caa24063d3654c8e275c897 | add PathMatch configuration | dotnetcore/CAP,dotnetcore/CAP,dotnetcore/CAP,ouraspnet/cap | src/DotNetCore.CAP/Dashboard/CAP.DashboardOptions.cs | src/DotNetCore.CAP/Dashboard/CAP.DashboardOptions.cs | using System;
using System.Collections.Generic;
using System.Text;
using DotNetCore.CAP.Dashboard;
namespace DotNetCore.CAP
{
public class DashboardOptions
{
public DashboardOptions()
{
AppPath = "/";
PathMatch = "/cap";
Authorization = new[] { new LocalRequestsOnlyAuthorizationFilter() };
StatsPollingInterval = 2000;
}
/// <summary>
/// The path for the Back To Site link. Set to <see langword="null" /> in order to hide the Back To Site link.
/// </summary>
public string AppPath { get; set; }
public string PathMatch { get; set; }
public IEnumerable<IDashboardAuthorizationFilter> Authorization { get; set; }
/// <summary>
/// The interval the /stats endpoint should be polled with.
/// </summary>
public int StatsPollingInterval { get; set; }
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using DotNetCore.CAP.Dashboard;
namespace DotNetCore.CAP
{
public class DashboardOptions
{
public DashboardOptions()
{
AppPath = "/";
Authorization = new[] { new LocalRequestsOnlyAuthorizationFilter() };
StatsPollingInterval = 2000;
}
/// <summary>
/// The path for the Back To Site link. Set to <see langword="null" /> in order to hide the Back To Site link.
/// </summary>
public string AppPath { get; set; }
public IEnumerable<IDashboardAuthorizationFilter> Authorization { get; set; }
/// <summary>
/// The interval the /stats endpoint should be polled with.
/// </summary>
public int StatsPollingInterval { get; set; }
}
}
| mit | C# |
e26023b3c31a82139dca1097612181f6c7eb21e8 | Fix Escape Tag for single quote in textboxes | mvbalaw/FluentWebControls | src/FluentWebControls/Extensions/StringExtensions.cs | src/FluentWebControls/Extensions/StringExtensions.cs | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using JetBrains.Annotations;
namespace FluentWebControls.Extensions
{
public static class StringExtensions
{
public static string CreateQuotedAttribute(this string value, string name)
{
return String.Format(" {0}='{1}'", name, EscapeForTagAttribute(value));
}
[CanBeNull]
public static string EmptyToNull([CanBeNull] this string str, bool trimFirst)
{
if (str == null)
{
return str;
}
string value = str;
if (trimFirst)
{
value = str.Trim();
}
return value.Length == 0 ? null : str;
}
[NotNull]
public static string EscapeForHtml(this string input)
{
if (input == null)
{
return "";
}
return HttpUtility.HtmlEncode(input);
}
public static string EscapeForTagAttribute(this string value)
{
return value == null ? "" : value.Replace("&", "&").Replace("\"", """).Replace("<", "<").Replace("\'", "'");
}
public static string EscapeForUrl(this string value)
{
if (value == null)
{
return "";
}
var parts = value.Split(' ');
string result = parts.Select(x => HttpUtility.UrlEncode(x)).Join("%20");
return result;
}
[NotNull]
public static ListSortDirection ToSortDirection([CanBeNull] this string sortDirection)
{
if (String.IsNullOrEmpty(sortDirection))
{
return ListSortDirection.Ascending;
}
switch (sortDirection.ToLower())
{
case "desc":
case "descending":
return ListSortDirection.Descending;
default:
return ListSortDirection.Ascending;
}
}
}
} | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Web;
using JetBrains.Annotations;
namespace FluentWebControls.Extensions
{
public static class StringExtensions
{
public static string CreateQuotedAttribute(this string value, string name)
{
return String.Format(" {0}='{1}'", name, EscapeForTagAttribute(value));
}
[CanBeNull]
public static string EmptyToNull([CanBeNull] this string str, bool trimFirst)
{
if (str == null)
{
return str;
}
string value = str;
if (trimFirst)
{
value = str.Trim();
}
return value.Length == 0 ? null : str;
}
[NotNull]
public static string EscapeForHtml(this string input)
{
if (input == null)
{
return "";
}
return HttpUtility.HtmlEncode(input);
}
public static string EscapeForTagAttribute(this string value)
{
var replacementString = value == null ? "" : value.Replace("&", "&").Replace("\"", """).Replace("<", "<").Replace("\'", "'");
return replacementString;
// return value == null ? "" : value.Replace("&", "&").Replace("\"", """).Replace("<", "<").Replace("\'", "'");
}
public static string EscapeForUrl(this string value)
{
if (value == null)
{
return "";
}
var parts = value.Split(' ');
string result = parts.Select(x => HttpUtility.UrlEncode(x)).Join("%20");
return result;
}
[NotNull]
public static ListSortDirection ToSortDirection([CanBeNull] this string sortDirection)
{
if (String.IsNullOrEmpty(sortDirection))
{
return ListSortDirection.Ascending;
}
switch (sortDirection.ToLower())
{
case "desc":
case "descending":
return ListSortDirection.Descending;
default:
return ListSortDirection.Ascending;
}
}
}
} | mit | C# |
ea1afb896fd97485c590e3bb59a245a1f7eebe9c | remove now unused member | dkackman/DynamicRestProxy,jamesholcomb/DynamicRestProxy,jamesholcomb/DynamicRestProxy,dkackman/DynamicRestProxy | UnitTestHelpers/CredentialStore.cs | UnitTestHelpers/CredentialStore.cs | using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace UnitTestHelpers
{
/// <summary>
/// This is a quick and dirty way to store service credentials in a place
/// that is easy to acces but stored outside of the source tree so that they
/// do not get checked into github
/// </summary>
public static class CredentialStore
{
private static string _root = @"d:\temp\"; //set this to wherever is appropriate for your keys
public static bool ObjectExists(string name)
{
return File.Exists(_root + name);
}
public static dynamic RetrieveObject(string name)
{
Debug.Assert(File.Exists(_root + name));
try
{
using (var file = File.OpenRead(_root + name))
using (var reader = new StreamReader(file))
{
string json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());
}
}
catch (Exception e)
{
Debug.Assert(false, e.Message);
}
return null;
}
public static void StoreObject(string name, dynamic o)
{
using (var file = File.Open(_root + name, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(file))
{
string json = JsonConvert.SerializeObject(o);
writer.Write(json);
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
namespace UnitTestHelpers
{
/// <summary>
/// This is a quick and dirty way to store service credentials in a place
/// that is easy to acces but stored outside of the source tree so that they
/// do not get checked into github
/// </summary>
public static class CredentialStore
{
//#error either load you key from a file outside of the source try like below or return it directly here
//#warning http://sunlightfoundation.com/api/accounts/register/
private static Dictionary<string, string> _keys = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
private static string _root = @"d:\temp\"; //set this to wherever is appropriate for your keys
public static bool ObjectExists(string name)
{
return File.Exists(_root + name);
}
public static dynamic RetrieveObject(string name)
{
Debug.Assert(File.Exists(_root + name));
try
{
using (var file = File.OpenRead(_root + name))
using (var reader = new StreamReader(file))
{
string json = reader.ReadToEnd();
return JsonConvert.DeserializeObject<ExpandoObject>(json, new ExpandoObjectConverter());
}
}
catch (Exception e)
{
Debug.Assert(false, e.Message);
}
return null;
}
public static void StoreObject(string name, dynamic o)
{
using (var file = File.Open(_root + name, FileMode.Create, FileAccess.Write, FileShare.None))
using (var writer = new StreamWriter(file))
{
string json = JsonConvert.SerializeObject(o);
writer.Write(json);
}
}
}
}
| apache-2.0 | C# |
c7a6f0668bb44170340d568b2a50f96170957a98 | Remove unused directives from benchmarking | nickbabcock/Pfim,nickbabcock/Pfim | src/Pfim.Benchmarks/DdsBenchmark.cs | src/Pfim.Benchmarks/DdsBenchmark.cs | using System.IO;
using BenchmarkDotNet.Attributes;
using FreeImageAPI;
using ImageMagick;
using DS = DevILSharp;
namespace Pfim.Benchmarks
{
public class DdsBenchmark
{
[Params("dxt1-simple.dds", "dxt3-simple.dds", "dxt5-simple.dds", "32-bit-uncompressed.dds")]
public string Payload { get; set; }
private byte[] data;
[GlobalSetup]
public void SetupData()
{
data = File.ReadAllBytes(Payload);
DS.Bootstrap.Init();
}
[Benchmark]
public IImage Pfim() => Dds.Create(new MemoryStream(data));
[Benchmark]
public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));
[Benchmark]
public int ImageMagick()
{
var settings = new MagickReadSettings { Format = MagickFormat.Dds };
using (var image = new MagickImage(new MemoryStream(data), settings))
{
return image.Width;
}
}
[Benchmark]
public int DevILSharp()
{
using (var image = DS.Image.Load(data, DS.ImageType.Dds))
{
return image.Width;
}
}
}
}
| using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BenchmarkDotNet.Attributes;
using FreeImageAPI;
using ImageMagick;
using DS = DevILSharp;
namespace Pfim.Benchmarks
{
public class DdsBenchmark
{
[Params("dxt1-simple.dds", "dxt3-simple.dds", "dxt5-simple.dds", "32-bit-uncompressed.dds")]
public string Payload { get; set; }
private byte[] data;
[GlobalSetup]
public void SetupData()
{
data = File.ReadAllBytes(Payload);
DS.Bootstrap.Init();
}
[Benchmark]
public IImage Pfim() => Dds.Create(new MemoryStream(data));
[Benchmark]
public FreeImageBitmap FreeImage() => FreeImageAPI.FreeImageBitmap.FromStream(new MemoryStream(data));
[Benchmark]
public int ImageMagick()
{
var settings = new MagickReadSettings { Format = MagickFormat.Dds };
using (var image = new MagickImage(new MemoryStream(data), settings))
{
return image.Width;
}
}
[Benchmark]
public int DevILSharp()
{
using (var image = DS.Image.Load(data, DS.ImageType.Dds))
{
return image.Width;
}
}
}
}
| mit | C# |
6856f535b9b518ea57bde33d3235839f8b82cdc0 | Update MvxFormsTouchPagePresenter.cs | Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins,Ideine/Cheesebaron.MvxPlugins,Cheesebaron/Cheesebaron.MvxPlugins | FormsPresenters/Touch/MvxFormsTouchPagePresenter.cs | FormsPresenters/Touch/MvxFormsTouchPagePresenter.cs | // MvxFormsTouchPagePresenter.cs
// 2015 (c) Copyright Cheesebaron. http://ostebaronen.dk
// Cheesebaron.MvxPlugins.FormsPresenters is licensed using Microsoft Public License (Ms-PL)
// Contributions and inspirations noted in readme.md and license.txt
//
// Project Lead - Tomasz Cielecki, @cheesebaron, mvxplugins@ostebaronen.dk
using System.Threading.Tasks;
using Cheesebaron.MvxPlugins.FormsPresenters.Core;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Touch.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using UIKit;
using Xamarin.Forms;
namespace Cheesebaron.MvxPlugins.FormsPresenters.Touch
{
public class MvxFormsTouchPagePresenter
: MvxFormsPagePresenter
, IMvxTouchViewPresenter
{
private readonly UIWindow _window;
public MvxFormsTouchPagePresenter(UIWindow window, Application mvxFormsApp)
: base(mvxFormsApp)
{
_window = window;
}
public virtual bool PresentModalViewController(UIViewController controller, bool animated)
{
return false;
}
public virtual void NativeModalViewControllerDisappearedOnItsOwn()
{
}
protected override void CustomPlatformInitialization(NavigationPage mainPage)
{
_window.RootViewController = mainPage.CreateViewController();
}
}
}
| using System.Threading.Tasks;
using Cheesebaron.MvxPlugins.FormsPresenters.Core;
using Cirrious.CrossCore;
using Cirrious.MvvmCross.Touch.Views.Presenters;
using Cirrious.MvvmCross.ViewModels;
using UIKit;
using Xamarin.Forms;
namespace Cheesebaron.MvxPlugins.FormsPresenters.Touch
{
public class MvxFormsTouchPagePresenter
: MvxFormsPagePresenter
, IMvxTouchViewPresenter
{
private readonly UIWindow _window;
public MvxFormsTouchPagePresenter(UIWindow window, Application mvxFormsApp)
: base(mvxFormsApp)
{
_window = window;
}
public virtual bool PresentModalViewController(UIViewController controller, bool animated)
{
return false;
}
public virtual void NativeModalViewControllerDisappearedOnItsOwn()
{
}
protected override void CustomPlatformInitialization(NavigationPage mainPage)
{
_window.RootViewController = mainPage.CreateViewController();
}
}
} | apache-2.0 | C# |
f61ede421e3b67b3bbf82da5fbb7749328e7f862 | Enable yaclops internal commands by default | dswisher/yaclops | src/Yaclops/GlobalParserSettings.cs | src/Yaclops/GlobalParserSettings.cs | using System.Collections.Generic;
namespace Yaclops
{
/// <summary>
/// Settings that alter the default behavior of the parser, but do not depend on the command type.
/// </summary>
public class GlobalParserSettings
{
/// <summary>
/// Constructor
/// </summary>
public GlobalParserSettings()
{
HelpVerb = "help";
HelpFlags = new[] { "-h", "--help", "-?" };
EnableYaclopsCommands = true;
}
/// <summary>
/// The verb that indicates help is desired. Defaults to "help".
/// </summary>
public string HelpVerb { get; set; }
/// <summary>
/// List of strings that indicate help is desired. Defaults to -h, -? and --help.
/// </summary>
public IEnumerable<string> HelpFlags { get; set; }
/// <summary>
/// Enable (hidden) internal Yaclops command used for debugging.
/// </summary>
public bool EnableYaclopsCommands { get; set; }
}
}
| using System.Collections.Generic;
namespace Yaclops
{
/// <summary>
/// Settings that alter the default behavior of the parser, but do not depend on the command type.
/// </summary>
public class GlobalParserSettings
{
/// <summary>
/// Constructor
/// </summary>
public GlobalParserSettings()
{
HelpVerb = "help";
HelpFlags = new[] { "-h", "--help", "-?" };
}
/// <summary>
/// The verb that indicates help is desired. Defaults to "help".
/// </summary>
public string HelpVerb { get; set; }
/// <summary>
/// List of strings that indicate help is desired. Defaults to -h, -? and --help.
/// </summary>
public IEnumerable<string> HelpFlags { get; set; }
/// <summary>
/// Enable (hidden) internal Yaclops command used for debugging.
/// </summary>
public bool EnableYaclopsCommands { get; set; }
}
}
| mit | C# |
69a6eccaf1b228b1bd9e38d6f24573bb63727aea | Fix tag | matthewrdev/monodevelop-addin-packager,matthew-ch-robbins/monodevelop-addin-packager | MonoDevelopAddinPackager/Properties/AssemblyInfo.cs | MonoDevelopAddinPackager/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("MonoDevelopAddinPackager")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("matthewcrobbins")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("2.1.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle ("MonoDevelopAddinPackager")]
[assembly: AssemblyDescription ("")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("")]
[assembly: AssemblyProduct ("")]
[assembly: AssemblyCopyright ("matthewcrobbins")]
[assembly: AssemblyTrademark ("")]
[assembly: AssemblyCulture ("")]
[assembly: AssemblyDescription("Tooling to assist the development of MonoDevelop addins.\n\nCurrent features:\n\n - 'Package Addin' to pack a MonoDevelop Addin project into an .mpack.\n - 'Create Addin Web Index (.mrep)' to build web index .mrep files for the addin.\n - 'Clean Addin Packages' to delete all generated package files for the active project and configuration.")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion ("2.1.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| mit | C# |
d2b3d8694f1e9da6e5816eaeb0fdf6feba6b4ad4 | 添加 Numeric 数据类型 | Sandwych/slipstream,Sandwych/slipstream,Sandwych/slipstream,Sandwych/slipstream | ObjectServer/ObjectServer/Model/Fields/FieldType.cs | ObjectServer/ObjectServer/Model/Fields/FieldType.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ObjectServer.Model
{
public enum FieldType
{
Integer,
BigInteger,
Float,
DateTime,
Boolean,
Decimal,
Money,
Chars,
Text,
Binary,
Enumeration,
Reference,
Property,
OneToMany,
ManyToOne,
ManyToMany,
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ObjectServer.Model
{
public enum FieldType
{
Integer,
BigInteger,
Float,
DateTime,
Boolean,
Money,
Chars,
Text,
Binary,
Enumeration,
Reference,
Property,
OneToMany,
ManyToOne,
ManyToMany,
}
}
| agpl-3.0 | C# |
e7e59719ac4e441e90a9af11f2f57f519c2a4553 | Fix error | TrickWaterArts/ProjectMinotaur | ProjectMinotaur/Assets/Script/Entity/Enemy/Enemy.cs | ProjectMinotaur/Assets/Script/Entity/Enemy/Enemy.cs | using UnityEngine;
public class Enemy : IHealthHaver {
public int damageAmt = 10;
public float timeBetweenDamage = 1.0f;
private float timeSinceLastDamage = 0.0f;
public void OnCollisionStay(Collision collision) {
if (timeSinceLastDamage >= timeBetweenDamage) {
collision.collider.SendMessage("Damage", new object[] { (byte) damageAmt, EntityDamageOrigin.ENEMY_DAMAGE, this });
timeSinceLastDamage = 0.0f;
}
}
void Update() {
if (timeSinceLastDamage < timeBetweenDamage * 2) {
timeSinceLastDamage += Time.deltaTime;
}
}
} | using UnityEngine;
public class Enemy : IHealthHaver {
public int damageAmt = 10;
public float timeBetweenDamage = 1.0f;
private float timeSinceLastDamage = 0.0f;
public void OnCollisionStay(Collision collision) {
if (timeSinceLastDamage >= timeBetweenDamage) {
if () {
}
collision.collider.SendMessage("Damage", new object[] { (byte) damageAmt, EntityDamageOrigin.ENEMY_DAMAGE, this });
timeSinceLastDamage = 0.0f;
}
}
void Update() {
if (timeSinceLastDamage < timeBetweenDamage * 2) {
timeSinceLastDamage += Time.deltaTime;
}
}
} | apache-2.0 | C# |
b3cfeb17fd38cd06026f5271c340fa5b87ff8b4a | Update VisualNovel.cs | Nikey646/VndbSharp | VndbSharp/Models/VisualNovel/VisualNovel.cs | VndbSharp/Models/VisualNovel/VisualNovel.cs | using System;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using VndbSharp.Attributes;
using VndbSharp.Models.Common;
namespace VndbSharp.Models.VisualNovel
{
public class VisualNovel
{
private VisualNovel() { }
public UInt32 Id { get; private set; }
[JsonProperty("title")]
public String Name { get; private set; }
[JsonProperty("original")]
public String OriginalName { get; private set; }
public SimpleDate Released { get; private set; } // Release or Released?
public ReadOnlyCollection<String> Languages { get; private set; }
[JsonProperty("orig_lang")]
public ReadOnlyCollection<String> OriginalLanguages { get; private set; }
public ReadOnlyCollection<String> Platforms { get; private set; }
[IsCsv]
public ReadOnlyCollection<String> Aliases { get; private set; }
public VisualNovelLength? Length { get; private set; }
public String Description { get; private set; }
[JsonProperty("links")]
public VisualNovelLinks VisualNovelLinks { get; private set; }
public String Image { get; private set; }
[JsonProperty("image_nsfw")]
public Boolean IsImageNsfw { get; private set; }
public AnimeMetadata[] Anime { get; private set; }
public VisualNovelRelation[] Relations { get; private set; }
public TagMetadata[] Tags { get; private set; }
public Single Popularity { get; private set; }
public UInt32 Rating { get; private set; }
[JsonProperty("screens")]
public ScreenshotMetadata[] Screenshots { get; private set; }
}
}
| using System;
using System.Collections.ObjectModel;
using Newtonsoft.Json;
using VndbSharp.Attributes;
using VndbSharp.Models.Common;
namespace VndbSharp.Models.VisualNovel
{
public class VisualNovel
{
private VisualNovel() { }
public UInt32 Id { get; private set; }
[JsonProperty("title")]
public String Name { get; private set; }
[JsonProperty("original")]
public String OriginalName { get; private set; }
public SimpleDate Released { get; private set; } // Release or Released?
public ReadOnlyCollection<String> Languages { get; private set; }
[JsonProperty("orig_lang")]
public ReadOnlyCollection<String> OriginalLanguages { get; private set; }
public ReadOnlyCollection<String> Platforms { get; private set; }
[IsCsv]
public ReadOnlyCollection<String> Aliases { get; private set; }
public VisualNovelLength? Length { get; private set; }
public String Description { get; private set; }
public VisualNovelLinks VisualNovelLinks { get; private set; }
public String Image { get; private set; }
[JsonProperty("image_nsfw")]
public Boolean IsImageNsfw { get; private set; }
public AnimeMetadata[] Anime { get; private set; }
public VisualNovelRelation[] Relations { get; private set; }
public TagMetadata[] Tags { get; private set; }
public Single Popularity { get; private set; }
public UInt32 Rating { get; private set; }
[JsonProperty("screens")]
public ScreenshotMetadata[] Screenshots { get; private set; }
}
}
| mit | C# |
f200c7d9189e2278bb142e1224aba8f82ef209d4 | Add nullcheck | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/JsonConverters/Uint256JsonConverter.cs | WalletWasabi/JsonConverters/Uint256JsonConverter.cs | using NBitcoin;
using Newtonsoft.Json;
using System;
using WalletWasabi.Helpers;
namespace WalletWasabi.JsonConverters
{
public class Uint256JsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(uint256);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = Guard.Correct((string)reader.Value);
return string.IsNullOrWhiteSpace(value) ? default : new uint256(value);
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((uint256)value)?.ToString());
}
}
}
| using NBitcoin;
using Newtonsoft.Json;
using System;
using WalletWasabi.Helpers;
namespace WalletWasabi.JsonConverters
{
public class Uint256JsonConverter : JsonConverter
{
/// <inheritdoc />
public override bool CanConvert(Type objectType)
{
return objectType == typeof(uint256);
}
/// <inheritdoc />
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var value = Guard.Correct((string)reader.Value);
return string.IsNullOrWhiteSpace(value) ? default : new uint256(value);
}
/// <inheritdoc />
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((uint256)value).ToString());
}
}
}
| mit | C# |
73c3e3f0c739483282c86d7eba52a34cff4186c7 | Add user interface Russian support | xavierfoucrier/gmail-notifier,xavierfoucrier/gmail-notifier | code/Program.cs | code/Program.cs | using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using notifier.Languages;
using notifier.Properties;
namespace notifier {
static class Program {
#region #attributes
/// <summary>
/// Mutex associated to the application instance
/// </summary>
static Mutex Mutex = new Mutex(true, "inboxnotifier-115e363ecbfefd771e55c6874680bc0a");
#endregion
#region #methods
[STAThread]
static void Main(string[] args) {
// initialize the configuration file with setup installer settings
if (args.Length == 3 && args[0] == "install") {
// language application setting
switch (args[1]) {
default:
Settings.Default.Language = "English";
break;
case "fr":
Settings.Default.Language = "Français";
break;
case "de":
Settings.Default.Language = "Deutsch";
break;
}
// start with Windows setting
Settings.Default.RunAtWindowsStartup = args[2] == "auto";
// commit changes to the configuration file
Settings.Default.Save();
return;
}
// initialize the interface with the specified culture, depending on the user settings
switch (Settings.Default.Language) {
default:
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
break;
case "Français":
CultureInfo.CurrentUICulture = new CultureInfo("fr-FR");
break;
case "Deutsch":
CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
break;
case "Русский":
CultureInfo.CurrentUICulture = new CultureInfo("ru-RU");
break;
}
// check if there is an instance running
if (!Mutex.WaitOne(TimeSpan.Zero, true)) {
MessageBox.Show(Translation.mutexError, Translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// set some default properties
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// set the process priority to "low"
Process process = Process.GetCurrentProcess();
process.PriorityClass = ProcessPriorityClass.BelowNormal;
// run the main window
Application.Run(new Main());
// release the mutex instance
Mutex.ReleaseMutex();
}
#endregion
#region #accessors
#endregion
}
} | using System;
using System.Diagnostics;
using System.Globalization;
using System.Threading;
using System.Windows.Forms;
using notifier.Languages;
using notifier.Properties;
namespace notifier {
static class Program {
#region #attributes
/// <summary>
/// Mutex associated to the application instance
/// </summary>
static Mutex Mutex = new Mutex(true, "inboxnotifier-115e363ecbfefd771e55c6874680bc0a");
#endregion
#region #methods
[STAThread]
static void Main(string[] args) {
// initialize the configuration file with setup installer settings
if (args.Length == 3 && args[0] == "install") {
// language application setting
switch (args[1]) {
default:
Settings.Default.Language = "English";
break;
case "fr":
Settings.Default.Language = "Français";
break;
case "de":
Settings.Default.Language = "Deutsch";
break;
}
// start with Windows setting
Settings.Default.RunAtWindowsStartup = args[2] == "auto";
// commit changes to the configuration file
Settings.Default.Save();
return;
}
// initialize the interface with the specified culture, depending on the user settings
switch (Settings.Default.Language) {
default:
CultureInfo.CurrentUICulture = new CultureInfo("en-US");
break;
case "Français":
CultureInfo.CurrentUICulture = new CultureInfo("fr-FR");
break;
case "Deutsch":
CultureInfo.CurrentUICulture = new CultureInfo("de-DE");
break;
}
// check if there is an instance running
if (!Mutex.WaitOne(TimeSpan.Zero, true)) {
MessageBox.Show(Translation.mutexError, Translation.multipleInstances, MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
// set some default properties
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
// set the process priority to "low"
Process process = Process.GetCurrentProcess();
process.PriorityClass = ProcessPriorityClass.BelowNormal;
// run the main window
Application.Run(new Main());
// release the mutex instance
Mutex.ReleaseMutex();
}
#endregion
#region #accessors
#endregion
}
} | mit | C# |
769fde1602bb590d04aff75def166cece69212f4 | Make EventProcesses not crash recompile | LDodson/HappyFunTimes,LDodson/HappyFunTimes,greggman/HappyFunTimes,greggman/HappyFunTimes | Unity3D/src/EventProcessor.cs | Unity3D/src/EventProcessor.cs | /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using UnityEngine;
using System;
using System.Collections.Generic;
namespace HappyFunTimes {
// This is needed to send the events to on the correct thread.
public class EventProcessor : MonoBehaviour {
public void QueueEvent(Action action) {
lock(m_queueLock) {
m_queuedEvents.Add(action);
}
}
void Start() {
m_queuedEvents = new List<Action>();
m_executingEvents = new List<Action>();
}
void Update() {
MoveQueuedEventsToExecuting();
if (m_executingEvents != null) {
while (m_executingEvents.Count > 0) {
Action e = m_executingEvents[0];
m_executingEvents.RemoveAt(0);
e();
}
}
}
private void MoveQueuedEventsToExecuting() {
lock(m_queueLock) {
if (m_executingEvents != null) {
while (m_queuedEvents.Count > 0) {
Action e = m_queuedEvents[0];
m_executingEvents.Add(e);
m_queuedEvents.RemoveAt(0);
}
}
}
}
private System.Object m_queueLock = new System.Object();
private List<Action> m_queuedEvents;
private List<Action> m_executingEvents;
}
} // namespace HappyFunTimes
| /*
* Copyright 2014, Gregg Tavares.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Gregg Tavares. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
using UnityEngine;
using System;
using System.Collections.Generic;
namespace HappyFunTimes {
// This is needed to send the events to on the correct thread.
public class EventProcessor : MonoBehaviour {
public void QueueEvent(Action action) {
lock(m_queueLock) {
m_queuedEvents.Add(action);
}
}
void Start() {
m_queuedEvents = new List<Action>();
m_executingEvents = new List<Action>();
}
void Update() {
MoveQueuedEventsToExecuting();
while (m_executingEvents.Count > 0) {
Action e = m_executingEvents[0];
m_executingEvents.RemoveAt(0);
e();
}
}
private void MoveQueuedEventsToExecuting() {
lock(m_queueLock) {
while (m_queuedEvents.Count > 0) {
Action e = m_queuedEvents[0];
m_executingEvents.Add(e);
m_queuedEvents.RemoveAt(0);
}
}
}
private System.Object m_queueLock = new System.Object();
private List<Action> m_queuedEvents;
private List<Action> m_executingEvents;
}
} // namespace HappyFunTimes
| bsd-3-clause | C# |
87262f9de5958fc322785a08c69b91690d1777bf | fix typo in FixAllSingleDocumentVaried case | stephentoub/roslyn,physhi/roslyn,gafter/roslyn,eriawan/roslyn,aelij/roslyn,weltkante/roslyn,AmadeusW/roslyn,gafter/roslyn,sharwell/roslyn,physhi/roslyn,mavasani/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,physhi/roslyn,mavasani/roslyn,shyamnamboodiripad/roslyn,jasonmalinowski/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,sharwell/roslyn,shyamnamboodiripad/roslyn,genlu/roslyn,KevinRansom/roslyn,heejaechang/roslyn,brettfo/roslyn,brettfo/roslyn,tannergooding/roslyn,AmadeusW/roslyn,CyrusNajmabadi/roslyn,tannergooding/roslyn,bartdesmet/roslyn,diryboy/roslyn,diryboy/roslyn,aelij/roslyn,jmarolf/roslyn,ErikSchierboom/roslyn,AlekseyTs/roslyn,mavasani/roslyn,eriawan/roslyn,weltkante/roslyn,jasonmalinowski/roslyn,bartdesmet/roslyn,panopticoncentral/roslyn,tmat/roslyn,ErikSchierboom/roslyn,bartdesmet/roslyn,mgoertz-msft/roslyn,CyrusNajmabadi/roslyn,wvdd007/roslyn,jasonmalinowski/roslyn,heejaechang/roslyn,AmadeusW/roslyn,dotnet/roslyn,stephentoub/roslyn,dotnet/roslyn,tannergooding/roslyn,jmarolf/roslyn,dotnet/roslyn,wvdd007/roslyn,stephentoub/roslyn,eriawan/roslyn,panopticoncentral/roslyn,jmarolf/roslyn,wvdd007/roslyn,AlekseyTs/roslyn,tmat/roslyn,AlekseyTs/roslyn,ErikSchierboom/roslyn,mgoertz-msft/roslyn,heejaechang/roslyn,panopticoncentral/roslyn,brettfo/roslyn,gafter/roslyn,KevinRansom/roslyn,KevinRansom/roslyn,KirillOsenkov/roslyn,mgoertz-msft/roslyn,aelij/roslyn,KirillOsenkov/roslyn,diryboy/roslyn,genlu/roslyn,genlu/roslyn,weltkante/roslyn,KirillOsenkov/roslyn | src/Analyzers/CSharp/Tests/ConvertNameOf/ConvertNameOfFixAllTests.cs | src/Analyzers/CSharp/Tests/ConvertNameOf/ConvertNameOfFixAllTests.cs | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.ConvertTypeofToNameof;
using Microsoft.CodeAnalysis.CSharp.CSharpConvertNameOfCodeFixProvider;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNameOf
{
public partial class ConvertNameOfTests
{
[Fact]
[Trait(Traits.Feature, Traits.Features.ConvertNameOf)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSingleDocumentSimple()
{
var input = @"class Test
{
static void Main()
{
var typeName1 = {|FixAllInDocument:typeof(Test).Name|};
var typeName2 = typeof(Test).Name;
var typeName3 = typeof(Test).Name;
}
}
";
var expected = @"class Test
{
static void Main()
{
var typeName1 = nameof(Test);
var typeName2 = nameof(Test);
var typeName3 = nameof(Test);
}
}
";
await TestInRegularAndScriptAsync(input, expected);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ConvertNameOf)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSingleDocumentVaried()
{
var input = @"class Test
{
static void Main()
{
var typeName1 = {|FixAllInDocument:typeof(Test).Name|};
var typeName2 = typeof(int).Name;
var typeName3 = typeof(System.String).Name;
}
}
";
var expected = @"class Test
{
static void Main()
{
var typeName1 = nameof(Test);
var typeName2 = nameof(System.Int32);
var typeName3 = nameof(System.String);
}
}
";
await TestInRegularAndScriptAsync(input, expected);
}
}
}
| // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.ConvertTypeofToNameof;
using Microsoft.CodeAnalysis.CSharp.CSharpConvertNameOfCodeFixProvider;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics;
using Microsoft.CodeAnalysis.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ConvertNameOf
{
public partial class ConvertNameOfTests
{
[Fact]
[Trait(Traits.Feature, Traits.Features.ConvertNameOf)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSingleDocumentSimple()
{
var input = @"class Test
{
static void Main()
{
var typeName1 = {|FixAllInDocument:typeof(Test).Name|};
var typeName2 = typeof(Test).Name;
var typeName3 = typeof(Test).Name;
}
}
";
var expected = @"class Test
{
static void Main()
{
var typeName1 = nameof(Test);
var typeName2 = nameof(Test);
var typeName3 = nameof(Test);
}
}
";
await TestInRegularAndScriptAsync(input, expected);
}
[Fact]
[Trait(Traits.Feature, Traits.Features.ConvertNameOf)]
[Trait(Traits.Feature, Traits.Features.CodeActionsFixAllOccurrences)]
public async Task TestFixAllInSingleDocumentVaried()
{
var input = @"class Test
{
static void Main()
{
var typeName1 = {|FixAllInDocument:typeof(Test).Name|};
var typeName2 = typeof(int).Name;
var typeName3 = typeof(System.String).Name;
}
}
";
var expected = @"class Program1
{
static void Main()
{
var typeName1 = nameof(Test);
var typeName2 = nameof(System.Int32);
var typeName3 = nameof(System.String);
}
}
";
await TestInRegularAndScriptAsync(input, expected);
}
}
}
| mit | C# |
3439480e38d0d0ad97b4be5bc7924de17ee7461c | Update ApprenticeshipBase.cs | SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments,SkillsFundingAgency/das-commitments | src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/ApprenticeshipBase.cs | src/CommitmentsV2/SFA.DAS.CommitmentsV2/Models/ApprenticeshipBase.cs | using System;
using System.Collections.Generic;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Models
{
public abstract class ApprenticeshipBase : Aggregate
{
protected ApprenticeshipBase()
{
ApprenticeshipUpdate = new List<ApprenticeshipUpdate>();
}
public bool IsApproved { get; set; }
public virtual long Id { get; set; }
public virtual long CommitmentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Uln { get; set; }
public ProgrammeType? ProgrammeType { get; set; }
public string CourseCode { get; set; }
public string CourseName { get; set; }
public string TrainingCourseVersion { get; set; }
public bool TrainingCourseVersionConfirmed { get; set; }
public string TrainingCourseOption { get; set; }
public string StandardUId { get; set; }
public decimal? Cost { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public DateTime? DateOfBirth { get; set; }
public string NiNumber { get; set; }
public string EmployerRef { get; set; }
public string ProviderRef { get; set; }
public DateTime? CreatedOn { get; set; }
public DateTime? AgreedOn { get; set; }
public string EpaOrgId { get; set; }
public long? CloneOf { get; set; }
public bool IsProviderSearch { get; set; }
public Guid? ReservationId { get; set; }
public long? ContinuationOfId { get; set; }
public DateTime? OriginalStartDate { get; set; }
public virtual Cohort Cohort { get; set; }
public virtual AssessmentOrganisation EpaOrg { get; set; }
public ApprenticeshipStatus ApprenticeshipStatus { get; set; }
public virtual ICollection<ApprenticeshipUpdate> ApprenticeshipUpdate { get; set; }
public bool IsContinuation => ContinuationOfId.HasValue;
public virtual Apprenticeship PreviousApprenticeship { get; set; }
}
}
| using System;
using System.Collections.Generic;
using SFA.DAS.CommitmentsV2.Types;
namespace SFA.DAS.CommitmentsV2.Models
{
public abstract class ApprenticeshipBase : Aggregate
{
public ApprenticeshipBase()
{
ApprenticeshipUpdate = new List<ApprenticeshipUpdate>();
}
public bool IsApproved { get; set; }
public virtual long Id { get; set; }
public virtual long CommitmentId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Uln { get; set; }
public ProgrammeType? ProgrammeType { get; set; }
public string CourseCode { get; set; }
public string CourseName { get; set; }
public string TrainingCourseVersion { get; set; }
public bool TrainingCourseVersionConfirmed { get; set; }
public string TrainingCourseOption { get; set; }
public string StandardUId { get; set; }
public decimal? Cost { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public PaymentStatus PaymentStatus { get; set; }
public DateTime? DateOfBirth { get; set; }
public string NiNumber { get; set; }
public string EmployerRef { get; set; }
public string ProviderRef { get; set; }
public DateTime? CreatedOn { get; set; }
public DateTime? AgreedOn { get; set; }
public string EpaOrgId { get; set; }
public long? CloneOf { get; set; }
public bool IsProviderSearch { get; set; }
public Guid? ReservationId { get; set; }
public long? ContinuationOfId { get; set; }
public DateTime? OriginalStartDate { get; set; }
public virtual Cohort Cohort { get; set; }
public virtual AssessmentOrganisation EpaOrg { get; set; }
public ApprenticeshipStatus ApprenticeshipStatus { get; set; }
public virtual ICollection<ApprenticeshipUpdate> ApprenticeshipUpdate { get; set; }
public bool IsContinuation => ContinuationOfId.HasValue;
public virtual Apprenticeship PreviousApprenticeship { get; set; }
}
}
| mit | C# |
8c16226dfce3fd3fe7ffca040720079e98088098 | Update PlayerController.cs | itsMilkid/Alien-Jump | Assets/Scripts/PlayerController.cs | Assets/Scripts/PlayerController.cs | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour {
[Header("Jump Force:")]
public float thresholdX = 5.5f;
public float thresholdY = 10.0f;
[Header("UI - POWERBAR:")]
public Slider powerBar;
[Header("LayerMaks Platforms:")]
public LayerMask platformLayer;
[Header("Groundcheck Raycast Position:")]
public Transform leftRay;
public Transform rightRay;
private Rigidbody2D rb2d;
private Animator anim;
private float forceX, forceY;
private bool setPower;
public bool isGrounded;
private float powerBarValue = 0.0f;
private void Awake(){
rb2d = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
powerBar.minValue = 0.0f;
powerBar.maxValue = thresholdY;
powerBar.value = powerBarValue;
}
private void Update(){
CheckForInput ();
SetJumpStrength ();
PlayAnimation ();
GroundCheck ();
}
private void CheckForInput(){
if (Input.GetMouseButtonDown (0)) {
if (isGrounded == true) {
SettingPower (true);
}
}
if (Input.GetMouseButtonUp (0)) {
if (isGrounded == true) {
SettingPower (false);
}
}
}
private void SettingPower(bool _setting){
setPower = _setting;
if (setPower == false) {
Jump ();
}
}
private void SetJumpStrength(){
if (setPower == true) {
forceX += thresholdX * Time.deltaTime;
forceY += thresholdY * Time.deltaTime;
if (forceX > 30.0f) {
forceX = 30.0f;
}
if (forceY > 50.0f) {
forceY = 50.0f;
}
powerBarValue = forceX;
powerBar.value = powerBarValue;
}
}
private void Jump(){
rb2d.velocity = new Vector2 (forceX, forceY);
forceX = 0;
forceY = 0;
anim.SetBool ("isJumping", true);
powerBarValue = 0.0f;
powerBar.value = powerBarValue;
}
private void PlayAnimation(){
if (isGrounded == true) {
anim.SetBool ("isJumping", false);
} else {
anim.SetBool ("isJumping", true);
}
}
private void GroundCheck(){
Debug.DrawRay (leftRay.position, Vector2.down * 10 , Color.red);
Debug.DrawRay (rightRay.position, Vector2.down * 10 , Color.red);
if (Physics2D.Raycast (leftRay.position, Vector2.down, 5, platformLayer) || Physics2D.Raycast (rightRay.position, Vector2.down, 5, platformLayer)) {
Debug.Log ("Grounded");
isGrounded = true;
} else {
isGrounded = false;
}
}
}
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[RequireComponent(typeof(Rigidbody2D))]
public class PlayerController : MonoBehaviour {
[Header("Jump Force:")]
public float thresholdX = 5.5f;
public float thresholdY = 10.0f;
[Header("UI - POWERBAR:")]
public Slider powerBar;
[Header("LayerMaks Platforms")]
public LayerMask platformLayer;
public Transform leftRay;
public Transform rightRay;
private Rigidbody2D rb2d;
private Animator anim;
private float forceX, forceY;
private bool setPower;
public bool isGrounded;
private float powerBarValue = 0.0f;
private void Awake(){
rb2d = GetComponent<Rigidbody2D> ();
anim = GetComponent<Animator> ();
powerBar.minValue = 0.0f;
powerBar.maxValue = thresholdY;
powerBar.value = powerBarValue;
}
private void Update(){
CheckForInput ();
SetJumpStrength ();
PlayAnimation ();
GroundCheck ();
}
private void CheckForInput(){
if (Input.GetMouseButtonDown (0)) {
if (isGrounded == true) {
SettingPower (true);
}
}
if (Input.GetMouseButtonUp (0)) {
if (isGrounded == true) {
SettingPower (false);
}
}
}
private void SettingPower(bool _setting){
setPower = _setting;
if (setPower == false) {
Jump ();
}
}
private void SetJumpStrength(){
if (setPower == true) {
forceX += thresholdX * Time.deltaTime;
forceY += thresholdY * Time.deltaTime;
if (forceX > 30.0f) {
forceX = 30.0f;
}
if (forceY > 50.0f) {
forceY = 50.0f;
}
powerBarValue = forceX;
powerBar.value = powerBarValue;
}
}
private void Jump(){
rb2d.velocity = new Vector2 (forceX, forceY);
forceX = 0;
forceY = 0;
anim.SetBool ("isJumping", true);
powerBarValue = 0.0f;
powerBar.value = powerBarValue;
}
private void PlayAnimation(){
if (isGrounded == true) {
anim.SetBool ("isJumping", false);
} else {
anim.SetBool ("isJumping", true);
}
}
private void GroundCheck(){
Debug.DrawRay (leftRay.position, Vector2.down * 10 , Color.red);
Debug.DrawRay (rightRay.position, Vector2.down * 10 , Color.red);
if (Physics2D.Raycast (leftRay.position, Vector2.down, 5, platformLayer) || Physics2D.Raycast (rightRay.position, Vector2.down, 5, platformLayer)) {
Debug.Log ("Grounded");
isGrounded = true;
} else {
isGrounded = false;
}
/*if (Physics2D.Raycast (rightRay.position, Vector2.down, 5, platformLayer)) {
Debug.Log ("Grounded");
isGrounded = true;
} else {
isGrounded = false;
}*/
}
}
| mit | C# |
bf63bbb916e47a52b8b2952d9650d2285af61246 | Implement AppHarborClient#GetApplications | appharbor/appharbor-cli | src/AppHarbor/AppHarborClient.cs | src/AppHarbor/AppHarborClient.cs | using System;
using System.Collections.Generic;
using AppHarbor.Model;
namespace AppHarbor
{
public class AppHarborClient : IAppHarborClient
{
private readonly AuthInfo _authInfo;
public AppHarborClient(string AccessToken)
{
_authInfo = new AuthInfo { AccessToken = AccessToken };
}
public CreateResult<string> CreateApplication(string name, string regionIdentifier = null)
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.CreateApplication(name, regionIdentifier);
}
public IEnumerable<Application> GetApplications()
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.GetApplications();
}
private AppHarborApi GetAppHarborApi()
{
try
{
return new AppHarborApi(_authInfo);
}
catch (ArgumentNullException)
{
throw new CommandException("You're not logged in. Log in with \"appharbor login\"");
}
}
public User GetUser()
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.GetUser();
}
}
}
| using System;
using System.Collections.Generic;
using AppHarbor.Model;
namespace AppHarbor
{
public class AppHarborClient : IAppHarborClient
{
private readonly AuthInfo _authInfo;
public AppHarborClient(string AccessToken)
{
_authInfo = new AuthInfo { AccessToken = AccessToken };
}
public CreateResult<string> CreateApplication(string name, string regionIdentifier = null)
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.CreateApplication(name, regionIdentifier);
}
public IEnumerable<Application> GetApplications()
{
throw new NotImplementedException();
}
private AppHarborApi GetAppHarborApi()
{
try
{
return new AppHarborApi(_authInfo);
}
catch (ArgumentNullException)
{
throw new CommandException("You're not logged in. Log in with \"appharbor login\"");
}
}
public User GetUser()
{
var appHarborApi = GetAppHarborApi();
return appHarborApi.GetUser();
}
}
}
| mit | C# |
4b91ed92ce1fe6b57a485436a2664c714438517e | build 7.1.16.0 | agileharbor/channelAdvisorAccess | src/Global/GlobalAssemblyInfo.cs | src/Global/GlobalAssemblyInfo.cs | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.16.0" ) ] | using System;
using System.Reflection;
using System.Runtime.InteropServices;
[ assembly : ComVisible( false ) ]
[ assembly : AssemblyProduct( "ChannelAdvisorAccess" ) ]
[ assembly : AssemblyCompany( "Agile Harbor, LLC" ) ]
[ assembly : AssemblyCopyright( "Copyright (C) Agile Harbor, LLC" ) ]
[ assembly : AssemblyDescription( "ChannelAdvisor webservices API wrapper." ) ]
[ assembly : AssemblyTrademark( "" ) ]
[ assembly : AssemblyCulture( "" ) ]
[ assembly : CLSCompliant( false ) ]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
// Keep in track with CA API version
[ assembly : AssemblyVersion( "7.1.15.0" ) ] | bsd-3-clause | C# |
2260067954c7eea0eea87630e14d3af4bf0cb136 | rename method due to conflict notification by VS | SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery,SoftwareFans/AstroPhotoGallery | AstroPhotoGallery/AstroPhotoGallery/Views/Shared/_LoginPartial.cshtml | AstroPhotoGallery/AstroPhotoGallery/Views/Shared/_LoginPartial.cshtml | @if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
@if (User.IsInRole("Admin"))
{
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Admin<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>@Html.ActionLink("Users", "Index", "User")</li>
<li>@Html.ActionLink("Categories", "Index", "Category")</li>
</ul>
</li>
}
<li>
@Html.ActionLink("Upload", "Upload", "Picture")
</li>
<li>
@Html.ActionLink("Hello " + User.Identity.Name + "!", "MyProfile", "Account", routeValues: null, htmlAttributes: new {title = "Manage"})
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
| @using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
{
@Html.AntiForgeryToken()
<ul class="nav navbar-nav navbar-right">
@if (User.IsInRole("Admin"))
{
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Admin<span class="caret"></span></a>
<ul class="dropdown-menu" role="menu">
<li>@Html.ActionLink("Users", "Index", "User")</li>
<li>@Html.ActionLink("Categories", "Index", "Category")</li>
</ul>
</li>
}
<li>
@Html.ActionLink("Upload", "Upload", "Picture")
</li>
<li>
@Html.ActionLink("Hello " + User.Identity.Name + "!", "Profile", "Account", routeValues: null, htmlAttributes: new {title = "Manage"})
</li>
<li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
</ul>
}
}
else
{
<ul class="nav navbar-nav navbar-right">
<li>@Html.ActionLink("Register", "Register", "Account", routeValues: null, htmlAttributes: new { id = "registerLink" })</li>
<li>@Html.ActionLink("Log in", "Login", "Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>
</ul>
}
| mit | C# |
e7f4eb9d5031f99ce723376bc918bfdcc1178ed6 | remove default params from call | etishor/Metrics.NET,DeonHeyns/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,alhardy/Metrics.NET,DeonHeyns/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,cvent/Metrics.NET,Recognos/Metrics.NET,alhardy/Metrics.NET,ntent-ad/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,Liwoj/Metrics.NET,MetaG8/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET,Liwoj/Metrics.NET,mnadel/Metrics.NET,MetaG8/Metrics.NET | Src/Adapters/Owin.Metrics/Middleware/TimerForEachRequestMiddleware.cs | Src/Adapters/Owin.Metrics/Middleware/TimerForEachRequestMiddleware.cs | using Metrics;
using Metrics.Utils;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Owin.Metrics.Middleware
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public class TimerForEachRequestMiddleware : MetricMiddleware
{
private const string RequestStartTimeKey = "__Metrics.RequestStartTime__";
private readonly MetricsContext context;
private AppFunc next;
public TimerForEachRequestMiddleware(MetricsContext context, Regex[] ignorePatterns)
: base(ignorePatterns)
{
this.context = context;
}
public void Initialize(AppFunc next)
{
this.next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
if (PerformMetric(environment))
{
environment[RequestStartTimeKey] = Clock.Default.Nanoseconds;
await next(environment);
var httpResponseStatusCode = int.Parse(environment["owin.ResponseStatusCode"].ToString());
var metricName = environment["owin.RequestPath"].ToString();
if (environment.ContainsKey("metrics-net.routetemplate"))
{
metricName = environment["metrics-net.routetemplate"] as string;
}
if (httpResponseStatusCode != (int)HttpStatusCode.NotFound)
{
var startTime = (long)environment[RequestStartTimeKey];
var elapsed = Clock.Default.Nanoseconds - startTime;
this.context.Timer(metricName, Unit.Requests)
.Record(elapsed, TimeUnit.Nanoseconds);
}
}
else
{
await next(environment);
}
}
}
}
| using Metrics;
using Metrics.Utils;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace Owin.Metrics.Middleware
{
using AppFunc = Func<IDictionary<string, object>, Task>;
public class TimerForEachRequestMiddleware : MetricMiddleware
{
private const string RequestStartTimeKey = "__Metrics.RequestStartTime__";
private readonly MetricsContext context;
private AppFunc next;
public TimerForEachRequestMiddleware(MetricsContext context, Regex[] ignorePatterns)
: base(ignorePatterns)
{
this.context = context;
}
public void Initialize(AppFunc next)
{
this.next = next;
}
public async Task Invoke(IDictionary<string, object> environment)
{
if (PerformMetric(environment))
{
environment[RequestStartTimeKey] = Clock.Default.Nanoseconds;
await next(environment);
var httpResponseStatusCode = int.Parse(environment["owin.ResponseStatusCode"].ToString());
var metricName = environment["owin.RequestPath"].ToString();
if (environment.ContainsKey("metrics-net.routetemplate"))
{
metricName = environment["metrics-net.routetemplate"] as string;
}
if (httpResponseStatusCode != (int)HttpStatusCode.NotFound)
{
var startTime = (long)environment[RequestStartTimeKey];
var elapsed = Clock.Default.Nanoseconds - startTime;
this.context.Timer(metricName, Unit.Requests, SamplingType.FavourRecent, TimeUnit.Seconds, TimeUnit.Milliseconds).Record(elapsed, TimeUnit.Nanoseconds);
}
}
else
{
await next(environment);
}
}
}
}
| apache-2.0 | C# |
96c72f6e89ff37212ab205417ccb1d516d5e0ff4 | Update PushalotExceptionTelemeter.cs | tiksn/TIKSN-Framework | TIKSN.Core/Analytics/Telemetry/Pushalot/PushalotExceptionTelemeter.cs | TIKSN.Core/Analytics/Telemetry/Pushalot/PushalotExceptionTelemeter.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TIKSN.Configuration;
namespace TIKSN.Analytics.Telemetry.Pushalot
{
public class PushalotExceptionTelemeter : PushalotTelemeterBase, IExceptionTelemeter
{
public PushalotExceptionTelemeter(IPartialConfiguration<PushalotOptions> pushalotConfiguration)
: base(pushalotConfiguration)
{
}
public async Task TrackException(Exception exception) => await this.SendMessage(exception.GetType().FullName,
exception.Message + Environment.NewLine + exception.StackTrace);
public async Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel) =>
await this.SendMessage(string.Format("{0} - {1}", exception.GetType().FullName, severityLevel),
exception.Message + Environment.NewLine + exception.StackTrace);
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration) =>
pushalotConfiguration.ExceptionAuthorizationTokens;
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration,
TelemetrySeverityLevel severityLevel)
{
if (pushalotConfiguration.SeverityLevelExceptionAuthorizationTokens.ContainsKey(severityLevel))
{
return pushalotConfiguration.SeverityLevelExceptionAuthorizationTokens[severityLevel];
}
return Enumerable.Empty<string>();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TIKSN.Configuration;
namespace TIKSN.Analytics.Telemetry.Pushalot
{
public class PushalotExceptionTelemeter : PushalotTelemeterBase, IExceptionTelemeter
{
public PushalotExceptionTelemeter(IPartialConfiguration<PushalotOptions> pushalotConfiguration)
: base(pushalotConfiguration)
{
}
public async Task TrackException(Exception exception)
{
await SendMessage(exception.GetType().FullName, exception.Message + Environment.NewLine + exception.StackTrace);
}
public async Task TrackException(Exception exception, TelemetrySeverityLevel severityLevel)
{
await SendMessage(string.Format("{0} - {1}", exception.GetType().FullName, severityLevel), exception.Message + Environment.NewLine + exception.StackTrace);
}
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration)
{
return pushalotConfiguration.ExceptionAuthorizationTokens;
}
protected override IEnumerable<string> GetAuthorizationTokens(PushalotOptions pushalotConfiguration, TelemetrySeverityLevel severityLevel)
{
if (pushalotConfiguration.SeverityLevelExceptionAuthorizationTokens.ContainsKey(severityLevel))
{
return pushalotConfiguration.SeverityLevelExceptionAuthorizationTokens[severityLevel];
}
return Enumerable.Empty<string>();
}
}
} | mit | C# |
5b167e3eb10b89341ee065bba5a5d101b8fefd52 | fix 'NoOpMediator' does not implement interface member (#308) | ardalis/CleanArchitecture,ardalis/CleanArchitecture,ardalis/CleanArchitecture | tests/Clean.Architecture.UnitTests/NoOpMediator.cs | tests/Clean.Architecture.UnitTests/NoOpMediator.cs | using System.Runtime.CompilerServices;
using MediatR;
namespace Clean.Architecture.UnitTests;
public class NoOpMediator : IMediator
{
public Task Publish(object notification, CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
public Task Publish<TNotification>(TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification
{
return Task.CompletedTask;
}
public Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
{
return Task.FromResult<TResponse>(default);
}
public Task<object?> Send(object request, CancellationToken cancellationToken = default)
{
return Task.FromResult<object?>(default);
}
public async IAsyncEnumerable<TResponse> CreateStream<TResponse>(IStreamRequest<TResponse> request,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
yield break;
}
public async IAsyncEnumerable<object?> CreateStream(object request,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await Task.CompletedTask;
yield break;
}
}
| using MediatR;
namespace Clean.Architecture.UnitTests;
public class NoOpMediator : IMediator
{
public Task Publish(object notification, CancellationToken cancellationToken = default)
{
return Task.CompletedTask;
}
public Task Publish<TNotification>(TNotification notification, CancellationToken cancellationToken = default) where TNotification : INotification
{
return Task.CompletedTask;
}
public Task<TResponse> Send<TResponse>(IRequest<TResponse> request, CancellationToken cancellationToken = default)
{
return Task.FromResult<TResponse>(default);
}
public Task<object?> Send(object request, CancellationToken cancellationToken = default)
{
return Task.FromResult<object?>(default);
}
}
| mit | C# |
08fdd0dc6bb3653aef7b101f1701cbd987dc4bb6 | Add Azure.Batch AssemblyAttributes version info | yugangw-msft/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,peshen/azure-sdk-for-net,r22016/azure-sdk-for-net,nathannfan/azure-sdk-for-net,samtoubia/azure-sdk-for-net,begoldsm/azure-sdk-for-net,atpham256/azure-sdk-for-net,stankovski/azure-sdk-for-net,samtoubia/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,pilor/azure-sdk-for-net,r22016/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,begoldsm/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,mihymel/azure-sdk-for-net,samtoubia/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,olydis/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jamestao/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,Yahnoosh/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,hyonholee/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,nathannfan/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,smithab/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,djyou/azure-sdk-for-net,atpham256/azure-sdk-for-net,djyou/azure-sdk-for-net,shutchings/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,pilor/azure-sdk-for-net,mihymel/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,peshen/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,djyou/azure-sdk-for-net,jamestao/azure-sdk-for-net,peshen/azure-sdk-for-net,r22016/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,shahabhijeet/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net,olydis/azure-sdk-for-net,DheerendraRathor/azure-sdk-for-net,AzCiS/azure-sdk-for-net,nathannfan/azure-sdk-for-net,samtoubia/azure-sdk-for-net,yugangw-msft/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,smithab/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,btasdoven/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,ScottHolden/azure-sdk-for-net,hyonholee/azure-sdk-for-net,shutchings/azure-sdk-for-net,AzCiS/azure-sdk-for-net,btasdoven/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,hyonholee/azure-sdk-for-net,ayeletshpigelman/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,btasdoven/azure-sdk-for-net,begoldsm/azure-sdk-for-net,hyonholee/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jamestao/azure-sdk-for-net,AzCiS/azure-sdk-for-net,pankajsn/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,SiddharthChatrolaMs/azure-sdk-for-net,markcowl/azure-sdk-for-net,stankovski/azure-sdk-for-net,shutchings/azure-sdk-for-net,mihymel/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,jhendrixMSFT/azure-sdk-for-net,pankajsn/azure-sdk-for-net,jackmagic313/azure-sdk-for-net,AsrOneSdk/azure-sdk-for-net,smithab/azure-sdk-for-net,pankajsn/azure-sdk-for-net,AzureAutomationTeam/azure-sdk-for-net,jamestao/azure-sdk-for-net,ahosnyms/azure-sdk-for-net,yoavrubin/azure-sdk-for-net,pilor/azure-sdk-for-net,JasonYang-MSFT/azure-sdk-for-net,brjohnstmsft/azure-sdk-for-net,atpham256/azure-sdk-for-net,olydis/azure-sdk-for-net,yaakoviyun/azure-sdk-for-net,MichaelCommo/azure-sdk-for-net | src/Batch/Client/Src/AssemblyAttributes.cs | src/Batch/Client/Src/AssemblyAttributes.cs | // Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Runtime.CompilerServices;
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Microsoft.Azure.Batch")]
[assembly: AssemblyDescription("Client library for interacting with the Azure Batch service.")]
[assembly: AssemblyVersion("5.0.0.0")]
[assembly: AssemblyFileVersion("5.0.0.0")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("Microsoft Azure")]
[assembly: AssemblyCopyright("Copyright (c) Microsoft Corporation. All rights reserved.")]
[assembly: CLSCompliant(false)]
[assembly: ComVisible(false)]
#if CODESIGN
[assembly: InternalsVisibleTo("Azure.Batch.Unit.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Azure.Batch.Unit.Tests")]
#endif
| // Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Runtime.CompilerServices;
#if CODESIGN
[assembly: InternalsVisibleTo("Azure.Batch.Unit.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
#else
[assembly: InternalsVisibleTo("Azure.Batch.Unit.Tests")]
#endif | mit | C# |
5d8bd66dd513e60c9e1dd13b84843f0d53fbbd38 | Update DirectionStep.cs | ericnewton76/gmaps-api-net | src/Google.Maps/Direction/DirectionStep.cs | src/Google.Maps/Direction/DirectionStep.cs | using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Google.Maps.Direction
{
[JsonObject(MemberSerialization.OptIn)]
public class DirectionStep
{
[JsonProperty("travel_mode")]
public TravelMode TravelMode { get; set; }
[JsonProperty("start_location")]
public LatLng StartLocation { get; set; }
[JsonProperty("end_location")]
public LatLng EndLocation { get; set; }
[JsonProperty("polyline")]
public Polyline Polyline { get; set; }
[JsonProperty("duration")]
public ValueText Duration { get; set; }
[Obsolete("maneuver is obsolete", false)]
public string Maneuver { get; set; }
[JsonProperty("transit_details")]
public DirectionTransitDetails TransitDetails { get; set; }
[JsonProperty("html_instructions")]
public string HtmlInstructions { get; set; }
[JsonProperty("distance")]
public ValueText Distance { get; set; }
public DirectionStep() { }
public DirectionStep(LatLng start, LatLng end)
{
StartLocation = start;
EndLocation = end;
}
public DirectionStep(decimal startLat, decimal startLng, decimal endLat, decimal endLng)
{
StartLocation = new LatLng(startLat, startLng);
EndLocation = new LatLng(endLat, endLng);
}
}
}
| using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace Google.Maps.Direction
{
[JsonObject(MemberSerialization.OptIn)]
public class DirectionStep
{
[JsonProperty("travel_mode")]
public TravelMode TravelMode { get; set; }
[JsonProperty("start_location")]
public LatLng StartLocation { get; set; }
[JsonProperty("end_location")]
public LatLng EndLocation { get; set; }
[JsonProperty("polyline")]
public Polyline Polyline { get; set; }
[JsonProperty("duration")]
public ValueText Duration { get; set; }
[JsonProperty("transit_details")]
public DirectionTransitDetails TransitDetails { get; set; }
[JsonProperty("html_instructions")]
public string HtmlInstructions { get; set; }
[JsonProperty("distance")]
public ValueText Distance { get; set; }
public DirectionStep() { }
public DirectionStep(LatLng start, LatLng end)
{
StartLocation = start;
EndLocation = end;
}
public DirectionStep(decimal startLat, decimal startLng, decimal endLat, decimal endLng)
{
StartLocation = new LatLng(startLat, startLng);
EndLocation = new LatLng(endLat, endLng);
}
}
}
| apache-2.0 | C# |
562b605bad57892ba98ef43a28b6eb117bb1fb65 | remove redundant check | NancyFx/Nancy.Serialization.JsonNet,NancyFx/Nancy.Serialization.JsonNet | src/Nancy.Serialization.JsonNet/Helpers.cs | src/Nancy.Serialization.JsonNet/Helpers.cs | namespace Nancy.Serialization.JsonNet
{
using System;
internal static class Helpers
{
/// <summary>
/// Attempts to detect if the content type is JSON.
/// Supports:
/// application/json
/// text/json
/// application/vnd[something]+json
/// Matches are case insentitive to try and be as "accepting" as possible.
/// </summary>
/// <param name="contentType">Request content type</param>
/// <returns>True if content type is JSON, false otherwise</returns>
public static bool IsJsonType(string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
return false;
}
var contentMimeType = contentType.Split(';')[0];
return contentMimeType.Equals("application/json", StringComparison.OrdinalIgnoreCase)
|| contentMimeType.Equals("text/json", StringComparison.OrdinalIgnoreCase)
|| contentMimeType.EndsWith("+json", StringComparison.OrdinalIgnoreCase);
}
}
}
| namespace Nancy.Serialization.JsonNet
{
using System;
internal static class Helpers
{
/// <summary>
/// Attempts to detect if the content type is JSON.
/// Supports:
/// application/json
/// text/json
/// application/vnd[something]+json
/// Matches are case insentitive to try and be as "accepting" as possible.
/// </summary>
/// <param name="contentType">Request content type</param>
/// <returns>True if content type is JSON, false otherwise</returns>
public static bool IsJsonType(string contentType)
{
if (string.IsNullOrEmpty(contentType))
{
return false;
}
var contentMimeType = contentType.Split(';')[0];
return contentMimeType.Equals("application/json", StringComparison.OrdinalIgnoreCase) ||
contentMimeType.Equals("text/json", StringComparison.OrdinalIgnoreCase) ||
(contentMimeType.StartsWith("application/vnd", StringComparison.OrdinalIgnoreCase) &&
contentMimeType.EndsWith("+json", StringComparison.OrdinalIgnoreCase));
}
}
}
| mit | C# |
9b213f5813f09c77f2dc8410692d8aa7f1a27a5c | change a testing uri to a correct public visible api | oelite/RESTme | src/OElite.Restme.UnitTests/RestmeTests.cs | src/OElite.Restme.UnitTests/RestmeTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace OElite.Restme.UnitTests
{
public class RestmeTests
{
[Fact]
public void GetTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = rest.Get<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = rest.Get<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = rest.Get<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
}
[Fact]
public async Task GetAsyncTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = await rest.GetAsync<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = await rest.GetAsync<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = await rest.GetAsync<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
rest = new Restme(new Uri("http://api-beta.oelite.com"));
rest.Add("id", 8);
var result4 = await rest.GetAsync<string>("/sites");
Assert.True(result4.Length > 30);
}
private class GeoResult
{
public string IP { get; set; }
public string Country_Code { get; set; }
public string Country_Name { get; set; }
public string Region_Code { get; set; }
public string Region_Name { get; set; }
public string City { get; set; }
public string Zip_Code { get; set; }
public string Time_Zone { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string Metro_Code { get; set; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace OElite.Restme.UnitTests
{
public class RestmeTests
{
[Fact]
public void GetTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = rest.Get<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = rest.Get<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = rest.Get<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
}
[Fact]
public async Task GetAsyncTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = await rest.GetAsync<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = await rest.GetAsync<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = await rest.GetAsync<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
rest = new Restme(new Uri("http://api-beta.webcider.com"));
rest.Add("id", 8);
var result4 = await rest.GetAsync<string>("/sites");
Assert.True(result4.Length > 30);
}
private class GeoResult
{
public string IP { get; set; }
public string Country_Code { get; set; }
public string Country_Name { get; set; }
public string Region_Code { get; set; }
public string Region_Name { get; set; }
public string City { get; set; }
public string Zip_Code { get; set; }
public string Time_Zone { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string Metro_Code { get; set; }
}
}
}
| mit | C# |
e4b877599d48c5155198c15b9c31431eaec4bb1a | add async test | oelite/RESTme | src/OElite.Restme.UnitTests/RestmeTests.cs | src/OElite.Restme.UnitTests/RestmeTests.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace OElite.Restme.UnitTests
{
public class RestmeTests
{
[Fact]
public void GetTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = rest.Get<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = rest.Get<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = rest.Get<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
}
[Fact]
public async Task GetAsyncTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = await rest.GetAsync<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = await rest.GetAsync<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = await rest.GetAsync<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
rest = new Restme(new Uri("http://api-beta.webcider.com"));
rest.Add("id", 8);
var result4 = await rest.GetAsync<string>("/sites");
Assert.True(result4.Length > 30);
}
private class GeoResult
{
public string IP { get; set; }
public string Country_Code { get; set; }
public string Country_Name { get; set; }
public string Region_Code { get; set; }
public string Region_Name { get; set; }
public string City { get; set; }
public string Zip_Code { get; set; }
public string Time_Zone { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string Metro_Code { get; set; }
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace OElite.Restme.UnitTests
{
public class RestmeTests
{
[Fact]
public void GetTests()
{
var rest = new Restme(new Uri("http://freegeoip.net"));
var result1 = rest.Get<string>("/json/github.com");
Assert.True(result1.Length > 0 && result1.Contains("region_code"));
var result2 = rest.Get<GeoResult>("/json/github.com");
Assert.True(result2?.Latitude != 0);
rest.Add("q", "github.com");
var result3 = rest.Get<GeoResult>("/json");
Assert.True(result3?.Latitude != null);
}
private class GeoResult
{
public string IP { get; set; }
public string Country_Code { get; set; }
public string Country_Name { get; set; }
public string Region_Code { get; set; }
public string Region_Name { get; set; }
public string City { get; set; }
public string Zip_Code { get; set; }
public string Time_Zone { get; set; }
public decimal Latitude { get; set; }
public decimal Longitude { get; set; }
public string Metro_Code { get; set; }
}
}
}
| mit | C# |
3152fb6fc69ef2d9e3b0ae4c996fba7e8a664da8 | Comment out ctrl-C System.Console test | shrutigarg/corefx,jlin177/corefx,tijoytom/corefx,akivafr123/corefx,lggomez/corefx,shrutigarg/corefx,pallavit/corefx,ptoonen/corefx,iamjasonp/corefx,jhendrixMSFT/corefx,n1ghtmare/corefx,jcme/corefx,brett25/corefx,andyhebear/corefx,alexandrnikitin/corefx,nbarbettini/corefx,heXelium/corefx,benjamin-bader/corefx,pgavlin/corefx,axelheer/corefx,heXelium/corefx,zhenlan/corefx,khdang/corefx,cartermp/corefx,billwert/corefx,BrennanConroy/corefx,n1ghtmare/corefx,dotnet-bot/corefx,zhenlan/corefx,MaggieTsang/corefx,DnlHarvey/corefx,shmao/corefx,pallavit/corefx,MaggieTsang/corefx,Frank125/corefx,gregg-miskelly/corefx,khdang/corefx,dhoehna/corefx,andyhebear/corefx,twsouthwick/corefx,twsouthwick/corefx,twsouthwick/corefx,twsouthwick/corefx,Priya91/corefx-1,alphonsekurian/corefx,parjong/corefx,marksmeltzer/corefx,alexperovich/corefx,mmitche/corefx,shmao/corefx,tstringer/corefx,weltkante/corefx,Jiayili1/corefx,nchikanov/corefx,adamralph/corefx,alphonsekurian/corefx,BrennanConroy/corefx,ericstj/corefx,josguil/corefx,tijoytom/corefx,huanjie/corefx,Jiayili1/corefx,the-dwyer/corefx,KrisLee/corefx,s0ne0me/corefx,richlander/corefx,shrutigarg/corefx,kkurni/corefx,krk/corefx,rahku/corefx,wtgodbe/corefx,iamjasonp/corefx,khdang/corefx,zmaruo/corefx,dhoehna/corefx,vidhya-bv/corefx-sorting,gregg-miskelly/corefx,YoupHulsebos/corefx,iamjasonp/corefx,s0ne0me/corefx,uhaciogullari/corefx,billwert/corefx,krk/corefx,YoupHulsebos/corefx,DnlHarvey/corefx,tstringer/corefx,matthubin/corefx,nchikanov/corefx,dhoehna/corefx,marksmeltzer/corefx,khdang/corefx,axelheer/corefx,rjxby/corefx,n1ghtmare/corefx,alphonsekurian/corefx,fgreinacher/corefx,gkhanna79/corefx,CherryCxldn/corefx,rahku/corefx,benpye/corefx,parjong/corefx,dotnet-bot/corefx,Chrisboh/corefx,pgavlin/corefx,Jiayili1/corefx,jcme/corefx,janhenke/corefx,yizhang82/corefx,krytarowski/corefx,yizhang82/corefx,stephenmichaelf/corefx,seanshpark/corefx,lydonchandra/corefx,jlin177/corefx,jlin177/corefx,richlander/corefx,lydonchandra/corefx,rahku/corefx,stone-li/corefx,mellinoe/corefx,mazong1123/corefx,lggomez/corefx,bitcrazed/corefx,krk/corefx,seanshpark/corefx,shmao/corefx,YoupHulsebos/corefx,parjong/corefx,jlin177/corefx,seanshpark/corefx,dotnet-bot/corefx,cartermp/corefx,cartermp/corefx,janhenke/corefx,zmaruo/corefx,tijoytom/corefx,shahid-pk/corefx,tstringer/corefx,Jiayili1/corefx,huanjie/corefx,Priya91/corefx-1,comdiv/corefx,axelheer/corefx,the-dwyer/corefx,Chrisboh/corefx,elijah6/corefx,nbarbettini/corefx,cartermp/corefx,gkhanna79/corefx,jcme/corefx,shahid-pk/corefx,lggomez/corefx,n1ghtmare/corefx,Alcaro/corefx,matthubin/corefx,690486439/corefx,alexandrnikitin/corefx,bitcrazed/corefx,mafiya69/corefx,tijoytom/corefx,mazong1123/corefx,jlin177/corefx,mellinoe/corefx,alphonsekurian/corefx,nbarbettini/corefx,dhoehna/corefx,rajansingh10/corefx,shimingsg/corefx,rjxby/corefx,stone-li/corefx,JosephTremoulet/corefx,zhenlan/corefx,lggomez/corefx,Priya91/corefx-1,690486439/corefx,690486439/corefx,s0ne0me/corefx,ViktorHofer/corefx,rubo/corefx,dsplaisted/corefx,benjamin-bader/corefx,pgavlin/corefx,cydhaselton/corefx,zhenlan/corefx,Alcaro/corefx,kyulee1/corefx,lydonchandra/corefx,axelheer/corefx,rajansingh10/corefx,Yanjing123/corefx,stephenmichaelf/corefx,manu-silicon/corefx,dotnet-bot/corefx,dhoehna/corefx,jhendrixMSFT/corefx,tijoytom/corefx,CloudLens/corefx,Jiayili1/corefx,elijah6/corefx,gkhanna79/corefx,adamralph/corefx,YoupHulsebos/corefx,comdiv/corefx,elijah6/corefx,690486439/corefx,marksmeltzer/corefx,rahku/corefx,ViktorHofer/corefx,Yanjing123/corefx,vs-team/corefx,kkurni/corefx,SGuyGe/corefx,nelsonsar/corefx,MaggieTsang/corefx,mafiya69/corefx,Petermarcu/corefx,shahid-pk/corefx,manu-silicon/corefx,SGuyGe/corefx,brett25/corefx,cartermp/corefx,krytarowski/corefx,ptoonen/corefx,rubo/corefx,stephenmichaelf/corefx,tstringer/corefx,JosephTremoulet/corefx,shmao/corefx,mmitche/corefx,fgreinacher/corefx,mokchhya/corefx,ellismg/corefx,twsouthwick/corefx,ravimeda/corefx,Jiayili1/corefx,krytarowski/corefx,MaggieTsang/corefx,shmao/corefx,Chrisboh/corefx,ViktorHofer/corefx,rjxby/corefx,richlander/corefx,mmitche/corefx,690486439/corefx,CloudLens/corefx,shimingsg/corefx,krk/corefx,mokchhya/corefx,krk/corefx,dtrebbien/corefx,Frank125/corefx,mazong1123/corefx,elijah6/corefx,yizhang82/corefx,bitcrazed/corefx,ViktorHofer/corefx,gregg-miskelly/corefx,lggomez/corefx,krk/corefx,alexperovich/corefx,janhenke/corefx,benpye/corefx,CherryCxldn/corefx,gkhanna79/corefx,Yanjing123/corefx,parjong/corefx,iamjasonp/corefx,jeremymeng/corefx,ptoonen/corefx,elijah6/corefx,PatrickMcDonald/corefx,SGuyGe/corefx,marksmeltzer/corefx,rjxby/corefx,Ermiar/corefx,zmaruo/corefx,ellismg/corefx,ptoonen/corefx,nelsonsar/corefx,DnlHarvey/corefx,rahku/corefx,billwert/corefx,mellinoe/corefx,mazong1123/corefx,bitcrazed/corefx,ptoonen/corefx,ravimeda/corefx,shimingsg/corefx,parjong/corefx,benpye/corefx,cydhaselton/corefx,PatrickMcDonald/corefx,pgavlin/corefx,benpye/corefx,weltkante/corefx,manu-silicon/corefx,iamjasonp/corefx,andyhebear/corefx,dhoehna/corefx,pallavit/corefx,jcme/corefx,Priya91/corefx-1,josguil/corefx,cartermp/corefx,shmao/corefx,manu-silicon/corefx,Alcaro/corefx,axelheer/corefx,PatrickMcDonald/corefx,yizhang82/corefx,jlin177/corefx,vidhya-bv/corefx-sorting,YoupHulsebos/corefx,benjamin-bader/corefx,twsouthwick/corefx,mafiya69/corefx,krytarowski/corefx,cydhaselton/corefx,nchikanov/corefx,nelsonsar/corefx,lggomez/corefx,JosephTremoulet/corefx,pallavit/corefx,mazong1123/corefx,jhendrixMSFT/corefx,weltkante/corefx,kyulee1/corefx,DnlHarvey/corefx,ellismg/corefx,mellinoe/corefx,the-dwyer/corefx,Petermarcu/corefx,JosephTremoulet/corefx,yizhang82/corefx,akivafr123/corefx,rjxby/corefx,yizhang82/corefx,ravimeda/corefx,josguil/corefx,JosephTremoulet/corefx,fgreinacher/corefx,janhenke/corefx,pallavit/corefx,jeremymeng/corefx,jhendrixMSFT/corefx,ViktorHofer/corefx,gkhanna79/corefx,khdang/corefx,rjxby/corefx,adamralph/corefx,Yanjing123/corefx,dotnet-bot/corefx,billwert/corefx,nchikanov/corefx,lggomez/corefx,wtgodbe/corefx,dhoehna/corefx,weltkante/corefx,ericstj/corefx,DnlHarvey/corefx,Chrisboh/corefx,rubo/corefx,mellinoe/corefx,janhenke/corefx,cydhaselton/corefx,mokchhya/corefx,krytarowski/corefx,brett25/corefx,CherryCxldn/corefx,alexandrnikitin/corefx,Ermiar/corefx,dtrebbien/corefx,ericstj/corefx,alexandrnikitin/corefx,PatrickMcDonald/corefx,khdang/corefx,kyulee1/corefx,DnlHarvey/corefx,Chrisboh/corefx,matthubin/corefx,n1ghtmare/corefx,cydhaselton/corefx,dotnet-bot/corefx,richlander/corefx,rjxby/corefx,brett25/corefx,MaggieTsang/corefx,shahid-pk/corefx,seanshpark/corefx,billwert/corefx,ravimeda/corefx,nbarbettini/corefx,ViktorHofer/corefx,stormleoxia/corefx,jeremymeng/corefx,billwert/corefx,Chrisboh/corefx,akivafr123/corefx,huanjie/corefx,Alcaro/corefx,CloudLens/corefx,manu-silicon/corefx,lydonchandra/corefx,shimingsg/corefx,ravimeda/corefx,matthubin/corefx,elijah6/corefx,wtgodbe/corefx,alexperovich/corefx,Priya91/corefx-1,elijah6/corefx,stephenmichaelf/corefx,billwert/corefx,JosephTremoulet/corefx,mokchhya/corefx,benjamin-bader/corefx,nbarbettini/corefx,MaggieTsang/corefx,zhenlan/corefx,benjamin-bader/corefx,dtrebbien/corefx,shmao/corefx,Frank125/corefx,manu-silicon/corefx,alexperovich/corefx,CherryCxldn/corefx,KrisLee/corefx,Priya91/corefx-1,ellismg/corefx,the-dwyer/corefx,heXelium/corefx,yizhang82/corefx,ericstj/corefx,wtgodbe/corefx,benpye/corefx,heXelium/corefx,Petermarcu/corefx,marksmeltzer/corefx,weltkante/corefx,stephenmichaelf/corefx,stormleoxia/corefx,jeremymeng/corefx,mellinoe/corefx,fgreinacher/corefx,SGuyGe/corefx,YoupHulsebos/corefx,KrisLee/corefx,richlander/corefx,stephenmichaelf/corefx,vs-team/corefx,comdiv/corefx,benpye/corefx,Frank125/corefx,mokchhya/corefx,wtgodbe/corefx,PatrickMcDonald/corefx,jcme/corefx,kkurni/corefx,zmaruo/corefx,dsplaisted/corefx,gregg-miskelly/corefx,Ermiar/corefx,ptoonen/corefx,iamjasonp/corefx,alexperovich/corefx,BrennanConroy/corefx,Ermiar/corefx,weltkante/corefx,the-dwyer/corefx,stone-li/corefx,alexandrnikitin/corefx,josguil/corefx,KrisLee/corefx,stone-li/corefx,uhaciogullari/corefx,mmitche/corefx,Petermarcu/corefx,kyulee1/corefx,andyhebear/corefx,mmitche/corefx,s0ne0me/corefx,vidhya-bv/corefx-sorting,axelheer/corefx,nchikanov/corefx,mmitche/corefx,ptoonen/corefx,dotnet-bot/corefx,stone-li/corefx,comdiv/corefx,ericstj/corefx,rubo/corefx,shahid-pk/corefx,Petermarcu/corefx,stone-li/corefx,alexperovich/corefx,vidhya-bv/corefx-sorting,the-dwyer/corefx,huanjie/corefx,zhenlan/corefx,wtgodbe/corefx,rajansingh10/corefx,krytarowski/corefx,alphonsekurian/corefx,ericstj/corefx,MaggieTsang/corefx,nchikanov/corefx,jhendrixMSFT/corefx,richlander/corefx,wtgodbe/corefx,alexperovich/corefx,janhenke/corefx,shimingsg/corefx,CloudLens/corefx,krk/corefx,ellismg/corefx,marksmeltzer/corefx,zhenlan/corefx,dsplaisted/corefx,shrutigarg/corefx,nelsonsar/corefx,marksmeltzer/corefx,vs-team/corefx,shimingsg/corefx,Ermiar/corefx,DnlHarvey/corefx,nchikanov/corefx,kkurni/corefx,Petermarcu/corefx,uhaciogullari/corefx,akivafr123/corefx,the-dwyer/corefx,alphonsekurian/corefx,ViktorHofer/corefx,jeremymeng/corefx,stephenmichaelf/corefx,Ermiar/corefx,tijoytom/corefx,seanshpark/corefx,ravimeda/corefx,mazong1123/corefx,vidhya-bv/corefx-sorting,parjong/corefx,rubo/corefx,pallavit/corefx,gkhanna79/corefx,rajansingh10/corefx,parjong/corefx,josguil/corefx,seanshpark/corefx,JosephTremoulet/corefx,mazong1123/corefx,uhaciogullari/corefx,Jiayili1/corefx,stormleoxia/corefx,YoupHulsebos/corefx,Petermarcu/corefx,iamjasonp/corefx,tstringer/corefx,rahku/corefx,mmitche/corefx,mokchhya/corefx,mafiya69/corefx,jlin177/corefx,shahid-pk/corefx,nbarbettini/corefx,kkurni/corefx,stone-li/corefx,stormleoxia/corefx,josguil/corefx,dtrebbien/corefx,vs-team/corefx,shimingsg/corefx,richlander/corefx,weltkante/corefx,jhendrixMSFT/corefx,twsouthwick/corefx,SGuyGe/corefx,Yanjing123/corefx,tstringer/corefx,ravimeda/corefx,rahku/corefx,nbarbettini/corefx,ellismg/corefx,Ermiar/corefx,bitcrazed/corefx,benjamin-bader/corefx,akivafr123/corefx,cydhaselton/corefx,seanshpark/corefx,jhendrixMSFT/corefx,mafiya69/corefx,SGuyGe/corefx,cydhaselton/corefx,krytarowski/corefx,alphonsekurian/corefx,gkhanna79/corefx,manu-silicon/corefx,mafiya69/corefx,jcme/corefx,tijoytom/corefx,ericstj/corefx,kkurni/corefx | src/System.Console/tests/CancelKeyPress.cs | src/System.Console/tests/CancelKeyPress.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using Xunit;
public class CancelKeyPress
{
private const int WaitFailTestTimeoutSeconds = 30;
[Fact]
public static void CanAddAndRemoveHandler()
{
ConsoleCancelEventHandler handler = (sender, e) =>
{
// We don't actually want to do anything here. This will only get called on the off chance
// that someone CTRL+C's the test run while the handler is hooked up. This is just used to
// validate that we can add and remove a handler, we don't care about exercising it.
};
Console.CancelKeyPress += handler;
Console.CancelKeyPress -= handler;
}
// Commented out InvokingCancelKeyPressHandler test:
// While this test works, it also causes problems when run as part of
// the xunit harness. Since it issues a ctrl-c back to itself, xunit's own
// CancelKeyPress event handler will likely stop running additional tests
// after this test has run. The test is here and commented out rather than
// being deleted in case we want to add something like it back in the future.
//
//[Fact]
//[PlatformSpecific(PlatformID.AnyUnix)]
//public static void InvokingCancelKeyPressHandler()
//{
// // On Windows we could use GenerateConsoleCtrlEvent to send a ctrl-C to the process,
// // however that'll apply to all processes associated with the same group, which will
// // include processes like the code coverage tool when doing code coverage runs, causing
// // those other processes to exit. As such, we test this only on Unix, where we can
// // send a SIGINT signal to this specific process only.
//
// using (var mres = new ManualResetEventSlim())
// {
// ConsoleCancelEventHandler handler = (sender, e) => {
// e.Cancel = true;
// mres.Set();
// };
//
// Console.CancelKeyPress += handler;
// try
// {
// Assert.Equal(0, kill(getpid(), SIGINT));
// Assert.True(mres.Wait(WaitFailTestTimeoutSeconds));
// }
// finally
// {
// Console.CancelKeyPress -= handler;
// }
// }
//}
//
//// P/Invokes included here rather than being pulled from Interop\Unix
//// to avoid platform-dependent includes in csproj
//[DllImport("libc", SetLastError = true)]
//private static extern int kill(int pid, int sig);
//
//[DllImport("libc")]
//private static extern int getpid();
//
//private const int SIGINT = 2;
}
| // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
using System.Threading;
using Xunit;
public class CancelKeyPress
{
private const int WaitFailTestTimeoutSeconds = 30;
[Fact]
public static void CanAddAndRemoveHandler()
{
ConsoleCancelEventHandler handler = (sender, e) =>
{
// We don't actually want to do anything here. This will only get called on the off chance
// that someone CTRL+C's the test run while the handler is hooked up. This is just used to
// validate that we can add and remove a handler, we don't care about exercising it.
};
Console.CancelKeyPress += handler;
Console.CancelKeyPress -= handler;
}
[Fact]
[PlatformSpecific(PlatformID.AnyUnix)]
public static void InvokingCancelKeyPressHandler()
{
// On Windows we could use GenerateConsoleCtrlEvent to send a ctrl-C to the process,
// however that'll apply to all processes associated with the same group, which will
// include processes like the code coverage tool when doing code coverage runs, causing
// those other processes to exit. As such, we test this only on Unix, where we can
// send a SIGINT signal to this specific process only.
using (var mres = new ManualResetEventSlim())
{
ConsoleCancelEventHandler handler = (sender, e) => {
e.Cancel = true;
mres.Set();
};
Console.CancelKeyPress += handler;
try
{
Assert.Equal(0, kill(getpid(), SIGINT));
Assert.True(mres.Wait(WaitFailTestTimeoutSeconds));
}
finally
{
Console.CancelKeyPress -= handler;
}
}
}
#region Unix Imports
// P/Invokes included here rather than being pulled from Interop\Unix
// to avoid platform-dependent includes in csproj
[DllImport("libc", SetLastError = true)]
private static extern int kill(int pid, int sig);
[DllImport("libc")]
private static extern int getpid();
private const int SIGINT = 2;
#endregion
}
| mit | C# |
208573bb252e8542d2d9fc25421918c94444866f | Update startup of sample to pass in the serviceProvider | pranavkm/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,pranavkm/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype | src/Glimpse.Owin.Sample/Startup.cs | src/Glimpse.Owin.Sample/Startup.cs | using Glimpse.Host.Web.Owin;
using Microsoft.Framework.DependencyInjection;
using Microsoft.Framework.DependencyInjection.Fallback;
using Owin;
using System.Collections.Generic;
namespace Glimpse.Owin.Sample
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var serviceDescriptors = new List<IServiceDescriptor>();
var serviceProvider = serviceDescriptors.BuildServiceProvider();
app.Use<GlimpseMiddleware>(serviceProvider);
app.UseWelcomePage();
app.UseErrorPage();
}
}
} | using Glimpse.Host.Web.Owin;
using Owin;
namespace Glimpse.Owin.Sample
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.Use<GlimpseMiddleware>();
app.UseWelcomePage();
app.UseErrorPage();
}
}
} | mit | C# |
8ecee64263d3ef72db54091a37c797a9dfa36d0d | Replace npmcdn.com with unpkg.com | Isdas/buldringno,Isdas/buldringno,Isdas/buldringno,Isdas/buldringno | src/buldringno/Views/Shared/_Layout.cshtml | src/buldringno/Views/Shared/_Layout.cshtml | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewBag.Title</title>
@*<base href="/">*@
<link href="~/lib/css/bootstrap.css" rel="stylesheet" />
<link href="~/lib/css/font-awesome.css" rel="stylesheet" />
@RenderSection("styles", required: false)
@*Solve IE 11 issues *@
@*<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
<script src="https://unpkg.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>*@
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="~/lib/js/systemjs.config.js"></script>
<script src="~/lib/js/jquery.js"></script>
<script src="~/lib/js/bootstrap.js"></script>
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("scripts", required: false)
<script type="text/javascript">
@RenderSection("customScript", required: false)
</script>
</body>
</html> | <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>@ViewBag.Title</title>
@*<base href="/">*@
<link href="~/lib/css/bootstrap.css" rel="stylesheet" />
<link href="~/lib/css/font-awesome.css" rel="stylesheet" />
@RenderSection("styles", required: false)
@*Solve IE 11 issues *@
@*<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-shim/0.33.3/es6-shim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/systemjs/0.19.20/system-polyfills.js"></script>
<script src="https://npmcdn.com/angular2/es6/dev/src/testing/shims_for_IE.js"></script>*@
<!-- 1. Load libraries -->
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<!-- 2. Configure SystemJS -->
<script src="~/lib/js/systemjs.config.js"></script>
<script src="~/lib/js/jquery.js"></script>
<script src="~/lib/js/bootstrap.js"></script>
</head>
<body>
<div>
@RenderBody()
</div>
@RenderSection("scripts", required: false)
<script type="text/javascript">
@RenderSection("customScript", required: false)
</script>
</body>
</html> | mit | C# |
c1e02743f05a116dad14f041899171f0de1fbeb8 | Fix battle sequence bug 2/2 | Albeoris/Memoria,Albeoris/Memoria,Albeoris/Memoria,Albeoris/Memoria | Assembly-CSharp/Global/SEQ_WORK.cs | Assembly-CSharp/Global/SEQ_WORK.cs | using System;
public class SEQ_WORK
{
public SeqFlag Flags;
public CMD_DATA CmdPtr;
public Int32 CurPtr;
public Int32 OldPtr;
public Int16 IncCnt;
public Int16 DecCnt;
public Int16 AnmCnt;
public Byte AnmIDOfs;
public Byte SfxTime;
public UInt16 SfxNum;
public Byte SfxAttr;
public Byte SfxVol;
public Int16 TurnOrg;
public Int16 TurnRot;
public Byte TurnCnt;
public Byte TurnTime;
public UInt16 SVfxNum;
public Byte SVfxParam;
public Byte SVfxTime;
public Byte FadeTotal;
public Byte FadeStep;
public Byte[] Work = new Byte[16];
}
| using System;
public class SEQ_WORK
{
public SeqFlag Flags;
public CMD_DATA CmdPtr;
public Int32 CurPtr;
public Int32 OldPtr;
public Int16 IncCnt;
public Int16 DecCnt;
public Int16 AnmCnt;
public Byte AnmIDOfs;
public Byte SfxTime;
public UInt16 SfxNum;
public Byte SfxAttr;
public Byte SfxVol;
public Int16 TurnOrg;
public Int16 TurnRot;
public Byte TurnCnt;
public Byte TurnTime;
public UInt16 SVfxNum;
public Byte SVfxParam;
public Byte SVfxTime;
public Byte FadeTotal;
public Byte FadeStep;
public Byte[] Work;
}
| mit | C# |
dda6e8e019028e8c9f42382d3d6d06e8efcd1a92 | test fix | iolevel/peachpie,peachpiecompiler/peachpie,iolevel/peachpie,iolevel/peachpie-concept,iolevel/peachpie-concept,iolevel/peachpie-concept,iolevel/peachpie,peachpiecompiler/peachpie,peachpiecompiler/peachpie | src/Tests/Peachpie.Test/Program.cs | src/Tests/Peachpie.Test/Program.cs | using System;
using System.IO;
using Pchp.Core;
namespace Peachpie.Test
{
class Program
{
const string ScriptPath = "index.php";
static void Main(string[] args)
{
// bootstrapper that compiles, loads and runs our script file
var provider = (Context.IScriptingProvider)new Library.Scripting.ScriptingProvider();
var fullpath = Path.Combine(Directory.GetCurrentDirectory(), ScriptPath);
using (var ctx = Context.CreateConsole(string.Empty, args))
{
//
var script = provider.CreateScript(new Context.ScriptOptions()
{
Context = ctx,
Location = new Location(fullpath, 0, 0),
EmitDebugInformation = true,
IsSubmission = false,
}, File.ReadAllText(fullpath));
//
script.Evaluate(ctx, ctx.Globals, null);
}
}
}
} | using System;
using System.IO;
using Pchp.Core;
namespace Peachpie.Test
{
class Program
{
const string ScriptPath = "index.php";
static void Main(string[] args)
{
// bootstrapper that compiles, loads and runs our script file
var provider = (Context.IScriptingProvider)new Library.Scripting.ScriptingProvider();
var fullpath = Path.Combine(Directory.GetCurrentDirectory(), ScriptPath);
using (var ctx = Context.CreateConsole(args))
{
//
var script = provider.CreateScript(new Context.ScriptOptions()
{
Context = ctx,
Location = new Location(fullpath, 0, 0),
EmitDebugInformation = true,
IsSubmission = false,
}, File.ReadAllText(fullpath));
//
script.Evaluate(ctx, ctx.Globals, null);
}
}
}
} | apache-2.0 | C# |
39dbecb3b39e0d67bb630bfbe606a85118b59a4f | Simplify logic in merge sort and remove duplicated code. | scott-fleischman/algorithms-csharp | src/Algorithms.Sort/MergeSort.cs | src/Algorithms.Sort/MergeSort.cs | using System.Collections.Generic;
namespace Algorithms.Sort
{
public class MergeSort : ISortInPlace
{
// 2.3.1, pp. 31-34
public void SortInPlace<T>(IList<T> items, IComparer<T> comparer)
{
MergeSortInPlace(items, 0, items.Count - 1, comparer);
}
private void MergeSortInPlace<T>(IList<T> items, int left, int right, IComparer<T> comparer)
{
if (left < right)
{
int middle = (left + right) / 2;
MergeSortInPlace(items, left, middle, comparer);
MergeSortInPlace(items, middle + 1, right, comparer);
Merge(items, left, middle, right, comparer);
}
}
private void Merge<T>(IList<T> items, int leftEnd, int middle, int rightEnd, IComparer<T> comparer)
{
T[] leftItems = Slice(items, leftEnd, middle);
T[] rightItems = Slice(items, middle + 1, rightEnd);
int left = 0;
int right = 0;
for (int index = leftEnd; index <= rightEnd; index++)
{
bool getFromLeft = left < leftItems.Length &&
((right < rightItems.Length && comparer.Compare(leftItems[left], rightItems[right]) <= 0) ||
right >= rightItems.Length);
if (getFromLeft)
{
items[index] = leftItems[left];
left++;
}
else
{
items[index] = rightItems[right];
right++;
}
}
}
private static T[] Slice<T>(IList<T> items, int start, int end)
{
var slice = new T[end - start + 1];
for (int index = 0; index < slice.Length; index++)
slice[index] = items[start + index];
return slice;
}
}
}
| using System;
using System.Collections.Generic;
namespace Algorithms.Sort
{
public class MergeSort : ISortInPlace
{
// 2.3.1, pp. 31-34
public void SortInPlace<T>(IList<T> items, IComparer<T> comparer)
{
MergeSortInPlace(items, 0, items.Count - 1, comparer);
}
private void MergeSortInPlace<T>(IList<T> items, int left, int right, IComparer<T> comparer)
{
if (left < right)
{
int middle = (left + right) / 2;
MergeSortInPlace(items, left, middle, comparer);
MergeSortInPlace(items, middle + 1, right, comparer);
Merge(items, left, middle, right, comparer);
}
}
private void Merge<T>(IList<T> items, int leftEnd, int middle, int rightEnd, IComparer<T> comparer)
{
T[] leftItems = Slice(items, leftEnd, middle);
T[] rightItems = Slice(items, middle + 1, rightEnd);
int index = leftEnd;
int left = 0;
int right = 0;
while (index <= rightEnd && left < leftItems.Length && right < rightItems.Length)
{
if (comparer.Compare(leftItems[left], rightItems[right]) <= 0)
{
items[index] = leftItems[left];
left++;
}
else
{
items[index] = rightItems[right];
right++;
}
index++;
}
while (index <= rightEnd && left < leftItems.Length)
{
items[index] = leftItems[left];
left++;
index++;
}
while (index <= rightEnd && right < rightItems.Length)
{
items[index] = rightItems[right];
right++;
index++;
}
if (index <= rightEnd)
throw new InvalidOperationException("Did not insert all elements into result");
}
private static T[] Slice<T>(IList<T> items, int start, int end)
{
var slice = new T[end - start + 1];
for (int index = 0; index < slice.Length; index++)
slice[index] = items[start + index];
return slice;
}
}
}
| mit | C# |
3bd5c1d6fafa38fd789581f9b10cef49915c55fd | Remove incorrect comment. | mdavid/manos-spdy,jacksonh/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jacksonh/manos,jmptrader/manos,jmptrader/manos,jacksonh/manos,jmptrader/manos,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,jmptrader/manos,mdavid/manos-spdy,jacksonh/manos,mdavid/manos-spdy,mdavid/manos-spdy,mdavid/manos-spdy | src/Manos/Manos.Server/IOLoop.cs | src/Manos/Manos.Server/IOLoop.cs |
using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Libev;
namespace Manos.Server {
public class IOLoop {
private static IOLoop instance = new IOLoop ();
private bool running;
private Loop evloop;
private PrepareWatcher prepare_watcher;
public IOLoop ()
{
evloop = Loop.CreateDefaultLoop (0);
prepare_watcher = new PrepareWatcher (evloop, HandlePrepareEvent);
prepare_watcher.Start ();
}
public static IOLoop Instance {
get { return instance; }
}
public Loop EventLoop {
get { return evloop; }
}
public void QueueTransaction (HttpTransaction trans)
{
//
// Since the switch to libev, it seems best to just run them
// for now I'll leave the queueing function call in, so its
// easy to experiment later.
trans.Run ();
}
public void Start ()
{
running = true;
evloop.RunBlocking ();
}
public void Stop ()
{
running = false;
}
private void HandlePrepareEvent (Loop loop, PrepareWatcher watcher, int revents)
{
if (!running) {
loop.Unloop (UnloopType.All);
prepare_watcher.Stop ();
}
}
public void AddTimeout (Timeout timeout)
{
TimerWatcher t = new TimerWatcher (timeout.begin, timeout.span, evloop, HandleTimeout);
t.UserData = timeout;
t.Start ();
}
private void HandleTimeout (Loop loop, TimerWatcher timeout, int revents)
{
Timeout t = (Timeout) timeout.UserData;
AppHost.RunTimeout (t);
if (!t.ShouldContinueToRepeat ())
timeout.Stop ();
}
}
}
|
using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Libev;
namespace Manos.Server {
public class IOLoop {
private static IOLoop instance = new IOLoop ();
private bool running;
private Loop evloop;
private PrepareWatcher prepare_watcher;
public IOLoop ()
{
evloop = Loop.CreateDefaultLoop (0);
prepare_watcher = new PrepareWatcher (evloop, HandlePrepareEvent);
prepare_watcher.Start ();
}
public static IOLoop Instance {
get { return instance; }
}
public Loop EventLoop {
get { return evloop; }
}
public void QueueTransaction (HttpTransaction trans)
{
//
// Since the switch to libev, it seems best to just run them
// for now I'll leave the queueing function call in, so its
// easy to experiment later.
trans.Run ();
}
public void Start ()
{
running = true;
evloop.RunBlocking ();
}
public void Stop ()
{
// This will need to tickle the loop so it wakes up and calls
// the prepare handler.
running = false;
}
private void HandlePrepareEvent (Loop loop, PrepareWatcher watcher, int revents)
{
if (!running) {
loop.Unloop (UnloopType.All);
prepare_watcher.Stop ();
}
}
public void AddTimeout (Timeout timeout)
{
TimerWatcher t = new TimerWatcher (timeout.begin, timeout.span, evloop, HandleTimeout);
t.UserData = timeout;
t.Start ();
}
private void HandleTimeout (Loop loop, TimerWatcher timeout, int revents)
{
Timeout t = (Timeout) timeout.UserData;
AppHost.RunTimeout (t);
if (!t.ShouldContinueToRepeat ())
timeout.Stop ();
}
}
}
| mit | C# |
e1a70d94e7a9a80f652c41cf1ea18ef6e60357dc | Fix test that was impacted by facility code bit shift | jmelosegui/pinvoke,vbfox/pinvoke,AArnott/pinvoke | src/Windows.Core/PInvokeExtensions.cs | src/Windows.Core/PInvokeExtensions.cs | // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
using System.Runtime.InteropServices;
using static PInvoke.HResult.FacilityCode;
/// <summary>
/// Extension methods for commonly defined types.
/// </summary>
public static class PInvokeExtensions
{
/// <summary>
/// Converts an <see cref="NTSTATUS"/> to an <see cref="HResult"/>.
/// </summary>
/// <param name="status">The <see cref="NTSTATUS"/> to convert.</param>
/// <returns>The <see cref="HResult"/>.</returns>
public static HResult ToHResult(this NTSTATUS status)
{
// From winerror.h
// #define HRESULT_FROM_NT(x) ((HRESULT) ((x) | FACILITY_NT_BIT))
return status | (int)FACILITY_NT_BIT;
}
/// <summary>
/// Converts a <see cref="Win32ErrorCode"/> to an <see cref="HResult"/>.
/// </summary>
/// <param name="error">The <see cref="Win32ErrorCode"/> to convert.</param>
/// <returns>The <see cref="HResult"/></returns>
public static HResult ToHResult(this Win32ErrorCode error)
{
// From winerror.h
// (HRESULT)(x) <= 0 ? (HRESULT)(x) : (HRESULT) (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000)
return error <= 0
? (HResult)(int)error
: (HResult)(int)(((int)error & 0x0000ffff) | ((int)FACILITY_WIN32 /*<< 16*/) | 0x80000000);
}
}
}
| // Copyright (c) to owners found in https://github.com/AArnott/pinvoke/blob/master/COPYRIGHT.md. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
namespace PInvoke
{
using System;
using System.Runtime.InteropServices;
using static PInvoke.HResult.FacilityCode;
/// <summary>
/// Extension methods for commonly defined types.
/// </summary>
public static class PInvokeExtensions
{
/// <summary>
/// Converts an <see cref="NTSTATUS"/> to an <see cref="HResult"/>.
/// </summary>
/// <param name="status">The <see cref="NTSTATUS"/> to convert.</param>
/// <returns>The <see cref="HResult"/>.</returns>
public static HResult ToHResult(this NTSTATUS status)
{
// From winerror.h
// #define HRESULT_FROM_NT(x) ((HRESULT) ((x) | FACILITY_NT_BIT))
return status | (int)FACILITY_NT_BIT;
}
/// <summary>
/// Converts a <see cref="Win32ErrorCode"/> to an <see cref="HResult"/>.
/// </summary>
/// <param name="error">The <see cref="Win32ErrorCode"/> to convert.</param>
/// <returns>The <see cref="HResult"/></returns>
public static HResult ToHResult(this Win32ErrorCode error)
{
// From winerror.h
// (HRESULT)(x) <= 0 ? (HRESULT)(x) : (HRESULT) (((x) & 0x0000FFFF) | (FACILITY_WIN32 << 16) | 0x80000000)
return error <= 0
? (HResult)(int)error
: (HResult)(int)(((int)error & 0x0000ffff) | ((int)FACILITY_WIN32 << 16) | 0x80000000);
}
}
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.