text
stringlengths
13
6.01M
using System; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using MovieFlow.Areas.Identity.Data; using MovieFlow.Data; [assembly: HostingStartup(typeof(MovieFlow.Areas.Identity.IdentityHostingStartup))] namespace MovieFlow.Areas.Identity { public class IdentityHostingStartup : IHostingStartup { public void Configure(IWebHostBuilder builder) { builder.ConfigureServices((context, services) => { services.AddDbContext<AuthorizationDbContext>(options => options.UseSqlServer( context.Configuration.GetConnectionString("AuthorizationDbContextConnection"))); services.AddDefaultIdentity<ApplicationUser>(options => { options.SignIn.RequireConfirmedAccount = false; // options.Password.RequireLowercase = false; // options.Password.RequireDigit = false; }) .AddEntityFrameworkStores<AuthorizationDbContext>(); }); } } }
using LuckyMasale.DAL.DataProviders; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LuckyMasale.BAL.Managers { public interface ICategoryManager { } public class CategoryManager:ICategoryManager { private Lazy<ICategoryDataProvider> categoryDataProvider; public CategoryManager(Lazy<ICategoryDataProvider> categoryDataProvider) { this.categoryDataProvider = categoryDataProvider; } } }
using System; using System.Threading.Tasks; using Aquamonix.Mobile.Lib.Domain; using Aquamonix.Mobile.Lib.Domain.Responses; namespace Aquamonix.Mobile.Lib.Utilities.WebSockets { public delegate void ConnectionEventHandler(object sender, ConnectionEventArgs e); public delegate void RequestEventHandler(object sender, RequestEventArgs e); public delegate void RequestFailureEventHandler(object sender, RequestFailureEventArgs e); public delegate void ConnectionClosedEventHandler(object sender, ConnectionClosedEventArgs e); public enum RequestFailureReason { Network, ServerRequestedReconnect, Timeout, Auth, ServerDown, Error } public class ConnectionEventArgs : EventArgs { public ConnectionEventArgs() : base() { } } public class RequestEventArgs: ConnectionEventArgs { public IApiRequest Request { get; private set; } public IApiResponse Response { get; private set; } public RequestEventArgs(IApiRequest request, IApiResponse response) : base() { this.Request = request; this.Response = response; } } public class RequestFailureEventArgs : RequestEventArgs { public RequestFailureReason FailureReason { get; private set; } public Action OnResume { get; private set; } public bool ForegroundAction { get; private set; } public RequestFailureEventArgs(IApiRequest request, IApiResponse response, RequestFailureReason reason, bool foregroundAction) : base(request, response) { this.FailureReason = reason; this.ForegroundAction = foregroundAction; } public RequestFailureEventArgs(IApiRequest request, IApiResponse response, RequestFailureReason reason, bool foregroundAction, Action onResume) : this(request, response, reason, foregroundAction) { this.OnResume = onResume; } } public class ConnectionClosedEventArgs : ConnectionEventArgs { public ConnectionClosedEventArgs() : base() { } } /// <summary> /// Interface for client-side websockets connection. /// </summary> public interface IWebSocketsClient : IDisposable { event ConnectionEventHandler ConnectionOpened; event ConnectionClosedEventHandler ConnectionClosed; event ConnectionEventHandler ConnectionFailed; event RequestEventHandler RequestSucceeded; event RequestFailureEventHandler RequestFailed; /// <summary> /// Gets a value indicating whether or not the client is currently connected. /// </summary> bool IsConnected { get; } /// <summary> /// Sets the server side url. /// </summary> /// <param name="url">The value to set.</param> void SetUrl(string url); /// <summary> /// Execute a request against the server, and wait for the response. /// </summary> /// <param name="request">The request to execute.</param> /// <param name="callback">Optional callback on completion.</param> /// <param name="silentMode">If true, no alerts or popups will be shown</param> /// <returns>A Task result</returns> Task<TResponse> DoRequestAsync<TRequest, TResponse>(TRequest request, Action callback, bool silentMode = false) where TRequest : IApiRequest where TResponse : IApiResponse, new(); /// <summary> /// Register a callback for updates from an async write command. /// </summary> /// <param name="commandId">The id of the command for which to register updates.</param> /// <param name="callback">The callback to register.</param> void RegisterForProgressUpdates(string commandId, Action<ProgressResponse> callback); /// <summary> /// Unregister a previously registered callback for updates from an async write command. /// </summary> /// <param name="commandId">The id of the command from which to unregister updates.</param> void UnregisterFromProgressUpdates(string commandId); /// <summary> /// Disconnects the connection from the server. /// </summary> /// <returns>A void task.</returns> Task Disconnect(); } }
using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using OpenQA.Selenium.Support.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace KeepTeamAutotests.Pages { public class DeleteEmployeePopup : PopupPage { [FindsBy(How = How.XPath, Using = "//li[1]/span/input")] private IWebElement CheckBox1; [FindsBy(How = How.XPath, Using = "//li[2]/span/input")] private IWebElement CheckBox2; [FindsBy(How = How.XPath, Using = "//li[3]/span/input")] private IWebElement CheckBox3; [FindsBy(How = How.XPath, Using = "//li[4]/span/input")] private IWebElement CheckBox4; [FindsBy(How = How.XPath, Using = "//div[@class ='l-right']/button")] private IWebElement DeleteButton; public DeleteEmployeePopup(PageManager pageManager) : base(pageManager) { pagename = "deleteuserpopup"; } public void setCheckBoxAll() { CheckBox1.Click(); CheckBox2.Click(); CheckBox3.Click(); CheckBox4.Click(); } public void deleteButtonClick() { DeleteButton.Click(); waitSaveDone(); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace BookStorage.Models { public class Book { public int Id { get; set; } public string Title { get; set; } public int YearPublish{ get; set; } public int Price { get; set; } public int? AuthorId { get; set; } public Author Author { get; set; } //navigation property } }
using EmployeeTaskMonitor.Core.Models; using EmployeeTaskMonitor.Core.ServiceInterfaces; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EmployeeTaskMonitor.API.Controllers { [Route("api/[controller]")] [ApiController] public class EmployeesController : ControllerBase { private readonly IEmployeeService _employeeService; public EmployeesController(IEmployeeService employeeService) { _employeeService = employeeService; } [HttpGet] [Route("allemployees")] public async Task<IActionResult> GetAllEmployees() { var employees = await _employeeService.GetAllEmployees(); if (!employees.Any()) { return NotFound("No employees"); } return Ok(employees); } [HttpPost("addemployee")] public async Task<IActionResult> CreateEmployee(EmployeeRequestModel employeeCreateRequest) { await _employeeService.AddEmployee(employeeCreateRequest); return Ok(); } } }
using EddiDataDefinitions; using System; using Utilities; namespace EddiEvents { [PublicAPI] public class SRVDockedEvent : Event { public const string NAME = "SRV docked"; public const string DESCRIPTION = "Triggered when you dock an SRV with your ship"; public const string SAMPLE = @"{ ""timestamp"":""2022-11-24T23:45:10Z"", ""event"":""DockSRV"", ""SRVType"":""combat_multicrew_srv_01"", ""SRVType_Localised"":""SRV Scorpion"", ""ID"":53 }"; [PublicAPI("The srv's id")] public int? id { get; private set; } [PublicAPI("The localized SRV type")] public string srvType => vehicleDefinition?.localizedName; [PublicAPI("The invariant SRV type")] public string srvTypeInvariant => vehicleDefinition?.invariantName; // Not intended to be public facing at this time public VehicleDefinition vehicleDefinition { get; private set; } public SRVDockedEvent(DateTime timestamp, VehicleDefinition vehicleDefinition, int? id) : base(timestamp, NAME) { this.vehicleDefinition = vehicleDefinition; this.id = id; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HouseRent.Models { public class DetailOfFlat { public int Id { get; set; } [Required] public string FlatName { get; set; } [Required] public int FlatId { get; set; } [ForeignKey("FlatId")] public Flat Flat { get; set; } [Required] public int RoomNumber { get; set; } [Required] public int BathNumber { get; set; } [Required] public bool CarParking { get; set; } [Required] public string Description { get; set; } public string Photo { get; set; } public int Price { get; set; } } }
using System.Collections.Generic; using System.Xml.XPath; namespace ShutterflyStatusPost { public class OrderInfo { public XPathNavigator Source { get; set; } private List<Item> _items = new List<Item>(); public List<Item> OrderItems { get { return _items; } set { _items = value; } } public OrderInfo(XPathNavigator source) { Source = source; ParseSourceOrder(); } private void ParseSourceOrder() { var items = this.Source.Select("order/orderitems/item"); while (items.MoveNext()) { var item = items.Current; this.OrderItems.Add(new Item(item)); } } } }
using System.ComponentModel; using Cradiator.Extensions; namespace Cradiator.Config { public class ViewSettings : IViewSettings, INotifyPropertyChanged { protected string _url; public string URL { get { return _url; } set { if (_url == value) return; _url = value; Notify("URL"); } } protected string _skinName; public string SkinName { get { return _skinName; } set { if (_skinName == value) return; _skinName = value; Notify("SkinName"); } } protected string _projectNameRegEx; public string ProjectNameRegEx { get { return _projectNameRegEx.GetRegEx(); } set { if (_projectNameRegEx == value) return; _projectNameRegEx = value; Notify("ProjectNameRegEx"); } } protected string _categoryRegEx; public string CategoryRegEx { get { return _categoryRegEx.GetRegEx(); } set { if (_categoryRegEx == value) return; _categoryRegEx = value; Notify("CategoryRegEx"); } } protected string _viewName; public string ViewName { get { return _viewName; } set { if (_viewName == value) return; _viewName = value; Notify("ViewName"); } } protected bool _showOnlyBroken; public bool ShowOnlyBroken { get { return _showOnlyBroken; } set { if (_showOnlyBroken == value) return; _showOnlyBroken = value; Notify("ShowOnlyBroken"); } } protected string _serverNameRegEx; public string ServerNameRegEx { get { return _serverNameRegEx;} set { if (_serverNameRegEx == value) return; _serverNameRegEx = value; Notify("ServerNameRegEx"); } } protected bool _ShowServerName; public bool ShowServerName { get { return _ShowServerName; } set { if (_ShowServerName == value) return; _ShowServerName = value; Notify("ShowServerName"); } } private bool _showOutOfDate; public bool ShowOutOfDate { get { return _showOutOfDate; } set { if (_showOutOfDate == value) return; _showOutOfDate = value; Notify("ShowOutOfDate"); } } private int _outOfDateDifferenceInMinutes; public int OutOfDateDifferenceInMinutes { get { return _outOfDateDifferenceInMinutes; } set { if (_outOfDateDifferenceInMinutes == value) return; _outOfDateDifferenceInMinutes = value; Notify("OutOfDateDifferenceInMinutes"); } } public event PropertyChangedEventHandler PropertyChanged; protected void Notify(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
namespace PizzaBox.Domain { public class PizzaFactory { //this entire class is awful, come up with something better Location _location; public PizzaFactory(Location loc) { _location = loc; } public string ListPresets() { return "Specialty Pizzas:\n" + "hawaiian"; } public Pizza MakeHawaiian() { InventoryItem hamItem = _location.Inventory.GetInventoryItem("Ham"); InventoryItem pineappleItem = _location.Inventory.GetInventoryItem("Pineapple"); if(!(hamItem is null) && !(pineappleItem is null)) { Topping ham = (Topping) hamItem.item; Topping pineapple = (Topping) pineappleItem.item; Pizza p = new Pizza(); p.AddTopping(ham); p.AddTopping(pineapple); return p; } else return null; } } }
using System; namespace L03ToDos { //2.ToDo public class Person { public string Name; public int Age; /*anzahl der jahre */ public override string ToString() { //ToString wandele den aufgerufenen in einen string um return $"Name: { Name }, Alter: { Age }"; } } class Program { static void Main(string[] args) { //int i = 4245; //bsp //2. ToDo //Person einePerson = new Person(); -> Array für call stack Person[] personen ={ new Person{ Name = "Horst", Age = 42}, new Person{ Name = "Dieter", Age = 46}, new Person{ Name = "Karl", Age = 79}, new Person{ Name = "Schorsch", Age = 45}, new Person{ Name = "Ernst", Age = 39}, }; foreach (var person in personen) { MachWasMitPerson(person); } } static void MachWasMitPerson(Person person) { if (person.Age > 40) { Console.WriteLine("Du bist alt!"); } else { Console.WriteLine("On the right side of fourty..."); } } // einePerson.Name = "Horst"; //einePerson.Age = 42; //Console.WriteLine(i); /*bsp, Inhalt einer integer variable angegeben statt zeichenkette, beachte Integer-Arithmetik */ //Console.WriteLine(einePerson); /*name L03ToDos.Person, daher einePerson.Name */ //} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.Rendering.Universal; public class Player : MonoBehaviour { public float ms = 6; public int life = 3; // Light radius private float timer = 0.0f; private float timeToFade = 1.0f; private float timeToShine = 20.0f; private float timeToPower = 2.0f; private float initialRadius; private Light2D point_light; // Start is called before the first frame update void Start() { point_light = GetComponentInChildren<Light2D>(); initialRadius = point_light.pointLightOuterRadius; } // Update is called once per frame void FixedUpdate() { // transform.Translate(Vector3.up * ms * Time.deltaTime); if (Input.GetKey(KeyCode.LeftArrow)) { transform.Translate(Vector3.left * ms * Time.deltaTime); } if (Input.GetKey(KeyCode.RightArrow)) { transform.Translate(Vector3.right * ms * Time.deltaTime); } // Every second timer += Time.deltaTime; if (timer > timeToFade) { timer = timer - timeToFade; point_light.pointLightOuterRadius = point_light.pointLightOuterRadius - initialRadius/timeToShine; } } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Alga") { point_light.pointLightOuterRadius = Mathf.Clamp(point_light.pointLightOuterRadius + initialRadius/timeToPower, 0, initialRadius); FindObjectOfType<AudioManager>().Play("EatAlgae"); Destroy(other.gameObject); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace TruckPad.Services.Models { public partial class Cidade { public Cidade() { Bairro = new HashSet<Bairro>(); } [Key] public int IdCidade { get; set; } public int IdEstado { get; set; } [Required] [Column("Cidade")] [StringLength(200)] public string Cidade1 { get; set; } [ForeignKey("IdEstado")] [InverseProperty("Cidade")] public Estado IdEstadoNavigation { get; set; } [InverseProperty("IdCidadeNavigation")] public ICollection<Bairro> Bairro { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems { public class Problem171 : ProblemBase { public override string ProblemName { get { return "171: Finding numbers for which the sum of the squares of the digits is a square"; } } public override string GetAnswer() { return Solve1(3).ToString(); return ""; } private ulong _sum = 0; private ulong Solve2(int maxDigit) { BuildSquares(maxDigit); BuildFactorials(); FindCombos(maxDigit, 1, new int[9], 0, 1000000000, maxDigit); return _sum; } private void FindCombos(int remaining, int currentDigit, int[] digits, ulong currentSum, ulong mod, int maxDigit) { if (currentDigit < 9) { FindCombos(remaining, currentDigit + 1, digits, currentSum, mod, maxDigit); } for (int next = 1; next <= remaining; next++) { digits[currentDigit - 1] = next; currentSum += (ulong)(currentDigit * currentDigit); if (_squares.Contains(currentSum)) { FoundOne(digits, currentSum, mod, maxDigit); } if (remaining - next > 0 && currentDigit < 9) { FindCombos(remaining - next, currentDigit + 1, digits, currentSum, mod, maxDigit); } } digits[currentDigit - 1] = 0; } private ulong _count = 0; private void FoundOne(int[] digits, ulong currentSum, ulong mod, int maxDigit) { _count++; ulong last = 1; ulong count = 0; int totalDigits = digits.Sum(); int remaining = totalDigits; for (int digit = 1; digit <= 9; digit++) { if (digits[digit - 1] > 0) { if (count == 0) { count = 1; } else { count = (count * last) % mod; } last = Choose(remaining, digits[digit - 1]); remaining -= digits[digit - 1]; } } _sum = (((count * currentSum) % mod) + _sum) % mod; CalcZeros(count, currentSum, mod, totalDigits, maxDigit); } private void CalcZeros(ulong count, ulong currentSum, ulong mod, int totalDigits, int maxDigit) { ulong sum = 0; for (int zeroCount = 1; zeroCount + totalDigits <= maxDigit; zeroCount++) { sum += Choose(totalDigits + zeroCount - 1, totalDigits - 1); } _sum = (((((count * currentSum) % mod) * sum) % mod) + _sum) % mod; } private ulong Choose(int x, int y) { return _factorial[x] / _factorial[y] / _factorial[x - y]; } private Dictionary<int, ulong> _factorial = new Dictionary<int, ulong>(); private void BuildFactorials() { _factorial.Add(0, 1); _factorial.Add(1, 1); ulong num = 1; for (ulong next = 2; next <= 20; next++) { num = (num * next); _factorial.Add((int)next, num); } } private ulong Solve1(int maxDigit) { BuildSquares(maxDigit); ulong sum = 0; ulong max = (ulong)Math.Pow(10, maxDigit); for (ulong num = 1; num < max; num++) { var digitSum = GetDigitSum(num); if (_squares.Contains(digitSum)) { sum = (sum + num) % 1000000000; } } return sum; } private ulong GetDigitSum(ulong num) { ulong sum = 0; do { var remainder = num % 10; sum += remainder * remainder; num /= 10; } while (num > 0); return sum; } private HashSet<ulong> _squares = new HashSet<ulong>(); private void BuildSquares(int maxDigit) { ulong max = (ulong)Math.Sqrt(maxDigit * 81); for (ulong n = 1; n <= max; n++) { _squares.Add(n * n); } } } }
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; using KartLib.Views; using KartObjects; using KartLib; using KartObjects.Entities; using KartSystem.Views.Dictionary; namespace KartSystem { /// <summary> /// Представление для кассового терминала. Получает список терминалов и отображает их в таблице. /// </summary> public partial class PointOfSaleView : KartUserControl,IPointOfSalesView { public PointOfSaleView() { InitializeComponent(); ViewObjectType = ObjectType.PointOfSale; MainGridView = gvPointOfSale; } PointOfSaleEditor _pointOfSaleEditor; /// <summary> /// Список всех кассовых терминалов /// </summary> public IList<PointOfSale> PointOfSales { get; set; } public override void InitView() { base.InitView(); PointOfSales = KartDataDictionary.sPointOfSales; //Значения членов перецисления POSDeviceType упорядоченные по их описаниям Dictionary<string, PosDeviceType> _POSDeviceTypesIdsByNames = new Dictionary<string, PosDeviceType>(); foreach (PosDeviceType currDT in Enum.GetValues(typeof(PosDeviceType))) { _POSDeviceTypesIdsByNames.Add(currDT.GetDescription(), currDT); } repositoryItemLookUpEdit3.DataSource = new List<KeyValuePair<string, PosDeviceType>>(_POSDeviceTypesIdsByNames); repositoryItemLookUpEdit3.DisplayMember = "Key"; repositoryItemLookUpEdit3.ValueMember = "Value"; repositoryItemLookUpEdit3.Columns.Clear(); repositoryItemLookUpEdit3.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Key", " ")); //Имена членов перечисления DeviceDrivers упорядоченные по их описаниям Dictionary<string, string> deviceDrivers = new Dictionary<string, string>(); foreach (DeviceDrivers dd in Enum.GetValues(typeof(DeviceDrivers))) { deviceDrivers.Add(dd.GetDescription(), Enum.GetName(typeof(DeviceDrivers), dd)); } repositoryItemLookUpEdit4.DataSource = new List<KeyValuePair<string, string>>(deviceDrivers); repositoryItemLookUpEdit4.DisplayMember = "Key"; repositoryItemLookUpEdit4.ValueMember = "Value"; repositoryItemLookUpEdit4.Columns.Clear(); repositoryItemLookUpEdit4.Columns.Add(new DevExpress.XtraEditors.Controls.LookUpColumnInfo("Key", " ")); pointOfSaleBindingSource.DataSource = PointOfSales; pOSGroupBindingSource.DataSource = KartDataDictionary.sPOSGroups = Loader.DbLoad<POSGroup>("")??new List<POSGroup>(); storeBindingSource.DataSource = KartDataDictionary.sStores = Loader.DbLoad<Store>("")??new List<Store>(); storeBindingSource1.DataSource = KartDataDictionary.sStores; gcPointOfSale.RefreshDataSource(); } public override void RefreshView() { base.RefreshView(); pointOfSaleBindingSource.DataSource = PointOfSales; if (PointOfSales == null || PointOfSales.Count == 0) pOSDeviceBindingSource.DataSource = null; pOSGroupBindingSource.DataSource = KartDataDictionary.sPOSGroups = Loader.DbLoad<POSGroup>("") ?? new List<POSGroup>(); storeBindingSource.DataSource = KartDataDictionary.sStores = Loader.DbLoad<Store>("") ?? new List<Store>(); storeBindingSource1.DataSource = KartDataDictionary.sStores; gcPointOfSale.RefreshDataSource(); } public override void EditorAction(bool addMode) { if (addMode) { PointOfSale newPointOfSale = new PointOfSale(); if (KartDataDictionary.sStores == null || KartDataDictionary.sStores.Count == 0) { MessageBox.Show("В системе нет данных о подразделениях!", "Ошибка заведения терминала"); return; } newPointOfSale.IdStore = KartDataDictionary.sStores[0].Id; if (KartDataDictionary.sPOSGroups == null || KartDataDictionary.sPOSGroups.Count == 0) { MessageBox.Show("В системе нет данных о группах устройств!", "Ошибка заведения терминала"); return; } newPointOfSale.IdPOSGroup = KartDataDictionary.sPOSGroups[0].Id; newPointOfSale.Number = (Loader.DbLoad<PointOfSale>("") ?? new List<PointOfSale>()).Count + 1; _pointOfSaleEditor = new PointOfSaleEditor(newPointOfSale); if (_pointOfSaleEditor.ShowDialog() == DialogResult.OK) { Saver.SaveToDb<PointOfSale>(newPointOfSale); PointOfSales.Add(newPointOfSale); KartDataDictionary.sPointOfSales = PointOfSales; RefreshView(); ActiveEntity = newPointOfSale; } gcPointOfSale.RefreshDataSource(); gcDevices.RefreshDataSource(); } else { if (pointOfSaleBindingSource.Current == null) return; _pointOfSaleEditor = new PointOfSaleEditor(pointOfSaleBindingSource.Current as PointOfSale); if (_pointOfSaleEditor.ShowDialog() == DialogResult.OK) { RefreshView(); gcPointOfSale.RefreshDataSource(); gcDevices.RefreshDataSource(); UpdateCurrItem(); }; } } public override bool RecordSelected { get { return pointOfSaleBindingSource.Current != null; } } /// <summary> /// Отображает новый терминал в редакторе. /// Если пользователь сохраняет терминал в редакторе, то добавляет его в список терминалов. /// </summary> //public override void InsertAction(object sender, DevExpress.XtraBars.ItemClickEventArgs e) //{ // if (IsActionBanned(AxiTradeAction.AddNew)) return; // base.InsertAction(sender, e); // PointOfSale newPointOfSale = new PointOfSale(); // Saver.SaveToDb<PointOfSale>(newPointOfSale); // _pointOfSaleEditor = new PointOfSaleEditor(newPointOfSale); // if (_pointOfSaleEditor.ShowDialog() == DialogResult.OK) // { // PointOfSales.Add(newPointOfSale); // RefreshView(); // } // else // { // Saver.DeleteFromDb<PointOfSale>(newPointOfSale); // } // gridControl1.RefreshDataSource(); // gridControl2.RefreshDataSource(); //} ///// <summary> ///// Отображает выбранный в таблице терминал в редакторе ///// </summary> //public override void EditAction(object sender, DevExpress.XtraBars.ItemClickEventArgs e) //{ // if (IsActionBanned(AxiTradeAction.Edit)) return; // if (pointOfSaleBindingSource.Current == null) return; // base.EditAction(sender, e); // _pointOfSaleEditor = new PointOfSaleEditor(pointOfSaleBindingSource.Current as PointOfSale); // if (_pointOfSaleEditor.ShowDialog() == DialogResult.OK) // { // gridControl1.RefreshDataSource(); // gridControl2.RefreshDataSource(); // }; //} public override void DeleteItem(object sender, DevExpress.XtraBars.ItemClickEventArgs e) { PointOfSale gk = pointOfSaleBindingSource.Current as PointOfSale; if (gk != null) { if (MessageBox.Show(this, "Вы уверены что хотите удалить кассовый терминал " + gk.Name, "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { Saver.DeleteFromDb<PointOfSale>(gk); foreach (POSDevice device in gk.POSDevices) Saver.DeleteFromDb<POSDevice>(device); PointOfSales.Remove(gk); gcPointOfSale.RefreshDataSource(); gcDevices.RefreshDataSource(); } } } /// <summary> /// При удалении выбранного в таблице терминала удаляет его а так же все его устройства из БД. /// </summary> //public override void DeleteAction(object sender, DevExpress.XtraBars.ItemClickEventArgs e) //{ // if (IsActionBanned(AxiTradeAction.Delete)) return; // PointOfSale gk = pointOfSaleBindingSource.Current as PointOfSale; // if (gk != null) // { // if (MessageBox.Show(this, "Вы уверены что хотите удалить кассовый терминал " + gk.Name, "Внимание", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) // { // Saver.DeleteFromDb<PointOfSale>(gk); // foreach(POSDevice device in gk.POSDeivces) // Saver.DeleteFromDb<POSDevice>(device); // PointOfSales.Remove(gk); // gridControl1.RefreshDataSource(); // gridControl2.RefreshDataSource(); // } // } //} private void pointOfSaleBindingSource_PositionChanged(object sender, EventArgs e) { UpdateCurrItem(); } private void UpdateCurrItem() { PointOfSale pos = pointOfSaleBindingSource.Current as PointOfSale; if (pos != null) { pOSDeviceBindingSource.DataSource = pos.POSDevices = Loader.DbLoad<POSDevice>("IdPointOfSale=" + pos.Id) ?? new List<POSDevice>(); gcDevices.RefreshDataSource(); } } private void gridControl1_DoubleClick(object sender, EventArgs e) { //EditorAction(false); EditAction(this,null); } public override bool IsEditable { get { return true; } } public override bool IsInsertable { get { return true; } } public override bool UseSubmenu { get { return false; } } public override bool IsDeletable { get { return true; } } public override bool IsPrintable { get { return false; } } } }
using Arda.Common.Interfaces.Reports; namespace Arda.Reports.Repositories { public class ReportsRepository : IReportsRepository { } }
using System; namespace MyGame { public struct GameData { Tuple<string, int> trait1; Tuple<string, int> trait2; int[] _colorRgbArray; string shapeType; public GameData(Tuple<string, int> t1, Tuple<string, int> t2, int[] intArr, string s){ trait1 = t1; trait2 = t2; _colorRgbArray = intArr; shapeType = s; } public Tuple<string, int> Trait1{ get{return trait1;} set{trait1 = value;} } public Tuple<string, int> Trait2{ get{return trait2;} set{trait2 = value;} } public int[] ColorRgbArray{ get{return _colorRgbArray;} } public string ShapeType{ get{return shapeType;} set{shapeType = value;} } } }
using UnityEngine; public class FlickeringLight : MonoBehaviour { private Vector3 startPos; //private Vector2 flickerOffset; [Header("Position related")] public Vector2 flickerRange; //[Range(0, 1)] public Vector2 flickerDeltaRange; public bool randomFlickerDirection; private float startIntensity; //private float intensityOffset; [Header("Intensity related")] public float intensityRange; [Range(0,1)] public float intensityDeltaRange; private float startRot; private float curRot; private float rotTimer; [Header("Angle related(in degree(in 2D(rotation around y, or x in code, because it's already rotated 90 degrees to point forward)))")] public float angleRange; [Range(0, 1)] public float angleDeltaRange; float curIntensity = 0.0f; Vector2 curFlickerPos = Vector2.zero; private Light lightComponent; // Use this for initialization void Start () { lightComponent = GetComponent<Light>(); startPos = transform.localPosition; // flickerOffset = Vector2.zero; startIntensity = lightComponent.intensity; //intensityOffset = 0.0f; startRot = 0; curRot = 0.0f; rotTimer = 0.0f; } // Update is called once per frame void Update () { //position curFlickerPos += TimeManager.instance.gameDeltaTime * (randomFlickerDirection ? new Vector2(Random.Range(-flickerDeltaRange.x, flickerDeltaRange.x), Random.Range(-flickerDeltaRange.y, flickerDeltaRange.y)) : flickerDeltaRange); //Vector3 newPos = startPos + new Vector3(Mathf.Cos(1 * 2 * Mathf.PI * curFlickerPos.x) * flickerRange.x, // Mathf.Sin(1 * 2 * Mathf.PI * curFlickerPos.y) * flickerRange.y, 0); transform.localPosition = startPos + new Vector3(Mathf.Cos(1 * 2 * Mathf.PI * curFlickerPos.x) * flickerRange.x, Mathf.Sin(1 * 2 * Mathf.PI * curFlickerPos.y) * flickerRange.y, 0); ; //intensity curIntensity += TimeManager.instance.gameDeltaTime * intensityDeltaRange; lightComponent.intensity = startIntensity + Mathf.Sin(curIntensity*2*Mathf.PI)*intensityRange; //angle rotTimer += TimeManager.instance.gameDeltaTime*angleDeltaRange; curRot = Mathf.Sin(rotTimer * 2 * Mathf.PI) *angleRange; transform.localRotation = Quaternion.Euler( new Vector3(startRot + curRot, 90,0)); } //public void setStartingRotation(float newRot) //{ //startRot = newRot; //} }
using System; using System.Globalization; namespace Task2 { class Program { //обработчик события ReadFinished static void OnReadFinished() { Console.WriteLine("Чтение из файла input.txt завершено!"); } //обработчик события OnWriteFinished() static void OnWriteFinished() { Console.WriteLine("Запись в файл output.txt завершена!"); } static void Main(string[] args) { Processing p = new Processing(); p.ReadFinished += OnReadFinished; p.WriteFinished += OnWriteFinished; p.Execute(@"C:\Users\user\Desktop\input.txt", @"C:\Users\user\Desktop\output.txt", (string s) => { return s.Length; }, (string s) => { return double.Parse(s, CultureInfo.InvariantCulture); } ); p.ReadFinished -= OnReadFinished; p.WriteFinished -= OnWriteFinished; Console.ReadLine(); } } }
using System; namespace _04_Pascal_Triangle { public class _04_Pascal_Triangle { public static void Main() { var n = int.Parse(Console.ReadLine()); var jaggetArray = new long[n][]; for (int i = 0; i < n; i++) { jaggetArray[i] = new long[i + 1]; jaggetArray[i][0] = 1; jaggetArray[i][jaggetArray[i].Length - 1] = 1; for (int j = 1; j < jaggetArray[i].Length - 1; j++) { jaggetArray[i][j] = jaggetArray[i - 1][j - 1] + jaggetArray[i - 1][j]; } } foreach (var row in jaggetArray) { Console.WriteLine(string.Join(" ", row)); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using Rune = System.Rune; namespace Terminal.Gui { /// <summary> /// Renders an overlay on another view at a given point that allows selecting /// from a range of 'autocomplete' options. /// </summary> public abstract class Autocomplete : IAutocomplete { private class Popup : View { Autocomplete autocomplete; public Popup (Autocomplete autocomplete) { this.autocomplete = autocomplete; CanFocus = true; WantMousePositionReports = true; } public override Rect Frame { get => base.Frame; set { base.Frame = value; X = value.X; Y = value.Y; Width = value.Width; Height = value.Height; } } public override void Redraw (Rect bounds) { if (autocomplete.LastPopupPos == null) { return; } autocomplete.RenderOverlay ((Point)autocomplete.LastPopupPos); } public override bool MouseEvent (MouseEvent mouseEvent) { return autocomplete.MouseEvent (mouseEvent); } } private View top, popup; private bool closed; int toRenderLength; private Point? LastPopupPos { get; set; } private ColorScheme colorScheme; private View hostControl; /// <summary> /// The host control to handle. /// </summary> public virtual View HostControl { get => hostControl; set { hostControl = value; top = hostControl.SuperView; if (top != null) { top.DrawContent += Top_DrawContent; top.DrawContentComplete += Top_DrawContentComplete; top.Removed += Top_Removed; } } } private void Top_Removed (View obj) { Visible = false; ManipulatePopup (); } private void Top_DrawContentComplete (Rect obj) { ManipulatePopup (); } private void Top_DrawContent (Rect obj) { if (!closed) { ReopenSuggestions (); } ManipulatePopup (); if (Visible) { top.BringSubviewToFront (popup); } } private void ManipulatePopup () { if (Visible && popup == null) { popup = new Popup (this) { Frame = Rect.Empty }; top?.Add (popup); } if (!Visible && popup != null) { top.Remove (popup); popup.Dispose (); popup = null; } } /// <summary> /// Gets or sets If the popup is displayed inside or outside the host limits. /// </summary> public bool PopupInsideContainer { get; set; } = true; /// <summary> /// The maximum width of the autocomplete dropdown /// </summary> public virtual int MaxWidth { get; set; } = 10; /// <summary> /// The maximum number of visible rows in the autocomplete dropdown to render /// </summary> public virtual int MaxHeight { get; set; } = 6; /// <summary> /// True if the autocomplete should be considered open and visible /// </summary> public virtual bool Visible { get; set; } /// <summary> /// The strings that form the current list of suggestions to render /// based on what the user has typed so far. /// </summary> public virtual ReadOnlyCollection<string> Suggestions { get; set; } = new ReadOnlyCollection<string> (new string [0]); /// <summary> /// The full set of all strings that can be suggested. /// </summary> /// <returns></returns> public virtual List<string> AllSuggestions { get; set; } = new List<string> (); /// <summary> /// The currently selected index into <see cref="Suggestions"/> that the user has highlighted /// </summary> public virtual int SelectedIdx { get; set; } /// <summary> /// When more suggestions are available than can be rendered the user /// can scroll down the dropdown list. This indicates how far down they /// have gone /// </summary> public virtual int ScrollOffset { get; set; } /// <summary> /// The colors to use to render the overlay. Accessing this property before /// the Application has been initialized will cause an error /// </summary> public virtual ColorScheme ColorScheme { get { if (colorScheme == null) { colorScheme = Colors.Menu; } return colorScheme; } set { colorScheme = value; } } /// <summary> /// The key that the user must press to accept the currently selected autocomplete suggestion /// </summary> public virtual Key SelectionKey { get; set; } = Key.Enter; /// <summary> /// The key that the user can press to close the currently popped autocomplete menu /// </summary> public virtual Key CloseKey { get; set; } = Key.Esc; /// <summary> /// The key that the user can press to reopen the currently popped autocomplete menu /// </summary> public virtual Key Reopen { get; set; } = Key.Space | Key.CtrlMask | Key.AltMask; /// <summary> /// Renders the autocomplete dialog inside or outside the given <see cref="HostControl"/> at the /// given point. /// </summary> /// <param name="renderAt"></param> public virtual void RenderOverlay (Point renderAt) { if (!Visible || HostControl?.HasFocus == false || Suggestions.Count == 0) { LastPopupPos = null; Visible = false; return; } LastPopupPos = renderAt; int height, width; if (PopupInsideContainer) { // don't overspill vertically height = Math.Min (HostControl.Bounds.Height - renderAt.Y, MaxHeight); // There is no space below, lets see if can popup on top if (height < Suggestions.Count && HostControl.Bounds.Height - renderAt.Y >= height) { // Verifies that the upper limit available is greater than the lower limit if (renderAt.Y > HostControl.Bounds.Height - renderAt.Y) { renderAt.Y = Math.Max (renderAt.Y - Math.Min (Suggestions.Count + 1, MaxHeight + 1), 0); height = Math.Min (Math.Min (Suggestions.Count, MaxHeight), LastPopupPos.Value.Y - 1); } } } else { // don't overspill vertically height = Math.Min (Math.Min (top.Bounds.Height - HostControl.Frame.Bottom, MaxHeight), Suggestions.Count); // There is no space below, lets see if can popup on top if (height < Suggestions.Count && HostControl.Frame.Y - top.Frame.Y >= height) { // Verifies that the upper limit available is greater than the lower limit if (HostControl.Frame.Y > top.Bounds.Height - HostControl.Frame.Y) { renderAt.Y = Math.Max (HostControl.Frame.Y - Math.Min (Suggestions.Count, MaxHeight), 0); height = Math.Min (Math.Min (Suggestions.Count, MaxHeight), HostControl.Frame.Y); } } else { renderAt.Y = HostControl.Frame.Bottom; } } if (ScrollOffset > Suggestions.Count - height) { ScrollOffset = 0; } var toRender = Suggestions.Skip (ScrollOffset).Take (height).ToArray (); toRenderLength = toRender.Length; if (toRender.Length == 0) { return; } width = Math.Min (MaxWidth, toRender.Max (s => s.Length)); if (PopupInsideContainer) { // don't overspill horizontally, let's see if can be displayed on the left if (width > HostControl.Bounds.Width - renderAt.X) { // Verifies that the left limit available is greater than the right limit if (renderAt.X > HostControl.Bounds.Width - renderAt.X) { renderAt.X -= Math.Min (width, LastPopupPos.Value.X); width = Math.Min (width, LastPopupPos.Value.X); } else { width = Math.Min (width, HostControl.Bounds.Width - renderAt.X); } } } else { // don't overspill horizontally, let's see if can be displayed on the left if (width > top.Bounds.Width - (renderAt.X + HostControl.Frame.X)) { // Verifies that the left limit available is greater than the right limit if (renderAt.X + HostControl.Frame.X > top.Bounds.Width - (renderAt.X + HostControl.Frame.X)) { renderAt.X -= Math.Min (width, LastPopupPos.Value.X); width = Math.Min (width, LastPopupPos.Value.X); } else { width = Math.Min (width, top.Bounds.Width - renderAt.X); } } } if (PopupInsideContainer) { popup.Frame = new Rect ( new Point (HostControl.Frame.X + renderAt.X, HostControl.Frame.Y + renderAt.Y), new Size (width, height)); } else { popup.Frame = new Rect ( new Point (HostControl.Frame.X + renderAt.X, renderAt.Y), new Size (width, height)); } popup.Move (0, 0); for (int i = 0; i < toRender.Length; i++) { if (i == SelectedIdx - ScrollOffset) { Application.Driver.SetAttribute (ColorScheme.Focus); } else { Application.Driver.SetAttribute (ColorScheme.Normal); } popup.Move (0, i); var text = TextFormatter.ClipOrPad (toRender [i], width); Application.Driver.AddStr (text); } } /// <summary> /// Updates <see cref="SelectedIdx"/> to be a valid index within <see cref="Suggestions"/> /// </summary> public virtual void EnsureSelectedIdxIsValid () { SelectedIdx = Math.Max (0, Math.Min (Suggestions.Count - 1, SelectedIdx)); // if user moved selection up off top of current scroll window if (SelectedIdx < ScrollOffset) { ScrollOffset = SelectedIdx; } // if user moved selection down past bottom of current scroll window while (toRenderLength > 0 && SelectedIdx >= ScrollOffset + toRenderLength) { ScrollOffset++; } } /// <summary> /// Handle key events before <see cref="HostControl"/> e.g. to make key events like /// up/down apply to the autocomplete control instead of changing the cursor position in /// the underlying text view. /// </summary> /// <param name="kb">The key event.</param> /// <returns><c>true</c>if the key can be handled <c>false</c>otherwise.</returns> public virtual bool ProcessKey (KeyEvent kb) { if (IsWordChar ((char)kb.Key)) { Visible = true; closed = false; return false; } if (kb.Key == Reopen) { return ReopenSuggestions (); } if (closed || Suggestions.Count == 0) { Visible = false; if (!closed) { Close (); } return false; } if (kb.Key == Key.CursorDown) { MoveDown (); return true; } if (kb.Key == Key.CursorUp) { MoveUp (); return true; } if (kb.Key == Key.CursorLeft || kb.Key == Key.CursorRight) { GenerateSuggestions (kb.Key == Key.CursorLeft ? -1 : 1); if (Suggestions.Count == 0) { Visible = false; if (!closed) { Close (); } } return false; } if (kb.Key == SelectionKey) { return Select (); } if (kb.Key == CloseKey) { Close (); return true; } return false; } /// <summary> /// Handle mouse events before <see cref="HostControl"/> e.g. to make mouse events like /// report/click apply to the autocomplete control instead of changing the cursor position in /// the underlying text view. /// </summary> /// <param name="me">The mouse event.</param> /// <param name="fromHost">If was called from the popup or from the host.</param> /// <returns><c>true</c>if the mouse can be handled <c>false</c>otherwise.</returns> public virtual bool MouseEvent (MouseEvent me, bool fromHost = false) { if (fromHost) { if (!Visible) { return false; } GenerateSuggestions (); if (Visible && Suggestions.Count == 0) { Visible = false; HostControl?.SetNeedsDisplay (); return true; } else if (!Visible && Suggestions.Count > 0) { Visible = true; HostControl?.SetNeedsDisplay (); Application.UngrabMouse (); return false; } else { // not in the popup if (Visible && HostControl != null) { Visible = false; closed = false; } HostControl?.SetNeedsDisplay (); } return false; } if (popup == null || Suggestions.Count == 0) { ManipulatePopup (); return false; } if (me.Flags == MouseFlags.ReportMousePosition) { RenderSelectedIdxByMouse (me); return true; } if (me.Flags == MouseFlags.Button1Clicked) { SelectedIdx = me.Y - ScrollOffset; return Select (); } if (me.Flags == MouseFlags.WheeledDown) { MoveDown (); return true; } if (me.Flags == MouseFlags.WheeledUp) { MoveUp (); return true; } return false; } /// <summary> /// Render the current selection in the Autocomplete context menu by the mouse reporting. /// </summary> /// <param name="me"></param> protected void RenderSelectedIdxByMouse (MouseEvent me) { if (SelectedIdx != me.Y - ScrollOffset) { SelectedIdx = me.Y - ScrollOffset; if (LastPopupPos != null) { RenderOverlay ((Point)LastPopupPos); } } } /// <summary> /// Clears <see cref="Suggestions"/> /// </summary> public virtual void ClearSuggestions () { Suggestions = Enumerable.Empty<string> ().ToList ().AsReadOnly (); } /// <summary> /// Populates <see cref="Suggestions"/> with all strings in <see cref="AllSuggestions"/> that /// match with the current cursor position/text in the <see cref="HostControl"/> /// </summary> /// <param name="columnOffset">The column offset.</param> public virtual void GenerateSuggestions (int columnOffset = 0) { // if there is nothing to pick from if (AllSuggestions.Count == 0) { ClearSuggestions (); return; } var currentWord = GetCurrentWord (columnOffset); if (string.IsNullOrWhiteSpace (currentWord)) { ClearSuggestions (); } else { Suggestions = AllSuggestions.Where (o => o.StartsWith (currentWord, StringComparison.CurrentCultureIgnoreCase) && !o.Equals (currentWord, StringComparison.CurrentCultureIgnoreCase) ).ToList ().AsReadOnly (); EnsureSelectedIdxIsValid (); } } /// <summary> /// Return true if the given symbol should be considered part of a word /// and can be contained in matches. Base behavior is to use <see cref="char.IsLetterOrDigit(char)"/> /// </summary> /// <param name="rune"></param> /// <returns></returns> public virtual bool IsWordChar (Rune rune) { return Char.IsLetterOrDigit ((char)rune); } /// <summary> /// Completes the autocomplete selection process. Called when user hits the <see cref="SelectionKey"/>. /// </summary> /// <returns></returns> protected bool Select () { if (SelectedIdx >= 0 && SelectedIdx < Suggestions.Count) { var accepted = Suggestions [SelectedIdx]; return InsertSelection (accepted); } return false; } /// <summary> /// Called when the user confirms a selection at the current cursor location in /// the <see cref="HostControl"/>. The <paramref name="accepted"/> string /// is the full autocomplete word to be inserted. Typically a host will have to /// remove some characters such that the <paramref name="accepted"/> string /// completes the word instead of simply being appended. /// </summary> /// <param name="accepted"></param> /// <returns>True if the insertion was possible otherwise false</returns> protected virtual bool InsertSelection (string accepted) { var typedSoFar = GetCurrentWord () ?? ""; if (typedSoFar.Length < accepted.Length) { // delete the text for (int i = 0; i < typedSoFar.Length; i++) { DeleteTextBackwards (); } InsertText (accepted); return true; } return false; } /// <summary> /// Returns the currently selected word from the <see cref="HostControl"/>. /// <para> /// When overriding this method views can make use of <see cref="IdxToWord(List{Rune}, int, int)"/> /// </para> /// </summary> /// <param name="columnOffset">The column offset.</param> /// <returns></returns> protected abstract string GetCurrentWord (int columnOffset = 0); /// <summary> /// <para> /// Given a <paramref name="line"/> of characters, returns the word which ends at <paramref name="idx"/> /// or null. Also returns null if the <paramref name="idx"/> is positioned in the middle of a word. /// </para> /// /// <para> /// Use this method to determine whether autocomplete should be shown when the cursor is at /// a given point in a line and to get the word from which suggestions should be generated. /// Use the <paramref name="columnOffset"/> to indicate if search the word at left (negative), /// at right (positive) or at the current column (zero) which is the default. /// </para> /// </summary> /// <param name="line"></param> /// <param name="idx"></param> /// <param name="columnOffset"></param> /// <returns></returns> protected virtual string IdxToWord (List<Rune> line, int idx, int columnOffset = 0) { StringBuilder sb = new StringBuilder (); var endIdx = idx; // get the ending word index while (endIdx < line.Count) { if (IsWordChar (line [endIdx])) { endIdx++; } else { break; } } // It isn't a word char then there is no way to autocomplete that word if (endIdx == idx && columnOffset != 0) { return null; } // we are at the end of a word. Work out what has been typed so far while (endIdx-- > 0) { if (IsWordChar (line [endIdx])) { sb.Insert (0, (char)line [endIdx]); } else { break; } } return sb.ToString (); } /// <summary> /// Deletes the text backwards before insert the selected text in the <see cref="HostControl"/>. /// </summary> protected abstract void DeleteTextBackwards (); /// <summary> /// Inser the selected text in the <see cref="HostControl"/>. /// </summary> /// <param name="accepted"></param> protected abstract void InsertText (string accepted); /// <summary> /// Closes the Autocomplete context menu if it is showing and <see cref="ClearSuggestions"/> /// </summary> protected void Close () { ClearSuggestions (); Visible = false; closed = true; HostControl?.SetNeedsDisplay (); ManipulatePopup (); } /// <summary> /// Moves the selection in the Autocomplete context menu up one /// </summary> protected void MoveUp () { SelectedIdx--; if (SelectedIdx < 0) { SelectedIdx = Suggestions.Count - 1; } EnsureSelectedIdxIsValid (); HostControl?.SetNeedsDisplay (); } /// <summary> /// Moves the selection in the Autocomplete context menu down one /// </summary> protected void MoveDown () { SelectedIdx++; if (SelectedIdx > Suggestions.Count - 1) { SelectedIdx = 0; } EnsureSelectedIdxIsValid (); HostControl?.SetNeedsDisplay (); } /// <summary> /// Reopen the popup after it has been closed. /// </summary> /// <returns></returns> protected bool ReopenSuggestions () { GenerateSuggestions (); if (Suggestions.Count > 0) { Visible = true; closed = false; HostControl?.SetNeedsDisplay (); return true; } return false; } } }
 namespace Pe.Stracon.Politicas.Aplicacion.TransferObject.Response.General { /// <summary> /// Datos generales de parametro /// </summary> /// <remarks> /// Creación: GMD 22122014 <br /> /// Modificación: <br /> /// </remarks> public class ParametroResponse { /// <summary> /// Código de parametro /// </summary> public int CodigoParametro { get; set; } /// <summary> /// Código Identificador /// </summary> public string CodigoIdentificador { get; set; } /// <summary> /// Identificador Empresa /// </summary> public bool IndicadorEmpresa { get; set; } /// <summary> /// Descripción de Identificador de Empresa /// </summary> public string DescripcionIndicadorEmpresa { get; set; } /// <summary> /// Código Empresa /// </summary> public string CodigoEmpresa { get; set; } /// <summary> /// Código Identificador de Empresa /// </summary> public string CodigoEmpresaIdentificador { get; set; } /// <summary> /// Nombre de Empresa /// </summary> public string NombreEmpresa { get; set; } /// <summary> /// Código Sistema /// </summary> public string CodigoSistema { get; set; } /// <summary> /// Código Identificador del Sistema /// </summary> public string CodigoSistemaIdentificador { get; set; } /// <summary> /// Nombre del Sistema /// </summary> public string NombreSistema { get; set; } /// <summary> /// Tipo de Parámetro /// </summary> public string TipoParametro { get; set; } /// <summary> /// Descripción de Tipo de Parámetro /// </summary> public string DescripcionTipoParametro { get; set; } /// <summary> /// Nombre del Parametro /// </summary> public string Nombre { get; set; } /// <summary> /// Descripción del Parametro /// </summary> public string Descripcion { get; set; } /// <summary> /// Indicador Permite Agregar /// </summary> public bool IndicadorPermiteAgregar { get; set; } /// <summary> /// Indicador Permite Modificar /// </summary> public bool IndicadorPermiteModificar { get; set; } /// <summary> /// Indicador Permite Eliminar /// </summary> public bool IndicadorPermiteEliminar { get; set; } /// <summary> /// Estadro de Registro /// </summary> public string EstadoRegistro { get; set; } } }
using jaytwo.Common.Extensions; using jaytwo.Common.Http; using NUnit.Framework; using System; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using System.Text; using System.Threading.Tasks; namespace jaytwo.Common.Test.Http.UrlHelperTests { public static partial class SetQueryTests { private static IEnumerable<TestCaseData> UrlHelper_SetUriScheme_TestCases() { yield return new TestCaseData(null, new NameValueCollection() { { "hello", "word" }, { "this", "that" } }).Throws(typeof(ArgumentNullException)); yield return new TestCaseData("http://www.google.com", null).Returns("http://www.google.com/"); yield return new TestCaseData("http://www.google.com", new NameValueCollection() { { "hello", "world" }, { "this", "that" } }).Returns("http://www.google.com/?hello=world&this=that"); yield return new TestCaseData("https://www.google.com/path", new NameValueCollection() { { "hello", "world" }, { "this", "that" } }).Returns("https://www.google.com/path?hello=world&this=that"); yield return new TestCaseData("../some/path", new NameValueCollection() { { "hello", "world" }, { "this", "that" } }).Returns("../some/path?hello=world&this=that"); } [Test] [TestCaseSource("UrlHelper_SetUriScheme_TestCases")] public static string UrlHelper_SetUriQuery(string url, NameValueCollection query) { var uri = TestUtility.GetUriFromString(url); return UrlHelper.SetUriQuery(uri, query).ToString(); } [Test] [TestCaseSource("UrlHelper_SetUriScheme_TestCases")] public static string UrlHelper_SetUrlScheme(string url, NameValueCollection query) { return UrlHelper.SetUrlQuery(url, query); } [Test] [TestCaseSource("UrlHelper_SetUriScheme_TestCases")] public static string HttpExtensionMethods_WithQuery(string url, NameValueCollection query) { var uri = TestUtility.GetUriFromString(url); return uri.WithQuery(query).ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SweepstakesProject { class Sweepstakes { //variables private Dictionary<int, Contestant> contestants; private string name; public string Name; public Contestant winnerContest; //constructor public Sweepstakes(string name) { this.name = name; contestants = new Dictionary<int, Contestant>(); } //methods public void RegisterContestant(Contestant contestant) { int keyNumber = contestants.Count + 1; contestants.Add(keyNumber, contestant); contestant.RegistrationNumber = keyNumber; Console.WriteLine($" Contestants count: {contestants.Count} {contestant.FirstName} " + $"{contestant.LastName}" + $" {contestant.EmailAddress}" + $" registration number: {contestant.RegistrationNumber} "); //Send this to user interface dude } public Contestant PickWinner() { int winningNumber = GetRandomNumber(contestants.Count + 1); foreach (KeyValuePair<int, Contestant> player in contestants) { if (winningNumber == player.Key) { winnerContest = player.Value; } } return winnerContest; } public void PrintContestantInfo(Contestant contestant) { } public int GetRandomNumber(int max) { Random randomNumber = new Random(); int randomResult = randomNumber.Next(max); return randomResult; } //sweepstakes1 = new Sweepstakes("October Sweep"); //contestant1 = new Contestant("Jim", "Baron", "JimBaron@gmail.com", sweepstakes1.GetRandomNumber(50)); //contestant2 = new Contestant("Tim", "Burton", "TimBurton@gmail.com", sweepstakes1.GetRandomNumber(50)); //sweepstakes1.RegisterContestant(contestant1); //sweepstakes1.RegisterContestant(contestant2); //Console.ReadLine(); } }
using NUnit.Framework; using Ejercicio; using System; using System.Collections.Generic; using System.Linq; namespace Testing { public class Tests { Batman batman; List<Tecnologias> batiriñonera; CiudadGotica ciudadGotica; List<Habitante> habitantes; List<Villano> villanos; [SetUp] public void Setup() { batiriñonera = new List<Tecnologias>(); Tecnologias batibumerangs = new Tecnologias("Batibumerangs", 100, 1); batiriñonera.Add(batibumerangs); batman = new Batman(batiriñonera); villanos = new List<Villano>(); Psicopatas psicopata = new Psicopatas(5, 100); villanos.Add(psicopata); Habitante habitante = new Habitante(2000000); Habitante habitante1 = new Habitante(7000000); Habitante habitante2 = new Habitante(8000000); Habitante habitante3 = new Habitante(9000000); Habitante habitante4 = new Habitante(10000000); Habitante habitante5 = new Habitante(11000000); Habitante habitante6 = new Habitante(12000000); Habitante habitante7 = new Habitante(13000000); Habitante habitante8 = new Habitante(14000000); Habitante habitante9 = new Habitante(15000000); Habitante habitante10 = new Habitante(16000000); Habitante habitante11 = new Habitante(500000); habitantes = new List<Habitante>(); habitantes.Add(habitante); habitantes.Add(habitante1); habitantes.Add(habitante2); habitantes.Add(habitante3); habitantes.Add(habitante4); habitantes.Add(habitante5); habitantes.Add(habitante6); habitantes.Add(habitante7); habitantes.Add(habitante8); habitantes.Add(habitante9); habitantes.Add(habitante10); habitantes.Add(habitante11); ciudadGotica = new CiudadGotica(habitantes); } [Test] public void TestSaberSiBatmanEstaEstresadoYHacerloCombatir() { Assert.AreEqual(false, batman.estaEstresado()); batman.combatirElCrimen(villanos); } [Test] public void TestSaberSiBatmanEstaALaModaBatmanBailaBatiTwistLosVillanosHacenMaldadesYSeMuestraLos10Top() { Assert.AreEqual(true, batman.estaALaModa()); batman.bailarBatiTwist(); villanos.ForEach(i => i.realizarMaldad()); List<Habitante> losMasTop = ciudadGotica.sonLosMasTop(); foreach (var i in losMasTop) Console.WriteLine(i.CantidadDeDinero); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Docller.Core.Models; using Docller.Core.Common; using Microsoft.Practices.EnterpriseLibrary.Data; namespace Docller.Core.Repository.Mappers.StoredProcMappers { public class TransmittalMapper:IResultSetMapper<Transmittal> { private readonly IRowMapper<Transmittal> _transmittaMapper; private readonly IRowMapper<TransmittalUser> _userMapper; private readonly IRowMapper<TransmittedFile> _fileMapper; private readonly IRowMapper<TransmittedFileVersion> _fileVersionMapper; public TransmittalMapper() { _transmittaMapper = MapBuilder<Transmittal>.MapNoProperties() .MapByName(x => x.TransmittalNumber) .MapByName(x => x.TransmittalId) .MapByName(x => x.Subject) .MapByName(x => x.Message) .MapByName(x => x.IsDraft) .MapByName(x => x.CreatedDate) .Map(x => x.TransmittalStatus) .WithFunc( r => new Status() { StatusId = r.GetNullableLong(5), StatusText = r.GetNullableString(6) }) .Map(x => x.CreatedBy) .WithFunc( record => new User() {FirstName = record.GetString(8), LastName = record.GetString(9)}) .MapByName(x => x.BlobContainer) .Build(); _userMapper = MapBuilder<TransmittalUser>.MapNoProperties() .MapByName(x=>x.UserId) .MapByName(x => x.FirstName) .MapByName(x => x.LastName) .MapByName(x=>x.Email) .Map(x => x.IsCced) .ToColumn("Cced") .Map(x=>x.Company).WithFunc( record => new Company() {CompanyName = record.GetString(5)}) .Build(); _fileMapper = MapBuilder<TransmittedFile>.MapNoProperties() .MapByName(x => x.FileId) .MapByName(x => x.FileInternalName) .MapByName(x => x.FileName) .MapByName(x => x.Title) .MapByName(x => x.Revision) .Map(x => x.RevisionNumber).ToColumn("CurrentRevision") .Map(x => x.Status) .ToColumn("StatusText") .Map(x => x.Folder).WithFunc(r => new Folder() {FullPath = r.GetString(7)}) .Build(); _fileVersionMapper = MapBuilder<TransmittedFileVersion>.MapNoProperties() .MapByName(x => x.FileId) .MapByName(x => x.VersionPath) .MapByName(x => x.FileInternalName) .MapByName(x => x.FileName) .MapByName(x => x.Title) .MapByName(x => x.Revision) .MapByName(x => x.RevisionNumber) .Map(x => x.Status) .ToColumn("StatusText") .Map(x => x.Folder) .WithFunc(r => new Folder() {FullPath = r.GetString(8)}) .Build(); } public IEnumerable<Transmittal> MapSet(IDataReader reader) { Transmittal transmittal; using (reader) { transmittal = MapSetTransmittal(reader); if (transmittal != null) { transmittal.Files = new List<TransmittedFile>(); if (reader.NextResult()) { while (reader.Read()) { TransmittedFile f = _fileMapper.MapRow(reader); f.Project = new Project() {BlobContainer = transmittal.BlobContainer}; transmittal.Files.Add(f); } } //We need to check for next result, as we might not have the last result returning back from stored proc if (reader.NextResult()) { while (reader.Read()) { TransmittedFileVersion version = _fileVersionMapper.MapRow(reader); version.Project = new Project() {BlobContainer = transmittal.BlobContainer}; transmittal.Files.Add(version); } } } } yield return transmittal; } internal Transmittal MapSetTransmittal(IDataReader reader) { if (reader.Read()) { Transmittal transmittal = _transmittaMapper.MapRow(reader); transmittal.Distribution = new List<TransmittalUser>(); if (reader.NextResult()) { while (reader.Read()) { transmittal.Distribution.Add(_userMapper.MapRow(reader)); } } return transmittal; } return null; } } }
using System; namespace Tomelt.Environment.Extensions { [AttributeUsage(AttributeTargets.Class)] public class TomeltFeatureAttribute : Attribute { public TomeltFeatureAttribute(string text) { FeatureName = text; } public string FeatureName { get; set; } } }
using System.Collections.Generic; using Tomelt.Packaging.Models; namespace Tomelt.Packaging.ViewModels { public class PackagingSourcesViewModel { public IEnumerable<PackagingSource> Sources { get; set; } } }
using System; using System.Windows; using System.Windows.Media.Imaging; using WpfAnimatedGif; namespace WpfAnimatedGifTestApp { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private int _currentStep = 0; private readonly BitmapImage _gif1; private readonly BitmapImage _gif1Reversed; private readonly BitmapImage _gif2; private readonly BitmapImage _gif2Reversed; public MainWindow() { InitializeComponent(); _gif1 = new BitmapImage(); _gif1.BeginInit(); _gif1.UriSource = new Uri("pack://application:,,,/Images/1.gif"); _gif1.EndInit(); _gif1Reversed = new BitmapImage(); _gif1Reversed.BeginInit(); _gif1Reversed.UriSource = new Uri("pack://application:,,,/Images/1 reversed.gif"); _gif1Reversed.EndInit(); _gif2 = new BitmapImage(); _gif2.BeginInit(); _gif2.UriSource = new Uri("pack://application:,,,/Images/2.gif"); _gif2.EndInit(); _gif2Reversed = new BitmapImage(); _gif2Reversed.BeginInit(); _gif2Reversed.UriSource = new Uri("pack://application:,,,/Images/2 reversed.gif"); _gif2Reversed.EndInit(); } private void Button_Click(object sender, RoutedEventArgs e) { _currentStep++; ImageBehavior.SetAnimatedSource(ImageControl, null); GC.Collect(2, GCCollectionMode.Forced); switch (_currentStep) { case 1: ImageBehavior.SetAnimatedSource(ImageControl, _gif1); break; case 2: ImageBehavior.SetAnimatedSource(ImageControl, _gif1Reversed); break; case 3: ImageBehavior.SetAnimatedSource(ImageControl, _gif2); break; case 4: ImageBehavior.SetAnimatedSource(ImageControl, _gif2Reversed); _currentStep = 0; break; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.InputSystem; public class RemixEditorGoalPost : MonoBehaviour, IComparable<RemixEditorGoalPost>, IPointerDownHandler { public static List<RemixEditorGoalPost> Instances = new List<RemixEditorGoalPost>(); public static RemixEditorGoalPost StartSpot = null; public static RemixEditorGoalPost FinishSpot = null; [Tooltip("Order of the object in the remix editor list")] public int RemixEditorOrder; [Space] [Tooltip("If this should be the default start line when entering remix editor for the first time, only one can be marked or there will be no guarantee of which will be used")] public bool InitStart = false; [Tooltip("If this should be the default finish line when entering remix editor for the first time, only one can be marked or there will be no guarantee of which will be used")] public bool InitFinish = false; [Space] public Transform GoalPost; // TODO: portal entrance and exit // IDEA: have same object for goal post and goal portal entrance, just toggle effect volume and use different ontrigger branches, place goal post with disabled trigger as portal exit? [Tooltip("Which previous segments the player is allowed to cross this finish line from")] public int[] AllowedPreviousSegments; [Tooltip("Where the car starts when starting a run from this goal line")] public Transform SpawnSpot; private void Awake() { Instances.Add(this); Instances.Sort(); if (InitStart) StartSpot = this; if (InitFinish) FinishSpot = this; // if (GoalPost.gameObject.activeSelf) { // StartSpot = this; // } // if (FinishSpot) // UpdateGoalPost(); GoalPost.gameObject.SetActive(false); } private void OnDestroy() { Instances.Remove(this); } public void OnPointerDown(PointerEventData eventData) { if (Mouse.current.leftButton.wasPressedThisFrame) { RemixMapScript.Select(this); } } public static void MoveCarToStart() { // TODO: use centerline for start/finish line instead SteeringScript.MainInstance?.Teleport(StartSpot.SpawnSpot.position, StartSpot.SpawnSpot.rotation); } public static void UpdateGoalPost() { if (StartSpot && !FinishSpot) FinishSpot = StartSpot; if (!StartSpot && FinishSpot) StartSpot = FinishSpot; if (!FinishSpot) { // Debug.LogError("no finish spot assigned"); return; } if (StartSpot == FinishSpot) { // Single finish line GoalPostScript.SetInstanceGoalPost(StartSpot); } else { // Portal GoalPostScript.SetInstanceGoalPortal(FinishSpot, StartSpot); } } public int CompareTo(RemixEditorGoalPost other) { return RemixEditorOrder - other.RemixEditorOrder; } }
using System; using ApartmentApps.Api; using ApartmentApps.Api.Modules; using ApartmentApps.Api.Services; using ApartmentApps.Api.ViewModels; using ApartmentApps.Data; namespace ApartmentApps.Portal.Controllers { public class UserLookupMapper : BaseMapper<ApplicationUser, UserLookupBindingModel> { public UserLookupMapper(IUserContext userContext, IModuleHelper moduleHelper) : base(userContext, moduleHelper) { } public override void ToModel(UserLookupBindingModel viewModel, ApplicationUser model) { throw new NotImplementedException(); } public override void ToViewModel(ApplicationUser model, UserLookupBindingModel viewModel) { if (model == null) return; viewModel.Id = model.Id; viewModel.Title = $"{model.FirstName} {model.LastName}"; if (model.Unit != null) viewModel.Title+=$" [ {model.Unit?.Building.Name} {model.Unit?.Name} ]"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Communication { [Serializable] public class Private_Message : Message { private string NameDest; public Private_Message(string msg, Profile p, string UserDest) : base(msg, p) { this.NameDest = UserDest; } public string NameDest1 { get => NameDest; set => NameDest = value; } } }
using AutoTests.Framework.Models; using AutoTests.Framework.Models.PropertyAttributes; namespace AutoTests.Framework.Tests.Models { public class ParentModel : Model { [Name("Title")] public string Name { get; set; } [Disabled] public bool Enabled { get; set; } public SubModel SubModel { get; private set; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MVVMJSON.ViewModel { public class BreedViewModel : NotificationBase { Model.Dogs breeds; public BreedViewModel() { Model.Dogs test = new Model.Dogs(); foreach (var dog in test.Breeds) { var np = new DogViewModel(dog); _dog.Add(np); } } ObservableCollection<DogViewModel> _dog = new ObservableCollection<DogViewModel>(); public ObservableCollection<DogViewModel> Dog { get { return _dog; } set { SetProperty(ref _dog, value); } } //String _Name; //public String Name //{ // get { return breeds.BreedName; } //} int _SelectedIndex; public int SelectedIndex { get { return _SelectedIndex; } set { if (SetProperty(ref _SelectedIndex, value)) { RaisePropertyChanged(nameof(SelectedDog)); } } } public DogViewModel SelectedDog { get { return (_SelectedIndex >= 0) ? _dog[_SelectedIndex] : null;} } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Shoot : MonoBehaviour { public Transform firePoint; public Transform firePoint2; public GameObject bulletPrefab; public Text ammoText; public int ammo; public Vector3 facing; public AudioClip shootSound; public AudioClip emptySound; private void Awake() { ammo = GameManager.instance.ammo; ammoText = GetComponentInParent<Player>().ammoText; } // Update is called once per frame void Update () { } public void ShootBullet() { facing = GetComponentInParent<Player>().facing; firePoint2 = firePoint; if (ammo == 0) { AudioManager.instance.playClip(emptySound); GameManager.instance.playersTurn = false; return; } AudioManager.instance.playClip(shootSound); if (facing.z == -90f) { firePoint.Translate(-0.3f, 0, 0); Instantiate(bulletPrefab, firePoint.position, Quaternion.Euler(facing)); firePoint.Translate(0.3f, 0, 0); } else { Instantiate(bulletPrefab, firePoint.position, Quaternion.Euler(facing)); } ammo--; ammoText.text = "" + ammo; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Xna.Framework; namespace Blocky.Model { public class Player : Entity { public Player() { } } }
 using ConfigurationService; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml.Serialization; namespace CacheSqlXmlService.SqlManager { internal static class ConfigHelper { //private const string DEFAULT_SQL_CONFIG_LIST_FILE_PATH = "Configuration/Data/DbCommandFiles.config";//没用到,支持linux的路径写法 private static string s_ConfigFolder = null; private static DataAccessSetting s_Setting = ConfigurationManage.dataAccessSetting;//ConfigurationManager.Instance.GetByPath<DataAccessSetting>("DataAccessSetting"); public static string ConfigFolder { get { if (ConfigHelper.s_ConfigFolder == null) { ConfigHelper.s_ConfigFolder = Path.GetDirectoryName(ConfigHelper.SqlConfigListFilePath); } return ConfigHelper.s_ConfigFolder; } } public static string SqlConfigListFilePath { get { string raletepath = Path.Combine( "Configuration", "Data", "DbCommandFiles.config");//linux和windwos同时支持 string text = s_Setting.SqlConfigListFilePath?? raletepath; string pathRoot = Path.GetPathRoot(text); string result; if (pathRoot == null || pathRoot.Trim().Length <= 0) { result = Path.Combine(Directory.GetCurrentDirectory(), "Configuration", "Data", "DbCommandFiles.config");//linux和windwos同时支持 } else { result = text; } return result; } } private static T LoadFromXml<T>(string fileName) { FileStream fileStream = null; T result; try { XmlSerializer xmlSerializer = new XmlSerializer(typeof(T)); fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); result = (T)((object)xmlSerializer.Deserialize(fileStream)); } finally { if (fileStream != null) { fileStream.Dispose(); } } return result; } public static DataCommandFileList LoadSqlConfigListFile() { string sqlConfigListFilePath = ConfigHelper.SqlConfigListFilePath; DataCommandFileList result; if (!string.IsNullOrWhiteSpace(sqlConfigListFilePath) && File.Exists(sqlConfigListFilePath.Trim())) { result = ConfigHelper.LoadFromXml<DataCommandFileList>(sqlConfigListFilePath.Trim()); } else { result = null; } return result; } public static DataOperations LoadDataCommandList(string filePath) { return ConfigHelper.LoadFromXml<DataOperations>(filePath); } } }
using MassEffect.GameObjects.Locations; using MassEffect.GameObjects.Projectiles; using MassEffect.Interfaces; namespace MassEffect.GameObjects.Ships { class Cruiser : Starship { private const int CHealt = 100; private const int CShields = 100; private const int CDamage = 50; private const int CFuel = 300; public Cruiser(string name, StarSystem location) : base(name, CHealt, CShields, CDamage, CFuel, location) { } public override IProjectile ProduceAttack() { return new PenetrationShell(this.Damage); } } }
using System.Collections.Generic; using EQS.AccessControl.Application.Interfaces; using EQS.AccessControl.Application.ViewModels.Input; using EQS.AccessControl.Application.ViewModels.Output; using EQS.AccessControl.Application.ViewModels.Output.Base; using EQS.AccessControl.Application.ViewModels.Output.Register; using EQS.AccessControl.API.Authorize; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace EQS.AccessControl.API.Controllers { /// <summary> /// Register API /// </summary> [Produces("application/json")] [Route("api/Register")] [Authorize("Bearer")] [AuthorizeRole("Admin")] public class RegisterController : Controller { private readonly IRegisterAppService _registerAppService; public RegisterController(IRegisterAppService registerAppService) { _registerAppService = registerAppService; } /// <summary> /// Get all the People /// </summary> /// <returns>List of People</returns> [HttpGet("GetAll")] public ResponseModelBase<List<RegisterPersonOutput>> Get() { return _registerAppService.GetAll(); } // GET: api/Register/5 [HttpGet("{id}")] public ResponseModelBase<RegisterPersonOutput> Get(int id) { return _registerAppService.GetById(id); } /// <summary> /// /// </summary> /// <returns></returns> [HttpPost("GetByExpression")] public ResponseModelBase<List<RegisterPersonOutput>> GetByExpression([FromBody]SearchObjectInput search) { return _registerAppService.GetByExpression(search); } // POST: api/Register [HttpPost] public ResponseModelBase<RegisterPersonOutput> Post([FromBody]PersonInput person) { return _registerAppService.Create(person); } // PUT: api/Register/5 [HttpPut] public ResponseModelBase<RegisterPersonOutput> Put( [FromBody]PersonInput person) { return _registerAppService.Update(person); } // DELETE: api/ApiWithActions/5 [HttpDelete("{id}")] public ResponseModelBase<RegisterPersonOutput> Delete(int id) { return _registerAppService.Delete(id); } } }
using Assets.Scripts.Ui; using System; using System.Collections.Generic; using UnityEngine; namespace Assets.Scripts.UI { public class EquipView : View { public List<UiSlot> Slots; public UISprite ShieldProgress; public Action<UiSlot> OnSlotClickAction { get; set; } private float _currentWaitUpdate = 0.0f; public override void Init(GameManager gameManager) { base.Init(gameManager); for (int i = 0; i < WorldConsts.EquipSlotsAmount; i++) { Slots[i].Init(gameManager, GameManager.PlayerModel.Inventory.EquipSlots[i], i); Slots[i].OnSlotClickAction += OnSlotClick; } } void Update() { if (IsShowing) { _currentWaitUpdate += Time.deltaTime; if (_currentWaitUpdate > 1.0f) { _currentWaitUpdate = 0.0f; UpdateDefence(); } } } private void OnSlotClick(UiSlot uiSlot) { if (OnSlotClickAction != null) OnSlotClickAction(uiSlot); } public override void UpdateView() { base.UpdateView(); for (int i = 0; i < WorldConsts.EquipSlotsAmount; i++) Slots[i].UpdateView(); UpdateDefence(); } private void UpdateDefence() { float amount = 0; foreach(var slot in Slots) { if(slot.ItemModel != null && slot.ItemModel.Item != null) { if (slot.ItemModel.Item.Effect == Models.ItemEffectType.Damage) amount += slot.ItemModel.Item.EffectAmount; } } if (amount > 100) amount = 100; ShieldProgress.fillAmount = amount / 100.0f; } public void UpdateItemsDurability() { for (int i = 0; i < WorldConsts.EquipSlotsAmount; i++) Slots[i].UpdateDurability(); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows; namespace Z.Framework.Workspace { /// <summary> /// App.xaml 的交互逻辑 /// </summary> public partial class App : Application { private System.Timers.Timer Timer { set; get; } private DateTime CurrentTime { set; get; } protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); this.DispatcherUnhandledException += App_DispatcherUnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; Timer = new System.Timers.Timer(1000); Timer.Elapsed += (s, a) => { CurrentTime = DateTime.Now; }; Timer.Enabled = true; } private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { //Log it } private void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) { e.Handled = true; MessageBox.Show("系统检测到部分未处理异常,即将关闭。若问题始终存在,请联系软件供应商,给您带来的不便深表歉意!", "警告"); Application.Current.Shutdown(1); } } }
using UnityEngine; using System.Collections; // the move state for the Agent AI state machine public class AgentMoveState : State<AgentAI> { public void enter(AgentAI agent) { Debug.Log ("Enter MoveState"); Debug.Log ("Agent awoken count = " + agent.count); } // during the execution of the move state, the agent checks to see how far away from the player it is // and if it's over the threshold then the agent stops moving and enters the SleepState public void execute(AgentAI agent, StateMachine<AgentAI> fsm) { agent.move (); GameObject g = GameObject.Find ("Player"); float distance = Vector3.Distance (agent.transform.position, g.transform.position); if (distance > 30f) fsm.changeState (new AgentSleepState ()); } public void exit(AgentAI agent) { Debug.Log ("Exit MoveState"); agent.rotateCW = !agent.rotateCW; // reverse rotation of scan mode } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using PlayNGoCoffee.Business.ServiceContract; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace PlayNGoCoffee.Web.Controllers { [Route("api/[controller]")] public class CoffeeTestController : Controller { private readonly ICoffeeService coffeeService; #region Protected Members /// <summary> /// Scoped application context /// </summary> protected ApplicationDbContext mContext; #endregion #region Constructor public CoffeeTestController(ApplicationDbContext context) { mContext = context; this.coffeeService = new CoffeeService(mContext); } #endregion [HttpGet("[action]")] public IEnumerable<LocationDataModel> Initialize() { var locations = coffeeService.GetLocations(); return locations; } [HttpGet("[action]/{locationId}")] public IEnumerable<StockDataModel> Stock(int locationId) { var stock = coffeeService.GetStockByLocationId(locationId); return stock; } [HttpGet("[action]")] public IEnumerable<OrderHistoryDataModel> GetHistory() { var history = coffeeService.GetHistory(); return history; } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace KafkaData { public class RESTConnectionMgr { public async Task<HttpResponseMessage> CreateConsumer() { //string topicString = "/SensorData"; //UriBuilder u1 = new UriBuilder(); ////u1.Host = "localhost"; //DEBUG //u1.Host = "wssccatiot.westus.cloudapp.azure.com"; //u1.Port = 8082; //u1.Path = "topics" + topicString; //u1.Scheme = "http"; //Uri topicUri = u1.Uri; string topicUri = "http://wssccatiot.westus.cloudapp.azure.com:8082"; //Currently focused on REST API surface for Confluent.io Kafka deployment. We can make this more generic in the future //DEBUG //string jsonBody = JsonConvert.SerializeObject(data, Formatting.None); //END DEBUG string jsonBody = "stuff goes here"; //string correctedJsonBody = jsonBody.Replace(",", "}}, {\"value\":{"); //have to add in some json features into the string. Easier than creating unnecessary classes that would make this come out automatically //jsonBody = jsonBody.Replace(",", "}}, {\"value\":{"); //have to add in some json features into the string. Easier than creating unnecessary classes that would make this come out automatically string jsonHeader = ("{\"records\":[{\"value\":"); //same as above, fixing string for Server requirements string jsonFooter = ("}]}"); //ditto string json = jsonHeader + jsonBody + jsonFooter; var baseFilter = new HttpClientHandler(); baseFilter.AutomaticDecompression = System.Net.DecompressionMethods.None; //turn off all compression methods HttpClient httpClient = new HttpClient(baseFilter); //httpClient.BaseAddress = topicUri; //httpClient.DefaultRequestHeaders.Accept.Clear(); //httpClient.DefaultRequestHeaders.AcceptEncoding.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.kafka.json.v1+json")); //Add Accept: application/vnd.kafka.json.vl+json, application... header ) var headerContent = new HttpRequestMessage(); //headerContent.Content.Headers.ContentType = null; // removing all header content and will replace with the required values headerContent.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.kafka.json.v1+json"); //Content-Type: application/vnd.kafka.json.v1+json HttpResponseMessage postResponse = await httpClient.PostAsync(topicUri, new StringContent(json)); //FROM IOT CLIENT SIDE CODE - DELETE ONCE THE SERVER SIDE CODE WORKS //var headerContent = new HttpStringContent(json); //headerContent.Headers.ContentType = null; // removing all header content and will replace with the required values //headerContent.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/vnd.kafka.json.v1+json"); //Content-Type: application/vnd.kafka.json.v1+json //httpClient.DefaultRequestHeaders.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/vnd.kafka.json.v1+json, application/vnd.kafka+json, application/json")); //Add Accept: application/vnd.kafka.json.vl+json, application... header //HttpResponseMessage postResponse = await httpClient.PostAsync(topicUri, headerContent); //END CLIENT SIDE CODE SNIPPET return postResponse; } } }
using UnityEngine; using System.Collections; public class PlayerParticles : MonoBehaviour { [SerializeField] private GameObject collissionParticle; [SerializeField] private GameObject mergeParticle; [SerializeField] private GameObject mergeFailParticle; void OnEnable() { PlayerMerge.IFailedToMerge += FailingToMerge; PlayerMerge.IMerged += SucceedsToMerge; } void OnDisable() { PlayerMerge.IFailedToMerge -= FailingToMerge; PlayerMerge.IMerged -= SucceedsToMerge; } void OnCollisionEnter2D(Collision2D coll) { Instantiate(collissionParticle, transform.position, Quaternion.identity); } void FailingToMerge(PlayerMerge temp, IsMergeable otherMerge) { Instantiate(mergeFailParticle, transform.position, Quaternion.identity); } void SucceedsToMerge(IsMergeable temp) { Instantiate(mergeParticle, transform.position, Quaternion.identity); } }
using System; using System.Threading; using System.Threading.Tasks; using CronScheduler.Extensions.Scheduler; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace CronSchedulerWorker; public class TestJob : IScheduledJob { private readonly TestJobOptions _options; private readonly ILogger<TestJob> _logger; public TestJob( IOptionsMonitor<TestJobOptions> options, ILogger<TestJob> logger, IHostLifetime lifetime) { _options = options.Get(Name); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); // _logger.LogInformation("IsSystemd: {isSystemd}", lifetime.GetType() == typeof(SystemdLifetime)); _logger.LogInformation("IHostLifetime: {hostLifetime}", lifetime.GetType()); } public string Name { get; } = nameof(TestJob); public async Task ExecuteAsync(CancellationToken cancellationToken) { _logger.LogInformation("{jobName} is executing with Custom Field Value: {customField}", nameof(TestJob), _options.CustomField); await Task.CompletedTask; } }
using System; using System.Collections.Generic; namespace gView.Framework.Geometry { class GeomTriangle { private Vector2D _a, _b, _c; public GeomTriangle(Vector2D a, Vector2D b, Vector2D c) { _a = a; _b = b; _c = c; } public GeomTriangle(double x1, double y1, double x2, double y2, double x3, double y3) : this(new Vector2D(x1, y1), new Vector2D(x2, y2), new Vector2D(x3, y3)) { } public Vector2D a { get { return _a; } } public Vector2D b { get { return _b; } } public Vector2D c { get { return _c; } } public List<Vector2D> PerpendicularVectors(double len) { List<Vector2D> vecs = new List<Vector2D>(); Vector2D v1 = _b - _a; Vector2D v2 = _c - _a; Vector2D v3 = _c - _b; v1.Length = len; v2.Length = len; v3.Length = len; double a1 = v1.Angle; double a2 = v2.Angle; double r = (a1 < a2) ? -Math.PI / 2.0 : Math.PI / 2.0; v1.Rotate(r); v2.Rotate(-r); v2.Rotate(-r); vecs.Add(new Vector2D(v1)); vecs.Add(new Vector2D(v2)); vecs.Add(new Vector2D(v3)); return vecs; } } }
using System; using System.IO; using System.Net; using System.Threading.Tasks; using System.Collections.Generic; using StardewModdingAPI; using Newtonsoft.Json; using StardewValley; namespace Entoarox.Framework.Core { internal class UpdateInfo { public string Latest; public string Recommended; public string Minimum; public static Dictionary<IManifest, string> Map = new Dictionary<IManifest, string>(); private static void HandleError(string name,WebException err) { switch (err.Status) { case WebExceptionStatus.ConnectFailure: ModEntry.Logger.Log("[UpdateChecker] The `" + name + "` mod failed to check for updates, connection failed.", LogLevel.Error); break; case WebExceptionStatus.NameResolutionFailure: ModEntry.Logger.Log("[UpdateChecker] The `" + name + "` mod failed to check for updates, DNS resolution failed", LogLevel.Error); break; case WebExceptionStatus.SecureChannelFailure: ModEntry.Logger.Log("[UpdateChecker] The `" + name + "` mod failed to check for updates, SSL handshake failed", LogLevel.Error); break; case WebExceptionStatus.Timeout: ModEntry.Logger.Log("[UpdateChecker] The `" + name + "` mod failed to check for updates, Connection timed out", LogLevel.Error); break; case WebExceptionStatus.TrustFailure: ModEntry.Logger.Log("[UpdateChecker] The `" + name + "` mod failed to check for updates, SSL certificate cannot be validated", LogLevel.Error); break; case WebExceptionStatus.ProtocolError: HttpWebResponse response = (HttpWebResponse)err.Response; ModEntry.Logger.Log($"[UpdateChecker] The `{name}` mod failed to check for updates, Server protocol error.\n\t[{response.StatusCode}]: {response.StatusDescription}", LogLevel.Error); break; default: ModEntry.Logger.Log("[UpdateChecker] The `" + name + "` mod failed to check for updates, a unknown error occured." + Environment.NewLine + err.ToString(), LogLevel.Error); break; } } public static void DoUpdateChecks() { try { string version = typeof(Game1).Assembly.GetName().Version.ToString(2); bool Connected; try { using (WebClient client = new WebClient()) using (Stream stream = client.OpenRead("http://www.google.com")) Connected = true; } catch { Connected = false; } if(Connected) Parallel.ForEach(Map, (pair) => { try { WebClient Client = new WebClient(); Uri uri = new Uri(pair.Value); SemanticVersion modVersion = (SemanticVersion)pair.Key.Version; try { Client.DownloadStringCompleted += (sender, evt) => { try { if (evt.Error != null) { HandleError(pair.Key.Name, (WebException)evt.Error); return; } Dictionary<string, UpdateInfo> Data = JsonConvert.DeserializeObject<Dictionary<string, UpdateInfo>>(evt.Result); UpdateInfo info = null; if (Data.ContainsKey(version)) info = Data[version]; else if (Data.ContainsKey("Default")) info = Data["Default"]; else ModEntry.Logger.ExitGameImmediately("[UpdateChecker] The `" + pair.Key.Name + "` mod does not support the current version of SDV."); if (info != null) { SemanticVersion min = new SemanticVersion(info.Minimum); SemanticVersion rec = new SemanticVersion(info.Recommended); SemanticVersion max = new SemanticVersion(info.Latest); if (min.IsNewerThan(modVersion)) ModEntry.Logger.ExitGameImmediately("[UpdateChecker] The `" + pair.Key.Name + "` mod is too old, a newer version is required."); if (rec.IsNewerThan(modVersion)) ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod has a new version available, it is recommended you update now.", LogLevel.Alert); if (modVersion.IsBetween(rec, max)) ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod has a new version available.", LogLevel.Info); } } catch (WebException err) { HandleError(pair.Key.Name, err); } catch (Exception err) { ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod failed to check for updates, unexpected error occured while reading result." + Environment.NewLine + err.ToString(), LogLevel.Error); } }; Client.DownloadStringAsync(uri); } catch (WebException err) { HandleError(pair.Key.Name, err); } } catch(Exception err) { ModEntry.Logger.Log("[UpdateChecker] The `" + pair.Key.Name + "` mod failed to check for updates, unexpected error occured." + Environment.NewLine + err.ToString(), LogLevel.Error); } }); else ModEntry.Logger.Log("[UpdateChecker] No internet connection, skipping update checks.", LogLevel.Debug); } catch(Exception err) { ModEntry.Logger.Log("[UpdateChecker] Unexpected failure, unexpected error occured."+Environment.NewLine+err.ToString(), LogLevel.Error); } } } }
using System.Collections.Generic; namespace DevExpress.Web.Demos { public static class WebSiteVisitorsProvider { public static IList<WebSiteWisitors> GetWebSiteVisitors() { return new List<WebSiteWisitors>() { new WebSiteWisitors("Visited a Web Site", 9152), new WebSiteWisitors("Downloaded a Trial", 6870), new WebSiteWisitors("Contacted to Support", 5121), new WebSiteWisitors("Subscribed", 2224), new WebSiteWisitors("Renewed", 1670) }; } } public class WebSiteWisitors { string caption; int count; public string Caption { get { return caption; } } public int Count { get { return count; } } public WebSiteWisitors(string caption, int count) { this.caption = caption; this.count = count; } } }
using OcTur.Control; using OcTur.View; using OcTur.Model; using OcTur.DTO; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace OcTur.View { public partial class FrmCadastroUsuario : Form { // inicialicia o Formulário de Cadastro de Usuário public FrmCadastroUsuario() { InitializeComponent(); } // configura evento do Botão cancelar private void btnCancelar_Click(object sender, EventArgs e) { // aqui volta pra tela de Autenticação //FrmAutenticacao telaAnterior = new FrmAutenticacao();// nesse caso Istacia o Formulário de Autenticação //this.Hide();// Esconde a Tela atual // telaAnterior.Show();// mostra a tela de Autenticação // aqui fecha a tela mas antes confirma se realmente o usuário que cancerlar o cadastro para voltar a tela de Configuração if (MessageBox.Show("Dejesa Cancelar Cadastro Funcionário", "Cadastro de Funcionários", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) // finaliza a tela this.Close(); } private void CadastroUsuarioFrm_Load(object sender, EventArgs e) { //ajuste do Perfil padrão picFotoUsuario.Image = Properties.Resources._1455554373_line_43_icon_icons1; picFotoUsuario.SizeMode = PictureBoxSizeMode.StretchImage; picFotoUsuario.Refresh(); //ajuste De Data int anoAtual = DateTime.Now.Year; int anoMinimo = anoAtual - 120; dtpDataNascimento.MinDate = new DateTime(anoMinimo, 1, 1); dtpDataNascimento.MinDate = DateTime.Now; //popular Combobox, futuramente Vira banco List<string> opcoes = new List<string>() { "Português", "Espanhol", "Inglês"}; foreach (var opcao in opcoes) { cboIdioma.Items.Add(opcao); } //desabilitar botão cadastro // btnCadastrar.Enabled = false; } private void btnAtualizarFoto_Click(object sender, EventArgs e) { OpenFileDialog alterarImagem = new OpenFileDialog(); alterarImagem.Title = "Selecione a foto"; alterarImagem.Filter = "Image File (*.jpg)|*.jpg"; if (alterarImagem.ShowDialog() == DialogResult.OK) { picFotoUsuario.ImageLocation = alterarImagem.FileName; picFotoUsuario.SizeMode = PictureBoxSizeMode.StretchImage; picFotoUsuario.Refresh(); } } // private void btnApagar_Click(object sender, EventArgs e) //{ // picFotoUsuario.Image = Properties.Resources._1455554373_line_43_icon_icons1; // } public void HabilitarCadastro() { if (!string.IsNullOrWhiteSpace(txtNome.Text) && !string.IsNullOrWhiteSpace(txtSenha.Text) && !string.IsNullOrWhiteSpace(txtUsuario.Text) && !string.IsNullOrWhiteSpace(dtpDataNascimento.Text) && (cboIdioma.SelectedIndex != -1) ) { btnCadastrar.Enabled = true; } else { btnCadastrar.Enabled = false; } } private void txtSenha_TextChanged(object sender, EventArgs e) { Util.VerificarSenha(txtSenha.Text); } private void btnCadastrar_Click(object sender, EventArgs e) { //TODO: Verificar imagem em array byte //Trasformar imagem em array byte MemoryStream ms = new MemoryStream(); picFotoUsuario.Image.Save(ms, ImageFormat.Jpeg); byte[] arrayBytesImagem = new byte[ms.Length]; ms.Position = 0; ms.Read(arrayBytesImagem, 0, arrayBytesImagem.Length); UsuarioDTO dto = new UsuarioDTO(); dto.Nome = txtNome.Text; dto.Senha = txtSenha.Text; dto.Usuario = txtUsuario.Text; dto.Foto = arrayBytesImagem; dto.Idioma = cboIdioma.SelectedIndex; dto.DataNascimento = dtpDataNascimento.Text; CadastroUsuarioControl controle = new CadastroUsuarioControl(dto); string retorno = controle.Inserir(); try { int idDto = Convert.ToInt32(retorno); MessageBox.Show("Usuário inserido com sucesso. Código: " + idDto.ToString()); } catch { MessageBox.Show("Não foi possével inserir o usuário. \nDetalhes: " + retorno, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void txtNome_TextChanged(object sender, EventArgs e) { HabilitarCadastro(); } private void cbxIdiomas_SelectedIndexChanged(object sender, EventArgs e) { HabilitarCadastro(); } //private void txtSenha_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrWhiteSpace(txtSenha.Text)) // { // picErrado.Visible = true; // picCorreto.Visible = false; // txtSenha.BackColor = Color.Tomato; // } // else // { // picErrado.Visible = true; // picCorreto.Visible = false; // txtSenha.BackColor = Color.Tomato; // if (Util.VerificarSenha(txtSenha.Text)) // { // picErrado.Visible = false; // picCorreto.Visible = true; // txtSenha.BackColor = Color.PaleGreen; // HabilitarCadastro(); // } // } //} //private void txtUsuario_TextChanged(object sender, EventArgs e) //{ // if (string.IsNullOrWhiteSpace(txtUsuario.Text)) // { // picErrado.Visible = true; // picCorreto.Visible = false; // txtUsuario.BackColor = Color.Tomato; // } // else // { // picErrado.Visible = true; // picCorreto.Visible = false; // txtUsuario.BackColor = Color.Tomato; // if (Util.VerificaCaracteresInvalidos(txtUsuario.Text)) // { // picErrado.Visible = false; // picCorreto.Visible = true; // txtUsuario.BackColor = Color.PaleGreen; // HabilitarCadastro(); // } // } //} } }
#define postprocess using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using System.Collections; using System.IO; public class PostProcessBuild { #if postprocess /// <summary> /// Copies the ExternalAssets Directory into the build. /// </summary> [PostProcessBuild] static public void Process(BuildTarget target, string pathToBuiltProject) { // if (target == BuildTarget.iOS) // { // DirectoryCopy(DirectoryUtility.ExternalAssets(), pathToBuiltProject + "/Data/ExternalAssets", true); // } // else if (target == BuildTarget.StandaloneWindows || target == BuildTarget.StandaloneWindows64) // { // string dataFolder = System.IO.Path.GetFileNameWithoutExtension(pathToBuiltProject) + "_Data"; // DirectoryCopy(DirectoryUtility.ExternalAssets(), pathToBuiltProject + "/../" + dataFolder + "/ExternalAssets", true); // } // else if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal) // { // DirectoryCopy(DirectoryUtility.ExternalAssets(), pathToBuiltProject + "/Contents/ExternalAssets", true); // } // else //if (target == BuildTarget.StandaloneOSXIntel || target == BuildTarget.StandaloneOSXIntel64 || target == BuildTarget.StandaloneOSXUniversal) // { // //DirectoryCopy(DirectoryUtility.ExternalAssets(), pathToBuiltProject , true); // DirectoryCopy(DirectoryUtility.ExternalAssets(), Application.streamingAssetsPath , true); // } DirectoryCopy(DirectoryUtility.ExternalAssets(), Application.streamingAssetsPath , true); } static public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { DirectoryInfo dir = new DirectoryInfo(sourceDirName); DirectoryInfo[] dirs = dir.GetDirectories(); // If the source directory does not exist, throw an exception. if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } // If the destination directory does not exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the file contents of the directory to copy. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { // Create the path to the new copy of the file. string temppath = Path.Combine(destDirName, file.Name); Debug.Log("Copying: " + temppath); // Copy the file. file.CopyTo(temppath, false); } // If copySubDirs is true, copy the subdirectories. if (copySubDirs) { foreach (DirectoryInfo subdir in dirs) { // Create the subdirectory. string temppath = Path.Combine(destDirName, subdir.Name); // Copy the subdirectories. DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } #endif }
using Microsoft.EntityFrameworkCore.Migrations; namespace Inventory.Data.Migrations { public partial class RestaurantCode : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Code", table: "Restaurant", nullable: true); migrationBuilder.UpdateData( table: "DbVersion", keyColumn: "Id", keyValue: 1, column: "Version", value: "3.2.5"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Code", table: "Restaurant"); migrationBuilder.UpdateData( table: "DbVersion", keyColumn: "Id", keyValue: 1, column: "Version", value: "3.2.4"); } } }
namespace ProgFrog.Interface.TaskRunning { public interface IInputWriter : IRunnerVisitor { void Write(string inp); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TricareManagementSystem.DataAccess.Employee; using TricareManagementSystem.Model; namespace TricareManagementSystem.BusinessLogic { public class ProcessAddNewComment { public bool AddComment(CommentDTO commentObject) { try { AddNewComment newCommentObject = new AddNewComment(); newCommentObject.Comment = commentObject; return newCommentObject.Add(); } catch { throw; } } } }
using System; namespace Inheritance { class Wizard : Human { public Wizard(string name) : base(name, 3, 25, 3, 50) { } public int Heal(Human target) { int healAmt = Intelligence * 10; target.health += healAmt; Console.WriteLine($"{Name} healed {target.Name} adding {healAmt} health!"); return target.health; } public override int Attack(Human target) { int dmg = Intelligence * 5; target.health -= dmg; health += dmg; Console.WriteLine($"{Name} attacks {target.Name} absorbing {dmg} health!"); return target.health; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Docller.Core.Repository.Mappers { public interface IReturnParameterMapper { /// <summary> /// Gets the return value. /// </summary> int? ReturnValue { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class time : MonoBehaviour { // Start is called before the first frame update int time_int = 30; public Text time_UI; void Start() { InvokeRepeating("timer", 1, 1); } void timer() { time_int -= 1; time_UI.text = time_int + ""; if (time_int == 0) { time_UI.text = "time\nup"; CancelInvoke("timer"); } } }
using Foundation; using System; using MaterialTransition; using UIKit; namespace Sample { public partial class SecondViewController : UIViewController { public SecondViewController(IntPtr handle) : base(handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); this.View.BackgroundColor = UIColor.FromRGB(54f / 256f, 70f / 256f, 93f / 256f); } partial void BtnCancelTouchUpInside(UIButton sender) { this.DismissViewController(true, null); } } }
using InterestRateApp.Contracts.Responses; using InterestRateApp.Domain.Entities; using InterestRateApp.Domain.Models; namespace InterestRateApp.Services.Mappers { public static class CustomerMapper { public static Customer ToDomain(this CustomerEntity customerEntity) { return new Customer { Id = customerEntity.Id, FirstName = customerEntity.FirstName, LastName = customerEntity.LastName, PersonalId = customerEntity.PersonalId }; } public static CustomerDTO ToDTO(this Customer customer) { return new CustomerDTO { Id = customer.Id, FirstName = customer.FirstName, LastName = customer.LastName, PersonalId = customer.PersonalId }; } } }
using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using LoLInfo.Models; using LoLInfo.Services; using LoLInfo.Services.ServiceModels; using LoLInfo.Services.WebServices; using Newtonsoft.Json; namespace LoLInfo.Services.WebServices { public class SummonerService : BaseService { public async Task<long> GetSummonerId(string summonerName, string regionCode = ServiceConstants.CurrentRegionCode) { //Note: this service can accept a comma-separated list of summoner names but we're assuming only one here using (var client = new HttpClient()) { var coreUrl = string.Format(ServiceConstants.GetSummonerIdUrl, regionCode, summonerName); var url = GetRegionRequestUrl(coreUrl, regionCode, null); var json = await client.GetStringAsync(url); if (string.IsNullOrWhiteSpace(json)) return -1; var summonerDictionary = JsonConvert.DeserializeObject<Dictionary<string,SummonerDto>>(json); return summonerDictionary[summonerName.ToLower()].Id; } } public async Task<List<MatchInfo>> GetMatchHistory(string summonerName, string regionCode = ServiceConstants.CurrentRegionCode) { var summonerId = await GetSummonerId(summonerName, regionCode); using (var client = new HttpClient()) { var coreUrl = string.Format(ServiceConstants.GetMatchHistoryUrl, regionCode, summonerId); var url = GetRegionRequestUrl(coreUrl, regionCode, null); var json = await client.GetStringAsync(url); if (string.IsNullOrWhiteSpace(json)) return null; var recentGames = JsonConvert.DeserializeObject<RecentGamesDto>(json); return recentGames.ToMatchHistory(); } } } }
 using Arduino_Alarm.SetAlarm.GetSchedule; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace Arduino_Alarm.EnterSettings { public class SettingsViewModel: INotifyPropertyChanged { public string Address { get; set; } public List<string> Transport { get; set; } public string TimeToReady { get; set; } public List<string> Minor { get; set; } public List<int> Subgroup { get; set; } public bool close; public int SelectedTransport { get; set; } public int SelectedMinor { get; set; } public int SelectedGroup { get; set; } public event PropertyChangedEventHandler PropertyChanged; public SettingsViewModel() { var set = Factory.GetSettings(); Transport = new List<string>() { "Driving", "Bicycling", "All public transport" }; OnPropertyChanged("Transport"); Minor = new List<string>() { "Урб", "Флс", "ММК", "НТ", "ПСБ", "ИАД", "Псх", "Лог", "Мен", "ФЭ" }; OnPropertyChanged("Minor"); Subgroup = new List<int>() { 1, 2 }; OnPropertyChanged("Subgroup"); if (set.Address != null) Address = set.Address; if (set.TimeToReady != null) TimeToReady = set.TimeToReady; if (set.Subgroup != 0) SelectedGroup = Subgroup.FindIndex(c => c == set.Subgroup); else SelectedGroup = -1; if (set.Minor != null) SelectedMinor = Minor.FindIndex(c => c == set.Minor); else SelectedMinor = -1; if (set.Transport != null) SelectedTransport = Transport.FindIndex(c => c == set.Transport); else SelectedTransport = -1; } public void Check() { try { string[] st = TimeToReady.Split(new char[] { ':' }); int Hours = Convert.ToInt16(st[0]); int Min = Convert.ToInt16(st[1]); if (Hours > 24 || (Min > 59)) { close = false; MessageBox.Show("Enter time in format 23:15", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } else close = true; } catch { throw new ArgumentException(); } } private void OnPropertyChanged(string name) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(name)); } public void Error() { MessageBox.Show("Error.Please enter the data", "Error", MessageBoxButton.OK, MessageBoxImage.Error); } public void SaveChanges() { Check(); if (close) { if (SelectedGroup != -1 && SelectedMinor != -1 && SelectedTransport != -1 && Address != null && Address.Trim().Count() != 0 && TimeToReady != null && TimeToReady.Count() != 0) { Factory._set = new Settings() { Address = Address, Transport = Transport[SelectedTransport], Minor = Minor[SelectedMinor], Subgroup = Subgroup[SelectedGroup], TimeToReady = TimeToReady }; Factory._set.ChangeSettings(Factory._set); Factory.Update(); } else { close = false; Error(); } } } } }
using UnityEngine; using System.Collections; using MainCharacter; public class MultiplayerCoordinator { static MultiplayerCoordinator _instance; public static MultiplayerCoordinator Instance{get{ if(_instance == null){ _instance = new MultiplayerCoordinator(); } backgroundUI = BackgroundUI.Instance; return _instance; } } public MultiplayerCharacterDriver OArcusDriver{ private get; set; } public MultiplayerCharacterDriver DarcusDriver{ private get; set; } public static BackgroundUI backgroundUI; public MultiplayerCoordinator(){ backgroundUI = BackgroundUI.Instance; } public void UpdateUI(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.uiDriver.UpdateBars (); } if (GameObject.Find("dArcus") != null) { DarcusDriver.uiDriver.UpdateBars (); } } public void GameOver(){ if (OArcusDriver.health <= 0 && DarcusDriver.health <= 0) { backgroundUI.ShowLoseScreen(); } /* else { if (GameObject.Find("oArcus") != null) { OArcusDriver.WinLevel(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.WinLevel(); } } */ } public void NewLevel(){ OArcusDriver.gameOver = false; DarcusDriver.gameOver = false; } public void UseOffensiveGreen(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.ActivateGreen(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.ActivateGreen(); } } public void UseOffensiveOrange(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.ActivateOrange(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.ActivateOrange(); } } public void UseOffensivePurple(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.ActivatePurple(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.ActivatePurple(); } } public void UseDefensiveGreen(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.PressDefensiveGreen(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.PressDefensiveGreen(); } } public void UseDefensiveOrange(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.PressDefensiveOrange(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.PressDefensiveOrange(); } } public void UseDefensivePurple(){ if (GameObject.Find("oArcus") != null) { OArcusDriver.PressDefensivePurple(); } if (GameObject.Find("dArcus") != null) { DarcusDriver.PressDefensivePurple(); } } }
using System; using System.Collections.Generic; using System.Text; namespace RSS.Business.Models.Enums { public enum SupplierType { PessoaFisica = 1, PessoaJuridica } }
namespace E1 { public class Pajaro : Animales { public Pajaro(int energia) : base(energia) { } public override void comer() => energia += 10; public override void jugar(){ if (energia >= 0) energia -= 5; } } }
using System; namespace Algorithms.Structures { public class SingleLinkedList<T> where T : struct { private Node? _head; private int _cnt; public int Count => _cnt; public void Insert(T value) { var node = new Node(value) { Next = _head }; _head = node; ++_cnt; } public T Remove() { if (_head is null) throw new ArgumentOutOfRangeException(); --_cnt; var value = _head.Value; _head = _head.Next; return value; } private class Node { public Node(T value) => Value = value; public T Value { get; } public Node? Next { get; set; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Markup; using CODE.Framework.Wpf.Validation; namespace CODE.Framework.Wpf.MarkupExtensions { /// <summary> /// An extension to the standard Binding markup extension provided by WPF. /// This extension provides all features of the standard WPF Binding class, as well as additional features, /// such as binding security setup, binding validation, and more /// </summary> /// <seealso cref="System.Windows.Markup.MarkupExtension" /> public class Bind : MarkupExtension { /// <summary> /// Initializes a new instance of the <see cref="Bind"/> class. /// </summary> public Bind() { _binding = new Binding(); BindSecurityAttribute = true; BindValidationAttributes = true; } /// <summary> /// Initializes a new instance of the <see cref="Bind"/> class. /// </summary> /// <param name="path">The path.</param> public Bind(string path) { _binding = new Binding(path); BindSecurityAttribute = true; BindValidationAttributes = true; } /// <summary> /// The decorated binding class. /// </summary> private readonly Binding _binding; /// <summary> /// The decorated binding class. /// </summary> [Browsable(false)] public Binding Binding { get { return _binding; } } /// <summary> Opaque data passed to the asynchronous data dispatcher </summary> [DefaultValue(null)] public object AsyncState { get { return _binding.AsyncState; } set { _binding.AsyncState = value; } } /// <summary> True if Binding should interpret its path relative to /// the data item itself. /// </summary> /// <remarks> /// The normal behavior (when this property is false) /// includes special treatment for a data item that implements IDataSource. /// In this case, the path is treated relative to the object obtained /// from the IDataSource.Data property. In addition, the binding listens /// for the IDataSource.DataChanged event and reacts accordingly. /// Setting this property to true overrides this behavior and gives /// the binding access to properties on the data source object itself. /// </remarks> [DefaultValue(false)] public bool BindsDirectlyToSource { get { return _binding.BindsDirectlyToSource; } set { _binding.BindsDirectlyToSource = value; } } /// <summary> /// The converter to apply /// </summary> /// <value>The converter.</value> [DefaultValue(null)] public IValueConverter Converter { get { return _binding.Converter; } set { _binding.Converter = value; } } /// <summary> /// Value to be used for the target when the bound value is null /// </summary> /// <value>The target null value.</value> [DefaultValue(null)] public object TargetNullValue { get { return _binding.TargetNullValue; } set { _binding.TargetNullValue = value; } } /// <summary> /// The converter culture to apply /// </summary> /// <value>The converter culture.</value> [TypeConverter(typeof (CultureInfoIetfLanguageTagConverter)), DefaultValue(null)] public CultureInfo ConverterCulture { get { return _binding.ConverterCulture; } set { _binding.ConverterCulture = value; } } /// <summary> /// Gets or sets the converter parameter. /// </summary> /// <value>The converter parameter.</value> [DefaultValue(null)] public object ConverterParameter { get { return _binding.ConverterParameter; } set { _binding.ConverterParameter = value; } } /// <summary> /// Name of the element to use as the source /// </summary> /// <value>The name of the element.</value> [DefaultValue(null)] public string ElementName { get { return _binding.ElementName; } set { _binding.ElementName = value; } } /// <summary> /// Fallback value to apply when no binding value can be determined /// </summary> /// <value>The fallback value.</value> [DefaultValue(null)] public object FallbackValue { get { return _binding.FallbackValue; } set { _binding.FallbackValue = value; } } /// <summary> /// Gets or sets a value indicating whether this instance is asynchronous. /// </summary> /// <value><c>true</c> if this instance is asynchronous; otherwise, <c>false</c>.</value> [DefaultValue(false)] public bool IsAsync { get { return _binding.IsAsync; } set { _binding.IsAsync = value; } } /// <summary> /// Binding Mode /// </summary> /// <value>The mode.</value> [DefaultValue(BindingMode.Default)] public BindingMode Mode { get { return _binding.Mode; } set { _binding.Mode = value; } } /// <summary> /// Raise SourceUpdated event whenever a value flows from target to source /// </summary> /// <value><c>true</c> if [notify on source updated]; otherwise, <c>false</c>.</value> [DefaultValue(false)] public bool NotifyOnSourceUpdated { get { return _binding.NotifyOnSourceUpdated; } set { _binding.NotifyOnSourceUpdated = value; } } /// <summary> /// Raise TargetUpdated event whenever a value flows from source to target /// </summary> /// <value><c>true</c> if [notify on target updated]; otherwise, <c>false</c>.</value> [DefaultValue(false)] public bool NotifyOnTargetUpdated { get { return _binding.NotifyOnTargetUpdated; } set { _binding.NotifyOnTargetUpdated = value; } } /// <summary> /// Raise ValidationError event whenever there is a ValidationError on Update /// </summary> /// <value><c>true</c> if [notify on validation error]; otherwise, <c>false</c>.</value> [DefaultValue(false)] public bool NotifyOnValidationError { get { return _binding.NotifyOnValidationError; } set { _binding.NotifyOnValidationError = value; } } /// <summary> /// The source path (for CLR bindings). /// </summary> /// <value>The path.</value> [DefaultValue(null)] public PropertyPath Path { get { return _binding.Path; } set { _binding.Path = value; } } /// <summary> /// Gets or sets the relative source. /// </summary> /// <value>The relative source.</value> [DefaultValue(null)] public RelativeSource RelativeSource { get { return _binding.RelativeSource; } set { _binding.RelativeSource = value; } } /// <summary> object to use as the source </summary> /// <remarks> To clear this property, set it to DependencyProperty.UnsetValue. </remarks> [DefaultValue(null)] public object Source { get { return _binding.Source; } set { _binding.Source = value; } } /// <summary> /// called whenever any exception is encountered when trying to update /// the value to the source. The application author can provide its own /// handler for handling exceptions here. If the delegate returns /// null - don't throw an error or provide a ValidationError. /// Exception - returns the exception itself, we will fire the exception using Async exception model. /// ValidationError - it will set itself as the BindingInError and add it to the element's Validation errors. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public UpdateSourceExceptionFilterCallback UpdateSourceExceptionFilter { get { return _binding.UpdateSourceExceptionFilter; } set { _binding.UpdateSourceExceptionFilter = value; } } /// <summary> /// Update type /// </summary> /// <value>The update source trigger.</value> [DefaultValue(UpdateSourceTrigger.Default)] public UpdateSourceTrigger UpdateSourceTrigger { get { return _binding.UpdateSourceTrigger; } set { _binding.UpdateSourceTrigger = value; } } /// <summary> /// True if a data error in the source item should be considered a validation error. /// </summary> /// <value><c>true</c> if [validates on data errors]; otherwise, <c>false</c>.</value> [DefaultValue(false)] public bool ValidatesOnDataErrors { get { return _binding.ValidatesOnDataErrors; } set { _binding.ValidatesOnDataErrors = value; } } /// <summary> /// True if an exception during source updates should be considered a validation error. /// </summary> /// <value><c>true</c> if [validates on exceptions]; otherwise, <c>false</c>.</value> [DefaultValue(false)] public bool ValidatesOnExceptions { get { return _binding.ValidatesOnExceptions; } set { _binding.ValidatesOnExceptions = value; } } /// <summary> /// The XPath path (for XML bindings). /// </summary> /// <value>The x path.</value> [DefaultValue(null)] public string XPath { get { return _binding.XPath; } set { _binding.XPath = value; } } /// <summary> /// Collection&lt;ValidationRule&gt; is a collection of ValidationRule /// implementations on either a Binding or a MultiBinding. Each of the rules /// is run by the binding engine when validation on update to source /// </summary> [DefaultValue(null)] public Collection<ValidationRule> ValidationRules { get { return _binding.ValidationRules; } } /// <summary> /// Gets or sets the string format. /// </summary> /// <value>The string format.</value> [DefaultValue(null)] public string StringFormat { get { return _binding.StringFormat; } set { _binding.StringFormat = value; } } /// <summary> /// Gets or sets the name of the binding group. /// </summary> /// <value>The name of the binding group.</value> [DefaultValue("")] public string BindingGroupName { get { return _binding.BindingGroupName; } set { _binding.BindingGroupName = value; } } /// <summary> /// Defines whether the security attribute on the binding source should automatically be bound /// to the CODE Framework security system for UI security. /// </summary> /// <value><c>true</c> if the security system is to automatically kick in (default)</value> [DefaultValue(true)] public bool BindSecurityAttribute { get; set; } /// <summary> /// Defines whether validation attributes should be automatically bound to the CODE Framework validation system /// </summary> /// <value><c>true</c> if the validation system is to automatically kick in (default)</value> [DefaultValue(true)] public bool BindValidationAttributes { get; set; } /// <summary> /// This basic implementation just sets a binding on the targeted /// <see cref="DependencyObject"/> and returns the appropriate /// <see cref="BindingExpressionBase"/> instance.<br/> /// All this work is delegated to the decorated <see cref="Binding"/> /// instance. /// </summary> /// <returns> /// The object value to set on the property where the extension is applied. /// In case of a valid binding expression, this is a <see cref="BindingExpressionBase"/> /// instance. /// </returns> /// <param name="provider">Object that can provide services for the markup /// extension.</param> public override object ProvideValue(IServiceProvider provider) { var valueProvider = provider as IProvideValueTarget; if (valueProvider != null) { var element = valueProvider.TargetObject as FrameworkElement; if (element != null) { // Automatically hook up CODE Framework security if applicable if (BindSecurityAttribute) if (element.DataContext == null) // We do not have a source yet, but if the data context ever changes, we can trigger another update element.DataContextChanged += (s, e) => { UpdateSecurity(element); }; else UpdateSecurity(element); // Automatically hook up CODE Framework validation if applicable if (BindValidationAttributes) if (element.DataContext == null) // We do not have a source yet, but if the data context ever changes, we can trigger another update element.DataContextChanged += (s, e) => { UpdateValidation(element); }; else UpdateValidation(element); } } // Invoke standard binding behavior return _binding.ProvideValue(provider); } private void UpdateValidation(DependencyObject targetObject) { var validationBinding = new AttributeValidationBinding(_binding.Path.Path); var attributes = validationBinding.GetAttributes(targetObject, InputValidation.ValidationAttributesProperty); if (attributes != null) InputValidation.SetValidationAttributes(targetObject, attributes); } private void UpdateSecurity(DependencyObject targetObject) { var readOnlyRolesBinding = new AttributePropertyBinding(_binding.Path.Path + "[Security.ReadOnlyRoles]"); var readOnlyRolesValue = readOnlyRolesBinding.GetAttributeProperty(targetObject, Security.Security.ReadOnlyRolesProperty); if (readOnlyRolesValue != null && readOnlyRolesValue is string) Security.Security.SetReadOnlyRoles(targetObject, (string)readOnlyRolesValue); var fullAccessBinding = new AttributePropertyBinding(_binding.Path.Path + "[Security.FullAccessRoles]"); var fullAccessRolesValue = fullAccessBinding.GetAttributeProperty(targetObject, Security.Security.FullAccessRolesProperty); if (fullAccessRolesValue != null && fullAccessRolesValue is string) Security.Security.SetFullAccessRoles(targetObject, (string)fullAccessRolesValue); } /// <summary> /// Validates a service provider that was submitted to the <see cref="ProvideValue"/> /// method. This method checks whether the provider is null (happens at design time), /// whether it provides an <see cref="IProvideValueTarget"/> service, and whether /// the service's <see cref="IProvideValueTarget.TargetObject"/> and /// <see cref="IProvideValueTarget.TargetProperty"/> properties are valid /// <see cref="DependencyObject"/> and <see cref="DependencyProperty"/> /// instances. /// </summary> /// <param name="provider">The provider to be validated.</param> /// <param name="target">The binding target of the binding.</param> /// <param name="dp">The target property of the binding.</param> /// <returns>True if the provider supports all that's needed.</returns> protected virtual bool TryGetTargetItems(IServiceProvider provider, out DependencyObject target, out DependencyProperty dp) { target = null; dp = null; if (provider == null) return false; //create a binding and assign it to the target var service = (IProvideValueTarget) provider.GetService(typeof (IProvideValueTarget)); if (service == null) return false; //we need dependency objects / properties target = service.TargetObject as DependencyObject; dp = service.TargetProperty as DependencyProperty; return target != null && dp != null; } } }
using System; using System.Threading.Tasks; using AutoFixture; using Moq; using NUnit.Framework; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Apprentices.ChangeEmployer; using SFA.DAS.ProviderCommitments.Interfaces; using SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice; using SFA.DAS.ProviderCommitments.Web.Services.Cache; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Apprentice.ChangeEmployer { [TestFixture] public class InformViewModelMapperTests { private InformViewModelMapper _mapper; private Mock<IOuterApiClient> _apiClient; private ChangeEmployerInformRequest _request; private GetInformResponse _apiResponse; private readonly Fixture _fixture = new Fixture(); [SetUp] public void Setup() { _request = _fixture.Create<ChangeEmployerInformRequest>(); _apiResponse = _fixture.Create<GetInformResponse>(); _apiClient = new Mock<IOuterApiClient>(); _apiClient.Setup(x => x.Get<GetInformResponse>(It.Is<GetInformRequest>(r => r.ApprenticeshipId == _request.ApprenticeshipId && r.ProviderId == _request.ProviderId))) .ReturnsAsync(_apiResponse); _mapper = new InformViewModelMapper(_apiClient.Object); } [Test] public async Task LegalEntityName_Is_Mapped_Correctly() { var result = await _mapper.Map(_request); Assert.AreEqual(_apiResponse.LegalEntityName, result.LegalEntityName); } } }
using SMG.Common.Code; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SMG.Common.Transitions { public class ProductTrigger : Trigger, IElementaryTriggerCondition { /// <summary> /// Creates a trigger based on another trigger, with new conditions. /// </summary> /// <param name="parent">The original trigger.</param> /// <param name="tset">The corresponding transition set.</param> /// <param name="pre">The precondition for the new trigger.</param> /// <param name="post">The postcondition for the new trigger.</param> internal ProductTrigger(Trigger parent, TransitionSet tset, IGate pre, IGate post) : base(parent, tset, pre, post) { } public ProductTrigger(Trigger parent) : base(parent, parent.Transitions, parent.PreCondition, parent.PostCondition) { } public void Qualify() { Transitions.QualifyForTrigger(); } } }
using System; using System.Collections.Generic; using System.Text; namespace RestDDD.Domain.Entities.Enum { public enum TipoUsuario { Administrador = 1, Funcionario = 2, Prestador = 3, Cliente = 4 } }
using System; using System.Collections.Generic; using StardewModdingAPI; using StardewModdingAPI.Events; using StardewValley.Menus; using StardewValley; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using StardewValley.Objects; namespace BiggerBackpack { public class Mod : StardewModdingAPI.Mod { public static Mod instance; private Texture2D bigBackpack; /// <summary>The mod entry point, called after the mod is first loaded.</summary> /// <param name="helper">Provides simplified APIs for writing mods.</param> public override void Entry(IModHelper helper) { instance = this; bigBackpack = Helper.Content.Load<Texture2D>("backpack.png"); helper.Events.Display.MenuChanged += onMenuChanged; helper.Events.Display.RenderingHud += onRenderingHud; helper.Events.Input.ButtonPressed += onButtonPressed; Helper.ConsoleCommands.Add("player_setbackpacksize", "Set the size of the player's backpack.", command); } private void command( string cmd, string[] args ) { if (args.Length != 1) { Log.info("Must have one command argument"); return; } int newMax = int.Parse(args[0]); if (newMax < Game1.player.MaxItems) { for (int i = Game1.player.MaxItems - 1; i >= newMax; --i) Game1.player.Items.RemoveAt(i); } else { for (int i = Game1.player.Items.Count; i < Game1.player.MaxItems; ++i) Game1.player.Items.Add(null); } Game1.player.MaxItems = int.Parse(args[0]); } /// <summary>Raised before drawing the HUD (item toolbar, clock, etc) to the screen. The vanilla HUD may be hidden at this point (e.g. because a menu is open).</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void onRenderingHud(object sender, RenderingHudEventArgs e) { if (!Context.IsWorldReady) return; if (Game1.currentLocation.Name == "SeedShop" && Game1.player.MaxItems == 36) { e.SpriteBatch.Draw(bigBackpack, Game1.GlobalToLocal(new Vector2(7 * Game1.tileSize + Game1.pixelZoom * 2, 17 * Game1.tileSize)), new Rectangle(0, 0, 12, 14), Color.White, 0.0f, Vector2.Zero, Game1.pixelZoom, SpriteEffects.None, (float)(19.25 * Game1.tileSize / 10000.0)); } } /// <summary>Raised after the player presses a button on the keyboard, controller, or mouse.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void onButtonPressed(object sender, ButtonPressedEventArgs e) { if (!Context.IsWorldReady) return; if (e.Button.IsActionButton() && !this.Helper.Input.IsSuppressed(e.Button)) { if (Game1.player.MaxItems == 36 && Game1.currentLocation.Name == "SeedShop" && e.Cursor.Tile.X == 7 && (e.Cursor.Tile.Y == 17 || e.Cursor.Tile.Y == 18) ) { this.Helper.Input.Suppress(e.Button); Response yes = new Response("Purchase", "Purchase (50,000g)"); Response no = new Response("Not", Game1.content.LoadString("Strings\\Locations:SeedShop_BuyBackpack_ResponseNo")); Response[] resps = new Response[] { yes, no }; Game1.currentLocation.createQuestionDialogue("Backpack Upgrade -- 48 slots", resps, "spacechase0.BiggerBackpack"); } } } /// <summary>Raised after a game menu is opened, closed, or replaced.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void onMenuChanged(object sender, MenuChangedEventArgs e) { // on closed if (Context.IsWorldReady && e.OldMenu is DialogueBox) { if (Game1.currentLocation.lastQuestionKey == "spacechase0.BiggerBackpack" && prevSelResponse == 0) { if (Game1.player.Money >= 50000) { Game1.player.Money -= 50000; Game1.player.MaxItems += 12; for (int index = 0; index < Game1.player.MaxItems; ++index) { if (Game1.player.Items.Count <= index) Game1.player.Items.Add((Item)null); } Game1.player.holdUpItemThenMessage((Item)new SpecialItem(99, "Premium Pack"), true); } else Game1.drawObjectDialogue(Game1.content.LoadString("Strings\\UI:NotEnoughMoney2")); } Helper.Events.GameLoop.UpdateTicked -= watchSelectedResponse; prevSelResponse = -1; } // on new menu switch (e.NewMenu) { case GameMenu gameMenu: { var pages = (List<IClickableMenu>)Helper.Reflection.GetField<List<IClickableMenu>>(gameMenu, "pages").GetValue(); var oldInv = pages[GameMenu.inventoryTab]; if (oldInv.GetType() == typeof(InventoryPage)) { pages[GameMenu.inventoryTab] = new NewInventoryPage(oldInv.xPositionOnScreen, oldInv.yPositionOnScreen, oldInv.width, oldInv.height); } break; } case MenuWithInventory menuWithInv: menuWithInv.inventory.capacity = 48; menuWithInv.inventory.rows = 4; menuWithInv.height += 64; break; case ShopMenu shop: shop.inventory = new InventoryMenu(shop.inventory.xPositionOnScreen, shop.inventory.yPositionOnScreen, false, (List<Item>)null, new InventoryMenu.highlightThisItem(shop.highlightItemToSell), 48, 4, 0, 0, true); break; case DialogueBox _: Helper.Events.GameLoop.UpdateTicked += watchSelectedResponse; break; } } int prevSelResponse = -1; /// <summary>Raised after the game state is updated (≈60 times per second), while waiting for a dialogue response.</summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event arguments.</param> private void watchSelectedResponse(object sender, UpdateTickedEventArgs e) { if (Game1.activeClickableMenu is DialogueBox db) { int sel = Helper.Reflection.GetField<int>(db, "selectedResponse").GetValue(); if (sel != -1) prevSelResponse = sel; } } } }
namespace Strategy_Checkpoint { public class Diesel_Truck : IVehicle { public double FuelPrice = 3.19; public double FuelCost(int consumed) { return FuelPrice * consumed; } } }
using System; using UnityEngine; using Unity.Mathematics; using static Unity.Mathematics.math; namespace IzBone.PhysCloth.Authoring { using Common; using Common.Field; /** * Compliance値として使用するfloatにつける属性。 * インスペクタ表示時に、いい感じのスライダーで設定可能にする。 */ public sealed class ComplianceAttribute : PropertyAttribute { public ComplianceAttribute() {} public const float LEFT_VAL = 0.1f; public const float RIGHT_VAL = 1e-12f; // 強度として表示する値と、実際のcomplianceの値との相互変換 static public float compliance2ShowValue(float cmp) => (float)PowRangeAttribute.srcValue2showValue( cmp, 1000, LEFT_VAL, RIGHT_VAL ); static public float showValue2Compliance(float val) => (float)PowRangeAttribute.showValue2srcValue( val, 1000, LEFT_VAL, RIGHT_VAL ); } /** * AngleCompliance値として使用するfloatにつける属性。 * インスペクタ表示時に、いい感じのスライダーで設定可能にする。 */ public sealed class AngleComplianceAttribute : PropertyAttribute { public AngleComplianceAttribute() {} public const float LEFT_VAL = 10; public const float RIGHT_VAL = 0.0001f; // 強度として表示する値と、実際のcomplianceの値との相互変換 static public float compliance2ShowValue(float cmp) => (float)PowRangeAttribute.srcValue2showValue( cmp, 1000, LEFT_VAL, RIGHT_VAL ); static public float showValue2Compliance(float val) => (float)PowRangeAttribute.showValue2srcValue( val, 1000, LEFT_VAL, RIGHT_VAL ); } }
using System; class DigitAsWord { private static void Main() { while (true) { string lsResult, lsEntNumber; sbyte lsbNumber = 0; Console.Write("Enter number between 0 and 9 : "); lsEntNumber = Console.ReadLine(); if (sbyte.TryParse(lsEntNumber, out lsbNumber)) { switch (lsbNumber) { case 0: lsResult = "zero"; break; case 1: lsResult = "one"; break; case 2: lsResult = "two"; break; case 3: lsResult = "three"; break; case 4: lsResult = "four"; break; case 5: lsResult = "five"; break; case 6: lsResult = "six"; break; case 7: lsResult = "seven"; break; case 8: lsResult = "eight"; break; case 9: lsResult = "nine"; break; default: lsResult = "not a digit"; break; } } else { lsResult = "not a digit"; } Console.WriteLine("{0} -> {1}", lsEntNumber, lsResult); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Data; namespace Olive.Desktop.WPF.Converters { public class MinutesFromHoursConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { object minutes; try { minutes = (int)value; if ((int)minutes > 55) { minutes = (int)value % 60; } } catch (Exception) { minutes=null; } return minutes; //Old //int minutes = (int)value; //if (minutes > 55) //{ // minutes = (int)value % 60; //} //return minutes; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return value; } return (int)value; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Media; using System.IO; namespace Labyrinth { public enum GameStatus { MENU, PLAY, INSTRUCTION, CREDITS, LOSE, ENDLEVEL, ENDGAME }; public partial class Game1 : Game { private GraphicsDeviceManager _graphics; private SpriteBatch _spriteBatch; Character character; public Game1() { _graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; IsMouseVisible = true; } protected override void Initialize() { _graphics.PreferredBackBufferWidth = (int)C.DISPLAYDIM.X; // set this value to the desired width of your window _graphics.PreferredBackBufferHeight = (int)C.DISPLAYDIM.Y; // set this value to the desired height of your window _graphics.ApplyChanges(); C.gameStatus = GameStatus.MENU; C.animationOn = false; base.Initialize(); } protected override void LoadContent() { _spriteBatch = new SpriteBatch(GraphicsDevice); Save.LoadBestTime(); LoadLevel(); character = new Character(this.GraphicsDevice); LoadLabel(); LoadButton(); LoadTexture(); LoadSoundEffect(); } void MediaPlayer_MediaStateChanged(object sender, System.EventArgs s) { MediaPlayer.Volume -= 0.1f; MediaPlayer.Play(C.song); } protected override void Update(GameTime gameTime) { if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape)) Exit(); UpdateState(gameTime); base.Update(gameTime); } protected override void Draw(GameTime gameTime) { _spriteBatch.Begin(); Status.DrawSatus(_spriteBatch, GraphicsDevice, character); _spriteBatch.End(); base.Draw(gameTime); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LinerendereScript : MonoBehaviour { public Transform[] LinePath; private LineRenderer _lineRenderer; void Start () { _lineRenderer = GetComponent<LineRenderer>(); _lineRenderer.positionCount = LinePath.Length +1; for (int i = 0; i < LinePath.Length; i++) { _lineRenderer.SetPosition(i, LinePath[i].position); } _lineRenderer.SetPosition(LinePath.Length,LinePath[1].position); } void Update() { /*for (int i = 0; i < LinePath.Length; i++) //Only need to set once, so moved to start { _lineRenderer.SetPosition(i, LinePath[i].position); }*/ } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainMenuHandler : MonoBehaviour { private int menuSlide = 1; public GameObject currentSprite; private GameObject oldSprite; public GameObject mainCamera; private GameObject nextSlide; private Vector3 newCameraPosition; private bool moveFinished = true; void Start() { //initiates first image currentSprite = Resources.Load<GameObject>("MainMenuExample" + menuSlide) as GameObject; currentSprite = GameObject.Instantiate(currentSprite, transform.position, transform.rotation); currentSprite.gameObject.transform.position = new Vector2(0, 0); } void Update() { if (Input.GetKeyDown("a")) { changeSlide(-1); } if (Input.GetKeyDown("d")) { changeSlide(1); } // Camera Movement if (!moveFinished) { mainCamera.transform.position = Vector3.MoveTowards(mainCamera.transform.position, newCameraPosition, Time.deltaTime * 100f); if (mainCamera.transform.position == newCameraPosition) moveFinished = true; } } private void changeSlide(int modifier) { //removes unused sprites if (oldSprite) Destroy(oldSprite); menuSlide = menuSlide + modifier; if (menuSlide > 5) menuSlide = 1; if (menuSlide < 1) menuSlide = 5; // Loads new Slide nextSlide = Resources.Load<GameObject>("MainMenuExample" + menuSlide) as GameObject; nextSlide = GameObject.Instantiate(nextSlide, transform.position, transform.rotation); // calculates position and moves float moveToPosition = currentSprite.gameObject.transform.position.x + (nextSlide.GetComponentInChildren<SpriteRenderer>().bounds.size.x) * modifier; nextSlide.gameObject.transform.position = new Vector2(moveToPosition, 0); // calculates where to move camera and initiates camera movement newCameraPosition = new Vector3(moveToPosition, 0, -10); moveFinished = false; oldSprite = currentSprite; currentSprite = nextSlide; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WinEvent : MonoBehaviour { public MovetoTarget moveTo; void Start(){ moveTo = GetComponentInParent <MovetoTarget> (); } public void DestroyBall(){ moveTo.DestroyTarget (); } public void OnHelloAnimationFinished(){ moveTo.Activate (); } }
using System.Data.Entity; using TwitterLikeApp.Repositories; namespace TwitterLikeApp.UI.Models { public class Context : IContext { private readonly DbContext _db; public Context(DbContext context = null, IUserRepository users = null, IRibbitRepository ribbits = null, IUserProfileRepository profiles = null) { _db = context ?? new RibbitContext(); Users = users ?? new UserRepository(_db, true); Ribbits = ribbits ?? new RibbitRepository(_db, true); Profiles = profiles ?? new UserProfileRepository(_db, true); } public IUserRepository Users { get; private set; } public IRibbitRepository Ribbits { get; private set; } public IUserProfileRepository Profiles { get; private set; } public int SaveChanges() { return _db.SaveChanges(); } public void Dispose() { if (_db != null) { try { _db.Dispose(); } catch { } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ChoiceCenium.SignalR; namespace ChoiceCenium.Services { public static class StatisticService { public static List<KjedeUpgradeStatusSignalR> PopulateKjedeUpgradeStatusList(List<HotelInfoSignalR> hotelListSignalR) { var kjedeInfoList = KjedeService.GetKjeder(); return (from h in hotelListSignalR group h by h.KjedeId into grp join k in kjedeInfoList on grp.Key equals k.KjedeId select new KjedeUpgradeStatusSignalR { KjedeId = grp.Key, KjedeNavn = k.KjedeNavn, TotalHotels = grp.Count(), UpgradedHotels = grp.Count(ht => ht.CeniumUpgradeComplete) }).ToList(); // Comfort Hotels 6 / 12 // Choice Hotels 1 / 8 // Clarion Hotels 6 / 33 } public static double GetUpgradeStatusPercentage(List<HotelInfoSignalR> hotelListSignalR) { int TotalNrOfHotelsToBeUpgraded = hotelListSignalR.Count(hl => !hl.NotUpgrading); int TotalNrOfUpgradedHotels = hotelListSignalR.Count(hl => hl.CeniumUpgradeComplete); return TotalNrOfUpgradedHotels/TotalNrOfHotelsToBeUpgraded*100; } } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; namespace Texts_Dictionary { class Program { static void Main(string[] args) { var path = Input.resourcePath + "\\Dictionary.txt"; var listOfWords = Input.GetWords("NewFile1", "txt"); if (!File.Exists(path)) { File.Create(path); } var newFile = File.AppendText(path); newFile.Write(listOfWords); } } }
 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { /// <summary> /// 班组 /// </summary> public class E_ClassInfo : E_BaseModel { /// <summary> /// 班组ID /// </summary> public int id { get; set; } /// <summary> /// 班组名称 /// </summary> public string CName { get; set; } /// <summary> /// 作业区ID /// </summary> public int operationid { get; set; } /// <summary> /// 区域ID /// </summary> public int AreaID { get; set; } /// <summary> /// 备注 /// </summary> public string Back { get; set; } /// <summary> /// 编号 /// </summary> public string temp1 { get; set; } /// <summary> /// 配送区域(作废) /// </summary> public int AID { get; set; } /// <summary> /// /// </summary> public int SeqNo { get; set; } /// <summary> /// /// </summary> public int Flag { get; set; } /// <summary> /// 公司ID /// </summary> public int companyid { 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.Windows.Forms; namespace Wisielec_poprawny { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public string password; public string visible_password = ""; public string passwd_holder = ""; public int tries = 5; private void Form1_Load(object sender, EventArgs e) { MessageBox.Show("Instrukcja: Celem gry jest odgadnięcie zamaskowanego hasła poprzez zgadywanie liter. Liczba możliwych błędów jest ograniczona. Miłej zabawy :) !"); password = wybierzSlowo("slowa.txt"); show_word(password); } public string wybierzSlowo(String filename) { int licznik = 1; System.IO.StreamReader sr = System.IO.File.OpenText(filename); while (!sr.EndOfStream) { String line = sr.ReadLine(); for (int k = 0; k < line.Length; k++) { if (line[k] == '|') { licznik++; } } line = line.Trim(); if (!String.IsNullOrEmpty(line)) { //haslo|haslo|haslo String[] a = line.Split('|'); int rand = new Random().Next(0, licznik); password = a[rand]; } } sr.Close(); return password; } private void show_word(string passwd) { for (int i = 0; i < passwd.Length; i++) { visible_password += "_"; passwd_holder += "_"; lbl_Passwd.Text += "_ "; } } private void check(KeyPressEventArgs key) { char[] password_lbl = lbl_Passwd.Text.ToCharArray(); char[] visible_inChar = visible_password.ToCharArray(); char[] holder_inChar = passwd_holder.ToCharArray(); char pressed_key = key.KeyChar; if (password.Contains(pressed_key)) { for (int i = 0; i < password.Length; i++) { if (password[i] == pressed_key) { visible_inChar[i] = pressed_key; string back = new string(visible_inChar); for (int j = 0; j < password.Length; j++) { if (visible_inChar[j] != '_' && holder_inChar[j] == '_') { holder_inChar[j] = visible_inChar[j]; } } passwd_holder = new string(holder_inChar); lbl_Passwd.Text = passwd_holder; } } } } private void final_test() { string temp; temp = lbl_Passwd.Text.ToString(); if (temp == password) { MessageBox.Show("WYGRAŁEŚ !!!"); Application.Exit(); } } private void Form1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar >= 97 && e.KeyChar <= 122) { MessageBox.Show("Wcisnąłeś klawisz: '" + e.KeyChar.ToString() + "' "); check(e); if (!password.Contains(e.KeyChar)) { tries--; MessageBox.Show(" Pozostało Ci: " + tries.ToString() + "prób"); if (tries == 0) { MessageBox.Show("Niestety, przegrałeś."); Application.Exit(); } } final_test(); } } } }
using System; using System.Linq; namespace PersonProject { public enum PersonState { Inghilterra,Italia,Spagna,Germania } public class Person { private string _name; private string _surname; public Person(int id, string name, string surname, DateTime dateOfBirth,PersonState nationality) { Id = id; Name = name; Surname = surname; DateOfBirth = dateOfBirth; Nationality = nationality; Speaking = GetSpeakingLanguage(nationality); } private ISpeaking GetSpeakingLanguage(PersonState nationality) { switch (nationality) { case PersonState.Inghilterra: return new EnglishSpeaking(); case PersonState.Italia: return new ItalianSpeaking(); case PersonState.Spagna: return new SpanishSpeaking(); case PersonState.Germania: return new GermanSpeaking(); default: throw new NotImplementedException(); } } public int Id { get; private set; } public string Name { get { return _name; } private set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Name must have a value"); if (value.Length > 35) throw new ArgumentException("Name cannot be longer than 35 characters"); if (value.Any(c => char.IsDigit(c))) throw new ArgumentException("Name cannot contain numbers"); _name = value; } } public string Surname { get { return _surname; } private set { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("Surname must have a value"); if (value.Length > 35) throw new ArgumentException("Surname cannot be longer than 35 characters"); if (value.Any(c => char.IsDigit(c))) throw new ArgumentException("Surname cannot contain numbers"); _surname = value; } } public DateTime DateOfBirth { get; private set; } public PersonState Nationality { get; set; } public ISpeaking Speaking { get; set; } public override string ToString() { return $"[{Id}] - {Name} {Surname} - DOB: {DateOfBirth.ToShortDateString()}"; } } }
using System.Collections.Generic; using UnityEngine; using HoloToolkit.Unity.InputModule; using Microsoft.Identity.Client; using System; using System.Threading.Tasks; using HoloToolkit.Unity; #if !UNITY_EDITOR && UNITY_WSA using System.Net.Http; using System.Net.Http.Headers; using Windows.Storage; #endif public class SignInScript : MonoBehaviour, ISpeechHandler { class AuthResult { public AuthenticationResult res; public string err; } IEnumerable<string> _scopes; PublicClientApplication _client; string _userId; TextMesh _welcomeText; TextMesh _statusText; async void Start() { #if !UNITY_EDITOR && UNITY_WSA ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings; Debug.Break(); _userId = localSettings.Values["UserId"] as string; #endif _scopes = new List<string>() { "User.Read", "Mail.Read" }; _client = new PublicClientApplication("e90a5e05-a177-468a-9f6e-eee32b946f86"); _welcomeText = transform.Find("WelcomeText").GetComponent<TextMesh>(); _statusText = transform.Find("StatusText").GetComponent<TextMesh>(); _statusText.text = "--- Not Signed In ---"; Debug.Log($"User ID: {_userId}"); if (string.IsNullOrEmpty(_userId)) { var tts = GetComponent<TextToSpeech>(); tts.StartSpeaking(_welcomeText.text); } else { _statusText.text = "Signing In..."; _welcomeText.text = ""; await SignInAsync(); } } private async Task<AuthResult> AcquireTokenAsync(IPublicClientApplication app, IEnumerable<string> scopes, string usrId) { var usr = !string.IsNullOrEmpty(usrId) ? app.GetUser(usrId) : null; var userStr = usr != null ? usr.Name : "null"; Debug.Log($"Found User {userStr}"); AuthResult res = new AuthResult(); try { Debug.Log($"Calling AcquireTokenSilentAsync"); res.res = await app.AcquireTokenSilentAsync(scopes, usr).ConfigureAwait(false); Debug.Log($"app.AcquireTokenSilentAsync called {res.res}"); } catch (MsalUiRequiredException) { Debug.Log($"Needs UI for Login"); try { res.res = await app.AcquireTokenAsync(scopes).ConfigureAwait(false); Debug.Log($"app.AcquireTokenAsync called {res.res}"); } catch (MsalException msalex) { res.err = $"Error Acquiring Token:{Environment.NewLine}{msalex}"; Debug.Log($"{res.err}"); return res; } } catch (Exception ex) { res.err = $"Error Acquiring Token Silently:{Environment.NewLine}{ex}"; Debug.Log($"{res.err}"); return res; } #if !UNITY_EDITOR && UNITY_WSA Debug.Log($"Access Token - {res.res.AccessToken}"); ApplicationData.Current.LocalSettings.Values["UserId"] = res.res.User.Identifier; #endif return res; } private async Task ListEmailAsync(string accessToken, Action<Value> success, Action<string> error) { #if !UNITY_EDITOR && UNITY_WSA var http = new HttpClient(); http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var response = await http.GetAsync("https://graph.microsoft.com/v1.0/me/messages?$top=5"); if (!response.IsSuccessStatusCode) { error(response.ReasonPhrase); return; } var respStr = await response.Content.ReadAsStringAsync(); Debug.Log(respStr); Rootobject email = null; try { // Parse the Json... email = JsonUtility.FromJson<Rootobject>(respStr); } catch (Exception ex) { Debug.Log($"Error = {ex.Message}"); return; } Debug.Log($"msg count = {email.value.Length}"); foreach (var msg in email.value) { success(msg); } #endif } private async Task SignInAsync() { var res = await AcquireTokenAsync(_client, _scopes, _userId); if (string.IsNullOrEmpty(res.err)) { _statusText.text = $"Signed in as {res.res.User.Name}"; await ListEmailAsync(res.res.AccessToken, t => { // put messages in a text ui element... _statusText.text += $"\nFrom: {t.from.emailAddress.address}\nSubject:{t.subject}"; }, t => { _statusText.text = $"{t}"; }); } else { _statusText.text = $"Error - {res.err}"; } } private void SignOut() { #if !UNITY_EDITOR && UNITY_WSA ApplicationData.Current.LocalSettings.Values["UserId"] = _userId = null; var usr = _client.GetUser(_userId); if (usr != null) { _client.Remove(usr); } #endif } public async void OnSpeechKeywordRecognized(SpeechEventData eventData) { if (eventData.RecognizedText == "sign in") { _statusText.text = "Signing In..."; _welcomeText.text = ""; await SignInAsync(); } if (eventData.RecognizedText == "sign out") { SignOut(); _statusText.text = "--- Not Signed In ---"; } } [Serializable] public class Rootobject { public string odatacontext; public string odatanextLink; public Value[] value; } [Serializable] public class Value { public string odataetag; public string id; public DateTime createdDateTime; public DateTime lastModifiedDateTime; public string changeKey; public object[] categories; public DateTime receivedDateTime; public DateTime sentDateTime; public bool hasAttachments; public string internetMessageId; public string subject; public string bodyPreview; public string importance; public string parentFolderId; public string conversationId; public object isDeliveryReceiptRequested; public bool isReadReceiptRequested; public bool isRead; public bool isDraft; public string webLink; public string inferenceClassification; public Body body; public Sender sender; public From from; public Torecipient[] toRecipients; public object[] ccRecipients; public object[] bccRecipients; public Replyto[] replyTo; } [Serializable] public class Body { public string contentType; public string content; } [Serializable] public class Sender { public Emailaddress emailAddress; } [Serializable] public class Emailaddress { public string name; public string address; } [Serializable] public class From { public Emailaddress1 emailAddress; } [Serializable] public class Emailaddress1 { public string name; public string address; } [Serializable] public class Torecipient { public Emailaddress2 emailAddress; } [Serializable] public class Emailaddress2 { public string name; public string address; } [Serializable] public class Replyto { public Emailaddress3 emailAddress; } [Serializable] public class Emailaddress3 { public string name; public string address; } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; namespace Svg2VectorDrawable { public class SvgGroupNode : SvgNode { const string INDENT_LEVEL = " "; List<SvgNode> children = new List<SvgNode>(); public SvgGroupNode(SvgTree svgTree, XmlNode docNode, string name) : base(svgTree, docNode, name) { } public void AddChild(SvgNode child) => children.Add(child); public override void DumpNode(string indent) { // Print the current group. // logger.log(Level.FINE, indent + "current group is :" + getName()); // Then print all the children. foreach (var node in children) { node.DumpNode(indent + INDENT_LEVEL); } } public override bool IsGroupNode => true; public override void Transform(float a, float b, float c, float d, float e, float f) { foreach (var p in children) p.Transform(a, b, c, d, e, f); } public override void WriteXml(StreamWriter writer) { foreach (var node in children) node.WriteXml(writer); } } }
using PopulationFitness.Models; using PopulationFitness.Simulation; namespace PopulationFitness { class Program { private const int DiseaseYears = 3; private const int PostDiseaseYears = 30; static void Main(string[] args) { Config config = new Config(); Epochs epochs = new Epochs(); Tuning tuning = new Tuning { Id = config.Id }; Commands.ConfigureTuningAndEpochsFromInputFiles(config, tuning, epochs, args); Simulations.SetInitialPopulationFromFirstEpochCapacity(config, epochs); Simulations.AddSimulatedEpochsToEndOfTunedEpochs(config, epochs, tuning, DiseaseYears, PostDiseaseYears); Simulations.RunAllInParallel(new SimulationThreadFactory(config, epochs, tuning), Commands.CacheType); } } }
 namespace RobotService.Models.Procedures { using RobotService.Models.Robots.Contracts; using System; public class Chip : Procedure { public override void DoService(IRobot robot, int procedureTime) { if (this.RobotHasEnoughTime(robot,procedureTime)) { if (robot.IsChipped) { throw new ArgumentException($"{robot.Name} is already chipped"); } robot.Happiness -= 5; robot.IsChipped = true; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations.Schema; namespace TwitterLikeApp.Entity { public class User { public int Id { get; set; } public string Username { get; set; } public string Password { get; set; } public DateTime DateCreated { get; set; } public int UserProfileId { get; set; } [ForeignKey("UserProfileId")] public virtual UserProfile Profile { get; set; } private ICollection<Ribbit> _ribbits; public virtual ICollection<Ribbit> Ribbits { get { return _ribbits ?? (_ribbits = new Collection<Ribbit>()); } set { _ribbits = value; } } private ICollection<User> _followings; public virtual ICollection<User> Followings { get { return _followings ?? (_followings = new Collection<User>()); } set { _followings = value; } } private ICollection<User> _followers; public virtual ICollection<User> Followers { get { return _followers ?? (_followers = new Collection<User>()); } set { _followers = value; } } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace GraphQL.Infra.Data.Migrations { public partial class Initial : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Author", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FirstName = table.Column<string>(nullable: true), LastName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Author", x => x.Id); }); migrationBuilder.CreateTable( name: "BlogPost", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Title = table.Column<string>(nullable: true), Content = table.Column<string>(nullable: true), AuthorId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_BlogPost", x => x.Id); table.ForeignKey( name: "FK_BlogPost_Author_AuthorId", column: x => x.AuthorId, principalTable: "Author", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Author", columns: new[] { "Id", "FirstName", "LastName" }, values: new object[] { 1, "Charles", "Mendes" }); migrationBuilder.InsertData( table: "Author", columns: new[] { "Id", "FirstName", "LastName" }, values: new object[] { 2, "Vitor", "Gorni" }); migrationBuilder.InsertData( table: "BlogPost", columns: new[] { "Id", "AuthorId", "Content", "Title" }, values: new object[,] { { 1, 1, "A maior banda do Mundo", "The Beatles" }, { 2, 1, "Tudo sobre o incrível universo dos bits", "O Codigo Binário" }, { 3, 2, "Como ser aprovado de primeira", "OAB Tributário" }, { 4, 2, "Vai fazer uma obra antes de casar?", "Obras a beira-mar" }, { 5, 2, "Saiba tudo e mais um pouco sobre games", "Xbox, PS4 e PC" } }); migrationBuilder.CreateIndex( name: "IX_BlogPost_AuthorId", table: "BlogPost", column: "AuthorId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "BlogPost"); migrationBuilder.DropTable( name: "Author"); } } }
using FluentValidation; using MediatR; using Microsoft.Extensions.DependencyInjection; using Order.Application.Behaviors; using Order.Application.Consumers; using System.Reflection; namespace Order.Application { public static class ApplicationServiceExtensions { public static void RegisterApplicationServices(this IServiceCollection services) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); services.AddMediatR(Assembly.GetExecutingAssembly()); services.AddScoped<BasketCheckoutConsumer>(); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(UnhandledExceptionBehavior<,>)); services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); } } }
using CSConsoleRL.Ai.Interfaces; using CSConsoleRL.Helpers; using CSConsoleRL.Entities; using CSConsoleRL.Events; using System.Collections.Generic; using SFML.System; using CSConsoleRL.Components; using GameTiles.Tiles; namespace CSConsoleRL.Ai.States { public class RangedAttack : IAiState { private readonly Entity _entity; private int _counter; private List<Vector2i> _path; public RangedAttack(Entity entity) { _entity = entity; _path = new List<Vector2i>(); } public string GetName() { return "MeleeSeek"; } public IGameEvent GetAiStateResponse(GameStateHelper gameStateHelper) { var map = gameStateHelper.GetVar<Tile[,]>("GameTiles"); var position = _entity.GetComponent<PositionComponent>(); var mainChar = gameStateHelper.GetVar<Entity>("MainEntity"); int horMovement = 0, verMovement = 0; int mainCharX = mainChar.GetComponent<PositionComponent>().ComponentXPositionOnMap; int mainCharY = mainChar.GetComponent<PositionComponent>().ComponentYPositionOnMap; //Call to A* Pathfinding to get path var path = PathfindingHelper.Instance.Path(map, new Vector2i(position.ComponentXPositionOnMap, position.ComponentYPositionOnMap), new Vector2i(mainCharX, mainCharY)); if (path != null) { if (path != null) _path = path; //if (_path[1] != null) seekerAi.AnalyzedPath = path[1]; // For debugging color in path and analyzed tiles // foreach (var tile in _path[1]) //{ // var fadingColorEnt = new FadingColorEntity("yellow"); // fadingColorEnt.GetComponent<PositionComponent>().ComponentXPositionOnMap = tile.X; // fadingColorEnt.GetComponent<PositionComponent>().ComponentYPositionOnMap = tile.Y; // SystemManager.RegisterEntity(fadingColorEnt); //} //foreach (var tile in path) //{ // var fadingColorEnt = new FadingColorEntity("green"); // fadingColorEnt.GetComponent<PositionComponent>().ComponentXPositionOnMap = tile.X; // fadingColorEnt.GetComponent<PositionComponent>().ComponentYPositionOnMap = tile.Y; // SystemManager.RegisterEntity(fadingColorEnt); //} } //Move to desired location if (position.ComponentXPositionOnMap < mainCharX) { horMovement++; } else if (position.ComponentXPositionOnMap > mainCharX) { horMovement--; } if (position.ComponentYPositionOnMap < mainCharY) { verMovement++; } else if (position.ComponentYPositionOnMap > mainCharY) { verMovement--; } return new MovementInputEvent(_entity.Id, horMovement, verMovement); } } }
using Meeting; using System; namespace Page.ShareWindow.Comment { public class MeetingShareParam { public string ClientId { get; set; } public string ServerIp { get; set; } public ClientVersion Version { get; set; } } }
using System.Linq; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.Rendering; using Microsoft.Data.Entity; using Stolons.Models; using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Hosting; using System.Security.Claims; using Stolons.ViewModels.WeekBasketManagement; namespace Stolons.Controllers { public class WeekBasketManagementController : Controller { private ApplicationDbContext _context; private readonly UserManager<ApplicationUser> _userManager; private IHostingEnvironment _environment; public WeekBasketManagementController(ApplicationDbContext context, UserManager<ApplicationUser> userManager, IHostingEnvironment environment) { _userManager = userManager; _environment = environment; _context = context; } // GET: Bills public IActionResult Index() { VmWeekBasketManagement vm = new VmWeekBasketManagement(); vm.ConsumerBills = _context.ConsumerBills.Include(x=>x.Consumer).Where(x => x.State == BillState.Pending).OrderBy(x=>x.Consumer.Id).ToList(); vm.ProducerBills = _context.ProducerBills.Include(x => x.Producer).Where(x => x.State != BillState.Paid).OrderBy(x => x.Producer.Id).ToList(); return View(vm); } // GET: UpdateConsumerBill public IActionResult UpdateConsumerBill(string billNumber) { IBill bill = _context.ConsumerBills.Include(x => x.Consumer).First(x => x.BillNumber == billNumber); bill.State = BillState.Paid; _context.Update(bill); _context.SaveChanges(); return RedirectToAction("Index"); } // GET: UpdateProducerBill public IActionResult UpdateProducerBill(string billNumber) { IBill bill = _context.ProducerBills.Include(x=>x.Producer).First(x => x.BillNumber == billNumber); bill.State++; _context.Update(bill); _context.SaveChanges(); return RedirectToAction("Index"); } private async Task<ApplicationUser> GetCurrentUserAsync() { return await _userManager.FindByIdAsync(HttpContext.User.GetUserId()); } } }
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 DSG东莞路测客户端 { public partial class FrmLonLatInputBox : Form { private Action<double, double> OnPoint; public FrmLonLatInputBox(Action<double, double> onPoint) { InitializeComponent(); this.OnPoint = onPoint; } private void FrmLonLatInputBox_Load(object sender, EventArgs e) { this.TopMost = true; button1.Click += Button1_Click; } private void Button1_Click(object sender, EventArgs e) { double.TryParse(txtLon.Text, out double lon); double.TryParse(txtLat.Text, out double lat); OnPoint?.Invoke(lon, lat); this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Anywhere2Go.DataAccess.Entity; using Anywhere2Go.DataAccess; using System.Collections; using log4net; using log4net.Config; using Anywhere2Go.DataAccess.Object; using Anywhere2Go.Library.Datatables; using Anywhere2Go.Library; using System.Globalization; using Anywhere2Go.Business.Utility; namespace Anywhere2Go.Business.Master { public class AnnouncementLogic { private static readonly ILog logger = LogManager.GetLogger(typeof(AnnouncementLogic )); MyContext _context = null; public AnnouncementLogic() { _context = new MyContext(); } public AnnouncementLogic(MyContext context) { _context = context; } public List<Announcement> GetAnnouncement(bool? isActive = null, DateTime? lastSyncedDateTime = null, bool checkExp = false, SortingCriteria sort = null, int id = 0) { var req = new Repository<Announcement>(_context); var query = req.GetQuery(); if (id != 0) { query = query.Where(t => t.Id == id); } if (isActive != null) { query = query.Where(t => t.IsActive == isActive); } if (lastSyncedDateTime != null) { query = query.Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value); } if (checkExp) { query = query.Where(x => (x.ExpireDate) > DateTime.Now); } return query.ToList(); } public APIAnnouncementList GetAnnouncementAPI(APIAnnouncementSearch searchModel,bool? isActive = null, DateTime? lastSyncedDateTime = null, bool checkExp = false, SortingCriteria sorting = null) { var res = new APIAnnouncementList(); var req = new Repository<Announcement>(_context); var query = req.GetQuery(); AccountProfileLogic accountLogic = new AccountProfileLogic(); AccountProfile account = new AccountProfile(); account = accountLogic.getAccountProfileById(searchModel.accId); try { if (sorting == null) { sorting = new SortingCriteria(); sorting.Add(new SortBy { Name = "DatetimeSend", Direction = SortDirection.DESC }); } res.this_page = searchModel.Page; res.page_size = searchModel.Size; if (searchModel.Page <= 1) { res.previous_page = 1; } else { res.previous_page = searchModel.Page - 1; } PagingCriteria page = new PagingCriteria { PageIndex = searchModel.Page - 1, PageSize = searchModel.Size }; if (isActive != null) { query = query.Where(t => t.IsActive == isActive); } if (lastSyncedDateTime != null) { query = query.Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value); } if (checkExp) { // ExpireDate hasvalue or ExpireDate is null query = query.Where(x => (x.ExpireDate) > DateTime.Now || x.ExpireDate == null); } query = query.Where(x => x.IsSend.Value); query = query.Where(x => (x.DatetimeSend) <= DateTime.Now); var exp = ExpressionBuilder.False<Announcement>(); /*case Send Company * case Send Dep * case Send All Company And Dep */ exp = exp.Or(t => (t.CompanyId == account.com_id && (string.IsNullOrEmpty(t.DepId)))); exp = exp.Or(t => (t.DepId.Contains(account.dev_id))); exp = exp.Or(t => (t.Topic == "news")); query= query.Where(exp); res.total_record = query.Count(); if ((searchModel.Size * searchModel.Page) > res.total_record) { res.next_page = searchModel.Page; } else { res.next_page = searchModel.Page + 1; } query = query.OrderBy(sorting).Page(page); res.Announcements = query.ToList(); } catch (Exception ex) { throw ex; } return res; } public Announcement GetAnnouncementById(int id) { var req = new Repository<Announcement>(_context); var query = req.GetQuery().Where(t => t.Id == id); return query.SingleOrDefault(); } public BaseResult<AnnouncementActionModel> SaveAnnouncement(Announcement obj, Authentication authen = null) { BaseResult<AnnouncementActionModel> res = new BaseResult<AnnouncementActionModel>(); string user = authen != null ? authen.first_name + " " + authen.last_name : ""; using (var con = _context.Database.BeginTransaction()) { try { var req = new Repository<Announcement>(_context); if (obj.Id == 0) // Insert data { obj.CreateBy = user; obj.CreateDate = DateTime.Now; obj.UpdateBy = user; obj.UpdateDate = DateTime.Now; req.Add(obj); var announcementList = GetAnnouncement(); var announcement = announcementList.Count() > 0 ? announcementList.Max(t => t.Id) : 0; obj.ContentUrl = Configurator.Host + "Announcement/AnnouncementNews/" + (announcement+1).ToString(); req.SaveChanges(); } else { var announcement = req.Find(t => t.Id == obj.Id).FirstOrDefault(); if (announcement != null) { announcement.ShortDesc = obj.ShortDesc; announcement.IsActive = obj.IsActive; announcement.AnnouncementTypeId = obj.AnnouncementTypeId; announcement.AppSend = obj.AppSend; // announcement.ContentUrl = obj.ContentUrl + obj.Id.ToString(); announcement.DatetimeSend = obj.DatetimeSend; announcement.DeviceType = obj.DeviceType; announcement.ExpireDate = obj.ExpireDate; announcement.GroupSendTo = obj.GroupSendTo; announcement.IsSend = obj.IsSend; announcement.Picture = obj.Picture; announcement.Title = obj.Title; announcement.UpdateDate = DateTime.Now; announcement.ContentHTML = obj.ContentHTML; if (!string.IsNullOrEmpty(user)) { announcement.UpdateBy = user; } announcement.CompanyId = obj.CompanyId; announcement.DepId = obj.DepId; announcement.Topic = obj.Topic; req.SaveChanges(); } } res.Result= new AnnouncementActionModel(); res.Result.Announcement = obj; res.Result.Success = true; con.Commit(); //if (obj.DatetimeSend <= DateTime.Now && (obj.IsActive.HasValue?obj.IsActive.Value:false) && (obj.IsSend.HasValue?!obj.IsSend.Value:false)) //{ // var response= PushAnnouncementById(obj.Id); //} } catch (Exception ex) { res.Result = null; res.Message = ex.Message; con.Rollback(); logger.Error(string.Format("Method = {0},User = {1}", "SaveAnnouncement", user), ex); } } return res; } public Func<Announcement, Object> GetAnnouncementByConditionOrder(DTParameters param) { Func<Announcement, Object> orderByFunc = null; if (param.SortOrder == "DatetimeSend") { orderByFunc = item => item.DatetimeSend; } else if (param.SortOrder == "ExpireDate") { orderByFunc = item => item.ExpireDate; } else if (param.SortOrder == "CreateDate") { orderByFunc = item => item.CreateDate; } return orderByFunc; } public DTResultAnnouncement<AnnouncementDataTables> GetAnnouncementByCondition(DTParameters param, Authentication auth) { var req = new Repository<Announcement>(_context); var query = req.GetQuery(); var exp = ExpressionBuilder.True<Announcement>(); var expCount = ExpressionBuilder.True<Announcement>(); List<String> columnFilters = new List<string>(); if (auth != null && auth.Role.roleId != Constant.Permission.SystemAdmin)// ถ้าไม่ใช่ system admin เห็นเฉพาะงานส่วนของบริษัท หรือ ตัวเอง { exp = exp.And(t => (t.CompanyId == auth.com_id)); } var startDate = param.GetSearchValueByColumnName("AnnouncementStartDate"); var endDate = param.GetSearchValueByColumnName("AnnouncementEndDate"); DateTime sDate = DateTime.Now; DateTime eDate = DateTime.Now; if (!string.IsNullOrEmpty(startDate) && !string.IsNullOrEmpty(endDate)) { sDate = DateTime.ParseExact(startDate, "dd/MM/yyyy", CultureInfo.CurrentCulture); eDate = DateTime.ParseExact(endDate + " 23:59", "dd/MM/yyyy HH:mm", CultureInfo.CurrentCulture); exp = exp.And(t => (t.CreateDate >= sDate && t.CreateDate <= eDate)); } else { sDate = DateTime.Now.AddDays(-30); eDate = DateTime.Now; exp = exp.And(t => (t.CreateDate >= sDate && t.CreateDate <= eDate) || !t.CreateDate.HasValue); } //count condition //expCount = exp; #region Dropdown Search var anouncementTypeId = param.GetSearchValueByColumnName("AnnouncementTypeId"); if (!string.IsNullOrEmpty(anouncementTypeId)) { exp = exp.And(p => p.AnnouncementTypeId == anouncementTypeId); } var appSend = param.GetSearchValueByColumnName("AppSend"); if (!string.IsNullOrEmpty(appSend)) { exp = exp.And(p => p.AppSend == appSend); } var deviceType = param.GetSearchValueByColumnName("DeviceType"); if (!string.IsNullOrEmpty(deviceType)) { exp = exp.And(p => p.DeviceType == deviceType); } var isActive = param.GetSearchValueByColumnName("IsActive"); if (!string.IsNullOrEmpty(isActive)) { if (isActive=="1") { exp = exp.And(p => p.IsActive == true); } else { exp = exp.And(p => p.IsActive == false); } } #endregion Dropdown Search if (param != null) { var exp2 = ExpressionBuilder.False<Announcement>(); //---> ค้นหา wordding exp2 = exp2.Or(p => (param.Search.Value == null)); //ถ้าไม่กรอกคำค้นหาให้แสดงทั้งหมด exp2 = exp2.Or(p => p.AnnouncementType != null && p.AnnouncementType.AnnouncementTypeName != null ? p.AnnouncementType.AnnouncementTypeName.ToLower().Contains(param.Search.Value.ToString().ToLower()) : false); //ค้นหา ประเภท exp2 = exp2.Or(p => p.AppSend.ToLower().Contains(param.Search.Value.ToString().ToLower())); //ค้นหา Applicatin exp2 = exp2.Or(p => p.ContentUrl.ToLower().Contains(param.Search.Value.ToString().ToLower())); //ค้นหา url exp2 = exp2.Or(p => p.DeviceType.ToLower().Contains(param.Search.Value.ToString().ToLower())); //ค้นหา Device exp2 = exp2.Or(p => p.Title.ToLower().Contains(param.Search.Value.ToString().ToLower())); //ค้นหาหัวข้อ exp = exp.And(exp2); } var obj = new ResultSet<Announcement>(); var orderByFunc = GetAnnouncementByConditionOrder(param); var dataList = obj.GetResultFuncOrderBy(param, query, exp, orderByFunc).Select((t, i) => new AnnouncementDataTables { Id = t.Id.ToString(), AnnouncementTypeId = t.AnnouncementTypeId, AnnouncementTypeName = t.AnnouncementType != null ? t.AnnouncementType.AnnouncementTypeName.CheckStringNull() : "", AppSend = t.AppSend != null ? t.AppSend : "ทั้งหมด", ContentUrl = t.ContentUrl.CheckStringNull(), DatetimeSend = t.DatetimeSend.HasValue ? t.DatetimeSend.Value.CheckStringNulltoString():"", DeviceType = t.DeviceType != null ? t.DeviceType : "ทั้งหมด", ExpireDate = t.ExpireDate.HasValue ? t.ExpireDate.Value.CheckStringNulltoString():"", IsActive = t.IsActive.HasValue && t.IsActive.Value ? "ใช้งาน" : "ไม่ใช้งาน", Title = t.Title.CheckStringNulltoString(), CreateDate = t.CreateDate.HasValue ? t.CreateDate.CheckStringNulltoString() :"", IsSend = t.IsSend.HasValue && t.IsSend.Value ? "ส่งแล้ว" : "ยังไม่ส่ง", }).ToList(); var allObj = query.Where(expCount); DTResultAnnouncement<AnnouncementDataTables> result = new DTResultAnnouncement<AnnouncementDataTables> { draw = param.Draw, data = dataList, recordsFiltered = obj.rowCount, recordsTotal = obj.rowCount, }; return result; } public List<AnnouncementType> GetAnnouncementType(bool? isActive = null, DateTime? lastSyncedDateTime = null) { var req = new Repository<AnnouncementType>(_context); var query = req.GetQuery(); if (isActive != null) { query = query.Where(t => t.IsActive == isActive); } if (lastSyncedDateTime != null) { query = query.Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value); } return query.ToList(); } public BaseResult<FCMPushNotification> PushAnnouncementById(int id,string device = "",bool isWeb=true) { var req = new Repository<Announcement>(_context); var res = new BaseResult<FCMPushNotification>(); var an = req.GetQuery().Where(t => t.Id == id).SingleOrDefault(); FCMNotification fcm = new FCMNotification(); res.Result = new FCMPushNotification(); var serverpush = Configurator.FireBaseServer; var devicePush = !string.IsNullOrEmpty(device)? "_" + device : ""; var topics = ""; if (an.DatetimeSend <= DateTime.Now && (an.IsActive.HasValue ? an.IsActive.Value : false)) { topics = an.Topic; if (!string.IsNullOrEmpty(an.DepId)) { var depArray = an.DepId.Split(','); if (depArray.Length > 3) //Maximum 3 Department per Request { for (int i = 0; i <= depArray.Length-1; i += 3) { var depString = ""; for (int j = 0; j <= 2; j++) { if (i + j <= depArray.Length - 1) { depString = depString + "'" + depArray[i + j] + devicePush + serverpush + "' in topics ||"; } } depString = depString.TrimEnd('|').TrimEnd('|').Trim(); an.Topic = depString; res.Result = fcm.SendNotificationTopic(an, FCMNotification.EPushType.News, device, true); } } else { var depString = ""; for (int i = 0; i <= depArray.Length - 1; i++) { depString += "'" + depArray[i] + devicePush + serverpush + "' in topics ||"; } depString = depString.TrimEnd('|').TrimEnd('|').Trim(); an.Topic = depString; res.Result = fcm.SendNotificationTopic(an, FCMNotification.EPushType.News, device, true); } } // Send single topic else { an.Topic = an.Topic + devicePush + serverpush; res.Result = fcm.SendNotificationTopic(an, FCMNotification.EPushType.News, device, false); } if (res.Result.Successful) { try { res.Result.Id = id.ToString(); an.IsSend = true; an.UpdateDate = DateTime.Now; an.Topic = topics; Authentication authen = new Authentication(); if (!isWeb) { authen.first_name = "system"; } SaveAnnouncement(an,authen); } catch (Exception ex) { res.Result = null; res.Message = ex.Message; logger.Error(string.Format("Method = {0}", "PushAnnouncementById"), ex); } } } return res; } public class AnnouncementActionModel { public bool Success { get; set; } public Announcement Announcement { get; set; } public bool IsSendPush { get; set; } public int TotalAssign { get; set; } public Anywhere2Go.Business.Utility.PushNotification.EPushType PushType { get; set; } } public List<Announcement> GetAnnouncementActiveAPI(APIAnnouncementSearch searchModel, bool? isActive = null, DateTime? lastSyncedDateTime = null, bool checkExp = false, SortingCriteria sorting = null) { var res = new List<Announcement>(); var req = new Repository<Announcement>(_context); var query = req.GetQuery(); AccountProfileLogic accountLogic = new AccountProfileLogic(); AccountProfile account = new AccountProfile(); account = accountLogic.getAccountProfileById(searchModel.accId); try { if (sorting == null) { sorting = new SortingCriteria(); sorting.Add(new SortBy { Name = "DatetimeSend", Direction = SortDirection.DESC }); } if (isActive != null) { query = query.Where(t => t.IsActive == isActive); } if (lastSyncedDateTime != null) { query = query.Where(x => (x.UpdateDate ?? x.CreateDate) > lastSyncedDateTime.Value); } if (checkExp) { // ExpireDate hasvalue or ExpireDate is null query = query.Where(x => (x.ExpireDate) > DateTime.Now || x.ExpireDate == null); } query = query.Where(x => x.IsSend.Value); query = query.Where(x => (x.DatetimeSend) <= DateTime.Now); var exp = ExpressionBuilder.False<Announcement>(); /*case Send Company * case Send Dep * case Send All Company And Dep */ exp = exp.Or(t => (t.CompanyId == account.com_id && (string.IsNullOrEmpty(t.DepId)))); exp = exp.Or(t => (t.DepId.Contains(account.dev_id))); exp = exp.Or(t => (t.Topic == "news")); query = query.Where(exp); query = query.OrderBy(sorting); res = query.ToList(); } catch (Exception ex) { throw ex; } return res; } } }
using MinistryPlatform.Translation.Models.DTO; using SignInCheckIn.Models.DTO; using System.Collections.Generic; namespace SignInCheckIn.Services.Interfaces { public interface IRoomService { List<EventRoomDto> GetLocationRoomsByEventId(int eventId); EventRoomDto CreateOrUpdateEventRoom(EventRoomDto eventRoom); EventRoomDto GetEventRoomAgesAndGrades(int eventId, int roomId); EventRoomDto UpdateEventRoomAgesAndGrades(int eventId, int roomId, EventRoomDto eventRoom); List<EventRoomDto> GetAvailableRooms(int roomId, int eventId); List<EventRoomDto> UpdateAvailableRooms(int roomId, int locationId, List<EventRoomDto> eventRoomDtos); List<AgeGradeDto> GetGradeAttributes(string authenticationToken, int siteId, string kioskId, int? eventId = null); List<MpGroupDto> GetEventUnassignedGroups(int eventId); EventRoomDto CreateOrUpdateAdventureClubRoom(string authenticationToken, EventRoomDto eventRoom); EventRoomDto GetEventRoom(int eventId, int roomId); EventRoomDto GetEventRoom(int eventId, int roomId, bool canCreateEventRoom); } }
using LitJson; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class GameRoot : MonoBehaviour { public static GameRoot instance; public PlayerModel playerModel; private void Awake() { instance = this; } //# // Start is called before the first frame update void Start() { DontDestroyOnLoad(this.gameObject); InitJsonLoader(); try { PlayerModelController.GetInstance().Init(); } catch { PlayerModelController.GetInstance().Init(); Invoke("T1", 0.1f); } //EQPLIST(); foreach (var item in instance.playerModel.CharaInfoDic) { Debug.Log(item.Key + item.Value.name + "!!!"); } } void T1() { PlayerModelController.GetInstance().Init(); } private void EQPLIST() { foreach (var item in GameConfig.GetInstance().GameConfig_equipmentList) { Debug.Log(": " + item.id + " : " + item.name +"v "+ item.upgrade_gold); } var temp2 = GameRoot.instance.playerModel.equipmentList.Find(t => t.id == 10003); //Debug.Log(temp2.id); //throw new NotImplementedException(); } private void Test2() { foreach (var item in GameConfig.GetInstance().GameConfig_fruitList) { Debug.Log(item.fruit_name + " :"+item.fruit_level.ToString() + " :" + item.fruit_size); } //throw new NotImplementedException(); } private void InitJsonLoader() { //Debug.Log("1"); JsonLoadSvc.GetInstance().Init(); } private void Update() { //if (Input.GetMouseButtonDown(0)) //{ // SoundClick(); //} if (Input.GetKeyDown(KeyCode.T)) { var tempList = PlayerModelController.GetInstance().GetLogList(1); Debug.Log("--------------------1-------------------"); foreach (var item in tempList) { Debug.Log("ID:1" + item.Info); } var tempList2 = PlayerModelController.GetInstance().GetLogList(2); Debug.Log("--------------------2-------------------"); foreach (var item in tempList2) { Debug.Log("ID:2" + item.Info); } } if (Input.GetKeyDown(KeyCode.K)) { LogSvc.GetInstance().WriteToDIsk(); } if (Input.GetKeyDown(KeyCode.C)) { CoinChangeSvc.GetInstance().Show(0); Debug.Log(GameRoot.instance.playerModel.Coin); } if (Input.GetKeyDown(KeyCode.A)) { PlayerModelController.GetInstance().GetCoin(10); //CoinChangeSvc.GetInstance().Show(10); Debug.Log(GameRoot.instance.playerModel.Coin); } if (Input.GetKeyDown(KeyCode.B)) { foreach (var item in instance.playerModel.equipmentList) { Debug.Log(item.level+" "+item.atk); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ScoreText : MonoBehaviour { public TextMesh text; public void SetScore(int score){ string scoreText = "Score: " + score; text.text = scoreText; } }