content stringlengths 23 1.05M |
|---|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "New Arrow", menuName = "Arrow")]
public class ArrowScriptable : ScriptableObject
{
public CardColor Color;
public Sprite Art;
public ArrowScriptable(CardColor color)
{
Color = color;
}
public override string ToString()
{
return '>' + Color.ToString() + '>';
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace BpToolsLib
{
public class StageSet : HashSet<Stage>, IBaseElement, IExpressionHolder, IDataNameHolder
{
public MutableExpressionSet Expressions
{
get
{
MutableExpressionSet expressions = new MutableExpressionSet();
foreach (Stage stage in this)
{
if (stage is IExpressionHolder)
{
expressions.UnionWith(((IExpressionHolder)stage).Expressions);
}
}
return expressions;
}
}
public MutableDataNameSet DataNames
{
get
{
MutableDataNameSet dataNames = new MutableDataNameSet();
foreach (Stage stage in this)
{
if (stage is IDataNameHolder)
{
dataNames.UnionWith(((IDataNameHolder)stage).DataNames);
}
}
return dataNames;
}
}
public StageSet() : base() { }
public StageSet(StageSet stageSet) : base((HashSet<Stage>)stageSet) { }
}
}
|
namespace Chakad.Core
{
public class ServiceSpecification
{
public static string ServiceId { get; set; }
public static string InstanceId { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace de.JochenHeckl.Unity.DataBinding.Example
{
public class TwoWayDataBindingView : ViewBehaviour
{
public Action<int> HandleSelectionChangedCallback { get; set; }
public void HandleDropDownSelectionChanged( int selectedValue )
{
if ( HandleSelectionChangedCallback != null )
{
HandleSelectionChangedCallback( selectedValue );
}
}
}
} |
using System;
using UnityObject = UnityEngine.Object;
namespace Vexe.Runtime.Types
{
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter)]
public class ResourcePathAttribute : DrawnAttribute
{
public Type ResourceType { get; set; }
public ResourcePathAttribute(Type objectType = null)
{
if (objectType == null || !typeof(UnityObject).IsAssignableFrom(objectType))
ResourceType = typeof(UnityObject);
else
ResourceType = objectType;
}
}
} |
namespace BankOrganization
{
using System;
public class Individual : Customer
{
public Individual(string custName, string custID, string customerNumber)
:base(custName, custID, customerNumber)
{
}
public override string ToString()
{
return base.ToString() + " " + this.GetType().Name;
}
}
}
|
using NaughtyAttributes;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GameplayIngredients.Logic
{
[AddComponentMenu(ComponentMenu.logicPath + "Global Logic")]
[HelpURL(Help.URL + "globals")]
[Callable("Data", "Logic/ic-generic-logic.png")]
public class GlobalLogic : LogicBase
{
[Header("Base Value")]
public Globals.Scope scope = Globals.Scope.Global;
public Globals.Type type = Globals.Type.Boolean;
public string Variable = "SomeVariable";
public Evaluation evaluation = Evaluation.Equal;
[Header("Compare To...")]
[ShowIf("isCompareToOther")]
public CompareTo compareTo = CompareTo.Value;
[ShowIf("isBool")]
public bool boolValue = true;
[ShowIf("isInt")]
public int intValue = 1;
[ShowIf("isString")]
public string stringValue = "Value";
[ShowIf("isFloat")]
public float floatValue = 1.0f;
[ShowIf("isGameObject")]
public GameObject gameObjectValue;
[ShowIf("isGlobal")]
public string compareToVariable = "OtherVariable";
[ShowIf("isGlobal")]
public Globals.Scope compareToScope = Globals.Scope.Global;
public enum Evaluation
{
Equal,
NotEqual,
Greater,
GreaterOrEqual,
Less,
LessOrEqual,
Exists
}
public enum CompareTo
{
Value,
OtherGlobalVariable,
}
bool isBool() { return isValue() && type == Globals.Type.Boolean; }
bool isInt() { return isValue() && type == Globals.Type.Integer; }
bool isFloat() { return isValue() && type == Globals.Type.Float; }
bool isString() { return isValue() && type == Globals.Type.String; }
bool isGameObject() { return isValue() && type == Globals.Type.GameObject; }
bool isValue() { return compareTo == CompareTo.Value && isCompareToOther(); }
bool isGlobal() { return compareTo == CompareTo.OtherGlobalVariable && isCompareToOther(); }
bool isCompareToOther() { return evaluation != Evaluation.Exists; }
public Callable[] OnTestSuccess;
public Callable[] OnTestFail;
public override void Execute(GameObject instigator = null)
{
bool result = false;
if (evaluation == Evaluation.Exists)
{
switch (type)
{
case Globals.Type.Boolean: result = Globals.HasBool(Variable, scope); break;
case Globals.Type.Float: result = Globals.HasFloat(Variable, scope); break;
case Globals.Type.Integer: result = Globals.HasInt(Variable, scope); break;
case Globals.Type.String: result = Globals.HasString(Variable, scope); break;
case Globals.Type.GameObject: result = Globals.HasObject(Variable, scope); break;
}
}
else
{
try
{
switch (type)
{
case Globals.Type.Boolean:
result = TestValue(Globals.GetBool(Variable, scope), GetBoolValue());
break;
case Globals.Type.Integer:
result = TestValue(Globals.GetInt(Variable, scope), GetIntValue());
break;
case Globals.Type.Float:
result = TestValue(Globals.GetFloat(Variable, scope), GetFloatValue());
break;
case Globals.Type.String:
result = TestValue(Globals.GetString(Variable, scope), GetStringValue());
break;
case Globals.Type.GameObject:
result = TestObjectValue(Globals.GetObject(Variable, scope), GetObjectValue());
break;
}
}
catch { }
}
if (result)
Callable.Call(OnTestSuccess, instigator);
else
Callable.Call(OnTestFail, instigator);
}
bool GetBoolValue()
{
switch (compareTo)
{
default:
case CompareTo.Value:
return boolValue;
case CompareTo.OtherGlobalVariable:
return Globals.GetBool(compareToVariable, compareToScope);
}
}
int GetIntValue()
{
switch (compareTo)
{
default:
case CompareTo.Value:
return intValue;
case CompareTo.OtherGlobalVariable:
return Globals.GetInt(compareToVariable, compareToScope);
}
}
float GetFloatValue()
{
switch (compareTo)
{
default:
case CompareTo.Value:
return floatValue;
case CompareTo.OtherGlobalVariable:
return Globals.GetFloat(compareToVariable, compareToScope);
}
}
string GetStringValue()
{
switch (compareTo)
{
default:
case CompareTo.Value:
return stringValue;
case CompareTo.OtherGlobalVariable:
return Globals.GetString(compareToVariable, compareToScope);
}
}
GameObject GetObjectValue()
{
switch (compareTo)
{
default:
case CompareTo.Value:
return gameObjectValue;
case CompareTo.OtherGlobalVariable:
return Globals.GetObject(compareToVariable, compareToScope);
}
}
bool TestValue<T>(T value, T other) where T : System.IComparable<T>
{
switch (evaluation)
{
case Evaluation.Equal: return value.CompareTo(other) == 0;
case Evaluation.NotEqual: return value.CompareTo(other) != 0;
case Evaluation.Greater: return value.CompareTo(other) > 0;
case Evaluation.GreaterOrEqual: return value.CompareTo(other) >= 0;
case Evaluation.Less: return value.CompareTo(other) < 0;
case Evaluation.LessOrEqual: return value.CompareTo(other) <= 0;
}
return false;
}
bool TestObjectValue(GameObject value, GameObject other)
{
switch (evaluation)
{
case Evaluation.Equal:
return value == other;
case Evaluation.NotEqual:
case Evaluation.Greater:
case Evaluation.GreaterOrEqual:
case Evaluation.Less:
case Evaluation.LessOrEqual:
return value != other;
}
return false;
}
}
}
|
using System.Collections.Generic;
namespace Smartling.Api.Model
{
public class RecentlyPublished
{
public List<PublishedItem> items { get; set; }
public int totalCount { get; set; }
}
}
|
using System.ComponentModel.DataAnnotations;
namespace Foyer.Families.Dto
{
public class GetFamilyInput
{
[Range(1, int.MaxValue)]
public int FamilyId { get; set; }
}
} |
using UnityEngine;
using Bachelor.Utilities;
using System.Collections.Generic;
using Object = System.Object;
using Handler = System.Action<System.Object, System.Object>;
using SenderTable = System.Collections.Generic.Dictionary<
System.Object,
System.Collections.Generic.List<System.Action<
System.Object,
System.Object>
>
>;
namespace Bachelor.Managers
{
public class NotificationCenter : SingletonMonoBehaviourPersistent<NotificationCenter>
{
private Dictionary<string, SenderTable> m_NotificationTable = new Dictionary<string, SenderTable>();
private HashSet<List<Handler>> m_Invoking = new HashSet<List<Handler>>();
private NotificationCenter() { }
public void AddObserver(Handler handler, string notificationName, Object sender)
{
if (handler == null)
{
Debug.LogError("Can't add a null event handler for notification, " + notificationName);
return;
}
if (string.IsNullOrEmpty(notificationName))
{
Debug.LogError("Can't observe an unnamed notification");
return;
}
if (!m_NotificationTable.ContainsKey(notificationName))
{
m_NotificationTable.Add(notificationName, new SenderTable());
}
SenderTable subTable = m_NotificationTable[notificationName];
Object key = sender ?? (this);
if (!subTable.ContainsKey(key))
{
subTable.Add(key, new List<Handler>());
}
List<Handler> list = subTable[key];
if (!list.Contains(handler))
{
if (m_Invoking.Contains(list))
{
subTable[key] = list = new List<Handler>(list);
}
list.Add(handler);
}
}
public void AddObserver(Handler handler, string notificationName)
{
AddObserver(handler, notificationName, null);
}
public void RemoveObserver(Handler handler, string notificationName, Object sender)
{
if (handler == null)
{
Debug.LogError("Can't remove a null event handler for notification, " + notificationName);
return;
}
if (string.IsNullOrEmpty(notificationName))
{
Debug.LogError("A notification name is required to stop observation");
return;
}
if (!m_NotificationTable.ContainsKey(notificationName))
return;
SenderTable subTable = m_NotificationTable[notificationName];
Object key = sender ?? (this);
if (!subTable.ContainsKey(key))
{
return;
}
List<Handler> list = subTable[key];
int index = list.IndexOf(handler);
if (index != -1)
{
if (m_Invoking.Contains(list))
{
subTable[key] = list = new List<Handler>(list);
}
list.RemoveAt(index);
}
}
public void RemoveObserver(Handler handler, string notificationName)
{
RemoveObserver(handler, notificationName, null);
}
public void PostNotification(string notificationName, Object sender, Object target)
{
if (string.IsNullOrEmpty(notificationName))
{
Debug.LogError("A notification name is required");
return;
}
if (!m_NotificationTable.ContainsKey(notificationName))
{
return;
}
SenderTable subTable = m_NotificationTable[notificationName];
if (sender != null && subTable.ContainsKey(sender))
{
List<Handler> handlers = subTable[sender];
m_Invoking.Add(handlers);
for (int i = 0; i < handlers.Count; ++i)
{
handlers[i](sender, target);
}
m_Invoking.Remove(handlers);
}
if (subTable.ContainsKey(this))
{
List<Handler> handlers = subTable[this];
m_Invoking.Add(handlers);
for (int i = 0; i < handlers.Count; ++i)
{
handlers[i](sender, target);
}
m_Invoking.Remove(handlers);
}
}
public void PostNotification(string notificationName, Object sender)
{
PostNotification(notificationName, sender, null);
}
public void PostNotification(string notificationName)
{
PostNotification(notificationName, null);
}
public void Clean()
{
string[] notKeys = new string[m_NotificationTable.Keys.Count];
m_NotificationTable.Keys.CopyTo(notKeys, 0);
for (int i = notKeys.Length - 1; i >= 0; --i)
{
string notificationName = notKeys[i];
SenderTable senderTable = m_NotificationTable[notificationName];
Object[] senKeys = new Object[senderTable.Keys.Count];
senderTable.Keys.CopyTo(senKeys, 0);
for (int j = senKeys.Length - 1; j >= 0; --j)
{
Object sender = senKeys[j];
List<Handler> handlers = senderTable[sender];
if (handlers.Count == 0)
{
senderTable.Remove(sender);
}
}
if (senderTable.Count == 0)
{
m_NotificationTable.Remove(notificationName);
}
}
}
}
} |
namespace Rhinobyte.Extensions.TestTools;
/// <summary>
/// Wait/delay configuration item values for a given category key
/// </summary>
public class WaitConfigurationItem
{
/// <summary>
/// The value to use for the delay or the initial delay value to use before first checking the wait condition
/// </summary>
public int? Delay { get; set; }
/// <summary>
/// The polling interval to wait for before subsequent checks of the wait condition
/// </summary>
public int? PollingInterval { get; set; }
/// <summary>
/// The timeout threshold of the wait condition
/// </summary>
public int? TimeoutInterval { get; set; }
}
|
using System;
using NUnit.Framework;
using static procdiag.tests.RunUtility;
namespace procdiag.tests.integration
{
[TestFixture]
[Category("Integration")]
internal class MemoryStatsTests
{
[Test]
public void X86_ShouldPrintMemoryStats()
{
// arrange
using (var process = StartProcess("TestProcessX86.exe"))
{
//act
var result = Execute(new[] { $"-p {process.Id} --stats" });
AssertOutput(result);
}
}
[Test]
public void X64private_ShouldPrintMemoryStats()
{
// arrange
using (var process = StartProcess("TestProcessX64.exe"))
{
//act
var result = Execute(new[] { $"-p {process.Id} --stats" });
AssertOutput(result);
}
}
private static void AssertOutput(string result)
{
StringAssert.Contains("Heap stats:", result);
StringAssert.Contains("Size Count Type", result);
StringAssert.EndsWith("Heap stats finished." + Environment.NewLine, result);
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using ProtoBuf;
namespace Mediator
{
public interface IData
{
//Weeell, let client be creating new data.
string Locked { get; }
string Version { get; }
string EditBy { get; }
string EditTime { get; }
string Id { get; set; }
bool IsFullDataRecieved { get; }
}
public class Data : IData, INotifyPropertyChanged
{
public string Id { get; set; }
public virtual bool IsFullDataRecieved => true;
public virtual string Locked { get; set; }
public virtual string Version { get; set; }
public virtual string EditBy { get; set; }
public virtual string EditTime { get; set; }
#region notify
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
[ProtoContract]
public class ScriptData : Data, INotifyPropertyChanged
{
#region kostyl' because of protobuf
private string _locked;
[ProtoMember(1)]
public override string Locked
{
get { return _locked; }
set
{
_locked = value;
OnPropertyChanged();
}
}
private string _version;
[ProtoMember(2)]
public override string Version
{
get { return _version; }
set
{
_version = value;
OnPropertyChanged();
}
}
private string _editBy;
[ProtoMember(3)]
public override string EditBy
{
get { return _editBy; }
set
{
_editBy = value;
OnPropertyChanged();
}
}
private string _editTime;
[ProtoMember(4)]
public override string EditTime
{
get { return _editTime; }
set
{
_editTime = value;
OnPropertyChanged();
}
}
#endregion
[ProtoMember(5)]
public string Type { get; set; }
[ProtoMember(6)]
public byte[] Data { get; set; }
}
[ProtoContract]
public class TextData : Data, INotifyPropertyChanged
{
#region kostyl' because of protobuf
private string _locked;
[ProtoMember(1)]
public override string Locked
{
get { return _locked; }
set
{
_locked = value;
OnPropertyChanged();
}
}
private string _version;
[ProtoMember(2)]
public override string Version
{
get { return _version; }
set
{
_version = value;
OnPropertyChanged();
}
}
private string _editBy;
[ProtoMember(3)]
public override string EditBy
{
get { return _editBy; }
set
{
_editBy = value;
OnPropertyChanged();
}
}
private string _editTime;
[ProtoMember(4)]
public override string EditTime
{
get { return _editTime; }
set
{
_editTime = value;
OnPropertyChanged();
}
}
#endregion
private string _text;
[ProtoMember(5)]
public string Text
{
get { return _text; }
set
{
_text = value;
OnPropertyChanged();
}
}
}
[ProtoContract]
public class DialogData : Data, INotifyPropertyChanged
{
#region kostyl' because of protobuf
private string _locked;
[ProtoMember(1)]
public override string Locked
{
get { return _locked; }
set
{
_locked = value;
OnPropertyChanged();
}
}
private string _version;
[ProtoMember(2)]
public override string Version
{
get { return _version; }
set
{
_version = value;
OnPropertyChanged();
}
}
private string _editBy;
[ProtoMember(3)]
public override string EditBy
{
get { return _editBy; }
set
{
_editBy = value;
OnPropertyChanged();
}
}
private string _editTime;
[ProtoMember(4)]
public override string EditTime
{
get { return _editTime; }
set
{
_editTime = value;
OnPropertyChanged();
}
}
#endregion
#region Members
private string _name;
[ProtoMember(5)]
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged();
}
}
private string _tags;
[ProtoMember(6)]
public string Tags
{
get { return _tags; }
set
{
_tags = value;
OnPropertyChanged();
}
}
private string _description;
[ProtoMember(7)]
public string Description
{
get { return _description; }
set
{
_description = value;
OnPropertyChanged();
}
}
/// <summary>
/// Data can be recieved only with using GetById() or with RecieveData()
/// </summary>
[ProtoMember(8, IsRequired = false)]
public byte[] Data { get; set; }
public new bool IsFullDataRecieved => Data != null;
#endregion
}
[ProtoContract]
public class CharacterData : Data, INotifyPropertyChanged
{
#region kostyl' because of protobuf
private string _locked;
[ProtoMember(1)]
public override string Locked
{
get { return _locked; }
set
{
_locked = value;
OnPropertyChanged();
}
}
private string _version;
[ProtoMember(2)]
public override string Version
{
get { return _version; }
set
{
_version = value;
OnPropertyChanged();
}
}
private string _editBy;
[ProtoMember(3)]
public override string EditBy
{
get { return _editBy; }
set
{
_editBy = value;
OnPropertyChanged();
}
}
private string _editTime;
[ProtoMember(4)]
public override string EditTime
{
get { return _editTime; }
set
{
_editTime = value;
OnPropertyChanged();
}
}
#endregion
#region Members
private string _nameId;
/// <summary>
/// ID of TextData from Texts DB. You must get it by yourself. A value of the field can be changed.
/// </summary>
[ProtoMember(5)]
public string NameId
{
get { return _nameId; }
set
{
_nameId = value;
OnPropertyChanged();
}
}
//TODO: Я сомневаюсь насчёт OnPropertyChanged в некоторых местах - решим потом.
private string _tags;
[ProtoMember(6)]
public string Tags
{
get { return _tags; }
set
{
_tags = value;
OnPropertyChanged();
}
}
private string _groups;
[ProtoMember(7)]
public string Groups
{
get { return _groups; }
set
{
_groups = value;
OnPropertyChanged();
}
}
private string _description;
[ProtoMember(8)]
public string Description
{
get { return _description; }
set
{
_description = value;
OnPropertyChanged();
}
}
[ProtoMember(9, IsRequired = false)]
public byte[] Sets { get; set; }
[ProtoMember(10, IsRequired = false)]
public byte[] Behavior { get; set; }
[ProtoMember(11, IsRequired = false)]
public byte[] Knowledge { get; set; }
public new bool IsFullDataRecieved => Behavior != null;
#endregion
}
}
|
using Hashtables.Classes;
using System;
using Xunit;
namespace HashtablesTest
{
public class UnitTest1
{
/// <summary>
/// Testing that a value can be added
/// </summary>
/// <param name="test">Value to add</param>
[Theory]
[InlineData("Test")]
[InlineData("Cat")]
[InlineData("Dog")]
public void CanAddToHashtable(string test)
{
//Arrange
Hashtable hs = new Hashtable();
//Act
hs.Add(test, "value");
//Assert
Assert.True(hs.Contains(test));
}
/// <summary>
/// Testing that a value can be found
/// </summary>
/// <param name="value">Value to add</param>
[Theory]
[InlineData("Test")]
[InlineData("Cat")]
[InlineData("Dog")]
public void CanFindOnHashtable(string value)
{
//Arrange
Hashtable hs = new Hashtable();
//Act
hs.Add("Key", value);
//Assert
Assert.Equal(value, hs.Find("Key"));
}
/// <summary>
/// Testing that a colliding key can be added
/// </summary>
/// <param name="val1">First value to add</param>
/// /// <param name="val1">Colliding value to add</param>
[Theory]
[InlineData("Top", "Pot")]
[InlineData("Dog", "God")]
[InlineData("Cool", "Loco")]
public void CanAddCollisonsOnHashtable(string val1, string val2)
{
//Arrange
Hashtable hs = new Hashtable();
//Act
hs.Add(val1, "Value");
hs.Add(val2, "Value 2");
//Assert
Assert.Equal("Value 2" , hs.Find(val2));
}
}
}
|
using TMPro;
using UnityEngine;
[RequireComponent(typeof(TextMeshProUGUI))]
public class ScoreTextDisplay : MonoBehaviour
{
[SerializeField]
private LevelSpec levelSpec;
[SerializeField]
private FloatReference charactersReachedGoal;
private TextMeshProUGUI textField;
private void Awake()
{
textField = gameObject.GetComponent<TextMeshProUGUI>();
}
private void Start()
{
UpdateText();
}
private void UpdateText()
{
if (textField != null)
{
textField.text = $"{charactersReachedGoal.Value}/{levelSpec.TargetGoalAmount.Value}";
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OmmitedDTOModel3
{
public class EntityDTO12 : BaseEntity
{
public EntityDTO12()
{
//this.Entities20 = new EntityDTO20();
//this.Entities14 = new EntityDTO14();
//Entities16 = new EntityDTO16();
}
public EntityDTO20 Entities20 { get; set; }
public EntityDTO16 Entities16 { get; set; }
public EntityDTO14 Entities14 { get; set; }
}
}
|
/*******************************************************
*
* 作者:CodeProject
* 创建时间:2009
* 说明:此文件只包含一个类,具体内容见类型注释。
* 运行环境:.NET 4.0
* 版本号:1.0.0
*
* 历史记录:
* 创建文件 CodeProject 2009
*
*******************************************************/
using System;
using System.Data;
using Rafy.Domain.ORM.Query;
using Rafy.Domain.ORM.SqlTree;
using Rafy.MetaModel;
namespace Rafy.Domain.ORM
{
/// <summary>
/// 数据表列
/// </summary>
internal interface IRdbColumnInfo : IColumnNode, ISqlSelectionColumn, ISqlNode, IHasName
{
/// <summary>
/// 对应的列的元数据。
/// </summary>
ColumnMeta Meta { get; }
/// <summary>
/// 对应的表
/// </summary>
new IRdbTableInfo Table { get; }
/// <summary>
/// 属性的类型。
/// 如果属性是可空类型。这里会去除可空类型,返回内部的真实属性类型。
/// </summary>
Type CorePropertyType { get; }
/// <summary>
/// 是否为自增长主键列。
/// </summary>
bool IsIdentity { get; }
/// <summary>
/// 是否主键列
/// </summary>
bool IsPrimaryKey { get; }
}
} |
/*
* ImageAttributes.cs - Implementation of the
* "System.Drawing.Imaging.ImageAttributes" class.
*
* Copyright (C) 2003 Southern Storm Software, Pty Ltd.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
using System;
using Portable.Drawing.Drawing2D;
namespace Portable.Drawing.Imaging
{
public sealed class ImageAttributes : ICloneable, IDisposable
{
public enum ColorAdjustType
{
Default = 0,
Bitmap = 1,
Brush = 2,
Pen = 3,
Text = 4,
Count = 5,
Any = 6
};
// Attribute information for a particular ColorAdjustType value.
private sealed class AttributeInfo : ICloneable
{
// Accessible state.
public AttributeInfo next;
public ColorAdjustType type;
public Color colorLow;
public Color colorHigh;
public ColorMatrix colorMatrix;
public ColorMatrix grayMatrix;
public ColorMatrixFlag matrixFlags;
public float gamma;
public bool noOp;
public ColorChannelFlag channelFlags;
public string profile;
public ColorMap[] map;
public float threshold;
// Constructor.
public AttributeInfo(AttributeInfo next, ColorAdjustType type)
{
this.next = next;
this.type = type;
}
// Clone this object.
public object Clone()
{
AttributeInfo info = (AttributeInfo)(MemberwiseClone());
if(next != null)
{
info.next = (AttributeInfo)(next.Clone());
}
return info;
}
}; // class AttributeInfo
// Internal state.
private WrapMode mode;
private Color color;
private bool clamp;
private AttributeInfo info;
// Constructor.
public ImageAttributes() {}
// Get the attribute information for a specific ColorAdjustType value.
private AttributeInfo GetInfo(ColorAdjustType type)
{
AttributeInfo current = info;
while(current != null)
{
if(current.type == type)
{
return current;
}
current = current.next;
}
info = new AttributeInfo(info, type);
return info;
}
// Clear the brush remap table.
public void ClearBrushRemapTable()
{
ClearRemapTable(ColorAdjustType.Brush);
}
// Clear color keys.
public void ClearColorKey()
{
ClearColorKey(ColorAdjustType.Default);
}
public void ClearColorKey(ColorAdjustType type)
{
AttributeInfo info = GetInfo(type);
info.colorLow = Color.Empty;
info.colorHigh = Color.Empty;
}
// Clear color matrices.
public void ClearColorMatrix()
{
ClearColorMatrix(ColorAdjustType.Default);
}
public void ClearColorMatrix(ColorAdjustType type)
{
AttributeInfo info = GetInfo(type);
info.colorMatrix = null;
info.grayMatrix = null;
info.matrixFlags = ColorMatrixFlag.Default;
}
// Disable gamma correction.
public void ClearGamma()
{
ClearGamma(ColorAdjustType.Default);
}
public void ClearGamma(ColorAdjustType type)
{
GetInfo(type).gamma = 0.0f;
}
// Clear the NoOp setting.
public void ClearNoOp()
{
ClearNoOp(ColorAdjustType.Default);
}
public void ClearNoOp(ColorAdjustType type)
{
GetInfo(type).noOp = false;
}
// Clear the output channel setting.
public void ClearOutputChannel()
{
ClearOutputChannel(ColorAdjustType.Default);
}
public void ClearOutputChannel(ColorAdjustType type)
{
GetInfo(type).channelFlags = ColorChannelFlag.ColorChannelC;
}
// Clear the output channel color profile setting.
public void ClearOutputChannelColorProfile()
{
ClearOutputChannelColorProfile(ColorAdjustType.Default);
}
public void ClearOutputChannelColorProfile(ColorAdjustType type)
{
GetInfo(type).profile = null;
}
// Clear the remap table.
public void ClearRemapTable()
{
ClearRemapTable(ColorAdjustType.Default);
}
public void ClearRemapTable(ColorAdjustType type)
{
GetInfo(type).map = null;
}
// Clear the threshold setting.
public void ClearThreshold()
{
ClearThreshold(ColorAdjustType.Default);
}
public void ClearThreshold(ColorAdjustType type)
{
GetInfo(type).threshold = 0.0f;
}
// Clone this object.
public object Clone()
{
ImageAttributes attrs = (ImageAttributes)(MemberwiseClone());
if(info != null)
{
attrs.info = (AttributeInfo)(info.Clone());
}
return attrs;
}
// Dispose of this object.
public void Dispose()
{
info = null;
GC.SuppressFinalize(this);
}
// Adjust a palette according to a color adjustment type.
[TODO]
public void GetAdjustedPalette(ColorPalette palette, ColorAdjustType type)
{
// TODO
}
// Set the brush remap table.
public void SetBrushRemapTable(ColorMap[] map)
{
SetRemapTable(map, ColorAdjustType.Brush);
}
// Set a color key.
public void SetColorKey(Color colorLow, Color colorHigh)
{
SetColorKey(colorLow, colorHigh, ColorAdjustType.Default);
}
public void SetColorKey(Color colorLow, Color colorHigh,
ColorAdjustType type)
{
AttributeInfo info = GetInfo(type);
info.colorLow = colorLow;
info.colorHigh = colorHigh;
}
// Set color matrices.
public void SetColorMatrices(ColorMatrix newColorMatrix,
ColorMatrix grayMatrix)
{
SetColorMatrices(newColorMatrix, grayMatrix,
ColorMatrixFlag.Default,
ColorAdjustType.Default);
}
public void SetColorMatrices(ColorMatrix newColorMatrix,
ColorMatrix grayMatrix,
ColorMatrixFlag flags)
{
SetColorMatrices(newColorMatrix, grayMatrix, flags,
ColorAdjustType.Default);
}
public void SetColorMatrices(ColorMatrix newColorMatrix,
ColorMatrix grayMatrix,
ColorMatrixFlag flags,
ColorAdjustType type)
{
AttributeInfo info = GetInfo(type);
info.colorMatrix = newColorMatrix;
info.grayMatrix = grayMatrix;
info.matrixFlags = flags;
}
public void SetColorMatrix(ColorMatrix newColorMatrix)
{
SetColorMatrix(newColorMatrix, ColorMatrixFlag.Default);
}
public void SetColorMatrix(ColorMatrix newColorMatrix, ColorMatrixFlag flags)
{
SetColorMatrix(newColorMatrix, flags, ColorAdjustType.Default);
}
public void SetColorMatrix(ColorMatrix newColorMatrix,
ColorMatrixFlag mode, ColorAdjustType type)
{
AttributeInfo info = GetInfo(type);
info.colorMatrix = newColorMatrix;
info.matrixFlags = mode;
}
// Set a gamma setting.
public void SetGamma(float gamma)
{
SetGamma(gamma, ColorAdjustType.Default);
}
public void SetGamma(float gamma, ColorAdjustType type)
{
GetInfo(type).gamma = gamma;
}
// Set the no-operation flag.
public void SetNoOp()
{
SetNoOp(ColorAdjustType.Default);
}
public void SetNoOp(ColorAdjustType type)
{
GetInfo(type).noOp = true;
}
// Set an output channel setting.
public void SetOutputChannel(ColorChannelFlag flags)
{
SetOutputChannel(flags, ColorAdjustType.Default);
}
public void SetOutputChannel(ColorChannelFlag flags, ColorAdjustType type)
{
GetInfo(type).channelFlags = flags;
}
// Set an output channel color profile setting.
public void SetOutputChannelColorProfile(string colorProfileFilename)
{
SetOutputChannelColorProfile(colorProfileFilename,
ColorAdjustType.Default);
}
public void SetOutputChannelColorProfile(string colorProfileFilename,
ColorAdjustType type)
{
GetInfo(type).profile = colorProfileFilename;
}
// Set a color remap table.
public void SetRemapTable(ColorMap[] map)
{
SetRemapTable(map, ColorAdjustType.Default);
}
public void SetRemapTable(ColorMap[] map, ColorAdjustType type)
{
GetInfo(type).map = map;
}
// Set the threshold setting.
public void SetThreshold(float threshold)
{
SetThreshold(threshold, ColorAdjustType.Default);
}
public void SetThreshold(float threshold, ColorAdjustType type)
{
GetInfo(type).threshold = threshold;
}
// Set the texture wrapping mode.
public void SetWrapMode(WrapMode mode)
{
SetWrapMode(mode, Color.Empty, false);
}
public void SetWrapMode(WrapMode mode, Color color)
{
SetWrapMode(mode, color, false);
}
public void SetWrapMode(WrapMode mode, Color color, bool clamp)
{
this.mode = mode;
this.color = color;
this.clamp = clamp;
}
}; // class ImageAttributes
}; // namespace System.Drawing.Imaging
|
using System.Threading.Tasks;
using BookLovers.Base.Infrastructure;
using BookLovers.Librarians.Domain.TicketOwners;
using BookLovers.Librarians.Domain.Tickets;
using BookLovers.Librarians.Domain.Tickets.TicketReasons;
using BookLovers.Librarians.Events.TicketOwners;
namespace BookLovers.Librarians.Domain.Librarians.DecisionNotifiers
{
internal class AcceptBookDecisionNotifier : IDecisionNotifier
{
private readonly ITicketOwnerRepository _ticketOwnerRepository;
private readonly IUnitOfWork _unitOfWork;
public ITicketSummary TicketSummary => new BookTicketAccepted();
public AcceptBookDecisionNotifier(
ITicketOwnerRepository ticketOwnerRepository,
IUnitOfWork unitOfWork)
{
this._ticketOwnerRepository = ticketOwnerRepository;
this._unitOfWork = unitOfWork;
}
public async Task Notify(Ticket ticket, string justification)
{
var ticketOwner =
await this._ticketOwnerRepository.GetOwnerByReaderGuidAsync(ticket.IssuedBy.TicketOwnerGuid);
this.TicketSummary.SetNotification(justification);
if (this.TicketSummary.IsValid())
{
var createdBookAccepted = CreatedBookAccepted.Initialize()
.WithAggregate(ticketOwner.Guid)
.AcceptedBy(ticket.SolvedBy.LibrarianGuid.Value)
.WithTicketOwner(ticketOwner.ReaderGuid)
.WithTicket(ticket.Guid, this.TicketSummary.Notification)
.WithBook(ticket.TicketContent.TicketObjectGuid, ticket.TicketContent.Content);
ticketOwner.NotifyOwner(createdBookAccepted);
}
await this._unitOfWork.CommitAsync(ticketOwner);
}
}
} |
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Microsoft.AspNetCore.Mvc.Rendering;
using MovieRating.Movies;
using System;
using System.Collections.Generic;
namespace MovieRating
{
[AutoMapFrom(typeof(MovieDetails))]
public class MovieListDto : IEntityDto
{
public string Title { get; set; }
public string Genre { get; set; }
public DateTime ReleaseDate { get; set; }
public int Id { get ; set ; }
public bool allowReviewAdd = true;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using Unity.Jobs;
using Unity.Collections;
using Unity.Physics;
using Unity.Physics.Systems;
public class RaycastHitJob : MonoBehaviour
{
public float distance = 10.0f;
public Vector3 direction = Vector3.forward;
public bool collect_all_hits = false;
public bool draw_surface_normals = true;
RaycastInput raycast_input;
float3 origin;
float3 ray_direction;
NativeList<Unity.Physics.RaycastHit> raycast_hits;
NativeList<DistanceHit> distance_hits;
BuildPhysicsWorld physics_world;
StepPhysicsWorld step_world;
EntityManager manager;
// Start is called before the first frame update
void Start()
{
// Allocator.Persistent: 持續存在記憶體當中,直到程式結束
raycast_hits = new NativeList<Unity.Physics.RaycastHit>(Allocator.Persistent);
distance_hits = new NativeList<DistanceHit>(Allocator.Persistent);
physics_world = World.DefaultGameObjectInjectionWorld.GetOrCreateSystem<BuildPhysicsWorld>();
step_world = World.DefaultGameObjectInjectionWorld.GetOrCreateSystem<StepPhysicsWorld>();
manager = World.DefaultGameObjectInjectionWorld.EntityManager;
}
// Update is called once per frame
void LateUpdate()
{
step_world.FinalJobHandle.Complete();
origin = transform.position;
ray_direction = (transform.rotation * direction) * distance;
raycast_hits.Clear();
distance_hits.Clear();
raycast_input = new RaycastInput
{
Start = origin,
End = origin + ray_direction,
Filter = CollisionFilter.Default
};
JobHandle handle = new RaycastJob
{
raycast_input = raycast_input,
raycast_hits = raycast_hits,
collect_all_hits = collect_all_hits,
world = physics_world.PhysicsWorld
}.Schedule();
handle.Complete();
foreach (Unity.Physics.RaycastHit hit in raycast_hits.ToArray())
{
var entity = physics_world.PhysicsWorld.Bodies[hit.RigidBodyIndex].Entity;
manager.DestroyEntity(entity);
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawRay(raycast_input.Start, raycast_input.End - raycast_input.Start);
if (raycast_hits.IsCreated)
{
foreach(Unity.Physics.RaycastHit hit in raycast_hits.ToArray())
{
Assert.IsTrue(0 <= hit.RigidBodyIndex && hit.RigidBodyIndex < physics_world.PhysicsWorld.NumBodies);
Assert.IsTrue(math.abs(math.lengthsq(hit.SurfaceNormal) - 1.0f) < 0.01f);
Gizmos.color = Color.magenta;
Gizmos.DrawRay(raycast_input.Start, hit.Position - raycast_input.Start);
Gizmos.DrawSphere(hit.Position, 0.02f);
if (draw_surface_normals)
{
Gizmos.color = Color.green;
Gizmos.DrawRay(hit.Position, hit.SurfaceNormal);
}
}
}
}
private void OnDestroy()
{
if (raycast_hits.IsCreated)
{
raycast_hits.Dispose();
}
if (distance_hits.IsCreated)
{
distance_hits.Dispose();
}
}
}
public struct RaycastJob : IJob
{
[ReadOnly] public PhysicsWorld world;
public RaycastInput raycast_input;
public NativeList<Unity.Physics.RaycastHit> raycast_hits;
public bool collect_all_hits;
public void Execute()
{
if (collect_all_hits)
{
world.CastRay(raycast_input, ref raycast_hits);
}
else if (world.CastRay(raycast_input, out Unity.Physics.RaycastHit hit))
{
raycast_hits.Add(hit);
}
}
} |
using System;
using System.Collections.Generic;
namespace Xyperico.Agres.MessageBus.Subscription
{
public interface ISubscriptionService
{
QueueName InputQueueName { get; }
/// <summary>
/// Local process making a subscription request to remote service
/// </summary>
/// <param name="messageType"></param>
void Subscribe(Type messageType, IMessageSink messageSink);
/// <summary>
/// Remote service subscribing to local process
/// </summary>
/// <param name="messageType"></param>
/// <param name="destination"></param>
void AddSubscriber(Type messageType, QueueName destination);
/// <summary>
/// Get all remote subscribers for a single message
/// </summary>
/// <param name="messageType"></param>
/// <returns></returns>
IEnumerable<QueueName> GetSubscribers(Type messageType);
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
using InventoryPoc.Data.Models.Profile;
namespace InventoryPoc.Data.Mappings.Profile
{
public class GroupMapping : EntityTypeConfiguration<Group>
{
public GroupMapping()
{
ToTable("Group");
HasKey(x => x.Id);
Property(x => x.GroupName).HasMaxLength(200).IsRequired();
Property(x => x.GroupName2).HasMaxLength(200);
Property(x => x.Location).HasMaxLength(200);
Property(x => x.GroupNumber).HasMaxLength(100);
Property(x => x.CostReplacementNewTrendDate).IsOptional();
Property(x => x.AtReportedCost).HasPrecision(18, 2);
HasOptional(x => x.Member).WithRequired(x => x.Group);
HasMany(x => x.InventoryEntities).WithRequired(x => x.Group).HasForeignKey(x => x.GroupId);
HasMany(x => x.AccountingHeaders).WithRequired(x => x.Group).HasForeignKey(x => x.GroupId);
HasMany(x => x.ScheduledItems).WithRequired(x => x.Group).HasForeignKey(x => x.GroupId);
HasMany(x => x.ProcessingInstructions).WithRequired(x => x.Group).HasForeignKey(x => x.GroupId);
HasMany(x => x.Comments).WithRequired(x => x.Group).HasForeignKey(x => x.GroupId);
HasMany(x => x.GroupUsers).WithOptional(x => x.Group).HasForeignKey(x => x.GroupId);
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace PropCalc
{
public static class DrawFormula
{
public static PictureBox pbDraw = null;
private static Font fntXr = new Font("Microsoft Sans Serif", 18,
FontStyle.Italic, GraphicsUnit.Point);
private static Font fntNumbers = new Font("Microsoft Sans Serif", 10,
FontStyle.Regular, GraphicsUnit.Point);
private static Bitmap view = null;
private static Graphics graph;
private static Timer tmrDraw = new Timer();
private static string M1 = "";
private static string M2 = "";
private static string D = "";
private static string A = "";
public static void InitGraph()
{
view = new Bitmap(pbDraw.Width, pbDraw.Height);
graph = Graphics.FromImage((Image)view);
tmrDraw.Interval = 100;
tmrDraw.Tick += new EventHandler(tmrDraw_Tick);
tmrDraw.Start();
}
public static void SetStrings(string m1, string m2, string d, string a)
{
M1 = m1; M2 = m2; D = d; A = a;
}
static void tmrDraw_Tick(object sender, EventArgs e)
{
graph.Clear(pbDraw.BackColor);
int width = graph.MeasureString("X = ", fntXr).ToSize().Width;
int height = graph.MeasureString("X = ", fntXr).ToSize().Height;
int ycenter = pbDraw.Height / 2;
int ycentertxt = ycenter - 15;
Brush brush = new SolidBrush(Color.Black);
graph.DrawString("X = ", fntXr, brush, 5, ycentertxt);
string sNumerator = M1 + " × " + M2;
int xnumerator = width + 12;
int ynumerator = ycenter - 20;
int wnumerator = graph.MeasureString(sNumerator, fntNumbers).
ToSize().Width;
int hnumerator = graph.MeasureString(sNumerator, fntNumbers).
ToSize().Height;
graph.DrawString(sNumerator, fntNumbers, brush, xnumerator, ynumerator);
int xdenom = width + 12;
int ydenom = ycenter + 5;
int wdenom = graph.MeasureString(D, fntNumbers).
ToSize().Width;
int hdenom = graph.MeasureString(sNumerator, fntNumbers).
ToSize().Height;
graph.DrawString(D, fntNumbers, brush, xdenom, ydenom);
int maxwidth = wnumerator;
if (maxwidth < wdenom) maxwidth = wdenom;
Pen pen = new Pen(brush, 2);
width = width + 12;
graph.DrawLine(pen, width, ycenter, width + maxwidth, ycenter);
string stAnswer = "";
if ((A == "0") && (calc.ErrorMessage != string.Empty))
{
stAnswer = " = ∅";
}
else
{
stAnswer = " = " + A;
}
int xanswer = width + maxwidth;
graph.DrawString(stAnswer, fntXr, brush, xanswer, ycentertxt);
pbDraw.Image = (Image)view;
}
}
}
|
using System;
using Foundation;
using UIKit;
using Plugin.SimpleAudioPlayer;
namespace SAPlayerSample.tvOS
{
public partial class ViewController : UIViewController
{
Plugin.SimpleAudioPlayer.Abstractions.ISimpleAudioPlayer player;
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
player = CrossSimpleAudioPlayer.Current;
player.Load("Diminished.mp3");
}
partial void PlayButton_PrimaryActionTriggered(UIButton sender)
{
player.Play();
isPlaying.Text = "Playing";
}
public override void DidReceiveMemoryWarning()
{
base.DidReceiveMemoryWarning();
// Release any cached data, images, etc that aren't in use.
}
partial void StopButton_PrimaryActionTriggered(UIButton sender)
{
player.Stop();
isPlaying.Text = "Stopped";
}
}
}
|
using FubuMVC.Core.ServiceBus.Runtime.Routing;
using NUnit.Framework;
using Shouldly;
namespace FubuMVC.Tests.ServiceBus.Runtime.Routing
{
[TestFixture]
public class LambdaRoutingRuleTester
{
[Test]
public void positive_match()
{
var rule = new LambdaRoutingRule(type => type == typeof (BusSettings));
rule.Matches(typeof(BusSettings)).ShouldBeTrue();
}
[Test]
public void negative_match()
{
var rule = new LambdaRoutingRule(type => type == typeof(BusSettings));
rule.Matches(GetType()).ShouldBeFalse();
}
}
} |
#region Copyright
// ****************************************************************************
// <copyright file="CompiledExpressionInvoker.cs">
// Copyright (c) 2012-2017 Vyacheslav Volkov
// </copyright>
// ****************************************************************************
// <author>Vyacheslav Volkov</author>
// <email>vvs0205@outlook.com</email>
// <project>MugenMvvmToolkit</project>
// <web>https://github.com/MugenMvvmToolkit/MugenMvvmToolkit</web>
// <license>
// See license.txt in this solution or http://opensource.org/licenses/MS-PL
// </license>
// ****************************************************************************
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Runtime.InteropServices;
using JetBrains.Annotations;
using MugenMvvmToolkit.Attributes;
using MugenMvvmToolkit.Binding.DataConstants;
using MugenMvvmToolkit.Binding.Interfaces.Models;
using MugenMvvmToolkit.Binding.Interfaces.Parse;
using MugenMvvmToolkit.Binding.Interfaces.Parse.Nodes;
using MugenMvvmToolkit.Binding.Models;
using MugenMvvmToolkit.Binding.Parse.Nodes;
using MugenMvvmToolkit.Infrastructure;
using MugenMvvmToolkit.Interfaces.Models;
using MugenMvvmToolkit.Models;
namespace MugenMvvmToolkit.Binding.Parse
{
public class CompiledExpressionInvoker : IExpressionInvoker
{
#region Nested types
[StructLayout(LayoutKind.Auto)]
public struct CacheKey
{
#region Fields
public int Hash;
public Type[] Types;
#endregion
#region Constructors
public CacheKey(Type[] types)
{
Types = types;
Hash = 0;
unchecked
{
for (int index = 0; index < types.Length; index++)
{
Type type = types[index];
Hash += type == null ? 0 : type.GetHashCode();
}
}
}
#endregion
}
[Preserve(AllMembers = true, Conditional = true)]
public sealed class MethodInvoker : Dictionary<CacheKey, Func<object[], object>>
{
#region Fields
private Type _type;
#endregion
#region Constructors
public MethodInvoker() : base(CacheKeyComparer.Instance)
{
}
#endregion
#region Methods
public object InvokeIndex(object target, object[] args)
{
return InvokeMethodInternal(target, ReflectionExtensions.IndexerName, args, null);
}
public object Invoke(object target, string methodName, object[] args, Type[] typeArgs)
{
return InvokeMethodInternal(target, methodName, args, typeArgs);
}
private object InvokeMethodInternal(object target, string methodName, object[] args, Type[] typeArgs)
{
var type = target.GetType();
var argTypes = GetArgTypes(args);
var key = new CacheKey(argTypes);
Func<object[], object> result = null;
lock (this)
{
if (type == _type)
TryGetValue(key, out result);
}
if (result != null)
return result(BindingReflectionExtensions.InsertFirstArg(args, target));
List<MethodInfo> methods;
if (methodName == ReflectionExtensions.IndexerName)
{
methods = new List<MethodInfo>();
foreach (var property in type.GetPropertiesEx(MemberFlags.Public | MemberFlags.Instance))
{
if (property.GetIndexParameters().Length == args.Length)
methods.AddIfNotNull(property.GetGetMethod(true));
}
}
else
{
methods = BindingReflectionExtensions.GetExtensionsMethods(methodName, BindingServiceProvider.ResourceResolver.GetKnownTypes());
foreach (var method in type.GetMethodsEx(MemberFlags.Public | MemberFlags.Instance))
{
try
{
if (method.Name == methodName)
methods.AddIfNotNull(BindingReflectionExtensions.ApplyTypeArgs(method, typeArgs));
}
catch
{
;
}
}
}
bool hasParams;
var resultIndex = TrySelectMethod(methods, argTypes, (i, types) => types, out hasParams);
if (resultIndex >= 0)
{
var method = methods[resultIndex];
var parameters = argTypes.Select(t => (Expression)Expression.Parameter(t)).ToList();
var argExpressions = ConvertParameters(method.GetParameters(), parameters, hasParams);
parameters.Insert(0, Expression.Parameter(type));
var compile = Expression.Lambda(Expression.Call(parameters[0], method, argExpressions), parameters.Cast<ParameterExpression>()).Compile();
var methodInfo = compile.GetType().GetMethodEx(nameof(Action.Invoke), MemberFlags.Public | MemberFlags.Instance);
if (methodInfo == null)
result = compile.DynamicInvoke;
else
{
var del = ToolkitServiceProvider.ReflectionManager.GetMethodDelegate(methodInfo);
result = objects => del(compile, objects);
}
}
lock (this)
{
_type = type;
this[key] = result;
}
if (result == null)
throw BindingExceptionManager.InvalidBindingMember(target.GetType(), methodName);
return result(BindingReflectionExtensions.InsertFirstArg(args, target));
}
private static Type[] GetArgTypes(object[] args)
{
if (args == null || args.Length == 0)
return Empty.Array<Type>();
var result = new Type[args.Length];
for (int i = 0; i < args.Length; i++)
{
var o = args[i];
result[i] = o == null ? typeof(object) : o.GetType();
}
return result;
}
#endregion
}
private sealed class CacheKeyComparer : IEqualityComparer<CacheKey>
{
#region Fields
public static readonly CacheKeyComparer Instance;
#endregion
#region Constructors
static CacheKeyComparer()
{
Instance = new CacheKeyComparer();
}
private CacheKeyComparer()
{
}
#endregion
#region Implementation of IEqualityComparer<in CacheKey>
bool IEqualityComparer<CacheKey>.Equals(CacheKey x, CacheKey y)
{
var xTypes = x.Types;
var yTypes = y.Types;
if (xTypes.Length != yTypes.Length)
return false;
for (int i = 0; i < xTypes.Length; i++)
{
if (xTypes[i] != yTypes[i])
return false;
}
return true;
}
int IEqualityComparer<CacheKey>.GetHashCode(CacheKey obj)
{
return obj.Hash;
}
#endregion
}
#endregion
#region Fields
private const float NotExactlyEqualWeight = 1f;
private const float NotExactlyEqualBoxWeight = 1.1f;
private const float NotExactlyEqualUnsafeCastWeight = 1000f;
private static readonly MethodInfo ProxyMethod;
private static readonly MethodInfo BindingMemberGetValueMethod;
private static readonly MethodInfo GetMemberValueDynamicMethod;
private static readonly MethodInfo GetIndexValueDynamicMethod;
private static readonly MethodInfo InvokeMemberDynamicMethod;
private static readonly MethodInfo EqualsMethod;
private static readonly Expression EmptyObjectArrayExpression;
private static readonly MethodInfo StringConcatMethod;
protected static readonly ParameterExpression DataContextParameter;
private readonly Dictionary<ExpressionNodeType, Func<IExpressionNode, Expression>> _nodeToExpressionMapping;
private readonly Dictionary<TokenType, Func<Expression, Expression>> _unaryToExpressionMapping;
private readonly Dictionary<TokenType, Func<Expression, Expression, Expression>> _binaryToExpressionMapping;
private readonly Dictionary<string, Expression> _lambdaParameters;
private readonly Dictionary<CacheKey, Func<object[], object>> _expressionCache;
private readonly ConstantExpression _thisExpression;
private readonly IExpressionNode _node;
private readonly bool _isEmpty;
private ParameterInfo _lambdaParameter;
private IDataContext _dataContext;
private IList<KeyValuePair<int, ParameterExpression>> _parameters;
private IList<object> _sourceValues;
#endregion
#region Constructors
static CompiledExpressionInvoker()
{
StringConcatMethod = typeof(string).GetMethodEx(nameof(string.Concat), new[] { typeof(object), typeof(object) }, MemberFlags.Public | MemberFlags.Static);
ProxyMethod = typeof(CompiledExpressionInvoker).GetMethodEx(nameof(InvokeDynamicMethod), MemberFlags.Instance | MemberFlags.Public);
DataContextParameter = Expression.Parameter(typeof(IDataContext), "dataContext");
BindingMemberGetValueMethod = typeof(IBindingMemberInfo).GetMethodEx(nameof(IBindingMemberInfo.GetValue), new[] { typeof(object), typeof(object[]) }, MemberFlags.Public | MemberFlags.Instance);
GetMemberValueDynamicMethod = typeof(CompiledExpressionInvoker).GetMethodEx(nameof(GetMemberValueDynamic), MemberFlags.Static | MemberFlags.Public);
GetIndexValueDynamicMethod = typeof(CompiledExpressionInvoker).GetMethodEx(nameof(GetIndexValueDynamic), MemberFlags.Static | MemberFlags.Public);
InvokeMemberDynamicMethod = typeof(CompiledExpressionInvoker).GetMethodEx(nameof(InvokeMemberDynamic), MemberFlags.Static | MemberFlags.Public);
EqualsMethod = typeof(object).GetMethodEx(nameof(Equals), MemberFlags.Public | MemberFlags.Static);
EmptyObjectArrayExpression = Expression.Constant(Empty.Array<object>(), typeof(object[]));
Should.BeSupported(BindingMemberGetValueMethod != null, nameof(BindingMemberGetValueMethod));
Should.BeSupported(GetMemberValueDynamicMethod != null, nameof(GetMemberValueDynamicMethod));
Should.BeSupported(GetIndexValueDynamicMethod != null, nameof(GetIndexValueDynamicMethod));
Should.BeSupported(InvokeMemberDynamicMethod != null, nameof(InvokeMemberDynamicMethod));
Should.BeSupported(EqualsMethod != null, nameof(EqualsMethod));
}
public CompiledExpressionInvoker([NotNull] IExpressionNode node, bool isEmpty)
{
Should.NotBeNull(node, nameof(node));
_node = node;
_isEmpty = isEmpty;
_expressionCache = new Dictionary<CacheKey, Func<object[], object>>(CacheKeyComparer.Instance);
_lambdaParameters = new Dictionary<string, Expression>();
_thisExpression = Expression.Constant(this);
_nodeToExpressionMapping = new Dictionary<ExpressionNodeType, Func<IExpressionNode, Expression>>
{
{ExpressionNodeType.Binary, expressionNode => BuildBinary((IBinaryExpressionNode) expressionNode)},
{ExpressionNodeType.Condition, expressionNode => BuildCondition((IConditionExpressionNode) expressionNode)},
{ExpressionNodeType.Constant, expressionNode => BuildConstant((IConstantExpressionNode) expressionNode)},
{ExpressionNodeType.Index, expressionNode => BuildIndex((IIndexExpressionNode) expressionNode)},
{ExpressionNodeType.Member, expressionNode => BuildMemberExpression((IMemberExpressionNode) expressionNode)},
{ExpressionNodeType.MethodCall, expressionNode => BuildMethodCall((IMethodCallExpressionNode) expressionNode)},
{ExpressionNodeType.Unary, expressionNode => BuildUnary((IUnaryExressionNode) expressionNode)},
{ExpressionNodeType.BindingMember, expressionNode => BuildBindingMember((BindingMemberExpressionNode) expressionNode)},
{ExpressionNodeType.Lambda, expressionNode => BuildLambdaExpression((ILambdaExpressionNode) expressionNode)}
};
_unaryToExpressionMapping = new Dictionary<TokenType, Func<Expression, Expression>>
{
{TokenType.Minus, Expression.Negate},
{TokenType.Exclamation, Expression.Not},
{TokenType.Tilde, Expression.Not}
};
_binaryToExpressionMapping = new Dictionary<TokenType, Func<Expression, Expression, Expression>>
{
{TokenType.Asterisk, (expression, expression1) => GenerateNumericalExpression(expression, expression1, Expression.Multiply)},
{TokenType.Slash, (expression, expression1) => GenerateNumericalExpression(expression, expression1, Expression.Divide)},
{TokenType.Minus, (expression, expression1) => GenerateNumericalExpression(expression, expression1, Expression.Subtract)},
{TokenType.Percent, (expression, expression1) => GenerateNumericalExpression(expression, expression1, Expression.Modulo)},
{TokenType.Plus, GeneratePlusExpression},
{TokenType.Amphersand, (expression, expression1) => GenerateBooleanExpression(expression, expression1, Expression.And)},
{TokenType.DoubleAmphersand, (expression, expression1) => GenerateBooleanExpression(expression, expression1, Expression.AndAlso)},
{TokenType.Bar, (expression, expression1) => GenerateBooleanExpression(expression, expression1, Expression.Or)},
{TokenType.DoubleBar, (expression, expression1) => GenerateBooleanExpression(expression, expression1, Expression.OrElse)},
{TokenType.DoubleEqual, GenerateEqual},
{TokenType.ExclamationEqual, (expression, expression1) => Expression.Not(GenerateEqual(expression, expression1))},
{TokenType.GreaterThan, (expression, expression1) => GenerateEqualityExpression(expression, expression1, Expression.GreaterThan)},
{TokenType.GreaterThanEqual, (expression, expression1) => GenerateEqualityExpression(expression, expression1, Expression.GreaterThanOrEqual)},
{TokenType.LessThan, (expression, expression1) => GenerateEqualityExpression(expression, expression1, Expression.LessThan)},
{TokenType.LessThanEqual, (expression, expression1) => GenerateEqualityExpression(expression, expression1, Expression.LessThanOrEqual)},
{TokenType.Equal, (expression, expression1) => Expression.Assign(expression, ExpressionReflectionManager.ConvertIfNeed(expression1, expression.Type, false))},
{TokenType.DoubleQuestion, (expression, expression1) =>
{
Convert(ref expression, ref expression1, true);
if (BindingServiceProvider.CompiledExpressionInvokerSupportCoalesceExpression)
return Expression.Coalesce(expression, expression1);
return Expression.Condition(Expression.Equal(expression, Expression.Constant(null, expression.Type)), expression1, expression);
}}
};
}
#endregion
#region Properties
protected Dictionary<ExpressionNodeType, Func<IExpressionNode, Expression>> NodeToExpressionMapping => _nodeToExpressionMapping;
protected Dictionary<TokenType, Func<Expression, Expression>> UnaryToExpressionMapping => _unaryToExpressionMapping;
protected Dictionary<TokenType, Func<Expression, Expression, Expression>> BinaryToExpressionMapping => _binaryToExpressionMapping;
protected ConstantExpression ThisExpression => _thisExpression;
protected IDataContext DataContext => _dataContext;
protected IList<KeyValuePair<int, ParameterExpression>> Parameters => _parameters;
protected IList<object> SourceValues => _sourceValues;
#endregion
#region Methods
public object Invoke(IDataContext context, IList<object> sourceValues)
{
var key = new CacheKey(sourceValues.ToArrayEx(o => o == null ? null : o.GetType()));
Func<object[], object> expression;
lock (_expressionCache)
{
if (!_expressionCache.TryGetValue(key, out expression))
{
try
{
_sourceValues = sourceValues;
_parameters = new List<KeyValuePair<int, ParameterExpression>>
{
new KeyValuePair<int, ParameterExpression>(-1, DataContextParameter)
};
_dataContext = context;
expression = CreateDelegate();
_expressionCache[key] = expression;
}
finally
{
_lambdaParameter = null;
_lambdaParameters.Clear();
_sourceValues = null;
_parameters = null;
_dataContext = null;
}
}
}
if (_isEmpty)
return expression.Invoke(new object[] { context });
return expression.Invoke(BindingReflectionExtensions.InsertFirstArg(sourceValues, context));
}
[Preserve(Conditional = true)]
public virtual object InvokeDynamicMethod(string methodName, IDataContext context, IList<Type> typeArgs, object[] items)
{
var resourceMethod = BindingServiceProvider.ResourceResolver.ResolveMethod(methodName, context, false);
if (resourceMethod != null)
return resourceMethod.Invoke(typeArgs, items, context);
var binding = context.GetData(BindingConstants.Binding);
Type targetType = binding == null
? typeof(object)
: binding.TargetAccessor.Source.GetPathMembers(false).LastMember.Type;
var converter = BindingServiceProvider.ResourceResolver.ResolveConverter(methodName, context, true);
return converter.Convert(items[0], targetType, items.Length > 1 ? items[1] : null,
items.Length > 2 ? (CultureInfo)items[2] : BindingServiceProvider.BindingCultureInfo(), context);
}
protected virtual Func<object[], object> CreateDelegate()
{
var expression = BuildExpression(_node);
var @delegate = Expression.Lambda(expression, Parameters.OrderBy(pair => pair.Key).Select(pair => pair.Value).ToArray()).Compile();
var methodInfo = @delegate.GetType().GetMethodEx(nameof(Action.Invoke), MemberFlags.Public | MemberFlags.Instance);
if (methodInfo == null)
return @delegate.DynamicInvoke;
var invokeMethod = ToolkitServiceProvider.ReflectionManager.GetMethodDelegate(methodInfo);
return objects => invokeMethod(@delegate, objects);
}
protected Expression BuildExpression(IExpressionNode node)
{
Func<IExpressionNode, Expression> func;
if (!_nodeToExpressionMapping.TryGetValue(node.NodeType, out func))
throw BindingExceptionManager.UnexpectedExpressionNode(node);
return func(node);
}
private Expression BuildBinary(IBinaryExpressionNode binary)
{
var left = BuildExpression(binary.Left);
var right = BuildExpression(binary.Right);
Func<Expression, Expression, Expression> func;
if (!_binaryToExpressionMapping.TryGetValue(binary.Token, out func))
throw BindingExceptionManager.UnexpectedExpressionNode(binary);
return func(left, right);
}
private Expression BuildCondition(IConditionExpressionNode condition)
{
var ifTrue = BuildExpression(condition.IfTrue);
var ifFalse = BuildExpression(condition.IfFalse);
Convert(ref ifTrue, ref ifFalse, true);
return Expression.Condition(ExpressionReflectionManager.ConvertIfNeed(BuildExpression(condition.Condition), typeof(bool), true), ifTrue,
ifFalse);
}
private static Expression BuildConstant(IConstantExpressionNode constant)
{
var expression = constant.Value as Expression;
if (expression != null)
return expression;
return Expression.Constant(constant.Value, constant.Type);
}
private Expression BuildUnary(IUnaryExressionNode unary)
{
var operand = BuildExpression(unary.Operand);
Func<Expression, Expression> func;
if (!_unaryToExpressionMapping.TryGetValue(unary.Token, out func))
throw BindingExceptionManager.UnexpectedExpressionNode(unary);
return func(operand);
}
private Expression BuildBindingMember(BindingMemberExpressionNode bindingMember)
{
var param = Parameters.FirstOrDefault(expression => expression.Value.Name == bindingMember.ParameterName);
if (param.Value != null)
return param.Value;
var index = bindingMember.Index;
if (index >= SourceValues.Count)
throw BindingExceptionManager.BindingSourceNotFound(bindingMember);
var parameter = SourceValues[index];
Type type = typeof(object);
if (parameter == null)
{
var binding = _dataContext.GetData(BindingConstants.Binding);
if (binding != null)
{
var last = binding.SourceAccessor.Sources[index].GetPathMembers(false).LastMember;
type = last.Type;
}
}
else
type = parameter.GetType();
var exParam = Expression.Parameter(type, bindingMember.ParameterName);
Parameters.Add(new KeyValuePair<int, ParameterExpression>(index, exParam));
return exParam;
}
private Expression BuildMemberExpression(IMemberExpressionNode expression)
{
if (expression.Member.Contains("("))
return BuildMethodCall(new MethodCallExpressionNode(expression.Target,
expression.Member.Replace("(", string.Empty).Replace(")", string.Empty), null, null));
if (expression.Target == null)
{
Expression value;
if (!_lambdaParameters.TryGetValue(expression.Member, out value))
throw BindingExceptionManager.UnexpectedExpressionNode(expression);
return value;
}
var target = BuildExpression(expression.Target);
var type = GetTargetType(ref target);
var @enum = BindingReflectionExtensions.TryParseEnum(expression.Member, type);
if (@enum != null)
return Expression.Constant(@enum);
if (type != null)
{
var bindingMember = BindingServiceProvider
.MemberProvider
.GetBindingMember(type, expression.Member, false, false);
if (bindingMember != null)
{
var methodCall = Expression.Call(Expression.Constant(bindingMember, typeof(IBindingMemberInfo)),
BindingMemberGetValueMethod,
ExpressionReflectionManager.ConvertIfNeed(target, typeof(object), false),
EmptyObjectArrayExpression);
return Expression.Convert(methodCall, bindingMember.Type);
}
}
var member = type.FindPropertyOrField(expression.Member, target == null);
//Trying to get dynamic value.
if (member == null)
return Expression.Call(null, GetMemberValueDynamicMethod,
ExpressionReflectionManager.ConvertIfNeed(target, typeof(object), false),
Expression.Constant(expression.Member, typeof(string)));
return member is PropertyInfo
? Expression.Property(target, (PropertyInfo)member)
: Expression.Field(target, (FieldInfo)member);
}
private Expression BuildLambdaExpression(ILambdaExpressionNode lambdaExpression)
{
if (_lambdaParameter == null)
throw BindingExceptionManager.UnexpectedExpressionNode(lambdaExpression);
var method = _lambdaParameter.ParameterType.GetMethodEx(nameof(Action.Invoke), MemberFlags.Instance | MemberFlags.Public);
if (method == null)
throw BindingExceptionManager.UnexpectedExpressionNode(lambdaExpression);
var parameters = method.GetParameters();
var lambdaParameters = new ParameterExpression[parameters.Length];
try
{
for (int i = 0; i < parameters.Length; i++)
{
var parameter = Expression.Parameter(parameters[i].ParameterType, lambdaExpression.Parameters[i]);
lambdaParameters[i] = parameter;
_lambdaParameters.Add(parameter.Name, parameter);
}
var expression = BuildExpression(lambdaExpression.Expression);
return Expression.Lambda(expression, lambdaParameters);
}
finally
{
for (int index = 0; index < lambdaParameters.Length; index++)
_lambdaParameters.Remove(lambdaParameters[index].Name);
}
}
private Expression BuildMethodCall(IMethodCallExpressionNode methodCall)
{
if (methodCall.Target == null)
throw BindingExceptionManager.UnexpectedExpressionNode(methodCall);
var typeArgs = GetTypes(methodCall.TypeArgs);
var hasLambda = methodCall.Arguments
.OfType<ILambdaExpressionNode>()
.Any();
if (methodCall.Target.NodeType == ExpressionNodeType.DynamicMember)
{
if (hasLambda)
throw BindingExceptionManager.UnexpectedExpressionNode(methodCall);
var parameters = methodCall.Arguments
.Select(node => ExpressionReflectionManager.ConvertIfNeed(BuildExpression(node), typeof(object), false));
var arrayArg = Expression.NewArrayInit(typeof(object), parameters);
Type returnType = typeof(object);
var dynamicMethod = BindingServiceProvider
.ResourceResolver
.ResolveMethod(methodCall.Method, _dataContext, false);
if (dynamicMethod != null)
returnType = dynamicMethod.GetReturnType(arrayArg.Expressions.ToArrayEx(expression => expression.Type), typeArgs, _dataContext);
return ExpressionReflectionManager.ConvertIfNeed(Expression.Call(_thisExpression, ProxyMethod, Expression.Constant(methodCall.Method),
DataContextParameter, Expression.Constant(typeArgs, typeof(IList<Type>)), arrayArg), returnType, false);
}
var target = BuildExpression(methodCall.Target);
var type = GetTargetType(ref target);
var targetData = new ArgumentData(methodCall.Target, target, type, target == null);
var args = methodCall
.Arguments
.ToArrayEx(node => new ArgumentData(node, node.NodeType == ExpressionNodeType.Lambda ? null : BuildExpression(node), null, false));
var types = new List<Type>(BindingServiceProvider.ResourceResolver.GetKnownTypes())
{
typeof (BindingReflectionExtensions)
};
var methods = targetData.FindMethod(methodCall.Method, typeArgs, args, types, target == null);
var exp = TryGenerateMethodCall(methods, targetData, args);
if (exp != null)
return exp;
var arrayArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++)
{
var data = args[i];
if (data.IsLambda || data.Expression == null)
throw BindingExceptionManager.InvalidBindingMember(type, methodCall.Method);
arrayArgs[i] = ExpressionReflectionManager.ConvertIfNeed(data.Expression, typeof(object), false);
}
if (target == null)
throw BindingExceptionManager.InvalidBindingMember(type, methodCall.Method);
return Expression.Call(InvokeMemberDynamicMethod,
ExpressionReflectionManager.ConvertIfNeed(target, typeof(object), false),
Expression.Constant(methodCall.Method),
Expression.NewArrayInit(typeof(object), arrayArgs), Expression.Constant(typeArgs),
Expression.Constant(new MethodInvoker()), DataContextParameter);
}
private Expression BuildIndex(IIndexExpressionNode indexer)
{
if (indexer.Object == null)
throw BindingExceptionManager.UnexpectedExpressionNode(indexer);
var target = BuildExpression(indexer.Object);
if (target.Type.IsArray)
return Expression.ArrayIndex(target, indexer.Arguments.Select(BuildExpression));
var type = GetTargetType(ref target);
var targetData = new ArgumentData(indexer.Object, target, type, target == null);
var args = indexer
.Arguments
.ToArrayEx(node => new ArgumentData(node, node.NodeType == ExpressionNodeType.Lambda ? null : BuildExpression(node), null, false));
var exp = TryGenerateMethodCall(targetData.FindIndexer(args, target == null), targetData, args);
if (exp != null)
return exp;
var arrayArgs = new Expression[args.Length];
for (int i = 0; i < args.Length; i++)
{
var data = args[i];
if (data.IsLambda || data.Expression == null)
throw BindingExceptionManager.InvalidBindingMember(type, ReflectionExtensions.IndexerName);
arrayArgs[i] = ExpressionReflectionManager.ConvertIfNeed(data.Expression, typeof(object), false);
}
return Expression.Call(GetIndexValueDynamicMethod,
ExpressionReflectionManager.ConvertIfNeed(target, typeof(object), false),
Expression.NewArrayInit(typeof(object), arrayArgs), Expression.Constant(new MethodInvoker()), DataContextParameter);
}
[CanBeNull]
private Expression TryGenerateMethodCall(IList<MethodData> methods, ArgumentData target, IList<ArgumentData> arguments)
{
if (methods == null || methods.Count == 0)
return null;
var methodInfos = new List<MethodInfo>(methods.Count);
var methodArgs = new List<Expression[]>(methods.Count);
for (int i = 0; i < methods.Count; i++)
{
try
{
var method = methods[i];
var args = BindingReflectionExtensions.GetMethodArgs(method.IsExtensionMethod, target, arguments);
var expressions = new Expression[args.Count];
for (int index = 0; index < args.Count; index++)
{
var data = args[index];
if (data.IsLambda)
{
_lambdaParameter = method.Parameters[index];
data.UpdateExpression(BuildExpression(data.Node));
_lambdaParameter = null;
}
expressions[index] = data.Expression;
}
var methodInfo = method.Build(args);
if (methodInfo != null)
{
methodInfos.Add(methodInfo);
methodArgs.Add(expressions);
}
}
catch
{
;
}
}
bool resultHasParams;
var resultIndex = TrySelectMethod(methodInfos, methodArgs, (i, args) => args[i].ToArrayEx(e => e.Type), out resultHasParams);
if (resultIndex < 0)
return null;
var result = methodInfos[resultIndex];
var resultArgs = methodArgs[resultIndex];
var resultParameters = result.GetParameters();
resultArgs = ConvertParameters(resultParameters, resultArgs, resultHasParams);
return Expression.Call(result.IsExtensionMethod() ? null : target.Expression, result, resultArgs);
}
private static int TrySelectMethod<TArgs>(IList<MethodInfo> methods, TArgs args, Func<int, TArgs, Type[]> getArgTypes, out bool resultHasParams)
{
int result = -1;
resultHasParams = true;
bool resultUseParams = true;
float resultNotExactlyEqual = float.MaxValue;
int resultUsageCount = int.MinValue;
for (int i = 0; i < methods.Count; i++)
{
try
{
var methodInfo = methods[i];
var parameters = methodInfo.GetParameters();
bool useParams = false;
bool hasParams = false;
int lastIndex = 0;
int usageCount = 0;
if (parameters.Length != 0)
{
lastIndex = parameters.Length - 1;
hasParams = parameters[lastIndex].IsDefined(typeof(ParamArrayAttribute), true);
}
float notExactlyEqual = 0;
bool valid = true;
var argTypes = getArgTypes(i, args);
for (int j = 0; j < argTypes.Length; j++)
{
//params
if (j > lastIndex)
{
valid = hasParams && CheckParamsCompatible(j - 1, lastIndex, parameters, argTypes, ref notExactlyEqual);
useParams = true;
break;
}
var argType = argTypes[j];
var parameterType = parameters[j].ParameterType;
if (parameterType.IsByRef)
parameterType = parameterType.GetElementType();
if (parameterType.Equals(argType))
{
++usageCount;
continue;
}
bool boxRequired;
if (argType.IsCompatibleWith(parameterType, out boxRequired))
{
notExactlyEqual += boxRequired ? NotExactlyEqualBoxWeight : NotExactlyEqualWeight;
++usageCount;
}
else
{
if (lastIndex == j && hasParams)
{
valid = CheckParamsCompatible(j, lastIndex, parameters, argTypes, ref notExactlyEqual);
useParams = true;
break;
}
if (argType.IsValueType())
{
valid = false;
break;
}
++usageCount;
notExactlyEqual += NotExactlyEqualUnsafeCastWeight;
}
}
if (!valid)
continue;
if (notExactlyEqual > resultNotExactlyEqual)
continue;
if (notExactlyEqual == resultNotExactlyEqual)
{
if (usageCount < resultUsageCount)
continue;
if (usageCount == resultUsageCount)
{
if (useParams && !resultUseParams)
continue;
if (!useParams && !resultUseParams)
{
if (hasParams && !resultHasParams)
continue;
}
}
}
result = i;
resultNotExactlyEqual = notExactlyEqual;
resultUsageCount = usageCount;
resultUseParams = useParams;
resultHasParams = hasParams;
}
catch
{
;
}
}
return result;
}
private static bool CheckParamsCompatible(int startIndex, int lastIndex, ParameterInfo[] parameters, Type[] types, ref float notExactlyEqual)
{
float weight = 0;
var elementType = parameters[lastIndex].ParameterType.GetElementType();
for (int k = startIndex; k < types.Length; k++)
{
var argType = types[k];
if (elementType.Equals(argType))
continue;
bool boxRequired;
if (argType.IsCompatibleWith(elementType, out boxRequired))
{
var w = boxRequired ? NotExactlyEqualBoxWeight : NotExactlyEqualWeight;
if (w > weight)
weight = w;
}
else
{
if (argType.IsValueType())
return false;
if (NotExactlyEqualUnsafeCastWeight > weight)
weight = NotExactlyEqualUnsafeCastWeight;
}
}
notExactlyEqual += weight;
return true;
}
private static Expression GeneratePlusExpression(Expression left, Expression right)
{
if (left.Type.Equals(typeof(string)) || right.Type.Equals(typeof(string)))
return GenerateStringConcat(left, right);
Convert(ref left, ref right, true);
return Expression.Add(left, right);
}
private static Expression GenerateStringConcat(Expression left, Expression right)
{
return Expression.Call(null, StringConcatMethod, ExpressionReflectionManager.ConvertIfNeed(left, typeof(object), false),
ExpressionReflectionManager.ConvertIfNeed(right, typeof(object), false));
}
private static Expression GenerateEqualityExpression(Expression left, Expression right,
Func<Expression, Expression, Expression> getExpr)
{
Convert(ref left, ref right, true);
return getExpr(left, right);
}
private static Expression GenerateBooleanExpression(Expression left, Expression right,
Func<Expression, Expression, Expression> getExpr)
{
Convert(ref left, ref right, true);
return getExpr(left, right);
}
private static Expression GenerateNumericalExpression(Expression left, Expression right, Func<Expression, Expression, Expression> getExpr)
{
Convert(ref left, ref right, true);
return getExpr(left, right);
}
private static Type GetTargetType(ref Expression target)
{
var constant = target as ConstantExpression;
Type type = target.Type;
if (constant != null && constant.Value is Type)
{
type = (Type)constant.Value;
target = null;
}
return type;
}
private static Expression[] ConvertParameters(ParameterInfo[] parameters, IList<Expression> args, bool hasParams)
{
var result = new Expression[parameters.Length];
for (int i = 0; i < parameters.Length; i++)
{
//optional or params
if (i > args.Count - 1)
{
for (int j = i; j < parameters.Length; j++)
{
if (j == parameters.Length - 1 && hasParams)
{
var type = parameters[j].ParameterType.GetElementType();
result[j] = Expression.NewArrayInit(type);
}
else
{
result[j] = ExpressionReflectionManager.ConvertIfNeed(Expression.Constant(parameters[j].DefaultValue), parameters[j].ParameterType, false);
}
}
break;
}
if (i == parameters.Length - 1 && hasParams && !args[i].Type.IsCompatibleWith(parameters[i].ParameterType))
{
var arrayType = parameters[i].ParameterType.GetElementType();
var arrayArgs = new Expression[args.Count - i];
for (int j = i; j < args.Count; j++)
arrayArgs[j - i] = ExpressionReflectionManager.ConvertIfNeed(args[j], arrayType, false);
result[i] = Expression.NewArrayInit(arrayType, arrayArgs);
}
else
{
result[i] = ExpressionReflectionManager.ConvertIfNeed(args[i], parameters[i].ParameterType, false);
}
}
return result;
}
private static void Convert(ref Expression left, ref Expression right, bool exactly)
{
if (left.Type.Equals(right.Type))
return;
if (left.Type.IsCompatibleWith(right.Type))
left = ExpressionReflectionManager.ConvertIfNeed(left, right.Type, exactly);
else if (right.Type.IsCompatibleWith(left.Type))
right = ExpressionReflectionManager.ConvertIfNeed(right, left.Type, exactly);
}
private static Expression GenerateEqual(Expression left, Expression right)
{
Convert(ref left, ref right, true);
try
{
return Expression.Equal(left, right);
}
catch
{
return Expression.Call(null, EqualsMethod, ExpressionReflectionManager.ConvertIfNeed(left, typeof(object), false),
ExpressionReflectionManager.ConvertIfNeed(right, typeof(object), false));
}
}
private Type[] GetTypes(IList<string> types)
{
if (types.IsNullOrEmpty())
return Empty.Array<Type>();
var resolver = BindingServiceProvider.ResourceResolver;
var typeArgs = new Type[types.Count];
for (int i = 0; i < types.Count; i++)
typeArgs[i] = resolver.ResolveType(types[i], _dataContext, true);
return typeArgs;
}
[Preserve(Conditional = true)]
public static object GetMemberValueDynamic(object target, string member)
{
if (target == null)
return null;
return BindingServiceProvider.MemberProvider.GetBindingMember(target.GetType(), member, false, true).GetValue(target, Empty.Array<object>());
}
[Preserve(Conditional = true)]
public static object GetIndexValueDynamic(object target, object[] args, MethodInvoker methodInvoker, IDataContext context)
{
if (target == null)
return null;
var dynamicObject = target as IDynamicObject;
if (dynamicObject != null)
return dynamicObject.GetIndex(args, context);
var bindingMember = BindingServiceProvider
.MemberProvider
.GetBindingMember(target.GetType(), ReflectionExtensions.IndexerName, false, false);
if (bindingMember != null)
return bindingMember.GetValue(target, args);
return methodInvoker.InvokeIndex(target, args);
}
[Preserve(Conditional = true)]
public static object InvokeMemberDynamic(object target, string member, object[] args, Type[] typeArgs, MethodInvoker methodInvoker, IDataContext context)
{
if (target == null)
return null;
var dynamicObject = target as IDynamicObject;
if (dynamicObject != null)
return dynamicObject.InvokeMember(member, args, typeArgs, context);
var bindingMember = BindingServiceProvider
.MemberProvider
.GetBindingMember(target.GetType(), member, false, false);
if (bindingMember != null)
return bindingMember.GetValue(target, args);
return methodInvoker.Invoke(target, member, args, typeArgs);
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Data;
using System.IO;
using dolphindb;
using dolphindb.data;
namespace DolphinDBForExcel
{
public class DbObjectInfo
{
public string name;
public string type;
public string forms;
public int rows;
public int columns;
public long bytes;
public bool shared;
}
class TableResult
{
public DataTable table;
public IList<DATA_TYPE> columnSrcType;
public DATA_FORM srcForm;
public IList<string> matrix_ColumnLabels;
public IList<string> matrix_RowLabels;
}
class AddinBackend
{
public static void ResetConnection(DBConnection conn, string ip,int port)
{
conn.close();
if (!conn.connect(ip, port))
throw new WebException("connect failed");
}
public static IEntity RunScript(DBConnection conn,string script)
{
IEntity entity = conn.run(script);
return entity;
}
public static bool IsConnected(DBConnection conn)
{
return conn.isConnected;
}
public static bool IsBusy(DBConnection conn)
{
return conn.isConnected ? conn.isBusy() : false;
}
public static DataTable RunScriptAndFetchResultAsTable(DBConnection conn,string script)
{
BasicTable tb = RunScriptAndFetchResultAsBasicTable(conn,script);
return tb.toDataTable();
}
private static IList<DbObjectInfo> UpdateSessionObjs(DBConnection conn)
{
BasicTable objs = (BasicTable)conn.tryRun("objs(true)");
if (objs == null)
return null;
var listObjs = new List<DbObjectInfo>(objs.rows());
for (int i = 0; i != objs.rows(); i++)
{
DbObjectInfo obj = new DbObjectInfo
{
name = objs.getColumn("name").get(i).getString(),
type = objs.getColumn("type").get(i).getString(),
forms = objs.getColumn("form").get(i).getString(),
rows = (objs.getColumn("rows").get(i) as BasicInt).getValue(),
columns = (objs.getColumn("columns").get(i) as BasicInt).getValue(),
shared = (objs.getColumn("shared").get(i) as BasicBoolean).getValue(),
bytes = (objs.getColumn("bytes").get(i) as BasicLong).getValue()
};
listObjs.Add(obj);
}
return listObjs;
}
public static IList<DbObjectInfo> TryToGetObjsInfo(DBConnection conn)
{
if (!conn.isConnected)
return null;
return UpdateSessionObjs(conn);
}
/*
* return null if get DT_VOID
* return table or throw exception if not DT_VOID
*/
public static TableResult RunScriptAndFetchResultAsDataTable(DBConnection conn,string script)
{
IEntity entity = RunScript(conn,script);
if (entity.getDataType() == DATA_TYPE.DT_VOID)
return null;
TableResult result = new TableResult
{
srcForm = entity.getDataForm(),
columnSrcType = new List<DATA_TYPE>()
};
if (entity.isTable())
{
BasicTable basicTable = entity as BasicTable;
for (int i = 0; i != basicTable.columns(); i++)
result.columnSrcType.Add(basicTable.getColumn(i).getDataType());
result.table = basicTable.toDataTable();
return result;
}
result.table = entity.toDataTable();
if (entity.isDictionary())
{
BasicDictionary basicDictionary = entity as BasicDictionary;
result.columnSrcType.Add(basicDictionary.KeyDataType);
result.columnSrcType.Add(basicDictionary.getDataType());
return result;
}
if(entity.isMatrix())
{
IMatrix m = entity as IMatrix;
IVector colLabels = m.getColumnLabels();
if(!(colLabels == null || colLabels.columns() == 0))
{
result.matrix_ColumnLabels = new List<string>();
for (int i = 0; i != colLabels.rows(); i++)
result.matrix_ColumnLabels.Add(colLabels.get(i).getString());
}
IVector rowLabels = m.getRowLabels();
if (!(rowLabels == null || rowLabels.columns() == 0))
{
result.matrix_RowLabels = new List<string>();
for (int i = 0; i != rowLabels.rows(); i++)
result.matrix_RowLabels.Add(rowLabels.get(i).getString());
}
}
for (int i = 0; i != result.table.Columns.Count; i++)
result.columnSrcType.Add(entity.getDataType());
return result;
}
public static BasicTable RunScriptAndFetchResultAsBasicTable(DBConnection conn, string script)
{
IEntity tb = RunScript(conn,script);
if (!tb.isTable())
throw new ArgumentException("Can't get table from script");
return (BasicTable)tb;
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace tezcat.Framework.Definition
{
public abstract class TezDefinitionSystemContainer
{
public abstract void addPrimaryNode(int id, TezDefinitionNode node);
public abstract void addSecondaryNode(int id, TezDefinitionLeaf node);
public abstract bool tryGetPrimaryNode(int id, out TezDefinitionNode node);
public abstract bool tryGetSecondaryNode(int id, out TezDefinitionLeaf node);
public abstract void close();
}
public class TezDefinitionSystemListContainer : TezDefinitionSystemContainer
{
List<TezDefinitionNode> m_PrimaryNodes = new List<TezDefinitionNode>();
List<TezDefinitionLeaf> m_SecondaryNodes = new List<TezDefinitionLeaf>();
public override void addPrimaryNode(int id, TezDefinitionNode node)
{
///id = 7 实际为第8个
///Count = 5
///rc = 2
///
var remain_count = m_PrimaryNodes.Count - id;
if (remain_count > 0)
{
m_PrimaryNodes[id] = node;
}
else if (remain_count == 0)
{
m_PrimaryNodes.Add(node);
}
else
{
remain_count = -remain_count + 1;
m_PrimaryNodes.AddRange(new TezDefinitionNode[remain_count]);
m_PrimaryNodes[id] = node;
}
}
public override void addSecondaryNode(int id, TezDefinitionLeaf node)
{
var remain_count = m_SecondaryNodes.Count - id;
if (remain_count > 0)
{
m_SecondaryNodes[id] = node;
}
else if (remain_count == 0)
{
m_SecondaryNodes.Add(node);
}
else
{
remain_count = -remain_count + 1;
m_SecondaryNodes.AddRange(new TezDefinitionLeaf[remain_count]);
m_SecondaryNodes[id] = node;
}
}
public override void close()
{
foreach (var item in m_PrimaryNodes)
{
item.close();
}
foreach (var item in m_SecondaryNodes)
{
item.close();
}
m_PrimaryNodes.Clear();
m_SecondaryNodes.Clear();
m_PrimaryNodes = null;
m_SecondaryNodes = null;
}
public override bool tryGetPrimaryNode(int id, out TezDefinitionNode node)
{
if (id < m_PrimaryNodes.Count)
{
node = m_PrimaryNodes[id];
return true;
}
node = null;
return false;
}
public override bool tryGetSecondaryNode(int id, out TezDefinitionLeaf node)
{
if (id < m_SecondaryNodes.Count)
{
node = m_SecondaryNodes[id];
return true;
}
node = null;
return false;
}
}
public class TezDefinitionSystemHashContainer : TezDefinitionSystemContainer
{
Dictionary<int, TezDefinitionNode> m_PrimaryNodes = new Dictionary<int, TezDefinitionNode>();
Dictionary<int, TezDefinitionLeaf> m_SecondaryNodes = new Dictionary<int, TezDefinitionLeaf>();
public override void addPrimaryNode(int id, TezDefinitionNode node)
{
m_PrimaryNodes.Add(id, node);
}
public override void addSecondaryNode(int id, TezDefinitionLeaf node)
{
m_SecondaryNodes.Add(id, node);
}
public override void close()
{
foreach (var pair in m_PrimaryNodes)
{
pair.Value.close();
}
foreach (var pair in m_SecondaryNodes)
{
pair.Value.close();
}
m_PrimaryNodes.Clear();
m_SecondaryNodes.Clear();
m_PrimaryNodes = null;
m_SecondaryNodes = null;
}
public override bool tryGetPrimaryNode(int id, out TezDefinitionNode node)
{
return m_PrimaryNodes.TryGetValue(id, out node);
}
public override bool tryGetSecondaryNode(int id, out TezDefinitionLeaf node)
{
return m_SecondaryNodes.TryGetValue(id, out node);
}
}
} |
using Quasardb.Exceptions;
using Quasardb.Native;
using Quasardb.TimeSeries;
namespace Quasardb
{
class QdbEntryFactory
{
readonly qdb_handle _handle;
public QdbEntryFactory(qdb_handle handle)
{
_handle = handle;
}
public QdbEntry Create(string alias)
{
qdb_entry_type type;
var error = qdb_api.qdb_get_type(_handle, alias, out type);
QdbExceptionThrower.ThrowIfNeeded(error, alias: alias);
return Create(type, alias);
}
QdbEntry Create(qdb_entry_type type, string alias)
{
switch (type)
{
case qdb_entry_type.qdb_entry_blob:
return new QdbBlob(_handle, alias);
case qdb_entry_type.qdb_entry_integer:
return new QdbInteger(_handle, alias);
case qdb_entry_type.qdb_entry_tag:
return new QdbTag(_handle, alias);
case qdb_entry_type.qdb_entry_ts:
return new QdbTable(_handle, alias);
default:
return new QdbUnknownEntry(_handle, alias, type);
}
}
}
}
|
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Variables/Float List Variable")]
public class GlobalFloatListVariable : GlobalVariable<List<float>> { }
|
//Problem 1. Sum of 3 Numbers
//Write a program that reads 3 real numbers from the console and prints their sum.
//Examples:
//a b c sum
//3 4 11 18
//-2 0 3 1
//5.5 4.5 20.1 30.1
using System;
class SumOf3Numbers
{
static void Main()
{
Console.WriteLine("Enter a");
double a = double.Parse(Console.ReadLine());
Console.WriteLine("Enter b");
double b = double.Parse(Console.ReadLine());
Console.WriteLine("Enter c");
double c = double.Parse(Console.ReadLine());
Console.WriteLine("And now i will sum them :)");
Console.WriteLine("The sum of the entered numbers is: {0}",
a + b + c);
}
}
|
using CompoundInterestBackend.Common.Contracts;
using CompoundInterestBackend.Common.Shared;
namespace CompoundInterestBackend.Utilities
{
public class UtilityFactory : FactoryBase
{
public UtilityFactory(AmbientContext context) : base(context)
{
}
public T CreateUtility<T>() where T : class
{
T result = base.GetInstanceForType<T>();
// Configure the context if the result is not a mock
if (result is UtilityBase)
{
(result as UtilityBase).Context = Context;
}
return result;
}
}
}
|
using System;
using HyperFastCgi.Interfaces;
using System.Threading;
using System.Collections.Generic;
namespace HyperFastCgi.Transports
{
public class TransportRequest
{
private static int nreq;
public ulong Hash;
public uint fd;
public ushort RequestId;
public int RequestNumber;
public bool StdOutSent;
public bool KeepAlive;
public List<KeyValuePair> tempKeys = new List<KeyValuePair> (128);
public string VHost;
public int VPort = -1;
public string VPath;
//use 'Host' for unmanaged transport
public IntPtr Host;
//use 'Transport' for managed transport
public IApplicationHostTransport Transport;
public TransportRequest(ushort requestId)
{
this.RequestId = requestId;
this.RequestNumber = Interlocked.Increment (ref nreq);
}
}
}
|
using UnityEngine;
public class ExitDetector : MonoBehaviour
{
public GameDirector director;
private void OnTriggerEnter(Collider col)
{
if (col.gameObject.TryGetComponent<PlayerController>(out _))
{
director.EnterNextRoom();
Destroy(this.gameObject);
}
}
}
|
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using MessageBoard;
namespace MessageBoard.Migrations
{
[DbContext(typeof(DataContext))]
partial class DataContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
modelBuilder
.HasAnnotation("ProductVersion", "1.1.2");
modelBuilder.Entity("MessageBoard.ChatInfo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Content")
.IsRequired()
.HasMaxLength(80);
b.Property<DateTime>("CreateTime");
b.Property<string>("IP")
.HasMaxLength(20);
b.Property<bool>("Sex");
b.Property<string>("UserName")
.HasMaxLength(20);
b.HasKey("Id");
b.ToTable("ChatInfo");
});
modelBuilder.Entity("MessageBoard.LogInfo", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Content");
b.Property<string>("IP")
.HasMaxLength(20);
b.HasKey("Id");
b.ToTable("LogInfos");
});
modelBuilder.Entity("MessageBoard.Message", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<string>("Content")
.IsRequired()
.HasMaxLength(80);
b.Property<DateTime>("CreateTime");
b.Property<string>("IP")
.HasMaxLength(20);
b.Property<string>("UserName")
.HasMaxLength(20);
b.HasKey("Id");
b.ToTable("Messages");
});
}
}
}
|
using OfficeAppointmentSoftware.Entities.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OfficeAppointmentSoftware.BLL.Abstracts.AdminServices
{
public interface IBannerService
{
void BannerAdd(Banner banner) ;
void BannerUpdate(Banner banner);
Banner BannerGet(short id);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BombInBoxApp
{
public partial class PictureBoxWithTimer : System.Windows.Forms.PictureBox
{
public delegate void ptrMethod(bool flag = true);
public ptrMethod CallBack = null;
private int count ;
private static int initial_picBox_X = 80;
private static int initial_picBox_Y = 380;
private System.ComponentModel.Container components;
private System.Windows.Forms.Timer timer;
public PictureBoxWithTimer():base()
{
this.Image = global::BombInBoxApp.Properties.Resources.box;
this.Location = new System.Drawing.Point(initial_picBox_X, initial_picBox_Y);
this.Name = "PictureBoxWithTimer";
this.Size = new System.Drawing.Size(150, 150);
this.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
//this.TabIndex = 1;
this.TabStop = false;
this.components = new System.ComponentModel.Container();
timer = new System.Windows.Forms.Timer(this.components);
initializeTimerMoveBox();
}
public void TimerStart() {
this.Visible = true;
timer.Start();
}
public void TimerStop() { timer.Stop(); }
public void Reset()
{
this.Image = global::BombInBoxApp.Properties.Resources.box;
this.Location = new System.Drawing.Point(initial_picBox_X, initial_picBox_Y);
count = 0;
}
private void initializeTimerMoveBox()
{
count = 0;
// set timer interval to 0.085 second
timer.Interval = 25;
// add a event hander for timer class
timer.Tick += new System.EventHandler(Tick);
}
private void Tick(object sender, EventArgs e)
{
if (++count % 200 == 0) // when counter reach 200, do something
{
TimerStop();
this.CallBack.Invoke();
count = 0;
}
System.Drawing.Point newPoint = this.Location;
this.Location = new System.Drawing.Point(newPoint.X + 1, newPoint.Y);
this.Refresh();
}
}
}
|
using UnityEngine;
namespace UniSkin
{
internal static class Texture2DExtensions
{
public static Texture2D ToDecompressedTexture(this Texture2D source)
{
var renderTexture = RenderTexture.GetTemporary(source.width, source.height);
Graphics.Blit(source, renderTexture);
var readableTexture = new Texture2D(source.width, source.height);
readableTexture.ReadPixels(new Rect(0, 0, renderTexture.width, renderTexture.height), 0, 0);
readableTexture.Apply();
RenderTexture.ReleaseTemporary(renderTexture);
return readableTexture;
}
public static string ToTextureId(this Texture2D source)
{
if (source == null) return null;
else return $"{source.name}{source.width}{source.height}";
}
public static SerializableTexture2D ToSerializableTexture2D(this Texture2D source)
{
return new SerializableTexture2D(source.ToTextureId(), source);
}
}
}
|
using System.Threading.Tasks;
using Todo.Core.Queries;
using Xunit;
namespace ToDo.Tests.Integration.Data.Queries
{
public class ToDoItemsByOwnerQueryShould
{
[Fact]
public async Task xxx()
{
ToDoItemsByOwnerQuery query = new ToDoItemsByOwnerQuery("wouterdekort");
var repository = RepositoryHelper.GetRepository();
await repository.AddAsync(new ToDoItemBuilder().WithOwnerId("wouterdekort").Build());
await repository.AddAsync(new ToDoItemBuilder().WithOwnerId("wouterdekort").Build());
await repository.AddAsync(new ToDoItemBuilder().WithOwnerId("wouterdekort").Build());
await repository.AddAsync(new ToDoItemBuilder().WithOwnerId("someoneelse").Build());
await repository.AddAsync(new ToDoItemBuilder().WithOwnerId("someoneelse").Build());
var itemsOwnedByWouter = await repository.ListAsync(query);
Assert.Equal(3, itemsOwnedByWouter.Count);
Assert.All(itemsOwnedByWouter, i => Assert.Equal("wouterdekort", i.OwnerId));
}
}
}
|
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp)
// Distributed under the MIT license. See the LICENSE.md file in the project root for more information.
using Xenko.Core.Assets;
namespace Xenko.Assets.Sprite
{
public class SpriteSheetSprite2DFactory : AssetFactory<SpriteSheetAsset>
{
public static SpriteSheetAsset Create()
{
return new SpriteSheetAsset
{
Type = SpriteSheetType.Sprite2D,
};
}
public override SpriteSheetAsset New()
{
return Create();
}
}
public class SpriteSheetUIFactory : AssetFactory<SpriteSheetAsset>
{
public static SpriteSheetAsset Create()
{
return new SpriteSheetAsset
{
Type = SpriteSheetType.UI,
};
}
public override SpriteSheetAsset New()
{
return Create();
}
}
}
|
namespace MiCake.Serilog.ExceptionHanding
{
/// <summary>
/// log error info with serilog
/// </summary>
//public class SerilogErrorHandlerProvider : ILogErrorHandlerProvider
//{
// private SerilogConfigureOption _serilogConfigure;
// public SerilogErrorHandlerProvider(SerilogConfigureOption serilogConfigure)
// {
// _serilogConfigure = serilogConfigure;
// }
// public Action<MiCakeErrorInfo> GetErrorHandler()
// {
// return serilogErrorHandler;
// void serilogErrorHandler(MiCakeErrorInfo miCakeError)
// {
// }
// }
//}
}
|
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace Xms.Web.Framework
{
/// <summary>
/// 图片结果视图
/// </summary>
public class ImageResult : ActionResult
{
public byte[] Image { get; set; }
public string ContentType { get; set; }
public ImageResult(byte[] image, string contenttype)
{
Image = image ?? throw new ArgumentNullException("image");
ContentType = contenttype;
}
public override Task ExecuteResultAsync(ActionContext context)
{
if (context == null) throw new ArgumentNullException("context");
var response = context.HttpContext.Response;
response.Clear();
if (!string.IsNullOrWhiteSpace(ContentType)) response.ContentType = ContentType;
return response.Body.WriteAsync(Image, 0, Image.Length);
}
}
} |
@model StepViewModel
<div class="content-container">
<div class="grid-row">
<div class="column-desktop-two-thirds" style="list-style: none;">
@Html.Raw(Model.Content)
</div>
</div>
</div>
|
//
// Automatically generated by JSComponentGenerator.
//
using UnityEngine;
public class JSComponent_TransChange_Visible : JSComponent
{
int idOnTransformChildrenChanged;
int idOnTransformParentChanged;
int idOnBecameInvisible;
int idOnBecameVisible;
protected override void initMemberFunction()
{
base.initMemberFunction();
idOnTransformChildrenChanged = JSApi.getObjFunction(jsObjID, "OnTransformChildrenChanged");
idOnTransformParentChanged = JSApi.getObjFunction(jsObjID, "OnTransformParentChanged");
idOnBecameInvisible = JSApi.getObjFunction(jsObjID, "OnBecameInvisible");
idOnBecameVisible = JSApi.getObjFunction(jsObjID, "OnBecameVisible");
}
void OnTransformChildrenChanged()
{
JSMgr.vCall.CallJSFunctionValue(jsObjID, idOnTransformChildrenChanged);
}
void OnTransformParentChanged()
{
JSMgr.vCall.CallJSFunctionValue(jsObjID, idOnTransformParentChanged);
}
void OnBecameInvisible()
{
JSMgr.vCall.CallJSFunctionValue(jsObjID, idOnBecameInvisible);
}
void OnBecameVisible()
{
JSMgr.vCall.CallJSFunctionValue(jsObjID, idOnBecameVisible);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SimpleWeather.TomorrowIO
{
public class AlertRootobject
{
public AlertData data { get; set; }
}
public class AlertData
{
public Event[] events { get; set; }
}
public class Event
{
public string insight { get; set; }
public DateTimeOffset startTime { get; set; }
public DateTimeOffset endTime { get; set; }
public DateTimeOffset updateTime { get; set; }
public string severity { get; set; }
public string certainty { get; set; }
public string urgency { get; set; }
public Eventvalues eventValues { get; set; }
}
public class Eventvalues
{
public string origin { get; set; }
public string title { get; set; }
public string headline { get; set; }
public string description { get; set; }
public Response[] response { get; set; }
//public string geocode { get; set; }
//public string geocodeType { get; set; }
//public string link { get; set; }
//public Location location { get; set; }
//public float distance { get; set; }
//public float direction { get; set; }
}
/*
public class Location
{
public string type { get; set; }
public float[][][][] coordinates { get; set; }
}
*/
public class Response
{
public string instruction { get; set; }
}
}
|
namespace FirebirdDbComparer.DatabaseObjects
{
public enum ContextTypeType
{
Table = 0,
View = 1,
Procedure = 2,
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace Looker.RTL
{
/// <summary>
/// Base type for all generated SDK models
/// </summary>
/// <remarks>
/// This is where general-purpose type functionality will appear
/// </remarks>
public class SdkModel
{
}
public class StringDictionary<T> : Dictionary<string, T>
{
};
public class DelimArray<T> : List<T>
{
public string Delimiter { get; set; } = ",";
public override string ToString()
{
var sb = new StringBuilder();
foreach(var item in this)
{
sb.Append(SdkUtils.EncodeParam(item));
sb.Append(Delimiter);
}
// remove last delimiter
if (Count > 1) sb.Remove(sb.Length - Delimiter.Length, Delimiter.Length);
return sb.ToString();
}
}
/// <summary>
/// Sweet extension methods for syntactic sugar
/// </summary>
public static class Extensions
{
/// <summary>
/// Assigned properties from <c>source</c> into <c>dest</c> where they're null in <c>dest</c>
/// </summary>
/// <remarks>
/// Sorta similar to ECMAScript spread operator.
/// </remarks>
/// <example>
/// settings = settings.Spread(AuthSession.Settings);
/// </example>
/// <param name="dest">Destination object</param>
/// <param name="source">Source object</param>
/// <typeparam name="T">Type of object (homogeneous)</typeparam>
/// <returns><c>dest</c> with merged values</returns>
public static T Spread<T>(this T dest, T source)
{
if (dest == null) return source;
var t = typeof(T);
var properties = t.GetProperties().Where(prop => prop.CanRead && prop.CanWrite);
foreach (var prop in properties)
{
// Skip any assigned properties
if (prop.GetValue(dest, null) != null) continue;
var value = prop.GetValue(source, null);
if (value != null)
prop.SetValue(dest, value, null);
}
return dest;
}
public static bool IsNullOrEmpty(this string value) => string.IsNullOrEmpty(value);
public static bool IsFull(this string value) => !string.IsNullOrEmpty(value);
}
public static class SdkUtils
{
/// <summary>
/// Encode parameter if not already encoded
/// </summary>
/// <param name="value">any value</param>
/// <returns>The Url encoded string of the parameter</returns>
public static string EncodeParam(object value)
{
string encoded;
switch (value)
{
case null:
return "";
case DateTime time:
{
var d = time;
encoded = d.ToString("O");
break;
}
case bool toggle:
{
encoded = Convert.ToString(toggle).ToLowerInvariant();
break;
}
default:
encoded = Convert.ToString(value);
break;
}
var decoded = WebUtility.UrlDecode(encoded);
if (encoded == decoded)
{
encoded = WebUtility.UrlEncode(encoded);
}
return encoded;
}
/// <summary>
/// Converts <c>values</c> to query string parameter format
/// </summary>
/// <param name="values">Name/value collection to encode</param>
/// <returns>Query string parameter formatted values. <c>null</c> values are omitted.</returns>
public static string EncodeParams(Values values = null)
{
if (values == null) return "";
var args = values
.Where(pair =>
pair.Value != null || (pair.Value is string && pair.Value.ToString().IsFull()))
.Select(x => $"{x.Key}=encodeParam(x.Value)");
return string.Join("&", args);
}
/// <summary>
/// constructs the path argument including any optional query parameters
/// </summary>
/// <param name="path">the current path of the request</param>
/// <param name="obj">optional collection of query parameters to encode and append to the path</param>
/// <returns>path + any query parameters as a URL string</returns>
public static string AddQueryParams(string path, Values obj = null)
{
if (obj == null)
{
return path;
}
var sb = new StringBuilder(path);
var qp = EncodeParams(obj);
if (qp.IsNullOrEmpty()) return sb.ToString();
sb.Append("?");
sb.Append(qp);
return sb.ToString();
}
/// <summary>
/// Awaits the SDK response task and returns either success or throws the error
/// </summary>
/// <param name="task">SDK response to await</param>
/// <typeparam name="TSuccess">Success type</typeparam>
/// <typeparam name="TError">Error type</typeparam>
/// <returns><c>TSuccess</c> or throws <c>TError</c></returns>
/// <exception cref="SdkError"></exception>
public static async Task<TSuccess> Ok<TSuccess, TError>(Task<SdkResponse<TSuccess, TError>> task)
where TSuccess : class where TError : Exception
{
var result = await task;
if (result.Ok)
{
return result.Value;
}
throw result.Error;
}
public static ResponseMode ResponseMode(string contentType)
{
if (contentType.IsNullOrEmpty()) return RTL.ResponseMode.Unknown;
if (Constants.ContentPatternString.IsMatch(contentType))
{
return RTL.ResponseMode.String;
}
if (Constants.ContentPatternBinary.IsMatch(contentType))
{
return RTL.ResponseMode.Binary;
}
return RTL.ResponseMode.Unknown;
}
/// <summary>
/// Read all input from a stream into a byte array
/// </summary>
/// <param name="inStream">input stream</param>
/// <returns>byte array of input stream content</returns>
public static byte[] ReadAllBytes(Stream inStream)
{
using var outStream = new MemoryStream();
inStream.CopyTo(outStream);
return outStream.ToArray();
}
/// <summary>
/// Convert a stream to a byte array
/// </summary>
/// <param name="stream">input stream</param>
/// <returns>byte array of input stream content</returns>
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream memoryStream)
{
return memoryStream.ToArray();
}
else
{
return ReadAllBytes(stream);
}
}
}
} |
using System;
using System.Text.Json;
using Shouldly;
using Xunit;
namespace DeltaSight.Statistics.Tests;
public class SimpleStatisticsTrackerTests
{
[Fact]
public void Remove_FromEmpty_ShouldThrow()
{
Assert.Throws<StatisticsTrackerException>(() =>
{
var tracker = new SimpleStatisticsTracker();
tracker.Remove(1d);
});
}
[Fact]
public void Remove_WithTooHighQuantity_ShouldThrow()
{
Assert.Throws<StatisticsTrackerException>(
() =>
{
var tracker = SimpleStatisticsTracker.From(10d);
tracker.Remove(10d, 2);
});
}
[Fact]
public void AddAndRemove_WithSameQuantity_ShouldBeEmpty()
{
var tracker = new SimpleStatisticsTracker();
tracker.Add(Math.PI, 10);
tracker.Remove(Math.PI, 10);
tracker.IsEmpty().ShouldBeTrue();
tracker
.TakeSnapshot()
.ShouldBeNull();
}
[Fact]
public void Empty_TakeSnapshot_ShouldBeNull()
{
new SimpleStatisticsTracker()
.TakeSnapshot()
.ShouldBeNull();
}
[Fact]
public void TakeSnapshot_FromSinglePositiveValue()
{
if (SimpleStatisticsTracker
.From(1d)
.TryTakeSnapshot(out var stats))
{
stats.PopulationVariance.ShouldBe(0d);
stats.PopulationStandardDeviation.ShouldBe(0d);
stats.Variance.ShouldBe(0d);
stats.StandardDeviation.ShouldBe(0d);
stats.CoefficientOfVariation.ShouldBe(0d);
stats.PopulationCoefficientOfVariation.ShouldBe(0d);
}
}
[Fact]
public void TakeSnapshot_FromSingleZero()
{
var stats = SimpleStatisticsTracker.From(0d).TakeSnapshot();
stats.ShouldNotBeNull();
stats.PopulationVariance.ShouldBe(0d);
stats.PopulationStandardDeviation.ShouldBe(0d);
stats.Variance.ShouldBe(0d);
stats.StandardDeviation.ShouldBe(0d);
stats.CoefficientOfVariation.ShouldBe(0d);
stats.PopulationCoefficientOfVariation.ShouldBe(0d);
}
[Fact]
public void Add_WithCountGreaterThanOne()
{
var tracker = SimpleStatisticsTracker.From(1d);
tracker.Add(2d, 5L);
tracker.IsEmpty().ShouldBeFalse();
var stats = tracker.TakeSnapshot();
stats.ShouldNotBeNull();
stats.Sum.ShouldBe(11d, 1e-2);
stats.Count.ShouldBe(6L);
stats.CountZero.ShouldBe(0L);
stats.Mean.ShouldBe(1.83, 1e-2);
stats.Variance.ShouldBe(0.17, 1e-2);
stats.PopulationVariance.ShouldBe(0.14, 1e-2);
tracker.Remove(2d);
tracker.IsEmpty().ShouldBeFalse();
var stats2 = tracker.TakeSnapshot();
stats2.ShouldNotBeNull();
stats2.Sum.ShouldBe(9d, 1e-2);
stats2.Count.ShouldBe(5L);
stats2.CountZero.ShouldBe(0L);
stats2.Mean.ShouldBe(1.8, 1e-2);
stats2.Variance.ShouldBe(0.2, 1e-2);
stats2.PopulationVariance.ShouldBe(0.16, 1e-2);
}
[Fact]
public void Combine()
{
var tracker1 = SimpleStatisticsTracker.From(1, 2, 3);
var tracker2 = SimpleStatisticsTracker.From(2, 4, 5, 6);
var tracker = tracker1.Combine(tracker2);
var stats = tracker.TakeSnapshot();
stats.ShouldNotBeNull();
stats.Sum.ShouldBe(23d, 1e-2);
stats.Count.ShouldBe(7L);
stats.Mean.ShouldBe(3.29, 1e-2);
stats.Variance.ShouldBe(3.24, 1e-2);
stats.PopulationVariance.ShouldBe(2.78, 1e-2);
}
[Fact]
public void Equality()
{
var values = new[] {1d, 2d, 3d, 4d, 10d};
var tracker1 = values.TrackSimpleStatistics();
var tracker2 = new SimpleStatisticsTracker(values);
tracker1.Equals(tracker2).ShouldBeTrue();
ReferenceEquals(tracker1, tracker2).ShouldBeFalse();
var snap1 = tracker1.TakeSnapshot();
var snap2 = tracker2.TakeSnapshot();
snap1.ShouldNotBeNull();
snap2.ShouldNotBeNull();
snap1.Equals(snap2).ShouldBeTrue();
ReferenceEquals(snap1, snap2).ShouldBeFalse();
}
[Fact]
public void AddAndRemove_ShouldHaveZeroVariance()
{
var tracker = SimpleStatisticsTracker.From(2d, 2d, 4d);
tracker.Remove(4);
tracker.IsEmpty().ShouldBeFalse();
var stats = tracker.TakeSnapshot();
stats.ShouldNotBeNull();
stats.Mean.ShouldBe(2);
stats.Variance.ShouldBe(0d, 1e-2);
stats.StandardDeviation.ShouldBe(0d, 1e-2);
}
[Fact]
public void AddAndRemove_ShouldNotHaveZeroVariance()
{
var tracker = SimpleStatisticsTracker.From(3, 3, 4, 1);
var stats = tracker.TakeSnapshot();
stats.ShouldNotBeNull();
stats.Variance.ShouldBe(1.58, 1e-2);
stats.StandardDeviation.ShouldBe(1.26, 1e-2);
tracker.Remove(1);
stats = tracker.TakeSnapshot();
stats.ShouldNotBeNull();
stats.Variance.ShouldBe(.33, 1e-2);
stats.StandardDeviation.ShouldBe(0.58, 1e-2);
}
[Fact]
public void Serialize()
{
JsonSerializer.Serialize(SimpleStatisticsTracker.From(0, 1, 2, 3))
.ShouldBe("{\"Sum\":6,\"SSE\":5,\"N\":4,\"N0\":1}");
}
[Fact]
public void Deserialize()
{
var tracker = JsonSerializer.Deserialize<SimpleStatisticsTracker>("{\"N0\":1,\"N\":3,\"Sum\":6,\"SSE\":2}");
tracker.ShouldNotBeNull();
if (tracker.TryTakeSnapshot(out var stats))
{
stats.Count.ShouldBe(3L);
stats.CountZero.ShouldBe(1L);
stats.Mean.ShouldBe(2d, 1e-2);
stats.Sum.ShouldBe(6d, 1e-2);
stats.SumSquaredError.ShouldBe(2d, 1e-2);
stats.StandardDeviation.ShouldBe(1d, 1e-2);
stats.PopulationStandardDeviation.ShouldBe(0.82, 1e-2);
stats.Variance.ShouldBe(1d, 1e-2);
stats.PopulationVariance.ShouldBe(.66, 1e-2);
}
}
[Fact]
public void Multiply()
{
var tracker = SimpleStatisticsTracker.From(2, 4, 6).Multiply(3);
tracker.IsEmpty().ShouldBeFalse();
var stats = tracker.TakeSnapshot();
stats.ShouldNotBeNull();
stats.Sum.ShouldBe(36d, 1e-2);
stats.Mean.ShouldBe(12d, 1e-2);
stats.Count.ShouldBe(3L);
stats.CountZero.ShouldBe(0L);
stats.Variance.ShouldBe(36d, 1e-2); // 4 * 3^2
stats.PopulationVariance.ShouldBe(24d, 1e-2);
stats.StandardDeviation.ShouldBe(6d, 1e-2);
stats.PopulationStandardDeviation.ShouldBe(4.90, 1e-2);
}
} |
using UnityEngine;
namespace CybSDK
{
/// <summary>
///
/// </summary>
public static class IVirtDeviceUnityExtensions
{
/// <summary>
/// Returns the movement direction as a speed scaled vector relative to the current player orientation.
/// </summary>
public static Vector3 GetMovementVector(this IVirtDevice device)
{
return device.GetMovementDirectionVector() * device.GetMovementSpeed();
}
/// <summary>
/// Returns the movement direction as vector relative to the current player orientation.
/// </summary>
/// <remarks>The origin is the GetPlayerOrientation method and increases clockwise.</remarks>
public static Vector3 GetMovementDirectionVector(this IVirtDevice device)
{
float movementDirection = device.GetMovementDirection() * Mathf.PI;
return new Vector3(
Mathf.Sin(movementDirection),
0.0f,
Mathf.Cos(movementDirection)).normalized;
}
/// <summary>
/// Returns the orientation of the player as vector.
/// </summary>
/// <remarks>The origin is set by the ResetPlayerOrientation method and increases clockwise.</remarks>
public static Vector3 GetPlayerOrientationVector(this IVirtDevice device)
{
float playerOrientation = device.GetPlayerOrientation() * 2.0f * Mathf.PI;
return new Vector3(
Mathf.Sin(playerOrientation),
0.0f,
Mathf.Cos(playerOrientation)).normalized;
}
/// <summary>
/// Returns the orientation of the player as quaternion.
/// </summary>
/// <remarks>The origin is set by the ResetPlayerOrientation method and increases clockwise.</remarks>
public static Quaternion GetPlayerOrientationQuaternion(this IVirtDevice device)
{
float playerOrientation = device.GetPlayerOrientation() * 360.0f;
return Quaternion.Euler(0.0f, playerOrientation, 0.0f);
}
}
}
|
// Requires Json.Net for Unity
/*
using UnityEngine;
using UnityEngine.Events;
namespace Playcraft.Saving
{
public class RespondToFlagValue : MonoBehaviour
{
[SerializeField] StringSO flag;
[SerializeField] UnityEvent True;
[SerializeField] UnityEvent False;
public void Trigger()
{
var response = flag.value.GetFlagValue() ? True : False;
response.Invoke();
}
}
}
*/ |
namespace Edgar.Unity.Editor
{
public interface IDoorModeInspector
{
void OnInspectorGUI();
void OnSceneGUI();
}
} |
using System.Collections.Generic;
namespace DataKit.Mapping
{
public interface IObjectMapper
{
/// <summary>
/// Map from <see cref="from"/> to a new instance of <see cref="TTo"/>.
/// </summary>
TTo Map<TFrom, TTo>(TFrom from)
where TFrom : class
where TTo : class;
/// <summary>
/// Map from enumerable <see cref="from"/> one at a time.
/// </summary>
/// <typeparam name="TTo"></typeparam>
/// <param name="from"></param>
/// <returns></returns>
IEnumerable<TTo> MapAll<TFrom, TTo>(IEnumerable<TFrom> from)
where TFrom : class
where TTo : class;
/// <summary>
/// Inject values from <see cref="from"/> into <see cref="to"/>.
/// </summary>
void Inject<TFrom, TTo>(TFrom from, TTo to)
where TFrom : class
where TTo : class;
/// <summary>
/// Inject values from all <see cref="from"/> into <see cref="to"/> one at a time.
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
void InjectAll<TFrom, TTo>(IEnumerable<TFrom> from, IEnumerable<TTo> to)
where TFrom : class
where TTo : class;
}
}
|
//-----------------------------------------------------------------------------
// EditCurveKeyCollection.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
namespace Xna.Tools
{
/// <summary>
/// This class provides same functionality of CurveEditCollection but
/// this contains EditCurveKey instead of CurveKey.
/// You have to use any curve key operations via this class because this class
/// also manipulates original curve keys.
/// </summary>
public class EditCurveKeyCollection : ICollection<EditCurveKey>
{
#region Constructors.
/// <summary>
/// Create new instance of EditCurveKeyCollection from Curve instance.
/// </summary>
/// <param name="curve"></param>
internal EditCurveKeyCollection(EditCurve owner)
{
// Generate EditCurveKey list from Curve class.
this.owner = owner;
foreach (CurveKey key in owner.OriginalCurve.Keys)
{
// Add EditCurveKey to keys.
int index = owner.OriginalCurve.Keys.IndexOf(key);
EditCurveKey newKey =
new EditCurveKey(EditCurveKey.GenerateUniqueId(), key);
keys.Insert(index, newKey);
idToKeyMap.Add(newKey.Id, newKey);
}
}
#endregion
#region IList<EditCurveKey> like Members
/// <summary>
/// Determines the index of a specfied CurveKey in the EditCurveKeyCollection.
/// </summary>
/// <param name="item">CurveKey to locate in the EditCurveKeyCollection</param>
/// <returns>The index of value if found in the EditCurveKeyCollection;
/// otherwise -1.</returns>
public int IndexOf(EditCurveKey item)
{
for (int i = 0; i < keys.Count; ++i)
{
if (keys[i].Id == item.Id) return i;
}
return -1;
}
/// <summary>
/// Remove a CurveKey from at the specfied index.
/// </summary>
/// <param name="index">The Zero-based index of the item to remove.</param>
public void RemoveAt(int index)
{
EditCurveKey key = keys[index];
idToKeyMap.Remove(key.Id);
keys.RemoveAt(index);
owner.OriginalCurve.Keys.RemoveAt(index);
}
/// <summary>
/// Gets or sets the element at the specfied index.
/// </summary>
/// <param name="index">The zero-based index of the element to
/// get or set.</param>
/// <returns>The element at the specfied index.</returns>
public EditCurveKey this[int index]
{
get
{
return keys[index];
}
set
{
if (value == null)
{
throw new System.ArgumentNullException();
}
// If new value has same position, it just change values.
float curPosition = keys[index].OriginalKey.Position;
if (curPosition == value.OriginalKey.Position)
{
keys[index] = value;
owner.OriginalCurve.Keys[index] = value.OriginalKey;
}
else
{
// Otherwise, remove given index key and add new one.
RemoveAt(index);
Add(value);
owner.Dirty = true;
}
}
}
#endregion
#region ICollection<EditCurveKey> Members
/// <summary>
/// Add an item to the EditCurveKeyCollection
/// </summary>
/// <param name="item">CurveKey to add to the EditCurveKeyCollection</param>
public void Add(EditCurveKey item)
{
if (item == null)
throw new System.ArgumentNullException("item");
// Add CurveKey to original curve.
owner.OriginalCurve.Keys.Add(item.OriginalKey);
// Add EditCurveKey to keys.
int index = owner.OriginalCurve.Keys.IndexOf(item.OriginalKey);
keys.Insert(index, item);
idToKeyMap.Add(item.Id, item);
owner.Dirty = true;
}
/// <summary>
/// Removes all EditCurveKeys from the EditCurveKeyCollection.
/// </summary>
public void Clear()
{
owner.OriginalCurve.Keys.Clear();
keys.Clear();
idToKeyMap.Clear();
owner.Dirty = true;
}
/// <summary>
/// Determines whether the ExpandEnvironmentVariables
/// contains a specific EditCurveKey.
/// </summary>
/// <param name="item">The EditCurveKey to locate in
/// the EditEditCurveKeyCollection. </param>
/// <returns>true if the EditCurveKey is found in
/// the ExpandEnvironmentVariables; otherwise, false. </returns>
public bool Contains(EditCurveKey item)
{
if (item == null)
throw new System.ArgumentNullException("item");
return keys.Contains(item);
}
public void CopyTo(EditCurveKey[] array, int arrayIndex)
{
throw new NotImplementedException(
"The method or operation is not implemented.");
}
/// <summary>
/// Gets the number of elements contained in the EditCurveKeyCollection.
/// </summary>
public int Count
{
get { return keys.Count; }
}
/// <summary>
/// Gets a value indicating whether the EditEditCurveKeyCollection is
/// read-only.
/// </summary>
public bool IsReadOnly
{
get { return false; }
}
/// <summary>
/// Removes the first occurrence of a specific EditCurveKey from
/// the EditCurveKeyCollection.
/// </summary>
/// <param name="item">The EditCurveKey to remove from
/// the EditCurveKeyCollection. </param>
/// <returns>true if item is successfully removed; otherwise, false.
/// This method also returns false if item was not found in
/// the EditCurveKeyCollection. </returns>
public bool Remove(EditCurveKey item)
{
if (item == null)
throw new System.ArgumentNullException("item");
bool result = owner.OriginalCurve.Keys.Remove(item.OriginalKey);
idToKeyMap.Remove(item.Id);
owner.Dirty = true;
return keys.Remove(item) && result;
}
#endregion
#region IEnumerable<EditCurveKey> Members
/// <summary>
/// Returns an enumerator that iterates through the EditCurveKeyCollection.
/// </summary>
/// <returns>A IEnumerator>EditCurveKey<
/// for the EditCurveKeyCollection. </returns>
public IEnumerator<EditCurveKey> GetEnumerator()
{
return keys.GetEnumerator();
}
#endregion
#region IEnumerable Members
/// <summary>
/// Returns an enumerator that iterates through the EditCurveKeyCollection.
/// </summary>
/// <returns>A IEnumerator for the EditCurveKeyCollection. </returns>
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return ((System.Collections.IEnumerable)keys).GetEnumerator();
}
#endregion
/// <summary>
/// Tries to look up a EditCurveKey by id.
/// </summary>
public bool TryGetValue(long keyId, out EditCurveKey value)
{
return idToKeyMap.TryGetValue(keyId, out value);
}
/// <summary>
/// look up a EditCurveKey by id.
/// </summary>
public EditCurveKey GetValue(long keyId)
{
return idToKeyMap[keyId];
}
/// <summary>
/// Creates a new object that is a copy of the current instance.
/// </summary>
/// <returns>A new object that is a copy of this instance.</returns>
public EditCurveKeyCollection Clone()
{
EditCurveKeyCollection newKeys = new EditCurveKeyCollection();
newKeys.keys = new List<EditCurveKey>(keys);
return newKeys;
}
#region Private methods.
/// <summary>
/// Private default construction.
/// </summary>
private EditCurveKeyCollection()
{
}
#endregion
#region Private members.
/// <summary>
/// Owner of this collection
/// </summary>
private EditCurve owner;
/// <summary>
/// EditCurveKey that contains EditCurveKey
/// </summary>
private List<EditCurveKey> keys = new List<EditCurveKey>();
/// <summary>
/// Id to EditCurveKey map.
/// </summary>
private Dictionary<long, EditCurveKey> idToKeyMap =
new Dictionary<long, EditCurveKey>();
#endregion
}
}
|
using JustSaying.Models;
namespace JustSaying.UnitTests.Messaging.Serialization.SerializationRegister
{
public class CustomMessage : Message
{
}
}
|
using StaticClasses.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace StaticClasses
{
// This static class is serving as a temporary database
// While the app is running, the static members of this class will keep their data
// It can also be accessed from anywhere
public static class OrdersTempDB
{
// This is an ID tracking property so that we generate the Id of orders automatically
public static int orderId = 5;
// These are the lists that will serve as tables in a database ( Store items in them )
public static List<User> Users { get; set; }
public static List<Order> Orders { get; set; }
// This is a static constructor
// It will only execute once, the first time this class is instanciated, when the app is started
// Static constructor does not have access modifier
static OrdersTempDB()
{
Orders = new List<Order>()
{
new Order(1, "book of books", "Best book ever", OrderStatus.Delivered),
new Order(2, "keyboard", "Mechanical", OrderStatus.DeliveryInProgress),
new Order(3, "Shoes", "Waterproof", OrderStatus.DeliveryInProgress),
new Order(4, "Set of Pens", "Ordinary pens", OrderStatus.Processing),
new Order(5, "sticky Notes", "Stickiest notes in the world", OrderStatus.CouldNotDeliver)
};
Users = new List<User>()
{
new User(12, "Bob22", "Bob St. 44"),
new User(13, "JillCoolCat", "Wayne St. 109a")
};
Users[0].Orders.Add(Orders[0]);
Users[0].Orders.Add(Orders[1]);
Users[0].Orders.Add(Orders[2]);
Users[1].Orders.Add(Orders[3]);
Users[1].Orders.Add(Orders[4]);
}
public static void ListUsers()
{
for (int i = 1; i <= Users.Count; i++)
{
Console.WriteLine($"{i}) {Users[i - 1].Username}");
}
}
public static void InsertOrder(int userId, Order order)
{
// When an order is added, we increment the ID and set it to the new order
order.Id = ++orderId;
Orders.Add(order);
Users.SingleOrDefault(x => x.Id == userId).Orders.Add(order);
Console.WriteLine("Order successfully added!");
}
}
}
|
using System;
namespace NimatorCouchBase.NimatorBooster.L.Parser.Storage
{
public interface IMemorySlot
{
IMemorySlotKey Key { get; }
Type ValueType { get; }
object Value { get; }
bool IsEmpty();
}
} |
//----------------------------------------------------------------
// <copyright company="Microsoft Corporation">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//----------------------------------------------------------------
namespace System.Activities.Presentation.View
{
using System.Runtime;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
internal class ScrollViewerPanner
{
private ScrollViewer scrollViewer;
private Point panningStartPosition;
private PanState currentPanState;
private bool inPanMode;
private MouseButton draggingMouseButton;
public ScrollViewerPanner(ScrollViewer scrollViewer)
{
Fx.Assert(scrollViewer != null, "ScrollViewer should never be null");
this.ScrollViewer = scrollViewer;
}
internal enum PanState
{
Normal, // Normal editing mode
ReadyToPan,
Panning,
}
public ScrollViewer ScrollViewer
{
get
{
return this.scrollViewer;
}
set
{
if (value != this.scrollViewer)
{
if (this.scrollViewer != null)
{
this.UnregisterEvents();
}
this.scrollViewer = value;
if (this.scrollViewer != null)
{
this.RegisterEvents();
}
}
}
}
public bool InPanMode
{
get
{
return this.inPanMode;
}
set
{
if (this.inPanMode != value)
{
this.inPanMode = value;
if (this.inPanMode)
{
this.CurrentPanState = PanState.ReadyToPan;
}
else
{
this.CurrentPanState = PanState.Normal;
}
}
}
}
public Cursor Hand { get; set; }
public Cursor DraggingHand { get; set; }
internal PanState CurrentPanState
{
get
{
return this.currentPanState;
}
set
{
if (this.currentPanState != value)
{
this.currentPanState = value;
switch (this.currentPanState)
{
case PanState.ReadyToPan:
this.scrollViewer.Cursor = this.Hand;
break;
case PanState.Panning:
this.scrollViewer.Cursor = this.DraggingHand;
break;
default:
this.scrollViewer.Cursor = null;
break;
}
this.UpdateForceCursorProperty();
}
}
}
internal bool IsInScrollableArea(Point mousePosition)
{
return mousePosition.X < this.scrollViewer.ViewportWidth && mousePosition.Y < this.scrollViewer.ViewportHeight;
}
internal void OnScrollViewerMouseDown(object sender, MouseButtonEventArgs e)
{
switch (this.CurrentPanState)
{
case PanState.Normal:
if (e.ChangedButton == MouseButton.Middle)
{
this.StartPanningIfNecessary(e);
}
break;
case PanState.ReadyToPan:
switch (e.ChangedButton)
{
case MouseButton.Left:
this.StartPanningIfNecessary(e);
break;
case MouseButton.Middle:
this.StartPanningIfNecessary(e);
break;
case MouseButton.Right:
e.Handled = true;
break;
}
break;
case PanState.Panning:
e.Handled = true;
break;
default:
break;
}
}
internal void OnLostMouseCapture(object sender, MouseEventArgs e)
{
this.StopPanning();
}
internal void OnScrollViewerMouseMove(object sender, MouseEventArgs e)
{
switch (this.CurrentPanState)
{
case PanState.Panning:
Point currentPosition = Mouse.GetPosition(this.scrollViewer);
Vector offset = Point.Subtract(currentPosition, this.panningStartPosition);
this.panningStartPosition = currentPosition;
this.scrollViewer.ScrollToHorizontalOffset(this.scrollViewer.HorizontalOffset - offset.X);
this.scrollViewer.ScrollToVerticalOffset(this.scrollViewer.VerticalOffset - offset.Y);
e.Handled = true;
break;
case PanState.ReadyToPan:
this.UpdateForceCursorProperty();
break;
default:
break;
}
}
internal void OnScrollViewerMouseUp(object sender, MouseButtonEventArgs e)
{
switch (this.CurrentPanState)
{
case PanState.ReadyToPan:
this.StopPanningIfNecessary(e);
// When the mouse is captured by other windows/views, that
// window/view needs this mouse-up message to release
// the capture.
if (!this.IsMouseCapturedByOthers())
{
e.Handled = true;
}
break;
case PanState.Panning:
this.StopPanningIfNecessary(e);
e.Handled = true;
break;
default:
break;
}
}
internal void OnScrollViewerKeyDown(object sender, KeyEventArgs e)
{
switch (this.CurrentPanState)
{
// Don't change to ReadyToPan mode if the space is a
// repeated input, because repeated-key input may come
// from activity element on the scroll view.
case PanState.Normal:
if (e.Key == Key.Space
&& !e.IsRepeat
&& this.AllowSwitchToPanning())
{
this.CurrentPanState = PanState.ReadyToPan;
}
break;
default:
break;
}
}
internal void OnScrollViewerKeyUp(object sender, KeyEventArgs e)
{
switch (this.CurrentPanState)
{
case PanState.ReadyToPan:
if (e.Key == Key.Space && !this.InPanMode)
{
this.CurrentPanState = PanState.Normal;
}
break;
default:
break;
}
}
private void StartPanningIfNecessary(MouseButtonEventArgs e)
{
if (DesignerView.IsMouseInViewport(e, this.scrollViewer))
{
this.draggingMouseButton = e.ChangedButton;
this.CurrentPanState = PanState.Panning;
this.scrollViewer.Focus();
this.panningStartPosition = Mouse.GetPosition(this.scrollViewer);
Mouse.Capture(this.scrollViewer);
e.Handled = true;
}
}
private void StopPanningIfNecessary(MouseButtonEventArgs e)
{
if (e.ChangedButton == this.draggingMouseButton && object.Equals(this.scrollViewer, Mouse.Captured))
{
// Trigers OnLostMouseCapture
this.scrollViewer.ReleaseMouseCapture();
}
}
private void StopPanning()
{
// stop panning
if (this.InPanMode
|| (Keyboard.IsKeyDown(Key.Space) && this.CurrentPanState == PanState.Panning))
{
this.CurrentPanState = PanState.ReadyToPan;
}
else
{
this.CurrentPanState = PanState.Normal;
}
}
private void UpdateForceCursorProperty()
{
Point pt = Mouse.GetPosition(this.ScrollViewer);
if (this.IsInScrollableArea(pt))
{
this.scrollViewer.ForceCursor = true;
}
else
{
this.scrollViewer.ForceCursor = false;
}
}
// Mouse is sometimes captured by ScrollViewer's children, like
// RepeatButton in Scroll Bar.
private bool IsMouseCapturedByOthers()
{
return (Mouse.Captured != null)
&& !object.Equals(Mouse.Captured, this.ScrollViewer);
}
private bool AllowSwitchToPanning()
{
return Mouse.LeftButton == MouseButtonState.Released
&& Mouse.RightButton == MouseButtonState.Released;
}
private void RegisterEvents()
{
this.scrollViewer.PreviewMouseDown += new MouseButtonEventHandler(this.OnScrollViewerMouseDown);
this.scrollViewer.PreviewMouseMove += new MouseEventHandler(this.OnScrollViewerMouseMove);
this.scrollViewer.PreviewMouseUp += new MouseButtonEventHandler(this.OnScrollViewerMouseUp);
this.scrollViewer.LostMouseCapture += new MouseEventHandler(this.OnLostMouseCapture);
this.scrollViewer.KeyDown += new KeyEventHandler(this.OnScrollViewerKeyDown);
this.scrollViewer.KeyUp += new KeyEventHandler(this.OnScrollViewerKeyUp);
}
private void UnregisterEvents()
{
this.scrollViewer.PreviewMouseDown -= new MouseButtonEventHandler(this.OnScrollViewerMouseDown);
this.scrollViewer.PreviewMouseMove -= new MouseEventHandler(this.OnScrollViewerMouseMove);
this.scrollViewer.PreviewMouseUp -= new MouseButtonEventHandler(this.OnScrollViewerMouseUp);
this.scrollViewer.LostMouseCapture -= new MouseEventHandler(this.OnLostMouseCapture);
this.scrollViewer.KeyDown -= new KeyEventHandler(this.OnScrollViewerKeyDown);
this.scrollViewer.KeyUp -= new KeyEventHandler(this.OnScrollViewerKeyUp);
}
}
}
|
using Equinor.ProCoSys.Preservation.Domain.AggregateModels.ProjectAggregate;
using MediatR;
using ServiceResult;
namespace Equinor.ProCoSys.Preservation.Command.TagCommands.DuplicateAreaTag
{
public class DuplicateAreaTagCommand : AbstractAreaTag, IRequest<Result<int>>, ITagCommandRequest
{
public DuplicateAreaTagCommand(
int tagId,
TagType tagType,
string disciplineCode,
string areaCode,
string tagNoSuffix,
string description,
string remark,
string storageArea)
{
TagId = tagId;
TagType = tagType;
DisciplineCode = disciplineCode;
AreaCode = areaCode;
TagNoSuffix = tagNoSuffix;
Description = description;
Remark = remark;
StorageArea = storageArea;
}
public int TagId { get; }
public override TagType TagType { get; }
public override string DisciplineCode { get; }
public override string AreaCode { get; }
public override string PurchaseOrderCalloffCode => null;
public override string TagNoSuffix { get; }
public string Description { get; }
public string Remark { get; }
public string StorageArea { get; }
}
}
|
namespace Elicon.Domain.GateLevel.Contracts.DataAccess
{
public interface INetlistFileReaderProvider
{
INetlistFileReader GetReaderFor(string source);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ServiceLibrary.DependencyInjection
{
public class ServiceHost : System.ServiceModel.ServiceHost
{
public ServiceHost()
{ }
public ServiceHost(object singletonInstance, params Uri[] baseAddresses)
: base(singletonInstance, baseAddresses)
{ }
public ServiceHost(Type serviceType, params Uri[] baseAddresses)
: base(serviceType, baseAddresses)
{ }
protected override void OnOpening()
{
Description.Behaviors.Add(new ServiceLibrary.DependencyInjection.ServiceBehavior());
base.OnOpening();
}
}
}
|
using Microsoft.Win32.SafeHandles;
using System.Runtime.InteropServices;
namespace MiniTerm.Native
{
/// <summary>
/// PInvoke signatures for win32 console api
/// </summary>
static class ConsoleApi
{
internal const int STD_OUTPUT_HANDLE = -11;
internal const uint ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004;
internal const uint DISABLE_NEWLINE_AUTO_RETURN = 0x0008;
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern SafeFileHandle GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetConsoleMode(SafeFileHandle hConsoleHandle, uint mode);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool GetConsoleMode(SafeFileHandle handle, out uint mode);
internal delegate bool ConsoleEventDelegate(CtrlTypes ctrlType);
internal enum CtrlTypes : uint
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetConsoleCtrlHandler(ConsoleEventDelegate callback, bool add);
}
}
|
using System;
using BTCPayServer.Configuration;
using Microsoft.Extensions.Configuration;
using NBitcoin;
namespace BTCPayServer
{
public static class ConfigurationExtensions
{
public static string GetDataDir(this IConfiguration configuration)
{
var networkType = DefaultConfiguration.GetNetworkType(configuration);
return GetDataDir(configuration, networkType);
}
public static string GetDataDir(this IConfiguration configuration, NetworkType networkType)
{
var defaultSettings = BTCPayDefaultSettings.GetDefaultSettings(networkType);
return configuration.GetOrDefault<string>("datadir", defaultSettings.DefaultDataDirectory);
}
public static Uri GetExternalUri(this IConfiguration configuration)
{
return configuration.GetOrDefault<Uri>("externalurl", null);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TeammatesMatchupLibrary
{
public enum RegionsEnum
{
euw1,
na1,
br1,
eun1,
jp1,
kr,
la1, la2,
oc1,
tr1,
ru,
pbe1
}
}
|
// <copyright company="Aspose Pty Ltd">
// Copyright (C) 2011-2020 GroupDocs. All Rights Reserved.
// </copyright>
namespace GroupDocs.Parser.Examples.CSharp.AdvancedUsage.WorkingWithZipArchivesAndAttachments
{
using System;
using System.Collections.Generic;
using System.Text;
using GroupDocs.Parser.Data;
/// <summary>
/// This example shows how to iterate through container items.
/// </summary>
static class IterateThroughContainerItems
{
public static void Run()
{
// Create an instance of Parser class
using (Parser parser = new Parser(Constants.SampleZip))
{
// Extract attachments from the container
IEnumerable<ContainerItem> attachments = parser.GetContainer();
// Check if container extraction is supported
if (attachments == null)
{
Console.WriteLine("Container extraction isn't supported");
}
// Iterate over attachments
foreach (ContainerItem item in attachments)
{
// Print an item name and size
Console.WriteLine(string.Format("{0}: {1}", item.Name, item.Size));
}
}
}
}
}
|
using System;
using VidlyConsoleApp01.Examples;
namespace VidlyConsoleApp01
{
class Program
{
static void Main(string[] args)
{
var custExamples = new CustomerExamples();
var codeTableExamples = new CodeTableExamples();
var movieExamples = new MovieExamples();
var aspNetExamples = new AspNetExamples();
//custExamples.Example01();
//codeTableExamples.Example01();
//codeTableExamples.Example02();
//custExamples.Example02();
//custExamples.Example03();
//movieExamples.Example02();
Console.WriteLine();
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleAppWebJob.Constants
{
public class Format
{
public const string DateTimeStr = "yyyy-MM-ddTHH:mm:ss";
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WaveManager : MonoBehaviour
{
public List<Wave> waves = new List<Wave>();
public Transform[] waypoints;
public bool shouldStartImmediately;
int currentWaveIndex;
public float waitBeforeSpawn;
public event Action<bool> waveCompleted;
public event Action<Enemy> enemySpawned;
IEnumerator Start()
{
if (shouldStartImmediately)
{
yield return new WaitForSeconds(waitBeforeSpawn);
StartWave();
}
}
public void StartWave()
{
if (waves.Count > 0 && currentWaveIndex < waves.Count)
{
Wave wave = waves[currentWaveIndex];
wave.waveCompleted += Wave_waveCompleted;
wave.enemySpawned += Wave_enemySpawned;
wave.StartSpawning(waypoints);
}
}
private void Wave_enemySpawned(Enemy spawned)
{
//bubble up
enemySpawned?.Invoke(spawned);
}
private void Wave_waveCompleted()
{
//bubble up
//param is: was last wave?
waveCompleted?.Invoke(currentWaveIndex + 1 >= waves.Count);
}
public void NextWave()
{
//cleanup
waves[currentWaveIndex].waveCompleted -= Wave_waveCompleted;
currentWaveIndex++;
StartWave();
}
}
|
// Copyright (c) Samuel Cragg.
//
// Licensed under the MIT license. See LICENSE file in the project root for
// full license information.
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: ComVisible(false)]
[assembly: CLSCompliant(true)]
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // Allow NSubstitute to mock our types
[assembly: InternalsVisibleTo("DataAccess.UnitTests")]
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DefaultState : IState {
private bool spawnEnemy;
public DefaultState()
{
this.spawnEnemy = true;
}
public DefaultState(bool spawnEnemy)
{
this.spawnEnemy = spawnEnemy;
}
public void Enter()
{
if (!spawnEnemy)
{
GameObject.FindWithTag("Enemy").gameObject.SetActive(false);
}
}
public void Execute()
{
}
public void Exit()
{
}
public string Log()
{
return "Default";
}
}
|
@model ControlGroup
@{
if (Model == null || !Model.Visible)
{
return;
}
}
<li class="control-group">
<h3 class="semi-bold">@Model.GroupName</h3>
<ul>
@foreach (var control in Model.Controls)
{
if (string.IsNullOrEmpty(control.Link))
{
<li>@Html.ActionLink(control.ControlName, "Index", control.ControlName)</li>
}
else
{
<li><a target="_blank" href="@control.Link">@control.ControlName</a></li>
}
}
</ul>
</li> |
namespace GeocodeApi.Geocode.DrivingDependencies
{
public class GeocodeRequest
{
public string Street { get; set; }
public string City { get; set; }
public string StateCode { get; set; }
public string ZipCode { get; set; }
}
}
|
using Editor_Mono.Cecil.Cil;
using Editor_Mono.Cecil.Metadata;
using System;
namespace Editor_Mono.Cecil.PE
{
internal sealed class Image
{
public ModuleKind Kind;
public string RuntimeVersion;
public TargetArchitecture Architecture;
public ModuleCharacteristics Characteristics;
public string FileName;
public Section[] Sections;
public Section MetadataSection;
public uint EntryPointToken;
public ModuleAttributes Attributes;
public DataDirectory Debug;
public DataDirectory Resources;
public DataDirectory StrongName;
public StringHeap StringHeap;
public BlobHeap BlobHeap;
public UserStringHeap UserStringHeap;
public GuidHeap GuidHeap;
public TableHeap TableHeap;
private readonly int[] coded_index_sizes = new int[13];
private readonly Func<Table, int> counter;
public Image()
{
this.counter = new Func<Table, int>(this.GetTableLength);
}
public bool HasTable(Table table)
{
return this.GetTableLength(table) > 0;
}
public int GetTableLength(Table table)
{
return (int)this.TableHeap[table].Length;
}
public int GetTableIndexSize(Table table)
{
if (this.GetTableLength(table) >= 65536)
{
return 4;
}
return 2;
}
public int GetCodedIndexSize(CodedIndex coded_index)
{
int num = this.coded_index_sizes[(int)coded_index];
if (num != 0)
{
return num;
}
return this.coded_index_sizes[(int)coded_index] = coded_index.GetSize(this.counter);
}
public uint ResolveVirtualAddress(uint rva)
{
Section sectionAtVirtualAddress = this.GetSectionAtVirtualAddress(rva);
if (sectionAtVirtualAddress == null)
{
throw new ArgumentOutOfRangeException();
}
return this.ResolveVirtualAddressInSection(rva, sectionAtVirtualAddress);
}
public uint ResolveVirtualAddressInSection(uint rva, Section section)
{
return rva + section.PointerToRawData - section.VirtualAddress;
}
public Section GetSection(string name)
{
Section[] sections = this.Sections;
for (int i = 0; i < sections.Length; i++)
{
Section section = sections[i];
if (section.Name == name)
{
return section;
}
}
return null;
}
public Section GetSectionAtVirtualAddress(uint rva)
{
Section[] sections = this.Sections;
for (int i = 0; i < sections.Length; i++)
{
Section section = sections[i];
if (rva >= section.VirtualAddress && rva < section.VirtualAddress + section.SizeOfRawData)
{
return section;
}
}
return null;
}
public ImageDebugDirectory GetDebugHeader(out byte[] header)
{
Section sectionAtVirtualAddress = this.GetSectionAtVirtualAddress(this.Debug.VirtualAddress);
ByteBuffer byteBuffer = new ByteBuffer(sectionAtVirtualAddress.Data);
byteBuffer.position = (int)(this.Debug.VirtualAddress - sectionAtVirtualAddress.VirtualAddress);
ImageDebugDirectory result = new ImageDebugDirectory
{
Characteristics = byteBuffer.ReadInt32(),
TimeDateStamp = byteBuffer.ReadInt32(),
MajorVersion = byteBuffer.ReadInt16(),
MinorVersion = byteBuffer.ReadInt16(),
Type = byteBuffer.ReadInt32(),
SizeOfData = byteBuffer.ReadInt32(),
AddressOfRawData = byteBuffer.ReadInt32(),
PointerToRawData = byteBuffer.ReadInt32()
};
if (result.SizeOfData == 0 || result.PointerToRawData == 0)
{
header = Empty<byte>.Array;
return result;
}
byteBuffer.position = (int)((long)result.PointerToRawData - (long)((ulong)sectionAtVirtualAddress.PointerToRawData));
header = new byte[result.SizeOfData];
Buffer.BlockCopy(byteBuffer.buffer, byteBuffer.position, header, 0, header.Length);
return result;
}
}
}
|
namespace Minotaur.Classification.Rules {
using System;
using System.Diagnostics.CodeAnalysis;
using Minotaur.Collections;
public sealed class Rule: IEquatable<Rule> {
public readonly int NonNullTestCount;
public readonly Antecedent Antecedent;
public readonly Consequent Consequent;
private readonly int _precomputedHashCode;
public Rule(Antecedent antecedent, Consequent consequent) {
Antecedent = antecedent;
Consequent = consequent;
_precomputedHashCode = HashCode.Combine(antecedent, consequent);
}
public bool Covers(Array<float> instance) => Antecedent.Covers(instance);
public override string ToString() {
var antecedent = "IF " + string.Join(" AND ", Antecedent);
var consequent = " THEN " + Consequent.ToString();
return antecedent + consequent;
}
public override int GetHashCode() => _precomputedHashCode;
public override bool Equals(object? obj) => Equals((Rule) obj!);
public bool Equals([AllowNull] Rule other) {
if (other is null)
throw new ArgumentNullException(nameof(other));
if (ReferenceEquals(this, other))
return true;
return Antecedent.Equals(other.Antecedent) &&
Consequent.Equals(other.Consequent);
}
}
}
|
using System;
namespace ESFA.DC.ILR.ValidationService.Data.External.LARS.Interface
{
/// <summary>
/// the lars framework aim
/// </summary>
public interface ILARSFrameworkAim
{
/// <summary>
/// Gets the framework code.
/// </summary>
int FworkCode { get; }
/// <summary>
/// Gets the type of the programme.
/// </summary>
int ProgType { get; }
/// <summary>
/// Gets the pathway code.
/// </summary>
int PwayCode { get; }
/// <summary>
/// Gets the learning aim reference.
/// </summary>
string LearnAimRef { get; }
/// <summary>
/// Gets the type of the framework component.
/// </summary>
int? FrameworkComponentType { get; }
/// <summary>
/// Gets the effective from date.
/// </summary>
DateTime EffectiveFrom { get; }
/// <summary>
/// Gets the effective to date.
/// </summary>
DateTime? EffectiveTo { get; }
}
}
|
using System.Collections.Generic;
namespace Plus.EventBus
{
/// <summary>
/// Defines an interface for factories those are responsible to create/get and release of event handlers.
/// </summary>
public interface IEventHandlerFactory
{
/// <summary>
/// Gets an event handler.
/// </summary>
/// <returns>The event handler</returns>
IEventHandlerDisposeWrapper GetHandler();
bool IsInFactories(List<IEventHandlerFactory> handlerFactories);
}
} |
namespace OpenDND.Data.Repositories.DND
{
public class SpellsRepository : RepositoryBase
{
public SpellsRepository(OpenDNDContext openDndContext) : base(openDndContext)
{
}
}
} |
using System;
class EqualWord
{
static void Main()
{
var word1 = Console.ReadLine().ToLower();
var word2 = Console.ReadLine().ToLower();
if (word1==word2)
{
Console.WriteLine("yes");
}
else
{
Console.WriteLine("no");
}
}
}
|
namespace Johnny.Controls.Windows.ListBoxSelector
{
partial class GenericListBoxSelector<T>
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.lstAllItems = new System.Windows.Forms.ListBox();
this.btnSelectAll = new System.Windows.Forms.Button();
this.btnUnselectAll = new System.Windows.Forms.Button();
this.btnUnselectOne = new System.Windows.Forms.Button();
this.btnSelectOne = new System.Windows.Forms.Button();
this.lstSelectedItems = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// lstAllItems
//
this.lstAllItems.FormattingEnabled = true;
this.lstAllItems.Location = new System.Drawing.Point(3, 3);
this.lstAllItems.Name = "lstAllItems";
this.lstAllItems.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lstAllItems.Size = new System.Drawing.Size(174, 225);
this.lstAllItems.TabIndex = 9;
//
// btnSelectAll
//
this.btnSelectAll.Location = new System.Drawing.Point(195, 68);
this.btnSelectAll.Name = "btnSelectAll";
this.btnSelectAll.Size = new System.Drawing.Size(40, 25);
this.btnSelectAll.TabIndex = 18;
this.btnSelectAll.Text = ">>";
this.btnSelectAll.UseVisualStyleBackColor = true;
this.btnSelectAll.Click += new System.EventHandler(this.btnSelectAll_Click);
//
// btnUnselectAll
//
this.btnUnselectAll.Location = new System.Drawing.Point(195, 170);
this.btnUnselectAll.Name = "btnUnselectAll";
this.btnUnselectAll.Size = new System.Drawing.Size(40, 25);
this.btnUnselectAll.TabIndex = 20;
this.btnUnselectAll.Text = "<<";
this.btnUnselectAll.UseVisualStyleBackColor = true;
this.btnUnselectAll.Click += new System.EventHandler(this.btnUnselectAll_Click);
//
// btnUnselectOne
//
this.btnUnselectOne.Location = new System.Drawing.Point(195, 119);
this.btnUnselectOne.Name = "btnUnselectOne";
this.btnUnselectOne.Size = new System.Drawing.Size(40, 25);
this.btnUnselectOne.TabIndex = 19;
this.btnUnselectOne.Text = "<";
this.btnUnselectOne.UseVisualStyleBackColor = true;
this.btnUnselectOne.Click += new System.EventHandler(this.btnUnselectOne_Click);
//
// btnSelectOne
//
this.btnSelectOne.Location = new System.Drawing.Point(195, 20);
this.btnSelectOne.Name = "btnSelectOne";
this.btnSelectOne.Size = new System.Drawing.Size(40, 25);
this.btnSelectOne.TabIndex = 17;
this.btnSelectOne.Text = ">";
this.btnSelectOne.UseVisualStyleBackColor = true;
this.btnSelectOne.Click += new System.EventHandler(this.btnSelectOne_Click);
//
// lstSelectedItems
//
this.lstSelectedItems.FormattingEnabled = true;
this.lstSelectedItems.Location = new System.Drawing.Point(253, 3);
this.lstSelectedItems.Name = "lstSelectedItems";
this.lstSelectedItems.SelectionMode = System.Windows.Forms.SelectionMode.MultiExtended;
this.lstSelectedItems.Size = new System.Drawing.Size(182, 225);
this.lstSelectedItems.TabIndex = 21;
//
// GenericListBoxSelector
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.lstSelectedItems);
this.Controls.Add(this.btnSelectAll);
this.Controls.Add(this.btnUnselectAll);
this.Controls.Add(this.btnUnselectOne);
this.Controls.Add(this.btnSelectOne);
this.Controls.Add(this.lstAllItems);
this.Name = "GenericListBoxSelector";
this.Size = new System.Drawing.Size(440, 231);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.ListBox lstAllItems;
private System.Windows.Forms.Button btnSelectAll;
private System.Windows.Forms.Button btnUnselectAll;
private System.Windows.Forms.Button btnUnselectOne;
private System.Windows.Forms.Button btnSelectOne;
private System.Windows.Forms.ListBox lstSelectedItems;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Threading.Tasks;
using MegaSolucao.Infraestrutura;
using Raven.Client.Documents;
using Raven.Client.Documents.Conventions;
using Raven.Client.Documents.Operations.Indexes;
using Raven.Client.ServerWide;
using Raven.Client.ServerWide.Operations;
namespace MegaSolucao.Persistencia.BancoDeDados.Raven
{
public class GSDocumentStore : DocumentStore
{
public GSDocumentStore()
{
Urls = new[] { Sessao.Configuracao.ConexaoRavenDB.Servidor };
Database = Sessao.Configuracao.ConexaoRavenDB.NomeDoBanco;
if (!string.IsNullOrEmpty(Sessao.Configuracao.ConexaoRavenDB.CaminhoCertificado))
{
Certificate = new X509Certificate2(Sessao.Configuracao.ConexaoRavenDB.CaminhoCertificado);
}
SobrescrevaConventions();
Initialize();
}
public GSDocumentStore(string url, string database)
{
Urls = new[] { url };
Database = database;
if (!string.IsNullOrEmpty(Sessao.Configuracao.ConexaoRavenDB.CaminhoCertificado))
{
Certificate = new X509Certificate2(Sessao.Configuracao.ConexaoRavenDB.CaminhoCertificado);
}
SobrescrevaConventions();
Initialize();
}
public sealed override IDocumentStore Initialize()
{
return base.Initialize();
}
private void SobrescrevaConventions()
{
base.Conventions.FindCollectionName = type =>
NomenclaturaDeColecaoCustomizada.ContainsKey(type)
? NomenclaturaDeColecaoCustomizada[type]
: DocumentConventions.DefaultGetCollectionName(type);
}
public static Dictionary<Type, string> NomenclaturaDeColecaoCustomizada =>
new Dictionary<Type, string>
{
//{ typeof(Interacao), "Interacoes" }
};
#region Operações de banco
private bool ObtenhaVersaoDoServidor(out BuildNumber buildNumber, int timeoutMilliseconds = 5000)
{
try
{
var task = Maintenance.Server.SendAsync(new GetBuildNumberOperation());
var success = task.Wait(timeoutMilliseconds);
buildNumber = task.Result;
return success;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
buildNumber = null;
return false;
}
}
public bool VerifiqueSeBancoExiste(string nomeDoBanco)
{
var result = Maintenance.Server.Send(new GetDatabaseRecordOperation(nomeDoBanco));
return result != null;
}
public bool VerifiqueSeServidorEstahOnline(int timeoutMilliseconds = 5000)
{
var conexaoOk = ObtenhaVersaoDoServidor(out _);
var databaseExists = false;
if (conexaoOk) databaseExists = VerifiqueSeBancoExiste(Database);
return conexaoOk && databaseExists;
}
public void CompactarBancoDeDados(string databaseName)
{
// Get all index names
var indexNames = Maintenance.Send(new GetIndexNamesOperation(0, int.MaxValue));
var settings = new CompactSettings
{
DatabaseName = databaseName,
Documents = true,
Indexes = indexNames
};
// Compact entire database: documents + all indexes
var operation = Maintenance.Server.Send(new CompactDatabaseOperation(settings));
operation.WaitForCompletion();
}
#endregion
}
}
|
using UnityEngine;
using System.Collections.Generic;
using VRDF.Core.SetupVR;
namespace VRDF.Core.Raycast
{
public static class ControllersRaycastOffset
{
public static Dictionary<EDevice, Vector3> RaycastPositionOffset = new Dictionary<EDevice, Vector3>
{
{ EDevice.GEAR_VR, Vector3.zero },
{ EDevice.HTC_FOCUS, Vector3.zero },
{ EDevice.HTC_VIVE, Vector3.zero },
{ EDevice.OCULUS_GO, Vector3.zero },
{ EDevice.OCULUS_QUEST, Vector3.zero },
{ EDevice.OCULUS_RIFT, Vector3.zero },
{ EDevice.OCULUS_RIFT_S, Vector3.zero },
{ EDevice.SIMULATOR, Vector3.zero },
{ EDevice.WMR, new Vector3(-0.01f, -0.02f, -0.01f)}
};
public static Dictionary<EDevice, Vector3> RaycastDirectionOffset = new Dictionary<EDevice, Vector3>
{
{ EDevice.GEAR_VR, Vector3.zero },
{ EDevice.HTC_FOCUS, Vector3.zero },
{ EDevice.HTC_VIVE, Vector3.zero },
{ EDevice.OCULUS_GO, Vector3.zero },
{ EDevice.OCULUS_QUEST, Vector3.zero },
{ EDevice.OCULUS_RIFT, Vector3.zero },
{ EDevice.OCULUS_RIFT_S, Vector3.zero },
{ EDevice.SIMULATOR, Vector3.zero },
{ EDevice.WMR, new Vector3(-0.015f, -0.5f, 0.0f)}
};
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using Fact.Extensions.States;
namespace Fact.Extensions.Collection
{
/// <summary>
/// A State Accessor is a more powerful type of session/state bag. It adds the following abilities:
///
/// 1) queryable type awareness of contents of bag
/// 2) a general repeatability as to the order & type of contents (see IParameterProvider)
/// 3) serializability for the entire bag
/// 4) dirty state tracking
/// </summary>
public interface IStateAccessor :
IStateAccessorBase,
IDirtyMarker,
INamedIndexer<object>,
IIndexer<int, object>
{
}
/// <summary>
/// The most basic IStateAccessor, get/set parameters directly by IParameterInfo
/// </summary>
public interface IStateAccessorBase : IIndexer<IParameterInfo, object>
{
IParameterProvider ParameterProvider { get; }
/// <summary>
/// Fired when a parameter is reassigned
/// </summary>
event Action<IParameterInfo, object> ParameterUpdated;
}
}
|
namespace WebApi.Infra
{
public interface IEnumnerableUser
{
}
} |
@page
@using Microsoft.AspNetCore.Mvc.Localization
@using Acme.BookStore.Localization
@using Volo.Abp.AspNetCore.Mvc.UI.Bootstrap.TagHelpers.Modal
@using Acme.BookStore.Web.Pages.Books
@using Acme.BookStore.Books;
@using System.Globalization
@inject IHtmlLocalizer<BookStoreResource> L
@model CreateModalModel
@{
Layout = null;
}
<form data-ajaxForm="true" asp-page="/Books/CreateModal" autocomplete="off">
<abp-modal>
<abp-modal-header title="@L["NewBook"].Value"></abp-modal-header>
<abp-modal-body>
<abp-input asp-for="Book.Name"/>
<abp-select asp-for="Book.Type"/>
<abp-input asp-for="Book.PublishDate" value="@DateTime.Now.ToString("yyyy-MM-dd")" type="date"/>
<abp-input asp-for="Book.Price"/>
</abp-modal-body>
<abp-modal-footer buttons="@(AbpModalButtons.Cancel|AbpModalButtons.Save)"></abp-modal-footer>
</abp-modal>
</form> |
using System;
using System.Collections.Generic;
using System.Linq;
using AutoFixture;
using Lucene.Net.DocumentMapper.FieldMappers;
using Lucene.Net.DocumentMapper.Helpers;
using Lucene.Net.DocumentMapper.Interfaces;
using Lucene.Net.DocumentMapper.Tests.Models;
using Lucene.Net.DocumentMapper.Tests.Models.NestedObjects;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Xunit;
namespace Lucene.Net.DocumentMapper.Tests
{
public class DocumentMapperTests
{
private readonly ServiceProvider _serviceProvider;
private readonly Fixture _fixture;
public DocumentMapperTests()
{
_fixture = new Fixture();
_serviceProvider = new ServiceCollection()
.AddLuceneDocumentMapper()
.BuildServiceProvider();
}
[Fact]
public void Test_Is_Tokenized()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("Body"));
Assert.Equal(typeof(TextFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Is_String()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
//var p = typeof(BlogPost).GetProperties().FirstOrDefault(x => x.Name == "Name");
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("Name"));
Assert.Equal(typeof(StringFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Is_Enum()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("Category3"));
Assert.Equal(typeof(EnumFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Is_DateTime()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("PublishedDate"));
Assert.Equal(typeof(DateTimeFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Is_DateTimeOffset()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("PublishedDateOffset"));
Assert.Equal(typeof(DateTimeOffsetFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Is_Object()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("Category"));
Assert.Equal(typeof(ObjectFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Is_Boolean()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("IsPublished"));
Assert.Equal(typeof(BooleanFieldMapper), propertyMapper?.GetType());
}
[Fact]
public void Test_Not_Indexed_If_Too_Large_String()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("SeoDescription"));
Assert.Equal(typeof(StringFieldMapper), propertyMapper?.GetType());
var blogPost = new BlogPost { SeoDescription = new string('*', 32767) };
var document = documentMapper.Map(blogPost);
var isIndexed = document.GetField("SeoDescription").IndexableFieldType.IsIndexed;
Assert.False(isIndexed);
}
[Fact]
public void Test_Field_Not_Stored()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("SeoTitle"));
Assert.Equal(typeof(StringFieldMapper), propertyMapper?.GetType());
var blogPost = new BlogPost { SeoTitle = "My Test Seo Title" };
var document = documentMapper.Map(blogPost);
var isStored = document.GetField("SeoTitle").IndexableFieldType.IsStored;
Assert.False(isStored);
}
[Fact]
public void Test_Object_Stored_As_Json()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("Category"));
Assert.Equal(typeof(ObjectFieldMapper), propertyMapper?.GetType());
var blogPost = new BlogPost
{
Category = new Category
{
Description = "My Test Category",
Name = "TestCategory"
}
};
var document = documentMapper.Map(blogPost);
var category = JsonConvert.DeserializeObject<Category>(document.GetField("Category").GetStringValue());
Assert.Equal("TestCategory", category?.Name);
}
[Fact]
public void Test_ComplexType_Stored_As_Individual_Fields()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper.GetFieldMapper(typeof(BlogPost).GetProperty("Category2"));
Assert.Null(propertyMapper);
var blogPost = new BlogPost
{
Category2 = new Category
{
Description = "My Test Category",
Name = "TestCategory"
}
};
var document = documentMapper.Map(blogPost);
var fields = document.Fields.Where(x => x.Name.StartsWith("Category2"));
Assert.Equal(2, fields.Count());
}
[Fact]
public void Test_Collection_Primitive_Type_Fields()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
var blogPost = new BlogPost
{
TagIds = new List<string>()
{
"1",
"2",
"3"
}
};
var document = documentMapper.Map(blogPost);
var fields = document.Fields.Where(x => x.Name.StartsWith("TagIds"));
Assert.Equal(3, fields.Count());
Assert.All(fields, field => field.Name.Equals("TagIds"));
}
[Fact]
public void Test_Enum_Properly_Mapped()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
var blogPost = new BlogPost
{
Category3 = EnumCategory.Database
};
var document = documentMapper.Map(blogPost);
var field = document.Fields.FirstOrDefault(x => x.Name.StartsWith("Category3"));
Assert.NotNull(field);
blogPost = documentMapper.Map<BlogPost>(document);
Assert.Equal(EnumCategory.Database, blogPost.Category3);
}
[Fact]
public void Test_Collection_Complex_Type_Fields()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
var blogPost = new BlogPost
{
PublishedDate = DateTime.Now,
PublishedDateOffset = DateTimeOffset.Now,
Tags = new List<Tag>
{
new Tag
{
Id = "1",
Name = "test"
},
new Tag
{
Id = "2",
Name = "test2"
},
new Tag
{
Id = "3",
Name = "test3"
}
}
};
var document = documentMapper.Map(blogPost);
var fields = document.Fields.Where(x => x.Name.StartsWith("Tags"));
Assert.Equal(6, fields.Count());
Assert.All(fields, field => field.Name.Equals("Tags"));
var mappedBlogPost = documentMapper.Map<BlogPost>(document);
for (var i = 0; i < blogPost.Tags.Count; i++)
{
Assert.Equal(mappedBlogPost.Tags[i].Id, blogPost.Tags[i].Id);
Assert.Equal(mappedBlogPost.Tags[i].Name, blogPost.Tags[i].Name);
}
}
[Fact]
public void Test_Collection_Nested_Complex_types()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
var node = _fixture.Create<Node>();
var document = documentMapper.Map(node);
var expectedNode = documentMapper.Map<Node>(document);
var obj1Str = JsonConvert.SerializeObject(node);
var obj2Str = JsonConvert.SerializeObject(expectedNode);
Assert.Equal(obj1Str, obj2Str);
}
[Fact]
public void Test_Not_Indexed_If_Too_Large_Text()
{
var documentMapper = _serviceProvider.GetRequiredService<IDocumentMapper>();
// public PropertyInfo? GetProperty(string name);
var propertyMapper = documentMapper?.GetFieldMapper(typeof(BlogPost).GetProperty("Body"));
Assert.Equal(typeof(TextFieldMapper), propertyMapper?.GetType());
var blogPost = new BlogPost { Body = new string('*', 32767) };
var document = documentMapper?.Map(blogPost);
var isIndexed = document?.GetField("Body").IndexableFieldType.IsIndexed;
Assert.False(isIndexed);
}
}
}
|
using EasyRoslynScript;
using FlexibleConfigEngine.Core.Graph;
using FlexibleConfigEngine.Core.Script.Fluent;
namespace FlexibleConfigEngine.Core.Script
{
public static class FluentScriptMethods
{
public static IGraphManager GraphManager { private get; set; }
public static GatherFluent Gather(this IScriptContext context, string name)
{
var gather = new Graph.Gather {Name = name};
GraphManager.AddGather(gather);
return new GatherFluent(gather);
}
public static ConfigFluent Config(this IScriptContext context, string name)
{
var config = new ConfigItem {Name = name};
GraphManager.AddConfig(config);
return new ConfigFluent(config);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using System.Threading.Tasks;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
namespace Dictionary.Services.Services
{
public class BotService
{
public static ITelegramBotClient GetBot()
{
string token = ConfigurationManager.ConnectionStrings["BotToken"].ConnectionString;
var bot = new TelegramBotClient(token);
return bot;
}
public static async Task Send(ITelegramBotClient bot, long chatId, string message)
{
try
{
if (message.Length >= 4096)
{
string[] messages = DivideLongMessage(message);
foreach (string messagePart in messages)
{
await bot.SendTextMessageAsync(
chatId,
messagePart,
ParseMode.Html,
true
);
}
}
else
{
await bot.SendTextMessageAsync(
chatId,
message,
ParseMode.Html,
true
);
}
}
catch (Exception exception)
{
Console.WriteLine($"Failed sending message with message: {exception.Message}");
await bot.SendTextMessageAsync(chatId, "Təəssüf ki, sözün izahı tapılmadı.", ParseMode.Html);
}
}
private static string[] DivideLongMessage(string message)
{
List<string> result = new List<string>();
int messageCount = message.Length / 4096;
string[] messageParts = message.Split('.');
StringBuilder messagePart = new StringBuilder();
for (int i = 0; i < messageCount; i++)
{
foreach (string sentence in messageParts)
{
if (messagePart.Length > 3000)
{
result.Add(messagePart + ".");
messagePart.Clear();
}
messagePart.Append(sentence);
messagePart.Append(".");
}
}
return result.ToArray();
}
}
}
|
using Autolib.Helpers;
using Autolib.Modeles;
using Autolib.Modeles.DAO;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace Autolib.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ClientController : ControllerBase
{
private IUserService _userService;
public ClientController(IUserService userService)
{
_userService = userService;
}
[HttpPost]
public IActionResult Authenticate(AuthenticateRequest model)
{
var response = _userService.Authenticate(model);
if (response == null)
return BadRequest(new { message = "Username or password is incorrect" });
return Ok(response);
}
//[HttpPost]
/*public async Task<IActionResult> Inscription([FromBody] Client c)
{
Client client = await createClient(c);
if (client == null)
{
return NotFound();
}
return Ok(client);
}*/
private Task<Client> createClient(Client client)
{
throw new NotImplementedException();
}
[Authorize]
[HttpGet]
public IActionResult GetAll()
{
var users = _userService.GetAll();
return Ok(users);
}
}
}
|
namespace Pat.Subscriber.UnitTests.Events
{
public class Eventv2 : Eventv1
{
}
} |
// Copyright (c) 2021-2021 Jean-Philippe Bruyère <jp_bruyere@hotmail.com>
//
// This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
using System;
using Crow;
using Crow.Text;
using System.Diagnostics;
using System.Collections;
namespace CrowEditBase
{
public abstract class SourceDocument : TextDocument {
public SourceDocument (string fullPath, string editorPath = "#ui.sourceEditor.itmp")
: base (fullPath, editorPath) {
}
protected Token[] tokens;
protected SyntaxNode RootNode;
protected Token currentToken;
protected SyntaxNode currentNode;
public Token[] Tokens => tokens;
public Token FindTokenIncludingPosition (int pos) {
if (pos == 0 || tokens == null || tokens.Length == 0)
return default;
int idx = Array.BinarySearch (tokens, 0, tokens.Length, new Token () {Start = pos});
return idx == 0 ? tokens[0] : idx < 0 ? tokens[~idx - 1] : tokens[idx - 1];
}
public SyntaxNode FindNodeIncludingPosition (int pos) {
if (RootNode == null)
return null;
if (!RootNode.Contains (pos))
return null;
return RootNode.FindNodeIncludingPosition (pos);
}
public T FindNodeIncludingPosition<T> (int pos) {
if (RootNode == null)
return default;
if (!RootNode.Contains (pos))
return default;
return RootNode.FindNodeIncludingPosition<T> (pos);
}
protected override void reloadFromFile () {
base.reloadFromFile ();
parse ();
}
protected override void apply(TextChange change)
{
base.apply(change);
parse ();
}
public virtual Crow.Color GetColorForToken (TokenType tokType) {
if (tokType.HasFlag (TokenType.Punctuation))
return Colors.DarkGrey;
if (tokType.HasFlag (TokenType.Trivia))
return Colors.DimGrey;
if (tokType == TokenType.Keyword)
return Colors.DarkSlateBlue;
return Colors.Red;
}
protected abstract Tokenizer CreateTokenizer ();
protected abstract SyntaxAnalyser CreateSyntaxAnalyser ();
public abstract IList GetSuggestions (int pos);
/// <summary>
/// complete current token with selected item from the suggestion overlay.
/// It may set a new position or a new selection.
/// </summary>
/// <param name="suggestion">selected object of suggestion overlay</param>
/// <param name="newSelection">new position or selection, null if normal position after text changes</param>
/// <returns>the TextChange to apply to the source</returns>
public abstract TextChange? GetCompletionForCurrentToken (object suggestion, out TextSpan? newSelection);
void parse () {
Tokenizer tokenizer = CreateTokenizer ();
tokens = tokenizer.Tokenize (Source);
SyntaxAnalyser syntaxAnalyser = CreateSyntaxAnalyser ();
Stopwatch sw = Stopwatch.StartNew ();
syntaxAnalyser.Process ();
sw.Stop();
RootNode = syntaxAnalyser.Root;
Console.WriteLine ($"Syntax Analysis done in {sw.ElapsedMilliseconds}(ms) {sw.ElapsedTicks}(ticks)");
foreach (SyntaxException ex in syntaxAnalyser.Exceptions)
Console.WriteLine ($"{ex}");
/*foreach (Token t in Tokens)
Console.WriteLine ($"{t,-40} {Source.AsSpan(t.Start, t.Length).ToString()}");
syntaxAnalyser.Root.Dump();*/
}
}
} |
/********************************************************************************
Copyright (c) jiniannet (http://www.jiniannet.com). All rights reserved.
Licensed under the MIT license. See licence.txt file in the project root for full license information.
********************************************************************************/
using System;
namespace JinianNet.JNTemplate.Nodes
{
/// <summary>
/// ForTag
/// </summary>
[Serializable]
public class ForTag : ComplexTag
{
private ITag initial;
private ITag condition;
private ITag dothing;
/// <summary>
/// Gets or sets the initial of the tag.
/// </summary>
public ITag Initial
{
get { return this.initial; }
set { this.initial = value; }
}
/// <summary>
/// Gets or sets the condition of the tag.
/// </summary>
public ITag Condition
{
get { return this.condition; }
set { this.condition = value; }
}
/// <summary>
/// do things.
/// </summary>
public ITag Do
{
get { return this.dothing; }
set { this.dothing = value; }
}
}
} |
// File generated from our OpenAPI spec
namespace Stripe
{
using System.Collections.Generic;
using Newtonsoft.Json;
public class PersonFutureRequirements : StripeEntity<PersonFutureRequirements>
{
/// <summary>
/// Fields that are due and can be satisfied by providing the corresponding alternative
/// fields instead.
/// </summary>
[JsonProperty("alternatives")]
public List<PersonFutureRequirementsAlternative> Alternatives { get; set; }
/// <summary>
/// Fields that need to be collected to keep the person's account enabled. If not collected
/// by the account's <c>future_requirements[current_deadline]</c>, these fields will
/// transition to the main <c>requirements</c> hash, and may immediately become
/// <c>past_due</c>, but the account may also be given a grace period depending on the
/// account's enablement state prior to transition.
/// </summary>
[JsonProperty("currently_due")]
public List<string> CurrentlyDue { get; set; }
/// <summary>
/// Fields that are <c>currently_due</c> and need to be collected again because validation
/// or verification failed.
/// </summary>
[JsonProperty("errors")]
public List<PersonFutureRequirementsError> Errors { get; set; }
/// <summary>
/// Fields that need to be collected assuming all volume thresholds are reached. As they
/// become required, they appear in <c>currently_due</c> as well, and the account's
/// <c>future_requirements[current_deadline]</c> becomes set.
/// </summary>
[JsonProperty("eventually_due")]
public List<string> EventuallyDue { get; set; }
/// <summary>
/// Fields that weren't collected by the account's <c>requirements.current_deadline</c>.
/// These fields need to be collected to enable the person's account. New fields will never
/// appear here; <c>future_requirements.past_due</c> will always be a subset of
/// <c>requirements.past_due</c>.
/// </summary>
[JsonProperty("past_due")]
public List<string> PastDue { get; set; }
/// <summary>
/// Fields that may become required depending on the results of verification or review. Will
/// be an empty array unless an asynchronous verification is pending. If verification fails,
/// these fields move to <c>eventually_due</c> or <c>currently_due</c>.
/// </summary>
[JsonProperty("pending_verification")]
public List<string> PendingVerification { get; set; }
}
}
|
using System;
using IbanLib.Countries;
using Moq;
using NUnit.Framework;
namespace IbanLib.Test.Common
{
public static class TestUtil
{
public static ICountry MockNotNullCountry = new Mock<ICountry>().Object;
public static void ExpectedException<TException>(Action action)
{
try
{
action.Invoke();
}
catch (Exception e)
{
Assert.AreEqual(typeof (TException), e.GetType());
}
}
}
} |
using System.Data.SqlClient;
using System.Data.SQLite;
using EtlLib.Pipeline;
using FluentAssertions;
using Xunit;
namespace EtlLib.UnitTests.EtlPipeline
{
public class DbConnectionFactoryTests
{
[Fact]
public void Can_register_typed_connections()
{
const string cs1 = "Data Source =:memory:; Version = 3; New = True;";
const string cs2 = "Data Source=:memory:;Version=3;New=False;";
const string cs3 = "Server=myServerAddress;Database=myDataBase;Trusted_Connection=True;";
var registrar = new DbConnectionFactory();
((IDbConnectionRegistrar) registrar)
.For<SQLiteConnection>(con => con
.Register("inmemory", cs1)
.Register("inmemory2", cs2))
.For<SqlConnection>(con => con
.Register("remotedb", cs3));
var connection1 = ((IDbConnectionFactory) registrar)
.CreateNamedConnection("inmemory");
connection1.Should().NotBeNull();
connection1.ConnectionString.Should().Be(cs1);
connection1.Should().BeOfType<SQLiteConnection>();
var connection2 = ((IDbConnectionFactory)registrar)
.CreateNamedConnection("inmemory2");
connection2.Should().NotBeNull();
connection2.ConnectionString.Should().Be(cs2);
connection2.Should().BeOfType<SQLiteConnection>();
var connection3 = ((IDbConnectionFactory)registrar)
.CreateNamedConnection("remotedb");
connection3.Should().NotBeNull();
connection3.ConnectionString.Should().Be(cs3);
connection3.Should().BeOfType<SqlConnection>();
}
[Fact]
public void Can_register_and_resolve_via_pipeline_context()
{
const string cs1 = "Data Source =:memory:; Version = 3; New = True;";
var context = new EtlPipelineContext();
context.DbConnections
.For<SQLiteConnection>(con => con.Register("inmemory", cs1));
var connection1 = context.CreateNamedDbConnection("inmemory");
connection1.Should().NotBeNull();
connection1.ConnectionString.Should().Be(cs1);
connection1.Should().BeOfType<SQLiteConnection>();
}
}
} |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System.Net;
using System.Net.Sockets;
namespace Microsoft.Azure.WebJobs.Script.Workers
{
public static class WorkerUtilities
{
public static int GetUnusedTcpPort()
{
using (Socket tcpSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
tcpSocket.Bind(new IPEndPoint(IPAddress.Loopback, 0));
int port = ((IPEndPoint)tcpSocket.LocalEndPoint).Port;
return port;
}
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using Telerik.Core;
namespace Telerik.Data.Core.Layouts
{
internal abstract class BaseLayout
{
private double defaultItemLength;
private double defaultItemOppositeLength;
public BaseLayout()
{
this.LayoutStrategies = new SortedSet<LayoutStrategyBase>(new LayoutStrategyComparer());
}
public event EventHandler<ExpandCollapseEventArgs> Collapsed;
public event EventHandler<ExpandCollapseEventArgs> Expanded;
public event EventHandler ItemsSourceChanged;
public SortedSet<LayoutStrategyBase> LayoutStrategies { get; private set; }
public abstract int GroupCount { get; }
public virtual int VisibleLineCount
{
get;
protected set;
}
public virtual int TotalSlotCount
{
get;
protected set;
}
public double DefaultItemLength
{
get
{
return this.defaultItemLength;
}
set
{
this.defaultItemLength = value;
this.RefreshRenderInfo(true);
}
}
public double DefaultItemOppositeLength
{
get
{
return this.defaultItemOppositeLength;
}
set
{
if (this.defaultItemOppositeLength != value)
{
this.defaultItemOppositeLength = value;
this.RefreshRenderInfo(true);
}
}
}
internal int AggregatesLevel
{
get;
private set;
}
internal TotalsPosition TotalsPosition
{
get;
private set;
}
internal bool ShowAggregateValuesInline
{
get;
private set;
}
internal IReadOnlyList<object> ItemsSource
{
get;
private set;
}
internal int GroupLevels
{
get;
private set;
}
protected abstract IRenderInfo RenderInfo
{
get;
}
public abstract IEnumerable<Group> GetGroupsByKey(object key);
public void SetSource(IEnumerable source)
{
this.SetSource(source, int.MaxValue, TotalsPosition.None, -1, 0, false, false);
}
public void SetSource(IEnumerable source, int groupLevels, TotalsPosition totalsPosition, int aggregatesLevel, int totalsCount, bool showAggregateValuesInline)
{
this.SetSource(source, groupLevels, totalsPosition, aggregatesLevel, totalsCount, showAggregateValuesInline, false);
}
// TODO: Too many arguments, pass a context instead
public void SetSource(IEnumerable source, int groupLevels, TotalsPosition totalsPosition, int aggregatesLevel, int totalsCount, bool showAggregateValuesInline, bool restoreCollapsed)
{
if ((aggregatesLevel <= -1 || aggregatesLevel >= groupLevels) && totalsCount > 1)
{
aggregatesLevel = Math.Max(0, groupLevels - 1);
}
else if (totalsCount <= 1)
{
aggregatesLevel = 0;
}
this.GroupLevels = groupLevels;
this.TotalsPosition = totalsPosition;
this.AggregatesLevel = aggregatesLevel;
this.ShowAggregateValuesInline = showAggregateValuesInline;
this.SetItemsSource(source);
this.SetItemsSourceOverride(this.ItemsSource, restoreCollapsed);
this.UpdateStrategiesCount();
this.RaiseItemsSourceChanged(EventArgs.Empty);
}
// Expand/Collapse API
public abstract bool IsCollapsed(object item);
public abstract void Expand(object item);
public abstract void Collapse(object item);
public abstract IEnumerable<IList<ItemInfo>> GetLines(int start, bool forward);
// TODO: Extract different layouts for the different controls so that this could move in something like pivot TabularLayout...
internal static GroupType GetItemType(object item)
{
IGroup group = item as IGroup;
if (group != null)
{
return group.Type;
}
return GroupType.BottomLevel;
}
internal abstract GroupInfo GetGroupInfo(object item);
internal abstract int GetVisibleSlot(int index);
internal abstract int GetCollapsedSlotsCount(int startSlot, int endSlot);
internal abstract int GetNextVisibleSlot(int slot);
internal abstract void RefreshRenderInfo(bool force);
internal abstract double SlotFromPhysicalOffset(double physicalOffset, bool includeCollapsed = false);
internal abstract void UpdateAverageLength(int startIndex, int endIndex);
internal virtual double PhysicalOffsetFromSlot(int slot)
{
return this.RenderInfo.OffsetFromIndex(slot);
}
internal virtual double PhysicalLengthForSlot(int slot)
{
return this.RenderInfo.ValueForIndex(slot);
}
internal virtual double GetTotalLength()
{
return this.TotalSlotCount > 0 ? this.PhysicalOffsetFromSlot(this.TotalSlotCount - 1) : 0;
}
internal abstract AddRemoveLayoutResult AddItem(object changedItem, object addRemoveItem, int addRemoveItemIndex);
internal abstract AddRemoveLayoutResult RemoveItem(object changedItem, object addRemoveItem, int addRemoveItemIndex);
internal void AddStrategy(IncrementalLoadingStrategy incrementalLoadingStrategy)
{
this.LayoutStrategies.Add(incrementalLoadingStrategy);
this.UpdateStrategiesCount();
}
internal virtual int CalculateFlatRowCount()
{
return this.ItemsSource.Count;
}
internal void RemoveWhere(Predicate<LayoutStrategyBase> condition)
{
this.LayoutStrategies.RemoveWhere(condition);
this.UpdateStrategiesCount();
}
internal abstract bool IsItemCollapsed(int slot);
internal abstract int IndexFromSlot(int slotToRequest);
internal abstract IRenderInfoState GetRenderLoadState();
internal abstract IList<ItemInfo> GetItemInfosAtSlot(int visibleLine, int slot);
internal abstract int CountAndPopulateTables(object item, int rootSlot, int level, int levels, GroupInfo parent, bool shouldIndexItem, List<GroupInfo> insert, ref int totalLines);
internal virtual void UpdateSlotLength(int slot, double length)
{
this.RenderInfo.Update(slot, length);
}
protected virtual void UpdateStrategiesCount()
{
if (this.ItemsSource == null || this.ItemsSource.Count == 0)
{
int totalCount = this.TotalSlotCount;
int calculatedCount = 0;
foreach (var strat in this.LayoutStrategies)
{
calculatedCount += strat.CalculateAppendedSlotsCount(this, 0, ref totalCount);
}
this.TotalSlotCount = this.VisibleLineCount = calculatedCount;
if (this.RenderInfo != null)
{
this.RenderInfo.InsertRange(0, IndexStorage.UnknownItemLength, calculatedCount);
}
}
}
protected void RaiseCollapsed(ExpandCollapseEventArgs e)
{
if (this.Collapsed != null)
{
this.Collapsed(this, e);
}
}
protected void RaiseExpanded(ExpandCollapseEventArgs e)
{
if (this.Expanded != null)
{
this.Expanded(this, e);
}
}
protected virtual void RaiseItemsSourceChanged(EventArgs e)
{
if (this.ItemsSourceChanged != null)
{
this.ItemsSourceChanged(this, e);
}
}
protected abstract void SetItemsSourceOverride(IReadOnlyList<object> source, bool restoreCollapsed);
private void SetItemsSource(IEnumerable source)
{
IReadOnlyList<object> readOnlyList = source as IReadOnlyList<object>;
if (readOnlyList != null)
{
this.ItemsSource = readOnlyList;
}
else
if (source == null)
{
this.ItemsSource = new ReadOnlyList<object, object>(new List<object>());
}
else
{
IList<object> sourceToList = new List<object>();
foreach (var item in source)
{
sourceToList.Add(item);
}
this.ItemsSource = new ReadOnlyList<object, object>(sourceToList);
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MLAgents;
using System.Linq;
public class StyleTransfer001Agent : Agent, IOnSensorCollision {
public List<float> SensorIsInTouch;
StyleTransfer001Master _master;
StyleTransfer001Animator _styleAnimator;
List<GameObject> _sensors;
public bool ShowMonitor = false;
// Use this for initialization
void Start () {
_master = GetComponent<StyleTransfer001Master>();
_styleAnimator = FindObjectOfType<StyleTransfer001Animator>();
}
// Update is called once per frame
void Update () {
if (agentParameters.onDemandDecision && _styleAnimator.AnimationStepsReady){
agentParameters.onDemandDecision = false;
_master.ResetPhase();
}
}
override public void InitializeAgent()
{
}
override public void CollectObservations()
{
// AddVectorObs(_master.PositionDistance);
// AddVectorObs(_master.RotationDistance);
// AddVectorObs(_master.TotalDistance);
AddVectorObs(_master.Phase);
foreach (var muscle in _master.Muscles)
{
if(muscle.Parent == null)
continue;
// animation training
// AddVectorObs(muscle.ObsDeltaFromAnimationPosition);
// AddVectorObs(muscle.ObsNormalizedDeltaFromAnimationRotation);
// self observation training
//AddVectorObs(muscle.ObsNormalizedDeltaFromTargetRotation);
AddVectorObs(muscle.ObsLocalPosition);
AddVectorObs(muscle.ObsRotation);
// AddVectorObs(muscle.ObsNormalizedRotation);
AddVectorObs(muscle.ObsRotationVelocity);
AddVectorObs(muscle.ObsVelocity);
}
if (SensorIsInTouch?.Count>0)
AddVectorObs(SensorIsInTouch);
}
public override void AgentAction(float[] vectorAction, string textAction)
{
int i = 0;
foreach (var muscle in _master.Muscles)
{
if(muscle.Parent == null)
continue;
muscle.TargetNormalizedRotationX = vectorAction[i++];
muscle.TargetNormalizedRotationY = vectorAction[i++];
muscle.TargetNormalizedRotationZ = vectorAction[i++];
}
var jointsAtLimitPenality = GetJointsAtLimitPenality() * 4;
float effort = GetEffort();
var effortPenality = 0.05f * (float)effort;
var poseReward = 1f - _master.RotationDistance;
var velocityReward = 1f - Mathf.Abs(_master.VelocityDistance);
var endEffectorReward = 1f - _master.EndEffectorDistance;
var centerMassReward = 0f; // TODO
float poseRewardScale = .65f + .1f;
// poseRewardScale *=2;
float velocityRewardScale = .1f;
float endEffectorRewardScale = .15f;
float centerMassRewardScale = .1f;
poseReward = Mathf.Clamp(poseReward, 0f, 1f);
velocityReward = Mathf.Clamp(velocityReward, 0f, 1f);
endEffectorReward = Mathf.Clamp(endEffectorReward, 0f, 1f);
centerMassReward = Mathf.Clamp(centerMassReward, 0f, 1f);
float distanceReward =
(poseReward * poseRewardScale) +
(velocityReward * velocityRewardScale) +
(endEffectorReward * endEffectorRewardScale) +
(centerMassReward * centerMassRewardScale);
float reward =
distanceReward
// - effortPenality +
- jointsAtLimitPenality;
if (ShowMonitor) {
var hist = new []{
reward,
distanceReward,
- jointsAtLimitPenality,
// - effortPenality,
(poseReward * poseRewardScale),
(velocityReward * velocityRewardScale),
(endEffectorReward * endEffectorRewardScale),
(centerMassReward * centerMassRewardScale),
}.ToList();
Monitor.Log("rewardHist", hist.ToArray());
}
if (!_master.IgnorRewardUntilObservation)
AddReward(reward);
if (!IsDone()){
//if (distanceReward < _master.ErrorCutoff && !_master.DebugShowWithOffset) {
if (distanceReward <= 0f && !_master.DebugShowWithOffset) {
AddReward(-1f);
Done();
// _master.StartAnimationIndex = _muscleAnimator.AnimationSteps.Count-1;
// if (_master.StartAnimationIndex < _muscleAnimator.AnimationSteps.Count-1)
// _master.StartAnimationIndex++;
}
if (_master.IsDone()){
// AddReward(1f*(float)this.GetStepCount());
Done();
//if (_master.StartAnimationIndex > 0 && distanceReward >= _master.ErrorCutoff)
if (_master.StartAnimationIndex > 0 && distanceReward > 0f)
_master.StartAnimationIndex--;
}
}
}
float GetEffort(string[] ignorJoints = null)
{
double effort = 0;
foreach (var muscle in _master.Muscles)
{
if(muscle.Parent == null)
continue;
var name = muscle.Name;
if (ignorJoints != null && ignorJoints.Contains(name))
continue;
var jointEffort = Mathf.Pow(Mathf.Abs(muscle.TargetNormalizedRotationX),2);
effort += jointEffort;
jointEffort = Mathf.Pow(Mathf.Abs(muscle.TargetNormalizedRotationY),2);
effort += jointEffort;
jointEffort = Mathf.Pow(Mathf.Abs(muscle.TargetNormalizedRotationZ),2);
effort += jointEffort;
}
return (float)effort;
}
float GetJointsAtLimitPenality(string[] ignorJoints = null)
{
int atLimitCount = 0;
foreach (var muscle in _master.Muscles)
{
if(muscle.Parent == null)
continue;
var name = muscle.Name;
if (ignorJoints != null && ignorJoints.Contains(name))
continue;
if (Mathf.Abs(muscle.TargetNormalizedRotationX) >= 1f)
atLimitCount++;
if (Mathf.Abs(muscle.TargetNormalizedRotationY) >= 1f)
atLimitCount++;
if (Mathf.Abs(muscle.TargetNormalizedRotationZ) >= 1f)
atLimitCount++;
}
float penality = atLimitCount * 0.2f;
return (float)penality;
}
// public override void AgentOnDone()
// {
// }
public override void AgentReset()
{
_sensors = _master.Muscles
.Where(x=>x.Group == MuscleGroup001.Foot)
.Select(x=>x.Rigidbody.gameObject)
.ToList();
foreach (var sensor in _sensors)
{
if (sensor.GetComponent<SensorBehavior>()== null)
sensor.AddComponent<SensorBehavior>();
}
SensorIsInTouch = Enumerable.Range(0,_sensors.Count).Select(x=>0f).ToList();
if (!agentParameters.onDemandDecision)
_master.ResetPhase();
}
public void OnSensorCollisionEnter(Collider sensorCollider, GameObject other) {
if (string.Compare(other.name, "Terrain", true) !=0)
return;
var sensor = _sensors
.FirstOrDefault(x=>x == sensorCollider.gameObject);
if (sensor != null) {
var idx = _sensors.IndexOf(sensor);
SensorIsInTouch[idx] = 1f;
}
}
public void OnSensorCollisionExit(Collider sensorCollider, GameObject other)
{
if (string.Compare(other.name, "Terrain", true) !=0)
return;
var sensor = _sensors
.FirstOrDefault(x=>x == sensorCollider.gameObject);
if (sensor != null) {
var idx = _sensors.IndexOf(sensor);
SensorIsInTouch[idx] = 0f;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.Reflection;
using System.Web;
namespace CHystrix.Utils.CFX
{
[SecurityCritical]
internal static class CommonAssemblies
{
internal static readonly Assembly MicrosoftWebInfrastructure = typeof(CommonAssemblies).Assembly;
internal static readonly Assembly mscorlib = typeof(object).Assembly;
internal static readonly Assembly System = typeof(Uri).Assembly;
internal static readonly Assembly SystemWeb = typeof(HttpContext).Assembly;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PaperMarioBattleSystem
{
/// <summary>
/// The Sequence for the Bobbery Bombs' Blink Faster action.
/// </summary>
public sealed class BlinkFasterSequence : Sequence
{
/// <summary>
/// The name of the animation to speed up.
/// </summary>
private string AnimName = string.Empty;
/// <summary>
/// The new speed value of the animation.
/// </summary>
private float SpeedValue = 1f;
/// <summary>
/// The Animation that is obtained from the animation name.
/// </summary>
private Animation Anim = null;
public BlinkFasterSequence(MoveAction moveAction, string animName, float speedVal) : base(moveAction)
{
AnimName = animName;
SpeedValue = speedVal;
Anim = User.AnimManager.GetAnimation<Animation>(AnimName);
}
protected override void SequenceStartBranch()
{
switch (SequenceStep)
{
case 0:
//Speed up the animation to the desired value, then end the sequence
Anim?.SetSpeed(SpeedValue);
EndSequence();
break;
default:
PrintInvalidSequence();
break;
}
}
protected override void SequenceEndBranch()
{
PrintInvalidSequence();
}
protected override void SequenceMainBranch()
{
PrintInvalidSequence();
}
protected override void SequenceSuccessBranch()
{
PrintInvalidSequence();
}
protected override void SequenceFailedBranch()
{
PrintInvalidSequence();
}
protected override void SequenceMissBranch()
{
PrintInvalidSequence();
}
}
}
|
using System;
using RapidCMS.Core.Models.Setup;
namespace RapidCMS.Core.Models.UI
{
public class CustomExpressionFieldUI : ExpressionFieldUI
{
internal CustomExpressionFieldUI(CustomExpressionFieldSetup field) : base(field)
{
CustomType = field.CustomType;
}
public Type CustomType { get; private set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.