text stringlengths 13 6.01M |
|---|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Globalization;
using NuGet.Versioning;
namespace NuGet.Protocol.Core.v3.DependencyInfo
{
internal class DependencyInfo
{
public string Id { get; set; }
public VersionRange Range { get; set; }
public RegistrationInfo RegistrationInfo { get; set; }
public override string ToString()
{
return String.Format(CultureInfo.InvariantCulture, "{0} {1}", Id, Range);
}
}
}
|
using ShCore.Extensions;
using System;
namespace ShCore.Attributes.Validators
{
public class ValidatorIsDateAttribute : ValidatorAttribute
{
/// <summary>
/// Xem có đúng định dạng ngày hay không
/// </summary>
/// <returns></returns>
public override bool Validate()
{
try
{
if (this.Value != null) this.Value.To<DateTime>();
return true;
}
catch
{
return false;
}
}
public override string GetMessage()
{
return "{0} không đúng định dạng ngày".Frmat(this.FieldName);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using isolutions.GrillAssesment.Client.Model;
using rebulanyum.GrillOptimizer.Business.Objects;
namespace rebulanyum.GrillOptimizer.Business
{
/// <summary>The Grill's configuration class.</summary>
public class GrillConfiguration
{
/// <summary>The pre-defined size of the Grill.</summary>
public Size GrillSize { get; private set; }
/// <summary>The smallest unit for the iteration of Grill's surface.</summary>
/// <remarks>Consider that the Grill consists of many equal squares. All squares will have it's side length with this value. And the business classes will iterate the squares when needed.</remarks>
public int BoxSize { get; private set; }
/// <summary>The constructor for the GrillConfiguration</summary>
/// <param name="grillSize">The size of the Grill.</param>
/// <param name="boxSize">The smallest unit for the iteration of Grill's surface.</param>
public GrillConfiguration(Size grillSize, int boxSize)
{
GrillSize = grillSize;
BoxSize = boxSize;
}
/// <summary>The default configuration instance: { GrillSize: { Width: 20, Height: 30 }, BoxSize: 1 }</summary>
public static readonly GrillConfiguration Default = new GrillConfiguration(new Size(20, 30), 1);
}
}
|
namespace Cogent.IoC.Generators.Models
{
internal class FactoryClassDeclaration
{
public FactoryClassDeclaration(string factoryImplimentationClassName, string factoryTypeName, ServiceConstructor[] serviceConstructorMethods)
{
FactoryImplimentationClassName = factoryImplimentationClassName;
FactoryTypeName = factoryTypeName;
ServiceConstructorMethods = serviceConstructorMethods;
}
public string FactoryImplimentationClassName { get; }
public string FactoryTypeName { get; }
public ServiceConstructor[] ServiceConstructorMethods { get; }
}
}
|
using CDSShareLib.Helper;
using IoTHubReceiver.Model;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Fabric;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IoTHubReceiver.Utilities
{
public class ConsoleLog
{
private bool _showDebugLog = true;
private StatelessServiceContext _context = null;
private LogHelper _appLogger = null;
string _iotHubReceiverLongName;
public ConsoleLog(StatelessServiceContext serviceContext, LogHelper appLogger, CdsInfo cdsInfo)
{
this._context = serviceContext;
this._appLogger = appLogger;
_iotHubReceiverLongName = "C" + cdsInfo.CompanyId + "_I" + cdsInfo.IoTHubId + "_P" + cdsInfo.PartitionNum + "_" + cdsInfo.Label;
if (_iotHubReceiverLongName.Length > 35)
_iotHubReceiverLongName = _iotHubReceiverLongName.Substring(0, 35) + "..";
}
public void Info(string format, params object[] args)
{
if (_showDebugLog)
writeConsoleLog(format, args);
}
public void Error(string format, params object[] args)
{
writeConsoleLog("[ERROR] " + format, args);
}
public void Warn(string format, params object[] args)
{
writeConsoleLog("[Warn] " + format, args);
}
public void CosmosDBDebug(string format, params object[] args)
{
Info("[CosmosDB] " + format, args);
}
public void MessageEventDebug(string format, params object[] args)
{
Info("[Event Debug] " + format, args);
}
public void MessageEventError(string format, params object[] args)
{
Error("[Event Error] " + format, args);
}
public void BlobLogInfo(string format, params object[] args)
{
if (_appLogger != null)
_appLogger.Info(build(format, args));
}
public void BlobLogDebug(string format, params object[] args)
{
if (_appLogger != null)
_appLogger.Debug(build(format, args));
}
public void BlobLogWarn(string format, params object[] args)
{
if (_appLogger != null)
_appLogger.Warn(build(format, args));
}
public void BlobLogError(string format, params object[] args)
{
if (_appLogger != null)
_appLogger.Error(build(format, args));
}
private StringBuilder build(string format, params object[] args)
{
StringBuilder logMessage = new StringBuilder();
logMessage.Append("(" + _iotHubReceiverLongName + ") ");
logMessage.AppendFormat(format, args);
return logMessage;
}
private void writeConsoleLog(string message, params object[] args)
{
if (_context != null)
ServiceEventSource.Current.ServiceMessage(_context, message, args);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using MyResources;
using TeaseAI_CE.Scripting.VType;
namespace TeaseAI_CE.Scripting
{
/// <summary> Operators that can be used with variables. </summary>
public enum Operators
{
// Math
Add,
Subtract,
Multiply,
Divide,
// Logic
Not,
Equal,
More,
Less,
And,
Or,
//
Assign,
}
/// <summary>
/// The base variable class, should be used for [bool, float, string]
/// by-reference thread-safe
/// </summary>
public class Variable : IKeyed
{
protected object _value = null;
public object Value { get { return getObj(); } set { setObj(value); } }
/// <summary> Does variable have a value? </summary>
public virtual bool IsSet { get { return getObj() != null; } }
/// <summary> If true scripts can only read. </summary>
public bool Readonly = false;
public Variable()
{ _value = null; }
public Variable(string value)
{ _value = value; }
public Variable(bool value)
{ _value = value; }
public Variable(float value)
{ _value = value; }
public Variable(IVType value)
{ _value = value; }
public Variable(VM.Function value)
{ _value = value; }
public Variable(Variable[] value)
{ _value = value; }
protected virtual object getObj()
{
return _value;
}
protected virtual void setObj(object value)
{
Interlocked.Exchange(ref _value, value);
}
public override string ToString()
{
if (IsSet)
return "Value is: " + Value.ToString();
return "Value is UnSet";
}
public virtual void WriteValueUser(Context sender, StringBuilder output)
{
if (!IsSet || sender.Root.Valid == BlockBase.Validation.Running)
return;
if (Value is Script && ((Script)Value).List)
((Script)Value).ExecuteAsList(sender, output);
else
output.Append(Value.ToString());
}
public virtual bool CanWriteValue()
{
if (!IsSet || Readonly)
return false;
return
Value is string ||
Value is float ||
Value is bool ||
Value is TimeSpan ||
Value is DateTime ||
Value is Query;
}
/// <summary>
/// Use to write a value as a string, when writing to files.
/// </summary>
/// <param name="sb"></param>
public virtual void WriteValue(StringBuilder sb)
{
// ToDo : Handle other types like scripts.
if (Value is string)
{
sb.Append('"');
var str = (string)Value;
str = str.Replace("\"", "\\\"").Replace("\n", "\\n");
sb.Append(str);
sb.Append('"');
}
else if (Value is float || Value is bool)
{
sb.Append(Value.ToString());
}
else if (Value is DateTime)
{
sb.Append("Date(\"");
sb.Append(((DateTime)Value).ToString("G"));
sb.Append("\")");
}
else if (Value is TimeSpan)
{
sb.Append("Time(\"");
sb.Append(((TimeSpan)Value).ToString("G"));
sb.Append("\")");
}
else if (Value is Query)
{
// ToDo 4: Query support for saving the variable key not just the values.
sb.Append(Value.ToString());
}
else
sb.Append("Unsupported_Variable_Write_Type");
}
#region IKeyed
public virtual Variable Get(Key key, Logger log = null)
{
if (key.AtEnd)
return this;
if (!IsSet)
{
Logger.LogF(log, Logger.Level.Error, StringsScripting.Formatted_IKeyedGet_Variable_Unset, key);
return null;
}
IKeyed value = Value as IKeyed;
if (value == null)
{
Logger.LogF(log, Logger.Level.Error, StringsScripting.Formatted_Variable_not_found, key);
return null;
}
return value.Get(key, log);
}
#endregion
public static Variable Evaluate(Context sender, Variable left, Operators op, Variable right)
{
var log = sender.Root.Log;
bool validating = sender.Root.Valid == BlockBase.Validation.Running;
object l = null, r;
// make sure variable is not null.
if (right == null)
{
log.Error(StringsScripting.Evaluate_null_variable);
return null;
}
r = right.Value;
if (op != Operators.Not) // "Not" doesn't use left variable.
{
if (left == null)
{
log.Error(StringsScripting.Evaluate_null_variable);
return null;
}
l = left.Value;
}
// allow equals to work on unset variables.
if (op == Operators.Equal)
{
if (l == null || r == null)
return new Variable(l == null && r == null);
}
// make sure variable is set.
if (!right.IsSet)
{
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_unset_variable, op.ToString())); // ToDo : Different error?
return null;
}
if (op != Operators.Not && op != Operators.Assign) // "Not" and "Assign" can use a unset left variable.
{
if (!left.IsSet)
{
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_unset_variable, op.ToString())); // ToDo : Different error?
return null;
}
}
// Do not allow assign to readonly variables.
if (op == Operators.Assign && left.Readonly)
{
log.Error(StringsScripting.Evaluate_Assign_Readonly);
return null;
}
// try to evaluate the viriable value directly.
if (l is IVType)
{
var results = ((IVType)l).Evaluate(sender, left, op, right);
if (results != null)
return results;
}
if (r is IVType)
{
var results = ((IVType)r).Evaluate(sender, left, op, right);
if (results != null)
return results;
}
switch (op)
{
// logic not
case Operators.Not:
object value = right.Value;
if (value is bool)
return new Variable(!(bool)value);
if (value is string)
return new Variable(Query.Not((string)value));
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), "", value.GetType().Name));
return null;
// assign
case Operators.Assign:
if (left.IsSet)
{
if (l.GetType() == r.GetType())
{
if (!validating) // Don't change variable if we are validating.
left.Value = r;
}
else
{
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Assign_type_mismatch, l.GetType().Name, r.GetType().Name));
return null;
}
}
else
{
if (validating)
left.Value = getDefault(right.Value.GetType());
else
left.Value = right.Value;
}
return left;
// Math
case Operators.Add:
if (l is float && r is float)
return new Variable((float)l + (float)r);
if (l is string && r is string)
return new Variable(string.Concat(l, r));
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
case Operators.Subtract:
if (l is float && r is float)
return new Variable((float)l - (float)r);
if (l is string && r is string)
return new Variable(((string)l).Replace((string)r, ""));
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
case Operators.Multiply:
if (l is float && r is float)
return new Variable((float)l * (float)r);
if (l is float && r is bool)
return new Variable((float)l * ((bool)r ? 1f : 0f));
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
case Operators.Divide:
if (l is float && r is float)
{
if (validating)
return new Variable(default(float));
float fl = (float)l;
float fr = (float)r;
if (fr == 0)
{
log.Warning(StringsScripting.Divide_by_zero);
fr = 1;
}
return new Variable(fl / fr);
}
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
// Logic
case Operators.Equal:
if (l is string && r is string) // for strings we want to ignore the case.
return new Variable((l as string).Equals((string)r, StringComparison.InvariantCultureIgnoreCase));
return new Variable(l.Equals(r));
case Operators.More:
if (l is float && r is float)
return new Variable((float)l > (float)r);
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
case Operators.Less:
if (l is float && r is float)
return new Variable((float)l < (float)r);
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
case Operators.And:
if (l is bool && r is bool)
return new Variable((bool)l && (bool)r);
if (l is string && r is string)
return new Variable(new Query((string)l, op, (string)r));
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
case Operators.Or:
if (l is bool && r is bool)
return new Variable((bool)l || (bool)r);
if (l is string && r is string)
return new Variable(new Query((string)l, op, (string)r));
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Operator_type_invalid, op.ToString(), l.GetType().Name, r.GetType().Name));
return null;
}
log.Error(string.Format(StringsScripting.Formatted_Evaluate_Invalid_operator, op.ToString()));
return null;
}
private static object getDefault(Type type)
{
try
{
if (type.IsValueType)
return Activator.CreateInstance(type);
}
catch { }
if (type == typeof(string))
return "";
return null;
}
}
/// <summary>
/// Generic variable, should be used for class typed values.
/// thread-safe, class T may not be thread-safe.
/// </summary>
public class Variable<T> : Variable where T : class, IKeyed
{
private new T _value = null;
public new T Value
{
get { return _value; }
set
{ Interlocked.Exchange(ref _value, value); }
}
public override bool IsSet { get { return _value != null; } }
public Variable(T value)
{
_value = value;
}
#region IKeyed
public override Variable Get(Key key, Logger log = null)
{
if (key.AtEnd)
return this;
if (!IsSet)
{
Logger.LogF(log, Logger.Level.Error, StringsScripting.Formatted_IKeyedGet_Variable_Unset, key);
return this;
}
return Value.Get(key, log);
}
#endregion
protected override object getObj()
{
return _value;
}
protected override void setObj(object value)
{
Interlocked.Exchange(ref _value, value as T);
}
// Does this help or cause problems?
public static implicit operator T(Variable<T> variable)
{
return variable.Value;
}
}
/// <summary>
/// Allows one to do nasty things, like using methods as variables.
/// </summary>
public class VariableFunc : Variable
{
public delegate object GetDelegate();
public delegate void SetDelegate(object value);
private GetDelegate get;
private SetDelegate set;
/// <param name="getter"></param>
/// <param name="setter"> if null, Variable is readonly. </param>
public VariableFunc(GetDelegate getter, SetDelegate setter)
{
get = getter;
set = setter;
Readonly = set == null;
}
public override bool IsSet { get { return set != null || get != null; } }
protected override object getObj()
{
if (get == null)
return _value = base.getObj();
else
return get();
}
protected override void setObj(object value)
{
_value = value;
if (set != null)
set(value);
}
}
}
|
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// VisualNovelToolkit /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
using UnityEngine;
using System.Collections;
using ViNoToolkit;
/// <summary>
/// Continue event script attached to save (load ) button.
/// </summary>
public class ContinueEvent : MonoBehaviour {
public string fileName;
public ViNoTextEventListener dateTextEvtLis;
public ViNoTextEventListener descriptionTextEvtLis;
[HideInInspector] public ViNoSaveInfo info;
private bool m_FileExists = false;
void UpdateText( string dateStr , string desc ){
// ViNoSaveInfo info = ScenarioCtrl.Instance.saveInfo;
// Update Text View.
if( dateTextEvtLis != null && descriptionTextEvtLis != null ){
dateTextEvtLis.OnUpdateText( dateStr );
descriptionTextEvtLis.OnUpdateText( desc );
}
}
void Start(){
if( info == null ){
info = ScriptableObject.CreateInstance<ViNoSaveInfo>();
}
m_FileExists = ExternalAccessor.IsSaveDataFileExists( fileName );
if( m_FileExists ){
// Load SaveInfo from Storage.
ViNo.LoadDataFromStorage( fileName , ref info) ;
UpdateText( info.m_Date , info.m_ScenarioDescription );
}
else{
UpdateText( "" , "NO DATA" );
}
}
void DoSave( bool t ){
if( t ){
ViNo.SaveData( fileName , info );
UpdateText( info.m_Date , info.m_ScenarioDescription );
}
}
void OnClickContinue(){
// Attach THIS info.
ScenarioCtrl.Instance.saveInfo = info;
ScenarioCtrl.Instance.fileName = fileName;
// Save.
if( SystemUIEvent.saveMode ){
#if false
// Native Dialog.
if( m_FileExists ){
Debug.Log( "SaveFileExists");
if( Application.isEditor ){
DoSave( true );
}
else{
DialogManager.Instance.ShowSelectDialog( "Overwrite File" , "Are you sure you want to overwrite file ?" , DoSave );
}
}
else{
#endif
DoSave( true );
// }
// Application.CaptureScreenShot( );
// CaptureScreenShot.StartCapture( fileName );
}
// Load.
else{
ViNoEventManager em = ViNoEventManager.Instance;
// Go to Level and Continue.
ScenarioCtrl.Instance.DoContinue();
// Deactive SaveLoad and Title Panels.
em.TriggerEvent( "ToggleActiveSaveLoadPanel" );
em.TriggerEvent( "OnClickLoadItem" );
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using SpiritMonsterMaster;
using TMPro;
public class Boss01_Controller : Monster
{
[SerializeField]
private Animator animator;
private Rigidbody2D rb;
private int Dir = 1;
private float HP, Distx, Disty, timer, timerJump;
private int hitted = 0;
public GameObject Player;
public Slider MonsterHP;
public GameStageController gamestage;
public GameObject HurtText, BoomHurtText;
public float force;
public int EnvironmentType;
public Boss01_Controller(int _id) : base(_id)
{
}
void Start()
{
//change to read file here
//warning = 5f;
//Attacknum = 10;
//speed = 1.5f;
//maxHP = 100;
//Monsterwind = 1;
rb = GetComponent<Rigidbody2D>();
Dir = -1;
HP = maxHP;
timer = 2.5f;
MonsterHP.gameObject.SetActive(false);
Random.seed = System.Guid.NewGuid().GetHashCode();
}
void Update()
{
if(gamestage.Gameover == 1 || gamestage.stop == 1) return;
if (gamestage.Gameover == 2)
{
animator.SetInteger("BossWin", 1);
return;
}
if (Mathf.Abs(rb.velocity.y) < 0.05f) timerJump += Time.deltaTime;
Distx = Mathf.Abs(Player.transform.position.x - gameObject.transform.position.x);
Disty = Mathf.Abs(Player.transform.position.y - gameObject.transform.position.y);
float moveHorizontal = (Player.transform.position.x - gameObject.transform.position.x) / Distx;
float moveVer = (Player.transform.position.y - gameObject.transform.position.y) / Disty;
animator.SetFloat("Speed", Mathf.Abs(moveHorizontal));
//move
float moveZ, moveY;
if ((Distx < warning || hitted == 1) && (Disty < warning))
{ //follow Player
moveZ = moveHorizontal * Random.Range(speed - 1, speed + 1); ;
moveY = moveVer * Random.Range(speed - 1, speed + 1);
moveZ *= Time.deltaTime;
moveY *= Time.deltaTime;
if(EnvironmentType == 0)transform.Translate(moveZ, 0, 0);
else if (EnvironmentType == 1) transform.Translate(moveZ, moveY, 0);//water
}
else
{
if (timer > 0)
{
moveZ = -1 * speed;
moveZ *= Time.deltaTime;
transform.Translate(moveZ, 0, 0);
}
else
{
moveZ = 1 * speed;
moveZ *= Time.deltaTime;
transform.Translate(moveZ, 0, 0);
}
if (timer < -2.5f) timer = 2.5f;
timer -= Time.deltaTime;
}
//jump
if ((rb.velocity.y < -0.5f && timerJump > 0.5f) || (Player.transform.position.y - gameObject.transform.position.y > warning / 2 && Distx < warning && timerJump > 0.5f))
{
rb.AddForce(Vector3.up * force);
animator.SetBool("isJumping", true);
timerJump = 0;
}
else animator.SetBool("isJumping", false);
//animation
Vector2 currentVelocity = gameObject.GetComponent<Rigidbody2D>().velocity;
if (moveZ * transform.localScale.x < 0)
{
if (Distx > 1f || Distx < -1f) transform.localScale = new Vector2(-transform.localScale.x, transform.localScale.y);
}
if (moveZ < 0 && currentVelocity.x <= 0)
{
// animator.SetInteger("DirectionX", -1);
Dir = -1;
//gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(currentVelocity.x - 0.1f, currentVelocity.y);// for ice
}
else if (moveZ > 0 && currentVelocity.x >= 0)
{
Dir = 1;
// animator.SetInteger("DirectionX", 1);
//gameObject.GetComponent<Rigidbody2D>().velocity = new Vector2(currentVelocity.x + 0.1f, currentVelocity.y);// for ice
}
else
{
// animator.SetInteger("DirectionX", 0);
}
//HP UI
if (hitted == 1 )
{
MonsterHP.gameObject.SetActive(true);
MonsterHP.value = HP / maxHP;
}
if (HP <= 0)
{
// animator.SetInteger("Dead", 1);
gamestage.Gameover = 1;//win
Destroy(gameObject);
}
}
//Hitted
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("PetAttack"))
{
//屬性相剋
float HurtNum = 0;
int i = Random.Range(0, (int)(other.GetComponent<Attack_far>().Attacknum * 0.5f));
if (Monsterfire == 1)
{
if (other.GetComponent<Attack_far>().fire == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 1;
else if (other.GetComponent<Attack_far>().water == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 1.2f;
else if (other.GetComponent<Attack_far>().wind == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 0.8f;
else HurtNum = other.GetComponent<Attack_far>().Attacknum + i;
HP -= HurtNum;
}
else if (Monsterwater == 1)
{
if (other.GetComponent<Attack_far>().fire == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 0.8f;
else if (other.GetComponent<Attack_far>().water == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 1;
else if (other.GetComponent<Attack_far>().wind == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 1.2f;
else HurtNum = other.GetComponent<Attack_far>().Attacknum + i;
HP -= HurtNum;
}
else if (Monsterwind == 1)
{
if (other.GetComponent<Attack_far>().fire == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 1.2f;
else if (other.GetComponent<Attack_far>().water == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 0.8f;
else if (other.GetComponent<Attack_far>().wind == 1) HurtNum = (other.GetComponent<Attack_far>().Attacknum + i) * 1f;
else HurtNum = other.GetComponent<Attack_far>().Attacknum + i;
HP -= HurtNum;
}
else
{
HurtNum = other.GetComponent<Attack_far>().Attacknum + i;
HP -= HurtNum;
}
GameObject text = GameObject.Instantiate(HurtText);
text.transform.parent = GameObject.Find("Canvas").transform;
text.transform.position = Camera.main.WorldToScreenPoint(transform.position) + new Vector3(50, 150, 0);
text.GetComponent<TextMeshProUGUI>().text = ((int)HurtNum).ToString();
//back
/*float Dist = Mathf.Abs(gameObject.transform.position.x - other.transform.position.x);
float moveHorizontal = (gameObject.transform.position.x - other.transform.position.x) / Dist;
rb.velocity = Vector2.zero;
rb.angularVelocity = 0;
rb.AddForce(new Vector3(1, 0, 0) * moveHorizontal * 250);*/
// animator.SetInteger("Hitted", 1);
hitted = 1;
other.GetComponent<Attack_far>().hitted = 1;
Destroy(other);
}
// else animator.SetInteger("Hitted", 0);
}
private void OnTriggerStay2D(Collider2D other)
{
//water
if (other.gameObject.GetComponent<Boom>().BoomHitted == 0 && other.gameObject.CompareTag("Boom") && other.gameObject.GetComponent<Boom>().Booming == true)
{
other.gameObject.GetComponent<Boom>().BoomHitted = 1;
int HurtNum;
if (other.gameObject.GetComponent<Boom>().Type == 1) HurtNum = 50;
else HurtNum = 20;
HP -= HurtNum;
GameObject text = GameObject.Instantiate(BoomHurtText);
text.transform.parent = GameObject.Find("Canvas").transform;
text.transform.position = Camera.main.WorldToScreenPoint(transform.position) + new Vector3(50, 30, 0);
text.GetComponent<TextMeshProUGUI>().text = (HurtNum).ToString();
}
}
}
|
using Microsoft.EntityFrameworkCore;
namespace API30v6.Models
{
public class PersonContext : DbContext
{
public PersonContext(DbContextOptions<PersonContext> options) : base(options)
{
}
public DbSet<Person> Peoples { get; set; }
}
} |
using System;
using System.Text;
using System.Collections.Generic;
using Newtonsoft.Json;
using NHibernate;
using NHibernate.Cfg;
using NHibernate.Criterion;
using NHibernate.Exceptions;
using LePapeoGenNHibernate.Exceptions;
using LePapeoGenNHibernate.EN.LePapeo;
using LePapeoGenNHibernate.CAD.LePapeo;
namespace LePapeoGenNHibernate.CEN.LePapeo
{
/*
* Definition of the class RegistradoCEN
*
*/
public partial class RegistradoCEN
{
private IRegistradoCAD _IRegistradoCAD;
public RegistradoCEN()
{
this._IRegistradoCAD = new RegistradoCAD ();
}
public RegistradoCEN(IRegistradoCAD _IRegistradoCAD)
{
this._IRegistradoCAD = _IRegistradoCAD;
}
public IRegistradoCAD get_IRegistradoCAD ()
{
return this._IRegistradoCAD;
}
public int New_ (string p_email, String p_pass, Nullable<DateTime> p_fecha_inscripcion, string p_nombre, string p_apellidos, Nullable<DateTime> p_fecha_nac)
{
RegistradoEN registradoEN = null;
int oid;
//Initialized RegistradoEN
registradoEN = new RegistradoEN ();
registradoEN.Email = p_email;
registradoEN.Pass = Utils.Util.GetEncondeMD5 (p_pass);
registradoEN.Fecha_inscripcion = p_fecha_inscripcion;
registradoEN.Nombre = p_nombre;
registradoEN.Apellidos = p_apellidos;
registradoEN.Fecha_nac = p_fecha_nac;
//Call to RegistradoCAD
oid = _IRegistradoCAD.New_ (registradoEN);
return oid;
}
public void Modify (int p_Registrado_OID, string p_email, String p_pass, Nullable<DateTime> p_fecha_inscripcion, string p_nombre, string p_apellidos, Nullable<DateTime> p_fecha_nac)
{
RegistradoEN registradoEN = null;
//Initialized RegistradoEN
registradoEN = new RegistradoEN ();
registradoEN.Id = p_Registrado_OID;
registradoEN.Email = p_email;
//registradoEN.Pass = Utils.Util.GetEncondeMD5 (p_pass);
registradoEN.Pass = p_pass;
registradoEN.Fecha_inscripcion = p_fecha_inscripcion;
registradoEN.Nombre = p_nombre;
registradoEN.Apellidos = p_apellidos;
registradoEN.Fecha_nac = p_fecha_nac;
//Call to RegistradoCAD
_IRegistradoCAD.Modify (registradoEN);
}
public void Destroy (int id
)
{
_IRegistradoCAD.Destroy (id);
}
public RegistradoEN ReadOID (int id
)
{
RegistradoEN registradoEN = null;
registradoEN = _IRegistradoCAD.ReadOID (id);
return registradoEN;
}
public System.Collections.Generic.IList<RegistradoEN> ReadAll (int first, int size)
{
System.Collections.Generic.IList<RegistradoEN> list = null;
list = _IRegistradoCAD.ReadAll (first, size);
return list;
}
public void AgregarDireccion (int p_Registrado_OID, int p_direccion_0_OID)
{
//Call to RegistradoCAD
_IRegistradoCAD.AgregarDireccion (p_Registrado_OID, p_direccion_0_OID);
}
public void DesvincularDireccion (int p_Registrado_OID, int p_direccion_0_OID)
{
//Call to RegistradoCAD
_IRegistradoCAD.DesvincularDireccion (p_Registrado_OID, p_direccion_0_OID);
}
public LePapeoGenNHibernate.EN.LePapeo.DireccionEN GetDireccion (int p_registrado)
{
return _IRegistradoCAD.GetDireccion (p_registrado);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SmallHouseManagerModel
{
public class BaseParkModel
{
/// <summary>
/// 停车场编号
/// </summary>
public int ParkID { get; set; }
/// <summary>
/// 停车场名
/// </summary>
public string Name { get; set; }
/// <summary>
/// 停车位数量
/// </summary>
public int Amount { get; set; }
/// <summary>
/// 说明
/// </summary>
public string Memo { get; set; }
}
}
|
using System.Collections.Generic;
using Service;
namespace MKService.QueryHandlers
{
/// <summary>
/// The query handler collection factory interface.
/// </summary>
public interface IQueryHandlerCollectionFactory
{
/// <summary>
/// Creates the specified query contract.
/// </summary>
/// <param name="queryContract">The query contract.</param>
/// <param name="commandContract">The command contract.</param>
/// <param name="rootHandler">The root handler.</param>
/// <returns>The IList.</returns>
IList<IQueryHandler> Create(
IQueryContract queryContract,
ICommandContract commandContract,
IQueryHandler rootHandler);
}
} |
using Microsoft.AspNetCore.Mvc.Razor;
using System;
using System.Collections.Generic;
using System.Linq;
namespace WebApplication
{
/// <summary>
///
/// </summary>
/// <example>
/// services.Configure<RazorViewEngineOptions>(options =>
/// {
/// options.ViewLocationExpanders.Add(typeof(ThemViewLocationExpander));
/// });
/// </example>
public class ThemeViewLocationExpander : IViewLocationExpander
{
public void PopulateValues(ViewLocationExpanderContext context)
{
var value = new Random().Next(0, 1);
var theme = value == 0 ? "Theme1" : "Theme2";
context.Values["theme"] = theme;
}
public virtual IEnumerable<string> ExpandViewLocations(ViewLocationExpanderContext context,
IEnumerable<string> viewLocations)
{
return viewLocations.Select(f => f.Replace("/Views/", "/Views/" + context.Values["theme"] + "/"));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using AgentStoryComponents.core;
namespace AgentStoryComponents.extAPI.commands
{
public class extraTackDieReveal : ICommand
{
private int reveal = -1;
private int storyID = -1;
private string gTX_ID = null;
public MacroEnvelope execute(Macro macro)
{
string targetDiv = MacroUtils.getParameterString("targetDiv", macro);
string gameCode = MacroUtils.getParameterString("gameCode", macro);
string tableName = gameCode + "GameData";
string tx_id64 = MacroUtils.getParameterString("tx_id64", macro);
storyID = MacroUtils.getParameterInt("storyID", macro);
reveal = MacroUtils.getParameterInt("reveal", macro);
string tx_id = TheUtils.ute.decode64(tx_id64);
this.gTX_ID = tx_id;
MacroEnvelope me = new MacroEnvelope();
string sql = string.Format("SELECT * from {0} WHERE tx_id ='{1}'",tableName,tx_id);
string html = this.getHTML(sql);
Macro p = new Macro("DisplayDiv", 2);
p.addParameter("html64", TheUtils.ute.encode64(html));
p.addParameter("targetDiv", targetDiv);
me.addMacro(p);
return me;
}
public string getHTML(string sql)
{
OleDbHelper dbHelper = TheUtils.ute.getDBcmd(config.conn);
dbHelper.cmd.CommandText = sql;
dbHelper.reader = dbHelper.cmd.ExecuteReader();
System.Text.StringBuilder sbHTML = new StringBuilder();
sbHTML.Append(@"<table id='tblController' class='clsGrid'
cellspacing='0' cellpadding='4' border='0'>");
int prize = TupleElements.getStoryTupleIntValue("prize", storyID, config.sqlConn);
int prize0 = TupleElements.getStoryTupleIntValue("prize0", storyID, config.sqlConn);
int prize50 = TupleElements.getStoryTupleIntValue("prize50", storyID, config.sqlConn);
int prize100 = TupleElements.getStoryTupleIntValue("prize100", storyID, config.sqlConn);
int costEntry = TupleElements.getStoryTupleIntValue("costEntry", storyID, config.sqlConn);
int furtherInvestment = TupleElements.getStoryTupleIntValue("furtherInvestment", storyID, config.sqlConn);
sbHTML.Append("<TR class='clsGridHeader'>");
sbHTML.Append("<td> </td>");
sbHTML.Append("<td>Pin Up</td>");
sbHTML.Append("<td>Pin Down</td>");
sbHTML.Append("</TR>");
//report rows
if (dbHelper.reader.HasRows)
{
dbHelper.reader.Read();
int k = 0;
int ProbUp = (int)dbHelper.reader["FinalProbability"];
int ProbDown = 100 - ProbUp;
double pup = (ProbUp / 100.00);
double pdown = (ProbDown / 100.00);
string sOutcome = null;
var max = System.Math.Max(ProbUp, ProbDown);
var min = System.Math.Min(ProbUp, ProbDown);
double dmax = max / 100.00;
double dmin = min / 100.00;
var EV = (prize * max) / 100;
//$100 * 1/3 + $20 * 1/2 + $0 * 1/6
double alternative = ((prize100 / 3) + (prize50 / 2)) - furtherInvestment; // * (max)) / 100; //=((100/3+50/2)-10)*E10
double valBeforeTackCall = (alternative * max) / 100;
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>Your Probability</td><td>{0}%</td><td>{1}%</td>", ProbUp, ProbDown);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>Chance to call correctly</td><td> </td><td>{0}%</td>", max);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td colspan='3'><pre><B>EV = ${0}</B> = ${1}*{2} + ${3}*{4} </pre></td>", EV, prize, dmax, prize0, dmin);
sbHTML.Append("</tr>");
//<h3>Probability of Pin Up</h3>
double valueOfPerfectInformation = (double)prize - (double)EV;
if (reveal > 1)
{
//VALUE OF INFORMATION
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td><div class='clsSpaceman'></div>Value with perfect information</td><td colspan='2'>${0}</td>", prize);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>Value without information</td><td colspan='2'><DIV style='border-bottom:single 1 black;'>${0}</DIV></td>", EV);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>Value of perfect information</td><td colspan='2'>${0}</td>", valueOfPerfectInformation);
sbHTML.Append("</tr>");
}
if (reveal > 2)
{
//ALTERNATIVE
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td><div class='clsSpaceman'></div>Value of new alternative, assuming you call tack correctly</td><td>${0}</td><td> </td>", alternative);
sbHTML.Append("</tr>");
// Value of new alternative, assuming you call tack correctly $43 = $100 * 1/3 + $20 * 1/2 + $0 * 1/6
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td colspan='3'><pre> ${0} = ( ${1}*1/3 + ${2}*1/2 + ${3}*1/6 ) - {4} </pre></td>", alternative,prize100,prize50,prize0,furtherInvestment);
sbHTML.Append("</tr>");
//Value before the tack call $x = final probability * $43 + (1- final probability) * $0
//var k = (prize100 / 3) + (prize50 / 2);
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td colspan='3'>Value before the tack call <br/> <pre><b>${0}</b> = ${1}*{2} + ${3}*{4}</pre></td>", valBeforeTackCall,alternative,dmax, prize0, dmin);
sbHTML.Append("</tr>");
}
int call = -1;
if (reveal > 3)
{
//your call
call = (int)dbHelper.reader["YourCall"];
var sCall = "";
if (call == 1) sCall = "Up";
if (call == 0) sCall = "Down";
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td valign='bottom'><div class='clsSpaceman'></div>Your Call </td><td valign='bottom'>{0}</td><td> </td>", sCall);
sbHTML.Append("</tr>");
}
if (reveal > 4)
{
//post dice simulation
int orient = (int)dbHelper.reader["TackOrient"];
var sOrient = "";
if (orient == 1) sOrient = "Up";
if (orient == 0) sOrient = "Down";
if (orient == call)
sOutcome = "correct";
else
sOutcome = "wrong";
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>The Tack is </td><td>{0}</td><td> </td>", sOrient);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>Your call was </td><td>{0}</td><td> </td>", sOutcome);
sbHTML.Append("</tr>");
}
if (reveal > 7)
{
//Commercial Outcome
int commercialResult = 0;
int net = 0;
int diver = 0;
var sDO = "";
int willInvestFurther = -1;
int dieOrient = -1;
if (dbHelper.reader["WillInvestFurther"] is DBNull)
{
}
else
{
willInvestFurther = (int)dbHelper.reader["WillInvestFurther"];
}
if (dbHelper.reader["DieOrient"] is DBNull)
{
}
else
{
dieOrient = (int)dbHelper.reader["DieOrient"];
}
if (sOutcome == "WRONG")
{
commercialResult = 0;
diver = 0;
}
else
{
if (willInvestFurther == -1)
{
// throw new Exception("willInvestFurtherStageNotReachedYet");
}
else
{
if (willInvestFurther == 1)
{
diver = furtherInvestment;
if (dieOrient == 1)
{
commercialResult = prize100;
sDO = "first";
}
if (dieOrient == 2)
{
commercialResult = prize50;
sDO = "second";
}
if (dieOrient == 3)
{
commercialResult = prize0;
sDO = "other";
}
if (dieOrient == -1)
{
commercialResult = 0;
sDO = " not thrown yet ";
}
}
else
{
commercialResult = prize;
diver = 0;
}
}
}
net = commercialResult - costEntry - diver;
var sWIF = "";
if (willInvestFurther == -1)
{
sWIF = "not an option";
}
if (willInvestFurther == 1)
{
sWIF = "YES";
}
if (willInvestFurther == 0)
{
sWIF = "NO";
}
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td valign='bottom'><div class='clsSpaceman'></div>Do you wish to invest further?</td><td valign='bottom'>{0}</td><td> </td>", sWIF);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>Market Position</td><td>{0}</td><td> </td>", sDO);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>You have won</td><td>{0}</td><td> </td>", commercialResult);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td>For a net winnings of</td><td>{0}</td><td> </td>", net);
sbHTML.Append("</tr>");
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.AppendFormat("<td valign='bottom'><div class='clsSpaceman'></div>The Commercial Result is</td><td valign='bottom' > <div class='clsGameTotal'>{0}</div></td><td> </td>", commercialResult);
sbHTML.Append("</tr>");
}
}
else
{
sbHTML.Append("<tr><td colspan='3'>no data</td>");
sbHTML.Append("</tr>");
}
sbHTML.Append("<tr class='clsDiceGameRow1'>");
sbHTML.Append("</tr>");
sbHTML.Append("</table>");
dbHelper.cleanup();
dbHelper = null;
return sbHTML.ToString();
}
}
}
|
using System;
namespace Lykke.Service.SmsSender.Client
{
public class SmsServiceException : Exception
{
public SmsServiceException(string message) : base (message)
{
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading.Tasks;
using System.Windows.Forms;
using SQLite;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Configuration;
using System.Xml;
namespace PersonalLibrary
{
public partial class BookGrid : Form
{
public BookGrid()
{
InitializeComponent();
FillBookGrid();
var create = CreateTable();
}
//Applies source to the book grid, sizes it properly, and refreshes the view
public void FillBookGrid() {
List<Book> books = GetAllBooks();
var bindingList = new BindingList<Book>(books);
var source = new BindingSource(bindingList, null);
bookGridView.DataSource = source;
bookGridView.Columns[0].Visible = false;
//Handy method to dynamically resize the grid based on the amount of entries
bookGridView.DataBindingComplete += (o, _) =>
{
var dataGridView = o as DataGridView;
if (dataGridView != null)
{
dataGridView.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
dataGridView.Columns[dataGridView.ColumnCount - 1].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
}
};
bookGridView.Refresh();
}
//Uses the ISBNDB API to find a book based on ISBN_10 or ISBN_13 value
public Book GetBookData(string isbn) {
Book book = new Book();
string accessKey = ConfigurationManager.AppSettings["isbnKey"];
string url = "http://isbndb.com/api/v2/json/" + accessKey + "/book/" + isbn;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
XmlTextReader reader = null;
try
{
String ISBNUriStr = "http://isbndb.com//api/books.xml?access_key=" +
accessKey + "&results=details&index1=isbn&value1=";
Uri uri = null;
if (isbn != null)
{
uri = new Uri(ISBNUriStr + isbn);
}
WebRequest http = HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)http.GetResponse();
Stream stream = response.GetResponseStream();
reader = new XmlTextReader(stream);
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element)
{
String name = reader.Name;
if (name == "BookData")
{
if (reader.MoveToFirstAttribute())
{
//book_id
}
while (reader.MoveToNextAttribute())
{
//isbn_10 and isbn_13
if (reader.Name == "isbn")
{
book.Isbn_10 = reader.Value;
}
else if (reader.Name == "isbn13")
{
book.Isbn_13 = reader.Value;
}
}
}
else if (name == "Title")
{
//Title
book.Title = reader.ReadString();
}
else if (name == "TitleLongText")
{
//Title Long
}
else if (name == "AuthorsText")
{
//Author
book.Author = reader.ReadString();
}
else if (name == "PublisherText")
{
//Publisher
book.Publisher = reader.ReadString();
}
else if (name == "Details")
{
if (reader.MoveToFirstAttribute())
{
//Change time
}
while (reader.MoveToNextAttribute())
{
//Price time
//Edition
//Language
//Description
//lcc
}
}
reader.Read();
}
}
return book;
}
catch (Exception)
{
Debug.WriteLine("Error");
return null;
}
}
//Create the database table, runs upon initialization
public async Task CreateTable() {
string databasePath = GetDataPath();
var conn = new SQLiteAsyncConnection(databasePath);
await conn.CreateTableAsync<Book>();
}
//Inserts a given book into the database then refreshes the grid
public async Task InsertBook(Book book) {
string databasePath = GetDataPath();
var conn = new SQLiteAsyncConnection(databasePath);
await conn.InsertAsync(book);
FillBookGrid();
}
//Get the path for the database file directory located in AppData
public string GetDataPath() {
string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string appFolder = Path.Combine(folder, "PersonalLibrary");
if (!Directory.Exists(appFolder))
Directory.CreateDirectory(appFolder);
return Path.Combine(appFolder, "Books.db");
}
//Return all books in the database for populating the main grid view
public List<Book> GetAllBooks() {
List<Book> books = new List<Book>();
var conn = new SQLiteConnection(GetDataPath());
var query = conn.Table<Book>();
foreach (var book in query)
books.Add(book);
return books;
}
//Click event for the search button, errors if no title was returned from GetBookData, otherwise inserts the new book
private void BookSearchBtn_Click(object sender, EventArgs e)
{
string isbn = isbnTextBox.Text;
Book book = GetBookData(isbn);
if (string.IsNullOrEmpty(book.Title))
{
MessageBox.Show("That ISBN returned no results. Ensure the ISBN contains only letters and numbers.", "", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else {
var task = InsertBook(book);
}
}
//Deletes the selected row from the grid and database table
private void BookDeleteBtn_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow row in bookGridView.Rows) {
if (row.Selected) {
string delID = row.Cells["id"].Value.ToString();
var conn = new SQLiteConnection(GetDataPath());
conn.Delete<Book>(delID);
FillBookGrid();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Peppy.Dependency
{
/// <summary>
/// All classes implement this interface are automatically registered to dependency injection as object.
/// </summary>
public interface IDependency
{
}
} |
using System;
using System.Buffers;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace NetFabric.Hyperlinq
{
public static partial class ArrayExtensions
{
[GeneratorMapping("TPredicate", "NetFabric.Hyperlinq.FunctionWrapper<TSource, bool>")]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static MemoryWhereEnumerable<TSource, FunctionWrapper<TSource, bool>> Where<TSource>(this ReadOnlyMemory<TSource> source, Func<TSource, bool> predicate)
=> source.Where(new FunctionWrapper<TSource, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static MemoryWhereEnumerable<TSource, TPredicate> Where<TSource, TPredicate>(this ReadOnlyMemory<TSource> source, TPredicate predicate = default)
where TPredicate : struct, IFunction<TSource, bool>
=> new(source, predicate);
[StructLayout(LayoutKind.Auto)]
public readonly partial struct MemoryWhereEnumerable<TSource, TPredicate>
: IValueEnumerable<TSource, MemoryWhereEnumerable<TSource, TPredicate>.Enumerator>
where TPredicate : struct, IFunction<TSource, bool>
{
internal readonly ReadOnlyMemory<TSource> source;
internal readonly TPredicate predicate;
internal MemoryWhereEnumerable(ReadOnlyMemory<TSource> source, TPredicate predicate)
=> (this.source, this.predicate) = (source, predicate);
public readonly WhereEnumerator<TSource, TPredicate> GetEnumerator()
=> new(source.Span, predicate);
readonly Enumerator IValueEnumerable<TSource, Enumerator>.GetEnumerator()
=> new(in this);
readonly IEnumerator<TSource> IEnumerable<TSource>.GetEnumerator()
// ReSharper disable once HeapView.BoxingAllocation
=> new Enumerator(in this);
readonly IEnumerator IEnumerable.GetEnumerator()
// ReSharper disable once HeapView.BoxingAllocation
=> new Enumerator(in this);
[StructLayout(LayoutKind.Auto)]
public struct Enumerator
: IEnumerator<TSource>
{
readonly ReadOnlyMemory<TSource> source;
TPredicate predicate;
int index;
internal Enumerator(in MemoryWhereEnumerable<TSource, TPredicate> enumerable)
{
source = enumerable.source;
predicate = enumerable.predicate;
index = -1;
}
public readonly TSource Current
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => source.Span[index];
}
readonly TSource IEnumerator<TSource>.Current
=> source.Span[index];
readonly object? IEnumerator.Current
// ReSharper disable once HeapView.PossibleBoxingAllocation
=> source.Span[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool MoveNext()
{
var span = source.Span;
while (++index < span.Length)
{
var item = span[index];
if (predicate.Invoke(item))
return true;
}
return false;
}
[ExcludeFromCodeCoverage]
public readonly void Reset()
=> throw new NotSupportedException();
public void Dispose() { }
}
#region Aggregation
public int Count()
=> source.Span.Count(predicate);
#endregion
#region Quantifier
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool All()
=> source.Span.All(predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool All(Func<TSource, bool> predicate)
=> All(new FunctionWrapper<TSource, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool All<TPredicate2>(TPredicate2 predicate)
where TPredicate2 : struct, IFunction<TSource, bool>
=> source.Span.All(new PredicatePredicateCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool All(Func<TSource, int, bool> predicate)
=> AllAt(new FunctionWrapper<TSource, int, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AllAt<TPredicate2>(TPredicate2 predicate)
where TPredicate2 : struct, IFunction<TSource, int, bool>
=> source.Span.AllAt(new PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Any()
=> source.Span.Any(predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Any(Func<TSource, bool> predicate)
=> Any(new FunctionWrapper<TSource, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Any<TPredicate2>(TPredicate2 predicate)
where TPredicate2 : struct, IFunction<TSource, bool>
=> source.Span.Any(new PredicatePredicateCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Any(Func<TSource, int, bool> predicate)
=> AnyAt(new FunctionWrapper<TSource, int, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AnyAt<TPredicate2>(TPredicate2 predicate)
where TPredicate2 : struct, IFunction<TSource, int, bool>
=> source.Span.AnyAt(new PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate));
#endregion
#region Filtering
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryWhereEnumerable<TSource, PredicatePredicateCombination<TPredicate, FunctionWrapper<TSource, bool>, TSource>> Where(Func<TSource, bool> predicate)
=> Where(new FunctionWrapper<TSource, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryWhereEnumerable<TSource, PredicatePredicateCombination<TPredicate, TPredicate2, TSource>> Where<TPredicate2>(TPredicate2 predicate = default)
where TPredicate2 : struct, IFunction<TSource, bool>
=> source.Where(new PredicatePredicateCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryWhereAtEnumerable<TSource, PredicatePredicateAtCombination<TPredicate, FunctionWrapper<TSource, int, bool>, TSource>> Where(Func<TSource, int, bool> predicate)
=> WhereAt<FunctionWrapper<TSource, int, bool>>(new FunctionWrapper<TSource, int, bool>(predicate));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryWhereAtEnumerable<TSource, PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>> WhereAt<TPredicate2>(TPredicate2 predicate = default)
where TPredicate2 : struct, IFunction<TSource, int, bool>
=> source.WhereAt(new PredicatePredicateAtCombination<TPredicate, TPredicate2, TSource>(this.predicate, predicate));
#endregion
#region Projection
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryWhereSelectEnumerable<TSource, TResult, TPredicate, FunctionWrapper<TSource, TResult>> Select<TResult>(Func<TSource, TResult> selector)
=> Select<TResult, FunctionWrapper<TSource, TResult>>(new FunctionWrapper<TSource, TResult>(selector));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public MemoryWhereSelectEnumerable<TSource, TResult, TPredicate, TSelector> Select<TResult, TSelector>(TSelector selector = default)
where TSelector : struct, IFunction<TSource, TResult>
=> source.WhereSelect<TSource, TResult, TPredicate, TSelector>(predicate, selector);
#endregion
#region Element
public Option<TSource> ElementAt(int index)
=> source.Span.ElementAt(index, predicate);
public Option<TSource> First()
=> source.Span.First(predicate);
public Option<TSource> Single()
=> source.Span.Single(predicate);
#endregion
#region Conversion
public TSource[] ToArray()
=> source.Span.ToArray(predicate);
public IMemoryOwner<TSource> ToArray(MemoryPool<TSource> memoryPool)
=> source.Span.ToArray(predicate, memoryPool);
public List<TSource> ToList()
=> source.Span.ToList(predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Dictionary<TKey, TSource> ToDictionary<TKey>(Func<TSource, TKey> keySelector, IEqualityComparer<TKey>? comparer = default)
where TKey : notnull
=> ToDictionary<TKey, FunctionWrapper<TSource, TKey>>(new FunctionWrapper<TSource, TKey>(keySelector), comparer);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Dictionary<TKey, TSource> ToDictionary<TKey, TKeySelector>(TKeySelector keySelector, IEqualityComparer<TKey>? comparer = default)
where TKey : notnull
where TKeySelector : struct, IFunction<TSource, TKey>
=> source.Span.ToDictionary(keySelector, comparer, predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Dictionary<TKey, TElement> ToDictionary<TKey, TElement>(Func<TSource, TKey> keySelector, Func<TSource, TElement> elementSelector, IEqualityComparer<TKey>? comparer = default)
where TKey : notnull
=> ToDictionary<TKey, TElement, FunctionWrapper<TSource, TKey>, FunctionWrapper<TSource, TElement>>(new FunctionWrapper<TSource, TKey>(keySelector), new FunctionWrapper<TSource, TElement>(elementSelector), comparer);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Dictionary<TKey, TElement> ToDictionary<TKey, TElement, TKeySelector, TElementSelector>(TKeySelector keySelector, TElementSelector elementSelector, IEqualityComparer<TKey>? comparer = default)
where TKey : notnull
where TKeySelector : struct, IFunction<TSource, TKey>
where TElementSelector : struct, IFunction<TSource, TElement>
=> source.Span.ToDictionary<TSource, TKey, TElement, TKeySelector, TElementSelector, TPredicate>(keySelector, elementSelector, comparer, predicate);
#endregion
public bool SequenceEqual(IEnumerable<TSource> other, IEqualityComparer<TSource>? comparer = null)
{
comparer ??= EqualityComparer<TSource>.Default;
var enumerator = GetEnumerator();
using var otherEnumerator = other.GetEnumerator();
while (true)
{
var thisEnded = !enumerator.MoveNext();
var otherEnded = !otherEnumerator.MoveNext();
if (thisEnded != otherEnded)
return false;
if (thisEnded)
return true;
if (!comparer.Equals(enumerator.Current, otherEnumerator.Current))
return false;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sum<TPredicate>(this MemoryWhereEnumerable<int, TPredicate> source)
where TPredicate : struct, IFunction<int, bool>
=> source.source.Span.Sum<int, int, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sum<TPredicate>(this MemoryWhereEnumerable<int?, TPredicate> source)
where TPredicate : struct, IFunction<int?, bool>
=> source.source.Span.Sum<int?, int, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Sum<TPredicate>(this MemoryWhereEnumerable<long, TPredicate> source)
where TPredicate : struct, IFunction<long, bool>
=> source.source.Span.Sum<long, long, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static long Sum<TPredicate>(this MemoryWhereEnumerable<long?, TPredicate> source)
where TPredicate : struct, IFunction<long?, bool>
=> source.source.Span.Sum<long?, long, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sum<TPredicate>(this MemoryWhereEnumerable<float, TPredicate> source)
where TPredicate : struct, IFunction<float, bool>
=> source.source.Span.Sum<float, float, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Sum<TPredicate>(this MemoryWhereEnumerable<float?, TPredicate> source)
where TPredicate : struct, IFunction<float?, bool>
=> source.source.Span.Sum<float?, float, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Sum<TPredicate>(this MemoryWhereEnumerable<double, TPredicate> source)
where TPredicate : struct, IFunction<double, bool>
=> source.source.Span.Sum<double, double, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static double Sum<TPredicate>(this MemoryWhereEnumerable<double?, TPredicate> source)
where TPredicate : struct, IFunction<double?, bool>
=> source.source.Span.Sum<double?, double, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Sum<TPredicate>(this MemoryWhereEnumerable<decimal, TPredicate> source)
where TPredicate : struct, IFunction<decimal, bool>
=> source.source.Span.Sum<decimal, decimal, TPredicate>(source.predicate);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static decimal Sum<TPredicate>(this MemoryWhereEnumerable<decimal?, TPredicate> source)
where TPredicate : struct, IFunction<decimal?, bool>
=> source.source.Span.Sum<decimal?, decimal, TPredicate>(source.predicate);
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
#if BIT64
using nuint = System.UInt64;
#else
using nuint = System.UInt32;
#endif
namespace System.IO.Compression
{
public struct BrotliPrimitives
{
const int defQuality = 11;
const int defLgWin = 24;
public static bool Compress(ReadOnlySpan<byte> source, Span<byte> destination, out nuint bytesConsumed, out nuint bytesWritten)
{
return Compress(source, destination, out bytesConsumed, out bytesWritten, defQuality, defLgWin);
}
public static bool Compress(ReadOnlySpan<byte> source, Span<byte> destination, out nuint bytesConsumed, out nuint bytesWritten, int quality, int lgwin)
{
unsafe
{
bytesConsumed = (nuint)source.Length;
bytesWritten = (nuint)0;
IntPtr bufIn, bufOut;
fixed (byte* inBytes = &source.DangerousGetPinnableReference())
fixed (byte* outBytes = &destination.DangerousGetPinnableReference())
{
bufIn = new IntPtr(inBytes);
bufOut = new IntPtr(outBytes);
return BrotliNative.BrotliEncoderCompress(quality, lgwin, BrotliNative.BrotliEncoderMode.Generic, bytesConsumed, bufIn, ref bytesWritten, bufOut);
}
}
}
public static BrotliNative.BrotliDecoderResult Decompress(ReadOnlySpan<byte> source, Span<byte> destination, out nuint bytesConsumed, out nuint bytesWritten)
{
unsafe
{
bytesConsumed = (nuint)source.Length;
bytesWritten = (nuint)0;
IntPtr bufIn, bufOut;
fixed (byte* inBytes = &source.DangerousGetPinnableReference())
fixed (byte* outBytes = &destination.DangerousGetPinnableReference())
{
bufIn = new IntPtr(inBytes);
bufOut = new IntPtr(outBytes);
return BrotliNative.BrotliDecoderDecompress(ref bytesConsumed, bufIn, ref bytesWritten, bufOut);
}
}
}
}
}
|
using System;
using Android.Support.V7.Widget;
using Android.Widget;
using Android.Views;
namespace FAB.Demo.Adapter
{
public class LanguageAdapter : RecyclerView.Adapter
{
private Java.Util.Locale[] locales;
public LanguageAdapter(Java.Util.Locale[] locales)
{
this.locales = locales;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(Android.Views.ViewGroup parent, int viewType)
{
TextView tv = (TextView)LayoutInflater.From(parent.Context).
Inflate(Android.Resource.Layout.SimpleListItem1, parent, false);
return new ViewHolder(tv);
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
((ViewHolder)holder).textView.Text = this.locales[position].DisplayName;
}
public override int ItemCount
{
get
{
return this.locales.Length;
}
}
private class ViewHolder : RecyclerView.ViewHolder
{
public TextView textView;
public ViewHolder(TextView v) : base(v)
{
this.textView = v;
}
}
}
}
|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PleaseThem
{
public abstract class Component : ICloneable, ISaveable
{
public int Id { get; set; }
public bool IsRemoved { get; set; }
public abstract void Draw(GameTime gameTime, SpriteBatch spriteBatch);
public abstract void Update(GameTime gameTime);
public object Clone()
{
return this.MemberwiseClone();
}
public abstract string GetSaveData();
}
}
|
using System.Threading.Tasks;
using lauthai_api.Models;
namespace lauthai_api.DataAccessLayer.Repository.Interfaces
{
public interface IUserRepository: IGenericRepository<User>
{
Task<User> GetUserById(int id);
}
} |
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Kernels.Sparse
{
using System;
using AForge;
using Accord.Math.Distances;
/// <summary>
/// Sparse Gaussian Kernel.
/// </summary>
///
/// <remarks>
/// <para>
/// The Gaussian kernel requires tuning for the proper value of σ. Different approaches
/// to this problem includes the use of brute force (i.e. using a grid-search algorithm)
/// or a gradient ascent optimization.</para>
///
/// <para>
/// For an example on how to create a sparse kernel, please see the <see cref="SparseLinear"/> page.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description>
/// P. F. Evangelista, M. J. Embrechts, and B. K. Szymanski. Some Properties of the
/// Gaussian Kernel for One Class Learning. Available on: http://www.cs.rpi.edu/~szymansk/papers/icann07.pdf </description></item>
/// </list></para>
/// </remarks>
///
[Serializable]
public sealed class SparseGaussian : KernelBase, IKernel, IDistance, IReverseDistance
{
private double sigma;
private double gamma;
/// <summary>
/// Constructs a new Sparse Gaussian Kernel
/// </summary>
///
public SparseGaussian()
: this(1)
{
}
/// <summary>
/// Constructs a new Sparse Gaussian Kernel
/// </summary>
///
/// <param name="sigma">The standard deviation for the Gaussian distribution. Default is 1.</param>
///
public SparseGaussian(double sigma)
{
this.Sigma = sigma;
}
/// <summary>
/// Gets or sets the sigma value for the kernel. When setting
/// sigma, gamma gets updated accordingly (gamma = 0.5*/sigma^2).
/// </summary>
///
public double Sigma
{
get { return sigma; }
set
{
sigma = value;
gamma = 1.0 / (2.0 * sigma * sigma);
}
}
/// <summary>
/// Gets or sets the gamma value for the kernel. When setting
/// gamma, sigma gets updated accordingly (gamma = 0.5*/sigma^2).
/// </summary>
///
public double Gamma
{
get { return gamma; }
set
{
gamma = value;
sigma = Math.Sqrt(1.0 / (gamma * 2.0));
}
}
/// <summary>
/// Gaussian Kernel function.
/// </summary>
///
/// <param name="x">Vector <c>x</c> in input space.</param>
/// <param name="y">Vector <c>y</c> in input space.</param>
/// <returns>Dot product in feature (kernel) space.</returns>
///
public override double Function(double[] x, double[] y)
{
// Optimization in case x and y are
// exactly the same object reference.
if (x == y)
return 1.0;
double norm = SparseLinear.SquaredEuclidean(x, y);
return Math.Exp(-gamma * norm);
}
/// <summary>
/// Computes the distance in input space
/// between two points given in feature space.
/// </summary>
///
/// <param name="x">Vector <c>x</c> in feature (kernel) space.</param>
/// <param name="y">Vector <c>y</c> in feature (kernel) space.</param>
///
/// <returns>
/// Distance between <c>x</c> and <c>y</c> in input space.
/// </returns>
///
public override double Distance(double[] x, double[] y)
{
if (x == y)
return 0.0;
double norm = SparseLinear.SquaredEuclidean(x, y);
return 2 - 2 * Math.Exp(-gamma * norm);
}
/// <summary>
/// Computes the squared distance in input space
/// between two points given in feature space.
/// </summary>
///
/// <param name="x">Vector <c>x</c> in feature (kernel) space.</param>
/// <param name="y">Vector <c>y</c> in feature (kernel) space.</param>
///
/// <returns>
/// Squared distance between <c>x</c> and <c>y</c> in input space.
/// </returns>
///
public double ReverseDistance(double[] x, double[] y)
{
if (x == y)
return 0.0;
double norm = SparseLinear.SquaredEuclidean(x, y);
return -(1.0 / gamma) * Math.Log(1.0 - 0.5 * norm);
}
/// <summary>
/// Estimate appropriate values for sigma given a data set.
/// </summary>
///
/// <remarks>
/// This method uses a simple heuristic to obtain appropriate values
/// for sigma in a radial basis function kernel. The heuristic is shown
/// by Caputo, Sim, Furesjo and Smola, "Appearance-based object
/// recognition using SVMs: which kernel should I use?", 2002.
/// </remarks>
///
/// <param name="inputs">The data set.</param>
/// <param name="samples">The number of random samples to analyze.</param>
/// <param name="range">The range of suitable values for sigma.</param>
/// <returns>A Gaussian kernel initialized with an appropriate sigma value.</returns>
///
public static SparseGaussian Estimate(double[][] inputs, int samples, out DoubleRange range)
{
if (samples > inputs.Length)
throw new ArgumentOutOfRangeException("samples");
double[] distances = Gaussian.Distances(inputs, samples);
double q1 = Math.Sqrt(distances[(int)Math.Ceiling(0.15 * distances.Length)] / 2.0);
double q9 = Math.Sqrt(distances[(int)Math.Ceiling(0.85 * distances.Length)] / 2.0);
double qm = Math.Sqrt(Measures.Median(distances, alreadySorted: true) / 2.0);
range = new DoubleRange(q1, q9);
return new SparseGaussian(sigma: qm);
}
}
}
|
using System;
using HashTables.Classes;
namespace HashTables
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Hashtables");
Console.WriteLine("");
displayHashes();
Console.ReadLine();
}
public static void displayHashes()
{
Hashtables hashTables = new Hashtables();
hashTables.Add("abc", "Josie");
hashTables.Add("Dog", "Woof");
hashTables.Add("333", "ponies");
hashTables.Add("moons", "44");
hashTables.Add("cba", "Doctor"); //Collision abc same as cba
Console.WriteLine($"Should return as 'True' for contains: {hashTables.Contains("moons")}");
Console.WriteLine($"Should return as 'False' for contains: {hashTables.Contains("planet")}");
Console.WriteLine($"Should return the value 'Woof' from key: {hashTables.GetValue("Dog")}");
Console.WriteLine($"Should return the value 'Doctor' from collision: {hashTables.GetValue("cba")}");
}
}
}
|
using FlickrNet;
using ModernCSApp.Services;
using ModernCSApp.Views;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
namespace ModernCSApp.Views.Controls.Flickr
{
public sealed partial class PictureDetails : BaseUserControl
{
public event PointerBasedEventHandler ChangeViewState;
public event EventHandler PictureChanged;
private bool _isShowingComments = false;
private bool _isShowingViews = false;
private bool _isShowingNotes = false;
public PictureDetails()
{
this.InitializeComponent();
}
public void LoadPicture(FlickrNet.PhotoInfo photoInfo)
{
this.DataContext = photoInfo;
_isShowingComments = false;
_isShowingNotes = false;
_isShowingViews = false;
if (photoInfo.Title == string.Empty || photoInfo.Title.Length == 0) grdTitle.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
else grdTitle.Visibility = Visibility.Visible;
String resultDescription = Regex.Replace(photoInfo.Description, @"<[^>]*>", String.Empty);
tbDescription.Text = resultDescription;
string resultDisplayName = "by ";
if (photoInfo.OwnerRealName != string.Empty) resultDisplayName += photoInfo.OwnerRealName;
if (photoInfo.OwnerUserName != string.Empty) resultDisplayName += " (" + photoInfo.OwnerUserName + ")";
tbOwnerDisplayName.Text = resultDisplayName;
tbLicense.Text = "License : " + photoInfo.License;
butViews.Content = "Views : " + photoInfo.ViewCount;
butComments.Content = "Comments : " + photoInfo.CommentsCount;
if(photoInfo.Notes!=null) butNotes.Content = "Notes : " + photoInfo.Notes.Count ;
if (ChangeViewState != null) ChangeViewState("Normal", null);
//try to load photostream
}
public void LoadPhotoStream(PhotoCollection photos)
{
if (this.DataContext is PhotoInfo)
{
PhotoInfo dc = (PhotoInfo)this.DataContext;
picsPhotoStream.LoadPictures(photos, dc.OwnerRealName + " photostream");
}
}
public void LoadComments(PhotoCommentCollection comments)
{
var pc = new PictureComments();
pc.LoadComments(comments, "Comments");
grdSubWindow.Children.Add(pc);
ShowSubWindow(0, 40, 0);
}
public async Task UnloadControl()
{
base.UnloadControl();
if (grdSubWindow.Children.Count > 1) grdSubWindow.Children.RemoveAt(1);
ClearAll();
}
private void picsPhotoStream_ChangeViewState(string action, Windows.Foundation.Point? point)
{
switch (action)
{
case "Minimized":
picsPhotoStream.Visibility = Visibility.Collapsed;
break;
case "Normal":
picsPhotoStream.Visibility = Visibility.Visible;
break;
case "Maximized": break;
case "StartExpandUserStreamTitle":
if (ChangeViewState != null) ChangeViewState("StartExpandUserStreamTitle", point);
break;
}
}
public void ClearAll()
{
picsPhotoStream.ClearAll();
MinimizeUserPictureStream();
HideSubWindow();
}
private void picsPhotoStream_PictureChanged(object sender, EventArgs e)
{
if (PictureChanged != null) PictureChanged(sender, e);
}
public void MaximizeUserPictureStream()
{
svDescription.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
picsPhotoStream.Height = 410;
}
public void MinimizeUserPictureStream()
{
svDescription.Visibility = Windows.UI.Xaml.Visibility.Visible;
picsPhotoStream.Height = 140;
}
private void butComments_Tapped(object sender, TappedRoutedEventArgs e)
{
var p = e.GetPosition(null);
Bang(p);
if (ChangeViewState != null) ChangeViewState("ShowComments", null);
_isShowingComments = !_isShowingComments;
if (_isShowingComments) { if (ChangeViewState != null) ChangeViewState("RequestShowComments", null); }
else
{
sbHideSubWindow.Begin();
grdSubWindow.Children.RemoveAt(1);
}
}
private void butViews_Tapped(object sender, TappedRoutedEventArgs e)
{
var p = e.GetPosition(null);
Bang(p);
if (ChangeViewState != null) ChangeViewState("ShowViews", null);
//_isShowingViews = !_isShowingViews;
//if(_isShowingViews)ShowSubWindow(-0.5, 180, 10);
//else sbHideSubWindow.Begin();
}
private void butNotes_Tapped(object sender, TappedRoutedEventArgs e)
{
var p = e.GetPosition(null);
Bang(p);
if (ChangeViewState != null) ChangeViewState("ShowNotes", null);
//_isShowingNotes = !_isShowingNotes;
//if (_isShowingNotes) ShowSubWindow(2.1, 310, 0);
//else sbHideSubWindow.Begin();
}
private void HideSubWindow()
{
_isShowingComments = false;
_isShowingNotes = false;
_isShowingViews = false;
if(grdSubWindow.Children.Count>1) grdSubWindow.Children.RemoveAt(1);
sbHideSubWindow.Begin();
}
private void ShowSubWindow(double angle, double leftPoint, double topMargin)
{
((CompositeTransform)grdSubWindow.RenderTransform).Rotation = angle;
pthSubWindowPoint.Margin = new Thickness(leftPoint, 0, 0, -20);
grdSubWindow.Margin = new Thickness(0, topMargin, 0, 80);
sbShowSubWindow.Begin();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerMove : MonoBehaviour
{
Rigidbody rb;
AudioSource source;
public AudioClip[] clip;
public float speed = 10;
public float forwardSpeed = 15;
bool startGame = false;
bool left = false;
bool right = false;
void Start()
{
rb = GetComponent<Rigidbody>();
source = GetComponent<AudioSource>();
}
public void PlayGameOver()
{
source.PlayOneShot(clip[0]);
}
public void PlayWin()
{
source.PlayOneShot(clip[1]);
}
void Update()
{
if (Input.anyKey)
startGame = true;
if (startGame == true)
rb.velocity = new Vector3(0, rb.velocity.y, forwardSpeed);
if (Input.GetKey(KeyCode.A))
left = true;
else if (Input.GetKey(KeyCode.D))
right = true;
if (Input.GetKeyUp(KeyCode.A))
left = false;
if (Input.GetKeyUp(KeyCode.D))
right = false;
if (transform.position.y < -5)
FindObjectOfType<GameManager>().Restart();
}
private void FixedUpdate()
{
if (left == true)
rb.velocity = new Vector3(-speed, rb.velocity.y, forwardSpeed);
else if (right == true)
rb.velocity = new Vector3(speed, rb.velocity.y, forwardSpeed);
}
}
|
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApplication1.Data;
using WebApplication1.Enums;
using WebApplication1.Models;
namespace WebApplication1.Services
{
public class DataService
{
private readonly ApplicationDbContext _dbContext;
private readonly RoleManager<IdentityRole> _roleManager;
private readonly UserManager<BlogUser> _userManager;
public DataService(ApplicationDbContext dbContext,
RoleManager<IdentityRole> roleManager,
UserManager<BlogUser> userManager)
{
_dbContext = dbContext;
_roleManager = roleManager;
_userManager = userManager;
}
public async Task ManageDataAsync()
{
await _dbContext.Database.MigrateAsync();
await SeedRolesAsync();
await SeedUsersAsync();
}
private async Task SeedRolesAsync()
{
if (_dbContext.Roles.Any())
{
return;
}
foreach (var role in Enum.GetNames(typeof(BlogRole)))
{
await _roleManager.CreateAsync(new IdentityRole(role));
}
}
private async Task SeedUsersAsync()
{
if (_dbContext.Users.Any())
{
return;
}
var adminUser = new BlogUser()
{
Email = "Jeremy.a.steward@gmail.com",
UserName = "Jeremy.a.steward@gmail.com",
FirstName = "Jeremy",
LastName = "Steward",
DisplayName = "Blog Admin",
EmailConfirmed = true,
PhoneNumber = "(800) 555-5555"
};
await _userManager.CreateAsync(adminUser, "Abc&123!");
await _userManager.AddToRoleAsync(adminUser, BlogRole.Administrator.ToString());
var modUser = new BlogUser()
{
Email = "Gianni.r.esposito@gmail.com",
UserName = "Gianni.r.esposito@gmail.com",
FirstName = "Gianni",
LastName = "Esposito",
DisplayName = "Blog Mod",
EmailConfirmed = true,
PhoneNumber = "(800) 444-4444"
};
await _userManager.CreateAsync(modUser, "Abc&123!");
await _userManager.AddToRoleAsync(modUser, BlogRole.Moderator.ToString());
}
}
}
|
using UnityEngine;
using System.Collections;
namespace ViNoToolkit{
/// <summary>
/// Sample TriggerVolume event receiver.
/// </summary>
public class TriggerVolumeEventReceiver : MonoBehaviour {
[System.Serializable]
public class TriggerVolEventEntry{
public ViNode node;
public GameObject triggerVolume;
}
public ScenarioNode scenario;
public TriggerVolEventEntry[] events;
private bool m_LockTrigger;
void OnTriggerEvent( ViNoEventData data ){
TriggerVolumeEventData tdata = data as TriggerVolumeEventData;
if (tdata == null) {
return;
}
// If event is already triggered, return.
if( ! m_LockTrigger ){
m_LockTrigger = true;
}
else{
return;
}
Collider col = tdata.collider;
Debug.Log( "OnTriggerEvent" );
foreach( TriggerVolEventEntry ent in events ){
if( col.gameObject.name.Equals( ent.triggerVolume.name ) ){
Debug.Log ( "Play from : " + ent.node.GetNodeLabel() );
scenario.PlayFrom( ent.node.GetNodeLabel() );
break;
}
}
}
/// <summary>
/// Raises the finish event event.
/// </summary>
void OnFinishEvent(){
Debug.Log( "OnFinishEvent" );
m_LockTrigger = false;
}
void Start () {
scenario.CompileAndSetCode();
}
}
}
|
using System;
using System.Drawing;
using System.Drawing.Imaging;
using OpenTK;
using OpenTK.Graphics.OpenGL4;
namespace Common.Graphics.FrameBuffer
{
public class FrameBufferDesc
{
public int TextureId { get; set; }
public int FramBufferObject { get; set; }
public int RenderBufferObject { get; set; }
public static FrameBufferDesc GetMainFrameBuffer(int width, int height)
{
int frameBufferObject = GL.GenFramebuffer();
int depthMapTextureId = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, depthMapTextureId);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Rgba,
width, height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.Bgra, PixelType.UnsignedByte, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
GL.BindTexture(TextureTarget.Texture2D, 0);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBufferObject);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.ColorAttachment0, TextureTarget.Texture2D, depthMapTextureId, 0);
int renderBufferObject = GL.GenRenderbuffer();
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, renderBufferObject);
GL.RenderbufferStorage(RenderbufferTarget.Renderbuffer, RenderbufferStorage.Depth24Stencil8, width, height);
GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0);
GL.FramebufferRenderbuffer(FramebufferTarget.Framebuffer,
FramebufferAttachment.DepthStencilAttachment,
RenderbufferTarget.Renderbuffer, renderBufferObject);
if (GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer) == FramebufferErrorCode.FramebufferComplete)
{
return new FrameBufferDesc()
{
FramBufferObject = frameBufferObject,
RenderBufferObject = renderBufferObject,
TextureId = depthMapTextureId,
};
}
throw new Exception($"main frameBuffer fail: {GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer)}");
}
public static FrameBufferDesc GetFrameBuffer(int width, int height)
{
int frameBufferObject = GL.GenFramebuffer();
int depthMapTextureId = GL.GenTexture();
GL.BindTexture(TextureTarget.Texture2D, depthMapTextureId);
GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.DepthComponent,
width, height, 0, OpenTK.Graphics.OpenGL4.PixelFormat.DepthComponent, PixelType.UnsignedByte, IntPtr.Zero);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (int)All.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (int)All.Linear);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapS, (int)All.ClampToBorder);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapR, (int)All.ClampToBorder);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureWrapT, (int)All.ClampToBorder);
GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureBorderColor, new float[] { 1, 1, 1, 1 });
GL.BindTexture(TextureTarget.Texture2D, 0);
GL.BindFramebuffer(FramebufferTarget.Framebuffer, frameBufferObject);
GL.FramebufferTexture2D(FramebufferTarget.Framebuffer, FramebufferAttachment.DepthAttachment, TextureTarget.Texture2D, depthMapTextureId, 0);
// no need for color attachment
GL.DrawBuffer(DrawBufferMode.None);
GL.ReadBuffer(ReadBufferMode.None);
var status = GL.CheckFramebufferStatus(FramebufferTarget.Framebuffer);
if (status == FramebufferErrorCode.FramebufferComplete)
{
return new FrameBufferDesc()
{
FramBufferObject = frameBufferObject,
RenderBufferObject = 0,
TextureId = depthMapTextureId,
};
}
throw new Exception("frameBuffer second fail" + status.ToString());
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
using System.IO;
using System.Text.RegularExpressions;
namespace IrcBot
{
class Irc
{
public string Hostname { get; }
public string ServerAdress { get; set; }
public int Port { get; }
public string Nickname { get; set; }
public string Realname { get; }
public bool Connected { get; }
TcpClient tcpClient;
StreamReader inputStream;
StreamWriter outputStream;
Queue<string> MessageQueue = new Queue<string>();
bool QueueIsRunning = false;
int QueueTimer = 800;
public Irc(string hostname, int port, string nickname, string realname)
{
Hostname = hostname;
Port = port;
Nickname = nickname;
Realname = realname;
try
{
tcpClient = new TcpClient(Hostname, Port);
inputStream = new StreamReader(tcpClient.GetStream());
outputStream = new StreamWriter(tcpClient.GetStream());
outputStream.Flush();
outputStream.WriteLine("NICK " + Nickname);
outputStream.WriteLine("USER " + Realname + " 8 * :" + Realname);// The USER message is used at the beginning of connection
//to specifythe username, hostname, servername and realname of s new user.
outputStream.Flush();
Connected = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Connected = false;
}
}
public string readData()
{
try
{
return inputStream.ReadLine();
}
catch (Exception ex)
{
return "Could not read data: " + ex.Message;
}
}
public void sendData(string Data)
{
try
{
outputStream.WriteLine(Data);
outputStream.Flush();
Console.WriteLine("<" + Data);
}
catch (Exception ex)
{
Console.WriteLine("Could not send data" + ex.Message);
}
}
public void joinRoom(string message)
{
if (Regex.IsMatch(message, "#([a-zA-Z0-9]+)"))
{
sendData("JOIN " + message);
}
else Console.WriteLine("No such channel");
}
public void ChatMessage(string message, string i)
{
//PRIVMSG (privatemessage)
string Message = "PRIVMSG " + i + " :" + message;
MessageQueue.Enqueue(Message);
if (!QueueIsRunning)
{
sendChatMessage();
}
}
private void sendChatMessage()
{
foreach (string i in MessageQueue)
{
QueueIsRunning = true;
outputStream.WriteLine(i);
outputStream.Flush();
System.Threading.Thread.Sleep(QueueTimer);
}
MessageQueue.Clear();
QueueIsRunning = false;
}
public void listNames(string channel)
{
if (Regex.IsMatch(channel, "#([a-zA-Z0-9]+)"))
{
sendData("NAMES " + channel);
}
else
{
sendData("NAMES ");
}
}
public void listChannels(string channel)
{
if (Regex.IsMatch(channel, "#([a-zA-Z0-9]+)"))
{
sendData("LIST " + channel);
}
else
{
sendData("LIST ");
}
}
public void quitSession()
{
sendData("QUIT " + ":Bye!");
}
public void serverStats(string queries)
{
if (Regex.IsMatch(queries, @"[chiklmoyu]"))
{
sendData("STATS " + queries);
}
else Console.WriteLine("Need to put stats query (c, h, i, k, l, m, o, y, u)");
}
public void commandWho(string mess)
{
sendData("WHO " + mess);
}
public void commandWhois(string mess)
{
sendData("WHOIS " + mess);
}
public void partChannel(string mess)
{
if (Regex.IsMatch(mess, "#([a-zA-Z0-9]+)"))
{
sendData("PART " + mess);
}
else Console.WriteLine("Channel not specified");
}
public void newNick(string mess)
{
sendData("NICK " + mess);
}
public void serverInfo()
{
sendData("INFO " + ServerAdress);
}
}
} |
using System.Collections.Generic;
using MvcMonitor.Models;
namespace MvcMonitor.ErrorHandling
{
public interface IErrorDataFactory
{
List<ErrorLocationModel> GetErrorLocations();
}
} |
using Game.Online.Multiplayer.Lobby;
using UnityEngine;
using UnityEngine.UI;
namespace Game.Graphics.UI.Buttons
{
public class OnlineViewButtons : MonoBehaviour
{
[SerializeField] private Lobby _lobby;
[SerializeField] private Button _createRoomButton;
[SerializeField] private Button _leaveRoomButton;
[SerializeField] private Button _joinRoomButton;
private void Start()
{
//_createRoomButton.onClick.AddListener(() => _lobby.);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InfoPole.Tests.TestData
{
class TessFilesPaths
{
public static IEnumerable<string> GetPaths()
{
return new string[]
{
@"C:\dev\test\rivegauche.ru.organic_G.keys.csv",
@"C:\dev\test\rivegauche.ru.organic_Y.keys.csv",
@"C:\dev\test\rivegauche.ru_G_spyw.csv",
@"C:\dev\test\rivegauche.ru_Y_spyw.csv"
};
}
public static string GetMarkupTagsPath()
{
return @"C:\dev\test\markupTags.csv";
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp1.file_handling
{
class MultipleBytes
{
static void Main(string[] args)
{
FileStream f = new FileStream("g:\\b.txt", FileMode.OpenOrCreate);
for (int i = 65; i<100; i++)
{
f.WriteByte((byte)i);
}
f.Close();
}
}
}
|
using System;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Models;
using OmniSharp.Extensions.LanguageServer.Protocol.Server;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.LanguageServer.Server
{
public class LanguageServerOptions : LanguageProtocolRpcOptionsBase<LanguageServerOptions>, ILanguageServerRegistry
{
public ServerInfo? ServerInfo { get; set; }
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions? options) =>
AddHandler(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler(string method, JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options) =>
AddHandler(method, handlerFunc, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandlers(params IJsonRpcHandler[] handlers) => AddHandlers(handlers);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler(JsonRpcHandlerFactory handlerFunc, JsonRpcHandlerOptions? options) =>
AddHandler(handlerFunc, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler(IJsonRpcHandler handler, JsonRpcHandlerOptions? options) =>
AddHandler(handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler<TTHandler>(JsonRpcHandlerOptions? options) => AddHandler<TTHandler>(options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler<TTHandler>(string method, JsonRpcHandlerOptions? options) =>
AddHandler<TTHandler>(method, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler(Type type, JsonRpcHandlerOptions? options) => AddHandler(type, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandler(string method, Type type, JsonRpcHandlerOptions? options) =>
AddHandler(method, type, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.AddHandlerLink(string fromMethod, string toMethod) =>
AddHandlerLink(fromMethod, toMethod);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnJsonRequest(string method, Func<JToken, Task<JToken>> handler, JsonRpcHandlerOptions? options) =>
OnJsonRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnJsonRequest(
string method, Func<JToken, CancellationToken, Task<JToken>> handler, JsonRpcHandlerOptions? options
) => OnJsonRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnRequest<TParams, TResponse>(
string method, Func<TParams, Task<TResponse>> handler, JsonRpcHandlerOptions? options
) => OnRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnRequest<TParams, TResponse>(
string method, Func<TParams, CancellationToken, Task<TResponse>> handler, JsonRpcHandlerOptions? options
) => OnRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.
OnRequest<TResponse>(string method, Func<Task<TResponse>> handler, JsonRpcHandlerOptions? options) => OnRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnRequest<TResponse>(
string method, Func<CancellationToken, Task<TResponse>> handler, JsonRpcHandlerOptions? options
) => OnRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnRequest<TParams>(string method, Func<TParams, Task> handler, JsonRpcHandlerOptions? options) =>
OnRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnRequest<TParams>(
string method, Func<TParams, CancellationToken, Task> handler, JsonRpcHandlerOptions? options
) => OnRequest(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnRequest<TParams>(
string method, Func<CancellationToken, Task> handler, JsonRpcHandlerOptions? options
) => OnRequest<TParams>(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnNotification<TParams>(
string method, Action<TParams, CancellationToken> handler, JsonRpcHandlerOptions? options
) => OnNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnJsonNotification(string method, Action<JToken> handler, JsonRpcHandlerOptions? options) =>
OnJsonNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnJsonNotification(
string method, Func<JToken, CancellationToken, Task> handler, JsonRpcHandlerOptions? options
) => OnJsonNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnJsonNotification(string method, Func<JToken, Task> handler, JsonRpcHandlerOptions? options) =>
OnJsonNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnJsonNotification(
string method, Action<JToken, CancellationToken> handler, JsonRpcHandlerOptions? options
) => OnJsonNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnNotification<TParams>(string method, Action<TParams> handler, JsonRpcHandlerOptions? options) =>
OnNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnNotification<TParams>(
string method, Func<TParams, CancellationToken, Task> handler, JsonRpcHandlerOptions? options
) => OnNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.
OnNotification<TParams>(string method, Func<TParams, Task> handler, JsonRpcHandlerOptions? options) => OnNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnNotification(string method, Action handler, JsonRpcHandlerOptions? options) =>
OnNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.
OnNotification(string method, Func<CancellationToken, Task> handler, JsonRpcHandlerOptions? options) => OnNotification(method, handler, options);
ILanguageServerRegistry IJsonRpcHandlerRegistry<ILanguageServerRegistry>.OnNotification(string method, Func<Task> handler, JsonRpcHandlerOptions? options) =>
OnNotification(method, handler, options);
}
}
|
using Assets.src.model;
using ManusMachina;
using System.Collections;
using UnityEngine;
/// <summary>
/// Abstract hand class, implementable by left/right hand controller
/// </summary>
public abstract class Hand : IHand
{
#region Fields
/// <summary>
/// Controls the vibration of the hand.
/// </summary>
public VibrateHand vh;
/// <summary>
/// The root transform.
/// </summary>
public Transform RootTransform;
/// <summary>
/// Left or right hand.
/// </summary>
protected GLOVE_HAND glove_hand;
/// <summary>
/// Manus Glove instance.
/// </summary>
protected Glove glove;
/// <summary>
/// The root (wrist) of the hand.
/// </summary>
protected GameObject root;
/// <summary>
/// The hand model.
/// </summary>
protected GameObject handModel;
/// <summary>
/// The manus grab.
/// </summary>
protected ManusGrab manusGrab;
/// <summary>
/// The colliders.
/// </summary>
protected ArrayList colliders;
/// <summary>
/// The game and model transforms.
/// </summary>
protected Transform[][] gameTransforms, modelTransforms;
/// <summary>
/// The base collider.
/// </summary>
protected BoxCollider baseCollider;
/// <summary>
/// The time factor.
/// </summary>
private const float timeFactor = 10.0f;
/// <summary>
/// The bend threshold.
/// </summary>
private const float BendThreshold = 0.4f;
/// <summary>
/// The sphere collider radius.
/// </summary>
private const float SphereColliderRadius = 0.035f;
/// <summary>
/// Numbers used for counting bend fingers.
/// </summary>
private static readonly int FOUR = 4, FIVE = 5;
/// <summary>
/// Game object hand.
/// </summary>
private GameObject hand;
/// <summary>
/// The sphere collider.
/// </summary>
private SphereCollider sphereCollider;
/// <summary>
/// The animation clip.
/// </summary>
private AnimationClip animationClip;
/// <summary>
/// The last touched gameobject.
/// </summary>
private GameObject lastTouched;
/// <summary>
/// The correction bends.
/// </summary>
private float[] correctionBends;
#endregion Fields
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="Hand"/> class.
/// </summary>
/// <param name="glove">The glove.</param>
/// <param name="RootTransform">The root transform.</param>
/// <param name="handModel">The hand model.</param>
/// <param name="handRoot">The hand root.</param>
/// <param name="hand">The hand.</param>
/// <param name="animation">The animation.</param>
/// <param name="highlightColor">Color of the highlight.</param>
public Hand(Glove glove, Transform RootTransform, GameObject handModel, GameObject handRoot, GameObject hand, AnimationClip animation, Color highlightColor)
{
Manus.ManusInit();
this.glove = glove;
this.RootTransform = RootTransform;
this.handModel = handModel;
this.root = handRoot;
this.hand = hand;
this.animationClip = animation;
this.lastTouched = null;
this.correctionBends = InitCorrectionBends();
this.gameTransforms = ManusControl.CreateGameTransforms(RootTransform);
this.modelTransforms = ManusControl.CreateModelTransforms(hand);
InitColliders();
this.manusGrab = new ManusGrab(baseCollider.gameObject, highlightColor, this);
this.vh = new VibrateHand(glove);
hand.SetActive(true);
}
#endregion Constructors
#region Methods
/// <summary>
/// Initializes the colliders.
/// </summary>
public void InitColliders()
{
this.colliders = new ArrayList();
this.colliders.AddRange(HandCollider.InitializeFingerColliders(gameTransforms));
this.baseCollider = (BoxCollider)HandCollider.CreateHandBaseCollider(RootTransform.gameObject);
this.colliders.Add(baseCollider);
}
/// <summary>
/// Update the position of the hand according to the arm.
/// </summary>
public abstract void UpdatePosition();
/// <summary>
/// Updates this instance.
/// </summary>
public void Update(bool[] bends)
{
UpdatePosition();
UpdateHand(bends);
UpdateGestures();
vh.Update();
}
/// <summary>
/// Updates the hand.
/// </summary>
public void UpdateHand(bool[] bends)
{
Quaternion q = glove.Quaternion;
float[] fingers = glove.Fingers;
RootTransform.localRotation = q;
for (int i = 0; i < fingers.Length; i++)
{
if (fingers[i] > correctionBends[i])
correctionBends[i] = bends[i] ? fingers[i] : correctionBends[i];
else
correctionBends[i] = fingers[i];
}
UpdateFingers(correctionBends, bends);
}
/// <summary>
/// Initializes the correction bends.
/// </summary>
/// <returns></returns>
public float[] InitCorrectionBends()
{
float[] res = new float[this.glove.Fingers.Length];
for (int i = 0; i < this.glove.Fingers.Length; i++)
res[i] = this.glove.Fingers[i];
return res;
}
/// <summary>
/// Updates the gestures.
/// </summary>
public virtual void UpdateGestures()
{
IMoveGesture gesture = GestureController.GetGesture(this.glove);
gesture.UpdateGrabbed(baseCollider.transform.rotation, this.manusGrab);
}
// Update is called once per frame
/// <summary>
/// Updates all fingers.
/// </summary>
/// <param name="f">Array of floats containing fingers.</param>
public void UpdateFingers(float[] f, bool[] bend)
{
float avgbend = 0.0f;
for (int i = 0; i < FIVE; i++)
{
animationClip.SampleAnimation(hand, f[i] * timeFactor);
avgbend += f[i];
for (int j = 0; j < FOUR; j++)
{
gameTransforms[i][j].localRotation = modelTransforms[i][j].localRotation;
}
}
avgbend /= 4;
float thumbvalue = (avgbend > f[0]) ? avgbend : f[0];
animationClip.SampleAnimation(hand, thumbvalue * timeFactor);
for (int j = 0; j < FOUR; j++)
{
gameTransforms[0][j].localRotation = modelTransforms[0][j].localRotation;
}
}
/// <summary>
/// Returns the ManusGrab.
/// </summary>
/// <returns>ManusGrab</returns>
public ManusGrab GetManusGrab()
{
return this.manusGrab;
}
/// <summary>
/// Checks if an object is touched.
/// </summary>
/// <param name="obj">The object.</param>
public void Touch(GameObject obj)
{
if ((lastTouched == null || !lastTouched.Equals(obj))
&& Manager.EnableVibration)
{
vh.Vibrate();
lastTouched = obj;
}
else
{
lastTouched = null;
}
}
/// <summary>
/// Gets the colliders.
/// </summary>
/// <returns>The colliders</returns>
public ArrayList GetColliders()
{
return this.colliders;
}
/// <summary>
/// Gets the root transform.
/// </summary>
/// <returns></returns>
public Transform GetRootTransform()
{
return this.RootTransform;
}
/// <summary>
/// Gets the position.
/// </summary>
/// <returns>The position</returns>
public Vector3 GetPosition()
{
return this.root.transform.position;
}
/// <summary>
/// When application is terminated, cancel Manus communication.
/// </summary>
private void OnApplicationQuit()
{
Manus.ManusExit();
}
#endregion Methods
} |
using DevExpress.Xpf.Core;
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Input;
using Tai_Shi_Xuan_Ji_Yi.Classes;
using Tai_Shi_Xuan_Ji_Yi.Windows;
namespace Tai_Shi_Xuan_Ji_Yi
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
#region Variables
CControlCentral control_central;
#endregion
public MainWindow()
{
// 设置鼠标光标到等待模式
System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.AppStarting;
this.Loaded += MainWindow_Loaded;
try
{
DXSplashScreen.SetState("正在启动...");
InitializeComponent();
/* 初始化控制板实例,该实例包含了串口通讯的协议 */
control_central = new CControlCentral();
control_central.ControllerCommStatusChanged += Control_central_ControllerCommStatusChanged;
/* 初始化左侧导航栏里的按钮 */
CPublicVariables.CureBandList = new ObservableCollection<CCureBandClass>();
for (int i = 0; i < 8; i++)
{
CPublicVariables.CureBandList.Add(new CCureBandClass(i, ref control_central));
}
leftNavBar.ItemCollection = CPublicVariables.CureBandList;
// pre-load windows to accelerate the openning speed
DXSplashScreen.SetState("加载历史记录...");
HistoryShow frmh = new HistoryShow();
DXSplashScreen.SetState("加载治疗信息...");
NewCureSetup fnew = new NewCureSetup(null);
DXSplashScreen.SetState("加载设置...");
Setting fset = new Setting();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
finally
{
// 回复鼠标光标到默认模式
System.Windows.Input.Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow;
}
}
void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
DXSplashScreen.Close();
}
/// <summary>
/// 通讯状态改变引发的事件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Control_central_ControllerCommStatusChanged(object sender, CommProgressReportArg e)
{
switch(e.Progress)
{
case CommProgressReportArg.ENUM_COMM_EVENT_TYPE.PortOpening:
txt_CommErrInfo.Text = e.Info;
break;
case CommProgressReportArg.ENUM_COMM_EVENT_TYPE.Err:
if (brd_CommErr.Visibility == Visibility.Hidden)
brd_CommErr.Visibility = Visibility.Visible;
txt_CommErrInfo.Text = e.Info;
break;
case CommProgressReportArg.ENUM_COMM_EVENT_TYPE.Finish:
if (brd_CommErr.Visibility == Visibility.Visible)
brd_CommErr.Visibility = Visibility.Hidden;
break;
}
}
private void btn_TemperSequenceEdit_Click(object sender, RoutedEventArgs e)
{
TemperatureSequenceEditor f = new TemperatureSequenceEditor(TemperatureSequenceEditor.ENUM_Window_Mode.Edit);
f.ShowDialog();
}
/// <summary>
/// 密码输入栏中按下回车
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void txt_UnlockPassword_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
btn_Unlock_Click(this, new RoutedEventArgs());
}
/// <summary>
/// 解锁屏幕
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Unlock_Click(object sender, RoutedEventArgs e)
{
if(txt_UnlockPassword.Password == CPublicVariables.Configuration.LoginPassword)
{
brd_LoginPanel.Visibility = System.Windows.Visibility.Hidden;
txt_UnlockPassword.Password = "";
}
else
{
txt_UnlockPassword.Password = "";
txt_UnlockPassword.Focus();
}
}
/// <summary>
/// 锁定屏幕
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Title_Locking(object sender, RoutedEventArgs e)
{
/* 显示解锁界面 */
brd_LoginPanel.Visibility = System.Windows.Visibility.Visible;
txt_UnlockPassword.Focus();
}
private void btn_Setting_Click(object sender, RoutedEventArgs e)
{
Setting f_setting = new Setting();
f_setting.ShowDialog();
}
private void btn_History_Click(object sender, RoutedEventArgs e)
{
HistoryShow f_history = new HistoryShow();
f_history.ShowDialog();
}
}
}
|
using System;
using System.Collections.Generic;
namespace ProductReviewManagementLinq
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Product Review Management using LINQ!");
///UC1 Create List of Product Review
List<ProductReview> productReview = new List<ProductReview>()
{
new ProductReview() { ProductId = 1,UserId = 1,Rating = 5,Review = "Good",isLike = true},
new ProductReview() { ProductId = 2,UserId = 2,Rating = 4,Review = "Nice",isLike = true},
new ProductReview() { ProductId = 3,UserId = 3,Rating = 3,Review = "Average",isLike = true},
new ProductReview() { ProductId = 4,UserId = 4,Rating = 2,Review = "Bad",isLike = false},
new ProductReview() { ProductId = 5,UserId = 5,Rating = 4,Review = "Nice",isLike = true},
new ProductReview() { ProductId = 6,UserId = 6,Rating = 5,Review = "Good",isLike = true},
new ProductReview() { ProductId = 4,UserId = 7,Rating = 3,Review = "Average",isLike = true},
new ProductReview() { ProductId = 8,UserId = 8,Rating = 2,Review = "Bad",isLike = false},
new ProductReview() { ProductId = 4,UserId = 9,Rating = 4,Review = "Nice",isLike = true},
new ProductReview() { ProductId = 1,UserId = 10,Rating = 3.5,Review = "Good",isLike = true}
};
foreach (var list in productReview)
{
Console.WriteLine("ProductId:" + list.ProductId + "\tUserId:" + list.UserId + "\tRating:" +
list.Rating + "\tReview:" + list.Rating + "\tisLike:" + list.isLike);
}
Management management = new Management();
/// UC2 Retrieve Top 3 records from list who's rating is high
management.TopRecords(productReview);
//UC3 Retrieve All data from list who's rating is greater than 3 and productid is 1 or 4 or 9
management.SelectRecords(productReview);
/// UC4 Retrieve Count of review present for each productid
management.RetrieveCountOfRecords(productReview);
/// UC5 UC7 Retrieve only productid and review from list for all records
management.RetrieveProductIdAndReview(productReview);
/// UC6 Skip Top 5 records from the list and display other records
management.SkipTopRecords(productReview);
/// UC8 Create DataTable and add ProductId,UserId,Rating,Review and isLike fields
management.InsertValuesInDataTable(productReview);
/// UC9 Retrieve All Records from datatable who's isLike value is true
management.RetrieveDataFromTable();
/// UC10 Find average rating of each productid
management.AverageRatingOfProductId();
/// UC11 Retrieve All records from list who's review message contain "Nice" in it
management.RetrieveDataFromTableForNiceMessage();
/// UC12 Retrieve All Records from list who's userid=10 and orderby rating
management.GetRecordsUsingUserId();
}
}
}
|
using SQLite;
using uwpEvernote.Interfaces;
namespace uwpEvernote.Model {
public class User: Notify {
private int _id;
[PrimaryKey, AutoIncrement]
public int Id {
get { return _id; }
set {
if (value != _id) {
_id = value;
OnPropertyChanged("id");
}
}
}
private string _name;
[MaxLength(50)]
public string Name {
get { return _name; }
set {
if (value != _name) {
_name = value;
OnPropertyChanged("name");
}
}
}
private string _lastName;
[MaxLength(50)]
public string LastName {
get { return _lastName; }
set {
if (value != _lastName) {
_lastName = value;
OnPropertyChanged("lastName");
}
}
}
private string _username;
public string Username {
get { return _username; }
set {
if (value != _username) {
_username = value;
OnPropertyChanged("username");
}
}
}
private string _email;
public string Email {
get { return _email; }
set {
if (value != _email) {
_email = value;
OnPropertyChanged("email");
}
}
}
private string _password;
public string Password {
get { return _password; }
set {
if (value != _password) {
_password = value;
OnPropertyChanged("password");
}
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BBMustacheCollision : MonoBehaviour
{
private CircleCollider2D m_triggerArea = null;
private GameOverHUDAnimations m_GameOverAnimations = null;
void Start()
{
m_triggerArea = GetComponent<CircleCollider2D>();
m_GameOverAnimations = FindObjectOfType<GameOverHUDAnimations>();
if(m_GameOverAnimations == null)
{
Debug.LogError("no GameOverHudAnimations reference");
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if(collision.GetComponent<BBDetectCollision>() != null)
{
m_GameOverAnimations.GameOverFromBBCollision();
}
}
}
|
namespace _02.DayOfWeekService.ConsoleClient
{
using DayOfWeekServiceReference;
using System;
using System.Text;
public class Startup
{
public static void Main()
{
// In order to see cyrilic letters change the console font to: consolas
DayOfWeekServiceClient client = new DayOfWeekServiceClient();
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine(client.GetDayOfWeek(DateTime.Now));
}
}
}
|
using NLog;
using System;
namespace Core.Log
{
public class Logger<T>
{
private readonly ILogger _log;
public Logger()
{
_log = LogManager.GetLogger(typeof(T).Name);
}
#region Методы логирования
/// <summary>
/// Расширенное логирование
/// </summary>
/// <param name="logEventInfo"></param>
public void Log(LogEventInfo logEventInfo)
{
_log.Log(logEventInfo);
}
/// <summary>
/// логирование критических ошибок
/// </summary>
/// <param name="message"></param>
public void Fatal(string message)
{
_log.Fatal(message);
}
/// <summary>
/// логирование критических ошибок
/// </summary>
/// <param name="message"></param>
public void Fatal(string message, Exception exception)
{
_log.Fatal(exception, message);
}
/// <summary>
/// Логирование ошибок
/// </summary>
/// <param name="message"></param>
public void Error(string message)
{
_log.Error(message);
}
/// <summary>
/// Логирование ошибок
/// </summary>
/// <param name="message"></param>
/// <param name="exception"></param>
public void Error(string message, Exception exception)
{
_log.Error(exception, message);
}
/// <summary>
/// Логирование прочей информации
/// </summary>
/// <param name="message"></param>
public void Info(string message)
{
_log.Info(message);
}
public void Info(string message, Exception exception)
{
_log.Info(exception, message);
}
public void Debug(string message)
{
_log.Debug(message);
}
public void Debug(string message, Exception exception)
{
_log.Debug(exception, message);
}
/// <summary>
/// логирование всего подряд
/// </summary>
/// <param name="message"></param>
public void Trace(string message)
{
_log.Trace(message);
}
/// <summary>
/// логирование всего подряд
/// </summary>
/// <param name="message"></param>
public void Trace(string message, Exception exception)
{
_log.Trace(exception, message);
}
#endregion
}
}
|
using System;
using UnityEngine;
namespace Assets.Scripts.Core.Scenarios
{
public class EffectItem : IScenarioItem
{
private readonly ParticleSystem particleSystem;
private IScenarioItem timerItem;
public EffectItem(ParticleSystem particleSystem, float duration = -1)
{
this.particleSystem = particleSystem;
if (duration > 0)
{
timerItem = new IterateItem(duration);
}
}
public IScenarioItem Play()
{
particleSystem.Play(true);
if (timerItem != null)
timerItem.Play();
return this;
}
public void Stop()
{
particleSystem.Stop(true);
if (timerItem != null)
timerItem.Stop();
}
public void Pause()
{
particleSystem.Pause(true);
if (timerItem != null)
timerItem.Pause();
}
public bool IsComplete
{
get { return timerItem == null ? particleSystem.IsAlive(true) : timerItem.IsComplete; }
}
}
} |
using ALM.ServicioAdminEmpresas.Entidades;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ALM.ServicioAdminEmpresas.Negocio
{
public static class NClaseEstatica
{
public static void EstablecerLstReemplazarMVC()
{
EClaseEstatica.LstReemplazarMVC = new NReemplazarMVC().ObtenerReemplazarMVC();
}
public static void EstablecerLstParametros()
{
EClaseEstatica.LstParametro = new NParametro().ObtenerParametros();
}
}
}
|
using System;
using EnvDTE;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
namespace EditorConfig.VisualStudio
{
/// <summary>
/// This plugin attaches to an editor instance and updates its settings at
/// the appropriate times
/// </summary>
internal class Plugin
{
IWpfTextView view;
DTE dte;
ErrorListProvider messageList;
ErrorTask message;
Results settings;
public Plugin(IWpfTextView view, ITextDocument document, DTE dte, ErrorListProvider messageList)
{
this.view = view;
this.dte = dte;
this.messageList = messageList;
this.message = null;
document.FileActionOccurred += FileActionOccurred;
view.GotAggregateFocus += GotAggregateFocus;
view.Closed += Closed;
LoadSettings(document.FilePath);
}
/// <summary>
/// Reloads the settings when the filename changes
/// </summary>
void FileActionOccurred(object sender, TextDocumentFileActionEventArgs e)
{
if ((e.FileActionType & FileActionTypes.DocumentRenamed) != 0)
LoadSettings(e.FilePath);
if (settings != null && view.HasAggregateFocus)
ApplyGlobalSettings();
}
/// <summary>
/// Updates the global settings when the local editor receives focus
/// </summary>
void GotAggregateFocus(object sender, EventArgs e)
{
if (settings != null)
ApplyGlobalSettings();
}
/// <summary>
/// Removes the any messages when the document is closed
/// </summary>
void Closed(object sender, EventArgs e)
{
ClearMessage();
}
/// <summary>
/// Loads the settings for the given file path
/// </summary>
private void LoadSettings(string path)
{
ClearMessage();
settings = null;
// Prevent parsing of internet-located documents,
// or documents that do not have proper paths.
if (path.StartsWith("http:", StringComparison.OrdinalIgnoreCase)
|| path.Equals("Temp.txt"))
return;
try
{
settings = Core.Parse(path);
ApplyLocalSettings();
}
catch (ParseException e)
{
ShowError(path, "EditorConfig syntax error in file \"" + e.File + "\", line " + e.Line);
}
catch (CoreException e)
{
ShowError(path, "EditorConfig core error: " + e.Message);
}
}
/// <summary>
/// Applies settings to the local text editor instance
/// </summary>
private void ApplyLocalSettings()
{
IEditorOptions options = view.Options;
if (settings.ContainsKey("tab_width"))
{
try
{
int value = Convert.ToInt32(settings["tab_width"]);
options.SetOptionValue<int>(DefaultOptions.TabSizeOptionId, value);
}
catch { }
}
if (settings.ContainsKey("indent_size"))
{
try
{
int value = Convert.ToInt32(settings["indent_size"]);
options.SetOptionValue<int>(DefaultOptions.IndentSizeOptionId, value);
}
catch { }
}
if (settings.ContainsKey("indent_style"))
{
string value = settings["indent_style"];
if (value == "tab")
options.SetOptionValue<bool>(DefaultOptions.ConvertTabsToSpacesOptionId, false);
else if (value == "space")
options.SetOptionValue<bool>(DefaultOptions.ConvertTabsToSpacesOptionId, true);
}
if (settings.ContainsKey("end_of_line"))
{
string value = settings["end_of_line"];
if (value == "lf")
{
options.SetOptionValue<string>(DefaultOptions.NewLineCharacterOptionId, "\n");
options.SetOptionValue<bool>(DefaultOptions.ReplicateNewLineCharacterOptionId, false);
}
else if (value == "cr")
{
options.SetOptionValue<string>(DefaultOptions.NewLineCharacterOptionId, "\r");
options.SetOptionValue<bool>(DefaultOptions.ReplicateNewLineCharacterOptionId, false);
}
else if (value == "crlf")
{
options.SetOptionValue<string>(DefaultOptions.NewLineCharacterOptionId, "\r\n");
options.SetOptionValue<bool>(DefaultOptions.ReplicateNewLineCharacterOptionId, false);
}
}
}
/// <summary>
/// Applies settings to the global Visual Studio application. Some
/// source-code formatters, such as curly-brace auto-indenter, ignore
/// the local text editor settings. This causes horrible bugs when
/// the local text-editor settings disagree with the formatter's
/// settings. To fix this, just apply the same settings at the global
/// application level as well.
/// </summary>
private void ApplyGlobalSettings()
{
EnvDTE.Properties props;
try
{
string type = view.TextDataModel.ContentType.TypeName;
props = dte.get_Properties("TextEditor", type);
}
catch
{
// If the above code didn't work, this particular content type
// didn't need its settings changed anyhow
return;
}
if (settings.ContainsKey("tab_width"))
{
try
{
int value = Convert.ToInt32(settings["tab_width"]);
props.Item("TabSize").Value = value;
}
catch { }
}
if (settings.ContainsKey("indent_size"))
{
try
{
int value = Convert.ToInt32(settings["indent_size"]);
props.Item("IndentSize").Value = value;
}
catch { }
}
if (settings.ContainsKey("indent_style"))
{
string value = settings["indent_style"];
if (value == "tab")
props.Item("InsertTabs").Value = true;
else if (value == "space")
props.Item("InsertTabs").Value = false;
}
}
/// <summary>
/// Adds an error message to the Visual Studio tasks pane
/// </summary>
void ShowError(string path, string text)
{
message = new ErrorTask();
message.ErrorCategory = TaskErrorCategory.Error;
message.Category = TaskCategory.Comments;
message.Document = path;
message.Line = 0;
message.Column = 0;
message.Text = text;
messageList.Tasks.Add(message);
messageList.Show();
}
/// <summary>
/// Removes the file's messages, if any
/// </summary>
void ClearMessage()
{
if (message != null)
messageList.Tasks.Remove(message);
message = null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Assignment___Chloe_Green
{
public class TransactionLogAdd : TransactionLog
{
public double price { get; }
public TransactionLogAdd(string type, int itemCode, string name, double price, DateTime d) : base(type, itemCode, name ,d)
{
this.price = price;
}
public override string ToString()
{
return Convert.ToString(price);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LSKYGuestAccountControl.Model
{
public class LoginSession
{
public string Username { get; set; }
public string IPAddress { get; set; }
public string Thumbprint { get; set; }
public string UserAgent { get; set; }
public bool CanUseBatches { get; set; }
public bool CanBypassLimits { get; set; }
public bool CanViewLogs { get; set; }
public DateTime SessionStarts { get; set; }
public DateTime SessionEnds { get; set; }
public int ActivationLimit
{
get
{
if (this.CanBypassLimits)
{
return int.MaxValue;
}
else
{
return Settings.AllowedRequisitionsPerDay;
}
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Archimedes.Library.Domain;
using Archimedes.Library.Extensions;
using Archimedes.Library.Message.Dto;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
namespace Archimedes.Service.Ui.Http
{
public class HttpHealthMonitorClient : IHttpHealthMonitorClient
{
private readonly ILogger<HttpHealthMonitorClient> _logger;
private readonly HttpClient _client;
//https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1
public HttpHealthMonitorClient(IOptions<Config> config, HttpClient httpClient, ILogger<HttpHealthMonitorClient> logger)
{
httpClient.BaseAddress = new Uri($"{config.Value.HealthUrl}api/");
httpClient.DefaultRequestHeaders.Add("Accept", "application/json");
_client = httpClient;
_logger = logger;
}
public async Task<IEnumerable<HealthMonitorDto>> GetHealthMonitor()
{
try
{
var response = await _client.GetAsync("health");
if (!response.IsSuccessStatusCode)
{
_logger.LogError($"GET Failed: {response.ReasonPhrase} from {response.RequestMessage.RequestUri}");
return null;
}
var health = await response.Content.ReadAsAsync<IEnumerable<HealthMonitorDto>>();
return health;
}
catch (Exception e)
{
_logger.LogError($"GET Failed: {e.Message} from {e.InnerException}");
return null;
}
}
}
}
|
// Accord Statistics Library
// The Accord.NET Framework
// http://accord-framework.net
//
// Copyright © César Souza, 2009-2015
// cesarsouza at gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
namespace Accord.Statistics.Distributions.Univariate
{
using System;
using Accord.Math;
using Accord.Statistics.Distributions.Fitting;
using AForge;
/// <summary>
/// F (Fisher-Snedecor) distribution.
/// </summary>
///
/// <remarks>
/// <para>
/// In probability theory and statistics, the F-distribution is a continuous
/// probability distribution. It is also known as Snedecor's F distribution
/// or the Fisher-Snedecor distribution (after R.A. Fisher and George W. Snedecor).
/// The F-distribution arises frequently as the null distribution of a test statistic,
/// most notably in the analysis of variance; see <see cref="Accord.Statistics.Testing.FTest"/>.</para>
///
/// <para>
/// References:
/// <list type="bullet">
/// <item><description><a href="http://en.wikipedia.org/wiki/F-distribution">
/// Wikipedia, The Free Encyclopedia. F-distribution. Available on:
/// http://en.wikipedia.org/wiki/F-distribution </a></description></item>
/// </list></para>
/// </remarks>
///
/// <example>
/// <para>
/// The following example shows how to construct a Fisher-Snedecor's F-distribution
/// with 8 and 5 degrees of freedom, respectively.</para>
///
/// <code>
/// // Create a Fisher-Snedecor's F distribution with 8 and 5 d.f.
/// FDistribution F = new FDistribution(degrees1: 8, degrees2: 5);
///
/// // Common measures
/// double mean = F.Mean; // 1.6666666666666667
/// double median = F.Median; // 1.0545096252132447
/// double var = F.Variance; // 7.6388888888888893
///
/// // Cumulative distribution functions
/// double cdf = F.DistributionFunction(x: 0.27); // 0.049463408057268315
/// double ccdf = F.ComplementaryDistributionFunction(x: 0.27); // 0.95053659194273166
/// double icdf = F.InverseDistributionFunction(p: cdf); // 0.27
///
/// // Probability density functions
/// double pdf = F.ProbabilityDensityFunction(x: 0.27); // 0.45120469723580559
/// double lpdf = F.LogProbabilityDensityFunction(x: 0.27); // -0.79583416831212883
///
/// // Hazard (failure rate) functions
/// double hf = F.HazardFunction(x: 0.27); // 0.47468419528555084
/// double chf = F.CumulativeHazardFunction(x: 0.27); // 0.050728620222091653
///
/// // String representation
/// string str = F.ToString(CultureInfo.InvariantCulture); // F(x; df1 = 8, df2 = 5)
/// </code>
/// </example>
///
[Serializable]
public class FDistribution : UnivariateContinuousDistribution,
ISampleableDistribution<double>
{
// Distribution parameters
private int d1;
private int d2;
// Derived values
private double b;
private double? mean;
private double? variance;
/// <summary>
/// Constructs a F-distribution with
/// the given degrees of freedom.
/// </summary>
///
public FDistribution()
: this(1, 1)
{
}
/// <summary>
/// Constructs a F-distribution with
/// the given degrees of freedom.
/// </summary>
///
/// <param name="degrees1">The first degree of freedom. Default is 1.</param>
/// <param name="degrees2">The second degree of freedom. Default is 1.</param>
///
public FDistribution([PositiveInteger] int degrees1, [PositiveInteger] int degrees2)
{
if (degrees1 <= 0)
throw new ArgumentOutOfRangeException("degrees1", "Degrees of freedom must be positive.");
if (degrees2 <= 0)
throw new ArgumentOutOfRangeException("degrees1", "Degrees of freedom must be positive.");
this.d1 = degrees1;
this.d2 = degrees2;
this.b = Beta.Function(degrees1 * 0.5, degrees2 * 0.5);
}
/// <summary>
/// Gets the first degree of freedom.
/// </summary>
///
public int DegreesOfFreedom1
{
get { return d1; }
}
/// <summary>
/// Gets the second degree of freedom.
/// </summary>
///
public int DegreesOfFreedom2
{
get { return d2; }
}
/// <summary>
/// Gets the mean for this distribution.
/// </summary>
///
public override double Mean
{
get
{
if (!mean.HasValue)
{
if (d2 <= 2)
{
mean = Double.NaN;
}
else
{
mean = d2 / (d2 - 2.0);
}
}
return mean.Value;
}
}
/// <summary>
/// Gets the variance for this distribution.
/// </summary>
///
public override double Variance
{
get
{
if (!variance.HasValue)
{
if (d2 <= 4)
{
variance = Double.NaN;
}
else
{
variance = (2.0 * d2 * d2 * (d1 + d2 - 2)) /
(d1 * (d2 - 2) * (d2 - 2) * (d2 - 4));
}
}
return variance.Value;
}
}
/// <summary>
/// Gets the mode for this distribution.
/// </summary>
///
/// <value>
/// The distribution's mode value.
/// </value>
///
public override double Mode
{
get
{
if (d1 > 2)
{
double a = (d1 - 2.0) / d1;
double b = d2 / (d2 + 2.0);
return a * b;
}
return Double.NaN;
}
}
/// <summary>
/// Gets the support interval for this distribution.
/// </summary>
///
/// <value>
/// A <see cref="DoubleRange" /> containing
/// the support interval for this distribution.
/// </value>
///
public override DoubleRange Support
{
get { return new DoubleRange(0, Double.PositiveInfinity); }
}
/// <summary>
/// Gets the entropy for this distribution.
/// </summary>
///
public override double Entropy
{
get { throw new NotSupportedException(); }
}
/// <summary>
/// Gets the cumulative distribution function (cdf) for
/// the F-distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
/// <remarks>
/// <para>
/// The Cumulative Distribution Function (CDF) describes the cumulative
/// probability that a given value or any value smaller than it will occur.</para>
/// <para>
/// The F-distribution CDF is computed in terms of the <see cref="Beta.Incomplete">
/// Incomplete Beta function Ix(a,b)</see> as CDF(x) = Iu(d1/2, d2/2) in which
/// u is given as u = (d1 * x) / (d1 * x + d2)</para>.
/// </remarks>
///
public override double DistributionFunction(double x)
{
if (x <= 0)
return 0;
double u = (d1 * x) / (d1 * x + d2);
return Beta.Incomplete(d1 * 0.5, d2 * 0.5, u);
}
/// <summary>
/// Gets the complementary cumulative distribution
/// function evaluated at point <c>x</c>.
/// </summary>
///
/// <remarks>
/// <para>
/// The F-distribution complementary CDF is computed in terms of the <see cref="Beta.Incomplete">
/// Incomplete Beta function Ix(a,b)</see> as CDFc(x) = Iu(d2/2, d1/2) in which
/// u is given as u = (d2 * x) / (d2 * x + d1)</para>.
/// </remarks>
///
public override double ComplementaryDistributionFunction(double x)
{
if (x <= 0)
return 1;
double u = d2 / (d2 + d1 * x);
return Beta.Incomplete(d2 * 0.5, d1 * 0.5, u);
}
/// <summary>
/// Gets the inverse of the cumulative distribution function (icdf) for
/// this distribution evaluated at probability <c>p</c>. This function
/// is also known as the Quantile function.
/// </summary>
///
/// <remarks>
/// The Inverse Cumulative Distribution Function (ICDF) specifies, for
/// a given probability, the value which the random variable will be at,
/// or below, with that probability.
/// </remarks>
///
public override double InverseDistributionFunction(double p)
{
// Cephes Math Library Release 2.8: June, 2000
// Copyright 1984, 1987, 1995, 2000 by Stephen L. Moshier
// Adapted under the LGPL with permission of original author.
if (p <= 0.0 || p > 1.0)
throw new ArgumentOutOfRangeException("p", "Input must be between zero and one.");
double d1 = this.d1;
double d2 = this.d2;
double x;
double w = Beta.Incomplete(0.5 * d2, 0.5 * d1, 0.5);
if (w > p || p < 0.001)
{
w = Beta.IncompleteInverse(0.5 * d1, 0.5 * d2, p);
x = d2 * w / (d1 * (1.0 - w));
}
else
{
w = Beta.IncompleteInverse(0.5 * d2, 0.5 * d1, 1.0 - p);
x = (d2 - d2 * w) / (d1 * w);
}
return x;
}
/// <summary>
/// Gets the probability density function (pdf) for
/// the F-distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
/// <returns>
/// The probability of <c>x</c> occurring
/// in the current distribution.
/// </returns>
///
/// <remarks>
/// The Probability Density Function (PDF) describes the
/// probability that a given value <c>x</c> will occur.
/// </remarks>
///
public override double ProbabilityDensityFunction(double x)
{
if (x <= 0)
return 0;
double u = Math.Pow(d1 * x, d1) * Math.Pow(d2, d2) /
Math.Pow(d1 * x + d2, d1 + d2);
return Math.Sqrt(u) / (x * b);
}
/// <summary>
/// Gets the log-probability density function (pdf) for
/// this distribution evaluated at point <c>x</c>.
/// </summary>
///
/// <param name="x">A single point in the distribution range.</param>
///
/// <returns>
/// The logarithm of the probability of <c>x</c>
/// occurring in the current distribution.
/// </returns>
///
/// <remarks>
/// The Probability Density Function (PDF) describes the
/// probability that a given value <c>x</c> will occur.
/// </remarks>
///
public override double LogProbabilityDensityFunction(double x)
{
if (x <= 0)
return Double.NegativeInfinity;
double lnu = d1 * Math.Log(d1 * x) + d2 * Math.Log(d2) -
(d1 + d2) * Math.Log(d1 * x + d2);
return 0.5 * lnu - Math.Log(x * b);
}
/// <summary>
/// Not available.
/// </summary>
///
public override void Fit(double[] observations, double[] weights, IFittingOptions options)
{
throw new NotSupportedException();
}
/// <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 override object Clone()
{
return new FDistribution(d1, d2);
}
#region ISamplableDistribution<double> Members
/// <summary>
/// Generates a random vector of observations from the current distribution.
/// </summary>
///
/// <param name="samples">The number of samples to generate.</param>
///
/// <returns>A random vector of observations drawn from this distribution.</returns>
///
public override double[] Generate(int samples)
{
return Random(d1, d2, samples);
}
/// <summary>
/// Generates a random observation from the current distribution.
/// </summary>
///
/// <returns>A random observations drawn from this distribution.</returns>
///
public override double Generate()
{
return Random(d1, d2);
}
/// <summary>
/// Generates a random vector of observations from the
/// F-distribution with the given parameters.
/// </summary>
///
/// <param name="d1">The first degree of freedom.</param>
/// <param name="d2">The second degree of freedom.</param>
/// <param name="samples">The number of samples to generate.</param>
///
/// <returns>An array of double values sampled from the specified F-distribution.</returns>
///
public static double[] Random(int d1, int d2, int samples)
{
double[] x = GammaDistribution.Random(shape: d1 / 2.0, scale: 2, samples: samples);
double[] y = GammaDistribution.Random(shape: d2 / 2.0, scale: 2, samples: samples);
for (int i = 0; i < x.Length; i++)
x[i] = x[i] / y[i];
return x;
}
/// <summary>
/// Generates a random observation from the
/// F-distribution with the given parameters.
/// </summary>
///
/// <param name="d1">The first degree of freedom.</param>
/// <param name="d2">The second degree of freedom.</param>
///
/// <returns>A random double value sampled from the specified F-distribution.</returns>
///
public static double Random(int d1, int d2)
{
double x = GammaDistribution.Random(shape: d1 / 2.0, scale: 2);
double y = GammaDistribution.Random(shape: d2 / 2.0, scale: 2);
return x / y;
}
#endregion
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
///
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
///
public override string ToString(string format, IFormatProvider formatProvider)
{
return String.Format("F(x; df1 = {0}, df2 = {1})",
d1.ToString(format, formatProvider),
d2.ToString(format, formatProvider));
}
}
}
|
using NLog;
using System;
using System.Threading;
namespace TNBase
{
/// <summary>
/// Handle unhandled exceptions (at least log them!)
/// </summary>
public static class ExceptionHandler
{
// Logging instance
private static Logger log = LogManager.GetCurrentClassLogger();
/// <summary>
/// Unhandled exception handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void AppDomain_CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Exception ex = (Exception) e.ExceptionObject;
log.Fatal(ex, $"Fatal exception occured: {ex.Message}");
}
/// <summary>
/// Unhandled exception handler
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void AppDomain_Application_ThreadException(object sender, ThreadExceptionEventArgs e)
{
Exception ex = (Exception)e.Exception;
log.Fatal(ex, $"Fatal (thread) exception occured: {ex.Message}");
}
}
}
|
namespace UserVoiceSystem.Web.Controllers
{
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Data.Models;
using Infrastructure.Filters;
using Microsoft.AspNet.Identity;
using Services.Data.Common;
using ViewModels.Votes;
[Authorize]
public class VotesController : BaseController
{
private readonly IVotesService votes;
private readonly IAuthorsService authors;
private readonly IIdeasService ideas;
public VotesController(IVotesService votes, IAuthorsService authors, IIdeasService ideas)
{
this.votes = votes;
this.authors = authors;
this.ideas = ideas;
}
[AjaxPost]
[ValidateAntiForgeryToken]
public ActionResult Vote(VotePostViewModel model)
{
if (model != null && this.ModelState.IsValid)
{
var userId = this.User.Identity.GetUserId();
var author = this.authors.GetAll()
.FirstOrDefault(x => x.UserId == userId);
if ((author.VotePoints - model.Points) > 0)
{
author.VotePoints -= model.Points;
this.authors.Update(author);
var vote = this.votes.GetAll()
.FirstOrDefault(x => x.IdeaId == model.IdeaId && x.AuthorIp == author.Ip);
if (vote == null)
{
vote = new Vote
{
AuthorIp = author.Ip,
IdeaId = model.IdeaId,
Points = model.Points
};
this.votes.Create(vote);
}
else
{
vote.Points = model.Points;
this.votes.Update(vote);
}
}
var newIdeaVotes = this.votes
.GetAll()
.Where(x => x.IdeaId == model.IdeaId)
.Sum(x => x.Points);
return this.Json(new { VotesCount = newIdeaVotes });
}
throw new HttpException(404, "not found !");
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace diyetisyenproje.Screens
{
public partial class HastaEkle : Form
{
public HastaEkle()
{
InitializeComponent();
}
private void Back_btn_Click(object sender, EventArgs e) {
Singleton.Instance.dScreen.OnLoad();
Singleton.Instance.ChangeScreen(this, Singleton.Instance.dScreen);
}
private void Exit_btn_Click(object sender, EventArgs e) => Singleton.Instance.ExitTheApplication();
private void HastaEkle_btn_Click(object sender, EventArgs e)
{
Singleton.Instance.islem.HastaEkle(newtc_txt.Text,newad_txt.Text,newsoyad_txt.Text,newtel_txt.Text,this);
}
}
}
|
using AprendendoBlazor.Server.Data;
using AprendendoBlazor.Shared.Model;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace AprendendoBlazor.Server.Controllers
{
[AllowAnonymous]
[Route("api/[controller]/[action]")]
[ApiController]
public class UsuariosController : ControllerBase
{
private ApplicationDbContext _Contexto;
public UsuariosController(ApplicationDbContext Contexto)
{
_Contexto = Contexto;
}
public ActionResult<bool> VerificarSeUsuarioExiste(int Id)
{
return true;
}
[HttpPost]
public ActionResult<int> AdicionaUsuario(Usuario novoUsuario)
{
Usuario user1 = new Usuario()
{
Checked = novoUsuario.Checked,
Nome = novoUsuario.Nome,
Email = novoUsuario.Email,
DataNascimento = novoUsuario.DataNascimento,
};
_Contexto.Usuario.Add(user1);
_Contexto.SaveChanges();
return user1.Id;
}
public ActionResult<List<Usuario>> BuscaUsuarios()
{
List<Usuario> UsuariosDb = new List<Usuario>();
UsuariosDb = _Contexto.Usuario.Where(u => u.Id != null).ToList();
return UsuariosDb;
}
[HttpPost]
public ActionResult<bool> ExcluiUsuario(Usuario user)
{
Console.WriteLine("Controller recebeu o ID: {0} para ser excluido!", user.Id);
int _id = user.Id;
if(_id > 0)
{
Console.WriteLine("Mensagem de dentro do controller, excluir usuario de Id: {0}", _id);
Usuario ParaRemover = _Contexto.Usuario.FirstOrDefault(u => u.Id == _id);
_Contexto.Usuario.Remove(ParaRemover);
_Contexto.SaveChanges();
return true;
}
return false;
}
}
}
|
#region using statements
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
#endregion
namespace RandomData.EF.Data.Entities
{
#region class Member
public partial class Member
{
#region Private Variables
private bool active;
private string firstName;
private int id;
private string lastName;
private Address address;
#endregion
#region Properties
#region Address
/// <summary>
/// This property gets or sets the value for 'Address'.
/// </summary>
[NotMapped]
public Address Address
{
get { return address; }
set { address = value; }
}
#endregion
#region bool Active
public bool Active
{
get
{
return active;
}
set
{
active = value;
}
}
#endregion
#region string FirstName
public string FirstName
{
get
{
return firstName;
}
set
{
firstName = value;
}
}
#endregion
#region int Id
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id
{
get
{
return id;
}
set
{
id = value;
}
}
#endregion
#region string LastName
public string LastName
{
get
{
return lastName;
}
set
{
lastName = value;
}
}
#endregion
#endregion
}
#endregion
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("GameStrings")]
public class GameStrings : MonoClass
{
public GameStrings(IntPtr address) : this(address, "GameStrings")
{
}
public GameStrings(IntPtr address, string className) : base(address, className)
{
}
public static void CheckConflicts(GameStringTable table)
{
object[] objArray1 = new object[] { table };
MonoClass.smethod_18(TritonHs.MainAssemblyPath, "", "GameStrings", "CheckConflicts", objArray1);
}
public static string Find(string key)
{
object[] objArray1 = new object[] { key };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "Find", objArray1);
}
public static string Get(string key)
{
object[] objArray1 = new object[] { key };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "Get", objArray1);
}
public static string GetAssetPath(Locale locale, string fileName)
{
object[] objArray1 = new object[] { locale, fileName };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetAssetPath", objArray1);
}
public static string GetCardSetName(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardSetName", objArray1);
}
public static string GetCardSetNameInitials(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardSetNameInitials", objArray1);
}
public static string GetCardSetNameKey(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardSetNameKey", objArray1);
}
public static string GetCardSetNameKeyShortened(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardSetNameKeyShortened", objArray1);
}
public static string GetCardSetNameShortened(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardSetNameShortened", objArray1);
}
public static string GetCardTypeName(TAG_CARDTYPE tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardTypeName", objArray1);
}
public static string GetCardTypeNameKey(TAG_CARDTYPE tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetCardTypeNameKey", objArray1);
}
public static string GetClassName(TAG_CLASS tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetClassName", objArray1);
}
public static string GetClassNameKey(TAG_CLASS tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetClassNameKey", objArray1);
}
public static string GetKeywordName(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetKeywordName", objArray1);
}
public static string GetKeywordNameKey(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetKeywordNameKey", objArray1);
}
public static string GetKeywordText(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetKeywordText", objArray1);
}
public static string GetKeywordTextKey(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetKeywordTextKey", objArray1);
}
public static int GetPluralIndex(int number)
{
object[] objArray1 = new object[] { number };
return MonoClass.smethod_14<int>(TritonHs.MainAssemblyPath, "", "GameStrings", "GetPluralIndex", objArray1);
}
public static string GetRaceName(TAG_RACE tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRaceName", objArray1);
}
public static string GetRaceNameKey(TAG_RACE tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRaceNameKey", objArray1);
}
public static string GetRandomTip(TipCategory tipCategory)
{
object[] objArray1 = new object[] { tipCategory };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRandomTip", objArray1);
}
public static string GetRarityText(TAG_RARITY tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRarityText", objArray1);
}
public static string GetRarityTextKey(TAG_RARITY tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRarityTextKey", objArray1);
}
public static string GetRefKeywordText(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRefKeywordText", objArray1);
}
public static string GetRefKeywordTextKey(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetRefKeywordTextKey", objArray1);
}
public static string GetTip(TipCategory tipCategory, int progress, TipCategory randomTipCategory)
{
object[] objArray1 = new object[] { tipCategory, progress, randomTipCategory };
return MonoClass.smethod_12(TritonHs.MainAssemblyPath, "", "GameStrings", "GetTip", objArray1);
}
public static bool HasCardSetName(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasCardSetName", objArray1);
}
public static bool HasCardSetNameInitials(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasCardSetNameInitials", objArray1);
}
public static bool HasCardSetNameShortened(TAG_CARD_SET tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasCardSetNameShortened", objArray1);
}
public static bool HasCardTypeName(TAG_CARDTYPE tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasCardTypeName", objArray1);
}
public static bool HasClassName(TAG_CLASS tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasClassName", objArray1);
}
public static bool HasKey(string key)
{
object[] objArray1 = new object[] { key };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasKey", objArray1);
}
public static bool HasKeywordName(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasKeywordName", objArray1);
}
public static bool HasKeywordText(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasKeywordText", objArray1);
}
public static bool HasRaceName(TAG_RACE tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasRaceName", objArray1);
}
public static bool HasRarityText(TAG_RARITY tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasRarityText", objArray1);
}
public static bool HasRefKeywordText(GAME_TAG tag)
{
object[] objArray1 = new object[] { tag };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "HasRefKeywordText", objArray1);
}
public static void LoadAll()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "GameStrings", "LoadAll");
}
public static bool LoadCategory(GameStringCategory cat)
{
object[] objArray1 = new object[] { cat };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "LoadCategory", objArray1);
}
public static string ParseLanguageRules(string str)
{
Class272.Enum20[] enumArray1 = new Class272.Enum20[] { Class272.Enum20.String };
object[] objArray1 = new object[] { str };
return MonoClass.smethod_13(TritonHs.MainAssemblyPath, "", "GameStrings", "ParseLanguageRules", enumArray1, objArray1);
}
public static void ReloadAll()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "GameStrings", "ReloadAll");
}
public static bool UnloadCategory(GameStringCategory cat)
{
object[] objArray1 = new object[] { cat };
return MonoClass.smethod_14<bool>(TritonHs.MainAssemblyPath, "", "GameStrings", "UnloadCategory", objArray1);
}
public static void WillReset()
{
MonoClass.smethod_17(TritonHs.MainAssemblyPath, "", "GameStrings", "WillReset");
}
public static List<char> LANGUAGE_RULE_ARG_DELIMITERS
{
get
{
Class246<char> class2 = MonoClass.smethod_7<Class246<char>>(TritonHs.MainAssemblyPath, "", "GameStrings", "LANGUAGE_RULE_ARG_DELIMITERS");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public static string NUMBER_PATTERN
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "GameStrings", "NUMBER_PATTERN");
}
}
public static string s_UnknownName
{
get
{
return MonoClass.smethod_8(TritonHs.MainAssemblyPath, "", "GameStrings", "s_UnknownName");
}
}
[Attribute38("GameStrings.PluralNumber")]
public class PluralNumber : MonoClass
{
public PluralNumber(IntPtr address) : this(address, "PluralNumber")
{
}
public PluralNumber(IntPtr address, string className) : base(address, className)
{
}
public int m_index
{
get
{
return base.method_2<int>("m_index");
}
}
public int m_number
{
get
{
return base.method_2<int>("m_number");
}
}
public bool m_useForOnlyThisIndex
{
get
{
return base.method_2<bool>("m_useForOnlyThisIndex");
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using ReactRestChat.Data;
namespace ReactRestChat.Models
{
public class ConversationInstance : IEntity
{
public ConversationInstance()
{
Created = DateTime.Now;
IsMessageReadVisible = true;
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
public Guid ConversationId { get; set; }
[ForeignKey("ConversationId")]
public virtual Conversation Conversation { get; set; }
public string ParticipantId { get; set; }
[ForeignKey("ParticipantId")]
public virtual ApplicationUser Participant { get; set; }
public DateTime Created { get; private set; }
public DateTime? Deleted { get; set; }
public bool IsMessageReadVisible { get; set; }
public Guid? ShowFromMessageId { get; set; }
[ForeignKey("ShowFromMessageId")]
public virtual ConversationMessage ShowFromMessage { get; set; }
public Guid? LastReadMessageId { get; set; }
[ForeignKey("LastReadMessageId")]
public virtual ConversationMessage LastReadMessage { get; set; }
public Guid? DeletedAfterMessageId { get; set; }
[ForeignKey("DeletedAfterMessageId")]
public virtual ConversationMessage DeletedAfterMessage { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SingleTargetProjectile : Projectile
{
private bool alreadyHitATarget;//This is to prevent OnTriggerEnter to cast multiple times if multiple targets enter the collider at the same time
protected override void OnTriggerEnter2D(Collider2D collider)
{
if (!alreadyHitATarget)
{
if (collider.gameObject.tag == "Platform" || collider.gameObject.tag == "Wall" || collider.gameObject.tag == "MapCeiling" || collider.gameObject.tag == "MapFloor" ||
collider.gameObject.tag == "FlyingPlatform" || collider.gameObject.tag == "MapWall" || collider.gameObject.tag == "Enemy")
{
ProjectileHit(collider.gameObject);
alreadyHitATarget = true;
GetComponent<Collider2D>().enabled = false;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BatteryMove : MonoBehaviour {
protected Vector2 trajec;
Rigidbody2D rigBod;
// Use this for initialization
void OnEnable() {
rigBod = GetComponent<Rigidbody2D> ();
}
void Start () {
}
// Update is called once per frame
void Update () {
}
void FixedUpdate () {
trajec.x = CreateGlobals.enemyBulletSpeed;
trajec = trajec / 40;
rigBod.position = rigBod.position + trajec;
}
void OnTriggerEnter2D (Collider2D collision) {
if (collision.gameObject.tag == "BulletKill")
Destroy (this.gameObject);
if (collision.gameObject.tag == "Player") {
AudioManager.Manager.Play ("Battery");
CreateGlobals.batterChargeLevel = 100;
Destroy (this.gameObject);
}
}
}
|
namespace Triton.Game.Mapping
{
using ns26;
using System;
[Attribute38("ClassFilterButton")]
public class ClassFilterButton : PegUIElement
{
public ClassFilterButton(IntPtr address) : this(address, "ClassFilterButton")
{
}
public ClassFilterButton(IntPtr address, string className) : base(address, className)
{
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void HandleRelease()
{
base.method_8("HandleRelease", Array.Empty<object>());
}
public void SetNewCardCount(int count)
{
object[] objArray1 = new object[] { count };
base.method_8("SetNewCardCount", objArray1);
}
public GameObject m_disabled
{
get
{
return base.method_3<GameObject>("m_disabled");
}
}
public GameObject m_newCardCount
{
get
{
return base.method_3<GameObject>("m_newCardCount");
}
}
public UberText m_newCardCountText
{
get
{
return base.method_3<UberText>("m_newCardCountText");
}
}
public CollectionManagerDisplay.ViewMode m_tabViewMode
{
get
{
return base.method_2<CollectionManagerDisplay.ViewMode>("m_tabViewMode");
}
}
}
}
|
using Athena.Data.Borrowings;
namespace Athena.Messages {
public class BorrowBookMessage {
public Borrowing Borrowing { get; set; }
}
} |
using System;
namespace CallCenter.Common.Entities
{
public interface IChatAction : IIdentifier
{
IChat Chat { get; set; }
DateTime ActionDate { get; set; }
ChatActionType ActionType { get; set; }
IOperator InvokeOperator { get; set; }
}
} |
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Prism.Logging;
namespace CaseInstaller.ViewModels
{
public class TrueManagementInstallViewModel : CaseInstallerBase
{
private readonly IRegionManager regionManager;
public DelegateCommand<string>InstallCommand { get; private set; }
public TrueManagementInstallViewModel(IRegionManager regionManager)
{
this.regionManager = regionManager;
this.InstallCommand = new DelegateCommand<string>(Navigate);
}
private void Navigate(string navigatePath)
{
if (navigatePath != null)
{
this.regionManager.RequestNavigate("ContentRegion", navigatePath);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public class NumberWizard : MonoBehaviour {
// Global variables and constants
int max, min, mid;
string guess, instruct;
char upArrow, downArrow;
// Use this for initialization
void Start () {
StartGame();
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.UpArrow)) {
print("up arrow was pressed");
// Set the new minimum to one higher than the old middle value
min = mid +1;
// Set the new middle value
GetMiddle();
// make new guess
Guess();
} else if (Input.GetKeyDown(KeyCode.DownArrow)) {
print("down arrow was pressed");
// Set ne maximum to one lower than the old middle value
max = mid -1;
// Set the new middle value
GetMiddle();
// make new guess
Guess();
} else if (Input.GetKeyDown(KeyCode.Return)) {
print("I won!");
StartGame();
}
}
void StartGame() {
max = 1000;
min = 1;
mid = 500;
upArrow = '\u2191';
downArrow = '\u2193';
instruct = "press up " + upArrow + " for higher, press down " + downArrow + " for lower, enter for equal";
print("============================================");
print("Welcome to NUmber Wizard");
print("Pick a number in your head but don't tell me");
print("Pick a number between " + min + " and " + max);
Guess();
}
void GetMiddle() {
int spread;
spread = max - min;
mid = max - spread/2;
}
void Guess() {
guess = "is the number higher or lower than " + mid + "?";
print(guess);
print(instruct);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MovieCruiserUserStories.DAO;
using MovieCruiserUserStories.Models;
namespace MovieCruiserUserStories.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AnonymousController : ControllerBase
{
private readonly DbCon con;
public AnonymousController(DbCon _con)
{
con = _con;
}
[HttpGet]
public IEnumerable<Movies> Get()
{
return con.Movies.ToList();
}
}
} |
using RedLine.Models.Gecko;
using System;
namespace RedLine.Logic.Browsers.Gecko
{
public static class Asn1Factory
{
public static Asn1Object Create(byte[] dataToParse)
{
Asn1Object asn1Object = new Asn1Object();
for (int i = 0; i < dataToParse.Length; i++)
{
Asn1Type asn1Type = (Asn1Type)dataToParse[i];
int num = 0;
switch (asn1Type)
{
case Asn1Type.Sequence:
{
byte[] array;
if (asn1Object.ObjectLength == 0)
{
asn1Object.ObjectType = Asn1Type.Sequence;
asn1Object.ObjectLength = dataToParse.Length - (i + 2);
array = new byte[asn1Object.ObjectLength];
}
else
{
asn1Object.Objects.Add(new Asn1Object
{
ObjectType = Asn1Type.Sequence,
ObjectLength = dataToParse[i + 1]
});
array = new byte[dataToParse[i + 1]];
}
num = ((array.Length > dataToParse.Length - (i + 2)) ? (dataToParse.Length - (i + 2)) : array.Length);
Array.Copy(dataToParse, i + 2, array, 0, array.Length);
asn1Object.Objects.Add(Create(array));
i = i + 1 + dataToParse[i + 1];
break;
}
case Asn1Type.Integer:
{
asn1Object.Objects.Add(new Asn1Object
{
ObjectType = Asn1Type.Integer,
ObjectLength = dataToParse[i + 1]
});
byte[] array = new byte[dataToParse[i + 1]];
num = ((i + 2 + dataToParse[i + 1] > dataToParse.Length) ? (dataToParse.Length - (i + 2)) : dataToParse[i + 1]);
Array.Copy(dataToParse, i + 2, array, 0, num);
asn1Object.Objects[asn1Object.Objects.Count - 1].ObjectData = array;
i = i + 1 + asn1Object.Objects[asn1Object.Objects.Count - 1].ObjectLength;
break;
}
case Asn1Type.OctetString:
{
asn1Object.Objects.Add(new Asn1Object
{
ObjectType = Asn1Type.OctetString,
ObjectLength = dataToParse[i + 1]
});
byte[] array = new byte[dataToParse[i + 1]];
num = ((i + 2 + dataToParse[i + 1] > dataToParse.Length) ? (dataToParse.Length - (i + 2)) : dataToParse[i + 1]);
Array.Copy(dataToParse, i + 2, array, 0, num);
asn1Object.Objects[asn1Object.Objects.Count - 1].ObjectData = array;
i = i + 1 + asn1Object.Objects[asn1Object.Objects.Count - 1].ObjectLength;
break;
}
case Asn1Type.ObjectIdentifier:
{
asn1Object.Objects.Add(new Asn1Object
{
ObjectType = Asn1Type.ObjectIdentifier,
ObjectLength = dataToParse[i + 1]
});
byte[] array = new byte[dataToParse[i + 1]];
num = ((i + 2 + dataToParse[i + 1] > dataToParse.Length) ? (dataToParse.Length - (i + 2)) : dataToParse[i + 1]);
Array.Copy(dataToParse, i + 2, array, 0, num);
asn1Object.Objects[asn1Object.Objects.Count - 1].ObjectData = array;
i = i + 1 + asn1Object.Objects[asn1Object.Objects.Count - 1].ObjectLength;
break;
}
}
}
return asn1Object;
}
}
}
|
//using System;
//using System.Collections;
//using System.Collections.Generic;
//using System.Linq;
//using UnityEditor;
//using UnityEngine;
//[CustomEditor(typeof(GizmoVolume))]
//public class GizmoVolumeEditor : Editor
//{
// public override void OnInspectorGUI()
// {
// GizmoVolume m_target = (GizmoVolume)target;
// //DrawDefaultInspector();
// if (!m_target.Hidden)
// {
// EditorGUILayout.LabelField("Gizmo Previewer", "Easily implement gizmos in your scene");
// m_target.volumeType = (GizmoVolume.VolumeType)EditorGUILayout.EnumPopup(m_target.volumeType);
// GUILayout.Space(10);
// m_target.color = EditorGUILayout.ColorField("Volume Color", m_target.color);
// if (m_target.volumeType != GizmoVolume.VolumeType.Line)
// {
// m_target._3DSize = GUILayout.Toggle(m_target._3DSize, "3D Size");
// m_target.fitCollisionSize = GUILayout.Toggle(m_target.fitCollisionSize, "Fit size to Collision Box");
// if (m_target._3DSize)
// {
// //EditorGUILayout.HelpBox("This is a help box", MessageType.Info);
// m_target.size = EditorGUILayout.Vector3Field("Size", m_target.size);
// }
// else
// {
// m_target.size.x = EditorGUILayout.FloatField("Size", m_target.size.x);
// m_target.size.y = m_target.size.x;
// m_target.size.z = m_target.size.x;
// }
// m_target.OffsetPosition = EditorGUILayout.Vector3Field("Offset Position", m_target.OffsetPosition);
// }
// else
// {
// m_target.OffsetPosition = EditorGUILayout.Vector3Field("Start Point", m_target.OffsetPosition);
// m_target.size = EditorGUILayout.Vector3Field("End Point", m_target.size);
// m_target.targetLine = EditorGUILayout.ObjectField("Target", m_target.targetLine, typeof(GameObject), true);
// }
// if (m_target.volumeType == GizmoVolume.VolumeType.Icon)
// {
// m_target.iconNameIndex = EditorGUILayout.IntSlider("Icon", m_target.iconNameIndex, 0, m_target.defaultIcons.Length - 1);
// EditorGUILayout.HelpBox("To Add Icons, Edit the 'defaultIcons' array in the code", MessageType.Info);
// }
// //FETCHING VARIABLES
// GUILayout.Space(10);
// m_target._fetchVariable = GUILayout.Toggle(m_target._fetchVariable, "Fetch Value Outside");
// if (m_target._fetchVariable)
// {
// m_target.fetchedComponent = (Component)EditorGUILayout.ObjectField("Component to fetch from", m_target.fetchedComponent, typeof(Component), true);
// if (m_target.fetchedVariables_names.Count > 0)
// {
// m_target.fetchedVarIndex = EditorGUILayout.Popup("Variables", m_target.fetchedVarIndex, m_target.fetchedVariables_names.ToArray());
// }
// else
// {
// m_target.UpdateComponents();
// }
// m_target.fetchedVarRealtimeUpdate = GUILayout.Toggle(m_target.fetchedVarRealtimeUpdate, "Update variable in Realtime");
// if (m_target.fetchedVarRealtimeUpdate)
// {
// m_target._UpdateFetchedVarOnlyOnFocus = GUILayout.Toggle(m_target._UpdateFetchedVarOnlyOnFocus, "Update only when selected");
// if (m_target._UpdateFetchedVarOnlyOnFocus && m_target.fetchedVarIndex > 0)
// {
// m_target.UpdateVar();
// }
// }
// else
// {
// if (GUILayout.Button("Update Component Variables"))
// {
// m_target.UpdateComponents();
// }
// }
// if (m_target._wrongFetch)
// {
// EditorGUILayout.HelpBox("WRONG FORMAT, Chosen variable is not valid.", MessageType.Warning);
// }
// //EditorGUILayout.LabelField("var index", m_target.fetchedVariables_values.Count.ToString());
// }
// //TEXT
// GUILayout.Space(10);
// m_target.addText = GUILayout.Toggle(m_target.addText, "Toggle Text");
// if (m_target.addText)
// {
// m_target.areaText = EditorGUILayout.TextField("Helper Text", m_target.areaText);
// m_target.textSize = EditorGUILayout.IntField("Text Size", m_target.textSize);
// m_target.textOffset = EditorGUILayout.Vector3Field("Text Offset", m_target.textOffset);
// m_target.textColor = EditorGUILayout.ColorField("Text Color", m_target.textColor);
// m_target.hideTextUnselected = GUILayout.Toggle(m_target.hideTextUnselected, "Hide if unselected");
// if (m_target.hideTextUnselected)
// {
// EditorGUILayout.HelpBox("Text only appears when the object is selected", MessageType.Info);
// }
// }
// GUILayout.Space(10);
// if (GUILayout.Button("Hide Inspector"))
// {
// m_target.Hidden = true;
// }
// }
// else
// {
// if(GUILayout.Button("Unhide Inspector"))
// {
// m_target.Hidden = false;
// }
// }
// EditorUtility.SetDirty(m_target);
// }
// private void OnSceneGUI()
// {
// GizmoVolume m_target = (GizmoVolume)target;
// //Handles
// /* Handles.PositionHandle(
// m_target.transform.position,
// m_target.transform.rotation);*/
// Handles.BeginGUI();
// //Text
// if (m_target.hideTextUnselected)
// {
// var rectMin = Camera.current.WorldToScreenPoint(
// m_target.transform.position + m_target.OffsetPosition +
// m_target.textOffset);
// var rect = new Rect();
// int widthSize = 256;
// int heightSize = 128;
// rect.xMin = rectMin.x - widthSize / 2;
// rect.yMin = Screen.height - 30 -
// rectMin.y;
// rect.width = widthSize;
// rect.height = heightSize;
// GUILayout.BeginArea(rect);
// GUIStyle style = new GUIStyle();
// style.fontSize = m_target.textSize;
// style.alignment = TextAnchor.MiddleCenter;
// style.normal.textColor = m_target.textColor;
// if (m_target.addText)
// {
// GUILayout.Label(m_target.areaText, style);
// }
// GUILayout.EndArea();
// }
// Handles.EndGUI();
// }
//}
|
using System.Buffers;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
// ReSharper disable HeapView.ObjectAllocation.Evident
namespace NetFabric.Hyperlinq
{
public static partial class AsyncValueEnumerableExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static async ValueTask<List<TSource>> ToListAsync<TEnumerable, TEnumerator, TSource>(this TEnumerable source, CancellationToken cancellationToken = default)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
=> (await source.ToArrayAsync<TEnumerable, TEnumerator, TSource>(cancellationToken).ConfigureAwait(false)).AsList();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static async ValueTask<List<TSource>> ToListAsync<TEnumerable, TEnumerator, TSource, TPredicate>(this TEnumerable source, TPredicate predicate, CancellationToken cancellationToken)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
where TPredicate : struct, IAsyncFunction<TSource, bool>
=> (await source.ToArrayAsync<TEnumerable, TEnumerator, TSource, TPredicate>(predicate, cancellationToken).ConfigureAwait(false)).AsList();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static async ValueTask<List<TSource>> ToListAtAsync<TEnumerable, TEnumerator, TSource, TPredicate>(this TEnumerable source, TPredicate predicate, CancellationToken cancellationToken)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
where TPredicate : struct, IAsyncFunction<TSource, int, bool>
=> (await source.ToArrayAtAsync<TEnumerable, TEnumerator, TSource, TPredicate>(predicate, cancellationToken).ConfigureAwait(false)).AsList();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static async ValueTask<List<TResult>> ToListAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(this TEnumerable source, TSelector selector, CancellationToken cancellationToken)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
where TSelector : struct, IAsyncFunction<TSource, TResult>
=> (await source.ToArrayAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(selector, cancellationToken).ConfigureAwait(false)).AsList();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static async ValueTask<List<TResult>> ToListAtAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(this TEnumerable source, TSelector selector, CancellationToken cancellationToken)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
where TSelector : struct, IAsyncFunction<TSource, int, TResult>
=> (await source.ToArrayAtAsync<TEnumerable, TEnumerator, TSource, TResult, TSelector>(selector, cancellationToken).ConfigureAwait(false)).AsList();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static async ValueTask<List<TResult>> ToListAsync<TEnumerable, TEnumerator, TSource, TResult, TPredicate, TSelector>(this TEnumerable source, TPredicate predicate, TSelector selector, CancellationToken cancellationToken)
where TEnumerable : IAsyncValueEnumerable<TSource, TEnumerator>
where TEnumerator : struct, IAsyncEnumerator<TSource>
where TPredicate : struct, IAsyncFunction<TSource, bool>
where TSelector : struct, IAsyncFunction<TSource, TResult>
=> (await source.ToArrayAsync<TEnumerable, TEnumerator, TSource, TResult, TPredicate, TSelector>(predicate, selector, cancellationToken).ConfigureAwait(false)).AsList();
}
}
|
using FacebookFeeder.Models;
using Orchard;
using Orchard.Services;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
namespace FacebookFeeder.Services
{
public interface IFacebookService : IDependency
{
IList<FacebookPost> GetLatestPosts(FacebookFeederPart part);
}
public class FacebookService : IFacebookService
{
private FacebookFeederPart _part;
private const string _urlBase = "https://graph.facebook.com/{0}/feed?access_token={1}&limit={2}";
public IList<FacebookPost> GetLatestPosts(FacebookFeederPart part)
{
_part = part;
string url = string.Format(_urlBase, part.PageId, part.AccessToken, part.Limit);
string json = GetFeedPosts(url);
return ParseFeed(json);
}
private string GetFeedPosts(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
string errorText = reader.ReadToEnd();
}
throw;
}
}
private IList<FacebookPost> ParseFeed(string json)
{
DefaultJsonConverter converter = new DefaultJsonConverter();
dynamic parsed = converter.Deserialize(json);
List<FacebookPost> posts = new List<FacebookPost>();
bool isPage = _part.FeedType.ToUpper().Equals("PAGE");
foreach (dynamic item in parsed.data)
{
FacebookUser poster = new FacebookUser()
{
Id = item.from.id,
Name = item.from.name
};
posts.Add(new FacebookPost()
{
PageId = poster.Id,
PostId = ParsePostId(_part.PageId, item.id.Value),
PostedBy = poster,
Story = ParseStory(item.story, poster.Name),
Message = item.message ?? string.Empty,
Created = item.created_time,
Photo = new FacebookImage()
{
ImagePage = isPage ? item.link : string.Empty,
ImageSource = item.picture ?? string.Empty
}
});
}
return posts;
}
private string ParsePostId(string pageId, string postId)
{
return postId.Replace(pageId, string.Empty).Replace("_", string.Empty);
}
private string ParseStory(dynamic story, string poster)
{
return story ?? string.Format("{0} added a post.", poster);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace NutritionalResearchBusiness.Extensions
{
public static class StringExtensions
{
#region 正则表达式
/// <summary>
/// 指示所指定的正则表达式在指定的输入字符串中是否找到了匹配项
/// </summary>
/// <param name="value">要搜索匹配项的字符串</param>
/// <param name="pattern">要匹配的正则表达式模式</param>
/// <returns>如果正则表达式找到匹配项,则为 true;否则,为 false</returns>
public static bool IsMatch(this string value, string pattern)
{
if (value == null)
{
return false;
}
return Regex.IsMatch(value, pattern);
}
/// <summary>
/// 在指定的输入字符串中搜索指定的正则表达式的第一个匹配项
/// </summary>
/// <param name="value">要搜索匹配项的字符串</param>
/// <param name="pattern">要匹配的正则表达式模式</param>
/// <returns>一个对象,包含有关匹配项的信息</returns>
public static string Match(this string value, string pattern)
{
if (value == null)
{
return null;
}
return Regex.Match(value, pattern).Value;
}
/// <summary>
/// 在指定的输入字符串中搜索指定的正则表达式的所有匹配项的字符串集合
/// </summary>
/// <param name="value"> 要搜索匹配项的字符串 </param>
/// <param name="pattern"> 要匹配的正则表达式模式 </param>
/// <returns> 一个集合,包含有关匹配项的字符串值 </returns>
public static IEnumerable<string> Matches(this string value, string pattern)
{
if (value == null)
{
return new string[] { };
}
MatchCollection matches = Regex.Matches(value, pattern);
return from Match match in matches select match.Value;
}
/// <summary>
/// 是否电子邮件
/// </summary>
public static bool IsEmail(this string value)
{
const string pattern = @"^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否是IP地址
/// </summary>
public static bool IsIpAddress(this string value)
{
const string pattern = @"^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否是整数
/// </summary>
public static bool IsNumeric(this string value)
{
const string pattern = @"^\-?[0-9]+$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否为浮点数
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsFloat(this string value)
{
float f = 0;
return float.TryParse(value,out f);
}
/// <summary>
/// 是否是Unicode字符串
/// </summary>
public static bool IsUnicode(this string value)
{
const string pattern = @"^[\u4E00-\u9FA5\uE815-\uFA29]+$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否Url字符串
/// </summary>
public static bool IsUrl(this string value)
{
const string pattern = @"^(http|https|ftp|rtsp|mms):(\/\/|\\\\)[A-Za-z0-9%\-_@]+\.[A-Za-z0-9%\-_@]+[A-Za-z0-9\.\/=\?%\-&_~`@:\+!;]*$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否身份证号,验证如下3种情况:
/// 1.身份证号码为15位数字;
/// 2.身份证号码为18位数字;
/// 3.身份证号码为17位数字+1个字母
/// </summary>
public static bool IsIdentityCard(this string value)
{
const string pattern = @"^(^\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否手机号码
/// </summary>
/// <param name="value"></param>
/// <param name="isRestrict">是否按严格格式验证</param>
public static bool IsMobileNumber(this string value, bool isRestrict = false)
{
string pattern = isRestrict ? @"^[1][3-8]\d{9}$" : @"^[1]\d{10}$";
return value.IsMatch(pattern);
}
/// <summary>
/// 是否日期
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool IsDateTime(this string value)
{
DateTime _tempDT;
return DateTime.TryParse(value, out _tempDT);
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MirrorShield : MagicItem
{
GameObject shield;
float cooldown = 1.0f;
Timer cooldownTimer;
bool isOnCooldown = false;
public MirrorShield()
{
Type = InventoryItems.Shield;
UISprite = DatabaseManager.Instance.GetSpriteFromDatabase("Items", "Treasures", "Shield", "UI Sprite");
Description = DatabaseManager.Instance.GetStringFromDatabase("Items", "Treasures", "Shield", "Description");
ItemName = "Mirror Shield";
GameObject shieldPrefab = DatabaseManager.Instance.GetGameObjectFromDataBase("Items", "Treasures", "Shield", "GameObject");
shield = GameObject.Instantiate(shieldPrefab);
shield.transform.SetParent(GameManager.Instance.Player.transform);
shield.SetActive(false);
cooldownTimer = new Timer(cooldown);
cooldownTimer.OnTick.AddListener(() => { isOnCooldown = false; });
}
public override void Activate()
{
if (!isOnCooldown)
{
IsActive = true;
shield.SetActive(true);
shield.transform.localPosition = GameManager.Instance.Player.Facing * 1.1f;
GameManager.Instance.Player.Freeze();
}
}
public override void Deactivate()
{
if (IsActive)
{
shield.SetActive(false);
IsActive = false;
isOnCooldown = true;
cooldownTimer.Start();
GameManager.Instance.Player.Unfreeze();
}
}
}
|
using UnityEngine;
using System.Collections;
public class SpawnDebris : MonoBehaviour {
public GameObject[] debris;
public int minInterval;
public int maxInterval;
// Use this for initialization
void Start () {
Invoke ("spawnDebris", 1f);
}
// Update is called once per frame
void Update () {
}
void spawnDebris(){
float randomTime = Random.Range (minInterval, maxInterval);
int randomObject = Random.Range (0, debris.Length);
Instantiate (debris [randomObject], transform.position, Quaternion.Euler(Random.Range(0,90), Random.Range(0,90), Random.Range(0,90)));
Invoke ("spawnDebris", randomTime);
}
}
|
using System;
using System.Web.UI;
using Aqueduct.Utils;
using Sitecore.Data.Items;
using Sitecore.Web.UI.WebControls;
using Sitecore.Data;
namespace Aqueduct.SitecoreLib
{
public static class SublayoutHelper
{
public static Control GetControl(Guid sublayoutId, Item currentItem)
{
Guard.AssertThat(sublayoutId != null && sublayoutId != Guid.Empty, "SublayoutId cannot be an empty Guid");
Guard.AssertThat(currentItem != null, "Cannot get sublayout for a null item");
var sublayoutItem = GetSublayoutItem(sublayoutId);
if (sublayoutItem != null)
{
var sublayout = new Sublayout();
sublayout.Path = sublayoutItem.FilePath;
sublayout.DataSource = currentItem.Paths.FullPath;
return sublayout.GetUserControl();
}
return null;
}
private static SublayoutItem GetSublayoutItem(Guid sublayoutId)
{
return new SublayoutItem(Databases.CurrentDatabase.GetItem(new ID(sublayoutId)));
}
}
}
|
using Arch.Data.Common.Logging;
using System;
namespace Arch.Data.DbEngine.Executor
{
public interface IExecutor
{
void Daemon();
void Dispose();
Boolean EnqueueLogEntry(ILogEntry entry);
Boolean EnqueueCallback(Action callback);
void StartRWCallback(Action callback, Int32 delay);
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
public class ListController : MonoBehaviour {
[System.Serializable]
public class StringEvent : UnityEvent<string> {};
public StringEvent onValueChanged;
public Toggle defaultItem;
private List<Toggle> toggles = new List<Toggle>();
private List<string> keys = new List<string>();
public Scrollbar scrollbar;
// Use this for initialization
private bool initialized = false;
void Start () {
if (initialized)
return;
toggles.Add (defaultItem);
keys.Add ("");
initialized = true;
}
public void setDefaultVisible(bool v) {
defaultItem.gameObject.SetActive (v);
}
private void updateSize() {
float itemSizeY = defaultItem.GetComponent<RectTransform> ().sizeDelta.y;
float sizey = itemSizeY * keys.Count;
if (sizey < 200)
sizey = 200;
GetComponent<RectTransform> ().sizeDelta = new Vector2 (0, sizey);
}
public void addItem(string key, string value, string new_key = "") {
if (!initialized)
Start ();
if (key == "")
return;
Toggle t = null;
for (int i = 0; i < keys.Count; i++)
if (keys [i] == key) {
t = toggles [i];
if (new_key != "") {
keys [i] = new_key;
if (selected == key)
selected = new_key;
}
}
if (t == null) {
t = Instantiate (defaultItem, transform).GetComponent<Toggle> ();
t.gameObject.SetActive (true);
toggles.Add (t);
keys.Add (key);
t.isOn = false;
updateSize ();
scrollbar.value = 0;
}
t.GetComponentInChildren<Text> ().text = value;
}
public void scrollUp() {
scrollbar.value = 1;
}
public void clear() {
if (!initialized)
Start ();
for (int i = keys.Count-1; i > 0; i--) {
Destroy (toggles [i].gameObject);
toggles.RemoveAt (i);
keys.RemoveAt (i);
}
updateSize ();
}
public void deleteItem(string key) {
if (!initialized)
Start ();
if (key == "")
return;
for (int i = 0; i < keys.Count; i++)
if (keys [i] == key) {
Destroy (toggles [i].gameObject);
toggles.RemoveAt (i);
keys.RemoveAt (i);
updateSize ();
return;
}
}
private string selected = "";
public string Selected {
get { return selected; }
set {
for (int i = 0; i < keys.Count; i++)
if (keys [i] == value)
toggles [i].isOn = true;
}
}
public void itemSelected(Toggle t) {
if (!t.isOn)
return;
for (int i = 0; i < toggles.Count; i++)
if (toggles [i] == t) {
selected = keys [i];
onValueChanged.Invoke(selected);
return;
}
}
}
|
using MongoDB.Driver;
using MongoDB.Driver.Builders;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace QuickCollab.Session
{
public class SessionInstanceRepository : ISessionInstanceRepository
{
private MongoDatabase _dbContext;
private MongoCollection _sessions;
public SessionInstanceRepository()
{
_dbContext = new MongoClient("mongodb://user1:pa55W0rd@localhost")
.GetServer()
.GetDatabase("QuickCollab");
_sessions = _dbContext.GetCollection<SessionInstance>("Sessions");
}
public IEnumerable<SessionInstance> ListAllSessions()
{
return _sessions.FindAllAs<SessionInstance>().AsQueryable();
}
public SessionInstance GetSession(string sessionName)
{
var query = Query<SessionInstance>.EQ(s => s.Name, sessionName);
return _sessions
.FindAs<SessionInstance>(query)
.SingleOrDefault();
}
public void AddSession(SessionInstance instance)
{
System.Diagnostics.Debug.Assert(!SessionExists(instance.Name));
_sessions.Insert(instance);
}
public void DeleteSession(string sessionName)
{
if (SessionExists(sessionName))
_sessions.Remove(Query<SessionInstance>.EQ(s => s.Name, sessionName));
}
public bool SessionExists(string sessionName)
{
var query = Query<SessionInstance>.EQ(s => s.Name, sessionName);
return _sessions
.FindAs<SessionInstance>(query)
.Any();
}
}
}
|
using System.Collections.Generic;
using System.Linq;
using Musher.EchoNest.Extensions;
using Musher.EchoNest.Models;
using Musher.EchoNest.Responses;
using RestSharp;
namespace Musher.EchoNest.Data
{
public class DataProvider : IDataProvider
{
private readonly ApiClient _apiClient;
public DataProvider(string apiUrl, string apiKey)
{
_apiClient = new ApiClient(apiUrl, apiKey);
}
public List<Artist> GetArtists(RecommendationQueryArgs args)
{
var request = _apiClient.CreateRequest("artist/search");
AddSearchArgs(request, args);
request.TryAddQueryParameter("genre", args.Genre);
request.AddQueryParameter("sort", "familiarity-desc");
var response = _apiClient.Execute<ArtistSearchResponse>(request);
return response.Artists;
}
public List<Song> GetSongs(RecommendationQueryArgs args)
{
var request = _apiClient.CreateRequest("song/search");
AddSearchArgs(request, args);
request.AddQueryParameter("sort", "artist_familiarity-desc");
var response = _apiClient.Execute<SongSearchResponse>(request);
return response.Songs;
}
public List<Artist> GetSimilarArtists(string name)
{
var request = _apiClient.CreateRequest("artist/similar");
request.AddQueryParameter("name", name);
var response = _apiClient.Execute<SimilarArtistsResponse>(request);
return response.Artists;
}
public List<Genre> GetGenres()
{
var request = _apiClient.CreateRequest("genre/list");
request.AddQueryParameter("results", "1500"); // There are about 1400 genres
var response = _apiClient.Execute<GenreListResponse>(request);
return response.Genres;
}
public List<Genre> GetGenres(string artistName)
{
var request = _apiClient.CreateRequest("artist/profile");
request.AddQueryParameter("name", artistName);
request.AddQueryParameter("bucket", "genre");
var response = _apiClient.Execute<ArtistProfileResponse>(request);
return response.Artist.Genres;
}
public List<Term> GetTerms(TermType type)
{
var request = _apiClient.CreateRequest("artist/list_terms");
request.AddQueryParameter("type", type.ToString().ToLowerInvariant());
var response = _apiClient.Execute<ArtistTermsResponse>(request);
return response.Terms;
}
public List<Term> GetArtistTerms(string name, TermType type)
{
var request = _apiClient.CreateRequest("artist/terms");
request.AddQueryParameter("name", name);
request.AddQueryParameter("type", type.ToString());
var response = _apiClient.Execute<ArtistTermsResponse>(request);
return response.Terms;
}
public List<Artist> GetArtists(string genre)
{
var request = _apiClient.CreateRequest("genre/artists");
request.AddQueryParameter("name", genre);
var response = _apiClient.Execute<GenreArtistsResponse>(request);
return response.Artists;
}
public List<Artist> SearchArtists(string name, string genre)
{
var request = _apiClient.CreateRequest("artist/search");
request.TryAddQueryParameter("name", name);
request.TryAddQueryParameter("genre", genre);
var response = _apiClient.Execute<ArtistSearchResponse>(request);
return response.Artists;
}
public Artist GetArtistProfile(string name)
{
var request = _apiClient.CreateRequest("artist/profile");
request.AddQueryParameter("name", name);
request.AddQueryParameter("bucket", "genre");
request.AddQueryParameter("bucket", "terms");
request.AddQueryParameter("bucket", "images");
request.AddQueryParameter("bucket", "biographies");
var response = _apiClient.Execute<ArtistProfileResponse>(request);
return response.Artist;
}
public Genre GetGenreProfile(string name)
{
var request = _apiClient.CreateRequest("genre/profile");
request.AddQueryParameter("name", name);
request.AddQueryParameter("bucket", "description");
request.AddQueryParameter("bucket", "urls");
var response = _apiClient.Execute<GenreProfileResponse>(request);
return response.Genres.FirstOrDefault();
}
public List<Genre> GetSimilarGenres(string name)
{
var request = _apiClient.CreateRequest("genre/similar");
request.AddQueryParameter("name", name);
var response = _apiClient.Execute<SimilarGenresResponse>(request);
return response.Genres;
}
private static void AddSearchArgs(RestRequest request, RecommendationQueryArgs args)
{
request.AddQueryParameter("rank_type", "familiarity");
request.TryAddQueryParameter("mood", args.Mood);
request.TryAddQueryParameter("style", args.Style);
if (args.StartYear.HasValue)
{
request.AddQueryParameter("artist_start_year_after", (args.StartYear - 1).ToString());
request.AddQueryParameter("artist_end_year_after", args.StartYear.ToString());
}
if (args.EndYear.HasValue)
{
request.AddQueryParameter("artist_end_year_before", (args.EndYear + 1).ToString());
request.AddQueryParameter("artist_start_year_before", args.EndYear.ToString());
}
}
}
}
|
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using System.Collections;
using System.IO;
using System.Collections.Generic;
/// <summary>
/// The Speech Handler, which takes the input from the UI and passes relevent bits
/// to the character (and it's ImportSpeech).
/// </summary>
public class SpeechHandler : MonoBehaviour {
/// <summary>
/// The Unity Text UI object that the speech should appear on..
/// </summary>
public GameObject textObject;
/// <summary>
/// The canvas of the main HUD (i.e. not the one the speech UI is attatched to).
/// </summary>
public HUDController hudCanvas;
/// <summary>
/// The world position that the text should appear in when the detective is talking.
/// </summary>
public Vector3 detectivePos;
/// <summary>
/// The world position that the text should appear in when the suspect is talking.
/// </summary>
public Vector3 suspectPos;
/// <summary>
/// An array of buttons to be linked to the detective's traits.
/// </summary>
public Button[] traitButtonArray;
/// <summary>
/// The active detective.
/// </summary>
public Detective activeDet;
/// <summary>
/// The active story.
/// </summary>
public Story activeStory;
/// <summary>
/// An array containing any UI elements that should be hidden when the speech UI is up.
/// </summary>
public GameObject[] otherUIElements;
/// <summary>
/// The panel object that holds the
/// </summary>
public GameObject speechPanel;
/// <summary>
/// The text object that shows the currently selected clue.
/// </summary>
public Text clueText;
/// <summary>
/// Any speech UI elements that should be hidden during the actual conversatsion.
/// </summary>
public GameObject[] speechUIElements;
/// <summary>
/// The button that this script is attatched to.
/// </summary>
private Button parentButton;
/// <summary>
/// The text of the text object that shows the speech.
/// </summary>
private Text actualText;
/// <summary>
/// The actual speech files attatched to the character in the scene.
/// </summary>
private ImportSpeech speechRef;
/// <summary>
/// The name of the currently/last active branch of discussion.
/// </summary>
private string branchName;
/// <summary>
/// A reference to the inventory of the detective.
/// </summary>
private Inventory playerInv;
/// <summary>
/// The character active in the current scene.
/// </summary>
private Character charInScene;
/// <summary>
/// The canvas of the Speech UI.
/// </summary>
private GameObject parentCanvas;
/// <summary>
/// The inventory index of the currently selected item.
/// </summary>
private int clueIndex = 0;
private Clue activeClue;
/// <summary>
/// Start this instance.
/// </summary>
void Start (){
waiting ();
//TODO: REMOVE STUPID CAPITALIZATION
// Assign various variables from objects in scene.
activeDet = FindObjectOfType<Detective> ();
activeStory = FindObjectOfType<Story> ();
playerInv = FindObjectOfType<Inventory> ();
hudCanvas = FindObjectOfType<HUDController> ();
string sceneName = SceneManager.GetActiveScene ().name;
int roomNo = (sceneName[sceneName.Length-1]) - '1';
Debug.Log (roomNo);
List<GameObject> listOfCharsInRoom = activeStory.getCharactersInRoom (roomNo);
actualText = textObject.GetComponentInChildren<Text> ();
// Try to access the data from the character in the scene.
try{
charInScene = listOfCharsInRoom [0].GetComponent<Character> ();
speechRef = charInScene.GetComponentInChildren<ImportSpeech> ();
charInScene.speechUI = this;
// This will fail if there is no character in scene,
// but that's fine because there's no access to the UI then.
} catch {}
// A bit more object fetching...
parentCanvas = GameObject.Find ("SpeechUI");
parentCanvas.SetActive (false);
gameObject.SetActive(false);
string[] strTraits = new string[activeDet.traits.Length];
// Set the values on the trait buttons from the detective traits.
for (int i = 0; i < strTraits.Length; i++) {
strTraits [i] = activeStory.getTraitString (activeDet.traits [i]);
Debug.Log (traitButtonArray [i].name);
Text buttonText = traitButtonArray [i].GetComponentInChildren<Text> ();
buttonText.text = strTraits [i];
traitButtonArray [i].name = strTraits [i];
}
}
// This just delays the setup for an update to make sure everything is initialised.
// You could _probably_ get rid of it but it's here for safety.
IEnumerator waiting(){
yield return new WaitForFixedUpdate ();
}
/// <summary>
/// Turns on the Speech UI, pauses the game.
/// </summary>
public void turnOnSpeechUI(){
if (parentCanvas.gameObject.activeSelf == false) {
// If the character is in a state where he can be talked to...
if (charInScene.canBeTalkedTo == true) {
// Turn off all of the non-speech UI elements...
foreach (GameObject forObj in otherUIElements) {
forObj.gameObject.SetActive (false);
}
speechPanel.SetActive (false);
// Then turn on all the speech UI stuff.
updateClueName (playerInv.collectedClueNames [clueIndex]);
parentCanvas.SetActive (true);
hudCanvas.loadPanelAndPause (parentCanvas);
if (charInScene.hasBeenTalkedTo == false) {
charInScene.hasBeenTalkedTo = true;
startBranch ("INTRO");
}
// Get the collider of the character and turn it off.
BoxCollider BoxCol = charInScene.GetComponent<BoxCollider> ();
BoxCol.enabled = false;
// If the character can't be talked to, the player will need to find another clue.
} else {
Debug.Log ("You need to find another clue");
}
// And if the speech UI is already on, we can't turn it doubly on, so do nothing.
} else {
Debug.Log ("Tried to turn on speech UI, but was already on");
}
}
/// <summary>
/// Turns off the speech UI, unpauses the game.
/// </summary>
public void turnOffSpeechUI(){
if (parentCanvas.gameObject.activeSelf == true) {
// Turn on all the non-speech UI elements first.
foreach (GameObject ForObj in otherUIElements) {
ForObj.gameObject.SetActive (true);
}
//Then turn off all of the speech UI elements.
clueIndex = 0;
parentCanvas.SetActive (false);
hudCanvas.hidePanelAndResume (parentCanvas);
// Re-enable the collider of the character..
BoxCollider boxCol = charInScene.GetComponent<BoxCollider> ();
boxCol.enabled = true;
// If we accused them, then turn it back off.
try{
if(branchName.Substring(0,6) == "Accuse"){
boxCol.enabled=false;
}
}
catch{}
//Obviously, you can't turn off a UI if it's already off, so do nothing if so.
} else {
Debug.Log ("Tried to turn off speech UI but it was already off.");
}
}
/// <summary>
/// Starts a branch from a trait button.
/// </summary>
/// <param name="sendingButton">The button pressed to start the branch.</param>
public void questionBranch(Button sendingButton){
// Set the branch name to be the trait combined with the item dev name.
branchName = sendingButton.name;
speechRef.itemIn = activeClue;
string longName = branchName + "-" + playerInv.collectedClueNames [clueIndex];
// See if the character has a branch for the combination of trait and item.
try{
speechRef.setBranch (longName);
branchName = longName;
}
// If they don't just go with the trait-only branch.
catch{
speechRef.setBranch(branchName);
}
// Let the character make any required changes.
charInScene.preSpeech (branchName);
// Turn on the text and continue button...
gameObject.SetActive(true);
textObject.SetActive(true);
speechPanel.SetActive (true);
// And turn off everything else.
foreach (Button forButton in traitButtonArray) {
forButton.gameObject.SetActive (false);
}
foreach (GameObject forButton in speechUIElements) {
forButton.gameObject.SetActive (false);
}
// Then display the first line of the speech.
OnClick ();
}
/// <summary>
/// Starts the branch from a string in lieu of a button.
/// </summary>
/// <param name="branchIn">The name of the branch to be started.</param>
public void startBranch(string branchIn){
// Set the name of the branch.
branchName = branchIn;
// Initialise the branch.
speechRef.itemIn = activeClue;
speechRef.setBranch(branchName);
// Let the character set up...
charInScene.preSpeech (branchName);
// Then turn on the text and continue button...
gameObject.SetActive(true);
textObject.SetActive(true);
speechPanel.SetActive (true);
// And turn off everything else.
foreach (Button forButton in traitButtonArray) {
forButton.gameObject.SetActive (false);
}
foreach (GameObject forButton in speechUIElements) {
forButton.gameObject.SetActive (false);
}
// Then display the first line of text.
OnClick ();
}
/// <summary>
/// Increments the clue index, then updates the displayed clue name.
/// </summary>
public void nextClue (){
clueIndex += 1;
if (clueIndex >= playerInv.collectedClueNames.Count) {
clueIndex = 0;
}
updateClueName (playerInv.collectedClueNames [clueIndex]);
}
/// <summary>
/// Decrements the clue index, then updates the displayed clue name
/// </summary>
public void prevClue (){
clueIndex -= 1;
if (clueIndex < 0) {
clueIndex = playerInv.collectedClueNames.Count - 1;
}
updateClueName (playerInv.collectedClueNames [clueIndex]);
}
/// <summary>
/// Updates the name of the clue on the UI
/// </summary>
/// <param name="ClueName">The dev name of the clue to be shown.</param>
void updateClueName (string ClueName){
activeClue = activeStory.getClueInformation (ClueName).GetComponent<Clue> ();
clueText.text = activeClue.longName;
}
/// <summary>
/// Accuse the character in the scene of being a murderer.
/// </summary>
public void accuse (){
// When accusing, we check if the detective has the motive clue and murder weapon...
bool hasMotiveClue = false;
bool hasMurderWeapon = false;
// As well as if the character is actually the murderer.
bool isMurderer = charInScene.isMurderer;
string branchName = "";
// Go through each clue to see if it's the murder weapon or motive clue.
foreach (string testClue in playerInv.collectedClueNames) {
if (testClue == activeStory.murderWeapon) {
hasMurderWeapon = true;
}
if (testClue == activeStory.motiveClue) {
hasMotiveClue = true;
}
}
// Then select a branch accordingly.
if (hasMotiveClue == false && hasMurderWeapon == false) {
branchName = "Accuse-NoItems";
} else if (hasMotiveClue == false) {
branchName = "Accuse-Motive";
} else if (hasMurderWeapon == false) {
branchName = "Accuse-Weapon";
} else if (isMurderer == false) {
branchName = "Accuse-WrongChar";
} else {branchName = "Accuse-Right";}
// Whatever branch gets selected, we can then start it.
startBranch(branchName);
}
/// <summary>
/// Displays the next line of text in the branch, or returns to the main speech UI.
/// </summary>
public void OnClick (){
// Get the next line of the branch.
string nextLine = speechRef.nextLine ();
if (nextLine != null) {
// Display it and put it in position.
actualText.text = nextLine.Substring(1, nextLine.Length - 1);
if (nextLine [0].ToString () == "$") {
speechPanel.transform.localPosition = detectivePos;
} else {
speechPanel.transform.localPosition = suspectPos;
}
// If the string was null then we have hit the end of the branch.
} else {
// Let the character update if needed.
charInScene.postSpeech (branchName);
// Disable the text and continue button, turn everything else on...
gameObject.SetActive(false);
speechPanel.SetActive (false);
foreach (Button forButton in traitButtonArray) {
forButton.gameObject.SetActive (true);
}
foreach (GameObject forButton in speechUIElements) {
forButton.gameObject.SetActive (true);
}
// If the branch was an accuse branch, we then close the speech UI.
try{
if(branchName.Substring(0,6) == "Accuse"){
turnOffSpeechUI();
}
}
// This is in a try because if the branch name is smaller than 6 characters
// it will raise an exception, but we know it's not Accuse so we can just
// carry on our merry way.
catch{}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace HackerRank_HomeCode
{
//https://www.ideserve.co.in/learn/word-break-problem
public class DP_WordBreakProblem
{
static HashSet<String> dictionary = new HashSet<String>(new string[] { "arrays", "dynamic", "heaps", "IDeserve", "learn", "learning", "linked", "list",
"platform", "programming", "stacks", "trees" });
public void TestWB()
{
if (hasValidWords("IDeservelearningplatform"))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}
}
public bool hasValidWords(String words)
{
if (words == null || words.Length == 0)
{
return true;
}
int n = words.Length;
bool[] validWords = new bool[n];
for (int i = 0; i < n; i++)
{
if (i + 1 < n)
{
if (dictionary.Contains(words.Substring(0, i + 1)))
{
validWords[i] = true;
}
}
if (validWords[i] == true & (i == n - 1))
{
return true;
}
if (validWords[i] == true)
{
int z = 1;
for (int j = i + 1; j < n; j++)
{
if (dictionary.Contains(words.Substring(i + 1, z)))
{
validWords[j] = true;
}
z++;
if (j == n - 1 && validWords[j] == true)
{
return true;
}
}
}
}
return false;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace UrTLibrary.Shaders.Directives.Attributes
{
public sealed class WaveFormFunctionType
{
public static readonly WaveFormFunctionType Sin = new WaveFormFunctionType("sin");
public static readonly WaveFormFunctionType Triangle = new WaveFormFunctionType("triangle");
public static readonly WaveFormFunctionType Square = new WaveFormFunctionType("square");
public static readonly WaveFormFunctionType SawTooth = new WaveFormFunctionType("sawTooth");
public static readonly WaveFormFunctionType InverseSawTooth = new WaveFormFunctionType("inverseSawTooth");
public static readonly WaveFormFunctionType Noise = new WaveFormFunctionType("noise");
public string Value { get; private set; }
private WaveFormFunctionType(string value)
{
this.Value = value;
}
public override string ToString()
{
return this.Value;
}
}
}
|
using System.Text.RegularExpressions;
namespace LoveLivePractice.Api {
[System.Serializable]
public class ApiLiveMap {
public string audiofile;
public int speed;
public ApiMapNote[] lane;
public static string Transform(string json) {
string result = Regex.Replace(json, @"\[\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\],\[([^\[\]]*)\]\]", @"[$1,$2,$3,$4,$5,$6,$7,$8,$9]");
// Fix empty lanes
result = Regex.Replace(result, @",+", @",");
result = Regex.Replace(result, @"\[,", @"[");
result = Regex.Replace(result, @"\,]", @"]");
return result;
}
public LiveNote[] GetLiveNotes(AxisTransformer2 transformer) {
var list = new System.Collections.Generic.List<LiveNote>();
foreach (var note in lane) {
list.Add(new LiveNote(
transformer(note.lane, 0),
note.starttime / 1000f,
note.parallel,
note.longnote));
}
return list.ToArray();
}
}
[System.Serializable]
public class ApiMapNote : System.IComparable<ApiMapNote> {
public int lane;
public float starttime, endtime;
public bool longnote, parallel, hold;
public int CompareTo(ApiMapNote other) {
return starttime.CompareTo(other.starttime);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using SysLogs.Models;
namespace SysLogs.Interfaces
{
public interface IManagementService
{
//Send unfiltered list of logs from database (Maybe implement pagination or some kind of arbitrary max list size)
public Task<List<SystemLog>> GetAllSystemLogs();
//Send Filtered list of logs
public Task<List<SystemLog>> GetFilteredSystemLogs(Filter filter);
}
}
|
using Microsoft.EntityFrameworkCore;
using SafeSpace.core.Models;
using System;
using System.Collections.Generic;
using System.Text;
namespace SafeSpace.core.Data
{
public class SafeSpaceContext : DbContext
{
public SafeSpaceContext(DbContextOptions<SafeSpaceContext> options) :base(options)
{
}
public DbSet<Organization> Organizations { get; set; }
public DbSet<AppUser> AppUsers { get; set; }
public DbSet<AppUserReport> AppUserReports { get; set; }
public DbSet<ReportItemDefinition> ReportItemDefinitions { get; set; }
public DbSet<RiskDefinition> RiskDefinitions { get; set; }
public DbSet<AppUserContact> AppUserContacts { get; set; }
}
}
|
namespace Triton.Bot
{
using System;
using System.Collections.ObjectModel;
using System.Linq.Expressions;
using System.Reflection;
using Triton.Bot.Settings;
using Triton.Common;
public class CustomDeckCache : JsonSettings
{
private long long_0;
private ObservableCollection<string> observableCollection_0;
private string string_1;
private string string_2;
public CustomDeckCache(long id) : base(GetFileNameFor(id))
{
if (this.observableCollection_0 == null)
{
this.observableCollection_0 = new ObservableCollection<string>();
}
}
public static string GetFileNameFor(long id)
{
string[] subPathParts = new string[] { Configuration.Instance.Name, "CustomDecks", string.Format("{0}.json", id) };
return JsonSettings.GetSettingsFilePath(subPathParts);
}
public ObservableCollection<string> CardIds
{
get
{
return this.observableCollection_0;
}
set
{
if (!value.Equals(this.observableCollection_0))
{
this.observableCollection_0 = value;
base.NotifyPropertyChanged<ObservableCollection<string>>(Expression.Lambda<Func<ObservableCollection<string>>>(Expression.Property(Expression.Constant(this, typeof(CustomDeckCache)), (MethodInfo) methodof(CustomDeckCache.get_CardIds)), new ParameterExpression[0]));
}
}
}
public long DeckId
{
get
{
return this.long_0;
}
set
{
if (!value.Equals(this.long_0))
{
this.long_0 = value;
base.NotifyPropertyChanged<long>(Expression.Lambda<Func<long>>(Expression.Property(Expression.Constant(this, typeof(CustomDeckCache)), (MethodInfo) methodof(CustomDeckCache.get_DeckId)), new ParameterExpression[0]));
}
}
}
public string HeroCardId
{
get
{
return this.string_2;
}
set
{
if (!value.Equals(this.string_2))
{
this.string_2 = value;
base.NotifyPropertyChanged<string>(Expression.Lambda<Func<string>>(Expression.Property(Expression.Constant(this, typeof(CustomDeckCache)), (MethodInfo) methodof(CustomDeckCache.get_HeroCardId)), new ParameterExpression[0]));
}
}
}
public string Name
{
get
{
return this.string_1;
}
set
{
if (!value.Equals(this.string_1))
{
this.string_1 = value;
base.NotifyPropertyChanged<string>(Expression.Lambda<Func<string>>(Expression.Property(Expression.Constant(this, typeof(CustomDeckCache)), (MethodInfo) methodof(CustomDeckCache.get_Name)), new ParameterExpression[0]));
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using Epsagon.Dotnet.Instrumentation.Handlers.SQS.Operations;
namespace Epsagon.Dotnet.Instrumentation.Handlers.SQS {
public class SQSOperationsFactory : BaseFactory<string, IOperationHandler> {
public SQSOperationsFactory() : base(null) {
}
protected override Dictionary<string, Func<IOperationHandler>> Operations => new Dictionary<string, Func<IOperationHandler>> {
{ "SendMessageRequest", () => new SendMessageRequestHandler() },
{ "ReceiveMessageRequest", () => new ReceiveMessageRequestHandler() }
};
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Promact.Oauth.Server.Constants;
namespace Promact.Oauth.Server.Services
{
public class SecurityHeadersAttribute : ActionFilterAttribute
{
private readonly IStringConstant _stringConstant;
public SecurityHeadersAttribute(IStringConstant stringConstant)
{
_stringConstant = stringConstant;
}
public override void OnResultExecuting(ResultExecutingContext context)
{
var result = context.Result;
if (result is ViewResult)
{
if (!context.HttpContext.Response.Headers.ContainsKey(_stringConstant.XContentTypeOptions))
{
context.HttpContext.Response.Headers.Add(_stringConstant.XContentTypeOptions, _stringConstant.Nosniff);
}
if (!context.HttpContext.Response.Headers.ContainsKey(_stringConstant.XFrameOptions))
{
context.HttpContext.Response.Headers.Add(_stringConstant.XFrameOptions, _stringConstant.Sameorigin);
}
var csp = _stringConstant.DefaultSrcSelf;
// once for standards compliant browsers
if (!context.HttpContext.Response.Headers.ContainsKey(_stringConstant.ContentSecurityPolicy))
{
context.HttpContext.Response.Headers.Add(_stringConstant.ContentSecurityPolicy, csp);
}
// and once again for IE
if (!context.HttpContext.Response.Headers.ContainsKey(_stringConstant.XContentSecurityPolicy))
{
context.HttpContext.Response.Headers.Add(_stringConstant.XContentSecurityPolicy, csp);
}
}
}
}
}
|
using Infra;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
namespace ConsoleTestProj
{
/// <summary>
///This is a test class for LinkListNodeTest and is intended
///to contain all LinkListNodeTest Unit Tests
///</summary>
[TestClass()]
public class LinkListNodeTest
{
private TestContext testContextInstance;
/// <summary>
///Gets or sets the test context which provides
///information about and functionality for the current test run.
///</summary>
public TestContext TestContext
{
get
{
return testContextInstance;
}
set
{
testContextInstance = value;
}
}
#region Additional test attributes
//
//You can use the following additional attributes as you write your tests:
//
//Use ClassInitialize to run code before running the first test in the class
//[ClassInitialize()]
//public static void MyClassInitialize(TestContext testContext)
//{
//}
//
//Use ClassCleanup to run code after all tests in a class have run
//[ClassCleanup()]
//public static void MyClassCleanup()
//{
//}
//
//Use TestInitialize to run code before running each test
//[TestInitialize()]
//public void MyTestInitialize()
//{
//}
//
//Use TestCleanup to run code after each test has run
//[TestCleanup()]
//public void MyTestCleanup()
//{
//}
//
#endregion
/// <summary>
///A test for ReverseLinkListIterative
///</summary>
[TestMethod()]
public void ReverseLinkListIterativeTest()
{
int[] inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
LinkListNode head = LinkListNode.CreateLinkList(inputArray);
LinkListNode actual;
actual = LinkListNode.ReverseLinkListIterative(head);
for (int i = 6; i >= 0; i--)
{
Assert.AreEqual(inputArray[i], actual.Value);
actual = actual.Next;
}
head = new LinkListNode(); head.Value = 1;
actual = LinkListNode.ReverseLinkListIterative(head);
Assert.IsNull(actual.Next, "should be only 1 element and next of the first node should be null");
Assert.AreEqual(1, actual.Value, "value should be 1");
head = null;
actual = LinkListNode.ReverseLinkListIterative(head);
Assert.IsNull(actual, "should be only 0 element, the first node should be null");
}
/// <summary>
///A test for RevertLinkListRecursive
///</summary>
[TestMethod()]
public void RevertLinkListRecursiveTest()
{
int[] inputArray = new int[] { 1, 2, 3, 4, 5, 6, 7 };
LinkListNode head = LinkListNode.CreateLinkList(inputArray);
LinkListNode actual;
actual = LinkListNode.RevertLinkListRecursive(head);
for (int i = 6; i >= 0; i--)
{
Assert.AreEqual(inputArray[i], actual.Value);
actual = actual.Next;
}
head = new LinkListNode(); head.Value = 1;
actual = LinkListNode.RevertLinkListRecursive(head);
Assert.IsNull(actual.Next, "should be only 1 element and next of the first node should be null");
Assert.AreEqual(1, actual.Value, "value should be 1");
head = null;
actual = LinkListNode.RevertLinkListRecursive(head);
Assert.IsNull(actual, "should be only 0 element, the first node should be null");
}
}
}
|
using System;
using Microsoft.Xna.Framework;
namespace MonoGame.Extended.Timers
{
public class CountdownTimer : GameTimer
{
public CountdownTimer(double intervalSeconds)
: base(intervalSeconds)
{
}
public CountdownTimer(TimeSpan interval)
: base(interval)
{
}
public event EventHandler TimeRemainingChanged;
public event EventHandler Completed;
public TimeSpan TimeRemaining { get; private set; }
protected override void OnStopped()
{
CurrentTime = TimeSpan.Zero;
}
protected override void OnUpdate(GameTime gameTime)
{
TimeRemaining = Interval - CurrentTime;
TimeRemainingChanged.Raise(this, EventArgs.Empty);
if (CurrentTime >= Interval)
{
State = TimerState.Completed;
CurrentTime = Interval;
TimeRemaining = TimeSpan.Zero;
Completed.Raise(this, EventArgs.Empty);
}
}
}
}
|
using Serenity;
using Serenity.Data;
using Serenity.Services;
using System;
using System.Data;
using MyRequest = Serenity.Services.SaveRequest<ARLink.Default.EmployeeRow>;
using MyResponse = Serenity.Services.SaveResponse;
using MyRow = ARLink.Default.EmployeeRow;
namespace ARLink.Default
{
public interface IEmployeeSaveHandler : ISaveHandler<MyRow, MyRequest, MyResponse> {}
public class EmployeeSaveHandler : SaveRequestHandler<MyRow, MyRequest, MyResponse>, IEmployeeSaveHandler
{
public EmployeeSaveHandler(IRequestContext context)
: base(context)
{
}
}
} |
using System.Text;
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using System.Net.Http;
using System.Drawing;
using System.Collections.ObjectModel;
using System.Xml;
using System.ComponentModel;
using System.Reflection;
namespace LinnworksAPI
{ [JsonConverter(typeof(StringEnumConverter))]
public enum ReturnType
{ UNKNOWN,
RETURN,
RETURNREFUND,
EXCHANGE,
RESEND,
RETURNBOOKING,
EXCHANGEBOOKING,
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RepositoryAndUnitOfWorkPatterns.Domain;
namespace RepositoryAndUnitOfWorkPatterns.Repositories.Interfaces
{
public interface ICustomerRepository : IRepository<Customer>
{
Customer GetCustomerWithOrders(int idCustomer);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Reference added to make WCF happen
using System.ServiceModel;
namespace DuplexServicesLib
{
[ServiceBehavior(
ConcurrencyMode = ConcurrencyMode.Single,
InstanceContextMode = InstanceContextMode.PerCall)]
public class DuplexServices : IDuplexServices
{
#region
private const string HELLOMESSAGE = "{0} has been connected....";
#endregion
#region Private varible
private static List<IServicesCallBack> _clientList = new List<IServicesCallBack>();
#endregion
#region Properties
public static List<IServicesCallBack> Clients
{
get
{
return _clientList;
}
}
#endregion
#region Ctor
public DuplexServices()
{
}
#endregion
#region Operation Contract
public void JoinNetWork(string clientInfo)
{
// Subscribe the client to the netWork
IServicesCallBack joinedClient = OperationContext.Current.GetCallbackChannel<IServicesCallBack>();
//add connected Client
if (!_clientList.Contains(joinedClient))
{
_clientList.Add(joinedClient);
//send message back to client
joinedClient.ShowMessageFromServer(string.Format(HELLOMESSAGE, clientInfo));
}
}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum AttackType { Null, Jab, LegSweep, Aerial, ArmourBreak, HeavyJab };
public enum Attackdirection { Forward, Low, Aerial, Down };
public enum HitBoxScale { Jab, ArmourBreak, Aerial };
public enum FollowDes { Centre, RightHand, RightElbow, LeftHand, LeftElbow , RightFoot, LeftFoot}
public class Hitbox : MonoBehaviour
{
private float gaugeDamageValue = 1.5f;
public bool viewHitBox;
public HitBoxScale _hitBoxScale;
public Attackdirection _attackDir;
public AttackType _attackType;
private FollowDes _followDes;
MeshRenderer meshRenderer;
Collider hitboxCollider;
public Transform HeadArmourPosition, ChestArmourPosition, LegArmourPosition;
[SerializeField] float LegLocationOffset;
[SerializeField] private float freezeCounter;
[SerializeField] private float freezeStep;
[SerializeField] private float freezeMaxValue;
public PlayerActions animantionManager;
public Animator anim;
[SerializeField] Player player;
PlayerInputHandler playerInput;
HitBoxManager hitBoxManager;
[SerializeField] private bool freezeCharacter;
public List<GameObject> HitHurtBoxes = new List<GameObject>();
public List<GameObject> HurtboxList = new List<GameObject>();
public int armIndex;
public GameObject tipHitBox, midHitBox;
public GameObject rightHand, leftHand,rightElbow, leftElbow, rightFoot, leftFoot, rightKnee, leftKnee, waist;
public ParticleSystem hitParticle;
public ParticleSystem dustHitParticle;
[SerializeField] ParticleManager particleManager;
Vector3 hitDirection;
public void AddHurtBoxToList(GameObject obj)
{
HurtboxList.Add(obj);
}
private void Awake()
{
hitboxCollider = GetComponent<Collider>();
meshRenderer = GetComponent<MeshRenderer>();
hitBoxManager = GetComponent<HitBoxManager>();
playerInput = GetComponentInParent<PlayerInputHandler>();
player = GetComponentInParent<Player>();
}
private void Start()
{
}
private void FixedUpdate()
{
AttackTypeCall();
HitBoxSize();
GaugeDamage();
}
void AttackTypeCall()
{
switch(_attackType)
{
case AttackType.Jab:
FollowHand();
break;
case AttackType.LegSweep:
FollowHand();
break;
case AttackType.Aerial:
FollowRightElbow();
break;
case AttackType.ArmourBreak:
FollowCenter();
break;
case AttackType.HeavyJab:
FollowHand();
break;
}
}
private void GaugeDamage()
{
switch (_attackType)
{
case AttackType.Jab:
gaugeDamageValue = 2.5f;
break;
case AttackType.HeavyJab:
gaugeDamageValue = 4;
break;
case AttackType.Aerial:
gaugeDamageValue = 3;
break;
case AttackType.LegSweep:
gaugeDamageValue = 3;
break;
case AttackType.ArmourBreak:
gaugeDamageValue = 5;
break;
}
}
void HitBoxSize()
{
switch (_hitBoxScale)
{
case HitBoxScale.Jab:
transform.localScale = new Vector3(0.4f,0.4f,0.4f);
break;
case HitBoxScale.ArmourBreak:
transform.localScale = new Vector3(1.5f,1.5f,1.5f);
break;
case HitBoxScale.Aerial:
transform.localScale = new Vector3(0.8f, 0.8f, 0.8f);
break;
}
}
void HitboxPosition()
{
switch(_followDes)
{
case FollowDes.Centre:
break;
case FollowDes.RightHand:
tipHitBox.gameObject.transform.position = new Vector3(rightHand.transform.position.x, rightHand.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = rightHand.transform.rotation;
break;
case FollowDes.RightElbow:
tipHitBox.gameObject.transform.position = new Vector3(rightElbow.transform.position.x, rightElbow.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = rightElbow.transform.rotation;
break;
case FollowDes.RightFoot:
tipHitBox.gameObject.transform.position = new Vector3(rightFoot.transform.position.x, rightFoot.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = rightFoot.transform.rotation;
break;
case FollowDes.LeftHand:
tipHitBox.gameObject.transform.position = new Vector3(leftHand.transform.position.x, leftHand.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = leftHand.transform.rotation;
break;
case FollowDes.LeftElbow:
break;
case FollowDes.LeftFoot:
tipHitBox.gameObject.transform.position = new Vector3(leftFoot.transform.position.x, leftFoot.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = leftFoot.transform.rotation;
break;
}
}
public void FollowCenter()
{
tipHitBox.gameObject.transform.position = waist.transform.position;
tipHitBox.gameObject.transform.rotation = waist.transform.rotation;
}
public void FollowHand()
{
if (armIndex == 0)
{
tipHitBox.gameObject.transform.position = new Vector3(leftHand.transform.position.x, leftHand.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = leftHand.transform.rotation;
}
else if (armIndex == 1)
{
tipHitBox.gameObject.transform.position = new Vector3(rightHand.transform.position.x, rightHand.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = rightHand.transform.rotation;
}
}
public void FollowRightElbow()
{
tipHitBox.gameObject.transform.position = new Vector3(rightElbow.transform.position.x, rightElbow.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = rightElbow.transform.rotation;
}
public void FollowRightFoot()
{
tipHitBox.gameObject.transform.position = new Vector3(rightFoot.transform.position.x, rightFoot.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = rightFoot.transform.rotation;
}
public void FollowLeftFoot()
{
tipHitBox.gameObject.transform.position = new Vector3(leftFoot.transform.position.x, leftFoot.transform.position.y, 0);
tipHitBox.gameObject.transform.rotation = leftFoot.transform.rotation;
}
public Vector3 KnockBackStrength()
{
switch (_attackType)
{
case AttackType.Jab:
return new Vector3(player.GetFacingDirection() * 30, 3, 0);
case AttackType.LegSweep:
return new Vector3(player.GetFacingDirection() * 20, 7, 0);
case AttackType.Aerial:
return new Vector3(player.GetFacingDirection() * 35, -0.5f, 0);
case AttackType.ArmourBreak:
return new Vector3(player.GetFacingDirection() * 50, 2, 0);
case AttackType.HeavyJab:
return new Vector3(player.GetFacingDirection() * 40, 2, 0);
}
return new Vector3(player.GetFacingDirection() * 5, 2, 0);
}
public void ShowHitBoxes()
{
//meshRenderer.enabled = true;
hitboxCollider.enabled = true;
}
public void HideHitBoxes()
{
meshRenderer.enabled = false;
hitboxCollider.enabled = false;
}
private void ResetMoveValues(Player DefendingPlayer, Player attackingPlayer)
{
DefendingPlayer.changeHeavyMoveValue(AttackType.HeavyJab ,600);
DefendingPlayer.changeHeavyMoveValue(AttackType.Jab, 200);
}
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Ground"))
{
return;
}
if (other.gameObject.CompareTag("Hurtbox"))
{
var tempDefendingPlayer = other.GetComponentInParent<Player>();
var tempAttackingPlayer = GetComponentInParent<Player>();
var tempDefendingPlayerHitBox = other.GetComponentInChildren<Hitbox>();
var temptArmourCheck = other.GetComponentInParent<ArmourCheck>();
HurtBox tempHurtBox = other.gameObject.GetComponent<HurtBox>();
var tempHitPosiiton = other.transform.position;
tempHurtBox.TurnOnHitBoxHit();
Debug.Log("Hit Character");
if (tempDefendingPlayer.Blocking == true)
{
if(_attackType != AttackType.LegSweep)
{
ResetMoveValues(tempDefendingPlayer, tempAttackingPlayer);
HideHitBoxes();
return;
}
else
{
DamagingPlayer(tempDefendingPlayer, tempAttackingPlayer, temptArmourCheck, tempHurtBox);
tempDefendingPlayer.HideHitBoxes();
//tempDefendingPlayer.ResetCharacterMaterialToStandard();
}
}
else
{
DamagingPlayer(tempDefendingPlayer, tempAttackingPlayer, temptArmourCheck, tempHurtBox);
tempDefendingPlayer.HideHitBoxes();
}
}
}
private void DamagingPlayer(Player DefendingPlayer, Player attackingPlayer, ArmourCheck armourCheck, HurtBox hurtBox)
{
DefendingPlayer.SetAddforceZero();
DefendingPlayer.changeHeavyMoveValue(AttackType.HeavyJab ,0);
DefendingPlayer.changeHeavyMoveValue(AttackType.Jab, 0);
ApplyDamageToPlayer(DefendingPlayer, attackingPlayer, _attackType);
if (hurtBox.BodyLocation == LocationTag.Chest)
{
Hitbox DefendingHitbox = DefendingPlayer.GetComponentInChildren<Hitbox>();
Transform hitLocation = DefendingHitbox.ChestArmourPosition;
DefendingPlayer.TakeDamageOnGauge(gaugeDamageValue, ArmourCheck.ArmourPlacement.Chest, _attackType, hitLocation.position);
Instantiate(hitParticle, transform.position, transform.rotation);
//Instantiate(dustHitParticle, transform.position, transform.rotation);
}
else if (hurtBox.BodyLocation == LocationTag.Legs)
{
Hitbox DefendingHitbox = DefendingPlayer.GetComponentInChildren<Hitbox>();
Transform hitLocation = DefendingHitbox.LegArmourPosition;
DefendingPlayer.TakeDamageOnGauge(gaugeDamageValue, ArmourCheck.ArmourPlacement.Legs, _attackType, (hitLocation.position + new Vector3(LegArmourPosition.position.x, (LegArmourPosition.position.y - 1), LegArmourPosition.position.z)));
Instantiate(hitParticle, transform.position, transform.rotation);
//Instantiate(dustHitParticle, transform.position, transform.rotation);
}
else if(hurtBox.BodyLocation == LocationTag.Head)
{
Hitbox DefendingHitbox = DefendingPlayer.GetComponentInChildren<Hitbox>();
Transform hitLocation = DefendingHitbox.HeadArmourPosition;
DefendingPlayer.TakeDamageOnGauge(gaugeDamageValue, ArmourCheck.ArmourPlacement.Head, _attackType, hitLocation.position);
Instantiate(hitParticle, transform.position, transform.rotation);
}
}
void ApplyDamageToPlayer(Player defendingPlayer, Player attackingPlayer, AttackType attackType)
{
defendingPlayer.FreezeCharacterBeingAttacked(KnockBackStrength(), attackingPlayer.GetFacingDirection());
attackingPlayer.FreezeCharacterAttacking();
if(attackType == AttackType.Aerial || attackType == AttackType.ArmourBreak || attackType == AttackType.HeavyJab)
{
defendingPlayer.KnockDown();
}
else if(attackType == AttackType.LegSweep)
{
defendingPlayer.KnockDown();
}
else if(attackType == AttackType.Jab)
{
defendingPlayer.JabKnockBack();
}
ResetMoveValues(defendingPlayer, attackingPlayer);
HideHitBoxes();
}
}
|
using System.Collections.Generic;
namespace Grubber.Web.Models
{
public class StateProvince
{
public StateProvince()
{
Stores = new HashSet<Store>();
}
// Primary key
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
// Navigation property
public virtual ICollection<Store> Stores { get; private set; }
}
} |
using System;
using System.Collections.Generic;
namespace JqD.Data.Repository
{
public abstract class RepositoryBase<T> : EntityBaseRepository<T>, IRepositoryBase<T> where T : class
{
protected override SqlStrings Sql { get; set; }
protected override Func<string, Dictionary<string, object>, SqlBuilder.Template> QueryByPageSql => GenerateQueryByPageSql;
protected RepositoryBase(ISqlDatabaseProxy databaseProxy):base(databaseProxy)
{
}
protected virtual SqlBuilder.Template GenerateQueryByPageSql(string queryByPageTemplate, Dictionary<string, object> querys)
{
//You have to override this, otherwise it will throw exception
throw new NotImplementedException();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace vpui2
{
public class Easing
{
// no easing, no acceleration
public static double linear(double t) { return t; }
// accelerating from zero velocity
public static double easeInQuad(double t) { return t * t; }
// decelerating to zero velocity
public static double easeOutQuad(double t) { return t * (2 - t); }
// acceleration until halfway, then deceleration
public static double easeInOutQuad(double t) { return t < .5 ? 2 * t * t : -1 + (4 - 2 * t) * t; }
// accelerating from zero velocity
public static double easeInCubic(double t) { return t * t * t; }
// decelerating to zero velocity
public static double easeOutCubic(double t) { return (--t) * t * t + 1; }
// acceleration until halfway, then deceleration
public static double easeInOutCubic(double t) { return t < .5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1; }
// accelerating from zero velocity
public static double easeInQuart(double t) { return t * t * t * t; }
// decelerating to zero velocity
public static double easeOutQuart(double t) { return 1 - (--t) * t * t * t; }
// acceleration until halfway, then deceleration
public static double easeInOutQuart(double t) { return t < .5 ? 8 * t * t * t * t : 1 - 8 * (--t) * t * t * t; }
// accelerating from zero velocity
public static double easeInQuint(double t) { return t * t * t * t * t; }
// decelerating to zero velocity
public static double easeOutQuint(double t) { return 1 + (--t) * t * t * t * t; }
// acceleration until halfway, then deceleration
public static double easeInOutQuint(double t) { return t < .5 ? 16 * t * t * t * t * t : 1 + 16 * (--t) * t * t * t * t; }
}
}
|
using System.Collections.ObjectModel;
namespace MonoGame.Extended.SceneGraphs
{
public class SceneEntityCollection : Collection<ISceneEntity>
{
}
} |
using ChromeVisualizerVSIntegration;
using Microsoft.VisualStudio.DebuggerVisualizers;
using System;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows.Forms;
// Visualizer metadata
[assembly: DebuggerVisualizer(typeof(DebuggerIntegration), typeof(VisualizerObjectSource), Target = typeof(String), Description = "Chrome Visualizer")]
namespace ChromeVisualizerVSIntegration
{
public class DebuggerIntegration : DialogDebuggerVisualizer
{
/// <summary>
/// The ChromeVisualizer.exe executable path
/// </summary>
private static readonly string chromeVisualizerPath = @"C:\Program Files\ChromeVisualizer\ChromeVisualizer.exe";
/// <summary>
/// Contains the code that actually creates the ChromeVisualizer (by starting its process)
/// </summary>
/// <param name="windowService"></param>
/// <param name="objectProvider"></param>
override protected void Show(IDialogVisualizerService windowService, IVisualizerObjectProvider objectProvider)
{
// Get the HTML we want to visualize
string html = objectProvider.GetObject().ToString();
// Get temp file path
string htmlFilePath = Path.GetTempFileName() + ".html";
try
{
// Try to write it out
File.WriteAllText(htmlFilePath, html, Encoding.UTF8);
}
catch (Exception exc)
{
// Report it to the user
MessageBox.Show("Failed to save HTML to a temporary text file: " + exc.Message);
return;
}
// Create a new process to launch our chrome visualizer
Process process = new Process();
// Link to the ChromeVisualizer.exe file
process.StartInfo.FileName = chromeVisualizerPath;
// Pass the HTML temp file path as argument
process.StartInfo.Arguments = htmlFilePath;
// Maximize the window
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
try
{
// Finally, start the process!
process.Start();
}
catch (Exception exc)
{
// Report it to the user
MessageBox.Show("Failed to start the Chrome Visualizer executable: " + exc.Message);
return;
}
// Wait for user to close window
process.WaitForExit();
try
{
// Finally, try to delete the temp file
File.Delete(htmlFilePath);
}
catch (Exception exc)
{
// Report it to the user
MessageBox.Show("Failed to delete the temporary HTML file: " + exc.Message);
return;
}
}
/// <summary>
/// Provides a way to test the debugger visualizer.
/// </summary>
/// <param name="objectToVisualize"></param>
public static void TestVisualizer(object objectToVisualize)
{
// Obtain a visualizer development host with this class as the target visualizer
VisualizerDevelopmentHost visualizerHost = new VisualizerDevelopmentHost(objectToVisualize, typeof(DebuggerIntegration));
// Run it
visualizerHost.ShowVisualizer();
}
}
}
|
using System.Linq;
using Microsoft.Dynamics365.UIAutomation.Browser;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TechTalk.SpecFlow;
using Vantage.Automation.LegalFlowUITest.Context;
using Vantage.Automation.LegalFlowUITest.Helpers;
namespace Vantage.Automation.LegalFlowUITest.Steps
{
[Binding]
public class CommonSteps
{
private readonly UIContext _uiContext;
public CommonSteps(UIContext context)
{
_uiContext = context;
}
[StepDefinition("I close the browser")]
public void CloseBrowser()
{
if (_uiContext.XrmApp != null)
{
_uiContext.XrmApp.Dispose();
_uiContext.WebClient = null;
_uiContext.XrmApp = null;
}
}
[StepDefinition("I click the Browser back button")]
public void NavigateBack()
{
_uiContext.WebClient.Browser.Driver.Navigate().Back();
}
[StepDefinition("I click the Browser forward button")]
public void NavigateForward()
{
_uiContext.WebClient.Browser.Driver.Navigate().Forward();
}
[StepDefinition("I save the Browser Url")]
public void SaveUrl()
{
_uiContext.SavedUrl = _uiContext.WebClient.Browser.Driver.Url;
}
[StepDefinition("I navigate to the saved Browser Url")]
public void GoToSavedUrl()
{
Assert.IsFalse(string.IsNullOrEmpty(_uiContext.SavedUrl), "Url has not been saved first");
_uiContext.WebClient.Browser.Driver.Url = _uiContext.SavedUrl;
}
[StepDefinition("I set the Browser zoom level to (.*)")]
public void SetZoomLevel(int level)
{
_uiContext.WebClient.Browser.Driver.ExecuteScript($"document.body.style.zoom='{level}%'");
_uiContext.WebClient.Browser.Driver.ClearFocus();
}
[StepDefinition("I wait for the Browser to go Idle")]
public void WaitUntilIdle()
{
_uiContext.WebClient.Browser.Driver.WaitForTransaction();
}
[StepDefinition("I wait for the Browser to go Idle and wait (.*) seconds")]
public void WaitUntilIdle(int seconds)
{
_uiContext.WebClient.Browser.Driver.WaitForTransaction();
_uiContext.XrmApp.ThinkTime(System.TimeSpan.FromSeconds(seconds));
}
[StepDefinition("I ignore the duplicate popup")]
public void IgnoreDuplicatePopup()
{
_uiContext.WebClient.Browser.Driver.WaitForTransaction();
_uiContext.XrmApp.Dialogs.DuplicateDetection(true);
// Sometimes a modal dialog will also pop up
_uiContext.XrmApp.Dialogs.CloseModalDialog();
_uiContext.WebClient.Browser.Driver.WaitForTransaction();
}
[StepDefinition("I fill out the following fields")]
public void FillOutFields(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h]);
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityFillOutFields(keyValues, true);
}
[StepDefinition("I fill out the following fields if they are present")]
public void FillOutFieldsIfPresent(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h]);
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityFillOutFields(keyValues, false);
}
[StepDefinition("I verify the following field values are")]
public void VerifyTheFollowingFieldValuesAre(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h]);
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityVerifyFieldValues(keyValues, false);
}
[StepDefinition("I verify the following field tooltips contain")]
public void VerifyTheFollowingFieldToolTipsContain(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h]);
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityFieldToolTipsContain(keyValues);
}
[StepDefinition("I verify the following field values contain")]
public void VerifyTheFollowingFieldValuesContain(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h]);
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityVerifyFieldValues(keyValues, true);
}
[StepDefinition("I verify that the following fields are present")]
public void VerifyFieldsArePresent(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h].ToLower() == "true");
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityFieldsArePresent(keyValues);
}
[StepDefinition("I verify that the following fields are required")]
public void VerifyFieldsAreMarkedRequired(Table table)
{
var keyValues = table.Header.ToArray().ToDictionary(h => h, h => table.Rows[0][h].ToLower() == "true");
FieldFiller fieldFiller = new FieldFiller(_uiContext);
fieldFiller.EntityFieldsAreRequired(keyValues);
}
[StepDefinition("I verify CommandBar button '(.*)' is present")]
public void CommandBarButtonIsPresent(string button)
{
Assert.IsTrue(_uiContext.XrmApp.CommandBar.GetCommandValues().Value.Contains(button), "CommandBar Button '{0}' is not present", button);
}
[StepDefinition("I verify CommandBar button '(.*)' is not present")]
public void CommandBarButtonIsNotPresent(string button)
{
Assert.IsFalse(_uiContext.XrmApp.CommandBar.GetCommandValues().Value.Contains(button), "CommandBar Button '{0}' is present but should not be", button);
}
}
} |
/*
------------------------------------------------
Generated by Cradle 2.0.1.0
https://github.com/daterre/Cradle
Original file: broom_guy.html
Story format: Harlowe
------------------------------------------------
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Cradle;
using IStoryThread = System.Collections.Generic.IEnumerable<Cradle.StoryOutput>;
using Cradle.StoryFormats.Harlowe;
public partial class @broom_guy: Cradle.StoryFormats.Harlowe.HarloweStory
{
#region Variables
// ---------------
public class VarDefs: RuntimeVars
{
public VarDefs()
{
}
}
public new VarDefs Vars
{
get { return (VarDefs) base.Vars; }
}
// ---------------
#endregion
#region Initialization
// ---------------
public readonly Cradle.StoryFormats.Harlowe.HarloweRuntimeMacros macros1;
@broom_guy()
{
this.StartPassage = "broom1";
base.Vars = new VarDefs() { Story = this, StrictMode = true };
macros1 = new Cradle.StoryFormats.Harlowe.HarloweRuntimeMacros() { Story = this };
base.Init();
passage1_Init();
passage2_Init();
passage3_Init();
passage4_Init();
passage5_Init();
passage6_Init();
}
// ---------------
#endregion
// .............
// #1: broom1
void passage1_Init()
{
this.Passages[@"broom1"] = new StoryPassage(@"broom1", new string[]{ }, passage1_Main);
}
IStoryThread passage1_Main()
{
yield return text("Hey! Get out of my way! Can't ya see I'm GENE WISP here?");
yield return lineBreak();
yield return lineBreak();
yield return link("space", "player1", null);
yield break;
}
// .............
// #2: broom2
void passage2_Init()
{
this.Passages[@"broom2"] = new StoryPassage(@"broom2", new string[]{ }, passage2_Main);
}
IStoryThread passage2_Main()
{
yield return text("You're not from A RUED HERON, are ya?");
yield return lineBreak();
yield return lineBreak();
yield return link("space", "broom3", null);
yield break;
}
// .............
// #3: player1
void passage3_Init()
{
this.Passages[@"player1"] = new StoryPassage(@"player1", new string[]{ "player", }, passage3_Main);
}
IStoryThread passage3_Main()
{
yield return text("Oh I'm sorry!");
yield return lineBreak();
yield return lineBreak();
yield return link("space", "broom2", null);
yield break;
}
// .............
// #4: broom3
void passage4_Init()
{
this.Passages[@"broom3"] = new StoryPassage(@"broom3", new string[]{ }, passage4_Main);
}
IStoryThread passage4_Main()
{
yield return text("DANG STIR OUT, traveling into town, making our DYES TEST RUST...");
yield return lineBreak();
yield return lineBreak();
yield return link("space", "broom4", null);
yield break;
}
// .............
// #5: broom4
void passage5_Init()
{
this.Passages[@"broom4"] = new StoryPassage(@"broom4", new string[]{ }, passage5_Main);
}
IStoryThread passage5_Main()
{
yield return text("BLURB MUGGER ELM");
yield return lineBreak();
yield return lineBreak();
yield return link("space", "player2", null);
yield break;
}
// .............
// #6: player2
void passage6_Init()
{
this.Passages[@"player2"] = new StoryPassage(@"player2", new string[]{ "player", "end", }, passage6_Main);
}
IStoryThread passage6_Main()
{
yield return text("Hey! I may not be able to understand you, but I can tell that wasn't very nice!");
yield return lineBreak();
yield return lineBreak();
yield return link("space", "broom1", null);
yield break;
}
} |
using log4net;
using Nwc.XmlRpc;
using System;
using System.Collections;
using System.Net;
using System.Reflection;
namespace OpenSim.Store
{
public class StoreServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public static Hashtable SendTransaction(string url, string trans, bool debug)
{
Hashtable hashtable = new Hashtable();
Hashtable hashtable2 = new Hashtable();
hashtable2["TransID"] = trans;
XmlRpcRequest xmlRpcRequest = new XmlRpcRequest("grid_store_transaction_message", new ArrayList
{
hashtable2
});
try
{
XmlRpcResponse xmlRpcResponse = xmlRpcRequest.Send(url, 10000);
Hashtable hashtable3 = (Hashtable)xmlRpcResponse.Value;
if (hashtable3.ContainsKey("success"))
{
if ((string)hashtable3["success"] == "true")
{
string value = (string)hashtable3["result"];
hashtable.Add("success", "true");
hashtable.Add("result", value);
if (debug)
{
StoreServiceConnector.m_log.DebugFormat("[Web Store Debug] Success", new object[0]);
}
}
else
{
string value2 = (string)hashtable3["result"];
hashtable.Add("success", "false");
hashtable.Add("result", value2);
if (debug)
{
StoreServiceConnector.m_log.DebugFormat("[Web Store Debug] Fail", new object[0]);
}
}
}
else
{
hashtable.Add("success", "false");
hashtable.Add("result", "The region server did not respond!");
StoreServiceConnector.m_log.DebugFormat("[Web Store Robust Module]: No response from Region Server! {0}", url);
}
}
catch (WebException ex)
{
hashtable.Add("success", "false");
StoreServiceConnector.m_log.ErrorFormat("[STORE]: Error sending transaction to {0} the host didn't respond " + ex.ToString(), url);
}
return hashtable;
}
public static Hashtable DoDelivery(string url, string trans, bool debug)
{
Hashtable hashtable = new Hashtable();
Hashtable hashtable2 = new Hashtable();
hashtable2["TransID"] = trans;
XmlRpcRequest xmlRpcRequest = new XmlRpcRequest("grid_store_delivery_message", new ArrayList
{
hashtable2
});
try
{
XmlRpcResponse xmlRpcResponse = xmlRpcRequest.Send(url, 10000);
Hashtable hashtable3 = (Hashtable)xmlRpcResponse.Value;
if (hashtable3.ContainsKey("success"))
{
if ((string)hashtable3["success"] == "true")
{
string value = (string)hashtable3["result"];
hashtable.Add("success", "true");
hashtable.Add("result", value);
if (debug)
{
StoreServiceConnector.m_log.DebugFormat("[Web Store Debug] Success", new object[0]);
}
}
else
{
string value2 = (string)hashtable3["result"];
hashtable.Add("success", "false");
hashtable.Add("result", value2);
if (debug)
{
StoreServiceConnector.m_log.DebugFormat("[Web Store Debug] Fail", new object[0]);
}
}
}
else
{
hashtable.Add("success", "false");
hashtable.Add("result", "The region server did not respond!");
StoreServiceConnector.m_log.DebugFormat("[Web Store Robust Module]: No response from Region Server! {0}", url);
}
}
catch (WebException ex)
{
hashtable.Add("success", "false");
StoreServiceConnector.m_log.ErrorFormat("[STORE]: Error sending transaction to {0} the host didn't respond " + ex.ToString(), url);
}
return hashtable;
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.