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 |
|---|---|---|---|---|---|---|---|---|
6db371bed6a3af588235a4df351ff9c731d7de8e | Update CommentsDisqus.cshtml | Shazwazza/Articulate,readingdancer/Articulate,readingdancer/Articulate,readingdancer/Articulate,Shazwazza/Articulate,Shazwazza/Articulate | src/Articulate.Web/App_Plugins/Articulate/Themes/Mini/Views/Partials/CommentsDisqus.cshtml | src/Articulate.Web/App_Plugins/Articulate/Themes/Mini/Views/Partials/CommentsDisqus.cshtml | @model Articulate.Models.PostModel
<div class="post-comment">
@if (Model.DisqusShortName.IsNullOrWhiteSpace())
{
<p>
<em>
To enable comments sign up for a <a href="http://disqus.com" target="_blank">Disqus</a> account and
enter your Disqus shortname in the Articulate node settings.
</em>
</p>
}
else
{
<div id="disqus_thread">
<script type="text/javascript">
/** ENTER DISQUS SHORTNAME HERE **/
var disqus_shortname = '@Model.DisqusShortName';
/** DO NOT MODIFY BELOW THIS LINE **/
var disqus_identifier = '@Model.GetKey()';
var disqus_url = '@Model.UrlWithDomain()';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>
Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a>
</noscript>
<a href="http://disqus.com" class="dsq-brlink">
comments powered by <span class="logo-disqus">Disqus</span>
</a>
</div>
}
</div>
| @model Articulate.Models.PostModel
<div class="post-comment">
@if (Model.DisqusShortName.IsNullOrWhiteSpace())
{
<p>
<em>
To enable comments sign up for a <a href="http://disqus.com" target="_blank">Disqus</a> account and
enter your Disqus shortname in the Articulate node settings.
</em>
</p>
}
else
{
<div id="disqus_thread">
<script type="text/javascript">
/** ENTER DISQUS SHORTNAME HERE **/
var disqus_shortname = '@Model.DisqusShortName';
/** DO NOT MODIFY BELOW THIS LINE **/
var disqus_identifier = '@Model.Id';
var disqus_url = '@Model.UrlWithDomain()';
(function () {
var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true;
dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
})();
</script>
<noscript>
Please enable JavaScript to view the <a href="http://disqus.com/?ref_noscript">comments powered by Disqus.</a>
</noscript>
<a href="http://disqus.com" class="dsq-brlink">
comments powered by <span class="logo-disqus">Disqus</span>
</a>
</div>
}
</div>
| mit | C# |
d800c2a9ef47e77b4ed417e54f850e7202b100c7 | Add magnet debug output | MorganR/wizards-chess,MorganR/wizards-chess | WizardsChess/WizardsChess/Movement/Drv/MagnetDrv.cs | WizardsChess/WizardsChess/Movement/Drv/MagnetDrv.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Gpio;
namespace WizardsChess.Movement.Drv
{
class MagnetDrv : IMagnetDrv
{
public MagnetDrv(int pinNum)
{
var gpio = GpioController.GetDefault();
pin = gpio.OpenPin(pinNum);
pin.Write(GpioPinValue.Low);
pin.SetDriveMode(GpioPinDriveMode.Output);
pin.Write(GpioPinValue.Low);
}
private GpioPin pin;
public bool IsOn
{
get
{
return pin.Read() == GpioPinValue.High;
}
}
public void TurnOn()
{
pin.Write(GpioPinValue.High);
System.Diagnostics.Debug.WriteLine("Turned the magnet on.");
}
public void TurnOff()
{
pin.Write(GpioPinValue.Low);
System.Diagnostics.Debug.WriteLine("Turned the magnet off.");
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Devices.Gpio;
namespace WizardsChess.Movement.Drv
{
class MagnetDrv : IMagnetDrv
{
public MagnetDrv(int pinNum)
{
var gpio = GpioController.GetDefault();
pin = gpio.OpenPin(pinNum);
pin.Write(GpioPinValue.Low);
pin.SetDriveMode(GpioPinDriveMode.Output);
pin.Write(GpioPinValue.Low);
}
private GpioPin pin;
public bool IsOn
{
get
{
return pin.Read() == GpioPinValue.High;
}
}
public void TurnOn()
{
pin.Write(GpioPinValue.High);
}
public void TurnOff()
{
pin.Write(GpioPinValue.Low);
}
}
}
| apache-2.0 | C# |
9afdbdeb781bf2a81ea13faa058dd19de2803a95 | update controls prop | Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal | Master/Appleseed/Projects/Appleseed.Framework.Web.UI.WebControls/Properties/AssemblyInfo.cs | Master/Appleseed/Projects/Appleseed.Framework.Web.UI.WebControls/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("Appleseed.Framework.Web.UI.WebControls")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : Framework Controls")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed.Framework.Web.UI.WebControls")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[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("9e4ca3a3-9394-41fd-ab23-8ec8c9568e35")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
| 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("Appleseed.Framework.Web.UI.WebControls")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed.Framework.Web.UI.WebControls")]
[assembly: AssemblyCopyright("Copyright © ANANT Corporation 2010-2017")]
[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("9e4ca3a3-9394-41fd-ab23-8ec8c9568e35")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
| apache-2.0 | C# |
4625f6976a71fdad89c19803b9ac44cebc8f5b69 | remove unused variables (#620) | Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms,Hitcents/Xamarin.Forms | Xamarin.Forms.Build.Tasks/MethodBodyExtensions.cs | Xamarin.Forms.Build.Tasks/MethodBodyExtensions.cs | using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using System;
using System.Linq;
using System.Collections.Generic;
namespace Xamarin.Forms.Build.Tasks
{
static class MethodBodyExtensions
{
public static void Optimize(this MethodBody self)
{
if (self == null)
throw new ArgumentNullException(nameof(self));
self.OptimizeLongs();
self.OptimizeStLdLoc();
self.RemoveUnusedLocals();
self.OptimizeMacros();
}
static void ExpandMacro(Instruction instruction, OpCode opcode, object operand)
{
instruction.OpCode = opcode;
instruction.Operand = operand;
}
//this can be removed if/when https://github.com/jbevain/cecil/pull/307 is released in a nuget we consume
static void OptimizeLongs(this MethodBody self)
{
for (var i = 0; i < self.Instructions.Count; i++) {
var instruction = self.Instructions[i];
if (instruction.OpCode.Code != Code.Ldc_I8)
continue;
var l = (long)instruction.Operand;
if (l < int.MinValue || l > int.MaxValue)
continue;
ExpandMacro(instruction, OpCodes.Ldc_I4, unchecked((int)l));
self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8));
}
}
static void OptimizeStLdLoc(this MethodBody self)
{
var method = self.Method;
for (var i = 0; i < self.Instructions.Count; i++) {
var instruction = self.Instructions[i];
if (instruction.OpCode.Code != Code.Stloc)
continue;
if (i + 1 >= self.Instructions.Count)
continue;
var next = self.Instructions[i + 1];
int num = ((VariableDefinition)instruction.Operand).Index;
var vardef = instruction.Operand;
if (next.OpCode.Code != Code.Ldloc || num != ((VariableDefinition)next.Operand).Index)
continue;
ExpandMacro(instruction, OpCodes.Dup, null);
ExpandMacro(next, OpCodes.Stloc, vardef);
}
}
static void RemoveUnusedLocals(this MethodBody self)
{
//Count ldloc for each variable
var ldlocUsed = new List<VariableDefinition>();
foreach (var instruction in self.Instructions) {
if (instruction.OpCode.Code != Code.Ldloc)
continue;
var varDef = (VariableDefinition)instruction.Operand;
if (!ldlocUsed.Contains(varDef))
ldlocUsed.Add(varDef);
}
foreach (var varDef in self.Variables.ToArray()) {
if (ldlocUsed.Contains(varDef))
continue;
//find the Stloc instruction
var instruction = (from instr in self.Instructions where instr.OpCode.Code == Code.Stloc && instr.Operand == varDef select instr).First();
//remove dup/stloc
if (instruction.Previous.OpCode.Code != Code.Dup)
break;
self.Instructions.Remove(instruction.Previous);
self.Instructions.Remove(instruction);
//and remove the variable
self.Variables.Remove(varDef);
}
}
}
} | using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using System;
namespace Xamarin.Forms.Build.Tasks
{
static class MethodBodyExtensions
{
public static void Optimize(this MethodBody self)
{
if (self == null)
throw new ArgumentNullException(nameof(self));
self.OptimizeLongs();
self.OptimizeStLdLoc();
self.OptimizeMacros();
}
static void ExpandMacro(Instruction instruction, OpCode opcode, object operand)
{
instruction.OpCode = opcode;
instruction.Operand = operand;
}
//this can be removed if/when https://github.com/jbevain/cecil/pull/307 is released in a nuget we consume
static void OptimizeLongs(this MethodBody self)
{
var method = self.Method;
for (var i = 0; i < self.Instructions.Count; i++) {
var instruction = self.Instructions[i];
if (instruction.OpCode.Code != Code.Ldc_I8)
continue;
var l = (long)instruction.Operand;
if (l < int.MinValue || l > int.MaxValue)
continue;
ExpandMacro(instruction, OpCodes.Ldc_I4, unchecked((int)l));
self.Instructions.Insert(++i, Instruction.Create(OpCodes.Conv_I8));
}
}
static void OptimizeStLdLoc(this MethodBody self)
{
var method = self.Method;
for (var i = 0; i < self.Instructions.Count; i++) {
var instruction = self.Instructions[i];
if (instruction.OpCode.Code != Code.Stloc)
continue;
if (i + 1 >= self.Instructions.Count)
continue;
var next = self.Instructions[i + 1];
int num = ((VariableDefinition)instruction.Operand).Index;
var vardef = instruction.Operand;
if (next.OpCode.Code != Code.Ldloc || num != ((VariableDefinition)next.Operand).Index)
continue;
ExpandMacro(instruction, OpCodes.Dup, null);
ExpandMacro(next, OpCodes.Stloc, vardef);
}
}
}
} | mit | C# |
8369a163f6adb9bcf91e2a2357386caff1407bd4 | print connection string when generating db | dinazil/blogsamples,dinazil/blogsamples,dinazil/blogsamples | ef_model_db_mismatch/DbGenerator/Program.cs | ef_model_db_mismatch/DbGenerator/Program.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DbGenerator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Rebuilding your DB...");
using (var ctx = new SampleDbContext())
{
Console.WriteLine("Your connection string is: {0}", ctx.Database.Connection.ConnectionString);
Console.WriteLine("Total number of rows in data model: {0}", ctx.Data.Count());
}
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DbGenerator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Rebuilding your DB...");
using (var ctx = new SampleDbContext())
{
Console.WriteLine("Total number of rows in data model: {0}", ctx.Data.Count());
}
}
}
}
| mit | C# |
68fe477b6ea3d6ccbc3fec84b669ed2c7868e23a | Build error resolved | Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist,Promact/trappist | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | Trappist/src/Promact.Trappist.Repository/Questions/QuestionRepository.cs | using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| using System.Collections.Generic;
using Promact.Trappist.DomainModel.Models.Question;
using System.Linq;
using Promact.Trappist.DomainModel.DbContext;
namespace Promact.Trappist.Repository.Questions
{
public class QuestionRepository : IQuestionRespository
{
private readonly TrappistDbContext _dbContext;
public QuestionRepository(TrappistDbContext dbContext)
{
_dbContext = dbContext;
}
/// <summary>
/// Get all questions
/// </summary>
/// <returns>Question list</returns>
public List<SingleMultipleAnswerQuestion> GetAllQuestions()
{
var question = _dbContext.SingleMultipleAnswerQuestion.ToList();
return question;
}
/// <summary>
/// Add single multiple answer question into model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
/// <summary>
/// Add single multiple answer question into SingleMultipleAnswerQuestion model
/// </summary>
/// <param name="singleMultipleAnswerQuestion"></param>
/// <param name="singleMultipleAnswerQuestionOption"></param>
public void AddSingleMultipleAnswerQuestion(SingleMultipleAnswerQuestion singleMultipleAnswerQuestion, SingleMultipleAnswerQuestionOption[] singleMultipleAnswerQuestionOption)
{
_dbContext.SingleMultipleAnswerQuestion.Add(singleMultipleAnswerQuestion);
foreach(SingleMultipleAnswerQuestionOption singleMultipleAnswerQuestionOptionElement in singleMultipleAnswerQuestionOption)
{
singleMultipleAnswerQuestionOptionElement.SingleMultipleAnswerQuestionID = singleMultipleAnswerQuestion.Id;
_dbContext.SingleMultipleAnswerQuestionOption.Add(singleMultipleAnswerQuestionOptionElement);
}
_dbContext.SaveChanges();
}
}
}
| mit | C# |
9f7b65400e1a3ce210eff923063b7c24e9d2956e | Convert bits to bytes. | appharbor/AppHarbor.Web.Security | AppHarbor.Web.Security/SymmetricEncryption.cs | AppHarbor.Web.Security/SymmetricEncryption.cs | using System.IO;
using System.Security.Cryptography;
using System;
namespace AppHarbor.Web.Security
{
public class SymmetricEncryption : Encryption
{
private readonly SymmetricAlgorithm _algorithm;
private readonly byte[] _secretKey;
public SymmetricEncryption(SymmetricAlgorithm algorithm, byte[] secretKey)
{
_algorithm = algorithm;
_secretKey = secretKey;
}
public override void Dispose()
{
_algorithm.Dispose();
}
public override byte[] Encrypt(byte[] valueBytes, byte[] initializationVector = null)
{
bool generateRandomIV = initializationVector == null;
if (generateRandomIV)
{
initializationVector = new byte[_algorithm.BlockSize / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(initializationVector);
}
}
using (var output = new MemoryStream())
{
if (generateRandomIV)
{
output.Write(initializationVector, 0, initializationVector.Length);
}
using (var cryptoOutput = new CryptoStream(output, _algorithm.CreateEncryptor(_secretKey, initializationVector), CryptoStreamMode.Write))
{
cryptoOutput.Write(valueBytes, 0, valueBytes.Length);
}
return output.ToArray();
}
}
public override byte[] Decrypt(byte[] encryptedValue, byte[] initializationVector = null)
{
int dataOffset = 0;
if (initializationVector == null)
{
initializationVector = new byte[_algorithm.BlockSize / 8];
Buffer.BlockCopy(encryptedValue, 0, initializationVector, 0, initializationVector.Length);
dataOffset = initializationVector.Length;
}
using (var output = new MemoryStream())
{
using (var cryptoOutput = new CryptoStream(output, _algorithm.CreateDecryptor(_secretKey, initializationVector), CryptoStreamMode.Write))
{
cryptoOutput.Write(encryptedValue, dataOffset, encryptedValue.Length - dataOffset);
}
return output.ToArray();
}
}
}
public sealed class SymmetricEncryption<T> : SymmetricEncryption where T : SymmetricAlgorithm, new()
{
public SymmetricEncryption(byte[] secretKey)
: base(new T(), secretKey)
{
}
}
}
| using System.IO;
using System.Security.Cryptography;
using System;
namespace AppHarbor.Web.Security
{
public class SymmetricEncryption : Encryption
{
private readonly SymmetricAlgorithm _algorithm;
private readonly byte[] _secretKey;
public SymmetricEncryption(SymmetricAlgorithm algorithm, byte[] secretKey)
{
_algorithm = algorithm;
_secretKey = secretKey;
}
public override void Dispose()
{
_algorithm.Dispose();
}
public override byte[] Encrypt(byte[] valueBytes, byte[] initializationVector = null)
{
bool generateRandomIV = initializationVector == null;
if (generateRandomIV)
{
initializationVector = new byte[_algorithm.BlockSize];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(initializationVector);
}
}
using (var output = new MemoryStream())
{
if (generateRandomIV)
{
output.Write(initializationVector, 0, initializationVector.Length);
}
using (var cryptoOutput = new CryptoStream(output, _algorithm.CreateEncryptor(_secretKey, initializationVector), CryptoStreamMode.Write))
{
cryptoOutput.Write(valueBytes, 0, valueBytes.Length);
}
return output.ToArray();
}
}
public override byte[] Decrypt(byte[] encryptedValue, byte[] initializationVector = null)
{
int dataOffset = 0;
if (initializationVector == null)
{
initializationVector = new byte[_algorithm.BlockSize];
Buffer.BlockCopy(encryptedValue, 0, initializationVector, 0, initializationVector.Length);
dataOffset = initializationVector.Length;
}
using (var output = new MemoryStream())
{
using (var cryptoOutput = new CryptoStream(output, _algorithm.CreateDecryptor(_secretKey, initializationVector), CryptoStreamMode.Write))
{
cryptoOutput.Write(encryptedValue, dataOffset, encryptedValue.Length - dataOffset);
}
return output.ToArray();
}
}
}
public sealed class SymmetricEncryption<T> : SymmetricEncryption where T : SymmetricAlgorithm, new()
{
public SymmetricEncryption(byte[] secretKey)
: base(new T(), secretKey)
{
}
}
}
| mit | C# |
dcc0a6f3b787e63d929249f93606bc330910a0cc | Apply camera offset in all directions | mysticfall/Alensia | Assets/Alensia/Core/Camera/CharacterCamera.cs | Assets/Alensia/Core/Camera/CharacterCamera.cs | using System;
using Alensia.Core.Character;
using Alensia.Core.Common;
using UnityEngine;
using Zenject;
namespace Alensia.Core.Camera
{
public class CharacterCamera : OrbitingCamera, ITrackingCamera<IHumanoid>
{
public override RotationalConstraints RotationalConstraints => _settings.Rotation;
public override DistanceSettings DistanceSettings => _settings.Distance;
public override bool Valid => base.Valid && Target != null;
public IHumanoid Target { get; private set; }
public Transform BodyPart { get; private set; }
public Vector3 CameraOffset { get; set; }
public override Vector3 Pivot => BodyPart.position +
AxisUp * CameraOffset.y +
AxisRight * CameraOffset.x +
AxisForward * CameraOffset.z;
public override Vector3 AxisForward => Target.Transform.forward * -1;
public override Vector3 AxisUp => Target.Transform.up;
private readonly Settings _settings;
public CharacterCamera(UnityEngine.Camera camera) : this(null, camera)
{
}
[Inject]
public CharacterCamera(
[InjectOptional] Settings settings,
UnityEngine.Camera camera) : base(camera)
{
_settings = settings ?? new Settings();
CameraOffset = _settings.CameraOffset;
}
public virtual void Track(IHumanoid target)
{
Target = target;
Distance = DistanceSettings.Default;
BodyPart = Target?.GetBodyPart(HumanBodyBones.Chest);
}
[Serializable]
public class Settings : IEditorSettings
{
public RotationalConstraints Rotation = new RotationalConstraints
{
Down = 80,
Side = 180,
Up = 80
};
public DistanceSettings Distance = new DistanceSettings
{
Minimum = 0.2f,
Maximum = 2f
};
public Vector3 CameraOffset;
}
}
} | using System;
using Alensia.Core.Character;
using Alensia.Core.Common;
using UnityEngine;
using Zenject;
namespace Alensia.Core.Camera
{
public class CharacterCamera : OrbitingCamera, ITrackingCamera<IHumanoid>
{
public override RotationalConstraints RotationalConstraints => _settings.Rotation;
public override DistanceSettings DistanceSettings => _settings.Distance;
public override bool Valid => base.Valid && Target != null;
public IHumanoid Target { get; private set; }
public Transform BodyPart { get; private set; }
public Vector3 CameraOffset { get; set; }
public override Vector3 Pivot => BodyPart.position + AxisUp * CameraOffset.y;
public override Vector3 AxisForward => Target.Transform.forward * -1;
public override Vector3 AxisUp => Target.Transform.up;
private readonly Settings _settings;
public CharacterCamera(UnityEngine.Camera camera) : this(null, camera)
{
}
[Inject]
public CharacterCamera(
[InjectOptional] Settings settings,
UnityEngine.Camera camera) : base(camera)
{
_settings = settings ?? new Settings();
CameraOffset = _settings.CameraOffset;
}
public virtual void Track(IHumanoid target)
{
Target = target;
Distance = DistanceSettings.Default;
BodyPart = Target?.GetBodyPart(HumanBodyBones.Chest);
}
[Serializable]
public class Settings : IEditorSettings
{
public RotationalConstraints Rotation = new RotationalConstraints
{
Down = 80,
Side = 180,
Up = 80
};
public DistanceSettings Distance = new DistanceSettings
{
Minimum = 0.2f,
Maximum = 2f
};
public Vector3 CameraOffset;
}
}
} | apache-2.0 | C# |
50984c87ab46ff9200c463b25dd9332a12b1755a | add ondisable method to yesandinspector component | YesAndGames/YesAndEngine | Assets/Editor/YesAndEditor/YesAndInspector.cs | Assets/Editor/YesAndEditor/YesAndInspector.cs | using UnityEngine;
using UnityEditor;
using System.Collections;
namespace YesAndEditor {
// Yes And editor layer for the object inspector window.
public abstract class YesAndInspector<T> : Editor where T:UnityEngine.Object {
// Layout object for this editor.
protected YesAndLayout Layout;
// The object this editor targets.
protected T selected;
// If set to true, this inspector will draw the default inspector.
private bool drawDefaultInspector = true;
// Initialize this inspector.
protected virtual void OnEnable () {
}
// Deinitialize this inspector.
protected virtual void OnDisable () {
}
// Render the inspector GUI.
public override void OnInspectorGUI () {
Reinitialize ();
if (drawDefaultInspector) {
base.OnInspectorGUI ();
}
}
// Reinitialize this editor.
protected virtual void Reinitialize () {
// Initialize the layout object.
if (Layout == null) {
Layout = new YesAndLayout ();
}
// Cast and cache the target.
if (selected == null) {
selected = target as T;
}
}
// Set the draw default inspector flag.
protected void SetDrawDefaultInspector (bool drawDefault = true) {
drawDefaultInspector = drawDefault;
}
// Returns true if the selected object is in the scene hierarchy.
protected bool InScene () {
// If the selected object is not a MonoBehavior, it can't ever be in the scene.
if (selected as MonoBehaviour == null) {
return false;
}
// Check the prefab type.
PrefabType prefabType = PrefabUtility.GetPrefabType (selected);
switch (prefabType) {
case PrefabType.None:
case PrefabType.PrefabInstance:
case PrefabType.ModelPrefabInstance:
case PrefabType.DisconnectedPrefabInstance:
return true;
default:
return false;
}
}
}
} | using UnityEngine;
using UnityEditor;
using System.Collections;
namespace YesAndEditor {
// Yes And editor layer for the object inspector window.
public abstract class YesAndInspector<T> : Editor where T:UnityEngine.Object {
// Layout object for this editor.
protected YesAndLayout Layout;
// The object this editor targets.
protected T selected;
// If set to true, this inspector will draw the default inspector.
private bool drawDefaultInspector = true;
// Initialize this inspector.
protected virtual void OnEnable () {
}
// Render the inspector GUI.
public override void OnInspectorGUI () {
Reinitialize ();
if (drawDefaultInspector) {
base.OnInspectorGUI ();
}
}
// Reinitialize this editor.
protected virtual void Reinitialize () {
// Initialize the layout object.
if (Layout == null) {
Layout = new YesAndLayout ();
}
// Cast and cache the target.
if (selected == null) {
selected = target as T;
}
}
// Set the draw default inspector flag.
protected void SetDrawDefaultInspector (bool drawDefault = true) {
drawDefaultInspector = drawDefault;
}
// Returns true if the selected object is in the scene hierarchy.
protected bool InScene () {
// If the selected object is not a MonoBehavior, it can't ever be in the scene.
if (selected as MonoBehaviour == null) {
return false;
}
// Check the prefab type.
PrefabType prefabType = PrefabUtility.GetPrefabType (selected);
switch (prefabType) {
case PrefabType.None:
case PrefabType.PrefabInstance:
case PrefabType.ModelPrefabInstance:
case PrefabType.DisconnectedPrefabInstance:
return true;
default:
return false;
}
}
}
} | apache-2.0 | C# |
b2ad2dbf5bf46e43b04c83c2a624082d150286e1 | allow admins to see outcome management | ucdavis/Badges,ucdavis/Badges | Badges/Areas/Admin/Views/Landing/Index.cshtml | Badges/Areas/Admin/Views/Landing/Index.cshtml | @model dynamic
@{
ViewBag.Title = "Admin Homepage";
}
<h2>Admin Homepage</h2>
<ul class="nav nav-pills nav-stacked">
<li>@Html.ActionLink("Manage Titles", "Index", "Title")</li>
<li>@Html.ActionLink("Manage Organizations", "Index", "Organization")</li>
<li>@Html.ActionLink("Manage Instructors", "Index", "Instructor")</li>
<li>@Html.ActionLink("Manage Experience Types", "Index", "ExperienceType")</li>
<li>@Html.ActionLink("Manage Outcomes", "Index", "Outcome")</li>
<li>@Html.ActionLink("Manage Badge Categories", "Index", "BadgeCategory")</li>
<li>@Html.ActionLink("Manage Badge Requests", "Index", "BadgeRequest")</li>
<li>@Html.ActionLink("Manage Badge Submissions", "Index", "BadgeSubmission")</li>
</ul> | @model dynamic
@{
ViewBag.Title = "Admin Homepage";
}
<h2>Admin Homepage</h2>
<ul class="nav nav-pills nav-stacked">
<li>@Html.ActionLink("Manage Titles", "Index", "Title")</li>
<li>@Html.ActionLink("Manage Organizations", "Index", "Organization")</li>
<li>@Html.ActionLink("Manage Instructors", "Index", "Instructor")</li>
<li>@Html.ActionLink("Manage Experience Types", "Index", "ExperienceType")</li>
<li>@Html.ActionLink("Manage Badge Categories", "Index", "BadgeCategory")</li>
<li>@Html.ActionLink("Manage Badge Requests", "Index", "BadgeRequest")</li>
<li>@Html.ActionLink("Manage Badge Submissions", "Index", "BadgeSubmission")</li>
</ul> | mpl-2.0 | C# |
75c2e9ad4fa8cd1160d3d49cd4b0d4b34c354473 | fix for cake.git version | bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity,bugsnag/bugsnag-unity | build.cake | build.cake | #addin nuget:?package=Cake.Git&version=1.1.0
#tool "nuget:?package=NUnit.ConsoleRunner"
var target = Argument("target", "Default");
var solution = File("./BugsnagUnity.sln");
var configuration = Argument("configuration", "Release");
var project = File("./src/BugsnagUnity/BugsnagUnity.csproj");
var version = "5.4.2";
Task("Restore-NuGet-Packages")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
MSBuild(solution, settings =>
settings
.SetVerbosity(Verbosity.Minimal)
.WithProperty("Version", version)
.SetConfiguration(configuration));
});
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll");
NUnit3(assemblies);
});
Task("Default")
.IsDependentOn("Test");
RunTarget(target);
| #addin nuget:?package=Cake.Git
#tool "nuget:?package=NUnit.ConsoleRunner"
var target = Argument("target", "Default");
var solution = File("./BugsnagUnity.sln");
var configuration = Argument("configuration", "Release");
var project = File("./src/BugsnagUnity/BugsnagUnity.csproj");
var version = "5.4.2";
Task("Restore-NuGet-Packages")
.Does(() => NuGetRestore(solution));
Task("Build")
.IsDependentOn("Restore-NuGet-Packages")
.Does(() => {
MSBuild(solution, settings =>
settings
.SetVerbosity(Verbosity.Minimal)
.WithProperty("Version", version)
.SetConfiguration(configuration));
});
Task("Test")
.IsDependentOn("Build")
.Does(() => {
var assemblies = GetFiles($"./tests/**/bin/{configuration}/**/*.Tests.dll");
NUnit3(assemblies);
});
Task("Default")
.IsDependentOn("Test");
RunTarget(target);
| mit | C# |
59d583416d8b667b7aa0c0ddc98535b8be830f37 | Add GetPosition test | PawelStroinski/StreamReaderSeeker,PawelStroinski/StreamReaderSeeker | Test/StreamReaderSeekerTest.cs | Test/StreamReaderSeekerTest.cs | using System.IO;
using System.Reflection;
using NUnit.Framework;
namespace StreamUtils
{
public class StreamReaderSeekerTest
{
[Test]
public void DiscardsBufferedDataWhenCharacterPositionIsNegative()
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("StreamUtils.input");
var reader = new StreamReader(stream);
var buffer = new char[30];
reader.Seek(new StreamReaderSeeker.Position(1158, -431));
reader.Read(buffer, 0, buffer.Length);
var expected = "5350240105107934054\r\n210821277";
var actual = new string(buffer);
Assert.AreEqual(expected, actual);
}
[Test]
public void GetPosition()
{
var reader = new StreamReader(new MemoryStream());
var actual = reader.GetPosition();
Assert.AreEqual("streamPosition=0, characterPosition=0", actual.ToString());
}
}
}
| using System.IO;
using System.Reflection;
using NUnit.Framework;
namespace StreamUtils
{
public class StreamReaderSeekerTest
{
[Test]
public void DiscardsBufferedDataWhenCharacterPositionIsNegative()
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("StreamUtils.input");
var reader = new StreamReader(stream);
var buffer = new char[30];
reader.Seek(new StreamReaderSeeker.Position(1158, -431));
reader.Read(buffer, 0, buffer.Length);
var expected = "5350240105107934054\r\n210821277";
var actual = new string(buffer);
Assert.AreEqual(expected, actual);
}
}
}
| mit | C# |
108e972435e316ff0f867b6c832662f1bd735c5a | bump version | nosami/XSTerm,nosami/XSTerm,nosami/XSTerm | XSTerm/Properties/AddinInfo.cs | XSTerm/Properties/AddinInfo.cs | using System;
using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
"XSTerm",
Namespace = "XSTerm",
Version = "1.0.2"
)]
[assembly: AddinName("XSTerm")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("XSTerm")]
[assembly: AddinAuthor("jason")]
| using System;
using Mono.Addins;
using Mono.Addins.Description;
[assembly: Addin(
"XSTerm",
Namespace = "XSTerm",
Version = "1.0.1"
)]
[assembly: AddinName("XSTerm")]
[assembly: AddinCategory("IDE extensions")]
[assembly: AddinDescription("XSTerm")]
[assembly: AddinAuthor("jason")]
| mit | C# |
1a024787a94e307713a3cfc8b8656b62871779c7 | Test of CD | mswietlicki/Oopm,mswietlicki/Oopm | Oopm.Web/Views/Home/Index.cshtml | Oopm.Web/Views/Home/Index.cshtml | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you 565656565 a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | @{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
<h1>ASP.NET</h1>
<p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS and JavaScript.</p>
<p><a href="http://asp.net" class="btn btn-primary btn-lg">Learn more »</a></p>
</div>
<div class="row">
<div class="col-md-4">
<h2>Getting started</h2>
<p>
ASP.NET MVC gives you a powerful, patterns-based way to build dynamic websites that
enables a clean separation of concerns and gives you full control over markup
for enjoyable, agile development.
</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301865">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Get more libraries</h2>
<p>NuGet is a free Visual Studio extension that makes it easy to add, remove, and update libraries and tools in Visual Studio projects.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301866">Learn more »</a></p>
</div>
<div class="col-md-4">
<h2>Web Hosting</h2>
<p>You can easily find a web hosting company that offers the right mix of features and price for your applications.</p>
<p><a class="btn btn-default" href="http://go.microsoft.com/fwlink/?LinkId=301867">Learn more »</a></p>
</div>
</div> | mit | C# |
d4da5ceaa1695caa25534835785e0b324138806a | add note | StefanoFiumara/Harry-Potter-Unity | Assets/Scripts/HarryPotterUnity/Enums/Enums.cs | Assets/Scripts/HarryPotterUnity/Enums/Enums.cs | using System;
namespace HarryPotterUnity.Enums
{
public enum State
{
InDeck, InHand, InPlay, Discarded
}
public enum Type
{
Lesson, Creature, Spell, Item, Location, Match, Adventure, Character
}
//TODO: Add [Flags] attribute and proper values
public enum Tag
{
Unique, Healing, Wand, Cauldron, Broom
}
public enum Rarity
{
Common, Uncommon, Rare, UltraRare
}
public enum LessonTypes
{
Creatures, Charms, Transfiguration, Potions, Quidditch
}
public enum ClassificationTypes
{
CareOfMagicalCreatures, Charms, Transfiguration, Potions, Quidditch,
Lesson,
Character,
Adventure
}
public enum FlipState
{
FaceUp, FaceDown
}
public enum TweenRotationType
{
NoRotate, Rotate90, Rotate180
}
public static class EnumExtensions
{
public static ClassificationTypes ToClassification(this LessonTypes type)
{
switch (type)
{
case LessonTypes.Creatures: return ClassificationTypes.CareOfMagicalCreatures;
case LessonTypes.Charms: return ClassificationTypes.Charms;
case LessonTypes.Transfiguration: return ClassificationTypes.Transfiguration;
case LessonTypes.Quidditch: return ClassificationTypes.Quidditch;
case LessonTypes.Potions: return ClassificationTypes.Potions;
default:
throw new ArgumentException("Unable to map lesson type");
}
}
}
}
| using System;
namespace HarryPotterUnity.Enums
{
public enum State
{
InDeck, InHand, InPlay, Discarded
}
public enum Type
{
Lesson, Creature, Spell, Item, Location, Match, Adventure, Character
}
public enum Tag
{
Unique, Healing, Wand, Cauldron, Broom
}
public enum Rarity
{
Common, Uncommon, Rare, UltraRare
}
public enum LessonTypes
{
Creatures, Charms, Transfiguration, Potions, Quidditch
}
public enum ClassificationTypes
{
CareOfMagicalCreatures, Charms, Transfiguration, Potions, Quidditch,
Lesson,
Character,
Adventure
}
public enum FlipState
{
FaceUp, FaceDown
}
public enum TweenRotationType
{
NoRotate, Rotate90, Rotate180
}
public static class EnumExtensions
{
public static ClassificationTypes ToClassification(this LessonTypes type)
{
switch (type)
{
case LessonTypes.Creatures: return ClassificationTypes.CareOfMagicalCreatures;
case LessonTypes.Charms: return ClassificationTypes.Charms;
case LessonTypes.Transfiguration: return ClassificationTypes.Transfiguration;
case LessonTypes.Quidditch: return ClassificationTypes.Quidditch;
case LessonTypes.Potions: return ClassificationTypes.Potions;
default:
throw new ArgumentException("Unable to map lesson type");
}
}
}
}
| mit | C# |
ab7ed721667f1126bcf4e61c894836b4ca997b37 | Update AzureClient.cs | jonathanpeppers/Xamarin.InAppPurchasing,jonathanpeppers/Xamarin.InAppPurchasing | Xamarin.InAppPurchasing/Models/AzureClient.cs | Xamarin.InAppPurchasing/Models/AzureClient.cs | using System;
using System.Threading.Tasks;
using System.Net.Http;
namespace Xamarin.InAppPurchasing
{
public class AzureClient
{
private const string BaseUrl = "https://YOUR_DOMAIN.azurewebsites.net/api/";
private readonly HttpClient _client = new HttpClient();
public async Task Verify(AppleReceipt receipt)
{
var content = new JsonContent(receipt);
var response = await _client.PostAsync(BaseUrl + "ios?code=YOUR_CODE_HERE", content);
response.EnsureSuccessStatusCode();
}
}
}
| using System;
using System.Threading.Tasks;
using System.Net.Http;
namespace Xamarin.InAppPurchasing
{
public class AzureClient
{
private const string BaseUrl = "https://xamarin-iap.azurewebsites.net/api/";
private readonly HttpClient _client = new HttpClient();
public async Task Verify(AppleReceipt receipt)
{
var content = new JsonContent(receipt);
var response = await _client.PostAsync(BaseUrl + "ios?code=KE5uZhyDC6bsu4eJuBMBtPpbBOLE3NYmpDUZOhdQQfCeCoSOn8t8iw==", content);
response.EnsureSuccessStatusCode();
}
}
}
| mit | C# |
bb9be865ef5eb3059bd96aa8caf50e0a51a54b75 | Replace tournament routes with generic {year}/{discipline}/{slug} | croquet-australia/website-application,croquet-australia/website-application,croquet-australia/croquet-australia-website,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/website-application,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia.com.au,croquet-australia/croquet-australia-website,croquet-australia/croquet-australia-website | source/CroquetAustralia.Website/app/tournaments/TournamentsController.cs | source/CroquetAustralia.Website/app/tournaments/TournamentsController.cs | using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using CroquetAustralia.Website.App.Infrastructure;
namespace CroquetAustralia.Website.App.tournaments
{
[RoutePrefix("tournaments")]
public class TournamentsController : ApplicationController
{
private readonly WebApi _webApi;
public TournamentsController(WebApi webApi)
{
_webApi = webApi;
}
[Route("{year}/{discipline}/{slug}")]
public ViewResult Tournament()
{
return View("tournament");
}
[Route("deposited")]
public async Task<ViewResult> Deposited(Guid id)
{
await _webApi.PostAsync("/tournament-entry/payment-received", new {entityId = id, paymentMethod = "EFT"});
return View("deposited");
}
}
} | using System;
using System.Threading.Tasks;
using System.Web.Mvc;
using CroquetAustralia.Website.App.Infrastructure;
namespace CroquetAustralia.Website.App.tournaments
{
[RoutePrefix("tournaments")]
public class TournamentsController : ApplicationController
{
private readonly WebApi _webApi;
public TournamentsController(WebApi webApi)
{
_webApi = webApi;
}
[Route("2016/ac/mens-open")]
public ViewResult Mens_AC_Open_2016()
{
return View("tournament");
}
[Route("2016/ac/womens-open")]
public ViewResult Womens_AC_Open_2016()
{
return View("tournament");
}
[Route("2016/gc/open-doubles")]
public ViewResult GC_Open_Doubles_2016()
{
return View("tournament");
}
[Route("2016/gc/open-singles")]
public ViewResult GC_Open_Singles_2016()
{
return View("tournament");
}
[Route("deposited")]
public async Task<ViewResult> Deposited(Guid id)
{
await _webApi.PostAsync("/tournament-entry/payment-received", new {entityId = id, paymentMethod = "EFT"});
return View("deposited");
}
}
} | mit | C# |
8b7e2d31c1d0b80dc80cca140b9a6fb98cd60de9 | Update IDragInfoBuilder.cs | punker76/gong-wpf-dragdrop | src/GongSolutions.WPF.DragDrop/IDragInfoBuilder.cs | src/GongSolutions.WPF.DragDrop/IDragInfoBuilder.cs | using System.Windows.Input;
namespace GongSolutions.Wpf.DragDrop
{
/// <summary>
/// Interface implemented by Drag Info Builders.
/// It enables custom construction of DragInfo objects to support 3rd party controls like DevExpress, Telerik, etc.
/// </summary>
public interface IDragInfoBuilder
{
/// <summary>
/// Creates a drag info object from <see cref="MouseButtonEventArgs"/>.
/// </summary>
///
/// <param name="sender">
/// The sender of the mouse event that initiated the drag.
/// </param>
///
/// <param name="e">
/// The mouse event that initiated the drag.
/// </param>
DragInfo CreateDragInfo(object sender, MouseButtonEventArgs e);
/// <summary>
/// Creates a drag info object from <see cref="TouchEventArgs"/>.
/// </summary>
///
/// <param name="sender">
/// The sender of the touch event that initiated the drag.
/// </param>
///
/// <param name="e">
/// The touch event that initiated the drag.
/// </param>
DragInfo CreateDragInfo(object sender, TouchEventArgs e);
}
} | using System.Windows.Input;
namespace GongSolutions.Wpf.DragDrop
{
/// <summary>
/// Interface implemented by Drag Info Builders.
/// It enables custom construction of DragInfo objects from 3rd party controls like DevExpress, Telerik, etc.
/// </summary>
public interface IDragInfoBuilder
{
/// <summary>
/// Creates a drag info object from <see cref="MouseButtonEventArgs"/>.
/// </summary>
///
/// <param name="sender">
/// The sender of the mouse event that initiated the drag.
/// </param>
///
/// <param name="e">
/// The mouse event that initiated the drag.
/// </param>
DragInfo CreateDragInfo(object sender, MouseButtonEventArgs e);
/// <summary>
/// Creates a drag info object from <see cref="TouchEventArgs"/>.
/// </summary>
///
/// <param name="sender">
/// The sender of the touch event that initiated the drag.
/// </param>
///
/// <param name="e">
/// The touch event that initiated the drag.
/// </param>
DragInfo CreateDragInfo(object sender, TouchEventArgs e);
}
} | bsd-3-clause | C# |
69278192fc85f46fed56f3b1669ad18fc9e037cb | Make code more compact | nikeee/HolzShots | src/HolzShots.Windows/Forms/Controls/PluginItem.cs | src/HolzShots.Windows/Forms/Controls/PluginItem.cs | using System.ComponentModel;
using System.Windows.Forms;
using HolzShots.Composition;
using Semver;
using System.Diagnostics;
namespace HolzShots.Windows.Forms.Controls
{
public partial class PluginItem : UserControl
{
private IPluginMetadata _model = new DummyMetadata();
public PluginItem() => InitializeComponent();
[Bindable(true)]
public IPluginMetadata DataSource
{
get => _model;
set
{
_model = value ?? new DummyMetadata();
modelBindingSource.DataSource = _model;
}
}
private void pluginSettings_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// TODO
}
private void authorWebSite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => OpenUrlIfPresent(_model?.Website);
private void reportBug_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) => OpenUrlIfPresent(_model?.BugsUrl);
private static void OpenUrlIfPresent(string /* ? */ url)
{
if (url == null)
return;
try
{
Process.Start(url);
}
catch
{
Trace.WriteLine("Failed to open url");
}
}
private class DummyMetadata : IPluginMetadata
{
public string Name => "Cool plugin";
public string Author => "Even cooler author";
public SemVersion Version => new SemVersion(1);
public string Website => "https://holzshots.net";
public string BugsUrl => "https://github.com/nikeee/holzshots/issues";
public string Contact => "https://github.com/nikeee/holzshots/issues";
public string Description => "A very cool plugin";
}
}
}
| using System.ComponentModel;
using System.Windows.Forms;
using HolzShots.Composition;
using Semver;
using System.Diagnostics;
namespace HolzShots.Windows.Forms.Controls
{
public partial class PluginItem : UserControl
{
private IPluginMetadata _model = new DummyMetadata();
public PluginItem()
{
InitializeComponent();
}
[Bindable(true)]
public IPluginMetadata DataSource
{
get => _model;
set
{
_model = value ?? new DummyMetadata();
modelBindingSource.DataSource = value;
}
}
private void pluginSettings_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
// TODO
}
private void authorWebSite_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var website = _model?.Website;
if (website != null)
OpenUrl(website);
}
private void reportBug_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
var bugsUrl = _model?.BugsUrl;
if (bugsUrl != null)
OpenUrl(bugsUrl);
}
private static void OpenUrl(string url)
{
try
{
Process.Start(url);
}
catch
{
Trace.WriteLine("Failed to open url");
}
}
private class DummyMetadata : IPluginMetadata
{
public string Name => "Cool plugin";
public string Author => "Even cooler author";
public SemVersion Version => new SemVersion(1);
public string Website => "https://holzshots.net";
public string BugsUrl => "https://github.com/nikeee/holzshots/issues";
public string Contact => "https://github.com/nikeee/holzshots/issues";
public string Description => "A very cool plugin";
}
}
}
| agpl-3.0 | C# |
204a720a156f466a5c2f7daf78106e86b132d016 | Fix minor typo | Azure/azure-webjobs-sdk,Azure/azure-webjobs-sdk | src/Microsoft.Azure.WebJobs.Extensions.Storage/StorageAccountProvider.cs | src/Microsoft.Azure.WebJobs.Extensions.Storage/StorageAccountProvider.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Abstraction to provide storage accounts from the connection names.
/// This gets the storage account name via the binding attribute's <see cref="IConnectionProvider.Connection"/>
/// property.
/// If the connection is not specified on the attribute, it uses a default account.
/// </summary>
public class StorageAccountProvider
{
private readonly IConfiguration _configuration;
public StorageAccountProvider(IConfiguration configuration)
{
_configuration = configuration;
}
public StorageAccount Get(string name, INameResolver resolver)
{
var resolvedName = resolver.ResolveWholeString(name);
return this.Get(resolvedName);
}
public virtual StorageAccount Get(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
name = ConnectionStringNames.Storage; // default
}
// $$$ Where does validation happen?
string connectionString = _configuration.GetWebJobsConnectionString(name);
if (connectionString == null)
{
// Not found
throw new InvalidOperationException($"Storage account connection string '{name}' does not exist. Make sure that it is defined in application settings.");
}
return StorageAccount.NewFromConnectionString(connectionString);
}
/// <summary>
/// The host account is for internal storage mechanisms like load balancer queuing.
/// </summary>
/// <returns></returns>
public virtual StorageAccount GetHost()
{
return this.Get(null);
}
}
}
| // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Azure.WebJobs
{
/// <summary>
/// Abstraction to provide storage accounts from the connection names.
/// This gets the storage account name via the binding attribute's <see cref="IConnectionProvider.Connection"/>
/// property.
/// If the connection is not specified on the attribute, it uses a default account.
/// </summary>
public class StorageAccountProvider
{
private readonly IConfiguration _configuration;
public StorageAccountProvider(IConfiguration configuration)
{
_configuration = configuration;
}
public StorageAccount Get(string name, INameResolver resolver)
{
var resolvedName = resolver.ResolveWholeString(name);
return this.Get(resolvedName);
}
public virtual StorageAccount Get(string name)
{
if (string.IsNullOrWhiteSpace(name))
{
name = ConnectionStringNames.Storage; // default
}
// $$$ Where does validation happen?
string connectionString = _configuration.GetWebJobsConnectionString(name);
if (connectionString == null)
{
// Not found
throw new InvalidOperationException($"Storage account connection string '{name}' does not exists. Make sure that it is defined in application settings.");
}
return StorageAccount.NewFromConnectionString(connectionString);
}
/// <summary>
/// The host account is for internal storage mechanisms like load balancer queuing.
/// </summary>
/// <returns></returns>
public virtual StorageAccount GetHost()
{
return this.Get(null);
}
}
} | mit | C# |
5c712fff821de6f25650bdea628264b9f1121736 | check to see if chatClient exists in the lobby and show login window if it doesn't | Necromunger/unitystation,fomalsd/unitystation,krille90/unitystation,Necromunger/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,Necromunger/unitystation,fomalsd/unitystation,fomalsd/unitystation,Necromunger/unitystation,Lancemaker/unitystation,MrLeebo/unitystation,MrLeebo/unitystation,fomalsd/unitystation,fomalsd/unitystation,MrLeebo/unitystation,fomalsd/unitystation,Necromunger/unitystation,MrLeebo/unitystation,Necromunger/unitystation,Lancemaker/unitystation,krille90/unitystation,krille90/unitystation,fomalsd/unitystation | Assets/scripts/UI/ControlDisplays.cs | Assets/scripts/UI/ControlDisplays.cs | using UnityEngine;
using System.Collections;
namespace UI
{
public class ControlDisplays : MonoBehaviour {
public UIManager parentScript;
public GameObject logInWindow;
public GameObject backGround;
public GameObject[] UIObjs;
//Temp buttons
public GameObject tempSceneButton;
public GameObject tempMenuButton;
public void ResetUI(){
//This empties all slots and returns everything back to default values, or should
//TODO: continue to update this when developing the UI. This is messy ATM
if (parentScript.hands.rightSlot.isFull) {
Destroy (parentScript.hands.rightSlot.inHandItem);
}
if (parentScript.hands.leftSlot.isFull) {
Destroy (parentScript.hands.leftSlot.inHandItem);
}
if (parentScript.bottomControl.storage01Slot.isFull) {
Destroy (parentScript.bottomControl.storage01Slot.inHandItem);
}
if (parentScript.bottomControl.storage02Slot.isFull) {
Destroy (parentScript.bottomControl.storage02Slot.inHandItem);
}
}
public void SetScreenForLobby(){
SoundManager.control.StopAmbient ();
SoundManager.control.PlayRandomTrack ();
ResetUI (); //Make sure UI is back to default for next play
foreach (GameObject obj in UIObjs) {
obj.SetActive (false);
}
backGround.SetActive (true);
if (parentScript.chatControl.chatClient != null) {
if (parentScript.chatControl.chatClient.CanChat) {
logInWindow.SetActive (false);
} else {
logInWindow.SetActive (true);
}
} else {
logInWindow.SetActive (true);
}
//TODO remove the temp button when scene transitions completed
tempSceneButton.SetActive (false);
tempMenuButton.SetActive (false);
}
public void SetScreenForGame(){
foreach (GameObject obj in UIObjs) {
obj.SetActive (true);
}
backGround.SetActive (false);
logInWindow.SetActive (false);
SoundManager.control.StopMusic ();
//TODO random ambient
SoundManager.control.PlayVarAmbient (0);
//TODO remove the temp button when scene transitions completed
tempSceneButton.SetActive (false);
tempMenuButton.SetActive (true);
}
}
}
| using UnityEngine;
using System.Collections;
namespace UI
{
public class ControlDisplays : MonoBehaviour {
public UIManager parentScript;
public GameObject logInWindow;
public GameObject backGround;
public GameObject[] UIObjs;
//Temp buttons
public GameObject tempSceneButton;
public GameObject tempMenuButton;
public void ResetUI(){
//This empties all slots and returns everything back to default values, or should
//TODO: continue to update this when developing the UI. This is messy ATM
if (parentScript.hands.rightSlot.isFull) {
Destroy (parentScript.hands.rightSlot.inHandItem);
}
if (parentScript.hands.leftSlot.isFull) {
Destroy (parentScript.hands.leftSlot.inHandItem);
}
if (parentScript.bottomControl.storage01Slot.isFull) {
Destroy (parentScript.bottomControl.storage01Slot.inHandItem);
}
if (parentScript.bottomControl.storage02Slot.isFull) {
Destroy (parentScript.bottomControl.storage02Slot.inHandItem);
}
}
public void SetScreenForLobby(){
SoundManager.control.StopAmbient ();
SoundManager.control.PlayRandomTrack ();
ResetUI (); //Make sure UI is back to default for next play
foreach (GameObject obj in UIObjs) {
obj.SetActive (false);
}
backGround.SetActive (true);
if (parentScript.chatControl.chatClient.CanChat) {
logInWindow.SetActive (false);
} else {
logInWindow.SetActive (true);
}
//TODO remove the temp button when scene transitions completed
tempSceneButton.SetActive (false);
tempMenuButton.SetActive (false);
}
public void SetScreenForGame(){
foreach (GameObject obj in UIObjs) {
obj.SetActive (true);
}
backGround.SetActive (false);
logInWindow.SetActive (false);
SoundManager.control.StopMusic ();
//TODO random ambient
SoundManager.control.PlayVarAmbient (0);
//TODO remove the temp button when scene transitions completed
tempSceneButton.SetActive (false);
tempMenuButton.SetActive (true);
}
}
}
| agpl-3.0 | C# |
72fb426c98f30415ac44c24e6c535b0c0960f5de | Fix initializing the auth view' | mpOzelot/Unity,mpOzelot/Unity,github-for-unity/Unity,github-for-unity/Unity,github-for-unity/Unity | src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationWindow.cs | src/UnityExtension/Assets/Editor/GitHub.Unity/UI/AuthenticationWindow.cs | using System;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
class AuthenticationWindow : BaseWindow
{
private const string Title = "Sign in";
[SerializeField] private AuthenticationView authView;
[MenuItem("GitHub/Authenticate")]
public static void Launch()
{
Open();
}
public static IView Open(Action<bool> onClose = null)
{
AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>();
if (onClose != null)
authWindow.OnClose += onClose;
authWindow.minSize = new Vector2(290, 290);
authWindow.Show();
return authWindow;
}
public override void OnGUI()
{
if (authView == null)
{
CreateViews();
}
authView.OnGUI();
}
public override void Refresh()
{
authView.Refresh();
}
public override void OnEnable()
{
// Set window title
titleContent = new GUIContent(Title, Styles.SmallLogo);
Utility.UnregisterReadyCallback(CreateViews);
Utility.RegisterReadyCallback(CreateViews);
Utility.UnregisterReadyCallback(ShowActiveView);
Utility.RegisterReadyCallback(ShowActiveView);
}
private void CreateViews()
{
if (authView == null)
authView = new AuthenticationView();
Initialize(EntryPoint.ApplicationManager);
authView.InitializeView(this);
}
private void ShowActiveView()
{
authView.OnShow();
Refresh();
}
public override void Finish(bool result)
{
Close();
base.Finish(result);
}
}
}
| using System;
using UnityEditor;
using UnityEngine;
namespace GitHub.Unity
{
[Serializable]
class AuthenticationWindow : BaseWindow
{
private const string Title = "Sign in";
[SerializeField] private AuthenticationView authView;
[MenuItem("GitHub/Authenticate")]
public static void Launch()
{
Open();
}
public static IView Open(Action<bool> onClose = null)
{
AuthenticationWindow authWindow = GetWindow<AuthenticationWindow>();
if (onClose != null)
authWindow.OnClose += onClose;
authWindow.minSize = new Vector2(290, 290);
authWindow.Show();
return authWindow;
}
public override void OnGUI()
{
authView.OnGUI();
}
public override void Refresh()
{
authView.Refresh();
}
public override void OnEnable()
{
// Set window title
titleContent = new GUIContent(Title, Styles.SmallLogo);
Utility.UnregisterReadyCallback(CreateViews);
Utility.RegisterReadyCallback(CreateViews);
Utility.UnregisterReadyCallback(ShowActiveView);
Utility.RegisterReadyCallback(ShowActiveView);
}
private void CreateViews()
{
if (authView == null)
authView = new AuthenticationView();
Initialize(EntryPoint.ApplicationManager);
authView.InitializeView(this);
}
private void ShowActiveView()
{
authView.OnShow();
Refresh();
}
public override void Finish(bool result)
{
Close();
base.Finish(result);
}
}
}
| mit | C# |
7daff28e6884cc6d5f1e7146d1b0c9f1c18734fe | Switch back to tabbed winforms example being the default (maybe one day create a method to switch between the two) | joshvera/CefSharp,jamespearce2006/CefSharp,yoder/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,wangzheng888520/CefSharp,VioletLife/CefSharp,Livit/CefSharp,illfang/CefSharp,joshvera/CefSharp,NumbersInternational/CefSharp,Haraguroicha/CefSharp,illfang/CefSharp,VioletLife/CefSharp,rover886/CefSharp,twxstar/CefSharp,gregmartinhtc/CefSharp,haozhouxu/CefSharp,jamespearce2006/CefSharp,VioletLife/CefSharp,yoder/CefSharp,windygu/CefSharp,yoder/CefSharp,dga711/CefSharp,haozhouxu/CefSharp,haozhouxu/CefSharp,wangzheng888520/CefSharp,Haraguroicha/CefSharp,ruisebastiao/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,twxstar/CefSharp,windygu/CefSharp,joshvera/CefSharp,NumbersInternational/CefSharp,dga711/CefSharp,gregmartinhtc/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,ITGlobal/CefSharp,battewr/CefSharp,jamespearce2006/CefSharp,rover886/CefSharp,wangzheng888520/CefSharp,yoder/CefSharp,rlmcneary2/CefSharp,illfang/CefSharp,gregmartinhtc/CefSharp,rover886/CefSharp,zhangjingpu/CefSharp,rover886/CefSharp,illfang/CefSharp,NumbersInternational/CefSharp,battewr/CefSharp,twxstar/CefSharp,NumbersInternational/CefSharp,gregmartinhtc/CefSharp,rlmcneary2/CefSharp,Haraguroicha/CefSharp,ruisebastiao/CefSharp,dga711/CefSharp,jamespearce2006/CefSharp,joshvera/CefSharp,zhangjingpu/CefSharp,rover886/CefSharp,ruisebastiao/CefSharp,windygu/CefSharp,jamespearce2006/CefSharp,AJDev77/CefSharp,ITGlobal/CefSharp,Livit/CefSharp,wangzheng888520/CefSharp,AJDev77/CefSharp,Livit/CefSharp,windygu/CefSharp,Haraguroicha/CefSharp,AJDev77/CefSharp,zhangjingpu/CefSharp,haozhouxu/CefSharp,twxstar/CefSharp,AJDev77/CefSharp,Haraguroicha/CefSharp,battewr/CefSharp,rlmcneary2/CefSharp,zhangjingpu/CefSharp,VioletLife/CefSharp,ITGlobal/CefSharp | CefSharp.WinForms.Example/Program.cs | CefSharp.WinForms.Example/Program.cs | // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Forms;
using CefSharp.Example;
using CefSharp.WinForms.Example.Minimal;
namespace CefSharp.WinForms.Example
{
class Program
{
[STAThread]
static void Main()
{
CefExample.Init();
var browser = new BrowserForm();
//var browser = new SimpleBrowserForm();
Application.Run(browser);
}
}
}
| // Copyright © 2010-2014 The CefSharp Authors. All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
using System;
using System.Windows.Forms;
using CefSharp.Example;
using CefSharp.WinForms.Example.Minimal;
namespace CefSharp.WinForms.Example
{
class Program
{
[STAThread]
static void Main()
{
CefExample.Init();
//var browser = new BrowserForm();
var browser = new SimpleBrowserForm();
Application.Run(browser);
}
}
}
| bsd-3-clause | C# |
a03758e06aa3d7da643dc5b77c1d2451557f94d3 | increase log buffer | kreeben/resin,kreeben/resin | src/Sir/Logging.cs | src/Sir/Logging.cs | using System;
using System.IO;
namespace Sir
{
public static class Logging
{
private static TextWriter Writer;
private static object Sync = new object();
public static bool SendToConsole { get; set; }
private static void Write(object message)
{
var writer = GetWriter();
writer.WriteLine(message);
writer.Flush();
if (SendToConsole)
{
Console.WriteLine(message);
}
}
public static void Log(object message)
{
Write(string.Format("{0}\t{1}", DateTime.Now, message));
}
public static void Log(string format, params object[] args)
{
Write(string.Format(DateTime.Now + " " + format, args));
}
private static TextWriter GetWriter()
{
if (Writer == null)
{
lock (Sync)
{
if (Writer == null)
{
var logDir = Path.Combine(Directory.GetCurrentDirectory(), "log");
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
var fn = Path.Combine(logDir, "sir.log");
var stream = Stream.Synchronized(new FileStream(fn, FileMode.Append, FileAccess.Write, FileShare.ReadWrite, 8*4096));
Writer = TextWriter.Synchronized(new StreamWriter(stream));
return Writer;
}
}
}
return Writer;
}
}
}
| using System;
using System.IO;
namespace Sir
{
public static class Logging
{
private static TextWriter Writer;
private static object Sync = new object();
public static bool SendToConsole { get; set; }
private static void Write(object message)
{
var writer = GetWriter();
writer.WriteLine(message);
writer.Flush();
if (SendToConsole)
{
Console.WriteLine(message);
}
}
public static void Log(object message)
{
Write(string.Format("{0}\t{1}", DateTime.Now, message));
}
public static void Log(string format, params object[] args)
{
Write(string.Format(DateTime.Now + " " + format, args));
}
private static TextWriter GetWriter()
{
if (Writer == null)
{
lock (Sync)
{
if (Writer == null)
{
var logDir = Path.Combine(Directory.GetCurrentDirectory(), "log");
if (!Directory.Exists(logDir))
{
Directory.CreateDirectory(logDir);
}
var fn = Path.Combine(logDir, "sir.log");
var stream = Stream.Synchronized(new FileStream(fn, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));
Writer = TextWriter.Synchronized(new StreamWriter(stream));
return Writer;
}
}
}
return Writer;
}
}
}
| mit | C# |
ee9dba486701627a429cacc06dbb92c50efbedcf | add constructor to Parser | ilovepi/Compiler,ilovepi/Compiler | compiler/frontend/Parser.cs | compiler/frontend/Parser.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using compiler.frontend;
namespace compiler.frontend
{
class Parser
{
public Token t;
public Lexer s;
string filename;
public Parser(string p_fileName)
{
filename = p_fileName;
t = null;
s = new Lexer(filename);
}
public void getExpected(Token expected)
{
if (t == expected)
{
next();
}
else {
error();
}
}
public void error(string str)
{
//TODO: determine location in file for error messages
Console.WriteLine ("Error Parsing file: " + filename + ", " + str);
error_fatal();
}
public void error_fatal(){
//TODO: determine location in file for error messages
throw new Exception("Fatal Error Parsing file: " + filename + ". Unable to continue";
}
public void next() {
t = s.getNextToken();
}
public void Designator() {
getExpected(Token.IDENTIFIER);
getExpected(Token.OPEN_BRACKET);
Expression();
getExpected(Token.CLOSE_BRACKET);
}
public void Factor(){
if ((t == Token.IDENTIFIER) || (t == Token.IDENTIFIER))
{
next();
}
else {
error();
}
}
public void Term(){
}
public void Expression(){
}
public void Relation(){
}
public void Assign()
{
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using compiler.frontend;
namespace compiler.frontend
{
class Parser
{
public Token t;
public Lexer s;
string filename;
int lineno;
int pos;
public void getExpected(Token expected)
{
if (t == expected)
{
next();
}
else {
error();
}
}
public void error(string str)
{
//TODO: determine location in file for error messages
Console.WriteLine ("Error Parsing file: " + filename + ", " + str);
error_fatal();
}
public void error_fatal(){
//TODO: determine location in file for error messages
throw new Exception("Fatal Error Parsing file: " + filename + ". Unable to continue";
}
public void next() {
t = s.getNextToken();
}
public void Designator() {
getExpected(Token.IDENTIFIER);
getExpected(Token.OPEN_BRACKET);
Expression();
getExpected(Token.CLOSE_BRACKET);
}
public void Factor(){
if ((t == Token.IDENTIFIER) || (t == Token.IDENTIFIER))
{
next();
}
else {
error();
}
}
public void Term(){
}
public void Expression(){
}
public void Relation(){
}
public void Assign()
{
}
}
}
| mit | C# |
607430d8ff26981430a7fcaf08f1d2aff87ee14b | disable test | poxet/tharga-console | Tharga.Toolkit.Console.Tests/TextInputTests.cs | Tharga.Toolkit.Console.Tests/TextInputTests.cs | using System;
using System.Collections.Generic;
using System.Threading;
using Moq;
using NUnit.Framework;
using Tharga.Toolkit.Console.Commands.Base;
using Tharga.Toolkit.Console.Commands.Helpers;
using Tharga.Toolkit.Console.Interfaces;
namespace Tharga.Toolkit.Console.Tests
{
[TestFixture]
public class TextInputTests
{
[Test]
[Ignore("Fix")]
public void When_()
{
//Arrange
var consoleMock = new Mock<IConsole>(MockBehavior.Strict);
consoleMock.Setup(x => x.Write(It.IsAny<string>()));
consoleMock.SetupGet(x => x.CursorLeft).Returns(0);
consoleMock.SetupGet(x => x.CursorTop).Returns(0);
consoleMock.SetupGet(x => x.BufferWidth).Returns(80);
consoleMock.Setup(x => x.NewLine());
consoleMock.Setup(x => x.ReadKey(new CancellationToken())).Returns(() => new ConsoleKeyInfo((char)13, ConsoleKey.Enter, false, false, false));
var inputManager = new InputManager(consoleMock.Object); //, "> ");
//Act
var response = inputManager.ReadLine("> ", new KeyValuePair<string, string>[] { }, false, new CancellationToken(), null, null);
//Assert
Assert.That(response, Is.EqualTo(string.Empty));
}
}
} | using System;
using System.Collections.Generic;
using System.Threading;
using Moq;
using NUnit.Framework;
using Tharga.Toolkit.Console.Commands.Base;
using Tharga.Toolkit.Console.Commands.Helpers;
using Tharga.Toolkit.Console.Interfaces;
namespace Tharga.Toolkit.Console.Tests
{
[TestFixture]
public class TextInputTests
{
[Test]
public void When_()
{
//Arrange
var consoleMock = new Mock<IConsole>(MockBehavior.Strict);
consoleMock.Setup(x => x.Write(It.IsAny<string>()));
consoleMock.SetupGet(x => x.CursorLeft).Returns(0);
consoleMock.SetupGet(x => x.CursorTop).Returns(0);
consoleMock.SetupGet(x => x.BufferWidth).Returns(80);
consoleMock.Setup(x => x.NewLine());
consoleMock.Setup(x => x.ReadKey(new CancellationToken())).Returns(() => new ConsoleKeyInfo((char)13, ConsoleKey.Enter, false, false, false));
var inputManager = new InputManager(consoleMock.Object); //, "> ");
//Act
var response = inputManager.ReadLine("> ", new KeyValuePair<string, string>[] { }, false, new CancellationToken(), null, null);
//Assert
Assert.That(response, Is.EqualTo(string.Empty));
}
}
} | mit | C# |
2f303eb64812b61ca570b93ebc7799b07636e3ae | update version | 0xFireball/FireCryptEx-Mono | FireCrypt/FireCryptEx/Properties/AssemblyInfo.cs | FireCrypt/FireCryptEx/Properties/AssemblyInfo.cs | #region Using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle ("FireCryptEx")]
[assembly: AssemblyDescription ("FireCryptEx - Encryption software to create secure encrypted volumes.")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("0xFireball, AluminumDev")]
[assembly: AssemblyProduct ("FireCryptEx")]
[assembly: AssemblyCopyright ("Copyright 2015-2016, 0xFireball. All Rights Reserved.")]
[assembly: AssemblyTrademark ("FireCryptEx")]
[assembly: AssemblyCulture ("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible (false)]
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion ("2.2.0.*")]
[assembly: AssemblyFileVersion ("2.2.0.*")]
[assembly: Guid ("a4067db9-0cc6-4a55-b87a-04b56a603f49")]
| #region Using directives
using System;
using System.Reflection;
using System.Runtime.InteropServices;
#endregion
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle ("FireCryptEx")]
[assembly: AssemblyDescription ("FireCryptEx - Encryption software to create secure encrypted volumes.")]
[assembly: AssemblyConfiguration ("")]
[assembly: AssemblyCompany ("0xFireball, AluminumDev")]
[assembly: AssemblyProduct ("FireCryptEx")]
[assembly: AssemblyCopyright ("Copyright 2015-2016, 0xFireball. All Rights Reserved.")]
[assembly: AssemblyTrademark ("FireCryptEx")]
[assembly: AssemblyCulture ("")]
// This sets the default COM visibility of types in the assembly to invisible.
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
[assembly: ComVisible (false)]
// The assembly version has following format :
//
// Major.Minor.Build.Revision
//
// You can specify all the values or you can use the default the Revision and
// Build Numbers by using the '*' as shown below:
[assembly: AssemblyVersion ("2.1.0.*")]
[assembly: AssemblyFileVersion ("2.1.0.*")]
[assembly: Guid ("a4067db9-0cc6-4a55-b87a-04b56a603f49")]
| agpl-3.0 | C# |
d63ef44c7a7e43f98260664dcdfa109a98737e53 | rename InlineComparer with InlineEqualityComparer | TakeAsh/cs-TakeAshUtility | TakeAshUtility/InlineComparer.cs | TakeAshUtility/InlineComparer.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TakeAshUtility {
/// <summary>
/// Create comparer from lambda
/// </summary>
/// <typeparam name="T">Type of the object to compare</typeparam>
/// <remarks>
/// [c# - Using IEqualityComparer for Union - Stack Overflow](http://stackoverflow.com/questions/5969505)
/// </remarks>
public class InlineEqualityComparer<T> :
IEqualityComparer<T> {
private readonly Func<T, T, bool> _equals;
private readonly Func<T, int> _getHashCode;
public InlineEqualityComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) {
_equals = equals;
_getHashCode = getHashCode;
}
public bool Equals(T x, T y) {
return _equals(x, y);
}
public int GetHashCode(T obj) {
return _getHashCode(obj);
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TakeAshUtility {
/// <summary>
/// Create comparer from lambda
/// </summary>
/// <typeparam name="T">Type of the object to compare</typeparam>
/// <remarks>
/// [c# - Using IEqualityComparer for Union - Stack Overflow](http://stackoverflow.com/questions/5969505)
/// </remarks>
public class InlineComparer<T> :
IEqualityComparer<T> {
private readonly Func<T, T, bool> _equals;
private readonly Func<T, int> _getHashCode;
public InlineComparer(Func<T, T, bool> equals, Func<T, int> getHashCode) {
_equals = equals;
_getHashCode = getHashCode;
}
public bool Equals(T x, T y) {
return _equals(x, y);
}
public int GetHashCode(T obj) {
return _getHashCode(obj);
}
}
}
| mit | C# |
5336123b31b7803e9a5feaf359f3fefec2dafafc | Test parallezation will work only in not debug mode | linkelf/GridDomain,andreyleskov/GridDomain | GridDomain.Tests.Unit/Properties/AssemblyInfo.cs | GridDomain.Tests.Unit/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// 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("GridDomain.Tests.XUnit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GridDomain.Tests.XUnit")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("46cc4be2-93be-4807-9b1a-7a10dfea29af")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("GridDomain.Tests.Acceptance")]
[assembly: InternalsVisibleTo("GridDomain.Tests.Acceptance")]
#if !DEBUG
[assembly: CollectionBehavior(DisableTestParallelization = true)]
#endif | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Xunit;
// 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("GridDomain.Tests.XUnit")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GridDomain.Tests.XUnit")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[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("46cc4be2-93be-4807-9b1a-7a10dfea29af")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: InternalsVisibleTo("GridDomain.Tests.Acceptance")]
[assembly: InternalsVisibleTo("GridDomain.Tests.Acceptance")]
| apache-2.0 | C# |
069d927e0e2cd0a9bae94b1201641bd1d9d2a6bc | Update Token.cs | gavronek/L2PAccess-Win | L2PAccess/Authentication/Model/Response/Token.cs | L2PAccess/Authentication/Model/Response/Token.cs | using System;
namespace L2PAccess.Authentication.Model.Response
{
public class Token
{
public string status { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in
{
get
{
return -1;
}
set
{
if (value != -1)
{
accessTokenExpirationDate = new DateTime(Math.Min(DateTime.Now.AddSeconds(value).Ticks, DateTime.Now.AddMinutes(30).Ticks));
}
}
}
public string refresh_token { get; set; }
public DateTime accessTokenExpirationDate { get; set; }
public bool TokenIsExpired()
{
return DateTime.Now >= accessTokenExpirationDate;
}
}
}
| using System;
namespace L2PAccess.Authentication.Model.Response
{
public class Token
{
public string status { get; set; }
public string access_token { get; set; }
public string token_type { get; set; }
public int expires_in
{
get
{
return -1;
}
set
{
if (value != -1)
{
accessTokenExpirationDate = new DateTime(Math.Min(DateTime.Now.AddSeconds(value).Ticks, DateTime.Now.AddMinutes(3).Ticks));
}
}
}
public string refresh_token { get; set; }
public DateTime accessTokenExpirationDate { get; set; }
public bool TokenIsExpired()
{
return DateTime.Now >= accessTokenExpirationDate;
}
}
}
| apache-2.0 | C# |
12d0f2851691570a51187bfb2c6ae652b5c943bc | Fix ExceptionExtensions | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi/Extensions/ExceptionExtensions.cs | WalletWasabi/Extensions/ExceptionExtensions.cs | using System.Collections.Generic;
using System.Net.Http;
using WalletWasabi.Helpers;
namespace System
{
public static class ExceptionExtensions
{
public static string ToTypeMessageString(this Exception ex)
{
var trimmed = Guard.Correct(ex.Message);
if (trimmed == "")
{
return ex.GetType().Name;
}
else
{
return $"{ex.GetType().Name}: {ex.Message}";
}
}
public static Dictionary<string, string> BitcoinCoreTransalations { get; } = new Dictionary<string, string> {
["too-long-mempool-chain"] = "At least one coin you are trying to spend is part of long chain of unconfirmed transactions. You must wait for some previous transactions to confirm.",
["bad-txns-inputs-missingorspent"] = "At least one coin you are trying to spend is already spent.",
["missing-inputs"] = "At least one coin you are trying to spend is already spent.",
["bad-txns-inputs-duplicate"] = "The transaction contains duplicated inputs.",
["bad-txns-nonfinal"] = "The transaction is not final and cannot be broadcasted.",
["bad-txns-oversize"] = "The transaction is too big."
};
public static string ToUserFriendlyString(this HttpRequestException ex)
{
var trimmed = Guard.Correct(ex.Message);
if (trimmed == "")
{
return ex.ToTypeMessageString();
}
else
{
foreach (KeyValuePair<string, string> pair in BitcoinCoreTransalations)
{
if (trimmed.Contains(pair.Key))
{
return pair.Value;
}
}
return ex.ToTypeMessageString();
}
}
}
}
| using System.Collections.Generic;
using System.Net.Http;
namespace System
{
public static class ExceptionExtensions
{
public static string ToTypeMessageString(this Exception ex)
{
return $"{ex.GetType().Name}: {ex.Message}";
}
public static string ToUserFriendlyString(this HttpRequestException ex)
{
var transalations = new Dictionary<string, string>
{
["too-long-mempool-chain"] = "At least one coin you are trying to spend is part of long chain of unconfirmed transactions. You must wait for some previous transactions to confirm.",
["bad-txns-inputs-missingorspent"] = "At least one coin you are trying to spend is already spent.",
["missing-inputs"] = "At least one coin you are trying to spend is already spent.",
["bad-txns-inputs-duplicate"] = "The transaction contains duplicated inputs.",
["bad-txns-nonfinal"] = "The transaction is not final and cannot be broadcasted.",
["bad-txns-oversize"] = "The transaction is too big."
};
var msg = ex.Message.Substring(0, ex.Message.IndexOf(','));
if(transalations.ContainsKey(msg))
{
return transalations[msg];
}
return ex.ToTypeMessageString();
}
}
}
| mit | C# |
10a1948720b15e8de61149ff7abfcad89d5eca8d | remove using directive | peppy/osu,smoogipoo/osu,ppy/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,peppy/osu,peppy/osu-new,UselessToucan/osu,NeoAdonis/osu,NeoAdonis/osu,peppy/osu,EVAST9919/osu,ppy/osu,EVAST9919/osu,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,NeoAdonis/osu | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage? Icon => OsuIcon.ModSpunout;
public override ModType Type => ModType.Automation;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var hitObject in drawables)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.Disc.Enabled = false;
spinner.Disc.OnUpdate += d =>
{
if (d is SpinnerDisc s && s.Valid)
s.Rotate(180 / MathF.PI * (float)s.Clock.ElapsedFrameTime / 40);
};
}
}
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Generic;
using osu.Framework.Graphics.Sprites;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables.Pieces;
using osu.Game.Rulesets.UI;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObjects
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage? Icon => OsuIcon.ModSpunout;
public override ModType Type => ModType.Automation;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override bool Ranked => true;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObjects(IEnumerable<DrawableHitObject> drawables)
{
foreach (var hitObject in drawables)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.Disc.Enabled = false;
spinner.Disc.OnUpdate += d =>
{
if (d is SpinnerDisc s && s.Valid)
s.Rotate(180 / MathF.PI * (float)s.Clock.ElapsedFrameTime / 40);
};
}
}
}
}
}
| mit | C# |
c4d95d3b6c08b7d3d2950d9c6405c980df0330f9 | Remove duplicated `[External]` for `Thread` class | bridgedotnet/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge,AndreyZM/Bridge,AndreyZM/Bridge,bridgedotnet/Bridge,bridgedotnet/Bridge,AndreyZM/Bridge | Bridge/System/Threading/Thread.cs | Bridge/System/Threading/Thread.cs | using Bridge;
using System.ComponentModel;
namespace System.Threading
{
[External]
[Namespace("Bridge.Threading")]
[EditorBrowsable(EditorBrowsableState.Never)]
public sealed class Thread
{
//public extern int ManagedThreadId
//{
// get;
//}
//public static extern Thread CurrentThread
//{
// get;
//}
/// <summary>
/// Suspends the current thread for the specified number of milliseconds.
/// Implemented as a loop checking timeout each iteration.
/// Please note maximum 1e7 iterations
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended. Should be positive or -1. -1 works the same as 0 (not Infinite)</param>
[Template("Bridge.sleep({millisecondsTimeout})")]
public extern static void Sleep(int millisecondsTimeout);
/// <summary>
/// Suspends the current thread for the specified anout of time.
/// Implemented as a loop checking timeout each iteration.
/// Please note maximum 1e7 iterations
/// </summary>
/// <param name="timeout">The amount of time for which the thread is suspended. Should be positive or -1. -1 works the same as 0 (not Infinite)</param>
[Template("Bridge.sleep(null, {timeout})")]
public extern static void Sleep(TimeSpan timeout);
}
} | using Bridge;
using System.ComponentModel;
namespace System.Threading
{
[External]
[Namespace("Bridge.Threading")]
[EditorBrowsable(EditorBrowsableState.Never)]
[External]
public sealed class Thread
{
//public extern int ManagedThreadId
//{
// get;
//}
//public static extern Thread CurrentThread
//{
// get;
//}
/// <summary>
/// Suspends the current thread for the specified number of milliseconds.
/// Implemented as a loop checking timeout each iteration.
/// Please note maximum 1e7 iterations
/// </summary>
/// <param name="millisecondsTimeout">The number of milliseconds for which the thread is suspended. Should be positive or -1. -1 works the same as 0 (not Infinite)</param>
[Template("Bridge.sleep({millisecondsTimeout})")]
public extern static void Sleep(int millisecondsTimeout);
/// <summary>
/// Suspends the current thread for the specified anout of time.
/// Implemented as a loop checking timeout each iteration.
/// Please note maximum 1e7 iterations
/// </summary>
/// <param name="timeout">The amount of time for which the thread is suspended. Should be positive or -1. -1 works the same as 0 (not Infinite)</param>
[Template("Bridge.sleep(null, {timeout})")]
public extern static void Sleep(TimeSpan timeout);
}
} | apache-2.0 | C# |
afbbbaf445f6b33ea72f59461598ce85843c74e9 | Update UnitFactory.createArmy() | Tyzeppelin/petitmondetemp,Tyzeppelin/petitmondetemp,Tyzeppelin/petitmondetemp | dix-nez-lande/dix-nez-lande/Implem/UnitFactory.cs | dix-nez-lande/dix-nez-lande/Implem/UnitFactory.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace dix_nez_lande
{
public class UnitFactory
{
#region Singleton
private static UnitFactory _instance = null;
private UnitFactory()
{
}
public static UnitFactory getUnitFactory()
{
if (_instance == null)
_instance = new UnitFactory();
return _instance;
}
#endregion
public List<Unit> createArmy(Race race, int sizeMap)
{
int nb;
switch (sizeMap)
{
case 6:
nb = 4;
break;
case 10:
nb = 6;
break;
case 8:
nb = 8;
break;
default:
nb=4;
break;
}
List<Unit> list = new List<Unit>();
for (int i = 0; i < nb; i++)
{
//voir nomdefantasy.com pour plus de pimp
list.Add(new UnitImpl(race, "Unit " + i));
}
return list;
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace dix_nez_lande
{
public class UnitFactory
{
#region Singleton
private static UnitFactory _instance = null;
private UnitFactory()
{
}
public static UnitFactory getUnitFactory()
{
if (_instance == null)
_instance = new UnitFactory();
return _instance;
}
#endregion
public List<Unit> createArmy(Race race, int nb)
{
List<Unit> list = new List<Unit>();
for (int i = 0; i < nb; i++)
{
//voir nomdefantasy.com pour plus de pimp
list.Add(new UnitImpl(race, "Unit " + i));
}
return list;
}
}
} | mit | C# |
34566d3962ccb11156c7ba777f2da5acbc2e76ea | Remove empty OnGet function. | Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net,Learnosity/learnosity-sdk-asp.net | LearnosityDemo/Pages/Index.cshtml.cs | LearnosityDemo/Pages/Index.cshtml.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace LearnosityDemo.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace LearnosityDemo.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
// public void OnGet()
// {
// }
}
}
| apache-2.0 | C# |
396a566a0e577b0f2b1a2ba71ee2f1aa687b6c7b | Add some randomness to click samples | ppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,ppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu | osu.Game/Graphics/UserInterface/HoverClickSounds.cs | osu.Game/Graphics/UserInterface/HoverClickSounds.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.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Input.Events;
using osu.Framework.Utils;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover and click sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverClickSounds : HoverSounds
{
private Sample sampleClick;
private readonly MouseButton[] buttons;
/// <summary>
/// a container which plays sounds on hover and click for any specified <see cref="MouseButton"/>s.
/// </summary>
/// <param name="sampleSet">Set of click samples to play.</param>
/// <param name="buttons">
/// Array of button codes which should trigger the click sound.
/// If this optional parameter is omitted or set to <code>null</code>, the click sound will only be played on left click.
/// </param>
public HoverClickSounds(HoverSampleSet sampleSet = HoverSampleSet.Default, MouseButton[] buttons = null)
: base(sampleSet)
{
this.buttons = buttons ?? new[] { MouseButton.Left };
}
protected override bool OnClick(ClickEvent e)
{
if (buttons.Contains(e.Button) && Contains(e.ScreenSpaceMousePosition))
{
sampleClick.Frequency.Value = 0.99 + RNG.NextDouble(0.02);
sampleClick.Play();
}
return base.OnClick(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Samples.Get($@"UI/{SampleSet.GetDescription()}-select")
?? audio.Samples.Get($@"UI/{HoverSampleSet.Default.GetDescription()}-select");
}
}
}
| // 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.Linq;
using osu.Framework.Allocation;
using osu.Framework.Audio;
using osu.Framework.Audio.Sample;
using osu.Framework.Extensions;
using osu.Framework.Input.Events;
using osuTK.Input;
namespace osu.Game.Graphics.UserInterface
{
/// <summary>
/// Adds hover and click sounds to a drawable.
/// Does not draw anything.
/// </summary>
public class HoverClickSounds : HoverSounds
{
private Sample sampleClick;
private readonly MouseButton[] buttons;
/// <summary>
/// a container which plays sounds on hover and click for any specified <see cref="MouseButton"/>s.
/// </summary>
/// <param name="sampleSet">Set of click samples to play.</param>
/// <param name="buttons">
/// Array of button codes which should trigger the click sound.
/// If this optional parameter is omitted or set to <code>null</code>, the click sound will only be played on left click.
/// </param>
public HoverClickSounds(HoverSampleSet sampleSet = HoverSampleSet.Default, MouseButton[] buttons = null)
: base(sampleSet)
{
this.buttons = buttons ?? new[] { MouseButton.Left };
}
protected override bool OnClick(ClickEvent e)
{
if (buttons.Contains(e.Button) && Contains(e.ScreenSpaceMousePosition))
sampleClick?.Play();
return base.OnClick(e);
}
[BackgroundDependencyLoader]
private void load(AudioManager audio)
{
sampleClick = audio.Samples.Get($@"UI/{SampleSet.GetDescription()}-select")
?? audio.Samples.Get($@"UI/{HoverSampleSet.Default.GetDescription()}-select");
}
}
}
| mit | C# |
df9535d195700205380bc624f2a9999cfa9e228c | Update RPM calculation for readability | ppy/osu,NeoAdonis/osu,peppy/osu,peppy/osu,peppy/osu,NeoAdonis/osu,NeoAdonis/osu,ppy/osu,ppy/osu | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | osu.Game.Rulesets.Osu/Mods/OsuModSpunOut.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObject
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage? Icon => OsuIcon.ModSpunOut;
public override ModType Type => ModType.Automation;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObject(DrawableHitObject hitObject)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.HandleUserInput = false;
spinner.OnUpdate += onSpinnerUpdate;
}
}
private void onSpinnerUpdate(Drawable drawable)
{
var spinner = (DrawableSpinner)drawable;
spinner.RotationTracker.Tracking = true;
// early-return if we were paused to avoid division-by-zero in the subsequent calculations.
if (Precision.AlmostEquals(spinner.Clock.Rate, 0))
return;
// because the spinner is under the gameplay clock, it is affected by rate adjustments on the track;
// for that reason using ElapsedFrameTime directly leads to fewer SPM with Half Time and more SPM with Double Time.
// for spinners we want the real (wall clock) elapsed time; to achieve that, unapply the clock rate locally here.
double rateIndependentElapsedTime = spinner.Clock.ElapsedFrameTime / spinner.Clock.Rate;
// multiply the SPM by 1.01 to ensure that the spinner is completed. if the calculation is left exact,
// some spinners may not complete due to very minor decimal loss during calculation
float rotationSpeed = (float)(1.01 * spinner.HitObject.SpinsRequired / spinner.HitObject.Duration);
spinner.RotationTracker.AddRotation(MathUtils.RadiansToDegrees((float)rateIndependentElapsedTime * rotationSpeed * MathF.PI * 2.0f));
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Utils;
using osu.Game.Graphics;
using osu.Game.Rulesets.Mods;
using osu.Game.Rulesets.Objects.Drawables;
using osu.Game.Rulesets.Osu.Objects.Drawables;
namespace osu.Game.Rulesets.Osu.Mods
{
public class OsuModSpunOut : Mod, IApplicableToDrawableHitObject
{
public override string Name => "Spun Out";
public override string Acronym => "SO";
public override IconUsage? Icon => OsuIcon.ModSpunOut;
public override ModType Type => ModType.Automation;
public override string Description => @"Spinners will be automatically completed.";
public override double ScoreMultiplier => 0.9;
public override Type[] IncompatibleMods => new[] { typeof(ModAutoplay), typeof(OsuModAutopilot) };
public void ApplyToDrawableHitObject(DrawableHitObject hitObject)
{
if (hitObject is DrawableSpinner spinner)
{
spinner.HandleUserInput = false;
spinner.OnUpdate += onSpinnerUpdate;
}
}
private void onSpinnerUpdate(Drawable drawable)
{
var spinner = (DrawableSpinner)drawable;
spinner.RotationTracker.Tracking = true;
// early-return if we were paused to avoid division-by-zero in the subsequent calculations.
if (Precision.AlmostEquals(spinner.Clock.Rate, 0))
return;
// because the spinner is under the gameplay clock, it is affected by rate adjustments on the track;
// for that reason using ElapsedFrameTime directly leads to fewer SPM with Half Time and more SPM with Double Time.
// for spinners we want the real (wall clock) elapsed time; to achieve that, unapply the clock rate locally here.
double rateIndependentElapsedTime = spinner.Clock.ElapsedFrameTime / spinner.Clock.Rate;
float rotationSpeed = (float)(spinner.HitObject.SpinsRequired / (spinner.HitObject.Duration / 1.01));
spinner.RotationTracker.AddRotation(MathUtils.RadiansToDegrees((float)rateIndependentElapsedTime * rotationSpeed * MathF.PI * 2.0f));
}
}
}
| mit | C# |
89d8a85db7ac78ebde48f2f56c4df7d38336aed9 | Update AssemblyInfo.cs (#281) | sergeyzwezdin/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo,sergeyzwezdin/Hangfire.Mongo | src/Hangfire.Mongo/Properties/AssemblyInfo.cs | src/Hangfire.Mongo/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("Hangfire.Mongo")]
[assembly: AssemblyDescription("MongoDB storage implementation for Hangfire (background job system for ASP.NET applications).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hangfire.Mongo")]
[assembly: AssemblyCopyright("Copyright © 2014-2019 Sergey Zwezdin, Martin Lobger, Jonas Gottschau")]
[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("02c80b18-125e-473f-be8b-f50dcd86396b")]
// 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.7.22")]
[assembly: AssemblyFileVersion("0.7.22")]
[assembly: AssemblyInformationalVersion("0.7.22")]
[assembly: InternalsVisibleTo("Hangfire.Mongo.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| 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("Hangfire.Mongo")]
[assembly: AssemblyDescription("MongoDB storage implementation for Hangfire (background job system for ASP.NET applications).")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Hangfire.Mongo")]
[assembly: AssemblyCopyright("Copyright © 2014-2019 Sergey Zwezdin, Martin Lobger, Jonas Gottschau")]
[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("02c80b18-125e-473f-be8b-f50dcd86396b")]
// 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.7.12")]
[assembly: AssemblyFileVersion("0.7.12")]
[assembly: AssemblyInformationalVersion("0.7.12")]
[assembly: InternalsVisibleTo("Hangfire.Mongo.Tests")]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")]
| mit | C# |
614246e0e932be0f5bfed902f35a5be33b678233 | Update contact page a bit. | ForNeVeR/fornever.me,ForNeVeR/fornever.me,ForNeVeR/fornever.me | ForneverMind/views/Contact.cshtml | ForneverMind/views/Contact.cshtml | @using RazorEngine.Templating
@inherits TemplateBase
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Контакты";
}
<p>
<a class="so-badge" href="http://stackoverflow.com/users/2684760/fornever">
<img src="http://stackoverflow.com/users/flair/2684760.png"
width="208"
height="58"
alt="мой профиль на Stack Overflow"
title="мой профиль на Stack Overflow" />
</a>
</p>
<p>Я в “социальных” сетях:</p>
<ul>
<li><a href="https://github.com/ForNeVeR">GitHub</a></li>
<li><a href="https://bitbucket.org/ForNeVeR">Bitbucket</a></li>
<li><a href="https://twitter.com/fvnever">Twitter</a></li>
</ul>
<p>На Хабрахабре: <a href="http://habrahabr.ru/users/ForNeVeR/">ForNeVeR</a></p>
<p>
Пишите мне по почте (<a href="mailto:friedrich@fornever.me"
class="email">friedrich@fornever.me</a>) или в
Jabber
(<a href="xmpp:fornever@codingteam.org.ru">fornever@codingteam.org.ru</a>).
</p>
<p>
Приходите в наше XMPP-сообщество:
<a href="xmpp:codingteam@conference.jabber.ru">codingteam@conference.jabber.ru</a>.
</p>
| @using RazorEngine.Templating
@inherits TemplateBase
@{
Layout = "_Layout.cshtml";
ViewBag.Title = "Контакты";
}
<p>
<a class="so-badge" href="http://stackoverflow.com/users/2684760/fornever">
<img src="http://stackoverflow.com/users/flair/2684760.png"
width="208"
height="58"
alt="profile for ForNeVeR at Stack Overflow, Q&A for professional and enthusiast programmers"
title="profile for ForNeVeR at Stack Overflow, Q&A for professional and enthusiast programmers" />
</a>
</p>
<p>Я в “социальных” сетях:</p>
<ul>
<li><a href="https://github.com/ForNeVeR">GitHub</a></li>
<li><a href="https://bitbucket.org/ForNeVeR">Bitbucket</a></li>
<li><a href="https://twitter.com/fvnever">Twitter</a></li>
</ul>
<p>На Хабрахабре: <a href="http://habrahabr.ru/users/ForNeVeR/">ForNeVeR</a></p>
<p>
Пишите мне по почте:
<a href="mailto:friedrich@fornever.me" class="email">friedrich@fornever.me</a>
или в Jabber:
<a href="xmpp:fornever@codingteam.org.ru">fornever@codingteam.org.ru</a>.
</p>
<p>Приходите в наше XMPP-сообщество: <a href="xmpp:codingteam@conference.jabber.ru">codingteam@conference.jabber.ru</a></p>
| mit | C# |
5ede2a2316fd57a52051f340c184380af9b84eba | fix #458 isconditionless on filtered | robrich/elasticsearch-net,NickCraver/NEST,jonyadamit/elasticsearch-net,SeanKilleen/elasticsearch-net,geofeedia/elasticsearch-net,amyzheng424/elasticsearch-net,mac2000/elasticsearch-net,abibell/elasticsearch-net,RossLieberman/NEST,Grastveit/NEST,RossLieberman/NEST,jonyadamit/elasticsearch-net,elastic/elasticsearch-net,mac2000/elasticsearch-net,tkirill/elasticsearch-net,ststeiger/elasticsearch-net,RossLieberman/NEST,junlapong/elasticsearch-net,DavidSSL/elasticsearch-net,abibell/elasticsearch-net,robertlyson/elasticsearch-net,TheFireCookie/elasticsearch-net,CSGOpenSource/elasticsearch-net,azubanov/elasticsearch-net,UdiBen/elasticsearch-net,Grastveit/NEST,tkirill/elasticsearch-net,NickCraver/NEST,KodrAus/elasticsearch-net,CSGOpenSource/elasticsearch-net,LeoYao/elasticsearch-net,TheFireCookie/elasticsearch-net,LeoYao/elasticsearch-net,mac2000/elasticsearch-net,Grastveit/NEST,robertlyson/elasticsearch-net,junlapong/elasticsearch-net,wawrzyn/elasticsearch-net,adam-mccoy/elasticsearch-net,KodrAus/elasticsearch-net,geofeedia/elasticsearch-net,tkirill/elasticsearch-net,faisal00813/elasticsearch-net,gayancc/elasticsearch-net,wawrzyn/elasticsearch-net,UdiBen/elasticsearch-net,adam-mccoy/elasticsearch-net,alanprot/elasticsearch-net,starckgates/elasticsearch-net,NickCraver/NEST,alanprot/elasticsearch-net,wawrzyn/elasticsearch-net,cstlaurent/elasticsearch-net,gayancc/elasticsearch-net,DavidSSL/elasticsearch-net,geofeedia/elasticsearch-net,gayancc/elasticsearch-net,ststeiger/elasticsearch-net,UdiBen/elasticsearch-net,robrich/elasticsearch-net,alanprot/elasticsearch-net,ststeiger/elasticsearch-net,faisal00813/elasticsearch-net,robrich/elasticsearch-net,faisal00813/elasticsearch-net,TheFireCookie/elasticsearch-net,cstlaurent/elasticsearch-net,KodrAus/elasticsearch-net,SeanKilleen/elasticsearch-net,joehmchan/elasticsearch-net,joehmchan/elasticsearch-net,alanprot/elasticsearch-net,cstlaurent/elasticsearch-net,robertlyson/elasticsearch-net,SeanKilleen/elasticsearch-net,elastic/elasticsearch-net,amyzheng424/elasticsearch-net,jonyadamit/elasticsearch-net,CSGOpenSource/elasticsearch-net,junlapong/elasticsearch-net,joehmchan/elasticsearch-net,amyzheng424/elasticsearch-net,LeoYao/elasticsearch-net,azubanov/elasticsearch-net,DavidSSL/elasticsearch-net,azubanov/elasticsearch-net,starckgates/elasticsearch-net,abibell/elasticsearch-net,adam-mccoy/elasticsearch-net,starckgates/elasticsearch-net | src/Nest/DSL/Query/FilteredQueryDescriptor.cs | src/Nest/DSL/Query/FilteredQueryDescriptor.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class FilteredQueryDescriptor<T> : IQuery where T : class
{
[JsonProperty(PropertyName = "query")]
internal BaseQuery _Query { get; set; }
[JsonProperty(PropertyName = "filter")]
internal BaseFilter _Filter { get; set; }
bool IQuery.IsConditionless
{
get
{
if (this._Query == null && this._Filter == null)
return true;
if (this._Filter == null && this._Query != null)
return this._Query.IsConditionless;
if (this._Filter != null && this._Query == null)
return this._Filter.IsConditionless;
return this._Query.IsConditionless && this._Filter.IsConditionless;
}
}
public FilteredQueryDescriptor<T> Query(Func<QueryDescriptor<T>, BaseQuery> querySelector)
{
querySelector.ThrowIfNull("querySelector");
var query = new QueryDescriptor<T>();
var q = querySelector(query);
this._Query = q;
return this;
}
public FilteredQueryDescriptor<T> Filter(Func<FilterDescriptor<T>, BaseFilter> filterSelector)
{
filterSelector.ThrowIfNull("filterSelector");
var filter = new FilterDescriptor<T>();
var f = filterSelector(filter);
this._Filter = f;
return this;
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
namespace Nest
{
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class FilteredQueryDescriptor<T> : IQuery where T : class
{
[JsonProperty(PropertyName = "query")]
internal BaseQuery _Query { get; set; }
[JsonProperty(PropertyName = "filter")]
internal BaseFilter _Filter { get; set; }
bool IQuery.IsConditionless
{
get
{
if (this._Query == null && this._Filter == null)
return true;
if (this._Filter == null && this._Query != null)
return this._Query.IsConditionless;
if (this._Filter != null && this._Query == null)
return this._Filter.IsConditionless;
return false;
}
}
public FilteredQueryDescriptor<T> Query(Func<QueryDescriptor<T>, BaseQuery> querySelector)
{
querySelector.ThrowIfNull("querySelector");
var query = new QueryDescriptor<T>();
var q = querySelector(query);
this._Query = q;
return this;
}
public FilteredQueryDescriptor<T> Filter(Func<FilterDescriptor<T>, BaseFilter> filterSelector)
{
filterSelector.ThrowIfNull("filterSelector");
var filter = new FilterDescriptor<T>();
var f = filterSelector(filter);
this._Filter = f;
return this;
}
}
}
| apache-2.0 | C# |
fbb3728eef74ddef12a9fbba5d2703c573e1ca81 | Update version. | Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex,Squidex/squidex | backend/src/Squidex/Areas/Api/Controllers/News/Service/FeaturesService.cs | backend/src/Squidex/Areas/Api/Controllers/News/Service/FeaturesService.cs | // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Squidex.Areas.Api.Controllers.News.Models;
using Squidex.ClientLibrary;
namespace Squidex.Areas.Api.Controllers.News.Service
{
public sealed class FeaturesService
{
private const int FeatureVersion = 13;
private readonly QueryContext flatten = QueryContext.Default.Flatten();
private readonly IContentsClient<NewsEntity, FeatureDto> client;
public sealed class NewsEntity : Content<FeatureDto>
{
}
public FeaturesService(IOptions<MyNewsOptions> options)
{
if (options.Value.IsConfigured())
{
var squidexOptions = new SquidexOptions
{
AppName = options.Value.AppName,
ClientId = options.Value.ClientId,
ClientSecret = options.Value.ClientSecret,
Url = "https://cloud.squidex.io"
};
var clientManager = new SquidexClientManager(squidexOptions);
client = clientManager.CreateContentsClient<NewsEntity, FeatureDto>("feature-news");
}
}
public async Task<FeaturesDto> GetFeaturesAsync(int version = 0)
{
var result = new FeaturesDto { Features = new List<FeatureDto>(), Version = FeatureVersion };
if (client != null && version < FeatureVersion)
{
var query = new ContentQuery
{
Filter = $"data/version/iv ge {FeatureVersion}"
};
var features = await client.GetAsync(query, flatten);
result.Features.AddRange(features.Items.Select(x => x.Data));
}
return result;
}
}
}
| // ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Options;
using Squidex.Areas.Api.Controllers.News.Models;
using Squidex.ClientLibrary;
namespace Squidex.Areas.Api.Controllers.News.Service
{
public sealed class FeaturesService
{
private const int FeatureVersion = 11;
private readonly QueryContext flatten = QueryContext.Default.Flatten();
private readonly IContentsClient<NewsEntity, FeatureDto> client;
public sealed class NewsEntity : Content<FeatureDto>
{
}
public FeaturesService(IOptions<MyNewsOptions> options)
{
if (options.Value.IsConfigured())
{
var squidexOptions = new SquidexOptions
{
AppName = options.Value.AppName,
ClientId = options.Value.ClientId,
ClientSecret = options.Value.ClientSecret,
Url = "https://cloud.squidex.io"
};
var clientManager = new SquidexClientManager(squidexOptions);
client = clientManager.CreateContentsClient<NewsEntity, FeatureDto>("feature-news");
}
}
public async Task<FeaturesDto> GetFeaturesAsync(int version = 0)
{
var result = new FeaturesDto { Features = new List<FeatureDto>(), Version = FeatureVersion };
if (client != null && version < FeatureVersion)
{
var query = new ContentQuery
{
Filter = $"data/version/iv ge {FeatureVersion}"
};
var features = await client.GetAsync(query, flatten);
result.Features.AddRange(features.Items.Select(x => x.Data));
}
return result;
}
}
}
| mit | C# |
87c551840f2b2ee29d2c96a57ce5185324c0bda0 | Remove unnecessary code | angellaa/RetailStoreSpike | RetailStore/RetailStore/Inventory.cs | RetailStore/RetailStore/Inventory.cs | using System.Collections.Generic;
namespace RetailStore
{
public class Inventory
{
public Inventory(Dictionary<string, Product> products)
{
Products = products;
}
private Dictionary<string, Product> Products { get; }
public Product FindProduct(string barcode)
{
return ProductNotFound(barcode) ? null : Products[barcode];
}
private bool ProductNotFound(string barcode)
{
return !Products.ContainsKey(barcode);
}
}
} | using System.Collections.Generic;
namespace RetailStore
{
public class Inventory
{
public Inventory(Dictionary<string, Product> products)
{
Products = products;
}
private Dictionary<string, Product> Products { get; }
public Product FindProduct(string barcode)
{
return ProductNotFound(barcode) ? null : Products[barcode];
}
private bool ProductNotFound(string barcode)
{
return barcode == null || !Products.ContainsKey(barcode);
}
}
} | mit | C# |
06d24206a06fdcc06d32d91174756a96afc934d5 | Increment build number | emoacht/SnowyImageCopy | Source/SnowyImageCopy/Properties/AssemblyInfo.cs | Source/SnowyImageCopy/Properties/AssemblyInfo.cs | using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Snowy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Snowy")]
[assembly: AssemblyCopyright("Copyright © 2014-2020 emoacht")]
[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("55df0585-a26e-489e-bd94-4e6a50a83e23")]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.1.0")]
[assembly: AssemblyFileVersion("2.1.1.0")]
// For unit test
[assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
| using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Snowy")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Snowy")]
[assembly: AssemblyCopyright("Copyright © 2014-2020 emoacht")]
[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("55df0585-a26e-489e-bd94-4e6a50a83e23")]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US" , UltimateResourceFallbackLocation.MainAssembly)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("2.1.0.0")]
[assembly: AssemblyFileVersion("2.1.0.0")]
// For unit test
[assembly: InternalsVisibleTo("SnowyImageCopy.Test")]
| mit | C# |
a886a15dbd1836a1c1dc4606ff16c983a1b0cd7b | Remove unused statements. | cube-soft/Cube.Core,cube-soft/Cube.Core | Tests/Sources/Details/GlobalSetup.cs | Tests/Sources/Details/GlobalSetup.cs | /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using NUnit.Framework;
using System.Reflection;
using System.Windows;
namespace Cube.Xui.Tests
{
/* --------------------------------------------------------------------- */
///
/// GlobalSetup
///
/// <summary>
/// NUnit で最初に実行する処理を記述するテストです。
/// </summary>
///
/* --------------------------------------------------------------------- */
[SetUpFixture]
public class GlobalSetup
{
/* ----------------------------------------------------------------- */
///
/// OneTimeSetup
///
/// <summary>
/// 一度だけ実行される初期化処理です。
/// </summary>
///
/* ----------------------------------------------------------------- */
[OneTimeSetUp]
public void OneTimeSetup()
{
Logger.Configure();
Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly());
Logger.ObserveTaskException();
Application.Current.ObserveUiException();
}
}
}
| /* ------------------------------------------------------------------------- */
//
// Copyright (c) 2010 CubeSoft, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/* ------------------------------------------------------------------------- */
using Cube.Log;
using NUnit.Framework;
using System.Reflection;
using System.Windows;
namespace Cube.Xui.Tests
{
/* --------------------------------------------------------------------- */
///
/// GlobalSetup
///
/// <summary>
/// NUnit で最初に実行する処理を記述するテストです。
/// </summary>
///
/* --------------------------------------------------------------------- */
[SetUpFixture]
public class GlobalSetup
{
/* ----------------------------------------------------------------- */
///
/// OneTimeSetup
///
/// <summary>
/// 一度だけ実行される初期化処理です。
/// </summary>
///
/* ----------------------------------------------------------------- */
[OneTimeSetUp]
public void OneTimeSetup()
{
Logger.Configure();
Logger.Info(typeof(GlobalSetup), Assembly.GetExecutingAssembly());
Logger.ObserveTaskException();
Application.Current.ObserveUiException();
}
}
}
| apache-2.0 | C# |
f8b120aa73f9d6068680508a0e2fb770b7cee1fe | update version to 1.12.1 | mike-mo/MoreTerra | WorldView/Properties/AssemblyInfo.cs | WorldView/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("MoreTerra")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MoreTerra Team")]
[assembly: AssemblyProduct("MoreTerra")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c4106344-4784-4541-8ca4-6189280a3b38")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.12.1.0")]
[assembly: AssemblyFileVersion("1.12.1.0")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MoreTerra")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("MoreTerra Team")]
[assembly: AssemblyProduct("MoreTerra")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c4106344-4784-4541-8ca4-6189280a3b38")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.11.5.0")]
[assembly: AssemblyFileVersion("1.11.5.0")]
| mit | C# |
e44abc390bc8a1f0fcb7d3607b5f80dfb6f6c403 | Add more invalid script tests | TheBerkin/Rant | Rant.Tests/Expressions/Invalid.cs | Rant.Tests/Expressions/Invalid.cs | using NUnit.Framework;
namespace Rant.Tests.Expressions
{
public class Invalid
{
private readonly RantEngine rant = new RantEngine();
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void BlockAsVariable() => rant.Do("[@ x = { 2 } ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void IfStatementAsVariable() => rant.Do("[@ x = if(true) { 2 } ]");
[Test]
[ExpectedException(typeof(RantRuntimeException))]
public void WrongNumberOfArgs() => rant.Do("[@ x = function(a, b) { }; x(2) ]");
[Test]
[ExpectedException(typeof(RantRuntimeException))]
public void WrongNumberOfArgsNative() => rant.Do("[@ Output.print(2, 3) ]");
[Test]
[ExpectedException(typeof(RantRuntimeException))]
public void NumberAsFunction() => rant.Do("[@ (2)() ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void AWholeBunchOfNumbers() => rant.Do("[@ 1 2 2 2 3 3 4 5 6 6 ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void MissingAdditionOperand() => rant.Do(@"[@ 0 + ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void TooManyOperators() => rant.Do(@"[@ 1 + * / 2]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void TooManyOperatorsMissingOperand() => rant.Do(@"[@ 1 + * ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void TooManyOperands() => rant.Do(@"[@ 1 + 1 1]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void TooManyOperatorsAndOperands() => rant.Do(@"[@ 1 + + 1 1]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void AssignmentToConstant() => rant.Do(@"[@ 1 = 2; ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void AssignmentToString() => rant.Do(@"[@ ""foo"" = 2; ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void TooManyEquals() => rant.Do(@"[@ var x = = 1; ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void UnexpectedInfixAfterEquals() => rant.Do(@"[@ var x = * 1; ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void UnexpectedInfixBeforeEquals() => rant.Do(@"[@ var x + = 1; ]");
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void AssignmentToKeyword() => rant.Do(@"[@ list = true; ]");
}
}
| using NUnit.Framework;
namespace Rant.Tests.Expressions
{
public class Invalid
{
private readonly RantEngine rant = new RantEngine();
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void BlockAsVariable()
{
rant.Do("[@ x = { 2 } ]");
}
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void IfStatementAsVariable()
{
rant.Do("[@ x = if(true) { 2 } ]");
}
[Test]
[ExpectedException(typeof(RantRuntimeException))]
public void WrongNumberOfArgs()
{
rant.Do("[@ x = function(a, b) { }; x(2) ]");
}
[Test]
[ExpectedException(typeof(RantRuntimeException))]
public void WrongNumberOfArgsNative()
{
rant.Do("[@ Output.print(2, 3) ]");
}
[Test]
[ExpectedException(typeof(RantRuntimeException))]
public void NumberAsFunction()
{
rant.Do("[@ (2)() ]");
}
[Test]
[ExpectedException(typeof(RantCompilerException))]
public void AWholeBunchOfNumbers()
{
rant.Do("[@ 1 2 2 2 3 3 4 5 6 6 ]");
}
}
}
| mit | C# |
32ccd19ff3e9acfdee8c349cd18c474c39ce2338 | Set the max number of expected elements. | nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet | WalletWasabi.Fluent/CrashReport/CrashReporter.cs | WalletWasabi.Fluent/CrashReport/CrashReporter.cs | using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using WalletWasabi.Logging;
using WalletWasabi.Microservices;
using WalletWasabi.Models;
namespace WalletWasabi.Fluent.CrashReport
{
public static class CrashReporter
{
public static void Invoke(Exception exceptionToReport)
{
try
{
var serializedException = exceptionToReport.ToSerializableException();
var base64ExceptionString = SerializableException.ToBase64String(serializedException);
var args = $"crashreport -exception=\"{base64ExceptionString}\"";
var path = Process.GetCurrentProcess().MainModule?.FileName;
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"Invalid path: '{path}'");
}
ProcessStartInfo startInfo = ProcessStartInfoFactory.Make(path, args);
using Process? p = Process.Start(startInfo);
}
catch (Exception ex)
{
Logger.LogWarning($"There was a problem while invoking crash report: '{ex}'.");
}
}
public static bool TryGetExceptionFromCliArgs(string[] args, [NotNullWhen(true)] out SerializableException? exception)
{
exception = null;
try
{
if (args.Length < 2)
{
return false;
}
if (args[0].Contains("crashreport") && args[1].Contains("-exception="))
{
var exceptionString = args[1].Split("=", count: 2)[1].Trim('"');
exception = SerializableException.FromBase64String(exceptionString);
return true;
}
}
catch (Exception ex)
{
// Report the current exception.
exception = ex.ToSerializableException();
Logger.LogCritical($"There was a problem: '{ex}'.");
return true;
}
return false;
}
}
}
| using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using WalletWasabi.Logging;
using WalletWasabi.Microservices;
using WalletWasabi.Models;
namespace WalletWasabi.Fluent.CrashReport
{
public static class CrashReporter
{
public static void Invoke(Exception exceptionToReport)
{
try
{
var serializedException = exceptionToReport.ToSerializableException();
var base64ExceptionString = SerializableException.ToBase64String(serializedException);
var args = $"crashreport -exception=\"{base64ExceptionString}\"";
var path = Process.GetCurrentProcess().MainModule?.FileName;
if (string.IsNullOrEmpty(path))
{
throw new InvalidOperationException($"Invalid path: '{path}'");
}
ProcessStartInfo startInfo = ProcessStartInfoFactory.Make(path, args);
using Process? p = Process.Start(startInfo);
}
catch (Exception ex)
{
Logger.LogWarning($"There was a problem while invoking crash report: '{ex}'.");
}
}
public static bool TryGetExceptionFromCliArgs(string[] args, [NotNullWhen(true)] out SerializableException? exception)
{
exception = null;
try
{
if (args.Length < 2)
{
return false;
}
if (args[0].Contains("crashreport") && args[1].Contains("-exception="))
{
var exceptionString = args[1].Split("=", StringSplitOptions.RemoveEmptyEntries)[1].Trim('"');
exception = SerializableException.FromBase64String(exceptionString);
return true;
}
}
catch (Exception ex)
{
// Report the current exception.
exception = ex.ToSerializableException();
Logger.LogCritical($"There was a problem: '{ex}'.");
return true;
}
return false;
}
}
}
| mit | C# |
264907a030a3a69da886027e2989dee3a330d987 | remove unused field | cvent/Metrics.NET,alhardy/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,huoxudong125/Metrics.NET,cvent/Metrics.NET,DeonHeyns/Metrics.NET,MetaG8/Metrics.NET,ntent-ad/Metrics.NET,Recognos/Metrics.NET,alhardy/Metrics.NET,DeonHeyns/Metrics.NET,Liwoj/Metrics.NET,etishor/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,huoxudong125/Metrics.NET,MetaG8/Metrics.NET,mnadel/Metrics.NET,Recognos/Metrics.NET,ntent-ad/Metrics.NET | Src/Metrics/Json/JsonBuilderV2.cs | Src/Metrics/Json/JsonBuilderV2.cs | using System.Globalization;
using System.Linq;
using Metrics.MetricData;
using Metrics.Utils;
namespace Metrics.Json
{
public sealed class JsonBuilderV2
{
public const int Version = 2;
public const string MetricsMimeType = "application/vnd.metrics.net.v2.metrics+json";
#if !DEBUG
private const bool DefaultIndented = false;
#else
private const bool DefaultIndented = true;
#endif
public static string BuildJson(MetricsData data) { return BuildJson(data, Clock.Default, indented: DefaultIndented); }
public static string BuildJson(MetricsData data, Clock clock, bool indented = DefaultIndented)
{
var version = Version.ToString(CultureInfo.InvariantCulture);
var timestamp = clock.UTCDateTime.ToString("yyyy-MM-ddTHH:mm:ss.ffffK", CultureInfo.InvariantCulture);
return JsonMetricsContext.FromContext(data, version, timestamp, AppEnvironment.Current.ToArray())
.ToJsonObject()
.AsJson(indented);
}
}
}
| using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Metrics.MetricData;
using Metrics.Utils;
namespace Metrics.Json
{
public sealed class JsonBuilderV2
{
public const int Version = 2;
public const string MetricsMimeType = "application/vnd.metrics.net.v2.metrics+json";
#if !DEBUG
private const bool DefaultIndented = false;
#else
private const bool DefaultIndented = true;
#endif
private readonly List<JsonProperty> root = new List<JsonProperty>();
public static string BuildJson(MetricsData data) { return BuildJson(data, Clock.Default, indented: DefaultIndented); }
public static string BuildJson(MetricsData data, Clock clock, bool indented = DefaultIndented)
{
var version = Version.ToString(CultureInfo.InvariantCulture);
var timestamp = clock.UTCDateTime.ToString("yyyy-MM-ddTHH:mm:ss.ffffK", CultureInfo.InvariantCulture);
return JsonMetricsContext.FromContext(data, version, timestamp, AppEnvironment.Current.ToArray())
.ToJsonObject()
.AsJson(indented);
}
}
}
| apache-2.0 | C# |
efff1ebc1d20283d482c99c7b1f2649ddc15a6e6 | Update Interop.PlatformDetection.cs with FreeBSD | seanshpark/corefx,jlin177/corefx,benpye/corefx,shimingsg/corefx,heXelium/corefx,Priya91/corefx-1,lggomez/corefx,nchikanov/corefx,jhendrixMSFT/corefx,shmao/corefx,popolan1986/corefx,wtgodbe/corefx,rajansingh10/corefx,josguil/corefx,chenxizhang/corefx,anjumrizwi/corefx,manu-silicon/corefx,uhaciogullari/corefx,richlander/corefx,pgavlin/corefx,n1ghtmare/corefx,the-dwyer/corefx,mokchhya/corefx,chenkennt/corefx,elijah6/corefx,MaggieTsang/corefx,rubo/corefx,DnlHarvey/corefx,weltkante/corefx,CloudLens/corefx,the-dwyer/corefx,shimingsg/corefx,krk/corefx,tijoytom/corefx,cydhaselton/corefx,ptoonen/corefx,s0ne0me/corefx,gkhanna79/corefx,richlander/corefx,dtrebbien/corefx,nbarbettini/corefx,rubo/corefx,Petermarcu/corefx,SGuyGe/corefx,gkhanna79/corefx,alphonsekurian/corefx,khdang/corefx,wtgodbe/corefx,MaggieTsang/corefx,iamjasonp/corefx,mazong1123/corefx,seanshpark/corefx,JosephTremoulet/corefx,n1ghtmare/corefx,zhangwenquan/corefx,uhaciogullari/corefx,jlin177/corefx,comdiv/corefx,misterzik/corefx,zhenlan/corefx,fffej/corefx,SGuyGe/corefx,weltkante/corefx,rubo/corefx,shana/corefx,bitcrazed/corefx,misterzik/corefx,stormleoxia/corefx,weltkante/corefx,mellinoe/corefx,andyhebear/corefx,Chrisboh/corefx,brett25/corefx,the-dwyer/corefx,nchikanov/corefx,mokchhya/corefx,alexandrnikitin/corefx,mokchhya/corefx,rjxby/corefx,yizhang82/corefx,shmao/corefx,erpframework/corefx,josguil/corefx,dtrebbien/corefx,lggomez/corefx,billwert/corefx,jlin177/corefx,mokchhya/corefx,khdang/corefx,dkorolev/corefx,Yanjing123/corefx,VPashkov/corefx,scott156/corefx,twsouthwick/corefx,Frank125/corefx,Yanjing123/corefx,shmao/corefx,gabrielPeart/corefx,ericstj/corefx,alexperovich/corefx,tstringer/corefx,BrennanConroy/corefx,stephenmichaelf/corefx,weltkante/corefx,MaggieTsang/corefx,Ermiar/corefx,seanshpark/corefx,viniciustaveira/corefx,Jiayili1/corefx,lydonchandra/corefx,chenkennt/corefx,stone-li/corefx,dhoehna/corefx,MaggieTsang/corefx,cydhaselton/corefx,billwert/corefx,dotnet-bot/corefx,stephenmichaelf/corefx,heXelium/corefx,krk/corefx,mellinoe/corefx,elijah6/corefx,zhenlan/corefx,stephenmichaelf/corefx,rajansingh10/corefx,shahid-pk/corefx,ViktorHofer/corefx,chaitrakeshav/corefx,mmitche/corefx,richlander/corefx,lydonchandra/corefx,the-dwyer/corefx,PatrickMcDonald/corefx,zhenlan/corefx,Ermiar/corefx,mmitche/corefx,tstringer/corefx,tijoytom/corefx,PatrickMcDonald/corefx,rahku/corefx,CherryCxldn/corefx,shmao/corefx,heXelium/corefx,alphonsekurian/corefx,stone-li/corefx,KrisLee/corefx,zmaruo/corefx,SGuyGe/corefx,axelheer/corefx,690486439/corefx,nchikanov/corefx,rahku/corefx,pgavlin/corefx,elijah6/corefx,chenxizhang/corefx,cydhaselton/corefx,alexperovich/corefx,SGuyGe/corefx,rjxby/corefx,pallavit/corefx,parjong/corefx,jcme/corefx,benjamin-bader/corefx,shana/corefx,the-dwyer/corefx,the-dwyer/corefx,VPashkov/corefx,parjong/corefx,ViktorHofer/corefx,marksmeltzer/corefx,nbarbettini/corefx,bitcrazed/corefx,jmhardison/corefx,alexperovich/corefx,benpye/corefx,tijoytom/corefx,stephenmichaelf/corefx,zhenlan/corefx,DnlHarvey/corefx,axelheer/corefx,cydhaselton/corefx,benpye/corefx,anjumrizwi/corefx,KrisLee/corefx,elijah6/corefx,kkurni/corefx,vidhya-bv/corefx-sorting,kkurni/corefx,popolan1986/corefx,ptoonen/corefx,Petermarcu/corefx,richlander/corefx,Yanjing123/corefx,jlin177/corefx,MaggieTsang/corefx,stone-li/corefx,alphonsekurian/corefx,cydhaselton/corefx,claudelee/corefx,ravimeda/corefx,ravimeda/corefx,nbarbettini/corefx,lggomez/corefx,alexperovich/corefx,misterzik/corefx,parjong/corefx,ellismg/corefx,kkurni/corefx,twsouthwick/corefx,gkhanna79/corefx,rahku/corefx,wtgodbe/corefx,gabrielPeart/corefx,Priya91/corefx-1,zhenlan/corefx,yizhang82/corefx,vs-team/corefx,krytarowski/corefx,CherryCxldn/corefx,nbarbettini/corefx,jmhardison/corefx,scott156/corefx,DnlHarvey/corefx,kyulee1/corefx,jcme/corefx,ViktorHofer/corefx,elijah6/corefx,mazong1123/corefx,Frank125/corefx,Alcaro/corefx,vidhya-bv/corefx-sorting,fgreinacher/corefx,mazong1123/corefx,PatrickMcDonald/corefx,alphonsekurian/corefx,dotnet-bot/corefx,nchikanov/corefx,shimingsg/corefx,nelsonsar/corefx,comdiv/corefx,mafiya69/corefx,manu-silicon/corefx,xuweixuwei/corefx,kkurni/corefx,matthubin/corefx,ravimeda/corefx,nelsonsar/corefx,shahid-pk/corefx,ViktorHofer/corefx,kyulee1/corefx,krytarowski/corefx,jeremymeng/corefx,oceanho/corefx,DnlHarvey/corefx,jhendrixMSFT/corefx,gregg-miskelly/corefx,krk/corefx,thiagodin/corefx,richlander/corefx,iamjasonp/corefx,shrutigarg/corefx,690486439/corefx,nelsonsar/corefx,s0ne0me/corefx,shrutigarg/corefx,marksmeltzer/corefx,bitcrazed/corefx,dotnet-bot/corefx,fgreinacher/corefx,huanjie/corefx,zhenlan/corefx,ptoonen/corefx,jcme/corefx,vrassouli/corefx,tstringer/corefx,shimingsg/corefx,zmaruo/corefx,bpschoch/corefx,cartermp/corefx,marksmeltzer/corefx,tstringer/corefx,shimingsg/corefx,ravimeda/corefx,gregg-miskelly/corefx,nbarbettini/corefx,benjamin-bader/corefx,mokchhya/corefx,bpschoch/corefx,ptoonen/corefx,Petermarcu/corefx,jhendrixMSFT/corefx,mafiya69/corefx,rubo/corefx,axelheer/corefx,Priya91/corefx-1,ericstj/corefx,Priya91/corefx-1,iamjasonp/corefx,cartermp/corefx,dsplaisted/corefx,tijoytom/corefx,benpye/corefx,pallavit/corefx,erpframework/corefx,dotnet-bot/corefx,benjamin-bader/corefx,marksmeltzer/corefx,vijaykota/corefx,erpframework/corefx,krk/corefx,seanshpark/corefx,mazong1123/corefx,bitcrazed/corefx,ViktorHofer/corefx,zhangwenquan/corefx,larsbj1988/corefx,fffej/corefx,richlander/corefx,gkhanna79/corefx,brett25/corefx,shahid-pk/corefx,zhangwenquan/corefx,billwert/corefx,scott156/corefx,krytarowski/corefx,jlin177/corefx,shrutigarg/corefx,Chrisboh/corefx,Petermarcu/corefx,benpye/corefx,shimingsg/corefx,gkhanna79/corefx,cnbin/corefx,alexandrnikitin/corefx,YoupHulsebos/corefx,ericstj/corefx,n1ghtmare/corefx,shahid-pk/corefx,Jiayili1/corefx,dsplaisted/corefx,ericstj/corefx,CloudLens/corefx,MaggieTsang/corefx,rahku/corefx,jlin177/corefx,VPashkov/corefx,manu-silicon/corefx,alexandrnikitin/corefx,alphonsekurian/corefx,thiagodin/corefx,oceanho/corefx,akivafr123/corefx,Jiayili1/corefx,nchikanov/corefx,alphonsekurian/corefx,twsouthwick/corefx,krk/corefx,vs-team/corefx,marksmeltzer/corefx,dtrebbien/corefx,shahid-pk/corefx,PatrickMcDonald/corefx,billwert/corefx,chenxizhang/corefx,cnbin/corefx,mafiya69/corefx,comdiv/corefx,Yanjing123/corefx,rjxby/corefx,larsbj1988/corefx,zmaruo/corefx,weltkante/corefx,rubo/corefx,Jiayili1/corefx,thiagodin/corefx,rjxby/corefx,rjxby/corefx,parjong/corefx,dsplaisted/corefx,shahid-pk/corefx,claudelee/corefx,chaitrakeshav/corefx,benjamin-bader/corefx,manu-silicon/corefx,yizhang82/corefx,the-dwyer/corefx,MaggieTsang/corefx,YoupHulsebos/corefx,stone-li/corefx,lggomez/corefx,scott156/corefx,larsbj1988/corefx,jeremymeng/corefx,mmitche/corefx,nbarbettini/corefx,larsbj1988/corefx,n1ghtmare/corefx,dhoehna/corefx,josguil/corefx,Petermarcu/corefx,Ermiar/corefx,mellinoe/corefx,janhenke/corefx,matthubin/corefx,YoupHulsebos/corefx,alphonsekurian/corefx,SGuyGe/corefx,krytarowski/corefx,ViktorHofer/corefx,YoupHulsebos/corefx,vrassouli/corefx,matthubin/corefx,rjxby/corefx,vijaykota/corefx,CherryCxldn/corefx,ellismg/corefx,yizhang82/corefx,xuweixuwei/corefx,Jiayili1/corefx,billwert/corefx,Ermiar/corefx,pallavit/corefx,jhendrixMSFT/corefx,nchikanov/corefx,lggomez/corefx,alexperovich/corefx,dhoehna/corefx,jlin177/corefx,matthubin/corefx,manu-silicon/corefx,pallavit/corefx,weltkante/corefx,rahku/corefx,alexperovich/corefx,rajansingh10/corefx,rahku/corefx,CloudLens/corefx,shrutigarg/corefx,iamjasonp/corefx,lggomez/corefx,dkorolev/corefx,parjong/corefx,mellinoe/corefx,mellinoe/corefx,ellismg/corefx,YoupHulsebos/corefx,akivafr123/corefx,shmao/corefx,weltkante/corefx,shmao/corefx,kyulee1/corefx,bitcrazed/corefx,fffej/corefx,heXelium/corefx,CloudLens/corefx,wtgodbe/corefx,seanshpark/corefx,billwert/corefx,iamjasonp/corefx,ellismg/corefx,anjumrizwi/corefx,fffej/corefx,vidhya-bv/corefx-sorting,Ermiar/corefx,Ermiar/corefx,cartermp/corefx,Jiayili1/corefx,viniciustaveira/corefx,shmao/corefx,andyhebear/corefx,stone-li/corefx,ravimeda/corefx,krk/corefx,fgreinacher/corefx,PatrickMcDonald/corefx,khdang/corefx,dotnet-bot/corefx,cydhaselton/corefx,s0ne0me/corefx,jhendrixMSFT/corefx,elijah6/corefx,vidhya-bv/corefx-sorting,zmaruo/corefx,bpschoch/corefx,Petermarcu/corefx,BrennanConroy/corefx,vidhya-bv/corefx-sorting,huanjie/corefx,adamralph/corefx,xuweixuwei/corefx,stephenmichaelf/corefx,billwert/corefx,mafiya69/corefx,Petermarcu/corefx,zhangwenquan/corefx,andyhebear/corefx,JosephTremoulet/corefx,jcme/corefx,cartermp/corefx,cartermp/corefx,JosephTremoulet/corefx,pallavit/corefx,s0ne0me/corefx,n1ghtmare/corefx,zhenlan/corefx,yizhang82/corefx,axelheer/corefx,cartermp/corefx,Chrisboh/corefx,andyhebear/corefx,akivafr123/corefx,viniciustaveira/corefx,ViktorHofer/corefx,elijah6/corefx,fgreinacher/corefx,ravimeda/corefx,mmitche/corefx,axelheer/corefx,JosephTremoulet/corefx,alexandrnikitin/corefx,chaitrakeshav/corefx,janhenke/corefx,cnbin/corefx,lggomez/corefx,wtgodbe/corefx,twsouthwick/corefx,nelsonsar/corefx,yizhang82/corefx,JosephTremoulet/corefx,janhenke/corefx,ericstj/corefx,krytarowski/corefx,BrennanConroy/corefx,thiagodin/corefx,gregg-miskelly/corefx,kkurni/corefx,jhendrixMSFT/corefx,wtgodbe/corefx,Alcaro/corefx,mazong1123/corefx,huanjie/corefx,manu-silicon/corefx,mellinoe/corefx,JosephTremoulet/corefx,axelheer/corefx,rahku/corefx,shana/corefx,khdang/corefx,nchikanov/corefx,jeremymeng/corefx,gabrielPeart/corefx,ellismg/corefx,Frank125/corefx,anjumrizwi/corefx,jmhardison/corefx,gkhanna79/corefx,pgavlin/corefx,SGuyGe/corefx,huanjie/corefx,YoupHulsebos/corefx,690486439/corefx,gkhanna79/corefx,YoupHulsebos/corefx,dtrebbien/corefx,CherryCxldn/corefx,dkorolev/corefx,krytarowski/corefx,KrisLee/corefx,uhaciogullari/corefx,VPashkov/corefx,adamralph/corefx,tstringer/corefx,mmitche/corefx,gregg-miskelly/corefx,manu-silicon/corefx,gabrielPeart/corefx,stormleoxia/corefx,stormleoxia/corefx,seanshpark/corefx,claudelee/corefx,lydonchandra/corefx,oceanho/corefx,mazong1123/corefx,vs-team/corefx,kkurni/corefx,Priya91/corefx-1,dhoehna/corefx,690486439/corefx,DnlHarvey/corefx,ptoonen/corefx,DnlHarvey/corefx,Alcaro/corefx,seanshpark/corefx,lydonchandra/corefx,janhenke/corefx,Jiayili1/corefx,Priya91/corefx-1,dhoehna/corefx,rajansingh10/corefx,yizhang82/corefx,khdang/corefx,kyulee1/corefx,comdiv/corefx,dotnet-bot/corefx,stephenmichaelf/corefx,twsouthwick/corefx,akivafr123/corefx,mazong1123/corefx,brett25/corefx,iamjasonp/corefx,Chrisboh/corefx,oceanho/corefx,tstringer/corefx,twsouthwick/corefx,parjong/corefx,marksmeltzer/corefx,chenkennt/corefx,mokchhya/corefx,nbarbettini/corefx,JosephTremoulet/corefx,iamjasonp/corefx,jeremymeng/corefx,pgavlin/corefx,tijoytom/corefx,690486439/corefx,ravimeda/corefx,josguil/corefx,vrassouli/corefx,pallavit/corefx,parjong/corefx,twsouthwick/corefx,Yanjing123/corefx,alexandrnikitin/corefx,vijaykota/corefx,dkorolev/corefx,ellismg/corefx,Frank125/corefx,rjxby/corefx,viniciustaveira/corefx,DnlHarvey/corefx,alexperovich/corefx,KrisLee/corefx,ptoonen/corefx,ericstj/corefx,josguil/corefx,vrassouli/corefx,jcme/corefx,krk/corefx,bpschoch/corefx,chaitrakeshav/corefx,richlander/corefx,tijoytom/corefx,cnbin/corefx,popolan1986/corefx,stone-li/corefx,tijoytom/corefx,stormleoxia/corefx,akivafr123/corefx,dotnet-bot/corefx,jcme/corefx,mafiya69/corefx,Alcaro/corefx,uhaciogullari/corefx,dhoehna/corefx,benjamin-bader/corefx,janhenke/corefx,stone-li/corefx,shimingsg/corefx,cydhaselton/corefx,stephenmichaelf/corefx,benpye/corefx,brett25/corefx,wtgodbe/corefx,shana/corefx,marksmeltzer/corefx,Chrisboh/corefx,vs-team/corefx,josguil/corefx,ericstj/corefx,Ermiar/corefx,janhenke/corefx,erpframework/corefx,mmitche/corefx,mmitche/corefx,benjamin-bader/corefx,Chrisboh/corefx,claudelee/corefx,krytarowski/corefx,jmhardison/corefx,dhoehna/corefx,khdang/corefx,mafiya69/corefx,ptoonen/corefx,adamralph/corefx,jeremymeng/corefx,jhendrixMSFT/corefx | src/Common/src/Interop/Interop.PlatformDetection.cs | src/Common/src/Interop/Interop.PlatformDetection.cs | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Runtime.InteropServices;
// TODO: This implementation is temporary until System.Runtime.InteropServices.RuntimeInformation
// is available, at which point that should be used instead.
internal static partial class Interop
{
internal enum OperatingSystem
{
Windows,
Linux,
OSX,
FreeBSD
}
internal static bool IsWindows
{
get { return OperatingSystem.Windows == PlatformDetection.OperatingSystem; }
}
internal static bool IsLinux
{
get { return OperatingSystem.Linux == PlatformDetection.OperatingSystem; }
}
internal static bool IsOSX
{
get { return OperatingSystem.OSX == PlatformDetection.OperatingSystem; }
}
internal static bool IsFreeBSD
{
get { return OperatingSystem.FreeBSD == PlatformDetection.OperatingSystem; }
}
internal static class PlatformDetection
{
internal static OperatingSystem OperatingSystem { get { return s_os.Value; } }
private static readonly Lazy<OperatingSystem> s_os = new Lazy<OperatingSystem>(() =>
{
if (Environment.NewLine != "\r\n")
{
IntPtr buffer = Marshal.AllocHGlobal(8192); // the size of the uname struct is platform-specific; this should be large enough for any OS
try
{
if (uname(buffer) == 0)
{
switch (Marshal.PtrToStringAnsi((IntPtr)buffer))
{
case "Darwin":
return OperatingSystem.OSX;
case "FreeBSD":
return OperatingSystem.FreeBSD;
default:
return OperatingSystem.Linux;
}
}
}
finally { Marshal.FreeHGlobal(buffer); }
}
return OperatingSystem.Windows;
});
// not in src\Interop\Unix to avoiding pulling platform-dependent files into all projects
[DllImport("libc")]
private static extern uint uname(IntPtr buf);
}
}
| // 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;
// TODO: This implementation is temporary until System.Runtime.InteropServices.RuntimeInformation
// is available, at which point that should be used instead.
internal static partial class Interop
{
internal enum OperatingSystem
{
Windows,
Linux,
OSX
}
internal static bool IsWindows
{
get { return OperatingSystem.Windows == PlatformDetection.OperatingSystem; }
}
internal static bool IsLinux
{
get { return OperatingSystem.Linux == PlatformDetection.OperatingSystem; }
}
internal static bool IsOSX
{
get { return OperatingSystem.OSX == PlatformDetection.OperatingSystem; }
}
internal static class PlatformDetection
{
internal static OperatingSystem OperatingSystem { get { return s_os.Value; } }
private static readonly Lazy<OperatingSystem> s_os = new Lazy<OperatingSystem>(() =>
{
if (Environment.NewLine != "\r\n")
{
IntPtr buffer = Marshal.AllocHGlobal(8192); // the size of the uname struct is platform-specific; this should be large enough for any OS
try
{
if (uname(buffer) == 0)
{
switch (Marshal.PtrToStringAnsi((IntPtr)buffer))
{
case "Darwin":
return OperatingSystem.OSX;
default:
return OperatingSystem.Linux;
}
}
}
finally { Marshal.FreeHGlobal(buffer); }
}
return OperatingSystem.Windows;
});
// not in src\Interop\Unix to avoiding pulling platform-dependent files into all projects
[DllImport("libc")]
private static extern uint uname(IntPtr buf);
}
}
| mit | C# |
cc0a742d0ae4483771f61d6798b9e79167e5abf4 | add test around internally-used class | fluffynuts/PeanutButter,fluffynuts/PeanutButter,fluffynuts/PeanutButter | source/Utils/PeanutButter.DuckTyping.Tests/Extensions/TestDictionaryWrappingNameValueCollection.cs | source/Utils/PeanutButter.DuckTyping.Tests/Extensions/TestDictionaryWrappingNameValueCollection.cs | using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using NUnit.Framework;
using PeanutButter.DuckTyping.Extensions;
using PeanutButter.Utils;
using static PeanutButter.RandomGenerators.RandomValueGen;
namespace PeanutButter.DuckTyping.Tests.Extensions
{
[TestFixture]
public class TestDictionaryWrappingNameValueCollection: AssertionHelper
{
[Test]
public void ExplicitIEnumerator_GetEnumerator_ShouldReturnSameAs_GenericMethod()
{
// Arrange
var sut = Create();
// Pre-Assert
// Act
var reference = sut.GetEnumerator();
var result = (sut as IEnumerable).GetEnumerator();
// Assert
Expect(reference, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(result, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(reference.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
Expect(result.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
}
[Test]
public void Add_GivenKeyValuePair_ShouldAddItToTheUnderlyingCollection()
{
// Arrange
var collection = new NameValueCollection();
var sut = Create(collection);
var kvp = GetRandom<KeyValuePair<string, object>>();
// Pre-Assert
// Act
sut.Add(kvp);
// Assert
Expect(collection[kvp.Key], Is.EqualTo(kvp.Value));
}
[Test]
public void Clear_ShouldClearTheUnderlyingNameValueCollection()
{
// Arrange
var collection = new NameValueCollection();
collection.Add(GetRandomString(), GetRandomString());
var sut = Create(collection);
// Pre-Assert
// Act
sut.Clear();
// Assert
Expect(collection, Is.Empty);
}
private DictionaryWrappingNameValueCollection Create(
NameValueCollection collection = null,
bool caseInsensitive = false
) {
return new DictionaryWrappingNameValueCollection(
collection ?? new NameValueCollection(),
caseInsensitive
);
}
}
}
| using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using NUnit.Framework;
using PeanutButter.DuckTyping.Extensions;
using PeanutButter.Utils;
using static PeanutButter.RandomGenerators.RandomValueGen;
namespace PeanutButter.DuckTyping.Tests.Extensions
{
[TestFixture]
public class TestDictionaryWrappingNameValueCollection: AssertionHelper
{
[Test]
public void ExplicitIEnumerator_GetEnumerator_ShouldReturnSameAs_GenericMethod()
{
// Arrange
var sut = Create();
// Pre-Assert
// Act
var reference = sut.GetEnumerator();
var result = (sut as IEnumerable).GetEnumerator();
// Assert
Expect(reference, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(result, Is.InstanceOf<DictionaryWrappingNameValueCollectionEnumerator>());
Expect(reference.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
Expect(result.Get<DictionaryWrappingNameValueCollection>("Data"), Is.EqualTo(sut));
}
[Test]
public void Add_GivenKeyValuePair_ShouldAddItToTheUnderlyingCollection()
{
// Arrange
var collection = new NameValueCollection();
var sut = Create(collection);
var kvp = GetRandom<KeyValuePair<string, object>>();
// Pre-Assert
// Act
sut.Add(kvp);
// Assert
Expect(collection[kvp.Key], Is.EqualTo(kvp.Value));
}
private DictionaryWrappingNameValueCollection Create(
NameValueCollection collection = null,
bool caseInsensitive = false
) {
return new DictionaryWrappingNameValueCollection(
collection ?? new NameValueCollection(),
caseInsensitive
);
}
}
}
| bsd-3-clause | C# |
9a1b943df0bf6b67bf359e461a3bf1889d829873 | Fix ConcurrentDictionary usages in PubSubSimpleDispatchStrategy | Whiteknight/Acquaintance,Whiteknight/Acquaintance | Acquaintance/PubSub/PubSubSimpleDispatchStrategy.cs | Acquaintance/PubSub/PubSubSimpleDispatchStrategy.cs | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Acquaintance.PubSub
{
public class PubSubSimpleDispatchStrategy : IPubSubChannelDispatchStrategy
{
private readonly ConcurrentDictionary<string, IPubSubChannel> _pubSubChannels;
public PubSubSimpleDispatchStrategy()
{
_pubSubChannels = new ConcurrentDictionary<string, IPubSubChannel>();
}
private string GetPubSubKey(Type type, string name)
{
return $"Type={type.AssemblyQualifiedName}:Name={name ?? string.Empty}";
}
public IPubSubChannel<TPayload> GetChannelForSubscription<TPayload>(string name)
{
string key = GetPubSubKey(typeof(TPayload), name);
var channel = _pubSubChannels.GetOrAdd(key, k => new PubSubChannel<TPayload>());
var typedChannel = channel as IPubSubChannel<TPayload>;
if (typedChannel == null)
throw new Exception("Channel has incorrect type");
return typedChannel;
}
public IEnumerable<IPubSubChannel<TPayload>> GetExistingChannels<TPayload>(string name)
{
string key = GetPubSubKey(typeof(TPayload), name);
if (!_pubSubChannels.ContainsKey(key))
return Enumerable.Empty<IPubSubChannel<TPayload>>();
IPubSubChannel channel;
bool ok = _pubSubChannels.TryGetValue(key, out channel);
if (!ok || channel == null)
return Enumerable.Empty<IPubSubChannel<TPayload>>();
var typedChannel = channel as IPubSubChannel<TPayload>;
if (typedChannel == null)
return Enumerable.Empty<IPubSubChannel<TPayload>>();
return new[] { typedChannel };
}
public void Dispose()
{
foreach (var channel in _pubSubChannels.Values)
channel.Dispose();
_pubSubChannels.Clear();
}
}
} | using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace Acquaintance.PubSub
{
public class PubSubSimpleDispatchStrategy : IPubSubChannelDispatchStrategy
{
private readonly ConcurrentDictionary<string, IPubSubChannel> _pubSubChannels;
public PubSubSimpleDispatchStrategy()
{
_pubSubChannels = new ConcurrentDictionary<string, IPubSubChannel>();
}
private string GetPubSubKey(Type type, string name)
{
return $"Type={type.AssemblyQualifiedName}:Name={name ?? string.Empty}";
}
public IPubSubChannel<TPayload> GetChannelForSubscription<TPayload>(string name)
{
string key = GetPubSubKey(typeof(TPayload), name);
if (!_pubSubChannels.ContainsKey(key))
_pubSubChannels.TryAdd(key, new PubSubChannel<TPayload>());
var channel = _pubSubChannels[key] as IPubSubChannel<TPayload>;
if (channel == null)
throw new Exception("Channel has incorrect type");
return channel;
}
public IEnumerable<IPubSubChannel<TPayload>> GetExistingChannels<TPayload>(string name)
{
string key = GetPubSubKey(typeof(TPayload), name);
if (!_pubSubChannels.ContainsKey(key))
return Enumerable.Empty<IPubSubChannel<TPayload>>();
var channel = _pubSubChannels[key] as IPubSubChannel<TPayload>;
if (channel == null)
return Enumerable.Empty<IPubSubChannel<TPayload>>();
return new[] { channel };
}
public void Dispose()
{
foreach (var channel in _pubSubChannels.Values)
channel.Dispose();
_pubSubChannels.Clear();
}
}
} | apache-2.0 | C# |
a9024911a2c7d328b8bfa553e19a0cc628a4435a | Write to debug in debug env | LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC,LibertyLocked/RestRPC | WebScriptHook.Framework/Logger.cs | WebScriptHook.Framework/Logger.cs | using System;
using System.IO;
using System.Diagnostics;
namespace WebScriptHook.Framework
{
public class Logger
{
public static string FileName
{
get;
internal set;
} = "WebScriptHook.log";
public static LogType LogLevel
{
get;
internal set;
} = LogType.Info | LogType.Warning | LogType.Error;
public static void Log(object message, LogType logType)
{
if ((LogLevel & logType) != LogType.None)
{
string formatedMessage = "[" + DateTime.Now + "] [" + logType.ToString() + "]: " + message;
File.AppendAllText(FileName, formatedMessage + Environment.NewLine);
#if DEBUG
Debug.WriteLine(formatedMessage);
#endif
}
}
public static void Log(object message)
{
Log(message, LogType.Info);
}
}
}
| using System;
using System.IO;
namespace WebScriptHook.Framework
{
public class Logger
{
public static string FileName
{
get;
internal set;
} = "WebScriptHook.log";
public static LogType LogLevel
{
get;
internal set;
} = LogType.Info | LogType.Warning | LogType.Error;
public static void Log(object message, LogType logType)
{
if ((LogLevel & logType) != LogType.None)
{
File.AppendAllText(FileName, "[" + DateTime.Now + "] [" + logType.ToString() + "]: " + message + Environment.NewLine);
}
}
public static void Log(object message)
{
Log(message, LogType.Info);
}
}
}
| mit | C# |
00bb58a9b2c17c1502cee26d1385429155a495a6 | Add InputNullWillBeEmpty | sdcb/sdmap | sdmap/test/sdmap.test/MacroImplTest/ValTest.cs | sdmap/test/sdmap.test/MacroImplTest/ValTest.cs | using sdmap.Macros.Implements;
using sdmap.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace sdmap.test.MacroImplTest
{
public class ValTest
{
[Fact]
public void HelloWorld()
{
var val = "Hello World";
var actual = CommonMacros.ValueItSelf(SdmapContext.CreateEmpty(), val, null);
Assert.True(actual.IsSuccess);
Assert.Equal(val, actual.Value);
}
[Fact]
public void InputNullWillBeEmpty()
{
string val = null;
var actual = CommonMacros.ValueItSelf(SdmapContext.CreateEmpty(), val, null);
Assert.True(actual.IsSuccess);
Assert.Equal(string.Empty, actual.Value);
}
}
}
| using sdmap.Macros.Implements;
using sdmap.Runtime;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Xunit;
namespace sdmap.test.MacroImplTest
{
public class ValTest
{
[Fact]
public void HelloWorld()
{
var val = "Hello World";
var actual = CommonMacros.ValueItSelf(SdmapContext.CreateEmpty(), val, null);
Assert.True(actual.IsSuccess);
Assert.Equal(val, actual.Value);
}
}
}
| mit | C# |
1642e1f7c8d6c7687c350fd08356a7e09beccdac | Drop player after teleporting | aornelas/Tiny-Planets,aornelas/Tiny-Planets | Assets/GameController.cs | Assets/GameController.cs | using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject currentPlanet;
private PlanetController planetController;
private int collectedCount;
private bool portalOpened;
void Start()
{
ResetPlanet();
}
void Update()
{
if (collectedCount >= 3 && !portalOpened)
{
Invoke("OpenPortal", 0.25f);
portalOpened = true;
}
}
public void PickUpCollectible(GameObject collectible)
{
collectible.GetComponent<CollectibleController>().PickUp();
collectedCount++;
}
public void TeleportToNextPlanet()
{
planetController.NextPlanet();
currentPlanet = planetController.nextPlanet;
ResetPlanet();
ResetPlayer();
}
private void ResetPlanet()
{
collectedCount = 0;
portalOpened = false;
planetController = currentPlanet.GetComponent<PlanetController>();
}
private void ResetPlayer()
{
gameObject.GetComponentsInChildren<PlayerController>()[0].ResetPlayer();
}
private void OpenPortal()
{
planetController.portal.SetActive(true);
GetComponent<AudioSource>().Play();
}
}
| using UnityEngine;
using System.Collections;
public class GameController : MonoBehaviour {
public GameObject currentPlanet;
private PlanetController planetController;
private int collectedCount;
private bool portalOpened;
void Start()
{
ResetPlanet();
}
void Update()
{
if (collectedCount >= 3 && !portalOpened)
{
Invoke("OpenPortal", 0.25f);
portalOpened = true;
}
}
public void PickUpCollectible(GameObject collectible)
{
collectible.GetComponent<CollectibleController>().PickUp();
collectedCount++;
}
public void TeleportToNextPlanet()
{
planetController.NextPlanet();
currentPlanet = planetController.nextPlanet;
ResetPlanet();
}
private void ResetPlanet()
{
collectedCount = 0;
portalOpened = false;
planetController = currentPlanet.GetComponent<PlanetController>();
}
private void OpenPortal()
{
planetController.portal.SetActive(true);
GetComponent<AudioSource>().Play();
}
}
| mit | C# |
1cfd3aea71e3c04c6bd4d012ea1343c0fa49f0dd | Fix collision issue in Ladder. | holycattle/towerofgod | Assets/Scripts/Ladder.cs | Assets/Scripts/Ladder.cs | using UnityEngine;
using System.Collections;
public class Ladder : MonoBehaviour {
private float climbingSpeed = 1.75f;
private bool withinLadder = false;
private GameObject player;
// Use this for initialization
void Start () {
}
void FixedUpdate() {
if(withinLadder) {
float direction = Input.GetAxis("Vertical");
if(Mathf.Abs(direction) > 0.1f) {
player.rigidbody2D.gravityScale = 0;
Debug.Log("Should be climbing");
//player.transform.Translate(new Vector2(0, Time.fixedDeltaTime * climbingSpeed * direction));
player.transform.rigidbody2D.velocity = new Vector2(player.transform.rigidbody2D.velocity.x, climbingSpeed * direction);
}
if(Input.GetButtonDown("Jump")) {
player.rigidbody2D.gravityScale = 9.81f;
}
}
}
void OnTriggerStay2D(Collider2D other) {
if(other.gameObject.name == "Player") {
withinLadder = true;
player = other.gameObject;
}
}
void OnTriggerExit2D(Collider2D other) {
if(other.gameObject.name == "Player") {
withinLadder = false;
other.gameObject.rigidbody2D.gravityScale = 9.81f;
}
}
}
| using UnityEngine;
using System.Collections;
public class Ladder : MonoBehaviour {
private float climbingSpeed = 1.75f;
private bool withinLadder = false;
private GameObject player;
// Use this for initialization
void Start () {
}
void FixedUpdate() {
if(withinLadder) {
float direction = Input.GetAxis("Vertical");
if(Mathf.Abs(direction) > 0.1f) {
player.rigidbody2D.gravityScale = 0;
Debug.Log("Should be climbing");
//player.transform.Translate(new Vector2(0, Time.fixedDeltaTime * climbingSpeed * direction));
player.transform.rigidbody2D.velocity = new Vector2(player.transform.rigidbody2D.velocity.x, climbingSpeed * direction);
}
if(Input.GetButtonDown("Jump")) {
player.rigidbody2D.gravityScale = 9.81f;
}
}
}
void OnTriggerStay2D(Collider2D other) {
if(other.gameObject.name == "Player") {
withinLadder = true;
player = other.gameObject;
}
}
void OnTriggerExit2D(Collider2D other) {
if(other.gameObject.name == "Player") {
withinLadder = false;
player.rigidbody2D.gravityScale = 9.81f;
}
}
}
| mit | C# |
6de08db65316679f99830c6448540aeb5b89ea06 | Add removed skin component back | peppy/osu-new,smoogipoo/osu,smoogipoo/osu,UselessToucan/osu,ppy/osu,ppy/osu,UselessToucan/osu,NeoAdonis/osu,ppy/osu,peppy/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,smoogipooo/osu,NeoAdonis/osu,peppy/osu,peppy/osu | osu.Game.Rulesets.Taiko/TaikoSkinComponents.cs | osu.Game.Rulesets.Taiko/TaikoSkinComponents.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.
namespace osu.Game.Rulesets.Taiko
{
public enum TaikoSkinComponents
{
InputDrum,
CentreHit,
RimHit,
DrumRollBody,
DrumRollTick,
Swell,
HitTarget,
TaikoDon
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
namespace osu.Game.Rulesets.Taiko
{
public enum TaikoSkinComponents
{
InputDrum,
RimHit,
DrumRollBody,
DrumRollTick,
Swell,
HitTarget,
TaikoDon
}
}
| mit | C# |
59f192ce9b5bd45196bb63c52ac0a558dd2e0b45 | add documentation | Ackara/Daterpillar | Code/Daterpillar.Core/Annotation/ColumnAttribute.cs | Code/Daterpillar.Core/Annotation/ColumnAttribute.cs | using System;
namespace Gigobyte.Daterpillar.Annotation
{
/// <summary>
/// Specifies the property is mapped to a table column.
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ColumnAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="ColumnAttribute"/> class.
/// </summary>
/// <param name="name">The name.</param>
public ColumnAttribute(string name)
{
Name = name;
}
/// <summary>
/// The name of the column.
/// </summary>
public readonly string Name;
/// <summary>
/// Gets or sets a value indicating whether this instance is a key.
/// </summary>
/// <value>
/// <c>true</c> if this instance is key; otherwise, <c>false</c>.
/// </value>
public bool IsKey { get; set; }
/// <summary>
/// Gets or sets whether the column is auto incremented.
/// </summary>
/// <value>
/// <c>true</c> if [automatic increment]; otherwise, <c>false</c>.
/// </value>
public bool AutoIncrement { get; set; }
}
} | using System;
namespace Gigobyte.Daterpillar.Annotation
{
/// <summary>
///
/// </summary>
/// <seealso cref="System.Attribute" />
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class ColumnAttribute : Attribute
{
public ColumnAttribute(string name)
{
Name = name;
}
public readonly string Name;
public bool IsKey { get; set; }
public bool AutoIncrement { get; set; }
}
} | mit | C# |
6929b8c21a62433bce6cc9b284b2f0a644ec2d92 | Update AssemblyInfo version ranges to allow 0.6.0-* | aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore,aspnet/AspNetCore | tooling/Microsoft.VisualStudio.BlazorExtension/Properties/AssemblyInfo.cs | tooling/Microsoft.VisualStudio.BlazorExtension/Properties/AssemblyInfo.cs | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
// Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show
// up in the Load context, which means that we can use ServiceHub and other nice things.
//
// The versions here need to match what the build is producing. If you change the version numbers
// for the Blazor assemblies, this needs to change as well.
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.6.0.0",
NewVersion = "0.6.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.6.0.0",
NewVersion = "0.6.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "AngleSharp",
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.9.9.0",
NewVersion = "0.9.9.0")] | // Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell;
// Add binding redirects for each assembly we ship in VS. This is required so that these assemblies show
// up in the Load context, which means that we can use ServiceHub and other nice things.
//
// The versions here need to match what the build is producing. If you change the version numbers
// for the Blazor assemblies, this needs to change as well.
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.AspNetCore.Blazor.Razor.Extensions",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.5.0.0",
NewVersion = "0.5.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "Microsoft.VisualStudio.LanguageServices.Blazor",
GenerateCodeBase = true,
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.5.0.0",
NewVersion = "0.5.0.0")]
[assembly: ProvideBindingRedirection(
AssemblyName = "AngleSharp",
PublicKeyToken = "",
OldVersionLowerBound = "0.0.0.0",
OldVersionUpperBound = "0.9.9.0",
NewVersion = "0.9.9.0")] | apache-2.0 | C# |
69a4ff8e83144ac452d6cbe6d4b6961031ca2c12 | Fix MathExtensions.AsDouble() affecting HtmlViewer. | wasteam/waslibs,wasteam/waslibs,pellea/waslibs,wasteam/waslibs,janabimustafa/waslibs,pellea/waslibs,pellea/waslibs,janabimustafa/waslibs,janabimustafa/waslibs | src/AppStudio.Uwp/Extensions/MathExtensions.cs | src/AppStudio.Uwp/Extensions/MathExtensions.cs | using System;
using System.Globalization;
namespace AppStudio.Uwp
{
public static class MathExtensions
{
public static int Mod(this int value, int module)
{
int res = value % module;
return res >= 0 ? res : (res + module) % module;
}
public static int IncMod(this int value, int module)
{
return (value + 1).Mod(module);
}
public static int DecMod(this int value, int module)
{
return (value - 1).Mod(module);
}
public static double Mod(this double value, double module)
{
double res = value % module;
return res >= 0 ? res : (res + module) % module;
}
public static double AsDouble(this string str)
{
str = str.Replace(',', '.');
double d = 0.0;
if (!String.IsNullOrEmpty(str))
{
Double.TryParse(str, NumberStyles.AllowDecimalPoint, CultureInfo.InvariantCulture, out d);
}
return d;
}
}
}
| using System;
namespace AppStudio.Uwp
{
public static class MathExtensions
{
public static int Mod(this int value, int module)
{
int res = value % module;
return res >= 0 ? res : (res + module) % module;
}
public static int IncMod(this int value, int module)
{
return (value + 1).Mod(module);
}
public static int DecMod(this int value, int module)
{
return (value - 1).Mod(module);
}
public static double Mod(this double value, double module)
{
double res = value % module;
return res >= 0 ? res : (res + module) % module;
}
public static double AsDouble(this string str)
{
double d = 0.0;
if (!String.IsNullOrEmpty(str))
{
Double.TryParse(str, out d);
}
return d;
}
}
}
| mit | C# |
5e7867c097a02d554d056b89764a12af362cba66 | add ApplicationName to Role | ifilipenko/Building-Blocks,ifilipenko/Building-Blocks,ifilipenko/Building-Blocks | src/BuildingBlocks.Membership/Entities/Role.cs | src/BuildingBlocks.Membership/Entities/Role.cs | using System;
using System.Collections.Generic;
namespace BuildingBlocks.Membership.Entities
{
public class Role
{
public Role()
{
Users = new List<string>();
}
public Guid RoleId { get; set; }
public string ApplicationName { get; set; }
public string RoleName { get; set; }
public string Description { get; set; }
public IEnumerable<string> Users { get; set; }
}
} | using System;
using System.Collections.Generic;
namespace BuildingBlocks.Membership.Entities
{
public class Role
{
private IList<string> _users;
public Role()
{
_users = new List<string>();
}
public virtual Guid RoleId { get; set; }
public virtual string RoleName { get; set; }
public virtual string Description { get; set; }
public virtual IEnumerable<string> Users
{
get { return _users; }
set { _users = (IList<string>)value; }
}
}
} | apache-2.0 | C# |
f5543101c90d7187872192905870409263a587ef | Rephrase ConventionDiscoverer in preparation for splitting Convention into separate Discovery and Lifecycle concerns. | fixie/fixie | src/Fixie/Execution/ConventionDiscoverer.cs | src/Fixie/Execution/ConventionDiscoverer.cs | namespace Fixie.Execution
{
using System;
using System.Linq;
using System.Reflection;
using Cli;
using Conventions;
class ConventionDiscoverer
{
readonly Assembly assembly;
readonly string[] conventionArguments;
public ConventionDiscoverer(Assembly assembly, string[] conventionArguments)
{
this.assembly = assembly;
this.conventionArguments = conventionArguments;
}
public Convention GetConvention()
{
if (assembly.GetName().Name == "Fixie.Tests")
return new DefaultConvention();
return Construct(ConventionType());
}
Type ConventionType()
{
var customConventionTypes = assembly
.GetTypes()
.Where(t => t.IsSubclassOf(typeof(Convention)) && !t.IsAbstract)
.ToArray();
if (customConventionTypes.Length > 1)
{
throw new Exception(
"A test assembly should have at most one convention, " +
"but the following conventions were discovered:" + Environment.NewLine +
String.Join(Environment.NewLine,
customConventionTypes
.Select(x => $"\t{x.FullName}")));
}
if (customConventionTypes.Any())
return customConventionTypes.Single();
return typeof(DefaultConvention);
}
Convention Construct(Type type)
{
try
{
return (Convention)CommandLine.Parse(type, conventionArguments);
}
catch (CommandLineException ex)
{
throw new Exception($"Command line argument parsing failed while attempting to construct an instance of type '{type.FullName}'. " + ex.Message);
}
catch (Exception ex)
{
throw new Exception($"Could not construct an instance of type '{type.FullName}'.", ex);
}
}
}
} | namespace Fixie.Execution
{
using System;
using System.Linq;
using System.Reflection;
using Cli;
using Conventions;
class ConventionDiscoverer
{
readonly Assembly assembly;
readonly string[] conventionArguments;
public ConventionDiscoverer(Assembly assembly, string[] conventionArguments)
{
this.assembly = assembly;
this.conventionArguments = conventionArguments;
}
public Convention GetConvention()
{
if (assembly.GetName().Name == "Fixie.Tests")
return new DefaultConvention();
var locallyDeclaredConventionTypes = LocallyDeclaredConventionTypes();
if (locallyDeclaredConventionTypes.Length > 1)
{
throw new Exception(
"A test assembly should have at most one convention, " +
"but the following conventions were discovered:" + Environment.NewLine +
String.Join(Environment.NewLine,
locallyDeclaredConventionTypes
.Select(x => $"\t{x.FullName}")));
}
if (!locallyDeclaredConventionTypes.Any())
return new DefaultConvention();
return ConstructConvention(locallyDeclaredConventionTypes.Single());
}
Type[] LocallyDeclaredConventionTypes()
{
return assembly
.GetTypes()
.Where(t => t.IsSubclassOf(typeof(Convention)) && !t.IsAbstract)
.ToArray();
}
Convention ConstructConvention(Type type)
{
try
{
return (Convention)CommandLine.Parse(type, conventionArguments);
}
catch (CommandLineException ex)
{
throw new Exception($"Command line argument parsing failed while attempting to construct an instance of type '{type.FullName}'. " + ex.Message);
}
catch (Exception ex)
{
throw new Exception($"Could not construct an instance of type '{type.FullName}'.", ex);
}
}
}
} | mit | C# |
6bbcf83e1e3e6c32f0e41ada956796921f74cbc8 | Add action | muhammedikinci/FuzzyCore | FuzzyCore/ConcreteCommands/GetFolderList_Command.cs | FuzzyCore/ConcreteCommands/GetFolderList_Command.cs | using FuzzyCore.Data;
using FuzzyCore.Commands;
namespace FuzzyCore.Server
{
public class GetFolderList_Command : Command
{
public GetFolderList_Command(JsonCommand comm) : base(comm)
{
}
public override void Execute()
{
GetFolderList folderList = new GetFolderList(Comm);
folderList.SendFoldersName();
}
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FuzzyCore.Data;
using FuzzyCore.Commands;
namespace FuzzyCore.Server
{
public class GetFolderList_Command : Command
{
public GetFolderList_Command(JsonCommand comm) : base(comm)
{
}
public override void Execute()
{
GetFolderList GetFolderList_Command = new GetFolderList();
GetFolderList_Command.GetFoldersName(Comm);
}
}
}
| mit | C# |
b9741cd1fce32479ae7ecb4b6563d8acd0cd13f8 | remove double ; | RadicalFx/radical | src/Radical/Extensions/EntityViewExtensions.cs | src/Radical/Extensions/EntityViewExtensions.cs | using Radical.ComponentModel;
using Radical.Validation;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Radical
{
public static class EntityViewExtensions
{
public static IEnumerable<T> AsEntityItems<T>(this IEntityView<T> view)
where T : class
{
return view.Select(item => item.EntityItem);
}
public static IEntityView<T> ApplySimpleSort<T>(this IEntityView<T> view, string property)
where T : class
{
Ensure.That(view).Named("view").IsNotNull();
var actualDirection = view.SortDirection;
var actualProperty = view.SortProperty == null ? (string)null : view.SortProperty.Name;
if (property != null && property == actualProperty)
{
/*
* Dobbiamo invertire il sort attuale.
*/
if (actualDirection == ListSortDirection.Ascending)
{
actualDirection = ListSortDirection.Descending;
}
else
{
actualDirection = ListSortDirection.Ascending;
}
var lsd = new ListSortDescription(view.GetProperty(property), actualDirection);
view.ApplySort(new ListSortDescriptionCollection(new[] { lsd }));
}
else
{
/*
* Arriviamo qui se un "nuovo" sort o se
* il sort su null
*/
view.ApplySort(property);
}
return view;
}
}
}
| using Radical.ComponentModel;
using Radical.Validation;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
namespace Radical
{
public static class EntityViewExtensions
{
public static IEnumerable<T> AsEntityItems<T>(this IEntityView<T> view)
where T : class
{
return view.Select(item => item.EntityItem); ;
}
public static IEntityView<T> ApplySimpleSort<T>(this IEntityView<T> view, string property)
where T : class
{
Ensure.That(view).Named("view").IsNotNull();
var actualDirection = view.SortDirection;
var actualProperty = view.SortProperty == null ? (string)null : view.SortProperty.Name;
if (property != null && property == actualProperty)
{
/*
* Dobbiamo invertire il sort attuale.
*/
if (actualDirection == ListSortDirection.Ascending)
{
actualDirection = ListSortDirection.Descending;
}
else
{
actualDirection = ListSortDirection.Ascending;
}
var lsd = new ListSortDescription(view.GetProperty(property), actualDirection);
view.ApplySort(new ListSortDescriptionCollection(new[] { lsd }));
}
else
{
/*
* Arriviamo qui se un "nuovo" sort o se
* il sort su null
*/
view.ApplySort(property);
}
return view;
}
}
}
| mit | C# |
e02ec11f03552a48d409fb3707d0d24f9067dc24 | Fix for unsubscribe freezing ui thread | JKorf/Binance.Net | Binance.Net/Objects/BinanceStreamConnection.cs | Binance.Net/Objects/BinanceStreamConnection.cs | using System.Threading.Tasks;
using CryptoExchange.Net.Interfaces;
namespace Binance.Net.Objects
{
internal class BinanceStream
{
internal bool TryReconnect { get; set; } = true;
public IWebsocket Socket { get; set; }
public BinanceStreamSubscription StreamResult { get; set; }
public async Task Close()
{
TryReconnect = false;
await Socket.Close().ConfigureAwait(false);
}
}
}
| using System.Threading.Tasks;
using CryptoExchange.Net.Interfaces;
namespace Binance.Net.Objects
{
internal class BinanceStream
{
internal bool TryReconnect { get; set; } = true;
public IWebsocket Socket { get; set; }
public BinanceStreamSubscription StreamResult { get; set; }
public async Task Close()
{
TryReconnect = false;
await Socket.Close();
}
}
}
| mit | C# |
022d5b205fda8f99f7adccea838142abe9a7da32 | Update IAsyncStreamWriter.cs | jboeuf/grpc,donnadionne/grpc,grpc/grpc,grpc/grpc,ejona86/grpc,ejona86/grpc,jtattermusch/grpc,ejona86/grpc,firebase/grpc,ctiller/grpc,ejona86/grpc,firebase/grpc,grpc/grpc,jtattermusch/grpc,jboeuf/grpc,jtattermusch/grpc,firebase/grpc,ejona86/grpc,donnadionne/grpc,ejona86/grpc,jboeuf/grpc,nicolasnoble/grpc,vjpai/grpc,donnadionne/grpc,vjpai/grpc,grpc/grpc,vjpai/grpc,jtattermusch/grpc,jtattermusch/grpc,stanley-cheung/grpc,ejona86/grpc,donnadionne/grpc,firebase/grpc,ctiller/grpc,grpc/grpc,vjpai/grpc,donnadionne/grpc,ejona86/grpc,ctiller/grpc,grpc/grpc,grpc/grpc,ctiller/grpc,jtattermusch/grpc,firebase/grpc,stanley-cheung/grpc,jtattermusch/grpc,donnadionne/grpc,stanley-cheung/grpc,grpc/grpc,stanley-cheung/grpc,grpc/grpc,jtattermusch/grpc,stanley-cheung/grpc,jboeuf/grpc,firebase/grpc,vjpai/grpc,donnadionne/grpc,firebase/grpc,ctiller/grpc,ctiller/grpc,ctiller/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,nicolasnoble/grpc,jboeuf/grpc,donnadionne/grpc,nicolasnoble/grpc,firebase/grpc,jboeuf/grpc,nicolasnoble/grpc,vjpai/grpc,ctiller/grpc,ejona86/grpc,firebase/grpc,nicolasnoble/grpc,ctiller/grpc,stanley-cheung/grpc,vjpai/grpc,jtattermusch/grpc,stanley-cheung/grpc,grpc/grpc,nicolasnoble/grpc,jboeuf/grpc,ctiller/grpc,donnadionne/grpc,jtattermusch/grpc,nicolasnoble/grpc,jboeuf/grpc,donnadionne/grpc,jboeuf/grpc,firebase/grpc,nicolasnoble/grpc,firebase/grpc,jboeuf/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,vjpai/grpc,jtattermusch/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,nicolasnoble/grpc,grpc/grpc,jtattermusch/grpc,vjpai/grpc,vjpai/grpc,firebase/grpc,nicolasnoble/grpc,donnadionne/grpc,stanley-cheung/grpc,nicolasnoble/grpc,ctiller/grpc,ctiller/grpc,vjpai/grpc,jboeuf/grpc,jboeuf/grpc | src/csharp/Grpc.Core.Api/IAsyncStreamWriter.cs | src/csharp/Grpc.Core.Api/IAsyncStreamWriter.cs | #region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grpc.Core
{
/// <summary>
/// A writable stream of messages.
/// </summary>
/// <typeparam name="T">The message type.</typeparam>
public interface IAsyncStreamWriter<in T>
{
/// <summary>
/// Writes a message asynchronously. Only one write can be pending at a time.
/// </summary>
/// <param name="message">The message to be written. Cannot be null.</param>
Task WriteAsync(T message);
/// <summary>
/// Write options that will be used for the next write.
/// If null, default options will be used.
/// Once set, this property maintains its value across subsequent
/// writes.
/// </summary>
WriteOptions WriteOptions { get; set; }
}
}
| #region Copyright notice and license
// Copyright 2015 gRPC authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Grpc.Core
{
/// <summary>
/// A writable stream of messages.
/// </summary>
/// <typeparam name="T">The message type.</typeparam>
public interface IAsyncStreamWriter<in T>
{
/// <summary>
/// Writes a single asynchronously. Only one write can be pending at a time.
/// </summary>
/// <param name="message">the message to be written. Cannot be null.</param>
Task WriteAsync(T message);
/// <summary>
/// Write options that will be used for the next write.
/// If null, default options will be used.
/// Once set, this property maintains its value across subsequent
/// writes.
/// </summary>
WriteOptions WriteOptions { get; set; }
}
}
| apache-2.0 | C# |
1cd9c1c3123dec7a6b1385cf1c20f6057881c0f3 | Revert "Set correct output type for RemoveRoleDefinition" | yadavbdev/azure-powershell,SarahRogers/azure-powershell,stankovski/azure-powershell,juvchan/azure-powershell,DeepakRajendranMsft/azure-powershell,haocs/azure-powershell,dulems/azure-powershell,chef-partners/azure-powershell,AzureAutomationTeam/azure-powershell,nickheppleston/azure-powershell,atpham256/azure-powershell,alfantp/azure-powershell,bgold09/azure-powershell,dominiqa/azure-powershell,yadavbdev/azure-powershell,kagamsft/azure-powershell,DeepakRajendranMsft/azure-powershell,bgold09/azure-powershell,DeepakRajendranMsft/azure-powershell,haocs/azure-powershell,kagamsft/azure-powershell,devigned/azure-powershell,jianghaolu/azure-powershell,enavro/azure-powershell,CamSoper/azure-powershell,enavro/azure-powershell,chef-partners/azure-powershell,seanbamsft/azure-powershell,dulems/azure-powershell,atpham256/azure-powershell,krkhan/azure-powershell,juvchan/azure-powershell,devigned/azure-powershell,TaraMeyer/azure-powershell,dominiqa/azure-powershell,seanbamsft/azure-powershell,tonytang-microsoft-com/azure-powershell,praveennet/azure-powershell,PashaPash/azure-powershell,AzureRT/azure-powershell,tonytang-microsoft-com/azure-powershell,seanbamsft/azure-powershell,PashaPash/azure-powershell,devigned/azure-powershell,krkhan/azure-powershell,zaevans/azure-powershell,akurmi/azure-powershell,nemanja88/azure-powershell,jtlibing/azure-powershell,pelagos/azure-powershell,yantang-msft/azure-powershell,pelagos/azure-powershell,naveedaz/azure-powershell,rhencke/azure-powershell,jianghaolu/azure-powershell,yadavbdev/azure-powershell,pankajsn/azure-powershell,hungmai-msft/azure-powershell,haocs/azure-powershell,bgold09/azure-powershell,naveedaz/azure-powershell,yantang-msft/azure-powershell,AzureAutomationTeam/azure-powershell,yantang-msft/azure-powershell,jianghaolu/azure-powershell,yoavrubin/azure-powershell,naveedaz/azure-powershell,zaevans/azure-powershell,rohmano/azure-powershell,pomortaz/azure-powershell,AzureRT/azure-powershell,kagamsft/azure-powershell,jasper-schneider/azure-powershell,DeepakRajendranMsft/azure-powershell,hallihan/azure-powershell,jtlibing/azure-powershell,jasper-schneider/azure-powershell,oaastest/azure-powershell,AzureRT/azure-powershell,atpham256/azure-powershell,pelagos/azure-powershell,zhencui/azure-powershell,oaastest/azure-powershell,TaraMeyer/azure-powershell,rohmano/azure-powershell,enavro/azure-powershell,ailn/azure-powershell,seanbamsft/azure-powershell,dominiqa/azure-powershell,atpham256/azure-powershell,praveennet/azure-powershell,akurmi/azure-powershell,ankurchoubeymsft/azure-powershell,pankajsn/azure-powershell,jianghaolu/azure-powershell,ClogenyTechnologies/azure-powershell,ailn/azure-powershell,pomortaz/azure-powershell,akurmi/azure-powershell,atpham256/azure-powershell,shuagarw/azure-powershell,jtlibing/azure-powershell,pankajsn/azure-powershell,devigned/azure-powershell,kagamsft/azure-powershell,ailn/azure-powershell,zaevans/azure-powershell,praveennet/azure-powershell,chef-partners/azure-powershell,AzureAutomationTeam/azure-powershell,ankurchoubeymsft/azure-powershell,rhencke/azure-powershell,rohmano/azure-powershell,krkhan/azure-powershell,enavro/azure-powershell,devigned/azure-powershell,TaraMeyer/azure-powershell,kagamsft/azure-powershell,arcadiahlyy/azure-powershell,akurmi/azure-powershell,Matt-Westphal/azure-powershell,stankovski/azure-powershell,naveedaz/azure-powershell,Matt-Westphal/azure-powershell,nickheppleston/azure-powershell,SarahRogers/azure-powershell,AzureAutomationTeam/azure-powershell,jasper-schneider/azure-powershell,hovsepm/azure-powershell,yoavrubin/azure-powershell,tonytang-microsoft-com/azure-powershell,nickheppleston/azure-powershell,yantang-msft/azure-powershell,jtlibing/azure-powershell,Matt-Westphal/azure-powershell,nickheppleston/azure-powershell,mayurid/azure-powershell,shuagarw/azure-powershell,AzureRT/azure-powershell,ankurchoubeymsft/azure-powershell,rohmano/azure-powershell,shuagarw/azure-powershell,yadavbdev/azure-powershell,tonytang-microsoft-com/azure-powershell,hungmai-msft/azure-powershell,SarahRogers/azure-powershell,dulems/azure-powershell,pelagos/azure-powershell,SarahRogers/azure-powershell,seanbamsft/azure-powershell,dominiqa/azure-powershell,pankajsn/azure-powershell,arcadiahlyy/azure-powershell,jasper-schneider/azure-powershell,AzureRT/azure-powershell,rhencke/azure-powershell,alfantp/azure-powershell,nemanja88/azure-powershell,bgold09/azure-powershell,naveedaz/azure-powershell,pomortaz/azure-powershell,tonytang-microsoft-com/azure-powershell,zhencui/azure-powershell,juvchan/azure-powershell,stankovski/azure-powershell,hovsepm/azure-powershell,hallihan/azure-powershell,zhencui/azure-powershell,arcadiahlyy/azure-powershell,shuagarw/azure-powershell,zhencui/azure-powershell,jtlibing/azure-powershell,ailn/azure-powershell,rohmano/azure-powershell,nemanja88/azure-powershell,rhencke/azure-powershell,shuagarw/azure-powershell,rohmano/azure-powershell,pankajsn/azure-powershell,jasper-schneider/azure-powershell,juvchan/azure-powershell,nemanja88/azure-powershell,hovsepm/azure-powershell,alfantp/azure-powershell,praveennet/azure-powershell,hungmai-msft/azure-powershell,TaraMeyer/azure-powershell,yoavrubin/azure-powershell,hovsepm/azure-powershell,hallihan/azure-powershell,juvchan/azure-powershell,AzureRT/azure-powershell,oaastest/azure-powershell,alfantp/azure-powershell,Matt-Westphal/azure-powershell,stankovski/azure-powershell,jianghaolu/azure-powershell,arcadiahlyy/azure-powershell,hovsepm/azure-powershell,PashaPash/azure-powershell,yoavrubin/azure-powershell,devigned/azure-powershell,dulems/azure-powershell,CamSoper/azure-powershell,zhencui/azure-powershell,nemanja88/azure-powershell,praveennet/azure-powershell,hungmai-msft/azure-powershell,PashaPash/azure-powershell,akurmi/azure-powershell,yantang-msft/azure-powershell,zhencui/azure-powershell,mayurid/azure-powershell,hallihan/azure-powershell,SarahRogers/azure-powershell,enavro/azure-powershell,naveedaz/azure-powershell,haocs/azure-powershell,CamSoper/azure-powershell,ClogenyTechnologies/azure-powershell,mayurid/azure-powershell,hungmai-msft/azure-powershell,zaevans/azure-powershell,yadavbdev/azure-powershell,zaevans/azure-powershell,oaastest/azure-powershell,nickheppleston/azure-powershell,krkhan/azure-powershell,ankurchoubeymsft/azure-powershell,pankajsn/azure-powershell,mayurid/azure-powershell,ClogenyTechnologies/azure-powershell,hallihan/azure-powershell,alfantp/azure-powershell,CamSoper/azure-powershell,AzureAutomationTeam/azure-powershell,chef-partners/azure-powershell,pomortaz/azure-powershell,pomortaz/azure-powershell,rhencke/azure-powershell,TaraMeyer/azure-powershell,yoavrubin/azure-powershell,CamSoper/azure-powershell,arcadiahlyy/azure-powershell,ClogenyTechnologies/azure-powershell,bgold09/azure-powershell,AzureAutomationTeam/azure-powershell,pelagos/azure-powershell,Matt-Westphal/azure-powershell,ankurchoubeymsft/azure-powershell,krkhan/azure-powershell,hungmai-msft/azure-powershell,dominiqa/azure-powershell,PashaPash/azure-powershell,yantang-msft/azure-powershell,DeepakRajendranMsft/azure-powershell,seanbamsft/azure-powershell,krkhan/azure-powershell,ailn/azure-powershell,oaastest/azure-powershell,chef-partners/azure-powershell,atpham256/azure-powershell,mayurid/azure-powershell,ClogenyTechnologies/azure-powershell,haocs/azure-powershell,dulems/azure-powershell,stankovski/azure-powershell | src/ResourceManager/Resources/Commands.Resources/RoleDefinitions/RemoveAzureRoleDefinitionCommand.cs | src/ResourceManager/Resources/Commands.Resources/RoleDefinitions/RemoveAzureRoleDefinitionCommand.cs | // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.Azure.Commands.Resources.Models;
using Microsoft.Azure.Commands.Resources.Models.Authorization;
using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources;
namespace Microsoft.Azure.Commands.Resources
{
/// <summary>
/// Deletes a given role definition.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureRoleDefinition"), OutputType(typeof(bool))]
public class RemoveAzureRoleDefinitionCommand : ResourcesBaseCmdlet
{
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Role definition id.")]
public string Id { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter Force { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter PassThru { get; set; }
public override void ExecuteCmdlet()
{
PSRoleDefinition roleDefinition = null;
ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemoveRoleDefinition, Id),
ProjectResources.RemoveRoleDefinition,
Id,
() => roleDefinition = PoliciesClient.RemoveRoleDefinition(Id));
if (PassThru)
{
WriteObject(roleDefinition);
}
}
}
}
| // ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// 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.Management.Automation;
using Microsoft.Azure.Commands.Resources.Models;
using Microsoft.Azure.Commands.Resources.Models.Authorization;
using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources;
namespace Microsoft.Azure.Commands.Resources
{
/// <summary>
/// Deletes a given role definition.
/// </summary>
[Cmdlet(VerbsCommon.Remove, "AzureRoleDefinition"), OutputType(typeof(PSRoleDefinition))]
public class RemoveAzureRoleDefinitionCommand : ResourcesBaseCmdlet
{
[ValidateNotNullOrEmpty]
[Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "Role definition id.")]
public string Id { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter Force { get; set; }
[Parameter(Mandatory = false)]
public SwitchParameter PassThru { get; set; }
public override void ExecuteCmdlet()
{
PSRoleDefinition roleDefinition = null;
ConfirmAction(
Force.IsPresent,
string.Format(ProjectResources.RemoveRoleDefinition, Id),
ProjectResources.RemoveRoleDefinition,
Id,
() => roleDefinition = PoliciesClient.RemoveRoleDefinition(Id));
if (PassThru)
{
WriteObject(roleDefinition);
}
}
}
}
| apache-2.0 | C# |
ca26901cdafc94e0dc0ed6c2b7a78f3c8cd21744 | Print "Other:" for single choice questions | bcemmett/SurveyMonkeyApi-v3 | SurveyMonkey/ProcessedAnswers/SingleChoiceAnswer.cs | SurveyMonkey/ProcessedAnswers/SingleChoiceAnswer.cs | using System;
using System.Text;
using SurveyMonkey.Helpers;
namespace SurveyMonkey.ProcessedAnswers
{
public class SingleChoiceAnswer : IProcessedResponse
{
public string Choice { get; set; }
public string OtherText { get; set; }
public string Printable
{
get
{
var sb = new StringBuilder();
if (Choice != null)
{
sb.Append(Choice);
sb.Append(Environment.NewLine);
}
if (OtherText != null)
{
sb.Append($"Other: {OtherText}");
}
return ProcessedAnswerFormatHelper.Trim(sb);
}
}
}
} | using System;
using System.Text;
using SurveyMonkey.Helpers;
namespace SurveyMonkey.ProcessedAnswers
{
public class SingleChoiceAnswer : IProcessedResponse
{
public string Choice { get; set; }
public string OtherText { get; set; }
public string Printable
{
get
{
var sb = new StringBuilder();
if (Choice != null)
{
sb.Append(Choice);
sb.Append(Environment.NewLine);
}
if (OtherText != null)
{
sb.Append(OtherText);
}
return ProcessedAnswerFormatHelper.Trim(sb);
}
}
}
} | mit | C# |
a42c79895d907351d3764f019f9e6ca475a41760 | Remove unnecessary private field | NeoAdonis/osu,ppy/osu,EVAST9919/osu,ppy/osu,johnneijzen/osu,peppy/osu,ZLima12/osu,UselessToucan/osu,ppy/osu,peppy/osu,EVAST9919/osu,smoogipooo/osu,2yangk23/osu,UselessToucan/osu,NeoAdonis/osu,johnneijzen/osu,smoogipoo/osu,peppy/osu-new,smoogipoo/osu,ZLima12/osu,NeoAdonis/osu,peppy/osu,smoogipoo/osu,2yangk23/osu,UselessToucan/osu | osu.Game/Rulesets/Mods/ModBlockFail.cs | osu.Game/Rulesets/Mods/ModBlockFail.cs | // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Screens.Play;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModBlockFail : Mod, IApplicableFailOverride, IApplicableToHUD, IReadFromConfig
{
private Bindable<bool> hideHealthBar;
/// <summary>
/// We never fail, 'yo.
/// </summary>
public bool AllowFail => false;
public void ReadFromConfig(OsuConfigManager config)
{
hideHealthBar = config.GetBindable<bool>(OsuSetting.HideHealthBarWhenCantFail);
}
public void ApplyToHUD(HUDOverlay overlay)
{
hideHealthBar.BindValueChanged(v => healthDisplay.FadeTo(v.NewValue ? 0 : 1, 250, Easing.OutQuint), true);
}
}
}
| // Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Bindables;
using osu.Framework.Graphics;
using osu.Game.Configuration;
using osu.Game.Screens.Play;
using osu.Game.Screens.Play.HUD;
namespace osu.Game.Rulesets.Mods
{
public abstract class ModBlockFail : Mod, IApplicableFailOverride, IApplicableToHUD, IReadFromConfig
{
private Bindable<bool> hideHealthBar;
private HealthDisplay healthDisplay;
/// <summary>
/// We never fail, 'yo.
/// </summary>
public bool AllowFail => false;
public void ReadFromConfig(OsuConfigManager config)
{
hideHealthBar = config.GetBindable<bool>(OsuSetting.HideHealthBarWhenCantFail);
}
public void ApplyToHUD(HUDOverlay overlay)
{
healthDisplay = overlay.HealthDisplay;
hideHealthBar.BindValueChanged(v => healthDisplay.FadeTo(v.NewValue ? 0 : 1, 250, Easing.OutQuint), true);
}
}
}
| mit | C# |
e4326c981428c3d28823d1f9f39f48e25e8531b9 | Fix typos in Log.cs (#599) | NicolasDorier/NBitcoin,MetacoSA/NBitcoin,MetacoSA/NBitcoin | NBitcoin/Logging/Logs.cs | NBitcoin/Logging/Logs.cs | using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace NBitcoin.Logging
{
public class Logs
{
static Logs()
{
Configure(new FuncLoggerFactory(n => NullLogger.Instance));
}
public static void Configure(ILoggerFactory factory)
{
NodeServer = factory.CreateLogger("NodeServer");
Utils = factory.CreateLogger("Utils");
}
public static ILogger NodeServer
{
get; set;
}
public static ILogger Utils
{
get; set;
}
public const int ColumnLength = 16;
}
public class FuncLoggerFactory : ILoggerFactory
{
private Func<string, ILogger> createLogger;
public FuncLoggerFactory(Func<string, ILogger> createLogger)
{
this.createLogger = createLogger;
}
public void AddProvider(ILoggerProvider provider)
{
}
public ILogger CreateLogger(string categoryName)
{
return createLogger(categoryName);
}
public void Dispose()
{
}
}
/// <summary>
/// Minimalistic logger that does nothing.
/// </summary>
public class NullLogger : ILogger
{
public static NullLogger Instance { get; } = new NullLogger();
private NullLogger()
{
}
/// <inheritdoc />
public IDisposable BeginScope<TState>(TState state)
{
return NullScope.Instance;
}
/// <inheritdoc />
public bool IsEnabled(LogLevel logLevel)
{
return false;
}
/// <inheritdoc />
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
}
}
/// <summary>
/// An empty scope without any logic
/// </summary>
public class NullScope : IDisposable
{
public static NullScope Instance { get; } = new NullScope();
private NullScope()
{
}
/// <inheritdoc />
public void Dispose()
{
}
}
}
| using System;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace NBitcoin.Logging
{
public class Logs
{
static Logs()
{
Configure(new FuncLoggerFactory(n => NullLogger.Instance));
}
public static void Configure(ILoggerFactory factory)
{
NodeServer = factory.CreateLogger("NodeServer");
NodeServer = factory.CreateLogger("Utils");
}
public static ILogger NodeServer
{
get; set;
}
public static ILogger Utils
{
get; set;
}
public const int ColumnLength = 16;
}
public class FuncLoggerFactory : ILoggerFactory
{
private Func<string, ILogger> createLogger;
public FuncLoggerFactory(Func<string, ILogger> createLogger)
{
this.createLogger = createLogger;
}
public void AddProvider(ILoggerProvider provider)
{
}
public ILogger CreateLogger(string categoryName)
{
return createLogger(categoryName);
}
public void Dispose()
{
}
}
/// <summary>
/// Minimalistic logger that does nothing.
/// </summary>
public class NullLogger : ILogger
{
public static NullLogger Instance { get; } = new NullLogger();
private NullLogger()
{
}
/// <inheritdoc />
public IDisposable BeginScope<TState>(TState state)
{
return NullScope.Instance;
}
/// <inheritdoc />
public bool IsEnabled(LogLevel logLevel)
{
return false;
}
/// <inheritdoc />
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
}
}
/// <summary>
/// An empty scope without any logic
/// </summary>
public class NullScope : IDisposable
{
public static NullScope Instance { get; } = new NullScope();
private NullScope()
{
}
/// <inheritdoc />
public void Dispose()
{
}
}
} | mit | C# |
5721b239e068ea62dfc8f20a26bd1de65fc4aa9e | Add SourceCode metadata | riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy,riganti/dotvvm-samples-academy | src/DotvvmAcademy.Validation/ISourceCode.cs | src/DotvvmAcademy.Validation/ISourceCode.cs | namespace DotvvmAcademy.Validation
{
public interface ISourceCode
{
string FileName { get; }
bool IsValidated { get; }
string GetContent();
}
} | namespace DotvvmAcademy.Validation
{
public interface ISourceCode
{
string GetContent();
}
} | apache-2.0 | C# |
51d5ea78807b546edec090d5066fdd32e03835e0 | Add nullability in extension method (#48) | tlycken/RdbmsEventStore | src/RdbmsEventStore/EventStoreExtensions.cs | src/RdbmsEventStore/EventStoreExtensions.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RdbmsEventStore
{
public static class EventStoreExtensions
{
public static Task<IEnumerable<TEvent>> Events<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Events(events => events);
public static Task<IEnumerable<TEvent>> Events<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store, TStreamId streamId)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Events(streamId, events => events);
public static Task<IEnumerable<TEvent>> Events<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store, TStreamId streamId, Func<IQueryable<TEventMetadata>, IQueryable<TEventMetadata>> query)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Events(events => events.Where(e => e.StreamId.Equals(streamId)).Apply(query));
public static Task Append<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store, TStreamId streamId, DateTimeOffset? versionBefore, object payload)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Append(streamId, versionBefore, new[] { payload });
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace RdbmsEventStore
{
public static class EventStoreExtensions
{
public static Task<IEnumerable<TEvent>> Events<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Events(events => events);
public static Task<IEnumerable<TEvent>> Events<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store, TStreamId streamId)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Events(streamId, events => events);
public static Task<IEnumerable<TEvent>> Events<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store, TStreamId streamId, Func<IQueryable<TEventMetadata>, IQueryable<TEventMetadata>> query)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Events(events => events.Where(e => e.StreamId.Equals(streamId)).Apply(query));
public static Task Append<TStreamId, TEvent, TEventMetadata>(this IEventStore<TStreamId, TEvent, TEventMetadata> store, TStreamId streamId, DateTimeOffset versionBefore, object payload)
where TStreamId : IEquatable<TStreamId>
where TEvent : class, TEventMetadata, IEvent<TStreamId>
where TEventMetadata : class, IEventMetadata<TStreamId>
=> store.Append(streamId, versionBefore, new[] { payload });
}
} | mit | C# |
1a7d06324bef845a4f60764f55cbd77c84ad1903 | Add checks to TwitterRepository to see if any of the Twitter authetication settings are the default value. If there is any default values, TwitterRepository will return null and not attempt to use LinqToTwitter to authorize with the SingleUserAuthorizer | binaryjanitor/allReady,enderdickerson/allReady,enderdickerson/allReady,MisterJames/allReady,anobleperson/allReady,chinwobble/allReady,gitChuckD/allReady,bcbeatty/allReady,bcbeatty/allReady,jonatwabash/allReady,binaryjanitor/allReady,jonatwabash/allReady,VishalMadhvani/allReady,anobleperson/allReady,JowenMei/allReady,BillWagner/allReady,stevejgordon/allReady,HTBox/allReady,VishalMadhvani/allReady,pranap/allReady,c0g1t8/allReady,arst/allReady,bcbeatty/allReady,mgmccarthy/allReady,VishalMadhvani/allReady,forestcheng/allReady,colhountech/allReady,stevejgordon/allReady,c0g1t8/allReady,binaryjanitor/allReady,GProulx/allReady,binaryjanitor/allReady,bcbeatty/allReady,pranap/allReady,BillWagner/allReady,c0g1t8/allReady,pranap/allReady,HTBox/allReady,c0g1t8/allReady,HamidMosalla/allReady,dpaquette/allReady,GProulx/allReady,HamidMosalla/allReady,shanecharles/allReady,JowenMei/allReady,JowenMei/allReady,mipre100/allReady,GProulx/allReady,VishalMadhvani/allReady,shanecharles/allReady,HTBox/allReady,anobleperson/allReady,arst/allReady,MisterJames/allReady,chinwobble/allReady,stevejgordon/allReady,dpaquette/allReady,chinwobble/allReady,enderdickerson/allReady,enderdickerson/allReady,dpaquette/allReady,JowenMei/allReady,HTBox/allReady,HamidMosalla/allReady,forestcheng/allReady,shanecharles/allReady,stevejgordon/allReady,gitChuckD/allReady,MisterJames/allReady,BillWagner/allReady,dpaquette/allReady,BillWagner/allReady,mipre100/allReady,mgmccarthy/allReady,mgmccarthy/allReady,forestcheng/allReady,gitChuckD/allReady,colhountech/allReady,gitChuckD/allReady,GProulx/allReady,jonatwabash/allReady,shanecharles/allReady,mgmccarthy/allReady,jonatwabash/allReady,arst/allReady,chinwobble/allReady,colhountech/allReady,MisterJames/allReady,HamidMosalla/allReady,anobleperson/allReady,mipre100/allReady,mipre100/allReady,arst/allReady,pranap/allReady,forestcheng/allReady,colhountech/allReady | AllReadyApp/Web-App/AllReady/Providers/ExternalUserInformationProviders/Providers/TwitterRepository.cs | AllReadyApp/Web-App/AllReady/Providers/ExternalUserInformationProviders/Providers/TwitterRepository.cs | using System.Linq;
using System.Threading.Tasks;
using LinqToTwitter;
using Microsoft.Extensions.Options;
namespace AllReady.Providers.ExternalUserInformationProviders.Providers
{
public class TwitterRepository : ITwitterRepository
{
private readonly IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings;
public TwitterRepository(IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings)
{
this.twitterAuthenticationSettings = twitterAuthenticationSettings;
}
public async Task<Account> GetTwitterAccount(string userId, string screenName)
{
if (AnyTwitterAuthenticationSettingsAreNotSet())
{
return null;
}
var authTwitter = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = twitterAuthenticationSettings.Value.ConsumerKey,
ConsumerSecret = twitterAuthenticationSettings.Value.ConsumerSecret,
OAuthToken = twitterAuthenticationSettings.Value.OAuthToken,
OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret,
UserID = ulong.Parse(userId),
ScreenName = screenName
}
};
await authTwitter.AuthorizeAsync();
var twitterCtx = new TwitterContext(authTwitter);
//VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work
var account = await (from acct in twitterCtx.Account
where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
select acct).SingleOrDefaultAsync();
return account;
}
private bool AnyTwitterAuthenticationSettingsAreNotSet()
{
return twitterAuthenticationSettings.Value.ConsumerKey == "[twitterconsumerkey]" || twitterAuthenticationSettings.Value.ConsumerSecret == "[twitterconsumersecret]" ||
twitterAuthenticationSettings.Value.OAuthToken == "[twitteroauthtoken]" || twitterAuthenticationSettings.Value.OAuthSecret == "[twitteroauthsecret]";
}
}
}
| using System.Linq;
using System.Threading.Tasks;
using LinqToTwitter;
using Microsoft.Extensions.Options;
namespace AllReady.Providers.ExternalUserInformationProviders.Providers
{
public class TwitterRepository : ITwitterRepository
{
private readonly IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings;
public TwitterRepository(IOptions<TwitterAuthenticationSettings> twitterAuthenticationSettings)
{
this.twitterAuthenticationSettings = twitterAuthenticationSettings;
}
public async Task<Account> GetTwitterAccount(string userId, string screenName)
{
var authTwitter = new SingleUserAuthorizer
{
CredentialStore = new SingleUserInMemoryCredentialStore
{
ConsumerKey = twitterAuthenticationSettings.Value.ConsumerKey,
ConsumerSecret = twitterAuthenticationSettings.Value.ConsumerSecret,
OAuthToken = twitterAuthenticationSettings.Value.OAuthToken,
OAuthTokenSecret = twitterAuthenticationSettings.Value.OAuthSecret,
UserID = ulong.Parse(userId),
ScreenName = screenName
}
};
await authTwitter.AuthorizeAsync();
var twitterCtx = new TwitterContext(authTwitter);
//VERY important you explicitly keep the "== true" part of comparison. ReSharper will prompt you to remove this, and if it does, the query will not work
var account = await (from acct in twitterCtx.Account
where (acct.Type == AccountType.VerifyCredentials) && (acct.IncludeEmail == true)
select acct).SingleOrDefaultAsync();
return account;
}
}
}
| mit | C# |
536b016613da9ef9445badfd4b46984ad7db0a0e | add some buffering when reading | kreeben/resin,kreeben/resin | src/ResinCore/FullTextReadSessionFactory.cs | src/ResinCore/FullTextReadSessionFactory.cs | using DocumentTable;
using StreamIndex;
using System;
using System.IO;
using System.Linq;
namespace Resin
{
public class FullTextReadSessionFactory : IReadSessionFactory, IDisposable
{
private readonly string _directory;
private readonly FileStream _compoundFile;
public FullTextReadSessionFactory(string directory)
{
_directory = directory;
var version = Directory.GetFiles(directory, "*.ix")
.Select(f => long.Parse(Path.GetFileNameWithoutExtension(f)))
.OrderBy(v => v).First();
var compoundFileName = Path.Combine(_directory, version + ".rdb");
_compoundFile = new FileStream(
compoundFileName,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite,
4096*8,
FileOptions.RandomAccess);
}
public IReadSession OpenReadSession(long version)
{
var ix = FullTextSegmentInfo.Load(Path.Combine(_directory, version + ".ix"));
return OpenReadSession(ix);
}
public IReadSession OpenReadSession(SegmentInfo ix)
{
return new FullTextReadSession(
ix,
new DocHashReader(_compoundFile, ix.DocHashOffset),
new BlockInfoReader(_compoundFile, ix.DocAddressesOffset),
_compoundFile);
}
public void Dispose()
{
_compoundFile.Dispose();
}
}
}
| using DocumentTable;
using StreamIndex;
using System;
using System.IO;
using System.Linq;
namespace Resin
{
public class FullTextReadSessionFactory : IReadSessionFactory, IDisposable
{
private readonly string _directory;
private readonly FileStream _compoundFile;
public FullTextReadSessionFactory(string directory)
{
_directory = directory;
var version = Directory.GetFiles(directory, "*.ix")
.Select(f => long.Parse(Path.GetFileNameWithoutExtension(f)))
.OrderBy(v => v).First();
var compoundFileName = Path.Combine(_directory, version + ".rdb");
_compoundFile = new FileStream(
compoundFileName,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite);
}
public IReadSession OpenReadSession(long version)
{
var ix = FullTextSegmentInfo.Load(Path.Combine(_directory, version + ".ix"));
return OpenReadSession(ix);
}
public IReadSession OpenReadSession(SegmentInfo ix)
{
return new FullTextReadSession(
ix,
new DocHashReader(_compoundFile, ix.DocHashOffset),
new BlockInfoReader(_compoundFile, ix.DocAddressesOffset),
_compoundFile);
}
public void Dispose()
{
_compoundFile.Dispose();
}
}
}
| mit | C# |
3b659677509eded99ceed3d2140209e6286cbd8b | remove jsonignore attr | vmlf01/OdooRpc.CoreCLR.Client | src/OdooRpc.CoreCLR.Client/Models/OdooMetadata.cs | src/OdooRpc.CoreCLR.Client/Models/OdooMetadata.cs | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OdooRpc.CoreCLR.Client.Models
{
public class OdooMetadata
{
[JsonProperty("id")]
public int Id { get; internal set; }
[JsonProperty("xmlid")]
public string ExternalId { get; internal set; }
[JsonProperty("create_date")]
public DateTime CreateDate { get; internal set; }
[JsonProperty("write_date")]
public DateTime WriteDate { get; internal set; }
[JsonProperty("noupdate")]
public bool NoUpdate { get; internal set; }
[JsonProperty("create_uid")]
public dynamic CreateUid { get; internal set; }
[JsonProperty("write_uid")]
public dynamic WriteUid { get; internal set; }
}
} | using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace OdooRpc.CoreCLR.Client.Models
{
public class OdooMetadata
{
[JsonProperty("id")]
public int Id { get; internal set; }
[JsonIgnore]
[JsonProperty("xmlid")]
public string ExternalId { get; internal set; }
[JsonProperty("create_date")]
public DateTime CreateDate { get; internal set; }
[JsonProperty("write_date")]
public DateTime WriteDate { get; internal set; }
[JsonProperty("noupdate")]
public bool NoUpdate { get; internal set; }
[JsonProperty("create_uid")]
public dynamic CreateUid { get; internal set; }
[JsonProperty("write_uid")]
public dynamic WriteUid { get; internal set; }
}
} | mit | C# |
b63456444547df64b99c3ee2965479422bdab599 | Make tests runnable on mono | philipcpresley/FAKE,dlsteuer/FAKE,beeker/FAKE,dlsteuer/FAKE,warnergodfrey/FAKE,naveensrinivasan/FAKE,mfalda/FAKE,darrelmiller/FAKE,MiloszKrajewski/FAKE,ilkerde/FAKE,mglodack/FAKE,Kazark/FAKE,yonglehou/FAKE,haithemaraissia/FAKE,hitesh97/FAKE,warnergodfrey/FAKE,MichalDepta/FAKE,yonglehou/FAKE,mat-mcloughlin/FAKE,dmorgan3405/FAKE,Kazark/FAKE,ArturDorochowicz/FAKE,yonglehou/FAKE,pacificIT/FAKE,dlsteuer/FAKE,wooga/FAKE,mfalda/FAKE,tpetricek/FAKE,ovu/FAKE,NaseUkolyCZ/FAKE,MichalDepta/FAKE,brianary/FAKE,mglodack/FAKE,modulexcite/FAKE,gareth-evans/FAKE,rflechner/FAKE,pacificIT/FAKE,mat-mcloughlin/FAKE,MiloszKrajewski/FAKE,xavierzwirtz/FAKE,satsuper/FAKE,rflechner/FAKE,naveensrinivasan/FAKE,molinch/FAKE,pmcvtm/FAKE,hitesh97/FAKE,molinch/FAKE,beeker/FAKE,molinch/FAKE,leflings/FAKE,modulexcite/FAKE,NaseUkolyCZ/FAKE,gareth-evans/FAKE,neoeinstein/FAKE,wooga/FAKE,featuresnap/FAKE,rflechner/FAKE,ovu/FAKE,molinch/FAKE,pmcvtm/FAKE,ovu/FAKE,beeker/FAKE,jayp33/FAKE,leflings/FAKE,ctaggart/FAKE,NaseUkolyCZ/FAKE,MiloszKrajewski/FAKE,RMCKirby/FAKE,neoeinstein/FAKE,mfalda/FAKE,MichalDepta/FAKE,mat-mcloughlin/FAKE,warnergodfrey/FAKE,JonCanning/FAKE,ArturDorochowicz/FAKE,ilkerde/FAKE,modulexcite/FAKE,xavierzwirtz/FAKE,dlsteuer/FAKE,gareth-evans/FAKE,ilkerde/FAKE,pmcvtm/FAKE,jayp33/FAKE,leflings/FAKE,haithemaraissia/FAKE,brianary/FAKE,ovu/FAKE,ctaggart/FAKE,featuresnap/FAKE,ArturDorochowicz/FAKE,neoeinstein/FAKE,daniel-chambers/FAKE,brianary/FAKE,pacificIT/FAKE,daniel-chambers/FAKE,tpetricek/FAKE,pacificIT/FAKE,Kazark/FAKE,ctaggart/FAKE,RMCKirby/FAKE,MichalDepta/FAKE,RMCKirby/FAKE,dmorgan3405/FAKE,philipcpresley/FAKE,wooga/FAKE,NaseUkolyCZ/FAKE,daniel-chambers/FAKE,MiloszKrajewski/FAKE,haithemaraissia/FAKE,satsuper/FAKE,featuresnap/FAKE,naveensrinivasan/FAKE,mfalda/FAKE,mglodack/FAKE,xavierzwirtz/FAKE,darrelmiller/FAKE,RMCKirby/FAKE,satsuper/FAKE,mat-mcloughlin/FAKE,tpetricek/FAKE,ArturDorochowicz/FAKE,philipcpresley/FAKE,dmorgan3405/FAKE,ilkerde/FAKE,brianary/FAKE,rflechner/FAKE,satsuper/FAKE,haithemaraissia/FAKE,darrelmiller/FAKE,warnergodfrey/FAKE,mglodack/FAKE,philipcpresley/FAKE,JonCanning/FAKE,jayp33/FAKE,modulexcite/FAKE,JonCanning/FAKE,wooga/FAKE,hitesh97/FAKE,JonCanning/FAKE,ctaggart/FAKE,naveensrinivasan/FAKE,hitesh97/FAKE,xavierzwirtz/FAKE,jayp33/FAKE,featuresnap/FAKE,beeker/FAKE,yonglehou/FAKE,darrelmiller/FAKE,daniel-chambers/FAKE,dmorgan3405/FAKE,tpetricek/FAKE,Kazark/FAKE,gareth-evans/FAKE,leflings/FAKE,neoeinstein/FAKE,pmcvtm/FAKE | src/test/Test.FAKECore/AssemblyInfoSpecs.cs | src/test/Test.FAKECore/AssemblyInfoSpecs.cs | using System;
using System.Collections.Generic;
using System.IO;
using Machine.Specifications;
namespace Test.FAKECore
{
public class when_accessing_internals
{
It should_have_access_to_FAKE_internals =
() => AssemblyInfoFile.getDependencies(new List<AssemblyInfoFile.Attribute>());
}
public class when_use_fsharp_task_with_default_config
{
It should_use_system_namespace_and_emit_a_verison_module = () =>
{
string infoFile = Path.GetTempFileName();
var attributes = new[]
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfo(infoFile, attributes);
string expected =
"namespace System\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\nmodule internal AssemblyVersionInformation =\r\n let [<Literal>] Version = \"1.0.0.0\"\r\n";
File.ReadAllText(infoFile)
.ShouldEqual(expected.Replace("\r\n", Environment.NewLine));
};
}
public class when_using_fsharp_task_with_custom_config
{
It should_use_custom_namespace_and_not_emit_a_version_module = () =>
{
var customConfig = new AssemblyInfoFile.AssemblyInfoFileConfig(false, "Custom");
string infoFile = Path.GetTempFileName();
var attributes = new[]
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfoWithConfig(infoFile, attributes, customConfig);
string expected =
"namespace Custom\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\n";
File.ReadAllText(infoFile)
.ShouldEqual(expected.Replace("\r\n", Environment.NewLine));
};
}
} | using System.Collections.Generic;
using System.IO;
using Fake;
using Machine.Specifications;
namespace Test.FAKECore
{
public class when_accessing_internals
{
It should_have_access_to_FAKE_internals = () => AssemblyInfoFile.getDependencies(new List<AssemblyInfoFile.Attribute>());
}
public class when_use_fsharp_task_with_default_config
{
It should_use_system_namespace_and_emit_a_verison_module = () =>
{
var infoFile = Path.GetTempFileName();
var attributes = new []
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfo(infoFile, attributes);
File.ReadAllText(infoFile)
.ShouldEqual("namespace System\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\nmodule internal AssemblyVersionInformation =\r\n let [<Literal>] Version = \"1.0.0.0\"\r\n");
};
}
public class when_use_fsharp_task_with_custom_config
{
It should_use_custom_namespace_and_not_emit_a_version_module = () =>
{
var customConfig = new AssemblyInfoFile.AssemblyInfoFileConfig(false,"Custom");
var infoFile = Path.GetTempFileName();
var attributes = new []
{
AssemblyInfoFile.Attribute.Product("TestLib"),
AssemblyInfoFile.Attribute.Version("1.0.0.0")
};
AssemblyInfoFile.CreateFSharpAssemblyInfoWithConfig(infoFile, attributes, customConfig);
File.ReadAllText(infoFile)
.ShouldEqual("namespace Custom\r\nopen System.Reflection\r\n\r\n[<assembly: AssemblyProductAttribute(\"TestLib\")>]\r\n[<assembly: AssemblyVersionAttribute(\"1.0.0.0\")>]\r\ndo ()\r\n\r\n");
};
}
} | apache-2.0 | C# |
7298fbf6c78602a056b6bbc4e5e5eb4c84fe6ed5 | make less code | jefking/King.Azure.Imaging,jefking/King.Azure.Imaging,jefking/King.Azure.Imaging | King.Azure.Imaging.Mvc/Controllers/HomeController.cs | King.Azure.Imaging.Mvc/Controllers/HomeController.cs | namespace King.Azure.Imaging.Mvc.Controllers
{
using System.Threading.Tasks;
using System.Web.Mvc;
using King.Azure.Data;
using King.Azure.Imaging.Entities;
using King.Azure.Imaging.Models;
using Microsoft.Azure;
public class HomeController : Controller
{
private static readonly IStorageElements elements = new StorageElements();
private static readonly string connection = CloudConfigurationManager.GetSetting("StorageAccount");
private readonly ITableStorage table = new TableStorage(elements.Table, connection);
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Thumbs()
{
var data = await this.table.QueryByRow<ImageEntity>("thumb");
return View(data);
}
public async Task<ActionResult> Originals()
{
var data = await this.table.QueryByRow<ImageEntity>(Naming.Original);
return View(data);
}
public async Task<ActionResult> Large()
{
var data = await this.table.QueryByRow<ImageEntity>("large");
return View(data);
}
public async Task<ActionResult> Medium()
{
var data = await this.table.QueryByRow<ImageEntity>("medium");
return View(data);
}
public async Task<ActionResult> Dynamic()
{
var data = await this.table.QueryByRow<ImageEntity>(Naming.Original);
return View(data);
}
}
} | namespace King.Azure.Imaging.Mvc.Controllers
{
using System.Threading.Tasks;
using System.Web.Mvc;
using King.Azure.Data;
using King.Azure.Imaging.Entities;
using King.Azure.Imaging.Models;
using Microsoft.Azure;
public class HomeController : Controller
{
#region Members
/// <summary>
/// Storage Elements
/// </summary>
private static readonly IStorageElements elements = new StorageElements();
/// <summary>
/// Connection String
/// </summary>
private static readonly string connection = CloudConfigurationManager.GetSetting("StorageAccount");
/// <summary>
/// Table Storage (Image Meta-Data)
/// </summary>
private readonly ITableStorage table = new TableStorage(elements.Table, connection);
#endregion
#region Methods
public ActionResult Index()
{
return View();
}
public async Task<ActionResult> Thumbs()
{
var data = await this.table.QueryByRow<ImageEntity>("thumb");
return View(data);
}
public async Task<ActionResult> Originals()
{
var data = await this.table.QueryByRow<ImageEntity>(Naming.Original);
return View(data);
}
public async Task<ActionResult> Large()
{
var data = await this.table.QueryByRow<ImageEntity>("large");
return View(data);
}
public async Task<ActionResult> Medium()
{
var data = await this.table.QueryByRow<ImageEntity>("medium");
return View(data);
}
public async Task<ActionResult> Dynamic()
{
var data = await this.table.QueryByRow<ImageEntity>(Naming.Original);
return View(data);
}
#endregion
}
} | mit | C# |
d3a300eb485c791f610b741c5d177f5be2a78548 | Adjust the CoinWarz price / exchange rate so that BTC is 1 (100%) | IWBWbiz/MultiMiner,IWBWbiz/MultiMiner,nwoolls/MultiMiner,nwoolls/MultiMiner | MultiMiner.CoinWarz.Api/CoinInformationExtensions.cs | MultiMiner.CoinWarz.Api/CoinInformationExtensions.cs | using MultiMiner.Coin.Api;
using Newtonsoft.Json.Linq;
namespace MultiMiner.CoinWarz.Api
{
public static class CoinInformationExtensions
{
public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken)
{
coinInformation.Symbol = jToken.Value<string>("CoinTag");
coinInformation.Name = jToken.Value<string>("CoinName");
coinInformation.Algorithm = jToken.Value<string>("Algorithm");
coinInformation.CurrentBlocks = jToken.Value<int>("BlockCount");
coinInformation.Difficulty = jToken.Value<double>("Difficulty");
coinInformation.Reward = jToken.Value<double>("BlockReward");
if (coinInformation.Symbol.Equals("BTC", System.StringComparison.OrdinalIgnoreCase))
coinInformation.Price = 1;
else
coinInformation.Price = jToken.Value<double>("ExchangeRate");
coinInformation.Exchange = jToken.Value<string>("Exchange");
coinInformation.Profitability = jToken.Value<double>("ProfitRatio");
coinInformation.AdjustedProfitability = jToken.Value<double>("ProfitRatio");
coinInformation.AverageProfitability = jToken.Value<double>("AvgProfitRatio");
}
}
}
| using MultiMiner.Coin.Api;
using Newtonsoft.Json.Linq;
namespace MultiMiner.CoinWarz.Api
{
public static class CoinInformationExtensions
{
public static void PopulateFromJson(this CoinInformation coinInformation, JToken jToken)
{
coinInformation.Symbol = jToken.Value<string>("CoinTag");
coinInformation.Name = jToken.Value<string>("CoinName");
coinInformation.Algorithm = jToken.Value<string>("Algorithm");
coinInformation.CurrentBlocks = jToken.Value<int>("BlockCount");
coinInformation.Difficulty = jToken.Value<double>("Difficulty");
coinInformation.Reward = jToken.Value<double>("BlockReward");
coinInformation.Price = jToken.Value<double>("ExchangeRate");
coinInformation.Exchange = jToken.Value<string>("Exchange");
coinInformation.Profitability = jToken.Value<double>("ProfitRatio");
coinInformation.AdjustedProfitability = jToken.Value<double>("ProfitRatio");
coinInformation.AverageProfitability = jToken.Value<double>("AvgProfitRatio");
}
}
}
| mit | C# |
909ea5762519a35eff63dcdf673d32c2e1838b5a | add timestamp to image files | yizeng/EventFiringWebDriverExamples | TestOnExceptionThrown.cs | TestOnExceptionThrown.cs | using System;
using System.Drawing.Imaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.Events;
using OpenQA.Selenium.Support.Extensions;
namespace EventFiringWebDriverExamples {
[TestClass]
public class TestOnExceptionThrown {
private IWebDriver driver;
[TestInitialize]
public void Initialize() {
IWebDriver parentDriver = new FirefoxDriver();
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(parentDriver);
eventFiringWebDriver.ExceptionThrown += new EventHandler<WebDriverExceptionEventArgs>(eventFiringWebDriver_TakeScreenshotOnException);
driver = eventFiringWebDriver;
driver.Navigate().GoToUrl("http://stackoverflow.com");
}
private void eventFiringWebDriver_TakeScreenshotOnException(object sender, WebDriverExceptionEventArgs e) {
string timestamp = DateTime.Now.ToString("yyyy-MM-dd-hhmm-ss");
driver.TakeScreenshot().SaveAsFile("Exception-" + timestamp + ".png", ImageFormat.Png);
}
[TestMethod]
public void LoadStackOverflow() {
Assert.IsTrue(driver.FindElement(By.CssSelector("#hlogo > a")).Displayed);
}
[TestMethod]
public void LoadStackOverflowWithException() {
// Wrong locator, expect NoSuchElementException
Assert.IsTrue(driver.FindElement(By.CssSelector("#hlogo > a > a > a")).Displayed);
}
[TestCleanup]
public void Cleanup() {
driver.Quit();
}
}
}
| using System;
using System.Drawing.Imaging;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.Events;
using OpenQA.Selenium.Support.Extensions;
namespace EventFiringWebDriverExamples {
[TestClass]
public class TestOnExceptionThrown {
private IWebDriver driver;
[TestInitialize]
public void Initialize() {
IWebDriver parentDriver = new FirefoxDriver();
EventFiringWebDriver eventFiringWebDriver = new EventFiringWebDriver(parentDriver);
eventFiringWebDriver.ExceptionThrown += new EventHandler<WebDriverExceptionEventArgs>(eventFiringWebDriver_TakeScreenshotOnException);
driver = eventFiringWebDriver;
driver.Navigate().GoToUrl("http://stackoverflow.com");
}
private void eventFiringWebDriver_TakeScreenshotOnException(object sender, WebDriverExceptionEventArgs e) {
driver.TakeScreenshot().SaveAsFile("Exception.png", ImageFormat.Png);
}
[TestMethod]
public void LoadStackOverflow() {
Assert.IsTrue(driver.FindElement(By.CssSelector("#hlogo > a")).Displayed);
}
[TestMethod]
public void LoadStackOverflowWithException() {
// Wrong locator, expect NoSuchElementException
Assert.IsTrue(driver.FindElement(By.CssSelector("#hlogo > a > a > a")).Displayed);
}
[TestCleanup]
public void Cleanup() {
driver.Quit();
}
}
}
| apache-2.0 | C# |
48d33a7c7aef56a077f8d0d11002de6f9b3691a5 | Revert "Added log of exceptions" | karolberezicki/EasySnippets | EasySnippets/App.xaml.cs | EasySnippets/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;
using System.Windows.Threading;
namespace EasySnippets
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
{
Console.WriteLine(@"An unexpected application exception occurred {0}", args.Exception);
MessageBox.Show("An unexpected exception has occurred. Shutting down the application. Please check the log file for more details.");
// Prevent default unhandled exception processing
args.Handled = true;
Environment.Exit(0);
}
}
}
| using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace EasySnippets
{
/// <summary>
/// Interaction logic for App.xaml
/// </summary>
public partial class App : Application
{
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs args)
{
Console.WriteLine(@"An unexpected application exception occurred {0}", args.Exception);
File.AppendAllLines(@".\es.log", new[] { $"{DateTime.UtcNow:yyyy-MM-dd HH\\:mm\\:ss.fff} {args.Exception.Message}", args.Exception.StackTrace });
MessageBox.Show("An unexpected exception has occurred. Shutting down the application. Please check the log file for more details.");
// Prevent default unhandled exception processing
args.Handled = true;
}
}
}
| mit | C# |
d5b794f5007b1a8a4858657f8e989c0dac92301f | Add ReplaceUnicode | nuke-build/nuke,nuke-build/nuke,nuke-build/nuke,nuke-build/nuke | source/Nuke.Common/Utilities/String.Replace.cs | source/Nuke.Common/Utilities/String.Replace.cs | // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
[PublicAPI]
[DebuggerNonUserCode]
[DebuggerStepThrough]
public static partial class StringExtensions
{
[Pure]
public static string ReplaceRegex(
this string str,
[RegexPattern] string pattern,
MatchEvaluator matchEvaluator,
RegexOptions options = RegexOptions.None)
{
return Regex.Replace(str, pattern, matchEvaluator, options);
}
private static readonly Regex s_unicodeRegex = new Regex(@"\\u(?<Value>[a-zA-Z0-9]{4})", RegexOptions.Compiled);
[Pure]
public static string ReplaceUnicode(this string str)
{
return s_unicodeRegex.Replace(str, m => ((char) int.Parse(m.Groups["Value"].Value, NumberStyles.HexNumber)).ToString());
}
}
}
| // Copyright 2019 Maintainers of NUKE.
// Distributed under the MIT License.
// https://github.com/nuke-build/nuke/blob/master/LICENSE
using System;
using System.Diagnostics;
using System.Linq;
using System.Text.RegularExpressions;
using JetBrains.Annotations;
namespace Nuke.Common.Utilities
{
[PublicAPI]
[DebuggerNonUserCode]
[DebuggerStepThrough]
public static partial class StringExtensions
{
[Pure]
public static string ReplaceRegex(
this string str,
[RegexPattern] string pattern,
MatchEvaluator matchEvaluator,
RegexOptions options = RegexOptions.None)
{
return Regex.Replace(str, pattern, matchEvaluator, options);
}
}
}
| mit | C# |
911e308f4d51aa729abc046c61f3be3f39e1e4d5 | make TheoremAttribute concrete. | jwChung/Experimentalism,jwChung/Experimentalism | src/Experiment.AutoFixture/TheoremAttribute.cs | src/Experiment.AutoFixture/TheoremAttribute.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
namespace Jwc.Experiment
{
/// <summary>
/// A test attribute declared on a test method to indicate a test case.
/// This attribute can be used for non-parameterized test as well as
/// parameterized test, and supports to generate auto data using
/// the AutoFixture library.
/// </summary>
public class TheoremAttribute : BaseTheoremAttribute
{
/// <summary>
/// Creates an instance of <see cref="ITestFixture"/>.
/// </summary>
/// <param name="testMethod">
/// The test method
/// </param>
/// <returns>
/// The created fixture.
/// </returns>
protected override ITestFixture CreateTestFixture(MethodInfo testMethod)
{
if (testMethod == null)
{
throw new ArgumentNullException("testMethod");
}
return new AutoFixtureAdapter(
CustomizeFixture(
CreateFixture(),
testMethod.GetParameters()));
}
/// <summary>
/// Creates the fixture.
/// </summary>
/// <returns>The new fixture instance.</returns>
protected virtual IFixture CreateFixture()
{
return new Fixture();
}
private static IFixture CustomizeFixture(
IFixture fixture, IEnumerable<ParameterInfo> parameters)
{
return parameters.SelectMany(SelectCustomizations)
.Aggregate(fixture, (f, c) => f.Customize(c));
}
private static IEnumerable<ICustomization> SelectCustomizations(ParameterInfo parameter)
{
return parameter.GetCustomAttributes(typeof(CustomizeAttribute), false)
.Cast<CustomizeAttribute>()
.Select(ca => ca.GetCustomization(parameter));
}
}
} | using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Ploeh.AutoFixture;
using Ploeh.AutoFixture.Xunit;
namespace Jwc.Experiment
{
/// <summary>
/// A test attribute declared on a test method to indicate a test case.
/// This attribute can be used for non-parameterized test as well as
/// parameterized test, and supports to generate auto data using
/// the AutoFixture library.
/// </summary>
public abstract class TheoremAttribute : BaseTheoremAttribute
{
/// <summary>
/// Creates an instance of <see cref="ITestFixture"/>.
/// </summary>
/// <param name="testMethod">
/// The test method
/// </param>
/// <returns>
/// The created fixture.
/// </returns>
protected override ITestFixture CreateTestFixture(MethodInfo testMethod)
{
if (testMethod == null)
{
throw new ArgumentNullException("testMethod");
}
return new AutoFixtureAdapter(
CustomizeFixture(
CreateFixture(),
testMethod.GetParameters()));
}
/// <summary>
/// Creates the fixture.
/// </summary>
/// <returns>The new fixture instance.</returns>
protected virtual IFixture CreateFixture()
{
return new Fixture();
}
private static IFixture CustomizeFixture(
IFixture fixture, IEnumerable<ParameterInfo> parameters)
{
return parameters.SelectMany(SelectCustomizations)
.Aggregate(fixture, (f, c) => f.Customize(c));
}
private static IEnumerable<ICustomization> SelectCustomizations(ParameterInfo parameter)
{
return parameter.GetCustomAttributes(typeof(CustomizeAttribute), false)
.Cast<CustomizeAttribute>()
.Select(ca => ca.GetCustomization(parameter));
}
}
} | mit | C# |
ec29641b3c4e3585fc987b091f1310aa4794a52e | Add a quit button. | bklimt/LandTheEagleUnity | Assets/SplashGUI.cs | Assets/SplashGUI.cs | using UnityEngine;
using System.Collections;
public class SplashGUI : MonoBehaviour {
public GUISkin defaultSkin;
void Start() {
}
void Update() {
}
void OnGUI() {
GameState state = GameState.Instance;
state.Crashed = false;
state.Landed = false;
GUI.skin = defaultSkin;
if (Screen.dpi > 200) {
GUI.skin.label.fontSize = 72;
GUI.skin.button.fontSize = 72;
}
GUI.Label(new Rect(0, 0, Screen.width, Screen.height / 2), "Land the Eagle");
/*
Rect button0Rect = GameState.GetGUIButtonRect(-2);
if (GUI.Button(button0Rect, "Skip Last")) {
state.StartLevel(29);
}
*/
Rect button1Rect = GameState.GetGUIButtonRect(0);
if (GUI.Button(button1Rect, (state.Level == 0 ? "Start" : ("Level " + (state.Level + 1))))) {
state.RestartLevel();
}
Rect button2Rect = GameState.GetGUIButtonRect(1);
if (GUI.Button(button2Rect, "Quit")) {
Application.Quit();
}
}
}
| using UnityEngine;
using System.Collections;
public class SplashGUI : MonoBehaviour {
public GUISkin defaultSkin;
void Start() {
}
void Update() {
}
void OnGUI() {
GameState state = GameState.Instance;
state.Crashed = false;
state.Landed = false;
GUI.skin = defaultSkin;
if (Screen.dpi > 200) {
GUI.skin.label.fontSize = 72;
GUI.skin.button.fontSize = 72;
}
GUI.Label(new Rect(0, 0, Screen.width, Screen.height / 2), "Land the Eagle");
Rect button1Rect = GameState.GetGUIButtonRect(0);
if (GUI.Button(button1Rect, (state.Level == 0 ? "Start" : ("Level " + (state.Level + 1))))) {
state.RestartLevel();
}
/*
Rect button2Rect = GameState.GetGUIButtonRect(0);
if (GUI.Button(button2Rect, "Skip Last")) {
state.StartLevel(29);
}
*/
}
}
| mit | C# |
dda81d7526559db3ae0007804f5ed8b705c0efd9 | Improve documentation of immutability. | nodatime/nodatime,malcolmr/nodatime,zaccharles/nodatime,BenJenkinson/nodatime,malcolmr/nodatime,BenJenkinson/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,zaccharles/nodatime,jskeet/nodatime,malcolmr/nodatime,zaccharles/nodatime,malcolmr/nodatime,nodatime/nodatime,jskeet/nodatime | src/NodaTime/Annotations/ImmutableAttribute.cs | src/NodaTime/Annotations/ImmutableAttribute.cs | // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Annotations
{
/// <summary>
/// Indicates that a type is immutable. After construction, the publicly visible
/// state of the object will not change.
/// </summary>
/// <remarks>
/// <p>
/// This attribute only applies to types, not fields:
/// it's entirely feasible to have a readonly field of a mutable type, or a read/write
/// field of an immutable type. In such cases for reference types (classes and interfaces)
/// it's important to distinguish between the value of the variable (a reference) and the
/// object it refers to. Value types are more complicated as in some cases the compiler
/// will copy values before operating on them; however as all value types in Noda Time are
/// immutable (aside from explictily implemented serialization operations) this rarely causes
/// an issue.
/// </p>
/// <p>
/// Some types may be publicly immutable, but contain privately mutable
/// aspects, e.g. caches. If it proves to be useful to indicate the kind of
/// immutability we're implementing, we can add an appropriate property to this
/// attribute.
/// </p>
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
internal sealed class ImmutableAttribute : Attribute
{
}
}
| // Copyright 2013 The Noda Time Authors. All rights reserved.
// Use of this source code is governed by the Apache License 2.0,
// as found in the LICENSE.txt file.
using System;
namespace NodaTime.Annotations
{
/// <summary>
/// Indicates that a type is mutable.
/// </summary>
/// <remarks>
/// Some types may be publicly immutable, but contain privately mutable
/// aspects, e.g. caches. If it proves to be useful to indicate the kind of
/// immutability we're implementing, we can add an appropriate property to this
/// attribute.
/// </remarks>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
internal sealed class ImmutableAttribute : Attribute
{
}
}
| apache-2.0 | C# |
ac2315099f897ef8b456eb72d646feec09950a6a | Fix test | JimBobSquarePants/Zoombraco,JimBobSquarePants/Zoombraco,JimBobSquarePants/Zoombraco | tests/Zoombraco.Tests/VersionParserTests.cs | tests/Zoombraco.Tests/VersionParserTests.cs | namespace Zoombraco.Tests
{
using System;
using Semver;
using Xunit;
using Zoombraco.Helpers;
public class VersionParserTests
{
[Fact]
public void VersionParserThrowsWhenGivenNull()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
SemVersion error = VersionParser.FromSemanticString(null);
});
}
[Fact]
public void VersionParserResolvesOrderCorrectly()
{
SemVersion beta1 = VersionParser.FromSemanticString("0.5.0-beta+1");
SemVersion beta2 = VersionParser.FromSemanticString("0.5.0-beta+2");
SemVersion release = VersionParser.ZoombracoProductVersion();
Assert.True(release > beta1);
Assert.True(release > beta2);
Assert.True(beta2 > beta1);
}
}
}
| namespace Zoombraco.Tests
{
using System;
using Semver;
using Xunit;
using Zoombraco.Helpers;
public class VersionParserTests
{
[Fact]
public void VersionParserThrowsWhenGivenNull()
{
Assert.Throws(typeof(ArgumentNullException), () =>
{
SemVersion error = VersionParser.FromSemanticString(null);
});
}
[Fact]
public void VersionParserResolvesOrderCorrectly()
{
SemVersion beta7 = VersionParser.FromSemanticString("0.5.0-beta+7");
SemVersion beta9 = VersionParser.FromSemanticString("0.5.0-beta+9");
SemVersion release = VersionParser.ZoombracoProductVersion();
Assert.True(release > beta7);
Assert.True(release > beta9);
Assert.True(beta9 > beta7);
}
}
}
| apache-2.0 | C# |
a1a7e61c4744095e74119f6a3554b3d04daf81b9 | Make CallingConvention enum public | ilkerhalil/dnlib,0xd4d/dnlib,modulexcite/dnlib,jorik041/dnlib,Arthur2e5/dnlib,picrap/dnlib,ZixiangBoy/dnlib,yck1509/dnlib,kiootic/dnlib | dot10/dotNET/Hi/CallingConvention.cs | dot10/dotNET/Hi/CallingConvention.cs | namespace dot10.dotNET.Hi {
/// <summary>
/// See CorHdr.h/CorCallingConvention
/// </summary>
public enum CallingConvention : byte {
/// <summary></summary>
Default = 0x0,
/// <summary></summary>
C = 0x1,
/// <summary></summary>
StdCall = 0x2,
/// <summary></summary>
ThisCall = 0x3,
/// <summary></summary>
FastCall = 0x4,
/// <summary></summary>
VarArg = 0x5,
/// <summary></summary>
Field = 0x6,
/// <summary></summary>
LocalSig = 0x7,
/// <summary></summary>
Property = 0x8,
/// <summary></summary>
Unmanaged = 0x9,
/// <summary>generic method instantiation</summary>
GenericInst = 0xA,
/// <summary>used ONLY for 64bit vararg PInvoke calls</summary>
NativeVarArg = 0xB,
/// <summary>Calling convention is bottom 4 bits</summary>
Mask = 0x0F,
/// <summary>Generic method</summary>
Generic = 0x10,
/// <summary>Method needs a 'this' parameter</summary>
HasThis = 0x20,
/// <summary>'this' parameter is the first arg if set (else it's hidden)</summary>
ExplicitThis = 0x40,
/// <summary>Used internally by the CLR</summary>
ReservedByCLR = 0x80,
}
}
| namespace dot10.dotNET.Hi {
/// <summary>
/// See CorHdr.h/CorCallingConvention
/// </summary>
enum CallingConvention : byte {
/// <summary></summary>
Default = 0x0,
/// <summary></summary>
C = 0x1,
/// <summary></summary>
StdCall = 0x2,
/// <summary></summary>
ThisCall = 0x3,
/// <summary></summary>
FastCall = 0x4,
/// <summary></summary>
VarArg = 0x5,
/// <summary></summary>
Field = 0x6,
/// <summary></summary>
LocalSig = 0x7,
/// <summary></summary>
Property = 0x8,
/// <summary></summary>
Unmanaged = 0x9,
/// <summary>generic method instantiation</summary>
GenericInst = 0xA,
/// <summary>used ONLY for 64bit vararg PInvoke calls</summary>
NativeVarArg = 0xB,
/// <summary>Calling convention is bottom 4 bits</summary>
Mask = 0x0F,
/// <summary>Generic method</summary>
Generic = 0x10,
/// <summary>Method needs a 'this' parameter</summary>
HasThis = 0x20,
/// <summary>'this' parameter is the first arg if set (else it's hidden)</summary>
ExplicitThis = 0x40,
/// <summary>Used internally by the CLR</summary>
ReservedByCLR = 0x80,
}
}
| mit | C# |
0cb1e3997403284570f75e53f49772a5fe33005d | Add extension method for App.Start() | MarinAtanasov/AppBrix,MarinAtanasov/AppBrix.NetCore | Core/AppBrix/App.cs | Core/AppBrix/App.cs | // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Application;
using AppBrix.Configuration;
using AppBrix.Modules;
namespace AppBrix;
/// <summary>
/// Static class used for loading of a default app.
/// </summary>
public static class App
{
#region Public and overriden methods
/// <summary>
/// Creates a default application with a specified configuration service.
/// </summary>
/// <param name="configService">The configuration service.</param>
/// <returns>The created app.</returns>
public static IApp Create(IConfigService configService) => new DefaultApp(configService);
/// <summary>
/// Creates and starts a default application with a specified configuration service.
/// </summary>
/// <param name="configService">The configuration service.</param>
/// <returns>The created and started app.</returns>
public static IApp Start(IConfigService configService)
{
var app = App.Create(configService);
app.Start();
return app;
}
/// <summary>
/// Creates a default application with a specified configuration service.
/// Registers the provided module type in the <see cref="AppConfig"/>.
/// </summary>
/// <typeparam name="T">Type of the <see cref="MainModuleBase"/> to be registered.</typeparam>
/// <param name="configService">The configuration service.</param>
/// <returns>The created app.</returns>
public static IApp Create<T>(IConfigService configService) where T : MainModuleBase, new()
{
var modules = configService.GetAppConfig().Modules;
var mainModuleConfigElement = ModuleConfigElement.Create<T>();
var type = mainModuleConfigElement.Type;
for (var i = 0; i < modules.Count; i++)
{
if (modules[i].Type == type)
return App.Create(configService);
}
modules.Add(mainModuleConfigElement);
return App.Create(configService);
}
/// <summary>
/// Creates and starts a default application with a specified configuration service.
/// Registers the provided module type in the <see cref="AppConfig"/> before starting.
/// </summary>
/// <typeparam name="T">Type of the <see cref="MainModuleBase"/> to be registered.</typeparam>
/// <param name="configService">The configuration service.</param>
/// <returns>The created and started app.</returns>
public static IApp Start<T>(IConfigService configService) where T : MainModuleBase, new()
{
var app = App.Create<T>(configService);
app.Start();
return app;
}
#endregion
}
| // Copyright (c) MarinAtanasov. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the project root for license information.
//
using AppBrix.Application;
using AppBrix.Configuration;
using AppBrix.Modules;
namespace AppBrix;
/// <summary>
/// Static class used for loading of a default app.
/// </summary>
public static class App
{
#region Public and overriden methods
/// <summary>
/// Creates a default application with a specified configuration service.
/// </summary>
/// <param name="configService">The configuration service.</param>
/// <returns>The created app.</returns>
public static IApp Create(IConfigService configService) => new DefaultApp(configService);
/// <summary>
/// Creates a default application with a specified configuration service.
/// Registers the provided module type in the <see cref="AppConfig"/>.
/// </summary>
/// <typeparam name="T">Type of the <see cref="MainModuleBase"/> to be registered.</typeparam>
/// <param name="configService">The configuration service.</param>
/// <returns>The created app.</returns>
public static IApp Create<T>(IConfigService configService) where T : MainModuleBase, new()
{
var modules = configService.GetAppConfig().Modules;
var mainModuleConfigElement = ModuleConfigElement.Create<T>();
var type = mainModuleConfigElement.Type;
for (var i = 0; i < modules.Count; i++)
{
if (modules[i].Type == type)
return App.Create(configService);
}
modules.Add(mainModuleConfigElement);
return App.Create(configService);
}
/// <summary>
/// Creates and starts a default application with a specified configuration service.
/// Registers the provided module type in the <see cref="AppConfig"/> before starting.
/// </summary>
/// <typeparam name="T">Type of the <see cref="MainModuleBase"/> to be registered.</typeparam>
/// <param name="configService">The configuration service.</param>
/// <returns>The created and started app.</returns>
public static IApp Start<T>(IConfigService configService) where T : MainModuleBase, new()
{
var app = App.Create<T>(configService);
app.Start();
return app;
}
#endregion
}
| mit | C# |
5171854c34eee042ea31cf15d57a475d718466f5 | Revert "zpt fix" | XomakNet/tasks | Eval/EvalProgram.cs | Eval/EvalProgram.cs | using System;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace EvalTask
{
class EvalProgram
{
static void Main(string[] args)
{
string input = Console.In.ReadLine();
string json = Console.In.ReadToEnd();
string output;
try
{
output = DoThings(json, input);
}
catch (Exception e)
{
output = "error";
}
Console.WriteLine(output);
}
private static string DoThings(string json, string input)
{
var replaced = JsonReplacer.Replace(json, input);
return new Calculator(replaced).Calc().ToString(CultureInfo.InvariantCulture);
}
[TestFixture]
public class EvalProgram_Should
{
[Test]
public void WorkOnNullJson()
{
string json = null;
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithEmptyJson()
{
string json = "{}";
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithJson()
{
string json = "{x:1,xx:2,yy:3,y:5}";
string expr = "x+xx+yy+y";
Assert.AreEqual("11", DoThings(json, expr));
}
}
}
} | using System;
using System.Globalization;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;
using System.Threading;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
namespace EvalTask
{
class EvalProgram
{
static void Main(string[] args)
{
string input = Console.In.ReadLine()?.Replace(',', '.');
string json = "";//Console.In.ReadToEnd();
string output;
try
{
output = DoThings(json, input);
}
catch (Exception e)
{
output = "error";
}
Console.WriteLine(output);
}
private static string DoThings(string json, string input)
{
var replaced = JsonReplacer.Replace(json, input);
return new Calculator(replaced).Calc().ToString(CultureInfo.InvariantCulture);
}
[TestFixture]
public class EvalProgram_Should
{
[Test]
public void WorkOnNullJson()
{
string json = null;
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithEmptyJson()
{
string json = "{}";
string expr = "1+2-2+1";
Assert.AreEqual("2", DoThings(json, expr));
}
[Test]
public void WorkWithJson()
{
string json = "{x:1,xx:2,yy:3,y:5}";
string expr = "x+xx+yy+y";
Assert.AreEqual("11", DoThings(json, expr));
}
}
}
} | mit | C# |
924d7ff221e5e4f1ece1a8ab7cca01efc4232aec | Remove unused directives | kinosang/QcloudSharp | ApiResult.cs | ApiResult.cs | using System.Collections.Generic;
using System.Dynamic;
namespace QcloudSharp
{
public class ApiResult : DynamicObject
{
private Dictionary<string, object> _attr = new Dictionary<string, object>();
public int Code { get; set; }
public string Message { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _attr.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_attr[binder.Name] = value;
return true;
}
}
}
| using System;
using System.Collections.Generic;
using System.Dynamic;
namespace QcloudSharp
{
public class ApiResult : DynamicObject
{
private Dictionary<string, object> _attr = new Dictionary<string, object>();
public int Code { get; set; }
public string Message { get; set; }
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
return _attr.TryGetValue(binder.Name, out result);
}
public override bool TrySetMember(SetMemberBinder binder, object value)
{
_attr[binder.Name] = value;
return true;
}
}
}
| mit | C# |
de54837390ed94aace46803c2aa0f07d62993ca9 | Fix bug in reset code | wbap/hackathon-2017-sample,wbap/hackathon-2017-sample,wbap/hackathon-2017-sample,wbap/hackathon-2017-sample | environment/Assets/Scripts/Trials.cs | environment/Assets/Scripts/Trials.cs | using UnityEngine;
public class Trials {
public static void Reset() {
PlayerPrefs.SetString("Trials", "");
}
public static void AddSuccess() {
string trials = PlayerPrefs.GetString("Trials");
trials += "S";
while(trials.Length > 100) {
trials = trials.Substring(1);
}
PlayerPrefs.SetString("Trials", trials);
}
public static void AddFailure() {
string trials = PlayerPrefs.GetString("Trials");
trials += "F";
while(trials.Length > 100) {
trials = trials.Substring(1);
}
PlayerPrefs.SetString("Trials", trials);
}
public static int GetSuccess() {
int count = 0;
string trials = PlayerPrefs.GetString("Trials");
foreach(char trial in trials) {
if(trial == 'S') {
count += 1;
}
}
return count;
}
public static int GetFailure() {
int count = 0;
string trials = PlayerPrefs.GetString("Trials");
foreach(char trial in trials) {
if(trial == 'F') {
count += 1;
}
}
return count;
}
}
| using UnityEngine;
public class Trials {
public static void Reset() {
Debug.Log("Reset trials");
}
public static void AddSuccess() {
string trials = PlayerPrefs.GetString("Trials");
trials += "S";
while(trials.Length > 100) {
trials = trials.Substring(1);
}
PlayerPrefs.SetString("Trials", trials);
}
public static void AddFailure() {
string trials = PlayerPrefs.GetString("Trials");
trials += "F";
while(trials.Length > 100) {
trials = trials.Substring(1);
}
PlayerPrefs.SetString("Trials", trials);
}
public static int GetSuccess() {
int count = 0;
string trials = PlayerPrefs.GetString("Trials");
foreach(char trial in trials) {
if(trial == 'S') {
count += 1;
}
}
return count;
}
public static int GetFailure() {
int count = 0;
string trials = PlayerPrefs.GetString("Trials");
foreach(char trial in trials) {
if(trial == 'F') {
count += 1;
}
}
return count;
}
}
| apache-2.0 | C# |
0914dfbc8f41a27f5603a665424f7e72d056d4f8 | add cloud build preprocessor keyword. | sassembla/Autoya,sassembla/Autoya,sassembla/Autoya | Assets/AutoyaTests/Editor/MiyamasuIgniter.cs | Assets/AutoyaTests/Editor/MiyamasuIgniter.cs | using Miyamasu;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad] public class MiyamasuIgniter {
static MiyamasuIgniter () {
#if CLOUDBUILD
{
Debug.LogError("hereComes!!");
}
#else
// {
// Debug.LogWarning("miyamasu start running.");
// var testRunner = new MiyamasuTestRunner();
// testRunner.RunTestsOnMainThread();
// }
#endif
}
} | using Miyamasu;
using UnityEditor;
using UnityEngine;
[InitializeOnLoad] public class MiyamasuIgniter {
static MiyamasuIgniter () {
Debug.LogWarning("miyamasu start running.");
var testRunner = new MiyamasuTestRunner();
testRunner.RunTestsOnMainThread();
}
} | mit | C# |
ce3c6bf550937096280c3147d93205e79ac93b9a | Update AssemblyInfo.cs (#3886) | fassadlr/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,stratisproject/StratisBitcoinFullNode,quantumagi/StratisBitcoinFullNode,fassadlr/StratisBitcoinFullNode | src/Stratis.Bitcoin/Properties/AssemblyInfo.cs | src/Stratis.Bitcoin/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("Stratis.Bitcoin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stratis Group Ltd.")]
[assembly: AssemblyProduct("Stratis.Bitcoin")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.6.0")]
[assembly: AssemblyFileVersion("3.0.6.0")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
| using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Stratis.Bitcoin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Stratis Group Ltd.")]
[assembly: AssemblyProduct("Stratis.Bitcoin")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[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("a6c18cae-7246-41b1-bfd6-c54ba1694ac2")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.0.5.0")]
[assembly: AssemblyFileVersion("3.0.5.0")]
[assembly: InternalsVisibleTo("Stratis.Bitcoin.Tests")]
| mit | C# |
75f2023ad3cac95bab01d801287a72a7d0fbdb38 | 添加 HtmlCommentRenderType 枚举 | wukaixian/Jumony,wukaixian/Jumony,zpzgone/Jumony,zpzgone/Jumony,yonglehou/Jumony,yonglehou/Jumony | Ivony.Html/IHtmlComment.cs | Ivony.Html/IHtmlComment.cs | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ivony.Html
{
/// <summary>
/// 定义一个 HTML 注释,或应当被忽略的 HTML 内容
/// </summary>
public interface IHtmlComment : IHtmlNode
{
/// <summary>
/// 注释文本
/// </summary>
string Comment
{
get;
}
}
/// <summary>
/// HTML 注释的类别
/// </summary>
public enum HtmlCommentRenderType
{
/// <summary>普通注释,使用 <!--内容--> 表示,输出时自动格式化</summary>
Normal,
/// <summary>原样输出,输出时保持原样输出,但不会被任何解析器理解为文本</summary>
AsIs,
/// <summary>不会输出的注释,仅存在于 DOM 结构中,无法输出</summary>
Unable
}
}
| using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ivony.Html
{
/// <summary>
/// 定义一个 HTML 注释,或应当被忽略的 HTML 内容
/// </summary>
public interface IHtmlComment : IHtmlNode
{
/// <summary>
/// 注释文本
/// </summary>
string Comment
{
get;
}
}
}
| apache-2.0 | C# |
13661061a6a676680db932b547d0ffb7c82c76c3 | Convert code to use extension method | Weingartner/SolidworksAddinFramework | SolidworksAddinFramework/Geometry/BSpline3D.cs | SolidworksAddinFramework/Geometry/BSpline3D.cs | using System;
using System.Diagnostics;
using System.Linq;
using System.DoubleNumerics;
using JetBrains.Annotations;
using SolidworksAddinFramework.OpenGl;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework.Geometry
{
public class BSpline3D : BSpline<Vector4>
{
public BSpline3D([NotNull] Vector4[] controlPoints, [NotNull] double[] knotVectorU, int order, bool isClosed, bool isRational) : base(controlPoints, knotVectorU, order, isClosed, isRational)
{
if(!IsRational)
{
Debug.Assert(controlPoints.All(c => Math.Abs(c.W - 1.0) < 1e-9));
}
}
public ICurve ToCurve()
{
var propsDouble = PropsDouble;
var knots = KnotVectorU;
var ctrlPtCoords = ControlPoints.SelectMany(p => p.ToDoubles()).ToArray();
return (ICurve) SwAddinBase.Active.Modeler.CreateBsplineCurve( propsDouble, knots, ctrlPtCoords);
}
public double[] ToDoubles(Vector4 t)
{
return t.ToDoubles();
}
public override int Dimension => IsRational ? 4 : 3;
}
} | using System;
using System.Diagnostics;
using System.Linq;
using System.DoubleNumerics;
using JetBrains.Annotations;
using SolidworksAddinFramework.OpenGl;
using SolidWorks.Interop.sldworks;
namespace SolidworksAddinFramework.Geometry
{
public class BSpline3D : BSpline<Vector4>
{
public BSpline3D([NotNull] Vector4[] controlPoints, [NotNull] double[] knotVectorU, int order, bool isClosed, bool isRational) : base(controlPoints, knotVectorU, order, isClosed, isRational)
{
if(!IsRational)
{
Debug.Assert(controlPoints.All(c => Math.Abs(c.W - 1.0) < 1e-9));
}
}
public ICurve ToCurve()
{
var propsDouble = PropsDouble;
var knots = KnotVectorU;
var ctrlPtCoords = ControlPoints.SelectMany(p => Vector3Extensions.ToDoubles((Vector4) p)).ToArray();
return (ICurve) SwAddinBase.Active.Modeler.CreateBsplineCurve( propsDouble, knots, ctrlPtCoords);
}
public double[] ToDoubles(Vector4 t)
{
return t.ToDoubles();
}
public override int Dimension => IsRational ? 4 : 3;
}
} | mit | C# |
9e57218fd6f689946804b7fd6c4477e1f3c05ce6 | Replace printing tokens with time's measurement | Nezaboodka/Nevod.TextParsing,Nezaboodka/Nevod.TextParsing | Source/TextParserDemoApplication/ParserDemo.cs | Source/TextParserDemoApplication/ParserDemo.cs | using System;
using System.Diagnostics;
using System.IO;
using TextParser;
using TextParser.Common;
namespace TextParserDemoApplication
{
class ParserDemo
{
static void Main(string[] args)
{
string fileName = args[0];
string text = File.ReadAllText(fileName);
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
Parser.ParsePlainText(text);
stopwatch.Stop();
FileInfo fileInfo = new FileInfo(fileName);
Console.WriteLine($"{fileInfo.Length} bytes, {stopwatch.ElapsedMilliseconds} ms");
}
}
}
| using System;
using TextParser;
using TextParser.Common;
namespace TextParserDemoApplication
{
class ParserDemo
{
static void Main(string[] args)
{
foreach (string arg in args)
{
ParsedText parsedText = Parser.ParsePlainText(arg);
foreach (Token token in parsedText.Tokens)
{
Console.WriteLine("\"" + parsedText.GetTokenText(token) + "\"");
}
}
}
}
}
| mit | C# |
24e78d015e40b633cdbd5b326aab94f82c504465 | Make UpdateScrollPosition virtual. | Nabile-Rahmani/osu,naoey/osu,EVAST9919/osu,johnneijzen/osu,UselessToucan/osu,peppy/osu-new,Drezi126/osu,RedNesto/osu,NeoAdonis/osu,DrabWeb/osu,naoey/osu,NeoAdonis/osu,Damnae/osu,peppy/osu,nyaamara/osu,osu-RP/osu-RP,smoogipoo/osu,tacchinotacchi/osu,Frontear/osuKyzer,ZLima12/osu,DrabWeb/osu,2yangk23/osu,smoogipoo/osu,smoogipooo/osu,UselessToucan/osu,NeoAdonis/osu,ZLima12/osu,peppy/osu,2yangk23/osu,peppy/osu,EVAST9919/osu,johnneijzen/osu,UselessToucan/osu,ppy/osu,ppy/osu,smoogipoo/osu,ppy/osu,DrabWeb/osu,naoey/osu | osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs | osu.Game.Modes.Taiko/Objects/Drawable/DrawableTaikoHitObject.cs | // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Taiko.Judgements;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgementInfo>
{
/// <summary>
/// The colour used for various elements of this DrawableHitObject.
/// </summary>
public virtual Color4 AccentColour { get; }
public DrawableTaikoHitObject(TaikoHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
LifetimeStart = HitObject.StartTime - HitObject.PreEmpt * 2;
LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt;
// Todo: Remove (suppresses Resharper)
AccentColour = Color4.White;
}
protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoJudgementInfo();
protected override void UpdateState(ArmedState state)
{
}
/// <summary>
/// Sets the scroll position of the DrawableHitObject relative to the offset between
/// a time value and the HitObject's StartTime.
/// </summary>
/// <param name="time"></param>
protected virtual void UpdateScrollPosition(double time)
{
MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt));
}
protected override void Update()
{
UpdateScrollPosition(Time.Current);
}
}
}
| // Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using OpenTK.Graphics;
using osu.Framework.Graphics;
using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Taiko.Judgements;
namespace osu.Game.Modes.Taiko.Objects.Drawable
{
public class DrawableTaikoHitObject : DrawableHitObject<TaikoHitObject, TaikoJudgementInfo>
{
/// <summary>
/// The colour used for various elements of this DrawableHitObject.
/// </summary>
public virtual Color4 AccentColour { get; }
public DrawableTaikoHitObject(TaikoHitObject hitObject)
: base(hitObject)
{
Anchor = Anchor.CentreLeft;
Origin = Anchor.Centre;
RelativePositionAxes = Axes.X;
LifetimeStart = HitObject.StartTime - HitObject.PreEmpt * 2;
LifetimeEnd = HitObject.StartTime + HitObject.PreEmpt;
// Todo: Remove (suppresses Resharper)
AccentColour = Color4.White;
}
protected override TaikoJudgementInfo CreateJudgementInfo() => new TaikoJudgementInfo();
protected override void UpdateState(ArmedState state)
{
}
/// <summary>
/// Sets the scroll position of the DrawableHitObject relative to the offset between
/// a time value and the HitObject's StartTime.
/// </summary>
/// <param name="time"></param>
protected void UpdateScrollPosition(double time)
{
MoveToX((float)((HitObject.StartTime - time) / HitObject.PreEmpt));
}
protected override void Update()
{
UpdateScrollPosition(Time.Current);
}
}
}
| mit | C# |
2859532705ca35641ddcc92c8d3905e54076dc83 | Mark 'GC.Allocate' with 'ReadNoneAttribute' | jonathanvdc/flame-llvm,jonathanvdc/flame-llvm,jonathanvdc/flame-llvm | runtime/GC.cs | runtime/GC.cs | namespace __compiler_rt
{
/// <summary>
/// Garbage collection functionality that can be used by the compiler.
/// </summary>
public static unsafe class GC
{
[#builtin_attribute(NoAliasAttribute)]
[#builtin_attribute(NoThrowAttribute)]
[#builtin_attribute(ReadNoneAttribute)]
private static extern void* GC_malloc(ulong size);
/// <summary>
/// Allocates a region of storage that is a number of bytes in size.
/// The storage is zero-initialized and a pointer to it is returned.
/// </summary>
/// <param name="size">The number of bytes to allocate.</param>
/// <returns>A pointer to a region of storage.</returns>
[#builtin_attribute(NoAliasAttribute)]
[#builtin_attribute(NoThrowAttribute)]
[#builtin_attribute(ReadNoneAttribute)]
public static void* Allocate(ulong size)
{
return GC_malloc(size);
}
}
}
| namespace __compiler_rt
{
/// <summary>
/// Garbage collection functionality that can be used by the compiler.
/// </summary>
public static unsafe class GC
{
[#builtin_attribute(NoAliasAttribute)]
[#builtin_attribute(NoThrowAttribute)]
private static extern void* GC_malloc(ulong size);
/// <summary>
/// Allocates a region of storage that is a number of bytes in size.
/// The storage is zero-initialized and a pointer to it is returned.
/// </summary>
/// <param name="size">The number of bytes to allocate.</param>
/// <returns>A pointer to a region of storage.</returns>
[#builtin_attribute(NoAliasAttribute)]
[#builtin_attribute(NoThrowAttribute)]
public static void* Allocate(ulong size)
{
return GC_malloc(size);
}
}
}
| mit | C# |
fd7b976d437459607581d916a7378707f7a4afb3 | Fix null reference check logic when unlocking a password. | bussemac/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,DejanMilicic/n2cms,SntsDev/n2cms,EzyWebwerkstaden/n2cms,nimore/n2cms,VoidPointerAB/n2cms,SntsDev/n2cms,bussemac/n2cms,nicklv/n2cms,VoidPointerAB/n2cms,nicklv/n2cms,n2cms/n2cms,bussemac/n2cms,DejanMilicic/n2cms,bussemac/n2cms,n2cms/n2cms,nicklv/n2cms,bussemac/n2cms,DejanMilicic/n2cms,n2cms/n2cms,DejanMilicic/n2cms,nimore/n2cms,nicklv/n2cms,EzyWebwerkstaden/n2cms,VoidPointerAB/n2cms,nimore/n2cms,SntsDev/n2cms,VoidPointerAB/n2cms,EzyWebwerkstaden/n2cms,EzyWebwerkstaden/n2cms,n2cms/n2cms,nimore/n2cms,nicklv/n2cms | src/Mvc/MvcTemplates/N2/Users/Password.aspx.cs | src/Mvc/MvcTemplates/N2/Users/Password.aspx.cs | using N2.Edit.Web;
using System;
using System.Web.Security;
using N2.Security;
namespace N2.Edit.Membership
{
public partial class Password : EditPage
{
string SelectedUserName;
private IAccountInfo SelectedUser;
private AccountManager AccountManager { get { return N2.Context.Current.Resolve<AccountManager>(); } }
protected void Page_Load(object sender, EventArgs e)
{
LoadSelectedUser();
}
protected void Page_PreRender(object sender, EventArgs e)
{
btnUnlock.Enabled = SelectedUser.IsLockedOut;
btnSave.Enabled = !SelectedUser.IsLockedOut;
}
private void LoadSelectedUser()
{
SelectedUserName = Request.QueryString["user"];
SelectedUser = AccountManager.FindUserByName(SelectedUserName);
if (SelectedUser == null)
throw new N2Exception("User '{0}' not found.", SelectedUserName);
/* REMOVE: MembershipUserCollection muc = System.Web.Security.Membership.FindUsersByName(SelectedUserName);
if (muc.Count < 1)
throw new N2.N2Exception("User '{0}' not found.", SelectedUserName);
SelectedUser = muc[SelectedUserName];
*/
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (SelectedUser == null)
throw new N2.N2Exception("User '{0}' not found.", SelectedUserName);
bool ok = AccountManager.ChangePassword(SelectedUser.UserName, this.txtPassword.Text);
/* REMOVE: string tempPW = SelectedUser.ResetPassword();
bool ok = SelectedUser.ChangePassword(tempPW, this.txtPassword.Text);
*/
if(ok)
Response.Redirect("Users.aspx");
}
protected void btnUnlock_Click(object sender, EventArgs e)
{
if (SelectedUser == null)
throw new N2.N2Exception("User '{0}' not found.", SelectedUserName);
AccountManager.UnlockUser(SelectedUser.UserName);
// REMOVE: SelectedUser.UnlockUser();
}
}
}
| using N2.Edit.Web;
using System;
using System.Web.Security;
using N2.Security;
namespace N2.Edit.Membership
{
public partial class Password : EditPage
{
string SelectedUserName;
private IAccountInfo SelectedUser;
private AccountManager AccountManager { get { return N2.Context.Current.Resolve<AccountManager>(); } }
protected void Page_Load(object sender, EventArgs e)
{
LoadSelectedUser();
}
protected void Page_PreRender(object sender, EventArgs e)
{
btnUnlock.Enabled = SelectedUser.IsLockedOut;
btnSave.Enabled = !SelectedUser.IsLockedOut;
}
private void LoadSelectedUser()
{
SelectedUserName = Request.QueryString["user"];
SelectedUser = AccountManager.FindUserByName(SelectedUserName);
if (SelectedUser == null)
throw new N2Exception("User '{0}' not found.", SelectedUserName);
/* REMOVE: MembershipUserCollection muc = System.Web.Security.Membership.FindUsersByName(SelectedUserName);
if (muc.Count < 1)
throw new N2.N2Exception("User '{0}' not found.", SelectedUserName);
SelectedUser = muc[SelectedUserName];
*/
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (SelectedUser == null)
throw new N2.N2Exception("User '{0}' not found.", SelectedUserName);
bool ok = AccountManager.ChangePassword(SelectedUser.UserName, this.txtPassword.Text);
/* REMOVE: string tempPW = SelectedUser.ResetPassword();
bool ok = SelectedUser.ChangePassword(tempPW, this.txtPassword.Text);
*/
if(ok)
Response.Redirect("Users.aspx");
}
protected void btnUnlock_Click(object sender, EventArgs e)
{
if (SelectedUser != null)
throw new N2.N2Exception("User '{0}' not found.", SelectedUserName);
AccountManager.UnlockUser(SelectedUser.UserName);
// REMOVE: SelectedUser.UnlockUser();
}
}
}
| lgpl-2.1 | C# |
995f4412b19a56790635e622cd27fc874dbe49f6 | include temp in indexname so we don't accidentally drop existing indexes and indicate that they are supposed to be temporary in case the drop statement gets lost | prebenh/Pregress.SqlPlanProblemFinder | src/Pregress.SqlPlanProblemFinder/IndexScan.cs | src/Pregress.SqlPlanProblemFinder/IndexScan.cs | using System.Linq;
using System.Xml.Linq;
namespace Pregress.SqlPlanProblemFinder
{
internal struct IndexScan
{
public string Table { get; set; }
public string Column { get; set; }
public XAttribute TableCardinality { get; set; }
public XAttribute AvgRowSize { get; set; }
public XAttribute EstimateRows { get; set; }
public IndexScan(XElement x)
{
var parent = x.Parent;
EstimateRows = parent.Attribute("EstimateRows");
AvgRowSize = parent.Attribute("AvgRowSize");
TableCardinality = parent.Attribute("TableCardinality");
var scalarString = x.Descendants(
"{http://schemas.microsoft.com/sqlserver/2004/07/showplan}ScalarOperator")
.Attributes("ScalarString").First().Value.Replace("[", "").Replace("]", "").Split('.');
Table = scalarString[2];
Column = scalarString[3].Remove(scalarString[3].IndexOf('='));
}
public string IndexName => $"IX_{Table}_{Column}_temp";
public string IfIndexNotExists => $"IF NOT EXISTS (SELECT 1 FROM sys.indexes i WHERE i.object_id = OBJECT_ID('{Table}') AND i.name = '{IndexName}')";
public string CreateStatement => $"CREATE NONCLUSTERED INDEX [{IndexName}] ON [{Table}] ([{Column}])";
public string DropStatement => $"DROP INDEX [{IndexName}] ON [{Table}]";
public override string ToString()
{
return $"-- {TableCardinality} {AvgRowSize} {EstimateRows}";
}
}
} | using System.Linq;
using System.Xml.Linq;
namespace Pregress.SqlPlanProblemFinder
{
internal struct IndexScan
{
public string Table { get; set; }
public string Column { get; set; }
public XAttribute TableCardinality { get; set; }
public XAttribute AvgRowSize { get; set; }
public XAttribute EstimateRows { get; set; }
public IndexScan(XElement x)
{
var parent = x.Parent;
EstimateRows = parent.Attribute("EstimateRows");
AvgRowSize = parent.Attribute("AvgRowSize");
TableCardinality = parent.Attribute("TableCardinality");
var scalarString = x.Descendants(
"{http://schemas.microsoft.com/sqlserver/2004/07/showplan}ScalarOperator")
.Attributes("ScalarString").First().Value.Replace("[", "").Replace("]", "").Split('.');
Table = scalarString[2];
Column = scalarString[3].Remove(scalarString[3].IndexOf('='));
}
public string CreateStatement => $"CREATE NONCLUSTERED INDEX [IX_{Table}_{Column}] ON [{Table}] ([{Column}])";
public string DropStatement => $"DROP INDEX [IX_{Table}_{Column}] ON [{Table}]";
public override string ToString()
{
return $"-- {TableCardinality} {AvgRowSize} {EstimateRows}";
}
}
} | mit | C# |
3109634e3e7f71c402d4df1ca86e1ca223b28a3b | Add ConnectionConfig to RawRabbitConfig | northspb/RawRabbit,pardahlman/RawRabbit | src/RawRabbit/Client/RawRabbitConfiguration.cs | src/RawRabbit/Client/RawRabbitConfiguration.cs | using System.Collections.Generic;
namespace RawRabbit.Client
{
public class RawRabbitConfiguration
{
public string Hostname { get; set; }
public List<ConnectionConfiguration> Connection { get; set; }
public static RawRabbitConfiguration Default = new RawRabbitConfiguration
{
Hostname = "localhost"
};
}
public class ConnectionConfiguration
{
public string Hostname { get; set; }
public string VirtualHost { get; set; }
public static ConnectionConfiguration Default => new ConnectionConfiguration
{
Hostname = "localhost",
VirtualHost = ""
};
}
}
| namespace RawRabbit.Client
{
public class RawRabbitConfiguration
{
public string Hostname { get; set; }
public static RawRabbitConfiguration Default = new RawRabbitConfiguration
{
Hostname = "localhost"
};
}
}
| mit | C# |
1078feb24cabdddd9b77a04aed3a5ba39158e0c6 | Move DMPPluginAttribute into the DarkMultiPlayerServer namespace, and only allow usage on classes. | RockyTV/DarkMultiPlayer,Dan-Shields/DarkMultiPlayer,Sanmilie/DarkMultiPlayer,81ninja/DarkMultiPlayer,godarklight/DarkMultiPlayer,rewdmister4/rewd-mod-packs,godarklight/DarkMultiPlayer,Kerbas-ad-astra/DarkMultiPlayer,RockyTV/DarkMultiPlayer,81ninja/DarkMultiPlayer,dsonbill/DarkMultiPlayer | Server/DMPPlugin.cs | Server/DMPPlugin.cs | using System;
using DarkMultiPlayerCommon;
namespace DarkMultiPlayerServer
{
[AttributeUsage(AttributeTargets.Class)]
public class DMPPluginAttribute : System.Attribute
{
//DMP will look for this attribute to load classes.
}
//Call your methods in your [DMPPlugin] class any of the following, minus the 'DMP' part. So DMPUpdate events require a method named Update.
public delegate void DMPUpdate();
public delegate void DMPOnServerStart();
public delegate void DMPOnServerStop();
public delegate void DMPOnClientConnect(ClientObject client);
public delegate void DMPOnClientAuthenticated(ClientObject client);
public delegate void DMPOnClientDisconnect(ClientObject client);
public delegate void DMPOnMessageReceived(ClientObject client, ClientMessage messageData);
public delegate void DMPOnMessageReceivedRaw(ClientObject client, ref ClientMessage messageData);
}
| using System;
using DarkMultiPlayerCommon;
public class DMPPluginAttribute : System.Attribute
{
//DMP will look for this attribute to load classes.
}
namespace DarkMultiPlayerServer
{
//Call your methods in your [DMPPlugin] class any of the following, minus the 'DMP' part. So DMPUpdate events require a method named Update.
public delegate void DMPUpdate();
public delegate void DMPOnServerStart();
public delegate void DMPOnServerStop();
public delegate void DMPOnClientConnect(ClientObject client);
public delegate void DMPOnClientAuthenticated(ClientObject client);
public delegate void DMPOnClientDisconnect(ClientObject client);
public delegate void DMPOnMessageReceived(ClientObject client, ClientMessage messageData);
public delegate void DMPOnMessageReceivedRaw(ClientObject client, ref ClientMessage messageData);
}
| mit | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.