text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; using Rastreador.Helpers; namespace Rastreador { // Note: For instructions on enabling IIS6 or IIS7 classic mode, // visit http://go.microsoft.com/?LinkId=9394801 public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } protected void Application_Start() { #region seta o Jobde Atualização de encomendas para rodar de 1 em 1 minuto //// construct a scheduler factory //ISchedulerFactory schedFact = new StdSchedulerFactory(); //// get a scheduler //IScheduler sched = schedFact.GetScheduler(); //sched.Start(); //// construct job info //IJobDetail jobDetail = JobBuilder.Create(typeof(AtualizaEncomendasJob)) //.WithIdentity("myJob", "group1") //.Build(); //ITrigger trigger = TriggerBuilder.Create() //.WithIdentity("trigger3", "group1") //.WithCronSchedule("0 0/1 * * * ?") //.ForJob("myJob", "group1") //.Build(); //sched.ScheduleJob(jobDetail, trigger); #endregion AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); } } }
using PatientJournalApplication.Models; using PatientJournalClassLib; using PatientJournalClassLib.Models; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Navigation; namespace PatientJournalApplication.Pages { /// <summary> /// Interaction logic for PagePatientList.xaml /// </summary> public partial class PagePatientList : Page { public PagePatientList(ViewModelPatientList vm) { InitializeComponent(); if (!vm.toggle) { LVPatients.ItemsSource = vm.ListOfActivePatients; } else { LVPatients.ItemsSource = vm.ListOfAllPatients; } } private void BtnCreatePatient_Click(object sender, RoutedEventArgs e) { PageCreatePatient pcp = new PageCreatePatient(); NavigationService.Navigate(pcp); } private void BtnShow_Click(object sender, RoutedEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is ListViewItem)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) return; Patient patient = (Patient)LVPatients.ItemContainerGenerator.ItemFromContainer(dep); PagePatient pp = new PagePatient(DbGet.GetPatient(patient.Id)); NavigationService.Navigate(pp); } private void BtnDelete_Click(object sender, RoutedEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is ListViewItem)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) return; Patient patient = (Patient)LVPatients.ItemContainerGenerator.ItemFromContainer(dep); patient.DeletePatient(patient); ViewModelPatientList vm = new ViewModelPatientList(); PagePatientList ppl = new PagePatientList(vm); NavigationService.Navigate(ppl); } private void ChkBxToggle_Checked(object sender, RoutedEventArgs e) { if ((bool)ChkBxToggle.IsChecked) LVPatients.ItemsSource = DbGet.GetPatientList(true); else LVPatients.ItemsSource = DbGet.GetPatientList(false); } private void TBArchive_Checked(object sender, RoutedEventArgs e) { DependencyObject dep = (DependencyObject)e.OriginalSource; while ((dep != null) && !(dep is ListViewItem)) { dep = VisualTreeHelper.GetParent(dep); } if (dep == null) return; Patient patient = (Patient)LVPatients.ItemContainerGenerator.ItemFromContainer(dep); patient.SetArchived(patient); ViewModelPatientList vm = new ViewModelPatientList(); PagePatientList ppl = new PagePatientList(vm); NavigationService.Navigate(ppl); } } }
using System.Collections.Generic; namespace Lfs.Calculator.Models { /// <summary> /// Описывает фигуры которыми может быть покрыта карта. /// </summary> public class Figure { public int BaseX { get; } public int BaseY { get; } public int SideX { get; } public int SideY { get; } public int Square => SideX * SideY; public List<Point> Coords = new List<Point>(); public Figure(bool[,][] map, int baseX, int baseY, int sideX, int sideY) { BaseX = baseX; BaseY = baseY; SideX = sideX; SideY = sideY; var mapSideX = map.GetLength(0); var mapSideY = map.GetLength(1); var tempSideX = sideX; var addSideX = 0; if (baseX + sideX > mapSideX) { tempSideX = mapSideX - baseX; addSideX = baseX + sideX - mapSideX; } var tempSideY = sideY; var addSideY = 0; if (baseY + sideY > mapSideY) { tempSideY = mapSideY - baseY; addSideY = baseY + sideY - mapSideY; } // Добавляем точки не выходящие ни за какие границы. for (int i = baseX; i < baseX + tempSideX; ++i) { for (int j = baseY; j < baseY + tempSideY; ++j) { Coords.Add(new Point { X = i, Y = j }); } } // Добавляем точки выходящие за границу справа. for (int i = baseX; i < baseX + tempSideX; ++i) { for (int j = 0; j < addSideY; ++j) { Coords.Add(new Point { X = i, Y = j }); } } // Добавляем точки выходящие за границу снизу. for (int i = baseY; i < baseY + tempSideY; ++i) { for (int j = 0; j < addSideX; ++j) { Coords.Add(new Point { X = j, Y = i }); } } // Добавляем точки выходящие за границу в уголке. for (int i = 0; i < addSideX; ++i) { for (int j = 0; j < addSideY; ++j) { Coords.Add(new Point { X = i, Y = j }); } } } /// <summary> /// Проверяет, является ли фигура логической компонентой. /// </summary> /// <param name="map">Рабочая карта (4 соединеные вместе)</param> /// <param name="resolve">Образец для сравнения (МДНФ или МКНФ)</param> /// <param name="baseX"></param> /// <param name="baseY"></param> /// <param name="sideX"></param> /// <param name="sideY"></param> /// <returns></returns> public static bool Check(bool[,] map, bool resolve, int baseX, int baseY, int sideX, int sideY) { for (int i = baseX; i < baseX + sideX; ++i) { for (int j = baseY; j < baseY + sideY; ++j) { if (resolve != map[i, j]) { return false; } } } return true; } } }
using System; namespace Feilbrot.Graphics { public struct ComplexPoint2d { public decimal r; public decimal i; public ComplexPoint2d(decimal r=0, decimal i=0) { this.r = r; this.i = i; } public override string ToString() { return $"ComplexPoint2d#(r: {r}, i: {i})"; } } }
using FLS.Business; using FuelSupervisorSetting.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FuelSupervisorSetting.ViewModel { public class InterpolationTabUIObjects : ObservableCollection<InterpolationTabUIObject> { protected override void InsertItem(int index, InterpolationTabUIObject item) { base.InsertItem(index, item); // handle any EndEdit events relating to this item item.ItemEndEdit += new ItemEndEditEventHandler(ItemEndEditHandler); } void ItemEndEditHandler(IEditableObject sender) { // simply forward any EndEdit events if (ItemEndEdit != null) { ItemEndEdit(sender); } } #region events public event ItemEndEditEventHandler ItemEndEdit; #endregion } public delegate void ItemEndEditEventHandler(IEditableObject sender); public class InterpolationTabUIObject : IEditableObject, INotifyPropertyChanged { private InterpolationRecord _Interpolation; public InterpolationTabUIObject() { _Interpolation = new InterpolationRecord(); } public InterpolationTabUIObject(InterpolationRecord interpolation) { _Interpolation = interpolation; } public InterpolationRecord GetDataObject() { return _Interpolation; } public UInt64 PK { get { return _Interpolation.PK;} set { _Interpolation.PK = value; RaisePropertyChanged("PK"); } } public long TankId { get { return _Interpolation.TankId; } set { _Interpolation.TankId = value; RaisePropertyChanged("TankId"); } } public Double Level { get { return _Interpolation.Level; } set { _Interpolation.Level = value; RaisePropertyChanged("Level"); } } public Double Capacity { get { return _Interpolation.Capacity; } set { _Interpolation.Capacity = value; RaisePropertyChanged("Capacity"); } } #region events public event ItemEndEditEventHandler ItemEndEdit; #endregion #region IEditableObject Members public void BeginEdit() { } public void CancelEdit() { } public void EndEdit() { if (ItemEndEdit != null) { ItemEndEdit(this); } } #endregion #region INotifyPropertyChanged Members public event PropertyChangedEventHandler PropertyChanged; private void RaisePropertyChanged(string property) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(property)); } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace poiLoader { class Item { public bool hasname(string name) { if (this.name.Contains(name)) { return true; } else { return false; } } public bool hasreforge(string name) { if (masterstring.Contains(name)) { return true; } else { return false; } } public string masterstring { get; set; } //all items WILL have these public int classid { get; set; } public string pocket { get; set; } public string name { get; set; } public int xpos { get; set; } public int ypos { get; set; } public string[] colour { get; set; } //equips will have these public int currentdura { get; set; } public int maxdura { get; set; } public bool ishammered { get; set; } public int proficiency { get; set; } public int upgrades { get; set; } //amour will have these public int defense { get; set; } public int protection { get; set; } //weapons will have these public int minattack { get; set; } public int maxattack { get; set; } public int balance { get; set; } public int critical { get; set; } //magic public int magicattack { get; set; } //weapons may have these public int range { get; set; } //extra flags for gear public int reforgelevel { get; set; } public string[] reforges { get; set; } public int tradesremaining { get; set; } //extra flags public int lifeadded { get; set; } public int manaadded { get; set; } public int staminaadded { get; set; } public int strengthadded { get; set; } public int intelligenceadded { get; set; } public int dexterityadded { get; set; } public int willadded { get; set; } public int luckadded { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /* * This class inherits GhostAgent and is used to train the search behavior in the agent. * At inference runtime (when we're going to play the game with a trained ghost), we won't * Be using this class. Instead we'll be infering from the GhostAgent class, and switching * between a search model and a combat (shooting) model there. * * To train the search behavior, drag this class into GhostAgent object's GhostAgent Script field. * Then in powershell run: mlagents-learn .\Assets\search_config.yaml --run-id=search-curriculum * */ public class SearchAgent : GhostAgent { private float searchDistance = 10f; private int maxStepCount = 300000; private int stepCount = 0; public override void Shoot() { // don't shoot when searching } public override void OnEpisodeBegin() { base.OnEpisodeBegin(); this.player.transform.localPosition = new Vector3(Random.Range(this.minX, this.maxX), 0.5f, Random.Range(this.minZ, this.maxZ)); stepCount = 0; this.searchDistance = this.envParams.GetWithDefault("search_distance", 1f); this.player.SetSpeed(0f); } public override void CheckEpisodeEnd() { base.CheckEpisodeEnd(); stepCount++; if (stepCount > maxStepCount) { // Debug.Log("timeout"); FinalizeReward(false); EndEpisode(); } float distance = Vector3.Distance(this.transform.localPosition, this.player.transform.localPosition); if (distance < searchDistance) { this.reward += 1f; FinalizeReward(true); EndEpisode(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI_nodeItem : MonoBehaviour { NodeSystem.Node node; [SerializeField] Text IDText; [SerializeField] Text CoordText; [SerializeField] pickingHandler spawnhandler; int id = 0; public void Clicked() { spawnhandler.SetSelectedNode(node); } public NodeSystem.Node Node { get { return node; } set { node = value; } } public int ID { get { return id; } set { id = value; } } public void UpdateUI() { IDText.text = "ID: " + id; if (node != null) { CoordText.text = "x: " + node.X + ", y: " + node.Y + ", z: " + node.Z; } else { CoordText.text = "no assigned node"; } } float nextUpdate = 0; // Start is called before the first frame update void Start() { spawnhandler = GameObject.FindGameObjectWithTag("spawner").GetComponent<pickingHandler>(); } // Update is called once per frame void Update() { nextUpdate -= Time.deltaTime; if(nextUpdate <= 0) { UpdateUI(); nextUpdate = 2; } } }
using ElosztottLabor.Data; using ElosztottLabor.Interfaces; using ElosztottLabor.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ElosztottLabor.Services { public class QuestionFormService : IQuestionFormService { private readonly HEMDbContext _context; // Consturctor of the service, called by the framework. Notice that the argument // list is populated in runtime by the Dependency Injection (DI) solution. public QuestionFormService(HEMDbContext context) { this._context = context; var existing = _context.QuestionForms.Find(1L); if (existing == null) { // Add some mock data _context.QuestionForms.Add(new QuestionForm { Id = 1, Name = "Mock Question Form", Active = true, Questions = new List<Question>() { new MultipleChoiceQuestion() { QuestionText = "Melyik a kedvenc tanszéked?", PossibleAnswers = new List<string>() { "AUT", "Az automatizálási", "Az Androidos" } } } }); _context.SaveChanges(); } } public QuestionForm SaveQuestionForm(QuestionForm questionForm) { // If there is already a question form with this Id, thrown an exception if (QuestionFormExistsById(questionForm.Id)) { throw new QuestionFormExistsException(); } // Register the new question form as an entity tracekd by EF var result = _context.QuestionForms.Add(questionForm); // Save to database _context.SaveChanges(); return result.Entity; } public void UpdateQuestionForm(long id, QuestionForm questionForm) { // If there are no question form with the id throw an expcetion if (!QuestionFormExistsById(id)) { throw new QuestionFormDoesntExistsException(); } var existing = _context .QuestionForms .Include(qf => qf.Questions) .SingleOrDefault(qf => qf.Id == id); // Remove the old questions foreach (var question in existing.Questions.ToList()) { _context.Questions.Remove(question); } // Save the new date existing.Name = questionForm.Name; existing.Active = questionForm.Active; existing.Questions = questionForm.Questions; _context.SaveChanges(); } public IEnumerable<QuestionForm> GetQuestionForms() { return _context .QuestionForms .Include(qf => qf.Questions) .ToList(); } public QuestionForm GetQuestionForm(long id) { return _context .QuestionForms .Include(qf => qf.Questions) .SingleOrDefault(qf => qf.Id == id); } public void DeleteQuestionForm(long id) { var questionForm = _context .QuestionForms .Find(id); if (questionForm != null) { _context.Remove(questionForm); _context.SaveChanges(); } } public bool QuestionFormExistsById(long id) { return _context .QuestionForms .Any(qf => qf.Id == id); } } }
using Microsoft.AspNetCore.Mvc; namespace tools.Controllers { public class IndexController : Controller { // GET [HttpGet] [Route("api/v1/Index")] public string Index() { return "Tools were free to every one,you can use it freely and freely!"; } } }
using System; using System.Linq; namespace Find_the_smallest_integer_in_the_array { class Program { public static int FindSmallestInt(int[] args) => args.Min(); } }
namespace catalog.merger.api.Features.CatalogMerger.Models { public class CatalogItemDto { public string SKU { get; set; } public string Description { get; set; } public string Source { get; set; } } }
using System; namespace ShCore.Types { /// <summary> /// Type code do Sơn định nghĩa /// </summary> [Flags] public enum ShTypeCode { [ShTypeCodeOf(typeof(int))] Int32, [ShTypeCodeOf(typeof(long))] Int64, [ShTypeCodeOf(typeof(string))] String, [ShTypeCodeOf(typeof(decimal))] Decimal, [ShTypeCodeOf(typeof(bool))] Boolean, [ShTypeCodeOf(typeof(DateTime))] DateTime, [ShTypeCodeOf(typeof(byte))] Byte, [ShTypeCodeOf(typeof(double))] Double, [ShTypeCodeOf(typeof(Guid))] Guid, [ShTypeCodeOf(typeof(short))] Int16, [ShTypeCodeOf(typeof(float))] Single, [ShTypeCodeOf(typeof(DBNull))] DBNull, UnKnown } /// <summary> /// Mở rộng phương thức cho ShTypeCode /// </summary> public static class ShTypeCodeExtender { /// <summary> /// Kiểm tra xem Type Code có hợp lệ, có nằm trong list Type Code cần check /// </summary> /// <param name="typeCode"></param> /// <param name="typeCodeChecking"></param> /// <returns></returns> public static bool IsSet(this ShTypeCode typeCode, ShTypeCode typeCodeChecking) { return (typeCode & typeCodeChecking) == typeCodeChecking; } } }
using System.Text; using System; using System.Collections.Generic; using Newtonsoft.Json.Converters; using Newtonsoft.Json; using System.Net.Http; using System.Drawing; using System.Collections.ObjectModel; using System.Xml; using System.ComponentModel; using System.Reflection; namespace LinnworksAPI { public class ApplicationProfileResponse { public String PlanTag; public String PlanName; public DateTime ActivationDate; public DateTime LastPaymentDate; public DateTime NextPaymentDate; public DateTime ProfileExpires; public Boolean IsProfileActive; } }
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Ayende.NHibernateQueryAnalyzer.Core.Model; using Ayende.NHibernateQueryAnalyzer.UserInterface.Commands; using Ayende.NHibernateQueryAnalyzer.UserInterface.Interfaces; namespace Ayende.NHibernateQueryAnalyzer.UserInterface.Presenters { public class ProjectPresenter : IProjectPresenter { private readonly IMainPresenter mainPresenter; private readonly Project prj; private IProjectView view; public ProjectPresenter(Project prj, IMainPresenter mainPresenter) { this.mainPresenter = mainPresenter; this.prj = prj; this.view = CreateView(mainPresenter); } protected virtual IProjectView CreateView(IMainPresenter mainPresenter) { return new ProjectView(this,mainPresenter.View); } public void BuildProject() { ICommand buildProject = new BuildProjectCommand(view, prj, mainPresenter.Repository); mainPresenter.EnqueueCommand(buildProject); view.DisplayProjectState(false, false); view.StartWait("Building project..", 5, 1000); } public void EditProject() { if (!mainPresenter.CloseProjectChildren()) return; prj.ResetProject(); view.DisplayProjectState(true, false); } public bool SaveProjectAs() { string name = view.Title; string newName = view.Ask("Project name:", name); if (newName != null) { Project existingProject = mainPresenter.Repository.GetProjectByName(newName); if (existingProject != null) { if (view.AskYesNo("A project with the name '" + newName + "' already exists, are you sure you want to overwrite it?", "Overwrite project?")) mainPresenter.Repository.RemoveProject(existingProject); else return false; } view.Title = newName; view.HasChanges = false; prj.Name = newName; mainPresenter.Repository.SaveProject(prj); return true; } return false; } public void ProjectViewDisposed() { prj.Dispose(); mainPresenter.Repository.RemoveFromCache(prj); } public Project Project { get { return prj; } } public bool SaveProject() { if(prj.Id==0) return SaveProjectAs(); mainPresenter.Repository.SaveProject(prj); view.HasChanges = false; return true; } public IProjectView View { get { return view; } } } }
 namespace DoE.Quota.Repositories.Data.Order { using EF; using Api; using Models; using Core.Logger.Api; using Core.Repositories.Data; public class OrderRepository : Repository<Order>, IOrdersRepository { public OrderRepository() {} // /* --> Pools a list of orders per grade per bookyear from the vw_rqLimp_OrderItems view and re-populate the results into the OrderPerGradeDashboardApp app which then return an IEnumerable list of ... */ //public IEnumerable<vw_Inventory> GetOrdersPerGradePerBookYear(int emisCode, int grade, string bookYear) //{ // return OrderDbContext.vw_Inventory // .Where(c => (c.EmisCode == emisCode) && (c.Grade == grade) && (c.BookYear.Equals(bookYear))) // .OrderBy( c => c.BookYear); //} //public IQueryable<vw_Inventory> GetOrdersPerGradePerBookYearQueryable(int emisCode, int grade, string bookYear) //{ // //return OrderSchema.LsmRequisitionItems // // .Where(c => (c.Emis_Code == emisCode) && (c.Grade == grade) && (c.Bookyear.Equals(bookYear))) // // .OrderBy(c => c.Grade); // return OrderDbContext.vw_Inventory // .Where(c => (c.EmisCode == emisCode) && (c.Grade == grade) && (c.BookYear.Equals(bookYear))) // .OrderBy(c => c.BookYear); //} //public IEnumerable<InventoryList> GetOrderList(string reqID, string bookYear, int emisCode) //{ // //add requisition validation // var orderItemsQuery = OrderDbContext.Inventories // .Where(c => (c.EmisCode == emisCode) && (c.BookYear.Equals(bookYear))) // .OrderBy(c => c.BookYear); // foreach (var e in orderItemsQuery) // { // yield return e; // } //} //public decimal RequisitionTotalPrice(string reqID) //{ // try // { // var requisition = OrderDbContext.req_vwRequisitionTotalPrice // .Where(c => c.ReqId.Equals(reqID)) // .SingleOrDefault(); // return requisition.TotalPrice ?? 0.0M ; // } // catch // { // return 0.0M; // } //} } }
using System; namespace SharpILMixins.Processor.Utils { public class MixinApplyException : InvalidOperationException { public MixinApplyException(string? message) : base(message) { } public MixinApplyException(string? message, Exception? innerException) : base(message, innerException) { } } }
using System; using System.Linq; using System.Collections.Generic; using NGrams.Profiles; using NGrams.DistanceCalculation; using System.Diagnostics; namespace NGrams { /// <summary> /// Синтаксис Ngrams [--option=<csv> ...] --target=<fileName> files ... /// Опции: /// --criteries - критерии(Ngram, WordLength), /// --distances - ф-ии расстояния(E,M,KS,NN,WH) /// </summary> class MainClass { public static void Main(string[] args){ string targetName; if (GetTargetName(args, out targetName)) { var distances = GetDistances(args); if (!distances.Any()){ distances = new HashSet<string>{"E"}; // по умолчанию - Евклидово расстояние } var criteries = GetCriteries(args); if (!criteries.Any()){ criteries = new HashSet<string>{"NGram"}; // по умолчанию - критерий Nграм } foreach(var criteria in criteries) { switch(criteria) { case "NGram": Console.WriteLine("Определение по Nграмам."); ProfileTest<NgramProfile, string>(args, distances, targetName); break; case "WordLength": Console.WriteLine("Определение по длине слов."); ProfileTest<WordLengthProfile, int>(args, distances, targetName); break; } } } else { Console.WriteLine("Укажите неизвестный текст параметром --target=<имя>"); } } private static bool GetTargetName(string[] consoleArgs, out string target) { string paramName="--target="; target = consoleArgs.FirstOrDefault(x => x.StartsWith(paramName)); if (target == default(string)) { return false; } target = target.Substring(paramName.Length); return true; } private static ISet<string> GetDistances(string[] consoleArgs) { string paramName="--distances="; var result = new HashSet<string>(); string distanceString = consoleArgs.FirstOrDefault(x=> x.StartsWith(paramName)); if (distanceString!=default(string)) { var distances = distanceString.Substring(paramName.Length).Split(','); foreach(var d in distances) { result.Add(d); } } return result; } private static ISet<string> GetCriteries(string[] consoleArgs) { string paramName="--criteries="; var result = new HashSet<string>(); string distanceString = consoleArgs.FirstOrDefault(x=> x.StartsWith(paramName)); if (distanceString!=default(string)) { var distances = distanceString.Substring(paramName.Length).Split(','); foreach(var d in distances) { result.Add(d); } } return result; } private static void ProfileTest<TProfile, TCriteria>(string[] args, ISet<string> distances, string targetFileName) where TProfile : class, IProfile<TCriteria> { var profiles = new Dictionary<string, TProfile>(); TProfile unknownText = null; foreach (string arg in args) { if (!arg.StartsWith("--")) // игнорим параметры { string fileName = extendHome(arg); Debug.WriteLine(fileName); var newProfile = ProfileFactory.GetProfile<TProfile, TCriteria>(fileName); newProfile.AddFile(fileName); profiles.Add(fileName, newProfile); } } unknownText = ProfileFactory.GetProfile<TProfile, TCriteria>("unknown"); unknownText.AddFile(targetFileName); TProfile normalProfile = ProfileFactory.GetProfile<TProfile, TCriteria>("normal"); foreach (var profile in profiles) { normalProfile.AddFile(profile.Key); } var others = profiles.Select(x => x.Value).ToArray(); foreach(var distance in distances) { switch(distance){ case "E": Print<TCriteria,EuclideanDistance>("Евклид",unknownText,others); break; case "M": Print<TCriteria,MatusitaDistance>("Матусита",unknownText,others); break; case "KS": Print<TCriteria,KolmogorovSmirnovDistance>("Колмогоров-Смирнов",unknownText,others); break; case "WH": Print<TCriteria,WaveHedgesDistance>("Wavehedges",unknownText,others); break; case "NN": Print<TCriteria,NonNormalizedDistance>("Ненормализ.",unknownText,others); break; } } } private static void Print<TCriteria, TDistance>(string distanceName, IProfile<TCriteria> unknown, IEnumerable<IProfile<TCriteria>> others) where TDistance:IDistance,new() { Console.WriteLine( "прошло {0} секунд", MeasureAction(() => PrintDistances(distanceName, DistanceCalculator.GetRelativeDistances<TCriteria, TDistance>, unknown, others))); } private static TimeSpan MeasureAction(Action action) { Stopwatch watch = new Stopwatch(); watch.Start(); action(); watch.Stop(); return watch.Elapsed; } private static void PrintDistances<TCriteria>( string distanceName, Func<IProfile<TCriteria>, IEnumerable<IProfile<TCriteria>>, IDictionary<IProfile<TCriteria>, double>> distanceFunc, IProfile<TCriteria> p1, IEnumerable<IProfile<TCriteria>> p2) { Console.WriteLine(distanceName); var d = distanceFunc(p1,p2).OrderByDescending(x => x.Value); double prev = d.First().Value; foreach (var distance in d) { Console.WriteLine("{0} - {1}, delta={2}", distance.Key.AuthorName, distance.Value, distance.Value - prev); } Console.WriteLine(); } private static void PrintDistances<TCriteria>( string distanceName, Func<IProfile<TCriteria>, IEnumerable<IProfile<TCriteria>>, IProfile<TCriteria>, IDictionary<IProfile<TCriteria>, double>> distanceFunc, IProfile<TCriteria> p1, IEnumerable<IProfile<TCriteria>> p2, IProfile<TCriteria> normal ) { Console.WriteLine(distanceName); var d = distanceFunc(p1, p2,normal).OrderByDescending(x => x.Value); double prev = d.First().Value; foreach (var distance in d) { Console.WriteLine("{0} - {1}, delta={2}", distance.Key.AuthorName, distance.Value, distance.Value - prev); } Console.WriteLine(); } /// <summary> /// Разворачивает символ '~' в путь к домашней директории на UNIX'ах /// </summary> /// <returns> /// The home. /// </returns> /// <param name='input'> /// Input. /// </param> private static string extendHome (string input) { OperatingSystem os = Environment.OSVersion; if (os.Platform == PlatformID.Unix) { Debug.WriteLine(@"I smell a penguin! Or is it an imp?..."); return input.Replace("~", System.Environment.GetEnvironmentVariable("$HOME")); } return input; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Image_processing.Processing; using System.Drawing; using System.Windows.Forms; namespace Image_processing.Options { public class PolygonOption : Option { public List<Point> Vertices { get; set; } = new List<Point>(); public PolygonOption(Bitmap image) : base(image) { } public void Initialize(Point[] vertices) { Vertices = vertices.ToList(); } public override void MakeProcess(Process processing, Point position) { if (Vertices.Count == 0) return; int ymin = Vertices.Min(p => p.Y); int ymax = Vertices.Max(p => p.Y); List<Edge>[] ET = new List<Edge>[ymax - ymin + 1]; for (int i = 0; i < ET.Length; i++) ET[i] = new List<Edge>(); for (int i = 0; i < Vertices.Count; i++) { int x1, x2, y1, y2; x1 = Vertices[i].X; x2 = Vertices[(i + 1) % Vertices.Count].X; y1 = Vertices[i].Y; y2 = Vertices[(i + 1) % Vertices.Count].Y; if (y1 == y2) continue; double dx = (x2 - x1) / (double)(y2 - y1); Edge e; if (y2 > y1) e = new Edge(y2, x1, dx); else e = new Edge(y1, x2, dx); ET[Math.Min(y1, y2) - ymin].Add(e); } List<Edge> AET = new List<Edge>(); int y = ymin; while (y <= ymax) { AET.RemoveAll(e => e.ymax == y); if (ET[y - ymin].Count > 0) AET = AET.Concat(ET[y - ymin]).ToList(); AET.Sort((e1, e2) => (int)(e1.xmin - e2.xmin)); //DrawLine ProcessLine(processing, AET, y); foreach (var e in AET) e.AddDx(); y++; } } private void ProcessLine(Process processing, List<Edge> AET, int y) { if (y < 0) return; for (int i = 0; i < AET.Count; i += 2) { for (int x = (int)Math.Ceiling(AET[i].xmin); x < (int)Math.Floor(AET[(i + 1) % Vertices.Count].xmin); x++) { if (x < 0) continue; processing.Processing(image, x, y); } } } public override void DrawOption(PaintEventArgs e, Point position) { if (Vertices.Count < 3) return; e.Graphics.DrawLines(Pens.Black, Vertices.ToArray()); e.Graphics.DrawLine(Pens.Black, Vertices.Last(), Vertices.First()); } private class Edge { public int ymax { get; } public double xmin { get; private set; } public double dx { get; } public Edge(int ymax, double xmin, double dx) { this.ymax = ymax; this.xmin = xmin; this.dx = dx; } public void AddDx() { xmin += dx; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class balaSniperNetwork : MonoBehaviour { public GameObject Hero; public GameObject Player; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(Hero == null) { Hero = GameObject.Find("Hero"); } if(Player == null) { Player = GameObject.Find("SniperSpawn"); } } }
using System; using System.Collections.Generic; using System.Text; namespace Banking { public class CheckingAccount { public decimal Balance { get; set; } public void Deposit(decimal amount) { Balance += amount; } public void Withdraw(decimal amount) { Balance -= amount; } } }
using System; namespace Tools.extensions.enums { public class EnumDisplayAttribute : Attribute { #region Properties public string String { get; set; } #endregion Properties #region Constructor public EnumDisplayAttribute(string value) { this.String = value; } #endregion Constructor } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using NewsEngine.Models; using System.Text.RegularExpressions; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using PagedList; namespace NewsEngine.Servises { public class RepliesDbServise { public IQueryable<Reply> ExtractReplies(ApplicationDbContext db) { return db.Replies.Include(r => r.Message); } public Reply FindReplyById(int? id, ApplicationDbContext db) { return db.Replies.Find(id); } public void AddReply(Reply reply, ApplicationDbContext db) { db.Replies.Add(reply); } public void ModifidedReply(Reply reply, ApplicationDbContext db) { db.Entry(reply).State = EntityState.Modified; } public void RemoveRepliy(Reply reply, ApplicationDbContext db) { db.Replies.Remove(reply); } public void SaveChanges(ApplicationDbContext db) { db.SaveChanges(); } } }
using System; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Input.Touch; using Microsoft.Xna.Framework.Media; namespace DCL.Phone.Xna { /// <summary> /// Represents an ellipse which is actually a many sided three-dimensional polygon. /// </summary> public class Ellipsoid: Shape { #region Properties /// <summary> /// Gets the radius. /// </summary> public float Radius { get; private set; } /// <summary> /// Gets a normalized vector with direction from the center to the upper pole. /// </summary> public Vector3 Axis { get { Vector3 v = new Vector3(currentVertices[0].Position.X, currentVertices[0].Position.Y, currentVertices[0].Position.Z) - Center; v.Normalize(); return v; } } #endregion #region Constructors /// <summary> /// Sets up an ellipse. /// </summary> /// <param name="cent">The center of the ellipse.</param> /// <param name="radius">The radius of the ellipse.</param> /// <param name="radiusRatioX">The coefficient of stretching along the X axis.</param> /// <param name="radiusRatioY">The coefficient of stretching along the Y axis.</param> /// <param name="radiusRatioZ">The coefficient of stretching along the Z axis.</param> /// <param name="precision">A factor which influences the precision with that the ellipse is drawn. The recommended value for Windows Phone 7 is 10-14.</param> public Ellipsoid(Vector3 cent, float radius, float radiusRatioX, float radiusRatioY, float radiusRatioZ, int precision) { if (radius <= 0) throw new ArgumentOutOfRangeException("radius", "Radius must be a positive value"); if (precision <= 0) throw new ArgumentOutOfRangeException("precision", "Precision coefficient must be a positive value"); Center = startCenter = cent; Radius = radius; precision *= 2; startVertices = new VertexPositionNormalTexture[precision * (precision + 1) * 4]; currentVertices = new VertexPositionNormalTexture[precision * (precision + 1) * 4]; lineIndices = new short[precision * precision * 8]; triangleIndices = new short[precision * precision * 6]; //SETTING UP A SPHERE float p, t; //parameters Vector3 Point; //Normal, temp; int ind; for (int j = 0; j < precision; j++) {//2 + (n-2)/2 //SETTING UP A CIRCLE for (int i = 0; i < precision; i++) { ind = (j * precision + i); for (int m = 0; m < 2; m++) for (int n = 0; n < 2; n++) { p = MathHelper.Pi * ((j + m) - precision / 2) / precision; t = MathHelper.Pi * 2 * (i + n) / precision; Point = new Vector3(radius * radiusRatioX * (float)(Math.Sin(t) * Math.Cos(p)), radius * radiusRatioY * (float)(Math.Cos(t)), radius * radiusRatioZ * (float)(Math.Sin(t) * Math.Sin(p))) + Center; currentVertices[ind * 4 + n * 2 + m] = new VertexPositionNormalTexture (Point, Vector3.Up, (t / MathHelper.Pi < 1 || i == precision / 2 - 1) ? //!!!!!!!! new Vector2((MathHelper.PiOver2 - p) / MathHelper.TwoPi, t / MathHelper.Pi) : new Vector2((MathHelper.PiOver2 - p) / MathHelper.TwoPi + 0.5f, 2 - t / MathHelper.Pi)); } lineIndices[ind * 8] = lineIndices[ind * 8 + 7] = (short)(ind * 4); lineIndices[ind * 8 + 1] = lineIndices[ind * 8 + 2] = (short)(ind * 4 + 1); lineIndices[ind * 8 + 6] = lineIndices[ind * 8 + 4] = (short)(ind * 4 + 2); lineIndices[ind * 8 + 3] = lineIndices[ind * 8 + 5] = (short)(ind * 4 + 3); if (i < precision / 2) { triangleIndices[ind * 6] = (short)(ind * 4); triangleIndices[ind * 6 + 1] = triangleIndices[ind * 6 + 3] = (short)(ind * 4 + 2); triangleIndices[ind * 6 + 2] = triangleIndices[ind * 6 + 5] = (short)(ind * 4 + 1); triangleIndices[ind * 6 + 4] = (short)(ind * 4 + 3); } else { triangleIndices[ind * 6] = (short)(ind * 4); triangleIndices[ind * 6 + 2] = triangleIndices[ind * 6 + 4] = (short)(ind * 4 + 2); triangleIndices[ind * 6 + 1] = triangleIndices[ind * 6 + 5] = (short)(ind * 4 + 1); triangleIndices[ind * 6 + 3] = (short)(ind * 4 + 3); } } } Array.Copy(currentVertices, startVertices, startVertices.Length); } /// <summary> /// Sets up an ellipse. /// </summary> /// <param name="cent">The center of the ellipse.</param> /// <param name="radius">The radius of the ellipse.</param> /// <param name="radiusRatio">The coefficient of stretching along the X axis.</param> /// <param name="precision">A factor which influences the precision with that the ellipse is drawn. The recommended value for Windows Phone 7 is 10-14.</param> /// <param name="texture">The texture that is drawn to the surface of the ellipse.</param> public Ellipsoid(Vector3 cent, float radius, float radiusRatioX, float radiusRatioY, float radiusRatioZ, int precision, Texture2D texture) : this(cent, radius, radiusRatioX, radiusRatioY, radiusRatioZ, precision) { Texture = texture; } /// <summary> /// Sets up an ellipse. /// </summary> /// <param name="cent">The center of the ellipse.</param> /// <param name="radius">The radius of the ellipse.</param> /// <param name="radiusRatioX">The coefficient of stretching along the X axis.</param> /// <param name="radiusRatioY">The coefficient of stretching along the Y axis.</param> /// <param name="radiusRatioZ">The coefficient of stretching along the Z axis.</param> /// <param name="precision">A factor which influences the precision with that the ellipse is drawn. The recommended value for Windows Phone 7 is 10-14.</param> /// <param name="texture">The texture that is drawn to the surface of the ellipse.</param> /// <param name="graphicsDevice">The graphics device to which the ellipse is drawn.</param> public Ellipsoid(Vector3 cent, float radius, float radiusRatioX, float radiusRatioY, float radiusRatioZ, int precision, Texture2D texture, GraphicsDevice graphicsDevice) : this(cent, radius, radiusRatioX, radiusRatioY, radiusRatioZ, precision, texture) { GraphicsDevice = graphicsDevice; } #endregion } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Xamarin.Forms; using Xamarin.Forms.Xaml; using System.Diagnostics; namespace App1 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MusicAllPage : ContentPage { private clsSimpleAudio simplePlay = clsSimpleAudio.getInstance; private List<MusicAllFile> musicAllList; private bool isReady; private int CurrentPlayIndex = -1; private string GetFileName(string strFilename) { int nPos = strFilename.LastIndexOf('/'); int nLength = strFilename.Length; if (nPos < nLength) return strFilename.Substring(nPos + 1, (nLength - nPos) - 1); return strFilename; } private void InitImageButton() { var tapPrePayImage = new TapGestureRecognizer(); tapPrePayImage.Tapped += (s, e) => { TapGestureRecognizer_TappedPrePlayMusic(this, null); }; PrePayImage.GestureRecognizers.Add(tapPrePayImage); var tapplayImagee = new TapGestureRecognizer(); tapplayImagee.Tapped += (s, e) => { TapGestureRecognizer_TappedPlay(this, null); }; playImage.GestureRecognizers.Add(tapplayImagee); var tapnextplayImage = new TapGestureRecognizer(); tapnextplayImage.Tapped += (s, e) => { TapGestureRecognizer_TappedNextPlayMusic(this, null); }; nextplayImage.GestureRecognizers.Add(tapnextplayImage); } private async void TapGestureRecognizer_TappedPrePlayMusic(object sender, EventArgs e) { try { await Task.Delay(500); if (musicAllList.Count == 0) return; CurrentPlayIndex--; if (CurrentPlayIndex < 0) CurrentPlayIndex = musicAllList.Count - 1; Play(CurrentPlayIndex); UpdatePlayState(); } catch { App.WriteString("MusicAllPage TapGestureRecognizer_TappedPrePlayMusic Failed"); } } private async void TapGestureRecognizer_TappedPlay(object sender, EventArgs e) { try { await Task.Delay(500); simplePlay.Pause(); UpdatePlayState(); } catch { App.WriteString("MusicAllPage TapGestureRecognizer_TappedPlay Failed"); } } private async void TapGestureRecognizer_TappedNextPlayMusic(object sender, EventArgs e) { try { await Task.Delay(500); if (musicAllList.Count == 0) return; CurrentPlayIndex++; if (CurrentPlayIndex > (musicAllList.Count - 1)) CurrentPlayIndex = 0; Play(CurrentPlayIndex); UpdatePlayState(); } catch { App.WriteString("MusicAllPage TapGestureRecognizer_TappedNextPlayMusic Failed"); } } private void Play(int nIndex) { if (musicAllList.Count == 0) return; CurrentPlayIndex = nIndex; Debug.WriteLine("Music Index:" + CurrentPlayIndex); simplePlay.Open(musicAllList[CurrentPlayIndex].Name); simplePlay.Play(); totalTime.Text = simplePlay.GetTotalTimeDisplay(); currentTime.Text = simplePlay.GetCurrentTimeDisplay(); } private void SimplePlay_PlayMp3CompletedNotice(object sender, EventArgs e) { bool bPlay = simplePlay.IsPlaying(); if (!bPlay) { if (musicAllList.Count == 0) return; CurrentPlayIndex++; if (CurrentPlayIndex > (musicAllList.Count - 1)) CurrentPlayIndex = 0; Play(CurrentPlayIndex); UpdatePlayState(); } } private void UpdatePlayState() { Device.StartTimer(new TimeSpan(1000), () => { progress.Progress = simplePlay.GetCurrentPosition() * 1.0f / simplePlay.GetPosition(); currentTime.Text = simplePlay.GetCurrentTimeDisplay(); bool bPlay = simplePlay.IsPlaying(); return bPlay; }); } public MusicAllPage() { InitializeComponent(); try { BackgroundColor = Color.FromHex("#253648"); InitImageButton(); simplePlay.PlayMp3CompletedNotice += SimplePlay_PlayMp3CompletedNotice; musicAllList = null; musicAllList = new List<MusicAllFile>(); MusicAllList.ItemsSource = musicAllList; MusicAllList.ItemTapped += MusicAllList_ItemTapped; LoadData(); MusicAllList.IsVisible = true; actIndicator.IsRunning = false; actIndicatorStackLayout.IsVisible = false; } catch { App.WriteString("MusicAllPage MusicAllPage Failed"); } } protected override bool OnBackButtonPressed() { return true; //return base.OnBackButtonPressed(); } private async void LoadData() { await Task.Factory.StartNew(() => { var MusicList = simplePlay.GetMusic(); for (int i = 0; i < MusicList.Count; i++) { musicAllList.Add(new MusicAllFile(MusicList[i], GetFileName(MusicList[i]))); Task.Delay(TimeSpan.FromMilliseconds(22)); } MusicList.Clear(); isReady = true; }); } protected override void OnAppearing() { base.OnAppearing(); try { if (XamarinAppSettings.PageName != "MusicAllPage") { XamarinAppSettings.PageName = "MusicAllPage"; } else { //check playing bool bPlay = simplePlay.IsPlaying(); if (bPlay) { UpdatePlayState(); } else { progress.Progress = simplePlay.GetCurrentPosition() * 1.0f / simplePlay.GetPosition(); } totalTime.Text = simplePlay.GetTotalTimeDisplay(); currentTime.Text = simplePlay.GetCurrentTimeDisplay(); } } catch { App.WriteString("MusicAllPage OnAppearing Failed"); } } private void MusicAllList_ItemTapped(object sender, ItemTappedEventArgs e) { try { if (e.Item == null || !isReady) return; var Music = (MusicAllFile)e.Item; CurrentPlayIndex = musicAllList.IndexOf(Music); Play(CurrentPlayIndex); UpdatePlayState(); ((ListView)sender).SelectedItem = null; } catch { App.WriteString("MusicAllPage MusicAllList_ItemTapped Failed"); } } protected override void OnDisappearing() { base.OnDisappearing(); App.CurrentIndex = 1; XamarinAppSettings.PageName = "MusicAllPage"; } } class MusicAllFile { public string Name { get; set; } public string DisplayName { get; set; } public MusicAllFile(string Name, string DisplayName) { this.Name = Name; this.DisplayName = DisplayName; } } }
using UnityEngine; using System.Collections; public class Bowl : MonoBehaviour { public Mesh LowQualityBowl; public float MaxVelocity; private bool m_hasSmashed = false; private Smashable m_smashable = null; private float m_lastVelocity = 0.0f; // Use this for initialization void Start () { m_smashable = GetComponent<Smashable>(); } // Update is called once per frame void FixedUpdate () { m_lastVelocity = this.rigidbody.velocity.sqrMagnitude; } void OnCollisionEnter(Collision collision) { if (!m_hasSmashed && m_lastVelocity > this.MaxVelocity) { m_hasSmashed = true; GetComponent<MeshFilter>().mesh = this.LowQualityBowl; this.collider.enabled = false; this.GetComponent<AudioSource>().Play(); m_smashable.SmashObject(); } } }
using UnityEngine; using Zenject; namespace UI.Dynamites.Code { public class UIDynamite : MonoBehaviour { public class Pool : MonoMemoryPool<UIDynamite> { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataObject.Abstract; namespace DataObject { public class Phong:Vat { private string tenPhong; private int loaiPhong; private int sucChua; private int tinhTrang; private decimal donGia; private string ghiChu; public string GhiChu { get { return ghiChu; } set { ghiChu = value; } } public decimal DonGia { get { return donGia; } set { donGia = value; } } public int TinhTrang { get { return tinhTrang; } set { tinhTrang = value; } } public int SucChua { get { return sucChua; } set { sucChua = value; } } public int LoaiPhong { get { return loaiPhong; } set { loaiPhong = value; } } public string TenPhong { get { return tenPhong; } set { tenPhong = value; } } } }
using UnityEngine; using System.Collections; public class Negro : NpcBase { public Transform LookStart; public Transform LookEnd; public float HitPowah; public float HitPowahY; public float RunPowah; private RaycastHit2D rh2; new void FixedUpdate() { Raycast(); if(WalkHorWoF == true) { WalkHorizontalNoFallling(); } } new void Raycast() { base.Raycast(); if(rh2 = Physics2D.Linecast(LookStart.position,LookEnd.position, 1 << LayerMask.NameToLayer("Player1") | 1 << LayerMask.NameToLayer("Player2"))) { rg.AddForce(new Vector2(Mathf.Sign(rh2.transform.position.x - transform.position.x)*RunPowah,0)); } } void OnCollisionEnter2D(Collision2D hit) { Debug.Log("Entre"); if(hit.transform.CompareTag("Player")) { Debug.Log("hello"); hit.rigidbody.AddForce(new Vector2(Mathf.Sign(rg.velocity.x)*HitPowah,HitPowahY)); } } }
using UnityEngine; using System.Collections; public enum SoundConfigType { MasterVolume, BgmVolume, SfxVolume, } public class SoundManager : Singleton<SoundManager> { /* 볼륨 크기 * * UI = 1 * Object = 0.85 * BGM(!InGame) = 0.8 * Character = 0.75 * BGM(InGame) = 0.6 * * 적용 후 변동사항 생기면 여기에 적어둘께. -요한 * */ public float MasterVolume { get { return _masterVolume; } set { _masterVolume = value; OnMasterVolumeChanged?.Invoke(_masterVolume); OnBgmVolumeChanged?.Invoke(_masterVolume * _bgmVolume); OnSfxVolumeChanged?.Invoke(_masterVolume * _sfxVolume); } } private float _masterVolume; public float BgmVolume { get { return _bgmVolume; } set { _bgmVolume = value; OnBgmVolumeChanged?.Invoke(_masterVolume * _bgmVolume); } } private float _bgmVolume; public float SfxVolume { get { return _sfxVolume; } set { _sfxVolume = value; OnSfxVolumeChanged?.Invoke(_masterVolume * _sfxVolume); } } private float _sfxVolume; #region Event public event System.Action<float> OnMasterVolumeChanged; public event System.Action<float> OnBgmVolumeChanged; public event System.Action<float> OnSfxVolumeChanged; #endregion protected override void Awake() { base.Awake(); MasterVolume = 1f; BgmVolume = 1f; SfxVolume = 1f; if(PlayerPrefs.HasKey(nameof(SoundConfigType.MasterVolume)) == true) { MasterVolume = PlayerPrefs.GetFloat(nameof(SoundConfigType.MasterVolume)); } if(PlayerPrefs.HasKey(nameof(SoundConfigType.BgmVolume)) == true) { BgmVolume = PlayerPrefs.GetFloat(nameof(SoundConfigType.BgmVolume)); } if(PlayerPrefs.HasKey(nameof(SoundConfigType.SfxVolume)) == true) { SfxVolume = PlayerPrefs.GetFloat(nameof(SoundConfigType.SfxVolume)); } } private void OnApplicationQuit() { PlayerPrefs.SetFloat(nameof(SoundConfigType.MasterVolume), MasterVolume); PlayerPrefs.SetFloat(nameof(SoundConfigType.BgmVolume), BgmVolume); PlayerPrefs.SetFloat(nameof(SoundConfigType.SfxVolume), SfxVolume); PlayerPrefs.Save(); } }
using UnityEngine; public class NoteRefractorSpin : MonoBehaviour { [System.Serializable] public struct SpinInfo { public enum Direction {Right, Up, Left, Down} public Direction direction; public float delay; } public NoteRepeater repeat; public SpinInfo[] info; private float timer; private int index; // Use this for initialization void Start() { timer = 0f; index = 0; } private void Update() { if (timer <= 0f) { ChangeDirection(info[index].direction); index++; if (index < info.Length) { timer = info[index].delay; } else if(info.Length > 0) { index = 0; timer = info[index].delay; } } else { timer -= Time.deltaTime; } } private void ChangeDirection(SpinInfo.Direction direction) { switch (direction) { case SpinInfo.Direction.Right: repeat.ChangeRefractDirection(0f); break; case SpinInfo.Direction.Up: repeat.ChangeRefractDirection(90f); break; case SpinInfo.Direction.Left: repeat.ChangeRefractDirection(180f); break; case SpinInfo.Direction.Down: repeat.ChangeRefractDirection(270f); break; default: break; } } }
/************************************ ** Created by Wizcas (wizcas.me) ************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { public Transform target; public float panSpeed = 3f; private Vector3 _offset; void Start() { _offset = transform.position - target.position; } void Update() { transform.position = Vector3.Lerp(transform.position, target.position + _offset, panSpeed * Time.deltaTime); } }
using System; using Serilog; using StoreDB.Models; using StoreDB.Repos; using StoreLib; namespace StoreUI { /// <summary> /// Customer menu implementing IMenu interface /// </summary> public class CustomerMenu : IMenu { private string userInput; private ICustomerRepo repo; private ReturningCustomerMenu returningCustomerMenu; private CustomerService customerService; public CustomerMenu(ICustomerRepo repo) { this.repo = repo; this.customerService = new CustomerService(repo); this.returningCustomerMenu = new ReturningCustomerMenu(repo); } public void Start() { do { Console.Write("Are you a new customer [0] or a returning customer [1]? (type \"x\" to go back) "); userInput = Console.ReadLine(); switch (userInput) { case "0": Customer newCustomer = CustomerSignup(); customerService.AddCustomer(newCustomer); Console.WriteLine($"Customer {newCustomer.Name} added!"); Log.Information("Customer has been added"); break; case "1": returningCustomerMenu.Start(); break; case "x": Console.WriteLine("Going back..."); break; } } while (!userInput.Equals("x")); } public Customer CustomerSignup() { Customer customer = new Customer(); Console.WriteLine("\nPlease sign up!"); Console.Write("What is your name? "); customer.Name = Console.ReadLine(); Console.Write("What is your phone number? "); customer.PhoneNumber = Console.ReadLine(); Console.Write("What is your email address? "); customer.EmailAddress = Console.ReadLine(); Console.Write("What is your mailing address? "); customer.MailingAddress = Console.ReadLine(); return customer; } } }
using System; namespace NLuaTest.Mock { public delegate TestClass TestDelegate4(int a, int b); }
using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Security; namespace Torshify.Radio.Utilities { [SuppressUnmanagedCodeSecurity] public static class ConsoleManager { #region Fields private const string Kernel32DllName = "kernel32.dll"; #endregion Fields #region Properties public static bool HasConsole { get { return GetConsoleWindow() != IntPtr.Zero; } } #endregion Properties #region Methods /// <summary> /// If the process has a console attached to it, it will be detached and no longer visible. Writing to the System.Console is still possible, but no output will be shown. /// </summary> public static void Hide() { if (HasConsole) { SetOutAndErrorNull(); FreeConsole(); } } /// <summary> /// Creates a new console instance if the process is not attached to a console already. /// </summary> public static void Show() { if (!HasConsole) { AllocConsole(); InvalidateOutAndError(); } } public static void Toggle() { if (HasConsole) { Hide(); } else { Show(); } } [DllImport(Kernel32DllName)] private static extern bool AllocConsole(); [DllImport(Kernel32DllName)] private static extern bool FreeConsole(); [DllImport(Kernel32DllName)] private static extern IntPtr GetConsoleWindow(); private static void InvalidateOutAndError() { Type type = typeof(Console); System.Reflection.FieldInfo @out = type.GetField( "_out", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.FieldInfo error = type.GetField( "_error", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); System.Reflection.MethodInfo initializeStdOutError = type.GetMethod( "InitializeStdOutError", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); Debug.Assert(@out != null, "out can't be null"); Debug.Assert(error != null, "error can't be null"); Debug.Assert(initializeStdOutError != null, "stdout can't be null"); @out.SetValue(null, null); error.SetValue(null, null); initializeStdOutError.Invoke(null, new object[] { true }); } private static void SetOutAndErrorNull() { Console.SetOut(TextWriter.Null); Console.SetError(TextWriter.Null); } #endregion Methods } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Text; using Collada141; using System.IO; namespace SonicRetro.SAModel { [Serializable] public class NJS_OBJECT { [Browsable(false)] public Attach Attach { get; set; } public Vertex Position { get; set; } public Rotation Rotation { get; set; } public Vertex Scale { get; set; } [Browsable(false)] public List<NJS_OBJECT> Children { get; set; } public NJS_OBJECT Sibling { get; private set; } public string Name { get; set; } public bool RotateZYX { get; set; } [DefaultValue(true)] public bool Animate { get; set; } [DefaultValue(true)] public bool Morph { get; set; } public static int Size { get { return 0x34; } } public NJS_OBJECT() { Name = "object_" + Extensions.GenerateIdentifier(); Position = new Vertex(); Rotation = new Rotation(); Scale = new Vertex(1, 1, 1); Children = new List<NJS_OBJECT>(); } public NJS_OBJECT(byte[] file, int address, uint imageBase, ModelFormat format) : this(file, address, imageBase, format, new Dictionary<int, string>()) { } public NJS_OBJECT(byte[] file, int address, uint imageBase, ModelFormat format, Dictionary<int, string> labels) { if (labels.ContainsKey(address)) Name = labels[address]; else Name = "object_" + address.ToString("X8"); ObjectFlags flags = (ObjectFlags)ByteConverter.ToInt32(file, address); RotateZYX = (flags & ObjectFlags.RotateZYX) == ObjectFlags.RotateZYX; Animate = (flags & ObjectFlags.NoAnimate) == 0; Morph = (flags & ObjectFlags.NoMorph) == 0; int tmpaddr = ByteConverter.ToInt32(file, address + 4); if (tmpaddr != 0) { tmpaddr = (int)unchecked((uint)tmpaddr - imageBase); Attach = Attach.Load(file, tmpaddr, imageBase, format, labels); } Position = new Vertex(file, address + 8); Rotation = new Rotation(file, address + 0x14); Scale = new Vertex(file, address + 0x20); Children = new List<NJS_OBJECT>(); NJS_OBJECT child = null; tmpaddr = ByteConverter.ToInt32(file, address + 0x2C); if (tmpaddr != 0) { tmpaddr = (int)unchecked((uint)tmpaddr - imageBase); child = new NJS_OBJECT(file, tmpaddr, imageBase, format, labels); } while (child != null) { Children.Add(child); child = child.Sibling; } tmpaddr = ByteConverter.ToInt32(file, address + 0x30); if (tmpaddr != 0) { tmpaddr = (int)unchecked((uint)tmpaddr - imageBase); Sibling = new NJS_OBJECT(file, tmpaddr, imageBase, format, labels); } } public byte[] GetBytes(uint imageBase, bool DX, Dictionary<string, uint> labels, out uint address) { for (int i = 1; i < Children.Count; i++) Children[i - 1].Sibling = Children[i]; List<byte> result = new List<byte>(); uint childaddr = 0; uint siblingaddr = 0; uint attachaddr = 0; byte[] tmpbyte; if (Children.Count > 0) { if (labels.ContainsKey(Children[0].Name)) childaddr = labels[Children[0].Name]; else { result.Align(4); result.AddRange(Children[0].GetBytes(imageBase, DX, labels, out childaddr)); childaddr += imageBase; } } if (Sibling != null) { if (labels.ContainsKey(Sibling.Name)) siblingaddr = labels[Sibling.Name]; else { result.Align(4); tmpbyte = Sibling.GetBytes(imageBase + (uint)result.Count, DX, labels, out siblingaddr); siblingaddr += imageBase + (uint)result.Count; result.AddRange(tmpbyte); } } if (Attach != null) { if (labels.ContainsKey(Attach.Name)) attachaddr = labels[Attach.Name]; else { result.Align(4); tmpbyte = Attach.GetBytes(imageBase + (uint)result.Count, DX, labels, out attachaddr); attachaddr += imageBase + (uint)result.Count; result.AddRange(tmpbyte); } } result.Align(4); address = (uint)result.Count; ObjectFlags flags = GetFlags(); result.AddRange(ByteConverter.GetBytes((int)flags)); result.AddRange(ByteConverter.GetBytes(attachaddr)); result.AddRange(Position.GetBytes()); result.AddRange(Rotation.GetBytes()); result.AddRange(Scale.GetBytes()); result.AddRange(ByteConverter.GetBytes(childaddr)); result.AddRange(ByteConverter.GetBytes(siblingaddr)); labels.Add(Name, address + imageBase); return result.ToArray(); } public ObjectFlags GetFlags() { ObjectFlags flags = 0; if (Position.IsEmpty) flags = ObjectFlags.NoPosition; if (Rotation.IsEmpty) flags |= ObjectFlags.NoRotate; if (Scale.X == 1 && Scale.Y == 1 && Scale.Z == 1) flags |= ObjectFlags.NoScale; if (Attach == null) flags |= ObjectFlags.NoDisplay; if (Children.Count == 0) flags |= ObjectFlags.NoChildren; if (RotateZYX) flags |= ObjectFlags.RotateZYX; if (!Animate) flags |= ObjectFlags.NoAnimate; if (!Morph) flags |= ObjectFlags.NoMorph; return flags; } public byte[] GetBytes(uint imageBase, bool DX, out uint address) { return GetBytes(imageBase, DX, new Dictionary<string, uint>(), out address); } public byte[] GetBytes(uint imageBase, bool DX) { return GetBytes(imageBase, DX, out uint address); } public NJS_OBJECT[] GetObjects() { List<NJS_OBJECT> result = new List<NJS_OBJECT> { this }; foreach (NJS_OBJECT item in Children) result.AddRange(item.GetObjects()); return result.ToArray(); } public int CountAnimated() { int result = Animate ? 1 : 0; foreach (NJS_OBJECT item in Children) result += item.CountAnimated(); return result; } public int CountMorph() { int result = Morph ? 1 : 0; foreach (NJS_OBJECT item in Children) result += item.CountMorph(); return result; } public void ProcessVertexData() { #if modellog Extensions.Log("Processing Object " + Name + Environment.NewLine); #endif if (Attach != null) Attach.ProcessVertexData(); foreach (NJS_OBJECT item in Children) item.ProcessVertexData(); } public COLLADA ToCollada(int texcount) { string[] texs = new string[texcount]; for (int i = 0; i < texcount; i++) texs[i] = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo); return ToCollada(texs); } public COLLADA ToCollada(string[] textures) { COLLADA result = new COLLADA { version = VersionType.Item140, asset = new asset { contributor = new assetContributor[] { new assetContributor() { authoring_tool = "SAModel" } }, created = DateTime.UtcNow, modified = DateTime.UtcNow } }; List<object> libraries = new List<object>(); List<image> images = new List<image>(); if (textures != null) { for (int i = 0; i < textures.Length; i++) { images.Add(new image { id = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo), name = "image_" + (i + 1).ToString(NumberFormatInfo.InvariantInfo), Item = textures[i] + ".png" }); } } libraries.Add(new library_images { image = images.ToArray() }); List<material> materials = new List<material>(); List<effect> effects = new List<effect>(); List<geometry> geometries = new List<geometry>(); List<string> visitedAttaches = new List<string>(); node node = AddToCollada(materials, effects, geometries, visitedAttaches, textures != null); libraries.Add(new library_materials { material = materials.ToArray() }); libraries.Add(new library_effects { effect = effects.ToArray() }); libraries.Add(new library_geometries { geometry = geometries.ToArray() }); libraries.Add(new library_visual_scenes { visual_scene = new visual_scene[] { new visual_scene { id = "RootNode", node = new node[] { node } } } }); result.Items = libraries.ToArray(); result.scene = new COLLADAScene { instance_visual_scene = new InstanceWithExtra { url = "#RootNode" } }; return result; } protected node AddToCollada(List<material> materials, List<effect> effects, List<geometry> geometries, List<string> visitedAttaches, bool hasTextures) { BasicAttach attach = Attach as BasicAttach; if (attach == null || visitedAttaches.Contains(attach.Name)) goto skipAttach; visitedAttaches.Add(attach.Name); int m = 0; foreach (NJS_MATERIAL item in attach.Material) { materials.Add(new material { id = "material_" + attach.Name + "_" + m, name = "material_" + attach.Name + "_" + m, instance_effect = new instance_effect { url = "#" + "material_" + attach.Name + "_" + m + "_eff" } }); if (hasTextures & item.UseTexture) { effects.Add(new effect { id = "material_" + attach.Name + "_" + m + "_eff", name = "material_" + attach.Name + "_" + m + "_eff", Items = new effectFx_profile_abstractProfile_COMMON[] { new effectFx_profile_abstractProfile_COMMON { Items = new object[] { new common_newparam_type { sid = "material_" + attach.Name + "_" + m + "_eff_surface", /*Item = new Collada141.fx_sampler2D_common() { instance_image = new Collada141.instance_image() { url = "#image_" + (item.TextureID + 1).ToString(System.Globalization.NumberFormatInfo.InvariantInfo) } }, ItemElementName = Collada141.ItemChoiceType.sampler2D*/ Item = new fx_surface_common { type = fx_surface_type_enum.Item2D, init_from = new fx_surface_init_from_common[] { new fx_surface_init_from_common { Value = "image_" + (item.TextureID + 1).ToString(NumberFormatInfo.InvariantInfo) } } }, ItemElementName = ItemChoiceType.surface } }, technique = new effectFx_profile_abstractProfile_COMMONTechnique { sid = "standard", Item = new effectFx_profile_abstractProfile_COMMONTechniquePhong { ambient = new common_color_or_texture_type { Item = new common_color_or_texture_typeTexture { texture = "material_" + attach.Name + "_" + m + "_eff_surface", texcoord = "CHANNEL0" } }, diffuse = new common_color_or_texture_type { Item = new common_color_or_texture_typeColor { Values = new double[] { item.DiffuseColor.R / 255d, item.DiffuseColor.G / 255d, item.DiffuseColor.B / 255d, item.UseAlpha ? item.DiffuseColor.A / 255d : 1 } } } } } } } }); } else { effects.Add(new effect { id = "material_" + attach.Name + "_" + m + "_eff", name = "material_" + attach.Name + "_" + m + "_eff", Items = new effectFx_profile_abstractProfile_COMMON[] { new effectFx_profile_abstractProfile_COMMON { technique = new effectFx_profile_abstractProfile_COMMONTechnique { sid = "standard", Item = new effectFx_profile_abstractProfile_COMMONTechniquePhong { diffuse = new common_color_or_texture_type { Item = new common_color_or_texture_typeColor { Values = new double[] { item.DiffuseColor.R / 255d, item.DiffuseColor.G / 255d, item.DiffuseColor.B / 255d, item.UseAlpha ? item.DiffuseColor.A / 255d : 1 } } } } } } } }); } m++; } List<double> verts = new List<double>(); foreach (Vertex item in attach.Vertex) { verts.Add(item.X); verts.Add(item.Y); verts.Add(item.Z); } source pos = new source { id = attach.Name + "_position", Item = new float_array { id = attach.Name + "_position_array", count = (ulong)verts.Count, Values = verts.ToArray() }, technique_common = new sourceTechnique_common { accessor = new accessor { source = "#" + attach.Name + "_position_array", count = (ulong)(verts.Count / 3), stride = 3, param = new param[] { new param { name = "X", type = "float" }, new param { name = "Y", type = "float" }, new param { name = "Z", type = "float" } } } } }; verts = new List<double>(); foreach (Vertex item in attach.Normal) { verts.Add(item.X); verts.Add(item.Y); verts.Add(item.Z); } source nor = new source { id = attach.Name + "_normal", Item = new float_array { id = attach.Name + "_normal_array", count = (ulong)verts.Count, Values = verts.ToArray() }, technique_common = new sourceTechnique_common { accessor = new accessor { source = "#" + attach.Name + "_normal_array", count = (ulong)(verts.Count / 3), stride = 3, param = new param[] { new param { name = "X", type = "float" }, new param { name = "Y", type = "float" }, new param { name = "Z", type = "float" } } } } }; List<source> srcs = new List<source> { pos, nor }; foreach (NJS_MESHSET mitem in attach.Mesh) { if (mitem.UV != null) { verts = new List<double>(); foreach (UV item in mitem.UV) { verts.Add(item.U); verts.Add(-item.V); } srcs.Add(new source { id = mitem.UVName, Item = new float_array { id = mitem.UVName + "_array", count = (ulong)verts.Count, Values = verts.ToArray() }, technique_common = new sourceTechnique_common { accessor = new accessor { source = "#" + mitem.UVName + "_array", count = (ulong)(verts.Count / 2), stride = 2, param = new param[] { new param { name = "S", type = "float" }, new param { name = "T", type = "float" } } } } }); } } List<triangles> tris = new List<triangles>(); foreach (NJS_MESHSET mesh in attach.Mesh) { bool hasVColor = mesh.VColor != null; bool hasUV = mesh.UV != null; uint currentstriptotal = 0; foreach (Poly poly in mesh.Poly) { List<uint> inds = new List<uint>(); switch (mesh.PolyType) { case Basic_PolyType.Triangles: for (uint i = 0; i < 3; i++) { inds.Add(poly.Indexes[i]); if (hasUV) inds.Add(currentstriptotal + i); } currentstriptotal += 3; break; case Basic_PolyType.Quads: for (uint i = 0; i < 3; i++) { inds.Add(poly.Indexes[i]); if (hasUV) inds.Add(currentstriptotal + i); } for (uint i = 1; i < 4; i++) { inds.Add(poly.Indexes[i]); if (hasUV) inds.Add(currentstriptotal + i); } currentstriptotal += 4; break; case Basic_PolyType.NPoly: case Basic_PolyType.Strips: bool flip = !((Strip)poly).Reversed; for (int k = 0; k < poly.Indexes.Length - 2; k++) { flip = !flip; if (!flip) { for (uint i = 0; i < 3; i++) { inds.Add(poly.Indexes[k + i]); if (hasUV) inds.Add(currentstriptotal + i); } } else { inds.Add(poly.Indexes[k + 1]); if (hasUV) inds.Add(currentstriptotal + 1); inds.Add(poly.Indexes[k]); if (hasUV) inds.Add(currentstriptotal); inds.Add(poly.Indexes[k + 2]); if (hasUV) inds.Add(currentstriptotal + 2); } currentstriptotal += 1; } currentstriptotal += 2; break; } string[] indstr = new string[inds.Count]; for (int i = 0; i < inds.Count; i++) indstr[i] = inds[i].ToString(NumberFormatInfo.InvariantInfo); List<InputLocalOffset> inp = new List<InputLocalOffset> { new InputLocalOffset { semantic = "VERTEX", offset = 0, source = "#" + attach.Name + "_vertices" } }; if (hasUV) { inp.Add(new InputLocalOffset { semantic = "TEXCOORD", offset = 1, source = "#" + mesh.UVName, setSpecified = true }); } tris.Add(new triangles { material = "material_" + attach.Name + "_" + mesh.MaterialID, count = (ulong)(inds.Count / (hasUV ? 6 : 3)), input = inp.ToArray(), p = string.Join(" ", indstr) }); } } geometries.Add(new geometry { id = attach.Name, name = attach.Name, Item = new mesh { source = srcs.ToArray(), vertices = new vertices { id = attach.Name + "_vertices", input = new InputLocal[] { new InputLocal { semantic = "POSITION", source = "#" + attach.Name + "_position" }, new InputLocal { semantic = "NORMAL", source = "#" + attach.Name + "_normal" } } }, Items = tris.ToArray() } }); skipAttach: node node = new node { id = Name, name = Name, Items = new object[] { new TargetableFloat3 { sid = "translate", Values = new double[] { Position.X, Position.Y, Position.Z } }, new rotate { sid = "rotateZ", Values = new double[] { 0, 0, 1, Rotation.BAMSToDeg(Rotation.Z) } }, new rotate { sid = "rotateX", Values = new double[] { 1, 0, 0, Rotation.BAMSToDeg(Rotation.X) } }, new rotate { sid = "rotateY", Values = new double[] { 0, 1, 0, Rotation.BAMSToDeg(Rotation.Y) } }, new TargetableFloat3 { sid = "scale", Values = new double[] { Scale.X, Scale.Y, Scale.Z } } }, ItemsElementName = new ItemsChoiceType2[] { ItemsChoiceType2.translate, ItemsChoiceType2.rotate, ItemsChoiceType2.rotate, ItemsChoiceType2.rotate, ItemsChoiceType2.scale } }; if (attach != null) { List<instance_material> mats = new List<instance_material>(); foreach (NJS_MESHSET item in attach.Mesh) { mats.Add(new instance_material { symbol = "material_" + attach.Name + "_" + item.MaterialID, target = "#" + "material_" + attach.Name + "_" + item.MaterialID }); } node.instance_geometry = new instance_geometry[] { new instance_geometry { url = "#" + attach.Name, bind_material = new bind_material { technique_common = mats.ToArray() } } }; } List<node> childnodes = new List<node>(); foreach (NJS_OBJECT item in Children) childnodes.Add(item.AddToCollada(materials, effects, geometries, visitedAttaches, hasTextures)); node.node1 = childnodes.ToArray(); return node; } public NJS_OBJECT ToBasicModel() { List<NJS_OBJECT> newchildren = new List<NJS_OBJECT>(Children.Count); foreach (NJS_OBJECT item in Children) newchildren.Add(item.ToBasicModel()); NJS_OBJECT result = new NJS_OBJECT(); if (Attach != null) result.Attach = Attach.ToBasicModel(); result.Position = Position; result.Rotation = Rotation; result.Scale = Scale; result.Children = newchildren; return result; } public NJS_OBJECT ToChunkModel() { List<NJS_OBJECT> newchildren = new List<NJS_OBJECT>(Children.Count); foreach (NJS_OBJECT item in Children) newchildren.Add(item.ToBasicModel()); NJS_OBJECT result = new NJS_OBJECT(); if (Attach != null) result.Attach = Attach.ToChunkModel(); result.Position = Position; result.Rotation = Rotation; result.Scale = Scale; result.Children = newchildren; return result; } public string ToStruct() { StringBuilder result = new StringBuilder("{ "); result.Append(((StructEnums.NJD_EVAL)GetFlags()).ToString().Replace(", ", " | ")); result.Append(", "); result.Append(Attach != null ? "&" + Attach.Name : "NULL"); foreach (float value in Position.ToArray()) { result.Append(", "); result.Append(value.ToC()); } foreach (int value in Rotation.ToArray()) { result.Append(", "); result.Append(value.ToCHex()); } foreach (float value in Scale.ToArray()) { result.Append(", "); result.Append(value.ToC()); } result.Append(", "); result.Append(Children.Count > 0 ? "&" + Children[0].Name : "NULL"); result.Append(", "); result.Append(Sibling != null ? "&" + Sibling.Name : "NULL"); result.Append(" }"); return result.ToString(); } public void ToStructVariables(TextWriter writer, bool DX, List<string> labels, string[] textures = null) { for (int i = 1; i < Children.Count; i++) Children[i - 1].Sibling = Children[i]; for (int i = Children.Count - 1; i >= 0; i--) { if (!labels.Contains(Children[i].Name)) { labels.Add(Children[i].Name); Children[i].ToStructVariables(writer, DX, labels, textures); writer.WriteLine(); } } if (Attach != null && !labels.Contains(Attach.Name)) { labels.Add(Attach.Name); Attach.ToStructVariables(writer, DX, labels, textures); writer.WriteLine(); } writer.Write("NJS_OBJECT "); writer.Write(Name); writer.Write(" = "); writer.Write(ToStruct()); writer.WriteLine(";"); } public string ToStructVariables(bool DX, List<string> labels, string[] textures = null) { using (StringWriter sw = new StringWriter()) { ToStructVariables(sw, DX, labels, textures); return sw.ToString(); } } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Microsoft.Extensions.Options; using RestSharp; using Riverside.Cms.Utilities.Net.RestSharpExtensions; namespace Riverside.Cms.Services.Element.Client { public enum Language { Apache, Bash, CSharp, CPlusPlus, Css, CoffeeScript, Diff, Html, Http, Ini, Json, Java, JavaScript, Makefile, Markdown, Nginx, ObjectiveC, Php, Perl, Python, Ruby, Sql, Xml } public class CodeSnippetElementSettings : ElementSettings { public string Code { get; set; } public Language Language { get; set; } } public interface ICodeSnippetElementService : IElementSettingsService<CodeSnippetElementSettings> { } public class CodeSnippetElementService : ICodeSnippetElementService { private readonly IOptions<ElementApiOptions> _options; public CodeSnippetElementService(IOptions<ElementApiOptions> options) { _options = options; } private void CheckResponseStatus<T>(IRestResponse<T> response) where T : new() { if (response.ErrorException != null) throw new ElementClientException($"Element API failed with response status {response.ResponseStatus}", response.ErrorException); } public async Task<CodeSnippetElementSettings> ReadElementSettingsAsync(long tenantId, long elementId) { try { RestClient client = new RestClient(_options.Value.ElementApiBaseUrl); RestRequest request = new RestRequest("tenants/{tenantId}/elementtypes/5401977d-865f-4a7a-b416-0a26305615de/elements/{elementId}", Method.GET); request.AddUrlSegment("tenantId", tenantId); request.AddUrlSegment("elementId", elementId); IRestResponse<CodeSnippetElementSettings> response = await client.ExecuteAsync<CodeSnippetElementSettings>(request); CheckResponseStatus(response); return response.Data; } catch (ElementClientException) { throw; } catch (Exception ex) { throw new ElementClientException("Element API failed", ex); } } } }
using bot_backEnd.BL.Interfaces; using bot_backEnd.DAL; using bot_backEnd.DAL.Interfaces; using bot_backEnd.Data; using bot_backEnd.Models; using bot_backEnd.Models.DbModels; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.BL { public class PostImageBL : IPostImageBL { private readonly IPostImageDAL _iPostImageDAL; private readonly IWebHostEnvironment _environment; public PostImageBL(IPostImageDAL iPostImageDAL, IWebHostEnvironment enviroment) { _environment = enviroment; _iPostImageDAL = iPostImageDAL; } public void addImage(PostImage image) { _iPostImageDAL.AddImage(image); } public List<PostImage> getImagesByPostID(int id) { return _iPostImageDAL.GetImagesByPostID(id).Result.Value; } public async Task<ActionResult<bool>> UploadImages(IFormFile[] images, int PostID) { int subFolderID; //number of subFolder string subFolder; //name of subfolder with ID on the END if (images == null || images.Length == 0) return false; string folder = "/post/"; if (!Directory.Exists(_environment.WebRootPath + folder)) Directory.CreateDirectory(_environment.WebRootPath + folder); foreach (IFormFile img in images) //foreach sent image { string imgext = Path.GetExtension(img.FileName); //maxID = _context.Image.Count() > 0 ? _context.Image.Max(i => i.Id) + 1 : 1; if (imgext == ".jpg" || imgext == ".png" || imgext == ".jpeg") { PostImage newImage = new PostImage { PostID = PostID, Path = folder, // + subFolder, Name = img.FileName }; await _iPostImageDAL.AddImage(newImage); subFolderID = newImage.Id / 3000 + 1; subFolder = string.Format("{0:D4}", subFolderID) + "/"; await _iPostImageDAL.UpdateImage(newImage.Id, imgext, folder + subFolder); if (!Directory.Exists(_environment.WebRootPath + folder + subFolder)) Directory.CreateDirectory(_environment.WebRootPath + folder + subFolder); using FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + folder + subFolder + newImage.Id.ToString() + imgext); await img.CopyToAsync(fileStream); fileStream.Flush(); } else return false; } return true; } public async Task<ActionResult<bool>> UploadInstitutionPostImage(int postID, string image) { try { string mainFolder = "/post/"; int subFolderID; string subFolderName; if (image == "" || image == null) return null; if (!Directory.Exists(_environment.WebRootPath + mainFolder)) Directory.CreateDirectory(_environment.WebRootPath + mainFolder); PostImage newImage = new PostImage { PostID = postID, Path = mainFolder, // + subFolder, Name = "name" }; await _iPostImageDAL.AddImage(newImage); //adds image to database table subFolderID = newImage.Id / 3000 + 1; subFolderName = string.Format("{0:D4}", subFolderID) + "/"; await _iPostImageDAL.UpdateImage(newImage.Id, ".jpg", mainFolder + subFolderName); //updates path and name after adding image to database if (!Directory.Exists(_environment.WebRootPath + mainFolder + subFolderName)) Directory.CreateDirectory(_environment.WebRootPath + mainFolder + subFolderName); //adding to server byte[] bytes = Convert.FromBase64String(image); var path = mainFolder + subFolderName + newImage.Id.ToString() + ".jpg"; var filePath = Path.Combine(_environment.WebRootPath + path); System.IO.File.WriteAllBytes(filePath, bytes); return true; } catch (Exception e) { throw e; } } } }
using Mis_Recetas.Controlador; 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 Mis_Recetas.Vista { public partial class FormRecetasRecibidasPorMedico : Form { public FormRecetasRecibidasPorMedico() { InitializeComponent(); } CmdReportes com = new CmdReportes(); private void FormRecetasRecibidasPorMedico_Load(object sender, EventArgs e) { CargarComboMedicos(); } private void CargarComboMedicos() { cboMedico.DataSource = com.CargarComboMedico(); cboMedico.DisplayMember = "Medico"; cboMedico.ValueMember = "Id_Medico"; } private void button1_Click(object sender, EventArgs e) { int idMed = (int)cboMedico.SelectedIndex + 1; // TODO: esta línea de código carga datos en la tabla 'dsRecetasRecibidasPorMedico.Receta' Puede moverla o quitarla según sea necesario. this.recetaTableAdapter.verRecetasRecibidasPorMedico(this.dsRecetasRecibidasPorMedico.Receta, idMed); this.reportViewer1.RefreshReport(); } } }
using Microsoft.Xna.Framework.Input; using SprintFour.Commands; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SprintFour.Controllers { public class LevelSelectController { private readonly IDictionary<Keys, ICommand> commandDictionary; public LevelSelectController() { commandDictionary = new Dictionary<Keys, ICommand> { {Keys.Up, new CursorUpCommand()}, {Keys.W, new CursorUpCommand()}, {Keys.Down, new CursorDownCommand()}, {Keys.S, new CursorDownCommand()}, {Keys.Enter, new CursorSelectCommand()}, {Keys.Space, new CursorSelectCommand()} }; } public void Update() { KeyboardState state = Keyboard.GetState(); foreach (Keys k in commandDictionary.Keys) { if (state.IsKeyDown(k)) commandDictionary[k].Execute(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; public class Program { public static void Main() { var emailsCount = int.Parse(Console.ReadLine()); var emails = new Dictionary<string, HashSet<string>>(); var validEmailPattern = @"\b(?<user>[a-zA-Z]{5,})@(?<domain>[a-z]{3,}\.(com|bg|org))\b"; for (int i = 0; i < emailsCount; i++) { var currInput = Console.ReadLine(); if (Regex.IsMatch(currInput, validEmailPattern)) { var match = Regex.Match(currInput, validEmailPattern); var user = match.Groups["user"].Value; var domain = match.Groups["domain"].Value; if (!emails.ContainsKey(domain)) { emails[domain] = new HashSet<string>(); } emails[domain].Add(user); } } foreach (var item in emails .OrderByDescending(m => m.Value.Count())) { var currDomain = item.Key; var currEmails = item.Value; Console.WriteLine($"{currDomain}:"); foreach (var currEmail in currEmails) { Console.WriteLine($"### {currEmail}"); } } } }
using MapOnly; using MapOnlyExample.Model; using MapOnlyExample.Service.ViewModel; namespace MapOnlyExample.WinformDemo { public static class MapOnlyConfig { public static void Register() { //MapExtension.Create<User, UserViewModel>(); //MapExtension.Create<User, UserDetailsViewModel>(); --> No need MapExtension.Create<UserViewModel, User>() .Ignore(u => u.CreatedDate) .Ignore(u => u.CreatedUser) .Ignore(u => u.IsActive) .Ignore(u => u.UpdatedDate) .Ignore(u => u.UpdatedUser); } } }
using System; using System.Configuration; using System.Data; //using Microsoft.Reporting.WebForms; using NETDataLuma; using Ext.Net; namespace Cool { public partial class ASPX_OE_SmarthPhone : System.Web.UI.Page { private string _perfil = string.Empty; private string _usuario = string.Empty; private DataSet z_dtsEmbaques; private ExecStoreSql _ejecutorSqlHarvester = new ExecStoreSql(ConfigurationManager.AppSettings["CON_PRODUCCION_11"], ConfigurationManager.AppSettings["BD_SIDTUM_PROD"], "http://www.tum.com.mx/datum/universal.xml");//OK A PRODUCCION protected void Page_Load(object sender, EventArgs e) { if (X.IsAjaxRequest) return; _perfil = Request.QueryString["param1"]; _usuario = Request.QueryString["param2"]; // var fechaActual = DateTime.Now; try { /* switch (_perfil) { case "NISSAN_USUARIO": z_strOperadores.DataSource = zMetConsultaOperadores(); z_strOperadores.DataBind(); break; case "NISSAN_EJECUTIVO": z_strOperadores.DataSource = zMetConsultaOperadores(); z_strOperadores.DataBind(); break; default: Response.Redirect(@"~/AccesoNoAutorizado.html"); break; }*/ } catch (Exception ex) { X.Msg.Show(new MessageBoxConfig { Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.ERROR, Title = "Error", Message = "No es posible conectarse al servidor, intente de nuevo" }); ResourceManager.AjaxSuccess = false; ResourceManager.AjaxErrorMessage = ex.Message; } } [DirectMethod] public string zMetConsultaEmbarques(string zparFolioViaje, string zparOperador, string zparFechaIni, string zparFechaFin) { string z_varstrresultado = ""; string spNombre = "ConsultaEmbarques"; try { z_dtsEmbaques = _ejecutorSqlHarvester.ExecuteSpDs("SPQRY_EmbarquesRegistradosSIDMOVIL", "Embarques", zparFolioViaje, zparOperador, zparFechaIni, zparFechaFin); if (z_dtsEmbaques != null) { if (z_dtsEmbaques.Tables["Embarques"].Rows.Count > 0) { if (z_dtsEmbaques.Tables["Embarques"].Rows[0][1].ToString() != "SQL_ERROR") { z_strBusqueda.DataSource = z_dtsEmbaques.Tables["Embarques"]; z_strBusqueda.DataBind(); z_GrdPnl_Detalle.ReRender(); z_varstrresultado = JsonResulEjec(1, "SQL_OK", spNombre, ""); } else { z_varstrresultado = JsonResulEjec(0, "SQL_ERROR", spNombre, "Error en ejecución SQL..."); } } else { z_varstrresultado = JsonResulEjec(3, "SQL_VACIO", spNombre, "No existen datos ..."); } } else { z_varstrresultado = JsonResulEjec(0, "SQL_NULL", spNombre, "Servidor de SQL no disponible..."); } } catch (Exception ex) { ExtNet.Msg.Show(new MessageBoxConfig { Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.INFO, Title = "Error", Message = JsonResulEjec(0, "SQL_ERROR", spNombre, "Error en ejecución SQL..."), }); ResourceManager.AjaxSuccess = false; ResourceManager.AjaxErrorMessage = ex.Message; } return z_varstrresultado; } protected void Store1_RefreshData(object sender, StoreReadDataEventArgs e) { if (z_dtsEmbaques!=null){ z_strBusqueda.DataSource = z_dtsEmbaques.Tables["Embarques"]; z_strBusqueda.DataBind(); } } private static string JsonResulEjec(Int16 codigo, string clave, string objeto, string observaciones) { var sbResultado = new System.Text.StringBuilder(); try { sbResultado.Append("{\"Rows\":[{"); sbResultado.Append("\"CtlCod\":" + codigo.ToString() + ","); sbResultado.Append("\"CtlCve\":\"" + clave + "\","); sbResultado.Append("\"CtlObj\":\"" + objeto + "\","); sbResultado.Append("\"CtlObs\":\"" + observaciones + "\"}]}"); } catch (Exception ex) { ExtNet.Msg.Show(new MessageBoxConfig { Buttons = MessageBox.Button.OK, Icon = MessageBox.Icon.INFO, Title = "Error", Message = "Error no Tipificado" }); ResourceManager.AjaxSuccess = false; ResourceManager.AjaxErrorMessage = ex.Message; } return sbResultado.ToString(); } private DataSet zMetConsultaOperadores() { DataSet z_dtsOperadores = new DataSet(); z_dtsOperadores = _ejecutorSqlHarvester.ExecuteSpDs("SPQRY_OperadorClaveDescripcion", "Operadores", ""); return z_dtsOperadores; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShotCursor : MonoBehaviour { [SerializeField] private Texture2D cursor; private Transform CameraTransform; public int hit_num=0; // Start is called before the first frame update void Start() { Cursor.SetCursor(cursor, new Vector2(cursor.width / 2, cursor.height / 2), CursorMode.ForceSoftware); CameraTransform = this.GetComponent<Transform>(); } // Update is called once per frame void Update() { float X_Rotation = Input.GetAxis("Mouse X"); float Y_Rotation = Input.GetAxis("Mouse Y"); CameraTransform.transform.Rotate(-Y_Rotation, X_Rotation, 0); if(Input.GetButtonDown("Fire1")) { Shot(); } } void Shot() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray, out hit, 100f, LayerMask.GetMask("Enemy"))) { Destroy(hit.collider.gameObject); hit_num++; } } }
using Breezy.Sdk.Printing; using Newtonsoft.Json; namespace Breezy.Sdk.Payloads { internal class FileUploadMessage { [JsonProperty("encrypted_symmetric_key")] public string EncryptedSymmetricKey { get; set; } [JsonProperty("encrypted_symmetric_iv")] public string EncryptedSymmetricIV { get; set; } [JsonProperty("print_options")] public PrinterSettings PrintOptions { get; set; } [JsonProperty("file")] public FileInfoMessage File { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security.Principal; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Forms; using System.ServiceProcess; using System.Threading; using System.Configuration; using SheriffLibrary; using Microsoft.Win32; using System.IO; namespace BrowserSheriffUI { public partial class MainWindow : Window { // Nazwa serwisu private readonly string serviceName; // Kontroler serwisu private ServiceController SheriffController; #region Konstruktor public MainWindow() { InitializeComponent(); // Przypisz nazwe serwisu serviceName = ConfigurationManager.AppSettings["ServiceName"]; // Jeśli aplikacja nie działa z uprawnieniami administratora, zapytaj o nie if(!IsRunAsAdmin()) { //SetAdminPrivilages(); } // Jeśli serwis jest zainstalowany zapamiętaj referencję do niego if(IsServiceInstalled(serviceName)) { SheriffController = new ServiceController() { ServiceName = serviceName }; } // Ustaw wyświetlany status serwisu SetServiceStatus(); // Jeśli ścieżka do folderu pobrane nie była zmieniana (pierwsze uruchomienie klienta) if(ConfigurationManager.AppSettings["DownloadsPath"].Equals("default")) { //string path = Environment.GetEnvironmentVariable("USERPROFILE") + @"\" + "Downloads"; string path = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders", "{374DE290-123F-4565-9164-39C4925E467B}", String.Empty).ToString(); SetDownloadsPath(path); } else { DownloadsDirectory.Text = ConfigurationManager.AppSettings["DownloadsPath"]; SetFileInformation(); } // Pokaż informacje o ostatnio uruchomionej przeglądarce ShowProcessInfo(); } #endregion #region Metody przycisków // Przycisk włączania seriwsu private void ServiceStartClick(object sender, RoutedEventArgs e) { if(!IsRunAsAdmin()) { SetAdminPrivilages(); } try { SheriffController.Start(); ServiceStartButton.IsEnabled = false; ServiceStopButton.IsEnabled = true; ChangeDirectoryButton.IsEnabled = true; SheriffState.Text = "Stan usługi: Uruchomiona"; } catch { System.Windows.MessageBox.Show("Nie mogę uruchomić usługi", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error); } } // Przycisk wyłączania serwisu private void ServiceStopClick(object sender, RoutedEventArgs e) { if(!IsRunAsAdmin()) { SetAdminPrivilages(); } try { SheriffController.Stop(); ServiceStartButton.IsEnabled = true; ServiceStopButton.IsEnabled = false; ChangeDirectoryButton.IsEnabled = false; SheriffState.Text = "Stan usługi: Zatrzymana"; } catch { System.Windows.MessageBox.Show("Nie mogę uruchomić usługi", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error); } } // Przycisk odświeżania private void RefreshButtonClick(object sender, RoutedEventArgs e) { SetServiceStatus(); SetFileInformation(); } // Przycisk zmiany katalogu private void ChangeDirectoryClick(object sedner, RoutedEventArgs e) { using(var fbd = new FolderBrowserDialog()) { DialogResult result = fbd.ShowDialog(); if(result == System.Windows.Forms.DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { // Ustaw nową ścieżke folderu Pobrane SetDownloadsPath(fbd.SelectedPath); } } } // Przycisk pokazania logów private async void ShowLogsClick(object sender, RoutedEventArgs e) { await WriteLogsAsync(); } // Przycisk czyszczenia logów private void WipeLogsClick(object sender, RoutedEventArgs e) { EventLog Log = new EventLog(ConfigurationManager.AppSettings["LogName"]) { Source = ConfigurationManager.AppSettings["LogSource"] }; Logs.Text = ""; Log.Clear(); } // Przycisk otwierania katalogu private void OpenDirectoryClick(object sender, RoutedEventArgs e) { Process.Start("explorer.exe", DownloadsDirectory.Text); } // Przycisk uruchamiania przeglądarki private void RunBrowserClick(object sender, RoutedEventArgs e) { switch(Browser.SelectedIndex) { case 0: try { // Uruchom przeglądarke Process browser = Process.Start("chrome.exe", BrowserUrl.Text); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Pobierz nazwe procesu config.AppSettings.Settings["ProcessName"].Value = browser.ProcessName; config.Save(ConfigurationSaveMode.Modified); } catch { System.Windows.MessageBox.Show("Nie można otworzyć przeglądarki", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error); } break; case 1: try { // Uruchom przeglądarke Process browser = Process.Start("firefox.exe", BrowserUrl.Text); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Pobierz nazwe procesu config.AppSettings.Settings["ProcessName"].Value = browser.ProcessName; config.Save(ConfigurationSaveMode.Modified); } catch { System.Windows.MessageBox.Show("Nie można otworzyć przeglądarki", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error); } break; case 2: try { // Uruchom przeglądarke Process browser = Process.Start("IExplore.exe", BrowserUrl.Text); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Pobierz nazwe procesu config.AppSettings.Settings["ProcessName"].Value = browser.ProcessName; ; config.Save(ConfigurationSaveMode.Modified); } catch { System.Windows.MessageBox.Show("Nie można otworzyć przeglądarki", "Błąd", MessageBoxButton.OK, MessageBoxImage.Error); } break; } ShowProcessInfo(); } // Przycisk aktualizacji procesu przeglądarki private void UpdateProcessClick(object sender, RoutedEventArgs e) { ShowProcessInfo(); } #endregion #region Metody użytkowe // Wypisz logi asynchronicznie private async Task WriteLogsAsync() { EventLog Log = new EventLog(ConfigurationManager.AppSettings["LogName"]) { Source = ConfigurationManager.AppSettings["LogSource"] }; Logs.Text = ""; switch(LogsType.SelectedIndex) { case 0: foreach(EventLogEntry LogEntry in Log.Entries) { string logMessage = await Task.Run(() => LogEntry.Message); Logs.Text = logMessage + "\n" + Logs.Text; } break; case 1: foreach(EventLogEntry LogEntry in Log.Entries) { if(LogEntry.EntryType == EventLogEntryType.Information) { string logMessage = await Task.Run(() => LogEntry.Message); Logs.Text = logMessage + "\n" + Logs.Text; } } break; case 2: foreach(EventLogEntry LogEntry in Log.Entries) { if(LogEntry.EntryType == EventLogEntryType.Error) { string logMessage = await Task.Run(() => LogEntry.Message); Logs.Text = logMessage + "\n" + Logs.Text; } } break; case 3: foreach(EventLogEntry LogEntry in Log.Entries) { if(LogEntry.EntryType == EventLogEntryType.Warning) { string logMessage = await Task.Run(() => LogEntry.Message); Logs.Text = logMessage + "\n" + Logs.Text; } } break; } } // Ustaw uprawnienia administratora private void SetAdminPrivilages() { ProcessStartInfo proc = new ProcessStartInfo { UseShellExecute = true, WorkingDirectory = System.Windows.Forms.Application.StartupPath, FileName = System.Windows.Forms.Application.ExecutablePath, Verb = "runas" }; try { Process.Start(proc); Close(); } catch { return; } } // Ustaw ścieżke do katalogu pobrane ( w aplikacji i plikach konfiguracyjnych aplikacji i serwisu) private void SetDownloadsPath(string path) { //*** Klient ***// // Otwórz plik konfiguracyjny Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Wpisz domyślną ścieżkę folderu Pobrane config.AppSettings.Settings["DownloadsPath"].Value = path; // Zapisz zmiany config.Save(ConfigurationSaveMode.Modified); //*** Serwis ***// // Otworz plik konfiguracyjny serwisu ExeConfigurationFileMap configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = @"C:\Program Files (x86)\Lashu\Browser Sheriff\BrowserSheriffService.exe.config" }; Configuration serviceConfig = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); // // Ustaw scieżke do pobranych w pliku konfiguracyjnym serwisu serviceConfig.AppSettings.Settings["DownloadsPath"].Value = path; // Zapisz zmiany serviceConfig.Save(ConfigurationSaveMode.Modified); if(SheriffState.Text.Equals("Stan usługi: Uruchomiona")) { // Zresetuj usługę SheriffController.Stop(); Thread.Sleep(100); SheriffController.Start(); } // Ustaw wyświetlaną ścieżkę katalogu pobrane DownloadsDirectory.Text = path; SetFileInformation(); } // Sprawdź czy aplikacja jest uruchomiona z prawami administratora private bool IsRunAsAdmin() { WindowsIdentity id = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(id); return principal.IsInRole(WindowsBuiltInRole.Administrator); } // Sprawdź czy istnieje serwis o zadanej nazwie private bool IsServiceInstalled(string serviceName) { return ServiceController.GetServices().Any(serviceController => serviceController.ServiceName.Equals(serviceName)); } // Ustaw status usługi private void SetServiceStatus() { if(IsServiceInstalled(serviceName)) { SheriffController = new ServiceController() { ServiceName = serviceName }; switch(SheriffController.Status) { case ServiceControllerStatus.Running: SheriffState.Text = "Stan usługi: Uruchomiona"; ServiceStartButton.IsEnabled = false; ServiceStopButton.IsEnabled = true; ChangeDirectoryButton.IsEnabled = true; break; default: SheriffState.Text = "Stan usługi: Zatrzymana"; ServiceStartButton.IsEnabled = true; ServiceStopButton.IsEnabled = false; ChangeDirectoryButton.IsEnabled = false; break; } } else { SheriffState.Text = "Stan usługi: Niezainstalowana"; ServiceStartButton.IsEnabled = false; ServiceStopButton.IsEnabled = false; ChangeDirectoryButton.IsEnabled = false; } } // Wyświetl informacje o katalogu pobrane private void SetFileInformation() { string path = DownloadsDirectory.Text; int fileCount = Directory.GetFiles(path, "*", SearchOption.TopDirectoryOnly).Length; int dirCount = Directory.GetDirectories(path, "*", SearchOption.TopDirectoryOnly).Length; // Ustaw ilość plików katalogu pobrane FileCount.Text = (fileCount + dirCount).ToString(); SpaceTaken.Text = (DirSize(new DirectoryInfo(path)) / 1000000).ToString() + "MB"; } // Zwróć rozmiar katalogu private long DirSize(DirectoryInfo d) { long size = 0; // Add file sizes. FileInfo[] fis = d.GetFiles(); foreach(FileInfo fi in fis) { size += fi.Length; } // Add subdirectory sizes. DirectoryInfo[] dis = d.GetDirectories(); foreach(DirectoryInfo di in dis) { size += DirSize(di); } return (size); } // Pokaż informacje o procesie przeglądarki private void ShowProcessInfo() { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); string processName = config.AppSettings.Settings["ProcessName"].Value; try { Process browser = Process.GetProcessesByName(processName)[0]; ProcessName.Text = browser.ProcessName; ProcessID.Text = browser.Id.ToString(); ProcessMemory.Text = (browser.WorkingSet64 / 1000000).ToString() + "MB"; ProcessStartTime.Text = browser.StartTime.ToString(); } catch { ProcessName.Text = ""; ProcessID.Text = ""; ProcessMemory.Text = ""; ProcessStartTime.Text = ""; } } #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Configuration; using Newtonsoft.Json.Linq; using PowerBI.Models; using PowerBI.Web.Models; namespace PowerBI.Web.Controllers { public class LoginController : Controller { HttpClient client = new HttpClient(); private readonly IConfiguration _config; public LoginController(IConfiguration config) { _config = config; } [HttpGet] public IActionResult Login() { return View(); } [HttpPost] public IActionResult Login(LoginModel login) { if (ModelState.IsValid) { string BaseAddress= _config.GetValue<string>("BaseUrl:BaseAddress"); client.DefaultRequestHeaders.Add("Authorization", "Basic " + "YWRpZGFhczpEaXN5c0AzMjE="); HttpResponseMessage response = client.GetAsync(BaseAddress + "?UserName=" + login.Username + "&Password=" + login.Password).Result; var results = response.Content.ReadAsStringAsync().Result; JObject jsons = JObject.Parse(results); string username = jsons["user_Name"].ToString(); if (username != "" & response.IsSuccessStatusCode) { return RedirectToAction("index", "Dashboard"); } else { ModelState.AddModelError("Invalid Error", "Invalid username and password"); } } return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using DevExpress.XtraEditors; using DevExpress.XtraCharts; namespace Tes4.GUI.Report { public partial class Reader : DevExpress.XtraEditors.XtraForm { public Income income; public List<SeriesPoint> series_data; ChartControl chartControl1; public Reader(List<SeriesPoint> series) { InitializeComponent(); series_data = new List<SeriesPoint>(); income = new Income(); series_data = series; create_Bar_Chart(); } public void create_Bar_Chart() { chartControl1 = new ChartControl(); Series series1 = new Series("Doanh số", ViewType.Bar); //Legend Format chartControl1.Legend.Title.Alignment = StringAlignment.Near; chartControl1.Legend.Visible = true; chartControl1.Legend.Title.MaxLineCount = 3; chartControl1.Legend.Title.WordWrap = true; foreach (SeriesPoint se in series_data) { series1.Points.Add(se); } chartControl1.Series.Add(series1); XYDiagram diagram = (XYDiagram)chartControl1.Diagram; ((XYDiagram)chartControl1.Diagram).AxisX.QualitativeScaleOptions.AutoGrid = true; ((XYDiagram)chartControl1.Diagram).AxisX.QualitativeScaleOptions.GridSpacing = 3; AxisLabel axisLabel = ((XYDiagram)chartControl1.Diagram).AxisX.Label; //Label settings column X diagram.AxisX.WholeRange.Auto = true; axisLabel.TextPattern = "{A:dd-MM}"; axisLabel.ResolveOverlappingOptions.AllowHide = true; axisLabel.ResolveOverlappingOptions.AllowRotate = true; axisLabel.ResolveOverlappingOptions.AllowStagger = true; axisLabel.ResolveOverlappingOptions.MinIndent = 5; axisLabel.Staggered = true; chartControl1.Legend.AlignmentHorizontal = LegendAlignmentHorizontal.Right; chartControl1.Legend.AlignmentVertical = LegendAlignmentVertical.Top; ((XYDiagram)chartControl1.Diagram).AxisY.Visibility = DevExpress.Utils.DefaultBoolean.True; //Display text On each colummn chartControl1.Series[0].LabelsVisibility = DevExpress.Utils.DefaultBoolean.True; BarSeriesLabel seriesLabel = chartControl1.Series[0].Label as BarSeriesLabel; seriesLabel.BackColor = Color.White; seriesLabel.Border.Color = Color.DarkSlateGray; seriesLabel.Font = new Font("Tahoma", 10, FontStyle.Regular); seriesLabel.Position = BarSeriesLabelPosition.TopInside; seriesLabel.TextOrientation = TextOrientation.Horizontal; seriesLabel.TextPattern = "{V}"; chartControl1.Dock = DockStyle.Fill; this.Controls.Add(chartControl1); } } }
namespace ShogunOptimizer.Characters { public class Kokomi : Character { public Kokomi() { BaseHp = 13471; BaseAtk = 234; BaseDef = 657; AscensionStat = .288; AscensionStatType = StatType.HydroDmgBonus; Stats[(int)StatType.HealBonus] += .25; Stats[(int)StatType.CritRate] -= 1; } public const string PropertyAttack1 = "attack1"; public const string PropertyAttack2 = "attack2"; public const string PropertyAttack3 = "attack3"; public const string PropertyCharged = "charged"; public const string PropertySkillDamage = "skillDamage"; public const string PropertySkillHealing = "skillHealing"; public const string PropertyBurstInitial = "burstInitial"; public const string PropertyBurstAttack1 = "burstAttack1"; public const string PropertyBurstAttack2 = "burstAttack2"; public const string PropertyBurstAttack3 = "burstAttack3"; public const string PropertyBurstAttack3C1 = "burstC1"; public const string PropertyBurstCharged = "burstCharged"; public const string PropertyBurstSkillDamage = "burstSkillDamage"; public const string PropertyBurstHealing = "burstHealing"; public override double Calculate(string property, Build build, HitType hitType, Enemy enemy) { switch (property) { case PropertyAttack1: return CalculateDamage(build, (0.6838 * GetTalentAttackScaling(AttackLevel)) * GetAtk(build), DamageType.Normal, Element.Hydro, hitType, enemy); case PropertyAttack2: return CalculateDamage(build, (0.6154 * GetTalentAttackScaling(AttackLevel)) * GetAtk(build), DamageType.Normal, Element.Hydro, hitType, enemy); case PropertyAttack3: return CalculateDamage(build, (0.9431 * GetTalentAttackScaling(AttackLevel)) * GetAtk(build), DamageType.Normal, Element.Hydro, hitType, enemy); case PropertyCharged: return CalculateDamage(build, (1.4832 * GetTalentAttackScaling(AttackLevel)) * GetAtk(build), DamageType.Charged, Element.Hydro, hitType, enemy); case PropertySkillDamage: return CalculateDamage(build, (1.0919 * GetTalentPercentageScaling(SkillLevel)) * GetAtk(build), DamageType.Skill, Element.Hydro, hitType, enemy); case PropertySkillHealing: return (0.044 * GetTalentPercentageScaling(SkillLevel)) * GetMaxHp(build) + (424 * GetTalentFlatScaling(SkillLevel)) * (1 + GetStat(StatType.HealBonus, build)); case PropertyBurstInitial: return CalculateDamage(build, (0.1042 * GetTalentPercentageScaling(BurstLevel)) * GetMaxHp(build), DamageType.Burst, Element.Hydro, hitType, enemy); case PropertyBurstAttack1: return (0.0484 * GetTalentPercentageScaling(BurstLevel) * GetMaxHp(build)) + Calculate(PropertyAttack1, build, hitType, enemy); case PropertyBurstAttack2: return (0.0484 * GetTalentPercentageScaling(BurstLevel) * GetMaxHp(build)) + Calculate(PropertyAttack2, build, hitType, enemy); case PropertyBurstAttack3: return (0.0484 * GetTalentPercentageScaling(BurstLevel) * GetMaxHp(build)) + Calculate(PropertyAttack3, build, hitType, enemy); case PropertyBurstAttack3C1: return CalculateDamage(build, 0.3 * GetMaxHp(build), DamageType.None, Element.Hydro, hitType, enemy); case PropertyBurstCharged: return (0.0678 * GetMaxHp(build) * GetTalentPercentageScaling(BurstLevel)) + Calculate(PropertyCharged, build, hitType, enemy); case PropertyBurstSkillDamage: return (0.071 * GetMaxHp(build) * GetTalentPercentageScaling(BurstLevel)) + Calculate(PropertySkillDamage, build, hitType, enemy); case PropertyBurstHealing: return (0.0081 * GetTalentPercentageScaling(SkillLevel)) * GetMaxHp(build) + (77 * GetTalentFlatScaling(SkillLevel)) * (1 + GetStat(StatType.HealBonus, build)); default: return base.Calculate(property, build, hitType, enemy); } } public override double CalculateStat(StatType statType, Build build) { var stat = base.CalculateStat(statType, build); switch (statType) { case StatType.AttackDmgBonus: case StatType.ChargedDmgBonus: stat += .15 * GetStat(StatType.HealBonus, build); break; } return stat; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Game { class Yakın:Silah { int mesafe; public int Mesafe { get { return mesafe; } set { mesafe = value; } } } }
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using KaVE.VS.FeedbackGenerator.SessionManager.Presentation; using NUnit.Framework; namespace KaVE.VS.FeedbackGenerator.Tests.SessionManager.Presentation { internal class JsonSyntaxHighlighterTest { [Test] public void ShouldHighlightNull() { const string origin = "null"; const string expected = origin; var actual = origin.AddJsonSyntaxHighlightingWithXaml(); Assert.AreEqual(expected, actual); } [TestCase("true"), TestCase("false")] public void ShouldHighlightBooleans(string origin) { var expected = origin; var actual = origin.AddJsonSyntaxHighlightingWithXaml(); Assert.AreEqual(expected, actual); } [TestCase("0"), TestCase("17"), TestCase("-42"), TestCase("2.3"), TestCase("-3.14")] public void ShouldHighlightNumbers(string origin) { var expected = origin; var actual = origin.AddJsonSyntaxHighlightingWithXaml(); Assert.AreEqual(expected, actual); } [Test] public void ShouldHighlightStrings() { const string origin = "\"Hello World!\""; const string expected = origin; var actual = origin.AddJsonSyntaxHighlightingWithXaml(); Assert.AreEqual(expected, actual); } [Test] public void ShouldHighlightKeys() { const string origin = "\"That's a key because it's surrounded by double-quotes and is followed by a colon\":"; const string expected = "<Bold>\"That's a key because it's surrounded by double-quotes and is followed by a colon\":</Bold>"; var actual = origin.AddJsonSyntaxHighlightingWithXaml(); Assert.AreEqual(expected, actual); } [Test] public void ShouldHighlightAllTogether() { const string origin = "{\"string-key\": \"string value\", \"null-key\": null, \"bool-key\": true, \"number-key\": 42}"; const string expected = "{<Bold>\"string-key\":</Bold> \"string value\", " + "<Bold>\"null-key\":</Bold> null, " + "<Bold>\"bool-key\":</Bold> true, " + "<Bold>\"number-key\":</Bold> 42}"; var actual = origin.AddJsonSyntaxHighlightingWithXaml(); Assert.AreEqual(expected, actual); } } }
using UnityEngine; using System.Collections; namespace HWREfx { public class ParticleSetting : MonoBehaviour { public float LightIntensityMult = -0.5f; public float LifeTime = 1; public bool RandomRotation = false; public Vector3 PositionOffset; public GameObject SpawnEnd; public float Scale = 1; private float timetemp; void Start () { timetemp = Time.time; if (RandomRotation) { this.gameObject.transform.rotation = Random.rotation; } SetScale (this.transform); foreach (Transform child in this.transform) { SetScale (child); } } void Update () { if (Time.time > timetemp + LifeTime) { if (SpawnEnd) { GameObject obj = (GameObject)GameObject.Instantiate (SpawnEnd, this.transform.position, this.transform.rotation); } GameObject.Destroy (this.gameObject); } if (this.gameObject.GetComponent<Light>()) { this.GetComponent<Light>().intensity += LightIntensityMult * Time.deltaTime; } } void SetScale (Transform obj) { obj.localScale *= Scale; if (obj.gameObject.GetComponent <Light> ()) { obj.gameObject.GetComponent <Light> ().range *= Scale; } if (obj.GetComponent <ParticleSystem> ()) { ParticleSystem particle = obj.GetComponent<ParticleSystem> (); particle.startSpeed *= Scale; particle.startSize *= Scale; particle.gravityModifier *= Scale; } } } }
using System; using System.Linq; using System.Windows.Forms; using Relocation.Com; using Relocation.Data; using Relocation.UI.Interface; using Relocation.Base; namespace Relocation.UI { public partial class ProjectList : BaseProjectList, IPrintForm { public ProjectList() : base() { InitializeComponent(); Initialize(); } public ProjectList(Session session) : base(session) { InitializeComponent(); Initialize(); } private void Initialize() { this.S_Field_EnableData.Tag = new ControlTag(null, null, new SearchInfo(Project.GetPropName(t=>t.created), SearchInfo.SearchFieldTypes.DateTime)); this.S_Field_Name.Tag = new ControlTag(null, null, new SearchInfo(Project.GetPropName(t => t.name))); this.S_Field_Org.Tag = new ControlTag(null, null, new SearchInfo(Project.GetPropName(t => t.organization))); this.SortField = Project.GetPropName(t => t.updated); this.ObjectQuery = this.Session.DataModel.Projects; } private void ButtonAdd_Click(object sender, EventArgs e) { try { using (ProjectsWindow projectWindow = new ProjectsWindow(this.Session)) { if (DialogResult.OK.Equals(projectWindow.ShowDialog())) this.Reload(); } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); System.Diagnostics.Debug.WriteLine(ex); this.MessageBoxShowInfo("操作失败!"); } } private void ButtonEdit_Click(object sender, EventArgs e) { try { Project project = this.GetSelectEntity(); if (project != null) { using (ProjectsWindow projectWindow = new ProjectsWindow(this.Session, project)) { if (DialogResult.OK.Equals(projectWindow.ShowDialog())) { this.Reload(); } } } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); System.Diagnostics.Debug.WriteLine(ex); this.MessageBoxShowInfo("操作失败!"); } } private void ButtonDel_Click(object sender, EventArgs e) { try { Project entity = this.GetSelectEntity(); if (entity == null) return; if (entity.project_id.Equals(this.Session.Project.project_id)) { MessageBoxShowInfo("该项目是当前项目,不允许删除!"); return; } if (entity.IsUsed()) { MessageBoxShowInfo("该项目下已包含拆迁户数据,不允许删除!"); return; } this.DeleteEntity(entity); } catch (Exception ex) { this.Log.Error(ex.GetInnerExceptionMessage()); MessageBoxError("记录删除失败!"); } } #region IPrintForm 成员 public void Print() { this.print(this.dataGridView1); } #endregion private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { try { string _name = this.dataGridView1.Columns[e.ColumnIndex].Name; if (!string.IsNullOrEmpty(_name) && _name.Equals(this.Files.Name)) { Project project = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as Project; if (project != null) { project.LoadFiles(); if (project.Files.Any(t => t.file_type == 1)) e.Value = "红线规划图"; else e.Value = "没有文件"; e.FormattingApplied = true; } } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); System.Diagnostics.Debug.WriteLine(ex); } } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { try { string _name = this.dataGridView1.Columns[e.ColumnIndex].Name; if (_name.Equals(this.Files.Name)) { Project project = this.dataGridView1.Rows[e.RowIndex].DataBoundItem as Project; if (project == null) return; using (ProjectPic ProjectPic = new ProjectPic(this.Session, project)) { ProjectPic.ShowDialog(); } } } catch (Exception ex) { Log.Error(ex.GetInnerExceptionMessage()); System.Diagnostics.Debug.WriteLine(ex); this.MessageBoxShowInfo("操作失败!"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace YoctoScheduler.Core.Database { [AttributeUsage(System.AttributeTargets.Property)] public class DatabaseProperty : Attribute { public string DatabaseName; public int Size; } [AttributeUsage(System.AttributeTargets.Class)] public class DatabaseKey : Attribute { public string DatabaseName; public int Size; } }
using System.Configuration; namespace SimpleShooter { static class Config { public static bool IsSoundOn { get { return ConfigurationManager.AppSettings["enableSound"] == bool.TrueString; } } public static bool ShowBoundingBox { get { return ConfigurationManager.AppSettings["showBox"] == bool.TrueString; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief テスト。 */ /** test03 UNIVRM。 */ public class test03 : main_base , NEventPlate.OnOverCallBack_Base { /** 削除管理。 */ private NDeleter.Deleter deleter; /** button */ private NUi.Button button; /** inputfield */ private NRender2D.InputField2D inputfield; /** bg */ private NRender2D.Sprite2D bg; /** bone */ private HumanBodyBones[] bone_index; private NRender2D.Sprite2D[] bone_sprite; private NRender2D.Text2D[] bone_name; private NEventPlate.Item[] bone_eventplate; /** ステータス。 */ private NRender2D.Text2D status; /** ロードアイテム。 */ private NFile.Item load_item; /** VRMアイテム。 */ private NUniVrm.Item vrm_item; private bool vrm_item_load; /** バイナリ。 */ private byte[] binary; /** mycamera */ private GameObject mycamera_gameobject; private Camera mycamera_camera; /** LayerIndex */ enum LayerIndex { LayerIndex_Bg = 0, LayerIndex_Model = 0, LayerIndex_Ui = 1, }; /** drawpriority */ long drawpriority_bg; long drawpriority_mode; long drawpriority_ui; long drawpriority_ui2; /** Start */ private void Start() { //タスク。インスタンス作成。 NTaskW.TaskW.CreateInstance(); //パフォーマンスカウンター。インスタンス作成。 NPerformanceCounter.Config.LOG_ENABLE = true; NPerformanceCounter.PerformanceCounter.CreateInstance(); //2D描画。インスタンス作成。 NRender2D.Render2D.CreateInstance(); //マウス。インスタンス作成。 NInput.Mouse.CreateInstance(); //キー。インスタンス作成。 NInput.Key.CreateInstance(); //イベントプレート。インスタンス作成。 NEventPlate.EventPlate.CreateInstance(); //UI。インスタンス作成。 NUi.Ui.CreateInstance(); //ファイル。インスタンス作成。 NFile.File.CreateInstance(); //UNIVRM。インスタンス作成。 NUniVrm.UniVrm.CreateInstance(); //削除管理。 this.deleter = new NDeleter.Deleter(); //戻るボタン作成。 this.CreateReturnButton(this.deleter,(NRender2D.Render2D.MAX_LAYER - 1) * NRender2D.Render2D.DRAWPRIORITY_STEP); //drawpriority this.drawpriority_bg = (int)LayerIndex.LayerIndex_Bg * NRender2D.Render2D.DRAWPRIORITY_STEP; this.drawpriority_mode = (int)LayerIndex.LayerIndex_Model * NRender2D.Render2D.DRAWPRIORITY_STEP; this.drawpriority_ui = (int)LayerIndex.LayerIndex_Ui * NRender2D.Render2D.DRAWPRIORITY_STEP; this.drawpriority_ui2 = ((int)LayerIndex.LayerIndex_Ui + 1) * NRender2D.Render2D.DRAWPRIORITY_STEP; { //button this.button = new NUi.Button(this.deleter,null,this.drawpriority_ui,this.CallBack_Click,0); this.button.SetRect(130,10,50,50); this.button.SetTexture(Resources.Load<Texture2D>("button")); this.button.SetText("Load"); //inputfield this.inputfield = new NRender2D.InputField2D(this.deleter,null,this.drawpriority_ui); this.inputfield.SetRect(130 + 50 + 10,10,700,50); this.inputfield.SetText("https://bbbproject.sakura.ne.jp/www/project_webgl/fee/StreamingAssets/nana.vrmx"); this.inputfield.SetMultiLine(false); //ステータス。 this.status = new NRender2D.Text2D(this.deleter,null,this.drawpriority_ui); this.status.SetRect(100,100,0,0); //bone { this.bone_index = new HumanBodyBones[]{ HumanBodyBones.Hips, HumanBodyBones.LeftUpperLeg, HumanBodyBones.RightUpperLeg, HumanBodyBones.LeftLowerLeg, HumanBodyBones.RightLowerLeg, HumanBodyBones.LeftFoot, HumanBodyBones.RightFoot, HumanBodyBones.Spine, HumanBodyBones.Chest, HumanBodyBones.Neck, HumanBodyBones.Head, HumanBodyBones.LeftShoulder, HumanBodyBones.RightShoulder, HumanBodyBones.LeftUpperArm, HumanBodyBones.RightUpperArm, HumanBodyBones.LeftLowerArm, HumanBodyBones.RightLowerArm, HumanBodyBones.LeftHand, HumanBodyBones.RightHand, HumanBodyBones.LeftToes, HumanBodyBones.RightToes, HumanBodyBones.LeftEye, HumanBodyBones.RightEye, HumanBodyBones.Jaw, HumanBodyBones.LeftThumbProximal, HumanBodyBones.LeftThumbIntermediate, HumanBodyBones.LeftThumbDistal, HumanBodyBones.LeftIndexProximal, HumanBodyBones.LeftIndexIntermediate, HumanBodyBones.LeftIndexDistal, HumanBodyBones.LeftMiddleProximal, HumanBodyBones.LeftMiddleIntermediate, HumanBodyBones.LeftMiddleDistal, HumanBodyBones.LeftRingProximal, HumanBodyBones.LeftRingIntermediate, HumanBodyBones.LeftRingDistal, HumanBodyBones.LeftLittleProximal, HumanBodyBones.LeftLittleIntermediate, HumanBodyBones.LeftLittleDistal, HumanBodyBones.RightThumbProximal, HumanBodyBones.RightThumbIntermediate, HumanBodyBones.RightThumbDistal, HumanBodyBones.RightIndexProximal, HumanBodyBones.RightIndexIntermediate, HumanBodyBones.RightIndexDistal, HumanBodyBones.RightMiddleProximal, HumanBodyBones.RightMiddleIntermediate, HumanBodyBones.RightMiddleDistal, HumanBodyBones.RightRingProximal, HumanBodyBones.RightRingIntermediate, HumanBodyBones.RightRingDistal, HumanBodyBones.RightLittleProximal, HumanBodyBones.RightLittleIntermediate, HumanBodyBones.RightLittleDistal, HumanBodyBones.UpperChest, }; this.bone_sprite = new NRender2D.Sprite2D[this.bone_index.Length]; this.bone_name = new NRender2D.Text2D[this.bone_index.Length]; this.bone_eventplate = new NEventPlate.Item[this.bone_index.Length]; for(int ii=0;ii<this.bone_index.Length;ii++){ this.bone_sprite[ii] = new NRender2D.Sprite2D(this.deleter,null,this.drawpriority_ui + ii); this.bone_sprite[ii].SetTexture(Resources.Load<Texture2D>("maru")); this.bone_sprite[ii].SetTextureRect(ref NRender2D.Render2D.TEXTURE_RECT_MAX); this.bone_sprite[ii].SetRect(0,0,50,20); this.bone_sprite[ii].SetMaterialType(NRender2D.Config.MaterialType.Alpha); this.bone_sprite[ii].SetVisible(false); this.bone_name[ii] = new NRender2D.Text2D(this.deleter,null,this.drawpriority_ui + ii); this.bone_name[ii].SetText(this.bone_index[ii].ToString()); this.bone_name[ii].SetRect(0,0,0,0); this.bone_name[ii].SetVisible(false); this.bone_eventplate[ii] = new NEventPlate.Item(this.deleter,NEventPlate.EventType.Button,this.drawpriority_ui + ii); this.bone_eventplate[ii].SetOnOverCallBack(this); this.bone_eventplate[ii].SetOnOverCallBackValue(ii); this.bone_eventplate[ii].SetRect(0,0,50,20); this.bone_eventplate[ii].SetEnable(false); } } } //bg { this.bg = new NRender2D.Sprite2D(this.deleter,null,this.drawpriority_bg); this.bg.SetTexture(Texture2D.whiteTexture); this.bg.SetTextureRect(ref NRender2D.Render2D.TEXTURE_RECT_MAX); this.bg.SetRect(ref NRender2D.Render2D.VIRTUAL_RECT_MAX); this.bg.SetColor(0.1f,0.1f,0.1f,1.0f); } //load_item this.load_item = null; //vrm this.vrm_item = null; this.vrm_item_load = false; //binary this.binary = null; //カメラ。 this.mycamera_gameobject = GameObject.Find("Main Camera"); this.mycamera_camera = this.mycamera_gameobject.GetComponent<Camera>(); if(this.mycamera_camera != null){ //クリアしない。 this.mycamera_camera.clearFlags = CameraClearFlags.Depth; //モデルだけを表示。 this.mycamera_camera.cullingMask = (1 << LayerMask.NameToLayer("Model")); //デプスを2D描画の合わせる。 this.mycamera_camera.depth = NRender2D.Render2D.GetInstance().GetCameraAfterDepth((int)LayerIndex.LayerIndex_Model); } } /** [Button_Base]コールバック。クリック。 */ private void CallBack_Click(int a_id) { if((this.load_item == null)&&(this.binary == null)){ GameObject t_model = GameObject.Find("Model"); if(t_model != null){ GameObject.Destroy(t_model); } #if(true) this.load_item = NFile.File.GetInstance().RequestDownLoadBinaryFile(this.inputfield.GetText(),null,NFile.ProgressMode.DownLoad); #else this.load_item = NFile.File.GetInstance().RequestLoadStreamingAssetsBinaryFile("nana.vrmx"); #endif } } /** [NEventPlate.OnOverCallBack_Base]イベントプレートに入場。 */ public void OnOverEnter(int a_value) { this.bone_name[a_value].SetDrawPriority(this.drawpriority_ui2); this.bone_name[a_value].SetColor(1.0f,0.0f,0.0f,1.0f); } /** [NEventPlate.OnOverCallBack_Base]イベントプレートから退場。 */ public void OnOverLeave(int a_value) { this.bone_name[a_value].SetDrawPriority(this.drawpriority_ui + a_value); this.bone_name[a_value].SetColor(1.0f,1.0f,1.0f,1.0f); } /** FixedUpdate */ private void FixedUpdate() { //マウス。 NInput.Mouse.GetInstance().Main(NRender2D.Render2D.GetInstance()); //キー。 NInput.Key.GetInstance().Main(); //イベントプレート。 NEventPlate.EventPlate.GetInstance().Main(NInput.Mouse.GetInstance().pos.x,NInput.Mouse.GetInstance().pos.y); //UI。 NUi.Ui.GetInstance().Main(); //ファイル。 NFile.File.GetInstance().Main(); //UNIVRM。 NUniVrm.UniVrm.GetInstance().Main(); if(this.load_item != null){ if(this.load_item.IsBusy() == true){ //ダウンロード中。 this.status.SetText("Load : " + this.load_item.GetResultProgress().ToString()); //キャンセル。 if(this.IsChangeScene() == true){ this.load_item.Cancel(); } }else{ //ダウンロード完了。 if(this.load_item.GetResultType() == NFile.Item.ResultType.Binary){ this.status.SetText("Load : Fix"); this.binary = this.load_item.GetResultBinary(); }else{ this.status.SetText("Load : Error"); } this.load_item = null; } } if(this.vrm_item_load == true){ if(this.vrm_item != null){ if(this.vrm_item.IsBusy() == true){ //ロード中。 this.status.SetText("LoavVrm : " + this.vrm_item.GetResultProgress().ToString()); //キャンセル。 if(this.IsChangeScene() == true){ this.vrm_item.Cancel(); } }else{ //ロード完了。 if(this.vrm_item.GetResultType() == NUniVrm.Item.ResultType.Context){ this.status.SetText("LoavVrm : Fix"); //レイヤー。設定。 this.vrm_item.SetLayer("Model"); //表示。設定。 this.vrm_item.SetRendererEnable(true); //アニメータコントローラ。設定。 this.vrm_item.SetAnimatorController(Resources.Load<RuntimeAnimatorController>("Anime/AnimatorController")); }else{ this.status.SetText("LoavVrm : Error"); } this.vrm_item_load = false; } } } if(this.binary != null){ this.status.SetText("Create : size = " + this.binary.Length.ToString()); { if(this.vrm_item != null){ this.vrm_item.Delete(); this.vrm_item = null; } this.vrm_item = NUniVrm.UniVrm.GetInstance().Request(this.binary); this.vrm_item_load = true; } this.binary = null; } //マウスイベント。 if(NInput.Mouse.GetInstance().left.down == true){ if(this.vrm_item != null){ if(this.vrm_item.IsBusy() == false){ this.vrm_item.SetAnime(Animator.StringToHash("Base Layer.standing_walk_forward_inPlace")); } } }else if(NInput.Key.GetInstance().enter.down == true){ if(this.vrm_item != null){ if(this.vrm_item.IsBusy() == false){ if(this.vrm_item.IsAnimeEnable() == true){ this.vrm_item.SetAnimeEnable(false); }else{ this.vrm_item.SetAnimeEnable(true); } } } } //カメラを回す。 if(this.vrm_item != null){ if(this.vrm_item.IsAnimeEnable() == true){ if(this.mycamera_gameobject != null){ float t_time = Time.realtimeSinceStartup / 3; Vector3 t_position = new Vector3(Mathf.Sin(t_time) * 2.0f,1.0f,Mathf.Cos(t_time) * 2.0f); Transform t_camera_transform = this.mycamera_gameobject.GetComponent<Transform>(); t_camera_transform.position = t_position; t_camera_transform.LookAt(new Vector3(0.0f,1.0f,0.0f)); } } } int t_none_index = 0; for(int ii=0;ii<this.bone_sprite.Length;ii++){ Transform t_transcorm_hand = null; if(this.vrm_item != null){ if(this.mycamera_camera != null){ t_transcorm_hand = this.vrm_item.GetBoneTransform(this.bone_index[ii]); } } if(t_transcorm_hand != null){ //位置。 Vector3 t_position = t_transcorm_hand.position; //スクリーン座標計算。 { int t_x; int t_y; NRender2D.Render2D.GetInstance().WorldToVirtualScreen(this.mycamera_camera,ref t_position,out t_x,out t_y); this.bone_sprite[ii].SetVisible(true); this.bone_sprite[ii].SetX(t_x - this.bone_sprite[ii].GetW()/2); this.bone_sprite[ii].SetY(t_y - this.bone_sprite[ii].GetH()/2); this.bone_name[ii].SetVisible(true); this.bone_name[ii].SetRect(t_x,t_y,0,0); this.bone_eventplate[ii].SetEnable(true); this.bone_eventplate[ii].SetX(t_x - this.bone_eventplate[ii].GetW()/2); this.bone_eventplate[ii].SetY(t_y - this.bone_eventplate[ii].GetH()/2); } }else{ this.bone_sprite[ii].SetVisible(false); this.bone_eventplate[ii].SetEnable(false); this.bone_name[ii].SetVisible(true); this.bone_name[ii].SetRect(NRender2D.Render2D.VIRTUAL_W - 150,100 + t_none_index * 20,0,0); t_none_index++; } } } /** 削除前。 */ public override bool PreDestroy(bool a_first) { return true; } /** OnDestroy */ private void OnDestroy() { this.deleter.DeleteAll(); } }
using UnityEngine; using System.Collections; public static class DRConstants { public const string exit_action_pop_up_text = "Are you sure you want to exit?"; public const string home_action_from_game_pop_up = "Are you sure you want to leave the game? All your current progress will be lost!"; public const string restart_action_from_game_pop_up = "Are you sure you want to restart the game? All your current progress will be lost!"; public const string pause_action_info_board_text = "GAME\nPAUSED"; public const string highest_score = "HIGHEST_SCORE"; public const string play_count = "PLAY_COUNT"; public const string total_shields_collected = "TOTAL_SHIELDS_COLLECTED"; public const string max_score_without_hit = "MAX_SCORE_WITHOUT_HIT"; public const string sound_settings = "SOUND_SETTINGS"; }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using GraphiQl; using GraphQL; using GraphQL.Server; using GraphQL.Server.Ui.Voyager; using GraphQL.Server.Ui.Playground; using ExampleData.Schema; using ExampleData.Repositorios.Interfaces; using ExampleData.Repositorios; using ExampleData.Schema.Types; namespace ExampleProject { public class Startup { public void ConfigureServices(IServiceCollection services) { // serviços services.AddSingleton<ITriboRepositorio, TriboRepositorio>(); services.AddSingleton<IGuildaRepositorio, GuildaRepositorio>(); services.AddSingleton<ISquadRepositorio, SquadRepositorio>(); // objetos services.AddSingleton<TriboType>(); services.AddSingleton<GuildaType>(); services.AddSingleton<SquadType>(); // query e schema services.AddSingleton<DtiQuery>(); services.AddSingleton<DtiSchema>(); services.AddSingleton<IDependencyResolver>( x => new FuncDependencyResolver( type => x.GetRequiredService(type) ) ); services.AddGraphQL(options => { options.EnableMetrics = true; }) .AddWebSockets() .AddDataLoader(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseGraphiQl(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseWebSockets(); app.UseGraphQLWebSockets<DtiSchema>("/graphql"); app.UseGraphQL<DtiSchema>("/graphql"); app.UseGraphQLPlayground(new GraphQLPlaygroundOptions() { Path = "/playground" }); app.UseGraphQLVoyager(new GraphQLVoyagerOptions() { GraphQLEndPoint = "/graphql", Path = "/voyager" }); } } }
 using System; using Foundation; using UIKit; using Facebook.LoginKit; using Facebook.CoreKit; using System.Collections.Generic; using CoreGraphics; namespace Lettuce.IOS { public partial class ProfileViewController : UIViewController { List<string> readPermissions = new List<string> { "public_profile" }; LoginButton loginButton; ProfilePictureView pictureView; UILabel nameLabel; public ProfileViewController () : base () { this.Title = "OpenDate Profile"; UIBarButtonItem menuBtn = new UIBarButtonItem ("Menu", UIBarButtonItemStyle.Plain, null); this.NavigationItem.SetLeftBarButtonItem (menuBtn, false); menuBtn.Clicked += (object sender, EventArgs e) => { SidebarController.ToggleMenu(); }; } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); NavigationController.NavigationBarHidden = false; InitFacebookLogin (); } private void InitFacebookLogin() { Profile.Notifications.ObserveDidChange ((sender, e) => { if (e.NewProfile == null) return; nameLabel.Text = e.NewProfile.Name; }); CGRect viewBounds = View.Bounds; // Set the Read and Publish permissions you want to get nfloat leftEdge = (viewBounds.Width - 220) /2; loginButton = new LoginButton (new CGRect (leftEdge, 60, 220, 46)) { LoginBehavior = LoginBehavior.Native, ReadPermissions = readPermissions.ToArray () }; // Handle actions once the user is logged in loginButton.Completed += (sender, e) => { if (e.Error != null) { // Handle if there was an error } if (e.Result.IsCancelled) { // Handle if the user cancelled the login request } // Handle your successful login }; // Handle actions once the user is logged out loginButton.LoggedOut += (sender, e) => { // Handle your logout nameLabel.Text = ""; }; // The user image profile is set automatically once is logged in pictureView = new ProfilePictureView (new CGRect (leftEdge, 140, 220, 220)); // Create the label that will hold user's facebook name nameLabel = new UILabel (new CGRect (20, 360, viewBounds.Width - 40, 21)) { TextAlignment = UITextAlignment.Center, BackgroundColor = UIColor.Clear }; // If you have been logged into the app before, ask for the your profile name if (AccessToken.CurrentAccessToken != null) { var request = new GraphRequest ("/me?fields=name", null, AccessToken.CurrentAccessToken.TokenString, null, "GET"); request.Start ((connection, result, error) => { // Handle if something went wrong with the request if (error != null) { new UIAlertView ("Error...", error.Description, null, "Ok", null).Show (); return; } // Get your profile name var userInfo = result as NSDictionary; nameLabel.Text = userInfo ["name"].ToString (); }); } // Add views to main view View.AddSubview (loginButton); View.AddSubview (pictureView); View.AddSubview (nameLabel); } protected SidebarNavigation.SidebarController SidebarController { get { return (UIApplication.SharedApplication.Delegate as AppDelegate).RootViewController.SidebarController; } } // provide access to the sidebar controller to all inheriting controllers protected NavController NavController { get { return (UIApplication.SharedApplication.Delegate as AppDelegate).RootViewController.NavController; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IndoorMap.Models { public class JsonShopDetailsModel { public string reason { get; set; } public ShopDetailsModel result{ get; set; } public string error_code{ get; set; } } public class ShopDetailsModel { public string id{ get; set; } public string ch_name{ get; set; } public string en_name{ get; set; } public string logo{ get; set; } public string catelogs{ get; set; } public string lon{ get; set; } public string lat{ get; set; } public List<Comment> comments{ get; set; } public List<Coupon> coupons{ get; set; } public Mall mall{ get; set; } public Mall building{ get; set; } public Mall floor{ get; set; } } public class Comment { public string user_nickname{ get; set; } public string create_time{ get; set; } public string text_excerpt{ get; set; } public string type{ get; set; } } public class Coupon { public string novalue{ get; set; } } public class Mall //include mall、building、floor { public string id{ get; set; } public string name{ get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StringVSStringBuilder { class Program { static void Main(string[] args) { Console.WriteLine("test mit String"); Stopwatch watch = new Stopwatch(); string text = ""; watch.Start(); for (int i = 0; i < 50000; i++) text += "x"; watch.Stop(); Console.WriteLine("Zeit: {0}", watch.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("test mit StringBuilder"); StringBuilder str = new StringBuilder(); Stopwatch watch2 = new Stopwatch(); watch2.Start(); for (int i = 0; i < 50000; i++) str = str.Append("x"); watch2.Stop(); Console.WriteLine("Zeit: {0}", watch2.ElapsedMilliseconds); Console.WriteLine(); Console.WriteLine("test mit umgewandeltem StringBuilder"); str = new StringBuilder(); Stopwatch watch3 = new Stopwatch(); watch3.Start(); for (int i = 0; i < 50000; i++) str.Append("x").ToString(); watch3.Stop(); Console.WriteLine("Zeit: {0}", watch3.ElapsedMilliseconds); Console.ReadLine(); } } }
namespace Umbraco.Web { internal class HybridUmbracoContextAccessor : HybridAccessorBase<UmbracoContext>, IUmbracoContextAccessor { public HybridUmbracoContextAccessor(IHttpContextAccessor httpContextAccessor) : base(httpContextAccessor) { } protected override string ItemKey => "Umbraco.Web.HybridUmbracoContextAccessor"; public UmbracoContext UmbracoContext { get { return Value; } set { Value = value; } } } }
using System; using Flunt.Notifications; using Flunt.Validations; namespace GameLoanManager.Domain.ViewModels.LoanedGame { public class LoanedGameUpdateViewModel : Notifiable, IValidatable { public long Id { get; set; } public long IdUser { get; set; } public long IdGame { get; set; } public bool Returned { get; set; } public DateTime UpdateAt { get { return DateTime.UtcNow; } } public void Validate() { AddNotifications( new Contract() .Requires() .IsGreaterThan(Id, 0, "Id Loaned Game", "O ID do empréstimo do jogo é obrigatório") .IsGreaterThan(IdUser, 0, "IdUser", "O ID do usuário é obrigatório") .IsGreaterThan(IdGame, 0, "IdGame", "O ID do jogo é obrigatório") ); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System; using Puppet; using System.IO; using Puppet.Core.Network.Http; public class SendSMSService : Singleton<SendSMSService> { ISendSMS send; protected override void Init() { #if UNITY_IPHONE && !UNITY_EDITOR send = new SendSMSIOS(); #elif UNITY_ANDROID && !UNITY_EDITOR send = new SendSMSAndroid(); #else send = new SendSMSEditor(); #endif } public bool IsSupportSimCard { get { return send.IsSupportSimCard; } } public bool SendSMSMessage(List<string> smsNumbers, string message) { if (smsNumbers.Count == 0) return false; string numbers = ""; for (int i = 0; i < smsNumbers.Count; i++) numbers += smsNumbers[i] + ","; if (numbers.Length > 0) numbers = numbers.Substring(0, numbers.Length - 1); if (!IsSupportSimCard) return false; return send.SendSMS(numbers, message); } public bool SendEmailMessage(List<string> emailAddresses, string subject, string message) { if (emailAddresses.Count == 0) return false; string email = string.Empty; for (int i = 0; i < emailAddresses.Count; i++) email += emailAddresses[i] + ","; if (!string.IsNullOrEmpty(email)) email = email.Substring(0, email.Length - 1); return send.SendMail(email, subject, message); } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Text; using Karkas.Core.DataUtil; namespace Karkas.Ornek.Dal.Ornekler { public partial class StoredProcedures { public static int BasitTabloIdentityEkle ( string @Adi ,string @Soyadi , AdoTemplate template ) { ParameterBuilder builder = template.getParameterBuilder(); builder.parameterEkle( "@Adi",DbType.String,@Adi); builder.parameterEkle( "@Soyadi",DbType.String,@Soyadi); SqlCommand cmd = new SqlCommand(); cmd.CommandText = "ORNEKLER.BASIT_TABLO_IDENTITY_EKLE"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(builder.GetParameterArray()); int tmp = Convert.ToInt32(template.TekDegerGetir(cmd));; return tmp; } public static int BasitTabloIdentityEkle ( string @Adi ,string @Soyadi ) { AdoTemplate template = new AdoTemplate(); template.Connection = ConnectionSingleton.Instance.getConnection("KARKAS_ORNEK"); return BasitTabloIdentityEkle( @Adi ,@Soyadi ,template ); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; //using ReqOneUI.ReqOneAPI; using ReqOneApiReference.ReqOneApi; namespace ReqOneUI { public static class SessionContext { public static User User { get { return HttpContext.Current.Session["__CrtUser"] as User; } set { HttpContext.Current.Session["__CrtUser"] = value; } } } }
using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Application.Common.Dtos; using Application.Common.Exceptions; using Application.Common.Interface; using Application.Common.Models; using AutoMapper; using Domain.Entities; using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Application.Discounts.Commands.UpdateDiscountCommands { public class UpdateDiscountCommand : IRequest<string> { public DiscountDto DiscountDto { get; set; } public IFormFile DiscountBanner { get; set; } } public class UpdateDiscountCommandHandler : BaseCommandHandler<UpdateDiscountCommandHandler>, IRequestHandler<UpdateDiscountCommand, string> { public UpdateDiscountCommandHandler (IAppDbContext context, IMapper mapper, ILogger<UpdateDiscountCommandHandler> logger) : base (context, mapper, logger) { } private static Random random = new Random (); public async Task<string> Handle (UpdateDiscountCommand request, CancellationToken cancellationToken) { var entity = Context.Discounts.Where (x => x.IdDiscount == request.DiscountDto.IdDiscount).FirstOrDefault (); if (entity == null) throw new NotFoundException ("Courier", "Courier Not Found!"); entity.Content = request.DiscountDto.Content; entity.DiscountName = request.DiscountDto.DiscountName; entity.DiscountStart = request.DiscountDto.DiscountStart; entity.DiscountType = request.DiscountDto.DiscountType; entity.DiscountEnd = request.DiscountDto.DiscountEnd; entity.Voucher = request.DiscountDto.Voucher; entity.Items = request.DiscountDto.Items; if (request.DiscountBanner != null) { try { File.Delete (Path.Combine ("./Resources/Discounts", entity.DiscountBanner)); } catch (Exception e) { Logger.LogError ($"Error when delete file : {e}"); } try { var fileName = $"{RandomString(6)}{random.Next(1,999)}{Path.GetExtension(request.DiscountBanner.FileName)}"; var path = Path.Combine ("./Resources/Discounts", fileName); using (var stream = System.IO.File.Create (path)) { await request.DiscountBanner.CopyToAsync (stream); } entity.DiscountBanner = fileName; } catch (Exception e) { Logger.LogError ($"Error when moving file : {e}"); } } await Context.SaveChangesAsync (true, cancellationToken); return "Sukses"; } public static string RandomString (int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; return new string (Enumerable.Repeat (chars, length) .Select (s => s[random.Next (s.Length)]).ToArray ()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace Psychokinesis { class background:entity { public Texture2D image; public void update(String direction) { if (direction == "right") { xVelocity = -4; } if (direction == "left") { xVelocity = 4; } if (x + xVelocity + width <= 900 || x + xVelocity > 0) { xVelocity = 0; } x += xVelocity; rectangle = new Rectangle(x, y, width, height); } public void draw(SpriteBatch sb) { sb.Draw(image, rectangle, Color.White); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace LMS.Models { public class Module { public int Id { get; set; } [StringLength(50, ErrorMessage = "The {0} must be between {1} and {2} characters long", MinimumLength = 1)] [Display(Name = "Module name")] [Required] public string ModuleName { get { return moduleName; } set { moduleName = InitialCapital(value); } } protected string moduleName { get; set; } [StringLength(200, ErrorMessage = "The {0} must be between {1} and {2} characters long", MinimumLength = 1)] [Required] public string Description { get; set; } [Display(Name = "Start Date")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] [Required] public DateTime StartDate { get; set; } [Display(Name = "Duration (days)")] [Required] [Range(1, int.MaxValue, ErrorMessage = "Only positive integers are valid")] public int DurationDays { get; set; } [Display(Name = "End date")] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}")] public DateTime EndDate { get { return StartDate.AddDays(DurationDays - 1); } } [StringLength(5000, ErrorMessage = "The {0} must be between {1} and {2} characters long", MinimumLength = 1)] [Display(Name = "Module Info")] public string ModuleInfo { get; set; } //navigational property public virtual Course Course { get; set; } public virtual ICollection<Activity> Activities {get; set;} /* Appendices*/ public string InitialCapital(string value) { if (value == null | value.Trim().Length == 0) value = ""; if (value.Trim().Length > 1) value = value.Trim().Substring(1, 1).ToUpper() + value.Trim().Substring(1, value.Length - 1).ToLower(); else value = value.Trim().ToUpper(); return value; } } }
namespace Stundenplan.Models { public class Classes { public static string[] classes = { "SEL81", "SEL71", "SEL61", "FIS81", "FIM82", "FIA83", "FIS71", "FIM72", "FIA73", "FIS61", "FIM62", "FIA63", "E-EG82", "E-EG61", "E-EG52", "E-IT71", "SEL71", "VTE81", "BGP81", "BGP71" }; public string[] GetClasses() { return classes; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodingChallenge { public class Direction { public const int Left = 1; public const int Right = 2; public const int Down = 3; } public class DirectionScanner { public List<List<PathNode>> pathNodeInTotalSearched { get; set; } = new List<List<PathNode>>(); public List<PathNode> avoidNodeList { get; set; } = new List<PathNode>(); public HashSet<PathNode> bottleNeckList { get; set; } = new HashSet<PathNode>(); public List<PathNode> pathNodeSearched { get; set; } = new List<PathNode>(); public PathNode currentNode { get; set; } = new PathNode(); public const int CURRENTNODE_MAXCOUNT = 3; public bool ScanLeft(PathNode[,] pathMap) { bool leftisScanned = false; int coordinate_X = currentNode.coordinate_X; int coordinate_Y = currentNode.coordinate_Y - 1; if (coordinate_Y >= 0) { if (!avoidNodeList.Contains(pathMap[coordinate_X, coordinate_Y]) && !bottleNeckList.Contains(pathMap[coordinate_X, coordinate_Y])) { if (currentNode.data > pathMap[coordinate_X, coordinate_Y].data) { currentNode = pathMap[coordinate_X, coordinate_Y]; pathNodeSearched.Add(pathMap[coordinate_X, coordinate_Y]); leftisScanned = true; } } } return leftisScanned; } public bool ScanRight(PathNode[,] pathMap,int mapMaxCountY) { bool rightisScanned = false; int coordinate_X = currentNode.coordinate_X; int coordinate_Y = currentNode.coordinate_Y + 1; if (coordinate_Y <= mapMaxCountY - 1) { if (!avoidNodeList.Contains(pathMap[coordinate_X, coordinate_Y]) && !bottleNeckList.Contains(pathMap[coordinate_X, coordinate_Y])) { if (currentNode.data > pathMap[coordinate_X, coordinate_Y].data) { currentNode = pathMap[coordinate_X, coordinate_Y]; pathNodeSearched.Add(pathMap[coordinate_X, coordinate_Y]); rightisScanned = true; } } } return rightisScanned; } public bool ScanDownward(PathNode[,] pathMap,int mapMaxCountX) { bool downwardisScanned = false; int coordinate_X = currentNode.coordinate_X+1; int coordinate_Y = currentNode.coordinate_Y; if (coordinate_X <= mapMaxCountX - 1) { if (!avoidNodeList.Contains(pathMap[coordinate_X, coordinate_Y]) && !bottleNeckList.Contains(pathMap[coordinate_X, coordinate_Y])) { if (currentNode.data > pathMap[coordinate_X, coordinate_Y].data) { currentNode = pathMap[coordinate_X, coordinate_Y]; pathNodeSearched.Add(pathMap[coordinate_X, coordinate_Y]); downwardisScanned = true; } } } if (!downwardisScanned) { if (pathNodeSearched.Count > 1) { this.avoidNodeList.Add(pathNodeSearched[pathNodeSearched.Count - 1]); this.pathNodeSearched.RemoveAt(pathNodeSearched.Count - 1); } if (pathNodeSearched.Count > 0) currentNode = pathNodeSearched[pathNodeSearched.Count - 1]; } return downwardisScanned; } } }
using System; using System.IO; using System.Linq; using Android.Content.Res; using Android.Graphics; using OmniGui.Xaml; using OmniXaml; using OmniXaml.Attributes; using Zafiro.Core; using AndroidBitmap = Android.Graphics.Bitmap; namespace OmniGui.Android { public class Conversion { [TypeConverterMember(typeof(Bitmap))] public static Func<string, ConvertContext, (bool, object)> ThicknessConverter = (str, v) => (true, GetBitmap(str)); private ITypeLocator locator; private static Bitmap GetBitmap(string str) { AndroidBitmap bmp; using (var stream = AndroidPlatform.Current.Assets.Open(str)) { bmp = BitmapFactory.DecodeStream(stream); } var pixels = new int[bmp.Width * bmp.Height]; bmp.GetPixels(pixels, 0, bmp.Width, 0, 0, bmp.Width, bmp.Height); return new Bitmap(bmp.Width, bmp.Height, pixels.ToByteArray()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bullet1 : MonoBehaviour { private void Start() { } private void Update() { transform.localScale = new Vector3(0.3f * Player_FPS.thisPlayer.shootcharge, 0.3f * Player_FPS.thisPlayer.shootcharge, 0.3f * Player_FPS.thisPlayer.shootcharge); } }
using System.Windows; namespace Bililive_dm { public class StyledWindow : Window { public StyledWindow() { SetResourceReference(StyleProperty, typeof(Window)); } } }
namespace SSU.CompetitiveTest.Play.Communicating { using System; using System.IO; using System.Diagnostics; public sealed class Communicator { #region Fields private readonly String name; private readonly String executablePath; private readonly ProcessStartInfo startInfo = new ProcessStartInfo(); #endregion #region Properties public String Name { get { return name; } } public String ExecutablePath { get { return executablePath; } } #endregion #region Methods #region Suppress error dialogs [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern UInt32 SetErrorMode(UInt32 hHandle); static Communicator() { SetErrorMode(0x0002); } #endregion /// <summary> /// Creates communicator with specified executable. /// </summary> /// <param name="executablePath">Path to console application's executable</param> /// <exception cref="ArgumentException">The executable doesn't exist or the format is not supported</exception> public Communicator(String executablePath) { if (!(File.Exists(executablePath) && executablePath.ToLower().EndsWith(".exe"))) { throw new ArgumentException("The executable either doesn\'t exist or has not supported format", "executablePath"); } this.executablePath = executablePath; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = false; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.ErrorDialog = false; startInfo.FileName = executablePath; Int32 slash = executablePath.LastIndexOf('\\') + 1; name = executablePath.Substring(slash, executablePath.LastIndexOf('.') - slash); } /// <summary> /// Runs the application ones /// </summary> /// <param name="incoming">Data for application's standard input stream</param> /// <param name="timeLimit">Time bound for execution</param> /// <returns>Data from application's standard output and associated information</returns> /// <exception cref="InvalidOperationException">The executable file has been missed</exception> /// <exception cref="RuntimeErrorException">The process has exited with an error</exception> /// <exception cref="TimeLimitException">Time limit exceeded</exception> public RunOutcome Run(String incoming, TimeSpan timeLimit) { if (!File.Exists(executablePath)) { throw new InvalidOperationException("The executable file has been missed"); } using (Process p = new Process()) { p.StartInfo = startInfo; p.Start(); p.StandardInput.WriteLine(incoming); p.StandardInput.Flush(); DateTime begin = DateTime.Now; p.WaitForExit((Int32)timeLimit.TotalMilliseconds); if (p.HasExited) { if (p.ExitCode != 0) { throw new RuntimeErrorException(p.ExitCode, "The process has exited with an error"); } TimeSpan elapsed = DateTime.Now - begin; return new RunOutcome(p.StandardOutput.ReadToEnd(), elapsed, begin); } else { p.Kill(); throw new TimeLimitException("Time limit exceeded"); } } } #endregion } }
// GIMP# - A C# wrapper around the GIMP Library // Copyright (C) 2004-2009 Maurits Rijk // // ByColorSelectTool.cs // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // using System; using System.Runtime.InteropServices; namespace Gimp { public sealed class ByColorSelectTool { readonly Int32 _drawableID; public ByColorSelectTool(Drawable drawable) { _drawableID = drawable.ID; } public void Select(RGB color, int threshold, ChannelOps operation, bool antialias, bool feather, double featherRadius, bool sampleMerged) { var rgb = color.GimpRGB; if (!gimp_by_color_select(_drawableID, ref rgb, threshold, operation, antialias, feather, featherRadius, sampleMerged)) { throw new GimpSharpException(); } } [DllImport("libgimp-2.0-0.dll")] static extern bool gimp_by_color_select(Int32 drawable_ID, ref GimpRGB color, int threshold, ChannelOps operation, bool antialias, bool feather, double feather_radius, bool sample_merged); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; namespace Channel.Mine { class Program { static void RebuildIndex() { Framework.Abstraction.DynamicPipeline<IMDB.Collections.MediaCollection> pipeline = null; #region Configure Pipeline pipeline &= new IMDB.Parsers.MovieParser(@"DataStore\movies.list"); pipeline &= new IMDB.Parsers.GenreParser(@"DataStore\genres.list"); // pipeline &= new IMDB.Parsers.RatingParser(); // pipeline &= new IMDB.Parsers.TitleParser(); // pipeline &= new IMDB.Parsers.PlotParser(); // pipeline &= new IMDB.Parsers.ReleaseDateParser(); pipeline &= new IMDB.Actions.IndexBuilder(@"DataStore"); #endregion IMDB.Collections.MediaCollection mediaLibrary = new IMDB.Collections.MediaCollection(); pipeline.Process(mediaLibrary); } static void ProcessMedia() { String rootPath = @"M:\TV Shows\"; // String rootPath = @"C:\Users\peter.dolkens.DDRIT\Music\iTunes\iTunes Media\TV Shows\"; Framework.Abstraction.DynamicPipeline<API.Entities.TVMedia> pipeline = null; API.Actions.TV.Collector collector = new API.Actions.TV.Collector(); #region Configure Pipeline // pipeline &= new API.Filters.TV.FileSystemFilter(@"\Drop Dead Diva\"); pipeline &= new API.Parsers.TV.FileSystemParser(rootPath); pipeline &= new API.Parsers.TV.IMDBParser(@"DataStore"); pipeline &= collector; #endregion #region Process Items List<API.Entities.TVMedia> tvShows = new List<API.Entities.TVMedia>(); new Thread(x => { #if DEBUG tvShows = (from filePath in File.ReadAllLines(@"c:\tvShows.txt") let tvShow = new API.Entities.TVMedia(filePath) where pipeline.Process(tvShow) select tvShow).ToList<API.Entities.TVMedia>(); #else List<API.Entities.TVMedia> tvShows = (from filePath in Directory.GetFiles(rootPath, "*.m4v", SearchOption.AllDirectories) let tvShow = new API.Entities.TVMedia(filePath) where pipeline.Process(tvShow) select tvShow).ToList<API.Entities.TVMedia>(); #endif }).Start(); #endregion while (!Console.KeyAvailable && (tvShows.Count == 0)) { Thread.Sleep(1000); Console.SetCursorPosition(0, 0); Console.WriteLine(collector.Items.Count); } API.Entities.TVMedia[] collection = new API.Entities.TVMedia[collector.Items.Values.Count]; collector.Items.Values.CopyTo(collection, 0); if (File.Exists(@"c:\hits.csv")) File.Delete(@"c:\hits.csv"); foreach (var item in collection) { String row = String.Format("\"{0}\",\"{1}\"", item.File.DirectoryName, item.File.Name); foreach (IMDB.Entities.Media hit in item.Context[API.Parsers.TV.IMDBParser.IMDB_SEARCHHIT] as List<IMDB.Entities.Media>) File.AppendAllText(@"c:\hits.csv", String.Format("{0},\"{1}\",\"{2}\",\"{3}\",\"{4}\",\"{5}\"\r\n", row, hit.Score, hit.Title.Replace('"', ' '), hit.EpisodeName.Replace('"', ' '), hit.SeasonNo, hit.EpisodeNo)); } var showsWithNoHits = (from show in tvShows let hits = show.Context[Channel.Mine.API.Parsers.TV.IMDBParser.IMDB_SEARCHHIT] as List<IMDB.Entities.Media> where hits.Count < 1 select show).ToList(); var showsWithHits = tvShows.Except(showsWithNoHits).ToList(); Console.WriteLine("There are {0} items with no hits", showsWithNoHits.Count); Console.WriteLine("There are {0} items", tvShows.Count); } static void Main(string[] args) { // RebuildIndex(); ProcessMedia(); Console.ReadKey(); } } }
using filter.data.entity; using filter.data.manager; using filter.data.model; using filter.data.model.Dto; using filter.framework.utility; using filter.framework.utility.Xport; using filter.framework.utility.XPort; using filter.framework.web; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; namespace filter.business { public class ShopsBiz:BaseBiz { private ShopsManager shopsManager; private SalemanManager salemanManager; public ShopsBiz() { shopsManager = new ShopsManager(); salemanManager = new SalemanManager(); } /// <summary> /// 分页获取店铺数据 /// </summary> /// <param name="page"></param> /// <param name="size"></param> /// <param name="conditions"></param> /// <returns></returns> public async Task<ResultBase<PagedData<ShopsModel>>> GetPagedShops(int page, int size, Dictionary<string, string> conditions) { var data = await shopsManager.GetPagedShops(page, size, conditions); return ResultBase<PagedData<ShopsModel>>.Sucess(data); } /// <summary> /// 保存 /// </summary> /// <param name="request"></param> /// <returns></returns> public async Task<ResultBase> Save(SaveShopsModel request) { if (request == null) return ResultBase.Fail(Enum_ResultBaseCode.ParamError); else if (string.IsNullOrEmpty(request.Name)) return ResultBase.Fail(Enum_ResultBaseCode.ParamLackError); else if(string.IsNullOrEmpty(request.SalemanName)) return ResultBase.Fail(Enum_ResultBaseCode.ParamLackError); //校验业务员 var saleman = await salemanManager.FindByName(request.SalemanName); if (saleman == null) return ResultBase.Fail("业务员不存在,请检查"); //判断有没有同名的店铺 var shop = await shopsManager.FindByNameWithDeleted(request.Name); if (shop != null) { if (shop.IsDelete) { shop.IsDelete = false; shop.DeletedBy = 0; shop.DeletedAt = null; shop.UpdatedAt = DateTime.Now; shop.UpdatedBy = 0; await shopsManager.UpdateAsync(shop); } } else { if (request.Id == 0) { ShopEntity entity = request.Convert<ShopEntity>(); entity.SalemanId = saleman.Id; entity.CreatedAt = DateTime.Now; entity.CreatedBy = 0; await shopsManager.InsertAsync(entity); } else { var entity = shopsManager.FindById<ShopEntity>(request.Id); if (entity == null) return ResultBase.Fail(Enum_ResultBaseCode.DataNotFoundError); entity.Name = request.Name; entity.Contact = request.Contact; entity.Mobile = request.Mobile; entity.SalemanId = saleman.Id; entity.UpdatedAt = DateTime.Now; entity.UpdatedBy = 0; await salemanManager.UpdateAsync(entity); } } return ResultBase.Sucess(); } /// <summary> /// 导入店铺 /// </summary> /// <param name="request"></param> /// <param name="files"></param> /// <param name="merchantId"></param> /// <returns></returns> public async Task<ResultBase> ImportShops(HttpFileCollectionBase files, int manager) { if (files == null || files.Count == 0) return ResultBase<UploadExcelCheckResultModel>.Fail("请上传文件"); var file = files[0]; if (file.ContentLength == 0) return ResultBase<UploadExcelCheckResultModel>.Fail("文件内容为空"); string fileName = file.FileName;//取得文件名字 var fileExt = fileName.Substring(fileName.LastIndexOf('.') + 1); string[] msExcelFiles = { "xlsx", "xls" }; if (!msExcelFiles.Any(m => m == fileExt)) return ResultBase<UploadExcelCheckResultModel>.Fail("只支持EXCEL文件"); var filePath = $"/Upload/Shops/"; var saveFilePath = HttpContext.Current.Server.MapPath($"~{filePath}"); if (!Directory.Exists(saveFilePath)) { Directory.CreateDirectory(saveFilePath); } //改名称 var newFileName = ConvertHelper.ConvertDtToUnixTimeSpan(DateTime.Now) + "." + fileExt; string path = saveFilePath + newFileName;//获取存储的目标地址 file.SaveAs(path); //读取excel var data = ExcelHelper.ReadExcelNoIndex<ExportShopsModel>(path, "店铺上传"); if (data == null || data.Count == 0) return ResultBase.Fail("没有有效数据"); mLogHelper.Info($"开始执行导入快递单号,总量:{data.Count}"); //分组批量插入数据 var groups = data.GroupBy(m => m.SalemanName); List<int> taskIds = new List<int>(); foreach (var group in groups) { var saleman =await salemanManager.FindByName(group.Key); if (saleman == null) continue; var items = group.ToList(); List<ShopEntity> entities = new List<ShopEntity>(); var total = 0; foreach (var item in items) { if (string.IsNullOrEmpty(item.Name) || string.IsNullOrEmpty(item.SalemanName)) continue; var entity = item.Convert<ShopEntity>(); entity.SalemanId = saleman.Id; entity.CreatedAt = DateTime.Now; entity.CreatedBy = manager; entities.Add(entity); total += 1; } var trans = DapperDataAccess.BeginTransaction(IsolationLevel.ReadCommitted); try { await shopsManager.InsertBatchAsync(entities, trans); DapperDataAccess.Commit(trans); } catch (ShowMessageException ex) { DapperDataAccess.Rollback(trans); return ResultBase.Fail(ex.Message); } catch (Exception ex) { DapperDataAccess.Rollback(trans); return ResultBase.Fail(ex.Message); } } mLogHelper.Info($"导入执行完毕"); return ResultBase.Sucess(); } /// <summary> /// 获取店铺信息 /// </summary> /// <param name="id"></param> /// <returns></returns> public async Task<ResultBase<ShopsModel>> GetShopInfoById(int id) { var shops = shopsManager.FindById<ShopEntity>(id); if (shops == null) return ResultBase<ShopsModel>.Fail(Enum_ResultBaseCode.DataNotFoundError); var saleman = salemanManager.FindById<SalemanEntity>(shops.SalemanId); if(saleman==null) return ResultBase<ShopsModel>.Fail("业务员数据错误"); var result = shops.Convert<ShopsModel>(); result.SalemanName = saleman.Name; return ResultBase<ShopsModel>.Sucess(result); } /// <summary> /// 逻辑删除 /// </summary> /// <param name="ids"></param> /// <returns></returns> public async Task<ResultBase> Delete(string ids) { if (string.IsNullOrEmpty(ids)) return ResultBase.Fail("参数缺失"); var idsString = ids.Split(','); var idsList = idsString.Select(id => Convert.ToInt32(id)).ToList(); await shopsManager.LogicDeleteAsync<ShopEntity>(idsList); return ResultBase.Sucess(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; namespace CS_Perf { class MemSize<T> { static private long SizeOfObj(Type T, object thevalue) { var type = T; long returnval = 0; if (type.IsValueType) { var nulltype = Nullable.GetUnderlyingType(type); returnval = System.Runtime.InteropServices.Marshal.SizeOf(nulltype ?? type); } else if (thevalue == null) return 0; else if (thevalue is string) returnval = Encoding.Default.GetByteCount(thevalue as string); else if (type.IsArray && type.GetElementType().IsValueType) { returnval = ((Array)thevalue).GetLength(0) * System.Runtime.InteropServices.Marshal.SizeOf(type.GetElementType()); } else if (thevalue is Stream) { Stream thestram = thevalue as Stream; returnval = thestram.Length; } else if (type.IsSerializable) { try { using (Stream s = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(s, thevalue); returnval = s.Length; } } catch { throw; } } else { var fields = type.GetFields(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); for (int i = 0; i < fields.Length; i++) { Type t = fields[i].FieldType; Object v = fields[i].GetValue(thevalue); returnval += 4 + SizeOfObj(t, v); } } if (returnval == 0) try { returnval = System.Runtime.InteropServices.Marshal.SizeOf(thevalue); } catch { } return returnval; } static public long SizeOf(T value) { return SizeOfObj(typeof(T), value); } } }
namespace Contoso.Parameters.Expressions { public class NotEqualsBinaryOperatorParameters : BinaryOperatorParameters { public NotEqualsBinaryOperatorParameters() { } public NotEqualsBinaryOperatorParameters(IExpressionParameter left, IExpressionParameter right) : base(left, right) { } } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using System; using Android.App; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using droid = Android.Widget.Orientation; using Com.Syncfusion.Sfrangeslider; using Android.Graphics; using Android.Content; namespace SampleBrowser { //[con(Label = "Orientation")] public class Equalizer : SamplePage { SfRangeSlider slider1,slider2,slider3; TextView textView,textView1,textView2,textView3,textView4,textView5,textView6,textView7,textView8,textView9,textView10; public override View GetSampleContent (Context con) { LinearLayout mainLayout,layout1,layout2,layout3;; int height = con.Resources.DisplayMetrics.HeightPixels/2; int width = con.Resources.DisplayMetrics.WidthPixels/3; /** * Defining Linear Layout */ mainLayout = new LinearLayout(con); mainLayout.SetBackgroundColor(Color.White); mainLayout.SetGravity(GravityFlags.Center); LinearLayout parentLayout=new LinearLayout(con); parentLayout.Orientation=droid.Vertical; parentLayout.SetBackgroundColor(Color.White); parentLayout.LayoutParameters=new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); FrameLayout.LayoutParams sliderLayout = new FrameLayout.LayoutParams(width,height+(height/4)); textView = new TextView(con); textView7 = new TextView(con); textView8 = new TextView(con); textView9 = new TextView(con); textView9.Text=""; textView.Typeface= Typeface.Create("Roboto", TypefaceStyle.Normal); textView9.TextSize=20; textView9.Gravity=GravityFlags.Center; textView9.SetTextColor (Color.Argb(255,182,182,182)); //parentLayout.AddView(textView9); textView10 = new TextView(con); parentLayout.AddView(textView10); parentLayout.AddView(mainLayout); parentLayout.SetGravity(GravityFlags.Center); /** * Defining First Slider */ slider1 = new SfRangeSlider(con); slider1.Minimum=-12; slider1.Maximum=12; slider1.TickFrequency=12; slider1.TrackSelectionColor=Color.Gray; slider1.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Vertical; slider1.TickPlacement=TickPlacement.None; slider1.ValuePlacement=ValuePlacement.TopLeft; slider1.ShowValueLabel=true; slider1.SnapsTo=SnapsTo.None; slider1.Value=6; // slider1.setLayoutParams(sliderLayout); slider1.ValueChanged += (object sender, SfRangeSlider.ValueChangedEventArgs e) => { String str=(string)(Math.Round(e.P1)+".0db"); textView4.Text=str; }; layout1 = new LinearLayout(con); layout1.Orientation=droid.Vertical; layout1.SetGravity(GravityFlags.Center); textView1=new TextView(con); textView1.Text="60HZ"; textView1.TextSize=20; textView1.SetTextColor(Color.Black); textView1.Gravity=GravityFlags.Center; textView1.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); textView4 = new TextView(con); textView4.TextSize=14; textView4.SetTextColor(Color.Argb(255, 50, 180, 228)); textView4.Text="0.0db"; textView4.Typeface=Typeface.Create("Helvetica", TypefaceStyle.Normal); textView4.Gravity=GravityFlags.Center; layout1.AddView(textView1); layout1.AddView(textView4); layout1.AddView(textView); layout1.AddView(slider1,sliderLayout); /** * Defining Second Slider */ slider2 = new SfRangeSlider(con); slider2.Minimum=-12; slider2.Maximum=12; slider2.TickFrequency=12; slider2.TrackSelectionColor=Color.Gray; slider2.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Vertical; slider2.TickPlacement=TickPlacement.None; slider2.ValuePlacement=ValuePlacement.TopLeft; slider2.ShowValueLabel=true; slider2.SnapsTo=SnapsTo.None; slider2.Value=-3; slider2.LayoutParameters=sliderLayout; slider2.ValueChanged+= (object sender, SfRangeSlider.ValueChangedEventArgs e) => { textView5.Text=Convert.ToString(Math.Round(e.P1)+".0db"); }; layout2 = new LinearLayout(con); layout2.Orientation=droid.Vertical; layout2.SetGravity(GravityFlags.Center); textView2=new TextView(con); textView2.Text="170HZ"; textView2.TextSize=20; textView2.SetTextColor(Color.Black); textView2.Gravity=GravityFlags.Center; textView2.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); textView5 = new TextView(con); textView5.TextSize=14; textView5.SetTextColor(Color.Argb(255, 50, 180, 228)); textView5.Text="0.0db"; textView5.Typeface=Typeface.Create("Helvetica", TypefaceStyle.Normal); textView5.Gravity=GravityFlags.Center; layout2.AddView(textView2); layout2.AddView(textView5); layout2.AddView(textView7); layout2.AddView(slider2,sliderLayout); /** * Defining Third Slider */ slider3 = new SfRangeSlider(con); slider3.Minimum=-12; slider3.Maximum=12; slider3.TickFrequency=12; slider3.TrackSelectionColor=Color.Gray; slider3.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Vertical; slider3.TickPlacement=TickPlacement.None; slider3.ValuePlacement=ValuePlacement.TopLeft; slider3.ShowValueLabel=true; slider3.SnapsTo=SnapsTo.None; slider3.Value=12; slider3.LayoutParameters=sliderLayout; slider3.ValueChanged+= (object sender, SfRangeSlider.ValueChangedEventArgs e) => { textView6.Text=Convert.ToString(Math.Round(e.P1)+".0db"); }; layout3 = new LinearLayout(con); layout3.Orientation=droid.Vertical; layout3.SetGravity(GravityFlags.Center); textView3=new TextView(con); textView3.Text="310HZ"; textView3.TextSize=20; textView3.SetTextColor(Color.Black); textView3.Gravity=GravityFlags.Center; textView3.Typeface = Typeface.Create("Helvetica", TypefaceStyle.Normal); textView6 = new TextView(con); textView6.TextSize=14; textView6.SetTextColor(Color.Argb(255, 50, 180, 228)); textView6.Text="0.0db"; textView6.Typeface=Typeface.Create("Helvetica", TypefaceStyle.Normal); textView6.Gravity=GravityFlags.Center; layout3.AddView(textView3); layout3.AddView(textView6); layout3.AddView(textView8); layout3.AddView(slider3,sliderLayout); /** * Adding sliders to Layout */ mainLayout.AddView(layout1); mainLayout.AddView(layout2); mainLayout.AddView(layout3); return parentLayout; } } }
/********************************************************** CoxlinCore - Copyright (c) 2023 Lindsay Cox / MIT License **********************************************************/ using System; using System.Collections; using System.Collections.Generic; using Unity.IL2CPP.CompilerServices; using UnityEngine; namespace CoxlinCore.ObjectPool { public sealed class ObjectPool : MonoBehaviour { [SerializeField] private PooledObjectData[] _pooledObjects; [SerializeField] private Transform _parent; private readonly HashSet<PooledObject> _objectsInUse = new HashSet<PooledObject>(); private Dictionary<string, PooledObject[]> _pooledObjectDic = new Dictionary<string, PooledObject[]>(); public void CreateObjectsFromPool(Action? onCreateAction = null) { StartCoroutine(CreateObjectsCoroutine()); } [Il2CppSetOption(Option.ArrayBoundsChecks, false)] private IEnumerator CreateObjectsCoroutine( Action? onCreateAction = null) { int count = _pooledObjects.Length; _pooledObjectDic.Clear(); for (int i = 0; i < count; ++i) { onCreateAction?.Invoke(); var p = _pooledObjects[i]; var pooledObjs = new PooledObject[p.Count]; _pooledObjectDic[p.Name] = pooledObjs; int pooledObjsLength = pooledObjs.Length; for (int j = 0; j < p.Count; ++j) { PooledObject pooledObject; if (j < pooledObjsLength) { pooledObject = pooledObjs[j]; } else { pooledObject = Instantiate(p.PooledObject, _parent); pooledObject.transform.localPosition = Vector2.zero; } pooledObject.gameObject.SetActive(false); pooledObject.OnReturn(); // Prepare the object for reuse } yield return null; } } [Il2CppSetOption(Option.ArrayBoundsChecks, false)] public PooledObject Acquire( string objName, Vector3 position, bool activateOnAcquire = true) { PooledObject pooledObject = null; if (!_pooledObjectDic.ContainsKey(objName)) { throw new UnityException($"{objName} is not in the object pool dic"); } var pooledObjs = _pooledObjectDic[objName]; if (_objectsInUse.ContainsAll(pooledObjs)) { throw new UnityException($"All objects for {objName} are already in use"); } int count = pooledObjs.Length; for (int i = 0; i < count; ++i) { if (_objectsInUse.Contains(pooledObjs[i])) continue; pooledObject = pooledObjs[i]; _objectsInUse.Add(pooledObject); pooledObject.transform.position = position; pooledObject.gameObject.SetActive(activateOnAcquire); pooledObject.OnAcquire(); break; } if (pooledObject == null) { throw new UnityException($"Trying to grab a null object for {objName}"); } return pooledObject; } public void Return( PooledObject pooledObj) { _objectsInUse.Remove(pooledObj); if (pooledObj == null) { return; } pooledObj.OnReturn(); pooledObj.transform.position = _parent.position; pooledObj.gameObject.SetActive(false); } } }
using Job.Customer.ExecuteCustomer.Interfaces; using Microsoft.Extensions.Configuration; namespace Job.Customer.ExecuteCustomer.Settings { public class CustomerAPISettings : ICustomerAPISettings { private readonly IConfiguration _configuration; public CustomerAPISettings(IConfiguration configuration) { _configuration = configuration; } public string ApiBasePath => _configuration.GetValue<string>("CustomerAPISettings:ApiBasePath"); public string ApiPath => _configuration.GetValue<string>("CustomerAPISettings:ApiPath"); } }
using System; using System.Collections.Generic; namespace Shared.Models { public class League { public LeagueType Type { get; set; } public string Name => GetCupName(); private string GetCupName() { switch (Type) { case LeagueType.A: case LeagueType.B: case LeagueType.C: case LeagueType.D: return Type.ToString(); case LeagueType.X: return "Arie de Boer toernooi"; case LeagueType.Cup: return "Beker"; default: throw new ArgumentOutOfRangeException(); } } public string LogoUrl { get; set; } // public CompetitionPart Competition { get; set; } public ICollection<Game> Games { get; set; } = new List<Game>(); // public ICollection<CompetitionPart> CompetitionParts { get; set; } public ICollection<Team> Teams { get; set; } = new List<Team>(); } public enum LeagueType { A,B,C,D,X,Cup } }
using UnityEngine; using System.Collections; using System; using System.Text; using System.Net; using System.Net.Sockets; using System.Threading; public class UDPSend : MonoBehaviour { // prefs private string IP="192.168.4.1"; // define in init private int port = 12345; // define in init // "connection" things IPEndPoint remoteEndPoint; UdpClient client; // call it from shell (as program) private static void Main() { UDPSend sendObj = new UDPSend(); sendObj.init(); // testing via console // sendObj.inputFromConsole(); // as server sending endless sendObj.sendEndless(" endless infos \n"); } // start from unity3d public void Start() { init(); } // init public void init() { remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port); client = new UdpClient(); // status print(IP+" : "+port); } // sendData public void sendString(string message) { remoteEndPoint = new IPEndPoint(IPAddress.Parse(IP), port); client = new UdpClient(); try { byte[] data = Encoding.UTF8.GetBytes(message); client.Send(data, data.Length, remoteEndPoint); } catch (Exception err) { print(err.ToString()); } } // endless test private void sendEndless(string testStr) { do { sendString(testStr); } while(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Trettim.Settings; using Trettim.Sicredi.DocumentLibrary.Entities; using Trettim.Sicredi.DocumentLibrary.Services; namespace Trettim.Sicredi.DocumentLibrary { public partial class SiteMaster : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { if (UAC.Logged) { litLogout.Visible = true; } else { litLogout.Visible = false; litLogon.Visible = true; } if (!Page.IsPostBack) { this.BindLabels(); } this.BindMenu(); } private void BindLabels() { litLogo.Text = "<a href='" + Param.SiteURL + "/Default.aspx'><img src='" + Param.SiteURL + "/Styles/img/logoSicredi.png' /></a>"; litLogout.Text = "<a href='" + Param.BackOfficeURL + "/Logout.aspx'><img src='" + Param.SiteURL + "/Styles/img/exit.png' width='26' height='26' Style='float: right; margin-top: -34px; margin-right: 10px' /></a>"; litFooter.Text = "<img src='" + Param.SiteURL + "/Styles/img/footer.png' /><img src='" + Param.SiteURL + "/Styles/img/cooperativa.png' width='30px;' height='30px' style='margin-top: -10px' />"; string margin = string.Empty; if (litLogout.Visible) { margin = "50"; } else { margin = "10"; } litLogon.Text = "<a href='" + Param.BackOfficeURL + "/FileList.aspx'><img src='" + Param.SiteURL + "/Styles/img/sureg.png' width='40px' height='40px' Style='float: right; margin-top: -40px; margin-right: " + margin + "px' /></a>"; } private void BindMenu() { String menuList;// = HttpContext.Current.Session["menuList"] as String; //if (menuList == null) { menuList = ServiceFactory.CreateConfigurationService.BuildMenu(); if (UAC.Logged) { menuList = menuList.Replace("</ul>", "<li><a href='#'>Admin</a><ul class='subnav' style='width:150px;'><li><a href=\"" + System.String.Concat(Param.BackOfficeURL, "/FileList.aspx\">Documentos</a></li><li><a href=\"" + System.String.Concat(Param.BackOfficeURL, "/NewsList.aspx\">Notícias</a></li><li><a href=\"" + System.String.Concat(Param.BackOfficeURL, "/UserList.aspx\">Usuários</a></li></ul></li></ul>")))); } foreach (var item in menuList) { } litMenu.Text = menuList; //HttpContext.Current.Session.Add("menuList", menuList); } // else //{ // litMenu.Text = menuList; //} int id = Convert.ToInt32(Request.QueryString["ID"]); string op = Request.QueryString["OP"]; if (String.IsNullOrEmpty(op)) { litMenu.Text = litMenu.Text.Replace(".aspx?ID=" + id + "\"", ".aspx?ID=" + id + "\" style=\"background-color:White;color:#0e6c0e;\""); } } } }
using System.Collections.Generic; namespace War { public class Player { private Deck _hand; public int CardCount { get { return _hand.Count; } } public int BountyCount { get; private set; } public Player() { _hand = new Deck(new List<Card>()); } public Card TakeCard(Card card) { _hand.Add(card); return card; } public Card PlayCard() { return _hand.Deal(); } public List<Card> PlayCard(int cardsToGet) { List<Card> cards = new List<Card>(); for (int i = 0; i < cardsToGet; i++) { cards.Add(_hand.Deal()); } return cards; } public void AddToBountyCount(int bountiesToAdd) { BountyCount += bountiesToAdd; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp; using LeagueSharp.Common; using TheCassiopeia.Commons; using TheCassiopeia.Commons.ComboSystem; namespace TheCassiopeia { class CassW: Skill { private CassQ _q; private CassR _r; public bool UseOnGapcloser; public CassW(SpellSlot slot) : base(slot) { SetSkillshot(0.5f, Instance.SData.CastRadius, Instance.SData.MissileSpeed, false, SkillshotType.SkillshotCircle); Range = 850; HarassEnabled = false; } public override void Initialize(ComboProvider combo) { _q = combo.GetSkill<CassQ>(); _r = combo.GetSkill<CassR>(); base.Initialize(combo); } public override void Execute(Obj_AI_Hero target) { if (_q.OnCooldown() && (!target.IsPoisoned() && !Provider.IsMarked(target))) { Cast(target); } } public override void Gapcloser(ComboProvider combo, ActiveGapcloser gapcloser) { if (UseOnGapcloser && (!_r.CanBeCast() || _r.GapcloserUltHp < ObjectManager.Player.HealthPercent)) { Cast(gapcloser.Sender); } } public override float GetDamage(Obj_AI_Hero enemy) { return 0; } public override void LaneClear() { var minions = MinionManager.GetMinions(900, MinionTypes.All, MinionTeam.NotAlly); if(!_q.OnCooldown() || minions.Any(minion => minion.IsPoisoned())) return; var farmLocation = MinionManager.GetBestCircularFarmLocation(minions.Select(minion => minion.Position.To2D()).ToList(), Instance.SData.CastRadius, 850); if (farmLocation.MinionsHit > 0) { Cast(farmLocation.Position); } base.LaneClear(); } public override int GetPriority() { return 1; } } }
using System; using System.Collections.Generic; using System.Text; namespace ConsoleAppInterfaceSeg.Model.Entities { public class Test { public Guid Id { get; set; } public Student Owner { get; set; } } }
using UnityEngine.UI; using UnityEngine; using System; namespace RPG.Stats { public class LevelDisplay : MonoBehaviour { // cached references BaseStats baseStats; void Awake() { baseStats = GameObject.FindWithTag("Player").GetComponent<BaseStats>(); } protected virtual void Update() { GetComponent<Text>().text = String.Format("{0:0}", baseStats.GetLevel()); } } }
using System.Collections; using System.Collections.Generic; using System.Timers; using UnityEngine; using UnityEngine.UI; public class DM : MonoBehaviour { private static DM _instance; public static DM Instance { get { return _instance; } } public Text textScreen; private int i = 0; private void Awake() { if (_instance != null && _instance != this) { Debug.Log("Duplicate DM found"); Destroy(this.gameObject); } else { _instance = this; } _instance.actors = new Dictionary<string, Entity>(); } // Start is called before the first frame update void Start() { StartCoroutine(ClearText(1f)); } private Dictionary<string, Entity> actors; public static void RegisterPlayer(string name, Entity self) { Debug.Log("Registering " + name); _instance.actors.Add(name, self); } IEnumerator ClearText(float time) { while (true) { if (Instance.msgTime < System.DateTime.Now) { SendMessage("..."); } yield return new WaitForSeconds(time); } } private System.DateTime msgTime; public static void SendMessage(string txt) { //Instance.msgTime = System.DateTime.Now.AddSeconds(2); //Instance.textScreen.text = txt; } // Update is called once per frame bool sceneInitiated = false; Scene scene; float timeLeft = 0f; void Update() { timeLeft += Time.deltaTime; if (timeLeft > 1f && sceneInitiated) { scene.Update(); timeLeft = 0f; } if (Input.GetKeyDown(KeyCode.Space)) { if (!sceneInitiated) { scene = new Scene(); //bug.Log("Scene created"); //scene._actors.Add(actors["player"]); //scene._actors.Add(actors["cals1"]); //scene._actors.Add(actors["cals2"]); //scene._actors.Add(actors["cals1"]); //bug.Log("Scene actors added"); scene.Start(); //ebug.Log("Scene started"); sceneInitiated = true; } scene.Update(); } //textScreen.text = i.ToString(); i++; } public static Entity FindActor(string name) { return Instance.actors[name]; } public Dictionary<string, bool> worldState = new Dictionary<string, bool>(); public static void SetWorldState(string key, bool value) { Instance.worldState[key] = value; } public static bool GetWorldState(string key) { return Instance.worldState[key]; } public static void PrintWorldState() { foreach (KeyValuePair<string, bool> pair in Instance.worldState) { Debug.Log(pair.Key + ":" + pair.Value); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BriefFebruar : MonoBehaviour { void OnSelect() { Debug.Log("Brief Februar ist sichtbar"); GetComponentInParent<MenuController>().SelectBriefFebruar(); } }
using System.IO; namespace VsmacHelper.Shared { public static class KnownStrings { private static readonly PathHelper _pathHelper = new PathHelper(); public const string DefaultVsmacVersion = "8.0"; public const string VsmacLogsFolderPath = "~/Library/Logs/VisualStudio"; public static readonly string VsMacLogFilePath = _pathHelper.GetFullPath(Path.Combine(VsmacLogsFolderPath, DefaultVsmacVersion, "Ide.log")); public static readonly string TelemetryLogFolder = Path.Combine(Path.GetTempPath(), "VSTelemetryLog"); public static readonly string TelemetryConfigFolder = _pathHelper.GetFullPath(Path.Combine(_pathHelper.GetHomeFolder(), "VSTelemetry")); public const string TelemetryConfigFilename = "channels.json"; public const string VisualStudioProcessName = "VisualStudio"; } }
using EchoNest; using EchoNest.Playlist; using Torshify.Radio.Framework; using Term = EchoNest.Term; namespace Torshify.Radio.EchoNest.Views.Style { public class StyleTrackStreamDataFavoriteHandler : FavoriteHandler<TrackStreamFavorite> { #region Methods public override bool CanHandleFavorite(Favorite favorite) { TrackStreamFavorite streamFavorite = favorite as TrackStreamFavorite; if (streamFavorite != null) { return streamFavorite.StreamData is StyleTrackStreamData; } return false; } protected override void Play(TrackStreamFavorite favorite) { var data = favorite.StreamData as StyleTrackStreamData; if (data != null) { Radio.Play(new StyleTrackStream(GetArgument(data), Radio, ToastService)); } else { ToastService.Show("Unable to play favorite"); } } protected override void Queue(TrackStreamFavorite favorite) { var data = favorite.StreamData as StyleTrackStreamData; if (data != null) { Radio.Queue(new StyleTrackStream(GetArgument(data), Radio, ToastService)); } else { ToastService.Show("Unable to play favorite"); } } private StaticArgument GetArgument(StyleTrackStreamData data) { StaticArgument argument = new StaticArgument(); argument.MinDanceability = data.MinDanceability; argument.MinEnergy = data.MinEnergy; argument.MinLoudness = data.MinLoudness; argument.MinTempo = data.MinTempo; argument.ArtistMinFamiliarity = data.ArtistMinFamiliarity; argument.ArtistMinHotttnesss = data.ArtistMinHotttnesss; argument.SongMinHotttnesss = data.SongMinHotttnesss; argument.Type = data.Type; FillTermList(data.Artist, argument.Artist); FillTermList(data.Styles, argument.Styles); FillTermList(data.Moods, argument.Moods); return argument; } private void FillTermList(Term[] terms, TermList target) { foreach (var term in terms) { target.Add(term); } } #endregion Methods } }
using System; namespace SoftwareAcademy { public abstract class WorldObject { private string name; public WorldObject(string name) { this.Name = name; } public string Name { get { return this.name; } set { if (value == null) { throw new ArgumentNullException("Name value cannot be null!"); } this.name = value; } } } }
using System; using System.Collections.Generic; using System.Linq; public class Program { static readonly LinkedList<int> s_numbers = new LinkedList<int>(); public static void Main(string[] args) { string[] tokens = Console.ReadLine().Split(' '); if(tokens == null || tokens.Count() < 1) { Console.WriteLine(0); return; } foreach(var word in tokens) { int number; if (Int32.TryParse(word, out number)) { s_numbers.AddLast(number); } else { int lastAddedNumber = s_numbers.Last(); s_numbers.RemoveLast(); int preLastAddedNumber = s_numbers.Last(); s_numbers.RemoveLast(); switch (word) { case "+": s_numbers.AddLast(preLastAddedNumber + lastAddedNumber); break; case "-": s_numbers.AddLast(preLastAddedNumber - lastAddedNumber); break; case "*": s_numbers.AddLast(preLastAddedNumber * lastAddedNumber); break; case "/": s_numbers.AddLast(preLastAddedNumber / lastAddedNumber); break; } } } Console.WriteLine(s_numbers.Last()); } }
namespace E05_SortByStringLength { using System; using System.Collections.Generic; using System.Linq; public class SortByStringLength { public static void Main(string[] args) { // You are given an array of strings. Write a method // that sorts the array by the length of its elements // (the number of characters composing them). // Example: // Lorem ipsum dolor sit amet, consectetur adipiscing elit. // // Result: // sit // amet // elit // Lorem // ipsum // dolor // adipiscing // consectetur Console.WriteLine("Please, enter an array of strings :"); string[] words = Console.ReadLine() .Split(new char[] { ' ', '\t', ',', '.' }, StringSplitOptions.RemoveEmptyEntries) .Select(ch => ch.ToString()) .ToArray(); List<string> sortedWords = new List<string>(); foreach (string word in SortByLength(words)) { sortedWords.Add(word); } for (int index = 0; index < sortedWords.Count; index++) { Console.WriteLine("position {0}: {1}", index, sortedWords[index]); } Console.WriteLine(); } private static IEnumerable<string> SortByLength(IEnumerable<string> wordsArray) { var sorted = from word in wordsArray orderby word.Length ascending select word; return sorted; } } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using WeRentCar.Entities; namespace WeRentCar.Data.EntityConfig { public class CustomerConfiguration : IEntityTypeConfiguration<Customer> { public void Configure(EntityTypeBuilder<Customer> builder) { builder.HasKey(obj => obj.CustomerID); builder.HasIndex(obj => obj.Ssn).IsUnique(); } } }
using System; using System.IO; using System.Linq; using System.Text; using Microsoft.Extensions.DependencyInjection; using QQWry; using QQWry.DependencyInjection; namespace Sample { class Program { private static void Main(string[] args) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); Console.WriteLine("QQWry Sample!"); var config = new QQWryOptions() { DbPath = MapRootPath("~/IP/qqwry.dat") }; #region QQWry Console.WriteLine(""); Console.WriteLine("QQWry"); var ipSearch = new QQWryIpSearch(config); for (var i = 0; i < 100; i++) { var ipLocation = ipSearch.GetIpLocation(GetRandomIp(ipSearch)); Write(ipLocation); } Console.WriteLine("记录总数" + ipSearch.IpCount); Console.WriteLine("版本" + ipSearch.Version); #endregion #region QQWry.DependencyInjection Console.WriteLine(""); Console.WriteLine("QQWry.DependencyInjection"); var service = new ServiceCollection(); service.AddQQWry(config); var serviceProvider = service.BuildServiceProvider(); using (var scope = serviceProvider.CreateScope()) { var ipSearchInterface = scope.ServiceProvider.GetRequiredService<IIpSearch>(); for (var i = 0; i < 100; i++) { var ipLocation = ipSearch.GetIpLocation(GetRandomIp(ipSearch)); Write(ipLocation); } Console.WriteLine("记录总数" + ipSearchInterface.IpCount); Console.WriteLine("版本" + ipSearchInterface.Version); } #endregion #region java to QQWry Console.WriteLine(""); Console.WriteLine("java to QQWry"); var qqWry = new Java2QQWry(config.DbPath); for (var i = 0; i < 100; i++) { var ip = GetRandomIp(ipSearch); var ipLocation = qqWry.SearchIPLocation(ip); Write(ip, ipLocation); } #endregion Console.ReadKey(); } private static void Write(IpLocation ipLocation) { Console.WriteLine($"ip:{ipLocation.Ip},country:{ipLocation.Country},area:{ipLocation.Area}"); } private static void Write(string ip, IPLocation ipLocation) { Console.WriteLine($"ip:{ip},country:{ipLocation.country},area:{ipLocation.area}"); } /// <summary> /// Maps a virtual path to a physical disk path. /// </summary> /// <param name="path">The path to map. E.g. "~/bin"</param> /// <returns>The physical path. E.g. "c:\inetpub\wwwroot\bin"</returns> public static string MapRootPath(string path) { path = path.Replace("~/", "").TrimStart('/').Replace('/', '\\'); return Path.Combine(AppDomain.CurrentDomain.BaseDirectory ?? string.Empty, path); } static string GetRandomIp(IIpSearch ipSearch) { while (true) { var sj = new Random(Guid.NewGuid().GetHashCode()); var s = ""; for (var i = 0; i <= 3; i++) { var q = sj.Next(0, 255).ToString(); if (i < 3) { s += (q + ".").ToString(); } else { s += q.ToString(); } } if (ipSearch.CheckIp(s)) { return s; } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerController : MonoBehaviour { public float speed = 0.5f; public float kasokuSpeed = 1.5f; public float jumpSpeed = 0.1f; private Rigidbody rB; void Start() { rB = GetComponent<Rigidbody>(); } void FixedUpdate() { float z = Input.GetAxis("Horizontal"); float x = Input.GetAxis("Vertical"); float y = 0f; float oldSpeed = speed; if (Input.GetKeyDown(KeyCode.Space) == true) { y = 1.0f; } if (Input.GetKeyDown(KeyCode.Z) == true) { speed = kasokuSpeed; } rB.AddForce(x * -speed, y * jumpSpeed, z * speed, ForceMode.Impulse); if (speed == kasokuSpeed) { speed = oldSpeed; } } }