text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Collections; using System.Text.RegularExpressions; using System.Net; using System.Net.Configuration; using System.Net.Mail; using System.Net.Mime; using VMTech.Email; using VMTech.Util; using System.IO; namespace VMTech.EnviarEmail { public partial class Envio : Form { List<String> erro; List<String> _emails; List<String> destinatarios; List<Anexo> atach; String dirAtual; String arqConfig; ConfiguracaoBE config; OpenFileDialog abrirArquivo; public Envio() { InitializeComponent(); pnStatus.Visible = false; abrirArquivo = new OpenFileDialog(); config = new ConfiguracaoBE(); erro = new List<String>(); _emails = new List<String>(); destinatarios = new List<String>(); dirAtual = Directory.GetCurrentDirectory(); arqConfig = "EmailConfig.txt"; dgvConfig.Columns.Add("Email", "E-Mail"); dgvConfig.Columns["Email"].Width = 300; dgvConfig.Columns.Add("SMTP", "Servidor SMTP"); dgvConfig.Columns["SMTP"].Width = 250; dgvConfig.Columns.Add("Porta", "Porta"); dgvConfig.Columns["Porta"].Width = 80; dgvConfig.Columns.Add("SSL", "SSL"); dgvConfig.Columns["SSL"].Width = 30; dgvConfig.Columns.Add("Cred", "Cred."); dgvConfig.Columns["Cred"].Width = 30; dgvConfig.ReadOnly = true; dgvAnexos.Columns.Add("FileName", "Arquivo Anexo"); dgvAnexos.Columns["FileName"].Width = 350; dgvAnexos.Columns.Add("Acao", " "); dgvAnexos.Columns["Acao"].Width = 30; dgvAnexos.Columns["Acao"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.BottomCenter; dgvAnexos.ReadOnly = true; atach = new List<Anexo>(); Point loc = new Point(); loc.X = 13; loc.Y = 4; pnDe.Location = loc; } private void btEnviar_Click(object sender, EventArgs e) { MensagemBE mensagem = new MensagemBE(); mensagem.Destinatario = txtPara.Text; mensagem.Remetente = txtDe.Text; mensagem.Assunto = txtAssunto.Text; mensagem.Mensagem = txtMensagem.Text; erro = new List<String>(); this.Enabled = false; pnStatus.Visible = true; pnStatus.Enabled = true; lbEnv.Enabled = true; lbQtd.Enabled = true; if (destinatarios.Count() == 0) { lbQtd.Text = "1 de 1"; Form.ActiveForm.Refresh(); AcaoEnviar(mensagem); } else { var x = 0; foreach (var des in destinatarios) { x++; lbQtd.Text = x.ToString() + " de " + destinatarios.Count().ToString(); Form.ActiveForm.Refresh(); var le = Diversos.SepararTexto(des, ';'); if (le.Count() > 0) { mensagem.Destinatario = le[0]; if (le.Count() > 1) mensagem.Assunto = le[1]; AcaoEnviar(mensagem); } } } this.Enabled = true; pnStatus.Visible = false; if (erro.Count() > 0) { erro.Insert(0, "Alguns erros foram encontrados: \n"); ValidaErros(); } else MessageBox.Show("Processo de envio de e-mail concluído com sucesso..."); this.Enabled = true; } private void AcaoEnviar(MensagemBE mensagem) { # region Funcionando por DLL if (mensagem.Remetente == "") MessageBox.Show("Email do remetente deve ser preenchido."); else if (!Validar.Email(mensagem.Remetente, erro)) MessageBox.Show("Email do remetente não é válido."); else if (mensagem.Destinatario == "") MessageBox.Show("Email do destinatário deve ser preenchido."); else if (!Validar.Email(mensagem.Destinatario, erro)) mensagem.Destinatario = mensagem.Destinatario; else if (mensagem.Assunto == "") MessageBox.Show("O Assunto deve ser preenchido."); else if (mensagem.Mensagem == "") MessageBox.Show("A mensagem esta em branco."); else { Email.Email send = new Email.Email(); if (atach.Count() > 0) { mensagem.Anexos = new List<Anexo>(); mensagem.Anexos = atach; } List<String> listaErros = send.Enviar(mensagem, config); if(listaErros != null && listaErros.Count() > 0) { foreach (var err in listaErros) { erro.Add(err); } } # endregion # region FunfandoLocal //try //{ // MailMessage email = new MailMessage(); // email.From = new MailAddress("verone@gmail.com"); // email.To.Add(txtPara.Text); // email.Priority = MailPriority.Normal; // email.IsBodyHtml = true; // email.Subject = txtAssunto.Text; // email.Body = txtMensagem.Text; // email.SubjectEncoding = Encoding.GetEncoding("ISO-8859-1"); // email.BodyEncoding = Encoding.GetEncoding("ISO-8859-1"); // SmtpClient client = new SmtpClient(); // client.Host = "smtp.gmail.com"; // client.Port = 587; //465 ou 587 // client.UseDefaultCredentials = false; // client.DeliveryMethod = SmtpDeliveryMethod.Network; // NetworkCredential netCred = new NetworkCredential(txtDe.Text, "Vermont159951"); // client.Credentials = netCred; // client.EnableSsl = true; // client.Send(email); // MessageBox.Show("Funfou!"); //} //catch (Exception ex) //{ // MessageBox.Show("Erro: " + ex.Message); //} # endregion } } private void btnAnexar_Click(object sender, EventArgs e) { OpenFileDialog anexaArquivo = new OpenFileDialog(); anexaArquivo.InitialDirectory = @"C:\"; anexaArquivo.Title = "Anexar Arquivo"; if (anexaArquivo.ShowDialog() == DialogResult.OK) { try { Anexo arq = new Anexo(); Stream file = File.OpenRead(anexaArquivo.FileName); arq.ArquivoStream = file; arq.NomeArquivo = anexaArquivo.SafeFileName; atach.Add(arq); dgvAnexos.Rows.Add(arq.NomeArquivo, " X "); } catch (Exception ex) { MessageBox.Show("Erro: " + ex.Message); } } } private void dgvAnexos_CellClick(object sender, DataGridViewCellEventArgs e) { if (dgvAnexos.CurrentCell.ColumnIndex.Equals(1) && e.RowIndex != -1) { if (dgvAnexos.CurrentCell != null && dgvAnexos.CurrentCell.Value != null) { try { atach.RemoveAt(dgvAnexos.CurrentCell.RowIndex); dgvAnexos.Rows.RemoveAt(dgvAnexos.CurrentCell.RowIndex); } catch (Exception) { MessageBox.Show("Essa linha não pode ser excluida"); } } } } public Boolean ValidaErros() { if (erro.Count() > 0) { String str = ""; foreach (var item in erro) { str += item + "\n"; } MessageBox.Show(str); erro = new List<String>(); return true; } else return false; } private void btSelecioneDe_Click(object sender, EventArgs e) { dgvConfig.Rows.Clear(); if (Arquivo.Existe(dirAtual, arqConfig, erro)) { _emails = Arquivo.Ler(dirAtual, arqConfig, erro); ValidaErros(); foreach (var item in _emails) { List<String> linha = Diversos.SepararTexto(item, ';'); dgvConfig.Rows.Add(linha[0], linha[2], linha[3], linha[4] == "1" ? "Sim" : "Não", linha[5] == "1" ? "Sim" : "Não"); } } pnDe.Visible = true; } private void btSelecionePara_Click(object sender, EventArgs e) { abrirArquivo.InitialDirectory = @"C:\"; abrirArquivo.Filter = "Texo (*.txt; *.csv)|*.txt;*.csv"; abrirArquivo.Title = "Selecione o arquivo com a lista de E-mails"; String caminho; if (abrirArquivo.ShowDialog() == DialogResult.OK) { caminho = abrirArquivo.FileName.Replace(abrirArquivo.SafeFileName, ""); destinatarios = Arquivo.Ler(caminho, abrirArquivo.SafeFileName, erro); txtPara.Text = abrirArquivo.FileName.Replace("\\", @"\"); } } private void dgvConfig_CellClick(object sender, DataGridViewCellEventArgs e) { if (dgvConfig.CurrentCell.ColumnIndex.Equals(0) || dgvConfig.CurrentCell.ColumnIndex.Equals(1) && e.RowIndex != -1) { if (dgvConfig.CurrentCell != null && dgvConfig.CurrentCell.Value != null) { try { List<String> linha = Diversos.SepararTexto(_emails[dgvConfig.CurrentCell.RowIndex], ';'); txtEmailConfig.Text = linha[0]; txtSenhaConfig.Text = linha[1]; txtSMTPConfig.Text = linha[2]; txtPortaConfig.Text = linha[3]; ckSSLConfig.Checked = linha[4] == "1" ? true : false; ckCredencialConfig.Checked = linha[5] == "1" ? true : false; CamposConfig(false); btAcao.Text = "Alterar"; btAcao2.Visible = true; btAcao2.Text = "Apagar"; } catch (Exception) { MessageBox.Show("Essa linha não pode ser excluida"); } } } } private void btAcao_Click(object sender, EventArgs e) { switch (btAcao.Text) { case "Adicionar" : if (ValidaConfig()) { String texto = txtEmailConfig.Text + ";" + txtSenhaConfig.Text + ";" + txtSMTPConfig.Text + ";" + txtPortaConfig.Text + ";" + (ckSSLConfig.Checked == true ? "1" : "0") + ";" + (ckCredencialConfig.Checked == true ? "1" : "0") + ";"; _emails.Add(texto); if (!Arquivo.Existe(dirAtual, arqConfig, erro)) Arquivo.Criar(dirAtual, arqConfig, texto, erro); else Arquivo.Escrever(dirAtual, arqConfig, texto, erro); if (!ValidaErros()) { dgvConfig.Rows.Add(txtEmailConfig.Text, txtSMTPConfig.Text, txtPortaConfig.Text, ckSSLConfig.Checked == true ? "Sim" : "Não", ckCredencialConfig.Checked == true ? "Sim" : "Não"); dgvConfig.CurrentCell = dgvConfig.Rows[dgvConfig.Rows.Count - 2].Cells[0]; CamposConfig(false); btAcao.Text = "Alterar"; btAcao2.Visible = true; btAcao2.Text = "Apagar"; } } break; case "Alterar" : CamposConfig(true); btAcao.Text = "Confirma"; btAcao2.Text = "Voltar"; break; case "Confirma": _emails.RemoveAt(dgvConfig.CurrentCell.RowIndex); String text = txtEmailConfig.Text + ";" + txtSenhaConfig.Text + ";" + txtSMTPConfig.Text + ";" + txtPortaConfig.Text + ";" + (ckSSLConfig.Checked == true ? "1" : "0") + ";" + (ckCredencialConfig.Checked == true ? "1" : "0") + ";"; _emails.Add(text); AtualizaArquivo(); dgvConfig.CurrentCell = dgvConfig.Rows[dgvConfig.Rows.Count - 2].Cells[0]; CamposConfig(false); btAcao.Text = "Alterar"; btAcao2.Visible = true; btAcao2.Text = "Apagar"; break; } } private void btAcao2_Click(object sender, EventArgs e) { switch (btAcao2.Text) { case "Apagar" : _emails.RemoveAt(dgvConfig.CurrentCell.RowIndex); AtualizaArquivo(); Limpar(); break; case "Voltar" : CamposConfig(false); btAcao.Text = "Alterar"; btAcao2.Text = "Apagar"; break; } } private void AtualizaArquivo() { dgvConfig.Rows.Clear(); if (Arquivo.Existe(dirAtual, arqConfig, erro)) Arquivo.Excluir(dirAtual, arqConfig, erro); foreach (var texto in _emails) { if (!Arquivo.Existe(dirAtual, arqConfig, erro)) Arquivo.Criar(dirAtual, arqConfig, texto, erro); else Arquivo.Escrever(dirAtual, arqConfig, texto, erro); } foreach (var item in _emails) { List<String> linha = Diversos.SepararTexto(item, ';'); dgvConfig.Rows.Add(linha[0], linha[2], linha[3], linha[4] == "1" ? "Sim" : "Não", linha[5] == "1" ? "Sim" : "Não"); } } private void btCancelaConfig_Click(object sender, EventArgs e) { Limpar(); pnDe.Visible = false; } private void btLimpar_Click(object sender, EventArgs e) { Limpar(); } private void Limpar() { txtEmailConfig.Text = ""; txtSenhaConfig.Text = ""; txtSMTPConfig.Text = ""; txtPortaConfig.Text = ""; ckSSLConfig.Checked = false; ckCredencialConfig.Checked = false; CamposConfig(true); btAcao.Text = "Adicionar"; btAcao2.Text = "Apagar"; btAcao2.Visible = false; } private void CamposConfig(Boolean status_) { txtEmailConfig.Enabled = status_; txtSenhaConfig.Enabled = status_; txtSMTPConfig.Enabled = status_; txtPortaConfig.Enabled = status_; ckSSLConfig.Enabled = status_; ckCredencialConfig.Enabled = status_; } private Boolean ValidaConfig() { var retorno = false; if (txtEmailConfig.Text == "") MessageBox.Show("O E-mail de Saída não foi informado."); else if (!Validar.Email(txtEmailConfig.Text, erro)) ValidaErros(); else if (txtSenhaConfig.Text == "") MessageBox.Show("A senha não foi informada."); else if (txtSMTPConfig.Text == "") MessageBox.Show("O servidor SMTP não foi informado."); else if (txtPortaConfig.Text == "") MessageBox.Show("Porta não informada."); else retorno = true; return retorno; } private void btConfirmarConfig_Click(object sender, EventArgs e) { if(ValidaConfig()) { txtDe.Text = txtEmailConfig.Text; config.EmailSaida = txtEmailConfig.Text; config.Senha = txtSenhaConfig.Text; config.SMTP = txtSMTPConfig.Text; config.Porta = Convert.ToInt32(txtPortaConfig.Text); config.SSL = ckSSLConfig.Checked; config.CredenciaisPadrao = ckCredencialConfig.Checked; pnDe.Visible = false; } } private void txtPortaConfig_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsDigit(e.KeyChar)) { e.Handled = true; } } } }
using P.Domain.Entities; using PService.Pattern; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace P.Service.ServiceInterface { public interface IFiscalPowerService : IService<FiscalPower> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Console2.From_051_To_75 { public class _074_SortColors { /* * Given an array with n objects colored red, white or blue, sort them so that objects of the same color are adjacent, with the colors in the order red, white and blue. Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively. Note: You are not suppose to use the library's sort function for this problem. */ // HashTable is one method. // override the compare method is second method. } }
// Copyright 2016, 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Microsoft.Win32; using System.Collections.Generic; using System.IO; using System.Security; namespace NtApiDotNet.Win32 { /// <summary> /// Class representing the information about a service. /// </summary> public class ServiceInformation { /// <summary> /// The name of the service. /// </summary> public string Name { get; } /// <summary> /// The security descriptor of the service. /// </summary> public SecurityDescriptor SecurityDescriptor { get; } /// <summary> /// The list of triggers for the service. /// </summary> public IEnumerable<ServiceTriggerInformation> Triggers { get; } /// <summary> /// The service SID setting. /// </summary> public ServiceSidType SidType { get; } /// <summary> /// The service launch protected setting. /// </summary> public ServiceLaunchProtectedType LaunchProtected { get; } /// <summary> /// The service required privileges. /// </summary> public IEnumerable<string> RequiredPrivileges { get; } /// <summary> /// The service type. /// </summary> public ServiceType ServiceType { get; } /// <summary> /// Service start type. /// </summary> public ServiceStartType StartType { get; } /// <summary> /// Error control. /// </summary> public ServiceErrorControl ErrorControl { get; } /// <summary> /// Binary path name. /// </summary> public string BinaryPathName { get; } /// <summary> /// Load order group. /// </summary> public string LoadOrderGroup { get; } /// <summary> /// Tag ID for load order. /// </summary> public int TagId { get; } /// <summary> /// Dependencies. /// </summary> public IEnumerable<string> Dependencies { get; } /// <summary> /// Display name. /// </summary> public string DisplayName { get; } /// <summary> /// Service start name. For user mode services this is the username, for drivers it's the driver name. /// </summary> public string ServiceStartName { get; } /// <summary> /// Indicates this service is set to delayed automatic start. /// </summary> public bool DelayedAutoStart { get; } /// <summary> /// The user name this service runs under. /// </summary> public string UserName { get; } /// <summary> /// Type of service host when using Win32Share. /// </summary> public string ServiceHostType { get; } /// <summary> /// Service main function when using Win32Share. /// </summary> public string ServiceMain { get; } /// <summary> /// Image path for the service. /// </summary> public string ImagePath { get; } /// <summary> /// Get name of the target image, either the ServiceDll or ImagePath. /// </summary> public string ImageName => string.IsNullOrEmpty(ServiceDll) ? Path.GetFileName(ImagePath) : Path.GetFileName(ServiceDll); /// <summary> /// Service DLL if a shared process server. /// </summary> public string ServiceDll { get; } /// <summary> /// The name of the machine this service was found on. /// </summary> public string MachineName { get; } /// <summary> /// Indicates if this service process is grouped with others. /// </summary> public bool SvcHostSplitDisabled { get; } private static RegistryKey OpenKeySafe(RegistryKey rootKey, string path) { try { return rootKey.OpenSubKey(path); } catch (SecurityException) { return null; } } private static string ReadStringFromKey(RegistryKey rootKey, string keyName, string valueName) { RegistryKey key = rootKey; try { if (keyName != null) { key = OpenKeySafe(rootKey, keyName); } string valueString = string.Empty; if (key != null) { object valueObject = key.GetValue(valueName); if (valueObject != null) { valueString = valueObject.ToString(); } } return valueString.TrimEnd('\0'); } finally { if (key != null && key != rootKey) { key.Close(); } } } internal ServiceInformation(string machine_name, string name, SecurityDescriptor sd, IEnumerable<ServiceTriggerInformation> triggers, ServiceSidType sid_type, ServiceLaunchProtectedType launch_protected, IEnumerable<string> required_privileges, SafeStructureInOutBuffer<QUERY_SERVICE_CONFIG> config, bool delayed_auto_start) { Name = name; SecurityDescriptor = sd; Triggers = triggers; SidType = sid_type; LaunchProtected = launch_protected; RequiredPrivileges = required_privileges; if (config == null) { BinaryPathName = string.Empty; LoadOrderGroup = string.Empty; Dependencies = new string[0]; DisplayName = string.Empty; ServiceStartName = string.Empty; return; } var result = config.Result; ServiceType = result.dwServiceType; StartType = result.dwStartType; ErrorControl = result.dwErrorControl; BinaryPathName = result.lpBinaryPathName.GetString(); LoadOrderGroup = result.lpLoadOrderGroup.GetString(); TagId = result.dwTagId; Dependencies = result.lpLoadOrderGroup.GetMultiString(); DisplayName = result.lpDisplayName.GetString(); ServiceStartName = result.lpServiceStartName.GetString(); DelayedAutoStart = delayed_auto_start; MachineName = machine_name ?? string.Empty; ImagePath = string.Empty; ServiceDll = string.Empty; ServiceHostType = string.Empty; ServiceMain = string.Empty; // TODO: Maybe try and query using remote registry service? if (!string.IsNullOrEmpty(MachineName)) return; ImagePath = Win32Utils.GetImagePathFromCommandLine(BinaryPathName); using (RegistryKey key = OpenKeySafe(Registry.LocalMachine, $@"SYSTEM\CurrentControlSet\Services\{Name}")) { if (key != null) { UserName = ReadStringFromKey(key, null, "ObjectName"); ServiceDll = ReadStringFromKey(key, "Parameters", "ServiceDll"); if (string.IsNullOrEmpty(ServiceDll)) { ServiceDll = ReadStringFromKey(key, null, "ServiceDll"); } if (!string.IsNullOrEmpty(ServiceDll)) { string[] args = Win32Utils.ParseCommandLine(BinaryPathName); for (int i = 0; i < args.Length - 1; ++i) { if (args[i] == "-k") { ServiceHostType = args[i + 1]; break; } } ServiceMain = ReadStringFromKey(key, "Parameters", "ServiceMain"); if (string.IsNullOrEmpty(ServiceMain)) { ServiceMain = "ServiceMain"; } } if (key.GetValue("SvcHostSplitDisable") is int disable) { SvcHostSplitDisabled = disable != 0; } } } } internal ServiceInformation(string machine_name, string name) : this(machine_name, name, null, new ServiceTriggerInformation[0], ServiceSidType.None, ServiceLaunchProtectedType.None, new string[0], null, false) { } } #pragma warning restore }
using CapstoneTravelApp.DatabaseTables; using CapstoneTravelApp.HelperFolders; using CapstoneTravelApp.TripsFolder; using SQLite; using System; using System.Collections.ObjectModel; using System.Linq; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace CapstoneTravelApp.AdminFolder { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class AddAdminPage : ContentPage { UserHelper helper = new UserHelper(); private SQLiteConnection conn; public AddAdminPage() { InitializeComponent(); emailEntry.ReturnCommand = new Command(() => userNameEntry.Focus()); userNameEntry.ReturnCommand = new Command(() => passwordEntry.Focus()); passwordEntry.ReturnCommand = new Command(() => confirmPasswordEntry.Focus()); conn = DependencyService.Get<ITravelApp_db>().GetConnection(); } private async void RegisterButton_Clicked(object sender, EventArgs e) { if ((string.IsNullOrWhiteSpace(userNameEntry.Text)) || (string.IsNullOrWhiteSpace(passwordEntry.Text)) || (string.IsNullOrWhiteSpace(emailEntry.Text))) { await DisplayAlert("Warning", "All fields are required", "Ok"); } else if (!string.Equals(passwordEntry.Text, confirmPasswordEntry.Text)) { await DisplayAlert("Warning", "Passwords don't match", "Ok"); passwordEntry.Text = string.Empty; confirmPasswordEntry.Text = string.Empty; } else { var admin = new Admin_Table(); conn.CreateTable<Admin_Table>(); admin.AdminEmail = emailEntry.Text; admin.AdminUserName = userNameEntry.Text; admin.AdminPassword = passwordEntry.Text; var returnValue = helper.AddAdmin(userNameEntry.Text); if (returnValue) { conn.Insert(admin); await DisplayAlert("Success!", "New admin created", "Ok"); await Navigation.PopAsync(); } else { await DisplayAlert("Failure", "That Admin Username already exists", "OK"); warningLabel.IsVisible = false; emailEntry.Text = string.Empty; userNameEntry.Text = string.Empty; passwordEntry.Text = string.Empty; confirmPasswordEntry.Text = string.Empty; } } } } }
//using System; //using System.Collections.Generic; //using System.Linq; //using System.Net.Http; //using System.Net.Http.Headers; //using System.Web; // public class WebApiClient<T> // { // public HttpClient client = new HttpClient(); // public WebApiClient() // { // client.BaseAddress = new Uri("http://localhost:62387/"); // client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); // } // public List<T> GetAll(String requestUrl) // { // var response = client.GetAsync(requestUrl).Result; // if (response.IsSuccessStatusCode) // { // var students = response.Content.ReadAsAsync<List<T>>().Result; // return students; // } // return null; // } // public T GetOne(String requestUrl) // { // var response = client.GetAsync(requestUrl).Result; // if (response.IsSuccessStatusCode) // { // var student = response.Content.ReadAsAsync<T>().Result; // return student; // } // return default(T); // } // public List<T> Post(String requestUrl, object data) // { // var response = client.PostAsJsonAsync(requestUrl, data).Result; // if (response.IsSuccessStatusCode) // { // var students = response.Content.ReadAsAsync<List<T>>().Result; // return students; // } // return null; // } // public bool Put(String requestUrl, object data) // { // var response = client.PutAsJsonAsync(requestUrl, data).Result; // if (response.IsSuccessStatusCode) // { // //var students = response.Content.ReadAsAsync<List<Student>>().Result; // //return students; // return true; // } // //return null; // return false; // } // public List<T> Delete(String requestUrl) // { // var response = client.DeleteAsync(requestUrl).Result; // if (response.IsSuccessStatusCode) // { // var students = response.Content.ReadAsAsync<List<T>>().Result; // return students; // } // return null; // } // }
using System; using System.Collections.Generic; using System.Text; using JabberPoint.Domain.Helpers; namespace JabberPoint.Domain.Themes { /// <summary> /// interface for style class /// </summary> public interface IStyle { /// <summary> /// determines the font or font-family used by this style /// </summary> string Font { get; } /// <summary> /// determines the text color used by this style /// </summary> string FontColor { get; } /// <summary> /// determines whether the text is shown in italics or not /// </summary> FontStyle FontStyle { get; } /// <summary> /// determines whether the text is bold or not /// </summary> FontWeight FontWeight { get; } /// <summary> /// determines the size of the text /// </summary> int FontSize { get; } /// <summary> /// determines the position of the text (left, right, center) /// </summary> Alignment TextAlign { get; } /// <summary> /// determines whether the text is underlined or not /// </summary> TextDecoration TextDecoration { get; } } /// <summary> /// A style is a set of rules that determines how a single piece of content is shown in a slideshow /// </summary> public class Style : IStyle { public string Font { get; set; } public string FontColor { get; set; } public FontStyle FontStyle { get; set; } public FontWeight FontWeight { get; set; } public int FontSize { get; set; } public Alignment TextAlign { get; set; } public TextDecoration TextDecoration { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Magnifinance.Models { public class Subject { public int SubjectID { get; set; } public int TeacherID { get; set; } public int CourseID { get; set; } public string Description { get; set; } public virtual Teacher Teacher { get; set; } public virtual Course Course { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace cn.bmob.io { public sealed class BmobDouble : BmobNumber<double> { public BmobDouble() : base() { } public BmobDouble(double value) : base(value) { } #region Implicit Conversions public static implicit operator BmobDouble(double data) { return new BmobDouble(data); } #endregion } }
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; namespace Simulator { public partial class SearchHistry : Form { private string filepath = "SearchHistry.csv"; private Encoding encode = Encoding.GetEncoding("shift_jis"); private csvReader cr; Form1 fm; public SearchHistry(Form1 fm) { InitializeComponent(); this.fm = fm; } private void SearchHistry_Load(object sender, EventArgs e) { cr = new csvReader(@filepath, encode); for(int i=0; i<cr.table.GetLength(0); i++){ dataGridView1.Rows.Add(cr.table[i,0],cr.table[i,1],cr.table[i,2],cr.table[i,3],cr.table[i,4],cr.table[i,5],cr.table[i,6],cr.table[i,7]); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { fm.setData(dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString(), dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString(), dataGridView1.Rows[e.RowIndex].Cells[3].Value.ToString(), dataGridView1.Rows[e.RowIndex].Cells[4].Value.ToString(), dataGridView1.Rows[e.RowIndex].Cells[5].Value.ToString(), dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString(), dataGridView1.Rows[e.RowIndex].Cells[7].Value.ToString()); this.Close(); } } }
using Microsoft.AspNet.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web.Mvc; using XRTTicket.ClassesHelper; using XRTTicket.BusinessModel; using XRTTicket.Contexts; using XRTTicket.DAO; using XRTTicket.Models; using XRTTicket.Models.Ticket; using System.Web; using System.IO; using XRTTicket.Models.Upload; namespace XRTTicket.Controllers.Ticket { public class TicketController : Controller { IUnitOfWork<ViewModelTicket> UnitOfTicket { get; set; } IUnitOfWork<Models.Ticket.Action> UnitOfTicketAction { get; set; } public TicketController() { this.UnitOfTicket = new TicketDao(); this.UnitOfTicketAction = new ActionDao(); } public ActionResult Index() { return View(); } #region AddTicket [Authorize] [HttpGet] public ActionResult NewTicket() { ViewBag.PriorityId = new SelectList(Permissions.PriorityUser(), "PriorityId", "PriorityLevel"); ViewBag.TicketTypeId = new SelectList(Repository._ticketType, "TicketTypeId", "TicketTypeName"); ViewBag.ProductId = new SelectList(Repository._product_list, "ProductId", "Name"); ViewBag.SubProductId = new SelectList(new List<SubProduct>(), "SubProductId", "Name"); ViewBag.TaskId = new SelectList(new List<Task>(), "TaskId", "Name"); ViewBag.VersionId = new SelectList(new List<Models.Ticket.Version>(), "VersionId", "VersionName"); ViewBag.NextTicket = Convert.ToInt32(UnitOfTicket.Next()); return View(); } [Authorize] [HttpPost] [ValidateAntiForgeryToken] public ActionResult SaveTicket(Models.Ticket.ViewModelTicket ticket, string description, HttpPostedFileBase file) { if (ModelState.IsValid) { ticket.TicketId = Convert.ToInt32(UnitOfTicket.Next()); ticket.OpenDateAndTime = DateTime.Now.ToLocalTime(); ticket.UserId = User.Identity.GetUserName(); var user = (System.Security.Claims.ClaimsIdentity)User.Identity; ticket.CompanyId = Convert.ToInt32( user.FindFirstValue("CompanyId")); ticket.StatusId = 1; var ret = Repository._priorityTime.Where(x => x.PriorityId == ticket.PriorityId) .Select(x => x.SlaTime).FirstOrDefault(); ticket.SlaExpiration = CalculateSla.AddWithinWorkingHours(ticket.OpenDateAndTime, TimeSpan.FromHours(ret ), 9, 8); this.UnitOfTicket.Save(ticket); // Chech if exists files var path = string.Empty; if(file != null) { path = UploadAndDownload.Upload(file, ticket.TicketId); } var actions = new Models.Ticket.Action { TicketId = ticket.TicketId, ActionDescription = description, StatusId = ticket.StatusId, Date = DateTime.Now.ToLocalTime(), AlteredBy = User.Identity.Name, SendToUser = true, SlaRest = TimeSpan.FromHours( Repository._priorityTime .Where(x => x.PriorityId == ticket.PriorityId) .Select(x => x.SlaTime).FirstOrDefault()), Files = path, IterationId = 1 }; this.UnitOfTicketAction.Save(actions); //return RedirectToAction(nameof(NewTicket)); if (User.IsInRole("User") || User.IsInRole("SuperUser")) { return RedirectToAction(nameof(MyTickets)); } else { return RedirectToAction(nameof(TicketList)); } } else{ return View(nameof(NewTicket), ticket); } } [HttpPost] public ContentResult UploadFiles(int ticketId) { var r = new List<UploadFilesResult>(); foreach (string file in Request.Files) { HttpPostedFileBase hpf = Request.Files[file] as HttpPostedFileBase; if (hpf.ContentLength == 0) continue; //"~/App_Data/Uploads/Tickets/" //string savedFileName = Path.Combine(Server.MapPath("~/App_Data"), Path.GetFileName(hpf.FileName)); //string path = "~/App_Data/Uploads/Tickets/"+ticketId.ToString(); var path = "C:/Users/lorran.palmeira/Source/Repos/XRTTicket/XRTTicket/App_Data/Uploads/Tickets/" + ticketId.ToString(); //var path = "C:/Users/lorran.palmeira/Downloads/Arquivos/" + ticketId.ToString() +"/"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); string savedFileName = Path.Combine(Server.MapPath("~/App_Data/Uploads/Tickets/"+ticketId.ToString()), Path.GetFileName(hpf.FileName)); hpf.SaveAs(savedFileName); var actions = new Models.Ticket.Action { TicketId = ticketId, ActionDescription = "Sucess UpLoaded file by " + User.Identity.Name + " " + DateTime.Now.ToLocalTime(), Date = DateTime.Now.ToLocalTime(), StatusId = UnitOfTicket.Where(x => x.TicketId == ticketId).Select(x => x.StatusId).FirstOrDefault(), PriorityId = UnitOfTicket.Where(x => x.TicketId == ticketId).Select(x => x.PriorityId).FirstOrDefault(), AlteredBy = User.Identity.Name, SendToUser = true, Files = path +"/"+ hpf.FileName, IterationId = UnitOfTicketAction.Where(x => x.TicketId == ticketId).Max(x => x.IterationId) + 1 }; UnitOfTicketAction.Save(actions); /* r.Add(new UploadFilesResult() { Name = hpf.FileName, Length = hpf.ContentLength, Type = hpf.ContentType }); */ } return Content("{\"name\":\"" + r[0].Name + "\",\"type\":\"" + r[0].Type + "\",\"size\":\"" + string.Format("{0} bytes", r[0].Length) + "\"}", "application/json"); //return Json("Sucess",JsonRequestBehavior.AllowGet); } [Authorize] public JsonResult SaveTicketAjaxUpdate(ViewModelTicket ticket, string description, bool SendToUser, HttpPostedFileBase file) { var diff = TimeSpan.Zero; var diffTime = 0.0; var lastStatus = UnitOfTicketAction.Where(x => x.TicketId == ticket.TicketId) .OrderByDescending(x => x.IterationId) .Select(x => x.StatusId).FirstOrDefault(); if (ticket.StatusId == 6 || ticket.StatusId == 7 && lastStatus != 6 && lastStatus != 7) { ticket.ClosedDateTime = DateTime.Now.ToLocalTime(); } else if (ticket.StatusId == 3 || ticket.StatusId == 4 || ticket.StatusId == 5 && lastStatus != 3 && lastStatus != 4 && lastStatus != 5) { var sla = new CalculateSla(); var TotalTime = sla.SlaRestTime(ticket.TicketId); var time = CalculateSla.SubtractWithinWorkingHours(DateTime.Now.ToLocalTime(), (int)TotalTime); ticket.SlaExpiration = CalculateSla.AddWithinWorkingHours(DateTime.Now.ToLocalTime(),TimeSpan.FromHours(time), 9, 8); /* var dateTicket = UnitOfTicket.Where(x => x.TicketId == ticket.TicketId) .Select(x => x.SlaExpiration).FirstOrDefault(); diffTime = dateTicket.Subtract(DateTime.Now.ToLocalTime()).TotalHours; CalculateSla.SubtractWithinWorkingHours(DateTime.Now.ToLocalTime(), (int)diffTime); */ } else if ( ticket.StatusId == 2 && lastStatus ==3 || lastStatus == 4 || lastStatus == 5) { var slaRest = UnitOfTicketAction.Where(x => x.TicketId == ticket.TicketId).OrderByDescending(x => x.IterationId).Select(x => x.SlaRest).FirstOrDefault(); //diff = slaRest; diffTime = slaRest.TotalHours; ticket.ClosedDateTime = DateTime.Now.ToLocalTime().Add(slaRest); } var path = string.Empty; if (file != null) { path = UploadAndDownload.Upload(file, ticket.TicketId); } //If Ticket exist then Update Ticket this.UnitOfTicket.Update(ticket, ticket.TicketId); var actions = new Models.Ticket.Action { TicketId = ticket.TicketId, ActionDescription = description, StatusId = ticket.StatusId, Date = DateTime.Now.ToLocalTime(), PriorityId = ticket.PriorityId, AlteredBy = User.Identity.Name, SendToUser = SendToUser, //SlaRest = TimeSpan.FromHours(diffTime), IterationId = UnitOfTicketAction.Where(x => x.TicketId == ticket.TicketId).Max(x => x.IterationId) + 1 }; if (!string.IsNullOrEmpty(description)) UnitOfTicketAction.Save(actions); return Json(new { actions, ticket }, JsonRequestBehavior.AllowGet ); } #endregion #region EditTicket public JsonResult DownloadFile(string path) { UploadAndDownload.Download(path); return Json(JsonRequestBehavior.AllowGet); } [Authorize] [Route("TicketUpdate/{id}")] public ActionResult TicketUpdate(int id) { var ticketId = id; var ticketIdResult = this.UnitOfTicket.GetById(ticketId); // var user = (System.Security.Claims.ClaimsIdentity)User.Identity; var company = Convert.ToInt32(user.FindFirstValue("CompanyId")); var roleUser = user.FindFirstValue("RoleName"); var userName = User.Identity.GetUserName(); // var subProduct = Repository._subproduct_list.Where(x => x.ProductId == ticketIdResult.ProductId); var task = Repository._task.Where(x => x.ProductId == ticketIdResult.ProductId && x.SubProductId == ticketIdResult.SubProductId); var version = Repository._patchlist.Where(x => x.ProductId == ticketIdResult.ProductId ); // List All User Role Analyst ViewBag.PriorityId = new SelectList(Repository._priority, "PriorityId", "PriorityLevel", ticketIdResult.PriorityId ); ViewBag.TicketTypeId = new SelectList(Repository._ticketType, "TicketTypeId", "TicketTypeName", ticketIdResult.TicketTypeId); ViewBag.ProductId = new SelectList(Repository._product_list, "ProductId", "Name", ticketIdResult.ProductId); ViewBag.SubProductId = new SelectList(subProduct, "SubProductId", "Name", ticketIdResult.SubProductId); ViewBag.TaskId = new SelectList(task, "TaskId", "Name", ticketIdResult.TaskId); ViewBag.VersionId = new SelectList(version, "VersionId", "VersionName", ticketIdResult.VersionId); ViewBag.StatusId = new SelectList(Repository._status, "StatusId", "StatusName",ticketIdResult.StatusId); var listUser = Repository.GetRolesToUsers("Analyst"); listUser.AddRange(Repository.GetRolesToUsers("SuperAnalyst")); ViewBag.UserId = new SelectList(listUser, "UserName", "UserName", !string.IsNullOrEmpty(ticketIdResult.AnalystDesignated) ? ticketIdResult.AnalystDesignated : null ); //List of Iterations var iterations = UnitOfTicketAction.Where(x => x.TicketId == ticketId). OrderByDescending(x => x.IterationId); var list = iterations.ToList(); ViewBag.Iterations = list; //Check If user has permission to acess TicketUpdate. if (ticketIdResult.UserId == user.GetUserName() || User.IsInRole("Analyst") || User.IsInRole("SuperAnalyst") || User.IsInRole("User") || User.IsInRole("SuperUser") && ticketIdResult.CompanyId == Convert.ToInt32( user.FindFirstValue("CompanyId"))) { return View(ticketIdResult); } return View("PageNotFound"); } public JsonResult LikeTicketAjax(string title, int ticketId) { var result = UnitOfTicket.Where(x => x.Title.Contains(title) && x.TicketId != ticketId ).Take(4); return Json( result, JsonRequestBehavior.AllowGet); } #endregion #region TicketList ListToPagination pagination = new ListToPagination(); [Authorize(Roles ="Analyst, SuperAnalyst")] public ActionResult TicketList() { //var list = UnitOfTicket.GetAll().ToList(); var list = pagination.ListItens(); ViewBag.QuantMaxLinhasPorPagina = 10; ViewBag.PaginaAtual = 1; //var quant = UnitOfTicket.GetAll().Count(); var quant = list.Count(); var difQuantPaginas = (quant % ViewBag.QuantMaxLinhasPorPagina) > 0 ? 1 : 0; ViewBag.QuantPages = (quant / ViewBag.QuantMaxLinhasPorPagina) + difQuantPaginas; return View(list); } public JsonResult GetListItens(int page, int sizePage) { var listItens = pagination.ListItens(); var result = (((page == 1 ? page = 0 : page-1) * sizePage)); var list = listItens.Skip(result ==0?result:result-1).Take(sizePage); return Json(list,JsonRequestBehavior.AllowGet); } [Authorize(Roles = "Analyst, SuperAnalyst")] public ActionResult Queue() { var userName = User.Identity.GetUserName(); var ticketClosedValid = Repository._status.Where(x => x.StatusId == 06).Select(x => x.StatusId).FirstOrDefault(); var ticketClosedInValid = Repository._status.Where(x => x.StatusId == 07).Select(x => x.StatusId).FirstOrDefault(); var list = UnitOfTicket.Where(x => x.StatusId != ticketClosedValid && x.StatusId != ticketClosedInValid && x.AnalystDesignated == userName) .ToList(); ViewBag.QuantMaxLinhasPorPagina = 10; ViewBag.PaginaAtual = 1; var quant = list.Count(); var difQuantPaginas = (quant % ViewBag.QuantMaxLinhasPorPagina) > 0 ? 1 : 0; ViewBag.QuantPages = (quant / ViewBag.QuantMaxLinhasPorPagina) + difQuantPaginas; //var list = UnitOfTicket.GetAll().ToList(); return View(list); } [Authorize(Roles = "User,SuperUser ")] public ActionResult MyTickets() { //var list = UnitOfTicket.GetAll().ToList(); var userName = User.Identity.GetUserName(); var list = UnitOfTicket.Where(x => x.UserId == userName && x.StatusId != 06 && x.StatusId != 07).ToList(); ViewBag.QuantMaxLinhasPorPagina = 10; ViewBag.PaginaAtual = 1; var quant = list.Count(); var difQuantPaginas = (quant % ViewBag.QuantMaxLinhasPorPagina) > 0 ? 1 : 0; ViewBag.QuantPages = (quant / ViewBag.QuantMaxLinhasPorPagina) + difQuantPaginas; return View(list); } [Authorize(Roles = "User,SuperUser ")] public ActionResult ClosedTickets() { //var list = UnitOfTicket.GetAll().ToList(); var userName = User.Identity.GetUserName(); var list = UnitOfTicket.Where(x => x.UserId == userName && x.StatusId == 06 || x.StatusId == 07).OrderByDescending(x => x.ClosedDateTime).Take(10).ToList(); ViewBag.QuantMaxLinhasPorPagina = 10; ViewBag.PaginaAtual = 1; var quant = list.Count(); var difQuantPaginas = (quant % ViewBag.QuantMaxLinhasPorPagina) > 0 ? 1 : 0; ViewBag.QuantPages = (quant / ViewBag.QuantMaxLinhasPorPagina) + difQuantPaginas; return View("MyTickets", list); } [Authorize(Roles ="SuperUser")] public ActionResult CompanyTickets() { //var list = UnitOfTicket.GetAll().ToList(); var company = UnitOfTicket.Where(x => x.UserId == User.Identity.GetUserName() && x.StatusId != 05 && x.StatusId != 06).Select(x => x.CompanyId).FirstOrDefault(); var list = UnitOfTicket.Where(x => x.CompanyId == company ).ToList(); return View(list); } #endregion #region SearchTicket public ActionResult SearchTicket() { var Status = Repository._status.ToList(); ViewBag.Status = Status; var designated = UnitOfTicket.Where(x => x.TicketId == x.TicketId).Select(x => x.AnalystDesignated).ToList(); ViewBag.Designated = Repository.GetRolesToUsers("Analyst").ToList(); ViewBag.OpenBy = Repository.GetAllUsers(); ViewBag.TicketType = Repository._ticketType.ToList(); ViewBag.Priority = Repository._priority.ToList(); ViewBag.Company = Repository.company.ToList(); return View(new List<ViewModelTicket>()); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult SearchTicket(ViewModelTicket ticket, DateTime? opendatefrom, DateTime? opendateto, DateTime? closedatefrom, DateTime? closedateto, string description) { ViewBag.QuantMaxLinhasPorPagina = 10; ViewBag.PaginaAtual = 1; var quant = ListItensSeachTicket(ticket, opendatefrom, opendateto, closedatefrom, closedateto, description).Count(); var difQuantPaginas = (quant % ViewBag.QuantMaxLinhasPorPagina) > 0 ? 1 : 0; ViewBag.QuantPages = (quant / ViewBag.QuantMaxLinhasPorPagina) + difQuantPaginas; var list = ListItensSeachTicket(ticket, opendatefrom, opendateto, closedatefrom, closedateto, description); return PartialView(@"/Views/Shared/Ticket/_PartialViewSearchTicketList.cshtml", list); } public List<ViewModelTicket> ListItensSeachTicket (ViewModelTicket ticket, DateTime? opendatefrom, DateTime? opendateto, DateTime? closedatefrom, DateTime? closedateto, string description) { var query = UnitOfTicket.Where(x => x.ProductId > 0); if (opendatefrom != null && opendateto != null) { query = query.Where(c => c.OpenDateAndTime >= opendatefrom && c.OpenDateAndTime.Date.AddHours(23).AddMinutes(59).AddSeconds(59) <= opendateto); } if (closedatefrom != null && closedateto != null) { query = query.Where(c => c.ClosedDateTime >= closedatefrom && c.ClosedDateTime <= closedateto.Value.AddHours(23).AddMinutes(59).AddSeconds(59)); } if (!string.IsNullOrEmpty(ticket.Title)) { query = query.Where(c => c.Title.Contains(ticket.Title)); } if (ticket.TicketId > 0) { query = query.Where(c => c.TicketId == ticket.TicketId); } if (ticket.StatusId > 0) { query = query.Where(c => c.StatusId == ticket.StatusId); } if (ticket.IdExternal > 0) { query = query.Where(c => c.IdExternal == ticket.IdExternal); } if (ticket.TicketTypeId > 0) { query = query.Where(c => c.TicketTypeId == ticket.TicketTypeId); } if (ticket.CompanyId > 0) { query = query.Where(c => c.CompanyId == ticket.CompanyId); } if (ticket.PriorityId > 0) { query = query.Where(c => c.PriorityId == ticket.PriorityId); } if (!string.IsNullOrEmpty(description)) { query = query.Where(c => c.Title.Contains(ticket.Title)); } if (!string.IsNullOrEmpty(ticket.UserId)) { query = query.Where(c => c.UserId == ticket.UserId); } if (!string.IsNullOrEmpty(ticket.AnalystDesignated)) { query = query.Where(c => c.AnalystDesignated == ticket.AnalystDesignated); } if (User.IsInRole("User")) { query = query.Where(c => c.UserId == User.Identity.GetUserName()); } if (User.IsInRole("SuperUser")) { var user = (System.Security.Claims.ClaimsIdentity)User.Identity; var companyId = Convert.ToInt32(user.FindFirstValue("CompanyId")); query = query.Where(x => x.CompanyId == companyId); } var list = query.ToList(); return list; } public JsonResult GetListItensSeachTicket(int page, int sizePage) { /* var listItens = pagination.ListItens(); var result = (((page == 1 ? page = 0 : page-1) * sizePage)); var list = listItens.Skip(result ==0?result:result-1).Take(sizePage); return Json(list,JsonRequestBehavior.AllowGet); */ var ticket = new ViewModelTicket(); var listItens = ListItensSeachTicket(ticket, null, null,null,null, null); var result = (((page == 1 ? page = 0 : page - 1) * sizePage)); var list = UnitOfTicket.GetAll().Skip(result == 0 ? result : result - 1).Take(sizePage); return Json(list, JsonRequestBehavior.AllowGet); } #endregion } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("FriendListRecruitUI")] public class FriendListRecruitUI : MonoBehaviour { public FriendListRecruitUI(IntPtr address) : this(address, "FriendListRecruitUI") { } public FriendListRecruitUI(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void OnCancelButtonPressed(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnCancelButtonPressed", objArray1); } public void OnCancelPopupResponse(AlertPopup.Response response, object userData) { object[] objArray1 = new object[] { response, userData }; base.method_8("OnCancelPopupResponse", objArray1); } public bool OnCancelShown(DialogBase dialog, object userData) { object[] objArray1 = new object[] { dialog, userData }; return base.method_11<bool>("OnCancelShown", objArray1); } public void SetInfo(Network.RecruitInfo info) { object[] objArray1 = new object[] { info }; base.method_8("SetInfo", objArray1); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public FriendListUIElement m_CancelButton { get { return base.method_3<FriendListUIElement>("m_CancelButton"); } } public Network.RecruitInfo m_recruitInfo { get { return base.method_3<Network.RecruitInfo>("m_recruitInfo"); } } public UberText m_recruitText { get { return base.method_3<UberText>("m_recruitText"); } } public GameObject m_success { get { return base.method_3<GameObject>("m_success"); } } } }
namespace SimpleCryptography.Ciphers.ADFGVX.Key_Management { public class AdfgvxKeyManagement : IAdfgvxKeyManagement { public AdfgvxKey GenerateCipherKey(string memorableKey) { throw new System.NotImplementedException(); } public bool IsValidCipherKey(AdfgvxKey cipherKey) { throw new System.NotImplementedException(); } } }
using UnityEngine; using System.Collections; public class SwipeDetector : MonoBehaviour { private float fingerStartTime = 0.0f; private Vector2 fingerStartPos = Vector2.zero; private bool isSwipe = false; private float minSwipeDist = 50.0f; private float maxSwipeTime = 0.5f; private int latestAction; private bool debug = true; void Update () { if (Input.touchCount > 0 && latestAction == (int)SwipeDirection.NONE){ foreach (Touch touch in Input.touches) { switch (touch.phase) { case TouchPhase.Began : /* this is a new touch */ isSwipe = true; fingerStartTime = Time.time; fingerStartPos = touch.position; break; case TouchPhase.Canceled : /* The touch is being canceled */ isSwipe = false; break; case TouchPhase.Ended : float gestureTime = Time.time - fingerStartTime; float gestureDist = (touch.position - fingerStartPos).magnitude; if (isSwipe && gestureTime < maxSwipeTime && gestureDist > minSwipeDist){ Vector2 direction = touch.position - fingerStartPos; Vector2 swipeType = Vector2.zero; if (Mathf.Abs(direction.x) > Mathf.Abs(direction.y)){ // the swipe is horizontal: swipeType = Vector2.right * Mathf.Sign(direction.x); }else{ // the swipe is vertical: swipeType = Vector2.up * Mathf.Sign(direction.y); } if(swipeType.x != 0.0f){ if(swipeType.x > 0.0f){ latestAction = (int)SwipeDirection.RIGHT; }else{ latestAction = (int)SwipeDirection.LEFT; } } if(swipeType.y != 0.0f ){ if(swipeType.y > 0.0f){ latestAction = (int)SwipeDirection.UP; }else{ latestAction = (int)SwipeDirection.DOWN; } } } break; } } } if(debug == true && latestAction == (int)SwipeDirection.NONE) { if(Input.GetKeyDown(KeyCode.LeftArrow) == true) latestAction = (int)SwipeDirection.LEFT; if(Input.GetKeyDown(KeyCode.RightArrow) == true) latestAction = (int)SwipeDirection.RIGHT; if(Input.GetKeyDown(KeyCode.UpArrow) == true) latestAction = (int)SwipeDirection.UP; if(Input.GetKeyDown(KeyCode.DownArrow) == true) latestAction = (int)SwipeDirection.DOWN; } } public int GetLatestAction() { return latestAction; } public void FlushLatestAction() { latestAction = (int)SwipeDirection.NONE; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Task 3 namespace Is_Seven { class Program { static void Main(string[] args) { Console.Write("Enter n: "); int n = int.Parse(Console.ReadLine()); int thirdDigit = (n / 100) % 10; bool isSeven = (thirdDigit == 7); Console.WriteLine(isSeven); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /*public class RobotmagnetismScript : MonoBehaviour { public bool Positive; public bool Negative; public PointEffector2D velocityPositive; public PointEffector2D velocityNegative; public ChildColliderScript pointing; public ChildColliderScript pointing2; public GameObject leftArm; public GameObject rightArm; private void Start() { //pointing.x = hue; leftArm.SetActive(true); rightArm.SetActive(true); } void Update() { if (Negative == true && pointing.x ==1) { velocityPositive.forceMagnitude = -30.0f; } else if (Negative == false || pointing.x < 1) { velocityPositive.forceMagnitude = 0.0f; } if (Positive == true && pointing2.x == 1) { velocityPositive.forceMagnitude = 30.0f; } if (Positive == true && pointing2.x == 2) { velocityNegative.forceMagnitude = -30.0f; } else if (Positive == false || pointing2.x < 2) { velocityNegative.forceMagnitude = 0.0f; } if (Negative == true && pointing.x == 2) { velocityNegative.forceMagnitude = 30.0f; } //else if (Positive == false) //{ // //velocity.forceMagnitude = 0.0f; //} Debug.Log(pointing2.x); } void OnTriggerEnter2D(Collider2D other) { if (other.gameObject.tag == "Positive") { } } //void OnTriggerStay2D(Collider2D other) //{ // if (other.gameObject.tag == "Negative") // { // if (Negative == true) // { // velocity.forceMagnitude = 0.0f; // } // if (Positive == true) // { // velocity.forceMagnitude = 0.0f; // } // } //} }*/
using System; using System.Threading; using Castle.DynamicProxy; namespace Simpler.Tests.Core.Mocks { public class MockOverrideAttribute : OverrideAttribute { public override void ExecuteOverride(IInvocation execute) { ((MockTaskWithOverrideAttribute)execute.InvocationTarget).OverrideWasCalledTime = DateTime.Now; Thread.Sleep(100); execute.Proceed(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using umbraco.interfaces; using System.Web; using PackageActionsContrib.Helpers; using System.Xml; using umbraco.cms.businesslogic.packager.standardPackageActions; namespace PackageActionsContrib { public class SetAttributeValue : IPackageAction { public string Alias() { return "SetAttributeValue"; } public bool Execute(string packageName, System.Xml.XmlNode xmlData) { //Set result default to false bool result = false; //The config file we want to modify string configFileName = VirtualPathUtility.ToAbsolute(XmlHelper.GetAttributeValueFromNode(xmlData, "file")); //Xpath expression to determine the rootnode string xPath = XmlHelper.GetAttributeValueFromNode(xmlData, "xpath"); //Xpath expression to determine the attributeName we want to select string attributeName = XmlHelper.GetAttributeValueFromNode(xmlData, "attributeName"); //Xpath expression to determine the attributeValue we want to select string attributeValue = XmlHelper.GetAttributeValueFromNode(xmlData, "attributeValue"); //Open the config file XmlDocument configDocument = umbraco.xmlHelper.OpenAsXmlDocument(configFileName); //Select rootnode using the xpath XmlNode rootNode = configDocument.SelectSingleNode(xPath); //If the rootnode != null continue if (rootNode != null) { if (rootNode.Attributes[attributeName] == null) { //Attribute doesn't exists, create it and set the attribute value XmlAttribute att = umbraco.xmlHelper.addAttribute(configDocument, attributeName, attributeValue); rootNode.Attributes.Append(att); } else { //Set attribute value rootNode.Attributes[attributeName].Value = attributeValue; } //Save the modified document configDocument.Save(HttpContext.Current.Server.MapPath(configFileName)); result = true; } return result; } public System.Xml.XmlNode SampleXml() { string sample = "<Action runat=\"install\" undo=\"false\" alias=\"SetAttributeValue\" file=\"~/web.config\" xpath=\"//system.webServer/modules\" attributeName=\"runAllManagedModulesForAllRequests\" attributeValue=\"true\"/>"; return helper.parseStringToXmlNode(sample); } /// <summary> /// User RemoveXMLFragment action to uninstall. /// </summary> /// <param name="packageName">Name of the package.</param> /// <param name="xmlData">The XML data.</param> /// <returns></returns> public bool Undo(string packageName, System.Xml.XmlNode xmlData) { return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.HandTracking { internal class IdGenerator { private IList<int> usedIds = new List<int>(); public int GetNextId() { var nextId = 1; while (this.usedIds.Contains(nextId)) { nextId++; } this.usedIds.Add(nextId); return nextId; } public void Return(int id) { this.usedIds.Remove(id); } public void Clear() { this.usedIds.Clear(); } public void SetUsed(int id) { this.usedIds.Add(id); } } }
using UnityEngine; /// <summary> /// Controls input for mouse input and grabbing balls /// </summary> public class MouseInputGrabber : MonoBehaviour { public float FollowSpeed = 1; public float HoldingYPosition = 0.5f; private Transform _trackedObject; private const int GroundLayerMask = 1 << 8; private void Update() { CheckForMouseInput(); UpdateTrackedObject(); } private void CheckForMouseInput() { if (Input.GetMouseButtonDown(0) && _trackedObject == null) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.transform.CompareTag("Ball")) _trackedObject = hit.transform; } } if (Input.GetMouseButtonUp(0)) _trackedObject = null; } private void UpdateTrackedObject() { if (_trackedObject != null) { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast (ray, out hit, Mathf.Infinity, GroundLayerMask)) { var targetPos = new Vector3(hit.point.x, HoldingYPosition, hit.point.z); _trackedObject.position = Vector3.Lerp(_trackedObject.position, targetPos, FollowSpeed*Time.deltaTime); } } } }
using Castle.DynamicProxy; using CSRedis; using LinCms.Aop.Attributes; using LinCms.Middleware; using Newtonsoft.Json; using System; using System.Linq; using System.Threading.Tasks; namespace LinCms.Middleware { /// <summary> /// Aop /// </summary> public class AopCacheIntercept : IInterceptor { public AopCacheIntercept() { } public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 var cacheAttrObj = method.GetCustomAttributes(typeof(AopCacheAttribute), false).FirstOrDefault(); if (cacheAttrObj is AopCacheAttribute cacheAttr) { //获取自定义缓存键 var cacheKey = string.IsNullOrEmpty(cacheAttr.CacheKey) ? GenerateCacheKey(invocation) : cacheAttr.CacheKey; //注意是 string 类型,方法GetValue var cacheValue = RedisHelper.Get(cacheKey); if (cacheValue != null) { //将当前获取到的缓存值,赋值给当前执行方法 var type = invocation.Method.ReturnType; var resultTypes = type.GenericTypeArguments; if (type.FullName == "System.Void") return; object response; if (type != null && typeof(Task).IsAssignableFrom(type)) { //返回Task<T> if (resultTypes.Count() > 0) { var resultType = resultTypes.FirstOrDefault(); dynamic temp = JsonConvert.DeserializeObject(cacheValue, resultType); response = Task.FromResult(temp); } else //Task 无返回方法 指定时间内不允许重新运行 response = Task.Yield(); } else response = Convert.ChangeType(RedisHelper.Get<object>(cacheKey), type); invocation.ReturnValue = response; return; } //去执行当前的方法 invocation.Proceed(); //存入缓存 if (!string.IsNullOrWhiteSpace(cacheKey)) { object response; var type = invocation.Method.ReturnType; if (type != null && typeof(Task).IsAssignableFrom(type)) { var resultProperty = type.GetProperty("Result"); response = resultProperty.GetValue(invocation.ReturnValue); } else response = invocation.ReturnValue; if (response == null) response = string.Empty; RedisHelper.SetAsync(cacheKey, response, exists: cacheAttr.AbsoluteExpires); } } else invocation.Proceed();//直接执行被拦截方法 } //自动生成缓存键 private string GenerateCacheKey(IInvocation invocation) { var typeName = invocation.TargetType.Name; var methodName = invocation.Method.Name; var methodArguments = invocation.Arguments.ToList(); string key = $"{typeName}:{methodName}:"; string parms = string.Empty; int hashCode = methodName.GetHashCode(); foreach (var param in methodArguments) { if (param is string || param is int || param is long) parms += param.ToString(); else if (param is object) parms += JsonConvert.SerializeObject(param).GetHashCode(); else if (param != null) parms += hashCode ^ param.GetHashCode(); } return string.Concat(key, parms); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Shapes; namespace SLApp { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { ServiceReference1.TestClient client = new ServiceReference1.TestClient(); client.EchoCompleted += new EventHandler<ServiceReference1.EchoCompletedEventArgs>(client_EchoCompleted); client.EchoAsync("Hello world"); this.AddToDebug("Called the service"); } void client_EchoCompleted(object sender, ServiceReference1.EchoCompletedEventArgs e) { this.AddToDebug("Service replied: {0}", e.Result); } void AddToDebug(string text, params object[] args) { if (args != null && args.Length > 0) { text = string.Format(text, args); } this.txtDebug.Text = this.txtDebug.Text + text + Environment.NewLine; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; public class Castle : MonoBehaviour, ISelectable { public float Integrity { get { return _integrity; } set { _integrity = value; if (_integrity > _maxIntegrity) { _integrity = _maxIntegrity; } if (_integrity < 0) { GameManager.GameOver(); } GameManager.Instance.UpdateCastleIntegrityUI(_integrity); } } private float _integrity; private float _maxIntegrity = 1f; void Start() { Integrity = _maxIntegrity; } public void DisplayHeroOnUI(Hero hero) { GameManager.Instance.KingdomCastleUI.DisplayHero(hero); } public void Select() { GameManager.Instance.KingdomCastleUI.Select(); } public void Deselect() { GameManager.Instance.KingdomCastleUI.Deselect(); } }
using Godot; using Godot.Collections; public class Turret : Node2D { [Export] public string bulletPath = "res://Scenes/Turrets/Bullet.tscn"; [Export] public float fireOffset = 0.1f; private int fireIndex = 0; private Array<Node2D> firePoints; private Timer fireTimer; private RandomNumberGenerator random; private Station parent; public override void _Ready() { parent = (Station)GetParent().GetParent(); fireTimer = (Timer)GetNode("TimerFire"); random = new RandomNumberGenerator(); firePoints = new Array<Node2D>(); foreach(Node node in GetNode("firePoints").GetChildren()) firePoints.Add((Node2D)node); } public override void _Process(float delta) { LookAtMouse(); if (Input.IsActionJustPressed("fire")) { fireTimer.Start(); } else if (Input.IsActionJustReleased("fire")) { fireTimer.Stop(); } } protected void LookAtMouse() { Vector2 mousePosition = GetGlobalMousePosition(); LookAt(mousePosition); } protected Bullet GetBullet(Vector2 position) { var bulletScene = GD.Load<PackedScene>(bulletPath); Bullet bullet = (Bullet)bulletScene.Instance(); GetTree().Root.AddChild(bullet); bullet.GlobalPosition = position; return bullet; } public void _Fire() { Bullet bullet = GetBullet(newSpawnPoint()); Vector2 offset = new Vector2(random.RandfRange(-fireOffset, fireOffset), random.RandfRange(-fireOffset, fireOffset)); bullet.setTarget((GetGlobalMousePosition() - this.GlobalPosition).Normalized() + offset, parent.GetLinearVelocity()); } private Vector2 newSpawnPoint() { fireIndex++; fireIndex %= firePoints.Count; return firePoints[fireIndex].GlobalPosition; } public void RemoveTurret() { QueueFree(); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; namespace WallPaperChangerV2 { [Serializable] public class StoreLoadFiles { string fileLocation; bool isRandom; bool dualScreen; double timeInMinutes; public StoreLoadFiles(string FileLocation, bool IsRandom, double TimeInMinutes) { this.FileLocation = FileLocation; this.IsRandom = IsRandom; this.TimeInMinutes = TimeInMinutes; } public string FileLocation { get { return fileLocation; } set { fileLocation = value; } } public bool IsRandom { get { return isRandom; } set { isRandom = value; } } public double TimeInMinutes { get { return timeInMinutes; } set { if(value <= 0) { timeInMinutes = 1; return; } timeInMinutes = value; } } public static void Store(string fileName, object userData) { BinaryFormatter binFormat = new BinaryFormatter(); Stream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None); binFormat.Serialize(stream, userData); stream.Close(); } public static object Load(string fileName) { if (!File.Exists(fileName)) { throw new ArgumentException("File not found!"); } BinaryFormatter binFormat = new BinaryFormatter(); Stream instream = File.OpenRead(fileName); object obj = binFormat.Deserialize(instream); instream.Close(); return obj; } } }
using System; namespace Tasks { public static class UVersion { public static int CompareVersions(string v1, string v2) { var versions1 = v1.Split('.'); var versions2 = v2.Split('.'); var len1 = versions1.Length; var len2 = versions2.Length; var max_len = Math.Max(len1, len2); for (int i = 0; i < max_len; ++i) { var fst = i < len1 ? int.Parse(versions1[i]) : 0; var snd = i < len2 ? int.Parse(versions2[i]) : 0; if (fst > snd) return 1; if (fst < snd) return -1; } return 0; } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using VocabularyApi.Dtos; using VocabularyApi.Models; namespace VocabularyApi.Services.Training.Abstractions { public interface ITrainingService<out QuestionDto> { Task<IEnumerable<UserVocabularyWordDto>> GetUserWordAsync(Guid userId, bool isReverseTraining, int wordsCount = 10); Task<IEnumerable<UserVocabularyWordDto>> GetUserWordAsync(Guid userId, IEnumerable<int> wordsId, bool isReverseTraining); IEnumerable<QuestionDto> GetQuestions(IEnumerable<UserVocabularyWordDto> words); } }
using MaterialSurface; using System; using System.Collections.Generic; using System.Drawing; using System.Runtime.InteropServices; using System.Threading.Tasks; using System.Windows.Forms; using TutteeFrame2.DataAccess; using TutteeFrame2.Model; using TutteeFrame2.Utils; namespace TutteeFrame2.View { public partial class OneTeacherAssignmentView : Form { #region Win32 Form public const int WM_NCLBUTTONDOWN = 0xA1; public const int HT_CAPTION = 0x2; [DllImportAttribute("user32.dll")] public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam); [DllImportAttribute("user32.dll")] public static extern bool ReleaseCapture(); protected override CreateParams CreateParams { get { const int CS_DROPSHADOW = 0x20000; CreateParams cp = base.CreateParams; cp.ClassStyle |= CS_DROPSHADOW; return cp; } } #endregion public bool success = false; public string classID; Teacher runnerTeacher = new Teacher(); Dictionary<string, Teaching> teachingSem1 = new Dictionary<string, Teaching>(); Dictionary<string, Teaching> teachingSem2 = new Dictionary<string, Teaching>(); Class _class = new Class(); public OneTeacherAssignmentView(string _classID) { InitializeComponent(); classID = _classID; } protected async override void OnLoad(EventArgs e) { base.OnLoad(e); SetLoad(true, "Đang lấy thông tin lớp..."); await Task.Run(() => _class = ClassDA.Instance.GetClass(classID)); if (_class.FormalTeacherID != null) { runnerTeacher = await Task.Run(() => TeacherDA.Instance.GetTeacher(_class.FormalTeacherID)); txtFormTeacher.Text = runnerTeacher.ID + " | " + runnerTeacher.GetName(); } lbClassID.Text = string.Format("Lớp {0}", _class.ClassID); lbClassInfor.Text = string.Format("Phòng học: {0} - Sỉ số: {1}", _class.RoomNumber, _class.StudentNumber); SetLoad(true, "Đamg lấy danh sách môn học..."); List<Subject> subjects = new List<Subject>(); await Task.Run(() => subjects = SubjectDA.Instance.GetSubjects()); teachingSem1 = await Task.Run(() => TeachingDA.Instance.GetClassTeachings(classID, 1)); teachingSem2 = await Task.Run(() => TeachingDA.Instance.GetClassTeachings(classID, 2)); if (subjects != null) { for (int index = 0; index < subjects.Count; index++) { if (!teachingSem1.ContainsKey(subjects[index].ID)) { Teaching teaching = new Teaching() { ClassID = classID, Semester = 1, Subject = subjects[index], TeacherID = null, TeacherName = null, Editable = true, Year = DateTime.Now.Year, ID = "", }; teachingSem1.Add(subjects[index].ID, teaching); } if (!teachingSem2.ContainsKey(subjects[index].ID)) { Teaching teaching = new Teaching() { ClassID = classID, Semester = 2, Subject = subjects[index], TeacherID = null, TeacherName = null, Editable = true, Year = DateTime.Now.Year, ID = "", }; teachingSem2.Add(subjects[index].ID, teaching); } Add(index, subjects[index]); } } SetLoad(false); } void SetLoad(bool isLoading, string loadInformation = "") { lbInformation.Text = loadInformation; mainProgressbar.Visible = lbInformation.Visible = isLoading; txtFormTeacher.Enabled = materialTabControl1.Enabled = btnSubmit.Enabled = !isLoading; } void Add(int index, Subject subject) { MaterialTextfield textfield1 = new MaterialTextfield() { ReadOnly = true, Location = new Point(5, 20 + 55 * index), Width = 380, Tag = subject.ID, HintText = subject.Name, FieldType = BoxType.Outlined, ShowCaret = false, PrimaryColor = Color.FromArgb(47, 144, 176), TabStop = false, Style = MaterialTextfield.TextfieldStyle.HintAsFloatingLabel, Text = (teachingSem1[subject.ID].TeacherID != null) ? (teachingSem1[subject.ID].TeacherID + " | " + teachingSem1[subject.ID].TeacherName) : "", }; textfield1.Enter += OnChooseTeacher; textfield1.TextChanged += OnTeacherSet; MaterialCheckbox checkbox1 = new MaterialCheckbox() { Location = new Point(390, 35 + 55 * index), Text = "Khoá bảng điểm", Tag = subject.ID, PrimaryColor = Color.FromArgb(47, 144, 176), Checked = teachingSem1[subject.ID].Editable, }; checkbox1.CheckedChanged += OnChangeEditable; tbpgSem1.Controls.Add(textfield1); tbpgSem1.Controls.Add(checkbox1); MaterialTextfield textfield2 = new MaterialTextfield { ReadOnly = true, Location = new Point(5, 20 + 55 * index), Width = 380, Tag = subject.ID, HintText = subject.Name, FieldType = BoxType.Outlined, ShowCaret = false, PrimaryColor = Color.FromArgb(47, 144, 176), TabStop = false, Style = MaterialTextfield.TextfieldStyle.HintAsFloatingLabel, Text = (teachingSem2[subject.ID].TeacherID != null) ? (teachingSem2[subject.ID].TeacherID + " | " + teachingSem2[subject.ID].TeacherName) : "", }; textfield2.Enter += OnChooseTeacher; textfield2.TextChanged += OnTeacherSet; MaterialCheckbox checkbox2 = new MaterialCheckbox() { Location = new Point(390, 35 + 55 * index), Text = "Khoá bảng điểm", Tag = subject.ID, PrimaryColor = Color.FromArgb(47, 144, 176), Checked = teachingSem2[subject.ID].Editable, }; checkbox2.CheckedChanged += OnChangeEditable; tbpgSem2.Controls.Add(textfield2); tbpgSem2.Controls.Add(checkbox2); } private void OnChangeEditable(object sender, EventArgs e) { MaterialCheckbox checkbox = (MaterialCheckbox)sender; if (materialTabControl1.SelectedTab == tbpgSem1) { teachingSem1[checkbox.Tag.ToString()].Editable = checkbox.Checked; } else { teachingSem2[checkbox.Tag.ToString()].Editable = checkbox.Checked; } } private void OnTeacherSet(object sender, EventArgs e) { MaterialTextfield textfield = (MaterialTextfield)sender; if (materialTabControl1.SelectedTab == tbpgSem1) { teachingSem1[textfield.Tag.ToString()].TeacherID = (textfield.Text.Length > 0) ? textfield.Text.Split(new string[] { " | " }, StringSplitOptions.None)[0] : null; } else { teachingSem2[textfield.Tag.ToString()].TeacherID = (textfield.Text.Length > 0) ? textfield.Text.Split(new string[] { " | " }, StringSplitOptions.None)[0] : null; } } private void OnExit(object sender, EventArgs e) { this.Close(); } private void OnChooseTeacher(object sender, EventArgs e) { MaterialTextfield textfield = (MaterialTextfield)sender; string currentTeacher = (textfield.Text.Length > 0) ? textfield.Text : null; ChooseTeacherView frmChooseTeacher = new ChooseTeacherView(textfield.Tag.ToString(), textfield.HintText, currentTeacher); OverlayForm overlay = new OverlayForm(this, frmChooseTeacher, setChild: false); frmChooseTeacher.FormClosed += (s, ev) => { this.Activate(); btnSubmit.Focus(); if (!frmChooseTeacher.success) return; if (frmChooseTeacher.chosenTeacherID.Length > 0) textfield.Text = frmChooseTeacher.chosenTeacherID; else textfield.Text = ""; }; frmChooseTeacher.Show(); } private async void OnSubmit(object sender, EventArgs e) { SetLoad(true, "Đang cập nhật GVCN..."); _class.FormalTeacherID = (txtFormTeacher.Text.Length > 0) ? txtFormTeacher.Text.Split(new string[] { " | " }, StringSplitOptions.None)[0] : null; Class resultClass = await Task.Run(() => ClassDA.Instance.UpdateClassInfo(_class)); if (resultClass == null) { Dialog.Show(this, "Đã có vấn đề xảy ra. Vui lòng hử lại sau ít giây!", "Lỗi"); return; } SetLoad(true, "Đang cập nhật thông tin giảng dạy..."); foreach (KeyValuePair<string, Teaching> teaching in teachingSem1) { Teaching resultTeaching = await Task.Run(() => TeachingDA.Instance.UpdateTeaching(teaching.Value)); } foreach (KeyValuePair<string, Teaching> teaching in teachingSem2) { Teaching resultTeaching = await Task.Run(() => TeachingDA.Instance.UpdateTeaching(teaching.Value)); } success = true; SetLoad(false); this.Close(); } } }
using System.Collections.Generic; namespace Allvis.Kaylee.Validator.SqlServer.Models.DB { public class Schema { public string Name { get; set; } = string.Empty; public List<Table> Tables { get; } = new List<Table>(); } }
using Model.InvoiceManagement; using System; using System.Collections.Generic; using System.Linq; using System.Web; using Utility; using Uxnet.Com.Helper; namespace TaskCenter.Helper.Jobs { public class AllJobs { static AllJobs() { var jobList = JobScheduler.JobList; if (jobList == null || !jobList.Any(j => j.AssemblyQualifiedName == typeof(MatchAttachment).AssemblyQualifiedName)) { JobScheduler.AddJob(new JobItem { AssemblyQualifiedName = typeof(MatchAttachment).AssemblyQualifiedName, Description = "對應發票附件", Schedule = DateTime.Now }); } } public static void StartUp() { } } public class MatchAttachment : IJob { public void Dispose() { } public void DoJob() { Logger.Info($"MatchAttachment => {AttachmentManager.MatchAttachment()}"); } public DateTime GetScheduleToNextTurn(DateTime current) { return current.AddMinutes(5); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Data.SqlClient; using System.Windows.Forms; namespace RT_OPT { public partial class MainForm : Form { // Working with Orders private int SetDropOrderDB(int vTPId, string vAction, string vCode, string vOperation, string vQuoteHedge, float vPrice, int vQuantity, long vOrderNo = -1) { int vResult = -1; if (gConn.State == ConnectionState.Open) { SqlCommand vSqlCommand = new SqlCommand(string.Format("exec New_Transaction {0}, '{1}', '{2}', '{3}', '{4}', {5}, {6}, {7}", vTPId, vAction, vCode, vOperation, vQuoteHedge, vPrice.ToString().Replace(',', '.'), vQuantity, vOrderNo), gConn); SqlDataReader vReader = vSqlCommand.ExecuteReader(); while (vReader.Read()) vResult = Convert.ToInt32(vReader[0]); vReader.Close(); } return vResult; } private void SetOrder(int vTPId, string vCode, string vOperation, string vQuoteHedge, float vPrice, int vQuantity) { string vTriFileName = RT_OPT.Properties.Settings.Default.TriFile.ToString(); if (System.IO.File.Exists(vTriFileName)) { int vTransId = SetDropOrderDB(vTPId, "S", vCode, vOperation, vQuoteHedge, vPrice, vQuantity, -1); if (vTransId > 0) { string vSetOrderStr = string.Format(RT_OPT.Properties.Settings.Default.SetOrderStr, vTransId, vCode, vOperation, vPrice, vQuantity); FileLog("SetOrderStr = {0}", vSetOrderStr); System.IO.File.AppendAllText(vTriFileName, vSetOrderStr + "\r\n"); } } else FileLog("Tri file does not exists {0}", vTriFileName); } private void DropOrder(int vTPId, string vCode, long vOrderNo) { string vTriFileName = RT_OPT.Properties.Settings.Default.TriFile.ToString(); if (System.IO.File.Exists(vTriFileName)) { int vTransId = SetDropOrderDB(vTPId, "D", vCode, "", "", 0, 0, vOrderNo); if (vTransId > 0) { string vDropOrderStr = string.Format(RT_OPT.Properties.Settings.Default.DropOrderStr, vTransId, vCode, vOrderNo); FileLog("DropOrderStr = {0}", vDropOrderStr); System.IO.File.AppendAllText(vTriFileName, vDropOrderStr + "\r\n"); } } else FileLog("Tri file does not exists {0}", vTriFileName); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace oopsconcepts { public class Methodoverloading { //Method overloading allows a class to have multiple methods with the same name but with a different signature. //So, In C# functions can be overloaded based on the number,type(int, float etc) and kind //(value, Ref or Out) of parameters //The signature of a method consists of the name of the method and //the type, kind (value, reference, or output) and the number of its formal parameters. //The signature of a method does not include the return type and the params modifier. //So, it is not possible to overload a function, just based on the return type or params //modifier. public static void Main() { //number of parameters add(20, 30); add(20, 30, 40); //Kind of parameters mul(20, 30.5f); //Type of parameters int sum = 0; add(20, 30, ref sum); //sum added(10,20,out sum); Console.ReadKey(); } /// <summary> /// Number of parameters /// </summary> public static void add(int i, int j) { Console.WriteLine("sum of Two numbers is " + (i + j)); } public static void add(int i, int j, int k) { Console.WriteLine("sum of Three numbers is " + (i + j + k)); } /// <summary> /// Kind of Parameters /// </summary> public static void mul(int i, float j) { Console.WriteLine("Kind of Parameters Multiplication of two numbers " + i * j); } /// <summary> /// Type of Parameters /// </summary> public static void add(int i, int j, ref int k) { Console.WriteLine("Reference sum of Two numbers is " + (i + j)); k = (i + j); } public static void added(int i,int j,out int k) { Console.WriteLine("Reference sum of Two numbers is " + (i + j)); k = 20; } } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using BookStore.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using BookStore.Model; namespace BookStore.DAL.Tests { [TestClass()] public class BookDALTests { BookDAL bookDAL = new BookDAL(); [TestMethod()] public void AddBookTest() { Book book = new Book(65555, "看见", "柴静", 45, 12); Assert.AreEqual(1, bookDAL.AddBook(book)); } [TestMethod()] public void BookDeleteByinformationTest() { Assert.AreEqual(1, bookDAL.BookDeleteByinformation(65555, "看见", "柴静", 45, 12)); } [TestMethod()] public void UpdateBookTest() { Book book = new Book(25, "简爱", "愚见", 30, 12); Assert.AreEqual(1, bookDAL.UpdateBook(book)); } [TestMethod()] public void GetAllBooksTest() { List<Book> books = bookDAL.GetAllBooks(); Assert.AreEqual(19, books.Count); } [TestMethod()] public void SelectBooksTest() { //Assert.Fail(); List<Book> books = bookDAL.SelectBooks("JavaScript高级程序设计"); Assert.AreEqual(1, books.Count); } } }
#region New BSD License // // TryParsers - TryParse from .NET Framework done right // Copyright (c) 2012, Atif Aziz. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // - Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // - The names of its contributors may be used to endorse or promote // products derived from this software without specific prior written // permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED // TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A // PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER // OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #endregion namespace TryParsers { using System; static partial class TryParse { /// <summary> /// Creates and returns a function that returns the default value of /// <typeparamref name="T"/> whenever the supplied parser function /// throws an exception and the parsed value otherwise. /// </summary> public static Func<string, T> Make<T>(Func<string, T> parser) => Make(parser, default(T)); /// <summary> /// Creates and returns a function that returns a user-defined /// default value whenever the supplied parser function throws an /// exception and the parsed value otherwise. /// </summary> public static Func<string, T> Make<T>(Func<string, T> parser, T defaultValue) => Make(parser, _ => defaultValue); /// <summary> /// Creates and returns a function that returns the result of a /// parser function and the result of a second function if the /// parser function throws an exception. /// </summary> public static Func<string, T> Make<T>(Func<string, T> parser, Func<Exception, T> onError) => Make<T, Exception>(parser, onError); /// <summary> /// Creates and returns a function that returns the result of a /// parser function and the result of a second function if the /// parser function throws an exception of type /// <typeparamref name="TException"/>. Exceptions of any other type /// are propagated. /// </summary> public static Func<string, T> Make<T, TException>( Func<string, T> parser, Func<TException, T> onError) where TException : Exception { return input => { try { return parser(input); } catch (TException e) { return onError(e); } }; } /// <summary> /// Creates and returns a function that returns the result of a /// parser function and the result of a second or third function if /// the parser function throws an exception of type /// <typeparamref name="TException1"/> or /// <typeparamref name="TException2"/>, respectively. /// Exceptions of any other type are propagated. /// </summary> public static Func<string, T> Make<T, TException1, TException2>( Func<string, T> parser, Func<TException1, T> onError1, Func<TException2, T> onError2) where TException1 : Exception where TException2 : Exception { return input => { try { return parser(input); } catch (TException1 e) { return onError1(e); } catch (TException2 e) { return onError2(e); } }; } /// <summary> /// Creates and returns a function that returns the result of a /// parser function and the result of a second, third or fourth /// function if the parser function throws an exception of type /// <typeparamref name="TException1"/> or /// <typeparamref name="TException2"/> or /// <typeparamref name="TException3"/>, respectively. /// Exceptions of any other type are propagated. /// </summary> public static Func<string, T> Make<T, TException1, TException2, TException3>( Func<string, T> parser, Func<TException1, T> onError1, Func<TException2, T> onError2, Func<TException3, T> onError3) where TException1 : Exception where TException2 : Exception where TException3 : Exception { return input => { try { return parser(input); } catch (TException1 e) { return onError1(e); } catch (TException2 e) { return onError2(e); } catch (TException3 e) { return onError3(e); } }; } } }
using NetworkToolkit.Connections; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Xunit; namespace NetworkToolkit.Tests.Connections { public class MemoryConnectionFactoryTests : TestsBase { [Theory] [InlineData(false), InlineData(true)] public async Task Connect_Success(bool clientFirst) { await using ConnectionFactory factory = new MemoryConnectionFactory(); await using ConnectionListener listener = await factory.ListenAsync(); using var semaphore = new SemaphoreSlim(0); await RunClientServer(async () => { if (!clientFirst) { bool success = await semaphore.WaitAsync(10_000); Assert.True(success); } ValueTask<Connection> task = factory.ConnectAsync(listener.EndPoint!); if (clientFirst) semaphore.Release(); await using Connection connection = await task; }, async () => { if (clientFirst) { bool success = await semaphore.WaitAsync(10_000); Assert.True(success); } ValueTask<Connection?> task = listener.AcceptConnectionAsync(); if (!clientFirst) semaphore.Release(); await using Connection? connection = await task; Assert.NotNull(connection); }); } [Fact] public async Task Listener_DisposeCancelsConnect_Success() { await using ConnectionFactory factory = new MemoryConnectionFactory(); await using ConnectionListener listener = await factory.ListenAsync(); ValueTask<Connection> connectTask = factory.ConnectAsync(listener.EndPoint!); await listener.DisposeAsync(); SocketException ex = await Assert.ThrowsAsync<SocketException>(async () => { await using Connection connection = await connectTask; }).ConfigureAwait(false); Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode); } [Fact] public async Task Listener_DisposeCancelsAccept_Success() { await using ConnectionFactory factory = new MemoryConnectionFactory(); await using ConnectionListener listener = await factory.ListenAsync(); ValueTask<Connection?> acceptTask = listener.AcceptConnectionAsync(); await listener.DisposeAsync(); Connection? connection = await acceptTask; Assert.Null(connection); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SnakeGame { public class Food:GameElement { private Position SpawnSpaceMaximum { get; set; } private RandomGenerator RND { get; set; } public Food(IRenderer renderer, Position position, string color, Position spawn, RandomGenerator rand) :base(renderer, position, color) { this.RND = rand; this.SpawnSpaceMaximum = spawn; } public override void Draw() { this.Renderer.DrawAt(this.Position, this.Color); } public void Remove() { this.Renderer.DrawAt(this.Position, "Black"); } public void RandomPosition() { this.Position = new Position(RND.GetRandom(1, this.SpawnSpaceMaximum.Y - 2), RND.GetRandom(1, this.SpawnSpaceMaximum.X - 2)); } } }
using PDV.CONTROLER.Funcoes; using PDV.CONTROLLER.NFE.Impressao; using PDV.CONTROLLER.NFE.Transmissao; using PDV.CONTROLLER.NFE.Util; using PDV.VIEW.App_Context; using PDV.VIEW.FRENTECAIXA.Forms.PDV; using PDV.VIEW.FRENTECAIXA.Tasks; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.VIEW.Task { public class EmitirNFeTask : AsyncTask<TaskParams, string, TaskResult> { public override TaskResult DoInBackGround(TaskParams param) { try { decimal idnfe = param.GetDecimal("idnfe"); decimal idmovimentofiscal = param.GetDecimal("idmovimentofiscal"); /* Caso Tenha a Série e Númeração, Usar a Existente, caso não existe, gerar uma nova numeração e usar a série configurada. */ DAO.Entidades.NFe.NFe Nf = FuncoesNFe.GetNFe(idnfe); int NumeroNFe = idmovimentofiscal > 0 ? Convert.ToInt32(FuncoesMovimentoFiscal.GetMovimento(idmovimentofiscal).Numero) : PDV.DAO.DB.Utils.Sequence.GetNextID(Contexto.CONFIGURACAO_SERIE.NomeSequenceNFe); EventosNFe Ev = new EventosNFe(Nf, Nf.Serie, NumeroNFe, idmovimentofiscal); Ev.CaminhoSolution = Contexto.CaminhoSolution; UpdateProgress("Emitindo NFe"); RetornoTransmissaoNFe Retorno = Ev.TransmitirNFe(); if(Retorno.isAutorizada) { UpdateProgress("NFe AUtorizada com sucesso!"); } else { UpdateProgress(""+ Retorno.MotivoErro); } return new TaskResult() .SetValue("Result", Retorno.isAutorizada) .SetValue("Msg", Retorno.MotivoErro) .SetValue("idmovimentofiscal",Retorno.IDMovimentoFiscal); } catch (Exception Ex) { UpdateProgress($"Erro: \n {Ex.Message}"); return new TaskResult() .SetValue("Result", false) .SetValue("Msg", Ex.Message); } } public override void OnPostExecute(TaskResult result) { gPDV_ProgressoNFe.Close(); } GPDV_ProgressoNFe gPDV_ProgressoNFe; public override void OnPreExecute() { gPDV_ProgressoNFe = new GPDV_ProgressoNFe(); gPDV_ProgressoNFe.TopMost = false; gPDV_ProgressoNFe.Show(); } public override void OnProgressUpdate(string progress) { gPDV_ProgressoNFe.PublicaProgresso(progress); } } }
using System; using System.Xml; using System.Collections.Specialized; using System.Configuration; namespace Config { /// <summary> /// Summary description for DBConfig. /// </summary> public class BasicConfiguration { protected static BasicConfiguration _configuration = new BasicConfiguration(); protected NameValueCollection _values; protected BasicConfiguration() { // // TODO: Add constructor logic here // initializeNameValueSettings(); } private void initializeNameValueSettings() { // _values = (NameValueCollection)System.Configuration.ConfigurationManager.GetSection("appParams"); _values = ConfigurationManager.AppSettings; } public static BasicConfiguration Values { get { return _configuration; } } public string this[int index] { get { return _values[index]; } } public string this[string name] { get { return _values[name]; } //set //{ // _values.Add(name, value); //} } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using FrbaCommerce.Modelo; using FrbaCommerce.Conexion; using System.Data.SqlClient; using System.Data; namespace FrbaCommerce.DAO { class DaoRubro { private static List<Rubro> rubros; public DaoRubro() { } public static Rubro getRubro(Decimal p_idRubro) { if (rubros == null) { DaoRubro.getRubros(); } Rubro rubro = rubros.Find(x => x.idRubro == p_idRubro); return rubro; } static public List<Rubro> getRubrosPorPublicacion(Decimal p_idPublicacion) { if (rubros == null) { DaoRubro.getRubros(); } List<Rubro> rubrosPorPublicacion = new List<Rubro>(); String query = "select * from dd.Publicacion_Rubro"+ "where id_publicacion = " + p_idPublicacion; SqlConnection conn = DBConexion.getConn(); SqlCommand sql = new SqlCommand(query, conn); SqlDataReader rs = sql.ExecuteReader(); while (rs.Read()) { if (!rs.IsDBNull(0)) { Decimal idRubroPublicacion = rs.GetDecimal(rs.GetOrdinal("id_rubro")); rubrosPorPublicacion.Add(rubros.Find(x => x.idRubro == idRubroPublicacion)); } } conn.Close(); return rubrosPorPublicacion; } static public List<Rubro> getRubros() { if (rubros != null) { return rubros; } rubros = new List<Rubro>(); String query = "select * from dd.rubro"; SqlConnection conn = DBConexion.getConn(); SqlCommand sql = new SqlCommand(query, conn); SqlDataReader rs = sql.ExecuteReader(); while (rs.Read()) { if (!rs.IsDBNull(0)) { Rubro rubro = new Rubro(); rubro.idRubro = rs.GetDecimal(rs.GetOrdinal("id_rubro")); rubro.codigo = rs.GetDecimal(rs.GetOrdinal("codigo")); rubro.descripcion = rs.GetString(rs.GetOrdinal("decripcion")); rubros.Add(rubro); } } conn.Close(); return rubros; } } }
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreLocation; namespace LondonBike { public class Application { static void Main (string[] args) { UIApplication.Main (args); } } // The name AppDelegate is referenced in the MainWindow.xib file. public partial class AppDelegate : UIApplicationDelegate { public UITabBarController tabBar; public UIView MainView; public UIViewController[] tabControllers; public NearDialogViewController near; public MapViewController map; public TimerViewController timer; public TripLogViewController tripLog; public InfoViewController infoPage; public void SetFocusOnLocation(BikeLocation bike) { UIView.BeginAnimations("foo"); UIView.SetAnimationDuration(1); tabBar.SelectedIndex = 1; UIView.SetAnimationTransition(UIViewAnimationTransition.None, tabBar.View, true); UIView.CommitAnimations(); map.FocusOnLocation(bike); } public override void WillEnterForeground (UIApplication application) { Util.Log("WillEnterForeground"); Appirator.AppLaunched(); Analytics.AppLaunched(); } public override void DidEnterBackground (UIApplication application) { Util.Log("Did enter background"); Analytics.Dispatch(); } public override void FinishedLaunching (UIApplication application) { Util.Log("In FinishedLaunching(application)"); } // This method is invoked when the application has loaded its UI and its ready to run public override bool FinishedLaunching (UIApplication app, NSDictionary options) { // If you have defined a view, add it here: // window.AddSubview (navigationController.View); //TripLog.MakeDummyData(); Util.Log("In finished launching (with options)"); bool localNotification = false; if (options != null) { if (Util.IsIOS4OrBetter) { UILocalNotification localNotif = (UILocalNotification)options.ObjectForKey(UIApplication.LaunchOptionsLocalNotificationKey); if (localNotif != null) { localNotification = true; } } } Util.LogStartup(); var bikes = BikeLocation.AllBikes; UIApplication.SharedApplication.StatusBarStyle = UIStatusBarStyle.BlackOpaque; tabBar = new UITabBarController();MainView = tabBar.View; window.AddSubview(MainView); near = new NearDialogViewController(); map = new MapViewController(); tripLog = new TripLogViewController(); infoPage = new InfoViewController(); timer = new TimerViewController{ TabBarItem = new UITabBarItem("Timer", Resources.Timer, 1) }; tabControllers = new UIViewController[] { new UINavigationController(near) { TabBarItem = new UITabBarItem("Near", Resources.Near, 0) }, new UINavigationController(map) { TabBarItem = new UITabBarItem("Map", Resources.Map, 2) }, timer, new UINavigationController(tripLog) { TabBarItem = new UITabBarItem("Trip Log", Resources.TripLog, 3) }, new UINavigationController(infoPage) { TabBarItem = new UITabBarItem("Info", Resources.Info, 4) } }; tabBar.SetViewControllers(tabControllers, false); if (localNotification) { tabBar.SelectedIndex = 2; } window.MakeKeyAndVisible (); BikeLocation.UpdateFromWebsite(delegate { Util.Log("Update on startup done"); map.RefreshPinColours(); }); Appirator.AppLaunched(); Analytics.AppLaunched(); return true; } UIAlertView alert; public override void ReceivedLocalNotification (UIApplication application, UILocalNotification notification) { //alert = new UIAlertView("Alarm", "there is an alarm going on.", null, "Ok"); //alert.Show(); tabBar.SelectedIndex = 2; } // This method is required in iPhoneOS 3.0 public override void OnActivated (UIApplication application) { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace QuestTextToSpeechGeneration { class GatherQuestInformation { public GatherQuestInformation( int questID, string questPageText, Dictionary<string, string> questInformation, StreamWriter loggingObj, WebPageQuery pageGrabber, List<string> raceList) { QuestID = questID; QuestPageText = questPageText; QuestInformation = questInformation; LoggingObj = loggingObj; PageGrabber = pageGrabber; RaceList = raceList; } public int QuestID { get; set; } public string QuestPageText { get; set; } public Dictionary<string, string> QuestInformation { get; set; } public StreamWriter LoggingObj { get; set; } public WebPageQuery PageGrabber { get; set; } public List<string> RaceList; public string DefaultVoice = "DefaultVoice"; /// <summary> /// /// </summary> /// <param name="questWebText"></param> /// <returns></returns> public Dictionary<string,string> GetQuestInformation(string questWebText) { //I am not super happy about either the specificity of the regex nor the fact that I have basically the same key twice in a dictionary //However ripping from websites are obnoxtious and this seems to be the easiest way to go about it and honestly I cant be arsed to get //Too much more detail here Dictionary<string, string> SearchSectionAndRegexs = new Dictionary<string, string> { {"Title","\\\"name\\\"\\:\\\"([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\>\\&\\;\\:]+)\\\",\\\"u"}, {"Objective","<script>WH\\.WAS\\.validateUnit\\(\\\"ad-mobileMedrec\\\"\\);<\\/script>\\n[\\s]+<\\/div>\\\n<\\/div>\\\n([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\\n\\\n\\<"}, {"Description","<h2 class=\\\"heading-size-3\\\">Description<\\/h2>\\n([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\n\\n\\n<h2"}, {"Progress",">Progress<\\/a><\\/h2>\\\n<div id=\\\"lknlksndgg-progress\\\" style=\\\"display: none\\\">([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\\n\\\n<\\/div>\\\n\\\n\\\n"}, {"Completion","div id=\\\"lknlksndgg-completion\\\" style=\\\"display: none\\\">([a-zA-Z0-9\\s\'\"\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\\n\\\n<\\/div>\\\n\\\n\\\n"}, {"Completion2",">Completion<\\/h2>\\n([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:\"]+)\\n\\n<div"}, }; ////Regex that works in regex101 Need to update Title, Obj, Des,Prog ////{"Title","\\\"name\\\"\\:\\\"([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\>\\&\\;\\:]+)\\\",\\\"u"}, ////{ "Objective","<script>WH\\.WAS\\.validateUnit\\(\\\"ad-mobileMedrec\\\"\\);<\\/script>\\n[\\s]+<\\/div>\\\n<\\/div>\\\n([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\\n\\\n\\<"}, ////{ "Description","<h2 class=\\\"heading-size-3\\\">Description<\\/h2>\\n([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\n\\n\\n<h2"}, ////{ "Progress",">Progress<\\/a><\\/h2>\\\n<div id=\\\"lknlksndgg-progress\\\" style=\\\"display: none\\\">([a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;\\:]+)\\\n\\\n<\\/div>\\\n\\\n\\\n"}, ////{ "Completion","div id=\\\"lknlksndgg-completion\\\" style=\\\"display: none\\\">([a-zA-Z0-9\s\'\-\.\,\!\?\<\\\/\>\&\;\:\"]+)\\n\\n<\/div>\\n\\n\\n"}, ////{ "Completion2",">Completion<\/h2>\\n([a-zA-Z0-9\s\'\-\.\,\!\?\<\\\/\>\&\;\:\"]+)\\n\\n<div"}, foreach (KeyValuePair<string, string> entry in SearchSectionAndRegexs) { GetQuestSection(entry); } GetNPCInformation(); return QuestInformation; } public void GetQuestSection(KeyValuePair<string, string> questSectionSearchInfo) { Regex rx = new Regex(questSectionSearchInfo.Value, RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection matches = rx.Matches(QuestPageText); if (matches.Count == 1) { string sectionText = ReplaceUnreadableText(matches[0].Groups[1].Value); string pattern = @"\d+$"; string replacement = ""; Regex rgx = new Regex(pattern); string questSectionKey = rgx.Replace(questSectionSearchInfo.Key, replacement); QuestInformation.Add(questSectionKey, sectionText); LoggingObj.WriteLine("Adding Quest {0} to QuestInformationDic: {1}", questSectionSearchInfo.Key, sectionText); } else if (matches.Count > 1) { LoggingObj.WriteLine("More than one {0} found for quest: {1}", questSectionSearchInfo.Key, QuestID); } else { LoggingObj.WriteLine("No {0} found for quest: {1}", questSectionSearchInfo.Key, QuestID); } } public string ReplaceUnreadableText(string OriginalQuestSectionText) { OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "<br />", " ", RegexOptions.IgnoreCase); OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "&lt;class&gt;", "one", RegexOptions.IgnoreCase); OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "&lt;name&gt;", "", RegexOptions.IgnoreCase); OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "&lt;race&gt;", "one", RegexOptions.IgnoreCase); OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "&lt;", " ", RegexOptions.IgnoreCase); OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "&gt;", " ", RegexOptions.IgnoreCase); OriginalQuestSectionText = Regex.Replace(OriginalQuestSectionText, "&nbsp;", " ", RegexOptions.IgnoreCase); return OriginalQuestSectionText; } public void GetNPCInformation() { bool startAndEndNPCExsist = true; string startNPCRegex = "Start: \\[url=[\\\\]+\\/[a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;]+=([0-9]+)\\]"; string endNPCRegex = "End: \\[url=[\\\\]+\\/[a-zA-Z0-9\\s\'\\-\\.\\,\\!\\?\\<\\\\/\\>\\&\\;]+=([0-9]+)\\]"; Regex rx = new Regex(startNPCRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection startNPCmatches = rx.Matches(QuestPageText); rx = new Regex(endNPCRegex, RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection endNPCmatches = rx.Matches(QuestPageText); string startNpcDictionaryName = "StartNpc"; string endNpcDictionaryName = "EndNpc"; if (startNPCmatches.Count == 0) { startAndEndNPCExsist = false; QuestInformation.Add(startNpcDictionaryName, DefaultVoice); } if (endNPCmatches.Count == 0) { startAndEndNPCExsist = false; QuestInformation.Add(endNpcDictionaryName, DefaultVoice); } string npcWebPage = string.Empty; string npcRace = string.Empty; string npcBaseUrl = "https://classic.wowhead.com/npc="; if (startAndEndNPCExsist == true) { if (startNPCmatches[0].Groups[1].Value == endNPCmatches[0].Groups[1].Value) { LoggingObj.WriteLine("Both the Start and End NPC are the same ID: {0}", startNPCmatches[0].Groups[1].Value); npcWebPage = PageGrabber.GetWebPageData(npcBaseUrl + startNPCmatches[0].Groups[1].Value); npcRace = GetNPCRace(npcWebPage); QuestInformation.Add(startNpcDictionaryName, npcRace); QuestInformation.Add(endNpcDictionaryName, npcRace); return; } } if (!QuestInformation.ContainsKey(startNpcDictionaryName)) { LoggingObj.WriteLine("The Start NPC is the ID: {0}", startNPCmatches[0].Groups[1].Value); npcWebPage = PageGrabber.GetWebPageData(npcBaseUrl + startNPCmatches[0].Groups[1].Value); npcRace = GetNPCRace(npcWebPage); QuestInformation.Add(startNpcDictionaryName, npcRace); } if (!QuestInformation.ContainsKey(endNpcDictionaryName)) { LoggingObj.WriteLine("The End NPC is the ID: {0}", endNPCmatches[0].Groups[1].Value); npcWebPage = PageGrabber.GetWebPageData(npcBaseUrl + endNPCmatches[0].Groups[1].Value); npcRace = GetNPCRace(npcWebPage); QuestInformation.Add(endNpcDictionaryName, npcRace); } } public string GetNPCRace(string NpcWebPage) { foreach (string curRace in RaceList) { Regex rx = new Regex(curRace, RegexOptions.Compiled | RegexOptions.IgnoreCase); MatchCollection Racematches = rx.Matches(NpcWebPage); if(Racematches.Count > 0) { LoggingObj.WriteLine("The Race was found to be:{0}", curRace); return curRace; } } LoggingObj.WriteLine("NO race was found and default was used"); return DefaultVoice; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chpoi.SuitUp.Service { //客户端服务 public interface ClientService { string Login(string Username, string Password); string ModifyInfor(string ClientName, int Age,string Address,string Password); void GetUserInfor(string ReturnMessage); string Register(string username, string password, string Email,string PhoneNumber); bool IsSuccess(string ReturnMessage); string GetFailedMessage(string ReturnMessage); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Xml; using System.Xml.Linq; using IMDb_Scraper; namespace Test { class Program { static void Main(string[] args) { GetMovieInfoImdbScrapping(); //GetMovieInfoUrl(); } private static void GetMovieInfoUrl() { Console.Write("Imdb url:"); const string key = "bbccdb8024a0ffe87d397d94b083b691"; var url = "tt1375666"; var serviceUri = new Uri(string.Format("http://api.themoviedb.org/2.1/Movie.imdbLookup/en/xml/{0}/{1}", key, url)); var client = new WebClient(); client.OpenReadCompleted += ClientOpenReadCompleted; client.OpenReadAsync(serviceUri); } static void ClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e) { if(e.Error!=null) { Console.WriteLine(e.Error.Message); return; } var responseStream = e.Result; var responseReader = XmlReader.Create(responseStream); var mov = XElement.Load(responseReader); var name = (string)mov.Element("movies").Element("movie").Element("name"); Console.WriteLine(name); Console.WriteLine("\nPress Enter..."); Console.ReadLine(); } private static void GetMovieInfoImdbScrapping() { Console.Write("Movie Title: "); var movTitle = Console.ReadLine(); var mov = new IMDb(movTitle, false); Console.WriteLine(mov.ImdbURL); Console.WriteLine("\nPress Enter..."); Console.ReadLine(); } private static void ConvertEncoding(Encoding unicode, Encoding ascii) { string storyline = "Cobb&#x27;s rare ability"; var sourceBytes = ascii.GetBytes(storyline); var destBytes = Encoding.Convert(ascii, unicode, sourceBytes); var destChars = new char[unicode.GetCharCount(destBytes, 0, destBytes.Length)]; unicode.GetChars(destBytes, 0, destBytes.Length, destChars, 0); var newString = new string(destChars); Console.WriteLine("\n-------------------------------"); Console.WriteLine(DateTime.Now); Console.WriteLine(unicode.EncodingName); Console.WriteLine(ascii.EncodingName); Console.WriteLine("==============================="); Console.WriteLine(newString); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UnitedPigeonAirlines.Data.Entities.EmailAggregate { public class EmailSettings { public string MailToAddress; public string MailFromAddress; public bool UseSsl; public string Username; public string Password; public string ServerName; public int ServerPort; public bool WriteAsFile; public string FileLocation; } }
using System; using System.Collections.Generic; using System.Linq; namespace SignalR.API.Utils { public static class Consts { public static IDictionary<string, IEnumerable<string>> QuestionGroups = new Dictionary<string, IEnumerable<string>>(); public static IEnumerable<string> GetQuestionGroupConnectionIds(Guid questionId) { _ = QuestionGroups.TryGetValue(questionId.ToString(), out IEnumerable<string> result); return result; } public static IEnumerable<string> AddConnectionIdToQuestionGroups(Guid questionId, string connectionId) { if (QuestionGroups.ContainsKey(questionId.ToString()) && !QuestionGroups[questionId.ToString()].Any(id => id == connectionId)) { var data = QuestionGroups[questionId.ToString()].ToList(); data.Add(connectionId); QuestionGroups[questionId.ToString()] = data; } if (!QuestionGroups.ContainsKey(questionId.ToString())) { QuestionGroups.Add(questionId.ToString(), new List<string>() { connectionId }); } return GetQuestionGroupConnectionIds(questionId); } public static IEnumerable<string> RemoveConnectionIdFromQuestionGroups(Guid questionId, string connectionId) { if (QuestionGroups.ContainsKey(questionId.ToString()) && QuestionGroups[questionId.ToString()].Any(id => id == connectionId)) { var data = QuestionGroups[questionId.ToString()].ToList(); data.Remove(connectionId); QuestionGroups[questionId.ToString()] = data; } return GetQuestionGroupConnectionIds(questionId); } } }
using System.Collections.Generic; using System.Configuration; using System.ServiceModel.Configuration; using System.Threading.Tasks; using log4net; using WsValidate.Contracts; namespace WsValidate { public class WsAppConfig : IWsAppConfig { private static readonly ILog Logger = LogManager.GetLogger(typeof(WsAppConfig)); private Configuration _appConfig; private string _configFilePath; public void LoadConfig(string configFilePath) { Logger.Info($"configuration: {configFilePath}"); _configFilePath = configFilePath; var map = new ExeConfigurationFileMap { ExeConfigFilename = _configFilePath }; _appConfig = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None); Logger.Info($"configuration: {configFilePath} loaded."); } public Task<List<string>> GetWsConfigs() { return Task.FromResult(new List<string> { "test" }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using FindAFriend.Data; using FindAFriend.Models; namespace FindAFriend.Controllers { public class FriendRequestsController : AuthenticationController { private readonly ApplicationDbContext _context; //TargetProfile är en global variabel som lagrar det profilobjekt som applikationen ibland behöver public static Profile TargetProfile { get; set; } public static int RequestCount { get; set; } public FriendRequestsController(ApplicationDbContext context) { _context = context; } //Hämtar alla vänförfrågningar där den inloggade användaren står som Recipient public async Task<IActionResult> Index() { return View(await _context.FriendRequests.Where(fr => fr.Recipient.Equals(User.Identity.Name)).ToListAsync()); } public IActionResult Create(string id) { Profile Recipient = _context.Profile.Single(e => e.UserID == id); TargetProfile = Recipient; return View(); } //Innan ett FriendRequest-objekt lagras i databasen kontrolleras det att en likadan request finns och att de två användarna inte redan är vänner [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("RequestID,Sender,Recipient")] FriendRequests friendRequests, string id) { Profile Recipient = _context.Profile.Single(e => e.UserID == id); if (ModelState.IsValid) { friendRequests.Sender = User.Identity.Name; friendRequests.Recipient = id; bool notEligibleFriends = false; FriendRequests friendRequest = _context.FriendRequests.FirstOrDefault(fr => fr.Recipient == id && fr.Sender == User.Identity.Name); Friends friend = _context.Friends.FirstOrDefault(f => f.User == User.Identity.Name && f.FriendWith == id); Friends friends = _context.Friends.FirstOrDefault(f => f.User == id && f.FriendWith == User.Identity.Name); if (friendRequest != null || friend != null || friends != null) { notEligibleFriends = true; } if(notEligibleFriends == false) { _context.Add(friendRequests); await _context.SaveChangesAsync(); } return RedirectToAction(nameof(Index)); } return View(friendRequests); } public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var friendRequests = await _context.FriendRequests .FirstOrDefaultAsync(m => m.RequestID == id); if (friendRequests == null) { return NotFound(); } TargetProfile = _context.Profile.FirstOrDefault(p => p.UserID == friendRequests.Sender); return View(friendRequests); } [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var friendRequests = await _context.FriendRequests.FindAsync(id); _context.FriendRequests.Remove(friendRequests); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } } }
namespace Happiness_Index { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; public class HappinessIndex { public static void Main(string[] args) { //string for happy pattern; var happyStr = @"(:\))|(:D)|(;\))|(:\*)|(:])|(;])|(:})|(;\})|(\(:)|(\*:)|(c:)|(\[:)|(\[;)"; //string for sad pattern; var sadStr = @"(:\()|(D:)|(;\()|(:\[)|(;\[)|(:{)|(;{)|(\):)|(:c)|(]:)|(];)"; //var for happy regex; var happyReg = new Regex(happyStr); //var for sad regex; var sadReg = new Regex(sadStr); //var for sentence; var sentence = Console.ReadLine(); //var for happy matches; var happyMatches = happyReg.Matches(sentence); //var for sad matches; var sadMatches = sadReg.Matches(sentence); //var for happy index; var happyIndex = Math.Round((double)happyMatches.Count / sadMatches.Count, 2); //printing the result; if (happyIndex >= 2) { Console.WriteLine("Happiness index: {0:F2} :D", happyIndex); } else if (happyIndex > 1 && happyIndex < 2) { Console.WriteLine("Happiness index: {0:F2} :)", happyIndex); } else if (happyIndex == 1) { Console.WriteLine("Happiness index: {0:F2} :|", happyIndex); } else if (happyIndex < 1) { Console.WriteLine("Happiness index: {0:F2} :(", happyIndex); } Console.WriteLine("[Happy count: {0}, Sad count: {1}]", happyMatches.Count, sadMatches.Count); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShootingState : StateMachineBehaviour { PlayerController m_Controller; Shoot m_Shoot; Rigidbody m_Body; GrowShrinkMechanic m_GrowMechanic; Vector3 moveDirection; Vector3 lastHeldDirection; override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { m_Controller = animator.GetComponent<PlayerController>(); m_Shoot = animator.GetComponent<Shoot>(); m_Body = animator.GetComponent<Rigidbody>(); m_GrowMechanic = animator.GetComponent<GrowShrinkMechanic>(); m_Body.velocity = Vector3.zero; } override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { Vector3 Direction = m_Controller.AimPoint.position - animator.transform.position; Vector3 LookPoint = new Vector3(Direction.x, 0, Direction.z); m_Body.rotation = Quaternion.LookRotation(LookPoint.normalized, Vector3.up); if (m_Controller.player.GetButton("Shoot")) { m_Shoot.StartCharge(m_Controller.player); } if (m_Controller.player.GetButtonUp("Shoot")) { m_Shoot.FireBullet(m_Controller.m_LibeeSorter.CurrentAmmoPool()); m_Shoot.StopCharge(); m_Controller.m_LibeeSorter.SortLibee(); } } override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { } }
using UnityEngine; using System.Collections; public class CountdownToVictory : MonoBehaviour { public float secsTillVic; public UnityEngine.UI.Text text; // Update is called once per frame void Update () { text.text = "Seconds until victory: " + (secsTillVic - Time.time).ToString("f2"); if(secsTillVic - Time.time <= 0){ Application.LoadLevel("Win"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Framework.Remote.Mobile { public partial class CxSkin { /// <summary> /// Initializes a new instance of the <see cref="T:Framework.Remote.CxSkin"/> class. /// </summary> internal CxSkin(string id, string name, byte[] skinData, bool isSelected) { Id = id; Name = name; SkinData = skinData; IsSelected = isSelected; } } }
using System; namespace MoneyBack.Calculators { public class SantanderCommisionCalculator : ICommisionCalculator { public decimal Calculate(decimal price) { return Math.Max(1.9m, Math.Round(price * 0.0019m, 2)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; using KT.DB; using KT.DB.CRUD; using KT.DTOs.Objects; using KT.ServiceInterfaces; using KT.Services.Mappers; namespace KT.Services.Services { // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "KtSubcategoriesService" in code, svc and config file together. public class KtSubcategoriesService : IKtSubcategoriesService { private static readonly ICrud<Subcategory> Repository = CrudFactory<Subcategory>.Get(); public SubcategoryDto[] GetAll() { var relatedObjects = new[] { "Questions" }; return (new SubcategoriesMapper()).Map(Repository.ReadArray(a => true, relatedObjects)).ToArray(); } public void Insert(SubcategoryDto subCat) { var entity = (new SubcategoriesMapper()).Map(subCat); Repository.Create(entity); } public SubcategoryDto[] GetByCategory(Guid catId) { var relatedObjects = new[] { "Tests", "Questions" }; var all = Repository.ReadArray(a => a.CategoryId == catId, relatedObjects); var mapped = (new SubcategoriesMapper()).Map(all); return mapped.ToArray(); } public SubcategoryDto GetById(Guid subCatId) { var relatedObjects = new[] { "Questions" }; var subcategory = Repository.Read(a => a.Id == subCatId, relatedObjects); return (new SubcategoriesMapper()).Map(subcategory); } public Guid Save(string name, Guid catId, Guid? subcatId = null) { if (subcatId.HasValue && !subcatId.Equals(Guid.Empty)) { var subCat = Repository.Read(a => a.Id == subcatId); if (subCat != null) subCat.Name = name; Repository.Update(subCat); return subcatId.Value; } else { var subCat = new Subcategory { Name = name, Id = Guid.NewGuid(), CategoryId = catId }; Repository.Create(subCat); return subCat.Id; } } public void Delete(Guid id) { Repository.Delete(a => a.Id == id); } public int GetCountByCategory(Guid id) { var count = Repository.ReadArray(a => a.CategoryId.Equals(id)).Length; return count; } } }
using UnityEngine; // Manages a skill that manipulates time public class SlowTime : MonoBehaviour { #region -Fields- // Constants public const int SPCostPerTenthSecond = 1; public const int MinimumRequiredSP = 3; public const float MinimumHoldTime = 0.25f; // Public Fields public Color tint; public ColorExtension.HSV shift; public AudioClip slowClip; public AudioClip fastClip; public CharacterStatChange statChange; // Private Fields private CameraImageEffect camfx; private Color oldTint; private ColorExtension.HSV oldShift; private float timer; private bool isLeader; private bool slowed; private AudioManager aux; private TimeManager time; private TeamManager team; #endregion #region -Monobehaviour- private void Awake() { aux = AudioManager.instance; time = TimeManager.instance; team = TeamManager.instance; isLeader = false; slowed = false; } private void OnEnable() { team.LeaderChange += CheckLeader; } private void OnDisable() { team.LeaderChange -= CheckLeader; } private void Start() { camfx = Camera.main.GetComponent<CameraImageEffect>(); if (camfx == null) { camfx = Camera.main.gameObject.AddComponent<CameraImageEffect>(); } oldShift = camfx.Shift; oldTint = camfx.Tint; } private void Update() { if (isLeader) { if (CastSkill()) { if (timer < MinimumHoldTime) { timer += Time.deltaTime; } else { timer = 0f; SlowdownTime(); Clock.OnTenthSecond += SPCost; } } else { timer = 0f; } if (CancelSkill()) { RestoreTime(); Clock.OnTenthSecond -= SPCost; } } } #endregion #region -Methods- // Check if skill can be casted private bool CastSkill() { bool buttonHeld = Input.GetButton("Secondary"); bool hasSP = statChange.Stat.curSP >= MinimumRequiredSP; bool notInteracting = !GameManager.instance.LeaderCanInteract; return buttonHeld && hasSP && !slowed && notInteracting; } // Check if skill is cancelled private bool CancelSkill() { bool buttonUp = Input.GetButtonUp("Secondary"); bool depletedSP = statChange.Stat.curSP <= 0; return (buttonUp || depletedSP) && slowed; } // Slows time down, changing visual and plays audio cue public void SlowdownTime() { slowed = true; camfx.ChangeColor(tint, shift, 0.25f); aux.PlaySound(slowClip, true); aux.ChangePitch(0.8f, 0.25f); time.SlowTime(0.25f); } // Restore time, changing visual and plays audio cue public void RestoreTime() { slowed = false; camfx.ChangeColor(oldTint, oldShift, 0.25f); aux.PlaySound(fastClip, true); aux.ChangePitch(1f, 0.25f); time.ResetTime(0.25f); } // Change SP private void SPCost() { statChange.ChangeSP(-SPCostPerTenthSecond); } // Check if the character is leader private void CheckLeader() { isLeader = team.IsLeader(gameObject); } #endregion }
using System; // you can also use other imports, for example: // using System.Collections.Generic; // you can write to stdout for debugging purposes, e.g. // Console.WriteLine("this is a debug message"); class Solution { public int solution(int N) { // write your code in C# 6.0 with .NET 4.5 (Mono) string N_binary = Convert.ToString(N, 2); int max_gap = 0; int current_gap = -1; for (int i = 1; i < N_binary.Length; i++) { if (N_binary[i-1] == '1' && N_binary[i] == '0') { current_gap = 1; } else if (N_binary[i - 1] == '0' && N_binary[i] == '0') { current_gap++; } else if (N_binary[i - 1] == '0' && N_binary[i] == '1') { max_gap = Math.Max(max_gap, current_gap); } } return max_gap; } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Jobs.Models; using WebinarBlazorApp.Server.DbContext; namespace BlazorApp5.Server.Controllers { [ApiController] [Route("[controller]")] public class JobsController : ControllerBase { private readonly ILogger<JobModel> logger; private readonly StaticContext context; public JobsController(ILogger<JobModel> logger, StaticContext context) { this.logger = logger; this.context = context; } [HttpGet] [Produces("application/json")] public List<JobModel> Get() { return context.Jobs; } [HttpPost] [Consumes("application/json")] [Produces("application/json")] public JobModel Post([FromBody] JobModel jobModel) { return context.CreateJob(jobModel); } [HttpPut] [Consumes("application/json")] [Produces("application/json")] public bool Put([FromBody]JobModel jobModel) { context.UpdateJobStatus(jobModel); return true; } } }
using QnABot.Tools; namespace QnABot.Comands { public class Test : ITool { public string Description { get; set; } public string CommandsName { get; set; } public Test() { Description = "реализация тестирования по теоретической части программирования"; CommandsName = "/test"; } } }
using System; using System.Collections.Generic; using System.Linq; namespace EigthPuzzleWithAStarAlgorithm { public class StepManager { List<Step> closedSteps = new List<Step>(); List<Step> openedSteps = new List<Step>(); int[] goalState; int[] initialState; List<int[]> AllStates = new List<int[]>(); public bool IsSucceed { get; private set; } Step currentStep; public StepManager(int[] _initialState, int[] _goalState) { initialState = _initialState; goalState = _goalState; } public List<int[]> SolveProblem() { var rootStep = new Step(state: initialState, goalState: goalState, 0); openedSteps.Add(rootStep); currentStep = rootStep; while (openedSteps.Any() && (!currentStep.IsFinished || !currentStep.IsSucceed)) { DeleteStepFromOpenedListAddToClosedList(currentStep); currentStep = FindBestNextStep()??currentStep;//Null donerse artik acik listede step kalmamistir dolayisiyla bir daha donguye giremeyecek. currentStep yine kullanilacagindan null a esitleme } if (currentStep.IsSucceed) { var tempStep = currentStep; while (tempStep!=null) { AllStates.Add(tempStep.State); tempStep = tempStep.ParentStep; } } IsSucceed = currentStep.IsSucceed; AllStates.Reverse(); return AllStates; } Step FindBestNextStep() { currentStep.LoadPossibleNextSteps(); var validNextSteps = currentStep.NextSteps.Where(nextStep => !closedSteps.Where(closedStep=>closedStep.CompareState(nextStep.State)).Any()); //Sonraki adimlar kapali listede olabilir onlari filtreleyerek openListe sonraki adimlari ekle openedSteps.AddRange(validNextSteps.Where(step=>!openedSteps.Where(stp=>step.CompareState(stp.State)).Any()));//Sonraki adimlar arasinda openedSteps Listesi icinde olan olabilir onlari ihmal ederek openedListe ekle return openedSteps.OrderBy(step => step.FX).FirstOrDefault(); //FX=HX+GX degeri en az olani gonder } void DeleteStepFromOpenedListAddToClosedList(Step step) { var willBeDeletedStep = openedSteps.Where(stp => stp.GX == step.GX && stp.StepId == step.StepId) .FirstOrDefault(); closedSteps.Add(willBeDeletedStep); openedSteps.Remove(willBeDeletedStep); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.Encodings.Web; using System.Threading.Tasks; using HardcoreHistoryBlog.Core; using HardcoreHistoryBlog.Data; using HardcoreHistoryBlog.Models; using HardcoreHistoryBlog.ViewModels; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; namespace HardcoreHistoryBlog.Controllers { public class AccountController : Controller { private readonly SignInManager<ApplicationUser> _signInManager; private readonly UserManager<ApplicationUser> _userManager; private readonly RoleManager<ApplicationRole> _roleManager; public AccountController(SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager) { _userManager = userManager; _signInManager = signInManager; _roleManager = roleManager; } public IActionResult Index(UsersViewModel vm) { var user = _userManager.GetUserAsync(HttpContext.User).Result; string mail = user?.Email; string firstname = user?.FirstName; string lastname = user?.LastName; return View(new UsersViewModel { FirstName = firstname, LastName = lastname, Email = mail }); } [AllowAnonymous] [HttpGet] public IActionResult Register() { return View(new RegisterViewModel()); } [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel vm) { if (!ModelState.IsValid) return View(vm); { var user = new ApplicationUser { UserName = vm.Email, Email = vm.Email, FirstName = vm.FirstName, LastName = vm.LastName }; var result = await _userManager.CreateAsync(user, vm.Password); if (result.Succeeded) { _userManager.AddToRoleAsync(user, "Customer").Wait(); await _signInManager.SignInAsync(user, false); return RedirectToAction("Index", "Home"); } else foreach (var error in result.Errors) { ModelState.AddModelError("", error.Description); } } return View(vm); } } }
using AutoMapper; using LuizalabsWishesManager.Domains.Models; using LuizalabsWishesManager.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LuizalabsWishesManager.Mappers { public class DomainToViewModelMappingProfile : Profile { public DomainToViewModelMappingProfile() { CreateMap<User, UserViewModel>(); CreateMap<Product, ProductViewModel>(); CreateMap<Wish, WishViewModel>(); CreateMap<WishProduct, ProductWishViewModel>(); } } }
using System; namespace Inheritance { public class Shape { public void setAttributes(double w, double h) { width = w; height = h; } protected double width; protected double height; } public class Rectangle : Shape { public double Perimeter(double width, double height) //return perimeter of rectangle { return 2 * width + 2 * height; } public double Area(double width, double height) //return area of rectangle { return width * height; } // Display a triangle's style. } // } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Klases_Advanced { abstract class Gyvunas { public byte KojuSkaicius { get; set; } public string Spalva { get; set; } public bool ArYraUodega { get; set; } public abstract float Kaina { get; } public virtual string Aprasymas() { return "Grazus gyvunas"; } public abstract void SiulytiKaina(float kaina); } }
using System.Collections.Generic; using Newtonsoft.Json; namespace CoinBot.Clients.Bittrex { internal sealed class BittrexMarketSummariesDto { [JsonProperty("result")] public List<BittrexMarketSummaryDto> Result { get; set; } } }
using Quintity.TestFramework.Core; namespace Quintity.TestFramework.TestLibrary { [TestClass] public class TestClass : TestClassBase { [TestMethod] public TestVerdict SampleTestMethod() { return TestVerdict.Pass; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TriodorArgeProject.Entities.EntityClasses; using TriodorArgeProject.Service.Abstract; namespace TriodorArgeProject.Service.Managers { public class PersonnelCostManager:ManagerBase<PersonnelCosts> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ALM.Empresa.Interfaz { public class Respuesta { public string Codigo { get; set; } public string MensajeUsuario { get; set; } public string Extras { get; set; } public System.Web.Mvc.JsonResult RespuestaInformacion { get; set; } } }
 Contest.Main(args);
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEditor; using UnityEngine; public class ReturnNet : MonoBehaviour { [SerializeField] private Volleyball _volleyball; [SerializeField] private Rigidbody2D _volleyballRb; [SerializeField] private Vector2 netCatchVelocity = new Vector2(2.0f, -1.0f); private void OnTriggerEnter2D(Collider2D collision) { _volleyball.UnlockBall(); SetCatchVelocity(netCatchVelocity); Debug.Log("Ball height = " + _volleyballRb.transform.position.y); } private Vector2 SetCatchVelocity(Vector2 velocity) { _volleyballRb.velocity = velocity; return _volleyballRb.velocity; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SealedClasses { class mySubClass : myExampleClass { // an instance of this class can never be created because it is // trying to inherite from a SEALED class that can not be inherrited from. } }
using SalaoG.Models; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace SalaoG.Data { public class LoginDAO:IMysql ,IDisposable { //public bool Logar(Login login) //{ // // return DependencyService.Get<IMysql>().Logar(login); // return true; //} public void Dispose() { } public void Abrircon() { throw new NotImplementedException(); } /* public bool Logar(Login login) { var strSql = "SELECT COUNT(*) FROM tb_usuarios "; strSql = strSql + "INNER JOIN tb_funcionarios ON codigoFUNCIONARIO = funcionarioUSUARIO"; strSql = strSql + " WHERE replace(replace(cpfFUNCIONARIO,'.',''),'-','')"; strSql = strSql + " = '" + login.cpf.Replace(".","").Replace("-","") + "'"; strSql = strSql + " AND senhaUSUARIO = '" + login.senha + "'"; return DependencyService.Get<IMysql>().Logar(strSql); } */ /* funcional public Login Logar(Login login) { var strSql = "SELECT COUNT(*) FROM tb_usuarios "; strSql = strSql + "INNER JOIN tb_funcionarios ON codigoFUNCIONARIO = funcionarioUSUARIO"; strSql = strSql + " WHERE replace(replace(cpfFUNCIONARIO,'.',''),'-','')"; strSql = strSql + " = '" + login.cpf.Replace(".", "").Replace("-", "") + "'"; strSql = strSql + " AND senhaUSUARIO = '" + login.senha + "'"; return DependencyService.Get<IMysql>().Logar(strSql); } */ public Login Logar(Login login) { var strSql = "SELECT nomeFUNCIONARIO,funcionarioUSUARIO,cpfFUNCIONARIO,coalesce(IdEmpresa,0) FROM tb_usuarios "; strSql = strSql + "INNER JOIN tb_funcionarios ON codigoFUNCIONARIO = funcionarioUSUARIO"; strSql = strSql + " WHERE replace(replace(replace(cpfFUNCIONARIO,'.',''),'-',''),',','')"; strSql = strSql + " = '" + login.cpf.Replace(".", "").Replace("-", "") + "'"; strSql = strSql + " AND senhaUSUARIO = '" + login.senha + "'"; return DependencyService.Get<IMysql>().Logar(strSql); } public bool Logar(string strSql) { throw new NotImplementedException(); } public List<ListaServico> ListaServico(string strSql) { throw new NotImplementedException(); } public bool FinalizarAtendimento(List<Atendimento> listaAtendimento) { throw new NotImplementedException(); } public bool FinalizarAtendimento(Atendimento listaAtendimento) { throw new NotImplementedException(); } Atendimento IMysql.FinalizarAtendimento(Atendimento listaAtendimento) { throw new NotImplementedException(); } Login IMysql.Logar(string strSql) { throw new NotImplementedException(); } public List<ListaAtendimento> ListaAtendimento(string strSql) { throw new NotImplementedException(); } //public bool Logar(string strSql) //{ // var strSql = "SELECT COUNT(*) FROM tb_usuarios WHERE UPPER(loginUSUARIO) = '" + login.cpf + "'" // + " AND senhaUSUARIO = '" + login.senha + "'"; // return DependencyService.Get<IMysql>().Logar(strSql); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.UI.Xaml; using Windows.UI.Xaml.Data; namespace IndoorMap.Helpers { public class OpenTimeConverter : IValueConverter { public Object Convert(Object value, Type targetType, Object parameter, String language) { if (value != null) { string openTime = value.ToString(); return "营业时间:" + openTime; } return string.Empty; } public Object ConvertBack(Object value, Type targetType, Object parameter, String language) { return value; } } public class EmptyStringToVisibilityConverter : IValueConverter { public Object Convert(Object value, Type targetType, Object parameter, String language) { Visibility visible = Visibility.Visible; if (value == null || string.IsNullOrEmpty(value.ToString())) visible = Visibility.Collapsed; return visible; } public Object ConvertBack(Object value, Type targetType, Object parameter, String language) { return value; } } public class TrafficMultiLineConverter : IValueConverter { public Object Convert(Object value, Type targetType, Object parameter, String language) { if(value == null) { return string.Empty; } string traffic = value.ToString(); var list = traffic.Split(';'); string returnValue = string.Empty; foreach (var item in list) { if (list.LastOrDefault() != item) returnValue += item + "\r\n"; else returnValue += item; } return returnValue.TrimStart(); } public Object ConvertBack(Object value, Type targetType, Object parameter, String language) { return value; } } public class FloorConverter : IValueConverter { public Object Convert(Object value, Type targetType, Object parameter, String language) { string floor = value.ToString(); floor = floor.Replace("Floor", "") + (floor.Contains("B")? "" : " ") + "楼"; return floor; } public Object ConvertBack(Object value, Type targetType, Object parameter, String language) { return value; } } }
using System.Linq; using System.Data; using System.Collections.Generic; using System; namespace calendar { class Program { static void Main(string[] args) { string command = Console.ReadLine(); string[] parameters = command.Split(" "); if (parameters.Length == 2) { if (parameters[0].Equals("calendar")) { Calendar calendar = new Calendar(); if (parameters[1] != null) { calendar.Month = Convert.ToInt32(parameters[1]); } calendar.Show(); } } else if (parameters.Length == 3) { if (parameters[0].Equals("calendar")) { Calendar calendar = new Calendar(); if (parameters[1] != null) { calendar.Month = Convert.ToInt32(parameters[1]); } if (parameters[2] != null) { calendar.Year = Convert.ToInt32(parameters[2]); } calendar.Show(); } } else if (parameters.Length == 1) { if (parameters[0].Equals("calendar")) { Calendar calendar = new Calendar(); calendar.Show(); } } else { Console.WriteLine($"{command}: command not found"); } } } }
namespace DownloadExtractLib { using Akka.Actor; using Akka.Event; using DownloadExtractLib.Messages; using System; using System.IO; using System.Net; using System.Net.Http; using System.Threading.Tasks; using SysDiag = System.Diagnostics; /// <summary> /// Defines the <see cref="DownloadActor" /> /// </summary> public class DownloadActor : ReceiveActor { #region Fields /// <summary> /// Defines the _Log /// </summary> internal readonly ILoggingAdapter _Log = Context.GetLogger(); /// <summary> /// Defines the Client /// </summary> internal readonly HttpClient Client; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DownloadActor"/> class. /// </summary> public DownloadActor(HttpClient client) { Client = client; Receive<DownloadMessage>(DownloadPage); Receive<GotContentMessage>(GotDownloadPage); } #endregion #region Methods /* bool DownloadPage(DownloadMessage msg) { var origmsg = msg; var tcs = new TaskCompletionSource<GotContentMessage>(); var gotMsg = new GotContentMessage(msg); Client.GetAsync(msg.DownloadUri,HttpCompletionOption.ResponseContentRead) .ContinueWith((response, origmsg2) => { response.Result.Content.ReadAsStringAsync(); return tcs.Task; }) .ContinueWith(t2=> DoResponse(t2)) .PipeTo(Self); return true; // show ActorSystem we handled message [expect next one immediately!] } */ /// <summary> /// process incoming DownloadMessage /// </summary> /// <param name="msg">incoming msg<see cref="DownloadMessage"/></param> /// <returns>true to state that message has been accepted</returns> internal bool DownloadPage(DownloadMessage msg) { var uri = msg.DownloadUri; SysDiag.Debug.Assert(uri.IsAbsoluteUri, $"DownloadActor.DownloadPage({uri}) called with non-absolute Url"); var fs = msg.TargetPath; var fi = new FileInfo(fs); var dn = fi.DirectoryName; // string representing the directory's full path if (Directory.Exists(dn)) { if (msg.EnumDisposition == DownloadMessage.E_FileDisposition.LeaveIfExists && File.Exists(fs)) { var failmsg = new DownloadedMessage(msg, fs, HttpStatusCode.NotModified); Sender.Tell(failmsg); } } else { _Log.Info("DownloadPage creating directory {0} for {1}.{2}", dn, fi.Name, fi.Extension); Directory.CreateDirectory(dn); } // preserve volatile state now (before t1 that starts hot) for use by subsequent completion var ctx1 = new Context1(Sender, msg); var t1 = Client.GetAsync(uri, HttpCompletionOption.ResponseHeadersRead); // returns Task<HttpResponseMessage> var t2A = t1.ContinueWith((req, state) => { var ctx1A = state as Context1; // recover entry context var dlmsg = ctx1A.DownloadMessage; var status = req.Result.StatusCode; if (req.IsFaulted) { var s = ""; Console.WriteLine(); PostBack(dlmsg, ctx1A, status, req.Exception); } else { var hrm = req.Result; try { hrm.EnsureSuccessStatusCode(); // throw if !IsSuccessStatusCode // TODO: refine the destination filename.extn from the response // TODO: decide if file already exists and if overwrite/transform #pragma warning disable GCop302 // Since '{0}' implements IDisposable, wrap it in a using() statement var outfs = new FileStream(fs, FileMode.Create); // open stream to write file. Disposed later ! #pragma warning restore GCop302 // Since '{0}' implements IDisposable, wrap it in a using() statement _Log.Info($"DownloadActor.DownloadPage({msg.Url} => {fs}) started"); } catch (Exception excp1) { PostBack(dlmsg, ctx1A, status, excp1); } } }, ctx1); var t2 = t1.ContinueWith(GetStuff, ctx1, TaskContinuationOptions.OnlyOnRanToCompletion); // happy path (no cancel/fault) var t2F = t1.ContinueWith((req2, state) => { var ctx1f = (Context1)state; }, TaskContinuationOptions.NotOnRanToCompletion); var t3 = t2.ContinueWith(t_gotContent) .PipeTo(Self); // Task return true; // show ActorSystem we handled message [expect next one immediately!] } /// <summary> /// process response header, decoding for text or binary and write to file [in+out streams by chunks] /// </summary> /// <param name="reqtask">antecedent</param> /// <param name="state">Context1</param> /// <returns>Task<GotContentMessage></returns> internal Task<GotContentMessage> GetStuff(Task<HttpResponseMessage> reqtask, object state) { var ctx1 = state as Context1; _Log.Info($"DownloadActor.GetStuff({ctx1.DownloadMessage.Url}) response header {reqtask.Status}"); var hrm = reqtask.Result; // non-blocking as antecedent Task<HttpResponseMessage> had completed hrm.EnsureSuccessStatusCode(); // throw if !IsSuccessStatusCode var fs = ctx1.DownloadMessage.TargetPath; var fi = new FileInfo(fs); var di = fi.Directory; if (!di.Exists) { di.Create(); // short-term block as no async method available } var filestrmOut = File.Create(fs); // ?? need an overload that sets FileOptions.Asynchronous ?? var copydone = hrm.Content.CopyToAsync(filestrmOut); copydone.ContinueWith<GotContentMessage>((antecedent) => FinishOff2(antecedent, ctx1), TaskContinuationOptions.OnlyOnRanToCompletion); var tcs = new TaskCompletionSource<GotContentMessage>(); // puppet that will return a GotContentMessage result /* // Create a file using the FileStream class int BUFFLEN = 4096; var fsWrite = File.Create(fs, BUFFLEN, FileOptions.Asynchronous); //*** DEBUG *** var TEMPsrc = File.OpenText(@"C:\dev\HttpSpike\GCop.json"); var TEMPxfr = TEMPsrc.BaseStream.CopyToAsync(fsWrite, BUFFLEN); await TEMPxfr; fsWrite.Close(); TEMPsrc.Close(); */ if (hrm.Content.Headers.ContentType == null) { // stream-in the binary content } var taskTxt = hrm.Content.ReadAsStringAsync(); /* var contnt = await reqtask.Result.Content.ReadAsStringAsync().ConfigureAwait(continueOnCapturedContext: false); try { if (state != null && reqtask.Result.IsSuccessStatusCode) { tcs.SetResult(new GotContentMessage(rcm, contnt)); } else { tcs.SetException(new ApplicationException($"download failed ({reqtask.Result.StatusCode})")); } } catch (Exception excp1) { tcs.SetException(excp1); } */ return tcs.Task; // unwrap the GotContentMessage } /// <summary> /// The PostBack /// </summary> /// <param name="dlmsg">The dlmsg<see cref="DownloadMessage"/></param> /// <param name="ctx1A">The ctx1A<see cref="Context1"/></param> /// <param name="status">The status<see cref="HttpStatusCode"/></param> /// <param name="excp1">The excp1<see cref="Exception"/></param> private static void PostBack(DownloadMessage dlmsg, Context1 ctx1A, HttpStatusCode status, Exception excp1) { var failmsg = new DownloadedMessage(dlmsg, ctx1A.DownloadMessage.TargetPath, status, excp1); ctx1A.OrigSender.Tell(failmsg); } /// <summary> /// The FinishOff /// </summary> /// <param name="arg">The arg<see cref="Task{string}"/></param> /// <returns>The <see cref="GotContentMessage"/></returns> private GotContentMessage FinishOff(Task<string> arg) => new GotContentMessage(null); /// <summary> /// The FinishOff2 /// </summary> /// <param name="arg">The arg<see cref="Task"/></param> /// <param name="state">The state<see cref="object"/></param> /// <returns>The <see cref="GotContentMessage"/></returns> private GotContentMessage FinishOff2(Task arg, object state) => throw new NotImplementedException(); /// <summary> /// The GotDownloadPage /// </summary> /// <param name="gotmsg">The gotmsg<see cref="GotContentMessage"/></param> /// <returns>The <see cref="bool"/></returns> private bool GotDownloadPage(GotContentMessage gotmsg) { var reqmsg = gotmsg.Message; _Log.Info($"DownloadActor.GotDownloadPage({reqmsg.Url}) Telling"); Sender.Tell(new DownloadedMessage(reqmsg, reqmsg.TargetPath)); // TODO: pass thru real Sender (don't assume) ! return true; // show ActorSystem we handled message [expect next one immediately!] } /// <summary> /// The t_gotContent /// </summary> /// <param name="obj">The obj<see cref="Task{Task{GotContentMessage}}"/></param> private void t_gotContent(Task<Task<GotContentMessage>> obj) => throw new NotImplementedException(); #endregion /// <summary> /// Defines the <see cref="Context1" /> /// </summary> public class Context1 { #region Fields /// <summary> /// Defines the DownloadMessage /// </summary> internal readonly DownloadMessage DownloadMessage; /// <summary> /// Defines the OrigSender /// </summary> internal readonly IActorRef OrigSender; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Context1"/> class. /// </summary> /// <param name="sender">The sender<see cref="IActorRef"/></param> /// <param name="downloadMessage">The downloadMessage<see cref="DownloadMessage"/></param> public Context1(IActorRef sender, DownloadMessage downloadMessage) { OrigSender = sender; DownloadMessage = downloadMessage; } #endregion } /// <summary> /// Defines the <see cref="GotContentMessage" /> /// </summary> public class GotContentMessage { #region Fields /// <summary> /// Defines the Content /// </summary> public readonly string Content; /// <summary> /// Defines the Message /// </summary> public readonly DownloadMessage Message; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="GotContentMessage"/> class. /// </summary> /// <param name="msg">The msg<see cref="DownloadMessage"/></param> public GotContentMessage(DownloadMessage msg) { Message = msg; } /// <summary> /// Initializes a new instance of the <see cref="GotContentMessage"/> class. /// </summary> /// <param name="msg">The msg<see cref="DownloadMessage"/></param> /// <param name="content">The content<see cref="string"/></param> public GotContentMessage(DownloadMessage msg, string content) : this(msg) { Content = content; } #endregion } } }
using Domain; using System.Windows; namespace Using_Resource_Files { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new Product { Name = "Milk", Price = 2.99m }; } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class BackGroundObj : MonoBehaviour { public Image mBackGround; }
using PurificationPioneer.Global; using PurificationPioneer.Utility; using UnityEngine; using UnityEngine.UI; namespace PurificationPioneer.Script { /// <summary> /// 游戏加载界面的每个玩家的Rect /// </summary> public class LoadingMatcherInfoUi : MonoBehaviour { public Image bigImage; public Image userIcon; public Text userNick; public Text userLevel; public Text userRank; public void InitValues(GlobalVar.MatcherInfo matcherInfo) { bigImage.sprite = matcherInfo.HeroConfig.icon; userIcon.sprite = AssetConstUtil.GetUserIcon(matcherInfo.Uface); userNick.text = matcherInfo.Unick; userLevel.text = matcherInfo.Ulevel.ToString(); userRank.text = matcherInfo.Urank.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySpawner : MonoBehaviour { public GameObject player; public GameObject enemy; public GameObject spawner_W; public GameObject spawner_N; public GameObject spawner_E; public GameObject spawner_S; /* Find player position in world space * decide what pole to spawn the enemy at. * Set enemy position to spawn pole position. * instantiate enemy at pole position. */ //player position. float playerPosX; float playerPosZ; //spawn pole locations Vector3 spawnerPosition_W; Vector3 spawnerPosition_N; Vector3 spawnerPosition_E; Vector3 spawnerPosition_S; void Start() { InvokeRepeating("EnemySpawnLocation", 0.0f, 2.0f); } // Update is called once per frame void Update() { //tell the console the updated position of the player. Just want to check I can find where the player is in space. playerPosX = player.transform.position.x; playerPosZ = player.transform.position.z; //Debug.Log("player pos is: " + playerPosX); //Assign actual position to Vec3's. spawnerPosition_W = spawner_W.transform.position; spawnerPosition_N = spawner_N.transform.position; spawnerPosition_E = spawner_E.transform.position; spawnerPosition_S = spawner_S.transform.position; } //method that checks where the player is in world space. Where they are depends where they spawn. void EnemySpawnLocation() { if (playerPosX >= 0) { enemy.GetComponent<EnemyGeneratorScript>().ChooseEnemyColour(); Instantiate(enemy, spawnerPosition_W, Quaternion.identity); } if (playerPosX < 0) { enemy.GetComponent<EnemyGeneratorScript>().ChooseEnemyColour(); Instantiate(enemy, spawnerPosition_E, Quaternion.identity); } if (playerPosZ < 0) { enemy.GetComponent<EnemyGeneratorScript>().ChooseEnemyColour(); Instantiate(enemy, spawnerPosition_N, Quaternion.identity); } if (playerPosZ > 0) { enemy.GetComponent<EnemyGeneratorScript>().ChooseEnemyColour(); Instantiate(enemy, spawnerPosition_S, Quaternion.identity); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace test_code__VS_connect { class Program { static void Main(string[] args) { Console.WriteLine("Lets see if this gets commited to git hub :)"); Console.WriteLine("this the second the change i am making to the file... and the second commit from the VS_13..DIRECTLY"); Console.WriteLine("NOW on all the changes can be made directly .... no rework .... GOD bless LINUS"); Console.WriteLine("Lets see when these will be reflected on hipcaht"); } } }
using System.Collections.Concurrent; using System.Linq; using Collections.Concurrent; using Xunit; namespace Collections.Tests.Concurrent { public class StackTests { [Theory] [InlineData(2)] [InlineData(64)] [InlineData(128)] public void SingleThread(int count) { var elements = Enumerable.Range(0, count).ToList(); var stack = new Stack<int>(); foreach (var element in elements) { stack.Push(element); Assert.True(stack.TryPeek(out var peek)); Assert.Equal(element, peek); } Assert.True(stack.Count == count); while (stack.TryPop(out _)) { } Assert.True(stack.Count == 0); } } }
using System.Data; namespace TutteeFrame.Reports.ReportModel { public class InformationOfStudentResultPrepareForPrint { public DataSet BaseInforSchool = new DataSet(); public DataSet scoreBoards { get; set; } // SE1 + SE2 public double averageResult { get; set; } public string nameOfStudent { get; set; } public string classOfStudent { get; set; } public string emulationTitle { get { if (averageResult > 6.5 && averageResult < 8.0) return "Học sinh tiên tiến"; if (averageResult >= 8.0 && averageResult < 9.0) return "Con ngoan trò giỏi"; if (averageResult >= 9.0) return "Đột biến gien"; return ""; } } public string conductS1 { get; set; } public string conductS2 { get; set; } public string conductS3 { get; set; } } }
namespace FileDownloader { using System; using System.Collections.Generic; public class DownloadArgs { public bool MaintainSameDirectoryStructure { get; set; } public string RootFolderForDownload { get; set; } public List<(Uri Source, string Destination)> Files { get; set; } public Func<string, string> PostFetchContentOverride { get; set; } public Action<(string sourceFileName, string destinationFileName)> ProgressTracker { get; set; } } }
/* Write a program to check if in a given expression the brackets are put correctly. * Example of correct expression: ((a+b)/5-d). * Example of incorrect expression: )(a+b)). */ using System; class CorrectExpressionCheck { static bool IsCorrectExpression(string expression) { int bracketCount = 0; for (int i = 0; i < expression.Length; i++) { if (expression[i] == ')' && bracketCount == 0) { return false; } else if (expression[i] == '(') { bracketCount++; } else if (expression[i] == ')') { bracketCount--; } } if (bracketCount != 0) { return false; } else { return true; } } static void Main() { Console.WriteLine("Please enter your expression: "); string expression = Console.ReadLine(); if (IsCorrectExpression(expression) == true) { Console.WriteLine("The expression {0} is correct", expression); } else { Console.WriteLine("The expression {0} is incorrect", expression); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Object : MonoBehaviour { public float maxHP = 10.0f; public GameObject damageEffectObject; public bool canSucking; public bool isBoss; public bool isSubBoss; public int score; public bool isSuperArmor; const float DAMAGE_VELOCITY_X = 7.0f; const float DAMAGE_VELOCITY_Y = 10.0f; const float STOP_TIME = 0.3f; const float INVINCIBLE_TIME = 0.1f; const float BOSS_INVINCIBLE_TIME = 0.5f; float hp; float invincibleTime, stopTime; bool isSucking; bool isDeadProcessed; GameObject playerObject; Player playerScript; EnemyGauge enemyGaugeScript, subEnemyGaugeScript; private Rigidbody2D rb; private SpriteRenderer spriteRenderer; // Start is called before the first frame update void Start() { playerObject = GameObject.Find("Player"); playerScript = playerObject.GetComponent<Player>(); enemyGaugeScript = GameObject.Find("EnemyHP").GetComponent<EnemyGauge>(); subEnemyGaugeScript = GameObject.Find("SubEnemyHP").GetComponent<EnemyGauge>(); rb = GetComponent<Rigidbody2D>(); spriteRenderer = GetComponentInChildren<SpriteRenderer>(); hp = maxHP; invincibleTime = 0; stopTime = 0; isSucking = false; isDeadProcessed = false; } // Update is called once per frame void Update() { UpdateColor(); UpdateTimes(); UpdateMove(); if (hp <= 0 && !isDeadProcessed) Dead(); } private void UpdateColor() { if (IsInvincible()) spriteRenderer.color = new Vector4(1, 1, 1, 0.5f); else spriteRenderer.color = new Vector4(1, 1, 1, 1); } private void UpdateTimes() { stopTime -= Time.deltaTime; invincibleTime -= Time.deltaTime; } private void UpdateMove() { if (isSucking) { float step = 5.0f * Time.deltaTime; transform.position = Vector3.MoveTowards(transform.position, playerObject.transform.position, step); } } private void OnTriggerStay2D(Collider2D collision) { switch (collision.gameObject.tag) { case "Bullet": if (!IsInvincible()) { Bullet bullet = collision.GetComponent<Bullet>(); if (StaticValues.isDebugPowerMax) hp -= 9999; else if ((StaticValues.GameLevel)StaticValues.gameLevel == StaticValues.GameLevel.EASY) // イージーモードはダメージ倍増 hp -= (bullet.GetAttackPower() * 2); else hp -= bullet.GetAttackPower(); if (isBoss) invincibleTime = BOSS_INVINCIBLE_TIME; else invincibleTime = INVINCIBLE_TIME; AudioManager.Instance.PlaySE("Damage", 0.1f); if (!isSuperArmor) { stopTime = STOP_TIME; float velocityX = (collision.gameObject.GetComponent<Rigidbody2D>().velocity.x < 0) ? -DAMAGE_VELOCITY_X : DAMAGE_VELOCITY_X; rb.velocity = new Vector2(velocityX, DAMAGE_VELOCITY_Y); } if (isBoss) { if (isSubBoss) { subEnemyGaugeScript.SetMaxHP(maxHP); subEnemyGaugeScript.SetHP(hp); } else { enemyGaugeScript.SetMaxHP(maxHP); enemyGaugeScript.SetHP(hp); } } if (!bullet.IsTrample()) bullet.Dead(); } break; } } public void Dead() { if (isBoss) { StaticValues.AddScore(score); } else { GameObject effect = Instantiate(damageEffectObject); Destroy(effect, 1.5f); effect.transform.position = this.transform.position; AudioManager.Instance.PlaySE("Hit", 0.1f); StaticValues.AddScore(score); foreach (Transform n in transform) { Destroy(n.gameObject); } Destroy(this.gameObject); } isDeadProcessed = true; } public bool IsInvincible() { return invincibleTime > 0; } public bool IsStop() { return stopTime > 0; } public float GetHp() { return hp; } public float GetMaxHp() { return maxHP; } public void SetHp(float h) { hp = h; } }
using QuestomAssets.AssetsChanger; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace QuestomAssets.Mods.Assets { public class AssetLocator { /// <summary> /// If specified, filters by a specific type of asset /// </summary> public AssetType? TypeIs { get; set; } /// <summary> /// If specified, filters by named assets with a specific name (case sensitive) /// </summary> public string NameIs { get; set; } /// <summary> /// If specified, filters by a specific file/path. Generally not used in combination with others, and also not version stable /// </summary> public PathLocator PathIs { get; set; } public AssetsObject Locate(AssetsManager manager, bool forceDeepSearch = false) { List<Func<IObjectInfo<AssetsObject>, bool>> filters = new List<Func<IObjectInfo<AssetsObject>, bool>>(); if (TypeIs.HasValue) { switch (TypeIs.Value) { case AssetType.AudioClip: filters.Add(x => typeof(IObjectInfo<AudioClipObject>).IsAssignableFrom(x.GetType())); break; case AssetType.Component: filters.Add(x => typeof(IObjectInfo<Component>).IsAssignableFrom(x.GetType())); break; case AssetType.GameObject: filters.Add(x => typeof(IObjectInfo<GameObject>).IsAssignableFrom(x.GetType())); break; case AssetType.Mesh: filters.Add(x => typeof(IObjectInfo<MeshObject>).IsAssignableFrom(x.GetType())); break; case AssetType.MeshFilter: filters.Add(x => typeof(IObjectInfo<MeshFilterObject>).IsAssignableFrom(x.GetType())); break; case AssetType.MonoBehaviour: filters.Add(x => typeof(IObjectInfo<MonoBehaviourObject>).IsAssignableFrom(x.GetType())); break; case AssetType.Sprite: filters.Add(x => typeof(IObjectInfo<SpriteObject>).IsAssignableFrom(x.GetType())); break; case AssetType.Text: filters.Add(x => typeof(IObjectInfo<TextAsset>).IsAssignableFrom(x.GetType())); break; case AssetType.Texture2D: filters.Add(x => typeof(IObjectInfo<Texture2DObject>).IsAssignableFrom(x.GetType())); break; case AssetType.Transform: filters.Add(x => typeof(IObjectInfo<Transform>).IsAssignableFrom(x.GetType())); break; case AssetType.Material: filters.Add(x => typeof(IObjectInfo<MaterialObject>).IsAssignableFrom(x.GetType())); break; default: throw new ArgumentException($"Unhandled type value {TypeIs.Value.ToString()}"); } } if (NameIs != null) { filters.Add(x => typeof(IObjectInfo<IHaveName>).IsAssignableFrom(x.GetType()) && (x.Object as IHaveName)?.Name == NameIs); } if (PathIs != null) { if (PathIs.AssetFilename == null) throw new ArgumentException("AssetFilename must be specified when using PathIs locator."); filters.Add(x => x.ParentFile.AssetsFilename == PathIs.AssetFilename && x.ObjectID == PathIs.PathID); } try { var found = manager.MassFindAssets<AssetsObject>(x => !filters.Any(y => !y(x)), forceDeepSearch).SingleOrDefault()?.Object; if (found == null) throw new LocatorException("Locator did not find any assets"); return found; } catch (Exception ex) { throw new LocatorException("The locator throw an exception, possibly because it returned more than one matching asset.", ex); } } } }
using System; using System.Text.Json.Serialization; namespace Crt.Model.Dtos.Project { public class ProjectSearchDto { [JsonPropertyName("id")] public decimal ProjectId { get; set; } [JsonIgnore] public decimal RegionNumber { get; set; } [JsonIgnore] public string RegionName { get; set; } [JsonIgnore] public string ProjectNumber { get; set; } [JsonIgnore] public string ProjectName { get; set; } [JsonPropertyName("regionId")] public string Region { get => $"{RegionNumber}-{RegionName}"; } [JsonPropertyName("projectNumber")] public string Project { get => $"{ProjectNumber}-{ProjectName}"; } public DateTime? EndDate { get; set; } public bool IsInProgress { get => EndDate == null || DateTime.Today < EndDate; } //the following two fields are used to generate the links for Planning Target & Tender Details public string WinningContractorName { get; set; } public decimal? ProjectValue { get; set; } } }
using AutoMapper; using Enrollment.XPlatform.Flow.Cache; using Enrollment.XPlatform.Flow.Requests; using Enrollment.XPlatform.Flow.Settings; using LogicBuilder.RulesDirector; using System.Threading.Tasks; namespace Enrollment.XPlatform.Flow { public interface IFlowManager { Progress Progress { get; } DirectorBase Director { get; } FlowDataCache FlowDataCache { get; } FlowState FlowState { get; set; } IDialogFunctions DialogFunctions { get; } IActions Actions { get; } IFlowActivity FlowActivity { get; } IMapper Mapper { get; } Task<FlowSettings> Start(string module); Task<FlowSettings> Next(CommandButtonRequest request); Task<FlowSettings> NewFlowStart(NewFlowRequest request); void FlowComplete(); void Terminate(); void SetCurrentBusinessBackupData(); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Net; using System.IO; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Switchex { public partial class frmUpdates: Form { string downloadLocation = Application.StartupPath; public frmUpdates() { InitializeComponent(); } private void frmUpdates_Load(object sender, EventArgs e) { lblDownload.Text = "Downloaded: 0KB out of 0KB\nProgress: 0%"; WebClient webClient = new WebClient(); string downloadFile = "Switchex_" + Globals.downloadVersion + "_SETUP.exe"; if(!Directory.Exists(downloadLocation)) { Directory.CreateDirectory(downloadLocation); } if(!File.Exists(Application.StartupPath + "\\" + downloadFile)) { prgbar.Value = 0; lblFile.Text = "File: " + downloadFile; webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(_DownloadFileCompleted); webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(_DownloadProgressChanged); webClient.DownloadFileAsync(new Uri("https://github.com/abluescarab/Switchex/releases/download/" + Globals.downloadVersion + "/" + downloadFile), downloadLocation + "\\" + downloadFile); } else { DialogResult result = MessageBox.Show("Downloaded file already exists. Close Switchex and install updates?", "Update", MessageBoxButtons.YesNo); if(result == DialogResult.Yes) { Application.Exit(); Process.Start(Application.StartupPath + "\\Switchex_" + Globals.downloadVersion + "_SETUP.exe"); } else { Close(); } } } private void _DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { frmMain frmMain = new frmMain(); DialogResult result = MessageBox.Show("Download has finished. Close Switchex and install updates? (This will overwrite your current database.)", "Download Complete", MessageBoxButtons.YesNo); Close(); if(result == DialogResult.Yes) { Application.Exit(); Process.Start(Application.StartupPath + "\\Switchex_" + Globals.downloadVersion + "_SETUP.exe"); } } private void _DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { try { prgbar.Value = e.ProgressPercentage; decimal downloadedKB = e.BytesReceived / 1000; decimal totalKB = e.TotalBytesToReceive / 1000; lblDownload.Text = "Downloaded: " + downloadedKB + "KB out of " + totalKB + "KB\nProgress: " + e.ProgressPercentage.ToString() + "%"; } catch(Exception ex) { Globals.frmError.ShowDialog(ex); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameProj.Controller { enum GameState { StartScreen, InGame, GamePaused, GameFinished, GameOver, BetweenLevels } }
using Ads.Webshop.Logic; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AdsWebshop.Logic { public class UserManager : BaseManager<User> { public UserManager(AdsWebShopDB db) : base(db) { } protected override DbSet<User> Table { get { return _db.Users; } } public User GetByEmailAndPassword(string email, string password) { var user = _db.Users.FirstOrDefault(u => u.Email == email && u.Password == password); return user; } public User GetByEmail(string email) { var user = _db.Users.FirstOrDefault(u => u.Email == email); return user; } public void Seed() { //Users.Add(new User() //{ // Id = 1, // Email = "test@mail.com", // Password = "pass123" //}); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace _04.HowManyTimes { class HowManyTimes { static void Main(string[] args) { /*Write a program that finds how many times a substring is contained in a given text (perform case insensitive search).*/ string str = "We are living in an yellow submarine. We don't have anything else.Inside the submarine is very tight. So we are drinking all the day. We will move out of it in 5 days."; string insense = str.ToLower(); string sub = "in"; int index = insense.IndexOf(sub); int counter = 0;//вече има един индекс, но в цикъла брои с един повече и затова се сетва на 0 while (index != -1) { index = insense.IndexOf(sub, index + 1); counter++; } Console.WriteLine("The result is: " + counter); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CollisionSideDetect { public static CollisionSide GetCollisionSide(Vector2 center, Vector2 contactPoint) { float xDiff = contactPoint.x - center.x; float yDiff = contactPoint.y - center.y; if(Mathf.Abs(xDiff) > Mathf.Abs(yDiff)) { return xDiff < 0 ? CollisionSide.Left : CollisionSide.Right; } else { return yDiff < 0 ? CollisionSide.Bottom : CollisionSide.Top; } } public static CollisionSide GetCollisionSideBasedOnTriangleAndBottomPoint(Vector2 leftPoint, Vector2 rightPoint, Vector2 bottomPoint, Vector2 targetPoint) { Vector2 leftToRightVector = rightPoint - leftPoint; Vector2 leftToTargetVector = targetPoint - leftPoint; float leftToTargetAngle = Vector2.Angle(leftToTargetVector.normalized, leftToRightVector.normalized); if(leftToTargetAngle >= 120) { return CollisionSide.Right; } Vector2 rightToLeftVector = leftPoint - rightPoint; Vector2 rightToTargetVector = targetPoint - rightPoint; float rightToTargetAngle = Vector2.Angle(rightToTargetVector.normalized, rightToLeftVector.normalized); if (rightToTargetAngle >= 120) { return CollisionSide.Left; } Vector2 centerPoint = (rightPoint + leftPoint) / 2; float objectCenterToTargetLength = (targetPoint - centerPoint).magnitude; float bottomToTargetLength = (targetPoint - bottomPoint).magnitude; if(objectCenterToTargetLength < bottomToTargetLength) { return CollisionSide.Bottom; } else { return CollisionSide.Top; } } }
using System; using UnityEngine.UIElements; namespace UnityLocalization { public class DoubleClickable : Clickable { public DoubleClickable(Action handler) : base(handler) { activators.Clear(); activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, clickCount = 2 }); } public DoubleClickable(Action<EventBase> handler) : base(handler) { activators.Clear(); activators.Add(new ManipulatorActivationFilter { button = MouseButton.LeftMouse, clickCount = 2 }); } } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using KaVE.Commons.Model.Naming; using KaVE.Commons.Model.TypeShapes; using KaVE.Commons.Utils.Collections; using NUnit.Framework; using Fix = KaVE.Commons.TestUtils.Model.Naming.NameFixture; namespace KaVE.RS.Commons.Tests_Integration.Analysis.TypeShapeAnalysisTestSuite { internal class NestedTypesTest : BaseCSharpCodeCompletionTest { [Test] public void NestedTypesEmptyWithoutNestedTypes() { CompleteInNamespace(@" public class C { public void M() { $ } } "); Assert.IsEmpty(ResultContext.TypeShape.NestedTypes); } [Test] public void ShouldRetrieveAllNestedTypes() { CompleteInCSharpFile(@" namespace TestNamespace { public interface AnInterface {} public class SuperClass {} public class TestClass { public void Doit() { this.Doit(); $ } public class N1 {} public class N2 {} public class N3 {} } }"); Assert.AreEqual( Sets.NewHashSet( Names.Type("TestNamespace.TestClass+N1, TestProject"), Names.Type("TestNamespace.TestClass+N2, TestProject"), Names.Type("TestNamespace.TestClass+N3, TestProject")), ResultContext.TypeShape.NestedTypes); } [Test] public void DoesNotStepIntoNestedTypes() { CompleteInNamespace(@" class C { $ public class N { // should not include any of these public delegate void D(); public event Action E; public int F; public void M() {} public int P { get; set; } } } "); var actual = ResultContext.TypeShape; var expected = new TypeShape { TypeHierarchy = new TypeHierarchy("N.C, TestProject"), NestedTypes = {Names.Type("N.C+N, TestProject")} }; Assert.AreEqual(expected, actual); } } }
using System.Collections.Generic; namespace McrBrowser.Data { public class ImageTagData { public string name { get; set; } public List<string> tags { get; set; } } }
 using MarsQA_1.Pages; using OpenQA.Selenium; using BoDi; using OpenQA.Selenium.Chrome; using TechTalk.SpecFlow; using Docker.DotNet.Models; using System; using MarsQA_1.Helper; using Driver = MarsQA_1.Helper.Driver; using MarsQA_1.Helpers; using System.Threading; namespace MarsQA_1.Hooks { [Binding] public class Hooks { [BeforeScenario] public void Setup() { //IWebDriver driver = new ChromeDriver(); //Defining the browser Driver driver = new Driver(); driver.Initialize(); ExcelLibHelper.PopulateInCollection(@"D:\Internship_2020\MarsQA_1\MarsQA_1\SpecflowTests\Data\Mars.xlsx", "Credentials"); Thread.Sleep(2000); Mars_Login _login = new Mars_Login(); _login.ClickIn(); _login.SignIn(); } //} [AfterScenario] public void AfterScenario() { // Driver.Close(); Driver.driver.Quit(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MarsRoverAPI.Model { public class MarsSurfaceInfo : IApiModel { public List<RoverInfo> Rovers { get; set; } } }
using UnityEngine; using UnityEngine.UI; namespace Unity.PixelText { public enum TextAlign { Left, Center, Right } public enum VerticalAlign { Top, Middle, Bottom } [AddComponentMenu("UI/Pixel Text")] [RequireComponent(typeof(CanvasRenderer))] public class PixelText : MaskableGraphic { [SerializeField, TextArea(3, 10)] string _text = ""; [SerializeField] TextProperties _props = TextProperties.defaultProperties; public override Texture mainTexture => font.texture == null ? base.mainTexture : font.texture; public string text { get => _text; set { if (value == _text) return; _text = value; SetVerticesDirty(); } } public BitmapFont font { get => _props.font; set { if (value == _props.font) return; _props.font = value; SetVerticesDirty(); } } public float scale { get => _props.scale; set { if (value == _props.scale) return; _props.scale = value; SetVerticesDirty(); } } public TextAlign horizontalAlign { get => _props.horizontalAlign; set { if (value == _props.horizontalAlign) return; _props.horizontalAlign = value; SetVerticesDirty(); } } public VerticalAlign verticalAlign { get => _props.verticalAlign; set { if (value == _props.verticalAlign) return; _props.verticalAlign = value; SetVerticesDirty(); } } protected override void OnPopulateMesh(VertexHelper vh) { if (font == null || !font.isValid) return; vh.Clear(); var glyphs = font.RenderText( text, rectTransform.rect, scale, horizontalAlign, verticalAlign, color); foreach (var glyph in glyphs) { var uv = glyph.uvRect; var dest = glyph.destinationRect; var bottomLeft = new UIVertex() { position = new Vector3(dest.xMin, dest.yMin, 0f), uv0 = new Vector2(uv.xMin, uv.yMin), color = color }; var bottomRight = new UIVertex() { position = new Vector3(dest.xMax, dest.yMin, 0f), uv0 = new Vector2(uv.xMax, uv.yMin), color = color }; var topRight = new UIVertex() { position = new Vector3(dest.xMax, dest.yMax, 0f), uv0 = new Vector2(uv.xMax, uv.yMax), color = color }; var topLeft = new UIVertex() { position = new Vector3(dest.xMin, dest.yMax, 0f), uv0 = new Vector2(uv.xMin, uv.yMax), color = color }; vh.AddUIVertexQuad(new UIVertex[] { bottomLeft, topLeft, topRight, bottomRight }); } } } }
namespace SoftwareDeveloperIO.Collections.Generic { public interface ILinkedList<T> { int Count { get; } LinkedListNode<T> First { get; } bool IsEmpty { get; } LinkedListNode<T> Last { get; } void AddFirst(T value); void AddLast(T value); void Clear(); bool Contains(T value); LinkedListNode<T> Find(T value); bool Remove(T value); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ImageAnime : MonoBehaviour { // Use this for initialization void Start () { string path = string.Format("LVL/imgs/{0}", Scenes.Id); transform.GetComponent<Image>().sprite = Resources.Load<Sprite>(path); } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using UnityEngine.UI; public class SnakeBehaviour : MonoBehaviour { Animator m_animator; private bool isDead; bool isWalkingPressed; bool isLeftPressed; bool isRightPressed; bool isAtackPressed; float speed = 1; int lifes = 2; private RawImage heart1, heart2, heart3; public Rigidbody rb; void OnCollisionEnter(Collision colider) { var fullname = colider.gameObject.name; var name = fullname.Substring(0, 4); if (name == "Cube") { lifes--; if (lifes < 1) { m_animator.SetBool("isDead", true); isDead = true; } Debug.Log(lifes); } else if (name == "Plan" & lifes < 3) { Destroy(colider.gameObject); lifes++; Debug.Log(lifes); } } void Start() { var boxCollider = gameObject.AddComponent<BoxCollider>(); boxCollider.isTrigger = true; rb = GetComponent<Rigidbody>(); m_animator = GetComponent<Animator>(); heart1 = GameObject.Find("heart1").GetComponent<RawImage>(); heart2 = GameObject.Find("heart2").GetComponent<RawImage>(); heart3 = GameObject.Find("heart3").GetComponent<RawImage>(); } void FixedUpdate() { if (!isDead) { moveAnimation(); move(); } } void Update(){ getLifes(); } private void move() { Vector3 movement = new Vector3(); if (isWalkingPressed) { transform.position += transform.forward * speed; rb.MovePosition(transform.position * Time.fixedDeltaTime); } if (isRightPressed) { movement = new Vector3(0, 79, 0); Quaternion deltaRotation = Quaternion.Euler(movement * Time.deltaTime); rb.MoveRotation(rb.rotation * deltaRotation); } if (isLeftPressed) { movement = new Vector3(0, -79, 0); Quaternion deltaRotation = Quaternion.Euler(movement * Time.deltaTime); rb.MoveRotation(rb.rotation * deltaRotation); } } private void moveAnimation() { isWalkingPressed = Input.GetKey("w"); isLeftPressed = Input.GetKey("a"); isRightPressed = Input.GetKey("d"); isAtackPressed = Input.GetKey("space"); if (isWalkingPressed || isLeftPressed || isRightPressed) { m_animator.SetBool("isWalking", true); } else { m_animator.SetBool("isWalking", false); } if (isAtackPressed) { m_animator.SetBool("isAtacking", true); } else { m_animator.SetBool("isAtacking", false); } } private void endGame() { } private void getLifes() { switch (lifes) { case 3: heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(true); heart3.gameObject.SetActive(true); break; case 2: heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(true); heart3.gameObject.SetActive(false); break; case 1: heart1.gameObject.SetActive(true); heart2.gameObject.SetActive(false); heart3.gameObject.SetActive(false); break; case 0: heart1.gameObject.SetActive(false); heart2.gameObject.SetActive(false); heart3.gameObject.SetActive(false); break; } } }