text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using UnityEngine;
using zm.Common;
using zm.Questioning;
using zm.Users;
using zm.Util;
namespace zm.Levels
{
[Serializable]
public class Level
{
#region Constants
private static readonly string ImgsPath = "Sprites/Levels/";
#endregion Constants
#region Constructor
public Level()
{
Id = ++IdGen;
}
#endregion Constructor
#region Private Methods
/// <summary>
/// Returns random position that is available.
/// </summary>
/// <returns></returns>
private Vector3 GetPosition()
{
Vector3 position = availablePositions.GetRandom();
availablePositions.Remove(position);
return position;
}
#endregion Private Methods
#region Fields and Properties
/// <summary>
/// Used for generating unique ids for this class.
/// </summary>
private static int IdGen;
public int Id { get; private set; }
/// <summary>
/// All question that user can answer in this level.
/// </summary>
private List<Question> questions;
/// <summary>
/// List of all possible positions for this level.
/// </summary>
public Vector3Collection Positions;
/// <summary>
/// Maximal number of questions that can be active in one moment in game.
/// </summary>
public int MaxNumQuestions;
/// <summary>
/// All categories from which we can take questions.
/// </summary>
public QuestionCategory[] Categories;
/// <summary>
/// Name that will be displayed for this level.
/// </summary>
public string Name;
/// <summary>
/// Return path for image that represents this level.
/// </summary>
public string ImgPath
{
get { return ImgsPath + Name; }
}
/// <summary>
/// Number of questions for this level.
/// </summary>
public int NumOfQuestions { get; private set; }
/// <summary>
/// Represents maximal number of points that user can gain during this level.
/// </summary>
public int MaxPoints { get; private set; }
/// <summary>
/// Available positions for questions on this level.
/// </summary>
private List<Vector3> availablePositions;
#endregion Fields and Properties
#region Public Methods
/// <summary>
/// Returns random question.
/// If there is no more questions in queue, it will return null.
/// </summary>
public Question GetQuestion()
{
Question question = null;
if (!questions.IsEmpty())
{
question = questions.GetRandom();
questions.Remove(question);
question.Position = GetPosition();
}
return question;
}
/// <summary>
/// Initialize all questions for this level.
/// </summary>
/// <param name="questions"></param>
public void InitializeQuestions(List<Question> questions)
{
this.questions = questions;
NumOfQuestions = questions.Count;
MaxPoints = 0;
MaxNumQuestions = questions.Count < MaxNumQuestions ? questions.Count : MaxNumQuestions;
foreach (Question question in questions)
{
MaxPoints += question.Points;
}
availablePositions = new List<Vector3>(Positions.Collection);
}
/// <summary>
/// Returns used position to available positions.
/// </summary>
/// <param name="position"></param>
public void ReturnPosition(Vector3 position)
{
availablePositions.Add(position);
}
#endregion Public Methods
}
} |
using System;
using AutoFixture;
using Moq;
using System.Threading.Tasks;
using NUnit.Framework;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi;
using SFA.DAS.ProviderCommitments.Interfaces;
using SFA.DAS.ProviderCommitments.Web.Mappers.Cohort;
using SFA.DAS.ProviderCommitments.Web.Models;
using SFA.DAS.ProviderCommitments.Web.Services.Cache;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Cohorts;
using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Types;
namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Cohort
{
[TestFixture]
public class SelectDeliveryModelViewModelMapperTests
{
private SelectDeliveryModelViewModelMapper _mapper;
private Mock<IOuterApiClient> _apiClient;
private Mock<ICacheStorageService> _cacheStorageService;
private CreateCohortWithDraftApprenticeshipRequest _request;
private GetAddDraftApprenticeshipDeliveryModelResponse _apiResponse;
private readonly Fixture _fixture = new Fixture();
private CreateCohortCacheItem _cacheItem;
[SetUp]
public void Setup()
{
_request = _fixture.Create<CreateCohortWithDraftApprenticeshipRequest>();
_apiResponse = _fixture.Create<GetAddDraftApprenticeshipDeliveryModelResponse>();
_cacheItem = new CreateCohortCacheItem(Guid.NewGuid());
_cacheStorageService = new Mock<ICacheStorageService>();
_cacheStorageService.Setup(x => x.RetrieveFromCache<CreateCohortCacheItem>(It.IsAny<Guid>()))
.ReturnsAsync(_cacheItem);
_apiClient = new Mock<IOuterApiClient>();
_apiClient.Setup(x => x.Get<GetAddDraftApprenticeshipDeliveryModelResponse>(It.Is<GetAddDraftApprenticeshipDeliveryModelRequest>(r =>
r.AccountLegalEntityId == _cacheItem.AccountLegalEntityId
&& r.CourseCode == _cacheItem.CourseCode
&& r.ProviderId == _request.ProviderId)))
.ReturnsAsync(_apiResponse);
_mapper = new SelectDeliveryModelViewModelMapper(_apiClient.Object, _cacheStorageService.Object);
}
[Test]
public async Task EmployerName_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_apiResponse.EmployerName, result.EmployerName);
}
[Test]
public async Task DeliveryModels_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_apiResponse.DeliveryModels, result.DeliveryModels);
}
[Test]
public async Task DeliveryModel_Is_Mapped_Correctly()
{
var result = await _mapper.Map(_request);
Assert.AreEqual(_cacheItem.DeliveryModel, result.DeliveryModel);
}
[TestCase(DeliveryModel.Regular)]
[TestCase(DeliveryModel.FlexiJobAgency)]
[TestCase(DeliveryModel.PortableFlexiJob)]
public async Task When_Only_One_Delivery_Model_Is_Available_It_Is_Saved_To_Cache(DeliveryModel selection)
{
_apiResponse.DeliveryModels.Clear();
_apiResponse.DeliveryModels.Add(selection);
await _mapper.Map(_request);
_cacheStorageService.Setup(x =>
x.SaveToCache<ICacheModel>(
It.Is<CreateCohortCacheItem>(m => m.DeliveryModel == selection), It.IsAny<int>()));
}
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace ProjetoAutoEscola
{
public partial class AdicionarAluno : Form
{
private MySqlConnection minhaConexao;
private MySqlCommand meuComando1, meuComando2, meuComando3, meuComando4;
private string formataData(string dataBR)
{
String tempDia, tempMes, tempAno;
tempDia = dataBR;
tempMes = dataBR;
tempAno = dataBR;
tempDia = tempDia.Substring(0, 2);
tempMes = tempMes.Substring(3, 2);
tempAno = tempAno.Substring(6, 4);
String dataUS = tempAno + "/" + tempMes + "/" + tempDia;
return dataUS;
}
public AdicionarAluno()
{
InitializeComponent();
txtNome.Focus();
minhaConexao = new MySqlConnection("Persist Security Info = False; server=localhost;user id=root; pwd=mysql; database=projeto");
}
public void CheckarAluno()
{
txtValor.Show();
lblVal.Show();
lblDesc.Show();
txtDescont.Show();
lblPagamento.Show();
cmbPagamento.Show();
lblParc.Show();
cmbParcela.Show();
lblQuitadoStatus.Show();
cmbQuitadoStatus.Show();
lblCategoria.Show();
cmbCategoriaAluno.Show();
}
public void LimparCampos()
{
txtNome.Clear();
mkbCpf.Clear();
mkbRg.Clear();
mkbDataNasc.Clear();
txtLagradouro.Clear();
txtNumero.Clear();
txtCompl.Clear();
mkbCep.Clear();
txtBairro.Clear();
txtEmail.Clear();
mkbTelRes.Clear();
mkbTelRec.Clear();
mkbTelCel.Clear();
mkbTelCelRec.Clear();
txtDefSenha.Clear();
txtDefUser.Clear();
cmbUf.Text = "";
cmbPagamento.Text = "";
cmbCategoriaAluno.Text = "";
txtCidade.Text = "";
txtValor.Text = "";
txtDescont.Text = "";
}
private void AdicionarAluno_Load(object sender, EventArgs e)
{
txtNome.Focus();
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void label10_Click(object sender, EventArgs e)
{
}
private void textBox6_TextChanged(object sender, EventArgs e)
{
}
private void btnAdd_Click(object sender, EventArgs e)
{
mkbCpf.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
mkbRg.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
mkbCep.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
mkbTelRec.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
mkbTelRes.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
mkbTelCel.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
mkbTelCelRec.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals;
string dataFormatada = formataData(mkbDataNasc.Text);
try
{
minhaConexao.Open();
if (minhaConexao.State == ConnectionState.Open)
{
meuComando1 = new MySqlCommand("INSERT INTO aluno (num_mat, senha, nome, cpf, rg, email, dt_nasc, id_aluno) VALUES ('"+ txtMatricula.Text +"', '"+ txtDefSenha.Text +"', '" + txtNome.Text + "','" + mkbCpf.Text + "', '" + mkbRg.Text + "', '" + txtEmail.Text + "', '"+ dataFormatada +"', '"+ txtDefUser.Text +"')", minhaConexao);
meuComando2 = new MySqlCommand("INSERT INTO end_aluno (cep, rua, bairro, uf, cidade) VALUES ('" + mkbCep.Text + "', '" + txtLagradouro.Text + "', '" + txtBairro.Text + "', '" + cmbUf.SelectedItem.ToString() + "', '" + txtCidade.Text + "')", minhaConexao);
meuComando3 = new MySqlCommand("INSERT INTO telefone_alun (tel_resid, tel_resid_rec, celular, cel_recad, num_mat) VALUES ('" + mkbTelRes.Text + "','" + mkbTelRec.Text + "','" + mkbTelCel.Text + "', '" + mkbTelCelRec.Text + "','" + txtMatricula.Text + "' )", minhaConexao);
meuComando4 = new MySqlCommand("INSERT INTO transacao (metodo, valor, nro_parcel, desconto, obs) VALUES ('"+ cmbPagamento.SelectedItem.ToString() +"', '"+ txtValor.Text +"', '"+ cmbParcela.SelectedItem.ToString() +"', '"+ txtDescont.Text +"', '"+ cmbQuitadoStatus.SelectedItem.ToString() +"')", minhaConexao);
meuComando1.ExecuteNonQuery();
meuComando2.ExecuteNonQuery();
meuComando3.ExecuteNonQuery();
meuComando4.ExecuteNonQuery();
MessageBox.Show("Usuario cadastrado!", "Sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Information);
Close();
}
else
MessageBox.Show("Usuario não cadastrado!", "Erro!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
catch
{
MessageBox.Show("Erro no envio para o Banco de Dados", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
minhaConexao.Close();
}
}
private void label21_Click(object sender, EventArgs e)
{
}
private void btnLimpar_Click(object sender, EventArgs e)
{
LimparCampos();
}
private void btnCancelar_Click(object sender, EventArgs e)
{
this.Close();
}
private void label11_Click(object sender, EventArgs e)
{
}
private void cmbProfissaoFunc_TextChanged(object sender, EventArgs e)
{
}
private void txtPagamento_TextChanged(object sender, EventArgs e)
{
}
private void cmbPagamento_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void cmbProfissaoFunc_SelectedIndexChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void lblCategoria_Click(object sender, EventArgs e)
{
}
private void cmbCategoriaAluno_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
|
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Mercadinho.DAO
{
class CarrinhoServicoDAO
{
private Model.CarrinhoServico carrinhoservicos;
private MySqlConnection con;
private Conexao.Conexao conexao;
private List<Model.Servicos> listadeservicos;
private List<Model.Fatura> faturas;
public CarrinhoServicoDAO()
{
listadeservicos = new List<Model.Servicos>();
faturas = new List<Model.Fatura>();
}
internal List<Model.Servicos> Listadeservicos { get => listadeservicos; set => listadeservicos = value; }
internal List<Model.Fatura> Faturas { get => faturas; set => faturas = value; }
//metodo para inserir dados no carrinho
public void InserirDadosCarrinho(Model.CarrinhoServico carrinho)
{
con = new MySqlConnection();
carrinhoservicos = new Model.CarrinhoServico();
conexao = new Conexao.Conexao();
con.ConnectionString = conexao.getConnectionString();
String query = "INSERT INTO carrinho(TotalCarrinho, CPF)";
query += " VALUES (?TotalCarrinho, ?CPF);SELECT LAST_INSERT_ID() as id;";
try
{
con.Open();
MySqlCommand cmd = new MySqlCommand(query, con);
cmd.Parameters.AddWithValue("?TotalCarrinho", carrinho.calcularcarrinho());
cmd.Parameters.AddWithValue("?CPF", carrinho.Cliente.CPF);
MySqlDataReader reader = cmd.ExecuteReader();
var idcarrinho = 0;
while (reader.Read())
{
idcarrinho = reader.GetInt32("id");
}
cmd.Dispose();
reader.Close();
foreach (Model.Servicos prod in carrinho.Servicos1)
{
String query2 = "INSERT INTO carrinho_servico(Id_Carrinho, Id_Servico)" +
" VALUES (?idCarrinho, ?Id_Servico);";
MySqlCommand cmd2 = new MySqlCommand(query2, con);
cmd2.Parameters.AddWithValue("?idCarrinho", idcarrinho);
cmd2.Parameters.AddWithValue("?Id_Servico", prod.Idservico);
cmd2.ExecuteNonQuery();
cmd2.Dispose();
}
foreach (Model.Fatura fat in carrinho.Parcelas)
{
String query3 = "INSERT INTO fatura(Valor_Total, Data_Vencimento,Data_Pagamento, FormaPagamento, EstaPago, Id_Carrinho)" +
" VALUES (?Valor_Total, ?Data_Vencimento,?Data_Pagamento, ?FormaPagamento, ?EstaPago, ?Id_Carrinho);";
MySqlCommand cmd3 = new MySqlCommand(query3, con);
cmd3.Parameters.AddWithValue("?Valor_Total", fat.Valorfatura);
cmd3.Parameters.AddWithValue("?Data_Vencimento", fat.DataVencimento1.Date);
cmd3.Parameters.AddWithValue("?Data_Pagamento", fat.DataPagamento1.Date);
cmd3.Parameters.AddWithValue("?FormaPagamento", fat.Formadepagamento);
cmd3.Parameters.AddWithValue("?EstaPago", fat.Estapago);
cmd3.Parameters.AddWithValue("?Id_Carrinho", idcarrinho);
cmd3.ExecuteNonQuery();
cmd3.Dispose();
}
}
catch (Exception ex)
{
MessageBox.Show("Erro: " + ex);
}
finally
{
con.Close();
}
}
}
}
|
namespace SpaceHosting.Index
{
public class IndexQueryDataPoint<TVector>
where TVector : IVector
{
public TVector Vector { get; set; } = default!;
}
}
|
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SizeFitter : MonoBehaviour {
// Use this for initialization
void Awake () {
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DistCWebSite.Core.Entities;
using DistCWebSite.Core.Interfaces;
namespace DistCWebSite.Infrastructure
{
public class MenuRepository : IMenu
{
/// <summary>
/// 根据角色列表获取菜单列表
/// </summary>
/// <param name="list"></param>
/// <returns></returns>
public List<M_Menu> MenuList(List<string> list)
{
List<M_Menu> realList = new List<M_Menu>();
//存储有角色的和任何角色都可以查看的菜单
List<M_Menu> m_list = new List<M_Menu>();
if (list.Count > 0)
{
var ctx = new DistCSiteContext();
//获取菜单列表
List<M_Menu> menuList = ctx.M_Menu.ToList();
foreach (var item in menuList)
{
//获取当前菜单页所有的可以访问的权限角色
List<string> arr = new List<string>();
if (!string.IsNullOrEmpty(item.RoleCode))
arr = item.RoleCode.Split(';').ToList();
if (arr.Count > 0)
{
foreach (var role in arr)
{
if (!string.IsNullOrEmpty(role))
{
//判断当前登录人的角色是否可以访问该页面
if (list.Contains(role))
m_list.Add(item);
}
}
}
else
{
//当前页面无权限设置
m_list.Add(item);
}
}
if (m_list.Count > 0)
{
m_list = m_list.Distinct().ToList();
var menu = m_list.OrderBy(x => x.OrderIndex).GroupBy(x => x.ParentID).ToList();
if (menu.Count > 0)
{
foreach (var item in menu)
{
//判断该页面是否启用
realList.AddRange(item.Where(x => x.Active == true));
}
}
}
}
return realList;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Windows.Input;
using Inventory.Common;
using Inventory.Data;
using Inventory.Models;
using Inventory.ViewModels;
using Linphone;
using Linphone.Model;
using Windows.Devices.Enumeration;
using Windows.Media.Devices;
namespace Inventory.Services
{
public class AudioCodec : ObservableObject
{
public int Channels { get; set; }
public int ClockRate { get; set; }
public string Description { get; set; }
public string EncoderDescription { get; set; }
public bool IsUsable { get; set; }
public bool IsVbr { get; set; }
public string MimeType { get; set; }
public int NormalBitrate { get; set; }
public int Number { get; set; }
public string RecvFmtp { get; set; }
public string SendFmtp { get; set; }
public int Type { get; set; }
private bool _isEnabled;
public bool IsEnabled
{
get { return _isEnabled; }
set { Set(ref _isEnabled, value); }
}
}
public class AudioCodecsViewModel : ViewModelBase
{
public AudioCodecsViewModel(ICommonServices commonServices) : base(commonServices)
{
ReadLinphoneCodecs();
}
public ICommand SaveAudioCodecsCommand => new RelayCommand(OnSaveAudioCodecs);
private IEnumerable<PayloadType> _audioPayloadTypes;
public List<AudioCodec> _audioCodec = new List<AudioCodec>();
private void ReadLinphoneCodecs()
{
_audioPayloadTypes = LinphoneManager.Instance.Core.AudioPayloadTypes;
foreach (var row in _audioPayloadTypes)
{
AudioCodec codec = new AudioCodec();
codec.Channels = row.Channels;
codec.ClockRate = row.ClockRate;
codec.Description = row.Description;
codec.EncoderDescription = row.EncoderDescription;
codec.IsVbr = row.IsVbr;
codec.MimeType = row.MimeType;
codec.NormalBitrate = row.NormalBitrate;
codec.Number = row.Number;
codec.RecvFmtp = row.RecvFmtp;
codec.SendFmtp = row.SendFmtp;
codec.Type = row.Type;
codec.IsEnabled = row.Enabled();
//codec.IsEnabled = true;
if (codec.SendFmtp == null) codec.SendFmtp = "";
if (codec.RecvFmtp == null) codec.RecvFmtp = "";
_audioCodec.Add(codec);
}
}
private void OnSaveAudioCodecs()
{
int i = 0;
_audioPayloadTypes = LinphoneManager.Instance.Core.AudioPayloadTypes;
foreach (var row in _audioPayloadTypes)
{
row.Enable(_audioCodec[i++].IsEnabled);
}
}
}
}
|
using UnityEngine;
using System.Collections;
public interface I_GameState {
bool Update(bool firstFrameOfState); //Is called for each frame. Returns true if the state finished and the next gameState should be started (isReady)
//NOTE: returning true doesn't guarantee, that the gameState is really changed - maybe the server needs to wait for other players too
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem173 : ProblemBase {
public override string ProblemName {
get { return "173: Using up to one million tiles how many different 'hollow' square laminae can be formed?"; }
}
public override string GetAnswer() {
return Solve(1000000).ToString();
}
public ulong Solve(ulong max) {
ulong sum = 0;
for (ulong num = 1; num <= max / 4; num++) {
ulong subSum = (num + 1) * 4;
ulong nextNum = subSum;
while (subSum <= max) {
sum += 1;
nextNum = ((nextNum / 4) + 2) * 4;
subSum += nextNum;
}
}
return sum;
}
}
}
|
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Collections;
using System.Collections.Generic;
class Player
{
static void Main(string[] args)
{
// game loop
while (true)
{
/*two variables, one to set the highest mountain (maxHeight)
the other one to set the index of such mountain*/
int maxHeight = 0, mountain = 0;
for (int i = 0; i < 8; i++)
{
//each input value gives you the height of a mountain
int mountainH = int.Parse(Console.ReadLine()); // represents the height of one mountain.
/*if a mountain is higher than maxHeight,
it becomes the highest mountain and we get
it's index*/
if(mountainH > maxHeight){
maxHeight = mountainH;
mountain = i;
}
}
//return maxHeight to 0 in case another pass is neeeded
maxHeight = 0;
//print the index (mountain) capture in the for loop.
Console.WriteLine(mountain);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BoulderInteract : MonoBehaviour {
//Author: Alecksandar Jackowicz
//When activated the boulder will launch according to an arc.
//If it hits the boss' shell then it will cause damage and spawn a particle effect
public Rigidbody boulder;
public int boldDmg = 50;
public bool isHit = false;
public float launchForce = 200f;
//Health code Variable
// Use this for initialization
void Start () {
boulder = this.GetComponent<Rigidbody> ();;
}
// Update is called once per frame
/*
void Update () {
if (Input.GetKeyDown (KeyCode.O)) {
Launch ();
}
}
*/
void OnCollisionEnter(Collision other){
if(other.gameObject.CompareTag("Genbu")){
//FakeGenbu fakeGen = other.transform.GetComponent<FakeGenbu>();
//fakeGen.fakeHealth -= boldDmg;
Genbu_AI genAi = other.transform.GetComponent<Genbu_AI>();
genAi.mainHealth -= boldDmg;
Destroy (this.gameObject);
}
}
public void Launch(){
boulder.constraints = RigidbodyConstraints.None;
boulder.velocity += transform.forward * launchForce;
}
//Health damage function
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Text;
using System.Threading.Tasks;
using Windows.ApplicationModel.AppService;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace DesktopBridge.UWP
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
if(App.Connection!=null)
{
messages.Items.Add("Sending: "+messageToSend.Text);
ValueSet valueSet = new ValueSet();
valueSet.Add("request", messageToSend.Text);
if (App.Connection != null)
{
AppServiceResponse response = await App.Connection.SendMessageAsync(valueSet);
foreach(var item in response.Message)
{
messages.Items.Add($"Received {item.Key}: {item.Value}");
}
}
}
else
{
MessageDialog dialog = new MessageDialog("The background Win32 AppService doesn't seem to run. Please see the other error messages.");
await dialog.ShowAsync();
}
}
}
}
|
using System;
using UnityEngine;
public class Rupee : MonoBehaviour
{
[SerializeField]
internal SpriteSheet mSpriteSheet;
public int mValue { get; private set; }
public void Start()
{
tag = Collision.TAG;
var newSprite = gameObject.AddComponent<Sprite>();
newSprite.mSpriteSheet = mSpriteSheet;
newSprite.mIsAnimated = true;
newSprite.mAnimWait = 45;
newSprite.mFrameSkip = 2;
mValue = UnityEngine.Random.Range(0, 3) + 1;
switch (mValue - 1)
{
case 0:
newSprite.mSpriteName = "G";
break;
case 1:
newSprite.mSpriteName = "B";
break;
case 2:
newSprite.mSpriteName = "R";
break;
}
}
} |
using BAH.BOS.WebAPI.ServiceStub.Permission.Dto;
using Kingdee.BOS.ServiceFacade.KDServiceFx;
using Kingdee.BOS.ServiceHelper;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BAH.BOS.WebAPI.ServiceStub.Permission.Method
{
public class GetUserOrg : KDBaseService
{
public GetUserOrg(KDServiceContext context) : base(context)
{
}
public ServiceResult Invoke()
{
var result = new ServiceResult<List<UserOrgInfoOutput>>();
try
{
var infos = PermissionServiceHelper.GetUserOrg(this.KDContext.Session.AppContext);
result.Code = (int)ResultCode.Success;
result.Message = ResultCode.Success.ToString();
result.Data = infos.Select(db => new UserOrgInfoOutput
{
Id = db.Id,
Number = db.Number,
Name = db.Name
}).ToList();
}
catch (Exception ex)
{
result.Code = (int)ResultCode.Fail;
result.Message = ex.Message;
}
return result;
}
}//end class
}//end namespace
|
using System;
namespace _1_Polymorphism_Basics
{
public class Animal
{
public virtual string talk()
{
return "Animal";
}
}
public class Cat : Animal
{
public override string talk()
{
return "Meow";
}
}
public class Dog : Animal
{
public override string talk()
{
return "Woof";
}
}
class Program
{
static void Main(string[] args)
{
Animal cat = new Cat();
Animal dog = new Dog();
Console.WriteLine(cat.talk());
Console.WriteLine(dog.talk());
// cat and dog are both declared as Animal types,
// but instead of the Animal talk() method, their
// respective overriden talk() methods get invoked
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Threading;
/*
* External dependencies, OAuth 2.0 support, and core client libraries are at:
* https://code.google.com/p/google-api-dotnet-client/wiki/APIs#YouTube_Data_API
* Also see the Samples.zip file for the Google.Apis.Samples.Helper classes at:
* https://code.google.com/p/google-api-dotnet-client/wiki/Downloads
*/
using DotNetOpenAuth.OAuth2;
using Google.Apis.Authentication;
using Google.Apis.Authentication.OAuth2;
using Google.Apis.Authentication.OAuth2.DotNetOpenAuth;
using Google.Apis.Samples.Helper;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Youtube.v3;
using Google.Apis.Youtube.v3.Data;
namespace dotnet
{
class upload_video
{
static void Main(string[] args)
{
CommandLine.EnableExceptionHandling();
CommandLine.DisplayGoogleSampleHeader("YouTube Data API: Upload Video");
var credentials = PromptingClientCredentials.EnsureFullClientCredentials();
var provider = new NativeApplicationClient(GoogleAuthenticationServer.Description)
{
ClientIdentifier = credentials.ClientId,
ClientSecret = credentials.ClientSecret
};
var auth = new OAuth2Authenticator<NativeApplicationClient>(provider, GetAuthorization);
var youtube = new YoutubeService(new BaseClientService.Initializer()
{
Authenticator = auth
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = CommandLine.RequestUserInput<string>("Video title");
video.Snippet.Description = CommandLine.RequestUserInput<string>("Video description");
video.Snippet.Tags = new string[] { "tag1", "tag2" };
// See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Snippet.CategoryId = "22";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = CommandLine.RequestUserInput<string>("Video privacy (public, private, or unlisted)");
var filePath = CommandLine.RequestUserInput<string>("Path to local video file");
var fileStream = new FileStream(filePath, FileMode.Open);
var videosInsertRequest = youtube.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
var uploadThread = new Thread(() => videosInsertRequest.Upload());
uploadThread.Start();
uploadThread.Join();
CommandLine.PressAnyKeyToExit();
}
static void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress obj)
{
CommandLine.WriteLine(String.Format("{0} bytes sent.", obj.BytesSent));
}
static void videosInsertRequest_ResponseReceived(Video obj)
{
CommandLine.WriteLine(String.Format("Video id {0} was successfully uploaded.", obj.Id));
}
private static IAuthorizationState GetAuthorization(NativeApplicationClient client)
{
var storage = MethodBase.GetCurrentMethod().DeclaringType.ToString();
var key = "storage_key";
IAuthorizationState state = AuthorizationMgr.GetCachedRefreshToken(storage, key);
if (state != null)
{
client.RefreshToken(state);
}
else
{
state = AuthorizationMgr.RequestNativeAuthorization(client, YoutubeService.Scopes.YoutubeUpload.GetStringValue());
AuthorizationMgr.SetCachedRefreshToken(storage, key, state);
}
return state;
}
}
}
|
using Iris.Infrastructure.Models;
using NUnit.Framework;
namespace Iris.Core.Tests
{
public class SetMousePositionTests
{
[Test]
public void ATestyTest()
{
MousePosition postion = new MousePosition();
postion.X = 10;
postion.Y = 10;
IrisCore.MouseService.SetMousePosition(postion);
}
}
}
|
using FluentMigrator;
namespace Profiling2.Migrations.Seeds
{
[Migration(201301231052)]
public class SCR_seeds : Migration
{
public override void Down()
{
}
public override void Up()
{
Execute.EmbeddedScript("201301231052_SCR_seeds.sql");
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using MinistryPlatform.Translation.Models.DTO;
using MinistryPlatform.Translation.Repositories.Interfaces;
using SignInCheckIn.Models.DTO;
using SignInCheckIn.Services.Interfaces;
namespace SignInCheckIn.Services
{
public class SiteService : ISiteService
{
private readonly ISiteRepository _siteRepository;
public SiteService(ISiteRepository siteRepository)
{
_siteRepository = siteRepository;
}
public List<CongregationDto> GetAll()
{
var congregationDtos = _siteRepository.GetAll();
return Mapper.Map<List<MpCongregationDto>, List<CongregationDto>>(congregationDtos);
}
}
} |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class RoomManager : MonoBehaviour {
//public Text roomNumber;
//public Text roomHost;
public ScrollRect scrollView;
public GameObject scrollContent;
public GameObject row;
// Use this for initialization
void Start () {
for (int i = 1; i < 20; i++)
{
generateRow(i);
Debug.Log("row "+i+"generated" );
}
scrollView.verticalNormalizedPosition = 1;
}
public void updateTable()
{
var roomsData = new Dictionary<int,string>();
roomsData = getRooms();
foreach (KeyValuePair<int, string> row in roomsData)
{
//Printing data to table.
Console.WriteLine("Key = {0}, Value = {1}", row.Key, row.Value);
}
}
Dictionary<int, string> getRooms()
{
//Get Rooms from database
return new Dictionary<int, string>();
}
void generateRow(int itemNumber)
{
GameObject scrollItemObj = Instantiate(row);
scrollItemObj.transform.SetParent(scrollContent.transform, false);
scrollItemObj.transform.Find("Room#Txt").gameObject.GetComponent<Text>().text = itemNumber.ToString();
}
}
|
namespace IronAHK.Scripting
{
partial class Parser
{
internal const string ScopeVar = ".";
internal const string VarProperty = "Vars";
private int internalID;
private string InternalID
{
get
{
return "e" + internalID++;
}
}
private string Scope
{
get
{
foreach (var block in blocks)
{
if (block.Kind == CodeBlock.BlockKind.Function)
return block.Method ?? mainScope;
}
return mainScope;
}
}
}
} |
using Quasar.Client.Config;
using Quasar.Client.IO;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Quasar.Client.Setup
{
public class ClientUninstaller : ClientSetupBase
{
public void Uninstall()
{
if (Settings.STARTUP)
{
var clientStartup = new ClientStartup();
clientStartup.RemoveFromStartup(Settings.STARTUPKEY);
}
if (Settings.ENABLELOGGER && Directory.Exists(Settings.LOGSPATH))
{
// this must match the keylogger log files
Regex reg = new Regex(@"^\d{4}\-(0[1-9]|1[012])\-(0[1-9]|[12][0-9]|3[01])$");
foreach (var logFile in Directory.GetFiles(Settings.LOGSPATH, "*", SearchOption.TopDirectoryOnly)
.Where(path => reg.IsMatch(Path.GetFileName(path))).ToList())
{
try
{
File.Delete(logFile);
}
catch (Exception)
{
// no important exception
}
}
}
string batchFile = BatchFile.CreateUninstallBatch(Application.ExecutablePath);
ProcessStartInfo startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
UseShellExecute = true,
FileName = batchFile
};
Process.Start(startInfo);
}
}
}
|
using Bolt;
using BuilderCore;
using ChampionsOfForest.Enemies;
using System.Collections;
using TheForest.Utils;
using UnityEngine;
namespace ChampionsOfForest.Effects
{
public class MagicArrow : MonoBehaviour
{
private static Material material;
public static void Create(Vector3 pos, Vector3 dir, float Damage, string CasterID, float debuffDuration, bool doubleSlow, bool dmgdebuff)
{
MagicArrow a = CreateEffect(pos, dir,dmgdebuff,debuffDuration);
BoxCollider col = a.gameObject.AddComponent<BoxCollider>();
col.isTrigger = true;
col.size = new Vector3(0.4f, 0.4f, 1.2f);
a.Damage = Damage;
a.casterID = CasterID;
a.DebuffDuration = debuffDuration;
a.GiveDoubleSlow = doubleSlow;
a.GiveDmgDebuff = dmgdebuff;
}
public static MagicArrow CreateEffect(Vector3 pos, Vector3 dir, bool debuff,float duration)
{
GameObject go = new GameObject("__MagicArrow__");
go.transform.position = pos;
go.transform.rotation = Quaternion.LookRotation(dir);
go.AddComponent<Rigidbody>().isKinematic = true;
if (!ModSettings.IsDedicated)
{
go.AddComponent<MeshFilter>().mesh = Res.ResourceLoader.instance.LoadedMeshes[113];
if (material == null)
{
material = Core.CreateMaterial(new BuildingData() { EmissionColor = new Color(0, 1, 0.287f), Metalic = 1, Smoothness = 1 });
}
go.AddComponent<MeshRenderer>().material = material;
}
MagicArrow a = go.AddComponent<MagicArrow>();
a.GiveDmgDebuff = debuff;
a.DebuffDuration = duration;
var light = go.AddComponent<Light>();
light.shadowStrength = 1;
light.shadows = LightShadows.Hard;
light.type = LightType.Point;
light.range = 18;
light.color = new Color(0.2f, 1f, 0.2f);
light.intensity = 0.6f;
Destroy(go, duration);
return a;
}
public string casterID;
public float Damage;
public float DebuffDuration;
public bool GiveDmgDebuff;
public bool GiveDoubleSlow;
private bool setupComplete = false;
private const float speed = 60;
public IEnumerator Animate()
{
transform.localScale = new Vector3(4, 4, 0);
yield return null;
while (transform.localScale.z < 4)
{
transform.localScale += Vector3.forward * Time.deltaTime / 2;
}
yield return new WaitForSeconds(0.7f);
setupComplete = true;
}
private void Start()
{
setupComplete = false;
StartCoroutine(Animate());
Destroy(gameObject, 7);
}
private void Update()
{
transform.Rotate(transform.forward * 80 * Time.deltaTime, Space.World);
if (setupComplete)
{
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
}
private void OnTriggerEnter(Collider other)
{
if (!setupComplete)
{
}
if (other.gameObject.CompareTag("enemyCollide"))
{
if (!GameSetup.IsMpClient) {
EnemyProgression prog = other.GetComponentInParent<EnemyProgression>();
DamageMath.DamageClamp(Damage, out int d, out int a);
if (prog != null)
{
for (int i = 0; i < a; i++)
{
prog.HitMagic(d);
}
float slowAmount = 0.35f;
if (GiveDoubleSlow)
{
slowAmount *= 2;
}
prog.Slow(41, 1 - slowAmount, DebuffDuration);
if (GiveDmgDebuff)
{
prog.DmgTakenDebuff(41, 1.15f, DebuffDuration);
}
}
else
{
other.SendMessageUpwards("HitMagic", d, SendMessageOptions.DontRequireReceiver);
}
}
}
}
}
}
|
using Enviosbase.Data;
using Enviosbase.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Enviosbase.Business
{
public class PaisBusiness
{
public int Create(PaisModel item)
{
return new PaisDataMapper().Create(item);
}
public void Update(PaisModel item)
{
PaisDataMapper PaisDM = new PaisDataMapper();
PaisDM.Update(item);
}
public List<PaisModel> GetAll()
{
return new PaisDataMapper().GetAll();
}
public PaisModel GetById(int Id)
{
return new PaisDataMapper().GetById(Id);
}
}
}
|
using System;
using UnityEngine;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using SCFramework;
namespace QFramework
{
[QMonoSingletonAttribute("[Tools]/ResMgr")]
public class ResMgr : QMonoSingleton<ResMgr>, IEnumeratorTaskMgr
{
#region 字段
private Dictionary<string, IRes> m_ResDictionary = new Dictionary<string, IRes>();
private List<IRes> m_ResList = new List<IRes>();
[SerializeField]
private int m_CurrentCoroutineCount = 0;
private int m_MaxCoroutineCount = 8;//最快协成大概在6到8之间
private TimeDebugger m_TimeDebugger;
private LinkedList<IEnumeratorTask> m_IEnumeratorTaskStack = new LinkedList<IEnumeratorTask>();
private bool m_IsWorking = true;
//Res 在ResMgr中 删除的问题,ResMgr定时收集列表中的Res然后删除
private bool m_IsResMapDirty = false;
#endregion
public override void OnSingletonInit ()
{
AssetDataTable.Instance.Reset();
List<string> outResult = new List<string>();
FileMgr.Instance.GetFileInInner("asset_bindle_config.bin", outResult);
foreach (string result in outResult) {
Debug.Log (result);
}
for (int i = 0; i < outResult.Count; ++i)
{
AssetDataTable.Instance.LoadFromFile(outResult[i]);
}
AssetDataTable.Instance.SwitchLanguage("cn");
}
public void InitResMgr()
{
Log.i("Init[ResMgr]");
}
#region 属性
public TimeDebugger timeDebugger
{
get
{
if (m_TimeDebugger == null)
{
m_TimeDebugger = new TimeDebugger("#Res");
}
return m_TimeDebugger;
}
}
public void SetResMapDirty()
{
m_IsResMapDirty = true;
}
public void PostIEnumeratorTask(IEnumeratorTask task)
{
if (task == null)
{
return;
}
m_IEnumeratorTaskStack.AddLast(task);
TryStartNextIEnumeratorTask();
}
public IRes GetRes(string name, bool createNew = false)
{
IRes res = null;
if (m_ResDictionary.TryGetValue(name, out res))
{
return res;
}
if (!createNew)
{
return null;
}
res = ResFactory.Create(name);
if (res != null)
{
m_ResDictionary.Add(name, res);
m_ResList.Add(res);
}
return res;
}
public R GetRes<R>(string name) where R : IRes
{
IRes res = null;
if (m_ResDictionary.TryGetValue(name, out res))
{
return (R)res;
}
return default(R);
}
public R GetAsset<R>(string name) where R : UnityEngine.Object
{
IRes res = null;
if (m_ResDictionary.TryGetValue(name, out res))
{
return res.asset as R;
}
return null;
}
#endregion
#region Private Func
private void Update()
{
if (m_IsWorking)
{
if (m_IsResMapDirty)
{
RemoveUnusedRes();
}
}
}
private void RemoveUnusedRes()
{
if (!m_IsResMapDirty)
{
return;
}
m_IsResMapDirty = false;
IRes res = null;
for (int i = m_ResList.Count - 1; i >= 0; --i)
{
res = m_ResList[i];
if (res.RefCount <= 0 && res.resState != eResState.kLoading)
{
if (res.ReleaseRes())
{
m_ResList.RemoveAt(i);
m_ResDictionary.Remove(res.name);
res.Recycle2Cache();
}
}
}
}
private void OnIEnumeratorTaskFinish()
{
--m_CurrentCoroutineCount;
TryStartNextIEnumeratorTask();
}
private void TryStartNextIEnumeratorTask()
{
if (m_IEnumeratorTaskStack.Count == 0)
{
return;
}
if (m_CurrentCoroutineCount >= m_MaxCoroutineCount)
{
return;
}
IEnumeratorTask task = m_IEnumeratorTaskStack.First.Value;
m_IEnumeratorTaskStack.RemoveFirst();
++m_CurrentCoroutineCount;
StartCoroutine(task.StartIEnumeratorTask(OnIEnumeratorTaskFinish));
}
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236
namespace BlendRocksTextInput.Navigation
{
public sealed partial class NavigationControl : UserControl
{
public NavigationControl()
{
this.InitializeComponent();
}
private void NavigateToFlipButton_Tapped(object sender, TappedRoutedEventArgs e)
{
var frame = Window.Current.Content as Frame;
frame.Navigate(typeof(FlipPage));
}
private void NavigateToIconicButton_Tapped(object sender, TappedRoutedEventArgs e)
{
var frame = Window.Current.Content as Frame;
frame.Navigate(typeof(IconicPage));
}
private void NavigateToSlideButton_Tapped(object sender, TappedRoutedEventArgs e)
{
var frame = Window.Current.Content as Frame;
frame.Navigate(typeof(MainPage));
}
private void NavigateToSplitButton_Tapped(object sender, TappedRoutedEventArgs e)
{
var frame = Window.Current.Content as Frame;
frame.Navigate(typeof(SplitPage));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ecommerce.DAO
{
static class connection
{
static string myconstrng = ConfigurationManager.ConnectionStrings["connstrng"].ConnectionString;
public static SqlConnection GetConnection()
{
SqlConnection conn = new SqlConnection(myconstrng);
return conn;
}
}
}
|
using DAL;
using Entity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BUS
{
public class teamBus
{
teamDal db;
public teamBus()
{
db = new teamDal();
}
public List<eTeam> getALlTeam()
{
return db.getALlTeam();
}
public bool CreateTeam(eTeam team)
{
return db.CreateDoiBong(team);
}
}
}
|
namespace Merchello.UkFest.Web.Models.DitFlo
{
using Umbraco.Core.Models;
using Umbraco.Web.Models;
/// <summary>
/// Defines a DitFloViewModel.
/// </summary>
public interface IDitFloViewModel : IRenderModel
{
/// <summary>
/// Gets the current page.
/// </summary>
IPublishedContent CurrentPage { get; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using alg;
/*
* tags: hash
* Time(n), Space(n)
*/
namespace leetcode
{
public class Lc001_Two_Sum
{
public int[] TwoSum(int[] nums, int target)
{
var map = new Dictionary<int, int>();
for (int j, i = 0; i < nums.Length; i++)
{
if (map.TryGetValue(target - nums[i], out j))
return new int[] { j, i };
map[nums[i]] = i;
}
return null;
}
public void Test()
{
var nums = new int[] { 2, 7, 11, 15 };
var exp = new int[] { 0, 1 };
Console.WriteLine(exp.SameSet(TwoSum(nums, 9)));
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
namespace TrafficNavigation
{
public class MI
{
static void Main(string[] args)
{
Console.WriteLine("Choose the problem: \n" +
"1.Problem1 \n" +
"2.Problem2: Mission Impossible");
int problem = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter the weather type:" + "\n" +
"1.Sunny" + "\n" +
"2.Windy" + "\n" +
"3.Rainy" + "\n");
Climate c = (Climate)Convert.ToInt32(Console.ReadLine());
Random r = new Random();
Orbit orbit1 = new Orbit()
{
Craters = 20,
Distance = 18,
TrafficSpeed = GetTrafficSpeed(r),
OrbitName = "Orbit1",
Destination = "Hallithiran"
};
Orbit orbit2 = new Orbit()
{
Craters = 10,
Distance = 20,
TrafficSpeed = GetTrafficSpeed(r),
OrbitName = "Orbit2",
Destination = "Hallithiran"
};
Orbit orbit3 = new Orbit()
{
Craters = 15,
Distance = 30,
TrafficSpeed = GetTrafficSpeed(r),
OrbitName = "Orbit3",
Destination = "RKPuram"
};
Orbit orbit4 = new Orbit()
{
Craters = 18,
Distance = 15,
TrafficSpeed = GetTrafficSpeed(r),
OrbitName = "Orbit4",
Destination = "Hallithiran"
};
Orbit[] orbitProblem1 = new Orbit[] { orbit1, orbit2 };
Orbit[] orbitProblem2 = new Orbit[] { orbit1, orbit2, orbit3, orbit4 };
List<CorrectOrbit> orbits = new List<CorrectOrbit>();
if (problem == 1)
{
orbits = OrbitGenerator.GenerateCorrectRoute(orbitProblem1, c, true);
}
else
{
orbits = OrbitGenerator.GenerateCorrectRoute(orbitProblem2, c, false);
orbits.First().Destination = "Hallithiran";
orbits[1].Destination = "RKPuram";
}
foreach (var item in orbits)
{
Console.WriteLine("The Shortest time taken to " + item.Destination + " is " + (item.TimeTaken * 60) +
" minutes via " + item.Orbit.ToString() + " using " + item.TypeofVehicle.ToString()
+ " with the current traffic being " + orbitProblem2.First(o => o.OrbitName == item.Orbit).TrafficSpeed);
}
Console.Read();
}
private static int GetTrafficSpeed(Random r)
{
return r.Next(5, 25);
}
}
}
|
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using MovieWebSite.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace MovieWebSite.Controllers
{
public class LogController : Controller
{
Context context = new Context();
[HttpGet]
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(AppUser appUser)
{
var datavalue = context.AppUser.FirstOrDefault(x => x.UserName == appUser.UserName && x.Password == appUser.Password);
if (datavalue != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name,appUser.UserName)
};
var useridentity = new ClaimsIdentity(claims, "Log");
ClaimsPrincipal principal = new ClaimsPrincipal(useridentity);
await HttpContext.SignInAsync(principal);
return RedirectToAction("Index", "Website");
}
return View();
}
public async Task<IActionResult> LogOut()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return RedirectToAction("Index", "Home");
}
}
}
|
namespace ModelTransformationComponent.SystemRules
{
/// <summary>
/// Системная конструкция начала описания параметров
/// <para/>
/// Наследует <see cref="SystemRule"/>
/// </summary>
public class Params_start : SystemRule{
/// <summary>
/// Литерал конструкции начала описания параметров
/// </summary>
public override string Literal=> "/params_start";
}
} |
namespace UniNode
{
public class NodeCanvas
{
}
} |
using Fingo.Auth.DbAccess.Repository.Interfaces;
using Fingo.Auth.Domain.Projects.Factories.Implementation;
using Fingo.Auth.Domain.Projects.Factories.Interfaces;
using Fingo.Auth.Domain.Projects.Implementation;
using Fingo.Auth.Domain.Projects.Interfaces;
using Moq;
using Xunit;
namespace Fingo.Auth.Domain.Projects.Tests.Factories
{
public class GetAllProjectFactoryTest
{
[Fact]
public void GetAllProjectFactory_Returns_Instance_Of_GetAllProjects_Given_By_IGetAllProjects()
{
//Arrange
var projectMock = new Mock<IProjectRepository>();
//Act
IGetAllProjectFactory target = new GetAllProjectFactory(projectMock.Object);
var result = target.Create();
//Assert
Assert.NotNull(result);
Assert.IsType<GetAllProjects>(result);
Assert.IsAssignableFrom<IGetAllProjects>(result);
}
}
} |
using System;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
namespace ServerSocket
{
class ServerSocket
{
public static ManualResetEvent thread = new System.Threading.ManualResetEvent(false);
public static byte[] bytes = new byte[1024];
public static string data;
/// 應用程式的主進入點
static void Main(string[] args)
{
try
{
// 取得本機的識別名稱
string hostname = Dns.GetHostName();
// 取得主機的DNS資訊
IPAddress serverIP = Dns.Resolve(hostname).AddressList[0];
// Port = 80
string Port = "80";
// 建立伺服端TcpListener
TcpListener tcpListener = new TcpListener(serverIP, Int32.Parse(Port));
// 等候用戶端連線
tcpListener.Start();
Console.WriteLine("Server started at: " + serverIP.ToString() + ":" + Port);
while (true)
{
thread.Reset();
// 開始非同步作業嘗試接受用戶端連線
// 並定義所呼叫的Callback方法為AcceptCallback
tcpListener.BeginAcceptTcpClient(new AsyncCallback(AcceptCallback), tcpListener);
thread.WaitOne();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
// 自訂Callback方法
public static void AcceptCallback(IAsyncResult asyncResult)
{
try
{
TcpListener tcpListener = (System.Net.Sockets.TcpListener)asyncResult.AsyncState;
// 以非同步作業接受用戶端連線
TcpClient tcpClient = tcpListener.EndAcceptTcpClient(asyncResult);
// 取得本機相關的網路資訊
IPEndPoint serverInfo = (IPEndPoint)tcpListener.LocalEndpoint;
// 以Client屬性取得用戶端之Socket物件
Socket clientSocket = tcpClient.Client;
// 取得連線用戶端相關的網路連線資訊
IPEndPoint clientInfo = (IPEndPoint)clientSocket.RemoteEndPoint;
Console.WriteLine("Server: " + serverInfo.Address.ToString() + ":" + serverInfo.Port.ToString());
Console.WriteLine("Client: " + clientInfo.Address.ToString() + ":" + clientInfo.Port.ToString());
// 取得伺服端的輸出入串流
NetworkStream networkStream = tcpClient.GetStream();
// 判斷串流是否支援讀取功能
if (networkStream.CanRead)
{
data = "";
// 開始非同步作業自資料串流中讀取資料
// 並定義所呼叫的Callback方法為ReadCallBack
networkStream.BeginRead(bytes, 0, bytes.Length, new AsyncCallback(ReadCallback), networkStream);
}
else
{
Console.WriteLine("串流不支援讀取功能.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
// 自訂Callback方法
public static void ReadCallback(IAsyncResult asyncResult)
{
try
{
NetworkStream networkStream = (NetworkStream)asyncResult.AsyncState;
// 結束非同步自資料串流中讀取資料
int bytesRead = networkStream.EndRead(asyncResult);
data = String.Concat(data, Encoding.ASCII.GetString(bytes, 0, bytesRead));
// 判斷串流中的資料是否可供讀取
while (networkStream.DataAvailable)
{
// 開始非同步作業自資料串流中讀取資料
// 並定義所呼叫的Callback方法為ReadCallBack
networkStream.BeginRead(bytes, 0, bytes.Length, new AsyncCallback(ReadCallback), networkStream);
}
Console.WriteLine("接收的資料內容: " + "\r\n" + "{0}", data + "\r\n");
// 判斷串流是否支援寫入功能
if (networkStream.CanWrite)
{
// 測試用
string htmlBody = "<html><head><title>Send Test</title></head><body><font size=2 face=Verdana>Sent OK.</font></body></html>";
string htmlHeader = "HTTP/1.0 200 OK" + "\r\n" + "Server: HTTP Server 1.0" + "\r\n" + "Content-Type: text/html" + "\r\n" + "Content-Length: " + htmlBody.Length + "\r\n" + "\r\n";
string htmlContent = htmlHeader + htmlBody;
// 設定傳送資料緩衝區
byte[] msg = Encoding.ASCII.GetBytes(htmlContent);
// 開始非同步作業將資料寫入資料串流中
// 並定義所呼叫的Callback方法為WriteCallBack
networkStream.BeginWrite(msg, 0, msg.Length, new AsyncCallback(WriteCallBack), networkStream);
}
else
{
Console.WriteLine("串流不支援寫入功能.");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
// 自訂Callback方法
public static void WriteCallBack(IAsyncResult asyncResult)
{
try
{
NetworkStream networkStream = (NetworkStream)asyncResult.AsyncState;
// 結束非同步將資料寫入資料串流中
networkStream.EndWrite(asyncResult);
// 關閉串流
networkStream.Close();
thread.Set();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace.ToString());
}
}
}
} |
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using NHibernate.Envers.Configuration.Attributes;
using Profiling2.Domain.Prf.Sources;
using SharpArch.Domain.DomainModel;
namespace Profiling2.Domain.Prf.Events
{
public class EventSource : Entity
{
[Audited]
public virtual Event Event { get; set; }
[Audited]
public virtual Source Source { get; set; }
[Audited(TargetAuditMode = RelationTargetAuditMode.NotAudited)]
public virtual Reliability Reliability { get; set; }
[Audited]
public virtual string Commentary { get; set; }
[Audited]
public virtual bool Archive { get; set; }
[Audited]
public virtual string Notes { get; set; }
protected readonly string CASE_CODE_REGEX = @"DH[A-Z]{3}[0-9]+";
public virtual bool HasCaseCode()
{
Regex regex = new Regex(CASE_CODE_REGEX);
return (!string.IsNullOrEmpty(this.Commentary) && regex.IsMatch(this.Commentary))
|| (!string.IsNullOrEmpty(this.Notes) && regex.IsMatch(this.Notes));
}
public virtual IList<string> GetCaseCodes()
{
if (this.HasCaseCode())
{
IList<string> codes = new List<string>();
Regex regex = new Regex(CASE_CODE_REGEX);
if (!string.IsNullOrEmpty(this.Commentary))
foreach (Match match in regex.Matches(this.Commentary))
codes.Add(match.Value);
if (!string.IsNullOrEmpty(this.Notes))
foreach (Match match in regex.Matches(this.Notes))
codes.Add(match.Value);
return codes.Distinct().ToList();
}
return null;
}
public override string ToString()
{
return (this.Event != null ? "Event(ID=" + this.Event.Id.ToString() + ")" : string.Empty)
+ (this.Source != null ? " is linked with Source(ID=" + this.Source.Id.ToString() + ")" : string.Empty);
}
public virtual object ToJSON(SourceDTO dto)
{
return new
{
Id = this.Id,
EventId = this.Event.Id,
Source = dto != null ? new
{
Id = dto.SourceID,
Name = dto.SourceName,
Archive = dto.Archive,
IsRestricted = dto.IsRestricted
} : null,
Reliability = this.Reliability != null ? this.Reliability.ToJSON() : null,
Commentary = this.Commentary,
Notes = this.Notes
};
}
}
}
|
using System.Collections.Generic;
namespace Codility
{
public class CoveringPrefixStrategy2 : ICoveringPrefixStrategy
{
public int Find(int[] A)
{
var numbersCovered = new List<int>();
var indexOfLatestNewNumber = 0;
for (var i = 0; i < A.Length; i++)
{
var currentNumber = A[i];
if (!numbersCovered.Contains(currentNumber))
{
numbersCovered.Add(currentNumber);
indexOfLatestNewNumber = i;
}
}
return indexOfLatestNewNumber;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UFIDA.U9.SM.Ship;
using UFSoft.UBF.PL;
using UFSoft.UBF.Business;
using UFIDA.U9.Base.FlexField.ValueSet;
namespace U9.VOB.Cus.HBHTianRiSheng.BEPlugIn
{
public class Ship_AfterUpdated: UFSoft.UBF.Eventing.IEventSubscriber
{
//private const string Const_DeliveryTypeCode = "Z06";
public void Notify(params object[] args)
{
if (args == null || args.Length == 0 || !(args[0] is UFSoft.UBF.Business.EntityEvent))
{
return;
}
UFSoft.UBF.Business.BusinessEntity.EntityKey key = ((UFSoft.UBF.Business.EntityEvent)args[0]).EntityKey;
if (key != null)
{
Ship entity = key.GetEntity() as Ship;
if (entity != null
&& entity.OriginalData != null
)
{
bool isApprove = false;
bool isUnApprove = false;
if (entity.Status == ShipStateEnum.Approved
&& entity.OriginalData.Status != ShipStateEnum.Approved
)
{
isApprove = true;
}
else if(entity.Status != ShipStateEnum.Approved
&& entity.OriginalData.Status == ShipStateEnum.Approved
)
{
isUnApprove = true;
}
if (isApprove)
{
CreateFollowService(entity);
}
else if (isUnApprove)
{
DeleteFollowService(entity);
}
}
}
}
private void CreateFollowService(Ship entity)
{
DeleteFollowService(entity);
using (ISession session = Session.Open())
{
FollowService fs = FollowService.Create();
fs.DocumentType = FollowServiceDocType.Finder.Find("DocHeaderSequenceStyle=@SeqStyle"
, new OqlParam((int)UFIDA.U9.Base.Doc.DocHeaderSequenceStyleEnumData.Auto)
);
if (fs.DocumentType == null)
{
throw new BusinessException("没有找到自动编号的 售后任务单单据类型。");
}
fs.SrcDoc = entity;
fs.SrcDocNo = entity.DocNo;
fs.BusinessDate = DateTime.Today;
if (entity.OrderBy != null)
{
fs.CustomerKey = entity.OrderBy.CustomerKey;
}
fs.Address = entity.DescFlexField.PubDescSeg2;
fs.Contracts = entity.DescFlexField.PubDescSeg3;
fs.Phone = entity.DescFlexField.PubDescSeg4;
fs.PayMoney = GetTotalMoney(entity);
// 发运方式
fs.DeliveryType = DefineValue.Finder.Find("ValueSetDef.Code=@SetDefCode and Code=@Code"
, new OqlParam(U9.VOB.Cus.HBHTianRiSheng.HBHHelper.DescFlexFieldHelper.Const_DeliveryTypeCode)
, new OqlParam(entity.DescFlexField.PrivateDescSeg1)
);
fs.DeliveryTime = DateTime.Today;
session.Commit();
}
}
private decimal GetTotalMoney(Ship entity)
{
decimal total = 0;
if (entity != null
&& entity.ShipLines != null
&& entity.ShipLines.Count > 0
)
{
foreach (ShipLine line in entity.ShipLines)
{
if (line != null)
{
total += line.TotalMoneyTC;
}
}
}
return total;
}
private void DeleteFollowService(Ship entity)
{
long shipID = entity.ID;
FollowService.EntityList lstFs = FollowService.Finder.FindAll("SrcDoc=@SrcID"
, new OqlParam(shipID)
);
if (lstFs != null
&& lstFs.Count > 0
)
{
using (ISession session = Session.Open())
{
foreach (FollowService fs in lstFs)
{
if (fs != null)
{
fs.Remove();
}
}
session.Commit();
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using JDWinService.Dal;
using JDWinService.Model;
using JDWinService.Utils;
using Kingdee.K3.API.SDK;
using System.IO;
using System.Net;
using System.Data;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
namespace JDWinService.Services
{
public class JD_OrderListApply_LogService
{
JD_OrderListApply_LogDal dal = new JD_OrderListApply_LogDal();
public void AddOrderEntry(int TaskID, string APIUrl, string APICode, string FileType)
{
dal.AddOrderEntry(TaskID, APIUrl, APICode, FileType);
}
public string AddPOOrderEntry(int TaskID, string APIUrl, string FuncName, string Token, string FileType)
{
return dal.AddPOOrderEntry(TaskID, APIUrl, FuncName, Token, FileType);
}
public DataView GetDistinctList()
{
return dal.GetDistinctList();
}
public void Updateordernum(int TaskID, string ordernum)
{
dal.Updateordernum(TaskID, ordernum);
}
public void UpdateFLinkQty(string SNumber, int ItemID, decimal FQty)
{
dal.UpdateFLinkQty(SNumber, ItemID, FQty);
}
public void Test(string APIUrl, string APICode)
{
ApiEnvironment apiEnv = new ApiEnvironment();
apiEnv.init(APIUrl, APICode);
string loginUrl = APIUrl + "PO/Save?Token=" + apiEnv.Token;
FileStream fs = new FileStream(@"D:\MyPrj\2018_苏州矩度\代码\JDWinService\JDWinService\Json2.txt", FileMode.Open, FileAccess.Read);
//仅 对文本 执行 读写操作
System.Text.Encoding code = System.Text.Encoding.GetEncoding("gb2312");
StreamReader sr = new StreamReader(fs, code);
string Json = sr.ReadToEnd();
new Common().WriteLogs(Common.FileType.采购订单_物料.ToString(), "Test数据:" + Json);
HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, Json, null, null, Encoding.UTF8, null);
Stream resStream = response.GetResponseStream();
StreamReader sr2 = new StreamReader(resStream, Encoding.UTF8);
string htmlCode = sr2.ReadToEnd();//获取返回JSON
new Common().WriteLogs(Common.FileType.采购订单_物料.ToString(), "htmlCode:" + htmlCode);
sr.Close();
fs.Close();
}
public void TestJson()
{
//FileStream fs = new FileStream(@"D:\MyPrj\2018_苏州矩度\代码\JDWinService\JDWinService\Json.txt", FileMode.Open, FileAccess.Read);
////仅 对文本 执行 读写操作
//System.Text.Encoding code = System.Text.Encoding.GetEncoding("gb2312");
//StreamReader sr = new StreamReader(fs, code);
//string Json = sr.ReadToEnd();
//JObject jobj = JObject.Parse(Json);
//string aaa ="{\"Page1\":"+ jobj["Data"]["Page1"].ToString().TrimStart('[').TrimEnd(']') + "}" ;
//Json_POOrder_Head model = JsonConvert.DeserializeObject<Json_POOrder_Head>(aaa);
//new Common().WriteLogs(Common.FileType.采购订单_物料.ToString(), "FStatus:" + model.Page1.FStatus);
K3JsonHelper helper = new K3JsonHelper();
//Json_POOrder_Head model = helper.GetPageMol<Json_POOrder_Head>(11111,APIUrl,"PO",T)
}
}
}
|
using System.Web.Mvc;
namespace com.Sconit.Web.Controllers
{
public class ExceptionHandlerController : Controller
{
//
// GET: /ExceptionHandler/
public ActionResult Error()
{
return View();
}
public ActionResult Unauthorized()
{
return View();
}
public ActionResult ObjectNotFound()
{
return View();
}
}
}
|
using EmberKernel.Plugins.Components;
using EmberKernel.Plugins.Models;
using EmberKernel.Services.EventBus.Handlers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace EmberMemory.Listener
{
public interface IProcessListener : IComponent, IEventHandler<EmberInitializedEvent>
{
ValueTask SearchProcessAsync(CancellationToken token);
ValueTask EnsureProcessLifetime(Process process, CancellationToken token);
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using p2_shop.Models;
namespace p2_shop.Controllers
{
public class Tip_ProizvodaController : Controller
{
private ShopingEntities db = new ShopingEntities();
// GET: Tip_Proizvoda
public ActionResult Index()
{
return View(db.Tip_Proizvodas.ToList());
}
// GET: Tip_Proizvoda/Details/5
public ActionResult Details(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tip_Proizvoda tip_Proizvoda = db.Tip_Proizvodas.Find(id);
if (tip_Proizvoda == null)
{
return HttpNotFound();
}
return View(tip_Proizvoda);
}
// GET: Tip_Proizvoda/Create
public ActionResult Create()
{
ViewBag.FK_Grupa_tipa_proizvoda = new SelectList(db.Grupa_tipa_proizvodas, "Grupa_tipa_proizvoda_ID", "Naziv_grupe_tipa_proizvoda");
return View();
}
// POST: Tip_Proizvoda/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Tip_Proizvoda_ID,Naziv_Tipa,FK_Grupa_tipa_proizvoda")] Tip_Proizvoda tip_Proizvoda)
{
if (ModelState.IsValid)
{
db.Tip_Proizvodas.Add(tip_Proizvoda);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FK_Grupa_tipa_proizvoda = new SelectList(db.Grupa_tipa_proizvodas, "Grupa_tipa_proizvoda_ID", "Naziv_grupe_tipa_proizvoda", tip_Proizvoda.FK_Grupa_tipa_proizvoda);
return View(tip_Proizvoda);
}
// GET: Tip_Proizvoda/Edit/5
public ActionResult Edit(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tip_Proizvoda tip_Proizvoda = db.Tip_Proizvodas.Find(id);
if (tip_Proizvoda == null)
{
return HttpNotFound();
}
ViewBag.FK_Grupa_tipa_proizvoda = new SelectList(db.Grupa_tipa_proizvodas, "Grupa_tipa_proizvoda_ID", "Naziv_grupe_tipa_proizvoda", tip_Proizvoda.FK_Grupa_tipa_proizvoda);
return View(tip_Proizvoda);
}
// POST: Tip_Proizvoda/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Tip_Proizvoda_ID,Naziv_Tipa,FK_Grupa_Tipa_Proizvoda")] Tip_Proizvoda tip_Proizvoda)
{
if (ModelState.IsValid)
{
db.Entry(tip_Proizvoda).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.FK_Grupa_tipa_proizvoda = new SelectList(db.Grupa_tipa_proizvodas, "Grupa_tipa_proizvoda_ID", "Naziv_grupe_tipa_proizvoda", tip_Proizvoda.FK_Grupa_tipa_proizvoda);
return View(tip_Proizvoda);
}
// GET: Tip_Proizvoda/Delete/5
public ActionResult Delete(long? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Tip_Proizvoda tip_Proizvoda = db.Tip_Proizvodas.Find(id);
if (tip_Proizvoda == null)
{
return HttpNotFound();
}
return View(tip_Proizvoda);
}
// POST: Tip_Proizvoda/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(long id)
{
Tip_Proizvoda tip_Proizvoda = db.Tip_Proizvodas.Find(id);
db.Tip_Proizvodas.Remove(tip_Proizvoda);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
public ActionResult Create_Modal()
{
ViewBag.FK_Grupa_tipa_proizvoda = new SelectList(db.Grupa_tipa_proizvodas, "Grupa_tipa_proizvoda_ID", "Naziv_grupe_tipa_proizvoda");
return PartialView();
}
// POST: Tip_Proizvoda/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create_Modal([Bind(Include = "Tip_Proizvoda_ID,Naziv_Tipa,FK_Grupa_tipa_proizvoda")] Tip_Proizvoda tip_Proizvoda)
{
if (ModelState.IsValid)
{
db.Tip_Proizvodas.Add(tip_Proizvoda);
db.SaveChanges();
return RedirectToAction("Create","Proizvodis");
}
ViewBag.FK_Grupa_tipa_proizvoda = new SelectList(db.Grupa_tipa_proizvodas, "Grupa_tipa_proizvoda_ID", "Naziv_grupe_tipa_proizvoda", tip_Proizvoda.FK_Grupa_tipa_proizvoda);
return View(tip_Proizvoda);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EBS.Query.DTO;
using EBS.Query.SyncObject;
using Dapper.DBContext;
using EBS.Domain.Entity;
namespace EBS.Query.Service
{
public class PosSyncQueryService:IPosSyncQuery
{
IQuery _query;
public PosSyncQueryService(IQuery query)
{
_query = query;
}
public IEnumerable<AccountSync> QueryAccountSync()
{
string sql = @"Select Id,UserName,Password,NickName,RoleId,StoreId,Status from Account";
var rows = this._query.FindAll<AccountSync>(sql, null);
return rows;
}
public IEnumerable<StoreSync> QueryStoreSync()
{
string sql = @"Select Id,Code,Name,LicenseCode from Store ";
var rows = this._query.FindAll<StoreSync>(sql, null);
return rows;
}
public IEnumerable<VipCardSync> QueryVipCardSync()
{
string sql = @"SELECT Id,Code,Discount FROM VipCard ";
var rows = this._query.FindAll<VipCardSync>(sql, null);
return rows;
}
public IEnumerable<VipProductSync> QueryVipProductSync()
{
string sql = @"SELECT Id,ProductId,SalePrice FROM VipProduct ";
var rows = this._query.FindAll<VipProductSync>(sql, null);
return rows;
}
IEnumerable<ProductStorePriceSync> IPosSyncQuery.QueryProductStorePriceSync(int storeId)
{
// string sql = @"SELECT Id,StoreId,ProductId,SalePrice FROM ProductStorePrice where StoreId=@StoreId";
string sql = @"SELECT Id,StoreId,ProductId,StoreSalePrice as SalePrice FROM storeinventory where StoreId=@StoreId and StoreSalePrice>0 ";
var rows = this._query.FindAll<ProductStorePriceSync>(sql, new { StoreId = storeId });
return rows;
}
IEnumerable<ProductAreaPriceSync> IPosSyncQuery.QueryProductAreaPriceSync(int storeId)
{
string sql = @"SELECT p.Id,p.AreaId,p.ProductId,p.SalePrice FROM ProductAreaPrice p
left join Store s on p.AreaId = s.AreaId
where s.Id=@StoreId";
var rows = this._query.FindAll<ProductAreaPriceSync>(sql, new { StoreId = storeId });
return rows;
}
public IEnumerable<ProductSync> QueryProductSync(int storeId,string productCodeOrBarCode)
{
string sql = @"SELECT p.Id,p.`Code`,p.`Name`,p.BarCode,p.Specification,p.Unit,p.SalePrice
FROM Product p inner join storeInventory i on p.Id = i.ProductId
where i.storeId=@StoreId ";
if (!string.IsNullOrEmpty(productCodeOrBarCode))
{
sql += string.Format("and (p.Code='{0}' or p.BarCode='{0}')", productCodeOrBarCode);
}
var rows = this._query.FindAll<ProductSync>(sql, new { StoreId = storeId });
return rows;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Task3
{
class CycledDynamicArray<T> : DynamicArray<T>, IEnumerable<T>, IEnumerable, ICloneable
{
public CycledDynamicArray() : base()
{
}
public CycledDynamicArray(int capacity) : base(capacity)
{
}
public CycledDynamicArray(IEnumerable<T> collection) : base(collection)
{
}
public new object Clone()
{
CycledDynamicArray<T> clone = new CycledDynamicArray<T>(dynamicArray);
return clone;
}
public new IEnumerator GetEnumerator()
{
return new CycledDynArrEnum(this);
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return new CycledDynArrEnum(this);
}
public class CycledDynArrEnum : IEnumerator<T>, IEnumerator
{
public T[] array;
int position = -1;
int length;
public CycledDynArrEnum(CycledDynamicArray<T> arr)
{
array = arr.dynamicArray;
length = arr.Length;
}
public T Current
{
get
{
try
{
return array[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
object IEnumerator.Current
{
get => Current;
}
public void Dispose()
{
}
public bool MoveNext()
{
position++;
if (position == length)
{
Reset();
}
return true;
}
public void Reset()
{
position = 0;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BusinessLayer
{
public class FixedAssetObject
{
public string AssetRegisterId { get; set; }
public string MajorCategory { get; set; }
public string MinorCategory { get; set; }
public string AssetNo { get; set; }
public string BarcodeNo { get; set; }
public string SerialNo { get; set; }
public string AssetDesc { get; set; }
public string ModelNo { get; set; }
public string Manufacturer { get; set; }
public string PoNo { get; set; }
public string PoLineNo { get; set; }
public string InvoiceNo { get; set; }
public string VendorName { get; set; }
public string OwnedOrLease { get; set; }
public string NewOrUsed { get; set; }
public string InUse { get; set; }
public string AssetType { get; set; }
public string DatePlacedInService { get; set; }
public string YearPlacedInService { get; set; }
public string ProrateDate { get; set; }
public string Depreciate { get; set; }
public string OriginalCost { get; set; }
public string RecoverableCost { get; set; }
public string CurrentCost { get; set; }
public string AccumulatedDepreciation { get; set; }
public string YearToDateDepreciation { get; set; }
public string NetBookValue { get; set; }
public string DepreciationMethod { get; set; }
public string LifeInMonths { get; set; }
public string Status { get; set; }
public string RetirementType { get; set; }
public string RetirementDate { get; set; }
public string RetirementAmount { get; set; }
public string RetirementComments { get; set; }
public string WarrantyStartDate { get; set; }
public string WarrantyEndDate { get; set; }
public string ChassisNo { get; set; }
public int NoOfUnits { get; set; }
public string EmployeeNo { get; set; }
public string EmployeeName { get; set; }
public string Username { get; set; }
public string CountryCode { get; set; }
public string City { get; set; }
public string BudgetCentre { get; set; }
public string PhysicalLocation { get; set; }
}
}
|
namespace Models{
public class MovieData{
public string Title {get; set;}
public int Year {get; set;}
}
} |
#version 430
layout(local_size_x = 1024) in;
layout(binding = 0, rg32f) uniform image2D prefixSumFlow;
uniform uint quadListCount;
layout(std430, binding = 0) buffer quadlistBuf
{
vec4 quadlist [];
};
layout(std430, binding = 1) buffer quadlistMeanTempBuf
{
vec2 outputMeanTemp [];
};
subroutine void launchSubroutine(in uint index, in vec2 xSum, in float quadSideLength);
subroutine uniform launchSubroutine stdDevSubroutine;
subroutine(launchSubroutine)
void firstPass(in uint index, in vec2 xSum, in float quadSideLength)
{
vec2 xMean = xSum / (quadSideLength * quadSideLength);
if (xSum.x == 0 || xSum.y ==0)
{
outputMeanTemp[index] = vec2(0);
}
else
{
outputMeanTemp[index] = xMean;
}
}
subroutine(launchSubroutine)
void secondPass(in uint index, in vec2 xSum, in float quadSideLength)
{
vec2 stdDev = sqrt(xSum / ((quadSideLength * quadSideLength) - 1)); // sqrt(xSum / ((quadSideLength * quadSideLength) - 1.0));
if (isinf(stdDev.x) || isnan(stdDev.x) || isinf(stdDev.y) || isnan(stdDev.y))
{
outputMeanTemp[index] = vec2(0.0f);
}
else
{
outputMeanTemp[index] = stdDev;
}
}
void main()
{
uint index = gl_GlobalInvocationID.x;
if (index > quadListCount)
{
return;
}
ivec2 pos = ivec2(quadlist[index].x, quadlist[index].y);
//uint xPos = uint(quadlist.x);
//uint yPos = uint(quadlist.y);
uint lod = uint(quadlist[index].z);
float quadSideLength = float(pow(2, lod)); //
float shiftedQSL = quadSideLength - 1.0f;
vec2 origin = vec2(pos * quadSideLength) - 1.0f; //
if (origin.x > 1280 - quadSideLength || origin.y > 720 - quadSideLength)
{
return;
}
//vec2 origin = ((vec2(xPos, yPos) * quadSideLength) + (quadSideLength * 0.5f)); //
// vec2 A, B, C, D;
// for a quad of the prefix sum image where
// A -- B
// - -
// - -
// C -- D
// sum of quad of the original image = A + D - B - C
// Actually the calc is a bit different, we need to go
// A -> A - (1, 1)
// B -> B - (0, 1)
// C -> C - (1, 0)
// If any of these go out of bounds (because we are on the image edge, then return a Zero)
// from the spec Note: Load operations from any texel that is outside of the boundaries of the bound image will return all zeros.
// This is desirable for us
vec2 A = imageLoad(prefixSumFlow, ivec2(origin)).xy;
vec2 B = imageLoad(prefixSumFlow, ivec2(origin.x + quadSideLength, origin.y)).xy;
vec2 C = imageLoad(prefixSumFlow, ivec2(origin.x, origin.y + quadSideLength)).xy;
vec2 D = imageLoad(prefixSumFlow, ivec2(origin.x + quadSideLength, origin.y + quadSideLength)).xy;
vec2 xSum = A + D - B - C;
//vec2 xSum = C + B - D - A;
stdDevSubroutine(index, xSum, quadSideLength);
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
namespace Food_Enforcement.Models
{
public class EF_Models
{
public class Results
{
[Key]
public int Results_ID { get; set; }
public int skip { get; set; }
public int limit { get; set; }
public int total { get; set; }
}
public class Meta
{
[Key]
public int Meta_ID { get; set; }
public string disclaimer { get; set; }
public string terms { get; set; }
public string license { get; set; }
public string last_updated { get; set; }
public Results results { get; set; }
}
public class Openfda
{
[Key]
public int Openfda_ID { get; set; }
}
public class Result
{
[Key]
public int Result_ID { get; set; }
public string country { get; set; }
public string city { get; set; }
public string reason_for_recall { get; set; }
public string address_1 { get; set; }
public string address_2 { get; set; }
public string code_info { get; set; }
public string product_quantity { get; set; }
public string center_classification_date { get; set; }
public string distribution_pattern { get; set; }
public string state { get; set; }
public string product_description { get; set; }
public string report_date { get; set; }
public string classification { get; set; }
public Openfda openfda { get; set; }
public string recall_number { get; set; }
public string recalling_firm { get; set; }
public string initial_firm_notification { get; set; }
public string event_id { get; set; }
public string product_type { get; set; }
public string termination_date { get; set; }
public string more_code_info { get; set; }
public string recall_initiation_date { get; set; }
public string postal_code { get; set; }
public string voluntary_mandated { get; set; }
public string status { get; set; }
}
public class RootObject
{
[Key]
public int RootObject_ID { get; set; }
public Meta meta { get; set; }
public List<Result> results { get; set; }
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace MyDiplom.Controllers
{
public class AlgorithmFindFailureController : Controller
{
///////////////////////////////////////////////////////////
///////////Algorithm_In_Central_Switch_Two_Wire////////////
///////////////////////////////////////////////////////////
/////////////////First_Line=>Arrow_Doesnt_Move/////////////
public IActionResult CentralSwitchTwoWire()
{
return View();
}
public IActionResult ArrowDoesntMove()
{
return View();
}
public IActionResult RedLampIsOnBellDoesntRing()
{
return View();
}
public IActionResult RedLampIsntOnBellDoesntRing()
{
return View();
}
public IActionResult RedLampOnBellRing()
{
return View();
}
public IActionResult YesIsVoltage()
{
return View();
}
public IActionResult NoIsntVoltage()
{
return View();
}
public IActionResult YesFuseIsWorking()
{
return View();
}
public IActionResult NoFuseIsntWorking()
{
return View();
}
public IActionResult ResistEqual23()
{
return View();
}
public IActionResult ResistMoreThen23()
{
return View();
}
////////////Second_Line=>Arrow_makes_small_throw//////////////
public IActionResult ArrowMakesSmallThrow()
{
return View();
}
public IActionResult TwoLineBellRing()
{
return View();
}
public IActionResult TwoLineBellDoesntRing()
{
return View();
}
/////////////Third_Line=>Arrow_2_5secondShowWorkingAmperage////////
public IActionResult Arrow_2_5secondShowWorkingAmperage()
{
return View();
}
public IActionResult ThreeLineBellRing()
{
return View();
}
public IActionResult ThreeLineBellDoesntRing()
{
return View();
}
public IActionResult ThreeLineRelayPK_MK_WithoutAmperage()
{
return View();
}
public IActionResult ThreeLineRelayPK_MK_WithAmperage()
{
return View();
}
public IActionResult ThreeLineRelay_K_WithAmperage()
{
return View();
}
public IActionResult ThreeLineRelay_K_WithoutAmperage()
{
return View();
}
public IActionResult ThreeThreeLineBellRing()
{
return View();
}
public IActionResult ThreeLineLampIsntOnBellRing()
{
return View();
}
public IActionResult ThreeLineLampIsOnBellDoesntRing()
{
return View();
}
public IActionResult ThreeLineLampIsntOnBellDoesntRing()
{
return View();
}
public IActionResult ThreeLineFusesIsntWorking()
{
return View();
}
public IActionResult ThreeLineFusesIsWorking()
{
return View();
}
public IActionResult ThreeLineVoltaheEqual_0_or_Unominal()
{
return View();
}
public IActionResult ThreeLineVoltageEqual_Unominal_and_Uless_()
{
return View();
}
public IActionResult ThreeLineNoRolleDoesntStand()
{
return View();
}
public IActionResult ThreeLineYesRolleDoesStand()
{
return View();
}
///////////////////Fourth_Line=>ArrowConstantlyShowingToqueFriction///////////////////
public IActionResult ArrowConstantlyShowingToqueFriction()
{
return View();
}
public IActionResult FourLineYesItIs()
{
return View();
}
public IActionResult FourLineNoItIsNot()
{
return View();
}
}
} |
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 System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using System.Activities.Expressions;
using System.Data.SqlClient;
namespace first_try
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void StergeClick(object sender, RoutedEventArgs e)
{
const string message = "Doriți să ștergeți toate OP/FV-urile?";
const string caption = "Ștergere OP/FV-uri";
MessageBoxResult result = MessageBox.Show(message, caption,
MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\My stuff\Licență\Baza de date\DateIncarcare.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand comm = new SqlCommand(@"DELETE FROM DateFormIncarcare", conn);
SqlCommand comm2 = new SqlCommand(@"DELETE FROM DateFormIncarcareFV", conn);
conn.Open();
comm.ExecuteNonQuery();
comm2.ExecuteNonQuery();
if(comm.ExecuteNonQuery()!=-1 && comm2.ExecuteNonQuery()!=-1)
{
const string mess = "Datele au fost șterse cu succes";
const string capt = "OP/FV-uri șterse";
MessageBoxButton boxButton = MessageBoxButton.OK;
MessageBoxImage boxImage = MessageBoxImage.Information;
MessageBox.Show(mess, capt, boxButton, boxImage);
}
conn.Close();
NrOrdCmb.Items.Clear();
NrOrdCmbOP.Items.Clear();
}
}
private void LegislatieClick(object sender, RoutedEventArgs e)
{
Fereastra_Legislatie legislatie = new Fereastra_Legislatie();
legislatie.Show();
}
private void Instruct_Click(System.Object sender, System.EventArgs e)
{
Fereastra_Instructiuni instructiuni = new Fereastra_Instructiuni();
instructiuni.Show();
}
private void Qst_Click(object sender, RoutedEventArgs e)
{
string message = "Numărul de ordine se găsește în partea stângă sus a OP/FV-ului.\r\n"
+"Puteți reveni oricând pentru modificări de conținut dacă îl selectați din listă.\r\n"
+"Pentru un OP/FV nou încărcat, nr. de ordine este egal cu numărul de OP/FV-uri încărcate plus unu.";
string title = "Informații";
MessageBox.Show(message, title, MessageBoxButton.OK, MessageBoxImage.Information);
}
private void Incarcare_Click(object sender, RoutedEventArgs e)
{
Fereastra_Tip_Completare_OP incarcare_completare_OP = new Fereastra_Tip_Completare_OP();
Fereastra_Tip_Completare_FV incarcare_completare_FV = new Fereastra_Tip_Completare_FV();
String nr_op_selectat, nr_fv_selectat;
if ((bool)OPRadiobtn.IsChecked)
{
if (NrOrdCmbOP.SelectedIndex > -1)
{
nr_op_selectat = NrOrdCmbOP.SelectedItem.ToString();
Fereastra_Incarcare fereastra_Incarcare = new Fereastra_Incarcare();
fereastra_Incarcare.Show();
while (fereastra_Incarcare.txtNr.Text != nr_op_selectat)
{
fereastra_Incarcare.click_btn_next(sender, e);
}
}
else
{
incarcare_completare_OP.Show();
}
}
else
{
if(NrOrdCmb.SelectedIndex > -1)
{
nr_fv_selectat = NrOrdCmb.SelectedItem.ToString();
Fereastra_Incarcare_FV fereastra_Incarcare_FV = new Fereastra_Incarcare_FV();
fereastra_Incarcare_FV.Show();
while(fereastra_Incarcare_FV.txtNr.Text != nr_fv_selectat)
{
fereastra_Incarcare_FV.click_btn_next(sender, e);
}
}
else
{
incarcare_completare_FV.Show();
}
}
}
private void Window_Closed(object sender, EventArgs e)
{
Application.Current.Shutdown();
}
private void NrOrdCmb_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\My stuff\Licență\Baza de date\DateIncarcare.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand command = new SqlCommand(@"SELECT nr FROM DateFormIncarcareFV", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while(reader.Read())
{
NrOrdCmb.Items.Add(reader[0]).ToString();
}
connection.Close();
}
private void NrOrdCmbOP_Loaded(object sender, RoutedEventArgs e)
{
SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\My stuff\Licență\Baza de date\DateIncarcare.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand command = new SqlCommand(@"SELECT nr FROM DateFormIncarcare", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
NrOrdCmbOP.Items.Add(reader[0]).ToString();
}
connection.Close();
}
private void ListareButton_Click(object sender, RoutedEventArgs e)
{
String nr_op_selectat, nr_fv_selectat;
if ((bool)OPRadiobtn.IsChecked)
{
if (NrOrdCmbOP.SelectedIndex > -1)
{
nr_op_selectat = NrOrdCmbOP.SelectedItem.ToString();
Fereastra_Incarcare fereastra_Incarcare = new Fereastra_Incarcare();
fereastra_Incarcare.Show();
fereastra_Incarcare.WindowState = WindowState.Minimized;
while (fereastra_Incarcare.txtNr.Text != nr_op_selectat)
{
fereastra_Incarcare.click_btn_next(sender, e);
}
fereastra_Incarcare.printare(sender, e);
}
else
{
MessageBox.Show("Alegeți un OP din listă");
}
}
else
{
if (NrOrdCmb.SelectedIndex > -1)
{
nr_fv_selectat = NrOrdCmb.SelectedItem.ToString();
Fereastra_Incarcare_FV fereastra_Incarcare_FV = new Fereastra_Incarcare_FV();
fereastra_Incarcare_FV.Show();
fereastra_Incarcare_FV.WindowState = WindowState.Minimized;
while (fereastra_Incarcare_FV.txtNr.Text != nr_fv_selectat)
{
fereastra_Incarcare_FV.click_btn_next(sender, e);
}
fereastra_Incarcare_FV.printare(sender, e);
}
else
{
MessageBox.Show("Alegeți un FV din listă");
}
}
}
private void FormularFVButton_Click(object sender, RoutedEventArgs e)
{
Fereastra_Incarcare_FV fereastra_Incarcare_FV = new Fereastra_Incarcare_FV();
fereastra_Incarcare_FV.Show();
fereastra_Incarcare_FV.WindowState = WindowState.Minimized;
fereastra_Incarcare_FV.printare(sender, e);
fereastra_Incarcare_FV.Close();
}
private void FormularOPButton_Click(object sender, RoutedEventArgs e)
{
Fereastra_Incarcare fereastra_Incarcare = new Fereastra_Incarcare();
fereastra_Incarcare.Show();
fereastra_Incarcare.WindowState = WindowState.Minimized;
fereastra_Incarcare.printare(sender, e);
fereastra_Incarcare.Close();
}
private void NrOrdCmbOP_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\My stuff\Licență\Baza de date\DateIncarcare.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand command = new SqlCommand(@"SELECT nr FROM DateFormIncarcare", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
NrOrdCmbOP.Items.Add(reader[0]).ToString();
}
connection.Close();
}
private void NrOrdCmb_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
SqlConnection connection = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\My stuff\Licență\Baza de date\DateIncarcare.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand command = new SqlCommand(@"SELECT nr FROM DateFormIncarcare", connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
NrOrdCmbOP.Items.Add(reader[0]).ToString();
}
connection.Close();
}
}
}
|
using Sitecore.Mvc.Pipelines.Response.GetPageRendering;
using Sitecore.Mvc.Presentation;
namespace Sitecore.Mvc.AddCassetteReferences.Processor
{
/// <summary>
/// mvc.BuildPageDefinition pipeline processor to dynamically reference Cassette Bundles
/// </summary>
public class AddCassetteReferences : GetPageRenderingProcessor
{
public override void Process(GetPageRenderingArgs args)
{
ApplyDefaultReferences();
ApplyRenderingSpecificReferences(args);
}
/// <summary>
/// Applies the default references to Cassette bundles.
/// </summary>
protected void ApplyDefaultReferences()
{
/* Example of references that apply to all pages
*
Bundles.Reference("css");
Bundles.Reference("js", "footer");
*/
}
/// <summary>
/// Applies the rendering specific references to Cassette bundles.
/// </summary>
/// <param name="args">The args.</param>
protected void ApplyRenderingSpecificReferences(GetPageRenderingArgs args)
{
foreach (Rendering rendering in args.PageContext.PageDefinition.Renderings)
{
switch (rendering.RenderingItem.ID.ToString())
{
/* Example of adding Bundle references based on the current item having a specific reference
* ItemReference is just a static class to reference ID's of specific items in Sitecore.
*
case ItemReference.SliderPanelRendering:
Bundles.Reference("js/vendor/jquery.flexslider.js", "footer");
Bundles.AddInlineScript("$(document).ready(function() { $('.home-slider').flexslider({ pauseOnHover: true, slideshow: false }); });", "footer");
break;
*/
default:
break;
}
}
}
}
}
|
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using TruckPad.Services.Models;
using Swashbuckle.AspNetCore.Swagger;
using TruckPad.Services.Repository;
namespace TruckPad.Services
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//services.AddCors(option => option.AddPolicy("MyTruckPadPolicy", builder => {
// builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod();
//}));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddDbContext<TruckPadContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("TruckPadDB")));
services.AddScoped<IMotoristaRepository, MotoristaRepository>();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new Info
{
Title = "APITruckPad",
Version = "v1",
Contact = new Contact
{
Name ="Ana Carolina Louverbeck Pandim Alves",
Email ="anapandim@outlook.com",
Url= "https://www.linkedin.com/in/carolinapandimalves/"
},
License = new License
{
Name = "TruckPad",
Url = "https://www.truckpad.com.br/"
}
});
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
app.UseHttpsRedirection();
//app.UseCors("MyTruckPadPolicy");
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "APITruckPad V1");
});
}
}
}
|
namespace SocialNetwork.Core
{
public enum CommandType
{
Post,
Follow,
Timeline,
Wall
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GDS.Entity.Result
{
public class DataGridResultEntity<T>
{
public int TotalRecords { get; set; }
public int DisplayRecords { get; set; }
public IList<T> ResultData { get; set; }
}
}
|
namespace StackOnList
{
interface IStack<T>
{
}
class Stack<T>
{
}
} |
using System;
class StringsAndObjects
{
static void Main()
{
Console.Title = "Strings and Objects";
string hello = "Hello";
string world = "World";
object sbor = hello + " " + world + "!";
string print = (string)sbor;
Console.WriteLine(print);
}
}
|
namespace TestDummies;
public class DummyAnonymousUserFilter : ILogEventFilter
{
public bool IsEnabled(LogEvent logEvent)
{
if (logEvent.Properties.ContainsKey("User"))
{
if (logEvent.Properties["User"] is ScalarValue sv)
{
if (sv.Value is "anonymous")
{
return false;
}
}
}
return true;
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Laoziwubo.Model.Common
{
public class QueryM
{
public int PageNum { get; set; }
public int PageSize { get; set; }
public string OrderBy { get; set; }
public string Where { get; set; }
}
}
|
namespace SOLIDPrinciples.ValidationClass.Example03
{
public class NomeRequerido : IRegraDeValidacao<Cliente>
{
IRegraDeValidacao<Cliente> proximaRegra;
public NomeRequerido(IRegraDeValidacao<Cliente> proximaRegra)
{
this.proximaRegra = proximaRegra;
}
public NomeRequerido() { }
public bool ehValido(Cliente cliente)
{
//regra de validacao de nome.
//Se tiver outras regras, chama o atributo passado no construtor
return true;
}
}
}
|
using Content.Client.Weapons.Ranged.Barrels.Components;
using Content.Shared.Weapons.Ranged;
using Robust.Client.Player;
using Robust.Shared.Containers;
using Robust.Shared.GameObjects;
using Robust.Shared.IoC;
namespace Content.Client.Weapons.Ranged;
public sealed class GunSystem : EntitySystem
{
[Dependency] private readonly IPlayerManager _playerManager = default!;
[Dependency] private readonly SharedContainerSystem _container = default!;
public override void Initialize()
{
base.Initialize();
SubscribeNetworkEvent<MagazineAutoEjectEvent>(OnMagAutoEject);
}
private void OnMagAutoEject(MagazineAutoEjectEvent ev)
{
var player = _playerManager.LocalPlayer?.ControlledEntity;
if (!TryComp(ev.Uid, out ClientMagazineBarrelComponent? mag) ||
!_container.TryGetContainingContainer(ev.Uid, out var container) ||
container.Owner != player) return;
mag.PlayAlarmAnimation();
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace OsuSqliteDatabase.Model
{
public enum OsuGameRuleSet
{
Standard = 0,
Taiko = 1,
Catch = 2,
Mania = 3
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using ConsoleApp1.Entities;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
//abre aplicação
IWebDriver driver = new InternetExplorerDriver(@"C:\Users\donald.barbosa\source\Project\ConsoleApp1\IEDriver");
driver.Navigate().GoToUrl("https://service.e-component.com/kioskdcs/kioskframe.html?platform=kioskole&plugin=dcsws");
Thread.Sleep(4000);
driver.FindElement(By.XPath("//*[@id='outerFr']")).Click();
IWebElement frameset = driver.FindElement(By.XPath("//*[@id='dynamicFrame']"));
driver.SwitchTo().Frame(frameset);
Thread.Sleep(5000);
driver.FindElement(By.XPath("/html/body/div[1]")).Click();
Thread.Sleep(2000);
//Clica no checkin
IWebElement checkin = driver.FindElement(By.XPath("//*[@id='mm_txtCheckin']"));
Thread.Sleep(2000);
if(!checkin.Displayed)
{
Console.WriteLine("Not displayed");
Thread.Sleep(3000);
driver.FindElement(By.XPath("/html/body/div[1]")).Click();
Thread.Sleep(3000);
}
Thread.Sleep(6000);
checkin.Click();
//busca por localizador
IWebElement localizador = driver.FindElement(By.XPath("//*[@id='mm_txtRecordLocator']"));
localizador.Click();
//IWebElement key1 = driver.FindElement(By.XPath("//*[@id='wrap']/div/div/button[1]/span"));
//key1.Click();
//solicita o localizador pelo console
//Console.WriteLine("Localizador: ");
Thread.Sleep(4000);
string loc = "GRSBUB";
Keyboard_Locator key = new Keyboard_Locator();
IWebElement field_localizador = driver.FindElement(By.XPath("//*[@id='btnNextrecordLocator']/div/div"));
Thread.Sleep(4000);
foreach (char charcter in loc.ToUpper())
{
key.Key_loc(driver, charcter);
}
//insere o localizador e busca o localizador
IWebElement Continuar_localizador = driver.FindElement(By.Id("btnNextrecordLocator"));
Continuar_localizador.Click();
//clica em continuar
//só funciona com 1 pax
IWebElement pax_continuar = driver.FindElement(By.Id("btnNextSelectPassenger"));
pax_continuar.Click();
//escolhe o RG e clica para continuar
Thread.Sleep(2000);
IWebElement rg_doc = driver.FindElement(By.Id("btn-identidade-RG"));
rg_doc.Click();
IWebElement docrg_continuar = driver.FindElement(By.Id("btnNextDocumentOptions"));
docrg_continuar.Click();
//Insere RG
Console.WriteLine("RG: ");
string rg = Console.ReadLine();
IWebElement field_numero_documento = driver.FindElement(By.Id("field_numero_documento"));
field_numero_documento.SendKeys(rg);
IWebElement rg_continuar = driver.FindElement(By.Id("btnNextDocumentNumber"));
rg_continuar.Click();
//DOB
//IWebElement bt1 = driver.FindElement(By.CssSelector(".ui-keyboard-button.ui-keyboard-1.ui-state-default.ui-corner-all.btnKeysDateOfBirth"));
//Thread.Sleep(4000);
//bt1.Click();
Console.WriteLine("DOB: ");
string dob = Console.ReadLine();
IWebElement field_data_nascimento = driver.FindElement(By.Id("field_data_nascimento"));
//field_data_nascimento.SendKeys(dob);
IWebElement dob_continuar = driver.FindElement(By.Id("btnNextDateOfBirth"));
//teclado dob
Keyboard_DOB birth = new Keyboard_DOB();
foreach (char charcter in dob)
{
birth.Key_dob(driver, charcter);
}
dob_continuar.Click();
}
}
} |
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using NUnit.Framework;
namespace Testing
{
[TestFixture]
public class BListTests
{
private Random _random = new Random();
[Test]
public void given_empty_blist_when_one_element_is_added_then_blist_count_should_equal_one()
{
var count = 1;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Add(item);
Assert.That(blist.Count, Is.EqualTo(count));
}
[Test]
public void given_empty_blist_when_one_element_is_added_then_blist_indexer_should_return_element()
{
var count = 1;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Add(item);
Assert.That(expected[0], Is.EqualTo(blist[0]));
}
[Test]
public void given_empty_blist_when_one_element_is_added_then_blist_iterator_should_return_element()
{
var count = 1;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Add(item);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_empty_blist_when_one_element_is_inserted_at_zero_index_then_blist_iterator_should_return_element()
{
var count = 1;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Insert(0, item);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void given_empty_blist_when_elements_are_added_individually_then_blist_count_should_equal_number_added()
{
var count = 1024;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Add(item);
Assert.That(blist.Count, Is.EqualTo(count));
}
[Test]
public void given_empty_blist_when_elements_are_added_individually_then_blist_indexer_should_return_elements()
{
var count = 1024;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Add(item);
for (int i = 0; i < count; i++)
{
Assert.That(expected[i], Is.EqualTo(blist[i]));
}
}
[Test]
public void given_empty_blist_when_elements_are_added_individually_then_blist_iterator_should_return_elements()
{
var count = 1024;
var expected = new int[count].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
foreach (var item in expected)
blist.Add(item);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_empty_blist_when_elements_are_inserted_at_zero_index_individually_then_blist_iterator_should_return_elements
()
{
var count = 1024;
var initial = new int[count].Select(_ => _random.Next()).ToArray();
var expected = initial.Reverse().ToArray();
var blist = new BList<int>();
foreach (var item in initial)
blist.Insert(0, item);
Assert.That(blist.Count, Is.EqualTo(count));
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_elements_are_replaced_in_middle_then_blist_iterator_should_return_correct_latest_elements
()
{
var initial = new int[1024].Select(_ => _random.Next()).ToArray();
var replacement = new int[256].Select(_ => _random.Next()).ToArray();
var expected = initial.Take(256).Concat(replacement).Concat(initial.Skip(512)).ToArray();
var blist = new BList<int>();
foreach (var item in initial)
blist.Add(item);
CollectionAssert.AreEqual(initial, blist);
for (int i = 0; i < 256; i++)
blist[256 + i] = replacement[i];
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_elements_are_inserted_in_middle_then_blist_iterator_should_return_correct_latest_elements
()
{
var initial = new int[768].Select(_ => _random.Next()).ToArray();
var inserts = new int[256].Select(_ => _random.Next()).ToArray();
var expected = initial.Take(256).Concat(inserts).Concat(initial.Skip(256)).ToArray();
var blist = new BList<int>();
foreach (var item in initial)
blist.Add(item);
for (int i = 0; i < 256; i++)
blist.Insert(256 + i, inserts[i]);
Assert.That(blist.Count, Is.EqualTo(1024));
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_elements_are_inserted_at_index_zero_then_blist_iterator_should_return_correct_latest_elements
()
{
var initial = new int[512].Select(_ => _random.Next()).ToArray();
var insertzero = new int[256].Select(_ => _random.Next()).ToArray();
var expected = insertzero.Reverse().Concat(initial).ToArray();
var blist = new BList<int>();
foreach (var item in initial)
blist.Add(item);
foreach (var item in insertzero)
blist.Insert(0, item);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_elements_are_removed_by_index_with_zero_index_then_blist_iterator_should_return_correct_elements
()
{
var initial = new int[512].Select(_ => _random.Next()).ToArray();
var expected = initial.Skip(32).ToArray();
var blist = new BList<int>();
foreach (var item in initial)
blist.Add(item);
for (int i = 0; i < 32; i++)
{
blist.RemoveAt(0);
}
Assert.That(blist.Count, Is.EqualTo(480));
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_elements_are_removed_by_element_then_blist_iterator_should_return_correct_elements
()
{
var initial = new int[512].Select(_ => _random.Next()).ToArray();
var expected = initial.Skip(32).ToArray();
var blist = new BList<int>();
foreach (var item in initial)
blist.Add(item);
for (int i = 0; i < 32; i++)
{
blist.Remove(initial[i]);
}
Assert.That(blist.Count, Is.EqualTo(480));
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void given_empty_blist_when_multiple_elements_added_then_blist_iteractor_should_return_elements()
{
var expected = new int[512].Select(_ => _random.Next()).ToArray();
var blist = new BList<int>();
blist.AddRange(expected);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_multiple_elements_inserted_at_zero_then_blist_iteractor_should_return_elements()
{
var initial = new int[256].Select(_ => _random.Next()).ToArray();
var expected = initial.Concat(initial).ToArray();
var blist = new BList<int>();
blist.AddRange(initial);
blist.InsertRange(initial, 0);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void given_existing_blist_when_multiple_elements_replaced_then_blist_iteractor_should_return_elements()
{
var initial = new int[256].Select(_ => _random.Next()).ToArray();
var replace = new int[32].Select(_ => _random.Next()).ToArray();
var expected = initial.Take(32).Concat(replace).Concat(initial.Skip(64)).ToArray();
var blist = new BList<int>();
blist.AddRange(initial);
blist.ReplaceRange(replace, 32);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void
given_existing_blist_when_multiple_elements_replaced_at_index_zero_then_blist_iteractor_should_return_elements
()
{
var initial = new int[256].Select(_ => _random.Next()).ToArray();
var replace = new int[32].Select(_ => _random.Next()).ToArray();
var expected = replace.Concat(initial.Skip(32)).ToArray();
var blist = new BList<int>();
blist.AddRange(initial);
blist.ReplaceRange(replace, 0);
CollectionAssert.AreEqual(expected, blist);
}
[Test]
public void given_blist_when_clear_is_called_then_collectionchanged_raised()
{
var blist = new BList<int>();
blist.AddRange(new int[32].Select(_ => _random.Next()).ToArray());
NotifyCollectionChangedEventArgs args = null;
blist.CollectionChanged += (_, a) => args = a;
blist.Clear();
Assert.That(args, Is.Not.Null);
Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Reset));
}
[Test]
public void given_blist_when_item_removed_then_collectionchanged_raised()
{
var blist = new BList<int>();
var initial = new int[32].Select(_ => _random.Next()).ToArray();
var expected = initial[16];
blist.AddRange(initial);
NotifyCollectionChangedEventArgs args = null;
blist.CollectionChanged += (_, a) => args = a;
blist.RemoveAt(16);
Assert.That(args, Is.Not.Null);
Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Remove));
Assert.That(args.OldStartingIndex, Is.EqualTo(16));
Assert.That(args.OldItems[0], Is.EqualTo(expected));
}
[Test]
public void given_blist_when_item_added_then_collectionchanged_raised()
{
var blist = new BList<int>();
var initial = new int[32].Select(_ => _random.Next()).ToArray();
var expected = _random.Next();
blist.AddRange(initial);
NotifyCollectionChangedEventArgs args = null;
blist.CollectionChanged += (_, a) => args = a;
blist.Insert(16, expected);
Assert.That(args, Is.Not.Null);
Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Add));
Assert.That(args.NewStartingIndex, Is.EqualTo(16));
Assert.That(args.NewItems[0], Is.EqualTo(expected));
}
[Test]
public void given_blist_when_item_replaced_then_collectionchanged_raised()
{
var blist = new BList<int>();
var index = 10;
var initial = new int[32].Select(_ => _random.Next()).ToArray();
var expectedNew = _random.Next();
var expectedOld = initial[index];
blist.AddRange(initial);
NotifyCollectionChangedEventArgs args = null;
blist.CollectionChanged += (_, a) => args = a;
blist[index] = expectedNew;
Assert.That(args, Is.Not.Null);
Assert.That(args.Action, Is.EqualTo(NotifyCollectionChangedAction.Replace));
Assert.That(args.NewStartingIndex, Is.EqualTo(10));
Assert.That(args.OldStartingIndex, Is.EqualTo(10));
Assert.That(args.NewItems[0], Is.EqualTo(expectedNew));
Assert.That(args.OldItems[0], Is.EqualTo(expectedOld));
}
[Test]
public void given_blist_with_one_element_when_two_inserted_at_index_zero_then_3rd_element_should_not_be_null()
{
var blist = new BList<string>();
blist.Add("Foo");
blist.InsertRange(new string[] {"Hello", "World"}, 0);
Assert.That(blist.Count, Is.EqualTo(3));
Assert.That(blist[0], Is.EqualTo("Hello"));
Assert.That(blist[1], Is.EqualTo("World"));
Assert.That(blist[2], Is.EqualTo("Foo"));
}
}
} |
using ReactMusicStore.Core.Data.Context.Interfaces;
namespace ReactMusicStore.Services.Interfaces.Common
{
public interface ITransactionAppService<TContext>
where TContext : IDbContext, new()
{
void BeginTransaction();
void Commit();
}
}
|
using MySql.Data.EntityFramework;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WordTree.Model;
namespace WordTree.Service
{
[DbConfigurationType(typeof(MySqlEFConfiguration))]
public class PlannedWordContext:DbContext
{
public PlannedWordContext():base("PlannedWordDataBase")
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<PlannedWordContext>());
}
public DbSet<PlannedWord> PlannedWords { get; set; }
public DbSet<DictionaryWord> DictionaryWords { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LoadingText : MonoBehaviour
{
private bool loading = true;
void Update()
{
if (loading)
{
StartCoroutine(LoadingTextAnim());
}
}
IEnumerator LoadingTextAnim()
{
loading = false;
gameObject.GetComponent<Text>().text = "Loading";
yield return new WaitForSeconds(0.5f);
gameObject.GetComponent<Text>().text = "Loading.";
yield return new WaitForSeconds(0.5f);
gameObject.GetComponent<Text>().text = "Loading..";
yield return new WaitForSeconds(0.5f);
gameObject.GetComponent<Text>().text = "Loading...";
yield return new WaitForSeconds(0.5f);
loading = true;
}
}
|
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Library;
using Library.Interfaces;
using Library.Model;
using Data;
using App.Service;
using Microsoft.AspNetCore.Authorization;
namespace App.Controllers
{
//[Route("api/[controller]")]
[ApiController]
public class RaceController : ControllerBase
{
private readonly IRaceRepository _raceRepository;
private readonly WebScraperService _webScraperService;
public RaceController(IRaceRepository raceRepository, WebScraperService webScraperService)
{
_raceRepository = raceRepository;
_webScraperService = webScraperService;
}
[AllowAnonymous]
[HttpGet("api/race")]
public async Task<IActionResult> ControllerGetAllRaces()
{
var races = await _raceRepository.GetRaces();
return Ok(races);
}
[AllowAnonymous]
[HttpGet("api/race/id/{raceId}")]
public async Task<IActionResult> ControllerGetRaceById(int raceId)
{
var race = await _raceRepository.GetRaceByID(raceId);
return Ok(race);
}
[AllowAnonymous]
[HttpGet("api/race/title/{raceTitle}")]
public async Task<IActionResult> ControllerGetRacesByTitle(string raceTitle)
{
var race = await _raceRepository.GetRacesByTitle(raceTitle);
return Ok(race);
}
[AllowAnonymous]
[HttpGet("api/race/play/{raceId}")]
public async Task<ContentResult> ControllerPlayRace(int raceId)
{
var race = await _raceRepository.GetRaceByID(raceId);
var page = await _webScraperService.Start(race.StartPage);
return Content(page, "text/html");
}
[AllowAnonymous]
[HttpGet("api/race/play/{raceId}/step")]
public async Task<ContentResult> ControllerPlayRaceStep(int raceId,string current, string step)
{
var race = await _raceRepository.GetRaceByID(raceId);
var page = await _webScraperService.Step(current, step);
if (step == race.EndPage && page != null)
{
return Content("Victory!");
}
return Content(page);
}
[AllowAnonymous]
[HttpPost("api/race")]
public async Task<IActionResult> ControllerAddRace([Required] Race race)
{
await _raceRepository.AddRace(race);
return Ok();
}
/*
// PUT api/<ValuesController>/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/<ValuesController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
*/
}
}
|
using Assets.Scripts.Models.ResourceObjects.CraftingResources;
using System.Collections.Generic;
using Assets.Scripts.Models.ResourceObjects;
namespace Assets.Scripts.Models.Constructions.Wood
{
public class WoodWall : Construction
{
public WoodWall()
{
ConstructionType = ConstructionType.Wall;
LocalizationName = "wood_wall";
Description = "wood_wall_descr";
IconName = "wood_wall_icon";
PrefabPath = "Prefabs/Constructions/Wood/Wall/WoodWall";
PrefabTemplatePath = "Prefabs/Constructions/Wood/Wall/WoodWallTemplate";
CraftRecipe = new List<HolderObject>();
CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(WoodResource), 40));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
using DAL.DAL;
namespace DAL.DataManager
{
public class QuestionManager:MainContext
{
public List<QuestionBE> GetQuestionForCategory(Guid categoryId, bool withVariants)
{
List<QuestionBE> result = null;
result = RaceDataContext.Questions.Where(q => q.CategoryId == categoryId).
Select(q => QuestionToBE(q, GetVariantById(q.RightId), withVariants ?
GetRandomTopVariantsForCategory(categoryId, coutOfVariantsInQuestion, q.RightId) : null)).ToList();
return result;
}
public void AddQuestion(QuestionBE question)
{
RaceDataContext.Questions.InsertOnSubmit(BEtoQuestion(question));
RaceDataContext.SubmitChanges();
}
public QuestionBE GetQuestionById(Guid id)
{
QuestionBE result = RaceDataContext.Questions.Where(q => q.Id == id).Select(q =>
QuestionToBE(q, GetVariantById(q.RightId), null)).First();
return result;
}
public void EditQuestion(QuestionBE question)
{
Question questionToEdit = RaceDataContext.Questions.First(q => q.Id == question.Id);
questionToEdit.RightId = question.RightVariant.Id;
questionToEdit.Question1 = question.Question;
questionToEdit.CategoryId = question.CategoryId;
RaceDataContext.SubmitChanges();
}
public void DeleteQuestion(Guid questionId)
{
RaceDataContext.Questions.DeleteOnSubmit(RaceDataContext.Questions.First(q => q.Id == questionId));
RaceDataContext.SubmitChanges();
}
public List<VariantBE> GetVariantsForCategory(Guid categoryId)
{
List<VariantBE> result = RaceDataContext.Variants.Where(v => v.categoryId == categoryId).
Select(v => VariantToBE(v)).ToList();
return result;
}
public List<VariantBE> GetRandomTopVariantsForCategory(Guid categoryId, int variantCount, Guid rightId)
{
Random rnd = new Random();
List<VariantBE> result = RaceDataContext.Variants.Where(v => v.categoryId == categoryId).AsEnumerable().OrderBy(v=> rnd.Next()).
Take(variantCount).Select(v => VariantToBE(v)).ToList();
return result;
}
public VariantBE GetVariantById(Guid id)
{
VariantBE result = VariantToBE(RaceDataContext.Variants.First(v => v.Id == id));
return result;
}
public void AddVariantToCategory(VariantBE variant)
{
Variant v = BEtoVariant(variant);
RaceDataContext.Variants.InsertOnSubmit(v);
RaceDataContext.SubmitChanges();
}
public void EditVariant(VariantBE variant)
{
Variant variantToEdit = RaceDataContext.Variants.First(v => v.Id == variant.Id);
variantToEdit.Value = variant.Value;
RaceDataContext.SubmitChanges();
}
public void DeleteVariant(Guid variantId)
{
RaceDataContext.Variants.DeleteOnSubmit(RaceDataContext.Variants.First(v => v.Id == variantId));
RaceDataContext.SubmitChanges();
}
}
}
|
namespace gView.Framework.Geometry
{
public interface IMultiPoint : IGeometry, IPointCollection
{
}
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Popups;
using Mfrc522Lib;
namespace ConsoleApp
{
public class Tools
{
public async Task RfidReader()
{
try
{
var mfrc = new Mfrc522();
await mfrc.InitIO();
Debug.WriteLine("InitIO Success");
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(1)); // Saniyelik saysın.
if (mfrc.IsTagPresent())
{
Debug.WriteLine("There is a Tah");
var uid = mfrc.ReadUid();
mfrc.HaltTag();
var dialog = new MessageDialog(uid.ToString()) { Title = "A card has been read" };
dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 });
dialog.Commands.Add(new UICommand { Label = "Cancel", Id = 1 });
var result = await dialog.ShowAsync();
Debug.WriteLine("Success");
if ((int)result.Id == 0)
{
// DO some stuff like sending id to web references
//send id to your db web service..
}
else
{
continue;
//skip your task
}
}
}
}
catch (Exception ex)
{
var dialog = new MessageDialog("An Error has Occured While Reading... Inner Exception is " + ex.Message) { Title = "What Da?" };
var result = await dialog.ShowAsync();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CassandraFinal {
public class Contact {
public Guid ID { get; set; }
public string Name { get; set; }
public List<long> PhoneNumbers { get; set; }
public List<string> Emails { get; set; }
public string Group { get; set; }
// Used by Cassandra driver to populate properties
public Contact() { }
public Contact(string name, List<long> phoneNumbers, List<string> emails, string group) {
ID = Guid.NewGuid();
Name = name;
PhoneNumbers = phoneNumbers;
Emails = emails;
Group = group;
}
public override string ToString() {
string contact = $"ID: {ID}\nName: {Name}Group: {Group}\nPhone numbers:";
foreach (long number in PhoneNumbers) {
contact += $"\n\t{number}";
}
contact += "\nEmails:";
foreach (string email in Emails) {
contact += $"\n\t{email}";
}
return contact;
}
}
} |
using Alabo.Domains.Repositories;
using Alabo.Industry.Offline.Product.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Industry.Offline.Product.Domain.Repositories
{
public interface IMerchantProductRepository : IRepository<MerchantProduct, ObjectId>
{
}
} |
using System;
class ComparingFloatingPointNumbers
{
static void Main()
{
double a = double.Parse(Console.ReadLine());
double b = double.Parse(Console.ReadLine());
double eps = 0.000001;
double difference = Math.Abs(a - b);
Console.WriteLine((difference < eps) ? "true" : "false");
}
}
|
using BusinessLogic.Service.ShoppingWeb;
using DataAccess.Domain;
using DataAccess.ShoppingWebDataBase;
using ITSWeb.Controllers.Base;
using ITSWeb.Models.Repository;
using System;
using System.Web.Http;
using System.Web.Mvc;
namespace ITSWeb.Controllers
{
[System.Web.Mvc.Authorize(Roles = "Admin, User")]
public class OrderManageController : BaseController
{
IOrderManagementService orderManagementService;
public OrderManageController()
{
orderManagementService = new OrderManagementService();
}
/// <summary>
/// 訂單畫面
/// </summary>
/// <returns></returns>
public ActionResult CheckOut()
{
return View();
}
/// <summary>
/// 新增訂單
/// </summary>
/// <param name="model">訂單資料</param>
/// <returns></returns>
[System.Web.Mvc.HttpPost]
public ActionResult CreateOrder([FromBody]OrderViewModel model)
{
ResponseMessage result = new ResponseMessage()
{
success = true
};
if (model == null)
{
result.success = false;
result.Message = "沒有訂單資料";
}
if (result.success)
{
model.OrderId = Guid.NewGuid().ToString();
model.OrderUser = base.UserSerivce.CurrentUser.Identity.Name;
result = orderManagementService.CreateOrder(model);
}
return Json(result);
}
}
} |
using Hayaa.CacheKeyStatic;
using Hayaa.Security.Client.Config;
using Hayaa.Security.Client.Model;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Hayaa.Security.Client
{
class JobAuthorityCache
{
public static Dictionary<String, List<String>> GetJobAuthData(string jobToken)
{
var data= Redis.Client.RedisService.Get<List<AppService>>(ConfigHelper.Instance.GetComponentConfig().CacheConfigName, String.Format(JobAuthorityCacheKey.AuthorityCacheKey, jobToken));
return data.ToDictionary(k => k.Name, v => v.AppFunctions.Select(a => a.FunctionName).ToList());
}
}
}
|
using System;
using System.Data.SqlClient;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Windows;
using NLog;
namespace RAM.Classes
{
internal class Search
{
private string _dbConnection;
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private User[] _users = null;
private readonly ObservableCollection<User> _names = new ObservableCollection<User>();
public ObservableCollection<User> SearchUser (string searchUserName)
{
_dbConnection = ConfigurationManager.AppSettings["DBConection"];
var sqlUsers = "Select DISTINCT tblADusers.Displayname, tblADusers.Username, tblAssets.AssetName, tblAssets.Lastseen" +
" From tblAssets Inner Join tblADusers On tblADusers.Username = tblAssets.Username Inner Join tblCPlogoninfo On tblAssets.AssetID = tblCPlogoninfo.AssetID" +
" where tblADusers.Username in (SELECT[Username] FROM [lansweeperdb].[dbo].[tblADusers] where ([Displayname] Like N'%" + searchUserName + "%' or Username like N'%" + searchUserName + "%'))"+
" and tblAssets.OScode not like N'%S' ORDER by tblAssets.Lastseen desc";
try
{
var srvConn = new SqlConnection(_dbConnection);
using (srvConn)
using (var cmd = new SqlCommand(sqlUsers, srvConn))
{
srvConn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
_names.Add(new User { Name = reader.GetString(0), Sam = reader.GetString(1) , Comp = reader.GetString(2) });
}
}
}
catch (SqlException e)
{
switch (e.Number)
{
case 4060:
MessageBox.Show("Произошла ошибка:" + Environment.NewLine + "Ошибка при подключении к базе данных." + Environment.NewLine + "Возможно в настройках указано неверное название БД или название было измененно");
Logger.Error(e, "Ошибка при подключении к базе данных.");
break;
case 18456:
MessageBox.Show("Произошла ошибка:" + Environment.NewLine + "Недостаточно прав для выполнения операции");
Logger.Error(e, "Недостаточно прав для выполнения операции");
break;
default:
MessageBox.Show("Произошла ошибка:" + Environment.NewLine + e.Message);
Logger.Error(e, "Произошла ошибка при подключении к SQL базе: ");
break;
}
}
catch (Exception e)
{
Logger.Error(e, "Ошибка при поиске");
MessageBox.Show("Произошла ошибка:" + Environment.NewLine + e.Message);
}
return _names;
}
}
}
|
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;
namespace Hyprsoft.Dns.Monitor.Providers
{
public class HyprsoftDnsProvider : DnsProvider
{
#region Constructors
public HyprsoftDnsProvider(ILogger<HyprsoftDnsProvider> logger, IPublicIpProvider provider) : base(logger, provider) { }
#endregion
#region Properties
public const string Key = nameof(HyprsoftDnsProvider);
#endregion
#region Methods
protected override Task<string> GetDnsIpAddressAsync(string domainName, CancellationToken cancellationToken = default)
{
Logger.LogWarning("This DNS provider is for testing purposes only and generates random IP addresses.");
var rng = new Random((int)DateTime.Now.Ticks);
return Task.FromResult($"{rng.Next(1, 256)}.{rng.Next(1, 256)}.{rng.Next(1, 256)}.{rng.Next(1, 256)}");
}
protected override Task SetDnsIpAddressAsync(string domainName, string ip, CancellationToken cancellationToken = default)
{
Logger.LogWarning("This DNS provider is for testing purposes only and does NOT update any DNS records.");
return Task.CompletedTask;
}
#endregion
}
}
|
namespace Foundry.Website.Models
{
public enum ViewMessageType
{
Info,
Warning,
Error
}
public class ViewMessageModel
{
public ViewMessageType MessageType { get; set; }
public string Text { get; set; }
public ViewMessageModel()
{ }
public ViewMessageModel(string text, ViewMessageType type)
{
MessageType = type;
Text = text;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using BusPoa.Models;
using BusPoa.Views;
using BusPoa.ViewModels;
using Xamarin.Forms.Maps;
using System.Threading;
using System.Diagnostics;
using Plugin.Geolocator;
using BusPoa.Services;
namespace BusPoa.Views
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class ItemsPage : ContentPage
{
ItemsViewModel viewModel;
bool isMapa = false;
//string lblBtTrocar = "Estou Esperando um Ônibus";
public static CancellationTokenSource CancellationToken { get; set; }
List<Localizacao> listaTeste;
public IDataStore<Item> DataStore => DependencyService.Get<IDataStore<Item>>();
public ItemsPage()
{
InitializeComponent();
listaTeste = new List<Localizacao>();
MyMap.MapType = MapType.Street;
MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(-30.0277, -51.2287), Distance.FromMiles(1)));
MyMap.IsVisible = false;
pickerLinha.IsVisible = true;
pickerLinhaEspera.IsVisible = false;
CancellationToken = new CancellationTokenSource();
BindingContext = viewModel = new ItemsViewModel();
getlocation();
}
async void getlocation()
{
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
MyMap.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(position.Latitude, position.Longitude), Distance.FromMiles(1)));
}
//async void OnItemSelected(object sender, SelectedItemChangedEventArgs args)
//{
// var item = args.SelectedItem as Item;
// if (item == null)
// return;
// await Navigation.PushAsync(new ItemDetailPage(new ItemDetailViewModel(item)));
// // Manually deselect item.
// ItemsListView.SelectedItem = null;
//}
void btTrocarItem_Clicked(object sender, EventArgs e)
{
//await Navigation.PushModalAsync(new NavigationPage(new NewItemPage()));
if (isMapa)
{
MyMap.IsVisible = true;
pickerLinha.IsVisible = false;
pickerLinhaEspera.IsVisible = true;
viewModel.lblBtTrocar = "Tô no Bus";
isMapa = false;
CancellationToken.Cancel();
}
else
{
MyMap.IsVisible = false;
pickerLinha.IsVisible = true;
pickerLinhaEspera.IsVisible = false;
viewModel.lblBtTrocar = "Perando Bus";
isMapa = true;
//cancela a thread de buscar a localizacao
CancellationToken.Cancel();
}
}
async void OnPickerSelectedIndexChanged(object sender, EventArgs e)
{
//codigo do que fazer quando troca
//envia para o banco as informacoes do gps
//token para cancelar a task quando ele trocar para "esperando um onibus"
CancellationToken = new CancellationTokenSource();
while (!CancellationToken.IsCancellationRequested)
{
try
{
//5000 = 5 segundos, 10000 = 10 segundos
CancellationToken.Token.ThrowIfCancellationRequested();
await Task.Delay(3000, CancellationToken.Token).ContinueWith(async (arg) =>
{
if (!CancellationToken.Token.IsCancellationRequested)
{
CancellationToken.Token.ThrowIfCancellationRequested();
//aqui pega as informacoes do gps e upa no banco
var locator = CrossGeolocator.Current;
locator.DesiredAccuracy = 50;
var position = await locator.GetPositionAsync(TimeSpan.FromSeconds(10));
double longitude = position.Longitude;
double latitude = position.Latitude;
var l = new Localizacao()
{
//Id = Guid.NewGuid().ToString(),
Data = DateTime.Now,
Linha = (string)pickerLinha.SelectedItem,
Latitude = latitude,
Longitude = longitude
};
MessagingCenter.Send(this, "AddLocalizacao", l);
var x = await ((AzureDataStore)DataStore).AddLocalizacaoAsync(l);
//adiciona na lista de testes fingindo que eh o banco
listaTeste.Add(l);
string longit = string.Format("{0:0.0000000}", longitude);
string lat = string.Format("{0:0.0000000}", latitude);
Debug.WriteLine("Armazenando \nLongitude: " + longit +"\nLatitude: " + lat);
}
});
}
catch (Exception ex)
{
Debug.WriteLine("EX 1: " + ex.Message);
}
}
}
async void OnPickerLinhaEsperaSelectedIndexChanged(object sender, EventArgs e)
{
//codigo do que fazer quando troca
//recebe do banco as informacoes da linha selecionada
CancellationToken = new CancellationTokenSource();
while (!CancellationToken.IsCancellationRequested)
{
try
{
//5000 = 5 segundos, 10000 = 10 segundos
CancellationToken.Token.ThrowIfCancellationRequested();
await Task.Delay(5000, CancellationToken.Token).ContinueWith(async (arg) =>
{
if (!CancellationToken.Token.IsCancellationRequested)
{
CancellationToken.Token.ThrowIfCancellationRequested();
//aqui pega as informacoes do banco e coloca no mapa
var x = await ((AzureDataStore)DataStore).GetLocalizacaoAsync((string)pickerLinhaEspera.SelectedItem);
if (x == null)
{
var xx = 0;
}
string longit = string.Format("{0:0.0000000}", x.Longitude);
string lat = string.Format("{0:0.0000000}", x.Latitude);
Debug.WriteLine("Lendo \nLongitude: " + longit + "\nLatitude: " + lat);
MyMap.Pins.Clear();
MyMap.Pins.Add(new Pin() { Position = new Position(x.Latitude, x.Longitude), Type = PinType.Place, Label = (string)pickerLinhaEspera.SelectedItem });
}
});
}
catch (Exception ex)
{
Debug.WriteLine("EX 1: " + ex.Message);
}
}
}
protected override void OnAppearing()
{
base.OnAppearing();
if (viewModel.Items.Count == 0)
viewModel.LoadItemsCommand.Execute(null);
}
}
} |
using System;
using SharpDX;
namespace MDX
{
class Camera
{
public enum PROJECTION_MODE { Perspective, Orthogonalize };
private PROJECTION_MODE mode;
private float clientw, clienth;
private float near, far;
private float fov;
private Matrix view;
private Matrix projection;
private Matrix GetProjection()
{
if (mode == PROJECTION_MODE.Orthogonalize)
return Matrix.OrthoLH(clientw, clienth, near, far);
return Matrix.PerspectiveFovLH(fov, clientw / clienth, near, far);
}
public Camera(float clientW, float clientH, PROJECTION_MODE proj_mode)
{
mode = proj_mode;
clientw = clientW;
clienth = clientH;
near = 0.3f;
far = 100.0f;
fov = ((float)System.Math.PI) * 0.25f;
view = Matrix.LookAtLH(new Vector3(0.0f, 0.0f, -10.0f), Vector3.Zero, Vector3.Up);
projection = GetProjection();
}
public void Move(Vector3 deltapos)
{
Matrix translation = Matrix.Translation(deltapos);
translation.Invert();
view = view * translation;
}
public void Rotation(Vector3 yaw_pitch_roll)
{
yaw_pitch_roll.X = yaw_pitch_roll.X * (float)Math.PI / 360.0f;
yaw_pitch_roll.Y = yaw_pitch_roll.Y * (float)Math.PI / 360.0f;
yaw_pitch_roll.Z = yaw_pitch_roll.Z * (float)Math.PI / 360.0f;
Matrix rx = Matrix.RotationAxis(view.Right, yaw_pitch_roll.Y);
Matrix ry = Matrix.RotationAxis(view.Up, yaw_pitch_roll.X);
Matrix rz = Matrix.RotationAxis(view.Forward, yaw_pitch_roll.Z);
view = view * rx * ry * rz;
}
public Matrix ViewProjection
{
get
{
return view * projection;
}
}
public Vector3 Forwrd { get { return view.Forward; } }
public Vector3 Right { get { return view.Right; } }
public Vector3 Up { get { return view.Up; } }
public float FOV
{
get
{
return fov;
}
set
{
fov = value;
projection = GetProjection();
}
}
public float Near
{
get
{
return near;
}
set
{
near = value;
projection = GetProjection();
}
}
public float Far
{
get
{
return far;
}
set
{
far = value;
projection = GetProjection();
}
}
public PROJECTION_MODE Mode
{
get
{
return mode;
}
set
{
mode = value;
projection = GetProjection();
}
}
}
}
|
namespace PostRequestFactory.Core
{
/// <summary>
/// Available parameter types
/// </summary>
public enum RequestParameterType
{
Basic = 1,
Text = 2,
Binary = 3
}
}
|
using System;
using Microsoft.EntityFrameworkCore.Migrations;
namespace HouseRent.Data.Migrations
{
public partial class AddBookingAndBookingDetail : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<int>(
name: "BookingId",
table: "DetailOfFlats",
type: "int",
nullable: true);
migrationBuilder.AddColumn<int>(
name: "BookingId",
table: "DetailOfDuplexs",
type: "int",
nullable: true);
migrationBuilder.CreateTable(
name: "Bookings",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
BookingNo = table.Column<string>(type: "nvarchar(max)", nullable: true),
Name = table.Column<string>(type: "nvarchar(max)", nullable: false),
PhoneNo = table.Column<string>(type: "nvarchar(max)", nullable: false),
Email = table.Column<string>(type: "nvarchar(max)", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: false),
OrderDate = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Bookings", x => x.Id);
});
migrationBuilder.CreateTable(
name: "bookingDetail2s",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
BookingId = table.Column<int>(type: "int", nullable: false),
DetailOfDuplexId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_bookingDetail2s", x => x.Id);
table.ForeignKey(
name: "FK_bookingDetail2s_Bookings_BookingId",
column: x => x.BookingId,
principalTable: "Bookings",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_bookingDetail2s_DetailOfDuplexs_DetailOfDuplexId",
column: x => x.DetailOfDuplexId,
principalTable: "DetailOfDuplexs",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "BookingDetails",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
BookingId = table.Column<int>(type: "int", nullable: false),
DetailOfFlatId = table.Column<int>(type: "int", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_BookingDetails", x => x.Id);
table.ForeignKey(
name: "FK_BookingDetails_Bookings_BookingId",
column: x => x.BookingId,
principalTable: "Bookings",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_BookingDetails_DetailOfFlats_DetailOfFlatId",
column: x => x.DetailOfFlatId,
principalTable: "DetailOfFlats",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateIndex(
name: "IX_DetailOfFlats_BookingId",
table: "DetailOfFlats",
column: "BookingId");
migrationBuilder.CreateIndex(
name: "IX_DetailOfDuplexs_BookingId",
table: "DetailOfDuplexs",
column: "BookingId");
migrationBuilder.CreateIndex(
name: "IX_bookingDetail2s_BookingId",
table: "bookingDetail2s",
column: "BookingId");
migrationBuilder.CreateIndex(
name: "IX_bookingDetail2s_DetailOfDuplexId",
table: "bookingDetail2s",
column: "DetailOfDuplexId");
migrationBuilder.CreateIndex(
name: "IX_BookingDetails_BookingId",
table: "BookingDetails",
column: "BookingId");
migrationBuilder.CreateIndex(
name: "IX_BookingDetails_DetailOfFlatId",
table: "BookingDetails",
column: "DetailOfFlatId");
migrationBuilder.AddForeignKey(
name: "FK_DetailOfDuplexs_Bookings_BookingId",
table: "DetailOfDuplexs",
column: "BookingId",
principalTable: "Bookings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_DetailOfFlats_Bookings_BookingId",
table: "DetailOfFlats",
column: "BookingId",
principalTable: "Bookings",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_DetailOfDuplexs_Bookings_BookingId",
table: "DetailOfDuplexs");
migrationBuilder.DropForeignKey(
name: "FK_DetailOfFlats_Bookings_BookingId",
table: "DetailOfFlats");
migrationBuilder.DropTable(
name: "bookingDetail2s");
migrationBuilder.DropTable(
name: "BookingDetails");
migrationBuilder.DropTable(
name: "Bookings");
migrationBuilder.DropIndex(
name: "IX_DetailOfFlats_BookingId",
table: "DetailOfFlats");
migrationBuilder.DropIndex(
name: "IX_DetailOfDuplexs_BookingId",
table: "DetailOfDuplexs");
migrationBuilder.DropColumn(
name: "BookingId",
table: "DetailOfFlats");
migrationBuilder.DropColumn(
name: "BookingId",
table: "DetailOfDuplexs");
}
}
}
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
[RequireComponent(typeof(Rigidbody))]
public class CollisionCheckerBit : MonoBehaviour {
#region events
public delegate void DetectHandler(Vector3? point);
public event DetectHandler OnDetect;
#endregion
#region private variables
private Rigidbody m_rigidbody;
private Vector3 m_previousPosition;
#endregion
#region serialized field
[SerializeField]
private int m_detectLimit = 1000;
#endregion
#region public variables
public List<GameObject> IgnoreObjects;
#endregion
/// <summary>
/// Start this instance.
/// </summary>
void Start () {
//
}
/// <summary>
/// Awake this instance.
/// </summary>
void Awake() {
m_rigidbody = GetComponent<Rigidbody>();
IgnoreObjects.Add(gameObject);
}
/// <summary>
/// Checks start.
/// </summary>
/// <param name="mass">Mass.</param>
/// <param name="startPosition">Start position.</param>
/// <param name="force">Force.</param>
/// <param name="gravity">Gravity.</param>
public void CheckStart(float mass, Vector3 startPosition, Vector3 force, Vector3 gravity) {
float time = 0;
float interval = Time.fixedDeltaTime;
int frame = 0;
Vector3 speed;
m_previousPosition = CalcPositionFromForce(0, mass, startPosition, force, gravity, out speed);
while (frame < m_detectLimit) {
Vector3 pos = CalcPositionFromForce(time, mass, startPosition, force, gravity, out speed);
m_rigidbody.MovePosition(pos);
Vector3 direction = pos - m_previousPosition;
m_previousPosition = pos;
float distance = speed.sqrMagnitude * interval;
RaycastHit hit;
bool needIgnore = false;
if (m_rigidbody.SweepTest(direction, out hit, distance)) {
foreach (GameObject ignore in IgnoreObjects) {
if (hit.collider.gameObject == ignore) {
needIgnore = true;
break;
}
}
// Continue the loop if collider is in ignore objects.
if (needIgnore) {
time += interval;
frame++;
continue;
}
if (OnDetect != null) {
OnDetect(hit.point);
}
Destroy(gameObject);
return;
}
time += interval;
frame++;
}
if (OnDetect != null) {
OnDetect(null);
}
Destroy(gameObject);
}
/// <summary>
/// Calculates the position from force.
/// </summary>
/// <returns>The position from force.</returns>
/// <param name="time">Time.</param>
/// <param name="mass">Mass.</param>
/// <param name="startPosition">Start position.</param>
/// <param name="force">Force.</param>
/// <param name="gravity">Gravity.</param>
Vector3 CalcPositionFromForce(float time, float mass, Vector3 startPosition, Vector3 force, Vector3 gravity, out Vector3 speed) {
speed = (force / mass) * Time.fixedDeltaTime;
Vector3 position = (speed * time) + (gravity * 0.5f * Mathf.Pow(time, 2));
return startPosition + position;
}
}
|
using System;
namespace LorikeetMApp.Interfaces
{
public interface IDialer
{
bool Dial(string number);
}
}
|
using AutomationFramework.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using AutomationFramework.Extensions;
namespace AutomationFramework.KendoWrapper
{
/// <summary>
/// Kendo controls which has 1 or 2 methods and need not required to create separate file for each controls.
/// </summary>
public class KendoCommonUtilities
{
public static bool IsModelPopUpClosed()
{
var jsTobeExecuted = Hooks.Driver.ScriptQuery<bool>(string.Format("return $('#window').parent().is(':visible');"));
return jsTobeExecuted;
}
}
}
|
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TimeTableApi.Application.Shared.EventManagement.Dtos;
using TimeTableApi.Application.Shared.TimeTableManagement;
using TimeTableApi.Application.Shared.UserManagement;
using TimeTableApi.Application.Shared.UserManagement.Dtos;
namespace TimeTableApi.Controllers
{
[Authorize]
[Route("TimeTable")]
public class TimeTableController : Controller
{
private readonly ITimeTableAppService _timeTableAppService;
public TimeTableController(ITimeTableAppService timeTableAppService) {
_timeTableAppService = timeTableAppService;
}
[HttpGet]
[Route("GetById/{id}")]
public TimeTableDto GetById(string id)
{
return _timeTableAppService.GetById(id);
}
[HttpPost]
[Route("CreateOrUpdate")]
public bool CreateOrUpdate([FromBody]CreateOrEditTimeTableInputDto input)
{
return _timeTableAppService.CreateOrUpdate(input);
}
[AllowAnonymous]
[HttpGet]
[Route("GetAllByEventName/{eventName}")]
public List<TimeTableDto> GetAllByEventName(string eventName)
{
return _timeTableAppService.GetAllByEventName(eventName);
}
[HttpGet]
[Route("GetAllByEventId/{eventId}")]
public List<TimeTableDto> GetAllByEventId(string eventId)
{
return _timeTableAppService.GetAllByEventId(eventId);
}
[HttpGet]
[Route("schedule/GetAllByEventId/{eventId}")]
public List<TimeTableDto> GetAllScheduleTimeTableByEventId(string eventId)
{
return _timeTableAppService.GetAllScheduleTimeTableByEventId(eventId);
}
[HttpDelete]
[Route("delete/{id}")]
public void Delete(string id)
{
_timeTableAppService.Remove(id);
}
}
}
|
using EmberKernel.Services.EventBus;
using System;
using System.Collections.Generic;
using System.Text;
namespace EmberMemory.Components
{
public class ProcessTerminatedEvent<T> : Event<T> where T : ProcessTerminatedEvent<T>
{
public int ProcessId { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Plotter.Tweet;
using Plotter.Tweet.Processing;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Plotter.Tests
{
[TestClass]
public class PingPongTests : TestBase
{
[TestMethod]
public void PingPongTest()
{
var result = TestTweet(new Tweet.Tweet()
{
CreatorScreenName = "anna",
Text = "ping"
});
Assert.AreEqual("@anna pong", result.GetMessageForSending());
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using RPG.Movement;
using UnityEngine;
using RPG.Combat;
using RPG.Core;
using RPG.Resources;
using UnityEditor;
using UnityEngine.AI;
using UnityEngine.EventSystems;
namespace RPG.Control
{
public class PlayerController : MonoBehaviour
{
Health health;
private Mover _mover;
[System.Serializable]
struct CursorStyleMapping
{
public CursorType type;
public Texture2D texture;
public Vector2 hotspot;
}
[SerializeField] private CursorStyleMapping[] cursorStyleMappings = null;
[SerializeField] private float maxNavMeshProjectionDistance = 1f;
[SerializeField] private float maxNavPathLength = 35f;
private void Awake()
{
_mover = GetComponent<Mover>();
health = GetComponent<Health>();
}
void Update()
{
if (InteractWithUI()) return;
if (health.IsDead())
{
SetCursor(CursorType.None);
return;
}
if (InteractWithComponent()) return;
if (InteractWithMovement()) return;
SetCursor(CursorType.None);
}
private bool InteractWithComponent()
{
RaycastHit[] hits = RaycastAllSorted();
foreach (var hit in hits)
{
IRaycastable[] raycastables = hit.transform.GetComponents<IRaycastable>();
foreach (var raycastable in raycastables)
{
if (raycastable.HandleRaycast(this))
{
SetCursor(raycastable.GetCursorType());
return true;
}
}
}
return false; //There was no raycastable component
}
private RaycastHit[] RaycastAllSorted()
{
RaycastHit[] hits = Physics.RaycastAll(GetMouseRay());
float[] distances = new float[hits.Length];
for (int i = 0; i < hits.Length; i++)
{
distances[i] = hits[i].distance;
}
Array.Sort(distances, hits);
return hits;
}
private bool InteractWithUI()
{
if(EventSystem.current.IsPointerOverGameObject())
{
SetCursor(CursorType.UI);
return true;
}
return false;
}
//This method will get all of the objects that were hit with the raycast and we will loop through each object in order to find the one we are looking for.
//This is so that even if a tree is blocking our screen and we want to attack an enemy, the enemy should have high priority.
private void SetCursor(CursorType type)
{
CursorStyleMapping styleMapping = GetCursorStyleMapping(type);
Cursor.SetCursor(styleMapping.texture, styleMapping.hotspot, CursorMode.Auto);
}
private CursorStyleMapping GetCursorStyleMapping(CursorType type)
{
foreach (CursorStyleMapping styleMapping in cursorStyleMappings)
{
if (styleMapping.type == type)
{
return styleMapping;
}
}
return cursorStyleMappings[0];
}
#region Movement
private bool InteractWithMovement()
{
//RaycastHit hit;
//bool hasHit = Physics.Raycast(GetMouseRay(), out hit)
Vector3 target;
bool hasHit = RaycastNavMesh(out target);
if (hasHit)
{
if (Input.GetMouseButton(0))
{
_mover.StartMoveAction(target, 1f);
}
SetCursor(CursorType.Movement);
return true;
}
return false;
}
private bool RaycastNavMesh(out Vector3 target)
{
target = new Vector3();
RaycastHit hit;
bool hasHit = Physics.Raycast(GetMouseRay(), out hit);
if (!hasHit) return false;
NavMeshHit navMeshHit;
bool hasCastToNavMesh = NavMesh.SamplePosition(hit.point, out navMeshHit,
maxNavMeshProjectionDistance, NavMesh.AllAreas);
if (!hasCastToNavMesh) return false; //have not found a navmesh near the point which the cursor clicked on.
target = navMeshHit.position;
NavMeshPath path = new NavMeshPath();
bool hasPath = NavMesh.CalculatePath(transform.position, target, NavMesh.AllAreas, path);
if (!hasPath) return false;
if (path.status != NavMeshPathStatus.PathComplete) return false; //if there is no complete path to the selected location, then return false.
//Check if the length is too long, this allows me to give the control to the user to manually guide the player to the location.
if (GetPathLength(path) > maxNavPathLength) return false;
return true;
}
private float GetPathLength(NavMeshPath path)
{
float runningTotal = 0;
//edge case check
if (path.corners.Length < 2) return runningTotal;
for (int i = 0; i < path.corners.Length - 1; i++)
{
runningTotal += Vector3.Distance(path.corners[i], path.corners[i + 1]);
}
return runningTotal;
}
#endregion
#region Mouse Ray
private static Ray GetMouseRay()
{
return Camera.main.ScreenPointToRay(Input.mousePosition);
}
#endregion
}
} |
using System;
using Admin.Models;
using Admin.ViewModels;
using AutoMapper;
using Musical_WebStore_BlazorApp.Server.Data.Models;
using Musical_WebStore_BlazorApp.Shared;
public class MappingProfile : Profile {
public MappingProfile() {
CreateMap<User, UserLimited>();
CreateMap<Comment, CommentLimited>();
CreateMap<Location, LocationViewModel>();
CreateMap<Device, ModuleViewModel>();
CreateMap<Metering, MeteringModel>();
CreateMap<Module, ModuleViewModel>();
CreateMap<Chat, ChatModel>();
CreateMap<Message, MessageModel>();
CreateMap<AddMessageModel, Message>();
CreateMap<OrderType, OrderTypeViewModel>();
CreateMap<AddOrderModel, Order>();
CreateMap<Service, ServiceViewModel>();
CreateMap<Order, OrderViewModel>();
CreateMap<OrderStatus, OrderStatusViewModel>();
CreateMap<Company, CompanyModel>();
CreateMap<OrderWorker, OrderWorkerModel>();
CreateMap<AddWorkerToOrderModel, OrderWorker>();
CreateMap<Service, ServicePageModel>();
CreateMap<Review, ReviewModel>();
CreateMap<AddReviewModel, Review>();
CreateMap<ChatUser, ChatUserModel>();
CreateMap<User, ProfileModel>();
CreateMap<Module, ModuleViewModel>();
}
} |
using System;
using System.Runtime.InteropServices;
namespace Vlc.DotNet.Core.Interops.Signatures
{
/// <summary>
/// Callback prototype to unlock a picture buffer.
/// When the video frame decoding is complete, the unlock callback is invoked.
/// This callback might not be needed at all.It is only an indication that the
/// application can now read the pixel values if it needs to.
/// </summary>
/// <remarks>
/// A picture buffer is unlocked after the picture is decoded,
/// but before the picture is displayed.
/// </remarks>
/// <param name="userData">
/// private pointer as passed to <see cref="SetVideoCallbacks"/>.
/// </param>
/// <param name="picture">
/// private pointer returned from the <see cref="LockVideoCallback"/>
/// callback
/// </param>
/// <param name="planes">
/// pixel planes as defined by the <see cref="LockVideoCallback"/>
/// callback (this parameter is only for convenience)
///
/// Its size is always PICTURE_PLANE_MAX, which is 5 in my experience. Only the number of planes required by chroma are usable, which is 1 for RV32.
/// </param>
[LibVlcFunction("libvlc_video_lock_cb")]
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
public delegate void UnlockVideoCallback(IntPtr userData, IntPtr picture, [MarshalAs(UnmanagedType.LPArray, SizeConst = 5)]IntPtr[] planes);
}
|
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Timers;
using Microsoft.AspNetCore.SignalR;
namespace WebApplication1.Hubs
{
public class ChatHub : Hub
{
public ChatHub()
{
Debug.WriteLine("hello");
var timer1 = new Timer();
timer1.Elapsed += this.Timer1_Elapsed;
timer1.Interval = 2000;
timer1.Start();
}
private async void Timer1_Elapsed(object sender, ElapsedEventArgs e)
{
Debug.WriteLine("tick");
await SendMessage("user", "hello");
}
public async Task SendMessage(string user, string message)
{
await Clients.All.SendAsync("ReceiveMessage", user, message);
}
}
}
|
using jaytwo.Common.Collections;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace jaytwo.Common.Test.Collections
{
[TestFixture]
public static class CollectionUtilityTests
{
[Test]
public static void CollectionUtility_CreateDictionary_FromNameValueCollection()
{
var collection = new NameValueCollection() { { "a", "b" }, { "c", "d" }, { "c", "e" }, { "f", null } };
var dynamicDictionaryAsDictionary = CollectionUtility.ToDictionary(collection);
Assert.AreEqual("b", dynamicDictionaryAsDictionary["a"]);
Assert.AreEqual("e", dynamicDictionaryAsDictionary["c"]);
Assert.AreEqual(null, dynamicDictionaryAsDictionary["f"]);
CollectionAssert.AreEquivalent(collection.AllKeys, dynamicDictionaryAsDictionary.Keys);
Assert.Throws(typeof(ArgumentNullException), () => CollectionUtility.ToDictionary((NameValueCollection)null));
}
[Test]
public static void CollectionUtility_CreateDictionary_FromNameValueCollection_ignore_case()
{
var collection = new NameValueCollection() { { "a", "b" }, { "f", null } };
var dynamicDictionaryAsDictionary = CollectionUtility.ToDictionary(collection, StringComparer.OrdinalIgnoreCase);
Assert.AreEqual("b", dynamicDictionaryAsDictionary["a"]);
Assert.AreEqual("b", dynamicDictionaryAsDictionary["A"]);
Assert.AreEqual(null, dynamicDictionaryAsDictionary["f"]);
CollectionAssert.AreEquivalent(collection.AllKeys, dynamicDictionaryAsDictionary.Keys);
Assert.Throws(typeof(ArgumentNullException), () => CollectionUtility.ToDictionary((NameValueCollection)null, StringComparer.OrdinalIgnoreCase));
}
}
}
|
using InvoicingApp.BusinessLogic.Contracts.Services;
using InvoicingApp.BusinessLogic.Services;
using InvoicingApp.DataAccess.Contexts;
using InvoicingApp.DataAccess.Repositories.Base;
using InvoicingApp.Domain.Models.Customer;
using InvoicingApp.Domain.Models.Invoice;
using InvoicingApp.Domain.Models.Production;
using InvoicingApp.ViewModels;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
namespace InvoicingApp.Controllers
{
public class InvoiceController : CrudControllerBase<Invoice, Guid>
{
#region private Members
private readonly InvoiceService _service;
private readonly IGenericService<Customer,Guid> _customerService;
private readonly IGenericService<Product, Guid> _productService;
private readonly MainDbContext _db;
#endregion
#region Public Constructor
/// <summary>
/// Default constructor
/// </summary>
/// <param name="service"></param>
public InvoiceController() : this(new InvoiceService(new GenericRepository<Invoice>(new DataAccess.Contexts.MainDbContext()),
new GenericRepository<InvoiceDetail>(new DataAccess.Contexts.MainDbContext())))
{
_db = new MainDbContext();
_customerService = new GenericService<Customer, Guid>(new GenericRepository<Customer>(_db));
_productService = new GenericService<Product, Guid>(new GenericRepository<Product>(_db));
}
public InvoiceController(InvoiceService service) : base(service)
{
_service = service;
}
#endregion
public override ActionResult Index()
{
return View(_service.GetInvoices());
}
public override ActionResult Create()
{
ViewBag.products = _productService.GetAll().Select(x => new SelectListItem { Text = x.Name , Value = x.Id.ToString()});
ViewBag.customer = _customerService.GetAll().Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() });
return View();
}
public async override Task<ActionResult> Create(Invoice entity)
{
await _service.Create(entity);
return Json("Registro Guardado");
}
[HttpGet]
public async Task<ActionResult> GetInvoiceDetail(string productId, string quantity)
{
var id = Guid.Parse(productId);
var cantidad = Convert.ToInt32(quantity);
var result = await _productService.FindBy(x => x.Id == id).Select(x => new InvoiceDetailsViewModel
{
ProductName = x.Name,
productId = x.Id,
Price = x.Price,
ProductCode = x.Code,
Quantity = cantidad,
Tax = x.ApplyTax ? 15 : 0,
Total = cantidad * x.Price
}).FirstOrDefaultAsync();
return Json(result, JsonRequestBehavior.AllowGet);
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1.Models
{
[DataContract]
public class Example2
{
public Example2(int num, Dictionary<string, string> dict, Dictionary<int, string> dictInt)
{
Num = num;
Dict = dict;
DictInt = dictInt;
}
[DataMember(Name = "num")]
public int Num { get; set; }
[DataMember(Name = "dict")]
public Dictionary<string, string> Dict { get; set; }
[DataMember(Name = "dictint")]
public Dictionary<int, string> DictInt { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArkSavegameToolkitNet
{
public interface INameContainer
{
//void CollectNames(ISet<string> nameTable);
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Loan_Calculator_Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
for (double i = 1; i <= 5; i += .25)
{
ddlRate.Items.Add(new ListItem(String.Format("{0}%", i), i.ToString()));
}
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
calculatePayment();
}
protected void btnClear_Click(object sender, EventArgs e)
{
txtAmount.Text = null;
ddlRate.SelectedIndex = 0;
txtMonths.Text = null;
mthlyPaymentLbl.Text = null;
}
protected void calculatePayment()
{
try
{
Double loanAmount = Convert.ToDouble(txtAmount.Text);
Double interestRate = (Convert.ToDouble(ddlRate.SelectedValue) / 100) / 12;
Double loanTerm = Convert.ToDouble(txtMonths.Text);
Double monthlyPayment = loanAmount * (interestRate / (1 - Math.Pow((1 + interestRate), -1 * loanTerm)));
mthlyPaymentLbl.Text = monthlyPayment.ToString("C2");
}
catch (Exception error)
{
mthlyPaymentLbl.Text = "Invalid Input";
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.