text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainCharacter : MonoBehaviour { public float movementSpeed = 10; public float turningSpeed = 10; public int jumpHeight = 1; public Rigidbody rb; void Start () { rb = GetComponent <Rigidbody> (); } void Update () { float leftAndRight = Input.GetAxis ("Horizontal") * turningSpeed * Time.deltaTime; transform.Translate (leftAndRight, 0, 0); float vertical = Input.GetAxis ("Vertical") * movementSpeed * Time.deltaTime; transform.Translate (0, 0, vertical); if (Input.GetKeyDown ("space")) { rb.AddForce(new Vector3(0, jumpHeight, 0), ForceMode.Impulse); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using UberFrba.Abm_Chofer; namespace UberFrba.Rendicion_Viajes { public class Rendicion { public DateTime Fecha { get; set; } public Decimal Chofer { get; set; } public Decimal Porcentaje { get; set; } public Decimal Turno { get; set; } public static DataTable traerViajesDeRendicion(Chofer choferElegido, DateTime fecha) { DataTable dtViajes = new DataTable(); //Creo el comando a ejecutar SqlCommand cmd = new SqlCommand("SELECT Viaje_Codigo,Viaje_Cant_Kilometros,Viaje_Fecha_Hora_Inicio,Viaje_Fecha_Hora_Fin,Viaje_Chofer as Dni_Chofer_Viaje,Viaje_Auto,Turno_Descripcion,Turno_Valor_Kilometro,Turno_Precio_Base FROM SAPNU_PUAS.Viaje JOIN SAPNU_PUAS.Auto on Viaje_Auto = Auto_Patente JOIN SAPNU_PUAS.Turno on Viaje_Turno = Turno_Codigo WHERE Viaje_Chofer = @chofer AND Viaje_Turno = Auto_Turno AND CONVERT(date,Viaje_Fecha_Hora_Inicio) = @fecha"); cmd.Connection = DBconnection.getInstance(); cmd.Parameters.Add("@chofer", SqlDbType.Decimal).Value = choferElegido.Telefono; cmd.Parameters.Add("@fecha", SqlDbType.Date).Value = fecha.Date; SqlDataAdapter adapterViajes = new SqlDataAdapter(cmd); try { adapterViajes.Fill(dtViajes); } catch (Exception ex) { throw ex; } return dtViajes; } public static String[] grabarRendicion(Rendicion nuevaRendicion) { //Creo el comando necesario para grabar la rendicion y sus viajes SqlCommand cmdRendicion = new SqlCommand("SAPNU_PUAS.sp_rendicion_viajes"); cmdRendicion.CommandType = CommandType.StoredProcedure; cmdRendicion.Connection = DBconnection.getInstance(); cmdRendicion.Parameters.Add("@chofer_telefono", SqlDbType.Decimal).Value = nuevaRendicion.Chofer; cmdRendicion.Parameters.Add("@fecha", SqlDbType.DateTime).Value = nuevaRendicion.Fecha; cmdRendicion.Parameters.Add("@turno_codigo", SqlDbType.Decimal).Value = nuevaRendicion.Turno; cmdRendicion.Parameters.Add("@porcentaje", SqlDbType.Decimal).Value = nuevaRendicion.Porcentaje; //Creo los parametros respuesta SqlParameter responseMsg = new SqlParameter(); SqlParameter responseErr = new SqlParameter(); responseMsg.ParameterName = "@resultado"; responseErr.ParameterName = "@codOp"; responseMsg.SqlDbType = System.Data.SqlDbType.VarChar; responseMsg.Direction = System.Data.ParameterDirection.Output; responseMsg.Size = 255; responseErr.SqlDbType = System.Data.SqlDbType.Int; responseErr.Direction = System.Data.ParameterDirection.Output; cmdRendicion.Parameters.Add(responseMsg); cmdRendicion.Parameters.Add(responseErr); try { cmdRendicion.Connection.Open(); //Ejecuto el SP y veo el codigo de error cmdRendicion.ExecuteNonQuery(); int codigoError = Convert.ToInt32(cmdRendicion.Parameters["@codOp"].Value); if (codigoError != 0) throw new Exception(cmdRendicion.Parameters["@resultado"].Value.ToString()); cmdRendicion.Connection.Close(); } catch (Exception ex) { cmdRendicion.Connection.Close(); return new String[2] { "Error", ex.Message }; } return new String[2] { "Ok", "Rendicion a chofer realizada satisfactoriamente" }; } } }
namespace WebMarkupMin.Core { using System.Collections.Generic; using System.Configuration; using Configuration; using Minifiers; using Resources; using Utilities; /// <summary> /// Code minification context /// </summary> public sealed class CodeContext { /// <summary> /// WebMarkupMin context /// </summary> private readonly WebMarkupMinContext _wmmContext; /// <summary> /// Registry of CSS minifiers /// </summary> private Dictionary<string, CodeMinifierInfo> _cssMinifierRegistry; /// <summary> /// Synchronizer of CSS minifiers registry /// </summary> private readonly object _cssMinifierRegistrySynchronizer = new object(); /// <summary> /// Registry of JS minifiers /// </summary> private Dictionary<string, CodeMinifierInfo> _jsMinifierRegistry; /// <summary> /// Synchronizer of JS minifiers registry /// </summary> private readonly object _jsMinifierRegistrySynchronizer = new object(); /// <summary> /// Constructs instance of code minification context /// </summary> /// <param name="wmmContext">WebMarkupMin context</param> internal CodeContext(WebMarkupMinContext wmmContext) { _wmmContext = wmmContext; } /// <summary> /// Gets a registry of CSS minifiers /// </summary> /// <returns>Registry of CSS minifiers</returns> public Dictionary<string, CodeMinifierInfo> GetCssMinifierRegistry() { lock (_cssMinifierRegistrySynchronizer) { if (_cssMinifierRegistry == null) { CodeMinifierRegistrationList cssMinifierRegistrationList = _wmmContext.GetCoreConfiguration().Css.Minifiers; _cssMinifierRegistry = new Dictionary<string, CodeMinifierInfo>(); foreach (CodeMinifierRegistration cssMinifierRegistration in cssMinifierRegistrationList) { _cssMinifierRegistry.Add(cssMinifierRegistration.Name, new CodeMinifierInfo( cssMinifierRegistration.Name, cssMinifierRegistration.DisplayName, cssMinifierRegistration.Type)); } } } return _cssMinifierRegistry; } /// <summary> /// Creates a instance of CSS minifier based on the settings /// that specified in configuration files (App.config or Web.config) /// </summary> /// <param name="name">CSS minifier name</param> /// <param name="loadSettingsFromConfigurationFile">Flag for whether to allow /// loading minifier settings from configuration file</param> /// <returns>CSS minifier</returns> public ICssMinifier CreateCssMinifierInstance(string name, bool loadSettingsFromConfigurationFile = true) { ICssMinifier cssMinifier; Dictionary<string, CodeMinifierInfo> cssMinifierRegistry = GetCssMinifierRegistry(); if (cssMinifierRegistry.ContainsKey(name)) { CodeMinifierInfo cssMinifierInfo = cssMinifierRegistry[name]; cssMinifier = Utils.CreateInstanceByFullTypeName<ICssMinifier>(cssMinifierInfo.Type); if (loadSettingsFromConfigurationFile) { cssMinifier.LoadSettingsFromConfigurationFile(); } } else { throw new CodeMinifierNotFoundException( string.Format(Strings.Configuration_CodeMinifierNotRegistered, "CSS", name)); } return cssMinifier; } /// <summary> /// Creates a instance of default CSS minifier based on the settings /// that specified in configuration files (App.config or Web.config) /// </summary> /// <param name="loadSettingsFromConfigurationFile">Flag for whether to allow /// loading minifier settings from configuration file</param> /// <returns>CSS minifier</returns> public ICssMinifier CreateDefaultCssMinifierInstance(bool loadSettingsFromConfigurationFile = true) { string defaultCssMinifierName = _wmmContext.GetCoreConfiguration().Css.DefaultMinifier; if (string.IsNullOrWhiteSpace(defaultCssMinifierName)) { throw new ConfigurationErrorsException( string.Format(Strings.Configuration_DefaultCodeMinifierNotSpecified, "CSS")); } ICssMinifier cssMinifier = CreateCssMinifierInstance(defaultCssMinifierName, loadSettingsFromConfigurationFile); return cssMinifier; } /// <summary> /// Gets a registry of JS minifiers /// </summary> /// <returns>Registry of JS minifiers</returns> public Dictionary<string, CodeMinifierInfo> GetJsMinifierRegistry() { lock (_jsMinifierRegistrySynchronizer) { if (_jsMinifierRegistry == null) { CodeMinifierRegistrationList jsMinifierRegistrationList = _wmmContext.GetCoreConfiguration().Js.Minifiers; _jsMinifierRegistry = new Dictionary<string, CodeMinifierInfo>(); foreach (CodeMinifierRegistration jsMinifierRegistration in jsMinifierRegistrationList) { _jsMinifierRegistry.Add(jsMinifierRegistration.Name, new CodeMinifierInfo( jsMinifierRegistration.Name, jsMinifierRegistration.DisplayName, jsMinifierRegistration.Type)); } } } return _jsMinifierRegistry; } /// <summary> /// Creates a instance of JS minifier based on the settings /// that specified in configuration files (App.config or Web.config) /// </summary> /// <param name="name">JS minifier name</param> /// <param name="loadSettingsFromConfigurationFile">Flag for whether to allow /// loading minifier settings from configuration file</param> /// <returns>JS minifier</returns> public IJsMinifier CreateJsMinifierInstance(string name, bool loadSettingsFromConfigurationFile = true) { IJsMinifier jsMinifier; Dictionary<string, CodeMinifierInfo> jsMinifierRegisty = GetJsMinifierRegistry(); if (jsMinifierRegisty.ContainsKey(name)) { CodeMinifierInfo jsMinifierInfo = jsMinifierRegisty[name]; jsMinifier = Utils.CreateInstanceByFullTypeName<IJsMinifier>(jsMinifierInfo.Type); if (loadSettingsFromConfigurationFile) { jsMinifier.LoadSettingsFromConfigurationFile(); } } else { throw new CodeMinifierNotFoundException( string.Format(Strings.Configuration_CodeMinifierNotRegistered, "JS", name)); } return jsMinifier; } /// <summary> /// Creates a instance of default JS minifier based on the settings /// that specified in configuration files (App.config or Web.config) /// </summary> /// <param name="loadSettingsFromConfigurationFile">Flag for whether to allow /// loading minifier settings from configuration file</param> /// <returns>JS minifier</returns> public IJsMinifier CreateDefaultJsMinifierInstance(bool loadSettingsFromConfigurationFile = true) { string defaultJsMinifierName = _wmmContext.GetCoreConfiguration().Js.DefaultMinifier; if (string.IsNullOrWhiteSpace(defaultJsMinifierName)) { throw new ConfigurationErrorsException( string.Format(Strings.Configuration_DefaultCodeMinifierNotSpecified, "JS")); } IJsMinifier jsMinifier = CreateJsMinifierInstance(defaultJsMinifierName, loadSettingsFromConfigurationFile); return jsMinifier; } } }
using System.Collections.Generic; using System.Windows.Forms; using CSharpUtils.Utils.StatusLogger; namespace CSharpUtils.GUI { public partial class StatusDisplay : Form { private readonly Dictionary<string, TreeNode> _nodes = new Dictionary<string, TreeNode>(); public StatusDisplay(BaseStatusLogger logger) { InitializeComponent(); logger.Changed += OnChanged; } private void OnChanged(object sender, StatusChangeEventArgs e) { if (tvStatus.InvokeRequired) { tvStatus.Invoke((MethodInvoker)delegate { OnChanged(sender, e); }); return; } string[] parts = e.Key.Split('.'); TreeNode rootNode = null; Dictionary<string, TreeNode> nodes = _nodes; foreach (string part in parts) { if (nodes != null && !nodes.ContainsKey(part)) { // Create child node. TreeNode node = new TreeNode { Name = part, Text = part, Tag = new Dictionary<string, TreeNode>() }; // Store child node. if (rootNode != null) { rootNode.Nodes.Add(node); } else { tvStatus.Nodes.Add(node); } nodes.Add(part, node); } // Get new root node. rootNode = nodes?[part]; nodes = rootNode?.Tag as Dictionary<string, TreeNode>; } // Update and show the final node. if (rootNode == null) return; if (e.NewValue == LocalStatusLogger.UNSET) { rootNode.Remove(); } else { rootNode.Text = $"{parts[parts.Length - 1]}: {e.NewValueString}"; rootNode.EnsureVisible(); rootNode.Expand(); } } } }
namespace StructureAssertions.Test.TestTypes { public class ClassWithBaseClassUsingString : ABaseClass { } public class ABaseClass { public string Something { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WpfApplication2 { class MessageList { List<Message> list = new List<Message>(); public MessageList(string data) { string[] messages = data.Split(';'); for (int i = 0; i < messages.Count() - 1; i++) this.list.Add(new Message(messages[i])); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; namespace Microsoft.CodeAnalysis.Sarif.Writers { /// <summary> /// This class caches all results and notifications that are passed to it. /// Data cached this way can subsequently be replayed into other IAnalysisLogger /// instances. The driver framework uses this mechanism to merge results /// produced by a multi-threaded analysis into a single output file. /// </summary> public class CachingLogger : IAnalysisLogger { public IDictionary<ReportingDescriptor, IList<Result>> Results { get; set; } public IList<Notification> ConfigurationNotifications { get; set; } public IList<Notification> ToolNotifications { get; set; } public void AnalysisStarted() { } public void AnalysisStopped(RuntimeConditions runtimeConditions) { } public void AnalyzingTarget(IAnalysisContext context) { } public void Log(ReportingDescriptor rule, Result result) { if (rule == null) { throw new ArgumentNullException(nameof(rule)); } if (result == null) { throw new ArgumentNullException(nameof(result)); } if (rule.GetType().Name != nameof(ReportingDescriptor)) { rule = rule.DeepClone(); } if (rule.Id != result.RuleId) { throw new ArgumentException($"rule.Id is not equal to result.RuleId ({rule.Id} != {result.RuleId})"); } Results ??= new Dictionary<ReportingDescriptor, IList<Result>>(); if (!Results.TryGetValue(rule, out IList<Result> results)) { results = Results[rule] = new List<Result>(); } results.Add(result); } public void LogConfigurationNotification(Notification notification) { ConfigurationNotifications ??= new List<Notification>(); ConfigurationNotifications.Add(notification); } public void LogMessage(bool verbose, string message) { } public void LogToolNotification(Notification notification) { ToolNotifications ??= new List<Notification>(); ToolNotifications.Add(notification); } } }
using System; using System.Collections.Generic; using System.Text; namespace HackerRank_HomeCode { class InsertionSort { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SmallHouseManagerModel { public class FixRepairModel { /// <summary> /// 维修编号 /// </summary> public int ID { get; set; } /// <summary> /// 设备编号 /// </summary> public string FixID { get; set; } /// <summary> /// 设备名称 /// </summary> public string FixName { get; set; } /// <summary> /// 维修日期 /// </summary> public DateTime RepairDate { get; set; } /// <summary> /// 结束日期 /// </summary> public DateTime EndDate { get; set; } /// <summary> /// 主要负责人 /// </summary> public string MainHead { get; set; } /// <summary> /// 维修费 /// </summary> public double ServiceFee { get; set; } /// <summary> /// 材料费 /// </summary> public double MaterielFee { get; set; } /// <summary> /// 维修总费用 /// </summary> public double RepairSum { get; set; } /// <summary> /// 维修说明 /// </summary> public string RepairMemo { get; set; } /// <summary> /// 是否付费 0:已付 1:未付 /// </summary> public int Sign { get; set; } /// <summary> /// 维修单位 /// </summary> public string RepairUnit { get; set; } } }
using ReadyGamerOne.Utility; using UnityEditor; using UnityEngine; namespace DialogSystem.Model.Editor { [CustomPropertyDrawer(typeof(DialogProgressPoint))] public class DialogProgressPointDrawer:UnityEditor.PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return EditorGUIUtility.singleLineHeight * 2; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var index = 0; var left = 0.1f; var s=new GUIStyle() { fontSize = 20 }; EditorGUI.LabelField(position.GetLeft(left), property.FindPropertyRelative("index").intValue.ToString(),s); position = position.GetRight(1 - left); EditorGUI.PropertyField(position.GetRectAtIndex(index++), property.FindPropertyRelative("name")); EditorGUI.PropertyField(position.GetRectAtIndex(index++), property.FindPropertyRelative("value")); } } }
using Microcharts; using SkiaSharp; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Test2project.Diet; using Xamarin.Forms; using Xamarin.Forms.Xaml; using System.ComponentModel; namespace Test2project.Diet { [DesignTimeVisible(false)] [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Pg1 : ContentPage { List<Microcharts.Entry> entries = new List<Microcharts.Entry> { new Microcharts.Entry(200) { Color=SKColor.Parse("#ff1493"), Label="january", ValueLabel="200" }, new Microcharts.Entry(400) { Color=SKColor.Parse("#00bfff"), Label="February", ValueLabel="400" }, new Microcharts.Entry(-100) { Color=SKColor.Parse("#00ced1"), Label="March", ValueLabel="-100" }, }; public Pg1() { InitializeComponent(); Chart1.Chart = new BarChart { Entries = entries }; } public void NextPg2(object sender, EventArgs e) { Navigation.PushModalAsync(new Pg2()); } private async void TapGestureRecognizer_TappedforDietPg1(object sender, EventArgs e) { await Navigation.PushModalAsync(new MainPage()); } protected override bool OnBackButtonPressed() { return true; } } }
using Enrollment.Bsl.Business.Requests; using Enrollment.Bsl.Business.Responses; using Enrollment.Web.Utils; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace Enrollment.Api.Controllers { [Produces("application/json")] [Route("api/List")] public class ListController : Controller { private readonly IHttpClientFactory clientFactory; private readonly ConfigurationOptions configurationOptions; public ListController(IHttpClientFactory clientFactory, IOptions<ConfigurationOptions> optionsAccessor) { this.clientFactory = clientFactory; this.configurationOptions = optionsAccessor.Value; } [HttpPost("GetList")] public Task<BaseResponse> GetList([FromBody] GetTypedListRequest request) => this.clientFactory.PostAsync<BaseResponse> ( "api/List/GetList", JsonSerializer.Serialize(request), this.configurationOptions.BaseBslUrl ); } }
using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerSpawner : MonoBehaviour { // SINGLETON private static PlayerSpawner instance; [SerializeField] private List<Vector2> SpawnPoints = new List<Vector2>(4); [SerializeField] private GameObject[] CharPrefabs; [SerializeField] private Transform PlayerParentObject; private List<GameObject> m_spawnnedPlayers = new List<GameObject>(); private List<PlayerInfo> m_spawnnedPlayersInfo = new List<PlayerInfo>(); // ACCESSORS public static List<GameObject> SpawnnedPlayers { get { return instance.m_spawnnedPlayers; } } public void Awake() { Debug.Assert(instance == null, this.gameObject.name + " - PlayerSpawnner must be unique!"); instance = this; } public static void SpawnPlayers(List<PlayerInfo> PlayersToSpawn) { instance.m_spawnnedPlayers.Clear(); List<Vector2> shuffledSpawns = instance.SpawnPoints.OrderBy( x => Random.value ).ToList( ); int i = 0; foreach(var pi in PlayersToSpawn){ var obj = Instantiate(instance.CharPrefabs[(int)pi.SelectedCharacter], shuffledSpawns[i], Quaternion.identity, instance.PlayerParentObject); obj.GetComponent<ChangeColor>().hasHoverText = true; obj.GetComponent<ChangeColor>().hoverText.text = "P" + (i+1); obj.GetComponent<ChangeColor>().color = pi.SelectedColor; obj.GetComponent<ChangeColor>().ManualValidate(); obj.GetComponent<PlayerInputCtlr>().m_nbPlayer = (PlayerInputCtlr.ePlayer)(pi.ControllerNumber+1); i++; instance.m_spawnnedPlayers.Add(obj); } instance.m_spawnnedPlayersInfo = PlayersToSpawn; } public static void RespawnPlayers(){ for(int i = 0; i < instance.m_spawnnedPlayers.Count; i++){ //instance.m_spawnnedPlayers[i].transform.position = instance.SpawnPoints[i]; //instance.m_spawnnedPlayers[i].GetComponent<WeaponPick>().WeaponList = new List<GameObject>(); //instance.m_spawnnedPlayers[i].GetComponent<PlayerStateMachine>().MSG_Respawn(); //instance.m_spawnnedPlayers[i].transform.Find("Hurtbox").GetComponent<DamageBehaviour>().RestartPhase(); //instance.m_spawnnedPlayers[i].GetComponent<PlayerInputCtlr>().enabled = true; ////reset other things here Destroy(instance.m_spawnnedPlayers[i]); } SpawnPlayers(instance.m_spawnnedPlayersInfo); } void OnDrawGizmosSelected(){ Gizmos.color = Color.red; for(int i = 0; i < 4; i++){ Gizmos.DrawCube((Vector3)SpawnPoints[i], new Vector3(0.5f,0.5f,0)); } } }
using Microsoft.EntityFrameworkCore; namespace EntityFramework.Demo { internal class EmployeeProviderWithInlineQuery : IEmployeeProvider { private readonly EmployeeContext employeeContext; public EmployeeProviderWithInlineQuery(EmployeeContext employeeContext) { this.employeeContext = employeeContext; } public Employee Get(int id) { return employeeContext.Employees.FromSqlRaw ("SELECT id, first_name,last_name,home_phone,cell_phone FROM Employee WHERE id=({0})", id) .FirstOrDefaultAsync().Result; } } }
using System; namespace Template_Method.Entities { public class ModoDificil : Jogo { public override void PrimeiraFase() { Console.WriteLine("Adicionar obstaculos na pista"); } public override void SegundaFase() { Console.WriteLine("Os carros devem correr mais"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Deployer2._0.Resources.APIResources { public class VMValue { public int memory_size_MiB { get; set; } public string vm { get; set; } public string name { get; set; } public string power_state { get; set; } public int cpu_count { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using System.Windows.Interactivity; //using Microsoft.Expression.Interactivity.Core; namespace BPiaoBao.Client.UIExt.Behaviors { public class DatePickerDisplayDateStartBehavior : Behavior<DatePicker> { public DatePickerDisplayDateStartBehavior() { } protected override void OnAttached() { base.OnAttached(); base.AssociatedObject.DisplayDateStart = DateTime.Now; } protected override void OnDetaching() { base.OnDetaching(); } } }
using System; using System.Collections.Generic; using System.Text; namespace homeworkCSharp2020 { class nal18 { //IZBIRNI MENI public static void izbirniMeni() { Console.WriteLine("1 - Sestej"); Console.WriteLine("2 - Odstej"); Console.WriteLine("3 - Mnozi"); Console.WriteLine("4 - Deli"); Console.WriteLine("5 - Potenca"); Console.WriteLine("6 - Kvadrat"); Console.WriteLine("7 - Ostanek"); Console.WriteLine("8 - Fibonacci (max 40)"); Console.WriteLine("9 - Koren"); Console.WriteLine("10 - Izhod"); try { int izbira = Convert.ToInt32(Console.ReadLine()); stikalo(izbira); } catch (Exception e) { Console.WriteLine("Napaka: {0}", e.Message); } } //SWITCH private static void stikalo(int izbira) { switch (izbira) { case 1: sestej(); break; case 2: odstej(); break; case 3: mnozi(); break; case 4: deli(); break; case 5: potenca(); break; case 6: kvadrat(); break; case 7: ostanek(); break; case 8: fib(); break; case 9: koren(); break; case 10: izhod(); break; default: Console.WriteLine("Neveljaven ukaz"); repeat(); break; } } private static void izhod() { Console.WriteLine("Zelis zakljuciti program? Y/N"); string choice = Console.ReadLine(); if(choice.Equals("y", StringComparison.OrdinalIgnoreCase)) { Environment.Exit(0); } else { izbirniMeni(); } } private static void koren() { try { Console.WriteLine("Vnesi stevilo"); int x = Convert.ToInt32(Console.ReadLine()); double y = Math.Sqrt(x); Console.WriteLine("Koren stevila {0} je {1}", x, y); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void fib() { try { Console.WriteLine("Vnesti stevilo"); int x = Convert.ToInt32(Console.ReadLine()); //int y = calcFib(x); int y = calcFibRecur(x); Console.WriteLine("Fibonacci {0} = {1}", x,y); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void ostanek() { try { Console.WriteLine("Vnesi prvo stevilo"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vnesi drugo stevilo"); int y = Convert.ToInt32(Console.ReadLine()); double z = x % y; Console.WriteLine("{0} % {1} = {2}", x, y, z); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void kvadrat() { try { Console.WriteLine("Vnesi stevilo"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Kvadrat stevila {0} je {1}", x, x *= x); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void potenca() { try { Console.WriteLine("Vnesi stevilo"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vnesi potenco"); int y = Convert.ToInt32(Console.ReadLine()); double z = Math.Pow(x, y); Console.WriteLine("{0} na {1} potenco = {2}", x, y, z); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void deli() { try { Console.WriteLine("Vnesi prvo stevilo"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vnesi drugo stevilo"); int y = Convert.ToInt32(Console.ReadLine()); int z = x / y; Console.WriteLine("{0} / {1} = {2}", x, y, z); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void mnozi() { try { Console.WriteLine("Vnesi prvo stevilo"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vnesi drugo stevilo"); int y = Convert.ToInt32(Console.ReadLine()); int z = x * y; Console.WriteLine("{0} - {1} = {2}", x, y, z); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void odstej() { try { Console.WriteLine("Vnesi prvo stevilo"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vnesi drugo stevilo"); int y = Convert.ToInt32(Console.ReadLine()); int z = x - y; Console.WriteLine("{0} - {1} = {2}", x, y, z); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void sestej() { try { Console.WriteLine("Vnesi prvo stevilo:"); int x = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Vnesi drugo stevilo:"); int y = Convert.ToInt32(Console.ReadLine()); int z = x + y; Console.WriteLine("{0} + {1} = {2}", x, y, z); repeat(); } catch (Exception e) { Console.WriteLine("Napacen ukaz, opis napake:"); Console.WriteLine(e.Message); } } private static void repeat() { Console.WriteLine("Nadaljuj? Y/N"); try { string choice = Console.ReadLine(); if( choice.Equals("Y", StringComparison.OrdinalIgnoreCase)){ izbirniMeni(); } else { Environment.Exit(0); } } catch(Exception e) { Console.WriteLine("Prislo je do napake:"); Console.WriteLine(e.Message); } } private static int calcFib(int x) { int rezultat = 0; int prvaStevilka = 0; int drugaStevilka = 1; if( x == 0) { return 0; } if( x == 1) { return 1; } for (int i = 0; i < x; i++) { rezultat = prvaStevilka + drugaStevilka; prvaStevilka = drugaStevilka; drugaStevilka = rezultat; } return rezultat; } private static int calcFibRecur(int x) { if (x == 0) return 0; if (x == 1) return 1; return calcFibRecur(x - 1) + calcFibRecur(x - 2); } } }
using System; using System.IO; using System.Collections.Generic; using System.Text; namespace HTMLReportingProject { public class HTMLReportor { private string _Name; private string _folder; private Queue<string> _Header = new Queue<string>(); private Queue<string> _Body = new Queue<string>(); public string ProjectName { get { return _Name; } set { _Name = value; } } public string FolderName { get { return _folder; } set { _folder = value; } } public HTMLReportor() //For when report had no name { _Name = "index"; _folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\"; CreateNewProject(); } public HTMLReportor(string ProjectName) { _Name = ProjectName; _folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\"; CreateNewProject(); } public HTMLReportor(string ProjectName, string Folder ) { _Name = ProjectName; //Check to see if folder exists, if it doesnt create it if(!Directory.Exists(Folder)) { Directory.CreateDirectory(Folder); } //If the folder already exists, use it if(Directory.Exists(Folder)) { if (!Folder.EndsWith("\\")) Folder += "\\"; _folder = Folder; } else { _folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\"; } CreateNewProject(); } public void WriteHTMLProject() { StreamWriter writeHTML = new StreamWriter(_folder + ProjectName + ".html"); try { CloseProject(); //Write header and body queues to file while (_Header.Count > 0) { writeHTML.WriteLine(_Header.Dequeue()); } while (_Body.Count > 0) { writeHTML.WriteLine(_Body.Dequeue()); } writeHTML.Flush(); writeHTML.Close(); } catch (Exception ex) { throw ex; } } private void CreateNewProject() { try { //Clear the header Q _Header.Clear(); //Open all HTML tags _Header.Enqueue("<!DOCTYPE html>"); _Header.Enqueue("<head>"); _Header.Enqueue("<title>" + ProjectName + "</title>"); _Header.Enqueue("<style type='text/css'>"); //Start the body _Body.Clear(); _Body.Enqueue("<body>"); } catch (Exception ex) { throw ex; } } private void CloseProject() { try { //Close out the header _Header.Enqueue("</style>"); _Header.Enqueue("</head>"); //Close out the body _Body.Enqueue("</body>"); _Body.Enqueue("</html>"); } catch (Exception ex) { throw ex; } } public void Header(string text, int index, string css) { try { switch (index) { case 1: { _Body.Enqueue("<h1 "+css+">" + text + "</h1>"); break; } case 2: { _Body.Enqueue("<h2 "+css+">" + text + "</h2>"); break; } case 3: { _Body.Enqueue("<h3 "+css+">" + text + "</h3>"); break; } case 4: { _Body.Enqueue("<h4 "+css+">" + text + "</h4>"); break; } case 5: { _Body.Enqueue("<h5 "+css+">" + text + "</h5>"); break; } case 6: { _Body.Enqueue("<h6 "+css+">" + text + "</h6>"); break; } default: { _Body.Enqueue("<h2 "+css+">" + text + "</h2>"); break; } } } catch (Exception ex) { throw ex; } } public void CSS_ID_Create(string ID_Name, string CSS_Style) { try { _Header.Enqueue("#"+ID_Name+"{"+ CSS_Style + "}"); } catch (Exception ex) { throw ex; } } public void CSS_Class_CreateNEW(string ClassName, string CSS_Style) { try { _Header.Enqueue("." + ClassName + "{" + CSS_Style + "}"); } catch (Exception ex) { throw ex; } } public void TableOPEN(string css) { try { _Body.Enqueue("<table " + css + ">"); } catch (Exception ex) { throw ex; } } public void TableCLOSE() { try { _Body.Enqueue("</table>"); } catch (Exception ex) { throw ex; } } public void TableRowOPEN(string css) { try { _Body.Enqueue("<tr " + css + ">"); } catch (Exception ex) { throw ex; } } public void TableRowCLOSE() { try { _Body.Enqueue("</tr>"); } catch (Exception ex) { throw ex; } } public void TableHead(string text, string css) { try { _Body.Enqueue("<th " + css + ">" + text + "</th>"); } catch (Exception ex) { throw ex; } } public void TableData(string text, string css) { try { _Body.Enqueue("<td" + css + ">" + text + "</td>"); } catch (Exception ex) { throw ex; } } public void OrderedListOPEN(string css) { try { _Body.Enqueue("<ol" + css + ">"); } catch (Exception ex) { throw ex; } } public void OrderedListCLOSE() { try { _Body.Enqueue("</ol>"); } catch (Exception ex) { throw ex; } } public void UnorderedListOPEN(string css) { try { _Body.Enqueue("<ul "+css+">"); } catch (Exception ex) { throw ex; } } public void UnorderedListCLOSE() { try { _Body.Enqueue("</ul>"); } catch (Exception ex) { throw ex; } } public void ListItem (string listItem, string css) { try { _Body.Enqueue("<li " + css + ">" + listItem + "</li>"); } catch (Exception ex) { throw ex; } } public void Paragraph(string text, string css) { try { _Body.Enqueue("<p " + css + ">" + text + "</p>"); } catch (Exception ex) { throw ex; } } public void TextBox(string css) { try{_Body.Enqueue("<input " + css + " type='text'>");} catch (Exception ex){ throw ex; } } public void Button(string txtValue, string css) { try { _Body.Enqueue("<button " + css + " type='button'>" + txtValue + "</button>"); } catch (Exception ex) { throw ex; } } public void DivOpen(string css) { try{ _Body.Enqueue("<div "+css+">"); } catch (Exception ex){throw ex;} } public void DivClose() { try{_Body.Enqueue("</div>");} catch (Exception ex){ throw ex;} } public void Break() { try{_Body.Enqueue("</br>");} catch (Exception ex){ throw ex;} } public void HorizontalRow() { try { _Body.Enqueue("<hr>"); } catch (Exception ex) { throw ex; } } public void Abbreviation(string abbreviation, string fullLength) { try { _Body.Enqueue("<abbr title='" + fullLength + "'>" + abbreviation + "</abbr>"); } catch (Exception ex) {throw ex; } } public void HyperLink(string link, string desc, string css) { try { _Body.Enqueue("<a " + css + " href='" + link + "'>" + desc + "</a>"); } catch (Exception ex) { throw ex; } } public void Image(string src, string css) { try { _Body.Enqueue("<img " + css + " src='" + src + "'>"); } catch (Exception ex) { throw ex; } } public void FooterOPEN(string css) { try { _Body.Enqueue("<footer " + css + " >"); } catch (Exception ex) { throw ex; } } public void FooterCLOSE() { try { _Body.Enqueue("</footer>"); } catch (Exception ex) { throw ex; } } // NOT USED public void FigCaption(string description) { try { _Body.Enqueue("<figcaption>" + description + "</figcaption>"); } catch (Exception ex) { throw ex; } } // NOT USED public void FigureOpen() { try { _Body.Enqueue("<figure>"); } catch (Exception ex) { throw ex; } } // NOT USED public void FigureClose() { try { _Body.Enqueue("</figure>"); } catch (Exception ex) { throw ex; } } } }
using System.Xml.Serialization; namespace ZaupHomeCommand { public class HomeGroup { [XmlAttribute] public string Id { get; set; } [XmlAttribute] public byte Wait { get; set; } } }
namespace Contoso.XPlatform.Flow.Requests { public class CommandButtonRequest { public string NewSelection { get; set; } } }
namespace WsValidate.Contracts { public interface IWsValidate { void Run(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StackTrace { class Program { static void Main(string[] args) { lv1 _lv1 = new lv1(); _lv1.work1(); System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(0); //จะได้ Execution Stack ตัวบนสุด คือ ตัวมันเอง Main string methodname = sf.GetMethod().Name; } class lv1 { public void work1() { lv2 _lv2 = new lv2(); _lv2.work2(); System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(0); //จะได้ Execution Stack ตัวบนสุด คือ ตัวมันเอง work1 string methodname = sf.GetMethod().Name; sf = st.GetFrame(1); //จะได้ Execution Stack ตัวที่ 2 จากบนสุด คือ Main methodname = sf.GetMethod().Name; } class lv2 { public void work2() { lv3 _lv3 = new lv3(); _lv3.work3(); System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(0); //จะได้ Execution Stack ตัวบนสุด คือ ตัวมันเอง work2 string methodname = sf.GetMethod().Name; sf = st.GetFrame(1); //จะได้ Execution Stack ตัวที่ 2 จากบนสุด คือ work1 methodname = sf.GetMethod().Name; sf = st.GetFrame(2); //จะได้ Execution Stack ตัวที่ 3 จากบนสุด คือ Main methodname = sf.GetMethod().Name; } class lv3 { public void work3() { lv4 _lv4 = new lv4(); _lv4.work4(); System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(0); //จะได้ Execution Stack ตัวบนสุด คือ ตัวมันเอง work3 string methodname = sf.GetMethod().Name; sf = st.GetFrame(1); //จะได้ Execution Stack ตัวที่ 2 จากบนสุด คือ work2 methodname = sf.GetMethod().Name; sf = st.GetFrame(2); //จะได้ Execution Stack ตัวที่ 3 จากบนสุด คือ work1 methodname = sf.GetMethod().Name; sf = st.GetFrame(3); //จะได้ Execution Stack ตัวที่ 4 จากบนสุด คือ Main methodname = sf.GetMethod().Name; } class lv4 { public void work4() { System.Diagnostics.StackTrace st = new System.Diagnostics.StackTrace(); System.Diagnostics.StackFrame sf = st.GetFrame(0); //จะได้ Execution Stack ตัวบนสุด คือ ตัวมันเอง work4 string methodname=sf.GetMethod().Name; sf = st.GetFrame(1); //จะได้ Execution Stack ตัวที่ 2 จากบนสุด คือ work3 methodname = sf.GetMethod().Name; sf = st.GetFrame(2); //จะได้ Execution Stack ตัวที่ 3 จากบนสุด คือ work2 methodname = sf.GetMethod().Name; sf = st.GetFrame(3); //จะได้ Execution Stack ตัวที่ 4 จากบนสุด คือ work1 methodname = sf.GetMethod().Name; sf = st.GetFrame(4); //จะได้ Execution Stack ตัวที่ 5 จากบนสุด คือ Main methodname = sf.GetMethod().Name; } } } } } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerExample : MonoBehaviour { public GameObject cat; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnCollisionEnter(Collision col) { if (col.gameObject.CompareTag("WallTag")) { ReverseCat(); } } void ReverseCat() { var currentSpeed = cat.GetComponent<movement>().speed; cat.gameObject.transform.RotateAround(transform.position, transform.up, 180f); if (currentSpeed <= 15) { var sp = currentSpeed * 1.3; currentSpeed = Convert.ToInt32(sp); } else { currentSpeed = 10; } cat.GetComponent<movement>().speed = currentSpeed * -1; } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; /* This Application Is Created By Bits Developments / Hasan Elsherbiny Feel Free To use Any code here but DON'T Forget To Mention The Author Support Us On Paypal https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=33739JHTLBA5W&source=url */ namespace MobileAssetsImageResizer { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { if (args != null && args.Any()) { //Opend From Windows Context Menu AssetsCreator.Create(args[0]); } else { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } } } }
using System; namespace SSW.DataOnion.Core { public class DataOnionException : Exception { public DataOnionException(string message) : base(message) { } public DataOnionException(string message, Exception innerException) : base(message, innerException) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PresenterLibrary.Views; using PresenterLibrary.Common; using ModelMVPDataBasePart.IModels; using ModelMVPDataBasePart.Common; namespace PresenterLibrary.Presenters { class ReminderAddingPresenter:BasePresenter<IRemindAddingView,ArgDepositer<int,string>> { private readonly IRemindAddingModel ModelInterface; private readonly IEnumerable<EventDataCreator> DateList; public ReminderAddingPresenter(IApplicationController Controller,IRemindAddingView InView, IRemindAddingModel InModel):base(Controller,InView) { ModelInterface = InModel; ViewInterface.AddRemind += (sender, args) => AddRemind(); ViewInterface.DeleteRemind += (arg) => RemoveSelectRemind(arg); ViewInterface.PanelConfirm += (arg) => PanelConfirm(arg); } public void PanelConfirm(int ConfirmIndex) { //var temp=ModelInterface.GetItemsForFormInitialize(Controller.DBClass, ConfirmIndex); //ViewInterface.SetTimersList(); //temp[ViewInterface.SelectedValue].EventRemindTable } public void AddRemind() { if (ViewInterface.RemindAfterBefore != null) { ModelInterface.AddItemToListStruct(new RemindDataCreator( DateList.ElementAt(ViewInterface.SelectedValue).EventDate.Add(ViewInterface.RemindAfterBefore.Value), ViewInterface.RemindUntil, (int)ViewInterface.HowToRemind)); } else { ModelInterface.AddItemToListStruct(new RemindDataCreator( DateList.ElementAt(ViewInterface.SelectedValue).EventDate, ViewInterface.RemindUntil, (int)ViewInterface.HowToRemind)); } } public void RemoveSelectRemind(int arg) { ModelInterface.RemoveItemFromListStruct(arg); ViewInterface.RemoveSelectedItem_From_RemindersList(arg); } public override void Run(ArgDepositer<int, string> Arg) { switch(Arg.FirstDataHandler) { case 0: ViewInterface.FirstPanelInitialization(Arg.FirstDataHandler, ModelInterface.GetEventNames(Controller.DBClass)); ViewInterface.Show(); break; } } } }
using CoordControl.Core.Domains; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CoordControl.Core { /// <summary> /// Участок перекрестка /// </summary> public sealed class RegionCross : Region { /// <summary> /// Перекресток, для которого создается регион /// </summary> public NodeCross CrossNode { get; set; } /// <summary> /// Ширина участка, метры /// </summary> public double Width { get; private set; } /// <summary> /// ширина верхней половины /// </summary> public double WidthTop; /// <summary> /// Часть потока, которая едет /// к левому выходу /// </summary> public double ToLeftFlowPart; /// <summary> /// Часть потока, которая едет /// к правому выходу /// </summary> public double ToRightFlowPart; /// <summary> /// Часть потока, которая едет /// к верхнему выходу /// </summary> public double ToTopFlowPart; /// <summary> /// Часть потока, которая едет к нижнему выходу /// /// </summary> public double ToBottomFlowPart; public RegionCross(NodeCross nc) { CrossNode = nc; CalcSizes(); } /// <summary> /// Перемещение части ТП с последнего региона /// на перекресток /// </summary> /// <param name="regionFrom">последний регион перегона</param> /// <param name="deltaFlowPart">часть ТП, которую необходимо переместить</param> /// <returns>реально перемещенную часть ТП с учетом ограничений</returns> public double MoveToCross(Region regionFrom, double deltaFlowPart) { double resultDeltaFP = deltaFlowPart; double regionFromFlowPart = regionFrom.FlowPart - regionFrom.DeltaFlowPartLast; //ограничение на количество имеющихся ТС if (regionFromFlowPart < deltaFlowPart) resultDeltaFP = regionFromFlowPart; //ограничение на максимальное количество ТС на участке перекрестка double FpNextMax = Lenght * (Width / ModelConst.LINE_WIDTH_DEFAULT) / ModelConst.CAR_LENGTH; double FpNext = FlowPart + resultDeltaFP; if (FpNext > FpNextMax) resultDeltaFP -= (FpNext - FpNextMax); //"остатки" ТС перемещаются на следующий регион if ((regionFromFlowPart - resultDeltaFP) < 0.5 && (regionFromFlowPart + FlowPart) < FpNextMax) resultDeltaFP = regionFromFlowPart; //перемещение части ТП FlowPart += resultDeltaFP; regionFrom.FlowPart -= resultDeltaFP; return resultDeltaFP; } /// <summary> /// Перемещение части ТП с перекрестка /// на некоторый перегон /// </summary> /// <param name="regionTo">Регион, на который перемещается</param> /// <param name="flowPartSource">Часть ТП перекрестка</param> /// <param name="deltaFlowPart">часть ТП для перемещения</param> /// <returns>Фактически перемещенная часть ТП</returns> public double MoveFromCross(Region regionTo, ref double flowPartSource, double deltaFlowPart) { double resultDeltaFP = deltaFlowPart; //ограничение на количество имеющихся ТС if (flowPartSource < deltaFlowPart) resultDeltaFP = flowPartSource; //ограничение на максимальное количество ТС на следующем участке double FpNextMax = regionTo.Lenght * regionTo.Way.GetInfo().LinesCount / ModelConst.CAR_LENGTH; double FpNext = regionTo.FlowPart + resultDeltaFP; if (FpNext > FpNextMax) resultDeltaFP -= (FpNext - FpNextMax); //"остатки" ТС перемещаются на следующий регион if ((flowPartSource - resultDeltaFP) < 0.5 && (flowPartSource + regionTo.FlowPart) < FpNextMax) resultDeltaFP = flowPartSource; //перемещение части ТП regionTo.FlowPart += resultDeltaFP; FlowPart -= resultDeltaFP; flowPartSource -= resultDeltaFP; return resultDeltaFP; } /// <summary> /// вычисление ширины и длины участка перекрестка /// </summary> private void CalcSizes() { Pass entryRightPass = CrossNode.EntityCross.PassRight; Pass exitLeftPass = (CrossNode.EntityCross.RoadLeft != null) ? CrossNode.EntityCross.RoadLeft.CrossLeft.PassRight : CrossNode.EntityCross.PassRight; Pass widthMax = ((entryRightPass.LineWidth * entryRightPass.LinesCount > exitLeftPass.LineWidth * exitLeftPass.LinesCount) ? entryRightPass : exitLeftPass); WidthTop = widthMax.LinesCount * widthMax.LineWidth; Width = WidthTop; Pass entryLeftPass = CrossNode.EntityCross.PassLeft; Pass exitRightPass = (CrossNode.EntityCross.RoadRight != null) ? CrossNode.EntityCross.RoadRight.CrossRight.PassLeft : CrossNode.EntityCross.PassLeft; widthMax = ((entryLeftPass.LineWidth * entryLeftPass.LinesCount > exitRightPass.LineWidth * exitRightPass.LinesCount) ? entryLeftPass : exitRightPass); Width += widthMax.LineWidth * widthMax.LinesCount; #region вычисление длины участка перекрестка Pass entryTopPass = CrossNode.EntityCross.PassTop; Lenght = entryTopPass.LinesCount * entryTopPass.LineWidth; Pass entryBottomPass = CrossNode.EntityCross.PassBottom; Lenght += entryBottomPass.LinesCount * entryBottomPass.LineWidth; #endregion } } }
using System; namespace KRF.Core.Entities.Product { public class Inventory { /// <summary> /// Inventory unique identifier /// </summary> public int ID { get; set; } /// <summary> /// Assembly ID /// </summary> public int? AssemblyID { get; set; } /// <summary> /// Assembly ID /// </summary> public int ItemID { get; set; } /// <summary> /// Assembly Qty. /// </summary> public decimal Qty { get; set; } /// <summary> /// DateUpdated /// </summary> public DateTime DateUpdated { get; set; } public string Type { get; set; } public string Comment { get; set; } } public class InventoryAudit { /// <summary> /// Inventory unique identifier /// </summary> public int ID { get; set; } /// <summary> /// Assembly ID /// </summary> public int? AssemblyID { get; set; } public int ItemID { get; set; } /// <summary> /// Assembly Qty. /// </summary> public decimal Qty { get; set; } /// <summary> /// DateUpdated /// </summary> public DateTime DateUpdated { get; set; } /// <summary> /// DateCreated /// </summary> public DateTime DateCreated { get; set; } public string Type { get; set; } public string Comment { get; set; } } }
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 AdifLog { public partial class PortSelect : Form { // the hamlib rig list is presented in a combo box with this class RigTypeEntry { public RigTypeEntry(int modelNumber, string mfg, string modelName) { this.modelNumber = modelNumber; this.modelName = modelName; this.mfg = mfg; } public int modelNumber; public string mfg; public string modelName; public override string ToString() { return mfg + " " + modelName; } }; public PortSelect() { InitializeComponent(); } private object NullItem = "Default"; private void PortSelect_Load(object sender, EventArgs e) { object sel = null; foreach (string s in System.IO.Ports.SerialPort.GetPortNames()) { comboBoxPorts.Items.Add(s); if (ComPort?.ToUpper() == s.ToUpper()) sel = s; } comboBoxPorts.SelectedItem = sel; sel = NullItem; comboBoxBaud.Items.Add(NullItem); for (uint i = 2400; i < 300000; i *= 2) { object v = i.ToString(); if (i == Baud) sel = v; comboBoxBaud.Items.Add(v); } comboBoxBaud.SelectedItem = sel; sel = null; HamlibThreadWrapper.listRigs((int model, string mfg, string modelname) => { object v = new RigTypeEntry(model, mfg, modelname); if (model == ModelNumber) sel = v; else if (null == sel && model == DUMMY_HAMLIB_RIG) sel = v; comboBoxRigSel.Items.Add(v); }); comboBoxRigSel.SelectedItem = sel; } public uint Baud { get; set; } = 0; public string ComPort { get; set; } = ""; public int ModelNumber { get; set; } = -1; private void buttonOK_Click(object sender, EventArgs e) { object baud = comboBoxBaud.SelectedItem; if (null != baud && NullItem != baud) Baud = UInt32.Parse(baud.ToString()); ComPort = comboBoxPorts.SelectedItem?.ToString(); RigTypeEntry rs = comboBoxRigSel.SelectedItem as RigTypeEntry; if (null != rs) ModelNumber = rs.modelNumber; } const int DUMMY_HAMLIB_RIG = 1; private void check_SelectedIndexChanged(object sender, EventArgs e) { RigTypeEntry re = comboBoxRigSel.SelectedItem as RigTypeEntry; bool isDummy = re?.modelNumber == DUMMY_HAMLIB_RIG; buttonOK.Enabled = (null != re) && (isDummy || (null != comboBoxPorts.SelectedItem)); if (isDummy) comboBoxPorts.SelectedItem = null; } } }
using System; using System.IO; class LineNumbers { static void Main() { using (StreamReader reader = new StreamReader("test.txt")) { using (StreamWriter writer = new StreamWriter("result.txt")) { string line; int lineNumber = 0; while ((line = reader.ReadLine()) != null) { writer.WriteLine(++lineNumber + " " + line); } } } Console.WriteLine("File successfully writen!"); } }
using UnityEngine; using System; using System.Runtime.InteropServices; public class BluetoothLEHardwareInterface { public enum CBCharacteristicProperties { CBCharacteristicPropertyBroadcast = 0x01, CBCharacteristicPropertyRead = 0x02, CBCharacteristicPropertyWriteWithoutResponse = 0x04, CBCharacteristicPropertyWrite = 0x08, CBCharacteristicPropertyNotify = 0x10, CBCharacteristicPropertyIndicate = 0x20, CBCharacteristicPropertyAuthenticatedSignedWrites = 0x40, CBCharacteristicPropertyExtendedProperties = 0x80, CBCharacteristicPropertyNotifyEncryptionRequired = 0x100, CBCharacteristicPropertyIndicateEncryptionRequired = 0x200, }; public enum CBAttributePermissions { CBAttributePermissionsReadable = 0x01, CBAttributePermissionsWriteable = 0x02, CBAttributePermissionsReadEncryptionRequired = 0x04, CBAttributePermissionsWriteEncryptionRequired = 0x08, }; #if UNITY_IPHONE [DllImport ("__Internal")] private static extern void _iOSBluetoothLELog (string message); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEInitialize (bool asCentral, bool asPeripheral); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEDeInitialize (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEPauseMessages (bool isPaused); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEScanForPeripheralsWithServices (string serviceUUIDsString, bool allowDuplicates); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERetrieveListOfPeripheralsWithServices (string serviceUUIDsString); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEStopScan (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEConnectToPeripheral (string name); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEDisconnectPeripheral (string name); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEReadCharacteristic (string name, string service, string characteristic); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEWriteCharacteristic (string name, string service, string characteristic, byte[] data, int length, bool withResponse); [DllImport ("__Internal")] private static extern void _iOSBluetoothLESubscribeCharacteristic (string name, string service, string characteristic); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEUnSubscribeCharacteristic (string name, string service, string characteristic); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEPeripheralName (string newName); [DllImport ("__Internal")] private static extern void _iOSBluetoothLECreateService (string uuid, bool primary); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveService (string uuid); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveServices (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLECreateCharacteristic (string uuid, int properties, int permissions, byte[] data, int length); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveCharacteristic (string uuid); [DllImport ("__Internal")] private static extern void _iOSBluetoothLERemoveCharacteristics (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEStartAdvertising (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEStopAdvertising (); [DllImport ("__Internal")] private static extern void _iOSBluetoothLEUpdateCharacteristicValue (string uuid, byte[] data, int length); #elif UNITY_ANDROID static AndroidJavaObject _android = null; #endif private static BluetoothDeviceScript bluetoothDeviceScript; public static void Log (string message) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLELog (message); #elif UNITY_ANDROID if (_android != null) { _android.Call("androidBluetoothLog", message); } #endif } } public static BluetoothDeviceScript Initialize (bool asCentral, bool asPeripheral, Action action, Action<string> errorAction) { bluetoothDeviceScript = null; if (GameObject.Find("BluetoothLEReceiver") == null) { GameObject bluetoothLEReceiver = new GameObject("BluetoothLEReceiver"); bluetoothDeviceScript = bluetoothLEReceiver.AddComponent<BluetoothDeviceScript>(); if (bluetoothDeviceScript != null) { bluetoothDeviceScript.InitializedAction = action; bluetoothDeviceScript.ErrorAction = errorAction; Debug.Log("bluetoothDeviceScript != null"); } } if (Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.SendMessage ("OnBluetoothMessage", "Initialized"); } else { #if UNITY_IPHONE _iOSBluetoothLEInitialize (asCentral, asPeripheral); #elif UNITY_ANDROID if (_android == null) { AndroidJavaClass javaClass = new AndroidJavaClass ("com.shatalmic.unityandroidbluetoothlelib.UnityBluetoothLE"); _android = javaClass.CallStatic<AndroidJavaObject> ("getInstance"); } if (_android != null) _android.Call ("androidBluetoothInitialize", asCentral, asPeripheral); #endif } return bluetoothDeviceScript; } public static void DeInitialize (Action action) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DeinitializedAction = action; if (Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.SendMessage ("OnBluetoothMessage", "DeInitialized"); } else { #if UNITY_IPHONE _iOSBluetoothLEDeInitialize (); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothDeInitialize"); #endif } } public static void FinishDeInitialize () { GameObject bluetoothLEReceiver = GameObject.Find("BluetoothLEReceiver"); if (bluetoothLEReceiver != null) GameObject.Destroy(bluetoothLEReceiver); } public static void PauseMessages (bool isPaused) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLEPauseMessages (isPaused); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothPause"); #endif } } public static void ScanForPeripheralsWithServices (string[] serviceUUIDs, Action<string, string> action, Action<string, string, int, byte[]> actionAdvertisingInfo = null) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.DiscoveredPeripheralAction = action; bluetoothDeviceScript.DiscoveredPeripheralWithAdvertisingInfoAction = actionAdvertisingInfo; if (bluetoothDeviceScript.DiscoveredDeviceList != null) bluetoothDeviceScript.DiscoveredDeviceList.Clear (); } string serviceUUIDsString = null; if (serviceUUIDs != null && serviceUUIDs.Length > 0) { serviceUUIDsString = ""; foreach (string serviceUUID in serviceUUIDs) serviceUUIDsString += serviceUUID + "|"; serviceUUIDsString = serviceUUIDsString.Substring (0, serviceUUIDsString.Length - 1); } #if UNITY_IPHONE _iOSBluetoothLEScanForPeripheralsWithServices (serviceUUIDsString, (actionAdvertisingInfo != null)); #elif UNITY_ANDROID if (_android != null) { if (serviceUUIDsString == null) serviceUUIDsString = ""; _android.Call ("androidBluetoothScanForPeripheralsWithServices", serviceUUIDsString); } #endif } } public static void RetrieveListOfPeripheralsWithServices (string[] serviceUUIDs, Action<string, string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.RetrievedConnectedPeripheralAction = action; if (bluetoothDeviceScript.DiscoveredDeviceList != null) bluetoothDeviceScript.DiscoveredDeviceList.Clear (); } string serviceUUIDsString = serviceUUIDs.Length > 0 ? "" : null; foreach (string serviceUUID in serviceUUIDs) serviceUUIDsString += serviceUUID + "|"; // strip the last delimeter serviceUUIDsString = serviceUUIDsString.Substring (0, serviceUUIDsString.Length - 1); #if UNITY_IPHONE _iOSBluetoothLERetrieveListOfPeripheralsWithServices (serviceUUIDsString); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothRetrieveListOfPeripheralsWithServices", serviceUUIDsString); #endif } } public static void StopScan () { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLEStopScan (); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothStopScan"); #endif } } public static void ConnectToPeripheral (string name, Action<string> connectAction, Action<string, string> serviceAction, Action<string, string, string> characteristicAction, Action<string> disconnectAction = null) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.ConnectedPeripheralAction = connectAction; bluetoothDeviceScript.DiscoveredServiceAction = serviceAction; bluetoothDeviceScript.DiscoveredCharacteristicAction = characteristicAction; bluetoothDeviceScript.ConnectedDisconnectPeripheralAction = disconnectAction; } #if UNITY_IPHONE _iOSBluetoothLEConnectToPeripheral (name); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothConnectToPeripheral", name); #endif } } public static void DisconnectPeripheral (string name, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DisconnectedPeripheralAction = action; #if UNITY_IPHONE _iOSBluetoothLEDisconnectPeripheral (name); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidBluetoothDisconnectPeripheral", name); #endif } } public static void ReadCharacteristic (string name, string service, string characteristic, Action<string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DidUpdateCharacteristicValueAction = action; #if UNITY_IPHONE _iOSBluetoothLEReadCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidReadCharacteristic", name, service, characteristic); #endif } } public static void WriteCharacteristic (string name, string service, string characteristic, byte[] data, int length, bool withResponse, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DidWriteCharacteristicAction = action; #if UNITY_IPHONE _iOSBluetoothLEWriteCharacteristic (name, service, characteristic, data, length, withResponse); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidWriteCharacteristic", name, service, characteristic, data, length, withResponse); #endif } } public static void SubscribeCharacteristic (string name, string service, string characteristic, Action<string> notificationAction, Action<string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction = notificationAction; bluetoothDeviceScript.DidUpdateCharacteristicValueAction = action; } #if UNITY_IPHONE _iOSBluetoothLESubscribeCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidSubscribeCharacteristic", name, service, characteristic); #endif } } public static void SubscribeCharacteristicWithDeviceAddress (string name, string service, string characteristic, Action<string, string> notificationAction, Action<string, string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) { bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicWithDeviceAddressAction = notificationAction; bluetoothDeviceScript.DidUpdateCharacteristicValueWithDeviceAddressAction = action; } #if UNITY_IPHONE _iOSBluetoothLESubscribeCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidSubscribeCharacteristic", name, service, characteristic); #endif } } public static void UnSubscribeCharacteristic (string name, string service, string characteristic, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.DidUpdateNotificationStateForCharacteristicAction = action; #if UNITY_IPHONE _iOSBluetoothLEUnSubscribeCharacteristic (name, service, characteristic); #elif UNITY_ANDROID if (_android != null) _android.Call ("androidUnsubscribeCharacteristic", name, service, characteristic); #endif } } public static void PeripheralName (string newName) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLEPeripheralName (newName); #endif } } public static void CreateService (string uuid, bool primary, Action<string> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.ServiceAddedAction = action; #if UNITY_IPHONE _iOSBluetoothLECreateService (uuid, primary); #endif } } public static void RemoveService (string uuid) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLERemoveService (uuid); #endif } } public static void RemoveServices () { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLERemoveServices (); #endif } } public static void CreateCharacteristic (string uuid, CBCharacteristicProperties properties, CBAttributePermissions permissions, byte[] data, int length, Action<string, byte[]> action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.PeripheralReceivedWriteDataAction = action; #if UNITY_IPHONE _iOSBluetoothLECreateCharacteristic (uuid, (int)properties, (int)permissions, data, length); #endif } } public static void RemoveCharacteristic (string uuid) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.PeripheralReceivedWriteDataAction = null; #if UNITY_IPHONE _iOSBluetoothLERemoveCharacteristic (uuid); #endif } } public static void RemoveCharacteristics () { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLERemoveCharacteristics (); #endif } } public static void StartAdvertising (Action action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.StartedAdvertisingAction = action; #if UNITY_IPHONE _iOSBluetoothLEStartAdvertising (); #endif } } public static void StopAdvertising (Action action) { if (!Application.isEditor) { if (bluetoothDeviceScript != null) bluetoothDeviceScript.StoppedAdvertisingAction = action; #if UNITY_IPHONE _iOSBluetoothLEStopAdvertising (); #endif } } public static void UpdateCharacteristicValue (string uuid, byte[] data, int length) { if (!Application.isEditor) { #if UNITY_IPHONE _iOSBluetoothLEUpdateCharacteristicValue (uuid, data, length); #endif } } }
using MinecraftLauncher.Model.Minecraft; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MinecraftLauncher.Services { /// <summary> /// Service which automaticaly saves and loads all ISaveables through a neat interface :) /// </summary> public interface ISettingsService { bool Loaded { get; } Task Save(); Task Load(); } }
using Assets.src.model; using ManusMachina; public class GestureController { #region Fields /// <summary> /// The bend threshold (above this we consider fingers bent). /// </summary> private const float BendThreshold = 0.4f; #endregion Fields #region Methods /// <summary> /// Returns the current made gesture. /// </summary> /// <param name="g">The glove that is making the gesture.</param> /// <returns></returns> public static IMoveGesture GetGesture(Glove g) { return DetermineGesture(g); } /// <summary> /// Determines the gesture. /// </summary> /// <param name="glove">The glove that is making the gesture.</param> /// <returns></returns> private static IMoveGesture DetermineGesture(Glove glove) { int bend = FingersBend(glove); if (bend == 5) return new GestureGrab(); else if (bend == 4 && glove.Fingers[0] < BendThreshold) return new GestureThumb(); else if (bend == 4 && glove.Fingers[4] < BendThreshold) return new GesturePinky(); else if (glove.Fingers[1] < 0.4f && glove.Fingers[2] < BendThreshold && bend == 3) return new GesturePoint(); else if (bend <= 1) return new GestureOpen(); else return new GestureNone(); } /// <summary> /// returns the number of bend fingers. /// </summary> /// <param name="glove">The glove used to determine the number of bend fingers.</param> /// <returns></returns> private static int FingersBend(Glove glove) { int fingersBent = 0; for (int i = 0; i < 5; i++) { if (glove.Fingers[i] >= BendThreshold) { fingersBent++; } } return fingersBent; } #endregion Methods }
//==================================================================== // ClassName : LiplisToneSetting // 概要 : 口調設定 // // // LiplisLive2D // Copyright(c) 2017-2018 sachin. All Rights Reserved. //==================================================================== using System.Collections.Generic; namespace Assets.Scripts.LiplisSystem.Model.Json { public class LiplisToneSetting { public List<ToneSetting> ToneList { get; set; } public LiplisToneSetting() { ToneList = new List<ToneSetting>(); } } public class ToneSetting { public int id { get; set; } public string name { get; set; } public string sentence { get; set; } public string befor { get; set; } public string after { get; set; } public string type { get; set; } } }
namespace SoftDeleteTest { public static class SoftDeleteTestDomainErrorCodes { /* You can add your business exception error codes here, as constants */ } }
using BLL.Request; using DLL.Models; using DLL.Repositories; using DLL.Wrapper; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Utility.Exceptions; using ViewModels.Request; namespace BLL.Services { public interface IDepartmentService { Task<Department> Insert(DepartmentRequestViewModel request); Task<PagedResponse<List<Department>>> GetAll(DepartmentPaginationViewModel model); Task<Department> GetSingle(int id); Task<Department> Delete(int id); Task<Department> Update(int id, DepartmentRequestViewModel dept); Task<bool> IsCodeExist(string code, int? id = 0); Task<bool> IsNameExist(string name, int? id = 0); } public class DepartmentService : IDepartmentService { private readonly IUnitOfWork _unitOfWork; public DepartmentService(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } public async Task<List<Department>> GetAll() { return await _unitOfWork.DepartmentRepository.GetList(); } public async Task<PagedResponse<List<Department>>> GetAll(DepartmentPaginationViewModel model) { return await _unitOfWork.DepartmentRepository.GetPagedDepartments(model); } public async Task<Department> GetSingle(int id) { var department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.DepartmentId == id); if (department == null) { throw new ApplicationValidationException("Department Not Found"); } return department; } public async Task<Department> Insert(DepartmentRequestViewModel request) { var department = new Department { Code = request.Code, Name = request.Name }; await _unitOfWork.DepartmentRepository.CreateAsync(department); if(await _unitOfWork.DepartmentRepository.SaveCompletedAsync()) { return department; } throw new ApplicationValidationException("Something went wrong"); } public async Task<Department> Update(int id, DepartmentRequestViewModel dept) { var department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.DepartmentId == id); if (department == null) { throw new ApplicationValidationException("Department Not Found"); } department.Code = dept.Code; department.Name = dept.Name; _unitOfWork.DepartmentRepository.Update(department); if (await _unitOfWork.DepartmentRepository.SaveCompletedAsync()) { return department; } throw new ApplicationValidationException("Something went wrong"); } public async Task<Department> Delete(int id) { var department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.DepartmentId == id); if (department == null) { throw new ApplicationValidationException("Department Not Found"); } _unitOfWork.DepartmentRepository.Delete(department); if (await _unitOfWork.DepartmentRepository.SaveCompletedAsync()) { return department; } throw new ApplicationValidationException("Something went wrong"); } public async Task<bool> IsCodeExist(string code, int? id = 0) { if (id != 0) { var department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.Code == code && x.DepartmentId != id); //if(dept.DepartmentId > 0) //{ // return false; //} //return true; if (department == null) { return true; } return false; } else { Department department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.Code == code); if (department == null) { return true; } return false; } } public async Task<bool> IsNameExist(string name, int? id = 0) { if (id != 0) { var department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.Name == name && x.DepartmentId != id); //if (!isDeptPresent) //{ // return true; //} if (department == null) { return true; } return false; } else { Department department = await _unitOfWork.DepartmentRepository.FindSingleAsync(x => x.Name == name); if (department == null) { return true; } return false; } } } }
namespace Belot.Engine.Tests.GameMechanics { using System.Collections.Generic; using Belot.Engine.Cards; using Belot.Engine.Game; using Belot.Engine.GameMechanics; using Belot.Engine.Players; using Xunit; public class IsBeloteAllowedTests { [Fact] public void AllTrumpsPlayingFirst() { var validAnnouncesService = new ValidAnnouncesService(); var hand = new CardCollection { Card.GetCard(CardSuit.Heart, CardType.Queen), Card.GetCard(CardSuit.Heart, CardType.King), Card.GetCard(CardSuit.Heart, CardType.Ace), }; var trick = new List<PlayCardAction>(); Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Heart, CardType.Queen))); Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Heart, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Heart, CardType.Ace))); } [Fact] public void AllTrumpsPlayingSecond() { var validAnnouncesService = new ValidAnnouncesService(); var hand = new CardCollection { Card.GetCard(CardSuit.Club, CardType.Queen), Card.GetCard(CardSuit.Club, CardType.King), Card.GetCard(CardSuit.Spade, CardType.Queen), Card.GetCard(CardSuit.Spade, CardType.King), Card.GetCard(CardSuit.Club, CardType.Ace), }; var trick = new List<PlayCardAction> { new PlayCardAction(Card.GetCard(CardSuit.Club, CardType.Jack)) }; Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Club, CardType.Queen))); Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Club, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Club, CardType.Ace))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Spade, CardType.Queen))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Spade, CardType.King))); } [Fact] public void TrumpsPlayingFirst() { var validAnnouncesService = new ValidAnnouncesService(); var hand = new CardCollection { Card.GetCard(CardSuit.Club, CardType.Queen), Card.GetCard(CardSuit.Club, CardType.King), Card.GetCard(CardSuit.Club, CardType.Ace), }; var trick = new List<PlayCardAction>(); Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.Clubs, trick, Card.GetCard(CardSuit.Club, CardType.Queen))); Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.Clubs, trick, Card.GetCard(CardSuit.Club, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Clubs, trick, Card.GetCard(CardSuit.Club, CardType.Ace))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Diamonds, trick, Card.GetCard(CardSuit.Club, CardType.Queen))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Diamonds, trick, Card.GetCard(CardSuit.Club, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Diamonds, trick, Card.GetCard(CardSuit.Club, CardType.Ace))); } [Fact] public void TrumpsPlayingSecond() { var validAnnouncesService = new ValidAnnouncesService(); var hand = new CardCollection { Card.GetCard(CardSuit.Club, CardType.Queen), Card.GetCard(CardSuit.Club, CardType.King), Card.GetCard(CardSuit.Club, CardType.Ace), }; var trick = new List<PlayCardAction> { new PlayCardAction(Card.GetCard(CardSuit.Club, CardType.Jack)) }; Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.Clubs, trick, Card.GetCard(CardSuit.Club, CardType.Queen))); Assert.True( validAnnouncesService.IsBeloteAllowed( hand, BidType.Clubs, trick, Card.GetCard(CardSuit.Club, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Clubs, trick, Card.GetCard(CardSuit.Club, CardType.Ace))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Diamonds, trick, Card.GetCard(CardSuit.Club, CardType.Queen))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Diamonds, trick, Card.GetCard(CardSuit.Club, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Diamonds, trick, Card.GetCard(CardSuit.Club, CardType.Ace))); } [Fact] public void NoTrumpsShouldNotAllowBelote() { var validAnnouncesService = new ValidAnnouncesService(); var hand = new CardCollection { Card.GetCard(CardSuit.Club, CardType.Queen), Card.GetCard(CardSuit.Club, CardType.King), Card.GetCard(CardSuit.Club, CardType.Ace), }; var trick = new List<PlayCardAction> { new PlayCardAction(Card.GetCard(CardSuit.Club, CardType.Jack)) }; Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.NoTrumps, trick, Card.GetCard(CardSuit.Club, CardType.Queen))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.NoTrumps, trick, Card.GetCard(CardSuit.Club, CardType.King))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.NoTrumps, trick, Card.GetCard(CardSuit.Club, CardType.Ace))); } [Fact] public void BeloteIsNotAllowedWhenNotHavingAKing() { var validAnnouncesService = new ValidAnnouncesService(); var hand = new CardCollection { Card.GetCard(CardSuit.Heart, CardType.Queen), Card.GetCard(CardSuit.Heart, CardType.Ace), }; var trick = new List<PlayCardAction>(); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.AllTrumps, trick, Card.GetCard(CardSuit.Heart, CardType.Queen))); Assert.False( validAnnouncesService.IsBeloteAllowed( hand, BidType.Hearts, trick, Card.GetCard(CardSuit.Heart, CardType.Queen))); } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace HW6MovieSharing.Migrations { public partial class moreuserinfo : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.RenameColumn( name: "RequestedBy", table: "BarrowRequest", newName: "RequestedByObjectIdentifier"); migrationBuilder.AddColumn<string>( name: "RequestedByEmailAddress", table: "BarrowRequest", nullable: true); migrationBuilder.AddColumn<string>( name: "RequestedByFirstName", table: "BarrowRequest", nullable: true); migrationBuilder.AddColumn<string>( name: "RequestedByLastName", table: "BarrowRequest", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "RequestedByEmailAddress", table: "BarrowRequest"); migrationBuilder.DropColumn( name: "RequestedByFirstName", table: "BarrowRequest"); migrationBuilder.DropColumn( name: "RequestedByLastName", table: "BarrowRequest"); migrationBuilder.RenameColumn( name: "RequestedByObjectIdentifier", table: "BarrowRequest", newName: "RequestedBy"); } } }
using PICSimulator.Helper; using System; using System.Collections.Generic; namespace PICSimulator.Model { class PICMemory { public const uint ADDR_INDF = 0x00; public const uint ADDR_TMR0 = 0x01; public const uint ADDR_PCL = 0x02; public const uint ADDR_STATUS = 0x03; public const uint ADDR_FSR = 0x04; public const uint ADDR_PORT_A = 0x05; public const uint ADDR_PORT_B = 0x06; public const uint ADDR_UNIMPL_A = 0x07; public const uint ADDR_PCLATH = 0x0A; public const uint ADDR_INTCON = 0x0B; public const uint ADDR_OPTION = 0x81; public const uint ADDR_TRIS_A = 0x85; public const uint ADDR_TRIS_B = 0x86; public const uint ADDR_UNIMPL_B = 0x87; public const uint ADDR_EECON1 = 0x88; public const uint ADDR_EECON2 = 0x89; public const uint STATUS_BIT_IRP = 7; // Unused in PIC16C84 public const uint STATUS_BIT_RP1 = 6; // Register Bank Selection Bit [1] (Unused in PIC16C84) public const uint STATUS_BIT_RP0 = 5; // Register Bank Selection Bit [0] public const uint STATUS_BIT_TO = 4; // Time Out Bit public const uint STATUS_BIT_PD = 3; // Power Down Bit public const uint STATUS_BIT_Z = 2; // Zero Bit public const uint STATUS_BIT_DC = 1; // Digit Carry Bit public const uint STATUS_BIT_C = 0; // Carry Bit public const uint OPTION_BIT_RBPU = 7; // PORT-B Pull-Up Enable Bit public const uint OPTION_BIT_INTEDG = 6; // Interrupt Edge Select Bit public const uint OPTION_BIT_T0CS = 5; // TMR0 Clock Source Select Bit public const uint OPTION_BIT_T0SE = 4; // TMR0 Source Edge Select Bit public const uint OPTION_BIT_PSA = 3; // Prescaler Alignment Bit public const uint OPTION_BIT_PS2 = 2; // Prescaler Rate Select Bit [2] public const uint OPTION_BIT_PS1 = 1; // Prescaler Rate Select Bit [1] public const uint OPTION_BIT_PS0 = 0; // Prescaler Rate Select Bit [0] public const uint INTCON_BIT_GIE = 7; // Global Interrupt Enable Bit public const uint INTCON_BIT_EEIE = 6; // EE Write Complete Interrupt Enable Bit public const uint INTCON_BIT_T0IE = 5; // TMR0 Overflow Interrupt Enable Bit public const uint INTCON_BIT_INTE = 4; // RB0/INT Interrupt Bit public const uint INTCON_BIT_RBIE = 3; // RB Port Change Interrupt Enable Bit public const uint INTCON_BIT_T0IF = 2; // TMR0 Overflow Interrupt Flag Bit public const uint INTCON_BIT_INTF = 1; // RB0/INT Interrupt Flag Bit public const uint INTCON_BIT_RBIF = 0; // RB Port Change Interrupt Flag Bit public delegate uint RegisterRead(uint Pos); public delegate void RegisterWrite(uint Pos, uint Value); private readonly Dictionary<uint, Tuple<RegisterRead, RegisterWrite>> SpecialRegisterEvents; private uint pc = 0; private uint[] register = new uint[0x100]; private PICTimer Timer; private PICInterruptLogic Interrupt; public PICMemory(PICTimer tmr, PICInterruptLogic il) { this.Timer = tmr; this.Interrupt = il; SpecialRegisterEvents = new Dictionary<uint, Tuple<RegisterRead, RegisterWrite>>() { #region Linked Register && PC //############################################################################## { ADDR_PCL, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p+0x80, v); UpdatePC(v); }) }, { ADDR_PCL + 0x80, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p-0x80, v); UpdatePC(v); }) }, //############################################################################## { ADDR_STATUS, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p+0x80, v); }) }, { ADDR_STATUS + 0x80, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p-0x80, v); }) }, //############################################################################## { ADDR_FSR, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p+0x80, v); }) }, { ADDR_FSR + 0x80, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p-0x80, v); }) }, //############################################################################## { ADDR_PCLATH, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p+0x80, v); }) }, { ADDR_PCLATH + 0x80, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p-0x80, v); }) }, //############################################################################## { ADDR_INTCON, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p+0x80, v); }) }, { ADDR_INTCON + 0x80, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); SetRegisterDirect(p-0x80, v); }) }, #endregion #region Unimplemented { ADDR_UNIMPL_A, Tuple.Create<RegisterRead, RegisterWrite>( (p) => 0, (p, v) => { /* NOP */ }) }, { ADDR_UNIMPL_B, Tuple.Create<RegisterRead, RegisterWrite>( (p) => 0, (p, v) => { /* NOP */ }) }, #endregion #region RB0/INT Interrupt + Port RB Interrupt { ADDR_PORT_B, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { Do_Interrupt_ADDR_PORT_B(v); SetRegisterDirect(p, v); }) }, #endregion #region Indirect Addressing { ADDR_INDF, Tuple.Create<RegisterRead, RegisterWrite>( (p) => { return (GetRegister(ADDR_FSR) % 0x80 == 0) ? (0) : (GetRegister(GetRegister(ADDR_FSR))); }, (p, v) => { if (GetRegister(ADDR_FSR) % 0x80 != 0) SetRegister(GetRegister(ADDR_FSR), v); }) }, { ADDR_INDF + 0x80, Tuple.Create<RegisterRead, RegisterWrite>( (p) => { return (GetRegister(ADDR_FSR) % 0x80 == 0) ? (0) : (GetRegister(GetRegister(ADDR_FSR))); }, (p, v) => { if (GetRegister(ADDR_FSR) % 0x80 != 0) SetRegister(GetRegister(ADDR_FSR), v); }) }, #endregion #region TMR0 { ADDR_TMR0, Tuple.Create<RegisterRead, RegisterWrite>( GetRegisterDirect, (p, v) => { SetRegisterDirect(p, v); Timer.clearPrescaler(); }) }, #endregion }; } #region Internal private void Do_Interrupt_ADDR_PORT_B(uint val) { uint changes = (register[ADDR_PORT_B] ^ val) & 0xFF; uint enabled = register[ADDR_TRIS_B]; // RB0/INT if (BinaryHelper.GetBit(changes, 0)) { if (BinaryHelper.GetBit(register[ADDR_OPTION], OPTION_BIT_INTEDG) && BinaryHelper.GetBit(val, 0)) // Rising Edge { Interrupt.AddInterrupt(PICInterruptType.PIT_RB0INT); } else if (!BinaryHelper.GetBit(register[ADDR_OPTION], OPTION_BIT_INTEDG) && !BinaryHelper.GetBit(val, 0)) // Falling Edge { Interrupt.AddInterrupt(PICInterruptType.PIT_RB0INT); } } // PORT RB if ((BinaryHelper.GetBit(changes, 4) && BinaryHelper.GetBit(enabled, 4)) || (BinaryHelper.GetBit(changes, 5) && BinaryHelper.GetBit(enabled, 5)) || (BinaryHelper.GetBit(changes, 6) && BinaryHelper.GetBit(enabled, 6)) || (BinaryHelper.GetBit(changes, 7) && BinaryHelper.GetBit(enabled, 7))) { Interrupt.AddInterrupt(PICInterruptType.PIT_PORTB); } } #endregion #region Getter/Setter public uint GetRegister(uint p) { if (SpecialRegisterEvents.ContainsKey(p)) { return SpecialRegisterEvents[p].Item1(p); } else { return GetRegisterDirect(p); } } public uint GetBankedRegister(uint p) { return GetRegister(p + GetBankOffset()); } public void SetRegister(uint p, uint n) { if (SpecialRegisterEvents.ContainsKey(p)) { SpecialRegisterEvents[p].Item2(p, n); } else { SetRegisterDirect(p, n); } } public void SetBankedRegister(uint p, uint n) { SetRegister(p + GetBankOffset(), n); } protected uint GetRegisterDirect(uint p) { return register[p]; } protected void SetRegisterDirect(uint p, uint n) { n %= 0x100; // Just 4 Safety register[p] = n; } public void SetRegisterBit(uint p, uint bitpos, bool newVal) { SetRegister(p, BinaryHelper.SetBit(GetRegister(p), bitpos, newVal)); } public void SetBankedRegisterBit(uint p, uint bitpos, bool newVal) { SetRegisterBit(p + GetBankOffset(), bitpos, newVal); } public bool GetRegisterBit(uint p, uint bitpos) { return BinaryHelper.GetBit(GetRegister(p), bitpos); } public bool GetBankedRegisterBit(uint p, uint bitpos) { return GetRegisterBit(p + GetBankOffset(), bitpos); } #endregion #region Helper public void HardResetRegister() { for (uint i = 0; i < 0xFF; i++) { SetRegister(i, 0x00); } SetRegister(ADDR_PCL, 0x00); SetRegister(ADDR_STATUS, 0x18); SetRegister(ADDR_PCLATH, 0x00); SetRegister(ADDR_INTCON, 0x00); SetRegister(ADDR_OPTION, 0xFF); SetRegister(ADDR_TRIS_A, 0x1F); SetRegister(ADDR_TRIS_B, 0xFF); SetRegister(ADDR_EECON1, 0x00); SetRegister(ADDR_EECON2, 0x00); } public void SoftResetRegister() { SetRegister(ADDR_PCL, 0x00); SetRegister(ADDR_PCLATH, 0x00); SetRegister(ADDR_INTCON, (GetRegister(ADDR_INTCON) & 0x01)); SetRegister(ADDR_OPTION, 0xFF); SetRegister(ADDR_TRIS_A, 0x1F); SetRegister(ADDR_TRIS_B, 0xFF); SetRegister(ADDR_EECON1, (GetRegister(ADDR_EECON1) & 0x08)); } private uint GetBankOffset() { return GetRegisterBit(ADDR_STATUS, STATUS_BIT_RP0) ? 0x80u : 0x00u; } #endregion #region Program Counter private void UpdatePC(uint value) { value &= 0xFF; // Only Low 8 Bit uint high = GetRegister(ADDR_PCLATH); high &= 0x1F; // Only Bit <0,1,2,3,4> high <<= 8; value = high | value; pc = value; SetRegisterDirect(ADDR_PCL, value & 0xFF); SetRegisterDirect(ADDR_PCL + 0x80, value & 0xFF); } public uint GetPC() { return pc; } public void SetPC(uint value) { pc = value; SetRegisterDirect(ADDR_PCL, value & 0xFF); SetRegisterDirect(ADDR_PCL + 0x80, value & 0xFF); } public void SetPC_11Bit(uint value) { value &= 0x7FF; // Only Low 11 Bit uint high = GetRegister(ADDR_PCLATH); high &= 0x18; // Only Bit <3,4> high <<= 8; value = high | value; pc = value; SetRegisterDirect(ADDR_PCL, value & 0xFF); SetRegisterDirect(ADDR_PCL + 0x80, value & 0xFF); } #endregion } }
using System; using System.Windows; using System.IO; using System.Windows.Input; using System.Windows.Media; using System.Media; using System.Windows.Media.Imaging; using System.Windows.Forms; using SDMClasses; namespace ShowDoMilhao { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { // Vetor de perguntas private Pergunta[] _perguntas = new Pergunta[120]; // Vetor com as perguntas selecionadas private Pergunta[] _perguntasSelecionadas = new Pergunta[10]; private Random R = new Random(); // Temporaziadores para criação de ações de segundo plano private Timer T = new Timer(); private Timer TTwo = new Timer(); private Timer TThree = new Timer(); // Stream relativa às falas do Silvio Santos private Stream SilvioSantos = Properties.Resources.sdm_intro; // Referência ao arquivo da música do show do milhão private Stream Musica = Properties.Resources.sdm; // Reprodutor de audio private SoundPlayer Player; private int _threadDelay; // Garante que o usuário não responda mais de uma vez private bool _respondeu; // Variavel Auxiliar para a animações private int _auxForAnimation; // Criador do jogo private string _criador; // Variavel reponsável pela ação "Aperte qualquer tecla continuar" private bool _canPressAnyKey; // Guarda a alternativa a escolha private byte _alternativaEscolhida; private ScoreManager _placar; // Jogador private Player _guest; // Número da pergunta private int _numeroDaPergunta = 1; // Getters e setters public int ThreadDelay { get { return this._threadDelay; } set { this._threadDelay = value; } } public string Criador { get { return "Pedro9558"; } } public int AuxForAnimation { get { return this._auxForAnimation; } set { this._auxForAnimation = value; } } public bool CanPressAnyKey { get { return this._canPressAnyKey; } set { this._canPressAnyKey = value; } } public bool Respondeu { get { return this._respondeu; } set { this._respondeu = value; } } public ScoreManager Placar { get { return this._placar; } set { this._placar = value; } } public Pergunta[] Perguntas { get { return this._perguntas; } } public Pergunta[] PerguntasSelecionadas { get { return this._perguntasSelecionadas; } } public Player Guest { get { return this._guest; } set { this._guest = value; } } public int NumeroDaPergunta { get { return this._numeroDaPergunta; } } public byte AlternativaEscolha { get { return this._alternativaEscolhida; } set { this._alternativaEscolhida = value; } } public MainWindow() { T.Tick += new EventHandler(AnimacaoInicial); this.ThreadDelay = 10; T.Interval = ThreadDelay; InitializeComponent(); Player = new SoundPlayer(SilvioSantos); T.InitializeLifetimeService(); T.Start(); this.Copyright.Content = "Criado por "+Criador+". Vídeo, Audios e Imagens by SBT Copyright © 2018 - Sistema Brasileiro de Televisão"; TThree.Tick += new EventHandler(AnimacaoPergunta); TThree.Interval = 8000; TTwo.Interval = 2000; TTwo.Tick += new EventHandler(EncerraJogo); } /// <summary> /// Faz a animação inicial da tela /// <param name="e"></param> /// <param name="sender"></param> /// </summary> private void AnimacaoInicial(object sender, EventArgs e) { switch(AuxForAnimation) { case 0: // Altera a opacidade do texto inicial aos poucos até ele ficar visivel if (Introducao.Opacity < 1) { Introducao.Opacity = Introducao.Opacity + 0.01; } else { T.Interval = 3000; AuxForAnimation++; } break; case 1: // Altera a opacidade do texto inicial aos poucos até ele ficar invisivel if (Introducao.Opacity > 0) { T.Interval = T.Interval != ThreadDelay ? ThreadDelay : T.Interval; Introducao.Opacity = Introducao.Opacity - 0.01; } else { T.Interval = 1500; AuxForAnimation++; } break; case 2: // Reproduz vídeo intro introVideo.Visibility = Visibility.Visible; introVideo.Play(); CanPressAnyKey = true; T.Interval = 41600; AuxForAnimation++; break; case 3: // Termina Reprodução do vídeo introVideo.Visibility = Visibility.Hidden; introVideo.Stop(); CanPressAnyKey = false; AuxForAnimation++; Player.Play(); T.Interval = 3000; break; case 4: // Toca música inicial de fundo AuxForAnimation++; Player.Stream = Musica; Player.PlayLooping(); break; case 5: // Exibe a logo do show do milhão T.Interval = ThreadDelay; if(SDMLogo.Opacity < 1) { SDMLogo.Opacity = SDMLogo.Opacity + 0.01; } else { T.Interval = 3000; AuxForAnimation++; } break; case 6: // Animação de pedir para o usuário apertar qualquer tecla T.Interval = 300; CanPressAnyKey = true; Titulo.Visibility = (Titulo.Visibility == Visibility.Hidden) ? Visibility.Visible : Visibility.Hidden; break; case 7: // Executado após o usuário apertar a tecla, logo desaparece e é perguntado o nome do usuário T.Interval = ThreadDelay; CanPressAnyKey = false; Titulo.Visibility = Visibility.Hidden; if (SDMLogo.Opacity > 0) { SDMLogo.Opacity = SDMLogo.Opacity - 0.01; }else { Titulo.Content = "Digite o seu nome abaixo:"; Titulo.Margin = new Thickness(106, 186, 0, 0); AuxForAnimation++; } break; case 8: // Mostra o menu de colocar o nome do participante Titulo.Visibility = Visibility.Visible; OKButton.Visibility = Visibility.Visible; InputNome.Visibility = Visibility.Visible; break; case 9: // Constroi o menu inicial do jogo OKButton.Visibility = Visibility.Hidden; InputNome.Visibility = Visibility.Hidden; MiniLogo.Visibility = Visibility.Visible; BIniciar.Visibility = Visibility.Visible; BPlacar.Visibility = Visibility.Visible; BSair.Visibility = Visibility.Visible; SilvioImage.Visibility = Visibility.Visible; // Cria o perfil do Jogador, caso não exista if(Guest == null) { Guest = new Player(InputNome.Text); Titulo.Content = "Bem-vindo(a) " + Guest.Nome + "!"; } else { Titulo.Visibility = Visibility.Visible; Titulo.Content = "Mais uma, " + Guest.Nome + "?"; } Titulo.Margin = new Thickness(152, 67, 0, 0); this.Width = 625.0; this.Height = 450.0; // Cria placar para o jogador caso não tenha sido criado if (Placar == null) { Placar = new ScoreManager(Guest, "SDMPlacar"); } this.AtualizarPlacar(); AuxForAnimation++; break; } } /// <summary> /// Handler caso alguma tecla do teclado seja apertada /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void keyPressed(object sender, System.Windows.Input.KeyEventArgs e) { // Testa se o usuário já pode apertar qualquer tecla if(CanPressAnyKey) { switch (AuxForAnimation) { case 3: T.Interval = 1; break; case 6: AuxForAnimation++; break; } } } /// <summary> /// Uma pequena animação do mostrador de perguntas /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void AnimacaoPergunta(object sender, EventArgs e) { // A animação ocorre conforme a visibilidade do indicador do número da pergunta if(IndicadorPergunta.Visibility == Visibility.Hidden) { // Esconde tudo da pergunta anterior Pergunta.Visibility = Visibility.Hidden; AlternativaA.Visibility = Visibility.Hidden; AlternativaB.Visibility = Visibility.Hidden; AlternativaC.Visibility = Visibility.Hidden; AlternativaD.Visibility = Visibility.Hidden; Pontos.Visibility = Visibility.Hidden; ImagemPergunta.Visibility = Visibility.Hidden; IndicadorPergunta.Content = "Pergunta " + NumeroDaPergunta; IndicadorPergunta.Margin = new Thickness(189, 161, 0, 0); IndicadorPergunta.Visibility = Visibility.Visible; // Executa um audio personalizado dependendo do número da pergunta switch(NumeroDaPergunta) { case 1: TThree.Interval = 8000; SilvioSantos = Properties.Resources.sdm_primeira_pergunta; break; case 2: TThree.Interval = 5000; SilvioSantos = Properties.Resources.sdm_segunda_pergunta; break; case 3: TThree.Interval = 5000; SilvioSantos = Properties.Resources.sdm_terceira_pergunta; break; case 4: TThree.Interval = 5000; SilvioSantos = Properties.Resources.sdm_quarta_pergunta; break; case 5: TThree.Interval = 6000; SilvioSantos = Properties.Resources.sdm_quinta_pergunta; break; case 6: TThree.Interval = 9000; SilvioSantos = Properties.Resources.sdm_sexta_pergunta; break; case 7: TThree.Interval = 6000; SilvioSantos = Properties.Resources.sdm_setima_pergunta; break; case 8: TThree.Interval = 5000; SilvioSantos = Properties.Resources.sdm_oitava_pergunta; break; case 9: TThree.Interval = 5000; SilvioSantos = Properties.Resources.sdm_nona_pergunta; break; case 10: TThree.Interval = 7000; SilvioSantos = Properties.Resources.sdm_ultima_pergunta; break; } Player.Stream = SilvioSantos; Player.Play(); } else { // Constroi a pergunta e exibe-a para o jogador Respondeu = false; this.ConstroiPergunta(); IndicadorPergunta.Visibility = Visibility.Hidden; Pergunta.Visibility = Visibility.Visible; AlternativaA.Visibility = Visibility.Visible; AlternativaB.Visibility = Visibility.Visible; AlternativaC.Visibility = Visibility.Visible; AlternativaD.Visibility = Visibility.Visible; Pontos.Visibility = Visibility.Visible; TThree.Stop(); } } /// <summary> /// Checa o nome do usuário para ver se é um nome válido /// Handler do botão "Pronto!" /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CheckName(object sender, RoutedEventArgs e) { if (InputNome.Text == null || InputNome.Text.Equals("")) { System.Windows.MessageBox.Show("Por favor, coloque um nome!", "Erro!", MessageBoxButton.OK, MessageBoxImage.Error); } else { System.Windows.MessageBox.Show("Bem-vindo(a) " + InputNome.Text+"!"); AuxForAnimation++; } } /// <summary> /// Constroi a proxima pergunta /// </summary> private void ConstroiPergunta() { AlternativaA.Background = new SolidColorBrush(Colors.Transparent); AlternativaB.Background = new SolidColorBrush(Colors.Transparent); AlternativaC.Background = new SolidColorBrush(Colors.Transparent); AlternativaD.Background = new SolidColorBrush(Colors.Transparent); Pontos.Content = "Placar: " + Guest.Pontuacao; this.Width = 750.0; // Dependendo de qual questão está, a tela mostra a questão conforme o número switch (NumeroDaPergunta) { case 1: Pergunta.Content = "1." + PerguntasSelecionadas[0].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[0].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[0].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[0].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[0].Alternativas[3]; // Testa se há uma imagem na questão if(PerguntasSelecionadas[0].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[0].LocalizacaoDaImagemDaPergunta); } break; case 2: Pergunta.Content = "2." + PerguntasSelecionadas[1].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[1].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[1].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[1].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[1].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[1].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[1].LocalizacaoDaImagemDaPergunta); } break; case 3: Pergunta.Content = "3." + PerguntasSelecionadas[2].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[2].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[2].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[2].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[2].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[2].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[2].LocalizacaoDaImagemDaPergunta); } break; case 4: Pergunta.Content = "4." + PerguntasSelecionadas[3].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[3].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[3].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[3].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[3].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[3].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[3].LocalizacaoDaImagemDaPergunta); } break; case 5: Pergunta.Content = "5." + PerguntasSelecionadas[4].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[4].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[4].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[4].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[4].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[4].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[4].LocalizacaoDaImagemDaPergunta); } break; case 6: Pergunta.Content = "6." + PerguntasSelecionadas[5].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[5].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[5].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[5].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[5].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[5].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[5].LocalizacaoDaImagemDaPergunta); } break; case 7: Pergunta.Content = "7." + PerguntasSelecionadas[6].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[6].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[6].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[6].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[6].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[6].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[6].LocalizacaoDaImagemDaPergunta); } break; case 8: Pergunta.Content = "8." + PerguntasSelecionadas[7].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[7].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[7].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[7].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[7].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[7].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[7].LocalizacaoDaImagemDaPergunta); } break; case 9: Pergunta.Content = "9." + PerguntasSelecionadas[8].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[8].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[8].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[8].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[8].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[8].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[8].LocalizacaoDaImagemDaPergunta); } break; case 10: Pergunta.Content = "10." + PerguntasSelecionadas[9].Questao; AlternativaA.Content = "A)" + PerguntasSelecionadas[9].Alternativas[0]; AlternativaB.Content = "B)" + PerguntasSelecionadas[9].Alternativas[1]; AlternativaC.Content = "C)" + PerguntasSelecionadas[9].Alternativas[2]; AlternativaD.Content = "D)" + PerguntasSelecionadas[9].Alternativas[3]; // Testa se há uma imagem na questão if (PerguntasSelecionadas[9].LocalizacaoDaImagemDaPergunta != null) { ImagemPergunta.Visibility = Visibility.Visible; ImagemPergunta.Source = new BitmapImage(PerguntasSelecionadas[9].LocalizacaoDaImagemDaPergunta); } break; } } /// <summary> /// Checa a resposta que o usuário deu /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void CheckAnswer(object sender, MouseButtonEventArgs e) { var Temp = 0; if (!Respondeu) { Temp = R.Next(1, 4); System.Windows.Controls.Label label = sender as System.Windows.Controls.Label; label.Foreground = new SolidColorBrush(Color.FromArgb(255, 255, 255, 255)); switch(Temp) { case 1: SilvioSantos = Properties.Resources.sdm_confirmar; break; case 2: SilvioSantos = Properties.Resources.sdm_confirmar2; break; case 3: SilvioSantos = Properties.Resources.sdm_confirmar3; break; } Player.Stream = SilvioSantos; Player.Play(); // Pede uma confirmação do usuário se ele quer escolher essa resposta if ((System.Windows.MessageBox.Show("Você tem certeza de sua resposta?", "Silvio Santos", MessageBoxButton.YesNo)) == MessageBoxResult.Yes) { Temp = R.Next(1, 3); Respondeu = true; // Testa se o usuário acertou a pergunta if (PerguntasSelecionadas[NumeroDaPergunta - 1].CheckAnswer(label.Content.ToString())) { switch(Temp) { case 1: SilvioSantos = Properties.Resources.sdm_acertou; break; case 2: SilvioSantos = Properties.Resources.sdm_acertou2; break; } Player.Stream = SilvioSantos; Player.Play(); label.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFF0FB0C")); label.Background = new SolidColorBrush(Colors.Green); // Determina quantos pontos serão dados dependendo do número da pergunta switch(NumeroDaPergunta) { case 1: case 2: case 3: case 4: case 5: Placar.AdicionarPontos(1000); break; case 6: Placar.AdicionarPontos(5000); break; case 7: case 8: Placar.AdicionarPontos(10000); break; case 9: Placar.AdicionarPontos(20000); break; case 10: Placar.AdicionarPontos(50000); break; } _numeroDaPergunta++; if (NumeroDaPergunta < 11) { TThree.Interval = 2000; TThree.Start(); } else { System.Windows.MessageBox.Show("Parabéns!!! Você acertou todas as perguntas!", "Parabéns! :-D"); TTwo.Interval = 4000; TTwo.Start(); } } else { switch (Temp) { case 1: SilvioSantos = Properties.Resources.sdm_errou; break; case 2: SilvioSantos = Properties.Resources.sdm_errou2; break; } Player.Stream = SilvioSantos; Player.Play(); label.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFF0FB0C")); label.Background = new SolidColorBrush(Colors.Red); // Mostra a resposta correta switch (PerguntasSelecionadas[NumeroDaPergunta - 1].IndexCorreto) { case 0: AlternativaA.Background = new SolidColorBrush(Colors.Green); break; case 1: AlternativaB.Background = new SolidColorBrush(Colors.Green); break; case 2: AlternativaC.Background = new SolidColorBrush(Colors.Green); break; case 3: AlternativaD.Background = new SolidColorBrush(Colors.Green); break; } TTwo.Interval = 4000; TTwo.Start(); } } else { label.Foreground = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFF0FB0C")); } } } /// <summary> /// Cria Perguntas pro questionário /// </summary> private void CriaPerguntas() { Perguntas[0] = new Pergunta("Em um triângulo retângulo, como é chamado a linha oposta ao ângulo reto?",new string[] { "Hipotenusa","Cateto Oposto","Cateto Adjacente","Cateto Reto" }, 0); Perguntas[1] = new Pergunta("Qual o nome do primeiro elemento quimico da tabela periodica?",new string[] { "Oxigênio","Carbono","Hidrogênio","Zinco" }, 2); Perguntas[2] = new Pergunta("Qual dessas moedas é a mais valiosa?",new string[] { "Rand","Real","Iene","Shekel" },1); Perguntas[3] = new Pergunta("Qual dessas palavras está escrita corretamente?", new string[] { "Meteorologia", "Espectativa", "Antiinflamatório", "Cabelereiro" }, 0); Perguntas[4] = new Pergunta("Quais países da américa tem o mesmo nome do que a capital?", new string[] { "Cuba e Venezuela", "México e Cuba", "Guiana e Guiana Francesa", "México e Guatemala" }, 3); Perguntas[5] = new Pergunta("Qual é a símbolo do enxofre?", new string[] { "E", "S", "X", "En" }, 1); Perguntas[6] = new Pergunta("Considerando que um carro percorre 1km em 50 segundos, Qual o valor de sua velocidade média?", new string[] { "60km/h","72km/h","80km/h","96km/h"}, 1); Perguntas[7] = new Pergunta("Quantos noves tem de 0 a 100?", new string[] { "18", "19", "20" , "21" }, 2); Perguntas[8] = new Pergunta("Qual destes órgãos faz parte do sistema digestivo?", new string[] { "Bexiga", "Pulmão", "Tireoide", "Duodeno" }, 3); Perguntas[9] = new Pergunta("Que animal é o Pateta?", new string[] { "Lontra", "Burro", "Cachorro", "Marmota" }, 2); Perguntas[10] = new Pergunta("A Osteoporose está ligada com a deficiência de qual vitamina?", new string[] { "B", "A", "K", "D" }, 3); Perguntas[11] = new Pergunta("Qual tecla é utilizada para atualizar uma página?", new string[] { "F5", "F12" , "F8" , "F9"}, 0); Perguntas[12] = new Pergunta("Qual desses elementos químicos é um gás nobre?", new string[] { "Kingium", "Xenônio", "Oxigênio", "Hidrogênio" }, 1); Perguntas[13] = new Pergunta("Das substâncias do cigarro, Qual dessas é a mais nociva?", new string[] { "Monóxido de Carbono", "Plutônio", "Nicotina", "Cianeto de Hidrogênio" }, 2); Perguntas[14] = new Pergunta("Qual destas alternativas é uma mudança do novo acordo ortográfico 2016?", new string[] { "Queda do acento diferencial", "Queda do cedilha", "Mudanças no \"porque\"", "Mudanças nas conjuções" }, 0); Perguntas[15] = new Pergunta("Qual dos estados abaixo tem sua capital com o mesmo nome?",new string[] { "Ceará", "Distrito Federal", "São Paulo" , "Paraná" }, 2); Perguntas[16] = new Pergunta("Em uma operação matemática, qual operação é resolvida primeiro?", new string[] { "Adição", "Subtração", "Divisão" , "Multiplicação" }, 3); Perguntas[17] = new Pergunta("O poeta romântico Álvares de Azevedo foi um poeta que se destacou em qual geração do Romantismo?", new string[] { "Primeira Geração - Nacionalista", "Segunda Geração - Mal do Século", "Terceira Geração - Condoreirista", "Quarta Geração - Simbolista" }, 1); Perguntas[18] = new Pergunta("A Claustrofobia é o medo de...", new string[] { "Lugares Abertos", "Lugares Fechados", "Enchente", "Avião" }, 1); Perguntas[19] = new Pergunta("Qual o valor da força gravitacional na lua?", new string[] { "10 m/s²", "1,6 m/s²", "3,2 m/s²", "17,2 m/s²" }, 1); Perguntas[20] = new Pergunta("Qual o animal é simbolizado pelo signo de Câncer?", new string[] { "Caranguejo" , "Carneiro" , "Leão" , "Lagarta" }, 0); Perguntas[21] = new Pergunta("Qual país sediou a primeira copa do mundo?", new string[] { "Uruguai", "Paraguai", "Argentina", "Brasil" }, 0); Perguntas[22] = new Pergunta("Que monstro da mitologia grega transformava qualquer um que olhasse para ele em pedra?", new string[] { "Medusa", "Cérbero" , "Hidra de Lerna", "Quimera" }, 0); Perguntas[23] = new Pergunta("É um país de Europa, No passado invadiu o Brasil, Terra das... Enfim, que país é esse?", new string[] { "Espanha", "França", "Itália", "Holanda" }, 3); Perguntas[24] = new Pergunta("Em um retângulo de base 5cm e altura de 3cm, qual o valor de sua área?", new string[] { "8 cm²", "15 cm²", "30 cm²", "34 cm²" }, 1); Perguntas[25] = new Pergunta("O que tem dentro das corcovas dos camelos?", new string[] { "Água", "Ar", "Gordura", "Osso" }, 2); Perguntas[26] = new Pergunta("Nos tempos antigos, o bronze era confudido com um outro metal muito parecido, só que de menor valor que o bronze. Que metal era esse?", new string[] { "Latão", "Cobre", "Zinco", "Estanho" }, 0); Perguntas[27] = new Pergunta("Qual o planeta mais quente do sistema solar?", new string[] { "Mercúrio", "Júpiter", "Vênus", "Marte" }, 2); Perguntas[28] = new Pergunta("Charles Darwin desenvolveu a Teoria da Evolução após navegar em qual navio que tinha nome de cachorro?", new string[] { "Poodle", "Chihuahua", "Bulldog", "Beagle" }, 3); Perguntas[29] = new Pergunta("Quantos decimetros cúbicos equivalem 1 litro?", new string[] { "1 dm³", "10 dm³", "100 dm³", "1000 dm³" }, 0); Perguntas[30] = new Pergunta("Qual é o único país cuja a bandeira não é retângular?", new string[] { "Nepal", "Senegal", "Filipinas", "Brunei" }, 0); Perguntas[31] = new Pergunta("Para se proteger de raios, você pode:", new string[] { "Se abrigar debaixo de uma árvore", "Abraçar os joelhos", "Ficar encostado em um carro", "Ir para um lugar aberto onde nada atraia raios" }, 1); Perguntas[32] = new Pergunta("Qual destes animais surgiu primeiro no planeta?", new string[] { "Tubarões", "Crocodilos", "Cobras", "Árvores" }, 0); Perguntas[33] = new Pergunta("Que presidente lançou um plano de metas cujo o lema era \"50 anos em 5\"?", new string[] { "Getúlio Vargas", "Fernando Collor", "Juscelino Kubitschek", "José Sarney" }, 2); Perguntas[34] = new Pergunta("O Ex-Presidente Carlos Luz detém o menor tempo de posse na presidência, que foi de:", new string[] { "4 dias", "1 semana", "2 semenas", "3 meses" }, 0); Perguntas[35] = new Pergunta("Do que eram feitos os travesseiros do Antigo Egito?", new string[] { "Peles de Animais", "Feixes de Trigo", "Sacos de Areia", "Pedra" }, 3); Perguntas[36] = new Pergunta("O que acontece com uma batata quando exposta no sol por muito tempo?", new string[] { "Ela fica seca e desmancha", "Ela fica verde e venenosa", "As raízes começam a brotar", "Ela fica dura e cinza feito pedra" }, 1); Perguntas[37] = new Pergunta("Por qual desses materiais o som viaja mais rápido?", new string[] { "Água", "Ar", "Gás Hélio", "Ferro" }, 3); Perguntas[38] = new Pergunta("O que é mais quente?", new string[] { "Um raio", "A superfície do Sol", "Lava de vulcão", "O núcleo da Terra" }, 0); Perguntas[39] = new Pergunta("Qual a temperatura aproximada em Celsius do chamado \"Zero absoluto\"?", new string[] { "-100°C", "-125°C", "-273°C", "-459°C" }, 2); Perguntas[40] = new Pergunta("Qual destes animais é o parente mais próximo do T-Rex?", new string[] { "Jacaré", "Dragão de Komodo", "Galinha", "Canguru" }, 2); Perguntas[41] = new Pergunta("BRIC é uma sigla que se refere a quais países?", new string[] { "Brasil, Rússia, Índia e China", "Brasil, Rússia, Inglaterra e China", "Bélgica, Rússia, Itália e China", "Bélgica, Rússia, Inglaterra e China" }, 0); Perguntas[42] = new Pergunta("Qual é o elemento que causou o acidente radioativo de Goiânia em 1987?", new string[] { "Carbono-14", "Urânio-235", "Polônio-210", "Césio-137" }, 3); Perguntas[43] = new Pergunta("Qual é o maior órgão do corpo humano?", new string[] { "Fígado", "Intestino", "Pulmão", "Pele" }, 3); Perguntas[44] = new Pergunta("Qual o elemento químico mais abundante no sol?", new string[] { "Hélio", "Hidrogênio", "Oxigênio", "Nitrogênio" }, 1); Perguntas[45] = new Pergunta("Com que frequência, em média, ocorre um eclipse total do sol?", new string[] { "18 meses", "12 anos", "28 anos", "57 anos" }, 0); Perguntas[46] = new Pergunta("Qual destas pessoas nunca foi indicada para um nobel da paz?", new string[] { "Hitler", "Kim Jong-il", "Stalin", "Mussolini" }, 1); Perguntas[47] = new Pergunta("Qual é o país que tem o maior número de pirâmides?", new string[] { "Sudão", "Egito", "México", "Índia" }, 0); Perguntas[48] = new Pergunta("O herói Thor de os Vingadores é uma referência a um deus de qual mitologia?", new string[] { "Grega", "Romana", "Nórdica", "Asteca" }, 2); Perguntas[49] = new Pergunta("Legalmente, um homem pode se casar com a irmã da sua viúva?", new string[] { "Sim", "Não", "Em alguns países, incluindo o Brasil", "Em alguns países, mas não no Brasil" }, 1); Perguntas[50] = new Pergunta("Como era chamada a máquina que criptografava as mensagens militares do nazistas durante a 2ª Guerra Mundial?", new string[] { "Heimlich", "Krebs", "Enigma", "Verboten" }, 2); Perguntas[51] = new Pergunta("Em um tocador de disco de vinil, do que são feitas as agulhas mais caras?", new string[] { "Ouro", "Tungstênio", "Cobre", "Diamante" }, 3); Perguntas[52] = new Pergunta("Qual foi o presidente que deu o Golpe do Estado Novo?", new string[] { "José Linhares", "João Goulart", "Getúlio Vargas", "Café Filho" }, 2); Perguntas[53] = new Pergunta("Qual o poder criado por D.Pedro II na Constituição de 1824?", new string[] { "Legislativo", "Executivo", "Judiciário", "Moderador" }, 3); Perguntas[54] = new Pergunta("Qual foi o Tratado assinado em 1810 por Dom João VI?", new string[] { "Tratado de Tordesilhas", "Tratado de Madrid", "Tratado de Comércio e Navegação", "Tratado de Porto Seguro" }, 2); Perguntas[55] = new Pergunta("Qual planta foi atingida por uma praga que causou a Grande Fome da Irlanda?", new string[] { "Beterraba", "Batata", "Milho", "Trigo" }, 1); Perguntas[56] = new Pergunta("Qual o maior deserto do mundo?", new string[] { "Saara", "Arábia", "Gobi", "Antártida" }, 3); Perguntas[57] = new Pergunta("Qual é a cor que fica do lado de fora do arco-íris?", new string[] { "Violeta", "Verde", "Amarelo", "Vermelho" }, 3); Perguntas[58] = new Pergunta("O que pesa mais?", new string[] { "1kg de Penas", "1kg de Ferro", "1kg de Madeira", "Mesmo Peso" }, 3); Perguntas[59] = new Pergunta("Qual é a unidade de medida do peso?", new string[] { "Kg", "N", "L", "M" }, 1); Perguntas[60] = new Pergunta("\"Só sei que nada sei\". Esta frase foi dita por qual filósofo?", new string[] { "Descartes", "Sócrates", "Platão", "Nietzsche" }, 1); Perguntas[61] = new Pergunta("Qual é o menor país do mundo?", new string[] { "Vaticano", "Mônaco", "Nauru", "Tuvalu" }, 0); Perguntas[62] = new Pergunta("Quanto tempo a luz do Sol demora para chegar à Terra?", new string[] { "1 segundo", "8 minutos", "1 hora", "1 dia" }, 1); Perguntas[63] = new Pergunta("Qual era o nome de Aleijadinho?", new string[] { "Alexandrino Francisco Lisboa", "Manuel Francisco Lisboa", "Francisco Manuel Lisboa", "Antônio Francisco Lisboa" }, 3); Perguntas[64] = new Pergunta("As pessoas de qual tipo sanguíneo são consideradas doadores universais?",new string[] { "Tipo A", "Tipo B", "Tipo AB", "Tipo O" },3); Perguntas[65] = new Pergunta("Normalmente, quantos litros de sangue uma pessoa tem?", new string[] { "De 2 a 4 litros", "De 4 a 6 litros", "De 6 a 8 litros", "De 8 a 10 litros" }, 1); Perguntas[66] = new Pergunta("Qual o número mínimo de jogadores numa partida de futebol?", new string[] { "5", "7", "9", "10" }, 1); Perguntas[67] = new Pergunta("Lady Di era o apelido de qual personalidade?", new string[] { "Joana d’Arc", "Grace Kelly", "Diana, a Princesa de Gales", "Chiquinha Gonzaga" }, 2); Perguntas[68] = new Pergunta("Qual é o maior ser vivo da Terra?", new string[] { "Um mamífero", "Um fungo", "Um réptil", "Um peixe" }, 1); Perguntas[69] = new Pergunta("Qual é a capital dos EUA?", new string[] { "Las Vegas", "California", "Nova York", "Washington D.C." }, 3); Perguntas[70] = new Pergunta("Qual é o maior osso do corpo humano?", new string[] { "Fêmur", "Rádio", "Tibia", "Estribo" }, 0); Perguntas[71] = new Pergunta("Qual mês do ano tem 28 dias?", new string[] { "Fevereiro", "Dezembro", "Nenhum", "Todos" }, 3); Perguntas[72] = new Pergunta("Qual é o alimento preferido do Garfield?", new string[] { "Macarronada", "Lasanha", "Rosbife", "Ração de Cachorro" }, 1); Perguntas[73] = new Pergunta("Em que ano começou, e em que ano terminou a guerra fria?", new string[] { "1947-1992", "1945-1992", "1945-1991", "1954-1992" }, 0); Perguntas[74] = new Pergunta("Qual foi a primeira civilização a habitar a Mesopotâmia?", new string[] { "Caldeus", "Babilôncos", "Sumérios", "Hititas" }, 2); Perguntas[75] = new Pergunta("Quem realmente descobriu o Brasil?", new string[] { "Duarte Pacheco Pereira", "Pedro Álvares Cabral", "D. Pedro II", "D. João IV" }, 0); Perguntas[76] = new Pergunta("Qual o nome do brasileiro conhecido como \"Pai da Aviação\"?", new string[] { "José de Alencar", "Santos Dumont", "Osvaldo Cruz", "Castro Alves" }, 1); Perguntas[77] = new Pergunta("Qual foi a revolução que alavancou a independência do Brasil?", new string[] { "Revolução Farroupilha", "Revolução Praieira", "Revolução Federalista", "Revolução Pernambucana" }, 3); Perguntas[78] = new Pergunta("O que é o Brexit?", new string[] { "Saída da Inglaterra do Reino Unido", "Saída do Reino Unido da União Europeia", "Fim da monarquia no Reino Unido", "Saída do Reino Unido da Zona Euro" }, 1); Perguntas[79] = new Pergunta("O acordo internacional de Paris, é um acordo que trata...", new string[] { "da restrição de imigrantes em Paris", "da proteção da França dos atentados terroristas", "do aquecimento global", "do Desenvolvimento Sustentável" }, 2); Perguntas[80] = new Pergunta("Por quanto tempo durou a Guerra dos 100 anos?", new string[] { "98 anos", "100 anos", "106 anos", "116 anos" }, 3); Perguntas[81] = new Pergunta("Como é chamado o nome das pinturas das cavernas?", new string[] { "Rupestre", "Moderna", "Geométrica", "Paleolitica" }, 0); Perguntas[82] = new Pergunta("Com quantos anos de casado se comemora a tradicional \"Bodas de Ouro\"?", new string[] { "25 anos", "50 anos", "75 anos", "100 anos" }, 1); Perguntas[83] = new Pergunta("Quantos elementos químicos a tabela periódica possui?", new string[] { "108", "109", "113", "118" }, 3); Perguntas[84] = new Pergunta("Quais os países que têm a maior e a menor expectativa de vida do mundo?", new string[] { "Austrália e Afeganistão", "Estados Unidos e Angola", "Japão e Serra Leoa", "Itália e Chade" }, 2); Perguntas[85] = new Pergunta("Para qual direção o ônibus abaixo está indo?", new string[] { "Esquerda", "Direita", "Inclinada", "Reta" }, 0, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio5.png")); Perguntas[86] = new Pergunta("Qual o valor da área do círculo abaixo?", new string[] { "28,26 cm²", "56,52 cm²", "254,34 cm²", "1017,36 cm²" }, 2, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio4.png")); Perguntas[87] = new Pergunta("O que as palavras abaixo tem em comum?", new string[] { "Ambas são substantivos", "Ambas são verbos", "Ambas estão no gênero masculino", "Nada" }, 1, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio2.png")); Perguntas[88] = new Pergunta("Qual o perimetro do retângulo abaixo?", new string[] { "24", "28", "40", "80" }, 1, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio3.png")); Perguntas[89] = new Pergunta("Qual o valor do ângulo X do triângulo abaixo?", new string[] { "90°", "60°", "45°", "30°" }, 3, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio1.png")); Perguntas[90] = new Pergunta("O que quer dizer a logo abaixo?", new string[] { "Playtone", "Youtube", "Vine", "Instagram" }, 1, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio6.png")); Perguntas[91] = new Pergunta("Quem é, atualmente(maio/2018), o técnico do Barcelona?", new string[] { "Ernesto Valverde", "Tito Vilanova", "Gerardo Martino", "José Mourinho" }, 0); Perguntas[92] = new Pergunta("Quando é celebrado o dia do Profissional de TI?", new string[] { "15 de Novembro", "17 de Novembro", "15 de Outubro", "19 de Outubro" }, 3); Perguntas[93] = new Pergunta("Como podemos definir uma sombra?", new string[] { "Ausência de luz", "Ausência de cor", "Ausência de eletricidade", "Ausência de vento" }, 0); Perguntas[94] = new Pergunta("Quem foi que criou o modelo conhecido como \"Pudim de Passas\"?", new string[] { "Bohr", "Tesla", "Rutherford", "Thomson" }, 3); Perguntas[95] = new Pergunta("Você tem um isqueiro, e os itens abaixo. Qual você acende primeiro?", new string[] { "A vela", "O lampião", "O monte de palha", "Nenhuma das alternativas" }, 3, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio7.png")); Perguntas[96] = new Pergunta("Qual desses países não faz fronteira com o Brasil?", new string[] { "Venezuela", "Equador", "Guiana", "Peru" }, 1); Perguntas[97] = new Pergunta("Com quantas linhas é possivel unir os pontos abaixo, sem tirar a caneta do papel?", new string[] { "3", "4", "5", "Desafio Impossivel" }, 1, new Uri("pack://application:,,,/ShowDoMilhao;component/Resources/sdm_exercicio8.png")); Perguntas[98] = new Pergunta("Qual mensagem o ET Bilu mandou para o mundo?", new string[] { "Beba água", "Procure a sabedoria", "Busquem conhecimento", "Encontre a verdade" }, 2); Perguntas[99] = new Pergunta("Qual assunto é muito polêmico, segundo um meme?", new string[] { "Crush", "Mamilos", "Religião", "Terrorismo" }, 2); Perguntas[100] = new Pergunta("Se um trem elétrico viaja em direção ao sul, em que direção vai a fumaça?", new string[] { "Norte", "Sul", "Pra Cima", "Nenhuma das Alternativas" }, 3); Perguntas[101] = new Pergunta("Quantas vezes é possível subtrair 10 de 100?", new string[] { "1 vez", "5 vezes", "10 vezes", "Infinitas Vezes" }, 0); Perguntas[102] = new Pergunta("A mãe de Maria tem 5 filhos: Lalá, Lelé, Lili, Loló e...?", new string[] { "Lila", "Lula", "Lulu", "Nenhuma das anteriores" }, 3); Perguntas[103] = new Pergunta("Qual era o monte mais alto do mundo antes do Everest ser descoberto?", new string[] { "Everest", "Kokoram-2", "Lhotse", "Makalu" }, 0); Perguntas[104] = new Pergunta("Em que ano o FC. Barcelona foi fundado?", new string[] { "1896", "1898", "1899", "1900" }, 2); Perguntas[105] = new Pergunta("Qual o ano do primeiro título Brasileiro do Corinthians?", new string[] { "1990", "1993", "1996", "1998" }, 0); Perguntas[106] = new Pergunta("Quantos anagramas tem a palavra: Ana?", new string[] { "1", "3", "10", "30" }, 1); Perguntas[107] = new Pergunta("Qual dos verbos abaixo está conjugado no gerúndio?", new string[] { "Entregar", "Respondido", "Acertando", "Errou" }, 2); Perguntas[108] = new Pergunta("Em que campeonato de 2016 o Palmeiras se sagrou campeão?", new string[] { "Campeonato Brasileiro", "Campeonato Paulista", "Copa Libertadores", "Nenhum" }, 0); Perguntas[109] = new Pergunta("Como é chamado o número que é representado por 0s e 1s?", new string[] { "Decimal", "Binário", "Hexadecimal", "Hexabinário" }, 1); Perguntas[110] = new Pergunta("\"Ser ponual\" Significa ser:", new string[] { "Atrasado", "Pontual", "Lento", "Certo"}, 1); Perguntas[111] = new Pergunta("Qual o plural de Guarda-Civil?", new string[] { "Guardas-Civil", "Guarda-Civis", "Guardas-Civis", "Guardas-Civeis"}, 2); Perguntas[112] = new Pergunta("Qual o presidente foi responsável pela construção de Brasilia?", new string[] { "Juscelino Kubitschek", "Jânio Quadros", "Getúlio Vargas", "Eurico Gaspar Dutra" }, 0); Perguntas[113] = new Pergunta("Como chamamos o sono do urso durante o inverno?", new string[] { "Preguiça", "Cochilo", "Desmaio", "Hibernação" }, 3); Perguntas[114] = new Pergunta("Qual foi o primeiro nome dado ao \"Show do Milhão\"?", new string[] { "Milionários", "Jogo do Milhão", "Ganhe um Milhão", "Sempre foi Show do Milhão" }, 1); Perguntas[115] = new Pergunta("Quem escreveu o livro \"O Guarani\"", new string[] { "Machado de Assis", "Olavo Billac", "José de Alencar", "Carlos Gomes" }, 2); Perguntas[116] = new Pergunta("Quem foi o amor de Isolda na obra medieval?", new string[] { "Romeu", "Hamlet", "Tristão", "Rigoletto" }, 2); Perguntas[117] = new Pergunta("Complete o dito popular: \"Todos os caminhos levam a...\"", new string[] { "Ruína", "Liberdade", "Nenhum Lugar", "Roma"}, 3); Perguntas[118] = new Pergunta("Em que século a Princesa Isabel assinou a Lei Áurea?", new string[] { "XVI", "XVII", "XVIII", "XIX" }, 3); Perguntas[119] = new Pergunta("Em qual estado brasileiro o pão de queijo é uma comida típica?", new string[] { "Minas Gerais", "Pernambuco", "Goiás", "Rio de Janeiro" }, 0); } /// <summary> /// Seleciona 10 perguntas aleatórias a serem usadas na rodada /// </summary> private void PrepararPerguntas() { int PerguntasPreparadas = 0; bool ConfirmarPergunta = false; for(var I = 0; PerguntasPreparadas < 10; I++) { var Index = R.Next(Perguntas.Length); for(var J = 0; J <= I && J < 10; J++) { // Testa se a pergunta já foi selecionada, para evitar repetição de perguntas if(PerguntasSelecionadas[J] == Perguntas[Index]) { ConfirmarPergunta = false; break; } else { ConfirmarPergunta = true; } } // Confirma que a pergunta não é repetida if(ConfirmarPergunta) { PerguntasSelecionadas[PerguntasPreparadas] = Perguntas[Index]; PerguntasPreparadas++; //Console.WriteLine("Pergunta " + I + ": " + PerguntasSelecionadas[PerguntasPreparadas].Questao); } } } /// <summary> /// Prepara o placar /// </summary> private void AtualizarPlacar() { // Evita clonagem de dados this.Scoreboard.Items.Clear(); foreach(Player usuario in Placar.GetPlacarOrdenado()) { this.Scoreboard.Items.Add(usuario); } this.Scoreboard.Items.Refresh(); } /// <summary> /// Encerra o jogo, salvando os dados /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void EncerraJogo(object sender, EventArgs e) { if(IndicadorPergunta.Visibility == Visibility.Hidden) { // Mostra quanto o jogador ganhou IndicadorPergunta.FontSize = 48.0; IndicadorPergunta.Margin = new Thickness(128, 171, 0, 0); IndicadorPergunta.Content = "Você ganhou R$" + Guest.Pontuacao + "!"; IndicadorPergunta.Visibility = Visibility.Visible; // Salva sua pontuação Placar.SalvarPontuacao(); // Silvio santos lhe deseja parabens caso você tenha ganhado! if(NumeroDaPergunta == 11) { SilvioSantos = Properties.Resources.sdm_parabens; Player.Stream = SilvioSantos; Player.Play(); } // Remove as perguntas e as alternativas Pergunta.Visibility = Visibility.Hidden; AlternativaA.Visibility = Visibility.Hidden; AlternativaB.Visibility = Visibility.Hidden; ImagemPergunta.Visibility = Visibility.Hidden; AlternativaC.Visibility = Visibility.Hidden; AlternativaD.Visibility = Visibility.Hidden; Pontos.Visibility = Visibility.Hidden; } else { // Mostra o menu AuxForAnimation = 9; IndicadorPergunta.FontSize = 48.0; // Reseta Pontuação Guest.Pontuacao = 0; // Atualiza o placar incluindo a nova pontuação this.AtualizarPlacar(); // Atualiza o número da pergunta de volta ao inicio _numeroDaPergunta = 1; IndicadorPergunta.Visibility = Visibility.Hidden; TTwo.Stop(); } } /// <summary> /// Handler dos botões do menu /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void MenuButtonClick(object sender, RoutedEventArgs e) { System.Windows.Controls.Button Botao = sender as System.Windows.Controls.Button; // Botão Iniciar if(Botao.Name.Equals("BIniciar")) { // Cria, caso não tenha sido criada as perguntas, e prepara as perguntas selecionando 10 aleatorias if(this.Perguntas[0] == null) { this.CriaPerguntas(); } this.PrepararPerguntas(); System.Windows.MessageBox.Show("Serão feitas 10 perguntas de múltipla escolha, onde na primeira rodada cada pergunta certa vale mais 1000 reais, na segundada rodada cada pergunta certa vale mais 10000 reais e a última pergunta vale 100000 reais! Preparado, "+ Guest.Nome+"?", "Como funciona?", MessageBoxButton.YesNo); Player.Stop(); System.Windows.MessageBox.Show("Ótimo, vamos começar!", "Perfeito!"); MiniLogo.Visibility = Visibility.Hidden; BIniciar.Visibility = Visibility.Hidden; SilvioImage.Visibility = Visibility.Hidden; BPlacar.Visibility = Visibility.Hidden; BSair.Visibility = Visibility.Hidden; Titulo.Visibility = Visibility.Hidden; TThree.Interval = 1; TThree.Start(); } // Botão do placar else if (Botao.Name.Equals("BPlacar")) { this.Height = 744.0; this.Width = 627.0; this.Copyright.Margin = new Thickness(0, 684, 0, 0); this.TelaPrincipal.Visibility = Visibility.Hidden; this.TelaPlacar.Visibility = Visibility.Visible; } // Botão de sair else if(Botao.Name.Equals("BSair")) { if((System.Windows.MessageBox.Show("Deseja sair do jogo?","Já vai embora?",MessageBoxButton.YesNo,MessageBoxImage.Information)) == MessageBoxResult.Yes) { Environment.Exit(0); } } else if (Botao.Name.Equals("VoltarMenu")) { this.TelaPlacar.Visibility = Visibility.Hidden; this.TelaPrincipal.Visibility = Visibility.Visible; this.Width = 625.0; this.Copyright.Margin = new Thickness(0, 390, 0, 0); this.Height = 450.0; } } // Muda a cor do background caso o item seja selecionado private void ItemSelected(object sender, System.Windows.Input.MouseEventArgs e) { if (!Respondeu) { System.Windows.Controls.Label L = sender as System.Windows.Controls.Label; L.Background = new SolidColorBrush(Colors.DarkRed); } } // Volta ao background padrão caso o item seja deselecionado private void ItemDeSelected(object sender, System.Windows.Input.MouseEventArgs e) { if (!Respondeu) { System.Windows.Controls.Label L = sender as System.Windows.Controls.Label; L.Background = new SolidColorBrush(Colors.Transparent); } } } }
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Web; namespace WebApplication2.Models { public class Medicine { public long MedicineId { get; set; } public string MedicineName { get; set; } public string Brand { get; set; } public long Price { get; set; } public long Quantity { get; set; } public DateTime? ExpiryDate {get; set;} public string Notes { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; using Ninject; using Dao.Mercadeo; namespace Blo.Mercadeo { public class CampaniaSucursalBlo : GenericBlo<crmCampaniaSucursal>, ICampaniaSucursalBlo { private ICampaniaSucursalDao _campaniaSucursalDao; public CampaniaSucursalBlo(ICampaniaSucursalDao campaniaSucursalDao) : base(campaniaSucursalDao) { _campaniaSucursalDao =campaniaSucursalDao; } } }
using System; using System.Collections.Generic; namespace AddressBook.ViewModel { public class CityGroupViewModel { public string City { get; set; } public List<AddressViewModel> Address { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; namespace NeuralNetworksLab1 { public class Point { public double X; public double Y; public int Class; public Point() { } public Point(double x, double y, int type) { X = x; Y = y; Class = type; } } }
using System; using System.Text.Json; using System.Text.Json.Serialization; namespace MCC.TwitCasting { public class DateTimeOffsetConverter : JsonConverter<DateTimeOffset> { public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => DateTimeOffset.FromUnixTimeSeconds(reader.GetInt64() / 1000); public override void Write(Utf8JsonWriter writer, DateTimeOffset dateTimeValue, JsonSerializerOptions options) => writer.WriteNumberValue(dateTimeValue.ToUnixTimeSeconds() * 1000); } }
using UnityEngine; namespace TypingGameKit { /// <summary> /// Triggers animations for an input sequence. /// </summary> public class InputSequenceAnimation : MonoBehaviour { [SerializeField] private Animator _animator = null; [SerializeField] protected InputSequence _sequence = null; private void Awake() { Debug.Assert(_animator != null, this); Debug.Assert(_sequence != null, this); _sequence.OnCompleted += OnCompleted; _sequence.OnInputRejected += OnInputFailed; _sequence.OnInputAccepted += OnInputSucceeded; _animator.Update(0); } private void OnCompleted(InputSequence _) { _animator.SetTrigger("Completed"); } private void OnInputFailed(InputSequence _) { _animator.SetTrigger("Failed"); } private void OnInputSucceeded(InputSequence sequence) { if (sequence.IsCompleted) { return; } _animator.SetTrigger("Succeeded"); } } }
using System; namespace ExamWork.Models { public class City : Entity { public string Name { get; set; } public Street Street { get; set; } public Guid StreetId { get; set; } } }
using System; using System.Threading.Tasks; using Lib.Net.Http.WebPush; using Microsoft.AspNetCore.Mvc; using Services.Abstractions; using Shared.Models.Other; namespace Api.Controllers { [Route("push-notifications-api")] public class PushNotificationsApiController : Controller { private readonly IPushSubscriptionStore _subscriptionStore; private readonly IPushNotificationService _notificationService; private readonly IPushNotificationsQueue _pushNotificationsQueue; private readonly ISoccerStore _soccerStore; public PushNotificationsApiController(IPushSubscriptionStore subscriptionStore, IPushNotificationService notificationService, IPushNotificationsQueue pushNotificationsQueue, ISoccerStore soccerStore) { _subscriptionStore = subscriptionStore; _notificationService = notificationService; _pushNotificationsQueue = pushNotificationsQueue; _soccerStore = soccerStore; } // GET push-notifications-api/public-key [HttpGet("public-key")] public ContentResult GetPublicKey() { return Content(_notificationService.PublicKey, "text/plain"); } // GET push-notifications-api/subscriptions?endpoint={endpoint} [HttpGet("subscriptions/{teamId}")] public async Task<IActionResult> GetSubscriptions(string endpoint, int teamId) { var subscription = await _subscriptionStore.GetSubscriptionAsync(endpoint, teamId); return Content((subscription != null).ToString(), "text/plain"); } // POST push-notifications-api/subscriptions [HttpPost("subscriptions/{teamId}")] public async Task<IActionResult> StoreSubscription([FromBody] PushSubscription subscription, int teamId) { await _subscriptionStore.StoreSubscriptionAsync(subscription, teamId); return NoContent(); } // DELETE push-notifications-api/subscriptions?endpoint={endpoint} [HttpDelete("subscriptions/{teamId}")] public async Task<IActionResult> DiscardSubscription(string endpoint, int teamId) { await _subscriptionStore.DiscardSubscriptionAsync(endpoint, teamId); return NoContent(); } // POST push-notifications-api/notifications [HttpPost("send")] public async Task<IActionResult> SendNotification() { await _soccerStore.SendMessagesForNewResults(); return NoContent(); } // POST push-notifications-api/notifications [HttpPost("send-todaysmatches")] public async Task<IActionResult> SendNotificationTodaysMatches() { await _soccerStore.SendMessagesForUpcomingGames(); return NoContent(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class VectPair { public Vector3 pos; public Vector3 color; public VectPair() { pos = new Vector3(0, 0, 0); color = new Vector3(0, 0, 0); } public VectPair(Vector3 startpos, Vector3 startcolor) { pos = startpos; color = startcolor; } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace ToyTwoToolbox { public class FileReader { public byte[] fstream; public int foffset; //public bool disableDefaultSeek; public FileReader(string path, bool disableSeek = false) { //disableDefaultSeek = disableSeek; fstream = File.ReadAllBytes(path); } public int length() { return fstream.Length; } public void read(byte[] array, ref int seekPTR, int count = 1, int offset = -1) { //Buffer.BlockCopy(fstream, (offset == -1) ? foffset : offset, array, 0, count); Buffer.BlockCopy(fstream, (offset != -1) ? offset : seekPTR, array, 0, count); seekPTR += count; } public byte[] readbytes(int count = 1, int offset = -1) { return _readbytes(ref foffset, count, offset); } public byte[] _readbytes(ref int seekPTR, int count = 1, int offset = -1) { checkInvalidSeek(ref seekPTR, ref offset); byte[] newbytes = new byte[count]; read(newbytes, ref seekPTR, count, offset); return newbytes; } public string readstring(int count = 1, int offset = -1) { return _readstring(ref foffset, count, offset); } public string _readstring(ref int seekPTR, int count = 1, int offset = -1) { checkInvalidSeek(ref seekPTR, ref offset); byte[] newbytes = new byte[count]; read(newbytes, ref seekPTR, count, offset); // gsjqFw2 byte[] decBytes4 = HttpServerUtility.UrlTokenDecode(s4); //if (BitConverter.IsLittleEndian) { Array.Reverse(newbytes); } //return HttpServerUtility.UrlTokenEncode(newbytes); return System.Text.Encoding.UTF8.GetString(newbytes).TrimEnd('\0'); } public int readint(int count = 1, int offset = -1) { return _readint(ref foffset, count, offset); } public int _readint(ref int seekPTR, int count = 1, int offset = -1) { checkInvalidSeek(ref seekPTR, ref offset); byte[] newbytes = new byte[count]; read(newbytes, ref seekPTR, count, offset); //if (swapEndian) { }//if (BitConverter.IsLittleEndian) { Array.Reverse(newbytes); } if (count > 1) { if (count < 3) { Array.Resize(ref newbytes, 4); return BitConverter.ToInt32(newbytes, 0); } else if (count < 5) { return BitConverter.ToInt32(newbytes, 0); } else { return -1; //dont fucking do this lol } } else { return newbytes[0]; } } public Single readflt(int count = 1, int offset = -1) { return _readflt(ref foffset, count, offset); } public Single _readflt(ref int seekPTR, int count = 1, int offset = -1) { checkInvalidSeek(ref seekPTR, ref offset); byte[] newbytes = new byte[count]; read(newbytes, ref seekPTR, count, offset); //if (BitConverter.IsLittleEndian) { Array.Reverse(newbytes); } if (count > 1) { if (count < 3) { Array.Resize(ref newbytes, 4); return BitConverter.ToSingle(newbytes, 0); } else if (count < 5) { return BitConverter.ToSingle(newbytes, 0); } else { return -1; //dont fucking do this lol } } else { return newbytes[0]; } } public void checkInvalidSeek(ref int seek, ref int offset) { //if (forceNoSeek == false && seek == true && offset != foffset) { // offset = foffset; //offset = (offset == -1) ? foffset : offset; // //if (offset != -1) { SessionManager.SMptr.SM("ARSoN ContractProtection: Prevented an attempt to seek read with an offset"); } //} } public void seek(int amount) { _seek(amount, ref foffset); } public void _seek(int amount, ref int seekPTR) { seekPTR += amount; if (seekPTR < 0) { seekPTR = 0; } if (seekPTR > fstream.Length) { seekPTR = fstream.Length; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; namespace Explorer { public partial class Explorer : WebBrowser { public Explorer() { InitializeComponent(); } [SuppressUnmanagedCodeSecurity] class NewExplorer : WebBrowser { [DllImport("shell32.dll")] private static extern int SHGetSpecialFolderLocation(IntPtr hwnd, int csidl, ref IntPtr ppidl); [DllImport("kernel32.dll")] private static extern uint LocalSize(IntPtr hMem); /// <summary> /// Navigate to a special folder. /// </summary> /// <param name="csidl">The CSIDL of the special folder.</param> public void Navigate2CSIDL(CSIDLValues csidl) { const int S_OK = 0; IntPtr pidl = IntPtr.Zero; if (SHGetSpecialFolderLocation(IntPtr.Zero, (int)csidl, ref pidl) == S_OK) { uint cbpidl = LocalSize(pidl); if (cbpidl > 0) { byte[] abpidl = new byte[cbpidl]; Marshal.Copy(pidl, abpidl, 0, ((int)cbpidl - 1)); object location = (object)abpidl; Marshal.FreeCoTaskMem(pidl); try { object nil = Type.Missing; ((SHDocVw.WebBrowser)base.ActiveXInstance).Navigate2(ref location, ref nil, ref nil, ref nil, ref nil); } catch (COMException exception) { if (exception.ErrorCode != -2147023673 /*Operation was canceled by the user*/) { throw; } } } } else { throw new ArgumentOutOfRangeException(); } } /// <summary> /// Returns the shell folder object displayed in the webbrowser control. /// </summary> public Shell32.Folder2 Folder { get { IShellFolderViewDual2 folderview = this.FolderView; if (folderview != null) { return folderview.Folder as Folder2; } else { return null; } } } /// <summary> /// Returns the shell folderview object displayed in the webbrowser control. /// </summary> public Shell32.IShellFolderViewDual2 FolderView { get { IShellFolderViewDual2 ret; ret = ((SHDocVw.WebBrowser)base.ActiveXInstance).Document as IShellFolderViewDual2; return ret; } } /// <summary> /// Tries to set the views to list views. /// </summary> /// <returns>Returns TRUE if operation was successful, otherwise returns FALSE</returns> public bool setViewToListView() { IShellFolderViewDual2 fview = this.FolderView; if (fview == null) return false; FolderviewMode viewmode = (FolderviewMode)(FolderviewMode.List); fview.CurrentViewMode = (uint)viewmode; return true; } } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using DotNetNuke.Entities.Modules.Actions; using DotNetNuke.UI.Modules; #endregion namespace DotNetNuke.UI.Containers { /// ----------------------------------------------------------------------------- /// Project : DotNetNuke /// Namespace: DotNetNuke.UI.Containers /// Class : IActionControl /// ----------------------------------------------------------------------------- /// <summary> /// IActionControl provides a common INterface for Action Controls /// </summary> /// ----------------------------------------------------------------------------- public interface IActionControl { ActionManager ActionManager { get; } IModuleControl ModuleControl { get; set; } event ActionEventHandler Action; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Cotizacion.Domain; using Cotizacion.Service.Interfaces; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; namespace Cotizacion.WebAPI.Controllers { [Route("api/[controller]")] [ApiController] public class CotizacionController : ControllerBase { private ICotizacionService _cotizacionService; public CotizacionController(ICotizacionService cotizacionService) { _cotizacionService = cotizacionService; } [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "dolar", "euro","real" }; } [HttpGet("{id}")] public ActionResult<CotizacionModel> Get(string id) { try { return _cotizacionService.GetByMoneda(id); } catch (Exception ex) { return NotFound(new { message = ex.Message }); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ClassLibrary.DAL; namespace ClassLibrary.Model { public class POIDTOSend : POIDTO { public int localID { get; set; } public string categoria { get; set; } public POIDTOSend() { } public POIDTOSend(POI poi) { this.PoiID = poi.PoiID; this.Nome = poi.Nome; this.Descricao = poi.Descricao; DatumContext db = new DatumContext(); this.localID = db.Locals.Find(poi.LocalID).LocalID; this.categoria = db.Categorias.Find(poi.CategoriaID).nome; this.duracaoVisita = poi.duracaoVisita; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Claims; namespace ClaimsGrabberWeb { public class SamlClaim { private ClaimsPrincipal _claimsPrincipal = new ClaimsPrincipal(); // Constructor used to set Claimsprincipal public SamlClaim() { ClaimsPrincipal claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal; _claimsPrincipal = claimsPrincipal; } // SamlClaim samlClaim = new SamlClaim(); //Dictionary<string, string> dictClaims = samlClaim.GetClaimsHashTable(claimTypes); // Returns a dictionary object for all the claims public Dictionary<string, string> GetClaimsHashTable() { Dictionary<string, string> returnDictionary = new Dictionary<string, string>(); //ClaimsPrincipal principal = HttpContext.Current.User as ClaimsPrincipal; if (null != _claimsPrincipal) { foreach (Claim claim in _claimsPrincipal.Claims) { returnDictionary.Add(claim.Type.ToString(), claim.Value.ToString()); } } return returnDictionary; } // Returns a dictionary object for claim types specifid in input list public Dictionary<string, string> GetClaimsHashTable(List<string> claimsDescriptors) { Dictionary<string, string> returnDictionary = new Dictionary<string, string>(); //ClaimsPrincipal principal = HttpContext.Current.User as ClaimsPrincipal; if (null != _claimsPrincipal) { foreach (Claim claim in _claimsPrincipal.Claims) { if (claimsDescriptors.Contains(claim.Type.ToString())) { returnDictionary.Add(claim.Type.ToString(), claim.Value.ToString()); } } } return returnDictionary; } //Returns the value for the specified type public string ReturnClaimValue(string ClaimDescription) { string claimValue = string.Empty; //ClaimsPrincipal principal = HttpContext.Current.User as ClaimsPrincipal; if (null != _claimsPrincipal) { foreach (Claim claim in _claimsPrincipal.Claims) { if (claim.Type == ClaimDescription) { claimValue = claim.Value; } } } if (string.IsNullOrEmpty(claimValue)) { return string.Empty; } else { return claimValue; } } // Checks to see if a claim type is in the SAML token // SamlClaim samlClaim = new SamlClaim(); // samlClaim.CheckClaimTypeIsPresent("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/email") public bool CheckClaimTypeIsPresent(string ClaimDescription) { if (null != _claimsPrincipal) { foreach (Claim claim in _claimsPrincipal.Claims) { if (claim.Type == ClaimDescription) { return true; } } } return false; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using Managers; public class PlayerController : MonoBehaviour { public float MovementSpeed = 5.0f; [SerializeField] private float _lookAtNpcTweenDuration = 0.5f; private float _e = .05f; public void OnTriggerEnter(Collider other) { if (other.CompareTag("NPC")) {/* var npcTransform = other.transform; transform.DOLookAt(npcTransform.position, _lookAtNpcTweenDuration);*/ } else if (other.CompareTag("Finish")) { EventManager.Instance.OnPlayingStateChanged.Invoke(GameManager.PlayingState.Won); } } private void Update() { if (GameManager.Instance.CurrentState == GameManager.PlayingState.Running) { float forwardWeight = Input.GetAxis("Vertical"); float turningWeight = Input.GetAxis("Horizontal"); var direction = new Vector3(turningWeight, 0f, forwardWeight); transform.Translate(direction * MovementSpeed * Time.deltaTime, Space.World); /*if (Mathf.Abs(forwardWeight) >= _e || Mathf.Abs(turningWeight) >= _e) transform.forward = direction;*/ } else { if (Input.GetButtonDown("A") || Input.GetKeyDown(KeyCode.K)) { EventManager.Instance.OnButtonPressed.Invoke(InputManager.ControllerButtons.A); } if (Input.GetButtonDown("B") || Input.GetKeyDown(KeyCode.L)) { EventManager.Instance.OnButtonPressed.Invoke(InputManager.ControllerButtons.B); } if (Input.GetButtonDown("X") || Input.GetKeyDown(KeyCode.J)) { EventManager.Instance.OnButtonPressed.Invoke(InputManager.ControllerButtons.X); } if (Input.GetButtonDown("Y") || Input.GetKeyDown(KeyCode.I)) { EventManager.Instance.OnButtonPressed.Invoke(InputManager.ControllerButtons.Y); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class HenDecisionTree : MonoBehaviour { public enum HenPersonalities { AGGRESSIVE, COWARD, PROTECTIVE, UNLIKABLE }; public enum HenStatus { CATCHINGUP, ENGAGING, FLEEING, GOINGTO, PROTECTING, ROAMING }; public HenPersonalities Personality; public HenStatus CurrentStatus; public float PushForce = 350f; private NavMeshAgent movAgent; public GameObject Rooster; private DecisionTree dt; private GameObject NearestChick; private GameObject NearestPlayer; public LayerMask HensLayer; private Collider[] NearbyHens = new Collider[7]; public LayerMask ChicksLayer; private Collider[] NearbyChicks = new Collider[7]; public LayerMask PlayersLayer; private Collider[] NearbyPlayers = new Collider[4]; private float AnimationTimer = HensParametersManager.AttackTime; // Use this for initialization void Start() { float RandomPersonality = Random.value; Debug.Log(gameObject.name + ": " + RandomPersonality); if (RandomPersonality < 0.2f) Personality = HenPersonalities.AGGRESSIVE; if (RandomPersonality >= 0.2f && RandomPersonality < 0.5f) Personality = HenPersonalities.COWARD; if (RandomPersonality >= 0.5f && RandomPersonality < 0.9f) Personality = HenPersonalities.PROTECTIVE; if (RandomPersonality >= 0.9f) Personality = HenPersonalities.UNLIKABLE; CurrentStatus = HenStatus.ROAMING; movAgent = GetComponent<NavMeshAgent>(); // DT Decisions DTDecision decAnimationStop = new DTDecision(AnimationStop); DTDecision decDistantFromRooster = new DTDecision(DistantFromRooster); DTDecision decPlayerInFOV = new DTDecision(PlayerInFOV); DTDecision decPlayerInAttackRange = new DTDecision(PlayerInAttackRange); DTDecision decChickInAttackRange = new DTDecision(ChickInAttackRange); DTDecision decNearerToTheChick = new DTDecision(NearerToTheChick); DTDecision decCowardHen = new DTDecision(CowardHen); DTDecision decUnlikableHen = new DTDecision(UnlikableHen); DTDecision decProtectiveHen = new DTDecision(ProtectiveHen); // DT Actions DTAction actWait = new DTAction(Wait); DTAction actChaseRooster = new DTAction(ChaseRooster); DTAction actFlee = new DTAction(Flee); DTAction actProtect = new DTAction(Protect); DTAction actEngageChick = new DTAction(EngageChick); DTAction actEngagePlayer = new DTAction(EngagePlayer); DTAction actChasePlayer = new DTAction(ChasePlayer); DTAction actRoam = new DTAction(Roam); // DT Links decAnimationStop.AddLink(true, actWait); decAnimationStop.AddLink(false, decDistantFromRooster); decDistantFromRooster.AddLink(true, actChaseRooster); decDistantFromRooster.AddLink(false, decPlayerInFOV); decPlayerInFOV.AddLink(true, decCowardHen); decPlayerInFOV.AddLink(false, decUnlikableHen); decPlayerInAttackRange.AddLink(true, actEngagePlayer); decPlayerInAttackRange.AddLink(false, decProtectiveHen); decChickInAttackRange.AddLink(true, actEngageChick); decChickInAttackRange.AddLink(false, actRoam); decNearerToTheChick.AddLink(true, actProtect); decNearerToTheChick.AddLink(false, actChasePlayer); decCowardHen.AddLink(true, actFlee); decCowardHen.AddLink(false, decPlayerInAttackRange); decUnlikableHen.AddLink(true, decChickInAttackRange); decUnlikableHen.AddLink(false, actRoam); decProtectiveHen.AddLink(true, decNearerToTheChick); decProtectiveHen.AddLink(false, actChasePlayer); // Setup DT dt = new DecisionTree(decAnimationStop); } private void Update() { dt.walk(); } //---------------------------------------------------------------- DT Decisions ---------------------------------------------------------------------- private object AnimationStop(object o) { return AnimationTimer <= HensParametersManager.AttackTime; } private object DistantFromRooster(object o) { return Vector3.Distance(Rooster.transform.position, transform.position) > 4f; } private object PlayerInFOV(object o) { if ((Personality == HenPersonalities.AGGRESSIVE && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenAggressiveFOV, NearbyPlayers, PlayersLayer) > 0) || Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenFOV, NearbyPlayers, PlayersLayer) > 0) { NearestPlayer = FindNearest(NearbyPlayers); return true; } else return false; } private object PlayerInAttackRange(object o) { return Vector3.Distance(NearestPlayer.transform.position, transform.position) <= HensParametersManager.HenAttackFOV; } private object ChickInAttackRange(object o) { NearestChick = FindNearest(NearbyChicks); return Vector3.Distance(NearestChick.transform.position, transform.position) <= HensParametersManager.HenAttackFOV; } private object NearerToTheChick(object o) { NearestChick = FindNearest(NearbyChicks); return Vector3.Distance(transform.position, NearestChick.transform.position) < Vector3.Distance(NearestPlayer.transform.position, NearestChick.transform.position); } private object CowardHen(object o) { return Personality == HenPersonalities.COWARD && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenCowardFOV, NearbyHens, HensLayer) <= 1; } private object UnlikableHen(object o) { return Personality == HenPersonalities.UNLIKABLE && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenProtectiveFOV, NearbyChicks, ChicksLayer) > 0; } private object ProtectiveHen(object o) { return Personality == HenPersonalities.PROTECTIVE && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenProtectiveFOV, NearbyChicks, ChicksLayer) > 0; } //---------------------------------------------------------------- DT Actions ---------------------------------------------------------------------- private object Wait(object o) { CurrentStatus = HenStatus.ENGAGING; movAgent.SetDestination(transform.position); AnimationTimer += Time.deltaTime; return null; } private object ChaseRooster(object o) { CurrentStatus = HenStatus.CATCHINGUP; movAgent.SetDestination(Rooster.transform.position); movAgent.speed = 5f; return null; } private object ChasePlayer(object o) { CurrentStatus = HenStatus.GOINGTO; movAgent.speed = 3.5f; if (Vector3.Distance(transform.position, NearestPlayer.transform.position) > 0.5f) movAgent.SetDestination(NearestPlayer.transform.position); else transform.LookAt(NearestPlayer.transform.position); return null; } private object Flee(object o) { CurrentStatus = HenStatus.FLEEING; Vector3 EscapeDirection = transform.position - NearestPlayer.transform.position; movAgent.SetDestination(transform.position + (EscapeDirection.normalized) / 2f); movAgent.speed = 3.5f; return null; } private object Protect(object o) { CurrentStatus = HenStatus.PROTECTING; GetComponent<ProtectBehaviour>().ExecuteBehaviour(NearestChick); return null; } private object EngagePlayer(object o) { AnimationTimer = 0; CurrentStatus = HenStatus.ENGAGING; NearestPlayer.GetComponent<Rigidbody>().AddForce(transform.forward * PushForce, ForceMode.Impulse); NearestPlayer.GetComponent<Rigidbody>().AddForce(transform.up * PushForce, ForceMode.Impulse); transform.LookAt(NearestPlayer.transform); return null; } private object EngageChick(object o) { AnimationTimer = 0; CurrentStatus = HenStatus.ENGAGING; NearestChick.GetComponent<Rigidbody>().AddForce(transform.forward * PushForce, ForceMode.Impulse); NearestChick.GetComponent<Rigidbody>().AddForce(transform.up * PushForce, ForceMode.Impulse); transform.LookAt(NearestChick.transform); return null; } private object Roam(object o) { CurrentStatus = HenStatus.ROAMING; movAgent.speed = 2.5f; GetComponent<RoamingBehaviour>().ExecuteBehaviour(Rooster); return null; } private GameObject FindNearest(Collider[] Neighborgs) { float distance = 0f; float nearestDistance = float.MaxValue; GameObject NearestElement = null; foreach (Collider NearbyElement in Neighborgs) { if (NearbyElement != null && NearbyElement.gameObject != gameObject) { distance = Vector3.Distance(NearbyElement.transform.position, transform.position); if (distance < nearestDistance) { nearestDistance = distance; NearestElement = NearbyElement.gameObject; } } } return NearestElement; } /* Update is called once per frame void Update() { if (timer < 2f) timer += Time.deltaTime; if (timer > HensParametersManager.AttackTime) { if (Vector3.Distance(Rooster.transform.position, transform.position) > 5f) { CurrentStatus = HenStatus.CATCHINGUP; CatchUp(); } else { if ((Personality == HenPersonalities.AGGRESSIVE && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenAggressiveFOV, NearbyPlayers, PlayersLayer) > 0) || Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenFOV, NearbyPlayers, PlayersLayer) > 0) { NearestPlayer = FindNearest(NearbyPlayers); if ((Personality == HenPersonalities.PROTECTIVE && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenProtectiveFOV, NearbyChicks, ChicksLayer) > 0)) { NearestChick = FindNearest(NearbyChicks); if (Vector3.Distance(transform.position, NearestChick.transform.position) < Vector3.Distance(NearestPlayer.transform.position, NearestChick.transform.position)) { if (Vector3.Distance(NearestPlayer.transform.position, transform.position) > HensParametersManager.HenAttackFOV) { CurrentStatus = HenStatus.PROTECTING; GetComponent<ProtectBehaviour>().ExecuteBehaviour(NearestChick); } else { timer = 0; CurrentStatus = HenStatus.ENGAGING; GetComponent<EngageBehaviour>().ExecuteBehaviour(NearestPlayer); } } else { if (Vector3.Distance(NearestPlayer.transform.position, transform.position) > HensParametersManager.HenAttackFOV) { CurrentStatus = HenStatus.GOINGTO; GetComponent<GoToBehaviour>().ExecuteBehaviour(NearestPlayer); } else { timer = 0; CurrentStatus = HenStatus.ENGAGING; GetComponent<EngageBehaviour>().ExecuteBehaviour(NearestPlayer); } } } else if ((Personality == HenPersonalities.UNLIKABLE && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenProtectiveFOV, NearbyChicks, ChicksLayer) > 0)) { NearestChick = FindNearest(NearbyChicks); if (Vector3.Distance(NearestChick.transform.position, transform.position) > HensParametersManager.HenAttackFOV) { CurrentStatus = HenStatus.GOINGTO; GetComponent<GoToBehaviour>().ExecuteBehaviour(NearestChick); } else { timer = 0; CurrentStatus = HenStatus.ENGAGING; GetComponent<EngageBehaviour>().ExecuteBehaviour(NearestChick); } } else { if ((Personality == HenPersonalities.COWARD) && Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenCowardFOV, NearbyHens, HensLayer) <= 1) { CurrentStatus = HenStatus.FLEEING; GetComponent<FleeBehaviour>().ExecuteBehaviour(NearestPlayer); } else { if (Vector3.Distance(NearestPlayer.transform.position, transform.position) > HensParametersManager.HenAttackFOV) { CurrentStatus = HenStatus.GOINGTO; GetComponent<GoToBehaviour>().ExecuteBehaviour(NearestPlayer); } else { timer = 0; CurrentStatus = HenStatus.ENGAGING; GetComponent<EngageBehaviour>().ExecuteBehaviour(NearestPlayer); } } } } else { Physics.OverlapSphereNonAlloc(transform.position, HensParametersManager.HenFOV, NearbyHens, HensLayer); if(CurrentStatus != HenStatus.ROAMING) GetComponent<RoamingBehaviour>().ResetDirection(); CurrentStatus = HenStatus.ROAMING; GetComponent<RoamingBehaviour>().ExecuteBehaviour(Rooster); } } } }*/ }
using Android.App; using Android.Runtime; using Microsoft.Practices.Unity; using Points.Shared.Services; using System; namespace Points.Droid { [Application] public class App : Application { public static UnityContainer Container { get; set; } public App(IntPtr h, JniHandleOwnership jho) : base(h, jho) { } public override void OnCreate() { Container = new UnityContainer(); Container.RegisterInstance<IPlacesService>(Container.Resolve<PlacesService>()); Container.RegisterInstance<IPointsService>(Container.Resolve<PointsService>()); base.OnCreate(); } } }
namespace TeamBuilder.Data.Configurations { using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.ModelConfiguration; using TeamBuilder.Models; public class UserConfiguration : EntityTypeConfiguration<User> { public UserConfiguration() { this.Property(u => u.Username).IsRequired(); this.Property(u => u.Password).IsRequired(); this.Property(u => u.Username) .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation( new IndexAttribute("IX_Users_Username", 1) { IsUnique = true })).HasMaxLength(25); this.Property(u => u.Username) .HasMaxLength(25); this.Property(u => u.FirstName) .HasMaxLength(25); this.Property(u => u.LastName) .HasMaxLength(25); this.Property(u => u.Password) .HasMaxLength(30) .IsRequired(); this.HasMany(u => u.CreatedTeams) .WithRequired(t => t.Creator) .WillCascadeOnDelete(false); this.HasMany(u => u.CreatedEvents) .WithRequired(t => t.Creator) .WillCascadeOnDelete(false); this.HasMany(u => u.Teams) .WithMany(t => t.Members) .Map( ca => { ca.MapLeftKey("UserId"); ca.MapRightKey("TeamId"); ca.ToTable("UserTeams"); }); this.HasMany(u => u.ReceivedInvitations) .WithRequired(i => i.InvitedUser) .WillCascadeOnDelete(false); } } }
using Mccole.Geodesy.Extension; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace Mccole.Geodesy.UnitTesting.Extention { [TestClass] public class FloatToleranceExtension_Tests { [TestMethod] public void WithinTolerance_Default_No_Assert() { double value = 1D; double obj = value + FloatToleranceExtension.DefaultTolerance; bool result = FloatToleranceExtension.WithinTolerance(value, obj); Assert.IsFalse(result); } [TestMethod] public void WithinTolerance_Default_Yes_Assert() { double value = 1D; double obj = value + (FloatToleranceExtension.DefaultTolerance / 2); bool result = FloatToleranceExtension.WithinTolerance(value, obj); Assert.IsTrue(result); } [TestMethod] public void WithinTolerance_No_Assert() { double tolerance = 0.001; double value = 1D; double obj = value + (tolerance * 2); bool result = FloatToleranceExtension.WithinTolerance(value, obj, tolerance); Assert.IsFalse(result); } [TestMethod] public void WithinTolerance_Yes_Assert() { double tolerance = 0.001; double value = 1D; double obj = value + (tolerance / 2); bool result = FloatToleranceExtension.WithinTolerance(value, obj, tolerance); Assert.IsTrue(result); } } }
 namespace Opbot.Core.Tasks { interface IPipelineTask<TIn, TResult> { TResult Execute(TIn input); } }
using HINVenture.Shared.Models; using HINVenture.Shared.Models.Entities; using HINVenture.Shared.Models.ViewModels; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.IdentityModel.Tokens; using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Text; using System.Threading.Tasks; namespace HINVenture.Server.Controllers { [Route("api/[controller]")] [ApiController] public class LoginController : ControllerBase { private readonly IConfiguration _configuration; private readonly UserManager<ApplicationUser> _userManager; public LoginController(IConfiguration configuration, UserManager<ApplicationUser> userManager) { _configuration = configuration; _userManager = userManager; } [HttpPost] public async Task<IActionResult> Login([FromBody] LoginModel login) { var user = await _userManager.FindByNameAsync(login.Email); if (user == null) return BadRequest(new LoginResult { Successful = false, Error = "Username and password are invalid." }); var result = await _userManager.CheckPasswordAsync(user, login.Password); if (!result) return BadRequest(new LoginResult { Successful = false, Error = "Username and password are invalid." }); var roles = await _userManager.GetRolesAsync(user); var claims = new List<Claim>(); claims.Add(new Claim(ClaimTypes.Name, login.Email)); foreach (var role in roles) { claims.Add(new Claim(ClaimTypes.Role, role)); } var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JwtSecurityKey"])); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var expiry = DateTime.Now.AddDays(Convert.ToInt32(_configuration["JwtExpiryInDays"])); var token = new JwtSecurityToken( _configuration["JwtIssuer"], _configuration["JwtAudience"], claims, expires: expiry, signingCredentials: creds ); return Ok(new LoginResult { Successful = true, Token = new JwtSecurityTokenHandler().WriteToken(token) }); } } }
namespace TheatreDatabase.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; internal sealed class Configuration : DbMigrationsConfiguration<TheatreDatabase.TheatreContext> { public Configuration() { AutomaticMigrationsEnabled = true; } protected override void Seed(TheatreDatabase.TheatreContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. } } public class AddConstraint : Migration { protected override void Up (MigrationBuilder builder) { builder.Sql(@"ALTER TABLE Auditoriums ADD CONSTRAINT CK_NumOfSeats CHECK ((NumberOfAvailableSeats > 0) AND (NumberOfAvailableSeats < NumberOfSeats))"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AmDmAnalogProject.Models.Entities { public class Artist { public Artist() { Songs = new List<Song>(); } public int Id { get; set; } public string Name { get; set; } public string PictureUrl { get; set; } public string Biography { get; set; } public int SongsCount { get; set; } public int ViewsCount { get; set; } public string PageUrl { get; set; } public virtual List<Song> Songs { get; set; } } }
namespace BlackPearl.Xamarin { public class Image { public byte[] Bytes { get; set; } } }
// // SharedAbiTests.cs: Test cases that are shared by all ABIs // // Author: // Alexander Corrado (alexander.corrado@gmail.com) // // Copyright (C) 2010 Alexander Corrado // using System; using NUnit.Framework; using Mono.VisualC.Interop; using Mono.VisualC.Interop.ABI; using Tests.Support; namespace Tests { public class SharedAbiTests { protected CppLibrary test_lib { get; private set; } protected IVirtualMethodTestClass virtual_test_class { get; private set; } protected SharedAbiTests (CppAbi abi) { this.test_lib = new CppLibrary ("CPPTestLib", abi); this.virtual_test_class = test_lib.GetClass<IVirtualMethodTestClass> ("VirtualMethodTestClass"); CppNUnitAsserts.Init (); } [Test] public void TestVirtualMethods () { CppInstancePtr vmtc = VirtualMethodTestClass.Create (); virtual_test_class.V0 (vmtc, 1, 2, 3); VirtualMethodTestClass.Destroy (vmtc); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class Spawning : MonoBehaviour { public static GameObject _Target; public GameObject Mobs; public List<GameObject> EnemyType; public GameObject MidBoss; public GameObject BigBoss; public GameObject LastBossMobs; public GameObject LastBoss; public GameObject VinAura; public int MobAmount; public int LastMobAmount; public int MidBossAmount; public int BigBossAmount; public List<Vector3> SpawnPoint= new List<Vector3>(); public GameObject[] SpawnPointPlacement; public GameObject[] MBSpawnPointPlacement; public List<Vector3> MBSpawnPoint= new List<Vector3>(); // Use this for initialization void Start () { EnemyType.Add(Resources.Load("Enemies/Mobs/Enemy")as GameObject); EnemyType.Add(Resources.Load("Enemies/Mobs/Enemey-Wrath-Mob")as GameObject); _Target = GameObject.FindGameObjectWithTag ("Player"); MobAmount = 0; MidBossAmount = 25; BigBossAmount = 7; // Mobs = GameObject.FindGameObjectWithTag("MobEnemy"); // // EnemyType = GameObject.FindGameObjectsWithTag("MobEnemy"); SpawnPointPlacement = GameObject.FindGameObjectsWithTag("Enemy_Spawn"); MBSpawnPointPlacement = GameObject.FindGameObjectsWithTag("MB_Enemy_Spawn"); MidBoss = GameObject.FindGameObjectWithTag("MidBossEnemy"); BigBoss= GameObject.FindGameObjectWithTag("BigBossEnemy"); LastBoss = GameObject.FindGameObjectWithTag("LastBossEnemy"); if (SpawnPoint.Capacity == 0) { for (int x = 0; x < SpawnPointPlacement.Length; x++) { SpawnPoint.Add (SpawnPointPlacement [x].transform.position); } } if (MBSpawnPoint.Capacity == 0) { for (int x = 0; x < MBSpawnPointPlacement.Length; x++) { MBSpawnPoint.Add (MBSpawnPointPlacement [x].transform.position); } } } // Update is called once per frame void Update () { _Target = GameObject.FindGameObjectWithTag ("Player"); if (_Target == null) { _Target= GameObject.FindGameObjectWithTag("AirCraft"); } if (MobAmount != 10) { Invoke ("SpawnMobEnemy", 5f); } // if(MobAmount< 1){ // InvokeRepeating("SpawnMidBossEnemy",5,10); // } } public void MobDown(){ MobAmount--; } void SpawnMobEnemy(){ int Spawnnum = Random.Range (0, SpawnPoint.Count); int Enemynum = Random.Range (0, EnemyType.Count); Instantiate (EnemyType[Enemynum] , SpawnPoint[Spawnnum], Quaternion.identity); MobAmount ++; CancelInvoke (); } void SpawnMidBossEnemy(){ int MSnum = Random.Range (0,MBSpawnPoint.Capacity); Instantiate (MidBoss , MBSpawnPoint[MSnum], Quaternion.identity); CancelInvoke (); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class World { #region debug public Box testBox = null; public List<Box> BoxList { get { return boxList; } } public List<Box> TriggerList { get { return triggerList; } } #endregion List<Box> boxList = new List<Box>(); List<Box> triggerList = new List<Box>(); float g = 1; #region life cycle public void Upt(float deltaTime) { foreach (Box box in boxList) { box.ApplyForce(-Vector2.up * g); box.Move(deltaTime); } } #endregion #region function public void AddBox(Box box, bool isTrigger = false) { box.world = this; var list = isTrigger ? triggerList : boxList; list.Add(box); } public void MoveBox(Box box, Vector2 speed) { Vector2 xSpeed = new Vector2(speed.x, 0); Vector2 ySpeed = new Vector2(0, speed.y); bool xInBox = false; bool yInBox = false; List<Box> enterBoxList = new List<Box>(); foreach (var b in triggerList) { Box.BoxCheckResult tmXInBoxCheck ; Box.BoxCheckResult tmYInBoxCheck ; tmXInBoxCheck = (box.CheckMoveBoxX(b, speed)); tmYInBoxCheck = (box.CheckMoveBoxY(b, speed)); if (tmXInBoxCheck != Box.BoxCheckResult.OutBox || tmYInBoxCheck != Box.BoxCheckResult.OutBox) { enterBoxList.Add(b); } if (tmXInBoxCheck == Box.BoxCheckResult.InBox || tmYInBoxCheck == Box.BoxCheckResult.InBox) { box.MoveToPivotPos(b, box.pos + speed, speed); } if (tmXInBoxCheck== Box.BoxCheckResult.InBox) xInBox = true; if (tmYInBoxCheck== Box.BoxCheckResult.InBox) yInBox = true; } box.CheckEnterBox(enterBoxList); if (xInBox || yInBox) { if (xInBox) { box.SetXSpeed(0); } else { box.SetPosXAdd(speed.x); } if (yInBox) { box.SetYSpeed(0); } else { box.SetPosYAdd(speed.y); } return; } box.pos += speed; } #endregion #region debug public void Draw() { Gizmos.color = Color.white; foreach (var box in boxList) { box.Draw(); } Gizmos.color = Color.red; foreach (var box in triggerList) { box.Draw(); } Gizmos.color = Color.green; if (testBox != null) { testBox.Draw(); } } #endregion }
using System.Drawing; namespace ItroublveTSC { internal class Mouse { public static Point newpoint = default(Point); public static int x; public static int y; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using MySql.Data.MySqlClient; namespace AnimalDB { public class Kontekstas { public string ConnectionString { get; set; } public Kontekstas(string connectionString) { this.ConnectionString = connectionString; } private MySqlConnection GetConnection() { return new MySqlConnection(ConnectionString); } #region Klasė public List<Klase> GetKlase() { List<Klase> klases = new List<Klase>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `klase`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Klase klase = new Klase(); klase.Pavadinimas = reader[0].ToString(); klase.Tipas = reader[1].ToString(); klase.Potipis = reader[2].ToString(); klases.Add(klase); } conn.Close(); return klases; } public void EditKlase(string Pavadinimas, string Tipas, string Potipis) { if(Pavadinimas == ""||Tipas == "" || Potipis == "") { throw new Exception("neivesti visi langeliai"); } MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE `klase` SET tipas='" + Tipas + "', potipis ='" +Potipis +"' WHERE pavadinimas='" + Pavadinimas + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void RemoveKlase(string Pavadinimas) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `veisle` WHERE fk_Klasepavadinimas='"+Pavadinimas+"';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Negalima panaikinti klases kol yra ja turinciu veisiu"); } cmd.CommandText = "DELETE FROM `klase` WHERE pavadinimas='" + Pavadinimas + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void AddKlase(string Pavadinimas, string tipas, string potipis) { if (Pavadinimas == "" || tipas == "" | potipis == "") { throw new Exception("Nenurodyti visi laukai"); } MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `klase` WHERE pavadinimas ='" + Pavadinimas + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if(sk>0) { throw new Exception("Toks elementas jau yra"); } cmd.CommandText = "INSERT INTO `klase` (pavadinimas, tipas, potipis) VALUES ('" + Pavadinimas + "','"+ tipas+"','"+potipis + "');"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region Gyvūnai public List<Gyvunas> GetGyvunas() { List<Gyvunas> Gyvunai = new List<Gyvunas>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `gyvunas`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Gyvunas gyvunas = new Gyvunas(); gyvunas.vardas = reader[0].ToString(); gyvunas.gimimo_data = Convert.ToDateTime(reader[1]).Date; gyvunas.lytis_id = Convert.ToInt32(reader[2]); gyvunas.savininko_kodas = Convert.ToInt64(reader[3]); gyvunas.fk_Isvaizda_id = Convert.ToInt32(reader[4]); gyvunas.fk_veisle = reader[5].ToString(); gyvunas.fk_vet_viz = Convert.ToDateTime(reader[6]).Date; gyvunas.fk_micro_id = Convert.ToInt32(reader[7]); gyvunas.fk_reg_id = Convert.ToInt32(reader[8]); Gyvunai.Add(gyvunas); } conn.Close(); return Gyvunai; } public void EditGyvunas(string Vardas, DateTime data, int lytis_id, long savininkas_id, int isvaizda_id, string veisle, DateTime vet_vid, int micro_id, int reg_id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE `gyvunas` SET lytis='" + lytis_id + "', fk_Savininkasasmens_kodas ='" + savininkas_id + "'" + ", fk_Isvaizdaid_Isvaizda ='" + isvaizda_id + "', fk_Veislepavadinimas='"+veisle+"'" + ", fk_Sveikatos_buklevizito_pas_veterinara_data='"+vet_vid+"', fk_Mikroschema_numeris='"+micro_id+"'," + " fk_Registracija_numeris='"+reg_id+"' WHERE vardas='" + Vardas + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void RemoveGyvunas(string Vardas, DateTime gimimo_data) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM `gyvunas` WHERE vardas='" + Vardas + "' AND gimimo_data='"+gimimo_data+"';"; cmd.ExecuteNonQuery(); conn.Close(); } public void AddGyvunas(string Vardas, DateTime data, int lytis_id, long savininkas_id, int isvaizda_id, string veisle, DateTime vet_vid, int micro_id, int reg_id) { if (Vardas == "" || data == null|| veisle == "") { throw new Exception("Nenurodyti visi laukai"); } MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `gyvunas` WHERE vardas ='" + Vardas + "' AND gimimo_data='"+data+"';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Toks elementas jau yra"); } cmd.CommandText = "INSERT INTO `gyvunas` (vardas, gimimo_data, lytis,fk_Savininkasasmens_kodas," + "fk_Isvaizdaid_Isvaizda, fk_Veislepavadinimas, fk_Sveikatos_buklevizito_pas_veterinara_data," + " fk_Mikroschema_numeris, fk_Registracija_numeris) VALUES ('" + Vardas + "','" + data + "','" + lytis_id + "','" + savininkas_id + "','" + isvaizda_id + "','" + veisle + "','" + vet_vid + "','" + micro_id + "','" + reg_id + "');"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region Lytys public List<Lytis> GetLytis() { List<Lytis> Lytys = new List<Lytis>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `lytys`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Lytis lytis = new Lytis(); lytis.id = Convert.ToInt32(reader[0]); lytis.name = reader[1].ToString(); Lytys.Add(lytis); } conn.Close(); return Lytys; } #endregion #region Savininkai public List<Savininkas> GetSavininkas() { List<Savininkas> Savininkai = new List<Savininkas>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `savininkas`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Savininkas savininkas = new Savininkas(); savininkas.id = Convert.ToInt64(reader[0]); savininkas.vardas = reader[1].ToString(); savininkas.pavarde = reader[2].ToString(); savininkas.numeris = Convert.ToInt32(reader[3]); savininkas.email = reader[4].ToString(); savininkas.gimimo_data = Convert.ToDateTime(reader[5]); savininkas.lytis = Convert.ToInt32(reader[6]); savininkas.adresas_id = Convert.ToInt32(reader[7]); Savininkai.Add(savininkas); } conn.Close(); return Savininkai; } public void EditSavininkas(long id, string vardas, string pavarde, int numeris, string email, DateTime data, int lytis, int adresas) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE `savininkas` SET vardas='" + vardas + "', pavarde ='" + pavarde + "'" + ", telefono_numeris ='" + numeris + "', elektroninis_pastas='" + email + "'" + ", gimimo_data='" + data + "', lytis='" + lytis + "'," + " fk_Adresasid_Adresas='" + adresas + "' WHERE asmens_kodas=" + id + ";"; cmd.ExecuteNonQuery(); conn.Close(); } public void RemoveSavininkas(long id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `gyvunas` WHERE fk_Savininkasasmens_kodas='" + id + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Negalima panaikinti savininko kol yra ji turinciu gyvunu"); } cmd.CommandText = "SELECT COUNT(*) FROM `registracija` WHERE fk_Savininkasasmens_kodas='" + id + "';"; int sk2 = Convert.ToInt32(cmd.ExecuteScalar()); if (sk2 > 0) { throw new Exception("Negalima panaikinti savininko kol yra ji turinciu registraciju"); } cmd.CommandText = "DELETE FROM `savininkas` WHERE asmens_kodas='" + id + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void AddSavininkas(long id, string vardas, string pavarde, int numeris, string email, DateTime data, int lytis, int adresas) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `savininkas` WHERE asmens_kodas ='" + id + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Toks elementas jau yra"); } cmd.CommandText = "INSERT INTO `savininkas` (asmens_kodas, vardas, pavarde, telefono_numeris," + "elektroninis_pastas, gimimo_data, lytis, fk_Adresasid_Adresas) VALUES ('" + id + "','" + vardas + "','" + pavarde + "','" + numeris + "','" + email + "','" + data + "','" + lytis + "','" + adresas + "');"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region Isvaizda public List<Isvaizda> GetIsvaizda() { List<Isvaizda> Isvaizdos = new List<Isvaizda>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `isvaizda`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Isvaizda isvaizda = new Isvaizda(); isvaizda.svoris = Convert.ToDouble(reader[0]); isvaizda.spalva = reader[1].ToString(); isvaizda.danga = reader[2].ToString(); isvaizda.aukstis = Convert.ToDouble(reader[3]); isvaizda.id = Convert.ToInt32(reader[4]); Isvaizdos.Add(isvaizda); } conn.Close(); return Isvaizdos; } public void EditIsvaizda(double svoris, string spalva, string danga, double aukstis, int id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE `isvaizda` SET svoris='" + svoris + "', spalva ='" + spalva + "'" + ", Kuno_danga ='" + danga + "', aukstis='" + aukstis+ "' WHERE id_Isvaizda=" + id + ";"; cmd.ExecuteNonQuery(); conn.Close(); } public void RemoveIsvaizda(int id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM `isvaizda` WHERE id_Isvaizda='" + id + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void AddIsvaizda(double svoris, string spalva, string danga, double aukstis, int id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `isvaizda` WHERE id_Isvaizda ='" + id + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Toks elementas jau yra"); } cmd.CommandText = "INSERT INTO `isvaizda` (svoris, spalva, kuno_danga, aukstis, id_Isvaizda) " + "VALUES ('" + svoris + "','" + spalva + "','" + danga + "','" + aukstis + "','" + id + "');"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region Mikroschema public List<Mikro> GetMikro() { List<Mikro> Mikroschemos = new List<Mikro>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `mikroschema`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Mikro mikroschema = new Mikro(); mikroschema.pavadinimas = reader[0].ToString(); mikroschema.numeris = Convert.ToInt32(reader[1]); mikroschema.gamintojas = reader[2].ToString(); mikroschema.data = Convert.ToDateTime(reader[3]); Mikroschemos.Add(mikroschema); } conn.Close(); return Mikroschemos; } #endregion #region Registracija public List<Registracija> GetRegistracija() { List<Registracija> Registracijos = new List<Registracija>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `registracija`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Registracija registracija = new Registracija(); registracija.numeris = Convert.ToInt32(reader[0]); registracija.data = Convert.ToDateTime(reader[1]); registracija.vieta = reader[2].ToString(); registracija.savininko_id = Convert.ToInt64(reader[3]); registracija.veterinaras_id = Convert.ToInt32(reader[4]); Registracijos.Add(registracija); } conn.Close(); return Registracijos; } public void EditRegistracija(int numeris, DateTime data, string vieta, long sav_id, int vet_id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE `registracija` SET data='" + data + "', vieta ='" + vieta + "'" + ", fk_Savininkasasmens_kodas ='" + sav_id + "', fk_Veterinarasasmens_kodas='" + vet_id + "' WHERE numeris=" + numeris + ";"; cmd.ExecuteNonQuery(); conn.Close(); } public void RemoveRegistracija(int id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `gyvunas` WHERE fk_Registracija_numeris='" + id + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Negalima panaikinti registracijos dar yra ji turinciu gyvunu"); } cmd.CommandText = "DELETE FROM `registracija` WHERE numeris='" + id + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void AddRegistracija(int numeris, DateTime data, string vieta, long sav_id, int vet_id) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `registracija` WHERE numeris ='" + numeris + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Toks elementas jau yra"); } cmd.CommandText = "INSERT INTO `registracija` (numeris, data, vieta, fk_Savininkasasmens_kodas, fk_Veterinarasasmens_kodas) " + "VALUES ('" + numeris + "','" + data + "','" + vieta + "','" + sav_id + "','" + vet_id + "');"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region Sveikata public List<Sveikata> GetSveikata() { List<Sveikata> sveikatos = new List<Sveikata>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `sveikatos_bukle`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Sveikata sveikata = new Sveikata(); sveikata.Vizito_data = Convert.ToDateTime(reader[0]).Date; sveikata.Skiepijymo_Data = Convert.ToDateTime(reader[1]).Date; sveikata.skiepu_galiojimas = Convert.ToInt32(reader[2]); sveikata.liga_id = Convert.ToInt32(reader[3]); sveikatos.Add(sveikata); } conn.Close(); return sveikatos; } public void RemoveSveikata(DateTime data) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM `sveikatos_bukle` WHERE vizito_pas_veterinara_data='" + data + "';"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region Veisle public List<Veisle> GetVeisle() { List<Veisle> veisles = new List<Veisle>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `veisle`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Veisle veisle = new Veisle(); veisle.kilmes_salis = reader[0].ToString(); veisle.gyvenimo_trukme = Convert.ToInt32(reader[1]); veisle.pavadinimas = reader[2].ToString(); veisle.klases_pavadinimas = reader[3].ToString(); veisles.Add(veisle); } conn.Close(); return veisles; } public void EditVeisle(string kilmes_salis, int gyv_trukme, string pavadinimas, string klase) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "UPDATE `veisle` SET kilmes_salis='" + kilmes_salis + "', gyvenimo_trukme ='" + gyv_trukme + "'" + ", fk_Klasepavadinimas ='" + klase + "' WHERE pavadinimas='" + pavadinimas + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void RemoveVeisle(string Pavadinimas) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "DELETE FROM `veisle` WHERE pavadinimas='" + Pavadinimas + "';"; cmd.ExecuteNonQuery(); conn.Close(); } public void AddVeisle(string kilmes_salis, int gyv_trukme, string pavadinimas, string klase) { MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = conn.CreateCommand(); cmd.CommandText = "SELECT COUNT(*) FROM `veisle` WHERE pavadinimas ='" + pavadinimas + "';"; int sk = Convert.ToInt32(cmd.ExecuteScalar()); if (sk > 0) { throw new Exception("Toks elementas jau yra"); } cmd.CommandText = "INSERT INTO `veisle` (kilmes_salis, gyvenimo_trukme, pavadinimas, fk_Klasepavadinimas) " + "VALUES ('" + kilmes_salis + "','" + gyv_trukme + "','" + pavadinimas + "','" + klase + "');"; cmd.ExecuteNonQuery(); conn.Close(); } #endregion #region adresas public List<Adresas> GetAdresas() { List<Adresas> Adresai = new List<Adresas>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `adresas`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Adresas adresas = new Adresas(); adresas.gatve = reader[0].ToString(); adresas.buto_nr = Convert.ToInt32(reader[1]); adresas.rajonas = reader[2].ToString(); adresas.pasto_kodas = reader[3].ToString(); adresas.fk_miestas = Convert.ToInt32(reader[4]); adresas.id_adresas = Convert.ToInt32(reader[5]); Adresai.Add(adresas); } conn.Close(); return Adresai; } #endregion #region veterinaras public List<Veterinaras> GetVeterinaras() { List<Veterinaras> Veterinarai = new List<Veterinaras>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT * FROM `veterinaras`;", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Veterinaras veterinaras = new Veterinaras(); veterinaras.vardas = reader[0].ToString(); veterinaras.pavarde = reader[1].ToString(); veterinaras.tel_nr = Convert.ToInt32(reader[2]); veterinaras.email = reader[3].ToString(); veterinaras.kodas = Convert.ToInt32(reader[4]); veterinaras.lytis_id = Convert.ToInt32(reader[5]); Veterinarai.Add(veterinaras); } conn.Close(); return Veterinarai; } #endregion #region PA1 public List<PA1c> GetAnimalsIn2018() { List<PA1c> Animals = new List<PA1c>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT gyvunas.vardas, gyvunas.gimimo_data, gyvunas.fk_Mikroschema_numeris, mikroschema.idejimo_data FROM gyvunas INNER JOIN mikroschema ON gyvunas.fk_Mikroschema_numeris = mikroschema.numeris WHERE mikroschema.idejimo_data >= '2018-01-01';", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { PA1c data = new PA1c(); data.Vardas = reader[0].ToString(); data.Gimimo_Data = Convert.ToDateTime(reader[1]); data.Mikroschemos_Numeris = Convert.ToInt32(reader[2]); data.Idejimo_Data = Convert.ToDateTime(reader[3]); Animals.Add(data); } conn.Close(); return Animals; } #endregion #region PA2 public List<PA2c> GetAnimalsInPlace(string vieta, DateTime from, DateTime to) { if(vieta == "") { throw new Exception("Nenurodytas vietos pavadinimas"); } List<PA2c> Animals = new List<PA2c>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT gyvunas.vardas, gyvunas.gimimo_data, gyvunas.fk_Registracija_numeris, registracija.vieta, registracija.data FROM `gyvunas` INNER JOIN registracija ON gyvunas.fk_Registracija_numeris = registracija.numeris WHERE registracija.vieta = '" + vieta + "'AND registracija.data >= '"+from+"' AND registracija.data <= '"+ to + "';", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { PA2c data = new PA2c(); data.Vardas = reader[0].ToString(); data.Gimimo_Data = Convert.ToDateTime(reader[1]); data.Registracijos_Numeris = Convert.ToInt32(reader[2]); data.Registracijos_Vieta = reader[3].ToString(); data.Registracijos_Data = Convert.ToDateTime(reader[4]); Animals.Add(data); } conn.Close(); if (Animals.Count == 0) throw new Exception("Tuščias sąrašas su nurodytais parametrais"); return Animals; } #endregion #region aa1 public List<AA1c> GetAA1() { List<AA1c> Animals = new List<AA1c>(); MySqlConnection conn = GetConnection(); conn.Open(); MySqlCommand cmd = new MySqlCommand("SELECT gyvunas.fk_Veislepavadinimas, AVG(isvaizda.svoris) AS VID_Svoris, MAX(isvaizda.aukstis) as max_aukstis FROM `gyvunas` INNER JOIN isvaizda ON gyvunas.fk_Isvaizdaid_Isvaizda = isvaizda.id_Isvaizda GROUP BY fk_Veislepavadinimas", conn); MySqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { AA1c data = new AA1c(); data.Veisle = reader[0].ToString(); data.VidSvoris = Convert.ToDouble(reader[1]); data.MaxAukstis = Convert.ToDouble(reader[2]); Animals.Add(data); } conn.Close(); return Animals; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace UniformShop.Models { public class Order { [Key] public long orderId { get; set; } public long itemId { get; set; } [ForeignKey("custId")] public virtual Customer Customer { get; set; } public string date { get; set; } public string createdBy { get; set; } public string createdDate { get; set; } public string modifiedBy { get; set; } public string modifiedDate { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace transGraph { public partial class editRoute : Form { public string id; dbFacade db = new dbFacade(); private Point screenOffset; private int indexOfItemUnderMouseToDrop; public editRoute(string id) { this.id = id; InitializeComponent(); loadit(); } private void addRoute_Load(object sender, EventArgs e) { } public void loadit() { DataTable data = db.FetchAllSql("SELECT id,title FROM citys"); foreach (DataRow rr in data.Rows) { listBox1.Items.Add(rr[1]); } data = db.FetchAllSql("SELECT id,title FROM ways"); foreach (DataRow rr in data.Rows) { comboBox1.Items.Add(rr[1]); } data = db.FetchAllSql("SELECT id,ways,wayid,km,note FROM routes WHERE id = '" + id + "'"); this.textBox2.Text = data.Rows[0][4].ToString(); this.textBox1.Text = data.Rows[0][3].ToString(); string wayid = Convert.ToString(data.Rows[0][2]); string wayidT = ""; try { DataTable dataB = db.FetchAllSql("SELECT title FROM ways WHERE id = '" + wayid + "'"); wayidT = dataB.Rows[0][0].ToString(); } catch (Exception) { } this.comboBox1.SelectedItem = wayidT; string ways = Convert.ToString(data.Rows[0][1]); string waysT = ""; foreach (string wid in ways.Split(';')) { try { DataTable dataB = db.FetchAllSql("SELECT title FROM citys WHERE id = '" + wid + "'"); // MessageBox.Show(dataB.Rows[0][0].ToString()); listBox2.Items.Add(dataB.Rows[0][0].ToString()); //for (int i = 0; i < checkedListBox1.Items.Count; i++) //{ // if(checkedListBox1.Items[i].ToString() == dataB.Rows[0][0].ToString()) // { // checkedListBox1.SetItemChecked(i, true); // } //} } catch (Exception) { } } } private void button1_Click(object sender, EventArgs e) { if (listBox2.Items.Count == 0) { MessageBox.Show("Не выбран ни один пункт маршрута"); return; } if (Convert.ToString(comboBox1.SelectedItem) == "") { MessageBox.Show("Не выбрано направление"); return; } string ways = ""; for (int i = 0; i < listBox2.Items.Count; i++) { try { DataTable data = db.FetchAllSql("SELECT id FROM `citys` WHERE title = '" + listBox2.Items[i] + "'"); string item = Convert.ToString(data.Rows[0][0]); ways += item + ";"; } catch (Exception) { } } string wayid = ""; try { DataTable data = db.FetchAllSql("SELECT id FROM `ways` WHERE title = '" + comboBox1.SelectedItem + "'"); wayid = Convert.ToString(data.Rows[0][0]); } catch (Exception) { } db.FetchAllSql("UPDATE `routes` SET `ways` = '" + ways + "',`wayid`='" + wayid + "',`note`='" + textBox2.Text + "',`km` = '" + textBox1.Text + "' WHERE id = '"+id+"'"); this.Close(); } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void listBox1_MouseDown(object sender, MouseEventArgs e) { int indexOfItem = listBox1.IndexFromPoint(e.X, e.Y); if (indexOfItem >= 0 && indexOfItem < listBox1.Items.Count) // check that an string is selected { listBox1.DoDragDrop(listBox1.Items[indexOfItem], DragDropEffects.Copy); } } private void listBox1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.Copy; // The cursor changes to show Copy } private void listBox1_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) { screenOffset = SystemInformation.WorkingArea.Location; ListBox lb = sender as ListBox; if (lb != null) { Form f = lb.FindForm(); if (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) || ((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) || ((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) || ((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) { e.Action = DragAction.Cancel; } } } private void listBox2_MouseDown(object sender, MouseEventArgs e) { int indexOfItem = listBox2.IndexFromPoint(e.X, e.Y); if (indexOfItem >= 0 && indexOfItem < listBox2.Items.Count) // check we clicked down on a string { listBox2.DoDragDrop(listBox2.Items[indexOfItem], DragDropEffects.Move); } } private void listBox2_DragDrop(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.StringFormat)) { if (indexOfItemUnderMouseToDrop >= 0 && indexOfItemUnderMouseToDrop < listBox2.Items.Count) { listBox2.Items.Insert(indexOfItemUnderMouseToDrop, e.Data.GetData(DataFormats.Text)); } else { for (int i = 0; i < listBox2.Items.Count; i++) { if (listBox2.Items[i] == e.Data.GetData(DataFormats.Text)) { return; } } listBox2.Items.Add(e.Data.GetData(DataFormats.Text)); } } } private void listBox2_DragEnter(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.StringFormat) && (e.AllowedEffect == DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy; else e.Effect = DragDropEffects.Move; } private void listBox2_DragOver(object sender, DragEventArgs e) { indexOfItemUnderMouseToDrop = listBox2.IndexFromPoint(listBox2.PointToClient(new Point(e.X, e.Y))); if (indexOfItemUnderMouseToDrop != ListBox.NoMatches) { listBox2.SelectedIndex = indexOfItemUnderMouseToDrop; } else { listBox2.SelectedIndex = indexOfItemUnderMouseToDrop; } if (e.Effect == DragDropEffects.Move) // When moving an item within listBox2 listBox2.Items.Remove((string)e.Data.GetData(DataFormats.Text)); } private void listBox2_QueryContinueDrag(object sender, QueryContinueDragEventArgs e) { screenOffset = SystemInformation.WorkingArea.Location; ListBox lb = sender as ListBox; if (lb != null) { Form f = lb.FindForm(); if (((Control.MousePosition.X - screenOffset.X) < f.DesktopBounds.Left) || ((Control.MousePosition.X - screenOffset.X) > f.DesktopBounds.Right) || ((Control.MousePosition.Y - screenOffset.Y) < f.DesktopBounds.Top) || ((Control.MousePosition.Y - screenOffset.Y) > f.DesktopBounds.Bottom)) { e.Action = DragAction.Cancel; } } } } }
using System.Collections; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; [SelectionBase] public class Player : MonoBehaviour { [SerializeField] float m_Health = 300.0f; [SerializeField] float m_Speed = 20.0f; [SerializeField] float m_BorderPadding = 1.0f; [SerializeField] float m_LaserSpeed = 10.0f; [SerializeField] float m_LaserFirePeriod = 0.2f; [SerializeField] float m_GameOverDelay = 1.5f; [SerializeField] GameObject m_LaserPrefab = null; [SerializeField] AudioClip m_DeathSFX = null; [SerializeField] float m_DeathSFXVol = 0.7f; [SerializeField] AudioClip m_LaserSFX = null; [SerializeField] float m_LaserSFXVol = 0.02f; Coroutine m_LaserFireRoutine = null; GameObject m_RuntimeSpawnContainer = null; private void Start() { m_RuntimeSpawnContainer = GameObject.Find(GlobalConstants.SpawnedRuntimeContainer); Debug.Assert(m_RuntimeSpawnContainer); } private void Update() { ProcessMovement(); ProcessFire(); } private void ProcessFire() { if (CrossPlatformInputManager.GetButtonDown("Fire1")) { if (m_LaserFireRoutine != null) { StopCoroutine(m_LaserFireRoutine); } m_LaserFireRoutine = StartCoroutine(FireContinuously()); } if (CrossPlatformInputManager.GetButtonUp("Fire1")) { StopCoroutine(m_LaserFireRoutine); } } IEnumerator FireContinuously() { while (true) { GameObject newLaser = Instantiate(m_LaserPrefab, transform.position, Quaternion.identity, m_RuntimeSpawnContainer.transform); newLaser.GetComponent<Rigidbody2D>().velocity = new Vector2(0f, m_LaserSpeed); AudioSource.PlayClipAtPoint(m_LaserSFX, Camera.main.transform.position, m_LaserSFXVol); yield return new WaitForSeconds(m_LaserFirePeriod); } } private void ProcessMovement() { float xVal = CrossPlatformInputManager.GetAxis("Horizontal") * m_Speed * Time.deltaTime; float yVal = CrossPlatformInputManager.GetAxis("Vertical") * m_Speed * Time.deltaTime; Vector3 botLeft = Camera.main.ViewportToWorldPoint(new Vector3(0f, 0f, 0f)); Vector3 topRight = Camera.main.ViewportToWorldPoint(new Vector3(1f, 1f, 0f)); SpriteRenderer spriteRend = GetComponentInChildren<SpriteRenderer>(); float spriteHalfWidth = spriteRend.size.x * 0.5f; float spriteHalfHeight = spriteRend.size.y * 0.5f; xVal = Mathf.Clamp(transform.position.x + xVal, botLeft.x + spriteHalfWidth + m_BorderPadding, topRight.x - spriteHalfWidth - m_BorderPadding); yVal = Mathf.Clamp(transform.position.y + yVal, botLeft.y + spriteHalfHeight + m_BorderPadding, topRight.y - spriteHalfHeight - m_BorderPadding); transform.position = new Vector2(xVal, yVal); } private void OnTriggerEnter2D(Collider2D other) { DamageDealer dmgDealer = other.gameObject.GetComponentInChildren<DamageDealer>(); if (dmgDealer) { if (dmgDealer.IsInstantKill()) { m_Health = 0f; } else { m_Health -= dmgDealer.GetDamage(); } if (m_Health <= 0f) { OnDeath(); } dmgDealer.TryDestroyDamager(); } } private void OnDeath() { AudioSource.PlayClipAtPoint(m_DeathSFX, Camera.main.transform.position, m_DeathSFXVol); Destroy(gameObject); SceneLoader.Singleton.LoadGameOverScene(m_GameOverDelay); } }
using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; using Utilities; namespace ManagerScripts { public class ScoreCanvasScript : MonoBehaviour { public Text depth; public Text damageTaken; public Text damageDealt; public Text amountHealed; private AnalyticsTracker info; private void Start() { SoundScript.PlaySound(SoundScript.Sound.Death); info = AnalyticsTracker.instance; depth.text = $"Depth\n {info.depth}"; damageDealt.text = $"Damage Dealt\n {info.damageDealt}"; damageTaken.text = $"Damage Taken\n {info.damageTaken}"; amountHealed.text = $"Amount Healed\n {info.amountHealed}"; } public void ExitToMainMenu() { SceneManager.LoadScene("Scenes/MainMenu", LoadSceneMode.Single); } } }
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 Bai4._1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void btnReset_Click(object sender, EventArgs e) { txtA.Text= ""; txtB.Text = ""; txtC.Text = ""; this.ActiveControl = txtA; } private void btnThoat_Click(object sender, EventArgs e) { DialogResult result = MessageBox.Show("Bạn có muốn thoát không?", "Xác nhận thoát",MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { this.Close(); } } private void btnCong_Click(object sender, EventArgs e) { double kq = Double.Parse(txtA.Text) + Double.Parse(txtB.Text); txtC.Text = kq + ""; } private void Form1_Load(object sender, EventArgs e) { } private void btnTru_Click(object sender, EventArgs e) { double kq = Double.Parse(txtA.Text) - Double.Parse(txtB.Text); txtC.Text = kq + ""; } private void btnNhan_Click(object sender, EventArgs e) { double kq = Double.Parse(txtA.Text) * Double.Parse(txtB.Text); txtC.Text = kq + ""; } private void btnChia_Click(object sender, EventArgs e) { double a = Double.Parse(txtA.Text); double b = Double.Parse(txtB.Text); if (b == 0) { txtC.Text = "không thể chia cho số 0"; } else { double kq = Math.Round(a/b,2) ; txtC.Text = kq + ""; } } } }
using mytry.Models; using SQLite; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; namespace mytry.Views { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class EventDetails : ContentPage { List<String> lsP = new List<String>() { "Amman", "Zarqa", "Irbid", "Jerash", "Mafraq", "Balqa" , "Madaba", "Karak" , "Tafilah", "Ma'an" , "Aqaba" , "Other country" }; public EventDetails() { InitializeComponent(); picker.ItemsSource = lsP; } private async void btnSave_Clicked(object sender, EventArgs e) { EventV eventV = this.BindingContext as EventV; Boolean answer = await DisplayAlert("Confirmation", "Are you sure you want to save?", "Yes", "No"); if (answer) { if (eventV.Id == 0) { eventV.Id = await App.MyEvVl.AddToEvent(eventV); } else { await App.MyEvVl.UpdateEventAsync(eventV); } await Navigation.PopAsync(); } } private async void tbiDelete_Clicked(object sender, EventArgs e) { Boolean answer = await DisplayAlert("Confirmation", "Are you sure you want to Delte the Event?", "Yes", "No"); if (answer) { EventV eventV = this.BindingContext as EventV; await App.MyEvVl.DeleteEventAsync(eventV.Id); await Navigation.PopAsync(); } } } }
// Copyright 2021 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using NtApiDotNet.Utilities.Security; using System; namespace NtApiDotNet.Win32.DirectoryService { /// <summary> /// Base class for a schema class or attribute object. /// </summary> public class DirectoryServiceSchemaObject : IDirectoryServiceObjectTree { /// <summary> /// The GUID of the schema class. /// </summary> public Guid SchemaId { get; } /// <summary> /// The name of the schema class. /// </summary> public string CommonName { get; } /// <summary> /// The LDAP display name. /// </summary> public string Name { get; } /// <summary> /// The object class for the schema class. /// </summary> public string ObjectClass { get; } /// <summary> /// The distinguished name for the schema class. /// </summary> public string DistinguishedName { get; } /// <summary> /// The domain name searched for this schema class. /// </summary> public string Domain { get; } /// <summary> /// The admin description for the object. /// </summary> public string Description { get; } /// <summary> /// Indicates if this schema object is system only. /// </summary> public bool SystemOnly { get; } Guid IDirectoryServiceObjectTree.Id => SchemaId; /// <summary> /// Overridden ToString method. /// </summary> /// <returns>The name of the schema class.</returns> public override string ToString() { return Name; } /// <summary> /// Convert the schema class to an object type tree. /// </summary> /// <returns>The tree of object types.</returns> public virtual ObjectTypeTree ToObjectTypeTree() { return new ObjectTypeTree(SchemaId, Name); } /// <summary> /// Convert the extended right to an object type tree. /// </summary> /// <param name="schema_class">The schema class to convert.</param> /// <returns>The tree of object types.</returns> public static explicit operator ObjectTypeTree(DirectoryServiceSchemaObject schema_class) { return schema_class.ToObjectTypeTree(); } internal DirectoryServiceSchemaObject(string domain, string dn, Guid schema_id, string name, string ldap_name, string description, string object_class, bool system_only) { Domain = domain ?? string.Empty; DistinguishedName = dn ?? string.Empty; SchemaId = schema_id; CommonName = name; Name = ldap_name; ObjectClass = object_class; Description = description; SystemOnly = system_only; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace internet_shop.Models { public class Cart { public Cart() { } public Cart(string cartId) { this.CartId = cartId; } public string CartId { get; set; } public string ProfileId { get; set; } public string Address { get; set; } //public List<CartProduct> Products { get; set; } } }
using Contoso.Common.Configuration.Json; using System.Text.Json.Serialization; namespace Contoso.Common.Configuration.ExpressionDescriptors { [JsonConverter(typeof(DescriptorConverter))] public abstract class OperatorDescriptorBase : IExpressionOperatorDescriptor { public string TypeString => this.GetType().AssemblyQualifiedName; } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HardcoreHistoryBlog.Models.Likes { public class SubcommentLike : Like { public int SubcommentId { get; set; } } }
namespace SampleConsoleApplication { public class CompanyEntities { } }
using System; using Logs.Authentication.Contracts; using Logs.Providers.Contracts; using Logs.Services.Contracts; using Logs.Web.Controllers; using Logs.Web.Infrastructure.Factories; using Moq; using NUnit.Framework; namespace Logs.Web.Tests.Controllers.MeasurementControllerTests { [TestFixture] public class ConstructorTests { [Test] public void TestConstructor_PassEverything_ShouldInitializeCorrectly() { // Arrange var mockedFactory = new Mock<IViewModelFactory>(); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedMeasurementService = new Mock<IMeasurementService>(); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); // Act var controller = new MeasurementController(mockedAuthenticationProvider.Object, mockedMeasurementService.Object, mockedFactory.Object); // Assert Assert.IsNotNull(controller); } [Test] public void TestConstructor_PassFactoryNull_ShouldThrowArgumentNullException() { // Arrange var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedMeasurementService = new Mock<IMeasurementService>(); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); // Act, Assert Assert.Throws<ArgumentNullException>(() => new MeasurementController(mockedAuthenticationProvider.Object, mockedMeasurementService.Object, null)); } [Test] public void TestConstructor_PassMeasurementServiceNull_ShouldThrowArgumentNullException() { // Arrange var mockedFactory = new Mock<IViewModelFactory>(); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedAuthenticationProvider = new Mock<IAuthenticationProvider>(); // Act, Assert Assert.Throws<ArgumentNullException>(() => new MeasurementController(mockedAuthenticationProvider.Object, null, mockedFactory.Object)); } [Test] public void TestConstructor_PassAuthenticationProviderNull_ShouldThrowArgumentNullException() { // Arrange var mockedFactory = new Mock<IViewModelFactory>(); var mockedDateTimeProvider = new Mock<IDateTimeProvider>(); var mockedMeasurementService = new Mock<IMeasurementService>(); // Act, Assert Assert.Throws<ArgumentNullException>(() => new MeasurementController(null, mockedMeasurementService.Object, mockedFactory.Object)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief ファイル。 */ /** NFile */ namespace NFile { /** MonoBehaviour_Base */ public abstract class MonoBehaviour_Base : MonoBehaviour { /** Mode */ protected enum Mode { /** リクエスト待ち。 */ WaitRequest, /** 開始。 */ Start, /** 実行中。 */ Do, /** エラー終了。 */ Do_Error, /** 正常終了。 */ Do_Success, /** 完了。 */ Fix, }; /** ResultType */ public enum ResultType { /** 未定義。 */ None, /** エラー。 */ Error, /** セーブ完了。 */ SaveEnd, /** バイナリー。 */ Binary, /** テキスト。 */ Text, /** テクスチャ。 */ Texture, /** アセットバンドル。 */ AssetBundle, /** サウンドプール。 */ SoundPool, }; /** [MonoBehaviour_Base]コールバック。初期化。 */ protected abstract void OnInitialize(); /** [MonoBehaviour_Base]コールバック。開始。 */ protected abstract IEnumerator OnStart(); /** [MonoBehaviour_Base]コールバック。実行。 */ protected abstract IEnumerator OnDo(); /** [MonoBehaviour_Base]コールバック。エラー終了。 */ protected abstract IEnumerator OnDoError(); /** [MonoBehaviour_Base]コールバック。正常終了。 */ protected abstract IEnumerator OnDoSuccess(); /** mode */ [SerializeField] private Mode mode; /** cancel_flag */ [SerializeField] private bool cancel_flag; /** delete_flag */ [SerializeField] private bool delete_flag; /** result_progress */ [SerializeField] private float result_progress; /** result_errorstring */ [SerializeField] private string result_errorstring; /** result_type */ [SerializeField] private ResultType result_type; /** result_binary */ [SerializeField] private byte[] result_binary; /** result_text */ [SerializeField] private string result_text; /** result_texture */ [SerializeField] private Texture2D result_texture; /** result_assetbundle */ [SerializeField] private AssetBundle result_assetbundle; /** result_soundpool */ [SerializeField] private NAudio.Pack_SoundPool result_soundpool; /** 結果フラグリセット。 */ protected void ResetResultFlag() { this.cancel_flag = false; this.result_progress = 0.0f; this.result_errorstring = null; this.result_type = ResultType.None; this.result_binary = null; this.result_text = null; this.result_texture = null; this.result_assetbundle = null; this.result_soundpool = null; } /** キャンセル。設定。 */ public void Cancel() { this.cancel_flag = true; } /** キャンセル。取得。 */ public bool IsCancel() { return this.cancel_flag; } /** プログレス。取得。 */ public float GetResultProgress() { return this.result_progress; } /** プログレス。設定。 */ public void SetResultProgress(float a_progress) { this.result_progress = a_progress; } /** エラー文字。取得。 */ public string GetResultErrorString() { return this.result_errorstring; } /** 結果タイプ。取得。 */ public ResultType GetResultType() { return this.result_type; } /** リクエスト待ち開始。 */ public void WaitRequest() { if(this.mode == Mode.Fix){ this.mode = Mode.WaitRequest; }else{ Tool.Assert(false); } } /** リクエスト待ち。 */ protected bool IsWaitRequest() { if(this.mode == Mode.WaitRequest){ return true; } return false; } /** 開始。 */ protected void SetModeStart() { this.mode = Mode.Start; } /** 実行。 */ protected void SetModeDo() { this.mode = Mode.Do; } /** 正常終了。 */ protected void SetModeDoSuccess() { this.mode = Mode.Do_Success; } /** エラー終了。 */ protected void SetModeDoError() { this.mode = Mode.Do_Error; } /** 完了。 */ protected void SetModeFix() { this.mode = Mode.Fix; } /** 完了チェック。 */ public bool IsFix() { if(this.mode == Mode.Fix){ return true; } return false; } /** 削除リクエスト。設定。 */ public void DeleteRequest() { this.delete_flag = true; } /** 削除リクエスト。取得。 */ public bool IsDeleteRequest() { return this.delete_flag; } /** 結果。設定。 */ public void SetResultErrorString(string a_error_string) { this.result_type = ResultType.Error; this.result_errorstring = a_error_string; } /** 結果。設定。 */ public void SetResultSaveEnd() { this.result_type = ResultType.SaveEnd; } /** 結果。設定。 */ public void SetResultBinary(byte[] a_binary) { this.result_type = ResultType.Binary; this.result_binary = a_binary; } /** 結果。取得。 */ public byte[] GetResultBinary() { return this.result_binary; } /** 結果。設定。 */ public void SetResultText(string a_text) { this.result_type = ResultType.Text; this.result_text = a_text; } /** 結果。取得。 */ public string GetResultText() { return this.result_text; } /** 結果。設定。 */ public void SetResultTexture(Texture2D a_texture) { this.result_type = ResultType.Texture; this.result_texture = a_texture; } /** 結果。取得。 */ public Texture2D GetResultTexture() { return this.result_texture; } /** 結果。設定。 */ public void SetResultAssetBundle(AssetBundle a_assetbundle) { this.result_type = ResultType.AssetBundle; this.result_assetbundle = a_assetbundle; } /** 結果。取得。 */ public AssetBundle GetResultAssetBundle() { return this.result_assetbundle; } /** 結果。設定。 */ public void SetResultSoundPool(NAudio.Pack_SoundPool a_soundpool) { this.result_type = ResultType.SoundPool; this.result_soundpool = a_soundpool; } /** 結果。取得。 */ public NAudio.Pack_SoundPool GetResultSoundPool() { return this.result_soundpool; } /** Awake */ private void Awake() { this.mode = Mode.WaitRequest; this.cancel_flag = false; this.delete_flag = false; this.result_progress = 0.0f; this.result_errorstring = null; this.result_type = ResultType.None; this.result_binary = null; this.result_text = null; this.result_texture = null; this.result_assetbundle = null; this.result_soundpool = null; this.OnInitialize(); } /** Start */ private IEnumerator Start() { bool t_loop = true; while(t_loop){ switch(this.mode){ case Mode.WaitRequest: { yield return null; if(this.delete_flag == true){ t_loop = false; } }break; case Mode.Fix: { yield return null; if(this.delete_flag == true){ t_loop = false; } }break; case Mode.Start: { yield return this.OnStart(); }break; case Mode.Do: { yield return this.OnDo(); }break; case Mode.Do_Error: { yield return this.OnDoError(); }break; case Mode.Do_Success: { yield return this.OnDoSuccess(); }break; } } Tool.Log(this.gameObject.name,"GameObject.Destroy"); GameObject.Destroy(this.gameObject); yield break; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using System.Data; public class pinzhuang2: MonoBehaviour { private Camera cam;//发射射线的摄像机 private GameObject go;//射线碰撞的物体 private GameObject go1; public static string btnName;//射线碰撞物体的名字 public static string btnName1; int cishu = 0; int num_shengyu=4; private Vector3 screenSpace; private Vector3 offset; SqlAccess sql = new SqlAccess(); void Start() { cam = Camera.main; } void Update () { //整体初始位置 Ray ray = cam.ScreenPointToRay (Input.mousePosition); //从摄像机发出到点击坐标的射线 RaycastHit hitInfo; if (Input.GetMouseButtonDown (0)) { if (Physics.Raycast (ray, out hitInfo)) { //划出射线,只有在scene视图中才能看到 Debug.DrawLine (ray.origin, hitInfo.point); if (cishu == 0) { go = hitInfo.collider.gameObject; btnName = go.name; print (btnName); cishu++; //组件的名字 } else if (cishu == 1) { go1 = hitInfo.collider.gameObject; btnName1 = go1.name; print (btnName1); if (btnName.Equals (btnName1)&&(go1.transform.parent.gameObject.name!=go.transform.parent.gameObject.name)) { print ("chenggong"); num_shengyu--; go.layer = LayerMask.NameToLayer ("Ignore Raycast"); go1.layer = LayerMask.NameToLayer ("Ignore Raycast"); GameObject gof;//判断两个物体设谁动; gof = go1.transform.parent.gameObject; if (gof.name == "jixiang") { go.transform.position = go1.transform.position; } else { go1.transform.position = go.transform.position; } } else { UnityEditor.EditorUtility.DisplayDialog ("Error", "拼接错误", "确认", "取消"); pinzhuang .defen-=5; print ("shibai"); } if (num_shengyu == 0) { DateTime date = DateTime.Now; string fenshu_date = date.ToString ("yyyy-MM-dd HH:mm:ss"); //Debug.Log(fenshu_date); DataSet ds = sql.InsertInto ("shixun_fenshu",denglu.username,"1",pinzhuang .defen,fenshu_date); sql.Close (); UnityEditor.EditorUtility.DisplayDialog ("Finish", "拼接成功", "确认", "取消"); } cishu = 0; } } } } }
using System; using System.Linq; namespace Battleships { public class BattleshipGame { public Player Player1 { get; set; } public Player Player2 { get; set; } public Player CurrentPlayer { get; set; } public bool Finished { get; set; } public BattleshipGame(Player player1, Player player2) { this.Player1 = player1; this.Player2 = player2; this.CurrentPlayer = player1; } public PublicFieldStates MakeMove(int x, int y) { if (this.Finished) { throw new InvalidOperationException("This game has ended"); } var enemy = this.CurrentPlayer == this.Player1 ? this.Player2 : this.Player1; Ship ship = enemy.Ships.SingleOrDefault(s => s.Positions.Any(p => p.Equals(new Position(x, y)))); var result = PublicFieldStates.Empty; if (ship != null) { result = PublicFieldStates.Hit; } enemy.PublicBoard[y, x] = result; if (result == PublicFieldStates.Hit) { result = CheckIfShipSunk(ship, enemy); } if (enemy.Ships.All(s => s.Positions.All(p => enemy.PublicBoard[p.Y, p.X] == PublicFieldStates.Sunk))) { this.Finished = true; } else { this.CurrentPlayer = enemy; } return result; } private static PublicFieldStates CheckIfShipSunk(Ship ship, Player enemy) { bool wholeShipHit = ship.Positions.All(position => enemy.PublicBoard[position.Y, position.X] == PublicFieldStates.Hit); if (wholeShipHit) { foreach (Position position in ship.Positions) { enemy.PublicBoard[position.Y, position.X] = PublicFieldStates.Sunk; } ship.Sunk = true; return PublicFieldStates.Sunk; } return PublicFieldStates.Hit; } } }
using FakeItEasy; using FluentAssertions; using Xunit; namespace FatCat.Nes.Tests.OpCodes.IO { public abstract class StoreItemAtAddressTests : OpCodeTest { protected const int AbsoluteAddress = 0x1915; protected abstract byte StoreData { get; } [Fact] public void Takes0Cycles() { var cycles = opCode.Execute(); cycles.Should().Be(0); } [Fact] public void WillWriteAccumulatorToAbsoluteAddress() { SetDataOnCpu(); cpu.AbsoluteAddress = AbsoluteAddress; opCode.Execute(); A.CallTo(() => cpu.Write(AbsoluteAddress, StoreData)).MustHaveHappened(); } protected abstract void SetDataOnCpu(); } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Business.Helper; using Model.DataEntity; using Model.Locale; using Model.Security.MembershipManagement; using Utility; using Uxnet.Web.WebUI; using eIVOGo.Module.Base; namespace eIVOGo.Module.SYS.Item { public partial class MessagesItem : EditEntityItemBase<EIVOEntityDataContext, SystemMessage> { protected void Page_Load(object sender, EventArgs e) { } protected override void OnInit(EventArgs e) { base.OnInit(e); this.QueryExpr = m => m.MsgID == (int?)modelItem.DataItem; btnUpdate.OnClientClick = doConfirm.GetPostBackEventReference(null); this.PreRender += new EventHandler(MessagesItem_PreRender); } void MessagesItem_PreRender(object sender, EventArgs e) { if (_entity != null) { if (_entity.StartDate.HasValue) DateFrom.DateTimeValue = _entity.StartDate.Value; else DateFrom.Reset(); if (_entity.EndDate.HasValue) DateTo.DateTimeValue = _entity.EndDate.Value; else DateTo.Reset(); } } public void Show() { this.ModalPopupExtender.Show(); } public void Clean() { modelItem.DataItem = null; this.txtMsg.Text = ""; DateFrom.Reset(); DateTo.Reset(); this.chkShowForever.Checked = true; } protected override bool saveEntity() { var mgr = dsEntity.CreateDataManager(); if (String.IsNullOrEmpty(this.txtMsg.Text.Trim())) { this.AjaxAlert("未填寫訊息內容!!"); return false; } loadEntity(); if (_entity == null) { _entity = new SystemMessage { CreateTime = DateTime.Now }; mgr.EntityList.InsertOnSubmit(_entity); } _entity.MessageContents = this.txtMsg.Text.Trim(); _entity.AlwaysShow = this.chkShowForever.Checked; if (DateFrom.HasValue) _entity.StartDate = DateFrom.DateTimeValue; if (DateTo.HasValue) _entity.EndDate = DateTo.DateTimeValue; _entity.AlwaysShow = this.chkShowForever.Checked; _entity.UpdateTime = DateTime.Now; mgr.SubmitChanges(); return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; public class ReadyFight : MonoBehaviour { [SerializeField] private Transform readyTrs; [SerializeField] private Transform fightTrs; public float scrollTime; public void InitReadyFight() { SetPositionReadyFightTrs(); } public void SetPositionReadyFightTrs() { readyTrs.localPosition = Vector2.zero; fightTrs.localPosition = new Vector2(0, 60); } public IEnumerator ChangeToFight() { readyTrs.DOLocalMoveY(-60, scrollTime).SetEase(Ease.InOutBack); yield return fightTrs.DOLocalMoveY(0f, scrollTime).SetEase(Ease.InOutBack).WaitForCompletion(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace StatsMain1 { class Parameters { Parameters(Parameters original) { this.params_inner_ = original.params_inner_.Clone(); } Parameters(ParametersInner params_inner) { this.params_inner_ = params_inner.Clone(); } public double Integral(double time1, double time2) { return params_inner_.Integral(time1, time2); } public double IntegralSquare(double time1, double time2) { return params_inner_.IntegralSquare(time1, time2); } public double Mean(double time1, double time2) { return (Integral(time1, time2) / (time2 - time1)); } public double RootMeanSquare(double time1, double time2) { return (IntegralSquare(time1, time2) / (time2 - time1)); } public static implicit operator Parameters(ParametersInner params_inner) { return new Parameters(params_inner); } private ParametersInner params_inner_; } abstract class ParametersInner { public abstract ParametersInner Clone(); public abstract double Integral(double time1, double time2); public abstract double IntegralSquare(double time1, double time2); } class ParametersConstant : ParametersInner { public ParametersConstant(double constant) { this.constant_ = constant; this.constantSquare_ = constant * constant; } public override ParametersInner Clone() { return new ParametersConstant(this.constant_); } public override double Integral(double time1, double time2) { return ((time2 - time1) * constant_); } public override double IntegralSquare(double time1, double time2) { return ((time2 - time1) * constantSquare_); } private double constant_; private double constantSquare_; } }
using System; using System.Collections.Generic; using System.Text; namespace OCP.Search { /** * The generic result of a search * @since 7.0.0 */ public class Result { /** * A unique identifier for the result, usually given as the item ID in its * corresponding application. * @var string * @since 7.0.0 */ public string id; /** * The name of the item returned; this will be displayed in the search * results. * @var string * @since 7.0.0 */ public string name; /** * URL to the application item. * @var string * @since 7.0.0 */ public string link; /** * The type of search result returned; for consistency, name this the same * as the class name (e.g. \OC\Search\File . 'file') in lowercase. * @var string * @since 7.0.0 */ public string type = "generic"; /** * Create a new search result * @param string id unique identifier from application: '[app_name]/[item_identifier_in_app]' * @param string name displayed text of result * @param string link URL to the result within its app * @since 7.0.0 */ public Result(string id = null, string name = null, string link = null) { this.id = id; this.name = name; this.link = link; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assignent1_PrivateSchoolStructure { public class Assignment { public string Description { get; set; } public DateTime SubmissionDateAndTime { get; set; } public Course Course { get; set; } public string Title { get; set; } public Assignment(string title, string description, DateTime submissionDateAndTime, Course course) { if (course == null) throw new InvalidOperationException("Assignment can not be created without a course."); if (submissionDateAndTime <= course.StartDate || submissionDateAndTime > course.EndDate) throw new InvalidOperationException("Submission date must be greater than course's starting date and lower or equal than course's end date."); if (submissionDateAndTime.DayOfWeek == DayOfWeek.Saturday || submissionDateAndTime.DayOfWeek == DayOfWeek.Sunday) throw new InvalidOperationException("Submission day must be in range [Monday...Friday]"); Title = title; Description = description; SubmissionDateAndTime = submissionDateAndTime; Course = course; } public override bool Equals(object obj) { if (obj is Assignment) { var objAsAssignment = (Assignment)obj; return (objAsAssignment.Title == Title) && (objAsAssignment.Description == Description) && (objAsAssignment.Course == Course); } return false; } public override string ToString() { return $"Course[{Course.Id}], {Title}, {Description}, Sub DateAndTime: {SubmissionDateAndTime}"; } } }
using System; using System.Collections.Immutable; using OmniSharp.Extensions.LanguageServer.Protocol.Models; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { public class SemanticTokensDocument { private readonly SemanticTokensLegend _legend; private Guid _id; internal ImmutableArray<int> Data; internal int DataLen; private ImmutableArray<int>? _prevData; public SemanticTokensDocument(SemanticTokensRegistrationOptions options) : this(options.Legend) { } public SemanticTokensDocument(SemanticTokensLegend legend) { _legend = legend; _prevData = null; Initialize(); } private void Initialize() { _id = Guid.NewGuid(); Data = new ImmutableArray<int>(); DataLen = 0; } public string Id => _id.ToString(); public SemanticTokensBuilder Create() { _prevData = null; return new SemanticTokensBuilder(this, _legend); } public SemanticTokensBuilder Edit(SemanticTokensDeltaParams @params) { if (@params.PreviousResultId == Id) { _prevData = Data; } return new SemanticTokensBuilder(this, _legend); } public SemanticTokens GetSemanticTokens() { _prevData = null; return new SemanticTokens { ResultId = Id, Data = Data }; } public SemanticTokens GetSemanticTokens(Range range) { _prevData = null; var data = ImmutableArray<int>.Empty.ToBuilder(); var currentLine = 0; var currentCharOffset = 0; var capturing = false; var innerOffset = 0; for (var i = 0; i < Data.Length; i += 5) { var lineOffset = Data[i]; currentLine += lineOffset; if (lineOffset > 0) currentCharOffset = 0; if (!capturing) { if (range.Start.Line == currentLine) { var charOffset = Data[i + 1]; var length = Data[i + 2]; // TODO: Do we want to capture partial tokens? // using Sys|tem.Collections.Generic| // ^^^ do we want a token for 'tem`? if (currentCharOffset + charOffset >= range.Start.Character) { capturing = true; // var overlap = ((currentCharOffset + charOffset) - range.Start.Character); data.AddRange(0, charOffset, length, Data[i + 3], Data[i + 4]); continue; } if (currentCharOffset + charOffset + length >= range.Start.Character) { capturing = true; var overlap = currentCharOffset + charOffset + length - range.Start.Character; data.AddRange(0, 0, overlap, Data[i + 3], Data[i + 4]); innerOffset = charOffset - overlap; continue; } currentCharOffset += charOffset; } } else { if (range.End.Line == currentLine) { var charOffset = Data[i + 1]; var length = Data[i + 2]; if (currentCharOffset + charOffset >= range.End.Character) { break; } if (currentCharOffset + charOffset + length >= range.End.Character) { var overlap = currentCharOffset + charOffset + length - range.End.Character; data.AddRange(lineOffset, charOffset, length - overlap, Data[i + 3], Data[i + 4]); break; } currentCharOffset += charOffset; data.AddRange(Data[i], Data[i + 1], Data[i + 2], Data[i + 3], Data[i + 4]); } else { if (innerOffset > 0) { data.AddRange( Data[i], Data[i + 1] - innerOffset, Data[i + 2], Data[i + 3], Data[i + 4] ); innerOffset = 0; } else { data.AddRange(Data[i], Data[i + 1], Data[i + 2], Data[i + 3], Data[i + 4]); } } } } return new SemanticTokens { ResultId = Id, Data = data.ToImmutable() }; } public SemanticTokensFullOrDelta GetSemanticTokensEdits() { if (!_prevData.HasValue) return GetSemanticTokens(); var prevData = _prevData.Value; var prevDataLength = prevData.Length; var dataLength = Data.Length; var startIndex = 0; while (startIndex < dataLength && startIndex < prevDataLength && prevData[startIndex] == Data[startIndex]) { startIndex++; } if (startIndex < dataLength && startIndex < prevDataLength) { // Find end index var endIndex = 0; while (endIndex < dataLength && endIndex < prevDataLength && prevData[prevDataLength - 1 - endIndex] == Data[dataLength - 1 - endIndex]) { endIndex++; } var newData = ImmutableArray.Create(Data, startIndex, dataLength - endIndex - startIndex); var result = new SemanticTokensDelta { ResultId = Id, Edits = new[] { new SemanticTokensEdit { Start = startIndex, DeleteCount = prevDataLength - endIndex - startIndex, Data = newData } } }; return result; } if (startIndex < dataLength) { return new SemanticTokensDelta { ResultId = Id, Edits = new[] { new SemanticTokensEdit { Start = startIndex, DeleteCount = 0, Data = ImmutableArray.Create(Data, startIndex, DataLen - startIndex) } } }; } if (startIndex < prevDataLength) { return new SemanticTokensDelta { ResultId = Id, Edits = new[] { new SemanticTokensEdit { Start = startIndex, DeleteCount = prevDataLength - startIndex } } }; } return new SemanticTokensDelta { ResultId = Id, Edits = Array.Empty<SemanticTokensEdit>() }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.GlobeCore; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.DataSourcesGDB; using ESRI.ArcGIS.DataSourcesFile; namespace MapAssign.PuTools { class EvaPara { /// <summary> /// Compute SpatialLocalMoranI /// </summary> /// <param name="PolygonValue">Polygons and their values</param> /// <param name="TargetPo"></param> /// <returns></returns> public double SpatialLocalMoranI(Dictionary<IPolygon, double> PolygonValue, IPolygon TargetPo) { double LM = 0; #region Get AveValue and WeigthMatrix List<double> ValueList = PolygonValue.Values.ToList(); double AveValue = this.AveCompute(ValueList); List<IPolygon> PoList=PolygonValue.Keys.ToList(); List<double> WeigthMatrix=this.GetLinearWeigth(PoList,TargetPo); #endregion #region LM Compute double S = 0; double Z = 0; foreach (KeyValuePair<IPolygon, double> Kv in PolygonValue) { S = S + (Kv.Value - AveValue) * (Kv.Value - AveValue); Z = Z + WeigthMatrix[PoList.IndexOf(Kv.Key)] * (Kv.Value - AveValue); } LM = (PolygonValue[TargetPo] - AveValue) * Z * ValueList.Count / S; #endregion return LM; } /// <summary> /// Compute TimeLocalMoranI for TargetTime /// </summary> /// <param name="TimeValue"></param> /// <param name="TargetTime"></param> /// selfLabel=true 考虑自身权重;selfLabel=false不考虑自身权重 /// <returns></returns> public double TimeLocalMoranI(Dictionary<int, double> TimeValue, int TargetTime,int Type,int T,double w1,double w2,bool selfLabel) { double LM = 0; List<double> ValueList = TimeValue.Values.ToList(); double AveValue = this.AveCompute(ValueList); List<int> TimeList = TimeValue.Keys.ToList(); List<double> WeigthMatrix = new List<double>(); #region 权重计算 if (Type == 1)//普通权重 { WeigthMatrix = this.GetTimeWeigth(TimeValue.Values.ToList(), TargetTime);//Get TimeWeight } else if (Type == 2)//不考虑周期的高斯权重 { WeigthMatrix = this.GetGasuWeigth(TimeValue.Values.ToList(), TargetTime); } else if (Type == 3)//考虑周期的高斯权重 { WeigthMatrix = this.GetGasuWeigthConsiderT(TimeValue.Values.ToList(), TargetTime, T, w1, w2,selfLabel); } #endregion #region LM Compute double S = 0; double Z = 0; foreach (KeyValuePair<int, double> Kv in TimeValue) { S = S + (Kv.Value - AveValue) * (Kv.Value - AveValue); Z = Z + WeigthMatrix[Kv.Key] * (Kv.Value - AveValue); } LM = (TimeValue[TargetTime] - AveValue) * Z * ValueList.Count / S; #endregion return LM; } /// <summary> /// Compute TimeLocalMoranI series /// </summary> /// <param name="TimeValue"></param> /// <param name="TargetTime"></param> /// selfLabel=true 考虑自身权重;selfLabel=false不考虑自身权重 /// <returns></returns> public List<double> TimeLocalMoranIList(Dictionary<int, double> TimeValue,int Type,int T,double w1,double w2,bool selfLabel) { List<int> TimeList = TimeValue.Keys.ToList(); List<double> TimeLocalMoranIList = new List<double>(); for (int i = 0; i < TimeList.Count; i++) { double LocalMoralI = this.TimeLocalMoranI(TimeValue, i, Type, T, w1, w2,selfLabel); TimeLocalMoranIList.Add(LocalMoralI); } return TimeLocalMoranIList; } /// <summary> /// Compute TimeGlobalMoranI /// </summary> /// <param name="TimeValue"></param> /// Type表示权重计算考虑的情况 1普通权重;2不考虑周期的高斯权重;3考虑周期的高斯权重 /// selfLabel=true考虑自身权重;selfLabel=false 不考虑自身权重 /// <returns></returns> public double GlobalTimeMoranI(Dictionary<int, double> TimeValue,int Type,int T,double w1,double w2,bool selfLabel) { double GlobalMoranI = 0; #region Computation List<int> TimeList = TimeValue.Keys.ToList(); double Ave=this.AveCompute(TimeValue.Values.ToList());//Ave value double WeightSum = 0; double S = 0; double Z = 0; for (int i = 0; i < TimeList.Count; i++) { List<double> TimeWeight=new List<double>(); #region 权重计算 if (Type == 1) { TimeWeight = this.GetTimeWeigth(TimeValue.Values.ToList(), i);//Get TimeWeight } else if (Type == 2) { TimeWeight = this.GetGasuWeigth(TimeValue.Values.ToList(), i); } else if (Type == 3) { TimeWeight = this.GetGasuWeigthConsiderT(TimeValue.Values.ToList(), i, T, w1, w2,selfLabel); } #endregion for (int j = 0; j < TimeList.Count; j++) { Z = Z + TimeWeight[j] * (TimeValue[i] - Ave) * (TimeValue[j] - Ave); WeightSum = WeightSum + TimeWeight[j]; } S = S + (TimeValue[i] - Ave) * (TimeValue[i] - Ave); } #endregion GlobalMoranI = (Z * TimeList.Count) / (S * WeightSum); return GlobalMoranI; } /// <summary> /// compute the average value /// </summary> /// <returns></returns> /// 0=Nodata;Else=average value public double AveCompute(List<double> ValueList) { if (ValueList.Count > 0) { double AveValue = 0; double SumValue = 0; foreach (double Value in ValueList) { SumValue = SumValue + Value; } AveValue = SumValue / ValueList.Count; return AveValue; } else { return -1; } } /// <summary> /// compute the touch relation between polygons /// </summary> /// <param name="PoList"></param> /// <returns></returns> 0=NoTouch;1=Touch public int[,] GetTouchRelation(List<IPolygon> PoList) { int FeatureNum = PoList.Count; int[,] matrixGraph = new int[FeatureNum, FeatureNum]; #region 矩阵初始化(不相邻用0表示) for (int i = 0; i < FeatureNum; i++) { for (int j = 0; j < FeatureNum; j++) { matrixGraph[i, j] = 0; } } #endregion #region 矩阵赋值(0表示不邻接;1表示相交或邻接;) for (int i = 0; i < FeatureNum; i++) { IPolygon pPolygon1 = PoList[i]; ITopologicalOperator pTopo = pPolygon1 as ITopologicalOperator; for (int j = 0; j < FeatureNum; j++) { if (j != i) { IPolygon pPolygon2 = PoList[j]; IGeometry iGeo1 = pTopo.Intersect(pPolygon2, esriGeometryDimension.esriGeometry0Dimension); IGeometry iGeo2 = pTopo.Intersect(pPolygon2, esriGeometryDimension.esriGeometry1Dimension); if (!iGeo1.IsEmpty || !iGeo2.IsEmpty) { matrixGraph[i, j] = matrixGraph[j, i] = 1; } } } } #endregion return matrixGraph; } /// <summary> /// Compute the weight between polygons /// </summary> /// <param name="PoList"></param> /// /// <param name="TargetPo"></param> /// <returns></returns> public double[,] GetWeigth(List<IPolygon> PoList,IPolygon TargetPo) { double TargetLength = TargetPo.Length;//Length of TargetPo int FeatureNum = PoList.Count; double[,] IntersectLengthMatrix = new double[FeatureNum, FeatureNum]; for (int i = 0; i < FeatureNum; i++) { IPolygon pPolygon1 = PoList[i]; ITopologicalOperator pTopo = pPolygon1 as ITopologicalOperator; for (int j = 0; j < FeatureNum; j++) { if (i != j) { IPolygon pPolygon2 = PoList[j]; IGeometry iGeo1 = pTopo.Intersect(pPolygon2, esriGeometryDimension.esriGeometry1Dimension); if (!iGeo1.IsEmpty) { IPolyline pPolyline = iGeo1 as IPolyline; IntersectLengthMatrix[i, j] = IntersectLengthMatrix[j, i] = pPolyline.Length / TargetLength; } else { IntersectLengthMatrix[i, j] = IntersectLengthMatrix[j, i] = 0; } } else { IntersectLengthMatrix[i, j] = IntersectLengthMatrix[j, i] = 0; } } } return IntersectLengthMatrix; } /// <summary> /// Compute the weight between polygons /// </summary> /// <param name="PoList"></param> /// /// <param name="TargetPo"></param> /// <returns></returns> public List<double> GetLinearWeigth(List<IPolygon> PoList, IPolygon TargetPo) { double TargetLength = TargetPo.Length;//Length of TargetPo int FeatureNum = PoList.Count; ITopologicalOperator pTopo = TargetPo as ITopologicalOperator; List<double> IntersectLengthMatrix = new List<double>(); for (int i = 0; i < FeatureNum; i++) { int j = PoList.IndexOf(TargetPo); if (i != j) { IPolygon pPolygon2 = PoList[i]; IGeometry iGeo1 = pTopo.Intersect(pPolygon2, esriGeometryDimension.esriGeometry1Dimension); if (!iGeo1.IsEmpty) { IPolyline pPolyline = iGeo1 as IPolyline; IntersectLengthMatrix.Add(pPolyline.Length / TargetLength); } else { IntersectLengthMatrix.Add(0); } } else { IntersectLengthMatrix.Add(0); } } return IntersectLengthMatrix; } /// <summary> /// Compute the weight between two Times /// </summary> /// <returns></returns> public List<double> GetTimeWeigth(List<Double> ValueList, int TimeIndex) { List<double> TimeWeight = new List<double>(); #region TimeIndex=0 //考虑了边缘的情况 if (TimeIndex == 0) { for (int i = 0; i < ValueList.Count; i++) { if(i==1) { TimeWeight.Add(0.7); } else if (i == 2) { TimeWeight.Add(0.3); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=1 //考虑了边缘的情况 else if (TimeIndex == 1) { for (int i = 0; i < ValueList.Count; i++) { if (i == 0) { TimeWeight.Add(0.41); } else if (i == 2) { TimeWeight.Add(0.41); } else if (i == 3) { TimeWeight.Add(0.18); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=ValueList.count-1 //考虑了边缘的情况 else if (TimeIndex == ValueList.Count - 1) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 2) { TimeWeight.Add(0.7); } else if (i == ValueList.Count - 3) { TimeWeight.Add(0.3); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=ValueList.count-2 //考虑了边缘的情况 else if (TimeIndex == ValueList.Count - 2) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 1) { TimeWeight.Add(0.41); } else if (i == ValueList.Count - 3) { TimeWeight.Add(0.41); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.18); } else { TimeWeight.Add(0); } } } #endregion #region Else else { for (int i = 0; i < ValueList.Count; i++) { if (i == TimeIndex - 1) { TimeWeight.Add(0.35); } else if (i == TimeIndex - 2) { TimeWeight.Add(0.15); } else if (i == TimeIndex + 1) { TimeWeight.Add(0.35); } else if (i == TimeIndex + 2) { TimeWeight.Add(0.15); } else { TimeWeight.Add(0); } } } #endregion return TimeWeight; } /// <summary> /// Compute the weight between two Times 高斯权重 /// </summary> /// <returns></returns> public List<double> GetGasuWeigth(List<Double> ValueList, int TimeIndex) { List<double> TimeWeight = new List<double>(); #region TimeIndex=0 if (TimeIndex == 0) { for (int i = 0; i < ValueList.Count; i++) { if (i == 1) { TimeWeight.Add(0.6826); } else if (i == 2) { TimeWeight.Add(0.2718); } else if (i == 3) { TimeWeight.Add(0.0456); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=1 else if (TimeIndex == 1) { for (int i = 0; i < ValueList.Count; i++) { if (i == 0) { TimeWeight.Add(0.6826 / 1.6826); } else if (i == 2) { TimeWeight.Add(0.6826 / 1.6826); } else if (i == 3) { TimeWeight.Add(0.2718 / 1.6826); } else if(i==4) { TimeWeight.Add(0.0456 / 1.6826); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex==2 else if (TimeIndex == 2) { for (int i = 0; i < ValueList.Count; i++) { if (i == 0) { TimeWeight.Add(0.2718 / 1.9544); } else if (i == 1) { TimeWeight.Add(0.6826 / 1.9544); } else if (i == 3) { TimeWeight.Add(0.6826 / 1.9544); } else if (i == 4) { TimeWeight.Add(0.2718 / 1.9544); } else if (i == 5) { TimeWeight.Add(0.0456 / 1.9544); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=ValueList.count-1 else if (TimeIndex == ValueList.Count - 1) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 2) { TimeWeight.Add(0.6826); } else if (i == ValueList.Count - 3) { TimeWeight.Add(0.2718); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.0456); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=ValueList.count-2 else if (TimeIndex == ValueList.Count - 2) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 1) { TimeWeight.Add(0.6826 / 1.6826); } else if (i == ValueList.Count - 3) { TimeWeight.Add(0.6826 / 1.6826); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.2718 / 1.6826); } else if (i == ValueList.Count - 5) { TimeWeight.Add(0.0456 / 1.6826); } else { TimeWeight.Add(0); } } } #endregion #region TimeIndex=ValueList.count-3 else if (TimeIndex == ValueList.Count - 3) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 1) { TimeWeight.Add(0.2718 / 1.9544); } if (i == ValueList.Count - 2) { TimeWeight.Add(0.6826 / 1.9544); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.6826 / 1.9544); } else if (i == ValueList.Count - 5) { TimeWeight.Add(0.2718 / 1.9544); } else if (i == ValueList.Count - 6) { TimeWeight.Add(0.0456 / 1.9544); } else { TimeWeight.Add(0); } } } #endregion #region Else else { for (int i = 0; i < ValueList.Count; i++) { if (i == TimeIndex - 1) { TimeWeight.Add(0.6826 / 2); } else if (i == TimeIndex - 2) { TimeWeight.Add(0.2718 / 2); } else if (i == TimeIndex - 3) { TimeWeight.Add(0.0456 / 2); } else if (i == TimeIndex + 1) { TimeWeight.Add(0.6826 / 2); } else if (i == TimeIndex + 2) { TimeWeight.Add(0.2718 / 2); } else if (i == TimeIndex + 3) { TimeWeight.Add(0.0456 / 2); } else { TimeWeight.Add(0); } } } #endregion return TimeWeight; } /// <summary> /// Compute the weight between two Times 高斯权重 /// </summary> /// <param name="ValueList">其他时刻</param> /// <param name="TimeIndex">给定时刻</param> /// <param name="T">周期</param> /// <param name="w1">周期内权重</param> /// <param name="w2">周期外</param> /// selfLabel=true,权重计算考虑自身;selfLable=false,权重计算不考虑自身 /// <returns></returns> public List<double> GetGasuWeigthConsiderT(List<Double> ValueList, int TimeIndex,int T,double w1,double w2,bool selfLabel) { List<double> TimeWeight = new List<double>(); #region TimeIndex=0 if (TimeIndex == 0) { for (int i = 0; i < ValueList.Count; i++) { if (i == 1) { TimeWeight.Add(0.6826 * w1); } else if (i == 2) { TimeWeight.Add(0.2718 * w1); } else if (i == 3) { TimeWeight.Add(0.0456 * w1); } else { if (Math.Abs(i - TimeIndex) >= T && Math.Abs(i - TimeIndex) % T == 0) { int D = Math.Abs(i - TimeIndex) / T; if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } } } #endregion #region TimeIndex=1 else if (TimeIndex == 1) { for (int i = 0; i < ValueList.Count; i++) { if (i == 0) { TimeWeight.Add(0.6826 / 1.6826 * w1); } else if (i == 2) { TimeWeight.Add(0.6826 / 1.6826 * w1); } else if (i == 3) { TimeWeight.Add(0.2718 / 1.6826 * w1); } else if (i == 4) { TimeWeight.Add(0.0456 / 1.6826 * w1); } else { if (Math.Abs(i - TimeIndex) >= T && Math.Abs(i - TimeIndex) % T == 0) { int D = Math.Abs(i - TimeIndex) / T; if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } } } #endregion #region TimeIndex==2 else if (TimeIndex == 2) { for (int i = 0; i < ValueList.Count; i++) { if (i == 0) { TimeWeight.Add(0.2718 / 1.9544 * w1); } else if (i == 1) { TimeWeight.Add(0.6826 / 1.9544 * w1); } else if (i == 3) { TimeWeight.Add(0.6826 / 1.9544 * w1); } else if (i == 4) { TimeWeight.Add(0.2718 / 1.9544 * w1); } else if (i == 5) { TimeWeight.Add(0.0456 / 1.9544 * w1); } else { if (Math.Abs(i - TimeIndex) >= T && Math.Abs(i - TimeIndex) % T == 0) { int D = Math.Abs(i - TimeIndex) / T; if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } } } #endregion #region TimeIndex=ValueList.count-1 else if (TimeIndex == ValueList.Count - 1) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 2) { TimeWeight.Add(0.6826 * w1); } else if (i == ValueList.Count - 3) { TimeWeight.Add(0.2718 * w1); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.0456 * w1); } else { if (Math.Abs(i - TimeIndex) >= T && Math.Abs(i - TimeIndex) % T == 0) { int D = Math.Abs(i - TimeIndex) / T; if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } } } #endregion #region TimeIndex=ValueList.count-2 else if (TimeIndex == ValueList.Count - 2) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 1) { TimeWeight.Add(0.6826 / 1.6826 * w1); } else if (i == ValueList.Count - 3) { TimeWeight.Add(0.6826 / 1.6826 * w1); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.2718 / 1.6826 * w1); } else if (i == ValueList.Count - 5) { TimeWeight.Add(0.0456 / 1.6826 * w1); } else { if (Math.Abs(i - TimeIndex) >= T && Math.Abs(i - TimeIndex) % T == 0) { int D = Math.Abs(i - TimeIndex) / T; if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } } } #endregion #region TimeIndex=ValueList.count-3 else if (TimeIndex == ValueList.Count - 3) { for (int i = 0; i < ValueList.Count; i++) { if (i == ValueList.Count - 1) { TimeWeight.Add(0.2718 / 1.9544 * w1); } if (i == ValueList.Count - 2) { TimeWeight.Add(0.6826 / 1.9544 * w1); } else if (i == ValueList.Count - 4) { TimeWeight.Add(0.6826 / 1.9544 * w1); } else if (i == ValueList.Count - 5) { TimeWeight.Add(0.2718 / 1.9544 * w1); } else if (i == ValueList.Count - 6) { TimeWeight.Add(0.0456 / 1.9544 * w1); } else { if (Math.Abs(i - TimeIndex) >= T && Math.Abs(i - TimeIndex) % T == 0) { int D = Math.Abs(i - TimeIndex) / T; if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } } } #endregion #region Else else { for (int i = 0; i < ValueList.Count; i++) { #region 获得距离 int D = 0; if (Math.Abs(i - TimeIndex) < T) { D = Math.Abs(i - TimeIndex); } else { if (Math.Abs(i - TimeIndex) % T == 0) { D = Math.Abs(i - TimeIndex) / T; } } #endregion #region 周期内权重 if (Math.Abs(i - TimeIndex) < T) { if (D == 1) { TimeWeight.Add(0.6826 * w1 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w1 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w1 / 2); } else { if (selfLabel) { if (i == TimeIndex) { TimeWeight.Add(0.5); } else { TimeWeight.Add(0); } } else { TimeWeight.Add(0); } } } #endregion #region 周期外权重 else { if (D == 1) { TimeWeight.Add(0.6826 * w2 / 2); } else if (D == 2) { TimeWeight.Add(0.2718 * w2 / 2); } else if (D == 3) { TimeWeight.Add(0.0456 * w2 / 2); } else { TimeWeight.Add(0); } } #endregion } } #endregion return TimeWeight; } /// <summary> /// Compute the class Entroy /// </summary> /// <param name="FreList"></param>frequency for each class /// Type=1 香农熵模型;Type=2 指数熵模型 /// <returns></returns> public double ClassEntroy(List<double> FreList,int Type) { double CEntroy = 0; #region 香农熵模型 if (Type == 1) { for (int i = 0; i < FreList.Count; i++) { if (FreList[i] != 1.0 && FreList[i] != 0) { CEntroy = CEntroy - FreList[i] * Math.Log(2, FreList[i]); } } } #endregion #region 指数熵模型 else if (Type == 2) { for (int i = 0; i < FreList.Count; i++) { CEntroy = CEntroy + FreList[i] * Math.Exp(1 - FreList[i]); } } #endregion return CEntroy; } /// <summary> /// Compute the class Entroy /// </summary> /// <param name="FreList"></param>frequency for each class /// Type=1 香农熵模型;Type=2 指数熵模型 /// <returns></returns> public double ClassEntroy(List<int> ClassList,int Type) { List<int> SingleClass = ClassList.Distinct().ToList(); List<double> FreList = new List<double>(); #region GetFreList for (int i = 0; i < SingleClass.Count; i++) { int Count = 0; for (int j = 0; j < ClassList.Count; j++) { if (ClassList[j] == SingleClass[i]) { Count++; } } double Fre = (double)Count / ClassList.Count;//Int/Int may a Int FreList.Add(Fre); } #endregion return this.ClassEntroy(FreList,Type); } /// <summary> /// Compute the metric entroy of a map (ClassEntroy) /// 每一类的总面积 /// </summary> /// <param name="PolygonValue"></param> /// Type=1 香农熵模型;Type=2 指数熵模型 /// <returns></returns> public double MapMetricEntroy1(Dictionary<IPolygon, int> PolygonValue,int Type) { double MMEntroy = 0; #region MapMetricEntroy double SumArea = this.GetSumArea(PolygonValue.Keys.ToList()); #region GetSingleClass List<int> ClassInt = new List<int>(); foreach (KeyValuePair<IPolygon, int> kv in PolygonValue) { ClassInt.Add(kv.Value); } List<int> SingleClass = ClassInt.Distinct().ToList(); #endregion for (int i = 0; i < SingleClass.Count; i++) { List<IPolygon> ClassPolygon = new List<IPolygon>(); foreach (KeyValuePair<IPolygon, int> kv in PolygonValue) { if (kv.Value == SingleClass[i]) { ClassPolygon.Add(kv.Key); } } double SumClassArea=this.GetSumArea(ClassPolygon); #region 香农熵 if (Type == 1) { if (SumClassArea / SumArea != 1 && SumClassArea / SumArea != 0) { MMEntroy = MMEntroy - SumClassArea / SumArea * Math.Log(2, SumClassArea / SumArea); } } #endregion #region 指数熵 else if (Type == 2) { MMEntroy = MMEntroy + SumClassArea / SumArea * Math.Exp(1 - SumClassArea / SumArea); } #endregion } #endregion return MMEntroy; } /// <summary> /// Compute the metric entroy of a map (UnitClassEntroy) /// 每一个区域的面积 /// </summary> /// <param name="PolygonValue"></param> /// Type=1 香农熵模型;Type=2 指数熵模型 /// <returns></returns> public double MapMetricEntroy2(Dictionary<IPolygon, int> PolygonValue,int Type) { double MMEntroy = 0; #region MapMetricEntroy double SumArea = this.GetSumArea(PolygonValue.Keys.ToList()); foreach (KeyValuePair<IPolygon, int> kv in PolygonValue) { IPolygon pPolygon = kv.Key; IArea pArea = pPolygon as IArea; double Area = pArea.Area; #region 香农熵 if (Type == 1) { MMEntroy = MMEntroy - Area / SumArea * Math.Log(2, Area / SumArea); } #endregion #region 指数熵 else if(Type==2) { MMEntroy = MMEntroy + Area / SumArea * Math.Exp(1 - Area / SumArea); } #endregion } #endregion return MMEntroy; } /// <summary> /// Compute the Thematic Entroy of a map /// </summary> /// <param name="PolygonValue"></param> /// Type=1 香农熵模型;Type=2 指数熵模型 /// <returns></returns> public double MapThematicEntroy(Dictionary<IPolygon, int> PolygonValue,int Type) { double MTEntroy = 0; List<IPolygon> PoList = PolygonValue.Keys.ToList(); int[,] TouchMatrix = this.GetTouchRelation(PoList);//Compute touch relation 0=NoTouch;1=Touch #region GetSingleClass List<int> ClassInt = new List<int>(); foreach (KeyValuePair<IPolygon, int> kv in PolygonValue) { ClassInt.Add(kv.Value); } List<int> SingleClass = ClassInt.Distinct().ToList(); #endregion #region MapThematicEntroy foreach (KeyValuePair<IPolygon, int> kv in PolygonValue) { #region GetTouchPolygons int PolygonID = PoList.IndexOf(kv.Key); List<IPolygon> TouchPolygons = new List<IPolygon>(); for (int j = 0; j < PoList.Count; j++) { if (TouchMatrix[PolygonID, j] == 1) { TouchPolygons.Add(PoList[j]); } } #endregion Dictionary<int, int> ClassCount = new Dictionary<int, int>();//ClassCount around the target polygon int TouchCount = TouchPolygons.Count;//Touch Polygon Count #region ClassCount around the target polygon for (int j = 0; j < SingleClass.Count; j++) { int Count = 0; for (int k = 0; k < TouchPolygons.Count; k++) { if (PolygonValue[TouchPolygons[k]] == j) { Count++; } } ClassCount.Add(j, Count); } #endregion #region Computation foreach (KeyValuePair<int, int> ckv in ClassCount) { double Fre = (double)ckv.Value / TouchCount;//Int/Int may a Int #region 香农熵 if (Type == 1) { if (Fre != 1.0 && Fre != 0) { MTEntroy = MTEntroy - Fre * Math.Log(2, Fre); } } #endregion #region else if (Type == 2) { MTEntroy = MTEntroy + Fre * Math.Exp(1 - Fre); } #endregion } #endregion } #endregion return MTEntroy; } /// <summary> /// Compute the sum of Area /// </summary> /// <param name="PolygonList"></param> /// <returns></returns> public double GetSumArea(List<IPolygon> PolygonList) { double SumArea = 0; for (int i = 0; i < PolygonList.Count; i++) { IArea pArea = PolygonList[i] as IArea; SumArea = SumArea + pArea.Area; } return SumArea; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player_Manager : MonoBehaviour { // player的路径 string PlayerPath = "prefab/Player/Player"; //play的出生点 public Transform PlayerPoint; //刷出时间 public float PlayerTime; void Awake() { //找到游戏中的Start点,并把它的位置付给PlayerPoint GameObject StartObject = GameObject.FindWithTag("Start"); PlayerPoint = StartObject.GetComponent<Transform>(); //实例化游戏物体 GameObject player = (GameObject)Instantiate(Resources.Load(PlayerPath), PlayerPoint.position, Quaternion.identity); player.AddComponent<PlayerMove>(); player.name = "Player"; StartObject.SetActive(false); } }
using Microsoft.Owin; using Owin; [assembly: OwinStartupAttribute(typeof(JavaCycles.Startup))] namespace JavaCycles { public partial class Startup { public void Configuration(IAppBuilder app) { ConfigureAuth(app); } } }
using GalaSoft.MvvmLight; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BPiaoBao.Client.UIExt.Model { /// <summary> /// 文件详细 /// </summary> public class FileInfoObject : ObservableObject { #region IsUploading /// <summary> /// The <see cref="IsUploading" /> property's name. /// </summary> public const string IsUploadingPropertyName = "IsUploading"; private bool isUploading = false; /// <summary> /// 是否正在上传 或 下载 /// </summary> public bool IsUploading { get { return isUploading; } set { if (isUploading == value) return; RaisePropertyChanging(IsUploadingPropertyName); isUploading = value; RaisePropertyChanged(IsUploadingPropertyName); if (value) ErrorMessage = SuccessMessage = null; } } #endregion #region IsUploaded /// <summary> /// The <see cref="IsUploaded" /> property's name. /// </summary> public const string IsUploadedPropertyName = "IsUploaded"; private bool isUploaded = false; /// <summary> /// 是否已经上传成功 /// </summary> public bool IsUploaded { get { return isUploaded; } set { if (isUploaded == value) return; RaisePropertyChanging(IsUploadedPropertyName); isUploaded = value; RaisePropertyChanged(IsUploadedPropertyName); } } #endregion #region FilePath /// <summary> /// The <see cref="FilePath" /> property's name. /// </summary> public const string FilePathPropertyName = "FilePath"; private string filePath = null; /// <summary> /// 文件路径 /// </summary> public string FilePath { get { return filePath; } set { if (filePath == value) return; RaisePropertyChanging(FilePathPropertyName); filePath = value; RaisePropertyChanged(FilePathPropertyName); } } #endregion #region FileName /// <summary> /// The <see cref="FileName" /> property's name. /// </summary> public const string FileNamePropertyName = "FileName"; private string fileName = null; /// <summary> /// 文件名 /// </summary> public string FileName { get { return fileName; } set { if (fileName == value) return; RaisePropertyChanging(FileNamePropertyName); fileName = value; RaisePropertyChanged(FileNamePropertyName); } } #endregion #region ServerAddress /// <summary> /// The <see cref="ServerAddress" /> property's name. /// </summary> public const string ServerAddressPropertyName = "ServerAddress"; private string serverAddress = null; /// <summary> /// 服务端地址 /// </summary> public string ServerAddress { get { return serverAddress; } set { if (serverAddress == value) return; RaisePropertyChanging(ServerAddressPropertyName); serverAddress = value; RaisePropertyChanged(ServerAddressPropertyName); } } #endregion #region ErrorMessage /// <summary> /// The <see cref="ErrorMessage" /> property's name. /// </summary> public const string ErrorMessagePropertyName = "ErrorMessage"; private string errorMessage = null; /// <summary> /// 错误消息 /// </summary> public string ErrorMessage { get { return errorMessage; } set { if (errorMessage == value) return; RaisePropertyChanging(ErrorMessagePropertyName); errorMessage = value; RaisePropertyChanged(ErrorMessagePropertyName); } } #endregion #region SuccessMessage /// <summary> /// The <see cref="SuccessMessage" /> property's name. /// </summary> public const string SuccessMessagePropertyName = "SuccessMessage"; private string successMessage = null; /// <summary> /// 成功消息 /// </summary> public string SuccessMessage { get { return successMessage; } set { if (successMessage == value) return; RaisePropertyChanging(SuccessMessagePropertyName); successMessage = value; RaisePropertyChanged(SuccessMessagePropertyName); } } #endregion } }
 using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RevisoHomework.model { public interface IRepository<T> where T : IDentifier { string ConnectionString { get; set; } T GetById(string id); T GetByName(string name); IEnumerable<T> GetAll(int limit = 10, int offset = 0); IEnumerable<T> GetByDateBetween(DateTime start, DateTime end, int limit = 10, int offset = 0); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ControllerManager : MonoBehaviour { public SteamVR_TrackedObject[] controllersForInitialization; public ControllerInformation[] controllerInfos; private void Awake() { controllerInfos = new ControllerInformation[controllersForInitialization.Length]; for (int i = 0; i < controllersForInitialization.Length; i++) { VRSensor sensor = null; try { sensor = controllersForInitialization[i].GetComponent<VRSensor>(); } catch (System.NullReferenceException) { Debug.LogError("The controller: " + controllersForInitialization[i] + " has no VRSensor attached."); } controllerInfos[i] = new ControllerInformation(controllersForInitialization[i], sensor); } } public SteamVR_Controller.Device GetController(int index) { int deviceIndex = (int)controllerInfos[index].trackedObj.index; if (deviceIndex >= 0) { return SteamVR_Controller.Input(deviceIndex); } else { return null; } } public SteamVR_Controller.Device GetController(SteamVR_TrackedObject trackedObj) { int deviceIndex = (int)trackedObj.index; if (deviceIndex >= 0) { return SteamVR_Controller.Input(deviceIndex); } else { return null; } } public bool ButtonHeldDownBothController(Valve.VR.EVRButtonId button) { if (controllerInfos.Length == 0) { return false; } for (int i = 0; i < controllerInfos.Length; i++) { if (GetController(i) == null) return false; if (!GetController(i).GetPress(button)) { return false; } } return true; } public ControllerInformation GetControllerInfo(SteamVR_TrackedObject obj) { foreach (var item in controllerInfos) { if (item.trackedObj == obj) { return item; } } return null; } public ControllerInformation getOtherController(ControllerInformation controller) { foreach (var item in controllerInfos) { if (item != controller) { return item; } } return null; } }
using System; using FluentAssertions; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using TestingUtils; using Xunit; namespace Lsp.Tests.Models { public class LocationOrLocationLinksTests { [Theory] [JsonFixture] public void SimpleTest(string expected) { var model = new LocationOrLocationLinks(); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject<LocationOrLocationLinks>(expected); deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); } [Theory] [JsonFixture] public void LocationTest(string expected) { var model = new LocationOrLocationLinks( new Location { Range = new Range(new Position(1, 1), new Position(3, 3)), } ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject<LocationOrLocationLinks>(expected); deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); } [Theory] [JsonFixture] public void LocationsTest(string expected) { var model = new LocationOrLocationLinks( new Location { Range = new Range(new Position(1, 1), new Position(3, 3)), }, new Location { Range = new Range(new Position(1, 1), new Position(3, 3)), } ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject<LocationOrLocationLinks>(expected); deresult.Should().BeEquivalentTo(model, x => x.UsingStructuralRecordEquality()); } [Theory] [JsonFixture] public void LocationLinkTest(string expected) { var model = new LocationOrLocationLinks( new LocationLink { TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), TargetRange = new Range(new Position(1, 1), new Position(3, 3)), TargetUri = new Uri("file:///asdfasdf/a.tst"), OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), } ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject<LocationOrLocationLinks>(expected); deresult.Should().BeEquivalentTo( model, x => x.UsingStructuralRecordEquality() .ComparingByMembers<LocationOrLocationLink>() ); } [Theory] [JsonFixture] public void LocationLinksTest(string expected) { var model = new LocationOrLocationLinks( new LocationLink { TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), TargetRange = new Range(new Position(1, 1), new Position(3, 3)), TargetUri = new Uri("file:///asdfasdf/a.tst"), OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), }, new LocationLink { TargetSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), TargetRange = new Range(new Position(1, 1), new Position(3, 3)), TargetUri = new Uri("file:///asdfasdf/a.tst"), OriginSelectionRange = new Range(new Position(1, 1), new Position(3, 3)), } ); var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new LspSerializer(ClientVersion.Lsp3).DeserializeObject<LocationOrLocationLinks>(expected); deresult.Should().BeEquivalentTo( model, x => x.UsingStructuralRecordEquality() .ComparingByMembers<LocationOrLocationLink>() .ComparingByMembers<Location>() .ComparingByMembers<LocationLink>() ); } } }