text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace StreamTest { public static class FileSystemInfoTest { public static void ThroughFilesAndDirs() { string path = @"C:\"; foreach (var entry in Directory.EnumerateDirectories(path)) { DisplayFileSystemInfoAttributes(new DirectoryInfo(entry)); } foreach (var entry in Directory.EnumerateFiles(path)) { DisplayFileSystemInfoAttributes(new FileInfo(entry)); } } static void DisplayFileSystemInfoAttributes(FileSystemInfo fsi) { string entryType = "File"; if((fsi.Attributes & FileAttributes.Directory) == FileAttributes.Directory) { entryType = "Directory"; } Console.WriteLine("{0} entry {1} was created on {2:Y}", entryType, fsi.FullName, fsi.CreationTime); } } }
using BP12.Collections; using DChild.Gameplay.Combat; using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public class GraveDiggerBrain : MinionAIBrain<GraveDigger> { [SerializeField] [MinValue(0f)] private float m_attackRange; [SerializeField] private CountdownTimer m_attackRest; private bool m_isAttacking; private bool m_isResting; public override void Enable(bool value) { enabled = value; m_minion.Idle(); } public override void ResetBrain() { m_attackRest.EndTime(false); m_isAttacking = false; m_isResting = false; } public override void SetTarget(IDamageable target) { m_target = target; } private void Update() { if (m_minion.waitForBehaviourEnd) return; if (m_isAttacking) { m_attackRest.Reset(); m_isResting = true; } else if (m_isResting) { m_attackRest.Tick(m_minion.time.deltaTime); } if (m_target == null) { m_minion.DigGrave(); } else { if (IsLookingAt(m_target.position)) { if (Vector2.Distance(m_minion.position, m_target.position) <= m_attackRange) { m_minion.Attack(); m_isAttacking = true; } else { m_minion.Idle(); } } else { m_minion.Turn(); } } } } }
using System; using Pe.Stracon.SGC.Infraestructura.CommandModel.Base; namespace Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual { /// <summary> /// Clase que representa la entidad Requerimiento Parrafo /// </summary> /// <remarks> /// Creación : GMD 20150511 <br /> /// Modificación : <br /> /// </remarks> public class RequerimientoParrafoEntity: Entity { /// <summary> /// Codigo de RequerimientoParrafo /// </summary> public Guid CodigoRequerimientoParrafo { get; set; } /// <summary> /// Codigo de Requerimiento /// </summary> public Guid CodigoRequerimiento { get; set; } /// <summary> /// Codigo de PlantillaParrafo /// </summary> public Guid CodigoPlantillaParrafo { get; set; } /// <summary> /// Contenido /// </summary> public string ContenidoParrafo { get; set; } } }
using System; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace BuildingGame { static class Fonts { public static SpriteFont Standard { get; set; } static Fonts() { } public static void LoadContent(ContentManager content) { Standard = content.Load<SpriteFont>(@"gui\font"); } } }
using Chloe.Dtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chloe.NBAClient.Contracts { public interface INBAClient { Task<AllPlayersResponseDto> GetAllPlayersAsync(); } }
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 NPOI; using NPOI.HPSF; using NPOI.HSSF; using NPOI.HSSF.UserModel; using NPOI.POIFS; using NPOI.Util; using NPOI.HSSF.Util; using NPOI.HSSF.Extractor; using System.IO; using System.Data.SqlClient; using NPOI.SS.UserModel; using System.Configuration; using NPOI.XSSF.UserModel; using TKITDLL; namespace TKECOMMERCE { public partial class FrmREDSCCOPTI : Form { SqlConnection sqlConn = new SqlConnection(); SqlCommand sqlComm = new SqlCommand(); string connectionString; StringBuilder sbSql = new StringBuilder(); StringBuilder sbSqlQuery = new StringBuilder(); SqlDataAdapter adapter = new SqlDataAdapter(); SqlCommandBuilder sqlCmdBuilder = new SqlCommandBuilder(); SqlTransaction tran; SqlCommand cmd = new SqlCommand(); DataSet ds = new DataSet(); DataTable dt = new DataTable(); string NowDB; string NowTable = null; int result; public FrmREDSCCOPTI() { InitializeComponent(); } #region FUNTION public void ExportExcel(DataSet dsExcel, string Tabelname) { String NowDB = "TK"; //建立Excel 2003檔案 IWorkbook wb = new XSSFWorkbook(); ISheet ws; dt = dsExcel.Tables[Tabelname]; ////建立Excel 2007檔案 //IWorkbook wb = new XSSFWorkbook(); //ISheet ws; if (dt.TableName != string.Empty) { ws = wb.CreateSheet(dt.TableName); } else { ws = wb.CreateSheet("Sheet1"); } ws.CreateRow(0);//第一行為欄位名稱 for (int i = 0; i < dt.Columns.Count; i++) { ws.GetRow(0).CreateCell(i).SetCellValue(dt.Columns[i].ColumnName); } for (int i = 0; i < dt.Rows.Count; i++) { ws.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { ws.GetRow(i + 1).CreateCell(j).SetCellValue(dt.Rows[i][j].ToString()); } } if (Directory.Exists(@"c:\temp\")) { //資料夾存在 } else { //新增資料夾 Directory.CreateDirectory(@"c:\temp\"); } StringBuilder filename = new StringBuilder(); filename.AppendFormat(@"c:\temp\銷退{0}.xlsx", DateTime.Now.ToString("yyyyMMdd")); FileStream file = new FileStream(filename.ToString(), FileMode.Create);//產生檔案 wb.Write(file); file.Close(); MessageBox.Show("匯出完成-EXCEL放在-" + filename.ToString()); FileInfo fi = new FileInfo(filename.ToString()); if (fi.Exists) { System.Diagnostics.Process.Start(filename.ToString()); } else { //file doesn't exist } } public void Search() { NowDB = "TK"; //20210902密 Class1 TKID = new Class1();//用new 建立類別實體 SqlConnectionStringBuilder sqlsb = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["dbconn"].ConnectionString); //資料庫使用者密碼解密 sqlsb.Password = TKID.Decryption(sqlsb.Password); sqlsb.UserID = TKID.Decryption(sqlsb.UserID); String connectionString; sqlConn = new SqlConnection(sqlsb.ConnectionString); sbSql.Clear(); sbSqlQuery.Clear(); sbSqlQuery.AppendFormat(" TI003>='{0}' AND TI003<='{1}'", dateTimePicker1.Value.ToString("yyyyMMdd"), dateTimePicker2.Value.ToString("yyyyMMdd")); if (comboBox1.Text.ToString().Equals("銷退明細")) { sbSql.AppendFormat(" SELECT TI001 AS '單別',TI002 AS '單號',TI003 AS '日期',TI004 AS '客代',TI021 AS '客戶' ,TJ004 AS '品號',TJ005 AS '品名',TJ007 AS '數量',TJ008 AS '單位',TJ021 AS '金額' FROM [{0}].dbo.COPTI,[{1}].dbo.COPTJ WHERE TI001=TJ001 AND TI002=TJ002 AND TI001='A246' AND TJ021='Y' AND {2} ", NowDB, NowDB, sbSqlQuery.ToString()); NowTable = "TEMP1"; } else if (comboBox1.Text.ToString().Equals("品號彙總")) { sbSql.AppendFormat(" SELECT TJ004 AS '品號',TJ005 AS '品名',CONVERT(real, SUM(TJ007)) AS '數量',TJ008 AS '單位',CONVERT(real, SUM(TJ012)) AS '金額' FROM [TK].dbo.COPTI,[TK].dbo.COPTJ WHERE TI001=TJ001 AND TI002=TJ002 AND TI001='A246' AND TJ021='Y' AND {2} GROUP BY TJ004,TJ005,TJ008 ORDER BY SUM(TJ007) DESC", NowDB, NowDB, sbSqlQuery.ToString()); NowTable = "TEMP2"; } else if (comboBox1.Text.ToString().Equals("金額日彙總")) { sbSql.AppendFormat(" SELECT TI003 AS '日期',CONVERT(real, SUM(TJ007)) AS '數量',CONVERT(real, SUM(TJ012)) AS '金額' FROM [TK].dbo.COPTI,[TK].dbo.COPTJ WHERE TI001=TJ001 AND TI002=TJ002 AND TI001='A246' AND TJ021='Y' AND {2} GROUP BY TI003 ", NowDB, NowDB, sbSqlQuery.ToString()); NowTable = "TEMP3"; } adapter = new SqlDataAdapter(@"" + sbSql, sqlConn); sqlCmdBuilder = new SqlCommandBuilder(adapter); sqlConn.Open(); ds.Clear(); if (comboBox1.Text.ToString().Equals("銷退明細")) { adapter.Fill(ds, NowTable); dataGridView1.DataSource = ds.Tables[NowTable]; } else if (comboBox1.Text.ToString().Equals("品號彙總")) { adapter.Fill(ds, NowTable); dataGridView1.DataSource = ds.Tables[NowTable]; } else if (comboBox1.Text.ToString().Equals("金額日彙總")) { adapter.Fill(ds, NowTable); dataGridView1.DataSource = ds.Tables[NowTable]; } sqlConn.Close(); } #endregion #region BUTTON private void button1_Click(object sender, EventArgs e) { Search(); } private void button2_Click(object sender, EventArgs e) { ExportExcel(ds, NowTable); } #endregion } }
using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Services; namespace Uintra.Core.UmbracoEvents.Services.Contracts { public interface IUmbracoMediaSavedEventService { void ProcessMediaSaved(IMediaService sender, SaveEventArgs<IMedia> args); } }
using System; using System.Collections.Generic; using System.IO; using System.Xml; using Manor.Plugin; using Manor.Plugin.Application; using PhuLiNet.Plugin.Application; using PhuLiNet.Plugin.Contracts; using PhuLiNet.Plugin.Manager; using PhuLiNet.Plugin.Menu; using PhuLiNet.Plugin.Menu.MainMenu; namespace PhuLiNet.Plugin { public class InternalHostApplication : IHostApplicationInternals { private string _startupPath; private string _appConfigFile; //private string _configId; private IPluginManager _pluginManager; private IMenuManager _mainMenuManager; //private IMenuManager _toolbarManager; //private Configurations _configs; //private Configuration _activeConfig; //public EMenuSource MenuSource //{ // get // { // if (_activeConfig != null && // _activeConfig.GetMainMenuConfig() is MenuConfigByDb) // { // return EMenuSource.Database; // } // return EMenuSource.XmlFile; // } //} public string AppConfigFile { get { return _appConfigFile; } internal set { _appConfigFile = value; } } public string StartupPath { get { return _startupPath; } internal set { _startupPath = value; } } //public string LanguageCode { get; set; } //public string MenuRootNode { get; set; } //public string ConfigId //{ // get { return _configId; } // internal set { _configId = value; } //} //public IApplicationInfo GetApplicationInfo() //{ // if (_applicationInfo == null) // { // LoadApplicationInfo(); // } // return _applicationInfo; //} //public List<IMenuItem> GetMainMenu() //{ // return _mainMenuManager.GetMenu(); //} //public List<IMenuItem> GetToolbarMenu() //{ // return _toolbarManager != null ? _toolbarManager.GetMenu() : null; //} //public IMenuItem GetAutoStartMenuItem() //{ // IMenuItem autoStartMenuItem = null; // foreach (IMenuItem item in _mainMenuManager.GetMenu()) // { // if (item.HasSubMenu) // { // foreach (IMenuItem subMenu in item.SubMenus) // { // if (subMenu.IsValid && subMenu.IsVisible && subMenu.SupportsAutoStart) // { // autoStartMenuItem = subMenu; // break; // } // } // } // } // return autoStartMenuItem; //} public string AutoStartPluginId { get; set; } public void AddPlugin(IPlugin plugin) { _pluginManager.AddPlugin(plugin); } public IPlugin GetPlugin(string pluginId) { return _pluginManager.GetPlugin(pluginId); } public bool PluginExists(string pluginId) { return _pluginManager.PluginExists(pluginId); } public IPlugin GetPlugin(Type pluginType) { return _pluginManager.GetPlugin(pluginType); } public IList<IPlugin> GetReplacementPlugin(IPlugin oldPlugin) { return _pluginManager.GetReplacementPlugin(oldPlugin); } public IPlugin GetPluginByShortcut(string pluginShortcut) { return _pluginManager.GetPluginByShortcut(pluginShortcut); } public List<IPlugin> GetPlugins() { return _pluginManager.GetPlugins(); } public List<IPlugin> GetPluginsAllowed() { return _pluginManager.GetPluginsAllowed(); } public List<IPluginSummary> GetPluginSummary() { return _pluginManager.GetPluginSummary(); } public List<IPluginSummary> GetPluginSummaryAllowed() { return _pluginManager.GetPluginSummaryAllowed(); } public IPluginValidator GetPluginValidator() { var pluginValidator = new PluginValidator(_pluginManager); return pluginValidator; } //internal void LoadApplicationInfo() //{ // _applicationInfo = ApplicationFactory.GetInstance(LoadConfig()); //} public void Run() { InitPluginManager(); InitMenus(); } public List<IMenuItem> GetMainMenu() { return _mainMenuManager.GetMenu(); } private void InitPluginManager() { _pluginManager = PluginManagerFactory.CreateInstance(_startupPath); } private void InitMenus() { InitMainMenuManager(); // InitToolbarMenuManager(); AssignPluginsToMenu(GetMainMenu()); // AssignPluginsToMenu(GetToolbarMenu()); } public void ReRun() { InitMenus(); } private void InitMainMenuManager() { _mainMenuManager = MenuManagerFactory.CreateInstanceByPlugin(GetPlugins()); } //private void InitToolbarMenuManager() //{ // if (_activeConfig.ToolbarConfigExists()) // { // if (_activeConfig.GetToolbarConfig() is MenuConfigByFile) // { // var menuConfigByFile = _activeConfig.GetToolbarConfig() as MenuConfigByFile; // _toolbarManager = // MenuManagerFactory.CreateInstanceByFile(Path.Combine(_startupPath, menuConfigByFile.ConfigFile)); // } // else // { // throw new PluginHostException("Unkown menu config found"); // } // } //} private void AssignPluginsToMenu(IEnumerable<IMenuItem> menuItemList) { var pluginAllocator = new PluginAllocator(_pluginManager); pluginAllocator.AssignPluginsToMenu(menuItemList); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace A_day_at_the_Races { public partial class Form1 : Form { public Random MyRandomizer; Greyhound[] GreyhoundArray = new Greyhound[4]; Guy[] GuyArray = new Guy[3]; RadioButton[] radButtons; static public int minimumBetVal = 5; public int counter; int currentGuy; public Form1() { MyRandomizer = new Random(); InitializeComponent(); radButtons = new RadioButton[] { radioButton1, radioButton2, radioButton3 }; counter = 0; int minBet = minimumBetVal; minimumBetLabel.Text = "Minimum bet: " + 5+ " bucks"; GuyArray[0] = new Guy() { Name = "Joe", Cash = 50, MyLabel = joeBetLabel, MyRadioButton = radioButton1, //MyBet = new Bet()// { Amount= 0, Dog =1, Bettor= GuyArray[0] } }; GuyArray[1] = new Guy() { Name = "Bob", Cash = 75, MyLabel = bobBetLabel, MyRadioButton = radioButton2, //MyBet = new Bet()// { Amount = 0, Dog =1 , Bettor = GuyArray[1] } }; GuyArray[2] = new Guy() { Name = "Al", Cash = 45, MyLabel = alBetLabel, MyRadioButton = radioButton3, //MyBet = new Bet() //{ Amount = 0, Dog = 1, Bettor = GuyArray[2] } }; PictureBox[] picBoxArray = { pictureBox1, pictureBox2, pictureBox3, pictureBox4 }; for (int i = 0; i < 4; ++i) { GreyhoundArray[i] = new Greyhound() { MyPictureBox = picBoxArray[i], StartingPosition = picBoxArray[i].Left, RacetrackLength = finishLine.Left, Randomizer = MyRandomizer }; } for (int i=0; i<3; ++i) { GuyArray[i].ClearBet(); GuyArray[i].UpdateLabels(); } radButtons[0].Checked = true; } private void timer1_Tick(object sender, EventArgs e) { ++counter; if (GreyhoundArray[counter % 4].Run()) { int winner = counter % 4 + 1; timer1.Stop(); MessageBox.Show("Congratulations Dog #" + winner + "!!!", "And the winner is..."); string[] GuyString = new string[3]; for (int i=0; i < 3; ++i) { int amountCollected= GuyArray[i].Collect(winner); if (amountCollected<0) GuyString[i] = GuyArray[i].Name+ " loses " + -amountCollected +" bucks. :-("; else if (amountCollected>0) GuyString[i] = GuyArray[i].Name + " wins " + amountCollected + " bucks! :-)"; else GuyString[i] = GuyArray[i].Name + " didn't bet anything... -_-"; GuyArray[i].ClearBet(); } MessageBox.Show(GuyString[0] + "\n\n" + GuyString[1] + "\n\n" + GuyString[2], "The Results are in..."); for (int i=0; i<4; ++i) GreyhoundArray[i].TakeStartingPosition(); betButton.Enabled = true; } } private void startRaceButton_Click(object sender, EventArgs e) { betButton.Enabled = false; timer1.Start(); } private void betButton_Click(object sender, EventArgs e) { GuyArray[currentGuy].PlaceBet((int)amountEntry.Value, (int)dogEntry.Value); } private void radioButton_CheckedChanged(object sender, EventArgs e) { for (currentGuy=0; currentGuy < 3;++currentGuy) { if (radButtons[currentGuy].Checked) break; } nameLabel.Text = GuyArray[currentGuy].Name; amountEntry.Value = (decimal)GuyArray[currentGuy].MyBet.Amount; dogEntry.Value = (decimal)GuyArray[currentGuy].MyBet.Dog; } } }
using BusinessLayer.Concrete; using DataAccessLayer.Concrete.Repositories; using EntityLayer.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using DataAccessLayer.Concrete; namespace MvcProjeKampi.Controllers { public class CategoryController : Controller { // GET: Category CategoryManager c = new CategoryManager(); public ActionResult Index() { return View(c.ListAllBl()) ; } } }
using NUnit.Framework; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wgaffa.Functional.Tests { [TestFixture] public class MaybeEqualityTests { [Test] public void Equals_ShouldReturnFalse_GivenType() { Maybe<int> maybeInt = 5; Assert.That(maybeInt.Equals(5), Is.False); } [Test] public void Equals_ShouldReturnFalse_GivenNone() { Maybe<int> maybeInt = 3; Assert.That(maybeInt.Equals(Maybe<int>.None()), Is.False); } [Test] public void Equals_ShouldReturnTrue_WhenBothAreNone() { Maybe<int> none = Maybe<int>.None(); Assert.That(none.Equals(Maybe<int>.None()), Is.True); } [Test] public void Equals_ShouldReturnTrue_WhenBothAreSomeAndHaveSameValue() { Maybe<int> maybeFive = 5; Maybe<int> maybeOtherFive = 5; Assert.That(maybeFive.Equals(maybeOtherFive), Is.True); } [Test] public void Equals_ShouldReturnFalse_GivenSomeAndNone() { Maybe<int> some = Maybe<int>.Some(5); Maybe<int> none = Maybe<int>.None(); var result = some.Equals(none); Assert.That(result, Is.False); } [Test] public void Equals_ShouldReturnFalse_GivenNoneAndSome() { Maybe<int> some = Maybe<int>.Some(5); Maybe<int> none = Maybe<int>.None(); var result = none.Equals(some); Assert.That(result, Is.False); } [Test] public void Equals_ShouldReturnFalse_ComparingNoneToNull() { var none = Maybe<int>.None(); var result = none.Equals((None<int>)null); Assert.That(result, Is.False); } } }
using Alabo.App.Share.HuDong.Domain.Entities; using System.Collections.Generic; namespace Alabo.App.Share.HuDong { /// <summary> /// 互动活动接口 /// </summary> public interface IHuDong { /// <summary> /// 获取活动的默认奖励 /// </summary> /// <returns></returns> List<HudongAward> DefaultAwards(); /// <summary> /// 互动设置 /// </summary> /// <returns></returns> HudongSetting Setting(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WcfServiceHost.ITS_Service { using Entity; using Repository.ITSRepo; using DTO.ITSDTO; using System.ServiceModel; public class FirmaShrinkService : ITS_ServiceBase<FirmaShrinkRepo , FirmaShrink , FirmaShrinkDTO >, IFirmaShrinkService { } [ServiceContract] public interface IFirmaShrinkService : IServiceBase<FirmaShrinkDTO> { } }
using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DgKMS.Cube.Models { [Table("party_photo")] public class PartyPhoto : Entity<long>, IHasCreationTime, IHasModificationTime { [Column("id")] public override long Id { get; set; } [Column("party_id")] public long PartyId { get; set; } [MaxLength(250)] [Column("url")] public string Url { get; set; } [MaxLength(250)] [Column("url_part")] public string UrlPart { get; set; } [MaxLength(60)] [Column("description")] public string Description { get; set; } [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = true)] [Column("create_time")] public DateTime CreationTime { get; set; } [DataType(DataType.DateTime)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd HH:mm:ss}", ApplyFormatInEditMode = true)] [Column("modified_time")] public DateTime? LastModificationTime { get; set; } } }
//using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TeacherMono : MonoBehaviour { public static TeacherMono instance = null; GameManager gamemanager; Teachermanager teachermanager; Teacher teacherinfo; public string Name; // initaial payment [SerializeField] private int HiringCost; // initaial payment [SerializeField] private int salary; // each teacher's salary that will be paid at the end of the day public int Salary { get => salary; set => salary = value; } public int HiringCost1 { get => HiringCost; set => HiringCost = value; } private void Awake() { if (instance == null) { instance = this; } else if (instance != this) { //Destroy(gameObject); } } void Start() { gamemanager = GameManager.instance; teachermanager = Teachermanager.instance; } void Update() { } }
using System; using System.Collections.Generic; using System.Text; namespace Cosmetic_Store { class Logica { //DECLARACION MATRIZ static string[,] matrizProductos = new string[5, 4]; #region INICIO ///<summary> /// INICIAMOS EL PROGRAMA Y PEDIMOS INGRESAR LOS DATOS DE USUARIOS ///</summary> public static void InicioPrograma() { string user; string pin; bool datosCorrectos = false; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("BIENVENIDOS A LA TIENDA DE COSMETICA!\n"); bool continuar = true; do { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Por favor ingrese su login:"); Console.ForegroundColor = ConsoleColor.White; user = Console.ReadLine().Trim(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Por favor ingrese su pasword:"); Console.ForegroundColor = ConsoleColor.White; //while (int.TryParse(Console.ReadLine().Trim(), out pin)); pin = Console.ReadLine().Trim(); Console.ResetColor(); if ((user == "Pepe" && pin == "123") || (user == "Caro" && pin == "456")) { datosCorrectos = true; Console.WriteLine("Se ingreso correctamente"); } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("\nNo se puedo ingresar, ingrese los datos correctos"); Console.ResetColor(); } Logica.LlenarMatriz(); if (datosCorrectos == true) { do { continuar = Menu.MainMenu(); } while (continuar == true); } } while (continuar == true); } #endregion #region DATOS DE LA MATRIZ ///<summary> /// LLENAMOS LA MATRIZ ///</summary> public static void LlenarMatriz() { matrizProductos[0, 0] = "1"; matrizProductos[1, 0] = "2"; matrizProductos[2, 0] = "3"; matrizProductos[3, 0] = "4"; matrizProductos[0, 1] = "Mascara"; matrizProductos[1, 1] = "Rush"; matrizProductos[2, 1] = "Delineador"; matrizProductos[3, 1] = "Desmaquillante"; matrizProductos[0, 2] = "Maybelline"; matrizProductos[1, 2] = "Maybelline"; matrizProductos[2, 2] = "MaxFactor"; matrizProductos[3, 2] = "Loreal"; matrizProductos[0, 3] = "600"; matrizProductos[1, 3] = "500"; matrizProductos[2, 3] = "300"; matrizProductos[3, 3] = "400"; } #endregion #region MOSTRAR TODO ///<summary> /// IMPRIMIMOS TODOS LOS DATOS DE LA MATRIZ ///</summary> public static void MostrarTodo() { for (int fila = 0; fila < matrizProductos.GetLength(0); fila++) { for (int columna = 0; columna < matrizProductos.GetLength(1); columna++) { if (!string.IsNullOrEmpty(matrizProductos[fila, 0])) { Console.ForegroundColor = ConsoleColor.White; Console.Write("{0,-1}| ", matrizProductos[fila, columna]); Console.ResetColor(); } } Console.WriteLine(); } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("\nPresione una tecla para volver al menu anterior"); Console.ResetColor(); Console.ReadKey(); } #endregion #region BUSCAR POR MARCA ///<summary> /// BUSCAMOS POR MARCA DENTRO DE LA MATRIZ ///</summary> public static void BuscarMarca() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Ingrese la marca que quiere encontrar"); Console.ForegroundColor = ConsoleColor.White; string datoBuscar = Console.ReadLine(); while (string.IsNullOrEmpty(datoBuscar.Trim())) { Console.WriteLine("Ingrese la marca para buscar"); datoBuscar = Console.ReadLine(); } Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("\nLos datos del producto buscado son:\n"); for (int fila = 0; fila < matrizProductos.GetLength(0); fila++) { if (string.IsNullOrEmpty(matrizProductos[fila, 2]) == false && matrizProductos[fila, 2].ToLower().Contains(datoBuscar.ToLower())) { for (int columna = 0; columna < matrizProductos.GetLength(1); columna++) { Console.ForegroundColor = ConsoleColor.White; Console.Write("{0} | ", matrizProductos[fila, columna]); Console.ResetColor(); } Console.WriteLine(); } } Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("\nPresione una tecla para volver al menu anterior"); Console.ResetColor(); Console.ReadKey(); } #endregion #region AGREGAR PRODUCTO NUEVO ///<summary> /// AGREGAMOS UN PRODUCTO NUEVO /// E IMPRIMIMOS LA MATRIZ CON EL PRODUCTO AGREGADO ///</summary> public static void AgregarProducto() { bool datoAgregar = false; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Ingrese el id del producto nuevo:"); Console.ForegroundColor = ConsoleColor.White; string idNew = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Ingrese el nombre del producto nuevo:"); Console.ForegroundColor = ConsoleColor.White; string nombreNew = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Ingrese la marca del producto nuevo:"); Console.ForegroundColor = ConsoleColor.White; string marcaNew = Console.ReadLine(); Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Ingrese el precio del producto nuevo:"); Console.ForegroundColor = ConsoleColor.White; string precioNew = Console.ReadLine(); for (int fila = 0; fila < matrizProductos.GetLength(0); fila++) { if (string.IsNullOrEmpty(matrizProductos[fila, 0])) { matrizProductos[fila, 0] = idNew; matrizProductos[fila, 1] = nombreNew; matrizProductos[fila, 2] = marcaNew; matrizProductos[fila, 3] = precioNew; datoAgregar = true; break; } } if (datoAgregar == true) { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("\nDato agregado correctamente!"); Console.WriteLine("Presione ENTER para ver todo con el dato agregado\n"); } else { Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("\nNo se pudo ingresar el dato\n"); } Console.ResetColor(); Console.ReadKey(); } #endregion #region ELIMINAR PRODUCTO ///<summary> /// ELIMINAMOS EL PRODUCTO /// E IMPRIMIMOS LA MATRIZ SIN EL PRODUCTO ELIMINADO ///</summary> public static void EliminarProducto() { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Ingrese el nombre del producto que queria eliminar"); Console.ForegroundColor = ConsoleColor.White; string datoEliminar = Console.ReadLine(); while (string.IsNullOrEmpty(datoEliminar.Trim())) { Console.WriteLine("Ingrese la marca para buscar"); datoEliminar = Console.ReadLine(); } for (int fila = 0; fila < matrizProductos.GetLength(0); fila++) { if (string.IsNullOrEmpty(matrizProductos[fila, 1]) == false && matrizProductos[fila, 1].ToLower().Contains(datoEliminar.ToLower())) { matrizProductos[fila, 0] = null; matrizProductos[fila, 1] = null; matrizProductos[fila, 2] = null; matrizProductos[fila, 3] = null; Console.ForegroundColor = ConsoleColor.Magenta; Console.WriteLine("\nEl producto " + datoEliminar + " fue eliminado"); Console.WriteLine("Presione ENTER para ver todo sin el dato eliminado\n"); Console.WriteLine(); } } Console.ResetColor(); Console.ReadKey(); } #endregion #region FACTURACION ///<summary> /// IMPRIMIMOS EL VALOR TOTAL DE UNA DE LAS COLUMNAS ///</summary> public static void Facturacion() { int montoTotal = 0; for (int fila = 0; fila < matrizProductos.GetLength(0); fila++) { if (matrizProductos[fila, 3] != null) { montoTotal += int.Parse(matrizProductos[fila, 3]); } } Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("La suma de todos los precios es {0}", montoTotal); Console.ForegroundColor = ConsoleColor.DarkGreen; Console.WriteLine("\nPresione una tecla para volver al menu anterior"); Console.ResetColor(); Console.ReadKey(); } #endregion } }
using GraphicalEditor.Enumerations; using GraphicalEditor.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GraphicalEditor.DTO; namespace GraphicalEditor.Service { public class RoomService : GenericHTTPService { public List<RoomDTO> GetAllRooms() { return (List<RoomDTO>)HTTPGetRequest<RoomDTO>("room"); } public List<RoomSchedulesDTO> GetRoomSchedules(int roomId) { return (List<RoomSchedulesDTO>)HTTPGetRequest<RoomSchedulesDTO>("room/roomSchedule/" + roomId); } } }
using Backend.Model.Pharmacies; using System.Collections.Generic; namespace IntegrationAdaptersTenderService.Repository { public interface ITenderMessageRepository { TenderMessage GetById(int id); IEnumerable<TenderMessage> GetAll(); IEnumerable<TenderMessage> GetAllByTender(int id); void CreateTenderMessage(TenderMessage tm); void UpdateTenderMessage(TenderMessage tm); TenderMessage GetAcceptedByTenderId(int id); } }
using Autofac; using EmberKernel.Services.Statistic; using EmberKernel.Services.Statistic.Hub; using Statistic.WpfUI.UI.Command; using Statistic.WpfUI.UI.Model; using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Input; using IComponent = EmberKernel.Plugins.Components.IComponent; namespace Statistic.WpfUI.UI.ViewModel { public class StatisticEditorViewModel : IComponent, IEditorContextViewModel { public IStatisticHub Formats { get; set; } public IDataSource Variables { get; set; } public event PropertyChangedEventHandler PropertyChanged; public event Action<EditorMode> OnEditorModeChanged; public ICommand CreateFormat { get; private set; } public ICommand SaveFormat { get; private set; } public ICommand CancelFormat { get; private set; } public ICommand DeleteFormat { get; private set; } private readonly ILifetimeScope _viewModeScope; public StatisticEditorViewModel(ILifetimeScope scope) { MoveTo(EditorMode.Idle); _viewModeScope = scope.BeginLifetimeScope((builder) => { builder.RegisterInstance(this).As<IEditorContextViewModel>().SingleInstance(); builder.RegisterType<NewFormatCommand>().As<IEditorContextCommand>().Named<IEditorContextCommand>("Create"); builder.RegisterType<SaveFormatCommand>().As<IEditorContextCommand>().Named<IEditorContextCommand>("Save"); builder.RegisterType<CancelCommand>().As<IEditorContextCommand>().Named<IEditorContextCommand>("Cancel"); builder.RegisterType<DeleteCommand>().As<IEditorContextCommand>().Named<IEditorContextCommand>("Delete"); }); CreateFormat = _viewModeScope.ResolveNamed<IEditorContextCommand>("Create"); SaveFormat = _viewModeScope.ResolveNamed<IEditorContextCommand>("Save"); CancelFormat = _viewModeScope.ResolveNamed<IEditorContextCommand>("Cancel"); DeleteFormat = _viewModeScope.ResolveNamed<IEditorContextCommand>("Delete"); } private HubFormat _selectedHubFormat; public HubFormat SelectedHubFormat { get => _selectedHubFormat; set { if (Equals(_selectedHubFormat, value)) return; _selectedHubFormat = value; OnPropertyChanged(); } } private InEditHubFormat _editingHubFormat; public InEditHubFormat EditingHubFormat { get => _editingHubFormat; set { if (Equals(_editingHubFormat, value)) return; _editingHubFormat = value; OnPropertyChanged(); } } public Visibility CreateVisibility { get; set; } public Visibility SaveVisibility { get; set; } public Visibility DeleteVisibility { get; set; } public Visibility CancelVisibility { get; set; } public Visibility EditorVisibility { get; set; } private EditorMode _mode; public EditorMode Mode { get => _mode; set { if (value == _mode) return; _mode = value; MoveTo(_mode); OnEditorModeChanged?.Invoke(_mode); OnPropertyChanged(); } } private void MoveTo(EditorMode mode) { switch (mode) { case EditorMode.Idle: CreateVisibility = Visibility.Visible; SaveVisibility = Visibility.Collapsed; DeleteVisibility = Visibility.Collapsed; CancelVisibility = Visibility.Collapsed; EditorVisibility = Visibility.Hidden; break; case EditorMode.Creating: CreateVisibility = Visibility.Collapsed; SaveVisibility = Visibility.Visible; DeleteVisibility = Visibility.Collapsed; CancelVisibility = Visibility.Visible; EditorVisibility = Visibility.Visible; break; case EditorMode.Editing: CreateVisibility = Visibility.Collapsed; SaveVisibility = Visibility.Visible; DeleteVisibility = Visibility.Visible; CancelVisibility = Visibility.Visible; EditorVisibility = Visibility.Visible; break; default: break; } OnPropertyChanged(nameof(CreateVisibility)); OnPropertyChanged(nameof(SaveVisibility)); OnPropertyChanged(nameof(DeleteVisibility)); OnPropertyChanged(nameof(CancelVisibility)); OnPropertyChanged(nameof(EditorVisibility)); } protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } public void Dispose() { _viewModeScope.Dispose(); } } }
using System.Collections.Generic; using System.Linq; using DFC.ServiceTaxonomy.GraphSync.Extensions; using DFC.ServiceTaxonomy.GraphSync.Interfaces; using DFC.ServiceTaxonomy.GraphSync.Models; namespace DFC.ServiceTaxonomy.GraphSync.CosmosDb.Commands { public class CosmosDbDeleteNodesByTypeCommand : IDeleteNodesByTypeCommand { public HashSet<string> NodeLabels { get; set; } = new HashSet<string>(); public List<string> ValidationErrors() { List<string> validationErrors = new List<string>(); if (!NodeLabels.Any()) validationErrors.Add($"Missing {nameof(NodeLabels)}."); return validationErrors; } public Query Query { get { this.CheckIsValid(); var contentTypes = string.Join(",", NodeLabels.Where(nodeLabel => !nodeLabel.Equals("Resource", System.StringComparison.InvariantCultureIgnoreCase)).ToArray()); var parameters = new Dictionary<string, object> { {"ContentType", contentTypes } }; return new Query("DeleteNodesByType", parameters); } } public static implicit operator Query(CosmosDbDeleteNodesByTypeCommand c) => c.Query; public void ValidateResults(List<IRecord> records, IResultSummary resultSummary) { //todo: What validation is possible here? } } }
using CarInsurance.Models; using CarInsurance.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CarInsurance.Controllers { public class AdminController : Controller { // GET: Admin public ActionResult Index() { using (AutoInsuranceEntities db = new AutoInsuranceEntities()) { var quotes = db.QuoteInfoes; var quotesVms = new List<QuotesVm>(); foreach (var quote in quotes) { var quoteVm = new QuotesVm(); quoteVm.FirstName = quote.FirstName; quoteVm.LastName = quote.LastName; quoteVm.EmailAddress = quote.EmailAddress; quotesVms.Add(quoteVm); } return View(quotesVms); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; public partial class Viewinvoice3 : System.Web.UI.Page { private String num; protected void Page_Load(object sender, EventArgs e) { num=Session["no"].ToString(); ConnectionClass obj = new ConnectionClass(); String qry="select * from Appointment where aptnumber='"+num+"'"; DataTable dt =obj.getTable(qry); apt.Text=dt.Rows[0]["aptnumber"].ToString(); txtname.Text = dt.Rows[0]["name"].ToString(); txtmob.Text = dt.Rows[0]["phone"].ToString(); txtaptdate.Text = dt.Rows[0]["aptdate"].ToString(); txtapttime.Text = dt.Rows[0]["tym"].ToString(); txtemail.Text = dt.Rows[0]["email"].ToString(); txtapplydate.Text = dt.Rows[0]["applydate"].ToString(); TextBox2.Text = dt.Rows[0]["service"].ToString(); String qry1 = " select service from Service where id='" + TextBox2.Text + "'"; ConnectionClass db = new ConnectionClass(); String s = db.getSingleData(qry1); txtservice.Text = s; txtstatus.Text=dt.Rows[0]["status"].ToString(); if (txtstatus.Text != null) { Label1.Visible = false; DropDownList1.Visible = false; txtrdate.Visible = true; txtrdate.Text = dt.Rows[0]["remarkdate"].ToString(); Button1.Visible = false; txtremark.ReadOnly = true; txtremark.Text = dt.Rows[0]["remark"].ToString(); } if(String.IsNullOrEmpty(txtstatus.Text)) { txtrdate.Visible = false; txtremark.ReadOnly = false; DropDownList1.Visible = true; Button1.Visible = true; Label2.Visible = false; Label1.Visible = true; } apt.ReadOnly = true; txtname.ReadOnly = true; txtmob.ReadOnly = true; txtaptdate.ReadOnly = true; txtapttime.ReadOnly = true; txtemail.ReadOnly = true; txtstatus.ReadOnly = true; txtapplydate.ReadOnly = true; txtservice.ReadOnly = true; txtrdate.ReadOnly = true; } protected void Button1_Click(object sender, EventArgs e) { String no = apt.Text; String remark=txtremark.Text; String status=DropDownList1.SelectedItem.Text; DateTime today=DateTime.Today; String d=today.ToString(); ConnectionClass obj = new ConnectionClass(); String qry = "update Appointment set status='" + status + "',remark='" + remark + "',remarkdate='" + d + "' where aptnumber='" + no + "'"; obj.Manipulate(qry); String qr1 = "select status,remark,remarkdate from appointment where aptnumber='" + no + "'"; DataTable dt = obj.getTable(qr1); txtstatus.Text = dt.Rows[0]["status"].ToString(); txtremark.Text = dt.Rows[0]["remark"].ToString(); txtrdate.Text = dt.Rows[0]["remarkdate"].ToString(); Label2.Visible = true; Label1.Visible = false; txtremark.ReadOnly = true; txtrdate.Visible = true; DropDownList1.Visible = false; Button1.Visible = false; } }
using System; using System.Collections; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Single; using UnityEditor; using UnityEngine; // A triangle shape consisting of Constant Strain Triangles (CST) // // As the name implies the strain is the same across the entire triangle. This leads to discontinuities in strain from one triangle to the next. public class CSTriangleShape : FEMShape2D<CSTriangleElement> { protected override int NodesPerElement => 3; protected override void Start() { base.Start(); foreach (var e in Elements) e.FixPointOrder(Nodes); } protected override void OnDrawGizmos() { // Elements Gizmos.color = Color.black; foreach (var e in Elements) { Gizmos.DrawLine(GetNodeWorldPosition(e.NodeIdxA), GetNodeWorldPosition(e.NodeIdxB)); Gizmos.DrawLine(GetNodeWorldPosition(e.NodeIdxB), GetNodeWorldPosition(e.NodeIdxC)); Gizmos.DrawLine(GetNodeWorldPosition(e.NodeIdxC), GetNodeWorldPosition(e.NodeIdxA)); } base.OnDrawGizmos(); } protected override void EnsureValidElements() { if (Elements == null) return; foreach (var e in Elements) { if (e.NodeIdxA >= Nodes.Count) e.NodeIdxA = Nodes.Count - 1; if (e.NodeIdxB >= Nodes.Count) e.NodeIdxB = Nodes.Count - 1; if (e.NodeIdxB >= Nodes.Count) e.NodeIdxB = Nodes.Count - 1; } } protected override void ApplyGravityToForceVector(Vector<float> forceVector, Vector2 scaledGravity) { foreach (var element in Elements) { // Load is equally distributed on all nodes. float elementWeight = element.GetTotalMass(Nodes) / 3.0f; scaledGravity *= elementWeight; forceVector[element.NodeIdxA*2] += scaledGravity.x; forceVector[element.NodeIdxA*2+1] += scaledGravity.y; forceVector[element.NodeIdxB*2] += scaledGravity.x; forceVector[element.NodeIdxB*2+1] += scaledGravity.y; forceVector[element.NodeIdxC*2] += scaledGravity.x; forceVector[element.NodeIdxC*2+1] += scaledGravity.y; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Forms; namespace CSharp_RegExpress { static class Program { /// <summary> /// 应用程序的主入口点。 /// </summary> [STAThread] static void Main() { //Application.EnableVisualStyles(); //Application.SetCompatibleTextRenderingDefault(false); //Application.Run(new Form1()); string TaobaoLink = "<a href=\"http://www.taobao.com\" title=\"特殊的\" target=\"_blank\"/><a href=\"http://www.taobao.com\" title=\"淘宝网 - 淘!我喜欢\" target=\"_blank\">淘宝</a><a href=\"http://www.taobao.com\" title=\"淘宝网 - 淘!我喜欢\" target=\"_blank\">淘宝</a><a href=\"http://www.taobao.com\" title=\"淘宝网 - 淘!我喜欢\" target=\"_blank\">淘宝</a><a href=\"http://www.taobao.com\" title=\"淘宝网 - 淘!我喜欢\" target=\"_blank\">淘宝</a><a href=\"http://www.taobao.com\" title=\"淘宝网 - 淘!我喜欢\" target=\"_blank\">淘宝</a>"; string RegexStr = @"<a[^>]+href=""(\S+)""[^>]+title=""([\s\S]+?)""[^>]+>(\S+)</a>"; Console.WriteLine($"TaobaoLink:\r\n{TaobaoLink}\r\n"); Console.WriteLine($"RegexStr:\r\n{RegexStr}\r\n"); Match mat = Regex.Match(TaobaoLink, RegexStr); for (int i = 0; i < mat.Groups.Count; i++) { Console.WriteLine("第" + i + "组:" + mat.Groups[i].Value); } Console.WriteLine("------------------------------------------------------------------"); RegexStr = @"<a.*?(/a>|/>)"; //@"<a.*?/a>"; var mats = Regex.Matches(TaobaoLink, RegexStr); Console.WriteLine($"TaobaoLink:\r\n{TaobaoLink}\r\n"); Console.WriteLine($"RegexStr:\r\n{RegexStr}\r\n"); for (int i = 0; i < mats.Count; i++) { for (int j = 0; j < mats[i].Groups.Count; j++) { Console.WriteLine($"第{i}{j}组:" + mats[i].Groups[j].Value); } } Console.WriteLine("------------------------------------------------------------------"); RegexStr = @"<a.*^[/>].*?</a>|<a.*?/>"; //@"<a.*?/a>"; mats = Regex.Matches(TaobaoLink, RegexStr); Console.WriteLine($"TaobaoLink:\r\n{TaobaoLink}\r\n"); Console.WriteLine($"RegexStr:\r\n{RegexStr}\r\n"); for (int i = 0; i < mats.Count; i++) { for (int j = 0; j < mats[i].Groups.Count; j++) { Console.WriteLine($"第{i}{j}组:" + mats[i].Groups[j].Value); } } Console.Read(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace ClassStudent { class Program { static void Main() { List<Student> students = new List<Student>(); students.Add(new Student("Maya", "Nikolova", 19, "113214", "099334123", "mokaa@abv.bg", new List<int> { 2, 4, 5, 6, }, 2)); students.Add(new Student("Nasko", "Cenov", 33, "234114", "0298334111", "mkok@yaho.bg", new List<int> { 2, 4, 4, 6, }, 2)); students.Add(new Student("Stan", "Azisov", 22, "14232123", "0899934123", "regex@abv.bg", new List<int> { 2, 3, 5, 3, }, 2)); students.Add(new Student("Daniel", "Petkanov", 25, "14923123", "0898333123", "c#sda@abv.bg", new List<int> { 2, 6, 6, 6, }, 1)); students.Add(new Student("Asen", "Dobrudjanski", 29, "213993123", "0234334123", "mkod@abv.bg", new List<int> { 2, 3, 5, 3, }, 2)); students.Add(new Student("Nono", "SkyWallker", 25, "12323123", "12348334123", "xaxaa@gmail.bg", new List<int> { 2, 4, 2, 3, }, 1)); students.Add(new Student("Borislav", "Svetoslavoc", 26, "132213123", "08123334123", "asdsa@abv.bg", new List<int> { 2, 2, 5, 3, }, 2)); students.Add(new Student("Maks", "Armenov", 21, "11323123", "0898334123", "arebea@abv.bg", new List<int> { 6, 4, 5, 6, }, 1)); //Problem 2 Console.WriteLine("/////////////////////////////////PROBLEM 2/////////////////////////"); var group2 = from student in students where student.GroupNumber == 2 orderby student.FirstName ascending select student; foreach (var student in group2) { Console.WriteLine($"Name: {student.FirstName} - Group: {student.GroupNumber}"); } Console.WriteLine("/////////////////////////////////PROBLEM 3/////////////////////////"); //Problem 3 var firstNameBefore = from student in students where student.FirstName.CompareTo(student.LastName) < 0 select student; foreach (var student in firstNameBefore) { Console.WriteLine($"Name: {student.FirstName} {student.LastName}"); } Console.WriteLine("/////////////////////////////////PROBLEM 4/////////////////////////"); //Problem 4 var orderByAge = from student in students where student.Age >= 18 & student.Age <= 24 select student; foreach (var student in orderByAge) { Console.WriteLine($"Name: {student.FirstName} {student.LastName} - Age: {student.Age}"); } Console.WriteLine("/////////////////////////////////PROBLEM 5/////////////////////////"); //Problem 5 List<Student> sortStudents = students.OrderByDescending(x => x.FirstName).ThenByDescending(x => x.LastName).ToList(); foreach (var stude in sortStudents) { Console.WriteLine($" {stude.FirstName} {stude.LastName}" ); } Console.WriteLine("/////////////////////////////////PROBLEM 6/////////////////////////"); //Problem 6 var filterByEmails = from student in students where Regex.IsMatch(student.Email, @"[\w]+@abv.bg", RegexOptions.IgnoreCase) select student; foreach (var a in filterByEmails) { Console.WriteLine($"{a.FirstName} {a.LastName} {a.Email}"); } Console.WriteLine("/////////////////////////////////PROBLEM 7/////////////////////////"); //Problem 7 var filterByPhone = from student in students where Regex.IsMatch(student.Phone, @"\b02", RegexOptions.IgnoreCase) select student; foreach (var a in filterByPhone) { Console.WriteLine($"{a.FirstName} {a.LastName} {a.Phone}"); } Console.WriteLine("/////////////////////////////////PROBLEM 8/////////////////////////"); //Problem 8 var anonymousBULLSHHIT = students. Where(student => student.Marks.Contains(6)) .Select(student => new { student.FirstName, student.LastName, student.Marks }); foreach (var a in anonymousBULLSHHIT) { Console.WriteLine("Name: {0} {1} Marks - {2}", a.FirstName, a.LastName ,string.Join(", ", a.Marks)); } Console.WriteLine("/////////////////////////////////PROBLEM 9/////////////////////////"); //Problem 9 var weekStudent = students.Where(student => student.Marks.Count(mark => mark == 2)==2).Select(student => new { student.FirstName, student.LastName, student.Marks }); foreach (var a in weekStudent) { Console.WriteLine("Name: {0} {1} Marks - {2}", a.FirstName, a.LastName, string.Join(", ", a.Marks)); } //Problem 10 Console.WriteLine("/////////////////////////////////PROBLEM 10/////////////////////////"); var sortByYear = from student in students where Regex.IsMatch(student.FacultyNumber, @"14\b") select student; foreach (var a in sortByYear) { Console.WriteLine("{0} Marks: {1}", a.FirstName, string.Join(", ", a.Marks)); } } } }
using HealthVault.Sample.Xamarin.Core.Configuration; using HealthVault.Sample.Xamarin.Core.Services; using HealthVault.Sample.Xamarin.Core.ViewModels; using HealthVault.Sample.Xamarin.Core.Views; using Microsoft.HealthVault.Client; using Xamarin.Forms; namespace HealthVault.Sample.Xamarin.Core { public partial class App : Application { public App() { InitializeComponent(); var connection = HealthVaultConnectionFactory.Current.GetOrCreateSodaConnection(ConfigurationReader.ReadConfiguration()); var navigationService = new NavigationService(); var mainPage = new MenuPage { BindingContext = new MenuViewModel(connection, navigationService), }; var navigationPage = new NavigationPage(mainPage) { BarBackgroundColor = Color.White, BarTextColor = Color.Black }; navigationService.RegisterNavigateEvents(navigationPage); MainPage = navigationPage; } protected override void OnStart() { // Handle when your app starts } protected override void OnSleep() { // Handle when your app sleeps } protected override void OnResume() { // Handle when your app resumes } } }
using System; using System.Collections.Generic; using Microsoft.SqlServer.XEvent.Linq; using NLog; using System.Data; using XESmartTarget.Core.Utils; using System.Net.Mail; using System.IO; namespace XESmartTarget.Core.Responses { [Serializable] public class EmailResponse : Response { private static Logger logger = LogManager.GetCurrentClassLogger(); public string SMTPServer { get; set; } public string Sender { get; set; } public string To { get; set; } public string Cc { get; set; } public string Bcc { get; set; } public string Subject { get; set; } public string Body { get; set; } public bool HTMLFormat { get; set; } public string Attachment { get; set; } public string AttachmentFileName { get; set; } public string UserName { get; set; } public string Password { get; set; } protected DataTable EventsTable = new DataTable("events"); private XEventDataTableAdapter xeadapter; public EmailResponse() { logger.Info(String.Format("Initializing Response of Type '{0}'", this.GetType().FullName)); } public override void Process(PublishedEvent evt) { if (xeadapter == null) { xeadapter = new XEventDataTableAdapter(EventsTable); xeadapter.Filter = this.Filter; xeadapter.OutputColumns = new List<OutputColumn>(); } xeadapter.ReadEvent(evt); lock (EventsTable) { foreach (DataRow dr in EventsTable.Rows) { string formattedBody = Body; string formattedSubject = Subject; Dictionary<string, object> eventTokens = new Dictionary<string, object>(); foreach (DataColumn dc in EventsTable.Columns) { eventTokens.Add(dc.ColumnName, dr[dc]); } // also add the Response tokens foreach(string t in Tokens.Keys) { if(!eventTokens.ContainsKey(t)) eventTokens.Add(t, Tokens[t]); } formattedBody = SmartFormatHelper.Format(Body, eventTokens); formattedSubject = SmartFormatHelper.Format(Subject, eventTokens); using (MailMessage msg = new MailMessage() { From = new MailAddress(Sender), Subject = formattedSubject, Body = formattedBody }) { foreach(var addrTo in To.Split(';')) { msg.To.Add(new MailAddress(addrTo)); } using (MemoryStream attachStream = new MemoryStream()) { if (!String.IsNullOrEmpty(Attachment) && dr.Table.Columns.Contains(Attachment)) { StreamWriter wr = new StreamWriter(attachStream); wr.Write(dr[Attachment].ToString()); wr.Flush(); attachStream.Position = 0; System.Net.Mime.ContentType ct = new System.Net.Mime.ContentType(System.Net.Mime.MediaTypeNames.Text.Plain); Attachment at = new Attachment(attachStream, ct); at.ContentDisposition.FileName = AttachmentFileName; msg.Attachments.Add(at); } msg.IsBodyHtml = HTMLFormat; using (SmtpClient client = new SmtpClient(SMTPServer)) { if (!String.IsNullOrEmpty(UserName)) { client.Credentials = new System.Net.NetworkCredential(UserName, Password); } // could be inefficient: sends synchronously client.Send(msg); } } } } EventsTable.Clear(); } } } }
using System; using BuildHelper.Editor.Core; using UnityEditor; namespace BuildHelper.Editor { public static class UserBuildCommands { #region Build Menu [MenuItem("Build/Build Win64")] public static void BuildWin64ToPathWithVersion() { BuildTime.RestoreSettingsIfFailed(() => { var buildVersion = BuildHelperStrings.GetBuildVersion(); var target = BuildTarget.StandaloneWindows64; var options = GetStandartPlayerOptions(target); options.locationPathName = BuildHelperStrings.GetBuildPath(target, buildVersion); BuildTime.Build(options); }); } [MenuItem("Build/Build Android ARMv7 and run on device")] public static void BuildAndroidARMv7AndRun() { IdentifierFormWindow.ShowIfNeedChange(BuildTargetGroup.Android, () => AndroidDevicesWindow.ShowIfNeedSelect(adbDeviceId => BuildTime.RestoreSettingsIfFailed(() => { var buildVersion = BuildHelperStrings.GetBuildVersion(); var target = BuildTarget.Android; var options = GetStandartPlayerOptions(target); var path = BuildAndroidForDevice(AndroidTargetDevice.ARMv7, buildVersion, options); PostBuildExecutor.Make(InstallApkToDeviceAndRun, new InstallApkParams { pathToApk = path, adbDeviceId = adbDeviceId }); }))); } [MenuItem("Build/Build Android separate ARMv7 and x86")] public static void BuildAndroidToPathWithVersion() { IdentifierFormWindow.ShowIfNeedChange(BuildTargetGroup.Android, () => BuildTime.RestoreSettingsIfFailed(() => { var buildVersion = BuildHelperStrings.GetBuildVersion(); var target = BuildTarget.Android; var options = GetStandartPlayerOptions(target); BuildAndroidForDevice(AndroidTargetDevice.ARMv7, buildVersion, options); BuildAndroidForDevice(AndroidTargetDevice.x86, buildVersion, options); })); } [MenuItem("Build/Build iOS")] public static void BuildIOSToPathWithVersion() { IdentifierFormWindow.ShowIfNeedChange(BuildTargetGroup.iOS, () => BuildTime.RestoreSettingsIfFailed(() => { var buildVersion = BuildHelperStrings.GetBuildVersion(); var target = BuildTarget.iOS; var options = GetStandartPlayerOptions(target); BuildTime.SaveSettingsToRestore(); PlayerSettings.iOS.buildNumber = BuildHelperStrings.GenBundleNumber().ToString(); options.locationPathName = BuildHelperStrings.GetBuildPath(target, buildVersion); BuildTime.Build(options); })); } [MenuItem("Build/Build all from master branch")] public static void BuildAllFromMaster() { var branch = GitRequest.CurrentBranch(); if (branch != BuildHelperStrings.RELEASE_BRANCH) GitRequest.Checkout(BuildHelperStrings.RELEASE_BRANCH); try { BuildWin64ToPathWithVersion(); BuildAndroidToPathWithVersion(); BuildIOSToPathWithVersion(); } finally { if (branch != BuildHelperStrings.RELEASE_BRANCH) GitRequest.Checkout(branch); } } #endregion #region Post build async operations /// <seealso cref="UserBuildCommands.InstallApkToDeviceAndRun"/> [Serializable] public class InstallApkParams { public string pathToApk; public string adbDeviceId; } /// <summary> /// Install apk on android device and run it. /// </summary> /// <param name="p">Install params.</param> public static void InstallApkToDeviceAndRun(InstallApkParams p) { var appIdentifier = PlayerSettings.GetApplicationIdentifier(BuildTargetGroup.Android); AdbRequest.InstallToDevice(p.pathToApk, p.adbDeviceId, OnDone: success => { if (success) AdbRequest.RunOnDevice(appIdentifier, p.adbDeviceId); }); } #endregion #region Utility functions /// <summary> /// Create default <i>BuildPlayerOptions</i> with specified target and return it. /// This options include all scenes that defined in Build Settings window. /// </summary> /// <param name="target">build target</param> /// <returns>new <i>BuildPlayerOptions</i></returns> private static BuildPlayerOptions GetStandartPlayerOptions(BuildTarget target) { return new BuildPlayerOptions { scenes = EditorBuildSettingsScene.GetActiveSceneList(EditorBuildSettings.scenes), target = target, options = BuildOptions.None }; } /// <summary> /// Build project for Android with specified AndroidTargetDevice. /// This function change PlayerSettings and restore it after build. /// Different devices will get different bundle version code. /// See: <see cref="BuildHelperStrings.GenBundleNumber(UnityEditor.AndroidTargetDevice)"/> /// </summary> /// <param name="device">Android target device</param> /// <param name="buildVersion">Build version wich will be available by <i>Application.version</i></param> /// <param name="options">Build player options</param> /// <returns>Build path</returns> private static string BuildAndroidForDevice(AndroidTargetDevice device, string buildVersion, BuildPlayerOptions options) { BuildTime.SaveSettingsToRestore(); PlayerSettings.Android.targetDevice = device; PlayerSettings.Android.bundleVersionCode = BuildHelperStrings.GenBundleNumber(device); var buildPath = BuildHelperStrings.GetBuildPath(BuildTarget.Android, buildVersion, specifyName: device.ToString()); options.locationPathName = buildPath; BuildTime.Build(options); return buildPath; } #endregion } }
using System; namespace Vlc.DotNet.Core { public sealed class VlcMediaPlayerPausableChangedEventArgs : EventArgs { public VlcMediaPlayerPausableChangedEventArgs(bool paused) { IsPaused = paused; } public bool IsPaused { get; private set; } } }
using Proiect.Models.MyValidation; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; using System.Web.Mvc; namespace Proiect.Models.MyModels { public class Vanzare { [Key] public int Vanzare_id { get; set; } //[NameValidator] [MinLength(2, ErrorMessage = "Seller name cannot be less than 2!"), MaxLength(30, ErrorMessage = "Seller name cannot be more than 30!")] public string name { get; set; } // one to many public virtual ICollection<Item> Items { get; set; } [NotMapped] public IEnumerable<SelectListItem> SellerList { get; set; } } }
using System.Collections.Generic; using System.Linq; using Mastermind.NET.Models; namespace Mastermind.NET.Validation { /// <summary> /// Guess validator static class. /// </summary> public static class GuessValidator { private const string VictoryString = "++++"; /// <summary> /// Validates the guess against the game state. Please see commentary within for details. /// </summary> /// <param name="state">Game state object for gaining access to the generated numbers.</param> /// <param name="guess">Guessed numbers input by the user.</param> /// <returns> /// GuessValidationResult indicating victory condition (true/false) and hints about /// whether or not the numbers in the guess exist in the actual numbers and in what position. /// </returns> public static GuessValidationResult Validate(IGameState state, IEnumerable<int> guess) { // Note that we could make this marginally more efficient by having the guess be an array. // However, I don't feel this is a worthwhile optimization given it's 4 characters. Regardless, // ReSharper WILL complain about multiple enumerations on guess. // Victory condition; guess and generated both match exactly. We can stop right here. // Technically, we don't need to do this and if it was a longer/more complex string // where performance is critical, I probably wouldn't. I think it simplifies the // readability a bit because you can now mentally discard success scenarios, but // it doesn't actually simplify the *logic* any because you can comment this check out // and all the unit tests will still pass. if (state.Numbers.SequenceEqual(guess)) return new GuessValidationResult {VictoryCondition = true, GuessResult = VictoryString}; // I'd really prefer to do all this with LINQ, but using Intersect() isn't a perfect solution // because it won't handle duplicated values. That is to say, if you had 2,2,1,1 and 1,1,2,2 // Intersect() would only give you 1,2. Not too helpful! So, we do it the old-school array // enumeration way. var nums = new List<int>(state.Numbers); var statusString = ""; for (var i = 0; i < guess.Count(); i++) { var digit = guess.ElementAt(i); // Digit at i exactly matches generated at i. This would result in a +. if (digit == nums[i]) { statusString += "+"; // Mark it in the generated copy as an out-of-bounds value to indicate it's been matched; // we don't want to accidentally pick it up again in the future. nums[i] = 0; // We can stop here and move to the next digit in the guess. continue; } // We don't have an exact match, so we'll have to scan the generated array // to see if that digit exists elsewhere in it. Then we'll change it to an // out of bounds value so we don't accidentally match it twice. for (var k = 0; k < nums.Count; k++) // We found a digit but it's in the wrong place. This would result in a -. if (nums[k] == digit) { statusString += "-"; // Now mark the generated digit as processed. nums[k] = 0; // And break, since we don't want to continue this inner for loop. break; } } return new GuessValidationResult { VictoryCondition = statusString == VictoryString, GuessResult = string.Concat(statusString.OrderBy(c => c)) }; } } }
using System; namespace OrgMan.DomainObjects.Common { public class EmailDomainModel { public Guid UID { get; set; } public Guid CommunicationTypeUID { get; set; } public Guid IndividualPersonUID { get; set; } public string EmailAdress { get; set; } public bool IsMain { get; set; } } }
using System; using System.Threading.Tasks; using Uintra.Features.Groups.Sql; using Uintra.Persistence.Sql; namespace Uintra.Features.Groups.Services { public class GroupActivityService : IGroupActivityService { private readonly ISqlRepository<GroupActivityRelation> _groupActivityRepository; public GroupActivityService(ISqlRepository<GroupActivityRelation> groupActivityRepository) { _groupActivityRepository = groupActivityRepository; } public void AddRelation(Guid groupId, Guid activityId) { var relation = new GroupActivityRelation { ActivityId = activityId, GroupId = groupId, Id = Guid.NewGuid() }; _groupActivityRepository.Add(relation); } public void RemoveRelation(Guid groupId, Guid activityId) { _groupActivityRepository.Delete(r => r.ActivityId.Equals(activityId) && r.GroupId.Equals(groupId)); } public Guid? GetGroupId(Guid activityId) { return _groupActivityRepository.Find(rel => rel.ActivityId == activityId)?.GroupId; } public async Task AddRelationAsync(Guid groupId, Guid activityId) { var relation = new GroupActivityRelation { ActivityId = activityId, GroupId = groupId, Id = Guid.NewGuid() }; await _groupActivityRepository.AddAsync(relation); } public async Task RemoveRelationAsync(Guid groupId, Guid activityId) { await _groupActivityRepository.DeleteAsync(r => r.ActivityId.Equals(activityId) && r.GroupId.Equals(groupId)); } public async Task<Guid?> GetGroupIdAsync(Guid activityId) { return (await _groupActivityRepository.FindAsync(rel => rel.ActivityId == activityId))?.GroupId; } } }
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.Odbc; using System.Data.SqlClient; using System.Configuration; using System.Threading.Tasks; using System.Windows; using System.IO; using Xceed.Wpf.Toolkit; public partial class MainReg : System.Web.UI.Page { OdbcConnection conn = new OdbcConnection(ConfigurationManager.ConnectionStrings["izozoDBConnection"].ConnectionString); protected void Page_Load(object sender, EventArgs e) { } bool IsValidEmail(string email) { try { var addr = new System.Net.Mail.MailAddress(email); return true; } catch { return false; } } protected void Button1_Click(object sender, EventArgs e) { try { conn.Open(); string str1 = "SELECT * from tblCustomer WHERE custUsername = '" + TextBox2.Text + "'AND custEmail = '" + TextBox3.Text + "'"; OdbcDataAdapter sda = new OdbcDataAdapter(str1, conn); DataTable dtbl = new DataTable(); sda.Fill(dtbl); if (IsValidEmail(TextBox3.Text) == false) { RegularExpressionValidator1.ErrorMessage = "Invalid email address!"; } else if (TextBox5.Text != TextBox6.Text) //Check if passwords are the same { CompareValidator1.ErrorMessage = "Passwords must match!"; } else if (dtbl.Rows.Count > 0)//Check if user exists in the DB { ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('User already exists!')", true); //lblReg.Text = "User already exists!"; } else { //Insert a new user's details into DB string str = "INSERT INTO tblCustomer (custID, custName, custSurname, custPhoneNo, " + "custUsername, custPassword, custStreetName, " + "custTown, custCity, custStandNo, custUnitNo," + "custPostCode, custEmail) " + "VALUES (NULL, '" + TextBox1.Text + "', '" + TextBox50.Text + "', '" + TextBox4.Text + "', '" + TextBox2.Text + "', '" + TextBox5.Text + "', NULL, NULL, NULL, " + "NULL, NULL, NULL, '" + TextBox3.Text + "')"; OdbcCommand cmd = new OdbcCommand(str, conn); cmd.ExecuteNonQuery(); // lblReg.Visible = true; // lblReg.Text = "successfully registered"; ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", "alert('successfully registered you can continue to login')", true); } } catch { //lblReg.Text = "Something went wrong!"; //ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "ClientScript", // "alert('successfully registered you can continue to login')", true); throw; } finally { conn.Close(); } } protected void RegularExpressionValidator1_Load(object sender, EventArgs e) { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace AlmenaraGames { /// <summary> /// Contains information about the specific StateSFX in the Animator State Invoking the corresponding Custom Play Method. /// The values returned will take in consideration any Per-Motion value (BlendTree) and State Behaviour Custom Position change. /// </summary> [System.Serializable] public struct MLPASACustomPlayMethodParameters { [SerializeField] private AudioObject audioObject; [SerializeField] private int channel; [SerializeField] private bool followPosition; [SerializeField] private Vector3 position; [SerializeField] private Transform transform; [SerializeField] private int blendTreeMotionIndex; [SerializeField] private AnimatorStateInfo animatorStateInfo; [SerializeField] private float playTime; private CustomParams customParameters; public AudioObject AudioObject { get { return audioObject; } } public int Channel { get { return channel; } } public bool FollowPosition { get { return followPosition; } } public Vector3 Position { get { return position; } } public Transform Transform { get { return transform; } } public int BlendTreeMotionIndex { get { return blendTreeMotionIndex; } } public AnimatorStateInfo AnimatorStateInfo { get { return animatorStateInfo; } } public float PlayTime { get { return playTime; } } /// <summary> /// The Custom Optional Parameters for this specific StateSFX. /// </summary> public CustomParams CustomParameters { get { return customParameters; } } public MLPASACustomPlayMethodParameters(AudioObject audioObject, int channel, bool followPosition, Vector3 position, Transform transform, int blendTreeMotionIndex, AnimatorStateInfo animatorStateInfo, float playTime, CustomParams userParameters) { this.audioObject = audioObject; this.channel = channel; this.followPosition = followPosition; this.position = position; this.transform = transform; this.blendTreeMotionIndex = blendTreeMotionIndex; this.animatorStateInfo = animatorStateInfo; this.playTime = playTime; this.customParameters = userParameters; } /// <summary> /// The Custom Optional Parameters for this specific StateSFX. /// </summary> [System.Serializable] public struct CustomParams { [SerializeField] private bool boolParameter; [SerializeField] private float floatParameter; [SerializeField] private int intParameter; [SerializeField] private string stringParameter; [SerializeField] private UnityEngine.Object objectParameter; public bool BoolParameter { get { return boolParameter; } } public float FloatParameter { get { return floatParameter; } } public int IntParameter { get { return intParameter; } } public string StringParameter { get { return stringParameter; } } public Object ObjectParameter { get { return objectParameter; } } public CustomParams(bool boolParameter, float floatParameter, int intParameter, string stringParameter, UnityEngine.Object objectParameter) { this.boolParameter = boolParameter; this.floatParameter = floatParameter; this.intParameter = intParameter; this.stringParameter = stringParameter; this.objectParameter = objectParameter; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.PermutationAndCombination { /// <summary> /// given a phone number we need to find all the different words that can be formed using the number /// for example 2 corresponds to a,b,c and 3 to d,e,f /// so 23 can have ad,ae,af,bd,be,bf,cd,ce,cf different combinations /// </summary> public class PhoneNumberToWords { /// <summary> /// this dictionary will contain the mapping between the number to the characters as shown in the pinpad /// </summary> public Dictionary<int, List<char>> NumToChar { get; set; } public Dictionary<char, List<char>> CharPhNumToChar { get; set; } public PhoneNumberToWords() { NumToChar = new Dictionary<int, List<char>>(); CharPhNumToChar = new Dictionary<char, List<char>>(); NumToChar.Add(2, new List<char> { 'A', 'B', 'C' }); NumToChar.Add(3, new List<char> { 'D', 'E', 'F' }); NumToChar.Add(4, new List<char> { 'G', 'H', 'I' }); NumToChar.Add(5, new List<char> { 'J', 'K', 'L' }); NumToChar.Add(6, new List<char> { 'M', 'N', 'O' }); NumToChar.Add(7, new List<char> { 'P', 'Q', 'R', 'S' }); NumToChar.Add(8, new List<char> { 'T', 'U', 'V' }); NumToChar.Add(9, new List<char> { 'W', 'X', 'Y', 'Z' }); foreach(KeyValuePair<int, List<char>> kvp in NumToChar) { CharPhNumToChar[Char.Parse(kvp.Key.ToString())] = kvp.Value; } } #region Method1: Recusive Method /// <summary> /// this is the recursive subroutine which helps in getting the combinations from the phonenumbers /// this subroutine will call itself with phonenumber /= 10 and the current subroutine will work /// with the last digit of the phone number (phoneNumber % 10) /// /// The running time of this method is O(4^n) /// The space requirement is also O(4^n) as we have to save all the combination /// </summary> /// <param name="phoneNumber"></param> /// <returns>list of combinations from the phone number</returns> public List<string> ConvertPhoneNumberToWords(long phoneNumber) { // Note if the phone number has 00<other_valid_number> at the start of the number then we will get the different // combinations from <other_valid_numbers> and not throw ill-formed expression exception if(phoneNumber == 0) { // base case which ends the recursion return new List<string>() { string.Empty }; } int lastDigit = (int)(phoneNumber % 10); phoneNumber = phoneNumber / 10; List<string> ret = new List<string>(); List<string> allCombinations = ConvertPhoneNumberToWords(phoneNumber); if(!NumToChar.ContainsKey(lastDigit)) { // if the digits do not lie between 2-9 then we throw the exception throw new Exception("ill formed phone number"); } foreach(char c in NumToChar[lastDigit]) { ret.AddRange(AddCurrentCharToAllString(c, allCombinations)); } return ret; } private List<string> AddCurrentCharToAllString(char currentChar, List<string> allStrings) { List<string> ret = new List<string>(); for(int i=0; i<allStrings.Count; i++) { ret.Add(currentChar + allStrings[i]); } return ret; } #endregion #region Method2: Iterative Method(Optimal method) /// <summary> /// This is the iterative method to get all possible combinations when a phone number is given. /// Here we will use 2 lists and keep adding the chars to the strings of one list and save it in the second list. /// /// The running time of this method is O(4^n) /// The space requirement is also O(4^n) as we have to save all the combinations /// </summary> /// <param name="phoneNumber"></param> /// <returns></returns> public List<string> ConvertPhoneNumberToWords(string phoneNumber) { if(phoneNumber == null || phoneNumber == string.Empty) { return null; } List<string> previous = new List<string>() { "" }; for(int numIndex = 0; numIndex < phoneNumber.Length; numIndex++) { List<string> currentList = new List<string>(); if (!CharPhNumToChar.ContainsKey(phoneNumber[numIndex])) { throw new Exception("Invalid Phone number"); } foreach (char c in CharPhNumToChar[phoneNumber[numIndex]]) { foreach(string str in previous) { currentList.Add(str + c.ToString()); } } previous = currentList; } return previous; } #endregion public static void TestPhoneNumberToWords() { PhoneNumberToWords PhToWords = new PhoneNumberToWords(); long phoneNumber = 285; Console.WriteLine("All the different combinations of {0} is as shown below", phoneNumber); Console.WriteLine("Recursive Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber)); Console.WriteLine("Iterative Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber.ToString())); phoneNumber = 9876; Console.WriteLine("All the different combinations of {0} is as shown below", phoneNumber); Console.WriteLine("Recursive Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber)); Console.WriteLine("Iterative Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber.ToString())); phoneNumber = 052; Console.WriteLine("All the different combinations of {0} is as shown below", phoneNumber); Console.WriteLine("Recursive Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber)); Console.WriteLine("Iterative Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber.ToString())); phoneNumber = 201; Console.WriteLine("All the different combinations of {0} is as shown below", phoneNumber); try { Console.WriteLine("Recursive Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber)); } catch (Exception e) { Console.WriteLine("{0}", e.Message); } try { Console.WriteLine("Iterative Solution"); PrintCombinations(PhToWords.ConvertPhoneNumberToWords(phoneNumber.ToString())); } catch (Exception e) { Console.WriteLine("{0}", e.Message); } } private static void PrintCombinations(List<string> combinations) { Console.WriteLine("The total number of different combinations are {0}", combinations.Count); foreach (string combination in combinations) { Console.Write("{0} ", combination); } Console.WriteLine(); } } }
using Ricky.Infrastructure.Core.ObjectContainer; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using VnStyle.Services.Business; using VnStyle.Services.Data; using VnStyle.Services.Data.Domain; using VnStyle.Services.Data.Enum; namespace VnStyle.Web.Controllers.Api { [RoutePrefix("api/categories")] public class CategoriesController : BaseController { private readonly IBaseRepository<Category> _categoryRepository; private readonly IRootCategoryService _rootCategoryService; public CategoriesController() { _rootCategoryService = EngineContext.Current.Resolve<IRootCategoryService>(); _categoryRepository = EngineContext.Current.Resolve<IBaseRepository<Category>>(); } [Route("{rootCateId}/query")] public async Task<HttpResponseMessage> Get(int rootCateId) { var query = _categoryRepository.Table.Where(p => (int)p.RootCategory == rootCateId); return Request.CreateResponse(HttpStatusCode.OK, query.ToList()); } [Route("root-categories/article")] public HttpResponseMessage GetArticleCategories() { var articleCate = new List<ERootCategory> { ERootCategory.Intro, ERootCategory.Event, ERootCategory.Course, ERootCategory.Tattoo, ERootCategory.Piercing }; return Request.CreateResponse(HttpStatusCode.OK, this._rootCategoryService.GetAllRootCategories().Where(p => articleCate.Contains((ERootCategory)p.Id))); } [Route("root-categories/gallery-photo")] public HttpResponseMessage GetGalleryPhotoCategories() { var articleCate = new List<ERootCategory> { ERootCategory.Image }; return Request.CreateResponse(HttpStatusCode.OK, this._rootCategoryService.GetAllRootCategories().Where(p => articleCate.Contains((ERootCategory)p.Id))); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace PlanMGMT.Converter { public class TimerToBtnContentConverter : System.Windows.Data.IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) return ""; return (short)value == 1 ? "停止" : "开始"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace Optymalizacja_wykorzystania_pamieci { class Options { public List<int> number_of_threads { get; set; } public int number_of_tasks { get; set; } public int number_of_issue { get; set; } public bool allocation { get; set; } public bool garbage_collector { get; set; } public bool show_result { get; set; } public Options() { this.number_of_issue = 5; // 1 - pliki, 2-kolorowanie grafu, 3 - tworzenie grafu, 4 - tablica liczb, 5 - drzewa decyzyjne //this.number_of_threads = 1; // gdy opcja lawinowa jest wybrana - maksymalna ilość uruchomionych wątków this.number_of_threads = new List<int>(); //this.number_of_threads.Add(1); this.number_of_tasks = 1; // ilość podzadań do zrealizowania przez silnik - nie każde zadanie je implementuje (np. kolorowanie, obsługa plików) this.allocation = false; // czy alokować pamięć przez wątki w silniku (wybrane zadania: tablica liczb) this.garbage_collector = false; this.show_result = false; } public Options LoadOptions(string path) { string[] datas = new string[6]; bool read_records = false; int i = 0; Options op = new Options(); try { using (var sr = new StreamReader(path)) { while (!sr.EndOfStream) { var line = sr.ReadLine(); if (read_records) { string[] tmp = line.Split('='); datas[i] = tmp[1]; i++; } if (line.IndexOf("OPTIONS", StringComparison.CurrentCultureIgnoreCase) >= 0) read_records = true; } } if (Int32.Parse(datas[0]) > 0 && Int32.Parse(datas[0]) < 7) op.number_of_issue = Int32.Parse(datas[0]); else op.number_of_issue = 1; string[] tmp_2 = datas[1].Split(','); foreach(string s in tmp_2) { // if(Int32.Parse(s) > 1 ) op.number_of_threads.Add(Int32.Parse(s)); } if (Int32.Parse(datas[2]) > 0) op.number_of_tasks = Int32.Parse(datas[2]); else op.number_of_tasks = 1; op.allocation = Convert.ToBoolean(datas[3]); op.garbage_collector = Convert.ToBoolean(datas[4]); op.show_result = Convert.ToBoolean(datas[5]); return op; } catch { return this; } } public void ShowOptions() { Console.WriteLine("\nOPCJE:\n"); Console.WriteLine("Numer zagadnienia: {0}", this.number_of_issue); Console.Write("Ilosc uruchamianych watkow: "); foreach (int i in this.number_of_threads) Console.Write("{0}, ", i); Console.WriteLine("\nIlosc rozpatryanych zadan: {0}", this.number_of_tasks); Console.WriteLine("Dodatkowa alokacja: {0}", this.allocation); Console.WriteLine("Reczne zwalnianie pamieci: {0}", this.garbage_collector); Console.WriteLine("Wypisywanie na ekran: {0}\n", this.show_result); } } }
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; namespace WerkWerk { public class WorkBuilder<T> { private WorkPipeline<T> _pipeline = new WorkPipeline<T>(); private string _name; private TimeSpan _interval; private int _maxRetries; public WorkBuilder<T> Setup(string name, TimeSpan interval, int maxRetries = 3) { _name = name; _interval = interval; _maxRetries = maxRetries; return this; } public WorkBuilder<T> Use(Func<WorkContext<T>, Task<WorkResult>> runner) { _pipeline.Enqueue(provider => new WorkMiddleware<T>(runner)); return this; } public WorkBuilder<T> Use<TMiddleware>() where TMiddleware : IWorkMiddleware<T> { _pipeline.Enqueue(provider => provider.GetRequiredService<TMiddleware>()); return this; } internal Work<T> Build() { return new Work<T>(_pipeline) { JobName = _name, Interval = _interval, MaxRetries = _maxRetries, }; } internal WorkBuilder() { } } }
using BankApp.DTO; using BankApp.Models; using BankAppCore.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web; namespace BankApp.Services { public class CsvCreator : ReportCreator { public Report GenerateReport(ReportPeriod reportPeriod) { return new CsvReport(Encoding.ASCII.GetBytes("sadsad")); } } }
using Microsoft.SqlServer.Management.Smo; using SqlServerWebAdmin.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SqlServerWebAdmin { public partial class EditDatabaseRole : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { if (Request["role"] == null) Response.Redirect("DatabaseRoles.aspx?database=" + Server.UrlEncode(Request["database"])); Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; DatabaseRole role = database.Roles[Request["role"]]; if (role == null) Response.Redirect("DatabaseRoles.aspx?database=" + Server.UrlEncode(Request["database"])); RoleNameLabel.Text = role.Name; RoleTypeLabel.Text = role.IsFixedRole ? "Application" : "Standard"; if (/*role.AppRole*/false) { ApplicationRolePanel.Visible = true; } else { StandardRolePanel.Visible = true; // Parse out names from Users ArrayList userNames = new ArrayList(); foreach (User user in database.Users) { userNames.Add(user.Name); } RoleUsers.DataSource = userNames; RoleUsers.DataBind(); foreach (ListItem item in RoleUsers.Items) { foreach (string name in role.EnumMembers()) { if (item.Value == name) { item.Selected = true; break; } } } } server.Disconnect(); } } protected void Save_Click(object sender, EventArgs e) { Microsoft.SqlServer.Management.Smo.Server server = DbExtensions.CurrentServer; try { server.Connect(); } catch (System.Exception ex) { Response.Redirect(String.Format("error.aspx?errormsg={0}&stacktrace={1}", Server.UrlEncode(ex.Message), Server.UrlEncode(ex.StackTrace))); } try { Database database = server.Databases[HttpContext.Current.Server.HtmlDecode(HttpContext.Current.Request["database"])]; DatabaseRole role = database.Roles[Request["Role"]]; foreach (ListItem item in RoleUsers.Items) { User user = database.Users[item.Value]; if (user.IsMember(role.Name) && !item.Selected) { role.DropMember(user.Name); } else if (!user.IsMember(role.Name) && item.Selected) { role.AddMember(role.Name); } } } catch (Exception ex) { ErrorMessage.Text = ex.Message; return; } finally { server.Disconnect(); } Response.Redirect("~/Modules/DatabaseRole/DatabaseRoles.aspx?database=" + Server.UrlEncode(Request["database"])); } } }
using System; using System.Threading; using System.Threading.Tasks; using CoherentSolutions.Extensions.Configuration.AnyWhere; using CoherentSolutions.Extensions.Configuration.AnyWhere.AdapterList; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace Code { public class ConfigurationPrinter : IHostedService { private readonly IConfiguration config; public ConfigurationPrinter( IConfiguration config) { this.config = config; } public Task StartAsync( CancellationToken cancellationToken) { foreach (var kv in this.config.AsEnumerable()) { Console.WriteLine($"{kv.Key} = {kv.Value}"); } return Task.CompletedTask; } public Task StopAsync( CancellationToken cancellationToken) { return Task.CompletedTask; } } public class Program { static void Main(string[] args) { new HostBuilder() .ConfigureAppConfiguration( config => { config .AddAnyWhereConfigurationAdapterList() .AddAnyWhereConfiguration(); }) .ConfigureServices( services => { services.AddTransient<IHostedService, ConfigurationPrinter>(); }) .UseConsoleLifetime() .Build() .Run(); } } }
using System; using System.Linq; namespace Exercise_10 { class Program { static void Main(string[] args) { int size = int.Parse(Console.ReadLine()); string command = string.Empty; int[] field = new int[size]; int[] initialBugPlaces = Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); //INITIAL BUG PLACES INPUT for (int i = 0; i < initialBugPlaces.Length; i++) //PLACE BUGS INTO ARRAY FIELD ex 0 1 --> 1 1 0 { if (initialBugPlaces[i] >= 0 && initialBugPlaces[i] < field.Length) { field[initialBugPlaces[i]] = 1; } } // Console.WriteLine(String.Join(" ", field)); while (true) { // Console.WriteLine(String.Join(" ", field)); command = Console.ReadLine(); if (command == "end") { Console.WriteLine(String.Join(" ", field)); return; } string[] comm = command.Split(" ", StringSplitOptions.RemoveEmptyEntries).ToArray(); int startingIndex = int.Parse(comm[0]); //STARTING INDEX string direction = comm[1]; int movement = int.Parse(comm[2]); //MOVEMENT PLACES int newIndex = 0; if (startingIndex >= 0 && startingIndex < field.Length && field[startingIndex] != 0) { if (direction == "right" && movement!=0) { newIndex = startingIndex + movement; if (newIndex <= field.Length - 1 && newIndex >= 0) { while (field[newIndex] != 0 && newIndex + movement <= field.Length - 1 && newIndex + movement >= 0) { newIndex += movement; } field[newIndex] = field[startingIndex]; field[startingIndex] = 0; } else if (newIndex == field.Length - 1) { field[newIndex] = field[startingIndex]; field[startingIndex] = 0; } else if (newIndex > field.Length - 1) { field[startingIndex] = 0; } else { field[startingIndex] = 0; } } if (direction == "left" && movement!=0) { newIndex = startingIndex - movement; //1 if (newIndex > 0 && newIndex <= field.Length - 1) { while (field[newIndex] != 0 && newIndex - movement <= field.Length - 1 && newIndex - movement >= 0) { newIndex -= movement; } field[newIndex] = field[startingIndex]; field[startingIndex] = 0; } else if (newIndex == 0) { field[newIndex] = field[startingIndex]; field[startingIndex] = 0; } else if (newIndex > field.Length - 1) { field[startingIndex] = 0; } else { field[startingIndex] = 0; } } } } } } }
using System.Linq; namespace EddiDataDefinitions { /// <summary> /// Squadron Ranks /// </summary> public class Power : ResourceBasedLocalizedEDName<Power> { static Power() { resourceManager = Properties.Powers.ResourceManager; resourceManager.IgnoreCase = false; None = new Power("None", Superpower.None, "None"); ALavignyDuval = new Power("ALavignyDuval", Superpower.Empire, "Kamadhenu"); AislingDuval = new Power("AislingDuval", Superpower.Empire, "Cubeo"); ArchonDelaine = new Power("ArchonDelaine", Superpower.Independent, "Harma"); DentonPatreus = new Power("DentonPatreus", Superpower.Empire, "Eotienses"); EdmundMahon = new Power("EdmundMahon", Superpower.Alliance, "Gateway"); FeliciaWinters = new Power("FeliciaWinters", Superpower.Federation, "Rhea"); LiYongRui = new Power("LiYongRui", Superpower.Independent, "Lembava"); PranavAntal = new Power("PranavAntal", Superpower.Independent, "Polevnic"); YuriGrom = new Power("YuriGrom", Superpower.Alliance, "Clayakarma"); ZacharyHudson = new Power("ZacharyHudson", Superpower.Federation, "Nanomam"); ZeminaTorval = new Power("ZeminaTorval", Superpower.Empire, "Synteini"); } public static readonly Power None; public static readonly Power ALavignyDuval; public static readonly Power AislingDuval; public static readonly Power ArchonDelaine; public static readonly Power DentonPatreus; public static readonly Power EdmundMahon; public static readonly Power FeliciaWinters; public static readonly Power LiYongRui; public static readonly Power PranavAntal; public static readonly Power YuriGrom; public static readonly Power ZacharyHudson; public static readonly Power ZeminaTorval; public Superpower Allegiance { get; private set; } public string headquarters { get; private set; } // dummy used to ensure that the static constructor has run public Power() : this("", Superpower.None, "None") { } private Power(string edname, Superpower allegiance, string headquarters) : base(edname, edname) { this.Allegiance = allegiance; this.headquarters = headquarters; } public new static Power FromEDName(string edName) { if (edName == null) { return null; } string tidiedName = edName.ToLowerInvariant().Replace(" ", "").Replace(".", "").Replace("-", ""); return AllOfThem.FirstOrDefault(v => v.edname.ToLowerInvariant() == tidiedName); } } }
using AutoFixture; using NUnit.Framework; using System.Threading.Tasks; using Moq; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.ProviderCommitments.Web.Mappers; using SFA.DAS.ProviderCommitments.Web.Models; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers { [TestFixture] public class WhenIMapSelectDeliveryModelViewModelFromEditDraftApprenticeshipViewModel { private SelectDeliveryModelViewModelFromEditDraftApprenticeshipViewModelMapper _mapper; private Mock<ISelectDeliveryModelMapperHelper> _helper; private SelectDeliveryModelViewModel _model; private EditDraftApprenticeshipViewModel _request; [SetUp] public void Arrange() { var fixture = new Fixture(); _request = fixture.Build<EditDraftApprenticeshipViewModel>().Without(x => x.BirthDay).Without(x => x.BirthMonth).Without(x => x.BirthYear) .Without(x => x.StartDate).Without(x => x.StartMonth).Without(x => x.StartYear) .Without(x => x.EndMonth).Without(x => x.EndYear).Create(); _model = fixture.Create<SelectDeliveryModelViewModel>(); _helper = new Mock<ISelectDeliveryModelMapperHelper>(); _helper.Setup(x => x.Map(It.IsAny<long>(), It.IsAny<string>(), It.IsAny<long>(), It.IsAny<DeliveryModel?>(), It.IsAny<bool?>())).ReturnsAsync(_model); _mapper = new SelectDeliveryModelViewModelFromEditDraftApprenticeshipViewModelMapper(_helper.Object); } [Test] public async Task TheParamsArePassedInCorrectly() { await _mapper.Map(_request); _helper.Verify(x=>x.Map(_request.ProviderId, _request.CourseCode, _request.AccountLegalEntityId, _request.DeliveryModel, _request.IsOnFlexiPaymentPilot)); } [Test] public async Task ThenModelIsReturned() { var result = await _mapper.Map(_request); Assert.AreEqual(_model, result); } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Plugin.Calendars; using Plugin.Calendars.Abstractions; namespace Tianhai.OujiangApp.Schedule.Services{ public class CalendarService{ public static string GetAccountName(){ Models.Preferences.OACredential credential=App.PreferenceDatabase.GetOACredential(); if(credential==null){ throw new Exceptions.NotLoggedInException("没有找到登陆过的账号"); } return String.Format("{0}@ojjx.wzu.edu.cn",credential.Username); } public static async Task<Calendar> CreateCalendar(string accountName){ Calendar cal=new Calendar{ AccountName=accountName, Name=accountName }; await CrossCalendars.Current.AddOrUpdateCalendarAsync(cal); App.PreferenceDatabase.SetParam(Enums.PreferenceParamKey.CalendarExternalID,cal.ExternalID); return cal; } public static async Task<Calendar> GetCalendar(){ string id=App.PreferenceDatabase.GetParam(Enums.PreferenceParamKey.CalendarExternalID); if(String.IsNullOrWhiteSpace(id)){ throw new Exception("No calendar ID."); } return await CrossCalendars.Current.GetCalendarByIdAsync(id); } public static async Task RemoveCalendar(){ string id=App.PreferenceDatabase.GetParam(Enums.PreferenceParamKey.CalendarExternalID); if(!String.IsNullOrWhiteSpace(id)){ await CrossCalendars.Current.DeleteCalendarAsync(await CrossCalendars.Current.GetCalendarByIdAsync(id)); } string accountName=GetAccountName(); foreach(Calendar c in (await CrossCalendars.Current.GetCalendarsAsync())){ if(String.Equals(c.Name,accountName)){ await CrossCalendars.Current.DeleteCalendarAsync(c); } } } public static async Task<Calendar> ResetCalendar(){ string accountName=GetAccountName(); await RemoveCalendar(); return await CreateCalendar(accountName); } public static List<CalendarEventReminder> CreateEventReminders(List<TimeSpan> timeBeforeList){ List<CalendarEventReminder> calendarEventReminders=new List<CalendarEventReminder>(); timeBeforeList.ForEach(timeBefore=>calendarEventReminders.Add(new CalendarEventReminder{ TimeBefore=timeBefore, Method=CalendarReminderMethod.Default })); return calendarEventReminders; } public static async Task<CalendarEvent> AddEvent(Calendar calendar,string eventName,string eventLocation,string eventDescription,DateTime eventTimeStart,DateTime eventTimeEnd,List<CalendarEventReminder> eventReminders,bool eventIsAllDay=false){ CalendarEvent calEvent=new CalendarEvent{ Name=eventName, Location=eventLocation, Description=eventDescription, AllDay=eventIsAllDay, Start=eventTimeStart, End=eventTimeEnd, Reminders=eventReminders }; await CrossCalendars.Current.AddOrUpdateEventAsync(calendar,calEvent); return calEvent; } } }
using UnityEngine; using System.Collections; using System; public abstract class State<T> { public T owner; public StateMachine<T> sm; public State(T _owner) { owner = _owner; } abstract public void Update(); abstract public void Enter(); abstract public void Exit(); }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class LogEditor : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (Session["user"] == null) Response.Redirect("Login.aspx"); else { if (!IsPostBack) { int logid = Convert.ToInt32(Session["logid"].ToString()); Logs log = new Logs(logid); txtHeadline.Text = log.Headline; txtContent.Text = log.Content; lbTime.Text = log.Time; } } } protected void btnSave_Click(object sender, EventArgs e) { int logid = Convert.ToInt32(Session["logid"].ToString()); string headline = txtHeadline.Text; string content = txtContent.Text; if (headline.Length == 0 || content.Length == 0) Response.Write("<script>alert('输入不能为空!')</script>"); else { string sql = "update Log set headline=N'" + headline + "',logcontent=N'" + content + "' where logid='" + logid + "'"; DataClass.Save(sql); Response.Write("<script>alert('修改成功!');location='Log.aspx'</script>"); } } }
using Abp.AutoMapper; using Abp.Modules; using Abp.Reflection.Extensions; namespace Dg.Fifth { [DependsOn( typeof(FifthCoreModule), typeof(AbpAutoMapperModule))] public class FifthApplicationModule : AbpModule { public override void Initialize() { IocManager.RegisterAssemblyByConvention(typeof(FifthApplicationModule).GetAssembly()); } } }
using System; using System.Collections.Generic; namespace bellyful_proj.Models { public partial class MealType { public MealType() { Batch = new HashSet<Batch>(); } public byte MealTypeId { get; set; } public string MealTypeName { get; set; } public string ShelfLocation { get; set; } public MealInstock MealInstock { get; set; } public ICollection<Batch> Batch { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Toaster : Interactable { public Material matOff; public Material matOn; Renderer rend; public void Start() { rend = GetComponent<Renderer>(); } public override void Activate() { base.Activate(); rend.material = matOn; } public override void Deactivate() { rend.material = matOff; } }
using CurrencyLib.US; namespace CurrencyLib { public class DollarCoin : USCoin { public DollarCoin() { this.MonetaryValue = 1.0; this.Name = "DollarCoin"; } public DollarCoin(USCoinMintMark cm) { this.MintMark = cm; this.MonetaryValue = 1.0; this.Name = "DollarCoin"; } } }
namespace Algorithmics { public static class Fibonacci { public static long RecursiveGet(int n) { if (n <= 1) return n; return RecursiveGet(n - 1) + RecursiveGet (n - 2); } public static long IterativeGet(int n) { long low = 0; long high = 1; for (int i = 2; i < n; i++) { var prevHigh = high; high = high + low; low = prevHigh; } return high; } } }
using EsferixisLazyCSharp.Esferixis.Misc; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace EsferixisLazyCSharp.Esferixis.Lazy { public sealed class RLazy<T> { private Action calculateValue; private int mustCalculateValue; private Task<T> deferredValue; /** * @post Creates a lazy value with the specified value generation function */ public RLazy(Action<TaskCompletionSource<T>> generateValue) { Preconditions.checkNotNull(generateValue, "generateValue"); TaskCompletionSource<T> valuePromise = new TaskCompletionSource<T>(); this.calculateValue = Trampoline.encapsulate( () => generateValue(valuePromise) ); this.deferredValue = valuePromise.Task; } /** * @post Creates a lazy value with the specified async function */ public RLazy( Func<Task<T>> generateValue ) : this( taskCompletionSource => generateValue().sendTo( taskCompletionSource )) {} public RLazy(Func<T> generateValue) : this(taskCompletionSource => taskCompletionSource.SetResult(generateValue())) {} /** * @post Creates a lazy value with the specified immediate value */ public RLazy( T value ) { this.calculateValue = null; this.mustCalculateValue = 0; this.deferredValue = Task<T>.FromResult(value); } public static implicit operator RLazy<T>(T value) { return new RLazy<T>(value); } /** * @post Gets the value */ public async Task<T> get() { this.calculate(); return await this.deferredValue; } /** * @post Calculates the value */ private void calculate() { if ( Interlocked.Exchange(ref this.mustCalculateValue, 0) != 0 ) { Action calculateValue = this.calculateValue; this.calculateValue = null; calculateValue(); } } } }
using LimenawebApp.Controllers.API; using LimenawebApp.Controllers.Session; using LimenawebApp.Models; using LimenawebApp.Models.Creditmemos_api; using LimenawebApp.Models.Invoices; using LimenawebApp.Models.Returnreasons_api; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Script.Serialization; namespace LimenawebApp.Controllers.Warehouse { public class WarehouseController : Controller { private dbLimenaEntities db = new dbLimenaEntities(); private Cls_session cls_session = new Cls_session(); private Cls_Creditmemos cls_creditmemos = new Cls_Creditmemos(); private Cls_Returnreasons cls_returnreasons = new Cls_Returnreasons(); private cls_invoices Cls_invoices = new cls_invoices(); private Cls_Authorizations cls_Authorizations = new Cls_Authorizations(); public ActionResult ReceiveCredits(string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Warehouse"; ViewData["Page"] = "Receive Credits"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //FILTROS VARIABLES DateTime filtrostartdate; DateTime filtroenddate; ////filtros de fecha (SEMANAL) var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); var saturday = sunday.AddDays(6).AddHours(23); if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); var creditmemos = cls_creditmemos.GetCreditMemos(0, "",filtrostartdate, filtroenddate, true); var returnreason = cls_returnreasons.GetReturnreasons(); var roles = new List<string>(); if (s.Contains("Front Desk")) { if (r.Contains("Receive Credits")) { roles.Add("FD"); } } else if (s.Contains("Operations")) { if (r.Contains("Receive Credits")) { roles.Add("OP"); roles.Add("QC"); } } if (r.Contains("Super Admin")) { roles.Add("FD"); roles.Add("OP"); roles.Add("QC"); } var returnsToshow= returnreason.data.Where(c => roles.Contains(c.authorizedBy)).ToList(); List<Returnreason_api> lstreturnsreasons = new List<Returnreason_api>(); var response = cls_returnreasons.GetReturnreasons(); if (response.data != null) { lstreturnsreasons = response.data.Where(c => c.visibleFor != null && c.visibleFor.Contains("SDA") && c.active == "Y" && roles.Contains(c.authorizedBy)).ToList(); } ViewBag.returnreasonschange = lstreturnsreasons; //filtramos data a mostrar var codes = returnsToshow.Select(c => c.reasonCode).ToArray(); string[] rrfilter; if (creditmemos.data != null) { var sss= creditmemos.data.Where(c => c.details.Any(d => codes.Contains(d.returnReasonCode))).OrderBy(p => p. details. OrderBy(c => c.returnReasonCode).Select(c => c.returnReasonCode).FirstOrDefault()).ToList(); creditmemos.data = sss; rrfilter = (from creditmemo in creditmemos.data from reason in creditmemo.details select reason.returnReasonCode).Distinct().ToArray(); returnsToshow = returnsToshow.Where(c => rrfilter.Contains(c.reasonCode)).Select(c => c).ToList(); } //filtramos nuevamente ViewBag.returnreasons = returnsToshow; return View(creditmemos.data); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public ActionResult getCreditmemoDetails(int DocEntry) { try { var creditmemos = cls_creditmemos.GetCreditMemos(DocEntry, "", null, null, true); JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer(); string result = javaScriptSerializer.Serialize(creditmemos.data.FirstOrDefault().details); return Json(result, JsonRequestBehavior.AllowGet); } catch(Exception ex) { return Json("Error: " + ex.Message, JsonRequestBehavior.AllowGet); } } public ActionResult ReceivedCredits(string fstartd, string fendd) { if (cls_session.checkSession()) { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //HEADER //ACTIVE PAGES ViewData["Menu"] = "Warehouse"; ViewData["Page"] = "Received Credits"; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstDepartments = JsonConvert.SerializeObject(s); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); ViewBag.lstRoles = JsonConvert.SerializeObject(r); //NOTIFICATIONS DateTime now = DateTime.Today; //List<Sys_Notifications> lstAlerts = (from a in db.Sys_Notifications where (a.ID_user == activeuser.ID_User && a.Active == true) select a).OrderByDescending(x => x.Date).Take(4).ToList(); //ViewBag.notifications = lstAlerts; ViewBag.activeuser = activeuser; //FIN HEADER //FILTROS VARIABLES DateTime filtrostartdate; DateTime filtroenddate; ////filtros de fecha (SEMANAL) var sunday = DateTime.Today.AddDays(-(int)DateTime.Today.DayOfWeek); var saturday = sunday.AddDays(6).AddHours(23); if (fstartd == null || fstartd == "") { filtrostartdate = sunday; } else { filtrostartdate = Convert.ToDateTime(fstartd); } if (fendd == null || fendd == "") { filtroenddate = saturday; } else { filtroenddate = Convert.ToDateTime(fendd).AddHours(23).AddMinutes(59); } ViewBag.filtrofechastart = filtrostartdate.ToShortDateString(); ViewBag.filtrofechaend = filtroenddate.ToShortDateString(); var creditmemos = cls_creditmemos.GetCreditMemosOriginals(0, "", filtrostartdate, filtroenddate, true); var returnreason = cls_returnreasons.GetReturnreasons(); var roles = new List<string>(); if (s.Contains("Front Desk")) { if (r.Contains("Receive Credits")) { roles.Add("FD"); } } else if (s.Contains("Operations")) { if (r.Contains("Receive Credits")) { roles.Add("OP"); roles.Add("QC"); } } if (r.Contains("Super Admin")) { roles.Add("FD"); roles.Add("OP"); roles.Add("QC"); } var returnsToshow = returnreason.data.Where(c => roles.Contains(c.authorizedBy)).ToList(); List<Returnreason_api> lstreturnsreasons = new List<Returnreason_api>(); var response = cls_returnreasons.GetReturnreasons(); if (response.data != null) { lstreturnsreasons = response.data.Where(c => c.visibleFor != null && c.visibleFor.Contains("SDA") && c.active == "Y" && roles.Contains(c.authorizedBy)).ToList(); } ViewBag.returnreasonschange = lstreturnsreasons; //filtramos data a mostrar var codes = returnsToshow.Select(c => c.reasonCode).ToArray(); string[] rrfilter; if (creditmemos.data != null) { var sss = creditmemos.data.Where(c => c.details.Any(d => codes.Contains(d.returnReasonCode))).OrderBy(p => p. details. OrderBy(c => c.returnReasonCode).Select(c => c.returnReasonCode).FirstOrDefault()).ToList(); creditmemos.data = sss; rrfilter = (from creditmemo in creditmemos.data from reason in creditmemo.details select reason.returnReasonCode).Distinct().ToArray(); returnsToshow = returnsToshow.Where(c => rrfilter.Contains(c.reasonCode)).Select(c => c).ToList(); } //filtramos nuevamente ViewBag.returnreasons = returnsToshow; return View(creditmemos.data); } else { return RedirectToAction("Login", "Home", new { access = false }); } } public ActionResult Put_creditMemoDetail(PutDetailsCreditmemos_api Item, int DocentryCredit) { try { var response = cls_creditmemos.PutCreditmemo(Item, DocentryCredit); if (response.IsSuccessful == true) { var result = "SUCCESS"; return Json(result, JsonRequestBehavior.AllowGet); } else { var result = "Error"; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { var resulterror = ex.Message; return Json(resulterror, JsonRequestBehavior.AllowGet); } } public ActionResult Put_creditMemoDetailNoshow(PutDetailsCreditmemos_api Item, int DocentryCredit, PutDetailsCreditmemos_apiNOSHOW newrow) { try { var response = cls_creditmemos.PutCreditmemo(Item, DocentryCredit); if (response.IsSuccessful == true) { //Agregamos nueva linea negativa var response2 = cls_creditmemos.CancelCreditmemoDetail(newrow, DocentryCredit); if (response.IsSuccessful == true) { var result = "SUCCESS"; return Json(result, JsonRequestBehavior.AllowGet); } else { var result = "Error"; return Json(result, JsonRequestBehavior.AllowGet); } } else { var result = "Error"; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { var resulterror = ex.Message; return Json(resulterror, JsonRequestBehavior.AllowGet); } } public ActionResult Get_creditMemoDetail(int DocentryCredit) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); var creditmemos = cls_creditmemos.GetCreditMemos(DocentryCredit, "", null, null, true); var returnreason = cls_returnreasons.GetReturnreasons(); var roles = new List<string>(); if (s.Contains("Front Desk")) { if (r.Contains("Receive Credits")) { roles.Add("FD"); } } else if (s.Contains("Operations")) { if (r.Contains("Receive Credits")) { roles.Add("OP"); roles.Add("QC"); } } if (r.Contains("Super Admin")) { roles.Add("FD"); roles.Add("OP"); roles.Add("QC"); } var returnsToshow = returnreason.data.Where(c => roles.Contains(c.authorizedBy)).ToList(); //filtramos data a mostrar var codes = returnsToshow.Select(c => c.reasonCode).ToArray(); if (creditmemos.data != null) { var sss = creditmemos.data.Where(c => c.details.Any(d => codes.Contains(d.returnReasonCode))).OrderBy(p => p. details. OrderBy(c => c.returnReasonCode).Select(c => c.returnReasonCode).FirstOrDefault()).ToList(); creditmemos.data = sss; } var result = new { details = creditmemos.data.FirstOrDefault().details, showsubmit = 0 }; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { var resulterror = ex.Message; var result = new { error = "Error", errormsg = resulterror }; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult Get_creditMemoDetailOriginal(int DocentryCredit) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; List<string> s = new List<string>(activeuser.Departments.Split(new string[] { "," }, StringSplitOptions.None)); List<string> r = new List<string>(activeuser.Roles.Split(new string[] { "," }, StringSplitOptions.None)); var creditmemos = cls_creditmemos.GetCreditMemoOriginal(DocentryCredit,true); var returnreason = cls_returnreasons.GetReturnreasons(); var roles = new List<string>(); if (s.Contains("Front Desk")) { if (r.Contains("Receive Credits")) { roles.Add("FD"); } } else if (s.Contains("Operations")) { if (r.Contains("Receive Credits")) { roles.Add("OP"); roles.Add("QC"); } } if (r.Contains("Super Admin")) { roles.Add("FD"); roles.Add("OP"); roles.Add("QC"); } var returnsToshow = returnreason.data.Where(c => roles.Contains(c.authorizedBy)).ToList(); //filtramos data a mostrar var codes = returnsToshow.Select(c => c.reasonCode).ToArray(); if (creditmemos.data != null) { var sss = creditmemos.data.Where(c => c.details.Any(d => codes.Contains(d.returnReasonCode))).OrderBy(p => p. details. OrderBy(c => c.returnReasonCode).Select(c => c.returnReasonCode).FirstOrDefault()).ToList(); creditmemos.data = sss; } var result = new { details= creditmemos.data.FirstOrDefault().details, showsubmit= 0 }; return Json(result, JsonRequestBehavior.AllowGet); } catch (Exception ex) { var resulterror = ex.Message; var result = new {error="Error", errormsg= resulterror }; return Json(result, JsonRequestBehavior.AllowGet); } } public ActionResult Transform_creditMemo(int docentryCreditMemo, int docEntryInv) { try { Sys_Users activeuser = Session["activeUser"] as Sys_Users; //Verificamos si no existen mas Creditos sin recibir var creditmemos = cls_creditmemos.GetCreditMemos(docEntryInv, "", null, null, true); var faltavalidar = false; foreach (var item in creditmemos.data) { foreach (var detail in item.details.Where(c=>c.quantity>0)) { if (detail.received == false && detail.noShow==false) { faltavalidar = true; } } } if (faltavalidar == false) { var response = cls_creditmemos.TransformCreditMemo(docentryCreditMemo, 1); if (response.IsSuccessful == true) { //Validamos que no haya autorizacion de NO recibir pago o incoming payments //1.Validamos estado de orden //Si el estado es =2, quiere decir que aun esta en Operaciones y el Vendedor NO ha realizado pagos var invoice = Cls_invoices.GetInvoice(docEntryInv, 0, false).data.FirstOrDefault(); PUT_Invoices_api newput = new PUT_Invoices_api(); //Si hay pagos, va para finanzas if (invoice.paymentsDraft > 0) { newput.stateSd = 3; } else { //Si no hay pagos y NO existe autorizacion, la dejamos en estado 6 Waiting for payment //Si autorizacion CODIGO 1 (deja producto sin recibir pago) se aprueba, colocar estado 6 y verificar que estado de factura NO sea 3 (sino quiere decir que el vendedor cambio ele stado) //Authorizations var authorizations = cls_Authorizations.GetAuthorizations(docEntryInv,"","",null,null); if (authorizations.data != null) { var existe = false; foreach (var auth in authorizations.data) { if (auth.idReason == 1) { existe = true; } } if (existe == true) { newput.stateSd = 6; } else { //Si NO existe, NO hay pagos, no hay otra evaluacion que hacer newput.stateSd = 6; } } } var response2 = Cls_invoices.PutInvoice(docEntryInv, newput); var result = "SUCCESS"; return Json(result, JsonRequestBehavior.AllowGet); } else { var result = "Error"; return Json(result, JsonRequestBehavior.AllowGet); } } else { var result = "VALIDAR"; return Json(result, JsonRequestBehavior.AllowGet); } } catch (Exception ex) { var resulterror = ex.Message; return Json(resulterror, JsonRequestBehavior.AllowGet); } } } }
using CarManageSystem.Extension; using CarManageSystem.helper; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.SessionState; namespace CarManageSystem.handler.FuelingCard { /// <summary> /// ViewCard 的摘要说明 /// </summary> public class ViewCard : IHttpHandler,IRequiresSessionState { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; var currentUser = CheckHelper.RoleCheck(context, 1); if (currentUser == null) return; dynamic json = new JObject(); json.state = "success"; var department = CheckHelper.GetDepartmentId(currentUser, context); using (cmsdbEntities cms = new cmsdbEntities()) { var cards = cms.mainfuelingcard .Where(s => department==-1?true:s.DepartmentId == department) .LeftJoin(cms.departmentmanage,c=>c.DepartmentId,d=>d.Id,(c,d)=>new { c,d.Name}) .Select(item => new { gasNumf=item.c.MainCardId, gasNums=item.c.AssociateCardId, gasLicence=item.c.CarNumber, gasState=item.c.Cardholder, department=item.Name }).ToList(); json.secondCardInf = JArray.FromObject(cards); json.gasSum = cards.Count(); context.Response.Write(json.ToString()); cms.Dispose(); } } public bool IsReusable { get { return false; } } } }
using UnityEngine; using ZST; using System; using System.Collections; using System.Collections.Generic; using Newtonsoft.Json; using MusicIO; public class ZmqMusicNode : MonoBehaviour { public InstrumentFactory m_instrumentSpawner; public string m_stageAddress = "127.0.0.1"; public string m_port = "6000"; public ZstNode node { get { return m_node; }} protected ZstNode m_node; protected Dictionary<string, ZstPeerLink> m_peers; protected ZstPeerLink m_livePeer; private static ZmqMusicNode m_instance; public static ZmqMusicNode Instance { get { return m_instance; }} // Use this for initialization void Start () { m_instance = this; m_node = new ZstNode("UnityNode", "tcp://" + m_stageAddress + ":" + m_port); m_node.requestRegisterNode(); m_peers = m_node.requestNodePeerlinks(); m_livePeer = m_peers["LiveNode"]; m_node.subscribeToNode(m_livePeer); m_node.connectToPeer(m_livePeer); ZstMethod response = m_node.updateRemoteMethod(m_livePeer.methods["get_song_layout"]); string output = response.output.ToString(); m_instrumentSpawner.LoadLiveSessionXml(output); //Subscribe to value updates m_node.subscribeToMethod(m_livePeer.methods["value_updated"], instrumentValueUpdated); m_node.subscribeToMethod(m_livePeer.methods["fired_slot_index"], clipFired); m_node.subscribeToMethod(m_livePeer.methods["playing_slot_index"], clipPlaying); //m_node.subscribeToMethod(m_livePeer.methods["value_updated"], clipFired); } /* * Incoming methods */ public object instrumentValueUpdated(ZstMethod methodData) { Debug.Log(methodData.output); Dictionary<string, object> output = JsonConvert.DeserializeObject<Dictionary<string, object>>(methodData.output.ToString()); BaseInstrumentParam param = InstrumentController.Instance.FindParameter(Convert.ToInt32(output["trackindex"]), Convert.ToInt32(output["deviceindex"]), Convert.ToInt32(output["parameterindex"])); if (param != null) param.setScaledVal(Convert.ToSingle(output["value"]), true); return null; } public object clipFired(ZstMethod methodData) { Dictionary<string, object> output = JsonConvert.DeserializeObject<Dictionary<string, object>>(methodData.output.ToString()); int trackIndex = Convert.ToInt32(output["trackindex"]); int slotIndex = Convert.ToInt32(output["slotindex"]); if (slotIndex >= 0) { InstrumentClip clip = InstrumentController.Instance.FindClip(trackIndex, slotIndex); clip.SetClipState(InstrumentClip.ClipState.IS_QUEUED); } return null; } public object clipPlaying(ZstMethod methodData) { Dictionary<string, object> output = JsonConvert.DeserializeObject<Dictionary<string, object>>(methodData.output.ToString()); int trackIndex = Convert.ToInt32(output["trackindex"]); int slotIndex = Convert.ToInt32(output["slotindex"]); InstrumentClip playingClip = InstrumentController.Instance.GetInstrumentByTrackindex(trackIndex).playingClip; if (slotIndex < 0) { //Stopping if(playingClip != null) playingClip.SetClipState(InstrumentClip.ClipState.IS_DISABLED); } else { if(playingClip != null) playingClip.SetClipState(InstrumentClip.ClipState.IS_DISABLED); InstrumentClip clip = InstrumentController.Instance.FindClip(trackIndex, slotIndex); clip.SetClipState(InstrumentClip.ClipState.IS_PLAYING); } return null; } /* * Outgoing methods */ public void updateInstrumentValue(int trackIndex, int deviceIndex, int parameterIndex, int value){ m_node.updateRemoteMethod( m_livePeer.methods["set_value"], new Dictionary<string, object>(){ {"deviceindex", deviceIndex}, {"trackindex", trackIndex}, {"parameterindex", parameterIndex}, {"value", value} }); } public void playNote(int trackIndex, int note, int velocity, int trigger) { m_node.updateRemoteMethod( m_livePeer.methods["play_note"], new Dictionary<string, object>(){ {"trackindex", trackIndex}, {"note", note}, {"state", trigger}, {"velocity", velocity} }); } public void fireClip(int trackIndex, int clipIndex){ m_node.updateRemoteMethod( m_livePeer.methods["fire_clip"], new Dictionary<string, object>(){ {"trackindex", trackIndex}, {"clipindex", clipIndex} }); } /* * Exit and cleanup */ public void OnApplicationQuit(){ bool result = m_node.close(); Debug.Log("Network cleanup: " + result); } }
using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Npgsql; using pract.Models; namespace pract.Controllers { [Route("api/Work")] [ApiController] public class WorkController : ControllerBase { private readonly WorkContext _context; public WorkController(WorkContext context) { _context = context; } [HttpGet] public IActionResult GetWorks() { var works = _context.Work.ToList(); return Ok(works); } [HttpGet("{id}")] public IActionResult GetWorksbyId(int id) { var work = _context.Work.Find(id); if (work == null) { return NotFound(); } return Ok(work); } [HttpPost("{name}/{id}")] public IActionResult PostWork(string name, int id) { var work = new Work() { work_Name = name, comp_Id = id }; _context.Add(work); _context.SaveChanges(); return Ok("Created"); } [HttpPut("{id}/{rename}/{id2}")] public IActionResult PutWork(int id, string rename, int id2) { var work = _context.Work.Find(id); if (work == null) { return NotFound(); } work.work_Name = rename; work.comp_Id = id2; _context.Work.Update(work); _context.SaveChanges(); return Ok("Update"); } [HttpDelete("{id}")] public IActionResult DeleteWork(int id) { var work = _context.Work.Find(id); if (work == null) { return NotFound(); } _context.Work.Remove(work); _context.SaveChanges(); return Ok("Deleted"); } } }
using System; using System.Collections.Generic; using System.Text; namespace SelectionCommittee.BLL.DataTransferObject { public class SpecialtyDTO { public int Id { get; set; } public int Number { get; set; } public string Name { get; set; } public int BudgetPlaces { get; set; } public int TotalPlaces { get; set; } public string Description { get; set; } public int FacultyId { get; set; } public string Photo { get; set; } } }
using Allyn.Application.Dto.Manage.Basic; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Security.Principal; using System.Web; using System.Web.Security; using System.Xml; namespace Allyn.MvcApp { public static class FormsAuthenticationManager { internal static void SignIn(this IPrincipal source, string name, bool isPersistent, string userData) { SignIn(source, name, isPersistent, userData, FormsAuthentication.FormsCookiePath); } /// <summary> /// 用户登录. /// </summary> /// <param name="source">源</param> /// <param name="name">用户名</param> /// <param name="isPersistent">是否记记住.</param> /// <param name="userData">Json格式的用户对象.</param> /// <param name="cookiePath">Cookie路径.</param> internal static void SignIn(this IPrincipal source, string name, bool isPersistent, string userData,string cookiePath) { //Cookie 名称 string cookieName = FormsAuthentication.FormsCookieName; //过期时间 TimeSpan timeout = FormsAuthentication.Timeout; //创建成员资格 FormsAuthenticationTicket tick = new FormsAuthenticationTicket(2, name, DateTime.Now, DateTime.Now.Add(timeout), isPersistent, JsonConvert.SerializeObject(userData), cookiePath ); HttpCookie cookie = new HttpCookie(cookieName, FormsAuthentication.Encrypt(tick)) { HttpOnly = true, Path = cookiePath, Expires = DateTime.Now.Add(timeout), Secure = FormsAuthentication.RequireSSL, }; HttpContext.Current.Response.Cookies.Remove(cookieName); HttpContext.Current.Response.Cookies.Add(cookie); } internal static void SignOut(this IPrincipal source) { FormsAuthentication.SignOut(); } internal static void SignOut(this IPrincipal source,string cookiePath) { //Cookie 名称 string cookieName = FormsAuthentication.FormsCookieName; //过期时间 TimeSpan timeout = FormsAuthentication.Timeout; //创建成员资格 FormsAuthenticationTicket tick = new FormsAuthenticationTicket(2, Guid.NewGuid().ToString("N"), DateTime.Now.AddDays(-1), DateTime.Now.AddDays(-1), false, string.Empty, cookiePath ); HttpCookie cookie = new HttpCookie(cookieName, FormsAuthentication.Encrypt(tick)) { HttpOnly = true, Path = cookiePath, Expires = DateTime.Now.Add(timeout), Secure = FormsAuthentication.RequireSSL, }; HttpContext.Current.Response.Cookies.Remove(cookieName); HttpContext.Current.Response.Cookies.Add(cookie); } internal static T GetDetails<T>(this IIdentity identity) where T:class { if (!identity.IsAuthenticated) { throw new Exception("用户未授权,不能读取用户数据!"); } HttpContext context = HttpContext.Current; if (context == null) { throw new HttpParseException("当前Http请求无效!"); } HttpCookie cookie = context.Request.Cookies[FormsAuthentication.FormsCookieName]; if (cookie == null) { throw new Exception("读取 Cookie 失败!"); } FormsAuthenticationTicket tick = FormsAuthentication.Decrypt(cookie.Value); try { return JsonConvert.DeserializeObject<T>(tick.UserData.Replace("\\", "").Trim('"')); } catch (Exception ex) { throw ex; } } internal static void UpdateDetails(this IIdentity identity, string userData) { if (!identity.IsAuthenticated) { throw new Exception("用户未授权,不能读取用户数据!"); } HttpContext context = HttpContext.Current; if (context == null) { throw new HttpParseException("当前Http请求无效!"); } //Cookie 名称 string cookieName = FormsAuthentication.FormsCookieName; HttpCookie cookie = context.Request.Cookies[cookieName]; if (cookie == null) { throw new Exception("读取 Cookie 失败!"); } //解密票证. FormsAuthenticationTicket tick = FormsAuthentication.Decrypt(cookie.Value); //创建新票证 FormsAuthenticationTicket newTick = new FormsAuthenticationTicket( tick.Version, tick.Name, tick.IssueDate, tick.Expiration, tick.IsPersistent, userData ); //创建新Cookie HttpCookie newCookie = new HttpCookie(cookieName, FormsAuthentication.Encrypt(newTick)) { HttpOnly = cookie.HttpOnly, Expires = cookie.Expires, Secure = cookie.Secure }; HttpContext.Current.Response.Cookies.Add(newCookie); } private static XmlNode GetAuthFormesNode(string configPath, string attributeName) { //检测参数 if (configPath == null || configPath.Length == 0) throw new ArgumentNullException("configPath"); if (attributeName == null || attributeName.Length == 0) throw new ArgumentNullException("attributeName"); //读取文件和节点 XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(configPath); return xmlDocument.SelectSingleNode("/configuration/system.web/authentication/forms"); } private static void SetAuthFormesAttribute(string configPath, string attributeName, string value) { //检测参数 if (configPath == null || configPath.Length == 0) throw new ArgumentNullException("configPath"); if (attributeName == null || attributeName.Length == 0) throw new ArgumentNullException("attributeName"); if (value == null || value.Length == 0) throw new ArgumentNullException("value"); //读取文件和节点 XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(configPath); XmlNode formsNode = xmlDocument.SelectSingleNode("/configuration/system.web/authentication/forms"); if (formsNode == null) throw new XmlException("没有找到指定路径的节点! 指定的路径: /configuration/system.web/authentication/forms"); XmlAttribute attr = formsNode.Attributes[attributeName]; if (attr == null) throw new XmlException("没有找到名称为" + attributeName + "的特性!"); attr.Value = value; xmlDocument.Save(configPath); } private static void AddAuthFormesAttribute(string configPath, string attributeName, string value) { //检测参数 if (configPath == null || configPath.Length == 0) throw new ArgumentNullException("configPath"); if (attributeName == null || attributeName.Length == 0) throw new ArgumentNullException("attributeName"); if (value == null || value.Length == 0) throw new ArgumentNullException("value"); //读取文件和节点 XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(configPath); XmlNode formsNode = xmlDocument.SelectSingleNode("/configuration/system.web/authentication/forms"); if (formsNode == null) throw new XmlException("没有找到指定路径的节点! 指定的路径: /configuration/system.web/authentication/forms"); XmlAttribute attr = xmlDocument.CreateAttribute(attributeName); attr.Value = value; formsNode.Attributes.Append(attr); xmlDocument.Save(configPath); } } }
namespace Sentry.EntityFramework; internal static class DbCommandInterceptionContextExtensions { internal static ISpan? GetSpanFromContext<T>(this DbCommandInterceptionContext<T> interceptionContext) => interceptionContext.FindUserState(SentryQueryPerformanceListener.SentryUserStateKey) as ISpan; internal static void AttachSpan<T>(this DbCommandInterceptionContext<T> interceptionContext, ISpan span) => interceptionContext.SetUserState(SentryQueryPerformanceListener.SentryUserStateKey, span); }
using System.Collections.Generic; using FluentAssertions; using NUnit.Framework; using Properties.Core.Objects; namespace Properties.Tests.UnitTests.Objects { [TestFixture] // ReSharper disable once InconsistentNaming public class SubmittedProperty_ShortDescription_TestFixture { [Test] public void No_Bedroom_Or_Bathroom_Feature_Generates_Short_Description() { //Arrange var property = new SubmittedProperty { PropertyType = PropertyType.Flat }; //Act var description = property.BuildShortDescription(); //Assert description.Should().NotBeNullOrEmpty(); description.Should().EndWith("Flat."); } [Test] public void Bedroom_But_No_Bathroom_Feature_Generates_Short_Description_Including_No_Of_Bedrooms() { //Arrange var property = new SubmittedProperty { PropertyType = PropertyType.Flat, Features = new List<Feature> {new Feature {FeatureType = FeatureType.NumberOfBedrooms, FeatureValue = "2"}} }; //Act var description = property.BuildShortDescription(); //Assert description.Should().NotBeNullOrEmpty(); description.Should().EndWith("2 Bedroom Flat."); } [Test] public void No_Bedroom_But_Has_Bathroom_Feature_Generates_Short_Description_Including_No_Of_Bathrooms() { //Arrange var property = new SubmittedProperty { PropertyType = PropertyType.Flat, Features = new List<Feature> { new Feature { FeatureType = FeatureType.NumberOfBathrooms, FeatureValue = "2" } } }; //Act var description = property.BuildShortDescription(); //Assert description.Should().NotBeNullOrEmpty(); description.Should().EndWith("2 Bathroom Flat."); } [Test] public void Bedroom_And_Bathroom_Feature_Generates_Short_Decsription_Including_Beds_And_Baths() { //Arrange var property = new SubmittedProperty { PropertyType = PropertyType.Flat, Features = new List<Feature> { new Feature { FeatureType = FeatureType.NumberOfBedrooms, FeatureValue = "2" }, new Feature { FeatureType = FeatureType.NumberOfBathrooms, FeatureValue = "2" } } }; //Act var description = property.BuildShortDescription(); //Assert description.Should().NotBeNullOrEmpty(); description.Should().EndWith("2 Bedroom, 2 Bathroom Flat."); } [Test] public void Multiple_Occupancy_And_Bedroom_And_Bathroom_Feature_Generates_Short_Decsription_Including_Beds_And_Baths() { //Arrange var property = new SubmittedProperty { PropertyType = PropertyType.Flat, Features = new List<Feature> { new Feature { FeatureType = FeatureType.NumberOfBedrooms, FeatureValue = "2" }, new Feature { FeatureType = FeatureType.NumberOfBathrooms, FeatureValue = "2" }, new Feature { FeatureType = FeatureType.MultipleOccupancy, FeatureValue = "Yes" } } }; //Act var description = property.BuildShortDescription(); //Assert description.Should().NotBeNullOrEmpty(); description.Should().EndWith("Room in a 2 Bedroom, 2 Bathroom Flat."); } } }
namespace DentistClinic.Core.Migrations { using System; using System.Data.Entity.Migrations; public partial class Teeth : DbMigration { public override void Up() { DropForeignKey("dbo.OutpatientCases", "Checkup_MedicalCategoryId", "dbo.MedicalCategories"); DropForeignKey("dbo.OutpatientCases", "Treatment_MedicalCategoryId", "dbo.MedicalCategories"); DropIndex("dbo.OutpatientCases", new[] { "Checkup_MedicalCategoryId" }); DropIndex("dbo.OutpatientCases", new[] { "Treatment_MedicalCategoryId" }); AddColumn("dbo.OutpatientCases", "Checkup", c => c.String()); AddColumn("dbo.OutpatientCases", "Treatment", c => c.String()); AddColumn("dbo.OutpatientCases", "TeethUpLeft", c => c.String()); AddColumn("dbo.OutpatientCases", "TeethUpRight", c => c.String()); AddColumn("dbo.OutpatientCases", "TeethDownLeft", c => c.String()); AddColumn("dbo.OutpatientCases", "TeethDownRight", c => c.String()); DropColumn("dbo.OutpatientCases", "TeethUp"); DropColumn("dbo.OutpatientCases", "TeethDown"); DropColumn("dbo.OutpatientCases", "Checkup_MedicalCategoryId"); DropColumn("dbo.OutpatientCases", "Treatment_MedicalCategoryId"); } public override void Down() { AddColumn("dbo.OutpatientCases", "Treatment_MedicalCategoryId", c => c.Int()); AddColumn("dbo.OutpatientCases", "Checkup_MedicalCategoryId", c => c.Int()); AddColumn("dbo.OutpatientCases", "TeethDown", c => c.String()); AddColumn("dbo.OutpatientCases", "TeethUp", c => c.String()); DropColumn("dbo.OutpatientCases", "TeethDownRight"); DropColumn("dbo.OutpatientCases", "TeethDownLeft"); DropColumn("dbo.OutpatientCases", "TeethUpRight"); DropColumn("dbo.OutpatientCases", "TeethUpLeft"); DropColumn("dbo.OutpatientCases", "Treatment"); DropColumn("dbo.OutpatientCases", "Checkup"); CreateIndex("dbo.OutpatientCases", "Treatment_MedicalCategoryId"); CreateIndex("dbo.OutpatientCases", "Checkup_MedicalCategoryId"); AddForeignKey("dbo.OutpatientCases", "Treatment_MedicalCategoryId", "dbo.MedicalCategories", "MedicalCategoryId"); AddForeignKey("dbo.OutpatientCases", "Checkup_MedicalCategoryId", "dbo.MedicalCategories", "MedicalCategoryId"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using jaytwo.Common.Extensions; namespace jaytwo.Common.Futures.Security { public class PasswordGenerator { private char[] lower = "abcdefghijklmnopqrxtuvwxyz".ToArray(); private char[] upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToArray(); private char[] numeric = "0123456789".ToArray(); private char[] punctuation = "!@#$%^&*()_+-={}|[]<>?.,;".ToArray(); private char[] similarCharacters = "|1lIoO0".ToArray(); private int passwordLength = 8; public int PasswordLength { get { return passwordLength; } set { passwordLength = value; } } private bool includeLetters = true; public bool IncludeLetters { get { return includeLetters; } set { includeLetters = value; } } private bool beginWithLetter = true; public bool BeginWithLetter { get { return beginWithLetter; } set { beginWithLetter = value; } } private bool includeMixedCase = true; public bool IncludeMixedCase { get { return includeMixedCase; } set { includeMixedCase = value; } } private bool includeNumeric = true; public bool IncludeNumeric { get { return includeNumeric; } set { includeNumeric = value; } } private bool includePunctuation = false; public bool IncludePunctuation { get { return includePunctuation; } set { includePunctuation = value; } } private bool noSimilarCharacters = true; public bool NoSimilarCharacters { get { return noSimilarCharacters; } set { noSimilarCharacters = value; } } private char GetRandomCharacter() { var sets = new List<char[]>(); if (IncludeLetters) { sets.Add(lower); if (IncludeMixedCase) { sets.Add(upper); } } if (IncludeNumeric) { sets.Add(numeric); } if (IncludePunctuation) { sets.Add(punctuation); } var randomSet = sets.FirstRandom(); return GetRandomCharacter(randomSet); } private char GetRandomCharacter(char[] chars) { if (NoSimilarCharacters) { var safeChars = chars .Where(x => similarCharacters.All(y => x != y)) .ToArray(); return safeChars.FirstRandom(); } else { return chars.FirstRandom(); } } public static string GenerateDefault() { return new PasswordGenerator().Generate(); } public static string GenerateDefault(int passwordLength) { var generator = new PasswordGenerator() { PasswordLength = passwordLength, }; return generator.Generate(); } public int GetComplexity() { int result = 0; if (IncludeLetters) { result++; if (IncludeMixedCase) { result++; } } if (IncludeNumeric) { result++; } if (IncludePunctuation) { result++; } return result; } public string Generate() { int complexity = GetComplexity(); if (complexity == 0) { throw new Exception("Password complexity must be greater than zero."); } else if (complexity > PasswordLength) { throw new Exception("Password length insufficient for complexity of " + complexity); } var result = new StringBuilder(); if (IncludeLetters) { result.Append(GetRandomCharacter(lower)); if (IncludeMixedCase) { result.Append(GetRandomCharacter(upper)); } } if (IncludeNumeric) { result.Append(GetRandomCharacter(numeric)); } if (IncludePunctuation) { result.Append(GetRandomCharacter(punctuation)); } while (result.Length < passwordLength) { result.Append(GetRandomCharacter()); } return Scramble(result.ToString()); } private string Scramble(string plain) { char[] result; if (BeginWithLetter && IncludeLetters) { var orderedByIsLetter = plain .OrderByRandom() .OrderByDescending(x => char.IsLetter(x)) .ToList(); var resultList = new List<char>(); resultList.Add(orderedByIsLetter.First()); resultList.AddRange(orderedByIsLetter.Skip(1).OrderByRandom()); result = resultList.ToArray(); } else { result = plain .OrderByRandom() .ToArray(); } return new string(result.ToArray()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Robots { abstract class RobotDecorator : PaintingRobot { public string DescriptionTemplate(string name, PaintingRobot r2) { string result = r2.ToString(); result = result.Replace("\n", "\n\t"); return $"{name} {this.GetPaintedLength(1)}\n(\n\t{result}\n)"; } public string DescriptionTemplate(string name, List<PaintingRobot> robots) { string result = ""; foreach (var robot in robots) { result += "\t" + robot.ToString().Replace("\n", "\n\t") + "\n"; } return $"{name} {this.GetPaintedLength(1)}\n(\n{result})"; } } class RobotDecoratorAdd : RobotDecorator { private double n; private PaintingRobot robot; public RobotDecoratorAdd(PaintingRobot robot, double n) { this.robot = robot; this.n = n; } public override double GetPaintedLength(double time) { return robot.GetPaintedLength(time) + n; } public override string ToString() { return this.DescriptionTemplate("adding robot", robot); } } class RobotDecoratorMultiply : RobotDecorator { private double n; private PaintingRobot robot; public RobotDecoratorMultiply(PaintingRobot robot, double n) { this.robot = robot; this.n = n; } public override double GetPaintedLength(double time) { return robot.GetPaintedLength(time) * n; } public override string ToString() { return this.DescriptionTemplate("multiplying robot", robot); } } class RobotDecoratorNlogN : RobotDecorator { private PaintingRobot robot; public RobotDecoratorNlogN(PaintingRobot robot) { this.robot = robot; } public override double GetPaintedLength(double time) { double n = robot.GetPaintedLength(time); return n * Math.Log(n); } public override string ToString() { return this.DescriptionTemplate("NlogN robot", robot); } } class RobotDecoratorMax : RobotDecorator { private List<PaintingRobot> robots; public RobotDecoratorMax(List<PaintingRobot> robots) { this.robots = robots; } public override double GetPaintedLength(double time) { double max = 0; foreach(var robot in robots) { if(robot.GetPaintedLength(time) > max) { max = robot.GetPaintedLength(time); } } return max; } public override string ToString() { return this.DescriptionTemplate("max robot", robots); } } class RobotDecoratorSum : RobotDecorator { private List<PaintingRobot> robots; public RobotDecoratorSum(List<PaintingRobot> robots) { this.robots = robots; } public override double GetPaintedLength(double time) { double sum = 0; foreach (var robot in robots) { sum += robot.GetPaintedLength(time); } return sum; } public override string ToString() { return this.DescriptionTemplate("sum robot", robots); } } class LazyRobot : PaintingRobot { double n; public LazyRobot(double n) { this.n = n; } public override double GetPaintedLength(double time) { return n * Math.Log(time); } public override string ToString() { return "lazy robot"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.Category { public class ICategory : Category { } /// <summary> /// 分类,由于缓存,只能实现一种类型,不要继承此类实现多个实例 /// </summary> [Attribute.Table(TableName = "Category")] public class Category : IModelBase { public override string CheckData() { return ""; } /// <summary> /// 类型,以作不同用途 /// </summary> public int DataType { get; set; } public string Name { get; set; } public string SequenceCode { get; set; } public string ParentCode { get; set; } public string Remark { get; set; } /// <summary> /// 是否禁用 /// </summary> public bool Disable { get; set; } public int Sort { get; set; } public override string ToString() { return Name; } } }
using System; namespace gView.MapServer { public interface IMapServiceSettings { MapServiceStatus Status { get; set; } IMapServiceAccess[] AccessRules { get; set; } DateTime RefreshService { get; set; } string OnlineResource { get; set; } string OutputUrl { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace elso_feladat { class Program { static void Main(string[] args) { string[] adatok = File.ReadAllLines("tanulok.csv", Encoding.Default); Tanulok[] tanulok = new Tanulok[adatok.Length]; for (int i = 0; i < adatok.Length; i++) { string[] bontottSor = adatok[i].Split(';'); tanulok[i] = new Tanulok(bontottSor[0], Convert.ToDouble(bontottSor[1]), bontottSor[2]); } for (int i = 0; i < tanulok.Length; i++) { Console.WriteLine(tanulok[i].Nev + " - " + tanulok[i].Atlag + " - " + tanulok[i].SzemelyiSzam); Console.WriteLine(); } Console.WriteLine("A tanulók átlaga: " + Tanulok.TanulokAtlaga(tanulok)); Console.ReadKey(); } } }
using Crystal.Plot2D.Common; using System; using System.Collections.Generic; using System.Linq; namespace Crystal.Plot2D.Charts { /// <summary> /// Represents a ticks provider for intefer values. /// </summary> public class IntegerTicksProvider : ITicksProvider<int> { /// <summary> /// Initializes a new instance of the <see cref="IntegerTicksProvider"/> class. /// </summary> public IntegerTicksProvider() { } private int minStep = 0; /// <summary> /// Gets or sets the minimal step between ticks. /// </summary> /// <value>The min step.</value> public int MinStep { get { return minStep; } set { Verify.IsTrue(value >= 0, "value"); if (minStep != value) { minStep = value; RaiseChangedEvent(); } } } private int maxStep = int.MaxValue; /// <summary> /// Gets or sets the maximal step between ticks. /// </summary> /// <value>The max step.</value> public int MaxStep { get { return maxStep; } set { if (maxStep != value) { if (value < 0) { throw new ArgumentOutOfRangeException("value", Strings.Exceptions.ParameterShouldBePositive); } maxStep = value; RaiseChangedEvent(); } } } #region ITicksProvider<int> Members /// <summary> /// Generates ticks for given range and preferred ticks count. /// </summary> /// <param name="range">The range.</param> /// <param name="ticksCount">The ticks count.</param> /// <returns></returns> public ITicksInfo<int> GetTicks(Range<int> range, int ticksCount) { double start = range.Min; double finish = range.Max; double delta = finish - start; int log = (int)Math.Round(Math.Log10(delta)); double newStart = RoundingHelper.Round(start, log); double newFinish = RoundingHelper.Round(finish, log); if (newStart == newFinish) { log--; newStart = RoundingHelper.Round(start, log); newFinish = RoundingHelper.Round(finish, log); } // calculating step between ticks double unroundedStep = (newFinish - newStart) / ticksCount; int stepLog = log; // trying to round step int step = (int)RoundingHelper.Round(unroundedStep, stepLog); if (step == 0) { stepLog--; step = (int)RoundingHelper.Round(unroundedStep, stepLog); if (step == 0) { // step will not be rounded if attempts to be rounded to zero. step = (int)unroundedStep; } } if (step < minStep) { step = minStep; } if (step > maxStep) { step = maxStep; } if (step <= 0) { step = 1; } int[] ticks = CreateTicks(start, finish, step); TicksInfo<int> res = new() { Info = log, Ticks = ticks }; return res; } private static int[] CreateTicks(double start, double finish, int step) { DebugVerify.Is(step != 0); int x = (int)(step * Math.Floor(start / (double)step)); List<int> res = new(); checked { double increasedFinish = finish + step * 1.05; while (x <= increasedFinish) { res.Add(x); x += step; } } return res.ToArray(); } private static readonly int[] tickCounts = new int[] { 20, 10, 5, 4, 2, 1 }; /// <summary> /// Decreases the tick count. /// Returned value should be later passed as ticksCount parameter to GetTicks method. /// </summary> /// <param name="ticksCount">The ticks count.</param> /// <returns>Decreased ticks count.</returns> public int DecreaseTickCount(int ticksCount) { return tickCounts.FirstOrDefault(tick => tick < ticksCount); } /// <summary> /// Increases the tick count. /// Returned value should be later passed as ticksCount parameter to GetTicks method. /// </summary> /// <param name="ticksCount">The ticks count.</param> /// <returns>Increased ticks count.</returns> public int IncreaseTickCount(int ticksCount) { int newTickCount = tickCounts.Reverse().FirstOrDefault(tick => tick > ticksCount); if (newTickCount == 0) { newTickCount = tickCounts[0]; } return newTickCount; } /// <summary> /// Gets the minor ticks provider, used to generate ticks between each two adjacent ticks. /// </summary> /// <value>The minor provider.</value> public ITicksProvider<int> MinorProvider { get { return null; } } /// <summary> /// Gets the major provider, used to generate major ticks - for example, years for common ticks as months. /// </summary> /// <value>The major provider.</value> public ITicksProvider<int> MajorProvider { get { return null; } } protected void RaiseChangedEvent() { Changed.Raise(this); } public event EventHandler Changed; #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abhs.Common.Enums { public class SysModel { } public enum PrepareTypeEnum { 错题巩固 = 1, 智能学习 = 2, 查漏补缺 = 3, 考试课 = 4 } public enum OpreationTypeEnum { 浏览页面 = 1, 按钮操作 = 2 } public enum EnumButtonModel { 备课 = 1 } public enum EnumSysModel { 数据初始化 = 1, 课表数据处理 = 2, 课表数据生成 = 3, 班级学生汇总数据 = 4 } }
using System; namespace CursoCsharp.Fundamentos { class OperadoresLogicos { public static void Execultar() { var execultouTrabalho1 = true; var execultouTrabalho2 = true; bool comprouTV50 = execultouTrabalho1 && execultouTrabalho2; Console.WriteLine("Comprou a TV de 50? {0}", comprouTV50); var comprouSorvete = execultouTrabalho1 || execultouTrabalho2; Console.WriteLine("Comprou Sorvete? {0}", comprouSorvete); var comprouTV32 = execultouTrabalho1 ^ execultouTrabalho2; Console.WriteLine("Comprou a TV 32 {0}", comprouTV32); Console.WriteLine("Mais saúdavel? {0}", !comprouSorvete); } } }
namespace AutoCodeBuilder { internal class FluentMethodInfo { public FluentMethodInfo(string name) { Name = name; } private string AddSuffix(string suffix) { if (IsFrom) return FluentPrefix + suffix; return FluentPrefix + "From" + suffix; } public bool AllowAncestor => IsFrom; private bool IsFrom => Name == "From"; public string Name { get; } public string FluentPrefix { get { if (IsFrom) return "WithBindFrom"; return "With" + Name; } } public string Static => AddSuffix("Static"); public string StaticResource => AddSuffix("Resource"); public string DynamicResource => AddSuffix("DynamicResource"); public string Ancestor => AddSuffix("Ancestor"); public string Self => AddSuffix("Self"); public string ElementName => AddSuffix("ElementName"); } }
using Microsoft.Owin.Hosting; using RRExpress.Service; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; using Topshelf; namespace MoqServicesHost { class WebApiServer : ServiceControl { private IDisposable _WebApp = null; private int Port; /// <summary> /// /// </summary> /// <param name="port">使用端口</param> /// <param name="url">基地址</param> public WebApiServer(int port = 80) { this.Port = port; } public bool Start(HostControl hostControl) { try { var opt = new StartOptions() { Port = this.Port }; opt.Urls.Add("http://localhost"); opt.Urls.Add("http://127.0.0.1"); var ips = Dns.GetHostAddresses(Dns.GetHostName()); foreach (var ip in ips) { if (ip.AddressFamily == AddressFamily.InterNetwork) { var str = $"http://{ip.MapToIPv4().ToString()}"; opt.Urls.Add(str); } } this._WebApp = WebApp.Start<Startup>(opt); return true; } catch (Exception) { return false; } } public bool Stop(HostControl hostControl) { if (this._WebApp != null) this._WebApp.Dispose(); return true; } } }
namespace ServiceDesk.Ticketing.DataAccess.Migrations { using System; using System.Data.Entity.Migrations; public partial class addColumnRequestedDateTicket : DbMigration { public override void Up() { AddColumn("Ticketing.Tickets", "RequestedDate", c => c.DateTime(nullable: false)); AlterColumn("Ticketing.Tickets", "DueDate", c => c.DateTime()); } public override void Down() { AlterColumn("Ticketing.Tickets", "DueDate", c => c.DateTime(nullable: false)); DropColumn("Ticketing.Tickets", "RequestedDate"); } } }
using System; using System.Collections.Generic; using System.Data.Entity.ModelConfiguration; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TransferData.DataAccess.Entity.Mapping { public class MappingResultCase :MappingBase { } public class MappingResultCaseConfig : EntityTypeConfiguration<MappingResultCase> { public MappingResultCaseConfig() { ToTable("MappingResultCase"); } } }
using UnityEngine; using UnityEngine.Events; public class Attack : MonoBehaviour { public UnityEvent OnAttack; [SerializeField] private float targetDistance = 0f; protected Sight sight; [SerializeField] protected float rangeAttack = 1f; private bool isAttacking = false; public Color gizmosColor = Color.red; public bool IsAttacking { get { return isAttacking; } set { isAttacking = value; } } private void Start() { sight = GetComponent<Sight>(); } private void Update() { if (IsAttacking) TryToAttackTarget(); } private void TryToAttackTarget() { targetDistance = Vector3.Distance(sight.target.position, transform.position); if (targetDistance < rangeAttack * transform.localScale.x) { AttackTarget(); } } public virtual void AttackTarget() { Debug.Log("Attacking to " + sight.target.name); if (OnAttack != null) OnAttack.Invoke(); } private void OnDrawGizmos() { Gizmos.color = gizmosColor; Gizmos.DrawWireSphere(transform.position, rangeAttack * transform.localScale.x); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using TechTalk.SpecFlow; using WatiN.Core; namespace ScoreSquid.Web.Functional.Tests.Steps { public class LoginSteps { private IE ie; [Given(@"that I have an existing account")] public void GivenThatIHaveAnExistingAccount() { ie = new IE("http://localhost:51341"); } [When(@"I enter valid login details")] public void WhenIEnterValidLoginDetails() { ie.TextField(Find.ById("Username")).TypeText("valid@gmail.com"); ie.TextField(Find.ById("Password")).TypeText("valid"); } [When(@"I submit my login request")] public void WhenISubmitMyLoginRequest() { ie.Button(Find.ByValue("Submit")).Click(); } [Then(@"I should gain access to my account")] public void ThenIShouldGainAccessToMyAccount() { ie.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Выпускной_проект1 { public class PasswordGenerator { private Random _rnd = new Random(); /// <summary> /// Gets the random password. /// </summary> /// <param name="stringCharacters">String to generate password from.</param> /// <param name="length">Length of the password.</param> /// <returns></returns> public string GeneratePassword(string stringCharacters, int length) { return GeneratePassword(stringCharacters.ToList(), length); } /// <summary> /// Gets the random password. /// </summary> /// <param name="chars">Characters to generate password from.</param> /// <param name="length">Length of the password.</param> /// <returns></returns> public string GeneratePassword(IEnumerable<char> chars, int length) { var builder = new StringBuilder(); for(int i = 0; i < length; i++) { var rndIndex = _rnd.Next(chars.Count()); builder.Append(chars.ElementAt(rndIndex)); } return builder.ToString(); } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.EntityFrameworkCore.Diagnostics; namespace WxShop.DBManager.EF { public class WxShopContextFactory : IDesignTimeDbContextFactory<WxShopContext> { public WxShopContext CreateDbContext(string[] args) { var optionsBuilder = new DbContextOptionsBuilder<WxShopContext>(); var connectionString = @"Data Source=.;Initial Catalog=WxShopDB;uid=sa;password=Sa123456;MultipleActiveResultSets=True;Connection Timeout=30;MultipleActiveResultSets=True;App=EntityFramework;"; optionsBuilder.UseSqlServer(connectionString, options => options.EnableRetryOnFailure()) .ConfigureWarnings(warnings => warnings.Throw(RelationalEventId.QueryClientEvaluationWarning)); return new WxShopContext(optionsBuilder.Options); } } }
using System; using System.Collections.Generic; namespace Twelve { public class TestService : ITestService { public TestService() { MyProperty = Guid.NewGuid(); } public Guid MyProperty { get; set; } public List<string> GetList(string a) { return new List<string>() { "LiLei", "ZhangSan", "LiSi" }; } } public interface ITestService { Guid MyProperty { get; } List<string> GetList(string a); } public interface ITestService2 { Guid MyProperty { get; } List<string> GetList(); } public interface ITestService3 { Guid MyProperty { get; } List<string> GetList(); } public class TestService2 : ITestService2 { public TestService2() { MyProperty = Guid.NewGuid(); } public Guid MyProperty { get; set; } public List<string> GetList() { return new List<string>() { "LiLei", "ZhangSan", "LiSi" }; } } public class TestService3 : ITestService3 { public TestService3() { MyProperty = Guid.NewGuid(); } public Guid MyProperty { get; set; } public List<string> GetList() { return new List<string>() { "LiLei", "ZhangSan", "LiSi" }; } } }
using System; using System.Collections; using UnityEngine; namespace GFW { public delegate void MonoUpdaterEvent(); public class MonoHelper:MonoBehaviour { private const string m_EntityName = "AppMain"; private static MonoHelper m_instance; public static MonoHelper Instance { get { if (m_instance == null) { GameObject obj = GameObject.Find(m_EntityName); if (obj == null) { obj = new GameObject(m_EntityName); } GameObject.DontDestroyOnLoad(obj); m_instance = obj.GetComponent<MonoHelper>(); if (m_instance == null) { m_instance = obj.AddComponent<MonoHelper>(); } } return m_instance; } } private event MonoUpdaterEvent UpdateEvent; private event MonoUpdaterEvent FixedUpdateEvent; public static void AddUpdateListener(MonoUpdaterEvent listener) { if (Instance != null) { Instance.UpdateEvent += listener; } } public static void RemoveUpdateListener(MonoUpdaterEvent listener) { if (Instance != null) { Instance.UpdateEvent -= listener; } } public static void AddFixedUpdateListener(MonoUpdaterEvent listener) { if (Instance != null) { Instance.FixedUpdateEvent += listener; } } public static void RemoveFixedUpdateListener(MonoUpdaterEvent listener) { if (Instance != null) { Instance.FixedUpdateEvent -= listener; } } void Update() { if (UpdateEvent != null) { UpdateEvent(); } } void FixedUpdate() { if (FixedUpdateEvent != null) { FixedUpdateEvent(); } } //=========================================================== public static new Coroutine StartCoroutine(IEnumerator routine) { MonoBehaviour mono = Instance; return mono.StartCoroutine(routine); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Euler_Logic.Problems.AdventOfCode.Y2021 { public class Problem11 : AdventOfCodeBase { private Dictionary<int, Dictionary<int, Point>> _grid; private int _maxX; private int _maxY; public override string ProblemName { get { return "Advent of Code 2021: 11"; } } public override string GetAnswer() { GetGrid(Input()); return Answer2().ToString(); } private int Answer1(int maxCount) { for (int count = 1; count <= maxCount; count++) { for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { _grid[x][y].Value++; } } for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { AttemptFlash(x, y, count); } } for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { if (_grid[x][y].Value > 9) { _grid[x][y].Value = 0; _grid[x][y].FlashCount++; } } } } return GetFlashCount(); } private int Answer2() { int cycle = 1; int all = (_maxX + 1) * (_maxY + 1); do { for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { _grid[x][y].Value++; } } for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { AttemptFlash(x, y, cycle); } } int total = 0; for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { if (_grid[x][y].Value > 9) { _grid[x][y].Value = 0; total++; } } } if (total == all) { return cycle; } cycle++; } while (true); } private int GetFlashCount() { int count = 0; for (int x = 0; x <= _maxX; x++) { count += _grid[x].Select(p => p.Value.FlashCount).Sum(); } return count; } private void AttemptFlash(int x, int y, int currentCycle) { var point = _grid[x][y]; if (point.Value > 9 && point.FlashCycle < currentCycle) { point.FlashCycle = currentCycle; if (x > 0) { _grid[x - 1][y].Value++; AttemptFlash(x - 1, y, currentCycle); if (y > 0) { _grid[x - 1][y - 1].Value++; AttemptFlash(x - 1, y - 1, currentCycle); } if (y < _maxY) { _grid[x - 1][y + 1].Value++; AttemptFlash(x - 1, y + 1, currentCycle); } } if (x < _maxX) { _grid[x + 1][y].Value++; AttemptFlash(x + 1, y, currentCycle); if (y > 0) { _grid[x + 1][y - 1].Value++; AttemptFlash(x + 1, y - 1, currentCycle); } if (y < _maxY) { _grid[x + 1][y + 1].Value++; AttemptFlash(x + 1, y + 1, currentCycle); } } if (y > 0) { _grid[x][y - 1].Value++; AttemptFlash(x, y - 1, currentCycle); } if (y < _maxY) { _grid[x][y + 1].Value++; AttemptFlash(x, y + 1, currentCycle); } } } private void GetGrid(List<string> input) { _grid = new Dictionary<int, Dictionary<int, Point>>(); for (int y = 0; y < input.Count; y++) { for (int x = 0; x < input[y].Length; x++) { var point = new Point() { X = x, Y = y, Value = Convert.ToInt32(new string(new char[1] { input[x][y] })) }; if (!_grid.ContainsKey(x)) { _grid.Add(x, new Dictionary<int, Point>()); } _grid[x].Add(y, point); } } _maxX = _grid.Keys.Max(); _maxY = _grid[0].Keys.Max(); } private string Output() { var text = new StringBuilder(); for (int x = 0; x <= _maxX; x++) { for (int y = 0; y <= _maxY; y++) { var point = _grid[x][y]; if (point.Value <= 9) { text.Append(point.Value); } else { text.Append("*"); } } text.AppendLine(); } return text.ToString(); } private class Point { public int X { get; set; } public int Y { get; set; } public int Value { get; set; } public int FlashCycle { get; set; } public int FlashCount { get; set; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace BusVenta { public static class Prompt { public static string ShowDialog() { Form prompt = new Form() { Width = 400, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = "CONFIGURACIÓN", StartPosition = FormStartPosition.CenterScreen }; Label textLabel = new Label() { Left = 50, Top = 22, Text = "KG POR CAJA:" }; textLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 12); textLabel.Size = new System.Drawing.Size(120, 18); textLabel.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; TextBox textBox = new TextBox() { Left = 170, Top = 20, Width = 100 }; textBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 12); textBox.Size = new System.Drawing.Size(120, 18); Label textLabel2 = new Label() { Left = 50, Top = 62, Text = "$ POR CAJA:" }; textLabel2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12); textLabel2.Size = new System.Drawing.Size(130, 18); textLabel2.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; TextBox textBox2 = new TextBox() { Left = 170, Top = 60, Width = 100 }; textBox2.Font = new System.Drawing.Font("Microsoft Sans Serif", 12); textBox2.Size = new System.Drawing.Size(120, 18); Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.OK }; confirmation.Click += (sender, e) => { prompt.Close(); }; prompt.Controls.Add(textBox); prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.Controls.Add(textBox2); prompt.Controls.Add(textLabel2); prompt.AcceptButton = confirmation; return prompt.ShowDialog() == DialogResult.OK ? textBox.Text + ":" +textBox2.Text : "" ; } } }
using System.Windows; using System.Windows.Controls; namespace CODE.Framework.Wpf.Controls { /// <summary> /// Extensions for list box items /// </summary> public class ListBoxItemEx : ListBoxItem { /// <summary>Indicates whether the list box item should automatically be considered selected when the focus moves to any of the controls within the item</summary> public static readonly DependencyProperty SelectItemWhenFocusWithinProperty = DependencyProperty.RegisterAttached("SelectItemWhenFocusWithin", typeof(bool), typeof(ListBoxItemEx), new UIPropertyMetadata(false, SelectItemwhenFocusWithinChanged)); /// <summary> /// Selects the itemwhen focus within changed. /// </summary> /// <param name="o">The o.</param> /// <param name="args">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param> private static void SelectItemwhenFocusWithinChanged(DependencyObject o, DependencyPropertyChangedEventArgs args) { var item = o as ListBoxItem; if (item == null) return; // This is a bit heavy handed, but it seems different scenarios fire different events, so I (Markus) added all these to account for various scenarios item.PreviewMouseDown += (s, e) => { if (!GetSelectItemWhenFocusWithin(item)) return; if (!item.IsSelected) item.IsSelected = true; }; item.MouseDown += (s, e) => { if (!GetSelectItemWhenFocusWithin(item)) return; if (!item.IsSelected) item.IsSelected = true; }; item.PreviewGotKeyboardFocus += (s, e) => { if (!GetSelectItemWhenFocusWithin(item)) return; if (!item.IsSelected) item.IsSelected = true; }; item.GotKeyboardFocus += (s, e) => { if (!GetSelectItemWhenFocusWithin(item)) return; if (!item.IsSelected) item.IsSelected = true; }; item.GotFocus += (s, e) => { if (!GetSelectItemWhenFocusWithin(item)) return; if (!item.IsSelected) item.IsSelected = true; }; item.IsKeyboardFocusWithinChanged += (s, e) => { if (!GetSelectItemWhenFocusWithin(item)) return; if (item.IsKeyboardFocusWithin && !item.IsSelected) item.IsSelected = true; }; } /// <summary>Indicates whether the list box item should automatically be considered selected when the focus moves to any of the controls within the item</summary> /// <param name="o">The object to set the value on.</param> /// <returns></returns> public static bool GetSelectItemWhenFocusWithin(DependencyObject o) { return (bool)o.GetValue(SelectItemWhenFocusWithinProperty); } /// <summary> /// Indicates whether the list box item should automatically be considered selected when the focus moves to any of the controls within the item /// </summary> /// <param name="o">The object to set the value on.</param> /// <param name="value">if set to <c>true</c> [value].</param> public static void SetSelectItemWhenFocusWithin(DependencyObject o, bool value) { o.SetValue(SelectItemWhenFocusWithinProperty, value); } } }
using Newtonsoft.Json; using System; namespace Model.IntelligenceDiningTable { /// <summary> /// 菜品表 /// </summary> [Serializable] public partial class E_Dish { /// <summary> /// 菜品 ID /// </summary> public string id { get; set; } /// <summary> /// 菜品名称 /// </summary> public string name { get; set; } /// <summary> /// 菜品标签 /// </summary> public string tag { get { var result = ""; if (!string.IsNullOrEmpty(taste)) { result += taste; } if (!string.IsNullOrEmpty(texture)) { result += "|" + texture; } return result; } } /// <summary> /// 味型 /// </summary> [JsonIgnore] public string taste { get; set; } /// <summary> /// 脆度 /// </summary> [JsonIgnore] public string texture { get; set; } public string remark { get; set; } /// <summary> /// 菜品描述 /// </summary> [JsonIgnore] public string Characteristic { get; set; } /// <summary> /// 建议取用量(单位 g) /// </summary> public int suggest_takeqty { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Mirror; using UnityEngine.UI; public class PlayerControler : NetworkBehaviour { public static Dictionary<string,string> hotelDecorationMapping = new Dictionary<string,string>{ {"SonoBom","quadro colorido na parede."}, {"DormeBem","quadro com o homem de chapéu na parede."}, {"RoncoAlto","quadro com o casal de guarda-chuva na parede."} }; public static Dictionary<string,string> itemDicaMapping = new Dictionary<string,string>{ {"Cachorro Quente","Você pode encontrar em barraquinhas espalhadas pela cidade."}, {"Bolo","Eu ouvi dizer que a padaria atrás do shopping vende os melhores bolos."}, {"Flores","Há uma barraquinha de flores no shopping."}, {"Frutas","Um supermercado no shopping vende deliciosas frutas orgânicas!"}, {"Batata Frita","Na lojinha de um posto de gasolina há muitas delas."}, {"Sorvete","No posto de gasolina há um freezer cheio, mas cuidado! Eles derretem rápidamente!"}, {"Croissant","O padeiro que trabalha no shopping é Francês."}, {"Pão a Metro","Aquela padaria do shopping vende de tudo"}, {"Refrigerante","Vai no posto BR! Mas cuidado! Refrigerante quente não desce!!"}, {"Pipoca","A lanchonete de fast food no shopping agora tambem vende pipoca!"} }; [Header("Barra de Energia")] public Slider energyBar = null; public float energyBarConsumeRate = 0.0f; private Animator animatorController; [Header("Camera")] public GameObject playerCamera; private Camera cam; private GameObject clickedObject; [Header("Interaction Variables")] public float interactDistance; private GameObject playercharacterchoice; public static string[,] characterModelMapping= new string [9,2] {{"1","Character_Father_01"},{"2","Character_SchoolBoy_01"},{"3","Character_Mother_02"},{"4","Character_Father_02"},{"5","Character_Daughter_01"},{"6","Character_Mother_01"},{"7","Character_SchoolGirl_01"},{"8","Character_ShopKeeper_01"},{"9","Character_Son_01"}}; public int playerIdNumber = 0; public float timeLastInteraction=0.0f; public float minimumTimeBetweenInteractions = 20.0f; [Header("Wallet")] public Text walletMoneyDisplay; public int walletMoneyValue = 2000; public string[] localPlayerMissionItems = new string[3]; public string localPlayerHotel; public bool localPlayerCalcularCompra; public int localPlayerWorkingMemoryDigits; private string wellcomeString ="Bem Vindo a Lugares Divertidos!!!\n"+ "A festa de 80 anos do seu amigo vai ser um arraso! \n"+ "Mas para isso você precisa encontrar alguns itens e "+ "trazê-los para a festa e trazê-los de volta ao seu hotel. \n"+ "Aqui está sua Lista:\n\n"+ "- 1 {0}\n"+ "- 1 {1}\n"+ "- 1 {2}\n\n"+ "Boa Sorte! Ah! E lembre-se seu hotel é o Hotel {3}, aquele com o {4}!"; [Header("Movement")] public float rotationSpeed = 100; // Start is called before the first frame update void Start() { if (isLocalPlayer) gameObject.transform.Find("HUD").gameObject.SetActive(true); animatorController = GetComponent<Animator>(); if (isLocalPlayer){ playerCamera.SetActive(true); cam = playerCamera.GetComponent<Camera>(); playerIdNumber = getCharacterId(); CmdRegisterPlayerNumberOnServer(playerIdNumber); switch (playerIdNumber){ case 1: CmdChangePlayerCharacterModel(GameObject.FindGameObjectWithTag("PlayerOptionsContainer").GetComponent<PlayerChoiceTracking>().p1CharId); break; case 2: CmdChangePlayerCharacterModel(GameObject.FindGameObjectWithTag("PlayerOptionsContainer").GetComponent<PlayerChoiceTracking>().p2CharId); break; case 3: CmdChangePlayerCharacterModel(GameObject.FindGameObjectWithTag("PlayerOptionsContainer").GetComponent<PlayerChoiceTracking>().p3CharId); break; } } if (!isServer){ DisableServerControls(); } if (isLocalPlayer){ RegisterMissionLocalPlayerMissionItemsGameOptions(playerIdNumber); showWellcomePopUp(); energyBarConsumeRate = 0.0001f; } } // Update is called once per frame void Update() { // movement for local player if (!isLocalPlayer) return; float x= Input.GetAxis("Horizontal")* Time.deltaTime *150.0f; float z = Input.GetAxis("Vertical")*Time.deltaTime *3.0f; transform.Rotate(0,x,0); transform.Translate(0,0,z); if (z==0){ animatorController.SetBool("isWalking",false); animatorController.SetBool("isWalkingBackwards",false); } if (z>0){ animatorController.SetBool("isWalking",true); animatorController.SetBool("isWalkingBackwards",false); }else if (z<0){ animatorController.SetBool("isWalking",false); animatorController.SetBool("isWalkingBackwards",true); } if (z!=0){ ConsumeEnergyWalking(); } //get lef mouse button click if (Input.GetMouseButtonDown(0)){ Debug.Log("name"); Ray ray = cam.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray,out hit)){ clickedObject = hit.collider.gameObject; if (clickedObject.tag == "Pickupable"){ gameObject.transform.Find("HUD/CreditCardMachine").gameObject.SetActive(true); if (Vector3.Distance(transform.position,clickedObject.transform.position) <= interactDistance){ Destroy(clickedObject); }else{ Debug.Log("O objeto está muito longe!"); } }else if(clickedObject.tag =="RefreshmentPoint") { UseRefreshmentPoint(clickedObject.tag); }else if (clickedObject.tag =="Player"){ if (Vector3.Distance(transform.position,clickedObject.transform.position) <= interactDistance){ if ((timeLastInteraction ==0.0f) || ((Time.time-timeLastInteraction)>minimumTimeBetweenInteractions)){ timeLastInteraction = Time.time; RefreshThroughInteraction(); } }else{ } } } } } [Command] public void CmdChangePlayerCharacterModel(int charNumber){ foreach(Transform child in gameObject.transform){ if (child.CompareTag("PlayerCharacterModel")){ child.gameObject.SetActive(false); if (child.gameObject.name == characterModelMapping[charNumber,1]){ child.gameObject.SetActive(true); } } } RpcNotifyClientsPlayerCharacterModelChange(charNumber); } [ClientRpc] public void RpcNotifyClientsPlayerCharacterModelChange(int charNumber){ foreach(Transform child in gameObject.transform){ if (child.CompareTag("PlayerCharacterModel")){ child.gameObject.SetActive(false); if (child.gameObject.name == characterModelMapping[charNumber,1]){ child.gameObject.SetActive(true); } } } } public int getCharacterId(){ PlayerChoiceTracking playerChoices = GameObject.FindGameObjectWithTag("PlayerOptionsContainer").GetComponent<PlayerChoiceTracking>(); return playerChoices.localPlayerPlayerNumber; } public void DisableServerControls(){ GameObject sm = GameObject.Find("ServerManager"); if (sm){ sm.SetActive(false); } } public void RegisterMissionLocalPlayerMissionItemsGameOptions(int playerId){ PlayerChoiceTracking playerChoices = GameObject.FindGameObjectWithTag("PlayerOptionsContainer").GetComponent<PlayerChoiceTracking>(); switch (playerId){ case 1: localPlayerMissionItems[0]= playerChoices.p1Item1; localPlayerMissionItems[1]= playerChoices.p1Item2; localPlayerMissionItems[2]= playerChoices.p1Item3; localPlayerHotel = playerChoices.p1Hotel; localPlayerCalcularCompra = playerChoices.p1CalcularCompra; localPlayerWorkingMemoryDigits = playerChoices.p1WorkingMemoryDigits; break; case 2: localPlayerMissionItems[0]= playerChoices.p2Item1; localPlayerMissionItems[1]= playerChoices.p2Item2; localPlayerMissionItems[2]= playerChoices.p2Item3; localPlayerHotel = playerChoices.p2Hotel; localPlayerCalcularCompra = playerChoices.p2CalcularCompra; localPlayerWorkingMemoryDigits = playerChoices.p2WorkingMemoryDigits; break; case 3: localPlayerMissionItems[0]= playerChoices.p3Item1; localPlayerMissionItems[1]= playerChoices.p3Item2; localPlayerMissionItems[2]= playerChoices.p3Item3; localPlayerHotel = playerChoices.p3Hotel; localPlayerCalcularCompra = playerChoices.p3CalcularCompra; localPlayerWorkingMemoryDigits = playerChoices.p3WorkingMemoryDigits; break; } } public void showWellcomePopUp(){ gameObject.transform.Find("HUD/WellcomeMessagePopUp").gameObject.SetActive(true); gameObject.transform.Find("HUD/WellcomeMessagePopUp/Panel_PopUpWindow/Panel_Content/WellcomeMessage").gameObject.GetComponent<Text>().text= string.Format(wellcomeString,localPlayerMissionItems[0],localPlayerMissionItems[1],localPlayerMissionItems[2],localPlayerHotel,getHotelDecorationTip(localPlayerHotel)); } public string getHotelDecorationTip(string hotelName){ return hotelDecorationMapping[hotelName]; } public void showItemListPanelPopUp(){ if (isLocalPlayer){ gameObject.transform.Find("HUD/ItemListPopUp").gameObject.SetActive(true); Toggle item1 = gameObject.transform.Find("HUD/ItemListPopUp/Panel_PopUpWindow/Item1FoundToggle").gameObject.GetComponent<Toggle>(); Toggle item2 = gameObject.transform.Find("HUD/ItemListPopUp/Panel_PopUpWindow/Item2FoundToggle").gameObject.GetComponent<Toggle>(); Toggle item3 = gameObject.transform.Find("HUD/ItemListPopUp/Panel_PopUpWindow/Item3FoundToggle").gameObject.GetComponent<Toggle>(); item1.transform.Find("Label").GetComponent<Text>().text = localPlayerMissionItems[0]; item2.transform.Find("Label").GetComponent<Text>().text = localPlayerMissionItems[1]; item3.transform.Find("Label").GetComponent<Text>().text = localPlayerMissionItems[2]; } } public void ShowItemTipPanelPopUp(int itemNumber){ if (isLocalPlayer){ gameObject.transform.Find("HUD/ItemTipPopUp").gameObject.SetActive(true); gameObject.transform.Find("HUD/ItemTipPopUp/Panel_PopUpWindow/Panel_Content/Text_Description").gameObject.GetComponent<Text>().text = itemDicaMapping[localPlayerMissionItems[itemNumber]]; } } public void ConsumeEnergyWalking(){ energyBar.value -=energyBarConsumeRate; } public void UseRefreshmentPoint(string clickedObjectTag){ if (clickedObjectTag == "RefreshmentPoint"){ CmdUpdateQuantidadeDeVezesQueTentouSeHidratar(); if (ReduceWalletMoney(100)){ CmdUpdateQuantidadeDeVezesQueSeHidratou(); if (energyBar.value >= 0.7f){ energyBar.value = 1.0f; }else{ energyBar.value += 0.3f; } } } } public void RefreshThroughInteraction(){ CmdUpdateQuantidadeDeVezesQueInteragiu(); if (energyBar.value >= 0.5f){ energyBar.value = 1.0f; }else{ energyBar.value += 0.5f; } } public bool ReduceWalletMoney(int itemOrActionPrice){ if (walletMoneyValue -itemOrActionPrice>0){ walletMoneyValue -= itemOrActionPrice; walletMoneyDisplay.text = walletMoneyValue.ToString(); Debug.Log("walletMoneyValue.ToString()"); return true; } return false; } [Command] public void CmdRegisterPlayerNumberOnServer(int IdNumber){ playerIdNumber = IdNumber; } [Command] public void CmdUpdateQuantidadeDeVezesQueTentouSeHidratar(){ gameObject.GetComponent<GameAnalytics>().M7_QuantidadeDeVezesQueTentouSeHidratar++; } [Command] public void CmdUpdateQuantidadeDeVezesQueSeHidratou(){ gameObject.GetComponent<GameAnalytics>().M8_QuantidadeDeVezesQueSeHidratou++; } [Command] public void CmdUpdateQuantidadeDeVezesQueInteragiu(){ gameObject.GetComponent<GameAnalytics>().M25_QuantidadeDeVezesQueInteragiu++; } } /* public void showTipPanelPopUp(){ foreach(GameObject gamePlayer in GameObject.FindGameObjectsWithTag("Player")){ if (gamePlayer.GetComponent<PlayerControler>().isLocalPlayer){ gamePlayer.transform.Find("HUD/ItemListPopUp").gameObject.SetActive(true); Toggle item1 = gamePlayer.transform.Find("HUD/ItemListPopUp/Panel_PopUpWindow/Item1FoundToggle").gameObject.GetComponent<Toggle>(); Toggle item2 = gamePlayer.transform.Find("HUD/ItemListPopUp/Panel_PopUpWindow/Item2FoundToggle").gameObject.GetComponent<Toggle>(); Toggle item3 = gamePlayer.transform.Find("HUD/ItemListPopUp/Panel_PopUpWindow/Item3FoundToggle").gameObject.GetComponent<Toggle>(); item1.GetComponent<Text>().text = gamePlayer.GetComponent<PlayerControler>().localPlayerMissionItems[0]; item2.GetComponent<Text>().text = gamePlayer.GetComponent<PlayerControler>().localPlayerMissionItems[1]; item3.GetComponent<Text>().text = gamePlayer.GetComponent<PlayerControler>().localPlayerMissionItems[2]; } } }*/
using Core2InMemoryUnitTesting.Domain; using Core2InMemoryUnitTesting.Repository; using Microsoft.EntityFrameworkCore; namespace Core2InMemoryUnitTesting { public class StoreAppContext : DbContext, IStoreAppContext { public StoreAppContext(DbContextOptions<StoreAppContext> options) : base(options) { } public DbSet<Product> Products { get; set; } public DbSet<Store> Stores { get; set; } public new void SaveChanges() { base.SaveChanges(); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.AddProduct("dbo"); modelBuilder.AddStore("dbo"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Автошкола { public class InstructorsCategoriesDA { private SqlDataAdapter dataAdapter; // сохранить изменения строки public void Save(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr) { dataAdapter = new SqlDataAdapter(); // на обновление dataAdapter.UpdateCommand = new SqlCommand("UPDATE InstructorsCategories SET ID = @ID, Instructor = @Instructor, Category = @Category " + "WHERE ID = @OldID", conn.getConnection(), tr.getTransaction()); dataAdapter.UpdateCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID"); dataAdapter.UpdateCommand.Parameters.Add("@Instructor", System.Data.SqlDbType.Int, 255, "Instructor"); dataAdapter.UpdateCommand.Parameters.Add("@Category", System.Data.SqlDbType.Int, 255, "Category"); dataAdapter.UpdateCommand.Parameters.Add("@OldID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original; // на вставку dataAdapter.InsertCommand = new SqlCommand("INSERT INTO InstructorsCategories (ID, Instructor, Category) VALUES (@ID, @Instructor, @Category)", conn.getConnection(), tr.getTransaction()); dataAdapter.InsertCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID"); dataAdapter.InsertCommand.Parameters.Add("@Instructor", System.Data.SqlDbType.Int, 255, "Instructor"); dataAdapter.InsertCommand.Parameters.Add("@Category", System.Data.SqlDbType.Int, 255, "Category"); // на удаление dataAdapter.DeleteCommand = new SqlCommand("DELETE InstructorsCategories WHERE ID = @ID", conn.getConnection(), tr.getTransaction()); dataAdapter.DeleteCommand.Parameters.Add("@ID", System.Data.SqlDbType.Int, 255, "ID").SourceVersion = System.Data.DataRowVersion.Original; dataAdapter.Update(dataSet, "InstructorsCategories"); } // прочитать таблицу public void Read(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr) { dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM InstructorsCategories", conn.getConnection(), tr.getTransaction()); dataAdapter.Fill(dataSet, "InstructorsCategories"); } public void ReadByInstructorID(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int ID) { dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM InstructorsCategories WHERE Instructor = @ID", conn.getConnection(), tr.getTransaction()); dataAdapter.SelectCommand.Parameters.AddWithValue("@ID", ID); dataAdapter.Fill(dataSet, "InstructorsCategories"); } public void ReadByCategoryID(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int ID) { dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM InstructorsCategories WHERE Category = @ID", conn.getConnection(), tr.getTransaction()); dataAdapter.SelectCommand.Parameters.AddWithValue("@ID", ID); dataAdapter.Fill(dataSet, "InstructorsCategories"); } public void ReadByInstructorIdANDCategoryId(AutoschoolDataSet dataSet, AbstractConnection conn, AbstractTransaction tr, int InstructorID, int CategoryID) { dataAdapter = new SqlDataAdapter(); dataAdapter.SelectCommand = new SqlCommand("SELECT * FROM InstructorsCategories WHERE Instructor = @InstructorID AND Category = @CategoryID", conn.getConnection(), tr.getTransaction()); dataAdapter.SelectCommand.Parameters.AddWithValue("@InstructorID", InstructorID); dataAdapter.SelectCommand.Parameters.AddWithValue("@CategoryID", CategoryID); dataAdapter.Fill(dataSet, "InstructorsCategories"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Agencia_Datos_Repositorio; using entidades = Agencia_Datos_Entidades; namespace Agencia_Dominio { public class D_MenuEmpleado { private readonly Repositorio<entidades.MenuEmpleado> menuempleado; public D_MenuEmpleado (Repositorio<entidades.MenuEmpleado> menuempleado) { this.menuempleado = menuempleado; } public void AgregarNuevo(entidades.MenuEmpleado modelo) { menuempleado.Agregar(modelo); menuempleado.Guardar(); menuempleado.Commit(); } public void Modificar(entidades.MenuEmpleado modelo) { menuempleado.Modificar(modelo); menuempleado.Guardar(); menuempleado.Commit(); } public void Eliminar(entidades.MenuEmpleado modelo) { menuempleado.Eliminar(modelo); menuempleado.Guardar(); menuempleado.Commit(); } public object TraerTodo() { return menuempleado.TraerTodo(); } public object TraerUnoPorId(int id) { return menuempleado.TraerUnoPorId(id); } public void Rollback() { menuempleado.RollBack(); } } }
using jaytwo.Common.Collections; using jaytwo.Common.Parse; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using jaytwo.Common.Extensions; using jaytwo.Common.Appendix; namespace jaytwo.Common.Futures { public class PolyNavigator { public static PolyNavigator FromObject(object value) { if (value != null) { return new PolyNavigator(value); } else { return null; } } public static PolyNavigator FromObject(object value, StringComparer stringComparer) { if (value != null) { return new PolyNavigator(value, stringComparer); } else { return null; } } public static PolyNavigator FromJson(string json) { if (!string.IsNullOrEmpty(json)) { var dictionary = ParseUtility.ParseJsonAsDictionary(json); return FromObject(dictionary); } else { return null; } } public static PolyNavigator FromJson(string json, StringComparer stringComparer) { if (!string.IsNullOrEmpty(json)) { var dictionary = ParseUtility.ParseJsonAsDictionary(json); return FromObject(dictionary, stringComparer); } else { return null; } } private StringComparer stringComparer; private object innerValue; private IList innerList; private IDictionary innerDictionary; public StringComparer StringComparer { get { return stringComparer; } } public PolyType Value { get { return PolyType.NewOrNull(innerValue); } } public string AsString() { return new PolyType(innerValue).AsString(); } public IDictionary AsDictionary() { return new PolyType(innerValue).AsDictionary(); } public IDictionary<TKey, TValue> AsDictionary<TKey, TValue>() { return new PolyType(innerValue).AsDictionary<TKey, TValue>(); } public IList AsList() { return new PolyType(innerValue).AsList(); } public IList<T> AsList<T>() { return new PolyType(innerValue).AsList<T>(); } public bool AsBoolean() { return new PolyType(innerValue).AsBoolean(); } public bool? AsBooleanNullable() { return new PolyType(innerValue).AsBooleanNullable(); } public byte AsByte() { return new PolyType(innerValue).AsByte(); } public byte? AsByteNullable() { return new PolyType(innerValue).AsByteNullable(); } public char AsChar() { return new PolyType(innerValue).AsChar(); } public char? AsCharNullable() { return new PolyType(innerValue).AsCharNullable(); } public DateTime AsDateTime() { return new PolyType(innerValue).AsDateTime(); } public DateTime? AsDateTimeNullable() { return new PolyType(innerValue).AsDateTimeNullable(); } public decimal AsDecimal() { return new PolyType(innerValue).AsDecimal(); } public decimal? AsDecimalNullable() { return new PolyType(innerValue).AsDecimalNullable(); } public double AsDouble() { return new PolyType(innerValue).AsDouble(); } public double? AsDoubleNullable() { return new PolyType(innerValue).AsDoubleNullable(); } public short AsInt16() { return new PolyType(innerValue).AsInt16(); } public short? AsInt16Nullable() { return new PolyType(innerValue).AsInt16Nullable(); } public int AsInt32() { return new PolyType(innerValue).AsInt32(); } public int? AsInt32Nullable() { return new PolyType(innerValue).AsInt32Nullable(); } public long AsInt64() { return new PolyType(innerValue).AsInt64(); } public long? AsInt64Nullable() { return new PolyType(innerValue).AsInt64Nullable(); } public sbyte AsSByte() { return new PolyType(innerValue).AsSByte(); } public sbyte? AsSByteNullable() { return new PolyType(innerValue).AsSByteNullable(); } public float AsSingle() { return new PolyType(innerValue).AsSingle(); } public float? AsSingleNullable() { return new PolyType(innerValue).AsSingleNullable(); } public ushort AsUInt16() { return new PolyType(innerValue).AsUInt16(); } public ushort? AsUInt16Nullable() { return new PolyType(innerValue).AsUInt16Nullable(); } public uint AsUInt32() { return new PolyType(innerValue).AsUInt32(); } public uint? AsUInt32Nullable() { return new PolyType(innerValue).AsUInt32Nullable(); } public ulong AsUInt64() { return new PolyType(innerValue).AsUInt64(); } public ulong? AsUInt64Nullable() { return new PolyType(innerValue).AsUInt64Nullable(); } public object InnerValue { get { return innerValue; } } private PolyNavigator(object value, StringComparer stringComparer) : this(value) { this.stringComparer = stringComparer; } private PolyNavigator(object value) { this.innerValue = value; this.innerList = value as IList; this.innerDictionary = value as IDictionary; } public T InnerValueAs<T>() { return (T)innerValue; } public string ToJson() { return InternalScabHelpers.SerializeToJson(innerValue); } public PolyNavigator this[string key] { get { object result; if (PolyNavigatorHelpers.TryGetDictionaryValue(innerDictionary, key, StringComparer, out result)) { // do nothing } else if (PolyNavigatorHelpers.TryGetListValue(innerList, key, out result)) { // do nothing } else if (PolyNavigatorHelpers.TryGetReflectionValue(innerValue, key, StringComparer, out result)) { // do nothing } return new PolyNavigator(result, StringComparer); } } public PolyNavigator this[int index] { get { object result = null; if (innerList != null && innerList.Count > index) { result = innerList[index]; } return new PolyNavigator(result, StringComparer); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public enum MoveState { Idle, Walk, Steer } public enum Filter { Interactable, Grab, Activate } public class PlayerController : MonoBehaviour { static public PlayerController instance; [Header("Components")] public Transform self; public Rigidbody body; public Transform holdPoint; public Animator anim; public AudioSource myAudioSource; [Space] [Header("Referencies")] public GameObject actionUI; public GameObject grabbedActionUI; Text actionText; Text grabbedActionText; public GameObject steerParticlesPrefab; public GameObject grabParticlesPrefab; public GameObject dropParticlesPrefab; public AudioClip steerClip; public AudioClip grabClip; public AudioClip dropClip; [Space] [Header("Inputs")] public KeyCode actionKey; public KeyCode grabKey; public float deadzone = 0.2f; [Space] [Header("Controls")] public MoveState moveState; [SerializeField] private float speed; [Tooltip("Minimum required speed to go to walking state")] public float minWalkSpeed = 0.1f; public float maxSpeed = 10; public float maxAcceleration = 10; public AnimationCurve accelerationCurve; [Space] public float movingDrag = .4f; public float idleDrag = .4f; public float steerDrag; [Space] [Range(0.01f, 1f)] public float turnSpeed = .25f; [Tooltip("Minimum required speed to go to steering state")] [Range(0.01f, 1f)] public float steerThresholdSpeed; public AnimationCurve walkAnimationSpeedCurve; [Space] [Header("Grab")] [Tooltip("Distance forward to check for objects")] public float checkCircleDistance; [Tooltip("Circle radius to check for objects")] public float checkCircleRadius; public float grabAngleTolerance; [Space] [Header("UI")] public Vector3 uiOffset; Vector3 speedVector; float accelerationTimer; Vector3 lastVelocity; Vector3 input; Quaternion turnRotation; float distance; Quaternion steerTarget; [System.NonSerialized] public Interactable grabbedObject; Interactable canInteract; private float steerTimer; public float steerTimerLimit = .2f; private void Awake() { if (instance == null) { instance = this; } else { Destroy(gameObject); } actionText = actionUI.GetComponentInChildren<Text>(); actionUI.SetActive(false); grabbedActionText = actionUI.GetComponentInChildren<Text>(); grabbedActionUI.SetActive(false); } private void Start() { self.position = SpawnPoint.instance.transform.position; } // Update is called once per frame void Update() { CheckForActions(); GetInput(); GrabbedInteractUI(); anim.SetFloat("MoveSpeed", walkAnimationSpeedCurve.Evaluate(speed)); } void GrabbedInteractUI() { if (grabbedObject != null && grabbedObject.parameters.activationType == ActivationType.Handheld) { grabbedActionUI.SetActive(true); grabbedActionText.text = "(" + actionKey + ") Use: " + grabbedObject.parameters.objectName; } else { grabbedActionUI.SetActive(false); } } private void FixedUpdate() { CheckMoveState(); if (moveState != MoveState.Steer) { if (input.magnitude != 0) { accelerationTimer += Time.fixedDeltaTime; Rotate(); Accelerate(); } else { accelerationTimer = 0; } Move(); } else { Steer(); } if (steerTimer > steerTimerLimit || steerTimer == 0) lastVelocity = body.velocity.normalized; } #region Input void GetInput() { if (HasGamepad()) { GamepadInput(); } else { KeyboardInput(); } } void GamepadInput() { input = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")); input = input.normalized * ((input.magnitude - deadzone) / (1 - deadzone)); // if (Input.GetKeyDown(grabKey)) if (Input.GetButtonDown("Grab")) { print("Grab"); Grab(); } //if (Input.GetKeyDown(actionKey)) if (Input.GetButtonDown("Action")) { print("Activate"); ActivateObject(); } } void KeyboardInput() { // if (Input.GetKeyDown(grabKey)) if (Input.GetButtonDown("Grab")) { print("Grab"); Grab(); } //if (Input.GetKeyDown(actionKey)) if (Input.GetButtonDown("Action")) { print("Activate"); ActivateObject(); } int _horDir = 0; if (Input.GetKey(KeyCode.LeftArrow)) { _horDir--; } if (Input.GetKey(KeyCode.RightArrow)) { _horDir++; } int _vertDir = 0; if (Input.GetKey(KeyCode.DownArrow)) { _vertDir--; } if (Input.GetKey(KeyCode.UpArrow)) { _vertDir++; } if ((Input.GetKey(KeyCode.DownArrow) && Input.GetKey(KeyCode.UpArrow)) || (Input.GetKey(KeyCode.LeftArrow) && Input.GetKey(KeyCode.RightArrow))) { if (steerTimer == 0) { lastVelocity = body.velocity; } steerTimer += Time.deltaTime; } else { steerTimer = 0; } input = new Vector3(_horDir, 0, _vertDir); input.Normalize(); } bool HasGamepad() { if (Input.GetJoystickNames().Length > 0) { return true; } else { return false; } } #endregion #region Movement void CheckMoveState() { if (Vector3.Dot(input, lastVelocity) < -0.8f && moveState != MoveState.Steer && speed >= steerThresholdSpeed * maxSpeed) { steerTarget = Quaternion.Euler(0, Mathf.Atan2(input.x, input.z) * 180 / Mathf.PI, 0); print("Start steeering"); body.drag = steerDrag; moveState = MoveState.Steer; anim.SetInteger("EnumState", 2); Vector3 positionSpawnParticleSteer = self.position + self.forward + (self.up*-0.6f); Vector3 eulerRotationSpawnParticleSteer = self.rotation.eulerAngles + new Vector3(-90, -90, -45); GameObject _steerParticle = Instantiate(steerParticlesPrefab, positionSpawnParticleSteer, Quaternion.Euler(eulerRotationSpawnParticleSteer)); Destroy(_steerParticle, 1.5f); myAudioSource.PlayOneShot(steerClip); } else if (body.velocity.magnitude <= minWalkSpeed) { if (moveState != MoveState.Idle) { body.velocity = Vector3.zero; } body.drag = idleDrag; moveState = MoveState.Idle; anim.SetInteger("EnumState", 0); } else if (moveState != MoveState.Steer) { if (input == Vector3.zero && (steerTimer > steerTimerLimit || steerTimer == 0)) { body.drag = idleDrag; } else { body.drag = movingDrag; } moveState = MoveState.Walk; anim.SetInteger("EnumState", 1); } } void Rotate() { turnRotation = Quaternion.Euler(0, Mathf.Atan2(input.x, input.z) * 180 / Mathf.PI, 0); transform.rotation = Quaternion.Slerp(transform.rotation, turnRotation, turnSpeed); } void Steer() { transform.rotation = Quaternion.Slerp(transform.rotation, steerTarget, turnSpeed); print("Steering"); } void Accelerate() { body.AddForce(input * (accelerationCurve.Evaluate(body.velocity.magnitude/maxSpeed) * maxAcceleration), ForceMode.Acceleration); body.drag = movingDrag; } void Move() { body.velocity = Vector3.ClampMagnitude(body.velocity, maxSpeed); speed = body.velocity.magnitude; } #endregion #region Actions void CheckForActions() { Collider[] objectsNear = Physics.OverlapSphere(self.position + self.forward * checkCircleDistance, 5); canInteract = null; if (grabbedObject == null) { if (objectsNear.Length > 0) { List<Interactable> InteractablesNear = FilteredObjects(objectsNear, Filter.Interactable); if (InteractablesNear.Count > 0) { canInteract = GetNearestInFront(InteractablesNear); } } } UpdateInteractUI(); } void UpdateInteractUI() { if (canInteract == null) { actionUI.SetActive(false); } else { //print("Object: " + canInteract + " has parameters: " + canInteract.parameters); if (canInteract.parameters.pickUp) { actionUI.SetActive(true); actionText.text = "(" + grabKey + ") GRAB: " + canInteract.parameters.objectName; } else if (canInteract.parameters.activationType == ActivationType.Proximity) { actionUI.SetActive(true); actionText.text = "(" + actionKey + ") ACTIVATE: " + canInteract.parameters.objectName; } else { actionUI.SetActive(false); } actionUI.transform.position = WorldToUIPosition(canInteract.transform.position) + uiOffset; } } Vector3 WorldToUIPosition(Vector3 _position) { Vector3 _UIPos = Camera.main.WorldToScreenPoint(_position); return _UIPos; } void Grab() { //Collider[] objectsGrab = Physics.OverlapSphere(self.position + self.forward * checkCircleDistance, checkCircleRadius); if ( grabbedObject == null) { // if (objectsGrab.Length > 0) // { // List<Interactable> grabbableObjects = FilteredObjects(objectsGrab, Filter.Grab); // if (grabbableObjects.Count > 0) // { // grabbedObject = GetNearestInFront(grabbableObjects); //grabbedObject.GetGrabbed(holdPoint); // GameObject _grabParticlesRef = Instantiate(grabParticlesPrefab, holdPoint.position, Quaternion.identity, holdPoint); // Destroy(_grabParticlesRef, 1); // myAudioSource.PlayOneShot(grabClip); // } // } if (canInteract != null && canInteract.GetComponent<Interactable>().parameters.pickUp) { grabbedObject = canInteract; grabbedObject.GetGrabbed(holdPoint); GameObject _grabParticlesRef = Instantiate(grabParticlesPrefab, holdPoint.position, Quaternion.identity, holdPoint); Destroy(_grabParticlesRef, 1); myAudioSource.PlayOneShot(grabClip); } } else { grabbedObject.GetDropped(); grabbedObject = null; GameObject _dropParticlesRef = Instantiate(dropParticlesPrefab, holdPoint.position, Quaternion.identity); Destroy(_dropParticlesRef, 1); myAudioSource.PlayOneShot(dropClip); } } void ActivateObject() { if (grabbedObject != null && grabbedObject.parameters.activationType == ActivationType.Handheld) { //grabbedObject.Activate(); switch (grabbedObject.parameters.objectName) { case "Bat": anim.SetTrigger("SwingTrigger"); break; default: grabbedObject.Activate(); break; } } else { //Collider[] objectsActivate = Physics.OverlapSphere(self.position + self.forward * checkCircleDistance, checkCircleRadius); //if (objectsActivate.Length > 0) //{ // List<Interactable> activableObjects = FilteredObjects(objectsActivate, Filter.Activate); // if (activableObjects.Count > 0) // { // GetNearestInFront(activableObjects).Activate(); // } //} if (canInteract != null && canInteract.GetComponent<Interactable>().parameters.activationType == ActivationType.Proximity) { canInteract.Activate(); } } } List<Interactable> FilteredObjects(Collider[] _objects, Filter _filter) { List<Interactable> filteredObjects = new List<Interactable>(); switch (_filter) { case Filter.Interactable: for (int i = 0; i < _objects.Length; i++) { if (_objects[i].tag == "Interactable") { filteredObjects.Add(_objects[i].GetComponent<Interactable>()); } } break; case Filter.Grab: for (int i = 0; i < _objects.Length; i++) { if (_objects[i].tag == "Interactable" && _objects[i].GetComponent<Interactable>().parameters.pickUp) { filteredObjects.Add(_objects[i].GetComponent<Interactable>()); } } break; case Filter.Activate: for (int i = 0; i < _objects.Length; i++) { if (_objects[i].tag == "Interactable" && _objects[i].GetComponent<Interactable>().parameters.activationType == ActivationType.Proximity) { filteredObjects.Add(_objects[i].GetComponent<Interactable>()); } } break; } return filteredObjects; } //TO OPTIMIZE Interactable GetNearestInFront(List<Interactable> _objects) { List<Interactable> inFrontObjects = new List<Interactable>(); float minAngle = Mathf.Infinity; for (int i = 0; i < _objects.Count; i++) { Vector3 directionToObject = _objects[i].self.position - self.position; float angle = Vector3.Angle(directionToObject, self.forward); if (Vector3.Angle(directionToObject, self.forward) < minAngle) { minAngle = angle; } } for (int i = 0; i < _objects.Count; i++) { Vector3 directionToObject = _objects[i].self.position - self.position; float angle = Vector3.Angle(directionToObject, self.forward); if (angle < minAngle + grabAngleTolerance) { inFrontObjects.Add(_objects[i]); } } float minDist = Mathf.Infinity; int minIndex = -1; for (int i = 0; i < inFrontObjects.Count; i++) { if (Vector3.Distance(self.position, inFrontObjects[i].self.position) < minDist) { minDist = Vector3.Distance(self.position, inFrontObjects[i].self.position); minIndex = i; } } return inFrontObjects[minIndex]; } #endregion }
using System.Collections; namespace Indexer { public class PersonCollection { private ArrayList people = new ArrayList(); // Custom indexer for PersonCollection class. // This looks like any other C# property declaration // apart from using this keyword. public Person this[int index] { // Return the correct object to the caller, // by delegating the request to the indexer of the ArrayList object (people) get => (Person)people[index]; // Adding new Person objects set => people.Insert(index, value); } public int Count { get => people.Count; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //********************************************************************** // // 文件名称(File Name):LoadNodePerformancelistResponse.CS // 功能描述(Description): // 作者(Author):Aministrator // 日期(Create Date): 2017-05-16 15:30:13 // // 修改记录(Revision History): // R1: // 修改作者: // 修改日期:2017-05-16 15:30:13 // 修改理由: //********************************************************************** namespace ND.FluentTaskScheduling.Model.response { public class LoadNodePerformancelistResponse { public LoadNodePerformancelistResponse() { NodePerfomance = new Dictionary<string, List<tb_nodeperformance>>(); } /// <summary> /// 每个节点对应的性能统计 /// </summary> public Dictionary<string, List<tb_nodeperformance>> NodePerfomance { get; set; } } }
using System.Collections.Generic; using System.Linq; using SelectionCommittee.BLL.DataTransferObject; using SelectionCommittee.BLL.Interfaces; using SelectionCommittee.DAL.Interfaces; namespace SelectionCommittee.BLL.Services { public class SubjectService : ISubjectService { private IUnitOfWork _database; public SubjectService(IUnitOfWork db) { _database = db; } public IEnumerable<SubjectDTO> GetCertificates() { var Subjects = new List<SubjectDTO>(); _database.SubjectRepository.GetCertificates().ToList().ForEach(subject => Subjects.Add(new SubjectDTO() { Id = subject.Id, Name = subject.Name, TypeSubjectId = subject.TypeSubjectId })); return Subjects; } public IEnumerable<SubjectDTO> GetSubjectsEIE() { var Subjects = new List<SubjectDTO>(); _database.SubjectRepository.GetSubjectsEIE().ToList().ForEach(subject => Subjects.Add(new SubjectDTO() { Id = subject.Id, Name = subject.Name, TypeSubjectId = subject.TypeSubjectId })); return Subjects; } public IEnumerable<string> GetSubjectsNamesEIE(IEnumerable<FacultySubjectDTO> facultySubjects) { List<string> subjects = new List<string>(); IEnumerable<SubjectDTO> subjectsEIE = GetSubjectsEIE(); var facultySubjectsDTO = facultySubjects.OrderBy(sub => sub.PositionSubject).ToList(); subjects.Add(subjectsEIE.First(subject => subject.Id == facultySubjectsDTO[0].SubjectId).Name); for (int i = 1; i < 5; i+=2) { if (facultySubjectsDTO[i+1].SubjectId!=0) { subjects.Add(subjectsEIE.First(subject => subject.Id == facultySubjectsDTO[i].SubjectId).Name + " или " + subjectsEIE.First(subject => subject.Id == facultySubjectsDTO[i+1].SubjectId).Name); } else subjects.Add(subjectsEIE.First(subject => subject.Id == facultySubjectsDTO[i].SubjectId).Name); } return subjects; } } }
using System; using System.Linq; namespace Extract_middle_element { class Program { static void Main(string[] args) { long[] nums = Console.ReadLine().Split(' ').Select(long.Parse).ToArray(); if (nums.Length == 1) { PrintOneElement(nums); return; } else if (nums.Length % 2 == 0) { PrintEvenElements(nums); } else if (nums.Length % 2 != 0) { PrintOddElements(nums); } Console.WriteLine(); } static void PrintOneElement(long[] nums) { Console.WriteLine("{ " + $"{nums[0]}" + " }"); } static void PrintEvenElements(long[] nums) { long first = nums.Length / 2 - 1; long second = nums.Length / 2; for (int i = 0; i < 1; i++) { Console.Write("{ " + $"{nums[first]}, " + $"{nums[second]}" + " } "); } } static void PrintOddElements(long[] nums) { long first = nums.Length / 2 - 1; long second = nums.Length / 2; long third = nums.Length / 2 + 1; for (int i = 0; i < 1; i++) { Console.Write("{ " + $"{nums[first]}, " + $"{nums[second]}, " + $"{nums[third]}" + " }"); } } } }
namespace Aranda.Users.BackEnd.Helpers { public class AppSettings { public string Secret { get; set; } public string DefaultScheme { get; set; } public string Issuer { get; set; } public string Audience { get; set; } public string AccessExpiration { get; set; } public string RefreshExpiration { get; set; } } }
using System; using Foundation; using AppKit; namespace MacLibrary { public partial class WindowController : NSWindowController { public WindowController (IntPtr handle) : base (handle) { } [Export ("initWithCoder:")] public WindowController (NSCoder coder) : base (coder) { } public WindowController () : base ("Window") { } public override void AwakeFromNib () { base.AwakeFromNib (); } public new Window Window { get { return (Window)base.Window; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace MyDiplom.Controllers { public class DocumentController : Controller { public IActionResult Index() { return View(); } public IActionResult ShowFirstLink() { return View("_DocumentZone"); } public async Task<IActionResult> Switch() { var mylist = new List<string>{ "Зазор контрольной тяги ", "Зазор рабочей тяги", "Отклонение насечки на контрольных тягах"}; return View(mylist); } public IActionResult Light() { List<string> mylist = new List<string> { "Габариты установки светофора ", "Напряжение на лампах", }; return View(mylist); } } }
using System; namespace com.Sconit.Entity.SI { [Serializable] public partial class LogToUser : EntityBase { #region O/R Mapping Properties public int Id { get; set; } public string Descritpion { get; set; } public string Emails { get; set; } public string Mobiles { get; set; } public string Template { get; set; } #endregion public override int GetHashCode() { if (Id != 0) { return Id.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { LogToUser another = obj as LogToUser; if (another == null) { return false; } else { return (this.Id == another.Id); } } } }