text stringlengths 13 6.01M |
|---|
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Media;
using System;
namespace Pong
{
class InputHelper
{
KeyboardState previousKeyboardState, currentKeyboardState;
public InputHelper()
{
}
public bool KeyPressed(Keys k)
{
return currentKeyboardState.IsKeyDown(k) && !previousKeyboardState.IsKeyDown(k);
}
public bool KeyReleased(Keys k)
{
return !currentKeyboardState.IsKeyDown(k) && previousKeyboardState.IsKeyDown(k);
}
public bool KeyDown(Keys k)
{
return currentKeyboardState.IsKeyDown(k);
}
public bool KeyUp(Keys k)
{
return !KeyDown(k);
}
public void Update()
{
previousKeyboardState = currentKeyboardState;
currentKeyboardState = Keyboard.GetState();
}
}
}
|
using MvcMonitor.Models;
namespace MvcMonitor.Broadcaster
{
public interface ISignalrBroadcaster
{
void ErrorReceived(ErrorModel error);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ControlValveMaintenance.Models.Lookups;
using System.Data;
using System.Data.SqlClient;
namespace ControlValveMaintenance.Services
{
class StatusCodesService
{
#region Variables
// CLASS VARIABLES
private SqlConnection localdbConnection;
#endregion
/// <summary>
/// DEFAULT CONSTRUCTOR
/// </summary>
public StatusCodesService()
{
localdbConnection = new SqlConnection(ControlValveMaintenance.Properties.Settings.Default.SiteMaintenanceConnectionString);
// try to open SQL connection
try
{
localdbConnection.Open();
}
catch (Exception ex)
{
throw new Exception("Local SQL Connection unable to connect. \n" + ex.Message);
}
}
/// <summary>
/// fill the status code instance model
/// </summary>
public void getStatusCodes()
{
// init command object
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "dbo.usp_GetStatusCodes";
myCommand.CommandType = System.Data.CommandType.StoredProcedure;
myCommand.Connection = localdbConnection;
// init data adaptor
SqlDataAdapter results = new SqlDataAdapter();
results.SelectCommand = myCommand;
DataSet allResults = new DataSet();
try
{
results.Fill(allResults, "tblStatusCodes");
}
catch (Exception ex)
{
Console.WriteLine("message is: " + ex.Message);
}
for (int i = 0; i < allResults.Tables["tblStatusCodes"].Rows.Count; i++)
{
if (allResults.Tables["tblStatusCodes"].Rows.Count == 0) continue;
StatusCodes.Instance.Codes[Convert.ToInt16(allResults.Tables["tblStatusCodes"].Rows[i].ItemArray[0])] =
allResults.Tables["tblStatusCodes"].Rows[i].ItemArray[1].ToString();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InstantiateBall : MonoBehaviour {
public Transform ball;
private Transform newThing;
int count = 0;
GameObject obj;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (count == 100)
{
count = 0;
newThing = Instantiate(ball, new Vector3(Random.Range(-7, 7), 5.5f), Quaternion.identity);
newThing.GetComponent<Rigidbody2D>().velocity.Set(.1f, 0f);
}
count++;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace api_cms.Models
{
public class ManagerModel
{
private CustomerModel customerModel;
public CustomerModel CustomerModel { get => CustomerModel.Instance; set => customerModel = value; }
public OrderModel OrderModel { get => OrderModel.Instance; set => orderModel = value; }
public AgencyModel AgencyModel { get => AgencyModel.Instance; set => agencyModel = value; }
public GameAcountModel GameAcountModel { get => GameAcountModel.Instance; set => gameAcountModel = value; }
private OrderModel orderModel;
private AgencyModel agencyModel;
private GameAcountModel gameAcountModel;
}
} |
using MovieLibrary2.Model;
using MovieLibrary2.DataManagement;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;
using System.Windows;
using System.IO;
using System.Windows.Controls;
using System.Threading;
using System.Windows.Input;
namespace MovieLibrary2.ViewModel
{
public class MoviesListView : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<Movie> _MovieList = MovieRepository.MovieList;
public ObservableCollection<Movie> MovieList
{
get
{
return _MovieList;
}
set
{
_MovieList = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MovieList"));
}
}
public string MovieCount => MovieList.Count + " Movies";
public Movie SelectedMovie { get; set; }
public Visibility DetailModeVisibility { get; set; } = Visibility.Hidden;
private string _filterString = null;
public string FilterString
{ get { return _filterString; }
private set
{
_filterString = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("FilterString"));
}
}
private bool _filterMode = false;
public bool IsFilterMode
{
get { return _filterMode; }
set
{
if (_filterMode && !value)
{
FilterString = null;
MovieList = MovieRepository.MovieList;
}
_filterMode = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsFilterMode"));
}
}
private bool _previewMode = true;
public bool IsPreviewMode
{
get { return _previewMode; }
set
{
_previewMode = value;
if (_previewMode)
{
ModeText = "Edit";
TextBackground = null;
}
else
{
ModeText = "View";
TextBackground = "DarkBlue";
}
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("IsPreviewMode"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("ModeText"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("TextBackground"));
}
}
public string ModeText { get; set; } = "Edit";
public string TextBackground { get; set; }
public MoviesListView() { }
public void ChangeMode() => IsPreviewMode = !IsPreviewMode;
public async Task DownloadInfo()
{
await Task.Run(() => MovieDataDownloader.DownloadMovieData(SelectedMovie));
UpdateValues();
}
public async Task DownloadAllMoviesInfo()
{
await Task.Run(() => DownloadAll());
}
public void DownloadAll()
{
foreach (var mov in MovieRepository.MovieList)
{
MovieDataDownloader.DownloadMovieData(mov);
Thread.Sleep(700);
}
}
public void CloseDetail()
{
if (DetailModeVisibility == Visibility.Visible)
{
SelectedMovie = null;
DetailModeVisibility = Visibility.Hidden;
IsPreviewMode = true;
UpdateValues();
}
}
public void LaunchMovie()
{
if (File.Exists(SelectedMovie.FilePath))
System.Diagnostics.Process.Start(SelectedMovie.FilePath);
else
MessageBox.Show($"File {SelectedMovie.FilePath} does not exist!", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
}
public void MovieClick(object item)
{
SelectedMovie = item as Movie;
DetailModeVisibility = Visibility.Visible;
UpdateValues();
}
public void OpenExternalLink()
{
string address = "";
Movie movie = SelectedMovie;
if (string.IsNullOrEmpty(movie.IMDbID))
{
address = @"http://www.imdb.com/search/title?"
+ $"title={movie.Title}"
+ ((movie.Year != -1) ? $"&release_date={movie.Year}" : "");
}
else
{
address = @"http://www.imdb.com/title/"
+ $"{movie.IMDbID}";
}
Uri uri = new Uri(address);
System.Diagnostics.Process.Start(uri.AbsoluteUri);
}
public void Update()
{
MovieRepository.GetMoviesFromDataFile(Properties.Settings.Default.DataFilePath);
MovieRepository.GetMoviesFromDirectory(Properties.Settings.Default.MoviesDirectoryPath);
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MovieList"));
}
public void UpdateValues()
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("SelectedMovie"));
//PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("MovieList.ImagePath"));
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("DetailModeVisibility"));
}
public void FilterEvent(Key key)
{
if (DetailModeVisibility == Visibility.Visible)
{
return;
}
if (key == Key.Back)
{
DeleteLetter();
}
if (IsFilterMode &&
(key == Key.Escape ||
(key == Key.Back &&
FilterString == string.Empty)))
{
IsFilterMode = false;
return;
}
else if (!IsFilterMode && IsAllowedKey(key))
{
IsFilterMode = true;
}
ApplyFilter(key);
}
private void ApplyFilter(Key key)
{
int yearFilter;
IEnumerable<Movie> filteredList;
FilterString += KeyToString(key);
int.TryParse(FilterString, out yearFilter);
if(yearFilter > 1900 && yearFilter < 2100)
filteredList = MovieRepository.MovieList.Where(
mov => mov.Title.ToUpper().Contains(FilterString) ||
mov.Year == yearFilter);
else
filteredList = MovieRepository.MovieList.Where(mov => mov.Title.ToUpper().Contains(FilterString));
if (filteredList != null)
{
MovieList = new ObservableCollection<Movie>(filteredList);
}
}
private void DeleteLetter()
{
if (FilterString != null && FilterString.Length > 0)
{
FilterString = FilterString.Remove(FilterString.Length-1, 1);
}
//MessageBox.Show(filterString);
}
private string KeyToString(Key key)
{
if (key == Key.Space)
{
return " ";
}
else if (IsAllowedKey(key))
{
return KeyValToString(key);
}
return null;
}
private bool IsAllowedKey(Key key)
{
var allowedKeys = "ABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";
return allowedKeys.Contains(KeyValToString(key));
}
private string KeyValToString(Key key)
{
if(key >= Key.D0 && key <= Key.D9)
{
return ((int)key - 34).ToString();
}
else if (key >= Key.NumPad0 && key <= Key.NumPad9)
{
return ((int)key - 74).ToString();
}
return key.ToString();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Homework_Theme_01
{
/// <summary>
/// Класс билдера сотрудников. В нем скрыта логика ввода данных/валидации
/// </summary>
class EmployeeBuilder
{
/// <summary>
/// Имя
/// </summary>
public string Name { get; set; }
/// <summary>
/// Возраст
/// </summary>
public sbyte Age { get; set; }
/// <summary>
/// Рост
/// </summary>
public short Height { get; set; }
/// <summary>
/// Балл по русскому
/// </summary>
public sbyte RussianScores { get; set; }
/// <summary>
/// Балл по истории
/// </summary>
public sbyte HistoryScores { get; set; }
/// <summary>
/// Балл по математике
/// </summary>
public sbyte MathScores { get; set; }
/// <summary>
/// Конструктор
/// </summary>
static EmployeeBuilder() { }
/// <summary>
/// Метод добавления сотрудника.
/// Данные добавляются один за другим. Если что-то введено верно - сохраняется в свойство класса.
/// Выбрасывает пользовательское исключение.
/// </summary>
public Employee Build()
{
string userInput;
bool successParse;
if (this.Name == null)
{
Console.WriteLine("Введите Имя сотрудника:");
userInput = Console.ReadLine();
if (userInput.Length < 3)
{
throw new EmployeeBuildException("Имя сотрудника не может быть меньше 3 символов.");
}
this.Name = userInput;
}
if (this.Age == 0)
{
Console.WriteLine($"Введите Возраст сотрудника \"{this.Name}\":");
userInput = Console.ReadLine();
successParse = SByte.TryParse(userInput, out sbyte parsedAge);
if (!successParse)
{
throw new EmployeeBuildException("Возраст сотрудника должен быть числом.");
}
if (parsedAge < 18 || parsedAge > 60)
{
throw new EmployeeBuildException("Все сотрудники должны быть старше 18 лет и моложе 60.");
}
this.Age = parsedAge;
}
if (this.Height == 0)
{
Console.WriteLine($"Введите Рост сотрудника \"{this.Name}\":");
userInput = Console.ReadLine();
successParse = Int16.TryParse(userInput, out short parsedHeight);
if (!successParse)
{
throw new EmployeeBuildException("Рост сотрудника должен быть числом.");
}
if (parsedHeight < 0)
{
throw new EmployeeBuildException("Рост не может быть отрицательным.");
}
this.Height = parsedHeight;
}
if (this.RussianScores == 0)
{
Console.WriteLine($"Введите баллы по Русскому языку сотрудника \"{this.Name}\":");
userInput = Console.ReadLine();
successParse = SByte.TryParse(userInput, out sbyte parsedRussianScores);
if (!successParse)
{
throw new EmployeeBuildException("Балл должен быть числом.");
}
if (parsedRussianScores < 1 || parsedRussianScores > 10)
{
throw new EmployeeBuildException("Балл по Русскому языку должен быть равен значению от 1 до 10 включительно.");
}
this.RussianScores = parsedRussianScores;
}
if (this.HistoryScores == 0)
{
Console.WriteLine($"Введите баллы по Истории сотрудника \"{this.Name}\":");
userInput = Console.ReadLine();
successParse = SByte.TryParse(userInput, out sbyte parsedHistoryScores);
if (!successParse)
{
throw new EmployeeBuildException("Балл должен быть числом.");
}
if (parsedHistoryScores < 1 || parsedHistoryScores > 10)
{
throw new EmployeeBuildException("Балл по Истории должен быть равен значению от 1 до 10 включительно.");
}
this.HistoryScores = parsedHistoryScores;
}
if (this.MathScores == 0)
{
Console.WriteLine($"Введите баллы по Математике сотрудника \"{this.Name}\":");
userInput = Console.ReadLine();
successParse = SByte.TryParse(userInput, out sbyte parsedMatchScores);
if (!successParse)
{
throw new EmployeeBuildException("Балл должен быть числом.");
}
if (parsedMatchScores < 1 || parsedMatchScores > 10)
{
throw new EmployeeBuildException("Балл по Математике должен быть равен значению от 1 до 10 включительно.");
}
this.MathScores = parsedMatchScores;
}
Employee employee = new Employee(this.Name, this.Age, this.Height, this.RussianScores, this.HistoryScores, this.MathScores);
employee.CalcAverageScore();
return employee;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
public class Kangaroo : Enemy
{
public NavMeshAgent navMeshAgent;
private MeshRenderer meshRenderer;
public SkinnedMeshRenderer head;
public SkinnedMeshRenderer body;
public Material defaultMat;
public Material trancparencyMat;
public float lookRadius = 10f;
private Player player;
private float damage;
public FieldOfView eyes;
private Animator animator;
private AudioManager audioManager;
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.red;
}
// Use this for initialization
protected override void OnStart()
{
base.OnStart();
animator = GetComponent<Animator>();
health = 100;
damage = 0.1f;
invisibled = false;
meshRenderer = GetComponent<MeshRenderer>();
navMeshAgent = GetComponent<NavMeshAgent>();
audioManager = AudioManager.GetInstance();
player = Player.GetInstance();
prevKangarooPosition = transform.position;
}
private float walkRadius = 20f;
private Vector3 finalPosition;
private Vector3 prevKangarooPosition;
private int count;
private bool afterChase;
// Update is called once per frame
protected override void OnUpdate()
{
base.OnUpdate();
bool isSeePlayer = eyes.IsSeePlayer();
if (playerSee && !invisibled && reloaded && (isSeePlayer || shooted))
{
BecomeInvisible();
}
if (invisibled)
{
currentInvisibleTime += Time.deltaTime;
if (currentInvisibleTime >= invisibleTime)
{
head.material = defaultMat;
body.material = defaultMat;
currentInvisibleTime = 0f;
invisibled = false;
reloaded = false;
}
}
if (!reloaded && !invisibled)
{
currentCoolDownTime += Time.deltaTime;
if (currentCoolDownTime >= coolDown)
{
reloaded = true;
currentCoolDownTime = 0;
}
}
if (isSeePlayer || shooted)
{
if (Vector3.Distance(transform.position, player.transform.position) <= navMeshAgent.stoppingDistance)
{
Attack();
audioManager.PlayBattleLoopSound();
afterChase = true;
}
else
{
if (transform.position != prevKangarooPosition && HasPath())
{
RunForPlayer();
audioManager.PlayBattleLoopSound();
afterChase = true;
}
else
{
Patrol();
if (afterChase)
{
audioManager.PlayBattleEndSound();
afterChase = false;
}
}
}
}
else
{
if (lastPlayerPosition != Vector3.zero && transform.position != prevKangarooPosition && HasPath())
{
CheckLastPlayerPosition();
audioManager.PlayBattleLoopSound();
afterChase = true;
}
else
{
Patrol();
lastPlayerPosition = Vector3.zero;
if (afterChase)
{
audioManager.PlayBattleEndSound();
afterChase = false;
}
}
}
prevKangarooPosition = transform.position;
shooted = false;
}
public override void Die()
{
base.Die();
audioManager.PlayBattleEndSound();
afterChase = false;
}
public bool playerSee { get; set; }
private bool invisibled;
private float currentInvisibleTime;
[SerializeField]
private float invisibleTime = 6f;
private float currentCoolDownTime;
[SerializeField]
private float coolDown = 10f;
[SerializeField]
private float runningSpeed = 3.75f;
[SerializeField]
private float normalSpeed = 2.5f;
private bool reloaded = true;
private float current = 0f;
private float delay = 1f;
public bool shooted { get; set; }
private void BecomeInvisible()
{
if (current >= delay)
{
head.material = trancparencyMat;
body.material = trancparencyMat;
invisibled = true;
reloaded = false;
current = 0;
}
current += Time.deltaTime;
}
private Vector3 lastPlayerPosition;
private void RunForPlayer()
{
navMeshAgent.speed = runningSpeed;
animator.SetBool("Walking", true);
navMeshAgent.SetDestination(player.transform.position);
transform.LookAt(player.transform.position);
lastPlayerPosition = new Vector3(player.transform.position.x, 0, player.transform.position.z);
}
private bool HasPath()
{
NavMeshPath path = new NavMeshPath();
return navMeshAgent.CalculatePath(player.transform.position, path);
}
private void CheckLastPlayerPosition()
{
navMeshAgent.speed = runningSpeed;
if (Vector3.Distance(new Vector3(transform.position.x, 0, transform.position.z), lastPlayerPosition) >= navMeshAgent.stoppingDistance)
{
animator.SetBool("Walking", true);
navMeshAgent.SetDestination(lastPlayerPosition);
transform.LookAt(navMeshAgent.nextPosition);
}
else
{
lastPlayerPosition = Vector3.zero;
animator.SetBool("Walking", false);
animator.SetTrigger("Looking");
}
}
private void GoToRandomPosition()
{
Vector3 randomDirection = Random.insideUnitSphere * walkRadius;
randomDirection += transform.position;
NavMeshHit hit;
NavMesh.SamplePosition(randomDirection, out hit, walkRadius, 1);
finalPosition = hit.position;
animator.SetBool("Walking", true);
navMeshAgent.SetDestination(finalPosition);
}
private void Attack()
{
transform.LookAt(player.transform.position);
animator.SetTrigger("Attacking");
MakeDamage(damage);
}
private void MakeDamage(float damage)
{
player.GetDamage(damage * Time.deltaTime);
}
private void Patrol()
{
navMeshAgent.speed = normalSpeed;
if (transform.position == prevKangarooPosition)
{
GoToRandomPosition();
}
prevKangarooPosition = transform.position;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
namespace UserStorageServices
{
/// <summary>
/// Represents a service that stores a set of <see cref="User"/>s and allows to search through them.
/// </summary>
public abstract class UserStorageServiceBase : IUserStorageService, INotificationSubscriber
{
/// <summary>
/// field validation
/// </summary>
private IValidator valid;
/// <summary>
/// new identification number
/// </summary>
private IGeneratorId newId;
/// <summary>
/// list of users
/// </summary>
private List<User> users;
/// <summary>
/// c-or
/// </summary>
public UserStorageServiceBase(IGeneratorId newId, IValidator valid)
{
users = new List<User>();
this.newId = newId;
this.valid = valid;
}
public abstract UserStorageServiceMode ServiceMode { get; }
/// <summary>
/// Gets the number of elements contained in the storage.
/// </summary>
/// <returns>An amount of users in the storage.</returns>
public int Count => users.Count;
/// <summary>
/// Adds a new <see cref="User"/> to the storage.
/// </summary>
/// <param name="user">A new <see cref="User"/> that will be added to the storage.</param>
public virtual void Add(User user)
{
valid.Validate(user);
user.Id = newId.Generate();
users.Add(user);
}
/// <summary>
/// Removes an existed <see cref="User"/> from the storage.
/// </summary>
public virtual bool Remove(User user)
{
valid.Validate(user);
user.Id = newId.Generate();
return users.Remove(user);
}
/// <summary>
/// Search by name
/// </summary>
/// <param name="firstName">name of user</param>
/// <returns>users</returns>
public virtual IEnumerable<User> SearchByFirstName(string firstName)
{
return SearchByPredicate(u => u.FirstName == firstName);
}
/// <summary>
/// Search users
/// </summary>
/// <param name="lastName">last name of user</param>
/// <returns></returns>
public virtual IEnumerable<User> SearchByLastName(string lastName)
{
return SearchByPredicate(u => u.LastName == lastName);
}
/// <summary>
/// Search users
/// </summary>
/// <param name="age">age/param>
/// <returns></returns>
public virtual IEnumerable<User> SearchByAge(int age)
{
return SearchByPredicate(u => u.Age == age);
}
/// <summary>
/// Search By Predicate
/// </summary>
/// <param name="predicate">predicate</param>
/// <returns></returns>
public virtual IEnumerable<User> SearchByPredicate(Predicate<User> predicate)
{
if (predicate == null)
{
throw new ArgumentNullException(nameof(predicate));
}
var choossingUsers = users.Where(u => predicate(u));
return choossingUsers;
}
public virtual void UserAdded(User user)
{
Add(user);
}
public virtual void UserRemoved(User user)
{
Remove(user);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ServiceModel;
using System.Data.SqlClient;
namespace BLL集团客运综合管理.ClassesManage
{
[ServiceContract]
class FRM_BaoBanGuanLi
{
DALPublic.DALMethod myDALMethod = new DALPublic.DALMethod();
#region 查询车辆编号
[OperationContract]
public DataSet SelectCheLiangBianHao()
{
SqlParameter[] mySqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar)
};
mySqlParameters[0].Value = "SelectCheLiangBianHao";
DataTable dt = myDALMethod.QueryDataTable("FRM_BaoBanGuanLi", mySqlParameters);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
#endregion
#region 查询报班信息通过车牌号
[OperationContract]
public DataSet SelectBaoBanXinXiByChePaiHao(string VehicleNumber)
{
SqlParameter[] mySqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar),
new SqlParameter("@VehicleNumber",SqlDbType.NChar)
};
mySqlParameters[0].Value = "SelectBaoBanXinXiByChePaiHao";
mySqlParameters[1].Value = VehicleNumber;
DataTable dt = myDALMethod.QueryDataTable("FRM_BaoBanGuanLi", mySqlParameters);
DataSet ds = new DataSet();
ds.Tables.Add(dt);
return ds;
}
#endregion
#region 查询驾驶员相片
[OperationContract]
public byte[] SelectJiaShiYuanXianPian(int DriverID)
{
SqlParameter[] mySqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar),
new SqlParameter("@DriverID",SqlDbType.Int)
};
mySqlParameters[0].Value = "SelectJiaShiYuanXianPian";
mySqlParameters[1].Value = DriverID;
return myDALMethod.QueryDataByte("FRM_BaoBanGuanLi", mySqlParameters);
}
#endregion
#region 查询副驾驶员相片
[OperationContract]
public byte[] SelectFuJiaShiYuanXianPian(int DriverID)
{
SqlParameter[] mySqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar),
new SqlParameter("@DriverID",SqlDbType.Int)
};
mySqlParameters[0].Value = "SelectFuJiaShiYuanXianPian";
mySqlParameters[1].Value = DriverID;
return myDALMethod.QueryDataByte("FRM_BaoBanGuanLi", mySqlParameters);
}
#endregion
#region 新增报班信息
[OperationContract]
public int InsertBaoBanXinXi(
int FrequencyID,
bool WhetherNnSchedule,
bool WhetherLate,
bool StayClassVehicleNo,
string Comment)
{
SqlParameter[] mySqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar),
new SqlParameter("@FrequencyID",SqlDbType.Int),
new SqlParameter("@WhetherNnSchedule",SqlDbType.Bit),
new SqlParameter("@WhetherLate",SqlDbType.Bit),
new SqlParameter("@StayClassVehicleNo",SqlDbType.Bit),
new SqlParameter("@Comment",SqlDbType.NChar)
};
mySqlParameters[0].Value = "InsertBaoBanXinXi";
mySqlParameters[1].Value = FrequencyID;
mySqlParameters[2].Value = WhetherNnSchedule;
mySqlParameters[3].Value = WhetherLate;
mySqlParameters[4].Value = StayClassVehicleNo;
mySqlParameters[5].Value = Comment;
int result = myDALMethod.UpdateData("FRM_BaoBanGuanLi", mySqlParameters);
return result;
}
#endregion
#region 修改车辆状态
[OperationContract]
public int UpdateVehicleState(int VehicleID)
{
SqlParameter[] mySqlParameters =
{
new SqlParameter("@TYPE",SqlDbType.NChar),
new SqlParameter("@VehicleID",SqlDbType.Int)
};
mySqlParameters[0].Value = "UpdateVehicleState";
mySqlParameters[1].Value = VehicleID;
int result = myDALMethod.UpdateData("FRM_BaoBanGuanLi", mySqlParameters);
return result;
}
#endregion
}
}
|
namespace syscrawl.Game.Models.Levels
{
public class EntranceNode : Node
{
public EntranceNode()
: base(NodeType.Entrance)
{
}
}
}
|
//using NuGet.Protocol.Core.Types;
//using System;
//using System.Collections.Generic;
//using System.Linq;
//using System.Text;
//using System.Threading.Tasks;
//using Xunit;
//namespace V2V3ResourcesTest
//{
// public class FactoryTests
// {
// [Fact]
// public async Task Factory_V2()
// {
// var v2repo = RepositoryFactory.CreateV2("https://api.nuget.org/v2/");
// var resource = v2repo.GetResource<UISearchResource>();
// Assert.NotNull(resource);
// }
// [Fact]
// public async Task Factory_V3()
// {
// var repo = RepositoryFactory.CreateV3("https://api.nuget.org/v3/index.json");
// var resource = repo.GetResource<UISearchResource>();
// Assert.NotNull(resource);
// }
// [Fact]
// public async Task Factory_All()
// {
// var repo = RepositoryFactory.Create("https://api.nuget.org/v3/index.json");
// var resource = repo.GetResource<UISearchResource>();
// Assert.NotNull(resource);
// }
// }
//}
|
using System;
namespace WeatherService
{
public class WeatherForecastV1
{
public string City { get; set; }
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
} |
using System;
using System.Reflection;
using UnityEngine;
using UnityEditor;
namespace CoreEditor
{
public interface IDrawer
{
bool DisplayProperty( SerializedProperty property, FieldInfo field, GUIContent label );
bool IsValid( object value );
string GetError( object value );
string Tooltip{get;}
}
} |
using System.Reactive;
using System.Reactive.Linq;
using MVVMSidekick.ViewModels;
using MVVMSidekick.Views;
using MVVMSidekick.Reactive;
using MVVMSidekick.Services;
using MVVMSidekick.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using IndoorMap.Models;
using Newtonsoft.Json;
using IndoorMap.Controller;
using Windows.UI.Core;
namespace IndoorMap.ViewModels
{
[DataContract]
public class ShopDetailsPage_Model : ViewModelBase<ShopDetailsPage_Model>
{
// If you have install the code sniplets, use "propvm + [tab] +[tab]" create a property。
// 如果您已经安装了 MVVMSidekick 代码片段,请用 propvm +tab +tab 输入属性
public string ActionUrl;
public ShopDetailsPage_Model()
{
}
public ShopDetailsPage_Model(string url)
{
ActionUrl = url;
DoSomething();
}
public void DoSomething()
{
FormAction action = new FormAction(ActionUrl);
action.isShowWaitingPanel = true;
action.Run();
action.FormActionCompleted += (result, ee) =>
{
JsonShopDetailsModel jsonShopDetails = JsonConvert.DeserializeObject<JsonShopDetailsModel>(result);
if (jsonShopDetails.reason == "成功" || jsonShopDetails.reason == "successed")
{
//HttpClientReturnCities(jsonShopDetails.result);
CommentList = jsonShopDetails.result.comments;
ShopName = jsonShopDetails.result.ch_name;
}
};
}
public String ShopName
{
get { return _ShopNameLocator(this).Value; }
set { _ShopNameLocator(this).SetValueAndTryNotify(value); }
}
#region Property String ShopName Setup
protected Property<String> _ShopName = new Property<String> { LocatorFunc = _ShopNameLocator };
static Func<BindableBase, ValueContainer<String>> _ShopNameLocator = RegisterContainerLocator<String>("ShopName", model => model.Initialize("ShopName", ref model._ShopName, ref _ShopNameLocator, _ShopNameDefaultValueFactory));
static Func<BindableBase, String> _ShopNameDefaultValueFactory = m => { return "姓名呀"; };
#endregion
public String Title
{
get { return _TitleLocator(this).Value; }
set { _TitleLocator(this).SetValueAndTryNotify(value); }
}
#region Property String Title Setup
protected Property<String> _Title = new Property<String> { LocatorFunc = _TitleLocator };
static Func<BindableBase, ValueContainer<String>> _TitleLocator = RegisterContainerLocator<String>("Title", model => model.Initialize("Title", ref model._Title, ref _TitleLocator, _TitleDefaultValueFactory));
static Func<BindableBase, String> _TitleDefaultValueFactory = m => m.GetType().Name;
#endregion
//CommentList
public List<Comment> CommentList
{
get { return _CommentListLocator(this).Value; }
set { _CommentListLocator(this).SetValueAndTryNotify(value); }
}
#region Property Channel CommentList Setup
protected Property<List<Comment>> _CommentList = new Property<List<Comment>> { LocatorFunc = _CommentListLocator };
static Func<BindableBase, ValueContainer<List<Comment>>> _CommentListLocator = RegisterContainerLocator<List<Comment>>("CommentList", model => model.Initialize("CommentList", ref model._CommentList, ref _CommentListLocator, _CommentListDefaultValueFactory));
static Func<BindableBase,List<Comment>> _CommentListDefaultValueFactory = m => { return new List<Comment>() { }; };
#endregion
#region Life Time Event Handling
/// <summary>
/// This will be invoked by view when this viewmodel instance is set to view's ViewModel property.
/// </summary>
/// <param name="view">Set target</param>
/// <param name="oldValue">Value before set.</param>
/// <returns>Task awaiter</returns>
protected override Task OnBindedToView(MVVMSidekick.Views.IView view, IViewModel oldValue)
{
return base.OnBindedToView(view, oldValue);
}
///// <summary>
///// This will be invoked by view when this instance of viewmodel in ViewModel property is overwritten.
///// </summary>
///// <param name="view">Overwrite target view.</param>
///// <param name="newValue">The value replacing </param>
///// <returns>Task awaiter</returns>
//protected override Task OnUnbindedFromView(MVVMSidekick.Views.IView view, IViewModel newValue)
//{
// return base.OnUnbindedFromView(view, newValue);
//}
/// <summary>
/// This will be invoked by view when the view fires Load event and this viewmodel instance is already in view's ViewModel property
/// </summary>
/// <param name="view">View that firing Load event</param>
/// <returns>Task awaiter</returns>
protected override Task OnBindedViewLoad(MVVMSidekick.Views.IView view)
{
return base.OnBindedViewLoad(view);
}
///// <summary>
///// This will be invoked by view when the view fires Unload event and this viewmodel instance is still in view's ViewModel property
///// </summary>
///// <param name="view">View that firing Unload event</param>
///// <returns>Task awaiter</returns>
//protected override Task OnBindedViewUnload(MVVMSidekick.Views.IView view)
//{
// return base.OnBindedViewUnload(view);
//}
///// <summary>
///// <para>If dispose actions got exceptions, will handled here. </para>
///// </summary>
///// <param name="exceptions">
///// <para>The exception and dispose infomation</para>
///// </param>
//protected override async void OnDisposeExceptions(IList<DisposeInfo> exceptions)
//{
// base.OnDisposeExceptions(exceptions);
// await TaskExHelper.Yield();
//}
#endregion
}
}
|
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using Torshify.Radio.Framework;
using System.Linq;
namespace Torshify.Radio.EchoNest.Views.Similar.Tabs
{
public class SimilarArtistsTrackStream : ITrackStream
{
#region Fields
private readonly IRadio _radio;
private readonly IEnumerable<string> _similarArtists;
private readonly IEnumerator<string> _similarArtistsEnumerator;
private IEnumerable<Track> _currentTrackList;
#endregion Fields
#region Constructors
public SimilarArtistsTrackStream(IRadio radio, IEnumerable<string> similarArtists)
{
_radio = radio;
_similarArtists = similarArtists;
_similarArtistsEnumerator =_similarArtists.GetEnumerator();
_currentTrackList = new Track[0];
}
#endregion Constructors
#region Properties
public IEnumerable<Track> Current
{
get { return _currentTrackList; }
}
public bool SupportsTrackSkipping
{
get { return true; }
}
public string Description
{
get; set;
}
public TrackStreamData Data
{
get
{
return new SimilarArtistsTrackStreamData
{
Name = "Similar artists playlist",
Description = string.Join(", ", _similarArtists),
Image = null,
Artists = _similarArtists.ToArray()
};
}
}
#endregion Properties
#region Methods
public void Dispose()
{
_similarArtistsEnumerator.Dispose();
}
public bool MoveNext(CancellationToken token)
{
if (_similarArtistsEnumerator.MoveNext())
{
_currentTrackList = _radio.GetTracksByName(_similarArtistsEnumerator.Current);
if (!_currentTrackList.Any())
{
return MoveNext(token);
}
return true;
}
_currentTrackList = new Track[0];
return false;
}
public void Reset()
{
_similarArtistsEnumerator.Reset();
}
#endregion Methods
}
} |
using System.Windows;
using System.Windows.Controls;
using HandyControl.Controls;
using HandyControl.Data;
namespace HandyControl.Tools
{
public class RadioGroupItemStyleSelector : StyleSelector
{
public override Style SelectStyle(object item, DependencyObject container)
{
if (container is RadioGroup radioGroup && item is UIElement radioButton)
{
var count = radioGroup.Items.Count;
if (count == 1)
{
return ResourceHelper.GetResource<Style>(ResourceToken.RadioGroupItemSingle);
}
var index = radioGroup.Items.IndexOf(radioButton);
return radioGroup.Orientation == Orientation.Horizontal
? index == 0
? ResourceHelper.GetResource<Style>(ResourceToken.RadioGroupItemHorizontalFirst)
: ResourceHelper.GetResource<Style>(index == count - 1
? ResourceToken.RadioGroupItemHorizontalLast
: ResourceToken.RadioGroupItemDefault)
: index == 0
? ResourceHelper.GetResource<Style>(ResourceToken.RadioGroupItemVerticalFirst)
: ResourceHelper.GetResource<Style>(index == count - 1
? ResourceToken.RadioGroupItemVerticalLast
: ResourceToken.RadioGroupItemDefault);
}
return null;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeteorController : MonoBehaviour
{
Rigidbody2D rigidbody2D;
public GameObject ship;
private void Awake()
{
rigidbody2D = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
private void Update()
{
if (rigidbody2D.position.x < -GameManager.instance.screenBounds.x)
{
ShipController shipScript = ship.GetComponent<ShipController>();
shipScript.ChangeHealth(-1);
Destroy(gameObject);
}
}
public void Spawn(Vector2 direction, float force)
{
rigidbody2D.AddForce(direction * force);
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.name == "Ship")
{
ShipController ship = collision.gameObject.GetComponent<ShipController>();
ship.ChangeHealth(-1);
}
else
{
Destroy(collision.gameObject);
}
Destroy(gameObject);
}
}
|
namespace Triton.Game.Mapping
{
using ns25;
using ns26;
using System;
using System.Collections.Generic;
using Triton.Game;
using Triton.Game.Mono;
[Attribute38("ChatMgr")]
public class ChatMgr : MonoBehaviour
{
public ChatMgr(IntPtr address) : this(address, "ChatMgr")
{
}
public ChatMgr(IntPtr address, string className) : base(address, className)
{
}
public void AddRecentWhisperPlayerToBottom(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
base.method_8("AddRecentWhisperPlayerToBottom", objArray1);
}
public void AddRecentWhisperPlayerToTop(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
base.method_8("AddRecentWhisperPlayerToTop", objArray1);
}
public void Awake()
{
base.method_8("Awake", Array.Empty<object>());
}
public void CleanUp()
{
base.method_8("CleanUp", Array.Empty<object>());
}
public void CloseChatUI()
{
base.method_8("CloseChatUI", Array.Empty<object>());
}
public KeyboardState ComputeKeyboardState()
{
return base.method_11<KeyboardState>("ComputeKeyboardState", Array.Empty<object>());
}
public Triton.Game.Mapping.FriendListFrame CreateFriendsListUI()
{
return base.method_14<Triton.Game.Mapping.FriendListFrame>("CreateFriendsListUI", Array.Empty<object>());
}
public void DestroyFriendListFrame()
{
base.method_8("DestroyFriendListFrame", Array.Empty<object>());
}
public void FireChatInfoChangedEvent(PlayerChatInfo chatInfo)
{
object[] objArray1 = new object[] { chatInfo };
base.method_8("FireChatInfoChangedEvent", objArray1);
}
public static ChatMgr Get()
{
return MonoClass.smethod_15<ChatMgr>(TritonHs.MainAssemblyPath, "", "ChatMgr", "Get", Array.Empty<object>());
}
public BnetPlayer GetMostRecentWhisperedPlayer()
{
return base.method_14<BnetPlayer>("GetMostRecentWhisperedPlayer", Array.Empty<object>());
}
public PlayerChatInfo GetPlayerChatInfo(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
return base.method_14<PlayerChatInfo>("GetPlayerChatInfo", objArray1);
}
public List<BnetPlayer> GetRecentWhisperPlayers()
{
Class267<BnetPlayer> class2 = base.method_14<Class267<BnetPlayer>>("GetRecentWhisperPlayers", Array.Empty<object>());
if (class2 != null)
{
return class2.method_25();
}
return null;
}
public void GoBack()
{
base.method_8("GoBack", Array.Empty<object>());
}
public void HandleGUIInput()
{
base.method_8("HandleGUIInput", Array.Empty<object>());
}
public void HandleGUIInputForQuickChat()
{
base.method_8("HandleGUIInputForQuickChat", Array.Empty<object>());
}
public bool HandleKeyboardInput()
{
return base.method_11<bool>("HandleKeyboardInput", Array.Empty<object>());
}
public void HideFriendsList()
{
base.method_8("HideFriendsList", Array.Empty<object>());
}
public void InitChatLogUI()
{
base.method_8("InitChatLogUI", Array.Empty<object>());
}
public void InitCloseCatcher()
{
base.method_8("InitCloseCatcher", Array.Empty<object>());
}
public bool IsChatLogFrameShown()
{
return base.method_11<bool>("IsChatLogFrameShown", Array.Empty<object>());
}
public bool IsFriendListShowing()
{
return base.method_11<bool>("IsFriendListShowing", Array.Empty<object>());
}
public bool IsMobilePlatform()
{
return base.method_11<bool>("IsMobilePlatform", Array.Empty<object>());
}
public void MoveChatBubbles(ChatBubbleFrame newBubbleFrame)
{
object[] objArray1 = new object[] { newBubbleFrame };
base.method_8("MoveChatBubbles", objArray1);
}
public void OnChatBubbleFadeOutComplete(ChatBubbleFrame bubbleFrame)
{
object[] objArray1 = new object[] { bubbleFrame };
base.method_8("OnChatBubbleFadeOutComplete", objArray1);
}
public void OnChatBubbleReleased(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnChatBubbleReleased", objArray1);
}
public void OnChatBubbleScaleInComplete(ChatBubbleFrame bubbleFrame)
{
object[] objArray1 = new object[] { bubbleFrame };
base.method_8("OnChatBubbleScaleInComplete", objArray1);
}
public void OnChatFramesMoved()
{
base.method_8("OnChatFramesMoved", Array.Empty<object>());
}
public void OnChatLogFrameHidden()
{
base.method_8("OnChatLogFrameHidden", Array.Empty<object>());
}
public void OnChatLogFrameShown()
{
base.method_8("OnChatLogFrameShown", Array.Empty<object>());
}
public void OnChatReceiverChanged(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
base.method_8("OnChatReceiverChanged", objArray1);
}
public void OnCloseCatcherRelease(UIEvent e)
{
object[] objArray1 = new object[] { e };
base.method_8("OnCloseCatcherRelease", objArray1);
}
public void OnDestroy()
{
base.method_8("OnDestroy", Array.Empty<object>());
}
public void OnFatalError(FatalErrorMessage message, object userData)
{
object[] objArray1 = new object[] { message, userData };
base.method_8("OnFatalError", objArray1);
}
public void OnFriendListClosed()
{
base.method_8("OnFriendListClosed", Array.Empty<object>());
}
public void OnFriendListFriendSelected(BnetPlayer friend)
{
object[] objArray1 = new object[] { friend };
base.method_8("OnFriendListFriendSelected", objArray1);
}
public void OnFriendListOpened()
{
base.method_8("OnFriendListOpened", Array.Empty<object>());
}
public void OnFriendsChanged(BnetFriendChangelist changelist, object userData)
{
object[] objArray1 = new object[] { changelist, userData };
base.method_8("OnFriendsChanged", objArray1);
}
public void OnKeyboardHide()
{
base.method_8("OnKeyboardHide", Array.Empty<object>());
}
public void OnKeyboardShow()
{
base.method_8("OnKeyboardShow", Array.Empty<object>());
}
public PlayerChatInfo RegisterPlayerChatInfo(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
return base.method_14<PlayerChatInfo>("RegisterPlayerChatInfo", objArray1);
}
public void RemoveAllChatBubbles()
{
base.method_8("RemoveAllChatBubbles", Array.Empty<object>());
}
public void ShowChatForPlayer(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
base.method_8("ShowChatForPlayer", objArray1);
}
public void ShowFriendsList()
{
base.method_8("ShowFriendsList", Array.Empty<object>());
}
public void Start()
{
base.method_8("Start", Array.Empty<object>());
}
public void Update()
{
base.method_8("Update", Array.Empty<object>());
}
public void UpdateChatBubbleLayout()
{
base.method_8("UpdateChatBubbleLayout", Array.Empty<object>());
}
public void UpdateChatBubbleParentLayout()
{
base.method_8("UpdateChatBubbleParentLayout", Array.Empty<object>());
}
public void UpdateLayout()
{
base.method_8("UpdateLayout", Array.Empty<object>());
}
public void UpdateLayoutForOnScreenKeyboard()
{
base.method_8("UpdateLayoutForOnScreenKeyboard", Array.Empty<object>());
}
public void UpdateLayoutForOnScreenKeyboardOnPhone()
{
base.method_8("UpdateLayoutForOnScreenKeyboardOnPhone", Array.Empty<object>());
}
public void UpdatePlayerFocusTime(BnetPlayer player)
{
object[] objArray1 = new object[] { player };
base.method_8("UpdatePlayerFocusTime", objArray1);
}
public void WillReset()
{
base.method_8("WillReset", Array.Empty<object>());
}
public Triton.Game.Mapping.FriendListFrame FriendListFrame
{
get
{
return base.method_14<Triton.Game.Mapping.FriendListFrame>("get_FriendListFrame", Array.Empty<object>());
}
}
public Rect keyboardArea
{
get
{
return base.method_2<Rect>("keyboardArea");
}
}
public Rect KeyboardRect
{
get
{
return base.method_11<Rect>("get_KeyboardRect", Array.Empty<object>());
}
}
public KeyboardState keyboardState
{
get
{
return base.method_2<KeyboardState>("keyboardState");
}
}
public List<ChatBubbleFrame> m_chatBubbleFrames
{
get
{
Class267<ChatBubbleFrame> class2 = base.method_3<Class267<ChatBubbleFrame>>("m_chatBubbleFrames");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public ChatMgrBubbleInfo m_ChatBubbleInfo
{
get
{
return base.method_3<ChatMgrBubbleInfo>("m_ChatBubbleInfo");
}
}
public bool m_chatLogFrameShown
{
get
{
return base.method_2<bool>("m_chatLogFrameShown");
}
}
public float m_chatLogXOffset
{
get
{
return base.method_2<float>("m_chatLogXOffset");
}
}
public PegUIElement m_closeCatcher
{
get
{
return base.method_3<PegUIElement>("m_closeCatcher");
}
}
public Triton.Game.Mapping.FriendListFrame m_friendListFrame
{
get
{
return base.method_3<Triton.Game.Mapping.FriendListFrame>("m_friendListFrame");
}
}
public ChatMgrPrefabs m_Prefabs
{
get
{
return base.method_3<ChatMgrPrefabs>("m_Prefabs");
}
}
public List<BnetPlayer> m_recentWhisperPlayers
{
get
{
Class267<BnetPlayer> class2 = base.method_3<Class267<BnetPlayer>>("m_recentWhisperPlayers");
if (class2 != null)
{
return class2.method_25();
}
return null;
}
}
public enum KeyboardState
{
None,
Below,
Above
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace POTM
{
public class EndGame : MonoBehaviour
{
public LevelChanger lc;
private void OnTriggerEnter(Collider other)
{
if (other.gameObject.GetComponent<PlaneController>())
{
lc.FadeToLevel("StarrySky");
}
}
}
}
|
using Microsoft.Extensions.DependencyInjection;
using System;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using TNBase.DataStorage;
using TNBase.External.DataExport;
using TNBase.External.DataImport;
using TNBase.Repository;
namespace TNBase
{
static class Program
{
private static string applicationDataDirectory;
public static IServiceProvider ServiceProvider { get; private set; }
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.SetHighDpiMode(HighDpiMode.SystemAware);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new ThreadExceptionEventHandler(ExceptionHandler.AppDomain_Application_ThreadException);
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandler.AppDomain_CurrentDomain_UnhandledException);
#if DEBUG
applicationDataDirectory = AppDomain.CurrentDomain.BaseDirectory;
#else
var appDataPath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
applicationDataDirectory = Path.Combine(appDataPath, Application.CompanyName, Application.ProductName);
Directory.CreateDirectory(applicationDataDirectory);
#endif
var services = new ServiceCollection();
ConfigureServices(services);
ServiceProvider = services.BuildServiceProvider();
var databaseManager = ServiceProvider.GetRequiredService<DatabaseManager>();
databaseManager.BackupDatabaseToBackupDrive();
ModuleGeneric.SaveStartTime();
var context = (TNBaseContext)ServiceProvider.GetService<ITNBaseContext>();
if (context == null)
{
MessageBox.Show("Unable to connect to database. Application will be closed.");
return;
}
context.UpdateDatabase();
var serviceLayer = ServiceProvider.GetRequiredService<IServiceLayer>();
serviceLayer.ResumePausedListeners();
serviceLayer.UpdateYearStatsInternal();
serviceLayer.DeleteOverdueDeletedListeners(Properties.Settings.Default.MonthsUntilDelete);
var form = ServiceProvider.GetRequiredService<FormMain>();
Application.Run(form);
}
public static void NewScope()
{
var scope = ServiceProvider.CreateScope();
ServiceProvider = scope.ServiceProvider;
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddSingleton(s => new DatabaseManagerOptions { DataLocation = applicationDataDirectory });
services.AddSingleton<DatabaseManager>();
services.AddScoped(s => s.GetService<DatabaseManager>().Database);
services.AddScoped<IServiceLayer, ServiceLayer>();
services.AddScoped<ScanService>();
services.AddScoped<CsvImportService>();
services.AddScoped<CsvExportService>();
var resourceDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Resource");
services.AddSingleton(s => new ResourceManager(resourceDirectory));
services.AddScoped<FormMain>();
}
}
}
|
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System;
using System.Text;
public class Client_Server
{
public int _port;
public IPAddress _ipAddr;
public Socket _sender;
public Client_Server(int port, IPAddress ipAddr)
{
_ipAddr = ipAddr;
_port = port;
}
public void Start()
{
IPEndPoint ipEndPoint = new IPEndPoint(_ipAddr, _port);
_sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
_sender.Connect(ipEndPoint);
}
public string GetMessage()
{
try
{
byte[] bytes = new byte[1024];
int bytesRec = _sender.Receive(bytes);
return Encoding.UTF8.GetString(bytes, 0, bytesRec);
}
catch
{
return null;
}
}
public void SendMessage(string message)
{
try
{
byte[] bytes = new byte[1024];
bytes = Encoding.UTF8.GetBytes(message);
_sender.Send(bytes);
}
catch
{
}
}
} |
namespace Logic_Circuit.Parser.Validation.VisitorObjects
{
/// <summary>
/// Defines a visitor used to validate ValidationElements.
/// </summary>
public abstract class ValidationVisitor
{
public abstract (bool success, string validationError) VisitNodeLine(NodeLine nodeLine);
public abstract (bool success, string validationError) VisitConnectionLine(ConnectionLine connectionLine);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace CoreComponents
{
public static class OS
{
public static bool CheckIsMacOSX(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.MacOSX;
}
public static bool CheckIsUnix(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.Unix;
}
public static bool CheckIsWin32NT(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.Win32NT;
}
public static bool CheckIsWin32S(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.Win32S;
}
public static bool CheckIsWin32Windows(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.Win32Windows;
}
public static bool CheckIsWinCE(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.WinCE;
}
public static bool CheckIsWindows(OperatingSystem TheOS)
{
PlatformID Platform = TheOS.Platform;
return Platform == PlatformID.Win32NT || Platform == PlatformID.Win32S || Platform == PlatformID.Win32Windows || Platform == PlatformID.WinCE;
}
public static bool CheckIsXbox(OperatingSystem TheOS)
{
return TheOS.Platform == PlatformID.Xbox;
}
public static bool CheckIsWindowsOrXbox(OperatingSystem TheOS)
{
PlatformID Platform = TheOS.Platform;
return Platform == PlatformID.Win32NT || Platform == PlatformID.Win32S || Platform == PlatformID.Win32Windows || Platform == PlatformID.WinCE || Platform == PlatformID.Xbox;
}
public static bool IsMacOSX
{
get
{
return CheckIsMacOSX(Environment.OSVersion);
}
}
public static bool IsUnix
{
get
{
return CheckIsUnix(Environment.OSVersion);
}
}
public static bool IsWin32NT
{
get
{
return CheckIsWin32NT(Environment.OSVersion);
}
}
public static bool IsWin32S
{
get
{
return CheckIsWin32S(Environment.OSVersion);
}
}
public static bool IsWin32Windows
{
get
{
return CheckIsWin32Windows(Environment.OSVersion);
}
}
public static bool IsWinCE
{
get
{
return CheckIsWinCE(Environment.OSVersion);
}
}
public static bool IsWindows
{
get
{
return CheckIsWindows(Environment.OSVersion);
}
}
public static bool IsXbox
{
get
{
return CheckIsXbox(Environment.OSVersion);
}
}
public static bool IsWindowsOrXbox
{
get
{
return CheckIsWindowsOrXbox(Environment.OSVersion);
}
}
}
}
|
namespace HH.RulesEngine.UI.ViewModels.Store
{
using System;
using System.Collections.Generic;
using System.Linq;
using HH.RulesEngine.Data.Entities;
public class CheckoutModel
{
public int Id { get; set; }
public decimal TaxPercentage { get; set; }
public IList<ProductQuantity> Products { get; set; }
public decimal SubTotal
{
get { return Math.Round(Products.Sum(pq => (pq.Quantity * pq.ProductPrice)), 2, MidpointRounding.AwayFromZero); }
}
public decimal Discounts
{
get { return Math.Round(_discounts, 2, MidpointRounding.AwayFromZero); }
set { _discounts = value; }
}
public decimal Fees
{
get { return Math.Round(_fees, 2, MidpointRounding.AwayFromZero); }
set { _fees = value; }
}
public decimal Total
{
get { return Math.Round(_total, 2, MidpointRounding.AwayFromZero); }
set { _total = value; }
}
public decimal Tax
{
get { return Math.Round(_tax, 2, MidpointRounding.AwayFromZero); }
set { _tax = value; }
}
private decimal _discounts;
private decimal _fees;
private decimal _total;
private decimal _tax;
}
} |
using System;
namespace Soko.Domain
{
/// <summary>
/// Summary description for Kategorija.
/// </summary>
public class Kategorija : DomainObject, IComparable
{
public static readonly int NAZIV_MAX_LENGTH = 50;
private string naziv;
public virtual string Naziv
{
get { return naziv; }
set { naziv = value; }
}
public Kategorija()
{
}
public override string ToString()
{
return Naziv;
}
public override void validate(Notification notification)
{
// validate Naziv
if (String.IsNullOrEmpty(Naziv))
{
notification.RegisterMessage(
"Naziv", "Naziv kategorije je obavezan.");
}
else if (Naziv.Length > NAZIV_MAX_LENGTH)
{
notification.RegisterMessage(
"Naziv", "Naziv kategorije moze da sadrzi maksimalno "
+ NAZIV_MAX_LENGTH + " znakova.");
}
}
#region IComparable Members
public virtual int CompareTo(object obj)
{
if (!(obj is Kategorija))
throw new ArgumentException();
Kategorija other = obj as Kategorija;
return this.Naziv.CompareTo(other.Naziv);
}
#endregion
}
}
|
using UnityEngine;
using RimWorld;
using Verse;
using System.Linq;
using System.Text;
using Verse.AI;
using System.Collections.Generic;
namespace Quests
{
public class Action_StartTrade : DialogAction
{
public Action_StartTrade()
{
}
public override void DoAction()
{
if (window.talker.trader != null && window.talker.trader.CanTradeNow)
{
Find.WindowStack.Add(new Dialog_Trade(this.window.initiator, window.talker, false));
}
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Timers;
public class salesforcePolkadotScript : MonoBehaviour {
private float deltaT = 0.01f;
private Texture2D generateRandomTexture(int frequency) {
var texture = new Texture2D (frequency, frequency, TextureFormat.ARGB32, false);
texture.filterMode = FilterMode.Point;
texture.wrapMode = TextureWrapMode.Clamp;
frequency = Mathf.FloorToInt (frequency);
// set the pixel values
for (var i = 0; i < frequency; i++)
{
for (var j = 0; j < frequency; j++)
{
var randomValue = Random.Range(0.0f, 1.0f);
if (randomValue < 0.10f) randomValue = 0.0f;
texture.SetPixel(i, j, new Color(randomValue,randomValue, randomValue, randomValue));
}
}
// Apply all SetPixel calls
texture.Apply ();
return texture;
}
public void Awake() {
// Create a new 2x2 texture ARGB32 (32 bit with alpha) and no mipmaps
var frequency = (int)GetComponent<Renderer> ().material.GetFloat ("_frequency");
var noiseA = generateRandomTexture (frequency);
var noiseB = generateRandomTexture (frequency);
// connect texture to material of GameObject this script is attached to
GetComponent<Renderer>().material.SetTexture("_noiseA", noiseA);
GetComponent<Renderer>().material.SetTexture("_noiseB", noiseB);
}
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update () {
deltaT += Time.deltaTime;
GetComponent<Renderer> ().material.SetFloat("_mixture", Mathf.Sin(deltaT));
}
}
|
//***************************************************************//
// ScribblePhysicsMainScript
//
// This script scans for mouse/touch input and instantiates a new scribble if necessary.
// Relevant user settings can be set in the unity editor or through an external script:
// 1) define a new variable that refers to the ScribblePhysicsMainScript:
// SPMS = gameObjectThatHoldsTheMainScript.GetComponent<ScribblePhysicsMainScript>();
//
// 2) all settings that defines new scribbles can now be accessed/changed as follows
// SPMS.lineWidth = 0.6;
// SPMS.physicsMaterial = userDefinedPhysicsMaterial;
// etc.
//
// The following variables can be set:
//
// * Rect canvasRect
// 'canvasRect' holds the rect that defines the drawing canvas.
// rect-sizes will be interpreted as relative screen-sizes
// e.g.:
// Rect(0,0,1,1) --> use the entire screen
// Rect(0,0,1,0.5) --> use the bottom half of the screen
// Rect(0,0,0.5,1) --> use the right half of the screen
//
// * Camera mainCamera
// The GameObject that holds the main camera.
// If this variable is left empty, than it is assumed that
// main camera is attached to the current gameObject
//
// * float cameraOrthographicSize
// The main camera will be put in orthographic view.
// The (initial) size of this view can be set through this variable
//
// * float drawDistanceFromCamera
// The drawing distance from the camera.
//
// * float lineWidth
// All new scribbles will be drawn using this width
//
// * float lineDepth
// All new scribbles will be draw using this depth value.
// Usually it won't be necessary to change this value
//
// * float density
// Bigger scribbles will have a bigger mass.
// The density is used to calculate this mass.
//
// * Material textureMaterial
// The texture material to be used.
//
// * PhysicMaterial physicsMaterial
// the physics material to be used
//
// * bool scribbleIsDynamic
// 'true': New scribbles will be dynamic, e.g. obey laws of gravity
// 'false' (default): New scribbles will be static
//
// * bool intersectionAllowed
// 'true': Each new scribble can be drawn right through all other
// objects in the scene. This can result in unpredictable
// and unrealistic behaviour from unity's physics engine.
// 'false' (default): Each new scribble can not intersect with other
// objects in the scene. Hitting an object will terminate
// drawing mode and the scribble will be finalized.
//
// * bool smoothScribble
// 'true' (default): The scribble will be smoothed after completion
// 'false': The scribble will not be smoothed after completion
//
//***************************************************************//
//***************************************************************//
//
using UnityEngine;
using System.Collections;
//
//***************************************************************//
public class ScribblePhysicsMainScript : MonoBehaviour
{
//***************************************************************//
//
public Rect canvasRect = new Rect (0f, 0f, 1f, 1f);
public Camera mainCamera;
public float cameraOrthographicSize = 20f;
public float drawDistanceFromCamera = 20f;
[Range (0.1f, 2.0f)]
public float lineWidth = 0.5f;
[Range (0.1f, 2.0f)]
public float lineDepth = 1.0f;
[Range (0.1f, 5.0f)]
public float density = 1.0f;
public Material textureMaterial;
public PhysicMaterial physicsMaterial;
public bool scribbleIsDynamic = false;
public bool intersectionAllowed = false;
public bool smoothScribble = true;
private Touch touch;
private int touchId = -1;
//
//***************************************************************//
//
void Start ()
{
// put the (main) camera in orthographic view,
// and give it a size of 'cameraOrthographicSize'.
// also make sure it faces forward.
if (!mainCamera) {
mainCamera = gameObject.GetComponent<Camera> ();
}
mainCamera.GetComponent<Camera> ().orthographic = true;
mainCamera.GetComponent<Camera> ().orthographicSize = cameraOrthographicSize;
mainCamera.transform.rotation = Quaternion.identity;
// recalculate the canvasRect to real screensizes
canvasRect.width *= Screen.width;
canvasRect.height *= Screen.height;
// Set the ambient light to clear and bright white
RenderSettings.ambientLight = Color.white;
}
//
//***************************************************************//
//***************************************************************//
//
void Update ()
{
// check if there's a new user input, within the defined drawing canvas
touchId = -1;
foreach (Touch touch in Input.touches) {
if (touch.phase == TouchPhase.Began && canvasRect.Contains (touch.position)) {
touchId = touch.fingerId; // remember the touchID, the new scribble needs it to keep track of the movement of this specific gesture
GameObject newObject = new GameObject ();
if (scribbleIsDynamic) {
newObject.name = "DynamicScribble";
} else {
newObject.name = "StaticScribble";
newObject.transform.parent = GameController.instance.scribbleHolder.transform;
}
newObject.AddComponent<ScribblePhysicsObjectScript> ();
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetTextureMaterial (textureMaterial);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetDrawDistance (drawDistanceFromCamera);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetCameraObject (mainCamera);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetLineWidth (lineWidth);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetLineDepth (lineDepth);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetMaterialDensity (density);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetScribbleIsDynamic (scribbleIsDynamic);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetSmoothScribble (smoothScribble);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetTouchId (touchId);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetIntersectionAllowed (intersectionAllowed);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetPhysicsMaterial (physicsMaterial);
}
}
if (Input.GetMouseButtonDown (0) && canvasRect.Contains (Input.mousePosition) && touchId == -1) {
touchId = -1; // setting value to -1, because there is no touchID
GameObject newObject = new GameObject ();
if (scribbleIsDynamic) {
newObject.name = "DynamicScribble";
} else {
newObject.name = "StaticScribble";
newObject.transform.parent = GameController.instance.scribbleHolder.transform;
}
newObject.AddComponent<ScribblePhysicsObjectScript> ();
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetTextureMaterial (textureMaterial);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetDrawDistance (drawDistanceFromCamera);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetCameraObject (mainCamera);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetLineWidth (lineWidth);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetLineDepth (lineDepth);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetMaterialDensity (density);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetScribbleIsDynamic (scribbleIsDynamic);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetSmoothScribble (smoothScribble);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetTouchId (touchId);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetIntersectionAllowed (intersectionAllowed);
newObject.GetComponent<ScribblePhysicsObjectScript> ().SetPhysicsMaterial (physicsMaterial);
}
}
//
//***************************************************************//
}
|
namespace HaloHistory.Business.Utilities
{
public class Constants
{
public const string PerfectKill = "780104cb-5b86-4ed9-8fb1-40b919de0766";
public const string RoundWinningKill = "5262f1d7-4273-48c3-8d2f-edfcb36a1617";
public const string FlagCapture = "7cda10c8-04c4-4916-8d6e-71a426a61de8";
public const string FlagGrabs = "0a719185-4780-4706-b9e6-f679fcbc65d6";
public const string FlagCarrierKills = "6e1e4e2c-1a57-4f64-a893-f594974b3f1f";
public const string StrongholdCaptured = "2b151d0f-cde6-4471-9f1d-d0f8e8644471";
public const string StrongholdDefense = "dcd5ff64-4b49-4020-96d0-88ba3fb28a56";
public const string StrongholdSecured = "f0d50d01-6197-4d0d-a3a5-a86110997e40";
public const string Score = "ba1b0043-3a1e-4894-a04f-f8d889103ec5";
public const string Kills = "7eade0bd-ae40-49f8-a6a4-536e7efdff11";
public const string RoundsSurvived = "f806f7ff-1ad0-457e-b649-b2ab707fff3b";
public const string RoundsComplete = "a52d165f-b42b-42ef-bb10-d857646ce5be";
public const string MythicTakedown = "3cc3c9a3-c9cc-4c42-991a-c7b91085eefb";
public const string LegendaryTakedown = "06ba69fe-3208-4a3e-821e-c92cbad89042";
public const string BossTakedown = "65df9735-86e1-48b3-a286-08b1d8af9c81";
public const string BasesCaptured = "63783dc0-7c2d-436a-bd5b-22da2f4705d4";
public const long SpartanWeaponId = 3168248199;
}
}
|
using UnityEngine;
using UnityEngine.SceneManagement;
public class Start : MonoBehaviour
{
public GameObject StartUI;
public GameObject button;
public void Startgame()
{
button.SetActive(false);
StartUI.SetActive(true);
Invoke("startInvoke", 1f);
}
void startInvoke()
{
SceneManager.LoadScene("StackUp");
}
} |
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;
using PowerString;
using PowerString.Data;
namespace PowerString
{
public partial class DeleteConfirmForm : Form
{
private MainMenuForm _mainMenuForm;
private UserInfoForm _userInfoForm;
private Tester _tester;
private DeleteConfirmForm()
{
InitializeComponent();
}
public DeleteConfirmForm(MainMenuForm mainMenuForm, UserInfoForm userInfoForm, Tester tester) : this()
{
_mainMenuForm = mainMenuForm;
_userInfoForm = userInfoForm;
_tester = tester;
}
private void DeleteOK_Click(object sender, EventArgs e)
{
MessageBox.Show("계정이 삭제되었습니다.");
DataRepository.Tester.Delete(_tester);
this.Close();
_userInfoForm.Close();
_mainMenuForm.CloseForm();
MoveEvent.MoveToForm(new StartForm());
}
private void DeleteNO_Click(object sender, EventArgs e)
{
this.Close();
}
private void DeleteNO_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Escape)
{
this.Close();
}
}
}
}
|
using App1.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App1
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
DependencyService.Get<IDownload>().DownloadFile();
}
protected override void OnAppearing()
{
base.OnAppearing();
App.Self.PropertyChanged += (s, e) => PropertyChange(s, e);
}
private void PropertyChange(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
if (e.PropertyName == "DownloadProgress")
{
var downloaded = (double)App.Self.DownloadProgress / (double)App.Self.DownloadTotal;
progress.Progress = downloaded;
if (!App.Self.DownloadCompleted)
Device.BeginInvokeOnMainThread(() => lblProg.Text = string.Format("Downloading {0}%", (int)(downloaded * 100)));
if (App.Self.DownloadTotal == App.Self.DownloadProgress)
App.Self.DownloadCompleted = true;
}
if (e.PropertyName == "DownloadCompleted")
{
Device.BeginInvokeOnMainThread(() =>
{
lblProg.Text = "Download completed";
var image = new Image
{
WidthRequest = 200,
HeightRequest = 250,
Source = DependencyService.Get<IDownload>().GetFilename()
};
progressStack.Children.Add(image);
});
}
}
}
} |
using System.Linq;
using OCP;
using OCP.App;
using OCP.Authentication.TwoFactorAuth;
namespace OCA.TwoFactorBackupCodes.Provider
{
public class BackupCodesProvider : IProvider, IProvidesPersonalSettings
{
/** @var string */
private string appName;
/** @var BackupCodeStorage */
private BackupCodeStorage storage;
/** @var IL10N */
private IL10N l10n;
/** @var AppManager */
private IAppManager appManager;
/** @var IInitialStateService */
private IInitialStateService initialStateService;
/**
* @param string appName
* @param BackupCodeStorage storage
* @param IL10N l10n
* @param AppManager appManager
*/
public BackupCodesProvider(string appName,
BackupCodeStorage storage,
IL10N l10n,
IAppManager appManager,
IInitialStateService initialStateService) {
this.appName = appName;
this.l10n = l10n;
this.storage = storage;
this.appManager = appManager;
this.initialStateService = initialStateService;
}
/**
* Get unique identifier of this 2FA provider
*
* @return string
*/
public string getId() {
return "backup_codes";
}
/**
* Get the display name for selecting the 2FA provider
*
* @return string
*/
public string getDisplayName() {
return this.l10n.t("Backup code");
}
/**
* Get the description for selecting the 2FA provider
*
* @return string
*/
public string getDescription() {
return this.l10n.t("Use backup code");
}
/**
* Get the template for rending the 2FA provider view
*
* @param IUser user
* @return Template
*/
public Template getTemplate(IUser user) {
return new Template("twofactor_backupcodes", "challenge");
}
/**
* Verify the given challenge
*
* @param IUser user
* @param string challenge
* @return bool
*/
public bool verifyChallenge(IUser user, string challenge) {
return this.storage.validateCode(user, challenge);
}
/**
* Decides whether 2FA is enabled for the given user
*
* @param IUser user
* @return boolean
*/
public bool isTwoFactorAuthEnabledForUser(IUser user) {
return this.storage.hasBackupCodes(user);
}
/**
* Determine whether backup codes should be active or not
*
* Backup codes only make sense if at least one 2FA provider is active,
* hence this method checks all enabled apps on whether they provide 2FA
* functionality or not. If there's at least one app, backup codes are
* enabled on the personal settings page.
*
* @param IUser user
* @return boolean
*/
public bool isActive(IUser user) {
var appIds = this.appManager.getEnabledAppsForUser(user).Where(appId => appId != this.appName).ToList();
foreach (var appId in appIds)
{
var info = this.appManager.getAppInfo(appId);
if (info.Twofactorproviders != null && info.Twofactorproviders.Providers.Count > 0 )
{
return true;
}
}
return false;
}
/**
* @param IUser user
*
* @return IPersonalProviderSettings
*/
public IPersonalProviderSettings getPersonalSettings(IUser user) {
var state = this.storage.getBackupCodesState(user);
this.initialStateService.provideInitialState(this.appName, "state", state);
return new Personal();
}
}
} |
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using Kers.Models.Entities.KERScore;
namespace Kers.Models.Entities.SoilData
{
public partial class FormTypeSignees : IEntityBase
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public CountyCode PlanningUnit {get;set;}
public int PlanningUnitId {get;set;}
public TypeForm TypeForm {get;set;}
public int TypeFormId {get;set;}
public string Signee {get;set;}
public string Title {get;set;}
}
} |
namespace XRTTicket.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class XRT001 : DbMigration
{
public override void Up()
{
CreateTable(
"dbo.AspNetRoles",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
Name = c.String(),
})
.PrimaryKey(t => t.Id);
CreateTable(
"dbo.Ticket",
c => new
{
TicketId = c.Int(nullable: false, identity: true),
OpenDateAndTime = c.DateTime(nullable: false),
ClosedDateTime = c.DateTime(),
VersionId = c.Int(nullable: false),
PriorityId = c.Int(nullable: false),
CompanyId = c.Int(nullable: false),
IdExternal = c.Int(),
UserId = c.String(),
AnalystDesignated = c.String(),
Rate = c.Int(),
SlaExpiration = c.DateTime(nullable: false),
Environment = c.String(),
Impact = c.String(),
TicketTypeId = c.Int(nullable: false),
DuplicatedOf = c.Int(),
StatusId = c.Int(nullable: false),
ProductId = c.Int(nullable: false),
SubProductId = c.Int(nullable: false),
TaskId = c.Int(nullable: false),
Title = c.String(nullable: false, maxLength: 50),
})
.PrimaryKey(t => t.TicketId);
}
public override void Down()
{
DropTable("dbo.Ticket");
DropTable("dbo.AspNetRoles");
}
}
}
|
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Common;
using Common.Log;
using Flurl.Http;
using Lykke.Service.SmsSender.Core.Services;
using Lykke.Service.SmsSender.Core.Settings.ServiceSettings.SenderSettings;
namespace Lykke.Service.SmsSender.Services.SmsSenders.Nexmo
{
public class NexmoSmsSender : ISmsSender
{
private readonly string _baseUrl;
private readonly ProviderSettings _settings;
private readonly ILog _log;
public NexmoSmsSender(
string baseUrl,
ProviderSettings settings,
ILog log)
{
_baseUrl = baseUrl;
_settings = settings;
_log = log.CreateComponentScope(nameof(NexmoSmsSender));
}
public async Task<string> SendSmsAsync(string commandId, string phone, string message, string countryCode)
{
int index = 0;
while (++index <= 3)
{
try
{
var sw = new Stopwatch();
_log.WriteInfo(nameof(SendSmsAsync), new {Id = commandId, Phone = phone.SanitizePhone(), CountryCode = countryCode},
$"Sending sms to nexmo endpoint {_settings.BaseUrl}/sms/json");
sw.Start();
var response = await $"{_settings.BaseUrl}/sms/json"
.WithTimeout(10)
.PostUrlEncodedAsync(new
{
to = phone,
from = _settings.GetFrom(countryCode),
text = message,
api_key = _settings.ApiKey,
api_secret = _settings.ApiSecret,
callback = $"{_baseUrl}/callback/nexmo"
}).ReceiveJson<NexmoResponse>();
sw.Stop();
_log.WriteInfo(nameof(SendSmsAsync), new {Id = commandId, messagesCount = response.MessagesCount, ElapsedMsec = sw.ElapsedMilliseconds },
$"Sms has been sent to nexmo endpoint {_settings.BaseUrl}/sms/json");
if (response.MessagesCount > 0)
{
var errors = response.Messages
.Where(item => item.Status != NexmoStatus.Ok)
.Select(item => new
{
Phone = phone.SanitizePhone(), item.Status, item.Error, item.RemainingBalance
})
.ToList();
if (errors.Any())
{
var notEnoughFunds =
errors.FirstOrDefault(item => item.Status == NexmoStatus.PartnerQuotaExceeded);
if (notEnoughFunds != null)
_log.WriteWarning(nameof(SendSmsAsync), new { Id = commandId, Error = notEnoughFunds }, "Not enough funds on Nexmo provider");
else
_log.WriteWarning(nameof(SendSmsAsync), new { Id = commandId, Errors = errors }, "Error sending SMS");
}
return response.Messages.FirstOrDefault(item => item.Status == NexmoStatus.Ok)?.MessageId;
}
else
{
_log.WriteWarning(nameof(SendSmsAsync), new { Id = commandId }, "Unexpected messages count in Nexmo response");
}
}
catch (Exception ex)
{
_log.WriteWarning(nameof(SendSmsAsync), new { Id = commandId }, "Error sending SMS", ex);
}
_log.WriteWarning(nameof(SendSmsAsync), new { Id = commandId }, "Failed to send SMS via Nexmo. Will be retried in 1 second");
await Task.Delay(1000);
}
_log.WriteWarning(nameof(SendSmsAsync), new { Id = commandId }, "First-level retries of SMS sending are exhausted");
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UrTLibrary.Server.Exceptions
{
public class TooMuchCommandFoundException : TooMuchElementFoundException
{
public TooMuchCommandFoundException(string target, params string[] results) : base("command", target, results)
{
}
}
}
|
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
// VisualNovelToolkit /_/_/_/_/_/_/_/_/_/.
// Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/.
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/.
#define ENABLE_DEBUG_MENU
#pragma warning disable 0219,0414,0649
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Debug Menu.
/// You can check the game state at runtime.
/// </summary>
public class _DebugMenu : MonoBehaviour {
public TextAsset requestTxtAsset1;
public TextAsset requestTxtAsset2;
public TextAsset requestTxtAsset3;
public TextMesh debugButtonText;
public Texture2D fontTexture;
public Font font;
public GameObject fontObject;
public GameObject mainPanel;
public bool show;
private float m_TargetFramerate = 60f;
// private string[] debugMenuItems = { "Scenario" , "Flag" , "Memory" , "Node" , "Font" , "Objects" , "FrameRate" };
private string[] debugMenuItems = { "Scenario" , "Flag" , "Memory" , "FrameRate" } ;//"Node" , "Font" , "Objects" , };
private int m_SelectedID = 0;
private List<string> m_NodeStrList;
private Rect m_WinRect;
private bool showMainPanel = true;
void Awake(){
Application.targetFrameRate = (int)m_TargetFramerate;
m_WinRect = new Rect( Screen.width/2 , 0 , Screen.width/2 , Screen.height/4f * 3f );
}
void OnClickDebugMenu(){
show = ! show;
if( show ){
if( ScenarioNode.Instance != null ){
/* if( VM.Instance != null ){
Dictionary<string,int>.KeyCollection keys = VM.Instance.GetNodeKeys();
m_NodeStrList = new List<string>();
foreach( string key in keys ){
m_NodeStrList.Add( key );
}
}
//*/
#if true
m_NodeStrList = ScenarioNode.Instance.GetNodeTagsUnderMe();
#else
ViNode[] nodes = ScenarioNode.Instance.GetComponentsInChildren<ViNode>();
m_NodeStrList = new List<string>();
for( int i=0;i<nodes.Length;i++){
m_NodeStrList.Add( nodes[ i ].GetNodeTag( nodes[ i ].name ) );
}
#endif
}
}
}
#if ENABLE_DEBUG_MENU
private Vector2 m_ScrollPos = Vector2.zero;
// Scene: Girls Talk Objects.
private bool _ToggleActiveBG_Street = true;
private bool _ToggleActiveCF_Girl = true;
private bool _ToggleActiveCF_Lady = true;
private bool _ToggleActiveCharacter = true;
private bool _ToggleActiveSystemUI = true;
private bool _ToggleActiveMenuBar = true;
public string[] varTypes = { "Passed Label" , "String" };
public int selectedVarType = 0;
void DrawDebugMenu( int windowID ){
show = GUILayout.Toggle( show , "Close" );
GUILayout.Label( "FPS:" + frameRate.ToString() );
m_SelectedID = GUILayout.SelectionGrid( m_SelectedID , debugMenuItems , 4 , GUILayout.Height(88f) );
m_ScrollPos = GUILayout.BeginScrollView( m_ScrollPos );
bool showFont = false;
string item = debugMenuItems[ m_SelectedID ];
switch( item ){
case "FrameRate":
m_TargetFramerate = GUILayout.HorizontalSlider( m_TargetFramerate , 30f , 60f );
GUILayout.Label( "TargetFPS:" + m_TargetFramerate.ToString() );
Application.targetFrameRate = (int)m_TargetFramerate;
break;
case "Scenario":
ScenarioNode s = ScenarioNode.Instance;
if( s != null ){
if( GUILayout.Button( "Play:" + s.name , GUILayout.Height( 66f ) )){
s.Play();
}
}
break;
case "Node":
if( m_NodeStrList != null ){
for( int i=0;i<m_NodeStrList.Count;i++){
if( GUILayout.Button( m_NodeStrList[ i ] , GUILayout.Height( 44f ) )){
VM.Instance.GoToLabel( m_NodeStrList[ i ] );
}
}
}
break;
case "Flag":
selectedVarType = GUILayout.Toolbar( selectedVarType , varTypes );
if( ScenarioNode.Instance != null && ScenarioNode.Instance.flagTable != null ){
string type = varTypes[ selectedVarType ];
FlagTable flagTable = ScenarioNode.Instance.flagTable;
GUILayout.Button( "FlagTable Name:" + flagTable.name );
switch( type ){
case "Passed Label":
if( flagTable.flags != null ){
for( int i=0;i<flagTable.flags.Length;i++){
string label = flagTable.flags[ i ].m_FlagName;
flagTable.flags[ i ].m_IsFlagOn = GUILayout.Toggle( flagTable.flags[ i ].m_IsFlagOn , label );
}
}
break;
case "String":
if( flagTable.stringValues != null ){
for( int i=0;i<flagTable.stringValues.Length;i++){
string label = flagTable.stringValues[ i ].m_FlagName;
if( ! string.IsNullOrEmpty( flagTable.stringValues[ i ].theValue ) ){
GUILayout.BeginHorizontal();
GUILayout.Label( label );
flagTable.stringValues[ i ].theValue = GUILayout.TextField( flagTable.stringValues[ i ].theValue );
GUILayout.EndHorizontal();
}
}
}
break;
}
}
break;
case "Memory":
GUILayout.Label( "VM Code Size (bytes):" + VM.Instance.code.Length.ToString() );
if( GUILayout.Button("Cause GC" , GUILayout.Height( 44f )) ){
System.GC.Collect();
}
if( GUILayout.Button("Resource Unloadunused Asset" , GUILayout.Height( 44f )) ){
Resources.UnloadUnusedAssets();
}
GUILayout.Label( "Total Memory (bytes):" + System.GC.GetTotalMemory(false).ToString() );
break;
case "Font":
showFont = true;
GUILayout.Label( "Font Texture width : " + fontTexture.width );
GUILayout.Label( "Font Texture height : " + fontTexture.height );
if ( GUILayout.Button( "Request String 1" , GUILayout.Height( 66f ) ) ){
font.RequestCharactersInTexture( requestTxtAsset1.text );
}
if ( GUILayout.Button( "Request String 2" , GUILayout.Height( 66f ) ) ){
font.RequestCharactersInTexture( requestTxtAsset2.text );
}
if ( GUILayout.Button( "Request String 3" , GUILayout.Height( 66f ) ) ){
font.RequestCharactersInTexture( requestTxtAsset3.text );
}
break;
case "Objects":
GUILayout.BeginHorizontal();
_ToggleActiveBG_Street = GUILayout.Toggle( _ToggleActiveBG_Street , "BG_Street" , GUILayout.Height( 44f ) );
_ToggleActiveCharacter = GUILayout.Toggle( _ToggleActiveCharacter , "character" , GUILayout.Height( 44f ) );
_ToggleActiveSystemUI = GUILayout.Toggle( _ToggleActiveSystemUI , "SystemUI" , GUILayout.Height( 44f ) );
_ToggleActiveMenuBar = GUILayout.Toggle( _ToggleActiveMenuBar , "MenuBar" , GUILayout.Height( 44f ) );
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
_ToggleActiveCF_Girl = GUILayout.Toggle( _ToggleActiveCF_Girl , "Girl" , GUILayout.Height( 44f ) );
_ToggleActiveCF_Lady = GUILayout.Toggle( _ToggleActiveCF_Lady , "Lady" , GUILayout.Height( 44f ) );
GUILayout.EndHorizontal();
GOCache.SetActive( "BG_Street" , _ToggleActiveBG_Street );
GOCache.SetActive( "CF_Girl" , _ToggleActiveCF_Girl );
GOCache.SetActive( "CF_Lady" , _ToggleActiveCF_Lady );
GOCache.SetActive( "character" , _ToggleActiveCharacter );
GOCache.SetActive( "SystemUI" , _ToggleActiveSystemUI );
GOCache.SetActive( "MenuBar" , _ToggleActiveMenuBar );
break;
//*/
}
GUILayout.EndScrollView();
/*
if( fontObject != null ){
fontObject.SetActive( showFont );
}
showMainPanel = GUILayout.Toggle( showMainPanel , "Show Main ColorPanel");
if( showMainPanel ){
mainPanel.SetActive( true );
}
else{
mainPanel.SetActive( false );
}
//*/
}
void OnGUI(){
show = GUI.Toggle( new Rect( Screen.width/2f , 0f , 100 , 100) , show , "Debug" );
if( ! show ){
return;
}
//*/
m_WinRect = GUILayout.Window( 0 , m_WinRect , DrawDebugMenu , "DebugMenu" );
}
void Update(){
UpdateFPS();
}
private float oldTime;
private int frame = 0;
private float frameRate = 0f;
private const float INTERVAL = 0.5f;
private void UpdateFPS(){
frame++;
float time = Time.realtimeSinceStartup - oldTime;
if (time >= INTERVAL ){
frameRate = frame / time;
oldTime = Time.realtimeSinceStartup;
frame = 0;
/* System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append( "Debug");
sb.Append( System.Environment.NewLine );
sb.Append( "Fps:" + frameRate.ToString() );
debugButtonText.text = sb.ToString();
//*/
if( debugButtonText != null ){
debugButtonText.text = frameRate.ToString();
}
}
}
#endif
}
|
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Kers.Models.Repositories;
using Kers.Models.Entities.KERScore;
using Kers.Models.Entities.KERSmain;
using Kers.Models.Abstract;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Linq.Expressions;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using Kers.Models.Entities;
using Kers.Models.Contexts;
using Newtonsoft.Json;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using System.Text.RegularExpressions;
namespace Kers.Controllers
{
[Route("api/[controller]")]
public class MileageController : BaseController
{
ILogRepository logRepo;
IFiscalYearRepository fiscalYearRepo;
IExpenseRepository expenseRepo;
public MileageController(
KERSmainContext mainContext,
KERScoreContext context,
IKersUserRepository userRepo,
ILogRepository logRepo,
IExpenseRepository expenseRepo,
IFiscalYearRepository fiscalYearRepo
):base(mainContext, context, userRepo){
this.context = context;
this.mainContext = mainContext;
this.userRepo = userRepo;
this.logRepo = logRepo;
this.fiscalYearRepo = fiscalYearRepo;
this.expenseRepo = expenseRepo;
}
[HttpGet("numb")]
[Authorize]
public IActionResult GetNumb(){
var lastExpenses = context.Expense.
Where(e=>e.KersUser == this.CurrentUser());
return new OkObjectResult(lastExpenses.Count());
}
[HttpGet("byrevid/{Id}")]
[Authorize]
public IActionResult ByRevId(int Id){
var revFull = this.context.ExpenseRevision
.Where( r => r.Id == Id)
.Include( r => r.Segments ).ThenInclude( s => s.Location).ThenInclude( l => l.Address)
.Include( r => r.StartingLocation).ThenInclude( s => s.Address)
.FirstOrDefault();
return new OkObjectResult(revFull);
}
[HttpGet("latest/{skip?}/{amount?}/{userId?}")]
[Authorize]
public IActionResult Get(int skip = 0, int amount = 10, int userId = 0){
if(userId == 0){
var user = this.CurrentUser();
userId = user.Id;
}
var lastExpenses = context.Expense.
Where(e=>e.KersUser.Id == userId).
Include(e=>e.Revisions).
OrderByDescending(e=>e.ExpenseDate).
Skip(skip).
Take(amount).ToList();
var revs = new List<ExpenseRevision>();
if( lastExpenses != null){
foreach(var expense in lastExpenses){
if(expense.Revisions.Count != 0){
var lastRev = expense.Revisions.OrderBy(r=>r.Created).Last();
var revFull = this.context.ExpenseRevision
.Where( r => r.Id == lastRev.Id)
.Include( r => r.Segments ).ThenInclude( s => s.Location).ThenInclude( l => l.Address)
.Include( r => r.StartingLocation).ThenInclude( s => s.Address)
.FirstOrDefault();
revs.Add( revFull );
}
}
}
return new OkObjectResult(revs);
}
[HttpGet("permonth/{year}/{month}/{userId?}/{orderBy?}")]
[Authorize]
public IActionResult PerMonth(int year, int month, int userId=0, string orderBy = "desc"){
KersUser user;
if(userId == 0){
user = this.CurrentUser();
}else{
user = this.context.KersUser.Where(u => u.Id == userId).FirstOrDefault();
}
var mileages = expenseRepo.MileagePerMonth(user, year, month).OrderBy( r => r.ExpenseDate);
var revs = mileages.Select( m => m.LastRevision);
return new OkObjectResult(revs);
}
[HttpGet("summarypermonth/{year}/{month}/{userId?}")]
[Authorize]
public IActionResult SummaryPerMonth(int year, int month, int userId=0){
KersUser user;
if(userId == 0){
user = this.CurrentUser();
}else{
user = this.context.KersUser.Where(u => u.Id == userId)
.Include( u => u.RprtngProfile)
.FirstOrDefault();
}
var mileages = expenseRepo.MileagePerMonth(user, year, month);
var segments = new List<MileageSegment>();
foreach( var mileage in mileages){
segments.AddRange( mileage.LastRevision.Segments);
}
List<ExpenseSummary> summaries = new List<ExpenseSummary>();
var sources = this.context.ExpenseFundingSource.Where( s => s.MileageAvailable);
foreach( var source in sources){
var sourceSegments = segments.Where( s => s.FundingSourceId == source.Id);
if(sourceSegments.Count() > 0){
var summary = new ExpenseSummary();
summary.miles = sourceSegments.Sum( s => s.Mileage );
summary.fundingSource = source;
summary.mileageCost = expenseRepo.MileageRate(user, year, month);
summary.total = summary.miles * summary.mileageCost;
summaries.Add(summary);
}
}
return new OkObjectResult(summaries);
}
[HttpGet("source/{id}")]
[Authorize]
public IActionResult SourceById(int id){
var srce = this.context.ExpenseFundingSource.Find(id);
return new OkObjectResult(srce);
}
[HttpGet("sources")]
[Authorize]
public IActionResult Sources(){
var srce = this.context.ExpenseFundingSource.Where( s => s.MileageAvailable);
return new OkObjectResult(srce);
}
[HttpGet("category/{id}")]
[Authorize]
public IActionResult CategoryById(int id){
var srce = this.context.ProgramCategory.Find(id);
return new OkObjectResult(srce);
}
[HttpGet("categories")]
[Authorize]
public IActionResult Categories(){
var srce = this.context.ProgramCategory;
return new OkObjectResult(srce);
}
[HttpGet("vehicle/{id}")]
[Authorize]
public IActionResult VehicleById(int id){
var vhcl = this.context.CountyVehicle.Find(id);
return new OkObjectResult(vhcl);
}
[HttpPost()]
[Authorize]
public IActionResult AddExpense( [FromBody] ExpenseRevision expense){
if(expense != null){
var user = this.CurrentUser();
var exp = new Expense();
exp.KersUser = user;
exp.Created = DateTime.Now;
exp.Updated = DateTime.Now;
exp.ExpenseDate = expense.ExpenseDate;
exp.PlanningUnitId = user.RprtngProfile.PlanningUnitId;
expense.Created = DateTime.Now;
exp.Revisions = new List<ExpenseRevision>();
exp.Revisions.Add(expense);
context.Add(exp);
context.SaveChanges();
this.Log(expense,"MileageReveision", "Mileage Added.", "MileageReveision", "Created Mileage Record");
exp.LastRevisionId = expense.Id;
context.SaveChanges();
return new OkObjectResult(expense);
}else{
this.Log( expense ,"MileageReveision", "Error in adding expense attempt.", "Expense", "Error");
return new StatusCodeResult(500);
}
}
[HttpPut("{id}")]
public IActionResult UpdateExpense( int id, [FromBody] ExpenseRevision expense){
var entity = context.ExpenseRevision.Find(id);
var exEntity = context.Expense.Find(entity.ExpenseId);
if(expense != null && exEntity != null){
expense.Created = DateTime.Now;
exEntity.Revisions.Add(expense);
exEntity.ExpenseDate = expense.ExpenseDate;
context.SaveChanges();
exEntity.LastRevisionId = expense.Id;
this.Log(expense,"ExpenseRevision", "Expense Updated.");
return new OkObjectResult(expense);
}else{
this.Log( expense ,"ExpenseRevision", "Not Found Expense in update attempt.", "Expense", "Error");
return new StatusCodeResult(500);
}
}
[HttpDelete("{id}")]
public IActionResult DeleteExpense( int id ){
var entity = context.ExpenseRevision.Find(id);
var exEntity = context.Expense.Find(entity.ExpenseId);
if(exEntity != null){
exEntity.LastRevisionId = 0;
context.SaveChanges();
context.Expense.Remove(exEntity);
context.SaveChanges();
this.Log(entity,"ExpenseRevision", "Expense Removed.");
return new OkResult();
}else{
this.Log( id ,"ExpenseRevision", "Not Found Expense in delete attempt.", "Expense", "Error");
return new StatusCodeResult(500);
}
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//Kurtis Watson
public class Ability_Handler : MonoBehaviour
{
[Header("Script References")]
[Space(2)]
private Player_Controller m_playerController; //Reference to player controller.
[Header("Ability Properties")]
[Space(2)]
[Tooltip("Set the amount of knives to spawn when the knife ability is used.")]
public int totalKnives;
public Transform shotPoint; //Where bullets are shot from.
private RaycastHit m_hitscanCast; //The raycast that determines the direction of the bullet.
[Header("Ability Objects")]
[Space(2)]
[Tooltip("The obejct that is spawned when the wall ability is used.")]
public GameObject wall; //Ability Game Objects.
[Tooltip("The object that is spawned when the wall ability is activated.")]
public GameObject storm;
[Tooltip("The object that is spawned when the knife throwing ability is activated.")]
public GameObject knife;
[Tooltip("The object that is spawned when the tornado object is used.")]
public GameObject tornado;
[Tooltip("The object that is spawned when the infector is used.")]
public GameObject infector;
[Tooltip("The object that is spawned when the pushback ability is used.")]
public GameObject pushBack;
private void Start()
{
m_playerController = GameObject.FindObjectOfType<Player_Controller>();
}
public void f_spawnWall() //Spawn a wall.
{
if (Physics.Raycast(shotPoint.position, shotPoint.forward, out m_hitscanCast, Mathf.Infinity)) //Creates a Raycast in direction player is looking.
{
GameObject o_wall = Instantiate(wall, new Vector3(m_hitscanCast.point.x, m_hitscanCast.point.y - 2, m_hitscanCast.point.z), Quaternion.LookRotation(Vector3.forward)); //Instantiate a wall that summons at the position of the players crosshair location.
o_wall.transform.eulerAngles = new Vector3(o_wall.transform.eulerAngles.x, m_playerController.playerRotX, o_wall.transform.eulerAngles.z); //Rotate the wall based on angle of player.
}
}
public void f_spawnTornado() //Spawn a tornado.
{
if (Physics.Raycast(shotPoint.position, shotPoint.forward, out m_hitscanCast, Mathf.Infinity)) //Creates a Raycast.
{
Instantiate(tornado, new Vector3(m_hitscanCast.point.x, m_hitscanCast.point.y - 2, m_hitscanCast.point.z), Quaternion.LookRotation(Vector3.forward)); //Spawns a tornado at position of player crosshair.
}
}
public void f_spawnStorm() //Spawn a storm.
{
if (Physics.Raycast(shotPoint.position, shotPoint.forward, out m_hitscanCast, Mathf.Infinity)) //Creates a Raycast.
{
Instantiate(storm, new Vector3(m_hitscanCast.point.x, m_hitscanCast.point.y - 2, m_hitscanCast.point.z), Quaternion.LookRotation(Vector3.forward)); //Intantiate a tornado at crosshair location.
}
}
public void f_spawnPushback() //Push enemies back.
{
Instantiate(pushBack, shotPoint.transform.position, shotPoint.rotation); //Spawn the pushback gameobject that adds force to any enemy that is hit.
}
public void f_spawnKnives() //Spawn knives.
{
float m_sideDirection = -40; //Angle of first knife.
for (int i = 0; i < totalKnives; i++) //Instantiate a set amount of knives.
{
GameObject m_knife = Instantiate(knife, shotPoint.position, Quaternion.identity);
Rigidbody m_krb = m_knife.GetComponent<Rigidbody>(); //Access that specific knife RigidBody and >
m_krb.AddForce(shotPoint.forward * 100);
m_krb.AddForce(shotPoint.right * m_sideDirection);
m_sideDirection += 10; //> change the RigidBody force from the right direction so it 'spreads' correctly.
}
}
public void f_spawnInfector() //Spawn infector.
{
if (Physics.Raycast(shotPoint.position, shotPoint.forward, out m_hitscanCast, Mathf.Infinity)) //Creates a Raycast.
{
Instantiate(infector, new Vector3(m_hitscanCast.point.x, m_hitscanCast.point.y - 2, m_hitscanCast.point.z), Quaternion.LookRotation(Vector3.forward)); //Spawns a tornade of position of player crosshair.
}
}
}
|
using System;
using System.Collections.Generic;
namespace RestApiEcom.Models
{
public partial class TCPieceIdentite
{
public TCPieceIdentite()
{
TCContribuable = new HashSet<TCContribuable>();
TCProprietaireOrdinaire = new HashSet<TCProprietaireOrdinaire>();
}
public string PieceCode { get; set; }
public string PieceLibelle { get; set; }
public virtual ICollection<TCContribuable> TCContribuable { get; set; }
public virtual ICollection<TCProprietaireOrdinaire> TCProprietaireOrdinaire { get; set; }
}
}
|
using System;
namespace TwinkleStar.Data.XMLRepository
{
/// <summary>
/// XML实体基类
/// </summary>
public abstract class XMLEntity : EntityBase
{
private string id = Guid.NewGuid().ToString();
/// <summary>
/// XML实体主键
/// </summary>
public string RootID
{
get { return id; }
set { id = value; }
}
}
}
|
// Accord Machine Learning 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.MachineLearning.DecisionTrees.Pruning
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Accord.Math;
using Accord.Statistics;
using Accord.MachineLearning.Structures;
/// <summary>
/// Reduced error pruning.
/// </summary>
///
public class ReducedErrorPruning
{
DecisionTree tree;
double[][] inputs;
int[] outputs;
int[] actual;
Dictionary<DecisionNode, NodeInfo> info;
private class NodeInfo
{
public List<int> subset;
public double error;
public double gain;
public NodeInfo()
{
subset = new List<int>();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="ReducedErrorPruning"/> class.
/// </summary>
///
/// <param name="tree">The tree to be pruned.</param>
/// <param name="inputs">The pruning set inputs.</param>
/// <param name="outputs">The pruning set outputs.</param>
///
public ReducedErrorPruning(DecisionTree tree, double[][] inputs, int[] outputs)
{
this.tree = tree;
this.inputs = inputs;
this.outputs = outputs;
this.info = new Dictionary<DecisionNode, NodeInfo>();
this.actual = new int[outputs.Length];
foreach (var node in tree)
info[node] = new NodeInfo();
for (int i = 0; i < inputs.Length; i++)
trackDecisions(tree.Root, inputs[i], i);
}
/// <summary>
/// Computes one pass of the pruning algorithm.
/// </summary>
///
public double Run()
{
// Compute misclassifications at each node
foreach (var node in tree)
info[node].error = computeError(node);
// Compute the gain at each node
foreach (var node in tree)
info[node].gain = computeGain(node);
// Get maximum violating node
double maxGain = Double.NegativeInfinity;
DecisionNode maxNode = null;
foreach (var node in tree)
{
double gain = info[node].gain;
if (gain > maxGain)
{
maxGain = gain;
maxNode = node;
}
}
if (maxGain >= 0 && maxNode != null)
{
int[] o = outputs.Submatrix(info[maxNode].subset.ToArray());
// prune the maximum gain node
int common = Measures.Mode(o);
maxNode.Branches = null;
maxNode.Output = common;
}
return computeError();
}
private double computeError(DecisionNode node)
{
List<int> indices = info[node].subset;
int error = 0;
foreach (int i in indices)
if (outputs[i] != actual[i]) error++;
return error / (double)indices.Count;
}
private double computeGain(DecisionNode node)
{
if (node.IsLeaf) return Double.NegativeInfinity;
// Compute the sum of misclassifications at the children
double sum = 0;
foreach (var child in node.Branches)
sum += info[child].error;
// Get the misclassifications at the current node
double current = info[node].error;
// Compute the expected gain at the current node:
return sum - current;
}
private double computeError()
{
int error = 0;
for (int i = 0; i < inputs.Length; i++)
{
int actual = tree.Compute(inputs[i]);
int expected = outputs[i];
if (actual != expected) error++;
}
return error / (double)inputs.Length;
}
private void trackDecisions(DecisionNode root, double[] input, int index)
{
DecisionNode current = root;
while (current != null)
{
info[current].subset.Add(index);
if (current.IsLeaf)
{
actual[index] = current.Output.HasValue ? current.Output.Value : -1;
return;
}
int attribute = current.Branches.AttributeIndex;
DecisionNode nextNode = null;
foreach (DecisionNode branch in current.Branches)
{
if (branch.Compute(input[attribute]))
{
nextNode = branch; break;
}
}
current = nextNode;
}
// Normal execution should not reach here.
throw new InvalidOperationException("The tree is degenerated.");
}
}
}
|
using Faux.Banque.Domain.Exceptions;
using Faux.Banque.Domain.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Faux.Banque.Domain.Storage
{
public class EventStore : IEventStore
{
private IAppendOnlyStore appendOnlyStore;
private IEventStoreSerializer serializer;
public event NewEventsArrivedHandler NewEventsArrived;
public delegate void NewEventsArrivedHandler(int count);
public EventStore(IAppendOnlyStore appendOnlyStore, IEventStoreSerializer serializer)
{
if (appendOnlyStore == null) throw new ArgumentNullException("appendOnlyStore");
if (serializer == null) throw new ArgumentNullException("serializer");
this.appendOnlyStore = appendOnlyStore;
this.serializer = serializer;
}
public EventStream LoadEventStream(IIdentity id)
{
var readTask = appendOnlyStore.ReadRecords(id.ToString(),0, int.MaxValue);
readTask.Wait();
EventStream stream = new EventStream();
foreach (var record in readTask.Result)
{
stream.Events.AddRange(serializer.DeserializeEvent(record.Data));
stream.Version = record.Version;
}
return stream;
}
public void AppendToStream(IIdentity id, long expectedVersion, ICollection<IEvent> events)
{
if (events.Count == 0)
return;
var name = id.ToString();
var data = serializer.SerializeEvents(events.ToArray());
try
{
appendOnlyStore.Append(name, data, expectedVersion);
if (NewEventsArrived != null) NewEventsArrived(events.Count);
}
catch (AppendOnlyStoreConcurrencyException e)
{
var stream = LoadEventStream(id);
throw OptimisticConcurrencyException.Create(stream.Version, expectedVersion, id.ToString(), stream.Events);
}
}
public IList<IEvent> LoadEvents(DateTimeOffset afterVersion, int maxCount)
{
var readTask = this.appendOnlyStore.ReadRecords(afterVersion, maxCount);
readTask.Wait();
var events = new List<IEvent>();
foreach (var record in readTask.Result)
{
events.AddRange(serializer.DeserializeEvent(record.Data));
}
return events;
}
}
}
|
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System;
using System.Collections;
using System.Collections.Generic;
public class TimeManager : Singleton<TimeManager>
{
public static UnityEvent PerDayEvent = new UnityEvent();
public static UnityEvent PerWeekEvent = new UnityEvent();
public static UnityEvent PerMonthEvent = new UnityEvent();
public static UnityEvent PerYearEvent = new UnityEvent();
public static UnityEventBool OnTogglePauseEvent = new UnityEventBool();
public static DateTime CurrentDate { get; private set; }
public static int Year { get { return CurrentDate.Year; } }
public static int Month { get { return CurrentDate.Month; } }
public static int Week { get { return Mathf.CeilToInt((float)CurrentDate.DayOfYear / 7); } }
public static int Day { get { return CurrentDate.Day; } }
public static string DateString { get { return CurrentDate.ToString("ddMMyyyy"); } }
private static bool paused;
private static bool locked;
void Awake()
{
Instance = this;
paused = false;
CurrentDate = DateTime.Today;
}
void Start()
{
StopAllCoroutines();
StartCoroutine(PerDayTick());
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space) && !locked)
TogglePause();
}
public static void SetCurrentDate(DateTime date)
{
CurrentDate = date;
}
public static void TogglePause()
{
paused = !paused;
OnTogglePauseEvent.Invoke(paused);
}
public static void Pause()
{
if (locked || paused) return;
paused = true;
OnTogglePauseEvent.Invoke(paused);
}
public static void Unpause()
{
if (locked || !paused) return;
paused = false;
OnTogglePauseEvent.Invoke(paused);
}
public static void Lock()
{
locked = true;
}
public static void Unlock()
{
locked = false;
}
IEnumerator PerDayTick()
{
while (Application.isPlaying)
{
while (!paused)
{
int old_week = Week;
int old_month = Month;
int old_year = Year;
CurrentDate = CurrentDate.AddDays(1.0);
//daily tick
PerDayEvent.Invoke();
if (Year > old_year)
{
PerYearEvent.Invoke();
old_week = 0;
old_month = 0;
}
if (Week > old_week)
PerWeekEvent.Invoke();
if (Month > old_month)
PerMonthEvent.Invoke();
yield return new WaitForSeconds(1.0f);
}
yield return null;
}
}
}
|
using UnityEngine;
using System.Collections;
public class AudioController : MonoBehaviour {
void Update () {
string status_BGM = PlayerPrefs.GetString("bgm");
// If status_BGM is true, the AudioListener will be listening.
switch (status_BGM.ToLower()) {
case "false":
AudioListener.pause = true;
break;
case "true": default:
AudioListener.pause = false;
break;
}
}
}
|
using System;
using System.Text.RegularExpressions;
namespace Gomoku.Commands.Classes
{
public class Start : ACommand
{
public Start()
:base(ECommand.START)
{}
public override DataCommand CreateDataCommand(string input)
{
Regex mRegex = new Regex("START (\\d+)");
Match match = mRegex.Match(input);
if (match.Success)
return new DataCommand {CommandType = Type, Data = Convert.ToUInt32(match.Groups[1].Value)};
return new DataCommand {CommandType = ECommand.ERROR, Data = null};
}
}
} |
// 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.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using NuGet.Configuration;
using NuGet.Packaging.Core;
using NuGet.Protocol.Core.Types;
namespace NuGet.Protocol.Core.v3
{
/// <summary>
/// Provides the download metatdata for a given package from a V3 server endpoint.
/// </summary>
public class DownloadResourceV3 : DownloadResource
{
private readonly RegistrationResourceV3 _regResource;
private readonly HttpClient _client;
public DownloadResourceV3(HttpClient client, RegistrationResourceV3 regResource)
{
if (client == null)
{
throw new ArgumentNullException("client");
}
if (regResource == null)
{
throw new ArgumentNullException("regResource");
}
_regResource = regResource;
_client = client;
}
private async Task<Uri> GetDownloadUrl(PackageIdentity identity, CancellationToken token)
{
Uri downloadUri = null;
var blob = await _regResource.GetPackageMetadata(identity, token);
if (blob != null
&& blob["packageContent"] != null)
{
downloadUri = new Uri(blob["packageContent"].ToString());
}
return downloadUri;
}
public override async Task<DownloadResourceResult> GetDownloadResourceResultAsync(PackageIdentity identity,
ISettings settings,
CancellationToken token)
{
if (identity == null)
{
throw new ArgumentNullException(nameof(identity));
}
if (settings == null)
{
throw new ArgumentNullException(nameof(settings));
}
Uri uri = await GetDownloadUrl(identity, token);
if (uri != null)
{
// Uri is not null, so the package exists in the source
// Now, check if it is in the global packages folder, before, getting the package stream
var packageFromGlobalPackages = GlobalPackagesFolderUtility.GetPackage(identity, settings);
if (packageFromGlobalPackages != null)
{
return packageFromGlobalPackages;
}
using (var packageStream = await _client.GetStreamAsync(uri))
{
var downloadResult = await GlobalPackagesFolderUtility.AddPackageAsync(identity,
packageStream,
settings,
token);
return downloadResult;
}
}
return null;
}
}
}
|
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved.
using SpriteDicing;
using System.Threading;
using System.Threading.Tasks;
using UnityCommon;
using UnityEngine;
namespace Naninovel
{
/// <summary>
/// A <see cref="ICharacterActor"/> implementation using <see cref="SpriteDicing.DicedSpriteRenderer"/> to represent the actor.
/// </summary>
public class DicedSpriteCharacter : MonoBehaviourActor, ICharacterActor
{
public override string Appearance { get => appearance; set => SetAppearance(value); }
public override bool IsVisible { get => isVisible; set => SetVisibility(value); }
public CharacterLookDirection LookDirection { get => GetLookDirection(); set => SetLookDirection(value); }
private readonly CharacterMetadata metadata;
private readonly DicedSpriteRenderer dicedSpriteRenderer;
private readonly Tweener<ColorTween> fadeTweener;
private LocalizableResourceLoader<DicedSpriteAtlas> appearanceLoader;
private string appearance;
private bool isVisible;
public DicedSpriteCharacter (string id, CharacterMetadata metadata)
: base(id, metadata)
{
this.metadata = metadata;
dicedSpriteRenderer = GameObject.AddComponent<DicedSpriteRenderer>();
fadeTweener = new Tweener<ColorTween>(ActorBehaviour);
SetVisibility(false);
}
public override async Task InitializeAsync ()
{
await base.InitializeAsync();
var providerMngr = Engine.GetService<ResourceProviderManager>();
var localeMngr = Engine.GetService<LocalizationManager>();
appearanceLoader = new LocalizableResourceLoader<DicedSpriteAtlas>(metadata.LoaderConfiguration, providerMngr, localeMngr);
}
public override async Task ChangeAppearanceAsync (string appearance, float duration, EasingType easingType = default, CancellationToken cancellationToken = default)
{
this.appearance = appearance;
if (string.IsNullOrEmpty(appearance)) return;
var atlasResource = await appearanceLoader.LoadAsync(Id);
if (!atlasResource.IsValid) return;
// In case user stored source sprites in folders, the diced sprites will have dots in their names.
var spriteName = appearance.Replace("/", ".");
var dicedSprite = atlasResource.Object.GetSprite(spriteName);
// TODO: Support crossfading diced sprite.
dicedSpriteRenderer.SetDicedSprite(dicedSprite);
}
public override async Task ChangeVisibilityAsync (bool isVisible, float duration, EasingType easingType = default, CancellationToken cancellationToken = default)
{
this.isVisible = isVisible;
if (fadeTweener.IsRunning)
fadeTweener.CompleteInstantly();
var opacity = isVisible ? 1 : 0;
var tween = new ColorTween(dicedSpriteRenderer.Color, new Color(0, 0, 0, opacity), ColorTweenMode.Alpha,
duration, value => dicedSpriteRenderer.Color = value, false, easingType);
await fadeTweener.RunAsync(tween);
}
public override async Task HoldResourcesAsync (object holder, string appearance)
{
if (string.IsNullOrEmpty(appearance)) return;
var resource = await appearanceLoader.LoadAsync(appearance);
if (resource.IsValid)
resource.Hold(holder);
}
public override void ReleaseResources (object holder, string appearance)
{
if (string.IsNullOrEmpty(appearance)) return;
appearanceLoader.GetLoadedOrNull(appearance)?.Release(holder);
}
public override void Dispose ()
{
base.Dispose();
appearanceLoader?.UnloadAll();
}
public Task ChangeLookDirectionAsync (CharacterLookDirection lookDirection, float duration, EasingType easingType = default, CancellationToken cancellationToken = default)
{
SetLookDirection(lookDirection);
return Task.CompletedTask;
}
protected virtual void SetAppearance (string appearance) => ChangeAppearanceAsync(appearance, 0).WrapAsync();
protected virtual void SetVisibility (bool isVisible)
{
this.isVisible = isVisible;
if (fadeTweener.IsRunning)
fadeTweener.CompleteInstantly();
dicedSpriteRenderer.Color = new Color(dicedSpriteRenderer.Color.r, dicedSpriteRenderer.Color.g, dicedSpriteRenderer.Color.b, isVisible ? 1 : 0);
}
protected override Color GetBehaviourTintColor () => dicedSpriteRenderer.Color;
protected override void SetBehaviourTintColor (Color tintColor)
{
if (!IsVisible) // Handle visibility-controlled alpha of the tint color.
tintColor.a = dicedSpriteRenderer.Color.a;
dicedSpriteRenderer.Color = tintColor;
}
protected virtual void SetLookDirection (CharacterLookDirection lookDirection)
{
if (metadata.BakedLookDirection == CharacterLookDirection.Center) return;
if (lookDirection == CharacterLookDirection.Center)
{
dicedSpriteRenderer.FlipX = false;
return;
}
if (lookDirection != LookDirection)
dicedSpriteRenderer.FlipX = !dicedSpriteRenderer.FlipX;
}
protected virtual CharacterLookDirection GetLookDirection ()
{
switch (metadata.BakedLookDirection)
{
case CharacterLookDirection.Center:
return CharacterLookDirection.Center;
case CharacterLookDirection.Left:
return dicedSpriteRenderer.FlipX ? CharacterLookDirection.Right : CharacterLookDirection.Left;
case CharacterLookDirection.Right:
return dicedSpriteRenderer.FlipX ? CharacterLookDirection.Left : CharacterLookDirection.Right;
default:
return default;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(Rigidbody2D))]
public class Chaining : MonoBehaviour
{
float kp=10f;
float ki=0f;
float kd=1f;
public GameObject target;
public Vector3 targetOffset;
float stableDistance=0.1f;
public Vector3 selftOffset;
Rigidbody2D playerRigidbody2D;
private Vector3 anchor;
private Vector3 selfPosition;
private float previousDistance;
private float currentDistance;
private Vector3 force;
private float I;
private float deltaTime;
void GetTargetAnchor()
{
anchor = target.transform.position + targetOffset;
}
void GetSelfPosition()
{
selfPosition = transform.position + selftOffset;
}
void GetDistance()
{
currentDistance = Vector3.Distance(anchor,selfPosition);
}
void PIDtoForceControl()
{
Vector3 baseForce = (anchor-selfPosition)/currentDistance;
deltaTime = Time.deltaTime;
float P = currentDistance - stableDistance;
I = I + P*deltaTime;
float D = 0;
if(deltaTime==0){
D = 0;
}else
{
D = (currentDistance-previousDistance)/deltaTime;
}
float F = kp*P+ki*I+kd*D;
previousDistance = currentDistance;
force = baseForce*F;
Vector2 Force2D = force;
playerRigidbody2D.AddForce(Force2D);
}
// Start is called before the first frame update
void Start()
{
playerRigidbody2D = GetComponent<Rigidbody2D>();
GetTargetAnchor();
GetSelfPosition();
GetDistance();
I = 0;
deltaTime = 0;
previousDistance = currentDistance;
}
// Update is called once per frame
void Update()
{
GetTargetAnchor();
GetSelfPosition();
GetDistance();
PIDtoForceControl();
//Debug.Log(currentDistance);
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace HackerRank_HomeCode
{
public class Kangaroo
{
public void DoTheyMeet()
{
var tokens_x1 = Console.ReadLine().Split(' ');
var x1 = Convert.ToInt32(tokens_x1[0]);
var v1 = Convert.ToInt32(tokens_x1[1]);
var x2 = Convert.ToInt32(tokens_x1[2]);
var v2 = Convert.ToInt32(tokens_x1[3]);
var sameLocationPossible = "";
if (x1 < x2 && v1 < v2)
{
sameLocationPossible = "NO";
}
else if(x2 < x1 && v2 < v1)
{
sameLocationPossible = "NO";
}
else if(x2 > x1)
{
var noOfjumps = ((double)(x2 - x1)) / (v1 - v2);
if(noOfjumps % 1 == 0)
{
sameLocationPossible = "YES";
}
else
{
sameLocationPossible = "NO";
}
}
else
{
var noOfjumps = ((double)(x1 - x2)) / (v2 - v1);
if (noOfjumps % 1 == 0)
{
sameLocationPossible = "YES";
}
else
{
sameLocationPossible = "NO";
}
}
Console.WriteLine(sameLocationPossible);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Interface_Segregation_Principle
{
//interface for shapes
public interface IShape
{
string Name { get; set; }
double CalculateArea();
}
}
|
using mg.hr.Core;
namespace mg.hr.API.Models
{
public class MonthlyEmployee : IEmployee
{
private readonly Employee _employee;
public int id { get => _employee.id; }
public string name { get => _employee.name; }
public string roleName { get => _employee.roleName; }
public MonthlyEmployee(Employee employee)
{
this._employee = employee;
}
public decimal AnnualSalary()
{
return _employee.monthlySalary * 12;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using ENTITY;
//<summary>
//Summary description for MonthlySalaryDetailsInfo
//</summary>
namespace ENTITY
{
public class MonthlySalaryDetailsInfo
{
private decimal _monthlySalaryDetailsId;
private decimal _employeeId;
private decimal _salaryPackageId;
private DateTime _extraDate;
private string _extra1;
private string _extra2;
private decimal _monthlySalaryId;
public decimal MonthlySalaryDetailsId
{
get { return _monthlySalaryDetailsId; }
set { _monthlySalaryDetailsId = value; }
}
public decimal EmployeeId
{
get { return _employeeId; }
set { _employeeId = value; }
}
public decimal SalaryPackageId
{
get { return _salaryPackageId; }
set { _salaryPackageId = value; }
}
public DateTime ExtraDate
{
get { return _extraDate; }
set { _extraDate = value; }
}
public string Extra1
{
get { return _extra1; }
set { _extra1 = value; }
}
public string Extra2
{
get { return _extra2; }
set { _extra2 = value; }
}
public decimal MonthlySalaryId
{
get { return _monthlySalaryId; }
set { _monthlySalaryId = value; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MoneyBack.Bankier.Models;
using MoneyBack.Requests;
namespace MoneyBack.Bankier
{
public class BankierConnection : IBankierConnection
{
public async Task<GetDataResponse> GetData(string symbol, bool intraday, bool today)
{
var jsonObject = await new JsonRequest("https://www.bankier.pl/new-charts/get-data")
.AddArgument("symbol", symbol)
.AddArgument("intraday", intraday.ToString().ToLower())
.AddArgument("type", "area")
.Get();
var response = new GetDataResponse(jsonObject);
return response;
}
public GetDataResponse GetData(string symbol, DateTime dateFrom, DateTime dateTo)
{
throw new NotImplementedException();
}
}
}
|
using PyFarmaceutica.acceso_a_datos.interfaces;
using PyFarmaceutica.Reportes.entidades;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PyFarmaceutica.acceso_a_datos.implementaciones
{
public class ReporteDao : IReporteDao
{
private string CadenaConexion;
private SqlConnection cnn;
public ReporteDao()
{
CadenaConexion = HelperDao.Instancia().CadenaConeccion();
cnn = new SqlConnection(CadenaConexion);
}
public DataTable AñosFacturados()
{
SqlCommand cmd = new SqlCommand("SP_CONSULTA_AÑOS_FACTURADOS", cnn);
cmd.CommandType = CommandType.StoredProcedure;
DataTable tabla = new DataTable();
cnn.Open();
tabla.Load(cmd.ExecuteReader());
cnn.Close();
return tabla;
}
public DataTable ReporteCantidadVentas_Suministro()
{
SqlCommand cmd = new SqlCommand("SP_REPORTE_CANTIDAD_VENTAS_SUMINISTRO", cnn);
cmd.CommandType = CommandType.StoredProcedure;
DataTable tabla = new DataTable();
cnn.Open();
tabla.Load(cmd.ExecuteReader());
cnn.Close();
return tabla;
}
public DataTable ReporteFacturacion_Mes(Año anio)
{
SqlCommand cmd = new SqlCommand("SP_REPORTE_FACTURACION_MES", cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("anio",anio.Anio);
DataTable tabla = new DataTable();
cnn.Open();
tabla.Load(cmd.ExecuteReader());
cnn.Close();
return tabla;
}
}
}
|
namespace MiHomeLibrary.Communication.Commands
{
public interface ICommand
{
string SerializeCommand();
}
}
|
using Microsoft.Xna.Framework;
namespace WUIClient {
public class MouseClickable<T> {
public delegate void MouseEvent(T sender);
public event MouseEvent OnMouseLeftClickDown;
public event MouseEvent OnMouseRightClickDown;
public event MouseEvent OnMouseLeftClickUp;
public event MouseEvent OnMouseRightClickUp;
public event MouseEvent WhileMouseOver;
public event MouseEvent OnMouseEnter;
public event MouseEvent OnMouseLeave;
private bool prevMouseOver;
private bool prevMouseLeftIn;
private bool prevMouseRightIn;
public bool MouseLeftClickDown { get; private set; }
public bool MouseRightClickDown { get; private set; }
public bool MouseLeftClickUp { get; private set; }
public bool MouseRightClickUp { get; private set; }
public bool MouseOver { get; private set; }
public bool MouseEnter { get; private set; }
public bool MouseLeave { get; private set; }
public void Update(T sender, RectangleF clickable, Vector2 mousePosition) {
prevMouseOver = MouseOver;
MouseOver = clickable.Contains(mousePosition);
if (prevMouseOver != MouseOver) {
if (MouseOver) {
MouseEnter = true;
OnMouseEnter?.Invoke(sender);
} else {
MouseLeave = true;
MouseLeftClickDown = false;
MouseRightClickDown = false;
MouseLeftClickUp = false;
MouseRightClickUp = false;
OnMouseLeave?.Invoke(sender);
}
} else {
MouseEnter = MouseLeave = false;
}
if (MouseOver) {
if (MouseLeftClickDown = WMouse.LeftMouseClick()) {
prevMouseLeftIn = true;
OnMouseLeftClickDown?.Invoke(sender);
}
if (MouseRightClickDown = WMouse.RightMouseClick()) {
prevMouseRightIn = true;
OnMouseRightClickDown?.Invoke(sender);
}
WhileMouseOver?.Invoke(sender);
}
if (prevMouseLeftIn && (MouseLeftClickUp = WMouse.LeftMouseClickUp())) {
prevMouseLeftIn = false;
OnMouseLeftClickUp?.Invoke(sender);
}
if (prevMouseRightIn && (MouseRightClickUp = WMouse.RightMouseClickUp())) {
prevMouseRightIn = false;
OnMouseRightClickUp?.Invoke(sender);
}
}
}
}
|
//-----------------------------------------------------------------------
// <copyright file="DotNetFileSystemProvider.cs" company="Fubar Development Junker">
// Copyright (c) Fubar Development Junker. All rights reserved.
// </copyright>
// <author>Mark Junker</author>
//-----------------------------------------------------------------------
using System.IO;
using System.Threading.Tasks;
using JetBrains.Annotations;
using Microsoft.Extensions.Options;
namespace FubarDev.FtpServer.FileSystem.DotNet
{
/// <summary>
/// A <see cref="IFileSystemClassFactory"/> implementation that uses
/// the standard .NET functionality to provide file system access.
/// </summary>
public class DotNetFileSystemProvider : IFileSystemClassFactory
{
private readonly string _rootPath;
private readonly bool _useUserIdAsSubFolder;
private readonly int _streamBufferSize;
private readonly bool _allowNonEmptyDirectoryDelete;
/// <summary>
/// Initializes a new instance of the <see cref="DotNetFileSystemProvider"/> class.
/// </summary>
/// <param name="options">The file system options.</param>
public DotNetFileSystemProvider([NotNull] IOptions<DotNetFileSystemOptions> options)
{
_rootPath = options.Value.RootPath ?? Path.GetTempPath();
_useUserIdAsSubFolder = options.Value.UseUserIdAsSubFolder;
_streamBufferSize = options.Value.StreamBufferSize ?? DotNetFileSystem.DefaultStreamBufferSize;
_allowNonEmptyDirectoryDelete = options.Value.AllowNonEmptyDirectoryDelete;
}
/// <inheritdoc/>
public Task<IUnixFileSystem> Create(IAccountInformation accountInformation)
{
var path = _rootPath;
if (_useUserIdAsSubFolder)
{
path = Path.Combine(path, accountInformation.User.Name);
}
return Task.FromResult<IUnixFileSystem>(new DotNetFileSystem(path, _allowNonEmptyDirectoryDelete, _streamBufferSize));
}
}
}
|
using System;
namespace logic
{
public abstract class Link : Node
{
public readonly int amount = -1;
protected Link(String id, int amount) : base(id)
{
this.amount = amount;
}
public abstract void Connect(Stores stores, Processes processes);
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entidades
{
public class Competencia
{
private short cantidadCompetidores;
private short cantidadDeVueltas;
private List<AutoF1> listaAutosF1;
private Competencia()
{
listaAutosF1 = new List<AutoF1>();
}
public Competencia(short cantVueltas, short cantCompetidores)
: this()
{
this.cantidadDeVueltas = cantVueltas;
this.cantidadCompetidores = cantCompetidores;
}
public string MostrarDatos()
{
StringBuilder str = new StringBuilder();
str.AppendFormat("Cantidad de Competidores: {0}\tCantidad de Vueltas: {1}", this.cantidadCompetidores, this.cantidadDeVueltas);
foreach(AutoF1 auto in this.listaAutosF1)
{
str.AppendLine();
str.Append(auto.MostrarDatos());
}
str.AppendLine("\n");
return str.ToString();
}
public static bool operator ==(Competencia c, AutoF1 a)
{
foreach (AutoF1 auto in c.listaAutosF1)
{
if (auto == a)
{
return true;
}
}
return false;
}
public static bool operator !=(Competencia c, AutoF1 a)
{
return !(c == a);
}
public static bool operator +(Competencia c, AutoF1 a)
{
bool retorno = false;
if((c.listaAutosF1.Count < c.cantidadCompetidores) && (c != a))
{
c.listaAutosF1.Add(a);
Random rnd = new Random();
rnd.Next(15, 100);
a.EnCompetencia = true;
a.VueltasRestantes = c.cantidadDeVueltas;
a.CantidadCombustible = (short)rnd.Next(15, 100);
retorno = true;
}
return retorno;
}
public static bool operator -(Competencia c, AutoF1 a)
{
bool retorno = false;
if (c.listaAutosF1.Contains(a))
{
retorno = true;
a.EnCompetencia = false;
a.VueltasRestantes = 0;
a.CantidadCombustible = 0;
c.listaAutosF1.Remove(a);
}
return retorno;
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_TweenWidth : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
TweenWidth o = new TweenWidth();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetStartToCurrentValue(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
tweenWidth.SetStartToCurrentValue();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int SetEndToCurrentValue(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
tweenWidth.SetEndToCurrentValue();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Begin_s(IntPtr l)
{
int result;
try
{
UIWidget widget;
LuaObject.checkType<UIWidget>(l, 1, out widget);
float duration;
LuaObject.checkType(l, 2, out duration);
int width;
LuaObject.checkType(l, 3, out width);
TweenWidth o = TweenWidth.Begin(widget, duration, width);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_from(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, tweenWidth.from);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_from(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
int from;
LuaObject.checkType(l, 2, out from);
tweenWidth.from = from;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_to(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, tweenWidth.to);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_to(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
int to;
LuaObject.checkType(l, 2, out to);
tweenWidth.to = to;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_updateTable(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, tweenWidth.updateTable);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_updateTable(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
bool updateTable;
LuaObject.checkType(l, 2, out updateTable);
tweenWidth.updateTable = updateTable;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_cachedWidget(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, tweenWidth.cachedWidget);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_value(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, tweenWidth.value);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_value(IntPtr l)
{
int result;
try
{
TweenWidth tweenWidth = (TweenWidth)LuaObject.checkSelf(l);
int value;
LuaObject.checkType(l, 2, out value);
tweenWidth.value = value;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "TweenWidth");
LuaObject.addMember(l, new LuaCSFunction(Lua_TweenWidth.SetStartToCurrentValue));
LuaObject.addMember(l, new LuaCSFunction(Lua_TweenWidth.SetEndToCurrentValue));
LuaObject.addMember(l, new LuaCSFunction(Lua_TweenWidth.Begin_s));
LuaObject.addMember(l, "from", new LuaCSFunction(Lua_TweenWidth.get_from), new LuaCSFunction(Lua_TweenWidth.set_from), true);
LuaObject.addMember(l, "to", new LuaCSFunction(Lua_TweenWidth.get_to), new LuaCSFunction(Lua_TweenWidth.set_to), true);
LuaObject.addMember(l, "updateTable", new LuaCSFunction(Lua_TweenWidth.get_updateTable), new LuaCSFunction(Lua_TweenWidth.set_updateTable), true);
LuaObject.addMember(l, "cachedWidget", new LuaCSFunction(Lua_TweenWidth.get_cachedWidget), null, true);
LuaObject.addMember(l, "value", new LuaCSFunction(Lua_TweenWidth.get_value), new LuaCSFunction(Lua_TweenWidth.set_value), true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_TweenWidth.constructor), typeof(TweenWidth), typeof(UITweener));
}
}
|
using System;
using CobWebs.Test.Abstraction;
namespace CobWebs.Test.Domain.Strategy
{
public class RandomPlayerStrategy : PlayerStrategyBase
{
public RandomPlayerStrategy(BasketGameConfig config) : base(config)
{
}
protected override int OnGetAnswer(BasketGameContext spec)
{
Random r = new Random();
return r.Next(_config.MinWeight, _config.MaxWeight);
}
}
} |
using System;
namespace Wilddog.Sms.Util
{
public class Const
{
/// <summary>
/// The send notify URL.
/// </summary>
public static string SEND_NOTIFY_URL = "https://sms.wilddog.com/api/v1/{0}/notify/send";
/// <summary>
/// The send notify sign template.
/// </summary>
public static string SEND_NOTIFY_SIGN_TEMPLATE = "mobiles={0}¶ms={1}&templateId={2}×tamp={3}&{4}";
/// <summary>
/// The send notify URL.
/// </summary>
public static string SEND_MARKETING_URL = "https://sms.wilddog.com/api/v1/{0}/marketing/send";
/// <summary>
/// The send notify sign template.
/// </summary>
public static string SEND_MARKETING_SIGN_TEMPLATE = "content={0}&extno={1}&mobiles={2}×tamp={3}&{4}";
/// <summary>
/// The send code URL.
/// </summary>
public static string SEND_CODE_URL = "https://sms.wilddog.com/api/v1/{0}/code/send";
/// <summary>
/// The send code sign no parameter template.
/// </summary>
public static string SEND_CODE_SIGN_NO_PARAM_TEMPLATE = "mobile={0}&templateId={1}×tamp={2}&{3}";
/// <summary>
/// The send code sign with parameter template.
/// </summary>
public static string SEND_CODE_SIGN_WITH_PARAM_TEMPLATE = "mobile={0}¶ms={1}&templateId={2}×tamp={3}&{4}";
/// <summary>
/// The check code URL.
/// </summary>
public static string CHECK_CODE_URL = "https://sms.wilddog.com/api/v1/{0}/code/check";
/// <summary>
/// The check code sign template.
/// </summary>
public static string CHECK_CODE_SIGN_TEMPLATE = "code={0}&mobile={1}×tamp={2}&{3}";
/// <summary>
/// The query status URL.
/// </summary>
public static string QUERY_STATUS_URL = "https://sms.wilddog.com/api/v1/{0}/status?rrid={1}&signature={2}";
/// <summary>
/// The query status sign template.
/// </summary>
public static string QUERY_STATUS_SIGN_TEMPLATE = "rrid={0}&{1}";
/// <summary>
/// The query status v2 URL.
/// </summary>
public static string QUERY_STATUS_V2_URL = "https://sms.wilddog.com/api/v2/{0}/status?timestamp={1}&signature={2}";
/// <summary>
/// The query status v2 sign template.
/// </summary>
public static string QUERY_STATUS_V2_SIGN_TEMPLATE = "timestamp={0}&{1}";
/// <summary>
/// The query balance URL.
/// </summary>
public static string QUERY_BALANCE_URL = "https://sms.wilddog.com/api/v1/{0}/getBalance?timestamp={1}&signature={2}";
/// <summary>
/// The query balance sign template.
/// </summary>
public static string QUERY_BALANCE_SIGN_TEMPLATE = "timestamp={0}&{1}";
/// <summary>
/// The wilddog sms user agent.
/// </summary>
public static string WILDDOG_SMS_USER_AGENT = "wilddog-sms-csharp/1.0.1";
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using dotNetRogueLootAPI.Application;
using dotNetRogueLootAPI.Application.Interfaces;
using dotNetRogueLootAPI.Domain.Models;
using Moq;
using Xunit;
namespace dotNetRogueLootAPI.Tests
{
public class WeaponGeneratorTests
{
public static Mock<IWeaponRarityRepository> RarityMock = new Mock<IWeaponRarityRepository>();
public static Mock<IWeaponTypeRepository> TypeMock = new Mock<IWeaponTypeRepository>();
public static Mock<IEffectRepository> EffectMock = new Mock<IEffectRepository>();
private void SetupMock()
{
EffectMock.Setup(x => x.GetEffects()).Returns(new List<Effect>()
{
new Effect("Burn", "flaming", 1, 0, 5),
new Effect("Burn lifesteal", "burning life stealing", 1, 1 ,5),
new Effect("Destructive", "destructive", 6, 0, 2),
new Effect("Healing", "healing", 0, 5, 0),
new Effect("Lifesteal", "life stealing", 3, 3, 0),
new Effect("Lightning", "shocking", 6, 0, 2),
new Effect("Poison", "poisonous", 5, 0, 1),
new Effect("Poison lifesteal", "poisonous life stealing", 5, 5, 2),
new Effect("Powerful", "powerful", 5, 5, 0)
});
RarityMock.Setup(x => x.GetAllRarities()).Returns(new List<WeaponRarity>()
{
new WeaponRarity("Common", 66, 1, 0),
new WeaponRarity("Uncommon", 19, 1.5, 0),
new WeaponRarity("Rare", 10, 2, 1),
new WeaponRarity("Legendary", 4, 3.3, 2),
new WeaponRarity("Heroic", 1, 5, 4)
});
TypeMock.Setup(x => x.GetAllTypes()).Returns(new List<WeaponType>()
{
new WeaponType("Battleaxe", 35, 1),
new WeaponType("Bow", 15, 20),
new WeaponType("Greatsword", 30, 2),
new WeaponType("Sword", 10, 10)
});
}
[Fact]
public void Generating_Price_Doesnt_Exceed_Minimum_Or_Maximum()
{
SetupMock();
WeaponManager weaponManager = new WeaponManager(RarityMock.Object, TypeMock.Object, EffectMock.Object);
for (int i = 0; i < 1000; i++)
{
var weapon = weaponManager.GenerateWeapon();
Assert.InRange(weapon.SellValue, 10, 1140);
// The theoretical minimum and maximum prices
}
}
[Fact]
public void Generating_Attack_Doesnt_Exceed_Minimum_Or_Maximum()
{
SetupMock();
WeaponManager weaponManager = new WeaponManager(RarityMock.Object, TypeMock.Object, EffectMock.Object);
for (int i = 0; i < 1000; i++)
{
var weapon = weaponManager.GenerateWeapon();
Assert.InRange(weapon.Stats["Attack"], weapon.Type.Damage - 5, (weapon.Type.Damage + 5) * 5);
}
}
[Fact]
public void Generating_Dodge_Doesnt_Exceed_Minimum_Or_Maximum()
{
SetupMock();
WeaponManager weaponManager = new WeaponManager(RarityMock.Object, TypeMock.Object, EffectMock.Object);
for (int i = 0; i < 1000; i++)
{
var weapon = weaponManager.GenerateWeapon();
if (weapon.Stats["Dodge"] != 0)
{
Assert.InRange(weapon.Stats["Dodge"], weapon.Type.DodgeChance - 5, (weapon.Type.DodgeChance + 3) * 5);
}
}
}
[Fact]
public void Generating_Speed_Doesnt_Exceed_Minimum_Or_Maximum()
{
SetupMock();
WeaponManager weaponManager = new WeaponManager(RarityMock.Object, TypeMock.Object, EffectMock.Object);
for (int i = 0; i < 1000; i++)
{
var weapon = weaponManager.GenerateWeapon();
Assert.InRange(weapon.Stats["Speed"], 10, 28);
}
}
[Fact]
public void Generating_Defense_Doesnt_Exceed_Minimum_Or_Maximum()
{
SetupMock();
WeaponManager weaponManager = new WeaponManager(RarityMock.Object, TypeMock.Object, EffectMock.Object);
for (int i = 0; i < 1000; i++)
{
var weapon = weaponManager.GenerateWeapon();
Assert.InRange(weapon.Stats["Defense"], 1, 50);
}
}
[Fact]
public void Generating_Coolness_Doesnt_Exceed_Minimum_Or_Maximum()
{
SetupMock();
WeaponManager weaponManager = new WeaponManager(RarityMock.Object, TypeMock.Object, EffectMock.Object);
for (int i = 0; i < 1000; i++)
{
var weapon = weaponManager.GenerateWeapon();
Assert.InRange(weapon.Stats["Coolness"], 1, 3);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Magnifinance.Models
{
public class Teacher : Person
{
public int Salary { get; set; }
public virtual ICollection<Subject> Subjects { get; set; }
}
} |
using System.Reflection;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("Тестировщик для членов комиссии с правом решающего голоса.")]
[assembly: AssemblyDescription("Бот с тестами для членов комиссии с правом решающего голоса. Бот доступен по ссылке t.me/PRGTrainerBot")]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("c229379e-7a59-49a4-9df9-b6b0dd0b9eec")]
|
namespace cartalk.api.models
{
public class Feed
{
public int Id { get; set; }
public string photoUrl { get; set; }
public int createdById { get; set; }
public string caption { get; set; }
public int likes { get; set; }
public string dateCreated { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using InvoicingWebApp.Models;
using Microsoft.EntityFrameworkCore;
namespace InvoicingWebApp.Data
{
public class InvoicingDbContext : DbContext
{
public InvoicingDbContext(DbContextOptions<InvoicingDbContext> options) : base(options)
{
}
public DbSet<Invoice> Invoices { get; set; }
public DbSet<StaleStatus> StaleStatuses { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Invoice>()
.ToContainer("Invoices")
.HasNoDiscriminator()
.HasPartitionKey(x => x.PartitionKey)
.HasKey(x => x.AggregateId);
modelBuilder.Entity<Invoice>().Property(x => x.AggregateId).ToJsonProperty("id");
modelBuilder.Entity<StaleStatus>()
.ToContainer("StaleStatuses")
.HasNoDiscriminator()
.HasPartitionKey(x => x.PartitionKey);
modelBuilder.Entity<StaleStatus>().Property(x => x.Id).ToJsonProperty("id");
}
}
}
|
using System;
using System.Threading.Tasks;
using DDDSouthWest.Domain;
using DDDSouthWest.Domain.Features.Account.Admin.ManageEvents.CreateNewEvent;
using DDDSouthWest.Domain.Features.Account.Admin.ManageEvents.UpdateExistingEvent;
using DDDSouthWest.Domain.Features.Account.Admin.ManageEvents.ViewEventDetail;
using FluentValidation;
using Shouldly;
using Xunit;
namespace DDDSouthWest.UnitTests.ManageEvents.UpdateExistingEventTests
{
public class UpdateExistingEventTests
{
[Fact]
public async Task Update_an_existing_event()
{
// Arrange
var mediator = ResolveContainer.MediatR;
var staticEventDate = DateTime.Now;
var response = await mediator.Send(new CreateNewEvent.Command
{
EventDate = staticEventDate,
EventFilename = Guid.NewGuid().ToString(),
EventName = "Before event name"
});
// Act
var afterFilename = Guid.NewGuid().ToString();
await mediator.Send(new UpdateExistingEvent.Command
{
Id = response.Id,
EventFilename = afterFilename,
EventName = "After event name",
EventDate = staticEventDate
});
// Assert
var result = await mediator.Send(new ViewEventDetail.Query
{
Id = response.Id
});
result.EventName.ShouldBe("After event name");
result.EventFilename.ShouldBe(afterFilename);
/*
TODO: Can't update event yet?
result.EventDate.ShouldBe(staticEventDate);*/
}
public void Prevent_duplicate_event()
{
}
public void Prevent_incomplete_event_submissions()
{
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using CT.Data;
using CT.Manager;
namespace CT.UI
{
public class TileUI : MonoBehaviour
{
public int X { get; private set; }
public int Y { get; private set; }
public Image image;
Base _base;
public Building Building { get; private set; }
public Construction Construction { get; private set; }
GridManager manager;
public bool IsFree => Building == null && Construction == null;
Color normalColor;
Color buildingHereColor;
public void Init(GridManager manager, int x, int y)
{
this.manager = manager;
_base = manager._base;
X = x;
Y = y;
Building = _base[x, y];
Construction = ConstructionManager.instance[x, y];
if (Building != null)
Construction = ConstructionManager.instance.GetUpgradeOf(Building.BaseInstanceData);
normalColor = manager.tileNormalColor;
var color = Building == null ? normalColor : manager.StartBuildingHereColor;
if (Construction != null) color = manager.ConstructionHereColor;
SetColor(color);
buildingHereColor = manager.NowBuildingHereColor;
}
public void ResetColor()
{
var color = Building == null ? normalColor : buildingHereColor;
if (Construction != null) color = manager.ConstructionHereColor;
SetColor(color);
}
public void SetColor(Color color)
{
image.color = color;
}
public void SetFree()
{
Building = null;
Construction = null;
ResetColor();
}
public void OnClick()
{
//if (Building != null) return; // may do something else
manager.OnTileClicked(X, Y);
}
}
} |
using System.Collections.Generic;
using UnityEngine;
namespace TypingGameKit
{
/// <summary>
/// Manages the dynamic overlay entities.
/// </summary>
public class OverlayManager : MonoBehaviour
{
[Tooltip("Specifies the settings to use for associated entities.")]
[SerializeField] private OverlaySettings _settings = null;
[Tooltip("Defines the bounds of the overlay entities if the restrict to bounds setting is enabled.")]
[SerializeField] private RectTransform _entityBounds = null;
[Tooltip("Camera to be used. If undefined the default camera will be used")]
[SerializeField] private Camera _camera = null;
private Vector3[] _cornerArray = new Vector3[4];
private List<OverlayEntity> _entities = new List<OverlayEntity>();
private Vector2 previousResolution;
/// <summary>
/// The settings used for the dynamic overlay system.
/// </summary>
public OverlaySettings Settings
{
get { return _settings; }
set { _settings = value; }
}
/// <summary>
/// Camera to be used for determining the position of the sequences..
/// </summary>
private Camera UsedCamera
{
get { return _camera == null ? Camera.main : _camera; }
}
private void Awake()
{
Debug.Assert(_settings != null, this);
Debug.Assert(_entityBounds != null, this);
}
/// <summary>
/// Adds the entity to the system.
/// </summary>
public void SubscribeEntity(OverlayEntity entity)
{
_entities.Add(entity);
entity.PrepareForPositionUpdate(_cornerArray, UsedCamera, _settings);
}
/// <summary>
/// Removes an entity from the system.
/// </summary>
public void UnsubscribeEntity(OverlayEntity entity)
{
_entities.Remove(entity);
}
private void UpdateDistanceScaling()
{
foreach (var entity in _entities)
{
ApplyDistanceScaling(entity);
}
}
private void UpdateSequencePositions()
{
foreach (var entity in _entities)
{
entity.UpdateMovement(_entities.ToArray());
}
}
private void PrepareForUpdate()
{
Camera camera = UsedCamera;
_entityBounds.GetWorldCorners(_cornerArray);
foreach (var entity in _entities)
{
entity.PrepareForPositionUpdate(_cornerArray, camera, _settings);
}
}
private void LateUpdate()
{
UpdateOverlaySystem();
}
protected void UpdateOverlaySystem()
{
CheckForResolutionChange();
PrepareForUpdate();
UpdateDistanceScaling();
UpdateSequencePositions();
}
private void CheckForResolutionChange()
{
if (previousResolution.x != Screen.width || previousResolution.y != Screen.height)
{
foreach (var entity in _entities)
{
entity.MoveToTargetPosition();
}
previousResolution.x = Screen.width;
previousResolution.y = Screen.height;
}
}
private void ApplyDistanceScaling(OverlayEntity entity)
{
if (Settings.UseDistanceScaling == false || entity.Target == null)
{
return;
}
var settings = Settings.DistanceScaleSettings;
if (settings.Furthest == settings.Closest)
{
return;
}
// Calculate the scale with a linear equation.
float x = Mathf.Clamp(entity.TargetDistanceFromCamera(), settings.Closest, settings.Furthest);
float k = (settings.FurthestScale - settings.ClosestScale) / (settings.Furthest - settings.Closest);
float m = settings.FurthestScale - k * settings.Furthest;
float scale = k * x + m;
entity.transform.localScale = Vector3.one * scale;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Kinect;
namespace KinectTheDotsKR
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region Member Variables
private KinectSensor _Kinect;
private Skeleton[] _FrameSkeletons;
private readonly Brush[] _SkeletonBrushes;
#endregion Member Variables
#region Constructor
public MainWindow()
{
InitializeComponent();
this._SkeletonBrushes = new[] {Brushes.Black, Brushes.Crimson, Brushes.Indigo,
Brushes.DodgerBlue, Brushes.Purple, Brushes.Pink };
KinectSensor.KinectSensors.StatusChanged += KinectSensors_StatusChanged;
this.Kinect = KinectSensor.KinectSensors.FirstOrDefault(x => x.Status == KinectStatus.Connected);
}
#endregion Constructor
#region Methods
private void KinectSensors_StatusChanged(object sendet, StatusChangedEventArgs e)
{
switch (e.Status)
{
case KinectStatus.Connected:
this.Kinect = e.Sensor;
break;
case KinectStatus.Disconnected:
MessageBox.Show("Plug in Kinect");
this.Kinect = null;
break;
default:
MessageBox.Show("Error!");
break;
}
}
private void Kinect_SkeletonFrameReady(object sender, SkeletonFrameReadyEventArgs e)
{
using (SkeletonFrame frame = e.OpenSkeletonFrame())
{
if (frame != null)
{
frame.CopySkeletonDataTo(this._FrameSkeletons);
Skeleton skeleton = GetPrimarySkeleton(this._FrameSkeletons);
if (skeleton == null)
{
HandCursorElement.Visibility = Visibility.Collapsed;
}
else
{
Joint primaryHand = GetPrimaryHand(skeleton);
TrackHand(primaryHand);
}
}
}
}
private static Skeleton GetPrimarySkeleton(Skeleton[] skeletons)
{
Skeleton skeleton = null;
if (skeletons != null)
{
//Find the closest skeleton
for (int i = 0; i < skeletons.Length; i++)
{
if (skeletons[i].TrackingState == SkeletonTrackingState.Tracked)
{
if (skeleton == null)
{
skeleton = skeletons[i];
}
else
{
if (skeleton.Position.Z > skeletons[i].Position.Z)
{
skeleton = skeletons[i];
}
}
}
}
}
return skeleton;
}
private static Joint GetPrimaryHand(Skeleton skeleton)
{
Joint primaryHand = new Joint();
if (skeleton != null)
{
primaryHand = skeleton.Joints[JointType.HandLeft];
Joint rightHand = skeleton.Joints[JointType.HandRight];
if (rightHand.TrackingState != JointTrackingState.NotTracked)
{
primaryHand = rightHand;
}
else
{
if (primaryHand.Position.Z > rightHand.Position.Z)
{
primaryHand = rightHand;
}
}
}
return primaryHand;
}
private void TrackHand(Joint hand)
{
if (hand.TrackingState == JointTrackingState.NotTracked)
{
HandCursorElement.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
HandCursorElement.Visibility = System.Windows.Visibility.Visible;
float x;
float y;
DepthImagePoint point = this.Kinect.MapSkeletonPointToDepth(hand.Position, DepthImageFormat.Resolution640x480Fps30);
point.X = (int)((point.X * LayoutRoot.ActualWidth / this.Kinect.DepthStream.FrameWidth) - (HandCursorElement.ActualWidth / 2.0));
point.Y = (int)((point.Y * LayoutRoot.ActualWidth / this.Kinect.DepthStream.FrameHeight) - (HandCursorElement.ActualHeight / 2.0));
Canvas.SetLeft(HandCursorElement, x);
Canvas.SetTop(HandCursorElement, y);
if (hand.ID == JointType.HandRight)
{
HandCursorScale.ScaleX = 1;
}
else
{
HandCursorScale.ScaleX = -1;
}
}
}
#endregion Methods
#region Propertes
public KinectSensor Kinect
{
get { return this._Kinect; }
set
{
if (this._Kinect != value)
{
//Uninitialize
if (this._Kinect != null)
{
this._Kinect.Stop();
this._Kinect.SkeletonFrameReady -= Kinect_SkeletonFrameReady;
this._Kinect.SkeletonStream.Disable();
//this._FrameSkeletons = null;
}
this._Kinect = value;
//Initialize
if (this._Kinect != null)
{
if (this._Kinect.Status == KinectStatus.Connected)
{
this._Kinect.SkeletonStream.Enable();
this._FrameSkeletons = new Skeleton[this._Kinect.SkeletonStream.FrameSkeletonArrayLength];
this._Kinect.SkeletonFrameReady += Kinect_SkeletonFrameReady;
this._Kinect.Start();
}
}
}
}
}
#endregion Properties
}
}
|
using System;
using System.Runtime.InteropServices;
using Mono.VisualC.Interop;
using Qt.Core;
namespace Qt.Gui {
public class QApplication : QCoreApplication {
#region Sync with qapplication.h
// C++ interface
public interface IQApplication : ICppClassOverridable<QApplication> {
// ...
[Constructor] void QApplication (CppInstancePtr @this, [MangleAs ("int&")] IntPtr argc,
[MangleAs ("char**")] IntPtr argv, int version);
// ...
[Virtual] bool macEventFilter(CppInstancePtr @this, IntPtr eventHandlerCallRef, IntPtr eventRef);
// ...
[Virtual] void commitData(CppInstancePtr @this, IntPtr qSessionManager); // was QSessionManager&
[Virtual] void saveState(CppInstancePtr @this, IntPtr qSessionManager); // was QSessionManager&
// ...
[Static] int exec ();
[Virtual, Destructor] void Destruct (CppInstancePtr @this);
}
// C++ fields
private struct _QApplication {
}
#endregion
private static IQApplication impl = Qt.Libs.QtGui.GetClass<IQApplication,_QApplication,QApplication> ("QApplication");
public QApplication () : base (impl.TypeInfo)
{
Native = impl.Alloc (this);
InitArgcAndArgv ();
impl.QApplication (Native, argc, argv, QGlobal.QT_VERSION);
}
public QApplication (IntPtr native) : base (impl.TypeInfo)
{
Native = native;
}
internal QApplication (CppTypeInfo subClass) : base (impl.TypeInfo)
{
subClass.AddBase (impl.TypeInfo);
}
public override int Exec ()
{
return impl.exec ();
}
public override void Dispose ()
{
impl.Destruct (Native);
FreeArgcAndArgv ();
Native.Dispose ();
}
}
}
|
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
{
public class BaseSession
{
public DateTime LastActivity;
public String Device;
public String DeviceType;
public String Server;
public StatusDetails Status;
public String BsonId;
public Guid Id;
public String Email;
public Guid UserId;
public String UserName;
public String UserType;
public Guid Token;
public Guid EntityId;
public String GroupName;
public LocalityType Locality;
public Dictionary<String,String> Properties;
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Model.Interfaces;
using Model;
namespace ProductReviewAPI.Controllers
{
[Route("api/[controller]")]
public class CustomersController : Controller
{
IProductReviewUnitOfWork productReviewUnitOfWork;
ICustomerRepository customerRepository;
public CustomersController(IProductReviewUnitOfWork productReviewUnitOfWork)
{
this.productReviewUnitOfWork = productReviewUnitOfWork;
this.customerRepository = productReviewUnitOfWork.CustomerRepository;
}
[HttpGet]
public async Task<IActionResult> Get()
{
try
{
var res = await customerRepository.GetAllAsync();
return Ok(res);
}
catch (Exception)
{ }
return BadRequest();
}
[HttpGet("{id}")]
public async Task<IActionResult> Get(int id)
{
try
{
Customer customer = await customerRepository.GetByIdAsync(id);
if (customer == null)
{
return NotFound();
}
return Ok(customer);
}
catch (Exception)
{
}
return BadRequest();
}
[HttpDelete("{id}")]
public async Task<IActionResult> Delete(int id)
{
try
{
if (await customerRepository.DeleteAsync(id))
{
await productReviewUnitOfWork.SaveAsync();
return Ok();
}
else
{
return NotFound();
}
}
catch (Exception)
{
}
return BadRequest();
}
[HttpPut()]
public async Task<IActionResult> Put([FromBody]Customer customer)
{
try
{
await customerRepository.UpdateAsync(customer);
if (await productReviewUnitOfWork.SaveAsync())
return Ok(customer);
}
catch (Exception)
{ }
return BadRequest();
}
}
} |
using EmployeeStorage.DataAccess.Entities;
using EmployeeStorage.DataAccess.Extensions;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace EmployeeStorage.DataAccess.Configuration
{
public class PositionConfiguration : DbEntityConfiguration<Position>
{
public override void Configuration(EntityTypeBuilder<Position> modelBuilder)
{
modelBuilder.Property(e => e.Name)
.IsRequired()
.HasMaxLength(50);
}
}
} |
using System.Collections.Generic;
namespace Wedding_Planner.Models
{
public class ViewModel
{
// Used for dashboard
public User loggedUser { get; set; }
public List<Wedding> allWeddings { get; set; }
public User User { get; set; }
public Wedding Wedding { get; set; }
}
} |
namespace MediaManager.API.Controllers
{
/// <summary>
/// The type of resource URI
/// </summary>
internal enum ResourceUriType
{
previousPage,
nextPage,
Current
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.GlobalIllumination;
public class FlashlightToggle : MonoBehaviour
{
public GameObject lightGO; //light gameObject to work with
public bool isOn = false; //is flashlight on or off?
public int MAX_INSANITY = 100; //maximum insanity
public int currentInsanity = 0; //Current insanity
public double Timer = 120; // The wait time between flashes
public double CurrentTime = 0; //Current time for the timer;
public bool Flicker = false;
public GameObject CheckCloseTo;
public int Range = 2;
public float insanityIncreaseInterval = 1.0f; //time it takes for insanity to increase in seconds (Decrease to make insanity increase faster)
private float time = 0.0f;
public float flickerChanceInterval = 1.0f; //Lights will have a chance to flicker after this many seconds (decrease for more frequent flickers)
private float flickerTime = 0.0f;
private string currentlyPlaying;
public GameObject scareImage1;
public GameObject scareImage2;
private GameObject activateImage;
private bool jumpScare = false;
private float scareTime = 0.0f;
private float jumpDuration = 0.1f;
public LevelChanger levelChanger;
AudioSource[] audio;
// Use this for initialization
void Start()
{
audio = GetComponents<AudioSource>();
//set lights on by default
turnLightOn();
}
// Update is called once per frame
void Update()
{
//if close to campfire decrease currentInsanity 3x quicker then you do increase currentInsanity
if (Vector3.Distance(transform.position, CheckCloseTo.transform.position) < Range)
{
if(currentInsanity > 0)
{
if (time >= insanityIncreaseInterval / 3)
{
currentInsanity -= 1;
CurrentTime = 0;
time = 0.0f;
}
}
}
if (isOn)
{
if(currentInsanity < MAX_INSANITY)
{
time += Time.deltaTime;
if (time >= insanityIncreaseInterval)
{
time = 0.0f;
currentInsanity += 1;
if(currentInsanity < 20)
{
if(currentlyPlaying != "stageone")
{
currentlyPlaying = "stageone";
audio[5].Stop();
audio[6].Play();
}
}
if (currentInsanity >= 20 && currentInsanity < 40)
{
if (currentlyPlaying != "stagetwo")
{
currentlyPlaying = "stagetwo";
audio[6].Stop();
audio[4].Stop();
audio[5].Play();
}
}
if (currentInsanity >= 40 && currentInsanity < 60)
{
if (currentlyPlaying != "stagethree")
{
currentlyPlaying = "stagethree";
audio[5].Stop();
audio[3].Stop();
audio[4].Play();
}
}
if (currentInsanity >= 60 && currentInsanity < 80)
{
if (currentlyPlaying != "stagefour")
{
currentlyPlaying = "stagefour";
audio[4].Stop();
audio[2].Stop();
audio[3].Play();
}
}
if (currentInsanity >= 80)
{
if (currentlyPlaying != "stagefive")
{
currentlyPlaying = "stagefive";
audio[3].Stop();
audio[2].Play();
}
}
}
}
}
if (lightGO.activeSelf)
{
if (Flicker == false)
{
flickerTime += Time.deltaTime;
if (flickerTime >= flickerChanceInterval)
{
flickerTime = 0.0f;
//currentInsanity += 1; maybe make them more insane with each flicker
if (Random.Range(0.0f, 100.0f) < currentInsanity)
{
turnLightOff();
Flicker = true;
Timer = Random.Range(100.0f, 250.0f / (currentInsanity / 10));
CurrentTime = 0;
}
}
}
}
else
{
if (Flicker == true)
{
CurrentTime += 1;
if (CurrentTime > Timer / 4)
{
//Debug.Log("How Quick");
turnLightOn();
Flicker = false;
CurrentTime = 0;
}
}
}
//toggle flashlight on key down
if (Input.GetKeyDown(KeyCode.C))
{
currentInsanity += 1;
}
if (Input.GetKeyDown(KeyCode.X))
{
if (Flicker == false)
if (CurrentTime < Timer)
{
//toggle light
//turn light on
isOn = !isOn;
if (isOn)
{
turnLightOn();
}
//turn light off
else
{
turnLightOff();
}
}
}
}
//Call this function to turn the light on
void turnLightOn()
{
lightGO.SetActive(true);
audio[0].Play();
}
//Call this function to turn the light off
void turnLightOff()
{
lightGO.SetActive(false);
audio[1].Play();
}
}
|
using LoadBalancer.Core;
using LoadBalancer.Heartbeat;
using LoadBalancer.LoadBalancer.Strategies;
using LoadBalancer.Providers;
using System;
using System.Collections.Generic;
using System.Threading;
namespace DemoLoadBalance
{
class Program
{
public static void Main(string[] args)
{
var lb = BuildLoadBalancer();
Console.WriteLine("The demo uses a round robin load balancing strategy to distribute requests between providers Echo, Foxtrot and Golf.");
Console.WriteLine("Every second, a new requests comes and the next in line provider picks it up.");
Console.WriteLine("There is a health check every 3 seconds.");
Console.WriteLine("Echo and Golf are stable but Foxtrot succeeds and fails health checks in alternating threes.");
Console.WriteLine("Foxtrot is then temporarily removed from the avaliable providers.");
Console.WriteLine("Press a key and read the logs to see the above story unfold.\n\n");
Console.ReadKey(true);
List<IProvider> providers = BuildProviders();
lb.Register(providers);
for (int i = 0; i < 100; i++)
{
Console.WriteLine($"Provider selected: {lb.Get().Result}");
Thread.Sleep(1000);
}
}
private static List<IProvider> BuildProviders()
{
return new List<IProvider>(new IProvider[]
{
new Provider("Echo"),
new SuccessFailureAlternateProvider("Foxtrot", 3), // 3 successful checks, 3 failed, alternating
new Provider("Golf")
});
}
private static DefaultLoadBalancer BuildLoadBalancer() // TODO: include this in library? IOptions / IConfig object?
{
var registry = new ProviderRegistry();
var strategy = new RoundRobinStrategy();
var scheduler = new Scheduler(interval: 3000); // healthcheck scheduled every 3 seconds
var heartbeatChecker = new HeartbeatChecker(registry, scheduler);
var lb = new DefaultLoadBalancer(registry, strategy, heartbeatChecker);
return lb;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using NetCode.Payloads;
namespace NetCode.Connection.UDP
{
public class UDPFeed : NetworkConnection
{
public IPEndPoint Destination { get; private set; }
public UDPServer Host { get; private set; }
public bool IsIncoming { get; private set; }
private List<byte[]> IncomingData;
public UDPFeed(UDPServer host, IPEndPoint destination, bool incoming)
{
Destination = destination;
Host = host;
IncomingData = new List<byte[]>();
IsIncoming = incoming;
}
internal void FeedData(byte[] data)
{
IncomingData.Add(data);
}
protected override void SendData(byte[] data)
{
Host.Transmit(data, Destination);
}
protected override List<byte[]> RecieveData()
{
Host.FlushRecieve();
if (IncomingData.Count > 0)
{
List<byte[]> data = IncomingData;
IncomingData = new List<byte[]>();
return data;
}
return null;
}
public override void Destroy()
{
Host.CloseFeed(this);
Host = null;
IncomingData.Clear();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StreetLight : MonoBehaviour
{
public float turnOnTime;
public float turnOffTime;
public float transitionSpeed;
private VRTime timescript;
private Light lightToControl;
private float defaultIntensity;
private bool isOn;
// Use this for initialization
void Start()
{
timescript = GameObject.FindObjectOfType<VRTime>();
timescript.timeChanged += TimeChanged;
lightToControl = GetComponent<Light>();
defaultIntensity = lightToControl.intensity;
}
private void TimeChanged(float time)
{
float twentyFourTimeFormat = timescript.getTimeAstwentyFourFormat();
if ((twentyFourTimeFormat > turnOnTime && twentyFourTimeFormat < turnOffTime) || (turnOffTime < turnOnTime && (twentyFourTimeFormat < turnOffTime && twentyFourTimeFormat < turnOnTime || twentyFourTimeFormat > turnOffTime && twentyFourTimeFormat > turnOnTime)))
{
if (!isOn)
{
StopAllCoroutines();
StartCoroutine(FadeLightOn());
}
}
else
{
if (isOn)
{
StopAllCoroutines();
StartCoroutine(FadeLightOff());
}
}
}
private IEnumerator FadeLightOn()
{
while (lightToControl.intensity < defaultIntensity)
{
lightToControl.intensity += transitionSpeed * Time.deltaTime;
yield return 0;
}
lightToControl.intensity = defaultIntensity;
isOn = true;
}
private IEnumerator FadeLightOff()
{
while (lightToControl.intensity > 0)
{
lightToControl.intensity -= transitionSpeed * Time.deltaTime;
yield return 0;
}
lightToControl.intensity = 0;
isOn = false;
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class shooting : MonoBehaviour
{
public GameObject bulletPrefab;
public Transform ShootPoint;
public Camera cam;
public Vector2 lookDirection;
public float angle;
public float bulletCap = 15;
public float ReloadTime = 1.5f;
public float BulletSpeed = 10f;
public SpriteRenderer sr;
public AudioSource ShootSound;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Vector3 MousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position;
if (MousePos.x < 0)
{
sr.flipX = true;
}
else
{
sr.flipX = false;
}
if (Input.GetButtonDown("Fire1"))
{
ShootSound.Play();
Shoot();
}
}
public void Shoot()
{
GameObject bullet = Instantiate(bulletPrefab, ShootPoint.position, ShootPoint.rotation);
Rigidbody2D rb = bullet.GetComponent<Rigidbody2D>();
rb.AddForce(ShootPoint.up * BulletSpeed, ForceMode2D.Impulse);
}
}
|
using System.Collections.Generic;
using UnityEngine.Serialization;
using System;
using System.Collections;
using UnityEngine;
using UnityEngine.Events;
public class AfterAudioFinishDo : MonoBehaviour
{
[Serializable]
public class StartThisEvent : UnityEvent { }
[FormerlySerializedAs("IfCounterOver")]
[SerializeField]
private StartThisEvent getCounter = new StartThisEvent();
protected AfterAudioFinishDo()
{ }
public StartThisEvent ifTextFound
{
get { return getCounter; }
set { getCounter = value; }
}
private void Press()
{
UISystemProfilerApi.AddMarker("Button.onClick", this);
getCounter.Invoke();
}
// Start is called before the first frame update
void Start()
{
StartCoroutine(waitForSound());
}
IEnumerator waitForSound()
{
while (GetComponent<AudioSource>().isPlaying)
{
yield return null;
}
Press();
}
}
|
using UnityEngine;
using System.Collections.Generic;
using System.IO;
public class MeanController : MonoBehaviour {
#region Setting
public Texture2D InputTEX;
private Color32[] InputColor32s;
#endregion
#region MONO_BEHAVIOUR
void Start () {
InputColor32s = InputTEX.GetPixels32();
Debug.Log("InputTEX WH: " + InputTEX.width + ", " + InputTEX.height);
}
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
Debug.Log("SPACE");
Debug.Log("V2:"+ MyMath.ConvertIndexToXY(20, 15));
}
if (Input.GetKeyDown(KeyCode.N))
{
Debug.Log("New IMG");
Texture2D Tex2D = new Texture2D(InputTEX.width, InputTEX.height, InputTEX.format, true);
List<Color32> L_Colors = new List<Color32>();
for (int I = 0; I < Tex2D.height; I++)
{
for (int J = 0; J < Tex2D.width; J++)
{
if (I % 2 == 0 && J % 2 == 0)
{
//Tex2D.SetPixel(J, I, Color.red);
L_Colors.Add(new Color32(0, 255, 0, 255));
}
else
{
L_Colors.Add(Color.cyan);
}
}
}
Tex2D.SetPixels32(L_Colors.ToArray());
Tex2D.Apply();
//Tex2D.SetPixels32(InputColor32s);
//Tex2D.Apply();
File.WriteAllBytes(Application.dataPath+"/NewIMG.png", Tex2D.EncodeToPNG());
}
}
#endregion
} |
using BPiaoBao.Common.Enums;
using BPiaoBao.DomesticTicket.Domain.Models.Orders.Behaviors;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BPiaoBao.DomesticTicket.Domain.Models.Orders.States
{
/// <summary>
/// 订单完成
/// </summary>
[OrderState(EnumOrderStatus.IssueAndCompleted)]
public class IssueAndCompletedState : BaseOrderState
{
public override Type[] GetBahaviorTypes()
{
return new Type[] {
typeof(AfterSaleApplyBehavior)
};
}
}
}
|
using PointOfSalesV2.Entities;
using System;
using System.Collections.Generic;
using System.Text;
namespace PointOfSalesV2.Repository
{
public class InventoryEntryRepository : Repository<InventoryEntry>, IInventoryEntryRepository
{
public InventoryEntryRepository(MainDataContext context) : base(context)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using WebBanHang_FoodHub.Model;
namespace WebBanHang_FoodHub.DataUtil
{
public class DataOrderDetail
{
SqlConnection conn = null;
SqlCommand cmd = null;
SqlDataReader dr = null;
public DataOrderDetail()
{
conn = Connection.Connect();
}
public int InsertOrderDetail(OrderDetail orderProduct)
{
conn.Open();
cmd = new SqlCommand("Proc_InsertOrderDetail", conn);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@ProductId", orderProduct.ProductId);
cmd.Parameters.AddWithValue("@Quantity", orderProduct.Quantity);
int rowAffects = cmd.ExecuteNonQuery();
conn.Close();
return rowAffects;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LemonadeStand
{
public class MarketPlace
{
Lemon lemon;
Water water;
Sugar sugar;
Ice ice;
int iceAmount;
int lemonAmount;
int waterAmount;
int sugarAmount;
public MarketPlace()
{
}
//have prices
public void GenerateIcePrice()
{
ice = new Ice();
int result = MainMenu.RollDie(0, 10);
if (result >= 5)
{
ice.price = 0.10;
}
else
{
ice.price = 0.05;
}
}
public void GenerateLemonPrice()
{
lemon = new Lemon();
int result = MainMenu.RollDie(0, 10);
if (result >= 5)
{
lemon.price = 0.25;
}
else
{
lemon.price = 0.10;
}
}
public void GenerateWaterPrice()
{
water = new Water();
int result = MainMenu.RollDie(0, 10);
if (result >= 5)
{
water.price = 0.05;
}
else
{
water.price = 0.00;
}
}
public void GenerateSugarPrice()
{
sugar = new Sugar();
int result = MainMenu.RollDie(0, 10);
if (result >= 5)
{
sugar.price = 0.75;
}
else
{
sugar.price = 0.50;
}
}
public void PopulateProjectedPrices()
{
ice.predictedPrice = ice.price;
lemon.predictedPrice = lemon.price;
water.predictedPrice = water.price;
sugar.predictedPrice = sugar.price;
}
public void BuyIce(Player player)
{
Console.WriteLine($"The price of ice is ${ice.price}.");
PopulateProjectedPrices();
Console.WriteLine("Would you like to buy ice?");
string getIceResult = Console.ReadLine().ToLower();
switch (getIceResult)
{
case "yes":
Console.WriteLine("How much ice would you like?");
string iceTextAmount=Console.ReadLine();
try
{
iceAmount = Convert.ToInt32(iceTextAmount);
}
catch
{
Console.WriteLine("Please type a numeric value from 1 or higher.");
BuyIce(player);
}
if (iceAmount >= 1)
{
ice.predictedAmount = iceAmount;
double projectedAmount = ice.predictedPrice * ice.predictedAmount;
if(projectedAmount > player.wallet.money)
{
Console.WriteLine("You do not have enough to buy! Please move on to another ingredient or try a different amount.");
BuyIce(player);
}
else
{
ice.amount += iceAmount;
double iceBuy= player.wallet.money -= projectedAmount;
int iceAdd=ice.amount + iceAmount;
double iceTransfer = player.inventory.icePrice;
double giveIcePrice = iceTransfer += ice.price;
Console.WriteLine($"You purchased {iceAmount} cups of ice at ${ice.price} a cup.");
Console.WriteLine($"You now have ${iceBuy} in your wallet.");
}
}
break;
case "no":
break;
default:
Console.WriteLine("Please type 'yes' or 'no'");
BuyIce(player);
break;
}
}
public void BuyLemon(Player player)
{
Console.WriteLine($"The price of a lemon is ${lemon.price}.");
PopulateProjectedPrices();
Console.WriteLine("Would you like to buy lemon?");
string getLemonResult = Console.ReadLine().ToLower();
switch (getLemonResult)
{
case "yes":
Console.WriteLine("How many lemons would you like?");
string lemonTextAmount = Console.ReadLine();
try
{
lemonAmount = Convert.ToInt32(lemonTextAmount);
}
catch
{
Console.WriteLine("Please type a numeric value from 1 or higher.");
BuyLemon(player);
}
if (lemonAmount >= 1)
{
lemon.predictedAmount = lemonAmount;
double projectedAmount = lemon.predictedPrice * lemon.predictedAmount;
if (projectedAmount > player.wallet.money)
{
Console.WriteLine("You do not have enough to buy! Please move on to another ingredient or try a different amount.");
BuyLemon(player);
}
else
{
lemon.amount += lemonAmount;
double lemonBuy = player.wallet.money -= projectedAmount;
double lemonTransfer = player.inventory.lemonPrice;
double giveLemonPrice = lemonTransfer += lemon.price;
int lemonAdd = lemon.amount + lemonAmount;
Console.WriteLine($"You purchased {lemonAmount} lemon(s) at ${lemon.price} a lemon.");
Console.WriteLine($"You now have ${lemonBuy} in your wallet.");
}
}
break;
case "no":
break;
default:
Console.WriteLine("Please type 'yes' or 'no'");
BuyLemon(player);
break;
}
}
public void BuySugar(Player player)
{
Console.WriteLine($"The price of sugar is ${sugar.price}.");
PopulateProjectedPrices();
Console.WriteLine("Would you like to buy sugar?");
string getSugarResult = Console.ReadLine().ToLower();
switch (getSugarResult)
{
case "yes":
Console.WriteLine("How much sugar would you like?");
string sugarTextAmount = Console.ReadLine();
try
{
sugarAmount = Convert.ToInt32(sugarTextAmount);
}
catch
{
Console.WriteLine("Please type a numeric value from 1 or higher.");
BuySugar(player);
}
if (sugarAmount >= 1)
{
sugar.predictedAmount = sugarAmount;
double projectedAmount = sugar.predictedPrice * sugar.predictedAmount;
if (projectedAmount > player.wallet.money)
{
Console.WriteLine("You do not have enough to buy! Please move on to another ingredient or try a different amount.");
BuySugar(player);
}
else
{
sugar.amount += sugarAmount;
double sugarBuy = player.wallet.money -= projectedAmount;
double sugarTransfer = player.inventory.sugarPrice;
double giveSugarPrice = sugarTransfer += sugar.price;
int sugarAdd = sugar.amount + sugarAmount;
Console.WriteLine($"You purchased {sugarAmount} cup(s) of sugar at ${sugar.price} a cup.");
Console.WriteLine($"You now have ${sugarBuy} in your wallet.");
}
}
break;
case "no":
break;
default:
Console.WriteLine("Please type 'yes' or 'no'");
BuySugar(player);
break;
}
}
public void BuyWater(Player player)
{
Console.WriteLine($"Water is ${water.price}.");
PopulateProjectedPrices();
Console.WriteLine("Would you like to get water?");
string getWaterResult = Console.ReadLine().ToLower();
switch (getWaterResult)
{
case "yes":
Console.WriteLine("How much water would you like?");
string waterTextAmount = Console.ReadLine();
try
{
waterAmount = Convert.ToInt32(waterTextAmount);
}
catch
{
Console.WriteLine("Please type a numeric value from 1 or higher.");
BuyWater(player);
}
if (waterAmount >= 1)
{
water.predictedAmount = waterAmount;
double projectedAmount = water.predictedPrice * water.predictedAmount;
if (projectedAmount > player.wallet.money)
{
Console.WriteLine("You do not have enough to buy! Please move on to another ingredient or try a different amount.");
BuyWater(player);
}
else
{
water.amount += waterAmount;
double waterBuy = player.wallet.money -= projectedAmount;
int waterAdd = water.amount + waterAmount;
double waterTransfer = player.inventory.waterPrice;
double giveWaterPrice = waterTransfer += water.price;
Console.WriteLine($"You purchased {waterAmount} cup(s) of water at ${water.price} a cup.");
Console.WriteLine($"You now have ${waterBuy} in your wallet.");
}
}
break;
case "no":
break;
default:
Console.WriteLine("Please type 'yes' or 'no'");
BuyWater(player);
break;
}
try
{
player.Inventory.GrabIngredientsFromStore(ice.amount, lemon.amount, sugar.amount, water.amount);
}
catch
{
}
}
public void EvaluateMarketPrices()
{
GenerateSugarPrice();
GenerateIcePrice();
GenerateLemonPrice();
GenerateWaterPrice();
Console.WriteLine($"A cup of sugar costs${sugar.price}, half a bag of ice costs ${ice.price}, a lemon costs ${lemon.price}, and water is {water.price}.");
}
public void DecideToShop(Player player)
{
Console.WriteLine("Would you like to purchase ingredients for your lemonade?");
string shopDecision = Console.ReadLine().ToLower();
switch (shopDecision)
{
case "yes":
PurchaseIngredients(player);
break;
case "no":
break;
default:
Console.WriteLine("Please type 'yes' or 'no'");
DecideToShop(player);
break;
}
}
public void PurchaseIngredients(Player player)
{
EvaluateMarketPrices();
BuyIce(player);
BuyLemon(player);
BuySugar(player);
BuyWater(player);
}
//public void GiveCurrentIngredientAmounts()
//{
// GiveCurrentIceAmount();
// GiveCurrentLemonAmount();
// GiveCurrentSugarAmount();
// GiveCurrentWaterAmount();
//}
//public int GiveCurrentLemonAmount()
//{
// int lemonTally = lemon.amount;
// return lemonTally;
//}
//public int GiveCurrentIceAmount()
//{
// int iceTally = ice.amount;
// return iceTally;
//}
//public int GiveCurrentWaterAmount()
//{
// int waterTally = water.amount;
// return waterTally;
//}
//public int GiveCurrentSugarAmount()
//{
// int sugarTally = sugar.amount;
// return sugarTally;
//}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
using AgentStoryComponents.core;
using AgentStoryComponents;
namespace AgentStoryComponents.commands
{
public class cmdDeleteStoryTuple : ICommand
{
public MacroEnvelope execute(Macro macro)
{
utils ute = new utils();
int storyID = MacroUtils.getParameterInt("storyID", macro);
int id = MacroUtils.getParameterInt("id", macro);
Tuple t = new Tuple(config.sqlConn, id);
Story.dissociateStoryTuple(config.conn, t.id, storyID);
t.delete();
string msg = string.Format("removed Story Tuple {0}",t.id);
MacroEnvelope me = new MacroEnvelope();
Macro m = new Macro("AlertAndRefresh", 2);
m.addParameter("msg", ute.encode64(msg));
m.addParameter("severity", "1");
me.addMacro(m);
return me;
}
}
}
|
using KRF.Core.Entities.Master;
using System.Collections.Generic;
namespace KRF.Core.DTO.Master
{
/// <summary>
/// This class does not have database table. This class acts as a container for below products classes
/// </summary>
public class VendorDTO
{
public IList<Vendor> Vendors { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using Sunny.Lib;
namespace Sunny.BackendTool
{
public class LotteryArg : BaseArg
{
[CommandAttribute("-ssq")]
public bool SSQ { get; set; }
[CommandAttribute("-dlt")]
public bool DLT { get; set; }
[CommandAttribute("-ex")]
public bool Exclude { get; set; }
[CommandAttribute("-ah")]
public bool AnalyzeHistory { get; set; }
[CommandAttribute("-reall")]
public bool ResetAll { get; set; }
[CommandAttribute("-reif")]
public bool ResetImpossiblehitFlag { get; set; }
[CommandAttribute("-ia")]
public bool ImportAll { get; set; }
[CommandAttribute("-ih")]
public bool ImportHistory { get; set; }
[CommandAttribute("-ge")]
public bool Generate { get; set; }
[CommandAttribute("-count")]
public int Count { get; set; }
[CommandAttribute("-out")]
public string Output { get; set; }
public override void Process()
{
LotteryConfiguration config = LotterySectionHandler.GetConfigurationObject(ConfigurationSectionConst.GroupNames[0], ConfigurationSectionConst.SectionNames[0]);
Logger.LogInformation(string.Format("Read Configures:'{0}'", config.ToString()), Const.ModuleName, LoggerCarrier.File);
if (this.SSQ)
{
LotteryProcessor.SSQProcess(this, config);
}
else
{
LotteryProcessor.DLTProcess(this, config);
}
}
public override void PrintUsage()
{
Console.WriteLine("-2 Usage:");
Console.WriteLine("[-ssq|dlt -ia] - Run to inport data to ssq_all_chance.");
Console.WriteLine("[-ssq|dlt -ih] - Run to inport data to ssq_history.");
Console.WriteLine("[-ssq|dlt -ah] - Run to analyze ssq history data.");
Console.WriteLine("[-ssq|dlt -reall] - Run to reset ssq database.");
Console.WriteLine("[-ssq|dlt -reif] - Run to reset [ssq_allchance].[b_impossiblehit_flag]");
Console.WriteLine("[-ssq|dlt -ex] - Run to set [ssq_allchance].[b_impossiblehit_flag] to exclude impossible hit numbers");
Console.WriteLine("[-ssq -ge -count 10000 -out ssq17025.txt] - Run to generate 10000 numbers into ssq17025.txt file.");
}
}
}
|
/*
* Bungie.Net API
*
* These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality.
*
* OpenAPI spec version: 2.1.1
* Contact: support@bungie.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter;
namespace BungieNetPlatform.Model
{
/// <summary>
/// The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.
/// </summary>
/// <value>The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.</value>
[JsonConverter(typeof(StringEnumConverter))]
public enum DestinyActivityGraphNodeHighlightType
{
/// <summary>
/// The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.
/// </summary>
[EnumMember(Value = "0")]
None,
/// <summary>
/// The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.
/// </summary>
[EnumMember(Value = "1")]
Normal,
/// <summary>
/// The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.
/// </summary>
[EnumMember(Value = "2")]
Hyper,
/// <summary>
/// The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.
/// </summary>
[EnumMember(Value = "3")]
Comet,
/// <summary>
/// The various known UI styles in which an item can be highlighted. It'll be up to you to determine what you want to show based on this highlighting, BNet doesn't have any assets that correspond to these states. And yeah, RiseOfIron and Comet have their own special highlight states. Don't ask me, I can't imagine they're still used.
/// </summary>
[EnumMember(Value = "4")]
RiseOfIron
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Remanufacture_level : MonoBehaviour,ILevel {
[SerializeField]
private float timerDuration = 1;
[SerializeField]
private float subtractAmount = 0.1f; //The step the timer downgrades
[SerializeField]
private bool hasTimer = true;
//Setup level with the correct lines
void Start() {
GameManager.instance.episodeManager.ResetLines();
GameManager.instance.levelTimer.SetupTimer(timerDuration, subtractAmount, hasTimer);
GameManager.instance.levelTimer.currentLevel = this.gameObject;
StartCoroutine(LevelDialogues());
}
void Update() { }
public IEnumerator LevelDialogues() {
Debug.Log("started level 2");
yield return new WaitForSeconds(2);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Soyboy, 5f));
yield return new WaitForSeconds(5);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Poppa, 10f));
yield return new WaitForSeconds(5);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Poppa, 5f));
yield return new WaitForSeconds(8);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Poppa, 5f));
yield return new WaitForSeconds(5);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Poppa, 5f));
yield return new WaitForSeconds(5);
}
public IEnumerator EndLevelSequence() {
yield return new WaitForSeconds(2);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Poppa, 5f));
yield return new WaitForSeconds(5);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Soyboy, 5f));
yield return new WaitForSeconds(5);
GameManager.instance.episodeManager.CallEpisodeAudioAndSubs(Episode.Episode2);
StartCoroutine(GameManager.instance.episodeManager.Talk(Speaker.Poppa, 5f));
yield return new WaitForSeconds(2);
StartCoroutine(GameManager.instance.episodeManager.EndCurrentEpisode());
}
}
/*
1 is de max (1.00F)
timer moet dus als max value 1.00F hebben
Stel 60 seconde
1/60 = de stapwaarde(?)
*/ |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace aoc
{
public class D32
{
public string Answer
{
get
{
var directions = File.ReadAllLines("d3.txt");
var w1Dirs = directions[0].Split(',');
var w2Dirs = directions[1].Split(',');
var w1 = CreateSegmentsFromDirections(w1Dirs);
var w2 = CreateSegmentsFromDirections(w2Dirs);
int minSteps = int.MaxValue;
int w1Steps = 0;
foreach (var seg1 in w1)
{
w1Steps += seg1.Length;
int w2Steps = 0;
foreach (var seg2 in w2)
{
w2Steps += seg2.Length;
var intersection1 = seg1.IntersectingPoint(seg2);
var intersection2 = seg2.IntersectingPoint(seg1);
var intersection = intersection1.HasValue ? intersection1 : intersection2.HasValue ? intersection2 : null;
if (intersection != null)
{
var totalSteps = w1Steps + w2Steps - seg1.LengthFromPoint(intersection.Value) - seg2.LengthFromPoint(intersection.Value);
if (totalSteps < minSteps) {
minSteps = totalSteps;
}
}
}
}
return minSteps.ToString();
}
}
private List<Segment> CreateSegmentsFromDirections(string[] directions)
{
var segments = new List<Segment>();
int x = 0, y = 0;
foreach (var dir in directions)
{
int newX = x, newY = y;
if (dir.StartsWith('R'))
newX += int.Parse(dir.Substring(1));
else if (dir.StartsWith('L'))
newX -= int.Parse(dir.Substring(1));
else if (dir.StartsWith('U'))
newY -= int.Parse(dir.Substring(1));
else if (dir.StartsWith('D'))
newY += int.Parse(dir.Substring(1));
segments.Add(new Segment { Start = new Point(x, y), End = new Point(newX, newY) });
x = newX;
y = newY;
}
return segments;
}
private class Segment
{
public Point Start;
public Point End;
public int LengthFromPoint(Point point) {
return Segment.LengthBetweenPoints(point, End);
}
public int Length => Segment.LengthBetweenPoints(Start, End);
private static int LengthBetweenPoints(Point p1, Point p2) {
var p = Subtract(p2, p1);
return Math.Abs(p.X) + Math.Abs(p.Y);
}
private static Point Subtract(Point p1, Point p2) {
return new Point(p2.X - p1.X, p2.Y - p1.Y);
}
internal Point? IntersectingPoint(Segment other)
{
var leftMostThisX = Math.Min(Start.X, End.X);
var rightMostThisX = Math.Max(Start.X, End.X);
var topMostThisY = Math.Min(Start.Y, End.Y);
var bottomMostThisY = Math.Max(Start.Y, End.Y);
var leftMostThatX = Math.Min(other.Start.X, other.End.X);
var rightMostThatX = Math.Max(other.Start.X, other.End.X);
var topMostThatY = Math.Min(other.Start.Y, other.End.Y);
var bottomMostThatY = Math.Max(other.Start.Y, other.End.Y);
if (leftMostThisX <= leftMostThatX && rightMostThisX >= rightMostThatX)
{
if (topMostThatY <= topMostThisY && bottomMostThatY >= bottomMostThisY)
{
if (other.Start.X != 0 && Start.Y != 0)
return new Point(other.Start.X, Start.Y);
}
}
return null;
}
}
}
} |
//Problem 18.* Trailing Zeroes in N!
//Write a program that calculates with how many zeroes the factorial of a given number n has at its end.
//Your program should work well for very big numbers, e.g. n=100000.
using System;
namespace Problem18TrailingZeroesInN
{
class TrailingZeroesInN
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
int zeros = 0;
int powFive = 1;
int denominator = 0;
while (denominator <= number)
{
denominator = (int)Math.Pow(5, powFive);
zeros += number / denominator;
++powFive;
}
Console.WriteLine("{0}! has {1} trailing zeros.", number, zeros);
}
}
}
|
using Core.Domain;
using Core.Dto;
using Core.Fakes;
using Core.Internal.Dependency;
using Core.Internal.Kendo.DynamicLinq;
using Core.Utils.Linq2Db;
using LightInject;
using LinqToDB.Mapping;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Core.MSTest.FakeContext
{
[TestClass]
public class FakeContextSelectTests
{
Scope _scope;
IServiceContainer _container;
public TaxRateForBankEntityService Service { get; set; }
/// <summary>
/// Инициализация фейкоговог контекста
/// </summary>
[TestInitialize]
public void InitFake()
{
//нужен Ioc
new DependencyInitializer()
.TestMode(true)
.ForAssembly(GetType().Assembly)
.Init((dbConfig, container) =>
{
container.SetFakeContext();
_scope = container.BeginScope();
container.InjectProperties(this);
_container = container;
});
//Определим фейковые данные
var bnkSeekList = new List<BnkSeekEntity>
{
new BnkSeekEntity
{
Id = 1,
Bik = "123456",
Name = "Bank1"
},
new BnkSeekEntity
{
Id = 2,
Bik = "3456789",
Name = "Bank2"
},
new BnkSeekEntity
{
Id = 3,
Bik = "4444444",
Name = "Bank4"
}
};
_container.SetTable(bnkSeekList);
var taxRateForBankList = new List<TaxRateForBankEntity>
{
new TaxRateForBankEntity
{
Id=1,
Bik="123456",
DateFrom= new DateTime(2017,1,1),
Rate = 0.01M,
Bank = bnkSeekList.First(e=>e.Id==1)
},
new TaxRateForBankEntity
{
Id=2,
Bik="123456",
DateFrom= new DateTime(2017,1,2),
Rate = 0.02M,
Bank = bnkSeekList.First(e=>e.Id==1)
},
new TaxRateForBankEntity
{
Id=3,
Bik="3456789",
DateFrom= new DateTime(2017,1,1),
Rate = 0.03M,
Bank = bnkSeekList.First(e=>e.Id==2)
},
new TaxRateForBankEntity
{
Id=4,
Bik="4444444",
DateFrom= new DateTime(2017,1,1),
Rate = 0.03M,
Bank = bnkSeekList.First(e=>e.Id==3)
},
};
_container.SetTable(taxRateForBankList);
}
[TestCleanup]
public void Dispose()
{
_scope.Dispose();
}
/// <summary>
/// Простой тест на фейковых данных
/// </summary>
[TestMethod]
public void SimpleSelectFakeTest()
{
var queryDto = Service.GetQuery().Take(3);
Assert.AreEqual(3, queryDto.Count());
}
/// <summary>
/// запрос на фейках
/// </summary>
[TestMethod]
public void SelectFakeTest()
{
var request = new DataSourceRequestDto<object>()
{
Take = 3
};
var queryDto = Service.GetBankQueryResultDto(request);
Assert.AreEqual(3, queryDto.Data.Count());
}
/// <summary>
/// сложный запрос на фейках
/// </summary>
[TestMethod]
public void SelectDifficultFakeTest()
{
// Подготовка
var request = new DataSourceRequestDto<TaxRateForBankFilterDto>()
{
FilterDto = new TaxRateForBankFilterDto()
{ CurDate = new DateTime(2017, 1, 3) }
};
// Действие
var queryDto = Service.GetQueryResultDto(request);
// Проверка. Ожидаем три записи, т.к. данные группируются по БИК,
// а в тестовых данных три уникальных БИКа
Assert.AreEqual(3, queryDto.Data.Count());
}
/// <summary>
/// Транзакция должна игнорироваться
/// </summary>
[TestMethod]
public void TransactionFakeTest()
{
using (Service.DataContext.BeginTransaction())
{
var queryDto = Service.GetQuery().Take(3);
Assert.AreEqual(3, queryDto.Count());
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GamepadInput;
public class Player : MonoBehaviour
{
public PlayerInfo PlayerInfo;
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.