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 |
|---|---|---|---|---|---|---|---|---|
cf0b63ccddde23e7ab98f37cff12dee63f30d958
|
Apply SqliteForeignKeyIndexConvention right after the ForeignKeyIndexConvetion.
|
liujunhua/SQLiteCodeFirst,msallin/SQLiteCodeFirst
|
SQLite.CodeFirst/SqliteInitializerBase.cs
|
SQLite.CodeFirst/SqliteInitializerBase.cs
|
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using SQLite.CodeFirst.Convention;
namespace SQLite.CodeFirst
{
public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext>
where TContext : DbContext
{
protected readonly DbModelBuilder ModelBuilder;
protected readonly string DatabaseFilePath;
protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder)
{
DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString);
ModelBuilder = modelBuilder;
// This convention will crash the SQLite Provider before "InitializeDatabase" gets called.
// See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details.
modelBuilder.Conventions.Remove<TimestampAttributeConvention>();
modelBuilder.Conventions.AddAfter<ForeignKeyIndexConvention>(new SqliteForeignKeyIndexConvention());
}
public virtual void InitializeDatabase(TContext context)
{
var model = ModelBuilder.Build(context.Database.Connection);
using (var transaction = context.Database.BeginTransaction())
{
try
{
var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model);
sqliteDatabaseCreator.Create();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
using (var transaction = context.Database.BeginTransaction())
{
try
{
Seed(context);
context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
protected virtual void Seed(TContext context) { }
}
}
|
using System;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace SQLite.CodeFirst
{
public abstract class SqliteInitializerBase<TContext> : IDatabaseInitializer<TContext>
where TContext : DbContext
{
protected readonly DbModelBuilder ModelBuilder;
protected readonly string DatabaseFilePath;
protected SqliteInitializerBase(string connectionString, DbModelBuilder modelBuilder)
{
DatabaseFilePath = SqliteConnectionStringParser.GetDataSource(connectionString);
ModelBuilder = modelBuilder;
// This convention will crash the SQLite Provider before "InitializeDatabase" gets called.
// See https://github.com/msallin/SQLiteCodeFirst/issues/7 for details.
modelBuilder.Conventions.Remove<TimestampAttributeConvention>();
}
public virtual void InitializeDatabase(TContext context)
{
var model = ModelBuilder.Build(context.Database.Connection);
using (var transaction = context.Database.BeginTransaction())
{
try
{
var sqliteDatabaseCreator = new SqliteDatabaseCreator(context.Database, model);
sqliteDatabaseCreator.Create();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
using (var transaction = context.Database.BeginTransaction())
{
try
{
Seed(context);
context.SaveChanges();
transaction.Commit();
}
catch (Exception)
{
transaction.Rollback();
throw;
}
}
}
protected virtual void Seed(TContext context) { }
}
}
|
apache-2.0
|
C#
|
e158aa2435fcc285bd100ac361244243e9c6f6da
|
add ET support for number literals
|
maul-esel/CobaltAHK,maul-esel/CobaltAHK
|
CobaltAHK/ExpressionTree/Generator.cs
|
CobaltAHK/ExpressionTree/Generator.cs
|
using System;
using System.Collections.Generic;
using DLR = System.Linq.Expressions;
using CobaltAHK.Expressions;
namespace CobaltAHK.ExpressionTree
{
public static class Generator
{
public static DLR.Expression Generate(Expression expr, Scope scope, ScriptSettings settings)
{
if (expr is FunctionCallExpression) {
return GenerateFunctionCall((FunctionCallExpression)expr, scope, settings);
} else if (expr is FunctionDefinitionExpression) {
return GenerateFunctionDefinition((FunctionDefinitionExpression)expr, scope, settings);
} else if (expr is StringLiteralExpression) {
return DLR.Expression.Constant(((StringLiteralExpression)expr).String);
} else if (expr is NumberLiteralExpression) {
return DLR.Expression.Constant(((NumberLiteralExpression)expr).GetValue());
}
throw new NotImplementedException();
}
private static DLR.Expression GenerateFunctionCall(FunctionCallExpression func, Scope scope, ScriptSettings settings)
{
var lambda = scope.ResolveFunction(func.Name);
var prms = new List<DLR.Expression>();
foreach (var p in func.Parameters) {
prms.Add(Generate(p, scope, settings));
}
return DLR.Expression.Invoke(lambda, prms);
}
private static DLR.Expression GenerateFunctionDefinition(FunctionDefinitionExpression func, Scope scope, ScriptSettings settings)
{
var funcScope = new Scope();
var prms = new List<DLR.ParameterExpression>();
var types = new List<Type>(prms.Count + 1);
foreach (var p in func.Parameters) {
// todo: default values
var param = DLR.Expression.Parameter(typeof(object), p.Name);
prms.Add(param);
funcScope.AddVariable(p.Name, param);
var type = typeof(object);
if (p.Modifier.HasFlag(Syntax.ParameterModifier.ByRef)) {
type = type.MakeByRefType();
}
types.Add(type);
}
types.Add(typeof(void)); // return value
var funcBody = new List<DLR.Expression>();
foreach (var e in func.Body) {
funcBody.Add(Generate(e, funcScope, settings));
}
var funcType = DLR.Expression.GetFuncType(types.ToArray());
var function = DLR.Expression.Lambda(funcType, DLR.Expression.Block(funcBody), func.Name, prms); // todo: use Label instead of Block? (see dlr-overview p. 35)
scope.AddFunction(func.Name, function); // todo: can't call itself, because body is generated before function is complete
return function;
}
}
}
|
using System;
using System.Collections.Generic;
using DLR = System.Linq.Expressions;
using CobaltAHK.Expressions;
namespace CobaltAHK.ExpressionTree
{
public static class Generator
{
public static DLR.Expression Generate(Expression expr, Scope scope, ScriptSettings settings)
{
if (expr is FunctionCallExpression) {
return GenerateFunctionCall((FunctionCallExpression)expr, scope, settings);
} else if (expr is FunctionDefinitionExpression) {
return GenerateFunctionDefinition((FunctionDefinitionExpression)expr, scope, settings);
} else if (expr is StringLiteralExpression) {
return DLR.Expression.Constant(((StringLiteralExpression)expr).String);
}
throw new NotImplementedException();
}
private static DLR.Expression GenerateFunctionCall(FunctionCallExpression func, Scope scope, ScriptSettings settings)
{
var lambda = scope.ResolveFunction(func.Name);
var prms = new List<DLR.Expression>();
foreach (var p in func.Parameters) {
prms.Add(Generate(p, scope, settings));
}
return DLR.Expression.Invoke(lambda, prms);
}
private static DLR.Expression GenerateFunctionDefinition(FunctionDefinitionExpression func, Scope scope, ScriptSettings settings)
{
var funcScope = new Scope();
var prms = new List<DLR.ParameterExpression>();
var types = new List<Type>(prms.Count + 1);
foreach (var p in func.Parameters) {
// todo: default values
var param = DLR.Expression.Parameter(typeof(object), p.Name);
prms.Add(param);
funcScope.AddVariable(p.Name, param);
var type = typeof(object);
if (p.Modifier.HasFlag(Syntax.ParameterModifier.ByRef)) {
type = type.MakeByRefType();
}
types.Add(type);
}
types.Add(typeof(void)); // return value
var funcBody = new List<DLR.Expression>();
foreach (var e in func.Body) {
funcBody.Add(Generate(e, funcScope, settings));
}
var funcType = DLR.Expression.GetFuncType(types.ToArray());
var function = DLR.Expression.Lambda(funcType, DLR.Expression.Block(funcBody), func.Name, prms); // todo: use Label instead of Block? (see dlr-overview p. 35)
scope.AddFunction(func.Name, function); // todo: can't call itself, because body is generated before function is complete
return function;
}
}
}
|
mit
|
C#
|
f9fbd56fea7499617883faac4994cd41eff0a1e2
|
Update CarroController.cs
|
cayodonatti/TopGearApi
|
TopGearApi/Controllers/CarroController.cs
|
TopGearApi/Controllers/CarroController.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TopGearApi.DataAccess;
using TopGearApi.Domain.Models;
using TopGearApi.Models;
namespace TopGearApi.Controllers
{
public class CarroController : TController<Carro>
{
[HttpGet]
[ActionName("ObterPorItem")]
public Response<IEnumerable<Carro>> GetByItem(int id)
{
return new Response<IEnumerable<Carro>>
{
Sucesso = true,
Dados = CarroDA.GetByItem(id)
};
}
[HttpGet]
[ActionName("ObterDisponiveis")]
public Response<IEnumerable<Carro>> GetDisponiveis()
{
return new Response<IEnumerable<Carro>>
{
Sucesso = true,
Dados = CarroDA.GetDisponiveis()
};
}
[HttpGet]
[ActionName("ObterDisponiveisPorAgencia")]
public Response<IEnumerable<Carro>> GetDisponiveisByAgencia(int id)
{
return new Response<IEnumerable<Carro>>
{
Sucesso = true,
Dados = CarroDA.GetDisponiveisByAgencia(id)
};
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TopGearApi.DataAccess;
using TopGearApi.Domain.Models;
using TopGearApi.Models;
namespace TopGearApi.Controllers
{
public class CarroController : TController<Carro>
{
private CarroDA DA = new CarroDA();
[HttpGet]
[ActionName("ObterPorItem")]
public Response<IEnumerable<Carro>> GetByItem(int id)
{
return new Response<IEnumerable<Carro>>
{
Sucesso = true,
Dados = DA.GetByItem(id)
};
}
[HttpGet]
[ActionName("ObterDisponiveis")]
public Response<IEnumerable<Carro>> GetDisponiveis()
{
return new Response<IEnumerable<Carro>>
{
Sucesso = true,
Dados = DA.GetDisponiveis()
};
}
[HttpGet]
[ActionName("ObterDisponiveisPorAgencia")]
public Response<IEnumerable<Carro>> GetDisponiveisByAgencia(int id)
{
return new Response<IEnumerable<Carro>>
{
Sucesso = true,
Dados = DA.GetDisponiveisByAgencia(id)
};
}
}
}
|
mit
|
C#
|
452b2c3463fe5002beb192303dbcc59983c1d441
|
add more pattern
|
autumn009/TanoCSharpSamples
|
chap36/PatternMatching/PatternMatching/Program.cs
|
chap36/PatternMatching/PatternMatching/Program.cs
|
using System;
using System.Linq;
class Program
{
static bool IsLetterOld(char c) => c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
static bool IsLetterNew(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';
static void Main()
{
// and/or sample
for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterOld((char)i) ? '1' : '0')}");
Console.WriteLine();
for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterNew((char)i) ? '1' : '0')}");
Console.WriteLine();
// is not null
object a1 = null, a2 = "";
bool b1 = a1 is not null;
bool b2 = a2 is not null;
Console.WriteLine($"{b1},{b2}");
// is int and/or
test(1);
test(101);
test("1");
void test(object p)
{
if (p is int x and <= 100)
Console.WriteLine($"{p}+1 is {x + 1}");
else
Console.WriteLine($"{p} is not the condition");
}
// property pattern
string[] s = { null, "", "Hello" };
foreach (var item in s) Console.WriteLine(item is { Length: > 1 });
// relational pattern
int[] ages = { 10, 30, 70 };
foreach (var item in ages)
{
Console.WriteLine(item switch
{
< 20 => "CHILD",
>= 20 and < 60 => "ADULT",
>= 60 => "OLDMAN"
});
}
}
}
|
using System;
class Program
{
static bool IsLetterOld(char c) => c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z';
static bool IsLetterNew(char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';
static void Main()
{
// and/or sample
for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterOld((char)i) ? '1' : '0')}");
Console.WriteLine();
for (int i = 0; i < 0xff; i++) Console.Write($"{(IsLetterNew((char)i) ? '1' : '0')}");
Console.WriteLine();
// is not null
object a1 = null, a2 = "";
bool b1 = a1 is not null;
bool b2 = a2 is not null;
Console.WriteLine($"{b1},{b2}");
// is int and/or
test(1);
test(101);
test("1");
void test(object p)
{
if (p is int x and <= 100)
Console.WriteLine($"{p}+1 is {x + 1}");
else
Console.WriteLine($"{p} is not the condition");
}
}
}
|
mit
|
C#
|
3525128742cddbfc7799f9aa0483ea43b73c62a0
|
Fix folder name for toolbar icon
|
DMagic1/KSP_Contract_Window,Kerbas-ad-astra/KSP_Contract_Window
|
Toolbar/contractToolbar.cs
|
Toolbar/contractToolbar.cs
|
#region license
/*The MIT License (MIT)
Contract Toolbar- Addon for toolbar interface
Copyright (c) 2014 DMagic
KSP Plugin Framework by TriggerAu, 2014: http://forum.kerbalspaceprogram.com/threads/66503-KSP-Plugin-Framework
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.IO;
using System;
using UnityEngine;
namespace ContractsWindow.Toolbar
{
class contractToolbar : DMC_MBE
{
private IButton contractButton;
protected override void Start()
{
setupToolbar();
}
private void setupToolbar()
{
if (!ToolbarManager.ToolbarAvailable) return;
int sceneInt = contractScenario.currentScene(HighLogic.LoadedScene);
contractButton = ToolbarManager.Instance.add("ContractsWindow", "ContractWindowPlus");
if (File.Exists(Path.Combine(new DirectoryInfo(KSPUtil.ApplicationRootPath).FullName, "GameData/ContractsWindow/Textures/ContractsIcon.png").Replace("\\", "/")))
contractButton.TexturePath = "ContractsWindow/Textures/ContractsIcon";
else
contractButton.TexturePath = "000_Toolbar/resize-cursor";
contractButton.ToolTip = "Contract Window";
contractButton.OnClick += (e) =>
{
if (contractScenario.Instance == null)
DMC_MBE.LogFormatted("Contract Scenario Not Loaded...");
else if (contractScenario.Instance.cWin == null)
DMC_MBE.LogFormatted("Contract Window Not Loaded...");
else
{
if (contractScenario.Instance.cWin.Visible)
{
contractScenario.Instance.cWin.Visible = false;
contractScenario.Instance.cWin.StopRepeatingWorker();
contractScenario.Instance.windowVisible[sceneInt] = false;
}
else
{
contractScenario.Instance.cWin.Visible = true;
contractScenario.Instance.cWin.StartRepeatingWorker(5);
contractScenario.Instance.windowVisible[sceneInt] = true;
}
}
};
}
protected override void OnDestroy()
{
if (!ToolbarManager.ToolbarAvailable) return;
if (contractButton != null)
contractButton.Destroy();
}
}
}
|
#region license
/*The MIT License (MIT)
Contract Toolbar- Addon for toolbar interface
Copyright (c) 2014 DMagic
KSP Plugin Framework by TriggerAu, 2014: http://forum.kerbalspaceprogram.com/threads/66503-KSP-Plugin-Framework
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#endregion
using System.IO;
using System;
using UnityEngine;
namespace ContractsWindow.Toolbar
{
class contractToolbar : DMC_MBE
{
private IButton contractButton;
protected override void Start()
{
setupToolbar();
}
private void setupToolbar()
{
if (!ToolbarManager.ToolbarAvailable) return;
int sceneInt = contractScenario.currentScene(HighLogic.LoadedScene);
contractButton = ToolbarManager.Instance.add("ContractsWindow", "ContractWindowPlus");
if (File.Exists(Path.Combine(new DirectoryInfo(KSPUtil.ApplicationRootPath).FullName, "GameData/Contracts Window/Textures/ContractsIcon.png").Replace("\\", "/")))
contractButton.TexturePath = "Contracts Window/Textures/ContractsIcon";
else
contractButton.TexturePath = "000_Toolbar/resize-cursor";
contractButton.ToolTip = "Contract Window";
contractButton.OnClick += (e) =>
{
if (contractScenario.Instance == null)
DMC_MBE.LogFormatted("Contract Scenario Not Loaded...");
else if (contractScenario.Instance.cWin == null)
DMC_MBE.LogFormatted("Contract Window Not Loaded...");
else
{
if (contractScenario.Instance.cWin.Visible)
{
contractScenario.Instance.cWin.Visible = false;
contractScenario.Instance.cWin.StopRepeatingWorker();
contractScenario.Instance.windowVisible[sceneInt] = false;
}
else
{
contractScenario.Instance.cWin.Visible = true;
contractScenario.Instance.cWin.StartRepeatingWorker(5);
contractScenario.Instance.windowVisible[sceneInt] = true;
}
}
};
}
protected override void OnDestroy()
{
if (!ToolbarManager.ToolbarAvailable) return;
if (contractButton != null)
contractButton.Destroy();
}
}
}
|
mit
|
C#
|
2000aaa4aa572699e80d6d4154e9d8d889b58bdb
|
Bump version to 3.3
|
jcheng31/DarkSkyApi,jcheng31/ForecastPCL
|
DarkSkyApi/Properties/AssemblyInfo.cs
|
DarkSkyApi/Properties/AssemblyInfo.cs
|
using System.Resources;
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("DarkSkyApi")]
[assembly: AssemblyDescription("An unofficial library for the Dark Sky weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("DarkSkyApi")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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.3.0.0")]
[assembly: AssemblyFileVersion("3.3.0.0")]
|
using System.Resources;
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("DarkSkyApi")]
[assembly: AssemblyDescription("An unofficial PCL for the Dark Sky weather API.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Jerome Cheng")]
[assembly: AssemblyProduct("DarkSkyApi")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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.2.1.0")]
[assembly: AssemblyFileVersion("3.2.1.0")]
|
mit
|
C#
|
7472ec4e451372d7e445e4d3b02485c41240ab25
|
Fix thet WarriorSkillPanel remains bright when player died during using space
|
bunashibu/kikan
|
Assets/Scripts/Canvas/Skill/Unique/WarriorSkillPanel.cs
|
Assets/Scripts/Canvas/Skill/Unique/WarriorSkillPanel.cs
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
namespace Bunashibu.Kikan {
public class WarriorSkillPanel : SkillPanel {
public void Register(Hammer hammer) {
base.Register(hammer);
hammer.IsAcceptingCtrlBreak
.Where(isAccepting => isAccepting)
.Subscribe(_ => ShowUniqueSlot(3, 0) )
.AddTo(hammer.gameObject);
hammer.IsAcceptingCtrlBreak
.Where(isAccepting => !isAccepting)
.Subscribe(_ => HideUniqueSlot(3, 0) )
.AddTo(hammer.gameObject);
hammer.IsAcceptingSpaceBreak
.Where(isAccepting => isAccepting)
.Subscribe(_ => ShowUniqueSlot(4, 1) )
.AddTo(hammer.gameObject);
hammer.IsAcceptingSpaceBreak
.Where(isAccepting => !isAccepting)
.Subscribe(_ => HideUniqueSlot(4, 1) )
.AddTo(hammer.gameObject);
EventStream.OnClientPlayerDied
.Subscribe(_ => HideUniqueSlot(4, 1) )
.AddTo(hammer.gameObject);
}
private void ShowUniqueSlot(int index, int slotIndex) {
_alphaRectTransform[index].parent.gameObject.SetActive(false);
_uniqueSlotObj[slotIndex].SetActive(true);
}
private void HideUniqueSlot(int index, int slotIndex) {
_alphaRectTransform[index].parent.gameObject.SetActive(true);
_uniqueSlotObj[slotIndex].SetActive(false);
}
protected override void HideAll() {
base.HideAll();
foreach (var uniqueSlotObj in _uniqueSlotObj)
uniqueSlotObj.SetActive(false);
}
// NOTE: CtrlBreakSlot is must be 0
// SpaceBreakSlot is must be 1
[SerializeField] private List<GameObject> _uniqueSlotObj;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UniRx;
namespace Bunashibu.Kikan {
public class WarriorSkillPanel : SkillPanel {
public void Register(Hammer hammer) {
base.Register(hammer);
hammer.IsAcceptingCtrlBreak
.Where(isAccepting => isAccepting)
.Subscribe(_ => ShowUniqueSlot(3, 0) )
.AddTo(hammer.gameObject);
hammer.IsAcceptingCtrlBreak
.Where(isAccepting => !isAccepting)
.Subscribe(_ => HideUniqueSlot(3, 0) )
.AddTo(hammer.gameObject);
hammer.IsAcceptingSpaceBreak
.Where(isAccepting => isAccepting)
.Subscribe(_ => ShowUniqueSlot(4, 1) )
.AddTo(hammer.gameObject);
hammer.IsAcceptingSpaceBreak
.Where(isAccepting => !isAccepting)
.Subscribe(_ => HideUniqueSlot(4, 1) )
.AddTo(hammer.gameObject);
}
private void ShowUniqueSlot(int index, int slotIndex) {
_alphaRectTransform[index].parent.gameObject.SetActive(false);
_uniqueSlotObj[slotIndex].SetActive(true);
}
private void HideUniqueSlot(int index, int slotIndex) {
_alphaRectTransform[index].parent.gameObject.SetActive(true);
_uniqueSlotObj[slotIndex].SetActive(false);
}
protected override void HideAll() {
base.HideAll();
foreach (var uniqueSlotObj in _uniqueSlotObj)
uniqueSlotObj.SetActive(false);
}
// NOTE: CtrlBreakSlot is must be 0
// SpaceBreakSlot is must be 1
[SerializeField] private List<GameObject> _uniqueSlotObj;
}
}
|
mit
|
C#
|
fbba6538d9687853e73fea162c3ac6524bba94f3
|
Load Context from file (step 1)
|
GGProductions/LetterStorm,GGProductions/LetterStorm,GGProductions/LetterStorm
|
Assets/Scripts/Context.cs
|
Assets/Scripts/Context.cs
|
using UnityEngine;
using System.Collections;
using GGProductions.LetterStorm.Data.Collections;
using GGProductions.LetterStorm.Data;
using GGProductions.LetterStorm.Utilities;
public class Context : MonoBehaviour
{
#region Pathfinding Variables ---------------------------------------------
// Boss word hint
public static string BossWordHint;
#endregion Pathfinding Variables ------------------------------------------
#region Private Variables ---------------------------------------------
// Create the private variables that the this class's
// properties will use to store their data
private static LessonBook _curriculum;
private static int _playerLives;
private static Inventory _playerInventory;
private static char[] _alphabet;
#endregion Private Variables ------------------------------------------
#region Properties ----------------------------------------------------
/// <summary>Stores the alphabet for efficient coding</summary>
public static char[] Alphabet
{
get { return _alphabet; }
set { _alphabet = value; }
}
/// <summary>Represents all the Lessons for a specific user</summary>
public static LessonBook Curriculum
{
get { return _curriculum; }
set { _curriculum = value; }
}
/// <summary>Player inventory</summary>
public static Inventory PlayerInventory
{
get { return _playerInventory; }
set { _playerInventory = value; }
}
/// <summary>Tracks player lives</summary>
public static int PlayerLives
{
get { return _playerLives; }
set { _playerLives = value; }
}
#endregion Properties -------------------------------------------------
#region Event Handlers ----------------------------------------------------
/// <summary>
/// Method that runs only once in the beginning
/// </summary>
void Start()
{
PlayerLives = 3;
PlayerInventory = new Inventory();
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
BossWordHint = "\nRoar, I am a hint >:D Rawrawrawrawrwrwarw";
// Populate the Context from the save file
LoadDataFromSaveFile(false);
}
#endregion Event Handlers -------------------------------------------------
#region Helper Methods ----------------------------------------------------
/// <summary>
/// Populate the Context from the save file
/// </summary>
/// <param name="loadGameState">
/// True=Load both the stateless data and the game state from the save file (ie the user is loading a saved game);
/// False=Load only the stateless data from the save file (ie the user is starting a new game)
/// </param>
private void LoadDataFromSaveFile(bool loadGameState)
{
// Retrieve all data from the save file
PlayerData tmpPlayerData = GameStateUtilities.Load();
// Copy the lessons to the Context
_curriculum = tmpPlayerData.Curriculum;
// If the user has not created any lessons, create a sample lesson to work with
if (_curriculum.Lessons.Count == 0)
{
_curriculum.CreateSampleLesson();
}
// If the game state should be loaded (ie the user is loading a saved game)...
if (loadGameState)
{
// PLACEHOLDER: This code has not yet been implimented
}
}
#endregion Helper Methods -------------------------------------------------
}
|
using UnityEngine;
using System.Collections;
public class Context : MonoBehaviour {
// Static variables to track in-game information
// Tracks player lives
public static int PlayerLives;
// Player inventory
public static Inventory PlayerInventory;
// Stores the alphabet for efficient coding
public static char[] Alphabet;
/// <summary>
/// Method that runs only once in the beginning
/// </summary>
void Start()
{
PlayerLives = 3;
PlayerInventory = new Inventory();
Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
}
}
|
mit
|
C#
|
99c5b77dc66a603df29ed6e7820e8f43c0a66180
|
Fix whitespace
|
dipeshc/BTDeploy
|
src/MonoTorrent/MonoTorrent.Tracker/Listeners/ManualListener.cs
|
src/MonoTorrent/MonoTorrent.Tracker/Listeners/ManualListener.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker.Listeners
{
public class ManualListener : ListenerBase
{
private bool running;
public override bool Running
{
get { return running; }
}
public override void Start()
{
running = true;
}
public override void Stop()
{
running = false;
}
public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress)
{
if (rawUrl == null)
throw new ArgumentNullException("rawUrl");
if (remoteAddress == null)
throw new ArgumentOutOfRangeException("remoteAddress");
rawUrl = rawUrl.Substring(rawUrl.LastIndexOf('/'));
bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase);
return Handle(rawUrl, remoteAddress, isScrape);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using MonoTorrent.BEncoding;
using System.Net;
namespace MonoTorrent.Tracker.Listeners
{
public class ManualListener : ListenerBase
{
private bool running;
public override bool Running
{
get { return running; }
}
public override void Start()
{
running = true;
}
public override void Stop()
{
running = false;
}
public BEncodedValue Handle(string rawUrl, IPAddress remoteAddress)
{
if (rawUrl == null)
throw new ArgumentNullException("rawUrl");
if (remoteAddress == null)
throw new ArgumentOutOfRangeException("remoteAddress");
rawUrl = rawUrl.Substring(rawUrl.LastIndexOf('/'));
bool isScrape = rawUrl.StartsWith("/scrape", StringComparison.OrdinalIgnoreCase);
return Handle(rawUrl, remoteAddress, isScrape);
}
}
}
|
mit
|
C#
|
649f30929c90202381c77b2ffcdd4c3656e8f523
|
Change SaveOrUpdateAsync to return the entity as the async natur will not know the result.
|
generik0/Smooth.IoC.Dapper.Repository.UnitOfWork,generik0/Smooth.IoC.Dapper.Repository.UnitOfWork
|
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/IRepository.cs
|
src/Smooth.IoC.Dapper.Repository.UnitOfWork/Repo/IRepository.cs
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public interface IRepository<TEntity, TPk>
where TEntity : class
{
TEntity GetKey(TPk key, ISession session);
TEntity GetKey<TSesssion>(TPk key) where TSesssion : class, ISession;
Task<TEntity> GetKeyAsync(TPk key, ISession session);
Task<TEntity> GetKeyAsync<TSesssion>(TPk key) where TSesssion : class, ISession;
TEntity Get(TEntity entity, ISession session);
TEntity Get<TSesssion>(TEntity entity) where TSesssion : class, ISession;
Task<TEntity> GetAsync(TEntity entity, ISession session);
Task<TEntity> GetAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
IEnumerable<TEntity> GetAll(ISession session);
IEnumerable<TEntity> GetAll<TSesssion>() where TSesssion : class, ISession;
Task<IEnumerable<TEntity>> GetAllAsync(ISession session);
Task<IEnumerable<TEntity>> GetAllAsync<TSesssion>() where TSesssion : class, ISession;
TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow);
TPk SaveOrUpdate<TSesssion>(TEntity entity) where TSesssion : class, ISession;
Task<TEntity> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow);
Task<TEntity> SaveOrUpdateAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
using Smooth.IoC.Dapper.Repository.UnitOfWork.Data;
namespace Smooth.IoC.Dapper.Repository.UnitOfWork.Repo
{
public interface IRepository<TEntity, TPk>
where TEntity : class
{
TEntity GetKey(TPk key, ISession session);
TEntity GetKey<TSesssion>(TPk key) where TSesssion : class, ISession;
Task<TEntity> GetKeyAsync(TPk key, ISession session);
Task<TEntity> GetKeyAsync<TSesssion>(TPk key) where TSesssion : class, ISession;
TEntity Get(TEntity entity, ISession session);
TEntity Get<TSesssion>(TEntity entity) where TSesssion : class, ISession;
Task<TEntity> GetAsync(TEntity entity, ISession session);
Task<TEntity> GetAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
IEnumerable<TEntity> GetAll(ISession session);
IEnumerable<TEntity> GetAll<TSesssion>() where TSesssion : class, ISession;
Task<IEnumerable<TEntity>> GetAllAsync(ISession session);
Task<IEnumerable<TEntity>> GetAllAsync<TSesssion>() where TSesssion : class, ISession;
TPk SaveOrUpdate(TEntity entity, IUnitOfWork uow);
TPk SaveOrUpdate<TSesssion>(TEntity entity) where TSesssion : class, ISession;
Task<TPk> SaveOrUpdateAsync(TEntity entity, IUnitOfWork uow);
Task<TPk> SaveOrUpdateAsync<TSesssion>(TEntity entity) where TSesssion : class, ISession;
}
}
|
mit
|
C#
|
692fe7f1b4131b15034f2f7c71792602ee54baea
|
test commit from stefan
|
abmes/UnityExtensions
|
Semba.UnityExtensions/UnityContainerExtensionMethods.cs
|
Semba.UnityExtensions/UnityContainerExtensionMethods.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
namespace Semba.UnityExtensions
{
public static class UnityContainerExtensionMethods
{
public static IUnityContainer RegisterTypeSingleton<TFrom, TTo>(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom
{
return container.RegisterType<TFrom, TTo>(new ContainerControlledLifetimeManager(), injectionMembers);
}
public static IUnityContainer RegisterTypeSingleton<T>(this IUnityContainer container, params InjectionMember[] injectionMembers)
{
return container.RegisterType<T>(new ContainerControlledLifetimeManager(), injectionMembers);
}
public static IUnityContainer RegisterIEnumerable(this IUnityContainer container)
{
return container.RegisterType(typeof(IEnumerable<>), new InjectionFactory((c, t, n) => c.ResolveAll(t.GetGenericArguments().Single())));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
namespace Semba.UnityExtensions
{
public static class UnityContainerExtensionMethods
{
public static IUnityContainer RegisterTypeSingleton<TFrom, TTo>(this IUnityContainer container, params InjectionMember[] injectionMembers) where TTo : TFrom
{
return container.RegisterType<TFrom, TTo>(new ContainerControlledLifetimeManager(), injectionMembers);
}
public static IUnityContainer RegisterTypeSingleton<T>(this IUnityContainer container, params InjectionMember[] injectionMembers)
{
return container.RegisterType<T>(new ContainerControlledLifetimeManager(), injectionMembers);
}
public static IUnityContainer RegisterIEnumerable(this IUnityContainer container)
{
return container.RegisterType(typeof(IEnumerable<>), new InjectionFactory((c, t, n) => c.ResolveAll(t.GetGenericArguments().Single())));
}
}
}
|
mit
|
C#
|
1f8a6492a3bd4eab9b2df9e725973ce0a2c87caf
|
Update build.cake
|
predictive-technology-laboratory/Xamarin.Plugins,jamesmontemagno/Xamarin.Plugins
|
Geolocator/build.cake
|
Geolocator/build.cake
|
#addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "NuGetPack"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Build").Does (() =>
{
const string sln = "./Geolocator.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Build")
.Does (() =>
{
NuGetPack ("./Geolocator.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET);
|
#addin "Cake.FileHelpers"
var TARGET = Argument ("target", Argument ("t", "Build"));
var version = EnvironmentVariable ("APPVEYOR_BUILD_VERSION") ?? Argument("version", "0.0.9999");
Task ("Build").Does (() =>
{
const string sln = "./Geolocator.sln";
const string cfg = "Release";
NuGetRestore (sln);
if (!IsRunningOnWindows ())
DotNetBuild (sln, c => c.Configuration = cfg);
else
MSBuild (sln, c => {
c.Configuration = cfg;
c.MSBuildPlatform = MSBuildPlatform.x86;
});
});
Task ("NuGetPack")
.IsDependentOn ("Build")
.Does (() =>
{
NuGetPack ("./Geolocator.Plugin.nuspec", new NuGetPackSettings {
Version = version,
Verbosity = NuGetVerbosity.Detailed,
OutputDirectory = "./",
BasePath = "./",
});
});
RunTarget (TARGET);
|
mit
|
C#
|
d938478f52961cda9d51f69fbbf0c9f714ab31f1
|
Update Assets/MixedRealityToolkit/Interfaces/InputSystem/IMixedRealityEyeGazeProvider.cs
|
killerantz/HoloToolkit-Unity,DDReaper/MixedRealityToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity,killerantz/HoloToolkit-Unity
|
Assets/MixedRealityToolkit/Interfaces/InputSystem/IMixedRealityEyeGazeProvider.cs
|
Assets/MixedRealityToolkit/Interfaces/InputSystem/IMixedRealityEyeGazeProvider.cs
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Implements the Gaze Provider for an Input Source.
/// </summary>
public interface IMixedRealityEyeGazeProvider : IMixedRealityGazeProvider
{
/// <summary>
/// Whether eye gaze is valid. It may be invalid due to timeout or lack of tracking hardware or permissions.
/// </summary>
bool IsEyeGazeValid { get; }
/// <summary>
/// If true, eye-based tracking will be used when available.
/// </summary>
/// <remarks>
/// The usage of eye-based tracking depends on having the Gaze Input permission set
/// and user approved, along with proper device eye calibration. This will fallback to head-based
/// gaze when eye-based tracking is not available.
/// </remarks>
bool UseEyeTracking { get; set; }
/// <summary>
/// DateTime in UTC when the signal was last updated.
/// </summary>
DateTime Timestamp { get; }
/// <summary>
/// Tells the eye gaze provider that eye gaze has updated.
/// </summary>
/// <param name="provider">The provider raising the event.</param>
/// <param name="eyeRay"></param>
/// <param name="timestamp"></param>
/// <remarks>
/// This method is to be called by implementations of the <see cref="IMixedRealityEyeGazeDataProvider"/> interface, not by application code.
/// </remarks>
void UpdateEyeGaze(IMixedRealityEyeGazeDataProvider provider, Ray eyeRay, DateTime timestamp);
}
}
|
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using System;
using UnityEngine;
namespace Microsoft.MixedReality.Toolkit.Input
{
/// <summary>
/// Implements the Gaze Provider for an Input Source.
/// </summary>
public interface IMixedRealityEyeGazeProvider : IMixedRealityGazeProvider
{
/// <summary>
/// Whether eye gaze is valid. It may be invalid due to timeout or lack of tracking hardware or permissions.
/// </summary>
bool IsEyeGazeValid { get; }
/// <summary>
/// If true, eye-based tracking will be used when available.
/// </summary>
/// <remarks>
/// The usage of eye-based tracking depends on having the Gaze Input permission set
/// and user approved, along with proper device eye calibration. This willback to head-based
/// gaze when eye-based tracking is not available.
/// </remarks>
bool UseEyeTracking { get; set; }
/// <summary>
/// DateTime in UTC when the signal was last updated.
/// </summary>
DateTime Timestamp { get; }
/// <summary>
/// Tells the eye gaze provider that eye gaze has updated.
/// </summary>
/// <param name="provider">The provider raising the event.</param>
/// <param name="eyeRay"></param>
/// <param name="timestamp"></param>
/// <remarks>
/// This method is to be called by implementations of the <see cref="IMixedRealityEyeGazeDataProvider"/> interface, not by application code.
/// </remarks>
void UpdateEyeGaze(IMixedRealityEyeGazeDataProvider provider, Ray eyeRay, DateTime timestamp);
}
}
|
mit
|
C#
|
d54d039e5beb72f8522b9270730a4163ce63d945
|
Add log project.
|
bzshang/PIFitness.Main
|
PIFitness.Fitbit/FitbitTableReader.cs
|
PIFitness.Fitbit/FitbitTableReader.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSIsoft.AF.Asset;
using PIFitness.Entities;
using PIFitness.Common.Interfaces;
using PIFitness.Log;
using System.Diagnostics;
namespace PIFitness.Fitbit
{
public class FitbitTableReader : ITableReader<UserEntry>
{
private UserRepository _userRepository;
private ITableFilter<UserEntry> _filter;
public FitbitTableReader(UserRepository userRepository, ITableFilter<UserEntry> filter)
{
_userRepository = userRepository;
_filter = filter;
}
public IQueryable<UserEntry> Read()
{
try
{
IQueryable<UserEntry> userTable = _userRepository.UserTable;
userTable = _filter.FilterTable(userTable);
return userTable;
}
catch (Exception ex)
{
PIFitnessLog.Write(TraceEventType.Error, 0, string.Format("Error in FitbitTableReader.Read(): {0}", ex.Message));
return null;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OSIsoft.AF.Asset;
using PIFitness.Entities;
using PIFitness.Common.Interfaces;
namespace PIFitness.Fitbit
{
public class FitbitTableReader : ITableReader<UserEntry>
{
private UserRepository _userRepository;
private ITableFilter<UserEntry> _filter;
public FitbitTableReader(UserRepository userRepository, ITableFilter<UserEntry> filter)
{
_userRepository = userRepository;
_filter = filter;
}
public IQueryable<UserEntry> Read()
{
IQueryable<UserEntry> userTable = _userRepository.UserTable;
userTable = _filter.FilterTable(userTable);
return userTable;
}
}
}
|
apache-2.0
|
C#
|
89bf7b1bd669d83e57b6f299b0489e8cd950b1ab
|
Resolve CA1835 inspection
|
NeoAdonis/osu,smoogipoo/osu,smoogipoo/osu,peppy/osu,ppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,peppy/osu,ppy/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,NeoAdonis/osu
|
osu.Game/IO/Archives/ArchiveReader.cs
|
osu.Game/IO/Archives/ArchiveReader.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Game.IO.Archives
{
public abstract class ArchiveReader : IResourceStore<byte[]>
{
/// <summary>
/// Opens a stream for reading a specific file from this archive.
/// </summary>
public abstract Stream GetStream(string name);
public IEnumerable<string> GetAvailableResources() => Filenames;
public abstract void Dispose();
/// <summary>
/// The name of this archive (usually the containing filename).
/// </summary>
public readonly string Name;
protected ArchiveReader(string name)
{
Name = name;
}
public abstract IEnumerable<string> Filenames { get; }
public virtual byte[] Get(string name) => GetAsync(name).Result;
public async Task<byte[]> GetAsync(string name)
{
using (Stream input = GetStream(name))
{
if (input == null)
return null;
byte[] buffer = new byte[input.Length];
await input.ReadAsync(buffer);
return buffer;
}
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using osu.Framework.IO.Stores;
namespace osu.Game.IO.Archives
{
public abstract class ArchiveReader : IResourceStore<byte[]>
{
/// <summary>
/// Opens a stream for reading a specific file from this archive.
/// </summary>
public abstract Stream GetStream(string name);
public IEnumerable<string> GetAvailableResources() => Filenames;
public abstract void Dispose();
/// <summary>
/// The name of this archive (usually the containing filename).
/// </summary>
public readonly string Name;
protected ArchiveReader(string name)
{
Name = name;
}
public abstract IEnumerable<string> Filenames { get; }
public virtual byte[] Get(string name) => GetAsync(name).Result;
public async Task<byte[]> GetAsync(string name)
{
using (Stream input = GetStream(name))
{
if (input == null)
return null;
byte[] buffer = new byte[input.Length];
await input.ReadAsync(buffer, 0, buffer.Length);
return buffer;
}
}
}
}
|
mit
|
C#
|
311fae95a1c53faf1da56b79ea8dbc2ba677fe35
|
fix loading setting
|
shrimpz/slua,luzexi/slua-3rd,haolly/slua_source_note,mr-kelly/slua,haolly/slua_source_note,haolly/slua_source_note,yaukeywang/slua,shrimpz/slua,pangweiwei/slua,Roland0511/slua,jiangzhhhh/slua,pangweiwei/slua,mr-kelly/slua,pangweiwei/slua,luzexi/slua-3rd-lib,Roland0511/slua,soulgame/slua,soulgame/slua,Roland0511/slua,luzexi/slua-3rd,mr-kelly/slua,luzexi/slua-3rd-lib,mr-kelly/slua,luzexi/slua-3rd-lib,haolly/slua_source_note,soulgame/slua,Roland0511/slua,soulgame/slua,luzexi/slua-3rd-lib,Roland0511/slua,yaukeywang/slua,yaukeywang/slua,pangweiwei/slua,jiangzhhhh/slua,pangweiwei/slua,luzexi/slua-3rd-lib,luzexi/slua-3rd,yaukeywang/slua,soulgame/slua,luzexi/slua-3rd,haolly/slua_source_note,luzexi/slua-3rd,yaukeywang/slua,jiangzhhhh/slua,jiangzhhhh/slua,mr-kelly/slua,soulgame/slua,jiangzhhhh/slua,luzexi/slua-3rd,yaukeywang/slua,jiangzhhhh/slua,haolly/slua_source_note,Roland0511/slua,luzexi/slua-3rd-lib,mr-kelly/slua
|
Assets/Plugins/Slua_Managed/SLuaSetting.cs
|
Assets/Plugins/Slua_Managed/SLuaSetting.cs
|
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace SLua{
public enum EOL{
Native,
CRLF,
CR,
LF,
}
public class SLuaSetting : ScriptableObject {
public EOL eol = EOL.Native;
public bool exportExtensionMethod = true;
public string UnityEngineGeneratePath = "Assets/Slua/LuaObject/";
public int debugPort=10240;
public string debugIP="0.0.0.0";
private static SLuaSetting _instance;
public static SLuaSetting Instance{
get{
if(_instance == null){
_instance = Resources.Load<SLuaSetting>("setting");
#if UNITY_EDITOR
if(_instance == null){
_instance = SLuaSetting.CreateInstance<SLuaSetting>();
AssetDatabase.CreateAsset(_instance,"Assets/Slua/Resources/setting.asset");
}
#endif
}
return _instance;
}
}
#if UNITY_EDITOR
[MenuItem("SLua/Setting")]
public static void Open(){
Selection.activeObject = Instance;
}
#endif
}
}
|
// The MIT License (MIT)
// Copyright 2015 Siney/Pangweiwei siney@yeah.net
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using UnityEngine;
using System.Collections;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace SLua{
public enum EOL{
Native,
CRLF,
CR,
LF,
}
public class SLuaSetting : ScriptableObject {
public EOL eol = EOL.Native;
public bool exportExtensionMethod = true;
public string UnityEngineGeneratePath = "Assets/Slua/LuaObject/";
public int debugPort=10240;
public string debugIP="0.0.0.0";
private static SLuaSetting _instance;
public static SLuaSetting Instance{
get{
if(_instance == null){
string path = "Assets/Slua/setting.asset";
_instance = Resources.Load<SLuaSetting>(path);
#if UNITY_EDITOR
if(_instance == null){
_instance = SLuaSetting.CreateInstance<SLuaSetting>();
AssetDatabase.CreateAsset(_instance,path);
}
#endif
}
return _instance;
}
}
#if UNITY_EDITOR
[MenuItem("SLua/Setting")]
public static void Open(){
Selection.activeObject = Instance;
}
#endif
}
}
|
mit
|
C#
|
99ba598b2b3a8b66d1a2230b3361d0e2abc0aa6b
|
Fix incorrect project file type description
|
JetBrains/resharper-unity,JetBrains/resharper-unity,JetBrains/resharper-unity
|
resharper/resharper-unity/src/Unity/Yaml/ProjectModel/MetaProjectFileType.cs
|
resharper/resharper-unity/src/Unity/Yaml/ProjectModel/MetaProjectFileType.cs
|
using JetBrains.Annotations;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
#nullable enable
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel
{
[ProjectFileTypeDefinition(Name)]
public class MetaProjectFileType : YamlProjectFileType
{
public new const string Name = "Meta";
[UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; }
public MetaProjectFileType()
: base(Name, "Unity Meta File", new[] { UnityFileExtensions.MetaFileExtensionWithDot })
{
}
}
}
|
using JetBrains.Annotations;
using JetBrains.ProjectModel;
using JetBrains.ReSharper.Plugins.Unity.UnityEditorIntegration;
using JetBrains.ReSharper.Plugins.Yaml.ProjectModel;
#nullable enable
namespace JetBrains.ReSharper.Plugins.Unity.Yaml.ProjectModel
{
[ProjectFileTypeDefinition(Name)]
public class MetaProjectFileType : YamlProjectFileType
{
public new const string Name = "Meta";
[UsedImplicitly] public new static MetaProjectFileType? Instance { get; private set; }
public MetaProjectFileType()
: base(Name, "Unity Yaml", new[] { UnityFileExtensions.MetaFileExtensionWithDot })
{
}
}
}
|
apache-2.0
|
C#
|
258a19fdf5b1ff6ced2ca2e59c0ddc8fd217ca0c
|
Make CSP more specific for docs
|
btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver,btcpayserver/btcpayserver
|
BTCPayServer/Views/Home/SwaggerDocs.cshtml
|
BTCPayServer/Views/Home/SwaggerDocs.cshtml
|
@inject BTCPayServer.Security.ContentSecurityPolicies csp
@{
Layout = null;
csp.Add("script-src", "https://cdn.jsdelivr.net");
csp.Add("worker-src", "blob: self");
}
<!DOCTYPE html>
<html>
<head>
<title>BTCPay Server Greenfield API</title>
<!-- needed for adaptive design -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true">
<link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
@*Ignore this, this is for making the test ClickOnAllSideMenus happy*@
<div class="navbar-brand" style="visibility:collapse;"></div>
<redoc spec-url="@Url.ActionLink("Swagger")"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script>
</body>
</html>
|
@inject BTCPayServer.Security.ContentSecurityPolicies csp
@{
Layout = null;
csp.Add("script-src", "https://cdn.jsdelivr.net");
csp.Add("worker-src", "blob:");
}
<!DOCTYPE html>
<html>
<head>
<title>BTCPay Server Greenfield API</title>
<!-- needed for adaptive design -->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="~/main/fonts/Roboto.css" rel="stylesheet" asp-append-version="true">
<link href="~/main/fonts/Montserrat.css" rel="stylesheet" asp-append-version="true">
<!--
ReDoc doesn't change outer page styles
-->
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
@*Ignore this, this is for making the test ClickOnAllSideMenus happy*@
<div class="navbar-brand" style="visibility:collapse;"></div>
<redoc spec-url="@Url.ActionLink("Swagger")"></redoc>
<script src="https://cdn.jsdelivr.net/npm/redoc@2.0.0-rc.45/bundles/redoc.standalone.js" integrity="sha384-RC31+q3tyqdcilXYaU++ii/FAByqeZ+sjKUHMJ8hMzIY5k4kzNqi4Ett88EZ/4lq" crossorigin="anonymous"></script>
</body>
</html>
|
mit
|
C#
|
ccbced0824fad5e888f65c6b00d5301f9d296e05
|
Fix up versions in AssemblyInfoStatic
|
tmds/Tmds.DBus
|
AssemblyInfoStatic.cs
|
AssemblyInfoStatic.cs
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
// This AssemblyInfo file is used in builds that aren't driven by autoconf, eg. Visual Studio
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyFileVersion("0.7.0")]
[assembly: AssemblyInformationalVersion("0.7.0")]
[assembly: AssemblyVersion("1.0")]
[assembly: AssemblyTitle ("dbus-sharp")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker and others")]
#if STRONG_NAME
[assembly: InternalsVisibleTo ("dbus-sharp-tests, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-daemon, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
#else
[assembly: InternalsVisibleTo ("dbus-sharp-tests")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies")]
#endif
|
// Copyright 2006 Alp Toker <alp@atoker.com>
// This software is made available under the MIT License
// See COPYING for details
// This AssemblyInfo file is used in builds that aren't driven by autoconf, eg. Visual Studio
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyFileVersion("@VERSION@")]
[assembly: AssemblyInformationalVersion("@VERSION@")]
[assembly: AssemblyVersion("@API_VERSION@")]
[assembly: AssemblyTitle ("dbus-sharp")]
[assembly: AssemblyDescription ("D-Bus IPC protocol library and CLR binding")]
[assembly: AssemblyCopyright ("Copyright (C) Alp Toker and others")]
#if STRONG_NAME
[assembly: InternalsVisibleTo ("dbus-sharp-tests, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-monitor, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-daemon, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies, PublicKey=0024000004800000440000000602000000240000525341318001000011000000ffbfaa640454654de78297fde2d22dd4bc4b0476fa892c3f8575ad4f048ce0721ce4109f542936083bc4dd83be5f7f97")]
#else
[assembly: InternalsVisibleTo ("dbus-sharp-tests")]
[assembly: InternalsVisibleTo ("dbus-monitor")]
[assembly: InternalsVisibleTo ("dbus-daemon")]
[assembly: InternalsVisibleTo ("dbus-sharp-glib")]
[assembly: InternalsVisibleTo ("dbus-sharp-proxies")]
#endif
|
mit
|
C#
|
1bea5466a81b3a32513949a7007920be39f59ecf
|
bump version
|
JakeGinnivan/GitVersion,distantcam/GitVersion,dpurge/GitVersion,pascalberger/GitVersion,GeertvanHorrik/GitVersion,orjan/GitVersion,ParticularLabs/GitVersion,DanielRose/GitVersion,dpurge/GitVersion,Philo/GitVersion,dazinator/GitVersion,anobleperson/GitVersion,TomGillen/GitVersion,asbjornu/GitVersion,openkas/GitVersion,JakeGinnivan/GitVersion,Kantis/GitVersion,GitTools/GitVersion,gep13/GitVersion,Kantis/GitVersion,ermshiperete/GitVersion,MarkZuber/GitVersion,ermshiperete/GitVersion,asbjornu/GitVersion,ermshiperete/GitVersion,DanielRose/GitVersion,FireHost/GitVersion,TomGillen/GitVersion,orjan/GitVersion,Philo/GitVersion,DanielRose/GitVersion,alexhardwicke/GitVersion,dpurge/GitVersion,anobleperson/GitVersion,ParticularLabs/GitVersion,pascalberger/GitVersion,MarkZuber/GitVersion,distantcam/GitVersion,dpurge/GitVersion,gep13/GitVersion,pascalberger/GitVersion,onovotny/GitVersion,dazinator/GitVersion,GeertvanHorrik/GitVersion,alexhardwicke/GitVersion,JakeGinnivan/GitVersion,onovotny/GitVersion,RaphHaddad/GitVersion,RaphHaddad/GitVersion,JakeGinnivan/GitVersion,FireHost/GitVersion,openkas/GitVersion,GitTools/GitVersion,onovotny/GitVersion,ermshiperete/GitVersion,anobleperson/GitVersion,Kantis/GitVersion
|
CommonAssemblyInfo.cs
|
CommonAssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("GitFlowVersion")]
[assembly: AssemblyProduct("GitFlowVersion")]
[assembly: AssemblyVersion("0.14.0")]
[assembly: AssemblyFileVersion("0.14.0")]
[assembly: InternalsVisibleTo("Tests")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyTitle("GitFlowVersion")]
[assembly: AssemblyProduct("GitFlowVersion")]
[assembly: AssemblyVersion("0.13.0")]
[assembly: AssemblyFileVersion("0.13.0")]
[assembly: InternalsVisibleTo("Tests")]
|
mit
|
C#
|
42bf4764d8ffcd3d67a838d3b97fceebf93fa681
|
Fix escaping
|
Microsoft/VisualStudio-TestHost,zooba/VisualStudio-TestHost
|
VSTestHost/Properties/AssemblyInfo.cs
|
VSTestHost/Properties/AssemblyInfo.cs
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
// 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("VS Test Host")]
[assembly: AssemblyDescription("Test host adapter for Visual Studio UI tests.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("VS Test Host")]
[assembly: AssemblyCopyright("(c) Microsoft Corporation")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion(AssemblyVersionInfo.VSVersion + ".0.5.0")]
[assembly: AssemblyFileVersion(AssemblyVersionInfo.VSVersion + ".0.5.0")]
[assembly: ProvideCodeBase(
AssemblyName = "Microsoft.VisualStudioTools.VSTestHost." + AssemblyVersionInfo.VSVersion + ".0",
CodeBase = "..\\..\\PublicAssemblies\\Microsoft.VisualStudioTools.VSTestHost." + AssemblyVersionInfo.VSVersion + ".0.dll",
Version = AssemblyVersionInfo.VSVersion + ".0.5.0"
)]
class AssemblyVersionInfo {
#if DEV10
public const string VSVersion = "10";
#elif DEV11
public const string VSVersion = "11";
#elif DEV12
public const string VSVersion = "12";
#elif DEV14
public const string VSVersion = "14";
#elif DEV15
public const string VSVersion = "15";
#else
#error Unrecognized VS version
#endif
}
|
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* vspython@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
using System;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.Shell;
// 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("VS Test Host")]
[assembly: AssemblyDescription("Test host adapter for Visual Studio UI tests.")]
[assembly: AssemblyCompany("Microsoft Corporation")]
[assembly: AssemblyProduct("VS Test Host")]
[assembly: AssemblyCopyright("(c) Microsoft Corporation")]
[assembly: ComVisible(false)]
[assembly: CLSCompliant(false)]
[assembly: NeutralResourcesLanguage("en-US")]
[assembly: AssemblyVersion(AssemblyVersionInfo.VSVersion + ".0.5.0")]
[assembly: AssemblyFileVersion(AssemblyVersionInfo.VSVersion + ".0.5.0")]
[assembly: ProvideCodeBase(
AssemblyName = "Microsoft.VisualStudioTools.VSTestHost." + AssemblyVersionInfo.VSVersion + ".0",
CodeBase = "..\..\PublicAssemblies\Microsoft.VisualStudioTools.VSTestHost." + AssemblyVersionInfo.VSVersion + ".0.dll",
Version = AssemblyVersionInfo.VSVersion + ".0.5.0"
)]
class AssemblyVersionInfo {
#if DEV10
public const string VSVersion = "10";
#elif DEV11
public const string VSVersion = "11";
#elif DEV12
public const string VSVersion = "12";
#elif DEV14
public const string VSVersion = "14";
#elif DEV15
public const string VSVersion = "15";
#else
#error Unrecognized VS version
#endif
}
|
apache-2.0
|
C#
|
94bc8b00a77242f721adf6918ac1a9e26433ab78
|
update DecodeEntityBase
|
lishewen/WeiXinMPSDK,wanddy/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,lishewen/WeiXinMPSDK,jiehanlin/WeiXinMPSDK,down4u/WeiXinMPSDK,down4u/WeiXinMPSDK,mc7246/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,wanddy/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,JeffreySu/WeiXinMPSDK,mc7246/WeiXinMPSDK,mc7246/WeiXinMPSDK
|
src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Entities/Watermark.cs
|
src/Senparc.Weixin.WxOpen/src/Senparc.Weixin.WxOpen/Senparc.Weixin.WxOpen/Entities/Watermark.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.Helpers;
namespace Senparc.Weixin.WxOpen.Entities
{
public class DecodeEntityBase
{
public Watermark watermark { get; set; }
}
public class Watermark
{
public string appid { get; set; }
public long timestamp { get; set; }
public DateTime TimeStamp
{
get { return DateTimeHelper.GetDateTimeFromXml(timestamp); }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Senparc.Weixin.WxOpen.Entities
{
public class DecodeEntityBase
{
public Watermark watermark { get; set; }
}
public class Watermark
{
public string appid { get; set; }
public string timestamp { get; set; }
}
}
|
apache-2.0
|
C#
|
9cb667183a5e1dced497e6571a72c35f95816c3c
|
Create damage value field
|
bartlomiejwolk/Health
|
DamageComponent/Damage.cs
|
DamageComponent/Damage.cs
|
using UnityEngine;
using System.Collections;
using HealthEx.HealthComponent;
namespace HealthEx.DamageComponent {
public sealed class Damage : MonoBehaviour {
#region CONSTANTS
public const string Version = "v0.1.0";
public const string Extension = "Health";
#endregion
#region DELEGATES
#endregion
#region EVENTS
#endregion
#region FIELDS
#pragma warning disable 0414
/// <summary>
/// Allows identify component in the scene file when reading it with
/// text editor.
/// </summary>
[SerializeField]
private string componentName = "Damage";
#pragma warning restore0414
#endregion
#region INSPECTOR FIELDS
[SerializeField]
private string description = "Description";
/// <summary>
/// Damage to be applied to the <c>Health</c> component.
/// </summary>
[SerializeField]
private int damageValue;
#endregion
#region PROPERTIES
/// <summary>
/// Optional text to describe purpose of this instance of the component.
/// </summary>
public string Description {
get { return description; }
set { description = value; }
}
/// <summary>
/// Damage to be applied to the <c>Health</c> component.
/// </summary>
public int DamageValue {
get { return damageValue; }
set { damageValue = value; }
}
#endregion
#region UNITY MESSAGES
private void Awake() { }
private void FixedUpdate() { }
private void LateUpdate() { }
private void OnEnable() { }
private void Reset() { }
private void Start() { }
private void Update() { }
private void OnValidate() { }
// todo filter by tag and layer
private void OnCollisionEnter(Collision collision) {
var healthComponent = collision.gameObject.GetComponent<Health>();
if (healthComponent == null) return;
// Apply damage.
healthComponent.HealthValue -= DamageValue;
}
private void OnCollisionStay(Collision collision) { }
private void OnCollisionExit(Collision collision) { }
#endregion
#region EVENT INVOCATORS
#endregion
#region EVENT HANDLERS
#endregion
#region METHODS
#endregion
}
}
|
using UnityEngine;
using System.Collections;
namespace HealthEx.DamageComponent {
public sealed class Damage : MonoBehaviour {
#region CONSTANTS
public const string Version = "v0.1.0";
public const string Extension = "Health";
#endregion
#region DELEGATES
#endregion
#region EVENTS
#endregion
#region FIELDS
#pragma warning disable 0414
/// <summary>
/// Allows identify component in the scene file when reading it with
/// text editor.
/// </summary>
[SerializeField]
private string componentName = "Damage";
#pragma warning restore0414
#endregion
#region INSPECTOR FIELDS
[SerializeField]
private string description = "Description";
#endregion
#region PROPERTIES
/// <summary>
/// Optional text to describe purpose of this instance of the component.
/// </summary>
public string Description {
get { return description; }
set { description = value; }
}
#endregion
#region UNITY MESSAGES
private void Awake() { }
private void FixedUpdate() { }
private void LateUpdate() { }
private void OnEnable() { }
private void Reset() { }
private void Start() { }
private void Update() { }
private void OnValidate() { }
#endregion
#region EVENT INVOCATORS
#endregion
#region EVENT HANDLERS
#endregion
#region METHODS
#endregion
}
}
|
mit
|
C#
|
6ca099ff17bb6734de780021a7c1c507341e2ac9
|
Fix a typo in a view
|
adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats,adrianbanks/BroadbandSpeedStats
|
Database.Migrations/Migrations/2-TodaysTestResultsView.cs
|
Database.Migrations/Migrations/2-TodaysTestResultsView.cs
|
using BroadbandSpeedStats.Database.Schema;
using FluentMigrator;
namespace BroadbandSpeedTests.Database.Migrations.Migrations
{
[Migration(20170228)]
public class TodaysTestResultsView : Migration
{
public override void Up()
{
Execute.Sql($@"
CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS
SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}],
[{Views.TodaysTestResults.Columns.Timestamp}],
[{Views.TodaysTestResults.Columns.PingTime}],
[{Views.TodaysTestResults.Columns.DownloadSpeed}],
[{Views.TodaysTestResults.Columns.UploadSpeed}]
FROM [dbo].[{Views.TodaysTestResults.SourceTable}]
WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0
ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC
GO");
}
public override void Down()
{
Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]");
}
}
}
|
using BroadbandSpeedStats.Database.Schema;
using FluentMigrator;
namespace BroadbandSpeedTests.Database.Migrations.Migrations
{
[Migration(20170228)]
public class TodaysTestResultsView : Migration
{
public override void Up()
{
Execute.Sql($@"
CREATE VIEW [{Views.TodaysTestResults.Name}] WITH SCHEMABINDING AS
SELECT TOP 100 PERCENT [{Views.TodaysTestResults.Columns.Id}],
[{Views.TodaysTestResults.Columns.Timestamp}],
[{Views.TodaysTestResults.Columns.PingTime}],
[{Views.TodaysTestResults.Columns.DownloadSpeed}],
[{Views.TodaysTestResults.Columns.UploadSpeed}]
FROM [dbo].[{Views.TodaysTestResults.SourceTable}]
WHERE WHERE DATEDIFF(d, {Views.TodaysTestResults.Columns.Timestamp}, GETUTCDATE()) = 0
ORDER BY [{Views.TodaysTestResults.Columns.Timestamp}] DESC
GO");
}
public override void Down()
{
Execute.Sql($"DROP VIEW [{Views.TodaysTestResults.Name}]");
}
}
}
|
mit
|
C#
|
4bbcfdbe8a8e9d19cc7966e5abf93d151f6f65e7
|
Fix of substring bug
|
ErikEJ/EntityFramework7.SqlServerCompact,ErikEJ/EntityFramework.SqlServerCompact
|
src/Provider40/Query/ExpressionTranslators/Internal/SqlCeStringSubstringTranslator.cs
|
src/Provider40/Query/ExpressionTranslators/Internal/SqlCeStringSubstringTranslator.cs
|
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Data.Entity.Query.Expressions;
namespace Microsoft.Data.Entity.Query.ExpressionTranslators.Internal
{
public class SqlCeStringSubstringTranslator : IMethodCallTranslator
{
private static readonly MethodInfo _methodInfo = typeof(string).GetTypeInfo()
.GetDeclaredMethods(nameof(string.Substring))
.Single(m => m.GetParameters().Count() == 2);
public virtual Expression Translate(MethodCallExpression methodCallExpression)
=> methodCallExpression.Method == _methodInfo
? new SqlFunctionExpression(
"SUBSTRING",
methodCallExpression.Type,
new[] {
methodCallExpression.Object,
// Accomodate for SQL Server Compact assumption of 1-based string indexes
methodCallExpression.Arguments[0].NodeType == ExpressionType.Constant
? (Expression)Expression.Constant(
(int)((ConstantExpression) methodCallExpression.Arguments[0]).Value + 1)
: Expression.Add(
methodCallExpression.Arguments[0],
Expression.Constant(1)),
methodCallExpression.Arguments[1] })
: null;
}
}
|
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using Microsoft.Data.Entity.Query.Expressions;
namespace Microsoft.Data.Entity.Query.ExpressionTranslators.Internal
{
public class SqlCeStringSubstringTranslator : IMethodCallTranslator
{
private static readonly MethodInfo _methodInfo = typeof(string).GetTypeInfo()
.GetDeclaredMethods(nameof(string.Substring))
.Single(m => m.GetParameters().Count() == 2);
public virtual Expression Translate(MethodCallExpression methodCallExpression)
=> methodCallExpression.Method == _methodInfo
? new SqlFunctionExpression(
"SUBSTRING",
methodCallExpression.Type,
new[] { methodCallExpression.Object }.Concat(methodCallExpression.Arguments))
: null;
}
}
|
apache-2.0
|
C#
|
44e354d680b7e316561f26aa86aa1e87860dffcf
|
Remove useless default constructor from SortDeclarationsPass.
|
SonyaSa/CppSharp,imazen/CppSharp,mydogisbox/CppSharp,nalkaro/CppSharp,mono/CppSharp,imazen/CppSharp,Samana/CppSharp,ktopouzi/CppSharp,nalkaro/CppSharp,imazen/CppSharp,ddobrev/CppSharp,Samana/CppSharp,ddobrev/CppSharp,xistoso/CppSharp,ktopouzi/CppSharp,imazen/CppSharp,mohtamohit/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,KonajuGames/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,KonajuGames/CppSharp,txdv/CppSharp,genuinelucifer/CppSharp,Samana/CppSharp,mydogisbox/CppSharp,ktopouzi/CppSharp,KonajuGames/CppSharp,mono/CppSharp,u255436/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,mohtamohit/CppSharp,txdv/CppSharp,ktopouzi/CppSharp,ktopouzi/CppSharp,txdv/CppSharp,txdv/CppSharp,inordertotest/CppSharp,xistoso/CppSharp,Samana/CppSharp,inordertotest/CppSharp,u255436/CppSharp,mono/CppSharp,mydogisbox/CppSharp,KonajuGames/CppSharp,SonyaSa/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,genuinelucifer/CppSharp,mono/CppSharp,ddobrev/CppSharp,mydogisbox/CppSharp,SonyaSa/CppSharp,imazen/CppSharp,mono/CppSharp,zillemarco/CppSharp,nalkaro/CppSharp,inordertotest/CppSharp,txdv/CppSharp,mydogisbox/CppSharp,genuinelucifer/CppSharp,genuinelucifer/CppSharp,KonajuGames/CppSharp,zillemarco/CppSharp,mono/CppSharp,SonyaSa/CppSharp,zillemarco/CppSharp,xistoso/CppSharp,ddobrev/CppSharp,mohtamohit/CppSharp,Samana/CppSharp,zillemarco/CppSharp,zillemarco/CppSharp,genuinelucifer/CppSharp,SonyaSa/CppSharp,u255436/CppSharp,mohtamohit/CppSharp,u255436/CppSharp,xistoso/CppSharp
|
src/Generator/Passes/SortDeclarationsPass.cs
|
src/Generator/Passes/SortDeclarationsPass.cs
|
using CppSharp.AST;
using CppSharp.Types;
namespace CppSharp.Passes
{
class SortDeclarationsPass : TranslationUnitPass
{
private static void SortDeclarations(Namespace @namespace)
{
@namespace.Classes.Sort((c, c1) =>
(int)(c.DefinitionOrder - c1.DefinitionOrder));
foreach (var childNamespace in @namespace.Namespaces)
SortDeclarations(childNamespace);
}
public override bool VisitTranslationUnit(TranslationUnit unit)
{
SortDeclarations(unit);
return true;
}
}
}
|
using CppSharp.AST;
using CppSharp.Types;
namespace CppSharp.Passes
{
class SortDeclarationsPass : TranslationUnitPass
{
public SortDeclarationsPass()
{
}
private static void SortDeclarations(Namespace @namespace)
{
@namespace.Classes.Sort((c, c1) =>
(int)(c.DefinitionOrder - c1.DefinitionOrder));
foreach (var childNamespace in @namespace.Namespaces)
SortDeclarations(childNamespace);
}
public override bool VisitTranslationUnit(TranslationUnit unit)
{
SortDeclarations(unit);
return true;
}
}
}
|
mit
|
C#
|
5a829b698f1d817d73bdde534745099a8129c049
|
implement settings storage/retrieval for ChargeUtils
|
innerfence/chargedemo-windows
|
InnerFence.ChargeDemo.Phone/ChargeAPI/ChargeUtilsPhone.cs
|
InnerFence.ChargeDemo.Phone/ChargeAPI/ChargeUtilsPhone.cs
|
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InnerFence.ChargeAPI
{
public static partial class ChargeUtils
{
public static void DeleteLocalData(string key)
{
IsolatedStorageSettings.ApplicationSettings.Remove(key);
}
public static object RetrieveLocalData(string key)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains(key))
{
return IsolatedStorageSettings.ApplicationSettings[key];
}
return null;
}
public static void SaveLocalData(string key, object value)
{
IsolatedStorageSettings.ApplicationSettings[key] = value;
IsolatedStorageSettings.ApplicationSettings.Save();
}
public static void SubmitChargeRequest(ChargeRequest chargeRequest)
{
throw new NotImplementedException();
}
public static uint GenerateRandomNumber()
{
throw new NotImplementedException();
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InnerFence.ChargeAPI
{
public static partial class ChargeUtils
{
public static void DeleteLocalData(string key)
{
throw new NotImplementedException();
}
public static object RetrieveLocalData(string key)
{
throw new NotImplementedException();
}
public static void SaveLocalData(string key, object value)
{
throw new NotImplementedException();
}
public static void SubmitChargeRequest(ChargeRequest chargeRequest)
{
throw new NotImplementedException();
}
public static uint GenerateRandomNumber()
{
throw new NotImplementedException();
}
}
}
|
mit
|
C#
|
40dc833aa66bfa9d5234bd92bd9140e6f30d6c06
|
Improve logic for retrieving enum value description.
|
Saritasa/SaritasaTools,krasninja/SaritasaTools,krasninja/SaritasaTools
|
src/Saritasa.Tools.Common/Utils/EnumUtils.cs
|
src/Saritasa.Tools.Common/Utils/EnumUtils.cs
|
// Copyright (c) 2015-2017, Saritasa. All rights reserved.
// Licensed under the BSD license. See LICENSE file in the project root for full license information.
using System;
#if NET40 || NET452 || NET461
using System.Collections.Generic;
using System.ComponentModel;
#endif
using System.Linq;
using System.Reflection;
namespace Saritasa.Tools.Common.Utils
{
/// <summary>
/// Enum utils.
/// </summary>
public static class EnumUtils
{
#if NET40 || NET452 || NET461
/// <summary>
/// Gets the value of Description attribute.
/// </summary>
/// <param name="target">Enum.</param>
/// <returns>Description text.</returns>
public static string GetDescription(Enum target)
{
var descAttribute = GetAttribute<DescriptionAttribute>(target);
if (descAttribute == null)
{
return target.ToString();
}
return descAttribute.Description;
}
#endif
/// <summary>
/// Gets the custom attribute of enum value.
/// </summary>
/// <param name="target">Enum.</param>
/// <typeparam name="TAttribute">Attribute type.</typeparam>
/// <returns>Attribute or null if not found.</returns>
public static TAttribute GetAttribute<TAttribute>(Enum target)
where TAttribute : Attribute
{
#if NET40 || NET452 || NET461
if (!target.GetType().IsEnum)
{
throw new ArgumentOutOfRangeException(nameof(target), Properties.Strings.ArgumentMustBeEnum);
}
#endif
#if NET40 || NET452 || NET461
FieldInfo fieldInfo = target.GetType().GetField(target.ToString());
#else
FieldInfo fieldInfo = target.GetType().GetTypeInfo().GetDeclaredField(target.ToString());
#endif
if (fieldInfo == null)
{
return null;
}
#if NETSTANDARD1_2
var attributes = fieldInfo.GetCustomAttributes<TAttribute>(false);
#else
var attributes =
(IEnumerable<TAttribute>)fieldInfo.GetCustomAttributes(typeof(TAttribute), false);
#endif
return attributes.FirstOrDefault();
}
}
}
|
// Copyright (c) 2015-2017, Saritasa. All rights reserved.
// Licensed under the BSD license. See LICENSE file in the project root for full license information.
using System;
#if NET40 || NET452 || NET461
using System.Collections.Generic;
using System.ComponentModel;
#endif
using System.Linq;
using System.Reflection;
namespace Saritasa.Tools.Common.Utils
{
/// <summary>
/// Enum utils.
/// </summary>
public static class EnumUtils
{
#if NET40 || NET452 || NET461
/// <summary>
/// Gets the value of Description attribute.
/// </summary>
/// <param name="target">Enum.</param>
/// <returns>Description text.</returns>
public static string GetDescription(Enum target)
{
var descAttribute = GetAttribute<DescriptionAttribute>(target);
return descAttribute?.Description;
}
#endif
/// <summary>
/// Gets the custom attribute of enum value.
/// </summary>
/// <param name="target">Enum.</param>
/// <typeparam name="TAttribute">Attribute type.</typeparam>
/// <returns>Attribute or null if not found.</returns>
public static TAttribute GetAttribute<TAttribute>(Enum target)
where TAttribute : Attribute
{
#if NET40 || NET452 || NET461
if (!target.GetType().IsEnum)
{
throw new ArgumentOutOfRangeException(nameof(target), Properties.Strings.ArgumentMustBeEnum);
}
#endif
#if NET40 || NET452 || NET461
FieldInfo fieldInfo = target.GetType().GetField(target.ToString());
#else
FieldInfo fieldInfo = target.GetType().GetTypeInfo().GetDeclaredField(target.ToString());
#endif
if (fieldInfo == null)
{
return null;
}
#if NETSTANDARD1_2
var attributes = fieldInfo.GetCustomAttributes<TAttribute>(false);
#else
var attributes =
(IEnumerable<TAttribute>)fieldInfo.GetCustomAttributes(typeof(TAttribute), false);
#endif
return attributes.FirstOrDefault();
}
}
}
|
bsd-2-clause
|
C#
|
becb65f702c2c1ed33ec963983d2f9969083fdf6
|
Fix ParallaxContainer breaking with no mouse state present.
|
naoey/osu,ppy/osu,theguii/osu,RedNesto/osu,EVAST9919/osu,DrabWeb/osu,peppy/osu,Frontear/osuKyzer,NotKyon/lolisu,johnneijzen/osu,Damnae/osu,UselessToucan/osu,EVAST9919/osu,smoogipoo/osu,Drezi126/osu,NeoAdonis/osu,osu-RP/osu-RP,2yangk23/osu,smoogipoo/osu,tacchinotacchi/osu,DrabWeb/osu,ppy/osu,naoey/osu,default0/osu,Nabile-Rahmani/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu,NeoAdonis/osu,DrabWeb/osu,peppy/osu-new,UselessToucan/osu,peppy/osu,ZLima12/osu,smoogipooo/osu,NeoAdonis/osu,naoey/osu,2yangk23/osu,nyaamara/osu,peppy/osu,ZLima12/osu,UselessToucan/osu
|
osu.Game/Graphics/Containers/ParallaxContainer.cs
|
osu.Game/Graphics/Containers/ParallaxContainer.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 osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Framework.Input;
using OpenTK;
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Transformations;
namespace osu.Game.Graphics.Containers
{
class ParallaxContainer : Container
{
public float ParallaxAmount = 0.02f;
public override bool Contains(Vector2 screenSpacePos) => true;
public ParallaxContainer()
{
RelativeSizeAxes = Axes.Both;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
private Container content;
private InputManager input;
protected override Container<Drawable> Content => content;
[BackgroundDependencyLoader]
private void load(UserInputManager input)
{
this.input = input;
}
bool firstUpdate = true;
protected override void Update()
{
base.Update();
Vector2 offset = input.CurrentState.Mouse == null ? Vector2.Zero : ToLocalSpace(input.CurrentState.Mouse.NativeState.Position) - DrawSize / 2;
content.MoveTo(offset * ParallaxAmount, firstUpdate ? 0 : 1000, EasingTypes.OutQuint);
content.Scale = new Vector2(1 + ParallaxAmount);
firstUpdate = false;
}
}
}
|
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics;
using osu.Framework.Input;
using OpenTK;
using osu.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics.Transformations;
namespace osu.Game.Graphics.Containers
{
class ParallaxContainer : Container
{
public float ParallaxAmount = 0.02f;
public override bool Contains(Vector2 screenSpacePos) => true;
public ParallaxContainer()
{
RelativeSizeAxes = Axes.Both;
AddInternal(content = new Container
{
RelativeSizeAxes = Axes.Both,
Anchor = Anchor.Centre,
Origin = Anchor.Centre
});
}
private Container content;
private InputManager input;
protected override Container<Drawable> Content => content;
[BackgroundDependencyLoader]
private void load(UserInputManager input)
{
this.input = input;
}
bool firstUpdate = true;
protected override void Update()
{
base.Update();
content.MoveTo((ToLocalSpace(input.CurrentState.Mouse.NativeState.Position) - DrawSize / 2) * ParallaxAmount, firstUpdate ? 0 : 1000, EasingTypes.OutQuint);
content.Scale = new Vector2(1 + ParallaxAmount);
firstUpdate = false;
}
}
}
|
mit
|
C#
|
a4d4efc312317f2a51e5a5624ee4901b582dc403
|
Fix missing comments
|
smoogipoo/osu,2yangk23/osu,smoogipooo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,peppy/osu,NeoAdonis/osu,johnneijzen/osu,EVAST9919/osu,smoogipoo/osu,ppy/osu,EVAST9919/osu,UselessToucan/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,2yangk23/osu,UselessToucan/osu,UselessToucan/osu,smoogipoo/osu,johnneijzen/osu,ppy/osu
|
osu.Game/Rulesets/Mods/IApplicableToDifficulty.cs
|
osu.Game/Rulesets/Mods/IApplicableToDifficulty.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.Game.Beatmaps;
namespace osu.Game.Rulesets.Mods
{
/// <summary>
/// An interface for mods that make general adjustments to difficulty.
/// </summary>
public interface IApplicableToDifficulty : IApplicableMod
{
/// <summary>
/// Called when a beatmap is changed. Can be used to read default values.
/// Any changes made will not be preserved.
/// </summary>
/// <param name="difficulty">The difficulty to read from.</param>
void ReadFromDifficulty(BeatmapDifficulty difficulty);
/// <summary>
/// Called post beatmap conversion. Can be used to apply changes to difficulty attributes.
/// </summary>
/// <param name="difficulty">The difficulty to mutate.</param>
void ApplyToDifficulty(BeatmapDifficulty difficulty);
}
}
|
// 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.Game.Beatmaps;
namespace osu.Game.Rulesets.Mods
{
/// <summary>
/// An interface for mods that make general adjustments to difficulty.
/// </summary>
public interface IApplicableToDifficulty : IApplicableMod
{
/// <summary>
/// Called when a beatmap is changed. Can be used to read default values.
/// Any changes made will not be preserved.
/// </summary>
/// <param name="difficulty"></param>
void ReadFromDifficulty(BeatmapDifficulty difficulty);
/// <summary>
/// Called post beatmap conversion. Can be used to apply changes to difficulty attributes.
/// </summary>
/// <param name="difficulty"></param>
void ApplyToDifficulty(BeatmapDifficulty difficulty);
}
}
|
mit
|
C#
|
e86834b74060d5fc7e2e9314142316b74ccf821b
|
Use local bound copy for `HiddenIssueTypes`
|
smoogipoo/osu,peppy/osu,peppy/osu,ppy/osu,peppy/osu-new,NeoAdonis/osu,UselessToucan/osu,UselessToucan/osu,ppy/osu,smoogipooo/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,smoogipoo/osu,smoogipoo/osu,ppy/osu,NeoAdonis/osu
|
osu.Game/Screens/Edit/Verify/VisibilitySection.cs
|
osu.Game/Screens/Edit/Verify/VisibilitySection.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
internal class VisibilitySection : EditorRoundedScreenSettingsSection
{
[Resolved]
private VerifyScreen verify { get; set; }
private readonly IssueType[] configurableIssueTypes =
{
IssueType.Warning,
IssueType.Error,
IssueType.Negligible
};
protected override string Header => "Visibility";
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colours)
{
var hiddenIssueTypes = verify.HiddenIssueTypes.GetBoundCopy();
foreach (IssueType issueType in configurableIssueTypes)
{
var checkbox = new SettingsCheckbox
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
LabelText = issueType.ToString()
};
checkbox.Current.Default = !hiddenIssueTypes.Contains(issueType);
checkbox.Current.SetDefault();
checkbox.Current.BindValueChanged(state =>
{
if (!state.NewValue)
hiddenIssueTypes.Add(issueType);
else
hiddenIssueTypes.Remove(issueType);
});
Flow.Add(checkbox);
}
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Game.Overlays.Settings;
using osu.Game.Rulesets.Edit.Checks.Components;
namespace osu.Game.Screens.Edit.Verify
{
internal class VisibilitySection : EditorRoundedScreenSettingsSection
{
[Resolved]
private VerifyScreen verify { get; set; }
private readonly IssueType[] configurableIssueTypes =
{
IssueType.Warning,
IssueType.Error,
IssueType.Negligible
};
protected override string Header => "Visibility";
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colours)
{
foreach (IssueType issueType in configurableIssueTypes)
{
var checkbox = new SettingsCheckbox
{
Anchor = Anchor.CentreLeft,
Origin = Anchor.CentreLeft,
LabelText = issueType.ToString()
};
checkbox.Current.Default = !verify.HiddenIssueTypes.Contains(issueType);
checkbox.Current.SetDefault();
checkbox.Current.BindValueChanged(state =>
{
if (!state.NewValue)
verify.HiddenIssueTypes.Add(issueType);
else
verify.HiddenIssueTypes.Remove(issueType);
});
Flow.Add(checkbox);
}
}
}
}
|
mit
|
C#
|
c15b3d01b7086b43ffa5a8772330a85b4d8266dd
|
Update HttpStringDecodeFilter.cs
|
CypressNorth/.NET-WebApi-HttpStringDecodeFilter
|
HttpStringDecodeFilter.cs
|
HttpStringDecodeFilter.cs
|
using System;
using System.Net;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace CN.WebApi.Filters
{
public class HttpStringDecodeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
// If the request is either a PUT or POST, attempt to decode all strings
if (actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Post
|| actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Put)
{
// For each of the items in the PUT/POST
foreach (var item in actionContext.ActionArguments.Values)
{
try {
// Get the type of the object
Type type = item.GetType();
// For each property of this object, html decode it if it is of type string
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
var prop = propertyInfo.GetValue(item);
if (prop != null && prop.GetType() == typeof(string))
{
propertyInfo.SetValue(item, WebUtility.HtmlDecode((string)prop));
}
}
} catch {}
}
}
}
}
}
|
using System;
using System.Net;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
namespace CN.WebApi.Filters
{
public class DecodeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
// If the request is either a PUT or POST, attempt to decode all strings
if (actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Post
|| actionContext.Request.Method.ToString() == System.Net.WebRequestMethods.Http.Put)
{
// For each of the items in the PUT/POST
foreach (var item in actionContext.ActionArguments.Values)
{
try {
// Get the type of the object
Type type = item.GetType();
// For each property of this object, html decode it if it is of type string
foreach (PropertyInfo propertyInfo in type.GetProperties())
{
var prop = propertyInfo.GetValue(item);
if (prop != null && prop.GetType() == typeof(string))
{
propertyInfo.SetValue(item, WebUtility.HtmlDecode((string)prop));
}
}
} catch {}
}
}
}
}
}
|
mit
|
C#
|
ce0b590ca80cf2108bc3203347473568fe01a23d
|
Change namespace
|
occar421/MyAnalyzerSamples
|
PublicFieldAnalyzer/PublicFieldAnalyzer/PublicFieldAnalyzer/PublicFieldAnalyzer.cs
|
PublicFieldAnalyzer/PublicFieldAnalyzer/PublicFieldAnalyzer/PublicFieldAnalyzer.cs
|
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace PublicFieldAnalyzer
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
class PublicFieldAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "PublicField";
private static readonly string Title = "Public field sucks.";
private static readonly string MessageFormat = "{0} {1} public field.";
private static readonly string Description = "Using public field is usually bad implemention.";
private const string Category = "PublicField.CSharp.Suggestion";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.FieldDeclaration);
}
private static void Analyze(SyntaxNodeAnalysisContext context)
{
var field = (FieldDeclarationSyntax)context.Node;
if (field.Modifiers.Any(SyntaxKind.PublicKeyword) && !field.Modifiers.Any(SyntaxKind.ConstKeyword))
{
var fieldNameTokens = field.Declaration.Variables.Select(x => x.Identifier);
var diagnostic = Diagnostic.Create(Rule, field.GetLocation(), string.Join(", ", fieldNameTokens.Select(x => $"\"{x}\"")), fieldNameTokens.Skip(1).Any() ? "are" : "is");
context.ReportDiagnostic(diagnostic);
}
}
}
}
|
using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
namespace AnalyzerTests
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
class PublicFieldAnalyzer : DiagnosticAnalyzer
{
public const string DiagnosticId = "PublicField";
private static readonly string Title = "Public field sucks.";
private static readonly string MessageFormat = "{0} {1} public field.";
private static readonly string Description = "Using public field is usually bad implemention.";
private const string Category = "PublicField.CSharp.Suggestion";
internal static DiagnosticDescriptor Rule = new DiagnosticDescriptor(DiagnosticId, Title, MessageFormat, Category, DiagnosticSeverity.Warning, isEnabledByDefault: true, description: Description);
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
{
get
{
return ImmutableArray.Create(Rule);
}
}
public override void Initialize(AnalysisContext context)
{
context.RegisterSyntaxNodeAction(Analyze, SyntaxKind.FieldDeclaration);
}
private static void Analyze(SyntaxNodeAnalysisContext context)
{
var field = (FieldDeclarationSyntax)context.Node;
if (field.Modifiers.Any(SyntaxKind.PublicKeyword) && !field.Modifiers.Any(SyntaxKind.ConstKeyword))
{
var fieldNameTokens = field.Declaration.Variables.Select(x => x.Identifier);
var diagnostic = Diagnostic.Create(Rule, field.GetLocation(), string.Join(", ", fieldNameTokens.Select(x => $"\"{x}\"")), fieldNameTokens.Skip(1).Any() ? "are" : "is");
context.ReportDiagnostic(diagnostic);
}
}
}
}
|
mit
|
C#
|
a8bf551e2d58a81c6bd578af6e254fab8b9f5140
|
Remove unused translator
|
ASP-NET-MVC-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-Core-Boilerplate/Templates,RehanSaeed/ASP.NET-MVC-Boilerplate,ASP-NET-MVC-Boilerplate/Templates,ASP-NET-Core-Boilerplate/Templates
|
Source/Boilerplate.Templates/Content/ApiTemplate/Translators/CarToCarTranslator.cs
|
Source/Boilerplate.Templates/Content/ApiTemplate/Translators/CarToCarTranslator.cs
|
namespace ApiTemplate.Translators
{
using Boilerplate;
using ApiTemplate.ViewModels;
public class CarToCarTranslator : ITranslator<Models.Car, Car>
{
public void Translate(Models.Car source, Car destination)
{
destination.CarId = source.CarId;
destination.Cylinders = source.Cylinders;
destination.Make = source.Make;
destination.Model = source.Model;
}
}
}
|
namespace ApiTemplate.Translators
{
using Boilerplate;
using ApiTemplate.ViewModels;
public class CarToCarTranslator : ITranslator<Models.Car, Car>, ITranslator<Car, Models.Car>
{
public void Translate(Models.Car source, Car destination)
{
destination.CarId = source.CarId;
destination.Cylinders = source.Cylinders;
destination.Make = source.Make;
destination.Model = source.Model;
}
public void Translate(Car source, Models.Car destination)
{
destination.CarId = source.CarId;
destination.Cylinders = source.Cylinders;
destination.Make = source.Make;
destination.Model = source.Model;
}
}
}
|
mit
|
C#
|
bdfe62de9162d052ed0a763f1a9aa10414ce1061
|
fix API signature
|
tomascassidy/BrockAllen.MembershipReboot,eric-swann-q2/BrockAllen.MembershipReboot,vinneyk/BrockAllen.MembershipReboot,DosGuru/MembershipReboot,rajendra1809/BrockAllen.MembershipReboot,brockallen/BrockAllen.MembershipReboot,vankooch/BrockAllen.MembershipReboot,rvdkooy/BrockAllen.MembershipReboot
|
samples/NoSql/SingleTenantWebApp/Areas/UserAccount/Controllers/ChangeSecretQuestionController.cs
|
samples/NoSql/SingleTenantWebApp/Areas/UserAccount/Controllers/ChangeSecretQuestionController.cs
|
using BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Models;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Linq;
using System;
using BrockAllen.MembershipReboot.Hierarchical;
namespace BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Controllers
{
[Authorize]
public class ChangeSecretQuestionController : Controller
{
UserAccountService<HierarchicalUserAccount> userAccountService;
public ChangeSecretQuestionController(UserAccountService<HierarchicalUserAccount> userAccountService)
{
this.userAccountService = userAccountService;
}
public ActionResult Index()
{
var account = this.userAccountService.GetByID(User.GetUserID());
var vm = new PasswordResetSecretsViewModel
{
Secrets = account.PasswordResetSecrets.ToArray()
};
return View("Index", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Remove(Guid id)
{
this.userAccountService.RemovePasswordResetSecret(User.GetUserID(), id);
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(AddSecretQuestionInputModel model)
{
if (ModelState.IsValid)
{
try
{
this.userAccountService.AddPasswordResetSecret(User.GetUserID(), model.Question, model.Answer);
return RedirectToAction("Index");
}
catch (ValidationException ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View("Add", model);
}
}
}
|
using BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Models;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using System.Linq;
using System;
using BrockAllen.MembershipReboot.Hierarchical;
namespace BrockAllen.MembershipReboot.Mvc.Areas.UserAccount.Controllers
{
[Authorize]
public class ChangeSecretQuestionController : Controller
{
UserAccountService<HierarchicalUserAccount> userAccountService;
public ChangeSecretQuestionController(UserAccountService<HierarchicalUserAccount> userAccountService)
{
this.userAccountService = userAccountService;
}
public ActionResult Index()
{
var account = this.userAccountService.GetByID(User.GetUserID());
var vm = new PasswordResetSecretsViewModel
{
Secrets = account.PasswordResetSecrets.ToArray()
};
return View("Index", vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Remove(Guid id)
{
this.userAccountService.RemovePasswordResetSecret(User.GetUserID(), id);
return RedirectToAction("Index");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Add(AddSecretQuestionInputModel model)
{
if (ModelState.IsValid)
{
try
{
this.userAccountService.AddPasswordResetSecret(User.GetUserID(), model.Password, model.Question, model.Answer);
return RedirectToAction("Index");
}
catch (ValidationException ex)
{
ModelState.AddModelError("", ex.Message);
}
}
return View("Add", model);
}
}
}
|
bsd-3-clause
|
C#
|
5e47b97fe8ebd785447d5e28efbd939909cfce11
|
bump version
|
Lone-Coder/letsencrypt-win-simple
|
letsencrypt-win-simple/Properties/AssemblyInfo.cs
|
letsencrypt-win-simple/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Let's Encrypt Simple Windows Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Let's Encrypt")]
[assembly: AssemblyProduct("LetsEncrypt.ACME.CLI")]
[assembly: AssemblyCopyright(" Let's Encrypt")]
[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("30cc3de8-aa52-4807-9b0d-eba08b539918")]
// 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("198.2.*")]
[assembly: AssemblyVersion("198.2.*")]
[assembly: AssemblyFileVersion("1.9.8.2")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Let's Encrypt Simple Windows Client")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Let's Encrypt")]
[assembly: AssemblyProduct("LetsEncrypt.ACME.CLI")]
[assembly: AssemblyCopyright(" Let's Encrypt")]
[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("30cc3de8-aa52-4807-9b0d-eba08b539918")]
// 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("198.1.*")]
[assembly: AssemblyVersion("198.1.*")]
[assembly: AssemblyFileVersion("1.9.8.1")]
|
apache-2.0
|
C#
|
4988c9c50ecda269bcfe7c8e4333a64ceebe322a
|
Test Cases
|
jefking/King.B-Trak
|
King.BTrak.Unit.Test/SqlDataReaderTests.cs
|
King.BTrak.Unit.Test/SqlDataReaderTests.cs
|
namespace King.BTrak.Unit.Test
{
using King.Data.Sql.Reflection;
using King.Mapper.Data;
using NSubstitute;
using NUnit.Framework;
using System;
[TestFixture]
public class SqlDataReaderTests
{
[Test]
public void Constructor()
{
var executor = Substitute.For<IExecutor>();
var reader = Substitute.For<ISchemaReader>();
var tableName = Guid.NewGuid().ToString();
new SqlDataReader(executor, reader, tableName);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructorReaderNull()
{
var executor = Substitute.For<IExecutor>();
var tableName = Guid.NewGuid().ToString();
new SqlDataReader(executor, null, tableName);
}
[Test]
[ExpectedException(typeof(ArgumentNullException))]
public void ConstructorExecutorNull()
{
var reader = Substitute.For<ISchemaReader>();
var tableName = Guid.NewGuid().ToString();
new SqlDataReader(null, reader, tableName);
}
[Test]
[ExpectedException(typeof(ArgumentException))]
public void ConstructorTableNameNull()
{
var reader = Substitute.For<ISchemaReader>();
var executor = Substitute.For<IExecutor>();
new SqlDataReader(executor, reader, null);
}
}
}
|
namespace King.BTrak.Unit.Test
{
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
[TestFixture]
public class SqlDataReaderTests
{
}
}
|
mit
|
C#
|
20104d7d6e60fd9f1dcd303a2448ff138ba4d986
|
Bump Version
|
c0nnex/SPAD.neXt,c0nnex/SPAD.neXt
|
SPAD.Interfaces/Properties/AssemblyInfo.cs
|
SPAD.Interfaces/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Markup;
// 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("SPAD.neXt.Interfaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SPAD.neXt.Interfaces")]
[assembly: AssemblyCopyright("Copyright © 2014-2016 Ulrich Strauss")]
[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("2b25a2bf-891e-4970-b709-e53f1ebecb41")]
[assembly: XmlnsPrefix("http://www.fsgs.com/SPAD.neXt.Interfaces", "Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces.Events")]
// 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.9.5.6")]
[assembly: AssemblyFileVersion("0.9.5.6")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows.Markup;
// 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("SPAD.neXt.Interfaces")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SPAD.neXt.Interfaces")]
[assembly: AssemblyCopyright("Copyright © 2014-2016 Ulrich Strauss")]
[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("2b25a2bf-891e-4970-b709-e53f1ebecb41")]
[assembly: XmlnsPrefix("http://www.fsgs.com/SPAD.neXt.Interfaces", "Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces")]
[assembly: XmlnsDefinition("http://www.fsgs.com/SPAD.neXt.Interfaces", "SPAD.neXt.Interfaces.Events")]
// 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.9.5.5")]
[assembly: AssemblyFileVersion("0.9.5.5")]
|
mit
|
C#
|
e257d7ad2595423553e1190187f41381a84d7d25
|
clarify parameters in EventStore
|
modulexcite/lokad-cqrs
|
SaaS.Wires/EventStore.cs
|
SaaS.Wires/EventStore.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using Lokad.Cqrs;
using Lokad.Cqrs.TapeStorage;
namespace SaaS.Wires
{
public sealed class EventStore : IEventStore
{
readonly MessageStore _store;
public EventStore(MessageStore store)
{
_store = store;
}
public void AppendEventsToStream(IIdentity id, long streamVersion, ICollection<IEvent> events)
{
if (events.Count == 0) return;
// functional events don't have an identity
var name = IdentityToKey(id);
try
{
_store.AppendToStore(name, MessageAttribute.Empty, streamVersion, events.Cast<object>().ToArray());
}
catch (AppendOnlyStoreConcurrencyException e)
{
// load server events
var server = LoadEventStream(id);
// throw a real problem
throw OptimisticConcurrencyException.Create(server.StreamVersion, e.ExpectedStreamVersion, id, server.Events);
}
}
static string IdentityToKey(IIdentity id)
{
return id == null ? "func" : (id.GetTag() + ":" + id.GetId());
}
public EventStream LoadEventStream(IIdentity id)
{
var key = IdentityToKey(id);
// TODO: make this lazy somehow?
var stream = new EventStream();
foreach (var record in _store.EnumerateMessages(key, 0, int.MaxValue))
{
stream.Events.AddRange(record.Items.Cast<IEvent>());
stream.StreamVersion = record.StreamVersion;
}
return stream;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using Lokad.Cqrs;
using Lokad.Cqrs.TapeStorage;
namespace SaaS.Wires
{
public sealed class EventStore : IEventStore
{
readonly MessageStore _store;
public EventStore(MessageStore store)
{
_store = store;
}
public void AppendEventsToStream(IIdentity id, long originalVersion, ICollection<IEvent> events)
{
if (events.Count == 0) return;
// functional events don't have an identity
var name = IdentityToKey(id);
try
{
_store.AppendToStore(name, MessageAttribute.Empty, originalVersion, events.Cast<object>().ToArray());
}
catch (AppendOnlyStoreConcurrencyException e)
{
// load server events
var server = LoadEventStream(id);
// throw a real problem
throw OptimisticConcurrencyException.Create(server.StreamVersion, e.ExpectedStreamVersion, id, server.Events);
}
}
static string IdentityToKey(IIdentity id)
{
return id == null ? "func" : (id.GetTag() + ":" + id.GetId());
}
public EventStream LoadEventStream(IIdentity id)
{
var key = IdentityToKey(id);
// TODO: make this lazy somehow?
var stream = new EventStream();
foreach (var record in _store.EnumerateMessages(key, 0, int.MaxValue))
{
stream.Events.AddRange(record.Items.Cast<IEvent>());
stream.StreamVersion = record.StreamVersion;
}
return stream;
}
}
}
|
bsd-3-clause
|
C#
|
44578c2d43db3cea223f7dee543b34500d70f6f4
|
Revert "Added method to perform validity check for effect parameters"
|
igece/SoxSharp
|
src/Effects/IBaseEffect.cs
|
src/Effects/IBaseEffect.cs
|
namespace SoxSharp.Effects
{
public interface IBaseEffect
{
string Name { get; }
string ToString();
}
}
|
namespace SoxSharp.Effects
{
public interface IBaseEffect
{
string Name { get; }
bool IsValid();
string ToString();
}
}
|
apache-2.0
|
C#
|
e1ab0ff6853edb9ae346a9cec56842a38603d8a7
|
remove unnecessary check
|
ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms,ZoranPandovski/al-go-rithms
|
cryptography/rot47_cipher/rot47_cipher/ROT_47_Cipher.cs
|
cryptography/rot47_cipher/rot47_cipher/ROT_47_Cipher.cs
|
using System;
namespace rot47_cipher
{
public class ROT_47_Cipher
{
public static string DoCipher(string text)
{
var result = "";
foreach (char c in text)
{
if ((int) c >= 32 && (int) c <= 126)
{
if (Char.IsWhiteSpace((char) c))
{
result += " ";
}
else
{
result += (char) (33 + ((int) c + 14) % 94);
}
}
}
return result;
}
}
}
|
using System;
namespace rot47_cipher
{
public class ROT_47_Cipher
{
public static string DoCipher(string text)
{
var result = "";
foreach (char c in text)
{
if ((int) c >= 32 && (int) c <= 126 || (int) c == 2)
{
if (Char.IsWhiteSpace((char) c))
{
result += " ";
}
else
{
result += (char) (33 + ((int) c + 14) % 94);
}
}
}
return result;
}
}
}
|
cc0-1.0
|
C#
|
5075428a1e5eeffb20b459719f01b372ce4ee6db
|
Update CustomersService.cs
|
zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,ServiceStack/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,zhaokunfay/ServiceStack.Examples,ServiceStack/ServiceStack.Examples
|
src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/CustomersService.cs
|
src/ServiceStack.Northwind/ServiceStack.Northwind.ServiceInterface/CustomersService.cs
|
namespace ServiceStack.Northwind.ServiceInterface
{
using ServiceStack.Northwind.ServiceModel.Operations;
using ServiceStack.Northwind.ServiceModel.Types;
using ServiceStack.OrmLite;
using ServiceStack.ServiceInterface;
public class CustomersService : Service
{
public IDbConnectionFactory DbFactory { get; set; }
public CustomersResponse Get(Customers request)
{
return new CustomersResponse { Customers = Db.Select<Customer>() };
}
}
}
|
namespace ServiceStack.Northwind.ServiceInterface
{
using ServiceStack.Northwind.ServiceModel.Operations;
using ServiceStack.Northwind.ServiceModel.Types;
using ServiceStack.OrmLite;
using ServiceStack.ServiceInterface;
public class CustomersService : Service
{
public IDbConnectionFactory DbFactory { get; set; }
public CustomersResponse Get(Customers request)
{
return new CustomersResponse {Customers = DbFactory.Run(dbCmd => dbCmd.Select<Customer>())};
}
}
}
|
bsd-3-clause
|
C#
|
2736aaae534fa476cc2aea31139b6dea5f5d124b
|
fix card requirement comparison
|
StefanoFiumara/Harry-Potter-Unity
|
Assets/Scripts/HarryPotterUnity/DeckGeneration/Requirements/DeckCardLimitRequirement.cs
|
Assets/Scripts/HarryPotterUnity/DeckGeneration/Requirements/DeckCardLimitRequirement.cs
|
using System.Collections.Generic;
using System.Linq;
using HarryPotterUnity.Cards;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.DeckGeneration.Requirements
{
public class DeckCardLimitRequirement : MonoBehaviour, IDeckGenerationRequirement
{
[SerializeField] private int _maximumAmountAllowed;
private BaseCard _cardInfo;
public int MaximumAmountAllowed
{
private get { return _maximumAmountAllowed; }
set { _maximumAmountAllowed = value; }
}
[UsedImplicitly]
private void Start()
{
_cardInfo = GetComponent<BaseCard>();
}
public bool MeetsRequirement(List<BaseCard> currentDeck)
{
return currentDeck.Count(c => c.CardName == _cardInfo.CardName) < MaximumAmountAllowed;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using HarryPotterUnity.Cards;
using JetBrains.Annotations;
using UnityEngine;
namespace HarryPotterUnity.DeckGeneration.Requirements
{
public class DeckCardLimitRequirement : MonoBehaviour, IDeckGenerationRequirement
{
[SerializeField] private int _maximumAmountAllowed;
private BaseCard _cardInfo;
public int MaximumAmountAllowed
{
private get
{
return _maximumAmountAllowed;
}
set
{
_maximumAmountAllowed = value;
}
}
[UsedImplicitly]
private void Start()
{
_cardInfo = GetComponent<BaseCard>();
}
public bool MeetsRequirement(List<BaseCard> currentDeck)
{
return currentDeck.Count(c => c.Equals(_cardInfo)) < MaximumAmountAllowed;
}
}
}
|
mit
|
C#
|
4a075063687515088f90e13857c7d1c2a627a75d
|
Update AutofacPlatformCompositionRootSetupBase.cs
|
tiksn/TIKSN-Framework
|
TIKSN.Framework.Platform/DependencyInjection/AutofacPlatformCompositionRootSetupBase.cs
|
TIKSN.Framework.Platform/DependencyInjection/AutofacPlatformCompositionRootSetupBase.cs
|
using Autofac.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
namespace TIKSN.DependencyInjection
{
public abstract class AutofacPlatformCompositionRootSetupBase : AutofacCompositionRootSetupBase
{
protected AutofacPlatformCompositionRootSetupBase(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
protected override IEnumerable<IModule> GetAutofacModules()
{
var modules = base.GetAutofacModules().ToList();
modules.Add(new PlatformModule());
return modules;
}
protected override void ConfigureServices(IServiceCollection services)
{
services.AddFrameworkPlatform();
}
}
}
|
using Autofac.Core;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;
using System.Linq;
namespace TIKSN.DependencyInjection
{
public abstract class AutofacPlatformCompositionRootSetupBase : AutofacCompositionRootSetupBase
{
protected AutofacPlatformCompositionRootSetupBase(IConfigurationRoot configurationRoot) : base(configurationRoot)
{
}
protected override IEnumerable<IModule> GetAutofacModules()
{
var modules = base.GetAutofacModules().ToList();
modules.Add(new PlatformModule());
return modules;
}
protected override void ConfigureServices(IServiceCollection services)
{
PlatformDependencyRegistration.Register(services);
}
}
}
|
mit
|
C#
|
ed14f69b361f6f389ea54e1c03dd8f32f4dc689a
|
Fix test path
|
dbarowy/Depends
|
Tests/COMWrapperTests.cs
|
Tests/COMWrapperTests.cs
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using COMWrapper;
namespace ExceLintTests
{
[TestClass]
public class COMWrapperTests
{
[TestMethod]
public void WorkbookIndexTest()
{
var path = @"..\..\TestData";
var wb1_name = "01-38-PK_tables-figures.xls";
var wb2_name = "chartssection2.xls";
var wb3_name = "gradef03-sec3.xls";
var wb4_name = "ribimv001.xls";
var wb5_name = "p36.xls";
var app = new Application();
var wb1 = app.OpenWorkbook(System.IO.Path.Combine(path, wb1_name));
Assert.AreEqual(wb1.WorkbookName, wb1_name);
var wb2 = app.OpenWorkbook(System.IO.Path.Combine(path, wb2_name));
Assert.AreEqual(wb2.WorkbookName, wb2_name);
app.CloseWorkbook(wb2);
var wb3 = app.OpenWorkbook(System.IO.Path.Combine(path, wb3_name));
Assert.AreEqual(wb3.WorkbookName, wb3_name);
var wb4 = app.OpenWorkbook(System.IO.Path.Combine(path, wb4_name));
Assert.AreEqual(wb4.WorkbookName, wb4_name);
app.CloseWorkbook(wb1);
var wb5 = app.OpenWorkbook(System.IO.Path.Combine(path, wb5_name));
Assert.AreEqual(wb5.WorkbookName, wb5_name);
}
}
}
|
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using COMWrapper;
namespace ExceLintTests
{
[TestClass]
public class COMWrapperTests
{
[TestMethod]
public void WorkbookIndexTest()
{
var path = "../../../../../data/analyses/CUSTODES/custodes/example/input_spreadsheets";
var wb1_name = "01-38-PK_tables-figures.xls";
var wb2_name = "chartssection2.xls";
var wb3_name = "gradef03-sec3.xls";
var wb4_name = "ribimv001.xls";
var wb5_name = "p36.xls";
var app = new Application();
var wb1 = app.OpenWorkbook(System.IO.Path.Combine(path, wb1_name));
Assert.AreEqual(wb1.WorkbookName, wb1_name);
var wb2 = app.OpenWorkbook(System.IO.Path.Combine(path, wb2_name));
Assert.AreEqual(wb2.WorkbookName, wb2_name);
app.CloseWorkbook(wb2);
var wb3 = app.OpenWorkbook(System.IO.Path.Combine(path, wb3_name));
Assert.AreEqual(wb3.WorkbookName, wb3_name);
var wb4 = app.OpenWorkbook(System.IO.Path.Combine(path, wb4_name));
Assert.AreEqual(wb4.WorkbookName, wb4_name);
app.CloseWorkbook(wb1);
var wb5 = app.OpenWorkbook(System.IO.Path.Combine(path, wb5_name));
Assert.AreEqual(wb5.WorkbookName, wb5_name);
}
}
}
|
bsd-2-clause
|
C#
|
e15ff7bfdbbc30161e5906f68815eb3fb3d55c31
|
Increase version number
|
fredatgithub/Matrix
|
TheMatrixHasYou/Properties/AssemblyInfo.cs
|
TheMatrixHasYou/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("TheMatrixHasYou")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TheMatrixHasYou")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("bcdbe837-3bcc-478b-aef6-f7c24db042fb")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.1.0.0")]
[assembly: AssemblyFileVersion("1.1.0.0")]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Les informations générales relatives à un assembly dépendent de
// l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations
// associées à un assembly.
[assembly: AssemblyTitle("TheMatrixHasYou")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TheMatrixHasYou")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly
// aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de
// COM, affectez la valeur true à l'attribut ComVisible sur ce type.
[assembly: ComVisible(false)]
// Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM
[assembly: Guid("bcdbe837-3bcc-478b-aef6-f7c24db042fb")]
// Les informations de version pour un assembly se composent des quatre valeurs suivantes :
//
// Version principale
// Version secondaire
// Numéro de build
// Révision
//
// Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut
// en utilisant '*', comme indiqué ci-dessous :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
b305a82db2249d1362c084d782037203b7c5e02b
|
Maintain menu open/closed state while OpenVR keyboard is active
|
virtuallynaked/virtually-naked,virtuallynaked/virtually-naked
|
Viewer/src/input/ControllerStateTracker.cs
|
Viewer/src/input/ControllerStateTracker.cs
|
using SharpDX;
using System;
using Valve.VR;
public class ControllerStateTracker {
private readonly uint deviceIdx;
private bool active;
private bool menuOpen;
private VRControllerState_t secondPreviousState;
private VRControllerState_t previousState;
private VRControllerState_t currentState;
private int staleness;
private int previousStaleness;
public ControllerStateTracker(uint deviceIdx) {
this.deviceIdx = deviceIdx;
}
public void Update() {
if (OpenVR.System.GetTrackedDeviceClass(deviceIdx) != ETrackedDeviceClass.Controller) {
active = false;
return;
}
if (!OpenVR.System.GetControllerState(deviceIdx, out var controllerState)) {
active = false;
return;
}
if (active) {
staleness += 1;
if (controllerState.unPacketNum == currentState.unPacketNum) {
return;
}
}
if (!active) {
//activate
Console.WriteLine("activate");
active = true;
secondPreviousState = default(VRControllerState_t);
previousState = default(VRControllerState_t);
} else {
secondPreviousState = previousState;
previousState = currentState;
previousStaleness = staleness;
}
currentState = controllerState;
staleness = 0;
if (WasClicked(EVRButtonId.k_EButton_ApplicationMenu)) {
menuOpen = !menuOpen;
}
}
public bool Active => active;
public bool IsFresh => staleness == 0;
public bool MenuActive => active && menuOpen;
public bool NonMenuActive => active && !menuOpen;
public bool WasClicked(EVRButtonId buttonId) {
return staleness == 0 && previousState.IsPressed(buttonId) && !currentState.IsPressed(buttonId);
}
public bool IsTouched(EVRButtonId buttonId) {
return currentState.IsTouched(buttonId);
}
public bool IsPressed(EVRButtonId buttonId) {
return currentState.IsPressed(buttonId);
}
public bool BecameUntouched(EVRButtonId buttonId) {
return staleness == 0 && previousState.IsTouched(buttonId) && !currentState.IsTouched(buttonId);
}
public bool HasTouchDelta(uint axisIdx) {
EVRButtonId buttonId = EVRButtonId.k_EButton_Axis0 + (int) axisIdx;
if (staleness > 0) {
return false;
}
if (!currentState.IsTouched(buttonId) || !previousState.IsTouched(buttonId)) {
return false;
}
if (!secondPreviousState.IsTouched(buttonId)) {
//workaround for SteamVR bug: http://steamcommunity.com/app/250820/discussions/3/2132869574256358055/
return false;
}
return true;
}
public Vector2 GetTouchDelta(uint axisIdx) {
Vector2 previousPosition = previousState.GetAxis(axisIdx).AsVector();
Vector2 currentPosition = currentState.GetAxis(axisIdx).AsVector();
return currentPosition - previousPosition;
}
public Vector2 GetAxisPosition(uint axisIdx) {
return currentState.GetAxis(axisIdx).AsVector();
}
public int GetUpdateRate() {
return previousStaleness;
}
}
|
using SharpDX;
using Valve.VR;
public class ControllerStateTracker {
private readonly uint deviceIdx;
private bool active;
private bool menuOpen;
private VRControllerState_t secondPreviousState;
private VRControllerState_t previousState;
private VRControllerState_t currentState;
private int staleness;
private int previousStaleness;
public ControllerStateTracker(uint deviceIdx) {
this.deviceIdx = deviceIdx;
}
public void Update() {
if (OpenVR.System.GetTrackedDeviceClass(deviceIdx) != ETrackedDeviceClass.Controller) {
active = false;
return;
}
if (!OpenVR.System.GetControllerState(deviceIdx, out var controllerState)) {
active = false;
}
if (active) {
staleness += 1;
if (controllerState.unPacketNum == currentState.unPacketNum) {
return;
}
}
if (!active) {
//activate
active = true;
menuOpen = false;
secondPreviousState = default(VRControllerState_t);
previousState = default(VRControllerState_t);
} else {
secondPreviousState = previousState;
previousState = currentState;
previousStaleness = staleness;
}
currentState = controllerState;
staleness = 0;
if (WasClicked(EVRButtonId.k_EButton_ApplicationMenu)) {
menuOpen = !menuOpen;
}
}
public bool Active => active;
public bool IsFresh => staleness == 0;
public bool MenuActive => active && menuOpen;
public bool NonMenuActive => active && !menuOpen;
public bool WasClicked(EVRButtonId buttonId) {
return staleness == 0 && previousState.IsPressed(buttonId) && !currentState.IsPressed(buttonId);
}
public bool IsTouched(EVRButtonId buttonId) {
return currentState.IsTouched(buttonId);
}
public bool IsPressed(EVRButtonId buttonId) {
return currentState.IsPressed(buttonId);
}
public bool BecameUntouched(EVRButtonId buttonId) {
return staleness == 0 && previousState.IsTouched(buttonId) && !currentState.IsTouched(buttonId);
}
public bool HasTouchDelta(uint axisIdx) {
EVRButtonId buttonId = EVRButtonId.k_EButton_Axis0 + (int) axisIdx;
if (staleness > 0) {
return false;
}
if (!currentState.IsTouched(buttonId) || !previousState.IsTouched(buttonId)) {
return false;
}
if (!secondPreviousState.IsTouched(buttonId)) {
//workaround for SteamVR bug: http://steamcommunity.com/app/250820/discussions/3/2132869574256358055/
return false;
}
return true;
}
public Vector2 GetTouchDelta(uint axisIdx) {
Vector2 previousPosition = previousState.GetAxis(axisIdx).AsVector();
Vector2 currentPosition = currentState.GetAxis(axisIdx).AsVector();
return currentPosition - previousPosition;
}
public Vector2 GetAxisPosition(uint axisIdx) {
return currentState.GetAxis(axisIdx).AsVector();
}
public int GetUpdateRate() {
return previousStaleness;
}
}
|
mit
|
C#
|
78a3d42c7945fc3d4b7b6d84372b65e8b9f332b2
|
Integrate the `Networking.Simulator.Boiler` project with the `ReferenceApplication` #302
|
mpostol/OPC-UA-OOI
|
Networking/Tests/Networking.Simulator.Boiler.Unit/Model/BoilersSetUnitTest.cs
|
Networking/Tests/Networking.Simulator.Boiler.Unit/Model/BoilersSetUnitTest.cs
|
//___________________________________________________________________________________
//
// Copyright (C) 2018, Mariusz Postol LODZ POLAND.
//
// To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI
//___________________________________________________________________________________
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
using System.Diagnostics;
using UAOOI.Networking.Simulator.Boiler.AddressSpace;
using UAOOI.Networking.Simulator.Boiler.Model;
using UAOOI.SemanticData.UANodeSetValidation.DataSerialization;
using Boilers = Commsvr.UA.Examples.BoilersSet;
namespace UAOOI.Networking.Simulator.Boiler.UnitTest.Model
{
[TestClass]
public class BoilersSetUnitTest
{
[TestMethod]
public void ConstructorTest()
{
using (BoilersSet _set = BoilersSet.Factory)
{
Assert.IsNotNull(_set);
Assert.AreEqual<string>(Boilers.BrowseNames.BoilersArea, _set.BrowseName.Name);
Assert.AreEqual<NodeClass>(NodeClass.Object_1, _set.NodeClass);
Assert.IsNull(_set.Parent);
}
}
[TestMethod]
public void GetSemanticDataSourcesTest()
{
using (ISemanticDataSource _set = BoilersSet.Factory)
{
Assert.IsNotNull(_set);
_set.GetSemanticDataSources((semanticDataSetRootBrowsePath, variableRelativeBrowsePath, variable) => AddressSpace.Add($"{semanticDataSetRootBrowsePath}:{variableRelativeBrowsePath}", variable));
Assert.AreEqual<int>(80, AddressSpace.Count);
foreach (KeyValuePair<string, IVariable> _var in AddressSpace)
Debug.WriteLine($"{_var.Key}:{_var.Value.ValueType}");
}
Assert.IsTrue(AddressSpace.ContainsKey("Boiler #1:CCX001_ControlOut"));
Assert.IsTrue(AddressSpace.ContainsKey("Boiler #2:CCX001_ControlOut"));
Assert.IsTrue(AddressSpace.ContainsKey("Boiler #3:CCX001_ControlOut"));
Assert.IsTrue(AddressSpace.ContainsKey("Boiler #4:CCX001_ControlOut"));
}
private Dictionary<string, IVariable> AddressSpace = new Dictionary<string, IVariable>();
}
}
|
//___________________________________________________________________________________
//
// Copyright (C) 2018, Mariusz Postol LODZ POLAND.
//
// To be in touch join the community at GITTER: https://gitter.im/mpostol/OPC-UA-OOI
//___________________________________________________________________________________
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UAOOI.Networking.Simulator.Boiler.Model;
namespace UAOOI.Networking.Simulator.Boiler.UnitTest.Model
{
[TestClass]
public class BoilersSetUnitTest
{
[TestMethod]
public void ConstructorTest()
{
BoilersSet _set = BoilersSet.Factory;
Assert.IsNotNull(_set);
}
}
}
|
mit
|
C#
|
6115acdeffbba5f35aa2ef20d4ec69b06a4116c0
|
Update DesktopGameHost post-rebase
|
default0/osu-framework,RedNesto/osu-framework,smoogipooo/osu-framework,DrabWeb/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,EVAST9919/osu-framework,paparony03/osu-framework,EVAST9919/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,default0/osu-framework,DrabWeb/osu-framework,peppy/osu-framework,Nabile-Rahmani/osu-framework,EVAST9919/osu-framework,EVAST9919/osu-framework,RedNesto/osu-framework,smoogipooo/osu-framework,Nabile-Rahmani/osu-framework,ZLima12/osu-framework,Tom94/osu-framework,NeoAdonis/osu-framework,ppy/osu-framework,ppy/osu-framework,naoey/osu-framework,peppy/osu-framework,paparony03/osu-framework,NeoAdonis/osu-framework,naoey/osu-framework,ppy/osu-framework
|
osu.Framework.Desktop/Platform/DesktopGameHost.cs
|
osu.Framework.Desktop/Platform/DesktopGameHost.cs
|
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.Platform;
namespace osu.Framework.Desktop.Platform
{
public abstract class DesktopGameHost : BasicGameHost
{
public override GLControl GLControl => Window?.Form;
private TextInputSource textInputBox;
public override TextInputSource TextInput => textInputBox ?? (textInputBox = ((DesktopGameWindow)Window).CreateTextInput());
private TcpIpcProvider IpcProvider;
private Task IpcTask;
public override void Load(BaseGame game)
{
IpcProvider = new TcpIpcProvider();
IsPrimaryInstance = IpcProvider.Bind();
if (IsPrimaryInstance)
{
IpcProvider.MessageReceived += msg => OnMessageReceived(msg);
IpcTask = IpcProvider.Start();
}
base.Load(game);
}
protected override async Task SendMessage(IpcMessage message)
{
await IpcProvider.SendMessage(message);
}
protected override void Dispose(bool isDisposing)
{
IpcProvider.Dispose();
IpcTask?.Wait(50);
base.Dispose(isDisposing);
}
}
}
|
// Copyright (c) 2007-2016 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using osu.Framework.Input;
using osu.Framework.Input.Handlers;
using osu.Framework.Platform;
namespace osu.Framework.Desktop.Platform
{
public abstract class DesktopGameHost : BasicGameHost
{
public override GLControl GLControl => Window?.Form;
private TextInputSource textInputBox;
public override TextInputSource TextInput => textInputBox ?? (textInputBox = ((DesktopGameWindow)Window).CreateTextInput());
private TcpIpcProvider IpcProvider;
private Task IpcTask;
public override void Load()
{
IpcProvider = new TcpIpcProvider();
IsPrimaryInstance = IpcProvider.Bind();
if (IsPrimaryInstance)
{
IpcProvider.MessageReceived += msg => OnMessageReceived(msg);
IpcTask = IpcProvider.Start();
}
base.Load();
}
protected override async Task SendMessage(IpcMessage message)
{
await IpcProvider.SendMessage(message);
}
protected override void Dispose(bool isDisposing)
{
IpcProvider.Dispose();
IpcTask?.Wait(50);
base.Dispose(isDisposing);
}
}
}
|
mit
|
C#
|
5efe7f8dad174336165b96dbda2707a083ca4c9f
|
Refactor plays/retries counting using osu events
|
Piotrekol/StreamCompanion,Piotrekol/StreamCompanion
|
plugins/PlaysReplacements/PlaysReplacements.cs
|
plugins/PlaysReplacements/PlaysReplacements.cs
|
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces;
using StreamCompanionTypes.Interfaces.Sources;
namespace PlaysReplacements
{
public class PlaysReplacements : IPlugin, ITokensSource
{
private int Plays, Retrys;
private Tokens.TokenSetter _tokenSetter;
public string Description { get; } = "";
public string Name { get; } = nameof(PlaysReplacements);
public string Author { get; } = "Piotrekol";
public string Url { get; } = "";
public string UpdateUrl { get; } = "";
public PlaysReplacements()
{
_tokenSetter = Tokens.CreateTokenSetter(Name);
UpdateTokens();
}
public void CreateTokens(MapSearchResult map)
{
//ignore replays/spect
if (map.Action != OsuStatus.Playing)
return;
switch (map.SearchArgs.EventType)
{
case OsuEventType.SceneChange:
case OsuEventType.MapChange:
Plays++;
break;
case OsuEventType.PlayChange:
Retrys++;
break;
}
UpdateTokens();
}
private void UpdateTokens()
{
_tokenSetter("plays", Plays);
_tokenSetter("retrys", Retrys);
}
}
}
|
using StreamCompanionTypes.DataTypes;
using StreamCompanionTypes.Enums;
using StreamCompanionTypes.Interfaces;
using StreamCompanionTypes.Interfaces.Sources;
namespace PlaysReplacements
{
public class PlaysReplacements : IPlugin, ITokensSource
{
private int Plays, Retrys;
private Tokens.TokenSetter _tokenSetter;
private string lastMapSearchString = "";
public string Description { get; } = "";
public string Name { get; } = nameof(PlaysReplacements);
public string Author { get; } = "Piotrekol";
public string Url { get; } = "";
public string UpdateUrl { get; } = "";
public PlaysReplacements()
{
_tokenSetter = Tokens.CreateTokenSetter(Name);
}
public void CreateTokens(MapSearchResult map)
{
if (map.Action == OsuStatus.Playing)
{
if (lastMapSearchString == map.MapSearchString)
Retrys++;
else
Plays++;
lastMapSearchString = map.MapSearchString;
}
_tokenSetter("plays", Plays);
_tokenSetter("retrys", Retrys);
}
}
}
|
mit
|
C#
|
5ebffb844cf8e5abf869758041217945f8a7ca82
|
Add an import of dll
|
Red-Folder/WebCrawl-Functions
|
WebCrawlStart/run.csx
|
WebCrawlStart/run.csx
|
#r "Microsoft.WindowsAzure.Storage"
#r "Newtonsoft.Json"
using System;
using System.Net;
using Microsoft.Azure; // Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount
using Microsoft.WindowsAzure.Storage.Queue; // Namespace for Queue storage types
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"Request to start WebCrawl");
var requestId = Guid.NewGuid();
HttpResponseMessage response = null;
try
{
string storageConnectionString = System.Environment.GetEnvironmentVariable("APPSETTING_rfcwebcrawl_STORAGE");
// Parse the connection string and return a reference to the storage account.
log.Info("Login to the storage account");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
// Create the queue client.
log.Info("Create the queueClient");
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a container.
log.Info("Create reference to the toWebCrawl queue");
CloudQueue queue = queueClient.GetQueueReference("towebcrawl");
// Create the queue if it doesn't already exist
log.Info("Create the queue if needed");
queue.CreateIfNotExists();
// Create a message and add it to the queue.
log.Info("Create the message");
CloudQueueMessage message = new CloudQueueMessage(requestId.ToString());
log.Info("Add the message");
queue.AddMessage(message);
log.Info("Returning OK");
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(new {id = requestId}))
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
} catch (Exception ex) {
log.Info($"Failed to handle request - exception thrown - {0}", ex.Message);
response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error has occurred. Refer to the server logs.")
};
}
return response;
}
|
#r "Microsoft.WindowsAzure.Storage"
using System;
using System.Net;
using Microsoft.Azure; // Namespace for CloudConfigurationManager
using Microsoft.WindowsAzure.Storage; // Namespace for CloudStorageAccount
using Microsoft.WindowsAzure.Storage.Queue; // Namespace for Queue storage types
using Newtonsoft.Json;
public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
log.Info($"Request to start WebCrawl");
var requestId = Guid.NewGuid();
HttpResponseMessage response = null;
try
{
string storageConnectionString = System.Environment.GetEnvironmentVariable("APPSETTING_rfcwebcrawl_STORAGE");
// Parse the connection string and return a reference to the storage account.
log.Info("Login to the storage account");
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(storageConnectionString);
// Create the queue client.
log.Info("Create the queueClient");
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
// Retrieve a reference to a container.
log.Info("Create reference to the toWebCrawl queue");
CloudQueue queue = queueClient.GetQueueReference("towebcrawl");
// Create the queue if it doesn't already exist
log.Info("Create the queue if needed");
queue.CreateIfNotExists();
// Create a message and add it to the queue.
log.Info("Create the message");
CloudQueueMessage message = new CloudQueueMessage(requestId.ToString());
log.Info("Add the message");
queue.AddMessage(message);
log.Info("Returning OK");
response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent(JsonConvert.SerializeObject(new {id = requestId}))
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
} catch (Exception ex) {
log.Info($"Failed to handle request - exception thrown - {0}", ex.Message);
response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
{
Content = new StringContent("An error has occurred. Refer to the server logs.")
};
}
return response;
}
|
mit
|
C#
|
5d3dc375962d68eb67eddd0ba65333c47f72eeeb
|
简化验证失败的回调方法的参数。
|
Zongsoft/Zongsoft.CoreLibrary
|
src/Common/IValidator.cs
|
src/Common/IValidator.cs
|
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2015-2018 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Common
{
/// <summary>
/// 表示提供有效性验证功能的接口。
/// </summary>
/// <typeparam name="T">指定</typeparam>
public interface IValidator<in T>
{
/// <summary>
/// 验证指定的数据是否有效。
/// </summary>
/// <param name="data">指定的待验证的数据。</param>
/// <param name="failure">当内部验证失败的回调处理函数,传入的字符串参数表示验证失败的消息文本。</param>
/// <returns>如果验证通过则返回真(True),否则返回假(False)。</returns>
bool Validate(T data, Action<string> failure = null);
}
}
|
/*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2015-2018 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.CoreLibrary.
*
* Zongsoft.CoreLibrary is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.CoreLibrary is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.CoreLibrary; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.Collections.Generic;
namespace Zongsoft.Common
{
/// <summary>
/// 表示提供有效性验证功能的接口。
/// </summary>
/// <typeparam name="T">指定</typeparam>
public interface IValidator<in T>
{
/// <summary>
/// 验证指定的数据是否有效。
/// </summary>
/// <param name="data">指定的待验证的数据。</param>
/// <param name="failure">当内部验证失败的回调处理函数。该回调函数返回一个布尔值(真或假)作为整个验证方法的返回值,空(null)表示继续后续的验证环节。</param>
/// <returns>如果验证通过则返回真(True),否则返回假(False)。</returns>
bool Validate(T data, Func<string, string, bool?> failure = null);
}
}
|
lgpl-2.1
|
C#
|
2613b7951c1b055338624362a7822e004ca3491b
|
change default view service view folder to "views" from "assets"
|
Agrando/IdentityServer3,tbitowner/IdentityServer3,delloncba/IdentityServer3,EternalXw/IdentityServer3,tuyndv/IdentityServer3,jackswei/IdentityServer3,jackswei/IdentityServer3,18098924759/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,ryanvgates/IdentityServer3,bestwpw/IdentityServer3,tuyndv/IdentityServer3,IdentityServer/IdentityServer3,mvalipour/IdentityServer3,ryanvgates/IdentityServer3,EternalXw/IdentityServer3,tonyeung/IdentityServer3,kouweizhong/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,bestwpw/IdentityServer3,bodell/IdentityServer3,kouweizhong/IdentityServer3,jackswei/IdentityServer3,wondertrap/IdentityServer3,18098924759/IdentityServer3,tbitowner/IdentityServer3,codeice/IdentityServer3,charoco/IdentityServer3,mvalipour/IdentityServer3,feanz/Thinktecture.IdentityServer.v3,johnkors/Thinktecture.IdentityServer.v3,chicoribas/IdentityServer3,olohmann/IdentityServer3,openbizgit/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,openbizgit/IdentityServer3,olohmann/IdentityServer3,uoko-J-Go/IdentityServer,18098924759/IdentityServer3,kouweizhong/IdentityServer3,delRyan/IdentityServer3,delRyan/IdentityServer3,wondertrap/IdentityServer3,openbizgit/IdentityServer3,mvalipour/IdentityServer3,tonyeung/IdentityServer3,delRyan/IdentityServer3,Agrando/IdentityServer3,EternalXw/IdentityServer3,ryanvgates/IdentityServer3,bodell/IdentityServer3,delloncba/IdentityServer3,Agrando/IdentityServer3,roflkins/IdentityServer3,uoko-J-Go/IdentityServer,roflkins/IdentityServer3,olohmann/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,faithword/IdentityServer3,chicoribas/IdentityServer3,SonOfSam/IdentityServer3,johnkors/Thinktecture.IdentityServer.v3,faithword/IdentityServer3,faithword/IdentityServer3,codeice/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,codeice/IdentityServer3,charoco/IdentityServer3,IdentityServer/IdentityServer3,tbitowner/IdentityServer3,wondertrap/IdentityServer3,bodell/IdentityServer3,SonOfSam/IdentityServer3,bestwpw/IdentityServer3,IdentityServer/IdentityServer3,tonyeung/IdentityServer3,charoco/IdentityServer3,huoxudong125/Thinktecture.IdentityServer.v3,SonOfSam/IdentityServer3,delloncba/IdentityServer3,tuyndv/IdentityServer3,uoko-J-Go/IdentityServer,roflkins/IdentityServer3
|
source/Core/Services/DefaultViewService/FileSystemWithEmbeddedFallbackViewLoader.cs
|
source/Core/Services/DefaultViewService/FileSystemWithEmbeddedFallbackViewLoader.cs
|
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
namespace IdentityServer3.Core.Services.Default
{
/// <summary>
/// View loader implementation that uses a combination of the file system view loader
/// and the embedded assets view loader. This allows for some templates to be defined
/// via the file system, while using the embedded assets templates for all others.
/// </summary>
public class FileSystemWithEmbeddedFallbackViewLoader : IViewLoader
{
readonly FileSystemViewLoader file;
readonly EmbeddedAssetsViewLoader embedded;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
public FileSystemWithEmbeddedFallbackViewLoader()
: this(GetDefaultDirectory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
/// <param name="directory">The directory.</param>
public FileSystemWithEmbeddedFallbackViewLoader(string directory)
{
this.file = new FileSystemViewLoader(directory);
this.embedded = new EmbeddedAssetsViewLoader();
}
static string GetDefaultDirectory()
{
var path = AppDomain.CurrentDomain.BaseDirectory;
path = Path.Combine(path, "views");
return path;
}
/// <summary>
/// Loads the HTML for the named view.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public string Load(string name)
{
var value = file.Load(name);
if (value == null)
{
value = embedded.Load(name);
}
return value;
}
}
}
|
/*
* Copyright 2014, 2015 Dominick Baier, Brock Allen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.IO;
namespace IdentityServer3.Core.Services.Default
{
/// <summary>
/// View loader implementation that uses a combination of the file system view loader
/// and the embedded assets view loader. This allows for some templates to be defined
/// via the file system, while using the embedded assets templates for all others.
/// </summary>
public class FileSystemWithEmbeddedFallbackViewLoader : IViewLoader
{
readonly FileSystemViewLoader file;
readonly EmbeddedAssetsViewLoader embedded;
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
public FileSystemWithEmbeddedFallbackViewLoader()
: this(GetDefaultDirectory())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FileSystemWithEmbeddedFallbackViewLoader"/> class.
/// </summary>
/// <param name="directory">The directory.</param>
public FileSystemWithEmbeddedFallbackViewLoader(string directory)
{
this.file = new FileSystemViewLoader(directory);
this.embedded = new EmbeddedAssetsViewLoader();
}
static string GetDefaultDirectory()
{
var path = AppDomain.CurrentDomain.BaseDirectory;
path = Path.Combine(path, "assets");
return path;
}
/// <summary>
/// Loads the HTML for the named view.
/// </summary>
/// <param name="name">The name.</param>
/// <returns></returns>
public string Load(string name)
{
var value = file.Load(name);
if (value == null)
{
value = embedded.Load(name);
}
return value;
}
}
}
|
apache-2.0
|
C#
|
9057723e8e9dea8810e73f1bbb00517839727f78
|
update some validation messages
|
collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists,collinbarrett/FilterLists
|
src/FilterLists.Agent/Features/Urls/Models/ValidationResults/UrlValidationResult.cs
|
src/FilterLists.Agent/Features/Urls/Models/ValidationResults/UrlValidationResult.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace FilterLists.Agent.Features.Urls.Models.ValidationResults
{
public class UrlValidationResult
{
public UrlValidationResult(Uri url)
{
Url = url;
}
public Uri Url { get; }
public List<string> Messages { get; } = new List<string>();
public bool IsValid()
{
return !Messages.Any();
}
public void SetBroken()
{
Messages.Add("The URL is broken and should maybe be fixed, replaced, or removed.");
}
public void SetSupportsHttps()
{
Messages.Add("The URL is set to `http` but can support and should probably be changed to `https`.");
}
public void SetRedirectsTo(Uri uri)
{
Messages.Add($"The URL redirects and should maybe be changed to `{uri}`.");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace FilterLists.Agent.Features.Urls.Models.ValidationResults
{
public class UrlValidationResult
{
public UrlValidationResult(Uri url)
{
Url = url;
}
public Uri Url { get; }
public List<string> Messages { get; } = new List<string>();
public bool IsValid()
{
return !Messages.Any();
}
public void SetBroken()
{
Messages.Add("The URL is broken.");
}
public void SetSupportsHttps()
{
Messages.Add("The URL is set to http but can support https.");
}
public void SetRedirectsTo(Uri uri)
{
Messages.Add($"The URL redirects to {uri}.");
}
}
}
|
mit
|
C#
|
07c84513e20e7c2e6010b9bac3d4178fcfd6b096
|
fix Ably logging
|
StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis,StephenClearyApps/DotNetApis
|
service/DotNetApis.Common/AsyncLocalAblyLogger.cs
|
service/DotNetApis.Common/AsyncLocalAblyLogger.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotNetApis.Common.Internals;
using Microsoft.Extensions.Logging;
namespace DotNetApis.Common
{
/// <summary>
/// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created.
/// </summary>
public sealed class AsyncLocalAblyLogger : ILogger
{
private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>();
public static void TryCreate(string channelName, ILogger logger)
{
try
{
ImplicitChannel.Value = AblyService.CreateLogChannel(channelName);
}
catch (Exception ex)
{
logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message);
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
if (IsEnabled(logLevel))
ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception));
}
public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel >= LogLevel.Information;
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using DotNetApis.Common.Internals;
using Microsoft.Extensions.Logging;
namespace DotNetApis.Common
{
/// <summary>
/// A logger that attempts to write to an implicit Ably channel. This type can be safely created before its channel is created.
/// </summary>
public sealed class AsyncLocalAblyLogger : ILogger
{
private static readonly AsyncLocal<AblyChannel> ImplicitChannel = new AsyncLocal<AblyChannel>();
public static void TryCreate(string channelName, ILogger logger)
{
try
{
ImplicitChannel.Value = AblyService.CreateLogChannel(channelName);
}
catch (Exception ex)
{
logger.LogWarning(0, ex, "Could not initialize Ably: {exceptionMessage}", ex.Message);
}
}
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
{
ImplicitChannel.Value?.LogMessage(logLevel.ToString(), formatter(state, exception));
}
public bool IsEnabled(LogLevel logLevel) => ImplicitChannel.Value != null && logLevel > LogLevel.Information;
public IDisposable BeginScope<TState>(TState state) => throw new NotImplementedException();
}
}
|
mit
|
C#
|
22a5df6309aad3ab7f075c38e7617eee64c4c12c
|
Clear all transforms of catcher trail sprite before returned to pool
|
smoogipooo/osu,ppy/osu,peppy/osu,NeoAdonis/osu,ppy/osu,NeoAdonis/osu,UselessToucan/osu,peppy/osu,UselessToucan/osu,peppy/osu-new,peppy/osu,smoogipoo/osu,NeoAdonis/osu,UselessToucan/osu,smoogipoo/osu,ppy/osu,smoogipoo/osu
|
osu.Game.Rulesets.Catch/UI/CatcherTrailSprite.cs
|
osu.Game.Rulesets.Catch/UI/CatcherTrailSprite.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherTrailSprite : PoolableDrawable
{
public Texture Texture
{
set => sprite.Texture = value;
}
private readonly Sprite sprite;
public CatcherTrailSprite()
{
InternalChild = sprite = new Sprite
{
RelativeSizeAxes = Axes.Both
};
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
protected override void FreeAfterUse()
{
ClearTransforms();
base.FreeAfterUse();
}
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using osu.Framework.Graphics;
using osu.Framework.Graphics.Pooling;
using osu.Framework.Graphics.Sprites;
using osu.Framework.Graphics.Textures;
using osuTK;
namespace osu.Game.Rulesets.Catch.UI
{
public class CatcherTrailSprite : PoolableDrawable
{
public Texture Texture
{
set => sprite.Texture = value;
}
private readonly Sprite sprite;
public CatcherTrailSprite()
{
InternalChild = sprite = new Sprite
{
RelativeSizeAxes = Axes.Both
};
Size = new Vector2(CatcherArea.CATCHER_SIZE);
// Sets the origin roughly to the centre of the catcher's plate to allow for correct scaling.
OriginPosition = new Vector2(0.5f, 0.06f) * CatcherArea.CATCHER_SIZE;
}
}
}
|
mit
|
C#
|
1950622ab868475fa27773f707ebb256b0cb8e92
|
Make DataStreamFileProcedures internal
|
peppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,smoogipooo/osu-framework,ppy/osu-framework,ppy/osu-framework,peppy/osu-framework,peppy/osu-framework
|
osu.Framework/Audio/Callbacks/DataStreamFileProcedures.cs
|
osu.Framework/Audio/Callbacks/DataStreamFileProcedures.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.IO;
#nullable enable
namespace osu.Framework.Audio.Callbacks
{
/// <summary>
/// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>.
/// </summary>
internal class DataStreamFileProcedures : IFileProcedures
{
private readonly Stream dataStream;
public DataStreamFileProcedures(Stream data)
{
dataStream = data;
}
public void Close(IntPtr user)
{
}
public long Length(IntPtr user)
{
if (!dataStream.CanSeek) return 0;
try
{
return dataStream.Length;
}
catch
{
return 0;
}
}
public unsafe int Read(IntPtr buffer, int length, IntPtr user)
{
if (!dataStream.CanRead) return 0;
try
{
return dataStream.Read(new Span<byte>((void*)buffer, length));
}
catch
{
return 0;
}
}
public bool Seek(long offset, IntPtr user)
{
if (!dataStream.CanSeek) return false;
try
{
return dataStream.Seek(offset, SeekOrigin.Begin) == offset;
}
catch
{
return false;
}
}
}
}
|
// 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.IO;
#nullable enable
namespace osu.Framework.Audio.Callbacks
{
/// <summary>
/// Implementation of <see cref="IFileProcedures"/> that supports reading from a <see cref="Stream"/>.
/// </summary>
public class DataStreamFileProcedures : IFileProcedures
{
private readonly Stream dataStream;
public DataStreamFileProcedures(Stream data)
{
dataStream = data;
}
public void Close(IntPtr user)
{
}
public long Length(IntPtr user)
{
if (!dataStream.CanSeek) return 0;
try
{
return dataStream.Length;
}
catch
{
return 0;
}
}
public unsafe int Read(IntPtr buffer, int length, IntPtr user)
{
if (!dataStream.CanRead) return 0;
try
{
return dataStream.Read(new Span<byte>((void*)buffer, length));
}
catch
{
return 0;
}
}
public bool Seek(long offset, IntPtr user)
{
if (!dataStream.CanSeek) return false;
try
{
return dataStream.Seek(offset, SeekOrigin.Begin) == offset;
}
catch
{
return false;
}
}
}
}
|
mit
|
C#
|
beb86a8b44cd0e082bb6a420ec29d7bc4391fef1
|
change start and connection positions
|
qoollo/bricksdb
|
src/BriksDb.RedisInterface/Server/RedisToBriks.cs
|
src/BriksDb.RedisInterface/Server/RedisToBriks.cs
|
using System;
using BricksDb.RedisInterface.BriksCommunication;
using BricksDb.RedisInterface.Server.RedisOperations;
using Qoollo.Client.Configuration;
using Qoollo.Client.Support;
namespace BricksDb.RedisInterface.Server
{
class RedisToBriks : RedisToSmthSystem
{
private readonly RedisGate _redisGate;
public RedisToBriks()
{
_redisGate = new RedisGate(
new NetConfiguration(ConfigurationHelper.Instance.Localhost, 8000, Consts.WcfServiceName),
new ProxyConfiguration(Consts.ChangeDistributorTimeoutSec),
new CommonConfiguration(ConfigurationHelper.Instance.CountThreads));
}
protected override void InnerBuild(RedisMessageProcessor processor)
{
_redisGate.Build();
processor.AddOperation("SET", new RedisSet(_redisGate.RedisTable, "SET"));
processor.AddOperation("GET", new RedisGet(_redisGate.RedisTable, "GET"));
}
public override void Start()
{
_redisGate.Start();
var result = _redisGate.RedisTable.SayIAmHere(ConfigurationHelper.Instance.DistributorHost,
ConfigurationHelper.Instance.DistributorPort);
Console.WriteLine(result);
base.Start();
}
public override void Stop()
{
base.Stop();
_redisGate.Dispose();
}
}
}
|
using System;
using BricksDb.RedisInterface.BriksCommunication;
using BricksDb.RedisInterface.Server.RedisOperations;
using Qoollo.Client.Configuration;
using Qoollo.Client.Support;
namespace BricksDb.RedisInterface.Server
{
class RedisToBriks : RedisToSmthSystem
{
private readonly RedisGate _redisGate;
public RedisToBriks()
{
_redisGate = new RedisGate(
new NetConfiguration(RedisListener.LocalIpAddress().ToString(), 8000, Consts.WcfServiceName),
new ProxyConfiguration(Consts.ChangeDistributorTimeoutSec),
new CommonConfiguration(ConfigurationHelper.Instance.CountThreads));
_redisGate.Build();
}
private void ConnectToBriksDb()
{
var result = _redisGate.RedisTable.SayIAmHere(ConfigurationHelper.Instance.DistributorHost,
ConfigurationHelper.Instance.DistributorPort);
Console.WriteLine(result);
}
protected override void InnerBuild(RedisMessageProcessor processor)
{
processor.AddOperation("SET", new RedisSet(_redisGate.RedisTable, "SET"));
processor.AddOperation("GET", new RedisGet(_redisGate.RedisTable, "GET"));
}
public override void Start()
{
ConnectToBriksDb();
_redisGate.Start();
base.Start();
}
public override void Stop()
{
base.Stop();
_redisGate.Dispose();
}
}
}
|
agpl-3.0
|
C#
|
341a7266cb9e3a3c3f703b8dd65a365c808af918
|
Update AssemblyInfo.cs
|
csuffyy/Orc.FilterBuilder
|
src/FilterBuilder.Test/Properties/AssemblyInfo.cs
|
src/FilterBuilder.Test/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("Orc.FilterBuilder.Test.NET45")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Orc.FilterBuilder.Test.NET45")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
|
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("Orc.FilterBuilder.Test.NET45")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Orc.FilterBuilder.Test.NET45")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
mit
|
C#
|
0d27b1e78f4c845babc29c28e407a71bb8b2270b
|
Add caching to avoid unnecessary hashing.
|
peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,zanetdev/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,Glimpse/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,zanetdev/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,mike-kaufman/Glimpse.Prototype,Glimpse/Glimpse.Prototype,peterblazejewicz/Glimpse.Prototype,pranavkm/Glimpse.Prototype,Glimpse/Glimpse.Prototype,zanetdev/Glimpse.Prototype
|
src/Glimpse.Agent.Web/Inspectors/UserInspector.cs
|
src/Glimpse.Agent.Web/Inspectors/UserInspector.cs
|
using System;
using System.Collections.Concurrent;
using Glimpse.Agent.Web.Framework;
using Glimpse.Agent.Web.Message;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
namespace Glimpse.Agent.Web.Inspectors
{
public class UserInspector : Inspector
{
private readonly IAgentBroker _broker;
private const string GlimpseCookie = ".Glimpse.Session"; // TODO: Move this somewhere configurable
private readonly ConcurrentDictionary<string, string> _gravatarCache = new ConcurrentDictionary<string, string>();
private readonly ConcurrentDictionary<string, string> _crcCache = new ConcurrentDictionary<string, string>();
public UserInspector(IAgentBroker broker)
{
_broker = broker;
}
public override void After(HttpContext context)
{
var user = context.User;
var userId = user.FindFirst("sub")?.Value ?? user.FindFirst("NameIdentifier")?.Value ?? context.Request.Cookies[GlimpseCookie];
if (string.IsNullOrWhiteSpace(userId))
{
#warning TODO: Use Glimpse RequestId
userId = Guid.NewGuid().ToString(); // TODO: This should be the Glimpse request ID
var response = context.Features.Get<IHttpResponseFeature>();
if (!response.HasStarted)
{
context.Response.Cookies.Append(GlimpseCookie, userId);
}
}
var username = user.FindFirst("name")?.Value ?? _crcCache.GetOrAdd(userId, id => id.Crc16().ToUpper());
var email = user.FindFirst("email")?.Value;
var pic = user.FindFirst("picture")?.Value ?? _gravatarCache.GetOrAdd(email ?? userId, GenerateGravatarUrl);
_broker.SendMessage(new UserIdentification(userId, username, email, pic));
}
private string GenerateGravatarUrl(string email)
{
var preppedEmail = email.Trim().ToLower();
var hash = preppedEmail.Md5();
return $"http://www.gravatar.com/avatar/{hash}.jpg?d=identicon";
}
}
}
|
using System;
using Glimpse.Agent.Web.Framework;
using Glimpse.Agent.Web.Message;
using Microsoft.AspNet.Http;
using Microsoft.AspNet.Http.Features;
namespace Glimpse.Agent.Web.Inspectors
{
public class UserInspector : Inspector
{
private readonly IAgentBroker _broker;
private const string GlimpseCookie = ".Glimpse.Session";
public UserInspector(IAgentBroker broker)
{
_broker = broker;
}
public override void After(HttpContext context)
{
var user = context.User;
var userId = user.FindFirst("sub")?.Value ?? user.FindFirst("NameIdentifier")?.Value ?? context.Request.Cookies[GlimpseCookie];
if (string.IsNullOrWhiteSpace(userId))
{
#warning TODO: Use Glimpse RequestId
userId = Guid.NewGuid().ToString(); // TODO: This should be the Glimpse request ID
var response = context.Features.Get<IHttpResponseFeature>();
if (!response.HasStarted)
{
context.Response.Cookies.Append(GlimpseCookie, userId);
}
}
var username = user.FindFirst("name")?.Value ?? userId.Crc16().ToUpper();
var email = user.FindFirst("email")?.Value;
var pic = user.FindFirst("picture")?.Value ?? GenerateGravatarUrl(email ?? userId);
_broker.SendMessage(new UserIdentification(userId, username, email, pic));
}
private string GenerateGravatarUrl(string email)
{
var preppedEmail = email.Trim().ToLower();
var hash = preppedEmail.Md5();
return $"http://www.gravatar.com/avatar/{hash}.jpg?d=identicon";
}
}
}
|
mit
|
C#
|
e982f485c7bd5df017892b7d8dafeaa1f4d49a5e
|
Remove drop shadow from `RoundedButton`
|
peppy/osu,ppy/osu,NeoAdonis/osu,smoogipoo/osu,NeoAdonis/osu,smoogipoo/osu,ppy/osu,peppy/osu,smoogipoo/osu,peppy/osu-new,NeoAdonis/osu,peppy/osu,ppy/osu,smoogipooo/osu
|
osu.Game/Graphics/UserInterfaceV2/RoundedButton.cs
|
osu.Game/Graphics/UserInterfaceV2/RoundedButton.cs
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Game.Graphics.UserInterface;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class RoundedButton : OsuButton, IFilterable
{
public override float Height
{
get => base.Height;
set
{
base.Height = value;
if (IsLoaded)
updateCornerRadius();
}
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Blue3;
}
protected override void LoadComplete()
{
base.LoadComplete();
updateCornerRadius();
}
private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2;
public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() };
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
}
}
|
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System.Collections.Generic;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Effects;
using osu.Game.Graphics.UserInterface;
using osuTK;
namespace osu.Game.Graphics.UserInterfaceV2
{
public class RoundedButton : OsuButton, IFilterable
{
public override float Height
{
get => base.Height;
set
{
base.Height = value;
if (IsLoaded)
updateCornerRadius();
}
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Blue3;
Content.EdgeEffect = new EdgeEffectParameters
{
Type = EdgeEffectType.Shadow,
Offset = new Vector2(0, 2),
Radius = 4,
Colour = Colour4.Black.Opacity(0.15f)
};
}
protected override void LoadComplete()
{
base.LoadComplete();
updateCornerRadius();
}
private void updateCornerRadius() => Content.CornerRadius = DrawHeight / 2;
public virtual IEnumerable<string> FilterTerms => new[] { Text.ToString() };
public bool MatchingFilter
{
set => this.FadeTo(value ? 1 : 0);
}
public bool FilteringActive { get; set; }
}
}
|
mit
|
C#
|
01e5ca24e916f8506f386e86ea99239977a9be0e
|
Remove test on argument null exception message
|
johanclasson/Unity.Interception.Serilog
|
src/Unity.Interception.Serilog.Tests/NullTests.cs
|
src/Unity.Interception.Serilog.Tests/NullTests.cs
|
using System;
using FluentAssertions;
using Microsoft.Practices.Unity;
using Unity.Interception.Serilog.Tests.Support;
using Xunit;
namespace Unity.Interception.Serilog.Tests
{
public class NullTests
{
[Fact]
public void NullMembersShouldThrow()
{
var container = new UnityContainer();
Action[] actions = {
() => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null),
() => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null),
() => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null),
() => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null)
};
foreach (var action in actions)
{
action.ShouldThrow<ArgumentNullException>();
}
}
[Fact]
public void NullContainerShouldThrow()
{
Action[] actions = {
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null),
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""),
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()),
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager())
};
foreach (var action in actions)
{
action.ShouldThrow<ArgumentNullException>();
}
}
}
}
|
using System;
using FluentAssertions;
using Microsoft.Practices.Unity;
using Unity.Interception.Serilog.Tests.Support;
using Xunit;
namespace Unity.Interception.Serilog.Tests
{
public class NullTests
{
[Fact]
public void NullMembersShouldThrow()
{
var container = new UnityContainer();
Action[] actions = {
() => container.RegisterLoggedType<IDummy, Dummy>((InjectionMember[])null),
() => container.RegisterLoggedType<IDummy, Dummy>("", (InjectionMember[])null),
() => container.RegisterLoggedType<IDummy, Dummy>(new ContainerControlledLifetimeManager(), null),
() => container.RegisterLoggedType<IDummy, Dummy>("", new ContainerControlledLifetimeManager(), null)
};
foreach (var action in actions)
{
action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: first");
}
}
[Fact]
public void NullContainerShouldThrow()
{
Action[] actions = {
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null),
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, ""),
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, new ContainerControlledLifetimeManager()),
() => UnityContainerExtensions.RegisterLoggedType<IDummy, Dummy>(null, "", new ContainerControlledLifetimeManager())
};
foreach (var action in actions)
{
action.ShouldThrow<ArgumentNullException>().WithMessage("Value cannot be null.\nParameter name: container");
}
}
}
}
|
mit
|
C#
|
f346969f37928cafa2661b5d6b6cb557e7cdbbfc
|
Update BoundsImage.cs
|
Core2D/Core2D,wieslawsoltes/Core2D,Core2D/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D,wieslawsoltes/Core2D
|
src/Core2D/Editor/Bounds/Shapes/BoundsImage.cs
|
src/Core2D/Editor/Bounds/Shapes/BoundsImage.cs
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Core2D.Shapes;
using Spatial;
namespace Core2D.Editor.Bounds.Shapes
{
public class BoundsImage : IBounds
{
public Type TargetType => typeof(IImageShape);
public IPointShape TryToGetPoint(IBaseShape shape, Point2 target, double radius, IDictionary<Type, IBounds> registered)
{
if (!(shape is IImageShape image))
{
throw new ArgumentNullException(nameof(shape));
}
var pointHitTest = registered[typeof(IPointShape)];
if (pointHitTest.TryToGetPoint(image.TopLeft, target, radius, registered) != null)
{
return image.TopLeft;
}
if (pointHitTest.TryToGetPoint(image.BottomRight, target, radius, registered) != null)
{
return image.BottomRight;
}
return null;
}
public bool Contains(IBaseShape shape, Point2 target, double radius, IDictionary<Type, IBounds> registered)
{
if (!(shape is IImageShape image))
{
throw new ArgumentNullException(nameof(shape));
}
return Rect2.FromPoints(
image.TopLeft.X,
image.TopLeft.Y,
image.BottomRight.X,
image.BottomRight.Y).Contains(target);
}
public bool Overlaps(IBaseShape shape, Rect2 target, double radius, IDictionary<Type, IBounds> registered)
{
if (!(shape is IImageShape image))
{
throw new ArgumentNullException(nameof(shape));
}
return Rect2.FromPoints(
image.TopLeft.X,
image.TopLeft.Y,
image.BottomRight.X,
image.BottomRight.Y).IntersectsWith(target);
}
}
}
|
// Copyright (c) Wiesław Šoltés. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using Core2D.Shapes;
using Spatial;
namespace Core2D.Editor.Bounds.Shapes
{
public class BoundsImage : IBounds
{
public Type TargetType => typeof(IImageShape);
public IPointShape TryToGetPoint(IBaseShape shape, Point2 target, double radius, IDictionary<Type, IBounds> registered)
{
if (!(shape is IImageShape image))
throw new ArgumentNullException(nameof(shape));
var pointHitTest = registered[typeof(IPointShape)];
if (pointHitTest.TryToGetPoint(image.TopLeft, target, radius, registered) != null)
{
return image.TopLeft;
}
if (pointHitTest.TryToGetPoint(image.BottomRight, target, radius, registered) != null)
{
return image.BottomRight;
}
return null;
}
public bool Contains(IBaseShape shape, Point2 target, double radius, IDictionary<Type, IBounds> registered)
{
if (!(shape is IImageShape image))
throw new ArgumentNullException(nameof(shape));
return Rect2.FromPoints(
image.TopLeft.X,
image.TopLeft.Y,
image.BottomRight.X,
image.BottomRight.Y).Contains(target);
}
public bool Overlaps(IBaseShape shape, Rect2 target, double radius, IDictionary<Type, IBounds> registered)
{
if (!(shape is IImageShape image))
throw new ArgumentNullException(nameof(shape));
return Rect2.FromPoints(
image.TopLeft.X,
image.TopLeft.Y,
image.BottomRight.X,
image.BottomRight.Y).IntersectsWith(target);
}
}
}
|
mit
|
C#
|
642ff3cee8aedb9d32b9540d2584a9ca3edffc9f
|
Rename GetOption to GetMaybe in DictionaryExtensions.
|
muhbaasu/fx-sharp
|
src/FxSharp/Extensions/DictionaryExtensions.cs
|
src/FxSharp/Extensions/DictionaryExtensions.cs
|
using System.Collections.Generic;
namespace FxSharp.Extensions
{
/// <summary>
/// Extension methods for dictionaries.
/// </summary>
public static class DictionaryExtensions
{
/// <summary>
/// Get a value from a dictionary.
/// Unlike the normal dictionary method, it returns Maybe.Nothing if the key is not
/// present and wraps the value in Maybe.Just if a value for this key is present.
/// </summary>
/// <typeparam name="TKey">Dictionary key type.</typeparam>
/// <typeparam name="TValue">Dictionary value type.</typeparam>
/// <param name="dict">Dictionary to access.</param>
/// <param name="key">Key to look up.</param>
/// <returns>
/// Maybe.Just(T) when key is present, Maybe.Nothing(T) when key is not present.
/// </returns>
public static Maybe<TValue> GetMaybe<TKey, TValue>
(this IDictionary<TKey, TValue> dict, TKey key)
{
return dict.ContainsKey(key) ? Maybe.Just(dict[key]) : Maybe.Nothing<TValue>();
}
}
}
|
using System.Collections.Generic;
namespace FxSharp.Extensions
{
/// <summary>
/// Extension methods for dictionaries.
/// </summary>
public static class DictionaryExtensions
{
/// <summary>
/// Get a value from a dictionary.
/// Unlike the normal dictionary method, it returns Maybe.Nothing if the key is not
/// present and wraps the value in Maybe.Just if a value for this key is present.
/// </summary>
/// <typeparam name="TKey">Dictionary key type.</typeparam>
/// <typeparam name="TValue">Dictionary value type.</typeparam>
/// <param name="dict">Dictionary to access.</param>
/// <param name="key">Key to look up.</param>
/// <returns>
/// Maybe.Just(T) when key is present, Maybe.Nothing(T) when key is not present.
/// </returns>
public static Maybe<TValue> GetOption<TKey, TValue>
(this IDictionary<TKey, TValue> dict, TKey key)
{
return dict.ContainsKey(key) ? Maybe.Just(dict[key]) : Maybe.Nothing<TValue>();
}
}
}
|
apache-2.0
|
C#
|
a17ff3e72b2fcb73adb9fb21aa482404ce10d2e9
|
simplify null management
|
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?.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#
|
211591c2ddb30a16fd4d8915430da30c4d308d88
|
Update player container
|
dncuug/dot-net.in.ua,dncuug/dot-net.in.ua,dncuug/dot-net.in.ua
|
src/WebSite/Views/Shared/_EmbededPlayer.cshtml
|
src/WebSite/Views/Shared/_EmbededPlayer.cshtml
|
@model string
@if(Model.Contains("iframe")) {
<section>
@Html.Raw(Model)
</section>
} else {
<div class="youtube-container">
<iframe class="video" src="@Model" frameborder="0" allowfullscreen>
</iframe>
</div>
}
|
@model string
<div class="youtube-container">
<iframe class="video" src="@Model" frameborder="0" allowfullscreen>
</iframe>
</div>
|
mit
|
C#
|
f4040e1a365d0aebbf5f544e2bc192c6f2f1285b
|
Remove org chart link
|
mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander,mattgwagner/Battery-Commander
|
Battery-Commander.Web/Views/Units/List.cshtml
|
Battery-Commander.Web/Views/Units/List.cshtml
|
@model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { unit.Id })
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
</td>
</tr>
}
</tbody>
</table>
|
@model IEnumerable<Unit>
<div class="page-header">
<h1>Units @Html.ActionLink("Add New", "New", "Units", null, new { @class = "btn btn-default" })</h1>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().Name)</th>
<th>@Html.DisplayNameFor(_ => _.FirstOrDefault().UIC)</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var unit in Model)
{
<tr>
<td>@Html.DisplayFor(s => unit)</td>
<td>@Html.DisplayFor(s => unit.UIC)</td>
<td>
@Html.ActionLink("Edit", "Edit", new { unit.Id })
@Html.ActionLink("Soldiers", "Index", "Soldiers", new { unit = unit.Id })
@Html.ActionLink("Org Chart", "Details", new { unit.Id })
</td>
</tr>
}
</tbody>
</table>
|
mit
|
C#
|
7afb5a31e86cdd4acc0d4abadcae85cdd47ee2d9
|
Add a unit test for the StringPattern class
|
openchain/openchain
|
test/Openchain.Ledger.Tests/StringPatternTests.cs
|
test/Openchain.Ledger.Tests/StringPatternTests.cs
|
// Copyright 2015 Coinprism, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using Openchain.Ledger.Validation;
using Xunit;
namespace Openchain.Ledger.Tests
{
public class StringPatternTests
{
[Fact]
public void IsMatch_Success()
{
Assert.True(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name_suffix"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nam"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nams"));
Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name"));
Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name_suffix"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nam"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nams"));
}
[Fact]
public void IsMatch_InvalidMatchingStrategy()
{
StringPattern pattern = new StringPattern("name", (PatternMatchingStrategy)1000);
Assert.Throws<ArgumentOutOfRangeException>(() => pattern.IsMatch("name"));
}
}
}
|
// Copyright 2015 Coinprism, 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 Openchain.Ledger.Validation;
using Xunit;
namespace Openchain.Ledger.Tests
{
public class StringPatternTests
{
[Fact]
public void IsMatch_Success()
{
Assert.True(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("name_suffix"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nam"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Exact).IsMatch("nams"));
Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name"));
Assert.True(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("name_suffix"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nam"));
Assert.False(new StringPattern("name", PatternMatchingStrategy.Prefix).IsMatch("nams"));
}
}
}
|
apache-2.0
|
C#
|
768c7570873126789afd0304b8d405ccd33ae51b
|
check UIContext in demo
|
tibel/Caliburn.Light
|
samples/Demo.ExceptionHandling/ShellViewModel.cs
|
samples/Demo.ExceptionHandling/ShellViewModel.cs
|
using System;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Caliburn.Light;
using Weakly;
namespace Demo.ExceptionHandling
{
public class ShellViewModel : BindableObject
{
public ShellViewModel()
{
ExecuteCommand = DelegateCommand.Create(OnExecute);
UIContextRunCommand = DelegateCommand.Create(OnUIContextRun);
TaskRunCommand = DelegateCommand.Create(OnTaskRun);
AsyncCommand = DelegateCommand.CreateAsync(OnAsync);
}
public ICommand ExecuteCommand { get; private set; }
public ICommand UIContextRunCommand { get; private set; }
public ICommand TaskRunCommand { get; private set; }
public ICommand AsyncCommand { get; private set; }
private void OnExecute()
{
Debug.Assert(UIContext.CheckAccess());
throw new InvalidOperationException("Error on execute.");
}
private void OnUIContextRun()
{
Task.Run(() =>
{
Debug.Assert(!UIContext.CheckAccess());
Thread.Sleep(100);
UIContext.Run(new Action(() =>
{
Debug.Assert(UIContext.CheckAccess());
Thread.Sleep(100);
throw new InvalidOperationException("Error on a background Task.");
})).ObserveException();
}).ObserveException();
}
private void OnTaskRun()
{
Task.Run(() =>
{
Debug.Assert(!UIContext.CheckAccess());
Thread.Sleep(100);
throw new InvalidOperationException("Error on a background Task.");
}).ObserveException();
}
private async Task OnAsync()
{
Debug.Assert(UIContext.CheckAccess());
await Task.Delay(100);
Debug.Assert(UIContext.CheckAccess());
throw new InvalidOperationException("Error on async execute.");
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using Caliburn.Light;
using Weakly;
namespace Demo.ExceptionHandling
{
public class ShellViewModel : BindableObject
{
public ShellViewModel()
{
ExecuteCommand = DelegateCommand.Create(OnExecute);
UIContextRunCommand = DelegateCommand.Create(OnUIContextRun);
TaskRunCommand = DelegateCommand.Create(OnTaskRun);
AsyncCommand = DelegateCommand.CreateAsync(OnAsync);
}
public ICommand ExecuteCommand { get; private set; }
public ICommand UIContextRunCommand { get; private set; }
public ICommand TaskRunCommand { get; private set; }
public ICommand AsyncCommand { get; private set; }
private void OnExecute()
{
throw new InvalidOperationException("Error on execute.");
}
private void OnUIContextRun()
{
Task.Run(() =>
{
Thread.Sleep(100);
UIContext.Run(new Action(() =>
{
Thread.Sleep(100);
throw new InvalidOperationException("Error on a background Task.");
})).ObserveException();
}).ObserveException();
}
private void OnTaskRun()
{
Task.Run(() =>
{
Thread.Sleep(100);
throw new InvalidOperationException("Error on a background Task.");
}).ObserveException();
}
private async Task OnAsync()
{
await Task.Delay(100);
throw new InvalidOperationException("Error on async execute.");
}
}
}
|
mit
|
C#
|
d19f93aa5633ae523ed43275f264ac49dcf08cfc
|
Remove redundant method call
|
martincostello/project-euler
|
src/ProjectEuler/Puzzles/Puzzle024.cs
|
src/ProjectEuler/Puzzles/Puzzle024.cs
|
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=24</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle024 : Puzzle
{
/// <inheritdoc />
public override string Question => "What is the millionth lexicographic permutation of the digits 0-9?";
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
var collection = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var millionthPermutation = Maths.Permutations(collection)
.Skip(999999)
.First()
.ToList();
Answer = Maths.FromDigits(millionthPermutation);
return 0;
}
}
}
|
// Copyright (c) Martin Costello, 2015. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
namespace MartinCostello.ProjectEuler.Puzzles
{
using System.Linq;
/// <summary>
/// A class representing the solution to <c>https://projecteuler.net/problem=24</c>. This class cannot be inherited.
/// </summary>
internal sealed class Puzzle024 : Puzzle
{
/// <inheritdoc />
public override string Question => "What is the millionth lexicographic permutation of the digits 0-9?";
/// <inheritdoc />
protected override int SolveCore(string[] args)
{
var collection = new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
var millionthPermutation = Maths.Permutations(collection)
.Skip(999999)
.Take(1)
.First()
.ToList();
Answer = Maths.FromDigits(millionthPermutation);
return 0;
}
}
}
|
apache-2.0
|
C#
|
2e62edf9cdb7f15a9ecf5ff8a329af56f30ff4c7
|
clean up
|
jonnii/SpeakEasy
|
src/SpeakEasy/TransmissionSettings.cs
|
src/SpeakEasy/TransmissionSettings.cs
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SpeakEasy.Serializers;
namespace SpeakEasy
{
public class TransmissionSettings : ITransmissionSettings
{
private readonly IEnumerable<ISerializer> serializers;
public TransmissionSettings(IEnumerable<ISerializer> serializers)
{
this.serializers = serializers;
}
public ISerializer DefaultSerializer => serializers.First();
public string DefaultSerializerContentType => DefaultSerializer.MediaType;
public IEnumerable<string> DeserializableMediaTypes
{
get { return serializers.SelectMany(d => d.SupportedMediaTypes).Distinct(); }
}
public Task SerializeAsync<T>(Stream stream, T body)
{
return DefaultSerializer.SerializeAsync(stream, body);
}
public ISerializer FindSerializer(string contentType)
{
var deserializer = serializers.FirstOrDefault(d => d.SupportedMediaTypes.Any(contentType.StartsWith));
return deserializer ?? new NullSerializer(contentType);
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using SpeakEasy.Serializers;
namespace SpeakEasy
{
public class TransmissionSettings : ITransmissionSettings
{
private readonly IEnumerable<ISerializer> serializers;
public TransmissionSettings(IEnumerable<ISerializer> serializers)
{
this.serializers = serializers;
}
public ISerializer DefaultSerializer
{
get { return serializers.First(); }
}
public string DefaultSerializerContentType
{
get { return DefaultSerializer.MediaType; }
}
public IEnumerable<string> DeserializableMediaTypes
{
get { return serializers.SelectMany(d => d.SupportedMediaTypes).Distinct(); }
}
public Task SerializeAsync<T>(Stream stream, T body)
{
return DefaultSerializer.SerializeAsync(stream, body);
}
public ISerializer FindSerializer(string contentType)
{
var deserializer = serializers.FirstOrDefault(d => d.SupportedMediaTypes.Any(contentType.StartsWith));
return deserializer ?? new NullSerializer(contentType);
}
}
}
|
apache-2.0
|
C#
|
e1220e1e602cea658cecb4cbd65382ac6a8ca7b7
|
Add Parser#ctor
|
lury-lang/lury-parser,lury-lang/lury-parser
|
lury-parser/Parser.cs
|
lury-parser/Parser.cs
|
//
// JayAdapt.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using Lury.Compiling.Logger;
using Lury.Compiling.Parser.Tree;
using LToken = Lury.Compiling.Lexer.Token;
namespace Lury.Compiling.Parser
{
public class Parser
{
#region -- Private Fields --
private readonly IEnumerable<LToken> input;
private IReadOnlyList<Node> output;
#endregion
#region -- Public Properties --
public IReadOnlyList<Node> TreeOutput
{
get
{
if (!this.IsFinished)
throw new InvalidOperationException("先に Parse メソッドを実行してください。");
return this.output;
}
}
public OutputLogger Logger { get; private set; }
public bool IsFinished { get; private set; }
#endregion
#region -- Constructors --
public Parser(IEnumerable<LToken> input)
{
if (input == null)
throw new ArgumentNullException("input");
this.input = input;
}
#endregion
#region -- Public Methods --
public bool Parse()
{
if (this.IsFinished)
throw new InvalidOperationException("Parsing is already finished.");
var parser = new FileParser();
this.output = (IReadOnlyList<Node>)parser.yyparse(new Lex2yyInput(this.input));
this.IsFinished = true;
return true;
}
#endregion
}
}
|
//
// JayAdapt.cs
//
// Author:
// Tomona Nanase <nanase@users.noreply.github.com>
//
// The MIT License (MIT)
//
// Copyright (c) 2015 Tomona Nanase
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Collections.Generic;
using Lury.Compiling.Logger;
using Lury.Compiling.Parser.Tree;
using LToken = Lury.Compiling.Lexer.Token;
namespace Lury.Compiling.Parser
{
public class Parser
{
#region -- Private Fields --
private IEnumerable<Node> output;
#endregion
#region -- Public Properties --
public IEnumerable<Node> TreeOutput
{
get
{
if (!this.IsFinished)
throw new InvalidOperationException("先に Parse メソッドを実行してください。");
return this.output;
}
}
public OutputLogger Logger { get; private set; }
public bool IsFinished { get; private set; }
#endregion
#region -- Public Methods --
public bool Parse(IEnumerable<LToken> input)
{
if (this.IsFinished)
throw new InvalidOperationException("Parsing is already finished.");
var parser = new FileParser();
this.output = (IEnumerable<Node>)parser.yyparse(new Lex2yyInput(input));
this.IsFinished = true;
return true;
}
#endregion
}
}
|
mit
|
C#
|
315f2b5b30644742a41f7974bc322e1ef2eb02fe
|
Update TemplateService.cs
|
loresoft/Estimatorx,loresoft/Estimatorx
|
src/EstimatorX.Core/Services/TemplateService.cs
|
src/EstimatorX.Core/Services/TemplateService.cs
|
using System.Security.Principal;
using AutoMapper;
using EstimatorX.Core.Repositories;
using EstimatorX.Shared.Definitions;
using EstimatorX.Shared.Extensions;
using EstimatorX.Shared.Models;
using EstimatorX.Shared.Services;
using Microsoft.Extensions.Logging;
namespace EstimatorX.Core.Services;
public class TemplateService : OrganizationServiceBase<ITemplateRepository, Template>, ITemplateService, IServiceTransient
{
private readonly IProjectBuilder _projectBuilder;
private readonly IProjectCalculator _projectCalculator;
public TemplateService(ILoggerFactory loggerFactory, IMapper mapper, ITemplateRepository repository, IUserCache userCache, IProjectBuilder projectBuilder, IProjectCalculator projectCalculator)
: base(loggerFactory, mapper, repository, userCache)
{
_projectBuilder = projectBuilder;
_projectCalculator = projectCalculator;
}
public override Task<Template> Save(string id, string partitionKey, Template model, IPrincipal principal, CancellationToken cancellationToken)
{
// ensure valid settings
_projectBuilder.UpdateSettings(model.Settings);
// re-calculate the computed values
_projectCalculator.UpdateProject(model);
return base.Save(id, partitionKey, model, principal, cancellationToken);
}
public override Task<Template> Create(Template model, IPrincipal principal, CancellationToken cancellationToken)
{
// ensure valid settings
_projectBuilder.UpdateSettings(model.Settings, true);
// re-calculate the computed values
_projectCalculator.UpdateProject(model);
return base.Create(model, principal, cancellationToken);
}
protected override IQueryable<Template> SearchQuery(IQueryable<Template> query, string searchTerm)
{
if (searchTerm.IsNullOrWhiteSpace())
return query;
return query
.Where(u =>
u.Name.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase) ||
u.Description.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase)
);
}
}
|
using AutoMapper;
using EstimatorX.Core.Repositories;
using EstimatorX.Shared.Definitions;
using EstimatorX.Shared.Extensions;
using EstimatorX.Shared.Models;
using Microsoft.Extensions.Logging;
namespace EstimatorX.Core.Services;
public class TemplateService : OrganizationServiceBase<ITemplateRepository, Template>, ITemplateService, IServiceTransient
{
public TemplateService(ILoggerFactory loggerFactory, IMapper mapper, ITemplateRepository repository, IUserCache userCache)
: base(loggerFactory, mapper, repository, userCache)
{
}
protected override IQueryable<Template> SearchQuery(IQueryable<Template> query, string searchTerm)
{
if (searchTerm.IsNullOrWhiteSpace())
return query;
return query
.Where(u =>
u.Name.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase) ||
u.Description.Contains(searchTerm, StringComparison.InvariantCultureIgnoreCase)
);
}
}
|
mit
|
C#
|
41accce91cdbfef5c41e9da4c13093d2ddcadb97
|
rename dictionary-based signature parameter to allow matching specific method signature by parameter name
|
jeffijoe/messageformat.net
|
src/Jeffijoe.MessageFormat/IMessageFormatter.cs
|
src/Jeffijoe.MessageFormat/IMessageFormatter.cs
|
// MessageFormat for .NET
// - IMessageFormatter.cs
// Author: Jeff Hansen <jeff@jeffijoe.com>
// Copyright (C) Jeff Hansen 2014. All rights reserved.
using System.Collections.Generic;
namespace Jeffijoe.MessageFormat
{
/// <summary>
/// The magical Message Formatter.
/// </summary>
public interface IMessageFormatter
{
#region Public Methods and Operators
/// <summary>
/// Formats the message with the specified arguments. It's so magical.
/// </summary>
/// <param name="pattern">
/// The pattern.
/// </param>
/// <param name="argsMap">
/// The arguments.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
string FormatMessage(string pattern, IDictionary<string, object> argsMap);
/// <summary>
/// Formats the message, and uses reflection to create a dictionary of property values from the specified object.
/// </summary>
/// <param name="pattern">
/// The pattern.
/// </param>
/// <param name="args">
/// The arguments.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
string FormatMessage(string pattern, object args);
#endregion
}
}
|
// MessageFormat for .NET
// - IMessageFormatter.cs
// Author: Jeff Hansen <jeff@jeffijoe.com>
// Copyright (C) Jeff Hansen 2014. All rights reserved.
using System.Collections.Generic;
namespace Jeffijoe.MessageFormat
{
/// <summary>
/// The magical Message Formatter.
/// </summary>
public interface IMessageFormatter
{
#region Public Methods and Operators
/// <summary>
/// Formats the message with the specified arguments. It's so magical.
/// </summary>
/// <param name="pattern">
/// The pattern.
/// </param>
/// <param name="args">
/// The arguments.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
string FormatMessage(string pattern, IDictionary<string, object> args);
/// <summary>
/// Formats the message, and uses reflection to create a dictionary of property values from the specified object.
/// </summary>
/// <param name="pattern">
/// The pattern.
/// </param>
/// <param name="args">
/// The arguments.
/// </param>
/// <returns>
/// The <see cref="string" />.
/// </returns>
string FormatMessage(string pattern, object args);
#endregion
}
}
|
mit
|
C#
|
afdfeb578966593681699c423ed970da01cebad3
|
Add option to install command
|
Brad-Christie/Sitecore-Instance-Manager,Sitecore/Sitecore-Instance-Manager,sergeyshushlyapin/Sitecore-Instance-Manager
|
src/SIM.Client/Commands/InstallCommandFacade.cs
|
src/SIM.Client/Commands/InstallCommandFacade.cs
|
namespace SIM.Client.Commands
{
using CommandLine;
using JetBrains.Annotations;
using SIM.Core.Commands;
public class InstallCommandFacade : InstallCommand
{
[UsedImplicitly]
public InstallCommandFacade()
{
}
[Option('n', "name", Required = true)]
public override string Name { get; set; }
[Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")]
public override string SqlPrefix { get; set; }
[Option('p', "product")]
public override string Product { get; set; }
[Option('v', "version")]
public override string Version { get; set; }
[Option('r', "revision")]
public override string Revision { get; set; }
[Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)]
public override bool? AttachDatabases { get; set; }
[Option('u', "skipUnnecessaryFiles", HelpText = "Skip unnecessary files to speed up installation", DefaultValue = AttachDatabasesDefault)]
public override bool? SkipUnnecessaryFiles { get; set; }
}
}
|
namespace SIM.Client.Commands
{
using CommandLine;
using JetBrains.Annotations;
using SIM.Core.Commands;
public class InstallCommandFacade : InstallCommand
{
[UsedImplicitly]
public InstallCommandFacade()
{
}
[Option('n', "name", Required = true)]
public override string Name { get; set; }
[Option('s', "sqlPrefix", HelpText = "Logical names prefix of SQL databases, by default equals to instance name")]
public override string SqlPrefix { get; set; }
[Option('p', "product")]
public override string Product { get; set; }
[Option('v', "version")]
public override string Version { get; set; }
[Option('r', "revision")]
public override string Revision { get; set; }
[Option('a', "attach", HelpText = "Attach SQL databases, or just update ConnectionStrings.config", DefaultValue = AttachDatabasesDefault)]
public override bool? AttachDatabases { get; set; }
}
}
|
mit
|
C#
|
e25ea70e29e8b70e447e1c8703398e711ce01fac
|
change version to 3.0
|
velyo/dotnet-data-access
|
src/Artem.Data.Access/Properties/AssemblyInfo.cs
|
src/Artem.Data.Access/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
[assembly: AssemblyTitle("Artem.Data.Access")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Artem")]
[assembly: AssemblyProduct("Artem.Data.Access")]
[assembly: AssemblyCopyright("Copyright Artem 2005")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1823068a-3a7f-4031-941f-2e3224e330ef")]
[assembly: AssemblyVersion("3.0.*")]
[assembly: AllowPartiallyTrustedCallers]
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Security;
[assembly: AssemblyTitle("Artem.Data.Access")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Artem")]
[assembly: AssemblyProduct("Artem.Data.Access")]
[assembly: AssemblyCopyright("Copyright Artem 2005")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("1823068a-3a7f-4031-941f-2e3224e330ef")]
[assembly: AssemblyVersion("2.3.0.0")]
[assembly: AssemblyFileVersion("2.3.0.0")]
[assembly: AllowPartiallyTrustedCallers]
|
mit
|
C#
|
4f19ddaac6147fdb31c6f1979acc0798912a3495
|
change default autocomplete documentation setting to false
|
x335/omnisharp-server,syl20bnr/omnisharp-server,corngood/omnisharp-server,OmniSharp/omnisharp-server,syl20bnr/omnisharp-server,x335/omnisharp-server,svermeulen/omnisharp-server,corngood/omnisharp-server
|
OmniSharp/AutoComplete/AutoCompleteRequest.cs
|
OmniSharp/AutoComplete/AutoCompleteRequest.cs
|
using OmniSharp.Common;
namespace OmniSharp.AutoComplete
{
public class AutoCompleteRequest : Request
{
private string _wordToComplete;
public string WordToComplete {
get {
return _wordToComplete ?? "";
}
set {
_wordToComplete = value;
}
}
private bool _wantDocumentationForEveryCompletionResult = false;
private bool _wantImportableTypes = false;
/// <summary>
/// Specifies whether to return the code documentation for
/// each and every returned autocomplete result.
/// </summary>
public bool WantDocumentationForEveryCompletionResult {
get { return _wantDocumentationForEveryCompletionResult; }
set { _wantDocumentationForEveryCompletionResult = value; }
}
/// <summary>
/// Specifies whether to return importable types. Defaults to
/// false. Can be turned off to get a small speed boost.
/// </summary>
public bool WantImportableTypes {
get { return _wantImportableTypes; }
set { _wantImportableTypes = value; }
}
}
}
|
using OmniSharp.Common;
namespace OmniSharp.AutoComplete
{
public class AutoCompleteRequest : Request
{
private string _wordToComplete;
public string WordToComplete {
get {
return _wordToComplete ?? "";
}
set {
_wordToComplete = value;
}
}
private bool _wantDocumentationForEveryCompletionResult = true;
private bool _wantImportableTypes = false;
/// <summary>
/// Specifies whether to return the code documentation for
/// each and every returned autocomplete result. Defaults to
/// true. Can be turned off to get a small speed boost.
/// </summary>
public bool WantDocumentationForEveryCompletionResult {
get { return _wantDocumentationForEveryCompletionResult; }
set { _wantDocumentationForEveryCompletionResult = value; }
}
/// <summary>
/// Specifies whether to return importable types. Defaults to
/// false. Can be turned off to get a small speed boost.
/// </summary>
public bool WantImportableTypes {
get { return _wantImportableTypes; }
set { _wantImportableTypes = value; }
}
}
}
|
mit
|
C#
|
ece5df5795baa8051bf66b7e1b5c4424d783ade2
|
Clean up TreeWalkerExtensions.GetAncestors
|
jasonmcboyd/Treenumerable
|
Source/Treenumerable/TreeWalkerExtensions/TreeWalkerExtensions.GetAncestors.cs
|
Source/Treenumerable/TreeWalkerExtensions/TreeWalkerExtensions.GetAncestors.cs
|
using System;
using System.Collections.Generic;
namespace Treenumerable
{
public static partial class TreeWalkerExtensions
{
/// <summary>
/// Gets a node's ancestors, starting with its parent node and ending with the root node.
/// </summary>
/// <typeparam name="T">The type of elements in the tree.</typeparam>
/// <param name="walker">
/// The <see cref="ITreeWalker<T>"/> that knows how to find the parent and child nodes.
/// </param>
/// <param name="node">
/// The node whose ancestors are to be returned.
/// </param>
/// <returns>
/// An <see cref="System.Collections.Generic.IEnumerable<T>"/> that contains all of the
/// node's ancestors, up to and including the root.
/// </returns>
public static IEnumerable<T> GetAncestors<T>(this ITreeWalker<T> walker, T node)
{
// Validate parameters.
if (walker == null)
{
throw new ArgumentNullException("walker");
}
if (node == null)
{
throw new ArgumentNullException("node");
}
// Return each ancestor node starting with the parent and ending with the root node.
while (walker.TryGetParent(node, out node))
{
yield return node;
}
}
}
}
|
using System;
using System.Collections.Generic;
namespace Treenumerable
{
public static partial class TreeWalkerExtensions
{
/// <summary>
/// Gets a nodes ancestors, starting with its parent node and ending with the root node.
/// </summary>
/// <typeparam name="T">The type of elements in the tree.</typeparam>
/// <param name="walker">
/// The <see cref="ITreeWalker<T>"/> that knows how to find the parent and child nodes.
/// </param>
/// <param name="node">
/// The node whose ancestors are to be returned.
/// </param>
/// <returns>
/// An <see cref="System.Collections.Generic.IEnumerable<T>"/> that contains all the nodes
/// ancestors, up to and including the root.
/// </returns>
public static IEnumerable<T> GetAncestors<T>(this ITreeWalker<T> walker, T node)
{
// Validate parameters.
if (walker == null)
{
throw new ArgumentNullException("walker");
}
if (node == null)
{
throw new ArgumentNullException("node");
}
// Get and return each parent node iteratively.
//ParentNode<T> parentNode = walker.GetParentNode(node);
//while (parentNode.HasValue)
//{
// yield return parentNode.Value;
// parentNode = walker.GetParentNode(parentNode.Value);
//}
while (walker.TryGetParent(node, out node))
{
yield return node;
}
}
}
}
|
mit
|
C#
|
8df710d623daf34ad3d65c14c27440c7ff0c3f87
|
Update PlatformFamily.cs
|
wangkanai/Detection
|
src/Wangkanai.Detection.Platform/PlatformFamily.cs
|
src/Wangkanai.Detection.Platform/PlatformFamily.cs
|
// Copyright (c) 2016 Sarin Na Wangkanai, All Rights Reserved.
// The GNU GPLv3. See License.txt in the project root for license information.
namespace Wangkanai.Detection
{
public enum PlatformFamily
{
Windows,
Mac,
iOS,
Android,
Linux,
Other
}
}
|
// Copyright (c) 2016 Sarin Na Wangkanai, All Rights Reserved.
// The GNU GPLv3. See License.txt in the project root for license information.
namespace Wangkanai.Detection
{
public enum PlatformFamily
{
Windows,
Mac,
iOS,
Andriod,
Linux,
Other
}
}
|
apache-2.0
|
C#
|
336218032ede9654b90a883a53505efcf4e976f1
|
fix value getter on product attribute
|
wilcommerce/Wilcommerce.Catalog
|
src/Wilcommerce.Catalog/Models/ProductAttribute.cs
|
src/Wilcommerce.Catalog/Models/ProductAttribute.cs
|
using Newtonsoft.Json;
using System;
namespace Wilcommerce.Catalog.Models
{
/// <summary>
/// Represent a product custom attribute
/// </summary>
public class ProductAttribute
{
/// <summary>
/// Get or set the attribute's id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Get the serialized value
/// </summary>
public string _Value { get; protected set; }
/// <summary>
/// Get or set the attribute's value
/// </summary>
public object Value
{
get => JsonConvert.DeserializeObject(_Value);
set
{
_Value = JsonConvert.SerializeObject(value);
}
}
/// <summary>
/// Get or set the attribute's product reference
/// </summary>
public virtual Product Product { get; set; }
/// <summary>
/// Get or set the attribute's custom attribute reference
/// </summary>
public virtual CustomAttribute Attribute { get; set; }
}
}
|
using Newtonsoft.Json;
using System;
namespace Wilcommerce.Catalog.Models
{
/// <summary>
/// Represent a product custom attribute
/// </summary>
public class ProductAttribute
{
/// <summary>
/// Get or set the attribute's id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// Get the serialized value
/// </summary>
public string _Value { get; protected set; }
/// <summary>
/// Get or set the attribute's value
/// </summary>
public object Value
{
get => JsonConvert.DeserializeObject<object>(_Value);
set
{
_Value = JsonConvert.SerializeObject(value);
}
}
/// <summary>
/// Get or set the attribute's product reference
/// </summary>
public virtual Product Product { get; set; }
/// <summary>
/// Get or set the attribute's custom attribute reference
/// </summary>
public virtual CustomAttribute Attribute { get; set; }
}
}
|
mit
|
C#
|
6ddab5650f1f87f64c8674e39d15d91a3ca4dcf4
|
Fix spelling mistake, 'collission' => 'collision'
|
mysticmind/marten,ericgreenmix/marten,ericgreenmix/marten,ericgreenmix/marten,mysticmind/marten,JasperFx/Marten,JasperFx/Marten,mysticmind/marten,mysticmind/marten,mdissel/Marten,ericgreenmix/marten,mdissel/Marten,JasperFx/Marten
|
src/Marten/Services/ConcurrentUpdateException.cs
|
src/Marten/Services/ConcurrentUpdateException.cs
|
using System;
namespace Marten.Services
{
public class ConcurrentUpdateException : Exception
{
public ConcurrentUpdateException(Exception innerException) : base("Write collision detected while commiting the transaction.", innerException)
{
}
}
}
|
using System;
namespace Marten.Services
{
public class ConcurrentUpdateException : Exception
{
public ConcurrentUpdateException(Exception innerException) : base("Write collission detected while commiting the transaction.", innerException)
{
}
}
}
|
mit
|
C#
|
baa1e5933d7715cde2b057519d55397da25c76ea
|
Fix regression causing allowing each worker to execute twice after stop requested
|
printerpam/purpleonion,neoeinstein/purpleonion,printerpam/purpleonion
|
src/Xpdm.PurpleOnion/OnionGenerator.cs
|
src/Xpdm.PurpleOnion/OnionGenerator.cs
|
using System;
using System.ComponentModel;
namespace Xpdm.PurpleOnion
{
class OnionGenerator
{
private readonly BackgroundWorker worker = new BackgroundWorker();
public bool Running { get; protected set; }
public bool StopRequested { get; protected set; }
public OnionGenerator()
{
worker.DoWork += GenerateOnion;
worker.RunWorkerCompleted += RunWorkerCompleted;
}
public event EventHandler<OnionGeneratedEventArgs> OnionGenerated;
public void Start()
{
Running = true;
worker.RunWorkerAsync();
}
public void Stop()
{
StopRequested = true;
}
protected virtual void GenerateOnion(object sender, DoWorkEventArgs e)
{
if (StopRequested)
{
e.Cancel = true;
return;
}
OnionAddress onion = OnionAddress.Create();
e.Result = onion;
if (StopRequested)
{
e.Cancel = true;
}
}
protected virtual void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled || StopRequested)
{
Running = false;
StopRequested = false;
return;
}
OnionGeneratedEventArgs args = new OnionGeneratedEventArgs {
Result = (OnionAddress) e.Result,
};
OnOnionGenerated(args);
if (!args.Cancel)
{
worker.RunWorkerAsync();
}
else
{
Running = false;
StopRequested = false;
}
}
protected virtual void OnOnionGenerated(OnionGeneratedEventArgs e)
{
EventHandler<OnionGeneratedEventArgs> handler = OnionGenerated;
if (handler != null)
{
handler(this, e);
}
}
public class OnionGeneratedEventArgs : EventArgs {
new internal static readonly OnionGeneratedEventArgs Empty = new OnionGeneratedEventArgs();
public bool Cancel { get; set; }
public OnionAddress Result { get; set; }
}
}
}
|
using System;
using System.ComponentModel;
namespace Xpdm.PurpleOnion
{
class OnionGenerator
{
private readonly BackgroundWorker worker = new BackgroundWorker();
public bool Running { get; protected set; }
public OnionGenerator()
{
worker.DoWork += GenerateOnion;
worker.RunWorkerCompleted += RunWorkerCompleted;
}
public event EventHandler<OnionGeneratedEventArgs> OnionGenerated;
public void Start()
{
Running = true;
worker.RunWorkerAsync();
}
public void Stop()
{
worker.CancelAsync();
}
protected virtual void GenerateOnion(object sender, DoWorkEventArgs e)
{
if (worker.CancellationPending)
{
e.Cancel = true;
return;
}
OnionAddress onion = OnionAddress.Create();
e.Result = onion;
if (worker.CancellationPending)
{
e.Cancel = true;
}
}
protected virtual void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (e.Cancelled)
{
Running = false;
return;
}
OnionGeneratedEventArgs args = new OnionGeneratedEventArgs {
Result = (OnionAddress) e.Result,
};
OnOnionGenerated(args);
if (!args.Cancel)
{
worker.RunWorkerAsync();
}
else
{
Running = false;
}
}
protected virtual void OnOnionGenerated(OnionGeneratedEventArgs e)
{
EventHandler<OnionGeneratedEventArgs> handler = OnionGenerated;
if (handler != null)
{
handler(this, e);
}
}
public class OnionGeneratedEventArgs : EventArgs {
new internal static readonly OnionGeneratedEventArgs Empty = new OnionGeneratedEventArgs();
public bool Cancel { get; set; }
public OnionAddress Result { get; set; }
}
}
}
|
bsd-3-clause
|
C#
|
a7044a27b344bb2b978757894ad2dcc76378314d
|
Add Nesting ServiceCollection Extension method overloads
|
thnetii/dotnet-common
|
src/THNETII.DependencyInjection.Nesting/NestedServicesServiceCollectionExtensions.cs
|
src/THNETII.DependencyInjection.Nesting/NestedServicesServiceCollectionExtensions.cs
|
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
namespace THNETII.DependencyInjection.Nesting
{
public static class NestedServicesServiceCollectionExtensions
{
public static IServiceCollection AddNestedServices(
this IServiceCollection rootServices,
string key,
Action<INestedServiceCollection> configureServices)
{
return AddNestedServices<string>(
rootServices,
key,
StringComparer.OrdinalIgnoreCase,
configureServices
);
}
public static IServiceCollection AddNestedServices<T>(
this IServiceCollection rootServices,
string key,
Action<INestedServiceCollection> configureServices)
=> AddNestedServices<T>(rootServices, key,
StringComparer.OrdinalIgnoreCase,
configureServices);
public static IServiceCollection AddNestedServices<T>(
this IServiceCollection rootServices,
string key, IEqualityComparer<string> keyComparer,
Action<INestedServiceCollection> configureServices)
{
throw new NotImplementedException();
return rootServices;
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using System;
namespace THNETII.DependencyInjection.Nesting
{
public static class NestedServicesServiceCollectionExtensions
{
public static IServiceCollection AddNestedServices(
this IServiceCollection rootServices,
string key,
Action<INestedServiceCollection> configureServices)
{
throw new NotImplementedException();
return rootServices;
}
}
}
|
mit
|
C#
|
f08fb8807d5c314e893ce10f93beb92c6e8c75c6
|
Add query and uri parameters to resource type #5
|
raml-org/raml-dotnet-parser-2,raml-org/raml-dotnet-parser-2
|
source/Raml.Parser/Expressions/Verb.cs
|
source/Raml.Parser/Expressions/Verb.cs
|
using System.Collections.Generic;
using System.Linq;
using Raml.Parser.Builders;
namespace Raml.Parser.Expressions
{
public class Verb
{
private readonly IDictionary<string, object> dynamicRaml;
private readonly VerbType type;
private readonly string defaultMediaType;
private readonly bool isOptional;
public Verb(IDictionary<string, object> dynamicRaml, VerbType type, string defaultMediaType, bool isOptional = false)
{
this.dynamicRaml = dynamicRaml;
this.type = type;
this.defaultMediaType = defaultMediaType;
this.isOptional = isOptional;
if (dynamicRaml == null)
return;
Headers = GetHeaders();
Responses = GetResponses();
Body = GetBody();
Description = GetDescription();
QueryParameters = GetQueryParameters();
UriParameters = ParametersBuilder.GetUriParameters(dynamicRaml, "uriParameters");
}
public VerbType Type { get { return type; } }
public bool IsOptional { get { return isOptional; } }
public string Description { get; set; }
public IDictionary<string,Parameter> Headers { get; set; }
public IEnumerable<Response> Responses { get; set; }
public MimeType Body { get; set; }
public IDictionary<string, Parameter> UriParameters { get; set; }
public IDictionary<string, Parameter> QueryParameters { get; set; }
private string GetDescription()
{
return dynamicRaml.ContainsKey("description") ? (string)dynamicRaml["description"] : null;
}
private IDictionary<string, Parameter> GetHeaders()
{
return dynamicRaml.ContainsKey("headers")
? new ParametersBuilder(dynamicRaml["headers"] as IDictionary<string, object>).GetAsDictionary()
: new Dictionary<string, Parameter>();
}
private IEnumerable<Response> GetResponses()
{
return dynamicRaml != null && dynamicRaml.ContainsKey("responses")
? new ResponsesBuilder(dynamicRaml["responses"] as IDictionary<string, object>).Get(defaultMediaType)
: new List<Response>();
}
private MimeType GetBody()
{
if (!dynamicRaml.ContainsKey("body"))
return null;
var mimeType = dynamicRaml["body"] as object[];
if (mimeType != null && mimeType.Any())
{
return new BodyBuilder((IDictionary<string, object>) mimeType.First()).GetMimeType(mimeType);
}
var body = dynamicRaml["body"] as IDictionary<string, object>;
return new BodyBuilder(body).GetMimeType(body);
}
private IDictionary<string, Parameter> GetQueryParameters()
{
return dynamicRaml.ContainsKey("queryParameters")
? new ParametersBuilder((IDictionary<string, object>)dynamicRaml["queryParameters"]).GetAsDictionary()
: null;
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Raml.Parser.Builders;
namespace Raml.Parser.Expressions
{
public class Verb
{
private readonly IDictionary<string, object> dynamicRaml;
private readonly VerbType type;
private readonly string defaultMediaType;
private readonly bool isOptional;
public Verb(IDictionary<string, object> dynamicRaml, VerbType type, string defaultMediaType, bool isOptional = false)
{
this.dynamicRaml = dynamicRaml;
this.type = type;
this.defaultMediaType = defaultMediaType;
this.isOptional = isOptional;
}
public VerbType Type { get { return type; } }
public bool IsOptional { get { return isOptional; } }
public string Description { get { return dynamicRaml.ContainsKey("description") ? (string)dynamicRaml["description"]: null; } }
public IDictionary<string,Parameter> Headers
{
get
{
return dynamicRaml.ContainsKey("headers")
? new ParametersBuilder(dynamicRaml["headers"] as IDictionary<string, object>).GetAsDictionary()
: new Dictionary<string, Parameter>();
}
}
public IEnumerable<Response> Responses
{
get
{
return dynamicRaml != null && dynamicRaml.ContainsKey("responses")
? new ResponsesBuilder(dynamicRaml["responses"] as IDictionary<string, object>).Get(defaultMediaType)
: new List<Response>();
}
}
public MimeType Body
{
get
{
if (dynamicRaml == null)
return null;
if (!dynamicRaml.ContainsKey("body"))
return null;
var mimeType = dynamicRaml["body"] as object[];
if (mimeType != null && mimeType.Any())
{
return new BodyBuilder((IDictionary<string, object>) mimeType.First()).GetMimeType(mimeType);
}
var body = dynamicRaml["body"] as IDictionary<string, object>;
return new BodyBuilder(body).GetMimeType(body);
}
}
}
}
|
apache-2.0
|
C#
|
d25442f59afb8812316eb80da5fa1c5c468bb9f4
|
Update Item.cs
|
QetriX/quly
|
Assets/Scripts/libs/Item.cs
|
Assets/Scripts/libs/Item.cs
|
namespace com.qetrix.apps.quly.libs
{
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Item
{
protected string _name;
protected float _weight = 1;
// List<Item> _rewards;
protected int _materialCapacity = 100; // How much material can the item contain (max)
protected int _materialCotnent = 0; // How much material the item contains
protected string _materialType; // What Material the item accepts or contains
public float weight()
{
return _weight;
}
}
}
|
namespace Quly
{
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[Serializable]
public class Item
{
protected string _name;
protected float _weight = 1;
// List<Item> _rewards;
protected int _materialCapacity = 100; // How much material can the item contain (max)
protected int _materialCotnent = 0; // How much material the item contains
protected string _materialType; // What Material the item accepts or contains
public float weight()
{
return _weight;
}
}
}
|
mit
|
C#
|
7a33326aaa2bd4346febcf50c5eb4d46cd58eea9
|
Add StatusCode to PostException data
|
bretcope/BosunReporter.NET
|
BosunReporter/Exceptions.cs
|
BosunReporter/Exceptions.cs
|
using System;
using System.Net;
using BosunReporter.Infrastructure;
namespace BosunReporter
{
/// <summary>
/// Exception uses when posting to the Bosun API fails.
/// </summary>
public class BosunPostException : Exception
{
/// <summary>
/// The status code returned by Bosun.
/// </summary>
public HttpStatusCode? StatusCode { get; }
internal BosunPostException(HttpStatusCode statusCode, string responseBody, Exception innerException)
: base("Posting to the Bosun API failed with status code " + statusCode, innerException)
{
Data["ResponseBody"] = responseBody;
Data["StatusCode"] = $"{(int)statusCode} ({statusCode})";
StatusCode = statusCode;
}
internal BosunPostException(Exception innerException)
: base("Posting to the Bosun API failed. Bosun did not respond.", innerException)
{
}
}
/// <summary>
/// Exception used when a BosunReporter queue is full and payloads are being dropped. This typically happens after repeated failures to post to the API.
/// </summary>
public class BosunQueueFullException : Exception
{
/// <summary>
/// The number of data points which were lost.
/// </summary>
public int MetricsCount { get; }
/// <summary>
/// The number of bytes in the dropped payload.
/// </summary>
public int Bytes { get; }
internal BosunQueueFullException(QueueType queueType, int metricsCount, int bytes)
: base($"Bosun {queueType} metric queue is full. Metric data is likely being lost due to repeated failures in posting to the Bosun API.")
{
MetricsCount = metricsCount;
Bytes = bytes;
Data["MetricsCount"] = metricsCount;
Data["Bytes"] = bytes;
}
}
}
|
using System;
using System.Net;
using BosunReporter.Infrastructure;
namespace BosunReporter
{
/// <summary>
/// Exception uses when posting to the Bosun API fails.
/// </summary>
public class BosunPostException : Exception
{
/// <summary>
/// The status code returned by Bosun.
/// </summary>
public HttpStatusCode? StatusCode { get; }
internal BosunPostException(HttpStatusCode statusCode, string responseBody, Exception innerException)
: base("Posting to the Bosun API failed with status code " + statusCode, innerException)
{
Data["ResponseBody"] = responseBody;
StatusCode = statusCode;
}
internal BosunPostException(Exception innerException)
: base("Posting to the Bosun API failed. Bosun did not respond.", innerException)
{
}
}
/// <summary>
/// Exception used when a BosunReporter queue is full and payloads are being dropped. This typically happens after repeated failures to post to the API.
/// </summary>
public class BosunQueueFullException : Exception
{
/// <summary>
/// The number of data points which were lost.
/// </summary>
public int MetricsCount { get; }
/// <summary>
/// The number of bytes in the dropped payload.
/// </summary>
public int Bytes { get; }
internal BosunQueueFullException(QueueType queueType, int metricsCount, int bytes)
: base($"Bosun {queueType} metric queue is full. Metric data is likely being lost due to repeated failures in posting to the Bosun API.")
{
MetricsCount = metricsCount;
Bytes = bytes;
Data["MetricsCount"] = metricsCount;
Data["Bytes"] = bytes;
}
}
}
|
mit
|
C#
|
16cf5a739105e20bbb969bd841ce30d37884847b
|
edit comment
|
arnovb-github/CmcLibNet
|
CmcLibNet/CommenceLimits.cs
|
CmcLibNet/CommenceLimits.cs
|
namespace Vovin.CmcLibNet
{
/// <summary>
/// Some internal Commence limits, non-exhaustive
/// </summary>
internal static class CommenceLimits
{
/// <summary>
/// Maximum number of items per category.
/// </summary>
internal static int MaxItems => 500000; // different from what Commence says (750.000)! Up to at least RM 7.1, this is the limit.
/// <summary>
/// Maximum number of fields per category, including connections.
/// </summary>
internal static int MaxFieldsPerCategory => 250;
/// <summary>
/// Maximum length of a THID.
/// </summary>
internal static int ThidLength => 21;
/// <summary>
/// Maximum number of characters a large text field can contain.
/// </summary>
internal static int MaxTextFieldCapacity => 30000;
/// <summary>
/// Maximum number of characters a name field can contain.
/// </summary>
internal static int MaxNameFieldCapacity => 50;
/// <summary>
/// Maximum length of a connection name.
/// </summary>
internal static int MaxConnectionNameLength => 16;
/// <summary>
/// Maximum length of a field name.
/// </summary>
internal static int MaxFieldNameLength = 20;
/// <summary>
/// Maximum number of fields that a view can display, including connections.
/// </summary>
internal static int MaxFieldsPerView => 255;
/// <summary>
/// Maximum number of filters that can be defined on a cursor
/// </summary>
internal static int MaxFilters => 8;
/// <summary>
/// Default maximum number of characters returned for connections in a cursor
/// </summary>
internal static int DefaultMaxFieldSize => 93750;
}
}
|
namespace Vovin.CmcLibNet
{
/// <summary>
/// Internal Commence limits
/// </summary>
internal static class CommenceLimits
{
/// <summary>
/// Maximum number of items per category.
/// </summary>
internal static int MaxItems => 500000; // different from what Commence says (750.000)! Up to at least RM 7.1, this is the limit.
/// <summary>
/// Maximum number of fields per category, including connections.
/// </summary>
internal static int MaxFieldsPerCategory => 250;
/// <summary>
/// Maximum length of a THID.
/// </summary>
internal static int ThidLength => 21;
/// <summary>
/// Maximum number of characters a large text field can contain.
/// </summary>
internal static int MaxTextFieldCapacity => 30000;
/// <summary>
/// Maximum number of characters a name field can contain.
/// </summary>
internal static int MaxNameFieldCapacity => 50;
/// <summary>
/// Maximum length of a connection name.
/// </summary>
internal static int MaxConnectionNameLength => 16;
/// <summary>
/// Maximum length of a field name.
/// </summary>
internal static int MaxFieldNameLength = 20;
/// <summary>
/// Maximum number of fields that a view can display, including connections.
/// </summary>
internal static int MaxFieldsPerView => 255;
/// <summary>
/// Maximum number of filters that can be defined on a cursor
/// </summary>
internal static int MaxFilters => 8;
/// <summary>
/// Default maximum number of characters returned for connections in a cursor
/// </summary>
internal static int DefaultMaxFieldSize => 93750;
}
}
|
mit
|
C#
|
198d97095a357165c89b72d27cf68166d6da7816
|
Update WalletWasabi.Gui/CrashReport/CrashReporter.cs
|
nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet,nopara73/HiddenWallet
|
WalletWasabi.Gui/CrashReport/CrashReporter.cs
|
WalletWasabi.Gui/CrashReport/CrashReporter.cs
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using WalletWasabi.Gui.CrashReport.Models;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Microservices;
namespace WalletWasabi.Gui.CrashReport
{
public class CrashReporter
{
private const int MaxRecursiveCalls = 5;
public int Attempts { get; private set; }
public string ExceptionString { get; private set; } = null;
public bool IsReport => ExceptionString is { };
public void Start()
{
var exceptionString = ExceptionString;
var prevAttempts = Attempts;
if (prevAttempts >= MaxRecursiveCalls)
{
Logger.LogCritical($"The crash helper has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors.");
return;
}
var args = $"crashreport -attempt={prevAttempts + 1} -exception={exceptionString}";
ProcessBridge processBridge = new ProcessBridge(Process.GetCurrentProcess().MainModule.FileName);
processBridge.Start(args, false);
return;
}
public void SetException(string exceptionString, int attempts)
{
Attempts = attempts;
ExceptionString = exceptionString;
}
/// <summary>
/// Sets the exception when it first time occurs and should be reported to the user.
/// </summary>
public void SetException(Exception ex)
{
SetException(SerializedException.ToCommandLineArgument(ex), 1);
}
public override string ToString()
{
var exceptionToDisplay = Guard.NotNullOrEmptyOrWhitespace(nameof(ExceptionString), ExceptionString);
exceptionToDisplay = exceptionToDisplay.Replace("\\X0009", "\'")
.Replace("\\X0022", "\"")
.Replace("\\X000A", "\n")
.Replace("\\X000D", "\r")
.Replace("\\X0009", "\t")
.Replace("\\X0020", " ");
return exceptionToDisplay;
}
}
}
|
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using WalletWasabi.Gui.CrashReport.Models;
using WalletWasabi.Helpers;
using WalletWasabi.Logging;
using WalletWasabi.Microservices;
namespace WalletWasabi.Gui.Models.CrashReport
{
public class CrashReporter
{
private const int MaxRecursiveCalls = 5;
public int Attempts { get; private set; }
public string ExceptionString { get; private set; } = null;
public bool IsReport => ExceptionString is { };
public void Start()
{
var exceptionString = ExceptionString;
var prevAttempts = Attempts;
if (prevAttempts >= MaxRecursiveCalls)
{
Logger.LogCritical($"The crash helper has been called {MaxRecursiveCalls} times. Will not continue to avoid recursion errors.");
return;
}
var args = $"crashreport -attempt={prevAttempts + 1} -exception={exceptionString}";
ProcessBridge processBridge = new ProcessBridge(Process.GetCurrentProcess().MainModule.FileName);
processBridge.Start(args, false);
return;
}
public void SetException(string exceptionString, int attempts)
{
Attempts = attempts;
ExceptionString = exceptionString;
}
/// <summary>
/// Sets the exception when it first time occurs and should be reported to the user.
/// </summary>
public void SetException(Exception ex)
{
SetException(SerializedException.ToCommandLineArgument(ex), 1);
}
public override string ToString()
{
var exceptionToDisplay = Guard.NotNullOrEmptyOrWhitespace(nameof(ExceptionString), ExceptionString);
exceptionToDisplay = exceptionToDisplay.Replace("\\X0009", "\'")
.Replace("\\X0022", "\"")
.Replace("\\X000A", "\n")
.Replace("\\X000D", "\r")
.Replace("\\X0009", "\t")
.Replace("\\X0020", " ");
return exceptionToDisplay;
}
}
}
|
mit
|
C#
|
ed6163d2028bb3ddda141e7ca99501dd74fc4f10
|
update description of what this does
|
Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal,Appleseed/portal
|
Master/Appleseed/Projects/Appleseed.Framework.UrlRewriting/Properties/AssemblyInfo.cs
|
Master/Appleseed/Projects/Appleseed.Framework.UrlRewriting/Properties/AssemblyInfo.cs
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Appleseed.UrlRewriting")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System : URL Rewriting ")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal")]
[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("01d79d33-2176-4a6d-a8aa-7cc02f308240")]
// 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
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Appleseed.UrlRewriting")]
[assembly: AssemblyDescription("Appleseed Portal and Content Management System")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("ANANT Corporation")]
[assembly: AssemblyProduct("Appleseed Portal")]
[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("01d79d33-2176-4a6d-a8aa-7cc02f308240")]
// 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
[assembly: AssemblyVersion("1.4.98.383")]
[assembly: AssemblyFileVersion("1.4.98.383")]
|
apache-2.0
|
C#
|
dc3aa45639c678e4f840aa4652efb9f69f86a085
|
revert the BOM issue fix
|
antiufo/NuGet2,OneGet/nuget,mrward/NuGet.V2,chocolatey/nuget-chocolatey,mrward/nuget,mrward/NuGet.V2,mono/nuget,RichiCoder1/nuget-chocolatey,dolkensp/node.net,mrward/NuGet.V2,mrward/nuget,jholovacs/NuGet,dolkensp/node.net,GearedToWar/NuGet2,jholovacs/NuGet,rikoe/nuget,mrward/nuget,xoofx/NuGet,jmezach/NuGet2,RichiCoder1/nuget-chocolatey,rikoe/nuget,alluran/node.net,chocolatey/nuget-chocolatey,pratikkagda/nuget,RichiCoder1/nuget-chocolatey,ctaggart/nuget,chocolatey/nuget-chocolatey,oliver-feng/nuget,antiufo/NuGet2,xoofx/NuGet,GearedToWar/NuGet2,OneGet/nuget,jholovacs/NuGet,GearedToWar/NuGet2,ctaggart/nuget,dolkensp/node.net,GearedToWar/NuGet2,ctaggart/nuget,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,indsoft/NuGet2,mono/nuget,antiufo/NuGet2,jholovacs/NuGet,mrward/nuget,rikoe/nuget,jholovacs/NuGet,mrward/NuGet.V2,mono/nuget,jmezach/NuGet2,akrisiun/NuGet,oliver-feng/nuget,oliver-feng/nuget,mrward/NuGet.V2,antiufo/NuGet2,mono/nuget,jholovacs/NuGet,alluran/node.net,chocolatey/nuget-chocolatey,indsoft/NuGet2,pratikkagda/nuget,xoofx/NuGet,mrward/nuget,indsoft/NuGet2,OneGet/nuget,akrisiun/NuGet,xoofx/NuGet,antiufo/NuGet2,rikoe/nuget,chocolatey/nuget-chocolatey,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,indsoft/NuGet2,ctaggart/nuget,alluran/node.net,RichiCoder1/nuget-chocolatey,jmezach/NuGet2,GearedToWar/NuGet2,oliver-feng/nuget,dolkensp/node.net,oliver-feng/nuget,xoofx/NuGet,GearedToWar/NuGet2,mrward/nuget,antiufo/NuGet2,pratikkagda/nuget,oliver-feng/nuget,pratikkagda/nuget,xoofx/NuGet,alluran/node.net,jmezach/NuGet2,pratikkagda/nuget,indsoft/NuGet2,indsoft/NuGet2,chocolatey/nuget-chocolatey,mrward/NuGet.V2,pratikkagda/nuget,OneGet/nuget
|
src/Core/FileModifiers/Preprocessor.cs
|
src/Core/FileModifiers/Preprocessor.cs
|
using NuGet.Resources;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace NuGet
{
/// <summary>
/// Simple token replacement system for content files.
/// </summary>
public class Preprocessor : IPackageFileTransformer
{
private static readonly Regex _tokenRegex = new Regex(@"\$(?<propertyName>\w+)\$");
public void TransformFile(IPackageFile file, string targetPath, IProjectSystem projectSystem)
{
ProjectSystemExtensions.TryAddFile(projectSystem, targetPath, () => Process(file, projectSystem).AsStream());
}
public void RevertFile(IPackageFile file, string targetPath, IEnumerable<IPackageFile> matchingFiles, IProjectSystem projectSystem)
{
Func<Stream> streamFactory = () => Process(file, projectSystem).AsStream();
FileSystemExtensions.DeleteFileSafe(projectSystem, targetPath, streamFactory);
}
internal static string Process(IPackageFile file, IPropertyProvider propertyProvider)
{
using (var stream = file.GetStream())
{
return Process(stream, propertyProvider, throwIfNotFound: false);
}
}
public static string Process(Stream stream, IPropertyProvider propertyProvider, bool throwIfNotFound = true)
{
string text = stream.ReadToEnd();
return _tokenRegex.Replace(text, match => ReplaceToken(match, propertyProvider, throwIfNotFound));
}
private static string ReplaceToken(Match match, IPropertyProvider propertyProvider, bool throwIfNotFound)
{
string propertyName = match.Groups["propertyName"].Value;
var value = propertyProvider.GetPropertyValue(propertyName);
if (value == null && throwIfNotFound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.TokenHasNoValue, propertyName));
}
return value;
}
}
}
|
using NuGet.Resources;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace NuGet
{
/// <summary>
/// Simple token replacement system for content files.
/// </summary>
public class Preprocessor : IPackageFileTransformer
{
private static readonly Regex _tokenRegex = new Regex(@"\$(?<propertyName>\w+)\$");
public void TransformFile(IPackageFile file, string targetPath, IProjectSystem projectSystem)
{
ProjectSystemExtensions.TryAddFile(projectSystem, targetPath, () => Process(file, projectSystem).AsStream());
}
public void RevertFile(IPackageFile file, string targetPath, IEnumerable<IPackageFile> matchingFiles, IProjectSystem projectSystem)
{
Func<Stream> streamFactory = () => Process(file, projectSystem).AsStream();
FileSystemExtensions.DeleteFileSafe(projectSystem, targetPath, streamFactory);
}
internal static string Process(IPackageFile file, IPropertyProvider propertyProvider)
{
using (var stream = file.GetStream())
{
return Process(stream, propertyProvider, throwIfNotFound: false);
}
}
public static string Process(Stream stream, IPropertyProvider propertyProvider, bool throwIfNotFound = true)
{
// Fix for bug https://nuget.codeplex.com/workitem/3174, source code transformations must support BOM
byte[] bytes = stream.ReadAllBytes();
string text = Encoding.UTF8.GetString(bytes);
return _tokenRegex.Replace(text, match => ReplaceToken(match, propertyProvider, throwIfNotFound));
}
private static string ReplaceToken(Match match, IPropertyProvider propertyProvider, bool throwIfNotFound)
{
string propertyName = match.Groups["propertyName"].Value;
var value = propertyProvider.GetPropertyValue(propertyName);
if (value == null && throwIfNotFound)
{
throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, NuGetResources.TokenHasNoValue, propertyName));
}
return value;
}
}
}
|
apache-2.0
|
C#
|
394209b7429fb531ec450380777795f54e406ea6
|
fix error list navigation
|
pdelvo/roslyn,akrisiun/roslyn,mattscheffer/roslyn,robinsedlaczek/roslyn,AnthonyDGreen/roslyn,nguerrera/roslyn,weltkante/roslyn,cston/roslyn,ErikSchierboom/roslyn,bbarry/roslyn,dotnet/roslyn,Hosch250/roslyn,vslsnap/roslyn,VSadov/roslyn,Giftednewt/roslyn,dotnet/roslyn,shyamnamboodiripad/roslyn,heejaechang/roslyn,TyOverby/roslyn,brettfo/roslyn,stephentoub/roslyn,MattWindsor91/roslyn,jkotas/roslyn,jkotas/roslyn,pdelvo/roslyn,vslsnap/roslyn,aelij/roslyn,Giftednewt/roslyn,xasx/roslyn,mgoertz-msft/roslyn,mgoertz-msft/roslyn,DustinCampbell/roslyn,cston/roslyn,AmadeusW/roslyn,cston/roslyn,srivatsn/roslyn,bkoelman/roslyn,Hosch250/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,khyperia/roslyn,stephentoub/roslyn,xasx/roslyn,jcouv/roslyn,tannergooding/roslyn,akrisiun/roslyn,heejaechang/roslyn,Giftednewt/roslyn,KevinRansom/roslyn,drognanar/roslyn,eriawan/roslyn,CyrusNajmabadi/roslyn,lorcanmooney/roslyn,CaptainHayashi/roslyn,MichalStrehovsky/roslyn,abock/roslyn,tmeschter/roslyn,srivatsn/roslyn,KevinH-MS/roslyn,orthoxerox/roslyn,reaction1989/roslyn,AmadeusW/roslyn,xoofx/roslyn,CaptainHayashi/roslyn,VSadov/roslyn,CaptainHayashi/roslyn,shyamnamboodiripad/roslyn,davkean/roslyn,MattWindsor91/roslyn,dotnet/roslyn,KirillOsenkov/roslyn,AnthonyDGreen/roslyn,nguerrera/roslyn,agocke/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,tannergooding/roslyn,swaroop-sridhar/roslyn,abock/roslyn,weltkante/roslyn,panopticoncentral/roslyn,srivatsn/roslyn,bartdesmet/roslyn,eriawan/roslyn,shyamnamboodiripad/roslyn,mavasani/roslyn,jkotas/roslyn,diryboy/roslyn,OmarTawfik/roslyn,wvdd007/roslyn,mavasani/roslyn,KevinH-MS/roslyn,paulvanbrenk/roslyn,mattwar/roslyn,KirillOsenkov/roslyn,KevinRansom/roslyn,AArnott/roslyn,TyOverby/roslyn,mattscheffer/roslyn,zooba/roslyn,a-ctor/roslyn,agocke/roslyn,drognanar/roslyn,lorcanmooney/roslyn,MichalStrehovsky/roslyn,wvdd007/roslyn,orthoxerox/roslyn,sharwell/roslyn,mattwar/roslyn,jmarolf/roslyn,amcasey/roslyn,xoofx/roslyn,jeffanders/roslyn,KevinRansom/roslyn,jmarolf/roslyn,kelltrick/roslyn,mmitche/roslyn,akrisiun/roslyn,gafter/roslyn,khyperia/roslyn,aelij/roslyn,gafter/roslyn,jasonmalinowski/roslyn,OmarTawfik/roslyn,tmat/roslyn,tmeschter/roslyn,jeffanders/roslyn,a-ctor/roslyn,heejaechang/roslyn,khyperia/roslyn,bkoelman/roslyn,bartdesmet/roslyn,AnthonyDGreen/roslyn,jmarolf/roslyn,dpoeschl/roslyn,abock/roslyn,AArnott/roslyn,ErikSchierboom/roslyn,amcasey/roslyn,physhi/roslyn,CyrusNajmabadi/roslyn,MattWindsor91/roslyn,davkean/roslyn,tannergooding/roslyn,sharwell/roslyn,dpoeschl/roslyn,jamesqo/roslyn,jasonmalinowski/roslyn,AmadeusW/roslyn,tvand7093/roslyn,zooba/roslyn,ErikSchierboom/roslyn,wvdd007/roslyn,tvand7093/roslyn,DustinCampbell/roslyn,amcasey/roslyn,genlu/roslyn,a-ctor/roslyn,DustinCampbell/roslyn,jcouv/roslyn,genlu/roslyn,drognanar/roslyn,tmat/roslyn,aelij/roslyn,panopticoncentral/roslyn,eriawan/roslyn,yeaicc/roslyn,jamesqo/roslyn,diryboy/roslyn,bbarry/roslyn,tmat/roslyn,CyrusNajmabadi/roslyn,diryboy/roslyn,pdelvo/roslyn,zooba/roslyn,bbarry/roslyn,robinsedlaczek/roslyn,paulvanbrenk/roslyn,mattwar/roslyn,AlekseyTs/roslyn,robinsedlaczek/roslyn,xoofx/roslyn,gafter/roslyn,bartdesmet/roslyn,nguerrera/roslyn,AlekseyTs/roslyn,TyOverby/roslyn,physhi/roslyn,agocke/roslyn,paulvanbrenk/roslyn,jcouv/roslyn,mmitche/roslyn,jeffanders/roslyn,sharwell/roslyn,OmarTawfik/roslyn,mavasani/roslyn,swaroop-sridhar/roslyn,davkean/roslyn,tmeschter/roslyn,AdamSpeight2008/roslyn-AdamSpeight2008,reaction1989/roslyn,Hosch250/roslyn,kelltrick/roslyn,jasonmalinowski/roslyn,KevinH-MS/roslyn,AArnott/roslyn,MichalStrehovsky/roslyn,physhi/roslyn,bkoelman/roslyn,VSadov/roslyn,dpoeschl/roslyn,stephentoub/roslyn,mattscheffer/roslyn,MattWindsor91/roslyn,swaroop-sridhar/roslyn,kelltrick/roslyn,tvand7093/roslyn,vslsnap/roslyn,reaction1989/roslyn,lorcanmooney/roslyn,brettfo/roslyn,AlekseyTs/roslyn,panopticoncentral/roslyn,genlu/roslyn,mmitche/roslyn,KirillOsenkov/roslyn,jamesqo/roslyn,weltkante/roslyn,orthoxerox/roslyn,mgoertz-msft/roslyn,brettfo/roslyn,xasx/roslyn,yeaicc/roslyn,yeaicc/roslyn
|
src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableControlEventProcessorProvider.cs
|
src/VisualStudio/Core/Def/Implementation/TableDataSource/AbstractTableControlEventProcessorProvider.cs
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal abstract class AbstractTableControlEventProcessorProvider<TData> : ITableControlEventProcessorProvider
{
public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl tableControl)
{
return CreateEventProcessor();
}
protected virtual EventProcessor CreateEventProcessor()
{
return new EventProcessor();
}
protected class EventProcessor : TableControlEventProcessorBase
{
protected static AbstractTableEntriesSnapshot<TData> GetEntriesSnapshot(ITableEntryHandle entryHandle)
{
int index;
return GetEntriesSnapshot(entryHandle, out index);
}
protected static AbstractTableEntriesSnapshot<TData> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index)
{
ITableEntriesSnapshot snapshot;
if (!entryHandle.TryGetSnapshot(out snapshot, out index))
{
return null;
}
return snapshot as AbstractTableEntriesSnapshot<TData>;
}
public override void PreprocessNavigate(ITableEntryHandle entryHandle, TableEntryNavigateEventArgs e)
{
int index;
var roslynSnapshot = GetEntriesSnapshot(entryHandle, out index);
if (roslynSnapshot == null)
{
return;
}
// we always mark it as handled if entry is ours
e.Handled = true;
roslynSnapshot.TryNavigateTo(index, e.IsPreview);
}
}
}
}
|
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.VisualStudio.Shell.TableControl;
using Microsoft.VisualStudio.Shell.TableManager;
namespace Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource
{
internal abstract class AbstractTableControlEventProcessorProvider<TData> : ITableControlEventProcessorProvider
{
public ITableControlEventProcessor GetAssociatedEventProcessor(IWpfTableControl tableControl)
{
return CreateEventProcessor();
}
protected virtual EventProcessor CreateEventProcessor()
{
return new EventProcessor();
}
protected class EventProcessor : TableControlEventProcessorBase
{
protected static AbstractTableEntriesSnapshot<TData> GetEntriesSnapshot(ITableEntryHandle entryHandle)
{
int index;
return GetEntriesSnapshot(entryHandle, out index);
}
protected static AbstractTableEntriesSnapshot<TData> GetEntriesSnapshot(ITableEntryHandle entryHandle, out int index)
{
ITableEntriesSnapshot snapshot;
if (!entryHandle.TryGetSnapshot(out snapshot, out index))
{
return null;
}
return snapshot as AbstractTableEntriesSnapshot<TData>;
}
public override void PreprocessNavigate(ITableEntryHandle entryHandle, TableEntryNavigateEventArgs e)
{
int index;
var roslynSnapshot = GetEntriesSnapshot(entryHandle, out index);
if (roslynSnapshot == null)
{
return;
}
// we always mark it as handled if entry is ours
e.Handled = true;
// REVIEW:
// turning off one click navigation.
// unlike FindAllReference which don't lose focus even after navigation,
// error list loses focus once navigation happens. I checked our find all reference implementation, and it uses
// same mechanism as error list, so it must be the find all reference window doing something to not lose focus or it must
// taking focus back once navigation happened. we need to implement same thing in error list. until then, I am disabling one
// click navigation.
if (!e.IsPreview)
{
roslynSnapshot.TryNavigateTo(index, e.IsPreview);
}
}
}
}
}
|
apache-2.0
|
C#
|
936a255a45e4ad0650451817bf099341b5b6c740
|
Update ClickTabOrPillAttribute trigger
|
atata-framework/atata-bootstrap,atata-framework/atata-bootstrap
|
src/Atata.Bootstrap/Triggers/ClickTabOrPillAttribute.cs
|
src/Atata.Bootstrap/Triggers/ClickTabOrPillAttribute.cs
|
using System;
using OpenQA.Selenium;
namespace Atata.Bootstrap
{
public class ClickTabOrPillAttribute : TriggerAttribute
{
private bool isInitialized;
private UIComponent navItemComponent;
public ClickTabOrPillAttribute(TriggerEvents on = TriggerEvents.BeforeAccess, TriggerPriority priority = TriggerPriority.Medium)
: base(on, priority)
{
}
private void Init<TOwner>(TriggerContext<TOwner> context)
where TOwner : PageObject<TOwner>
{
var tabPane = context.Component.GetAncestorOrSelf<BSTabPane<TOwner>>() as IUIComponent<TOwner>;
if (tabPane == null)
throw new InvalidOperationException($"Cannot find '{nameof(BSTabPane<TOwner>)}' ancestor.");
string tabPillInnerXPath = $".//a[@href='#{tabPane.Attributes.Id.Value}']";
string pillXPath = UIComponentResolver.GetControlDefinition(typeof(BSPill<TOwner>)).ScopeXPath;
bool isUsingPill = tabPane.Parent.Scope.Exists(By.XPath($".//{pillXPath}[{tabPillInnerXPath}]").SafelyAtOnce());
var findAttribute = new FindByInnerXPathAttribute(tabPillInnerXPath);
string navItemName = tabPane.ComponentName;
navItemComponent = isUsingPill
? (UIComponent)tabPane.Parent.Controls.Create<BSPill<TOwner>>(navItemName, findAttribute)
: tabPane.Parent.Controls.Create<BSTab<TOwner>>(navItemName, findAttribute);
isInitialized = true;
}
protected override void Execute<TOwner>(TriggerContext<TOwner> context)
{
if (!isInitialized)
Init(context);
BSNavItem<TOwner> navItem = (BSNavItem<TOwner>)navItemComponent;
if (!navItem.IsActive)
navItem.Click();
}
}
}
|
using System;
using OpenQA.Selenium;
namespace Atata.Bootstrap
{
public class ClickTabOrPillAttribute : TriggerAttribute
{
private bool isInitialized;
private UIComponent navItemComponent;
public ClickTabOrPillAttribute(TriggerEvents on = TriggerEvents.BeforeAccess, TriggerPriority priority = TriggerPriority.Medium)
: base(on, priority)
{
}
private void Init<TOwner>(TriggerContext<TOwner> context)
where TOwner : PageObject<TOwner>
{
var tabPane = context.Component.GetAncestorOrSelf<BSTabPane<TOwner>>() as IUIComponent<TOwner>;
if (tabPane == null)
throw new InvalidOperationException($"Cannot find '{nameof(BSTabPane<TOwner>)}' ancestor.");
string tabPillInnerXPath = $".//a[@href='#{tabPane.Attributes.Id.Value}']";
string pillXPath = UIComponentResolver.GetControlDefinition(typeof(BSPill<TOwner>)).ScopeXPath;
bool isUsingPill = tabPane.Parent.Scope.Exists(By.XPath($".//{pillXPath}[{tabPillInnerXPath}]").SafelyAtOnce());
var findAttribute = new FindByInnerXPathAttribute(tabPillInnerXPath);
navItemComponent = isUsingPill
? (UIComponent)tabPane.Parent.Controls.Create<BSPill<TOwner>>(context.Component.Parent.ComponentName, findAttribute)
: tabPane.Parent.Controls.Create<BSTab<TOwner>>(context.Component.Parent.ComponentName, findAttribute);
isInitialized = true;
}
protected override void Execute<TOwner>(TriggerContext<TOwner> context)
{
if (!isInitialized)
Init(context);
BSNavItem<TOwner> navItem = (BSNavItem<TOwner>)navItemComponent;
if (!navItem.IsActive)
navItem.Click();
}
}
}
|
apache-2.0
|
C#
|
bbf4e9f532dd751a692d3e3c85424a464a718846
|
revert configname
|
AndreGleichner/NLog,michaeljbaird/NLog,UgurAldanmaz/NLog,babymechanic/NLog,ArsenShnurkov/NLog,BrutalCode/NLog,tmusico/NLog,tmusico/NLog,tohosnet/NLog,Niklas-Peter/NLog,sean-gilliam/NLog,luigiberrettini/NLog,michaeljbaird/NLog,breyed/NLog,kevindaub/NLog,bjornbouetsmith/NLog,ilya-g/NLog,bryjamus/NLog,hubo0831/NLog,Niklas-Peter/NLog,pwelter34/NLog,FeodorFitsner/NLog,hubo0831/NLog,zbrad/NLog,ilya-g/NLog,vbfox/NLog,kevindaub/NLog,nazim9214/NLog,bryjamus/NLog,littlesmilelove/NLog,MoaidHathot/NLog,AndreGleichner/NLog,ArsenShnurkov/NLog,NLog/NLog,304NotModified/NLog,tetrodoxin/NLog,bhaeussermann/NLog,littlesmilelove/NLog,ajayanandgit/NLog,bhaeussermann/NLog,pwelter34/NLog,snakefoot/NLog,tetrodoxin/NLog,MoaidHathot/NLog,breyed/NLog,luigiberrettini/NLog,RRUZ/NLog,ie-zero/NLog,MartinTherriault/NLog,vbfox/NLog,babymechanic/NLog,campbeb/NLog,matteobruni/NLog,nazim9214/NLog,RRUZ/NLog,BrutalCode/NLog,tohosnet/NLog,MartinTherriault/NLog,bjornbouetsmith/NLog,FeodorFitsner/NLog,campbeb/NLog,ajayanandgit/NLog,matteobruni/NLog,ie-zero/NLog,UgurAldanmaz/NLog,zbrad/NLog
|
src/NLog/LogReceiverService/ILogReceiverTwoWayClient.cs
|
src/NLog/LogReceiverService/ILogReceiverTwoWayClient.cs
|
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LogReceiverService
{
using System;
#if WCF_SUPPORTED
using System.ServiceModel;
#endif
/// <summary>
/// Service contract for Log Receiver client.
/// </summary>
#if WCF_SUPPORTED
[ServiceContract(Namespace = LogReceiverServiceConfig.WebServiceNamespace, ConfigurationName = "NLog.LogReceiverService.ILogReceiverClient")]
#endif
public interface ILogReceiverTwoWayClient : ILogReceiverClient
{
/// <summary>
/// Begins processing of log messages.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="callback">The callback.</param>
/// <param name="asyncState">Asynchronous state.</param>
/// <returns>
/// IAsyncResult value which can be passed to <see cref="ILogReceiverClient.EndProcessLogMessages"/>.
/// </returns>
#if WCF_SUPPORTED
[OperationContractAttribute(AsyncPattern = true, Action = "http://nlog-project.org/ws/ILogReceiverServer/ProcessLogMessages", ReplyAction = "http://nlog-project.org/ws/ILogReceiverServer/ProcessLogMessagesResponse")]
#endif
new IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState);
/// <summary>
/// Ends asynchronous processing of log messages.
/// </summary>
/// <param name="result">The result.</param>
new void EndProcessLogMessages(IAsyncResult result);
}
}
|
//
// Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net>
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * Neither the name of Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LogReceiverService
{
using System;
#if WCF_SUPPORTED
using System.ServiceModel;
#endif
/// <summary>
/// Service contract for Log Receiver client.
/// </summary>
#if WCF_SUPPORTED
[ServiceContract(Namespace = LogReceiverServiceConfig.WebServiceNamespace, ConfigurationName = "NLog.LogReceiverService.ILogReceiverTwoWayClient")]
#endif
public interface ILogReceiverTwoWayClient : ILogReceiverClient
{
/// <summary>
/// Begins processing of log messages.
/// </summary>
/// <param name="events">The events.</param>
/// <param name="callback">The callback.</param>
/// <param name="asyncState">Asynchronous state.</param>
/// <returns>
/// IAsyncResult value which can be passed to <see cref="ILogReceiverClient.EndProcessLogMessages"/>.
/// </returns>
#if WCF_SUPPORTED
[OperationContractAttribute(AsyncPattern = true, Action = "http://nlog-project.org/ws/ILogReceiverServer/ProcessLogMessages", ReplyAction = "http://nlog-project.org/ws/ILogReceiverServer/ProcessLogMessagesResponse")]
#endif
new IAsyncResult BeginProcessLogMessages(NLogEvents events, AsyncCallback callback, object asyncState);
/// <summary>
/// Ends asynchronous processing of log messages.
/// </summary>
/// <param name="result">The result.</param>
new void EndProcessLogMessages(IAsyncResult result);
}
}
|
bsd-3-clause
|
C#
|
995e6403161fc9b86e875b18451fec4d6e569c42
|
Test commit
|
optivem/immerest,optivem/optivem-commons-cs
|
src/Optivem.Commons.Parsing.Default/BaseNumberParser.cs
|
src/Optivem.Commons.Parsing.Default/BaseNumberParser.cs
|
using System;
using System.Globalization;
namespace Optivem.Commons.Parsing.Default
{
public abstract class BaseNumberParser<T> : BaseParser<T>
{
public BaseNumberParser(NumberStyles? numberStyles = null, IFormatProvider formatProvider = null)
{
NumberStyles = numberStyles;
FormatProvider = formatProvider;
}
public IFormatProvider FormatProvider { get; private set; }
public NumberStyles? NumberStyles { get; private set; }
protected override T ParseInner(string value)
{
if(NumberStyles != null && FormatProvider != null)
{
return ParseNumber(value, NumberStyles.Value, FormatProvider);
}
if(NumberStyles != null)
{
return ParseNumber(value, NumberStyles.Value);
}
if(FormatProvider != null)
{
return ParseNumber(value, FormatProvider);
}
return ParseNumber(value);
}
protected abstract T ParseNumber(string value);
protected abstract T ParseNumber(string value, IFormatProvider formatProvider);
protected abstract T ParseNumber(string value, NumberStyles numberStyles);
protected abstract T ParseNumber(string value, NumberStyles numberStyles, IFormatProvider formatProvider);
}
}
|
using System;
using System.Globalization;
namespace Optivem.Commons.Parsing.Default
{
public abstract class BaseNumberParser<T> : BaseParser<T>
{
public BaseNumberParser(NumberStyles? numberStyles = null, IFormatProvider formatProvider = null)
{
NumberStyles = numberStyles;
FormatProvider = formatProvider;
}
publics IFormatProvider FormatProvider { get; private set; }
public NumberStyles? NumberStyles { get; private set; }
protected override T ParseInner(string value)
{
if(NumberStyles != null && FormatProvider != null)
{
return ParseNumber(value, NumberStyles.Value, FormatProvider);
}
if(NumberStyles != null)
{
return ParseNumber(value, NumberStyles.Value);
}
if(FormatProvider != null)
{
return ParseNumber(value, FormatProvider);
}
return ParseNumber(value);
}
protected abstract T ParseNumber(string value);
protected abstract T ParseNumber(string value, IFormatProvider formatProvider);
protected abstract T ParseNumber(string value, NumberStyles numberStyles);
protected abstract T ParseNumber(string value, NumberStyles numberStyles, IFormatProvider formatProvider);
}
}
|
apache-2.0
|
C#
|
1df12fd7ab52cdb8ffdbe486d3e6a4a383a20309
|
Work around Bl-923: L10NSharp Crash when accessed from javascript
|
StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop,StephenMcConnel/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,gmartin7/myBloomFork,andrew-polk/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,andrew-polk/BloomDesktop,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,JohnThomson/BloomDesktop,BloomBooks/BloomDesktop,andrew-polk/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,BloomBooks/BloomDesktop,gmartin7/myBloomFork,JohnThomson/BloomDesktop,gmartin7/myBloomFork,BloomBooks/BloomDesktop,JohnThomson/BloomDesktop,StephenMcConnel/BloomDesktop,gmartin7/myBloomFork,StephenMcConnel/BloomDesktop
|
src/BloomExe/web/I18NHandler.cs
|
src/BloomExe/web/I18NHandler.cs
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using Bloom.Collection;
using L10NSharp;
using Newtonsoft.Json;
namespace Bloom.web
{
/// <summary>
/// This class handles requests for internationalization. It uses the L10NSharp LocalizationManager to look up values.
/// </summary>
static class I18NHandler
{
private static bool _localizing = false;
public static bool HandleRequest(string localPath, IRequestInfo info, CollectionSettings currentCollectionSettings)
{
var lastSep = localPath.IndexOf("/", System.StringComparison.Ordinal);
var lastSegment = (lastSep > -1) ? localPath.Substring(lastSep + 1) : localPath;
switch (lastSegment)
{
case "loadStrings":
while (_localizing)
{
Thread.Sleep(0);
}
try
{
_localizing = true;
var d = new Dictionary<string, string>();
var post = info.GetPostData();
if (post != null)
{
foreach (string key in post.Keys)
{
try
{
if (!d.ContainsKey(key))
{
var translation = LocalizationManager.GetDynamicString("Bloom", key, post[key]);
d.Add(key, translation);
}
}
catch (Exception error)
{
Debug.Fail("Debug Only:" +error.Message+Environment.NewLine+"A bug reported at this location is BL-923");
//Until BL-923 is fixed (hard... it's a race condition, it's better to swallow this for users
}
}
}
info.ContentType = "application/json";
info.WriteCompleteOutput(JsonConvert.SerializeObject(d));
return true;
}
finally
{
_localizing = false;
}
}
return false;
}
}
}
|
using System.Collections.Generic;
using System.Threading;
using Bloom.Collection;
using L10NSharp;
using Newtonsoft.Json;
namespace Bloom.web
{
/// <summary>
/// This class handles requests for internationalization. It uses the L10NSharp LocalizationManager to look up values.
/// </summary>
static class I18NHandler
{
private static bool _localizing = false;
public static bool HandleRequest(string localPath, IRequestInfo info, CollectionSettings currentCollectionSettings)
{
var lastSep = localPath.IndexOf("/", System.StringComparison.Ordinal);
var lastSegment = (lastSep > -1) ? localPath.Substring(lastSep + 1) : localPath;
switch (lastSegment)
{
case "loadStrings":
while (_localizing)
{
Thread.Sleep(0);
}
try
{
_localizing = true;
var d = new Dictionary<string, string>();
var post = info.GetPostData();
if (post != null)
{
foreach (string key in post.Keys)
{
var translation = LocalizationManager.GetDynamicString("Bloom", key, post[key]);
if (!d.ContainsKey(key)) d.Add(key, translation);
}
}
info.ContentType = "application/json";
info.WriteCompleteOutput(JsonConvert.SerializeObject(d));
return true;
}
finally
{
_localizing = false;
}
}
return false;
}
}
}
|
mit
|
C#
|
4c8fba0a5848b0f69156916f22cffa8a8323417c
|
Fix argument null check in SecurityHeadersMiddleware
|
andrewlock/blog-examples,andrewlock/blog-examples,andrewlock/blog-examples,andrewlock/blog-examples
|
adding-default-security-headers/src/AddingDefaultSecurityHeaders/Middleware/SecurityHeadersMiddleware.cs
|
adding-default-security-headers/src/AddingDefaultSecurityHeaders/Middleware/SecurityHeadersMiddleware.cs
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AddingDefaultSecurityHeaders.Middleware.Constants;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
namespace AddingDefaultSecurityHeaders.Middleware
{
/// <summary>
/// An ASP.NET middleware for adding security headers.
/// </summary>
public class SecurityHeadersMiddleware
{
private readonly RequestDelegate _next;
private readonly SecurityHeadersPolicy _policy;
/// <summary>
/// Instantiates a new <see cref="SecurityHeadersMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="policy">An instance of the <see cref="SecurityHeadersPolicy"/> which can be applied.</param>
public SecurityHeadersMiddleware(RequestDelegate next, SecurityHeadersPolicy policy)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
_next = next;
_policy = policy;
}
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var response = context.Response;
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
var headers = response.Headers;
foreach (var headerValuePair in _policy.SetHeaders)
{
headers[headerValuePair.Key] = headerValuePair.Value;
}
foreach (var header in _policy.RemoveHeaders)
{
headers.Remove(header);
}
await _next(context);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using AddingDefaultSecurityHeaders.Middleware.Constants;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
namespace AddingDefaultSecurityHeaders.Middleware
{
/// <summary>
/// An ASP.NET middleware for adding security headers.
/// </summary>
public class SecurityHeadersMiddleware
{
private readonly RequestDelegate _next;
private readonly SecurityHeadersPolicy _policy;
/// <summary>
/// Instantiates a new <see cref="SecurityHeadersMiddleware"/>.
/// </summary>
/// <param name="next">The next middleware in the pipeline.</param>
/// <param name="policy">An instance of the <see cref="SecurityHeadersPolicy"/> which can be applied.</param>
public SecurityHeadersMiddleware(RequestDelegate next, SecurityHeadersPolicy policy)
{
if (next == null)
{
throw new ArgumentNullException(nameof(next));
}
if (_policy == null)
{
throw new ArgumentNullException(nameof(policy));
}
_next = next;
_policy = policy;
}
public async Task Invoke(HttpContext context)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
var response = context.Response;
if (response == null)
{
throw new ArgumentNullException(nameof(response));
}
var headers = response.Headers;
foreach (var headerValuePair in _policy.SetHeaders)
{
headers[headerValuePair.Key] = headerValuePair.Value;
}
foreach (var header in _policy.RemoveHeaders)
{
headers.Remove(header);
}
await _next(context);
}
}
}
|
mit
|
C#
|
bd16be64689be0632a7fab4fb058afb9be1e4eb0
|
Add Int.To(Int) Method, which allow to generate a sequence between two numbers.
|
garlab/Ext.NET
|
Ext.NET/IntegerExtension.cs
|
Ext.NET/IntegerExtension.cs
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ext.NET
{
class IntegerExtension
{
public static void Times(this int n, Action<int> action)
{
for (int i = 0; i < n; ++i)
{
action(i);
}
}
public static IEnumerable<int> To(this int n, int to)
{
if (n == to)
{
yield return n;
}
else if (to > n)
{
for (int i = n; i < to; ++i)
yield return i;
}
else
{
for (int i = n; i > to; --i)
yield return i;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Ext.NET
{
class IntegerExtension
{
public static void Times(this int n, Action<int> action)
{
for (int i = 0; i < n; ++i)
{
action(i);
}
}
}
}
|
mit
|
C#
|
e05bb59ca8102fd20ff0069d7bd94ac8f10a4c06
|
Update Holiday.cs
|
kiyoaki/JpPublicHolidays.NET
|
JpPublicHolidays/Holiday.cs
|
JpPublicHolidays/Holiday.cs
|
using System;
namespace JpPublicHolidays
{
public class Holiday
{
private static readonly TimeZoneInfo JstTimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
public string Name { get; set; }
public DateTime Date { get; set; }
public DateTimeOffset DateWithTimeZone
{
get
{
return new DateTimeOffset(Date, JstTimeZoneInfo.BaseUtcOffset);
}
}
}
}
|
using System;
namespace JpPublicHolidays
{
public class Holiday
{
public string Name { get; set; }
public DateTime Date { get; set; }
}
}
|
mit
|
C#
|
7ea761ae73e3b44be2aa371e0b82e308f217b170
|
Support null contexts in WPF TextLayout
|
hamekoz/xwt,mminns/xwt,mono/xwt,directhex/xwt,steffenWi/xwt,sevoku/xwt,cra0zy/xwt,hwthomas/xwt,TheBrainTech/xwt,lytico/xwt,mminns/xwt,iainx/xwt,residuum/xwt,antmicro/xwt,akrisiun/xwt
|
Xwt.WPF/Xwt.WPFBackend/TextLayoutBackendHandler.cs
|
Xwt.WPF/Xwt.WPFBackend/TextLayoutBackendHandler.cs
|
//
// TextLayoutBackendHandler.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Drawing;
using Xwt.Backends;
using Xwt.Drawing;
using Xwt.Engine;
using Font = Xwt.Drawing.Font;
namespace Xwt.WPFBackend
{
public class TextLayoutBackendHandler
: ITextLayoutBackendHandler
{
public object Create (Context context)
{
DrawingContext drawingContext;
if (context == null)
drawingContext = new DrawingContext (Graphics.FromImage (new Bitmap (1, 1)));
else
drawingContext = (DrawingContext)WidgetRegistry.GetBackend (context);
return new TextLayoutContext (drawingContext);
}
public void SetWidth (object backend, double value)
{
((TextLayoutContext) backend).Width = value;
}
public void SetText (object backend, string text)
{
((TextLayoutContext) backend).Text = text;
}
public void SetFont (object backend, Font font)
{
((TextLayoutContext) backend).Font = font.ToDrawingFont();
}
public Size GetSize (object backend)
{
return ((TextLayoutContext) backend).GetSize ();
}
}
}
|
//
// TextLayoutBackendHandler.cs
//
// Author:
// Eric Maupin <ermau@xamarin.com>
//
// Copyright (c) 2012 Xamarin, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using Xwt.Backends;
using Xwt.Drawing;
using Xwt.Engine;
namespace Xwt.WPFBackend
{
public class TextLayoutBackendHandler
: ITextLayoutBackendHandler
{
public object Create (Context context)
{
var drawingContext = (DrawingContext)WidgetRegistry.GetBackend (context);
return new TextLayoutContext (drawingContext);
}
public void SetWidth (object backend, double value)
{
((TextLayoutContext) backend).Width = value;
}
public void SetText (object backend, string text)
{
((TextLayoutContext) backend).Text = text;
}
public void SetFont (object backend, Font font)
{
((TextLayoutContext) backend).Font = font.ToDrawingFont();
}
public Size GetSize (object backend)
{
return ((TextLayoutContext) backend).GetSize ();
}
}
}
|
mit
|
C#
|
1d13673ad0cd4b1489547a2288ef528c1083d109
|
Fix files validation logic
|
kwokhou/HelloSignNet
|
HelloSignNet.Core/HSSendSignatureRequestData.cs
|
HelloSignNet.Core/HSSendSignatureRequestData.cs
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace HelloSignNet.Core
{
public class HSSendSignatureRequestData
{
public string Title { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public string SigningRedirectUrl { get; set; }
public List<HSSigner> Signers { get; set; }
public List<string> CcEmailAddresses { get; set; }
public List<FileInfo> Files { get; set; }
public List<string> FileUrls { get; set; }
public int TestMode { get; set; } // true=1, false=0
public bool IsValid
{
get
{
if (Files == null && FileUrls == null)
{
return false;
}
if (Files != null && FileUrls == null)
{
if (!Files.Any())
return true;
}
if (Files == null && FileUrls != null)
{
if (!FileUrls.Any())
return false;
}
if (Signers == null || Signers.Count == 0)
return false;
if (Signers.Any(s => string.IsNullOrEmpty(s.Name) || string.IsNullOrEmpty(s.EmailAddress)))
return false;
return true;
}
}
}
}
|
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace HelloSignNet.Core
{
public class HSSendSignatureRequestData
{
public string Title { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public string SigningRedirectUrl { get; set; }
public List<HSSigner> Signers { get; set; }
public List<string> CcEmailAddresses { get; set; }
public List<FileInfo> Files { get; set; }
public List<string> FileUrls { get; set; }
public int TestMode { get; set; } // true=1, false=0
public bool IsValid
{
get
{
if (Files == null && FileUrls == null)
return false;
if (Files != null && (Files.Count == 0 && FileUrls.Count == 0))
return false;
if ((Files != null && FileUrls != null) && (Files.Count > 0 && FileUrls.Count > 0))
return false;
if (Signers == null || Signers.Count == 0)
return false;
if (Signers.Any(s => string.IsNullOrEmpty(s.Name) || string.IsNullOrEmpty(s.EmailAddress)))
return false;
return true;
}
}
}
}
|
mit
|
C#
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.