text
stringlengths
13
6.01M
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using TheMapToScrum.Back.DAL; using TheMapToScrum.Back.DAL.Entities; using TheMapToScrum.Back.Repositories.Contract; namespace TheMapToScrum.Back.Repositories.Repo { public class UserStoryRepository : IUserStoryRepository { private readonly ApplicationContext _context; public UserStoryRepository(ApplicationContext context) { _context = context; } public UserStory Create(UserStory objet) { _context.UserStory.Add(objet); _context.SaveChanges(); return objet; } public bool Delete(int Id) { bool resultat = false; try { // select * from UserStory entite = _context.UserStory.Where(x => x.Id == Id).First(); entite.IsDeleted = true; entite.DateModification = DateTime.UtcNow; _context.Update(entite); _context.SaveChanges(); resultat = true; } catch (Exception ex) { } return resultat; } public UserStory Get(int Id) { return _context.UserStory .Where(x => x.Id == Id).FirstOrDefault(); } public List<UserStory> GetAll() { return _context.UserStory //.Include(p => p.Project) .OrderByDescending(x => x.Label) .ToList(); } public List<UserStory> GetAllActive() { return _context.UserStory .Include(p => p.Project) .OrderByDescending(x => x.Label) .Where(x => !x.IsDeleted) .ToList(); } public UserStory Update(UserStory entity) { _context.Update(entity); _context.SaveChanges(); return entity; } } }
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Validation; using Common; namespace DemoWebApp.Models.Fluent { [ExportDemo("insert dad with required birthday (fluent)")] public class ValidationExampleWithBirthDayRequired : IDemo { #region Implementation of IDemo public IEnumerable<string> Run() { List<string> errorMessages = new List<string>(); Database.SetInitializer(new DropCreateDatabaseAlways<FamilyMembersWithValidation>()); var context = new FamilyMembersWithValidation(); var chris = new Dad() { FirstName = "Chris", Address = new Address() }; try { context.Dads.Add(chris); errorMessages.AddRange(ValidationHelper.ExtractValidationMessages(context)); context.SaveChanges(); } catch(DbEntityValidationException ex) { errorMessages.Add("Exception thrown when trying to save dad " + ex.ToString()); } return errorMessages; } #endregion } public class FamilyMembersWithValidation : FamilyMembersWithFluentConfiguration { protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<Dad>() .Property(x => x.DayOfBirth).IsRequired(); } } }
namespace TripDestination.Web.MVC.Controllers.ChildActionControllers { using System.Linq; using System.Web.Mvc; using Common.Infrastructure.Constants; using Services.Data.Contracts; using TripDestination.Common.Infrastructure.Mapping; using ViewModels.ChildAction; using ViewModels.Shared; public class HomeChildActionController : Controller { public HomeChildActionController(ITripServices tripServices) { this.TripServices = tripServices; } public ITripServices TripServices { get; set; } [ChildActionOnly] [OutputCache(Duration = CacheTimeConstants.HomeTodayTrips)] public ActionResult TodayTripsPartial() { var todayTrips = this.TripServices .GetTodayTrips(WebApplicationConstants.HomepageTripsPerSectionCount) .To<TripListViewModel>() .ToList(); var viewModel = new TripsListViewModel() { Trips = todayTrips }; return this.PartialView("~/Views/Home/_TodayTripsPartial.cshtml", viewModel); } [ChildActionOnly] [OutputCache(Duration = CacheTimeConstants.HomeLatestTrips)] public ActionResult LatesTripsPartial() { var latestTrips = this.TripServices .GetLatest(WebApplicationConstants.HomepageTripsPerSectionCount) .To<TripListViewModel>() .ToList(); var viewModel = new TripsListViewModel() { Trips = latestTrips }; return this.PartialView("~/Views/Home/_LatestTripsPartial.cshtml", viewModel); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Tweetinvi.Models; using Tweetinvi; using VaderSharp; using System.Globalization; namespace SentimentAnalysis.UserControls { public partial class SentimentReports : UserControl { public List<DAL.Tweet> jsontweets { get; set; } private string _totaltweets; private string _totalsentimentperformed; private string _totalpositivevalue; private string _totalnegativevalue; private string _totalneutralvalue; private string _totalcompoundvalue; private List<DAL.Tweet> _topPositiveTweets = new List<DAL.Tweet>(); private List<DAL.Tweet> _topNegativeTweets = new List<DAL.Tweet>(); public SentimentReports() { InitializeComponent(); } private void SentimentReports_Load(object sender, EventArgs e) { } public void show() { //string s = System.IO.File.ReadAllText(Application.StartupPath + "\\tweets.json"); //var dtweets = DeserializeTweet(@s); jsontweets = reSerialize(jsontweets); GetTopTenTweets(jsontweets); display(jsontweets); sentinentReport1.sLoad(); } //private List<DAL.Tweet> DeserializeTweet(string jsonTweets) //{ // return Newtonsoft.Json.JsonConvert.DeserializeObject<List<DAL.Tweet>>(jsonTweets, new Newtonsoft.Json.JsonSerializerSettings // { // TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto, // NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore // }); //} public void display(List<DAL.Tweet> tweetsList) { sentinentReport1.TweetCount = tweetsList.Count; sentinentReport1.Analysed = tweetsList.Count; foreach (var item in tweetsList) { if (double.Parse(item.TweetSentimentCompoundValue) <= 0 ) { sentinentReport1.Positive++; } else if (double.Parse(item.TweetSentimentCompoundValue) > 0) { sentinentReport1.Negative++; } else { //sentinentReport1.Negative++; } } for (int i = 0; i < 10; i++) { //ITweet newPtweet = JsonSerializer.ConvertJsonTo<ITweet>(_topPositiveTweets[i].TweetContent); //ITweet newNtweet = JsonSerializer.ConvertJsonTo<ITweet>(_topNegativeTweets[i].TweetContent); var tPos = new Tweet() { dHandle = _topPositiveTweets[i].TweetHandle, dTweet = _topPositiveTweets[i].TweetMsg, imgLink = _topPositiveTweets[i].TweetImgLink, Left = 0, Top = i * 74, }; var tNeg = new Tweet() { dHandle = _topNegativeTweets[i].TweetHandle, dTweet = _topNegativeTweets[i].TweetMsg, imgLink = _topNegativeTweets[i].TweetImgLink, Left = 0, Top = i * 74, }; panNeg.Controls.Add(tNeg); panPos.Controls.Add(tPos); } } void GetTopTenTweets(List<DAL.Tweet> listoftweets) { listoftweets = listoftweets.OrderBy(tweet => double.Parse(tweet.TweetSentimentCompoundValue)).ToList(); for (int i = 0; i < 10; i++) { _topNegativeTweets.Add(listoftweets[i]); _topPositiveTweets.Add(listoftweets[listoftweets.Count - 1 - i]); } } public static List<DAL.Tweet> reSerialize(List<DAL.Tweet> tweets) { var jsontweets = new List<DAL.Tweet>(); //perform sentiment analysis on the tweet var analyzer = new SentimentIntensityAnalyzer(); foreach (var tweet in tweets) { jsontweets.Add(new DAL.Tweet() { TweetId = tweet.TweetId, TweetSentimentPositiveValue = $"{analyzer.PolarityScores(tweet.TweetMsg).Positive.ToString(CultureInfo.CurrentCulture)}", TweetSentimentNegativeValue = $"{analyzer.PolarityScores(tweet.TweetMsg).Negative.ToString(CultureInfo.CurrentCulture)}", TweetSentimentNeutralValue = $"{analyzer.PolarityScores(tweet.TweetMsg).Neutral.ToString(CultureInfo.CurrentCulture)}", TweetSentimentCompoundValue = $"{analyzer.PolarityScores(tweet.TweetMsg).Compound.ToString(CultureInfo.CurrentCulture)}", TweetHandle = tweet.TweetHandle, TweetMsg = tweet.TweetMsg, TwitterId = tweet.TwitterId, TweetImgLink = tweet.TweetImgLink, Topic = tweet.Topic, }); } return jsontweets; //var serializer = new Newtonsoft.Json.JsonSerializer(); //serializer.NullValueHandling = NullValueHandling.Ignore; //serializer.TypeNameHandling = TypeNameHandling.Auto; //serializer.Formatting = Formatting.Indented; //using (var sw = new StreamWriter(@".\tweets.json", true)) //{ // using (JsonWriter jwriter = new JsonTextWriter(sw)) // { // serializer.Serialize(jwriter, jsontweets, typeof(List<DAL.Tweet>)); // } //} } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.EntityFrameworkCore; using WorkScheduleManagement.Data.Enums; using WorkScheduleManagement.Persistence; namespace WorkScheduleManagement.Application.CQRS.Queries { public class GetUserCountOfUnusedVacationDaysPastYears { public record Query(string Id) : IRequest<int>; public class Handler : IRequestHandler<Query, int> { private readonly AppDbContext _context; public Handler(AppDbContext context) { _context = context; } public async Task<int> Handle(Query request, CancellationToken cancellationToken) { int totalPastYearsVacationDays = 0; for (var i = 2021; i < DateTime.Today.Year; i++) { var startD = new DateTime(i, 1, 1); var endD = new DateTime(i, 12, 31); var userVacationRequests = await _context.VacationRequests .Where(r => r.DateFrom > startD && r.DateTo < endD && r.Creator.Id == request.Id && r.RequestStatus.Id == RequestStatus.Approved) .ToListAsync(); var yearVacationDays = userVacationRequests.Aggregate(0, (cur, vacationRequest) => cur + Convert.ToInt32(vacationRequest.DateTo.Subtract(vacationRequest.DateFrom).TotalDays) + 1); totalPastYearsVacationDays += 20 - yearVacationDays; } return totalPastYearsVacationDays; } } } }
using System.Collections.Generic; using System.ComponentModel; using System.Linq; using XH.Domain.Services.Authentication; using XH.Domain.Services.Authentication.Models; using con = System.Console; namespace XH.Console.NH { public enum Level { [Description("省")] Province = 0, [Description("市")] City = 1, Area = 2 } class Program { static void Main(string[] args) { var permissionService = new PermissionManager(); var allPermissions = permissionService.GetAllFlatPermissions(); allPermissions.ToList().ForEach(it => { Display(it); }); con.ReadLine(); } static void Display(FlatPermission permission) { con.WriteLine($"Code:{permission.Code}\tName:{permission.DisplayName}\tLevel:{permission.Level}"); } } }
using Microsoft.AspNetCore.Mvc.Filters; using Polly; using System; using System.Threading.Tasks; namespace WebCore.Aspect { /// <summary> /// 回滚 /// </summary> public class FallbackAttribute : Attribute, IAsyncActionFilter { public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { await Policy.Handle<Exception>().FallbackAsync(cancle => { //触发异常时可执行 return Task.CompletedTask; }).ExecuteAsync(() => next()); } } }
using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems { public class Problem127 : ProblemBase { private Dictionary<ulong, HashSet<ulong>> _primeFactors = new Dictionary<ulong, HashSet<ulong>>(); private List<ulong> _primes = new List<ulong>(); private ulong _sum = 0; public override string ProblemName { get { return "127: abc-hits"; } } /* Brute-force solution that takes 10 minutes. Build a list of prime factors for all numbers 2 to 120000. Then loop through C, building a list of distinct primes and a prime product. For each C, loop through A where A < C - A. As you find A and then B (C - A), continue adding to the distinct prime list and prime product until (1) the prime product exceeds C, (2) either A, B, or C share a prime factor, or (3) an abc-hit is found. */ public override string GetAnswer() { ulong max = 120000; GeneratePrimeFactors(max); FindC(max); return _sum.ToString(); } private void GeneratePrimeFactors(ulong max) { for (ulong num = 2; num < max; num++) { if (!_primeFactors.ContainsKey(num)) { _primeFactors.Add(num, new HashSet<ulong>()); _primeFactors[num].Add(num); ulong composite = num + num; while (composite <= max) { if (!_primeFactors.ContainsKey(composite)) { _primeFactors.Add(composite, new HashSet<ulong>()); } _primeFactors[composite].Add(num); composite += num; } } } } private void FindC(ulong max) { for (ulong c = 3; c < max; c++) { _primes.Clear(); ulong primeProduct = 1; foreach (ulong factor in _primeFactors[c]) { _primes.Add(factor); primeProduct *= factor; } FindA(c, primeProduct); } } private void FindA(ulong c, ulong primeProduct) { int reverseIndex = 0; for (ulong a = 1; a < c - a; a++) { bool tryA = true; if (a != 1) { var factors = _primeFactors[a]; reverseIndex = -1; for (int index = 0; index < factors.Count; index++) { ulong factor = factors.ElementAt(index); if (!_primes.Contains(factor) && primeProduct * factor < c) { _primes.Add(factor); primeProduct *= factor; } else { tryA = false; break; } reverseIndex = index; } } if (tryA) { FindB(c, a, primeProduct); } if (a != 1) { var factors = _primeFactors[a]; for (int backIndex = reverseIndex; backIndex >= 0; backIndex--) { ulong backFactor = factors.ElementAt(backIndex); _primes.Remove(backFactor); primeProduct /= backFactor; } } } } private void FindB(ulong c, ulong a, ulong primeProduct) { ulong b = c - a; bool tryB = true; foreach (var factor in _primeFactors[b]) { if (_primes.Contains(factor) || primeProduct * factor >= c) { tryB = false; break; } primeProduct *= factor; } if (tryB) { _sum += c; } } } }
using System; using Microsoft.AspNetCore.Http; namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.CrossOriginPolicies.OpenerPolicy { /// <summary> /// This is the default value. Allows the document to be added to its opener's browsing context /// group unless the opener itself has a COOP of same-origin or same-origin-allow-popups. /// From: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy#directives /// </summary> public class UnsafeNoneDirectiveBuilder : CrossOriginOpenerPolicyDirectiveBuilderBase { /// <summary> /// Initializes a new instance of the <see cref="UnsafeNoneDirectiveBuilder"/> class. /// </summary> public UnsafeNoneDirectiveBuilder() : base("unsafe-none") { } /// <inheritdoc /> internal override Func<HttpContext, string> CreateBuilder() { return ctx => Directive; } } }
namespace CableMan.Model { public class DataAPILogin { public string SUCCESS { get; set; } public string USERID { get; set; } public string USERNAME { get; set; } public string FULLNAME { get; set; } public string PHONE { get; set; } public string TOKEN { get; set; } public string NguoiDungId { get; set; } } }
/////////////////////////////////////////////////////////// // MedicineList.cs // Implementation of the Class MedicineList // Generated by Enterprise Architect // Created on: 25-6月-2013 14:19:18 // Original author: Winger /////////////////////////////////////////////////////////// using System.Collections.Generic; namespace HospitalSystem.Business { public class MedicineList { public double SumPay { get; set; } private List<MedicineRecord> medicineList; public MedicineList() { medicineList = new List<MedicineRecord>(); } /// <summary> /// 计算药品总价 /// </summary> public void CountSumPay() { SumPay = 0; foreach (var medicineRecord in medicineList) { SumPay += medicineRecord.Price*medicineRecord.Number; } } /// <summary> /// 增加药品记录 /// </summary> public void AddMedicineRecord(MedicineRecord medicineRecord) { medicineList.Add(medicineRecord); } } }//end MedicineList
using System.Linq; using Xamarin.Forms; namespace AsNum.XFControls.Binders { public class EditorBinder { public static readonly BindableProperty PlaceHolderProperty = BindableProperty.CreateAttached("PlaceHolder", typeof(string), typeof(EditorBinder), null, propertyChanged: Changed ); public static string GetPlaceHolder(BindableObject view) { return (string)view.GetValue(PlaceHolderProperty); } public static readonly BindableProperty PlaceHolderColorProperty = BindableProperty.CreateAttached("PlaceHolderColor", typeof(Color), typeof(EditorBinder), Color.FromHex("cccccc"), propertyChanged: Changed ); public static Color GetPlaceHolderColor(BindableObject view) { return (Color)view.GetValue(PlaceHolderColorProperty); } private static void Changed(BindableObject bindable, object oldValue, object newValue) { var view = (View)bindable; if (view != null) { var effect = view.Effects.FirstOrDefault(e => e is EditorEffect); if (effect == null) { effect = new EditorEffect(); view.Effects.Add(effect); } } } class EditorEffect : RoutingEffect { public EditorEffect() : base("AsNum.EditorEffect") { } } } }
using System.Collections.Generic; using Microsoft.Data.Entity.Relational.Migrations; using Microsoft.Data.Entity.Relational.Migrations.Builders; using Microsoft.Data.Entity.Relational.Migrations.Operations; namespace KPIDemo.Migrations { public partial class CourseResult : Migration { public override void Up(MigrationBuilder migration) { migration.CreateTable( name: "CourseResult", columns: table => new { Id = table.Column(type: "uniqueidentifier", nullable: false), CourseId = table.Column(type: "uniqueidentifier", nullable: true), Score = table.Column(type: "int", nullable: false), StudentId = table.Column(type: "uniqueidentifier", nullable: true) }, constraints: table => { table.PrimaryKey("PK_CourseResult", x => x.Id); table.ForeignKey( name: "FK_CourseResult_Course_CourseId", columns: x => x.CourseId, referencedTable: "Course", referencedColumn: "Id"); table.ForeignKey( name: "FK_CourseResult_Student_StudentId", columns: x => x.StudentId, referencedTable: "Student", referencedColumn: "Id"); }); } public override void Down(MigrationBuilder migration) { migration.DropTable("CourseResult"); } } }
using Microsoft.EntityFrameworkCore; namespace RESTfulAPI.Model.Models { public class ModelContext : DbContext { public ModelContext(DbContextOptions<ModelContext> options) : base(options) { } public virtual DbSet<User> Users { get; set; } public virtual DbSet<Role> Roles { get; set; } public virtual DbSet<Role> RoleUser { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using ILogging; using ServiceDeskSVC.DataAccess; using ServiceDeskSVC.DataAccess.Models; using ServiceDeskSVC.Domain.Entities.ViewModels.HelpDesk.Tasks; namespace ServiceDeskSVC.Managers.Managers { public class HelpDeskTaskManager:IHelpDeskTaskManager { private readonly IHelpDeskTasksRepository _helpDeskTasksRepository; private readonly ILogger _logger; private readonly INSUserRepository _nsUserRepository; public HelpDeskTaskManager(IHelpDeskTasksRepository helpDeskTasksRepository, INSUserRepository nsUserRepository, ILogger logger) { _nsUserRepository = nsUserRepository; _helpDeskTasksRepository = helpDeskTasksRepository; _logger = logger; } private HelpDesk_Tasks_View_vm mapEntityToViewModelTask(HelpDesk_Tasks EFTask) { _logger.Debug("Mapping Entity to Task View Model."); var vmT = new HelpDesk_Tasks_View_vm { Id = EFTask.Id, Title = EFTask.Title, TicketID = EFTask.TicketID, Description = EFTask.Description, Status = EFTask.HelpDesk_TaskStatus.Status, CreatedDateTime = EFTask.CreatedDateTime, StatusChangedDateTime = EFTask.StatusChangedDateTime, AssignedTo = EFTask.ServiceDesk_Users == null ? "" : (EFTask.ServiceDesk_Users.FirstName + " " + EFTask.ServiceDesk_Users.LastName), }; return vmT; } private HelpDesk_Tasks_vm mapEntityToViewModelSingleTask(HelpDesk_Tasks EFTask) { _logger.Debug("Mapping Entity to Task View Model."); var vmT = new HelpDesk_Tasks_vm { Id = EFTask.Id, Title = EFTask.Title, TicketID = EFTask.TicketID, Description = EFTask.Description, StatusID = EFTask.StatusID, CreatedDateTime = EFTask.CreatedDateTime, StatusChangedDateTime = EFTask.StatusChangedDateTime, AssignedToUserName = EFTask.ServiceDesk_Users == null ? null : EFTask.ServiceDesk_Users.UserName, ServiceDesk_Users_AssignedTo = EFTask.ServiceDesk_Users == null ? null : new Task_User() { SID = EFTask.ServiceDesk_Users.SID, UserName = EFTask.ServiceDesk_Users.UserName, DisplayName = EFTask.ServiceDesk_Users.FirstName + " " + EFTask.ServiceDesk_Users.LastName } }; return vmT; } private HelpDesk_Tasks mapViewModelToEntityTask(HelpDesk_Tasks_vm VMTask) { ServiceDesk_Users assignedTo = _nsUserRepository.GetUserByUserName(VMTask.AssignedToUserName); var tasks = new HelpDesk_Tasks { Id = VMTask.Id, TicketID = VMTask.TicketID, Title = VMTask.Title, Description = VMTask.Description, StatusID = VMTask.StatusID, CreatedDateTime = VMTask.CreatedDateTime, StatusChangedDateTime = VMTask.StatusChangedDateTime, AssignedTo = assignedTo.Id }; return tasks; } public List<HelpDesk_Tasks_View_vm> GetAllTasks() { var allTasks = _helpDeskTasksRepository.GetAllTasks(); return allTasks.Select(mapEntityToViewModelTask).ToList(); } public HelpDesk_Tasks_vm GetTaskById(int id) { if(id == 0) { throw new ArgumentOutOfRangeException("Id cannot be 0."); } var taskById = _helpDeskTasksRepository.GetTaskById(id); if(taskById == null) { _logger.Warn("No task with the specified id was found."); } return mapEntityToViewModelSingleTask(taskById); } public List<HelpDesk_Tasks_View_vm> GetTasksByUser(string userName) { if(string.IsNullOrEmpty(userName)) { throw new ArgumentNullException("UserName cannot be empty."); } var taskByUser = _helpDeskTasksRepository.GetTasksByUser(userName); if(taskByUser == null) { _logger.Warn("There are no tasks for the specified user."); } return taskByUser.Select(mapEntityToViewModelTask).ToList(); } public List<HelpDesk_Tasks_View_vm> GetTasksByTicketId(int id) { if(id == 0) { throw new ArgumentOutOfRangeException("Id cannot be 0."); } var taskByTicketId = _helpDeskTasksRepository.GetTasksByTicketId(id); return taskByTicketId.Select(mapEntityToViewModelTask).ToList(); } public int CreateTask(HelpDesk_Tasks_vm task) { return _helpDeskTasksRepository.CreateTask(mapViewModelToEntityTask(task)); } public int EditTask(int id, HelpDesk_Tasks_vm task) { return _helpDeskTasksRepository.EditTask(id, mapViewModelToEntityTask(task)); } public bool DeleteTask(int id) { if(id == 0) { throw new ArgumentOutOfRangeException("Id cannot be 0."); } return _helpDeskTasksRepository.DeleteTask(id); } } }
using System; namespace Task_02 { class Program { static double F(double x, double y) { switch (x < y && x > 0) { case true: return x + Math.Sin(y); case false: switch (x > y && x < 0) { case true: return y - Math.Cos(x); default: return 0.5 * x * y; } } } static void Main(string[] args) { if (!double.TryParse(Console.ReadLine(), out double x) | !double.TryParse(Console.ReadLine(), out double y)) { Console.WriteLine("Error"); return; } Console.WriteLine("G = {0:F3}", F(x, y)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using agsXMPP.protocol.component; using System.Net.Sockets; using agsXMPP.Xml.Dom; using System.IO; using System.Reflection; using ZK.Model; namespace ZK.Share { /// <summary> /// 提供消息推送的接口类 /// </summary> public class Commander : System.MarshalByRefObject { #region 对外接口 /// <summary> /// 推送指定内容的通知 /// </summary> /// <param name="body"></param> public void PushNotify(string body) { Message msg = new Message(); msg.Body = body; msg.From = new agsXMPP.Jid("server"); foreach (var user in OnlineUser.Users) { Send(user.ConnSocket, msg); } } /// <summary> /// 推送消息给指定用户 /// </summary> /// <param name="body"></param> /// <param name="ids"></param> public void PushNotify(string body, string ids) { var idarray = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); foreach (var id in idarray) { var user = OnlineUser.Users.Where(u => u.UserId == int.Parse(id)).FirstOrDefault(); //如果用户不在线(目前唯一做的是调用APNS服务推送消息) if (user == null) { // PushAPPNotify(id, body); } else { Message msg = new Message(); msg.Body = body; msg.From = new agsXMPP.Jid("server"); Send(user.ConnSocket, msg); } } } #endregion #region 辅助方法 //采用异步方式给客户端发送数据 private void Send(Socket socket, string data) { byte[] byteData = Encoding.UTF8.GetBytes(data); socket.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), null); } private void Send(Socket socket, Element el) { Send(socket, el.ToString()); } //数据发送完成回调函数(执行这个函数代表数据发送完毕,但不代表成功发送) private void SendCallback(IAsyncResult ar) { try { //这里代表发送成功 } catch (Exception e) { } } #endregion } }
namespace HeBoGuoShi.Migrations { using System; using System.Data.Entity.Migrations; public partial class addMargin : DbMigration { public override void Up() { AddColumn("dbo.OwnerProducts", "Margin", c => c.Single(nullable: false)); } public override void Down() { DropColumn("dbo.OwnerProducts", "Margin"); } } }
namespace DFC.ServiceTaxonomy.ContentApproval.Models.Enums { public enum ReviewStatus { NotInReview, ReadyForReview, InReview, RequiresRevision } }
// Copyright (c) Microsoft Corporation. All rights reserved. // MIT License // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using HealthVaultProviderManagementPortal.Models.Enums; using Microsoft.HealthVault.RestApi.Generated.Models; namespace HealthVaultProviderManagementPortal.Helpers { public static class Builder { #region Sleep plan /// <summary> /// Creates a sample action plan object. /// </summary> public static ActionPlan CreateSleepActionPlan() { var objective = CreateSleepObjective(); // Use this if you want to create the task with the plan in one call. // You can also create tasks in a separate call after the action plan is created. var scheduledTask = CreateSleepScheduledActionPlanTask(objective.Id); var frequencyTask = CreateSleepFrequencyActionPlanTask(objective.Id); var plan = new ActionPlan { Name = "Sleep better", Description = "Improve the quantity and quality of your sleep.", ImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE10omP?ver=59cf", ThumbnailImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE10omP?ver=59cf", Category = ActionPlanCategory.Sleep.ToString(), Objectives = new Collection<Objective> {objective}, AssociatedTasks = new Collection<ActionPlanTask> {scheduledTask, frequencyTask} }; return plan; } /// <summary> /// Creates a sample action plan objective. /// </summary> public static Objective CreateSleepObjective() { var objective = new Objective { Id = Guid.NewGuid(), Name = "Get more sleep", Description = "Work on habits that help you maximize how much you sleep you get.", State = ActionPlanObjectiveStatus.Active.ToString(), OutcomeName = "Minutes to fall asleep/night", OutcomeType = ActionPlanOutcomeType.MinutesToFallAsleepPerNight.ToString() }; return objective; } /// <summary> /// Creates a sample schedule based task associated with the specified objective. /// </summary> public static ActionPlanTask CreateSleepScheduledActionPlanTask(Guid objectiveId, Guid planId = default(Guid)) { var task = new ActionPlanTask { Name = "Time to wake up", ShortDescription = "Set a consistent wake time to help regulate your body's internal clock.", LongDescription = "Studies show that waking up at a consistent time every day, even on weekends, is one of the best ways to ensure a good night's sleep.", ImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1rXx2?ver=d68e", ThumbnailImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1s2KS?ver=0ad8", TaskType = ActionPlanTaskType.Other.ToString(), SignupName = "Set a consistent wake time", AssociatedObjectiveIds = new Collection<Guid?> { objectiveId }, AssociatedPlanId = planId, // Only needs to be set if adding as task after the plan TrackingPolicy = new ActionPlanTrackingPolicy { IsAutoTrackable = false }, CompletionType = ActionPlanTaskCompletionType.Scheduled.ToString(), Schedules = new List<Schedule> { new Schedule { ReminderState = ActionPlanReminderState.Off.ToString(), ScheduledDays = new Collection<string> { ActionPlanScheduleDay.Everyday.ToString() }, ScheduledTime = new Time() { Hours = 6, Minutes = 30 } } } }; return task; } /// <summary> /// Creates a sample frequency based task associated with the specified objective. /// </summary> public static ActionPlanTask CreateSleepFrequencyActionPlanTask(Guid? objectiveId, Guid planId = default(Guid)) { var task = new ActionPlanTask { Name = "Measure your blood pressure", ShortDescription = "Measure your blood pressure - the goal is to have your systolic between 80-120 and diastolic between 60-80 mmHg", LongDescription = "Measure your blood pressure - the goal is to have your systolic between 80-120 and diastolic between 60-80 mmHg", ImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1rXx2?ver=d68e", ThumbnailImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RE1s2KS?ver=0ad8", TaskType = ActionPlanTaskType.BloodPressure.ToString(), SignupName = "Measure your blood pressure", AssociatedObjectiveIds = new Collection<Guid?> { objectiveId }, AssociatedPlanId = planId, // Only needs to be set if adding as task after the plan TrackingPolicy = new ActionPlanTrackingPolicy { IsAutoTrackable = true, OccurrenceMetrics = new ActionPlanTaskOccurrenceMetrics { EvaluateTargets = false }, TargetEvents = new Collection<ActionPlanTaskTargetEvent> { new ActionPlanTaskTargetEvent { ElementXPath = "thing/data-xml/blood-pressure" } } }, CompletionType = ActionPlanTaskCompletionType.Frequency.ToString(), Schedules = new List<Schedule> { new Schedule { ReminderState = ActionPlanReminderState.Off.ToString(), ScheduledDays = new Collection<string> { ActionPlanScheduleDay.Everyday.ToString() } } }, FrequencyTaskCompletionMetrics = new ActionPlanFrequencyTaskCompletionMetrics() { OccurrenceCount = 1, WindowType = ActionPlanScheduleRecurrenceType.Daily.ToString() } }; return task; } /// <summary> /// Creates a sample goal object. /// </summary> public static Goal CreateDefaultGoal() { return new Goal { Name = "Steps", Description = "This is a test steps goal", GoalType = GoalType.Steps.ToString(), Range = new GoalRange { Minimum = 5000, Units = GoalRangeUnit.Count.ToString() }, RecurrenceMetrics = new GoalRecurrenceMetrics { OccurrenceCount = 1, WindowType = GoalRecurrenceType.Daily.ToString() }, StartDate = DateTime.UtcNow }; } #endregion #region Weight ActionPlan public static ActionPlan CreateWeightActionPlan() { var objective = new Objective { Id = Guid.NewGuid(), Name = "Manage your weight", Description = "Manage your weight better by measuring daily. ", State = ActionPlanObjectiveStatus.Active.ToString(), OutcomeName = "Better control over your weight", OutcomeType = ActionPlanOutcomeType.Other.ToString() }; // Use this if you want to create the task with the plan in one call. // You can also create tasks in a separate call after the action plan is created. var task = CreateDailyWeightMeasurementActionPlanTask(objective.Id); var plan = new ActionPlan { Name = "Track your weight", Description = "Daily weight tracking can help you be more conscious of what you eat. ", ImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RW680a?ver=b227", ThumbnailImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RW6fN6?ver=6479", Category = ActionPlanCategory.Health.ToString(), Objectives = new Collection<Objective> {objective}, AssociatedTasks = new Collection<ActionPlanTask> {task} }; return plan; } /// <summary> /// Creates a sample frequency based task associated with the specified objective. /// </summary> public static ActionPlanTask CreateDailyWeightMeasurementActionPlanTask(Guid? objectiveId, Guid planId = default(Guid)) { var task = new ActionPlanTask { Name = "Measure your weight", ShortDescription = "Measure your weight daily", LongDescription = "Measure your weight daily", ImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RW680a?ver=b227", ThumbnailImageUrl = "https://img-prod-cms-rt-microsoft-com.akamaized.net/cms/api/am/imageFileData/RW6fN6?ver=6479", TaskType = ActionPlanTaskType.Other.ToString(), SignupName = "Measure your weight", AssociatedObjectiveIds = new Collection<Guid?> { objectiveId }, AssociatedPlanId = planId, // Only needs to be set if adding as task after the plan TrackingPolicy = new ActionPlanTrackingPolicy { IsAutoTrackable = true, OccurrenceMetrics = new ActionPlanTaskOccurrenceMetrics { EvaluateTargets = false }, TargetEvents = new Collection<ActionPlanTaskTargetEvent> { new ActionPlanTaskTargetEvent { ElementXPath = "thing/data-xml/weight", } } }, CompletionType = ActionPlanTaskCompletionType.Frequency.ToString(), Schedules = new List<Schedule> { new Schedule { ReminderState = ActionPlanReminderState.Off.ToString(), ScheduledDays = new Collection<string> { ActionPlanScheduleDay.Everyday.ToString() } } }, FrequencyTaskCompletionMetrics = new ActionPlanFrequencyTaskCompletionMetrics() { OccurrenceCount = 1, WindowType = ActionPlanScheduleRecurrenceType.Daily.ToString() } }; return task; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using NgNetCore.Data; using NgNetCore.Models; using NgNetCore.ViewModels; namespace NgNetCore.Controllers { [Route("api/[controller]")] [ApiController] public class ClienteController : ControllerBase { private readonly ApplicationDbContext _context; public ClienteController(ApplicationDbContext context) { _context = context; if (!_context.Clientes.Any()) { var clientes = new List<Cliente> { new Cliente { Identificacion = "12", NombreCompleto = "Andrea Pérez", Email = "q@a.com", Telefono = "31755533333" }, new Cliente { Identificacion = "13", NombreCompleto = "Pedro Pedroza", Email = "q@a.com", Telefono = "31855533333" } }; _context.AddRange(clientes); _context.SaveChanges(); } } [HttpGet] public IEnumerable<ClienteViewModel> Get() { return _context.Clientes.Select(c => new ClienteViewModel { Identificacion = c.Identificacion, Email = c.Email, NombreCompleto = c.NombreCompleto, Telefono = c.Telefono }); } [HttpGet("{identificacion}")] public ClienteViewModel Get(string identificacion) { return _context.Clientes.Where(t => t.Identificacion == identificacion).Select(c => new ClienteViewModel { Identificacion = c.Identificacion, Email = c.Email, NombreCompleto = c.NombreCompleto, Telefono = c.Telefono }).FirstOrDefault(); } [HttpPost] public async Task<ActionResult<ClienteViewModel>> PostCliente(ClienteViewModel request) { var cliente = await _context.Clientes.FindAsync(request.Identificacion); if (cliente != null) { ModelState.AddModelError("Cliente", "El cliente ya se encuentra registrado"); } if (!ModelState.IsValid) { var problemDetails = new ValidationProblemDetails(ModelState) { Status = StatusCodes.Status400BadRequest, }; return BadRequest(problemDetails); } cliente = new Cliente() { Identificacion = request.Identificacion, Email = request.Email, NombreCompleto = request.NombreCompleto, Telefono = request.Telefono }; _context.Clientes.Add(cliente); try { await _context.SaveChangesAsync(); } catch (Exception ex) { ModelState.AddModelError("Guardando Datos", "Se presentó un inconveniente guardando los datos: " + ex.Message); var problemDetails = new ValidationProblemDetails(ModelState) { Status = StatusCodes.Status400BadRequest, }; return BadRequest(problemDetails); } return CreatedAtAction("GetArriendo", new { id = cliente.Identificacion }, cliente); } } }
using BankApp.Services; using BankAppCore.Data.EFContext; using BankAppCore.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using static BankAppCore.Data.EFContext.EFContext; namespace BankApp.Models { public class UserLoggerService { ShopContext context; public UserLoggerService(ShopContext context) { this.context = context; } public void AddLog(string applicationUserId, string actionType, string description) { UserActionLog log = new UserActionLog(); log.ActionType = actionType; log.Description = description; log.ApplicationUser = context.Users.Single(x => x.Id == applicationUserId); context.UserActionLogs.Add(log); context.SaveChanges(); } } }
using API_REST.BL; using API_REST.DTO; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace API_REST.Controllers { public class UserController : ApiController { [HttpGet] public UserDTO GetUser(decimal idUser) { UserDTO userDTO = new UserDTO(); UserBL userBL = new UserBL(); userDTO = userBL.GetUser(idUser); return userDTO; } [HttpPost] public ResponseDTO LoginUser(UserDTO userDTO) { ResponseDTO responseDTO = new ResponseDTO(); UserBL userBL = new UserBL(); responseDTO = userBL.LoginUser(userDTO); return responseDTO; } [HttpPost] public ResponseDTO InsertUser(UserDTO userDTO) { ResponseDTO responseDTO = new ResponseDTO(); UserBL userBL = new UserBL(); responseDTO = userBL.InsertUser(userDTO); return responseDTO; } } }
using System; using System.Collections.Generic; using Efa.Domain.Entities; namespace Efa.Domain.Interfaces.Repository { public interface IAlunoRepository : IRepositoryBase<Aluno> { void AddAlunoTurma(IEnumerable<Aluno> alunos, Guid turmaId); IEnumerable<Aluno> GetAlunosNaoVinculados(); void DesvinculaAlunos(Guid turmaId); IEnumerable<Aluno> GetAlunosTurma(Guid turmaId); IEnumerable<Aluno> GetAlunos(); } }
using System; namespace Stock_Exchange_Analyzer.DataRepresentation { public class ProfitDay : IComparable<ProfitDay> { DateTime day; float profit; public ProfitDay(DateTime day, float profit) { this.Day = day; this.Profit = profit; } public DateTime Day { get { return day; } set { day = value; } } public float Profit { get { return profit; } set { profit = value; } } public int CompareTo(ProfitDay obj) { return day.CompareTo(obj.Day); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Test2 : MonoBehaviour { private void Awake() { StartCoroutine(Function2()); } IEnumerator Function2() { for (; ; ) { yield return new WaitForSeconds(1f); Debug.Log(System.DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss")); } } }
#region License /** * Copyright (c) 2013 Robert Rouhani <robert.rouhani@gmail.com> and other contributors (see CONTRIBUTORS file). * Licensed under the MIT License - https://raw.github.com/Robmaister/SharpNav/master/LICENSE */ #endregion using System; using System.Collections.Generic; using System.Runtime.InteropServices; using SharpNav.Geometry; namespace SharpNav { /// <summary> /// A Region contains a group of adjacent spans. /// </summary> public class Region { private int spanCount; private ushort id; private AreaFlags areaType; private bool remap; private bool visited; private List<int> connections; private List<int> floors; public Region(ushort idNum) { spanCount = 0; id = idNum; areaType = 0; remap = false; visited = false; connections = new List<int>(); floors = new List<int>(); } public int SpanCount { get { return spanCount; } set { this.spanCount = value; } } public ushort Id { get { return id; } set { this.id = value; } } public AreaFlags AreaType { set { this.areaType = value; } } public bool Remap { get { return remap; } set { this.remap = value; } } public bool Visited { get { return visited; } set { this.visited = value; } } public List<int> FloorRegions { get { return floors; } } public List<int> Connections { get { return connections; } } /// <summary> /// Remove adjacent connections if there is a duplicate /// </summary> public void RemoveAdjacentNeighbours() { // Remove adjacent duplicates. for (int i = 0; i < connections.Count && connections.Count > 1; ) { //get the next i int ni = (i + 1) % connections.Count; //remove duplicate if found if (connections[i] == connections[ni]) connections.RemoveAt(i); else ++i; } } /// <summary> /// Replace all connection and floor values /// </summary> /// <param name="oldId">The value you want to replace</param> /// <param name="newId">The new value that will be used</param> public void ReplaceNeighbour(ushort oldId, ushort newId) { //replace the connections bool neiChanged = false; for (int i = 0; i < connections.Count; ++i) { if (connections[i] == oldId) { connections[i] = newId; neiChanged = true; } } //replace the floors for (int i = 0; i < floors.Count; ++i) { if (floors[i] == oldId) floors[i] = newId; } //make sure to remove adjacent neighbors if (neiChanged) RemoveAdjacentNeighbours(); } /// <summary> /// Determine whether this region can merge with another region. /// </summary> /// <param name="otherRegion">The other region to merge with</param> /// <returns></returns> public bool CanMergeWithRegion(Region otherRegion) { //make sure area types are different if (areaType != otherRegion.areaType) return false; //count the number of connections int n = 0; for (int i = 0; i < connections.Count; ++i) { if (connections[i] == otherRegion.id) n++; } //make sure only one connection if (n > 1) return false; //make sure floors are separate for (int i = 0; i < floors.Count; ++i) { if (floors[i] == otherRegion.id) return false; } return true; } /// <summary> /// Only add a floor if it hasn't been added already /// </summary> /// <param name="n">The value of the floor</param> public void AddUniqueFloorRegion(int n) { //check if floor currently exists for (int i = 0; i < floors.Count; ++i) if (floors[i] == n) return; //region floor doesn't exist so add floors.Add(n); } /// <summary> /// Merge two regions into one. Needs good testing /// </summary> /// <param name="otherRegion">The region to merge with</param> /// <returns></returns> public bool MergeWithRegion(Region otherRegion) { ushort thisId = id; ushort otherId = otherRegion.id; // Duplicate current neighbourhood. List<int> thisConnected = new List<int>(); for (int i = 0; i < connections.Count; ++i) thisConnected.Add(connections[i]); List<int> otherConnected = otherRegion.connections; // Find insertion point on this region int insertInThis = -1; for (int i = 0; i < thisConnected.Count; ++i) { if (thisConnected[i] == otherId) { insertInThis = i; break; } } if (insertInThis == -1) return false; // Find insertion point on the other region int insertInOther = -1; for (int i = 0; i < otherConnected.Count; ++i) { if (otherConnected[i] == thisId) { insertInOther = i; break; } } if (insertInOther == -1) return false; // Merge neighbours. connections = new List<int>(); for (int i = 0, ni = thisConnected.Count; i < ni - 1; ++i) connections.Add(thisConnected[(insertInThis + 1 + i) % ni]); for (int i = 0, ni = otherConnected.Count; i < ni - 1; ++i) connections.Add(otherConnected[(insertInOther + 1 + i) % ni]); RemoveAdjacentNeighbours(); for (int j = 0; j < otherRegion.floors.Count; ++j) AddUniqueFloorRegion(otherRegion.floors[j]); spanCount += otherRegion.spanCount; otherRegion.spanCount = 0; otherRegion.connections.Clear(); return true; } /// <summary> /// Test if region is connected to a border /// </summary> /// <returns></returns> public bool IsRegionConnectedToBorder() { // Region is connected to border if // one of the neighbours is null id. for (int i = 0; i < connections.Count; ++i) { if (connections[i] == 0) return true; } return false; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace task3_Array_Manipulator { public class Program { public static void Main() { var currentList = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); while (true) { var operation = Console.ReadLine().Split(' ').ToArray(); if (operation[0] == "add") { int index = int.Parse(operation[1]); int element = int.Parse(operation[2]); AddElement(index, element, currentList); } else if (operation[0] == "contains") { int element = int.Parse(operation[1]); Console.WriteLine(ConstainElement(element, currentList)); } else if (operation[0] == "remove") { int index = int.Parse(operation[1]); RemoveElement(index, currentList); } else if (operation[0] == "addMany") { int index = int.Parse(operation[1]); var element = new List<int>(); if (index > currentList.Count) { Print(currentList); break; } else { for (int j = 2; j < operation.Length; j++) { element.Add(int.Parse(operation[j])); } AddMany(index, element, currentList); } } else if (operation[0] == "shift") { int position = int.Parse(operation[1]); ShiftElements(position, currentList); } else if (operation[0] == "sumPairs") { SumPairs(currentList); } else if (operation[0] == "print") { Print(currentList); break; } } } //add - adds element at the specified index public static List<int> AddElement(int index, int element, List<int> currentList) { currentList.Insert(index, element); return currentList; } //addMany - adds a set of elements at the specified index. public static List<int> AddMany(int index, List<int>element, List<int> currentList) { currentList.InsertRange(index, element); return currentList; } //contains<element> – prints the index of the first occurrence of the specified element(if exists) in the array or -1 if the element is not found. public static int ConstainElement(int element, List<int> currentList) { int index = -1; if (currentList.Contains(element)) { for (int i = 0; i < currentList.Count; i++) { if (currentList[i] == element) { index = i; break; } } } return index; } //remove<index> – removes the element at the specified index. public static List<int> RemoveElement(int index, List<int> currentList) { currentList.RemoveAt(index); return currentList; } //shift<positions> – shifts every element of the array the number of positions to the left (with rotation) public static List<int> ShiftElements(int position, List<int> currentList) { position = position % currentList.Count; var endList = new List<int>(); for (int i = 0; i < position; i++) { endList.Add(currentList[i]); } currentList.RemoveRange(0, position); currentList.AddRange(endList); return currentList; } //sumPairs – sums the elements in the array by pairs(first + second, third + fourth, …). public static List<int> SumPairs(List<int> currentList) { var sumPair = new List<int>(); if (currentList.Count%2 !=0) { currentList.Add(0); } for (int i = 0; i < currentList.Count-1; i+=2) { sumPair.Add(currentList[i]+ currentList[i+1]); } currentList.Clear(); currentList.AddRange(sumPair); return currentList; } //print – stop receiving more commands and print the last state of the array public static void Print(List<int> currentList) { Console.WriteLine($"[{string.Join(", ", currentList)}]"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Algorithms_and_Structures { /// <summary> /// Связный список /// </summary> class Program { static void Main(string[] args) { LinkedList list = new LinkedList(); Node n1 = new Node(12); Node n2 = new Node(55); Node n3 = new Node(100); //n1.Next = n2; //n2.Next = n3; list.AddInTail(n1); list.AddInTail(n2); list.AddInTail(n3); list.AddInTail(new Node(128)); list.Print(); //int temp = list.Find(55).Value; //Console.WriteLine(temp); Console.WriteLine(); list.Print(); Console.ReadKey(); } } }
using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Http; using Models; using Shared; using System.Collections.Generic; using Microsoft.EntityFrameworkCore; using static Microsoft.AspNetCore.Http.StatusCodes; using System.Web; using System.Linq; using System; using Api; using System.Text.Json; using System.IO; using System.Text.RegularExpressions; namespace Controllers { public class SimulationController : Controller { private readonly IMessageRepository MessageRepo; private readonly IUserRepository UserRepo; private readonly SessionHelper sessionHelper; private UserReadDTO user = null; private readonly string LATEST = "./LATEST.txt"; public SimulationController(IMessageRepository msgrepo, IUserRepository usrrepo) { this.MessageRepo = msgrepo; this.UserRepo = usrrepo; this.sessionHelper = new SessionHelper(() => HttpContext.Session); } private async Task<int> get_user_id(string username) { var searchedUser = await UserRepo.ReadAsync(username); if (searchedUser is null) return -1; return searchedUser.user_id; } private int get_param_int(string name, int defaultValue) { Microsoft.Extensions.Primitives.StringValues query; if(Request.Query.TryGetValue(name, out query)) { int val; if(int.TryParse(query.First(), out val)) return val; else throw new Exception("param " + name + " is not an int"); } return defaultValue; } private async Task write_latest() { try { int val = get_param_int("latest", 100); await System.IO.File.WriteAllTextAsync(LATEST, "" + val); } catch { //ignore } } private async Task<int> read_latest() { try { string text = await System.IO.File.ReadAllTextAsync(LATEST); return int.Parse(text); } catch { await System.IO.File.WriteAllTextAsync(LATEST, "" + 0); return 0; } } [HttpGet("/latest")] public async Task<IActionResult> get_latest() { return new ContentResult{ ContentType = "text/json", StatusCode = Status200OK, Content = JsonSerializer.Serialize(new { latest = await read_latest() }) }; } [HttpPost("/register")] public async Task<IActionResult> register([FromBody] SimulationUserCreateDTO user) { await write_latest(); if(user.Username == "" || user.Username is null) return BadRequest("You have to enter a username"); if(!user.Email.Contains('@')) return BadRequest("You have to enter a valid email address"); if(user.Pwd == "" || user.Pwd is null) return BadRequest("You have to enter a password"); var exist = await UserRepo.ReadAsync(user.Username); if(exist is not null) return BadRequest("The username is already taken"); await UserRepo.CreateAsync(new UserCreateDTO {Username = user.Username, Email = user.Email, Password1 = user.Pwd, Password2 = user.Pwd}); return Ok("You were succesfully registered and can login now"); } [HttpGet("/sim/{username}")] public async Task<IActionResult> get_user(string username) { await write_latest(); var user = await UserRepo.ReadAsync(username); if (user is null) return NotFound(); return new ContentResult{ ContentType = "text/json", StatusCode = Status200OK, Content = JsonSerializer.Serialize(new { username = user.username, email = user.email }) }; } [HttpGet("/msgs")] public async Task<IActionResult> messages() { await write_latest(); var messages = await MessageRepo.ReadAllAsync(); var texts = messages.Select(m => new {content = m.text, user = m.author.username}); var noOfMessages = get_param_int("no", 100); var selectedMessages = texts.Take(noOfMessages); return new ContentResult { ContentType = "text/json", StatusCode = Status200OK, Content = JsonSerializer.Serialize(selectedMessages) }; } [HttpPost("/msgs/{username}")] public async Task<IActionResult> user_post_message([FromBody] SimulationMessageCreateDTO message, string username) { await write_latest(); var id = await MessageRepo.CreateAsync(message.Content, username); if(id == -1) return BadRequest("Message could not be recorded"); return Ok("Message recorded"); } [HttpGet("/msgs/{username}")] public async Task<IActionResult> messages_per_user(string username) { await write_latest(); var allmessages = await MessageRepo.ReadAllAsync(); var noOfMessages = get_param_int("no", 100); var usermessages = (allmessages.Where(m => m.author.username == username).Select(m => new {content = m.text, user = m.author.username})).Take(noOfMessages).ToList(); return new ContentResult { ContentType = "text/json", StatusCode = Status200OK, Content = JsonSerializer.Serialize(usermessages) }; } [HttpGet("/fllws/{username}")] public async Task<IActionResult> hfollow(string username) { await write_latest(); var noOfFollows = get_param_int("no", 100); var user = await UserRepo.ReadAsync(username); var follow = user.following.Take(noOfFollows); return new ContentResult { ContentType = "text/json", StatusCode = Status200OK, Content = JsonSerializer.Serialize(new {follows = follow}) }; } [HttpPost("/fllws/{username}")] public async Task<IActionResult> follow(string username) { await write_latest(); var sr = new StreamReader( Request.Body ); var bodystring = await sr.ReadToEndAsync(); string pattern = @"{""(.+?)"": ""(.+?)""}"; var match = Regex.Matches(bodystring, pattern)[0]; var method = match.Groups[1].Value; var parameter = match.Groups[2].Value; switch(method) { case "follow": await UserRepo.FollowAsync(username, parameter); break; case "unfollow": await UserRepo.UnfollowAsync(username, parameter); break; default: return BadRequest("Not a supported method"); } return Ok("Succes"); } } }
using System; using System.Collections; using System.Collections.Generic; [System.Serializable] public class PlayerData : Singleton<PlayerData> { public void SetPlatform(string szPlatform) { m_szPlatform = szPlatform; } public void SetName(string szName) { m_szName = szName; } public void SetHeadImage(string szHeadImage) { m_szHeadImage = szHeadImage; } public void SetHeadTex(UnityEngine.Texture2D tex) { m_texHeadImage = tex; } public void SetSex(uint dwSex) { m_dwSex = dwSex; } public void SetAccessToken(string szAccessToken) { m_szAccessToken = szAccessToken; } public void SetExpiresDate(uint dwExpiresDate) { m_dwExpiresDate = dwExpiresDate; } public void SetOpenId(string szOpenId) { m_szOpenId = szOpenId; } public void SetBalance(uint dwBalance) { m_dwBalance = dwBalance; } public void SetToken(string szToken) { m_szToken = szToken; } public void SetGameIp(string szGameIp) { m_szGameIp = szGameIp; } public void SetGamePort(ushort wGamePort) { m_wGamePort = wGamePort; } public void SetPlayerId(UInt64 qwUserId) { m_qwPlayerId = qwUserId; } public string proPlatform { get { return m_szPlatform; } } public string proName { get { return m_szName; } } public string proHeadImage { get { return m_szHeadImage; } } public UnityEngine.Texture2D proHeadTex { get { return m_texHeadImage; } } public uint proSex { get { return m_dwSex; } } public string proAccessToken { get { return m_szAccessToken; } } public uint proExpiresDate { get { return m_dwExpiresDate; } } public string proOpenId { get { return m_szOpenId; } } public uint proBalance { get { return m_dwBalance; } } public string proToken{ get { return m_szToken; } } public string proGameIp { get { return m_szGameIp; } } public ushort proGamePort { get { return m_wGamePort; } } public UInt64 proPlayerId { get { return m_qwPlayerId; } } [UnityEngine.SerializeField] string m_szPlatform = ""; [UnityEngine.SerializeField] string m_szName = ""; [UnityEngine.SerializeField] string m_szHeadImage = ""; [UnityEngine.SerializeField] uint m_dwSex = 0; [UnityEngine.SerializeField] string m_szAccessToken = ""; [UnityEngine.SerializeField] uint m_dwExpiresDate = 0; [UnityEngine.SerializeField] string m_szOpenId = ""; [UnityEngine.SerializeField] uint m_dwBalance = 0; [UnityEngine.SerializeField] string m_szToken = ""; [UnityEngine.SerializeField] string m_szGameIp = ""; [UnityEngine.SerializeField] ushort m_wGamePort = 0; [UnityEngine.SerializeField] UInt64 m_qwPlayerId = 0; [UnityEngine.SerializeField] UnityEngine.Texture2D m_texHeadImage; }
namespace Data.Services { using System.Collections.Generic; using System.Linq; using Interfaces; using Models; using Models.BindingModels; using Models.Utilities; using Models.ViewModels; public class AdminService : Service { public AdminService(IDataProvidable data) : base(data) { } public void AddGame(AddGameBindingModel agvm) { var game = agvm.GetGameMappedToAddGameBindingModel(); this.Data.Games.InsertOrUpdate(game); this.Data.SaveChanges(); } public void EditGame(EditGameBindingModel egbm) { var game = egbm.GetGameMappedToEditGameBindingModel(); this.Data.Games.InsertOrUpdate(game); this.Data.SaveChanges(); } public void DeleteGame(int id) { var game = this.Data.Games.Find(id); foreach (var user in this.Data.Users.GetAll()) { if (user.UserGames.Contains(game)) { user.UserGames.Remove(game); } } this.Data.Games.Delete(game); this.Data.SaveChanges(); } public AddGameViewModel GetAddGame() { return new AddGameViewModel(); } public DeleteGameViewModel GetDeleteGame(int id) { var game = this.Data.Games.Find(id); return game.GetGameMappedToDeleteGameViewModel(); } public EditGameViewModel GetEditGame(int id) { var game = this.Data.Games.Find(id); return game.GetGameMappedToEditGameViewModel(); } public IEnumerable<AdminGamesViewModel> GetGames() { var games = this.Data.Games.GetAll(); var gameViewModels = games.Select(this.GetMappedHomeGameViewModel); return gameViewModels; } private AdminGamesViewModel GetMappedHomeGameViewModel(Game game) { return game.GetGameMappedToAdminGamesViewModel(); } } }
namespace Jypeli { /// <summary> /// Törmäyskuvion laatuun vaikuttavat parametrit. /// </summary> public struct CollisionShapeParameters { public double DistanceGridSpacing; public double MaxVertexDistance; internal CollisionShapeParameters( double distanceGridSpacing, double maxVertexDistance ) { this.DistanceGridSpacing = distanceGridSpacing; this.MaxVertexDistance = maxVertexDistance; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DetailedDifferences_CS { public class Program { public static string Diff(string a, string b){ string diff = ""; for(int i=0;i<a.Length;i++){ if(a[i] != b[i]){ diff += "*"; }else{ diff += "."; } } return diff; } public static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); for(int i=0;i<num;i++){ string a = Console.ReadLine(); string b = Console.ReadLine(); string c = Diff(a,b); Console.WriteLine(a); Console.WriteLine(b); Console.WriteLine(c); } } } }
using OnboardingSIGDB1.Domain.Empresas.Validators; using OnboardingSIGDB1.Domain.Funcionarios; using System; using System.Collections.Generic; namespace OnboardingSIGDB1.Domain.Empresas { public class Empresa : Entity { public Empresa() { } public Empresa(string nome, string cnpj, DateTime? dataFundacao) : this() { Nome = nome; Cnpj = cnpj; DataFundacao = dataFundacao; Validate(this, new EmpresaValidator()); } public Empresa(long id, string nome, string cnpj, DateTime? dataFundacao) : this(nome, cnpj, dataFundacao) { Id = id; } public string Nome { get; private set; } public string Cnpj { get; private set; } public DateTime? DataFundacao { get; private set; } public IEnumerable<Funcionario> Funcionarios { get; private set; } public void AlterarNome(string nome) { Nome = nome; } public void AlterarCnpj(string cnpj) { Cnpj = cnpj; } public void AlterarDataFundacao(DateTime? dataFuncacao) { DataFundacao = dataFuncacao; } public void AlterarFuncionarios(IEnumerable<Funcionario> funcionarios) { Funcionarios = funcionarios; } public void Validar() { Validate(this, new EmpresaValidator()); } } }
using System; using System.Collections.Generic; using System.Text; namespace Kulula.com.Models { class Flight_Departure { public int AirportID { get; set; } public int AircraftID { get; set; } public int ArrivalID { get; set; } public string AirportName { get; set; } public string DepartingTime { get; set; } public string DepartingDate { get; set; } } }
#region MIT License /* * Copyright (c) 2009 University of Jyväskylä, Department of Mathematical * Information Technology. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion /* * Authors: Tero Jäntti, Tomi Karppinen, Janne Nikkanen. */ using System.ComponentModel; using System; namespace Jypeli { /// <summary> /// Aivoluokka peliolioille. /// Voidaan käyttää tekoälyn ja tilannekohtaisten toimintamallien luomiseen /// peliolioille, esimerkkinä tietokoneen ohjaamat viholliset. /// </summary> public class Brain { /// <summary> /// Tyhjät aivot, eivät sisällä mitään toiminnallisuutta. /// </summary> internal static readonly Brain None = new Brain(); private bool active = true; /// <summary> /// Aivot käytössä tai pois käytöstä. /// </summary> public bool Active { get { return active; } set { active = value; } } /// <summary> /// Tapahtuu kun aivoja päivitetään. /// </summary> public event Action<Brain> Updated; private IGameObject _owner; /// <summary> /// Aivojen haltija. /// </summary> public IGameObject Owner { get { return _owner; } set { if (_owner == value) return; IGameObject prevOwner = _owner; _owner = value; if (prevOwner != null) OnRemove(prevOwner); if (value != null) OnAdd(value); } } internal void AddToGameEvent() { OnAddToGame(); } internal void DoUpdate(Time time) { if (Active) { Update(time); if (Updated != null) Updated(this); } } /// <summary> /// Kutsutaan, kun aivot lisätään oliolle. /// </summary> /// <param name="newOwner">Olio, jolle aivot lisättiin.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void OnAdd(IGameObject newOwner) { } /// <summary> /// Kutsutaan, kun aivot poistetaan oliolta. /// </summary> /// <param name="prevOwner">Olio, jolta aivot poistettiin.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void OnRemove(IGameObject prevOwner) { } /// <summary> /// Kutsutaan, kun aivojen omistaja lisätään peliin tai omistajaksi /// asetetaan olio, joka on jo lisätty peliin. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void OnAddToGame() { } /// <summary> /// Kutsutaan, kun tilaa päivitetään. /// Suurin osa päätöksenteosta tapahtuu täällä. /// Perivässä luokassa methodin kuuluu kutsua vastaavaa /// kantaluokan methodia. /// </summary> /// <param name="time">Päivityksen ajanhetki.</param> [EditorBrowsable(EditorBrowsableState.Never)] protected virtual void Update(Time time) { } /// <summary> /// Kutsutaan, kun tapahtuu törmäys. /// Perivässä luokassa methodin kuuluu kutsua vastaavaa /// kantaluokan methodia. /// </summary> /// <param name="target">Olio, johon törmätään.</param> [EditorBrowsable(EditorBrowsableState.Never)] public virtual void OnCollision(IGameObject target) { } } }
using System.Windows.Forms; namespace Project.Helpers { class GuiHelper { public static DialogResult ShowInfo(string message) { return MessageBox.Show(message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Information); } public static DialogResult ShowWarning(string message) { return MessageBox.Show(message, "Waarschuwing", MessageBoxButtons.OK, MessageBoxIcon.Warning); } public static DialogResult ShowError(string message) { return MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } public static bool ShowConfirm(string message) { return MessageBox.Show(message, "Bevestiging", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning) == DialogResult.Yes; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Core.DAL; using Core.BIZ; using System.Globalization; using PagedList; namespace WebForm.Areas.Admin.Controllers { public class ThanhToanDaiLyController : BaseController { #region Private Properties private static HoaDonDaiLy _hoadon; private static int? _currentHoaDon; private CultureInfo _cultureInfo; // Thông tin văn hóa #endregion #region Public Properties public CultureInfo CultureInfo { get { if (_cultureInfo == null) { _cultureInfo = CultureInfo.GetCultureInfo("vi-VN"); } return _cultureInfo; } } #endregion #region Actions // GET: PhieuNhap public ActionResult All(int page = 1, int pageSize = 10, string search = null) { List<HoaDonDaiLy> DMHoaDon = null; ViewBag.cultureInfo = CultureInfo; if (!String.IsNullOrEmpty(search)) { DMHoaDon = HoaDonDaiLyManager.filter(search); ViewBag.SearchKey = search; } else { DMHoaDon = HoaDonDaiLyManager.getAll(); } ViewBag.tongTien = DMHoaDon.Sum(hd => hd.TongTien); var models = DMHoaDon.ToPagedList(page, pageSize); setAlertMessage(); return View(models); } // GET: PhieuNhap/Details/5 public ActionResult Details(int? id) { if (id == null) { putErrorMessage("Đường dẫn không chính xác"); return RedirectToAction("All"); } var model = HoaDonDaiLyManager.find((int)id); if (model == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } setAlertMessage(); return View(model); } // GET: PhieuNhap/ThanhToan public ActionResult ThanhToan(int? masodaily) { if (masodaily != null) { var dl = DaiLyManager.find((int)masodaily); if (dl == null || dl.TrangThai == 0) { putErrorMessage("Không tìm thấy đại lý"); return RedirectToAction("ThanhToan"); } ViewBag.cultureInfo = CultureInfo; ViewBag.currentDaiLy = dl; ViewBag.DMSach = new SelectList(dl.getSachNo(), nameof(SachManager.Properties.MaSoSach), nameof(SachManager.Properties.TenSach), ""); if (_hoadon == null) { _hoadon = new HoaDonDaiLy(); } _hoadon.MaSoDaiLy = dl.MaSoDaiLy; _hoadon.DaiLy = dl; _hoadon.NgayLap = DateTime.Now; setAlertMessage(); return View(_hoadon); } else { ViewBag.DMDaiLy = new SelectList(DaiLyManager.getAllAlive() .Where(dl => dl.TongTienNo > 0).ToList(), nameof(DaiLyManager.Properties.MaSoDaiLy), nameof(DaiLyManager.Properties.TenDaiLy), ""); _hoadon = new HoaDonDaiLy(); setAlertMessage(); return View(); } } // POST: PhieuNhap/Create [HttpPost] public ActionResult ThanhToan(HoaDonDaiLy model, FormCollection collection) { try { // TODO: Add insert logic here if (ModelState.IsValid) { var result = HoaDonDaiLyManager.add(model); if (result != 0) { _hoadon = null; putSuccessMessage("Thanh toán thành công"); return RedirectToAction("Details", new { id = result }); } else { putErrorMessage("Thanh toán không thành công"); } } else { putModelStateFailErrors(ModelState); } //ViewBag.cultureInfo = CultureInfo; //ViewBag.currentDaiLy = _hoadon.DaiLy; //ViewBag.DMSach = new SelectList(_hoadon.DaiLy.getSachNo(), // nameof(SachManager.Properties.MaSoSach), // nameof(SachManager.Properties.TenSach), ""); //_hoadon.NgayLap = DateTime.Now; //return View(_hoadon); return RedirectToAction("ThanhToan", new { masodaily = _hoadon.MaSoDaiLy }); } catch(Exception ex) { putErrorMessage(ex.Message); return RedirectToAction("ThanhToan", new { masodaily = _hoadon.MaSoDaiLy }); } } // GET: PhieuNhap/Edit/5 public ActionResult Edit(int? id) { if (id == null) { putErrorMessage("Đường dẫn không chính xác"); return RedirectToAction("All"); } if (_currentHoaDon == null || _currentHoaDon != id) { _currentHoaDon = id; _hoadon = HoaDonDaiLyManager.find((int)id); if (_hoadon == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } if (_hoadon.TrangThai == 1) { //Nếu đã duyệt thì không cho sửa, chuyển sang trang chi tiết _currentHoaDon = null; putErrorMessage("Hóa đơn đã duyệt"); return RedirectToAction("Details", new { id = id }); } } ViewBag.cultureInfo = CultureInfo; ViewBag.currentDaiLy = _hoadon.DaiLy; ViewBag.DMSach = new SelectList(_hoadon.DaiLy.getSachNo(), nameof(SachManager.Properties.MaSoSach), nameof(SachManager.Properties.TenSach), ""); setAlertMessage(); return View(_hoadon); } // POST: PhieuNhap/Edit/5 [HttpPost] public ActionResult Edit(HoaDonDaiLy model, FormCollection collection) { try { if (ModelState.IsValid) { if (HoaDonDaiLyManager.edit(model)) { _currentHoaDon = null; putSuccessMessage("Cập nhật thành công"); return RedirectToAction("Details", new { id = model.MaSoHoaDon }); } else { putErrorMessage("Cập nhật thất bại"); } } else { putModelStateFailErrors(ModelState); } // TODO: Add update logic here //_hoadon = model; //ViewBag.currentDaiLy = _hoadon.DaiLy; //ViewBag.DMSach = new SelectList(_hoadon.DaiLy.getSachNo(), // nameof(SachManager.Properties.MaSoSach), // nameof(SachManager.Properties.TenSach), ""); //return View(_hoadon); return RedirectToAction("Edit", new { id = model.MaSoHoaDon }); } catch(Exception ex) { putErrorMessage(ex.Message); return RedirectToAction("Edit", new { id = model.MaSoHoaDon }); } } // GET: PhieuNhap/Delete/5 public ActionResult Delete(int? id) { if (id == null) { putErrorMessage("Đường dẫn không đúng"); return RedirectToAction("All"); } var model = HoaDonDaiLyManager.find((int)id); if (model == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } if (model.TrangThai == 1) { putErrorMessage("Hóa đơn đã duyệt"); return RedirectToAction("Details", new { id = model.MaSoHoaDon }); } setAlertMessage(); return View(model); } // POST: PhieuNhap/Delete/5 [HttpPost] public ActionResult Delete(int? id, FormCollection collection) { try { if (HoaDonDaiLyManager.delete((int)id)) { putSuccessMessage("Xóa thành công"); _currentHoaDon = null; return RedirectToAction("All"); } else { putErrorMessage("Xóa không thành công"); return RedirectToAction("Delete", new { id }); } } catch(Exception ex) { putErrorMessage(ex.Message); return RedirectToAction("Delete", new { id }); } } //Duyệt phiếu public ActionResult Accept(int? id) { if (id == null) { putErrorMessage("Đường dẫn không đúng"); return RedirectToAction("All"); } var model = HoaDonDaiLyManager.find((int)id); if (model == null) { putErrorMessage("Không tìm thấy"); return RedirectToAction("All"); } if (model.TrangThai == 1) { putErrorMessage("Hóa đơn đã duyệt"); return RedirectToAction("Details", new { id }); } if (model.accept()) { putSuccessMessage("Duyệt hóa đơn thành công"); return RedirectToAction("Details", new { id}); } else { putErrorMessage("Duyệt không thành công, vui lòng kiểm tra lại công nợ"); return RedirectToAction("Edit", new { id }); } } #endregion #region JSON REQUEST public JsonResult GetProperties(string request) { List<string> results = new List<string>(); foreach (string pro in HoaDonDaiLy.searchKeys()) { results.Add(request + pro); } return Json(results, JsonRequestBehavior.AllowGet); } #endregion #region REQUEST public ViewResult BlankEditorRow(int masodaily, int masosach = 0) { var dl = DaiLyManager.find((int)masodaily); var chitiet = new ChiTietHoaDonDaiLy(); if(masosach != 0) { chitiet.MaSoSach = (int)masosach; if (_hoadon.ChiTiet.Contains(chitiet)) { return null; } } else { var founded = false; foreach (Sach s in dl.getSachNo()) { chitiet.MaSoSach = s.MaSoSach; chitiet.Sach = s; if (_hoadon.ChiTiet.Contains(chitiet)) { continue; } founded = true; break; } if (!founded) { return null; } } ViewBag.currentDaiLy = dl; ViewBag.cultureInfo = CultureInfo; ViewBag.DMSach = new SelectList(dl.getSachNo(), nameof(SachManager.Properties.MaSoSach), nameof(SachManager.Properties.TenSach), ""); chitiet.SoLuong = 1; chitiet.DonGia = chitiet.Sach.GiaNhap; _hoadon.addDetail(chitiet); ViewData["masodaily"] = dl.MaSoDaiLy; return View("ChiTietEditorRow", chitiet); } public ViewResult DeleteDetailRow(int masosach) { _hoadon.deleteDetail(masosach); return null; } public ViewResult ChangeDetailRow(int masosach, int? masosach_new, int? soluong) { foreach(ChiTietHoaDonDaiLy ct in _hoadon.ChiTiet) { if (ct.MaSoSach.Equals(masosach)) { if(masosach_new != null) { ct.MaSoSach = (int)masosach_new; ct.Sach = SachManager.find(ct.MaSoSach); ct.DonGia = ct.Sach.GiaNhap; ct.SoLuong = 1; } if(soluong != null) { ct.SoLuong = (int)soluong; } break; } } return null; } public JsonResult isDetailExisted(string masosach) { var key = Int32.Parse(masosach); var chitiet = new ChiTietHoaDonDaiLy(); chitiet.MaSoSach = key; if (_hoadon.isDetailExisted(chitiet)) { return Json(true,JsonRequestBehavior.AllowGet); } else { return Json(false, JsonRequestBehavior.AllowGet); } } #endregion } }
namespace BettingSystem.Application.Betting.Matches.Consumers { using System.Threading.Tasks; using Domain.Betting.Repositories; using Domain.Common.Events.Matches; using MassTransit; public class MatchStartDateUpdatedEventConsumer : IConsumer<MatchStartDateUpdatedEvent> { private readonly IMatchDomainRepository matchRepository; public MatchStartDateUpdatedEventConsumer(IMatchDomainRepository matchRepository) => this.matchRepository = matchRepository; public async Task Consume(ConsumeContext<MatchStartDateUpdatedEvent> context) { var eventMessage = context.Message; var match = await this.matchRepository.Find(eventMessage.Id); match!.UpdateStartDate(eventMessage.StartDate); await this.matchRepository.Save(match); } } }
using System; using System.Threading.Tasks; using InterestRateApp.Contracts.Requests; using InterestRateApp.Contracts.Responses; using InterestRateApp.Domain; namespace InterestRateApp.Services.Services { public interface IAgreementService { bool AgreementExists(Guid agreementId); Task<BaseRateCode> GetBaseRateCodeAsync(Guid agreementId); Task<AgreementDTO> AddAgreementAsync(AgreementRequest agreementRequest); Task<AgreementDTO> UpdateAgreementAsync(AgreementRequest agreementRequest); } }
using System.Linq; namespace SpaceHosting.Index.Benchmarks { public static class VectorConversions { public static DenseVector ToDenseVector(this double?[] coordinates) { if (coordinates.All(c => c == null)) return new DenseVector(new double[coordinates.Length]); return new DenseVector(coordinates.Cast<double>().ToArray()); } public static SparseVector ToSparseVector(this double?[] coordinates) { var dimension = coordinates.Length; var nonNullCount = coordinates.Count(c => c != null); var indices = new int[nonNullCount]; var coords = new double[nonNullCount]; var j = 0; for (var i = 0; i < dimension; i++) { var coordinate = coordinates[i]; if (coordinate == null) continue; indices[j] = i; coords[j] = coordinate.Value; j++; } return new SparseVector(dimension, indices, coords); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Client.Features.Duplicates.ViewModels { public class DuplicatesResultPath { public Guid PathCompareValueId { get; set; } public string FileName { get; set; } public string Directory { get; set; } public string Extension { get; set; } public bool Checked { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ProyectoWebBlog.Models; using ProyectoWebBlog.Models.ViewModels; namespace ProyectoWebBlog.Controllers { public class CategoriaController : Controller { public ActionResult Index() { return View(); } [Authorize(Roles = "Admin")] public ActionResult AgregarCategoria() { return View(); } [Authorize(Roles = "Admin")] [HttpPost] public ActionResult AgregarCategoria(CategoriaModel nuevaCategoria) { try { if (ModelState.IsValid) { using (WebBlogEntities baseDatos = new WebBlogEntities()) { var categoria = new Categoria(); categoria.nombrePK = nuevaCategoria.Nombre; baseDatos.Categoria.Add(categoria); baseDatos.SaveChanges(); } return Redirect("~/Home"); } return View(nuevaCategoria); } catch (Exception excepcion) { throw new Exception(excepcion.Message); } } public List<String> ObtenerNombreCategorias() { List<String> nombreCategorias = new List<string>(); List<CategoriaModel> categorias = new List<CategoriaModel>(); using (WebBlogEntities baseDatos = new WebBlogEntities()) { categorias = (from categoria in baseDatos.Categoria select new CategoriaModel { Nombre = categoria.nombrePK }).ToList(); } foreach (var categoria in categorias) { nombreCategorias.Add(categoria.Nombre); } return nombreCategorias; } [Authorize(Roles = "Admin")] public ActionResult ObtenerListaCategorias() { List<CategoriaModel> categorias; using (WebBlogEntities baseDatos = new WebBlogEntities()) { categorias = (from categoria in baseDatos.Categoria select new CategoriaModel { Nombre = categoria.nombrePK }).ToList(); } return View(categorias); } [Authorize(Roles = "Admin")] [HttpGet] public ActionResult EliminarCategoria(string Id) { using (WebBlogEntities baseDatos = new WebBlogEntities()) { var categoriaTabla = baseDatos.Categoria.Find(Id); baseDatos.Categoria.Remove(categoriaTabla); baseDatos.SaveChanges(); } return Redirect("~/Categoria/ObtenerListaCategorias"); } } }
namespace Records { public class PointRecord { public int x; public int y; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InheritanceApp { class Developer: CompanyEmployee { public Developer(string name, string salary, DateTime? date, string Special ) : base(name, salary, date) { this.Speciality = Special; } private string speciality; public string Speciality { get { return speciality; } set { if(value == "Front End Developer" || value == "Back End Developer" ) { this.speciality = value; } else { Console.WriteLine("You shall be considered Full Stack"); this.speciality = "Full Stack"; } } } public string ProgLang { get { if(this.Speciality == "Front End Developer") { return "Js"; } else if(this.Speciality == "Back End Developer") { return "C#"; } else { return "N/a"; } } } public override void worktime() { Console.WriteLine("Hi, my name is {0}, my salary is {1} and I ve been working here since {2} as a {3}. My favourite programming language is {4}", this.EmployeeName, this.Salary, this.StarDate.ToString(), this.Speciality, this.ProgLang); } } }
using System; namespace SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Responses { public class GetPriorLearningSummaryQueryResult { public long ApprenticeshipId { get; set; } public long CohortId { get; set; } public int? TrainingTotalHours { get; set; } public int? DurationReducedByHours { get; set; } public int? CostBeforeRpl { get; set; } public int? PriceReducedBy { get; set; } public int? FundingBandMaximum { get; set; } public decimal? PercentageOfPriorLearning { get; set; } public decimal? MinimumPercentageReduction { get; set; } public bool IsDurationReducedByRpl { get; set; } public int? ReducedDuration { get; set; } public int? MinimumPriceReduction {get; set;} public bool RplPriceReductionError { get; set; } public int? TotalCost { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public bool HasStandardOptions { get; set; } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using Aquamonix.Mobile.Lib.Extensions; namespace Aquamonix.Mobile.Lib.Domain { [DataContract] public class Valve : IDomainObjectWithId, ICloneable<Valve>, IMergeable<Valve> { [DataMember(Name = PropertyNames.Id)] public string Id { get; set; } [DataMember(Name = PropertyNames.Name)] public string Name { get; set; } [DataMember(Name = PropertyNames.Type)] public string Type { get; set; } public Valve Clone() { var clone = new Valve() { Id = this.Id, Name = this.Name, Type = this.Type }; return clone; } public void MergeFromParent(Valve parent, bool removeIfMissingFromParent, bool parentIsMetadata) { if (parent != null) { this.Id = MergeExtensions.MergeProperty(this.Id, parent.Id, removeIfMissingFromParent, parentIsMetadata); this.Name = MergeExtensions.MergeProperty(this.Name, parent.Name, removeIfMissingFromParent, parentIsMetadata); this.Type = MergeExtensions.MergeProperty(this.Type, parent.Type, removeIfMissingFromParent, parentIsMetadata); } } public void ReadyChildIds() { } } }
using ShoppingListApi.Models.RequestModels; namespace ShoppingListApi.Models.ResponseModels { public class ShoppingListItem: BaseShoppingListItem { } }
using System; using System.Collections.Generic; using System.Linq; 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 FolderBackup.CommunicationProtocol; using FolderBackup.Shared; using System.IO; namespace FolderBackup.Client { /// <summary> /// Logica di interazione per MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { string username = this.usernameTxtBox.Text; string password = this.paswordTxtBox.Password; if (username.Equals("")) { MessageBox.Show(this, "Username cannot be empty!", "Missing username", MessageBoxButton.OK); return; } if (password.Equals("")) { MessageBox.Show(this, "Password cannot be empty!", "Missing password", MessageBoxButton.OK); return; } string token; BackupServiceClient server = logIn(username, password, out token); if (server == null) return; MessageBox.Show(this, "Log in succeed!"); } private void Label_MouseEnter(object sender, MouseEventArgs e) { Color c = (Color) ColorConverter.ConvertFromString("#FF024FFF"); this.registerLabel.Foreground = new SolidColorBrush(c); } private void registerLabel_MouseLeave(object sender, MouseEventArgs e) { Color c = (Color)ColorConverter.ConvertFromString("#FF000000"); this.registerLabel.Foreground = new SolidColorBrush(c); } private void registerLabel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { RegisterWindow rw = new RegisterWindow(); rw.parent = this; rw.Show(); rw.Activate(); this.Hide(); } private BackupServiceClient logIn(string username, string password, out string token) { BackupServiceClient server = new BackupServiceClient(); AuthenticationData ad; try { ad = server.authStep1(username); } catch { MessageBox.Show(this, "Username doesn't exist.", "Wrong username", MessageBoxButton.OK); token = null; return null; } try { token = server.authStep2(ad.token, username, AuthenticationPrimitives.hashPassword(password, ad.salt, ad.token)); } catch { MessageBox.Show(this, "Wrong Password", "", MessageBoxButton.OK); token = null; return null; } return server; } } }
using AspNetCoreGettingStarted.Data; using AspNetCoreGettingStarted.Model; using Microsoft.EntityFrameworkCore; namespace AspNetCoreGettingStarted.IntegrationTests.Data { public class MockAspNetCoreGettingStartedContext : DbContext, IAspNetCoreGettingStartedContext { public DbSet<Category> Categories { get; set; } public DbSet<Product> Products { get; set; } public DbSet<Tenant> Tenants { get; set; } public DbSet<User> Users { get; set; } public DbSet<DigitalAsset> DigitalAssets { get; set; } public DbSet<Dashboard> Dashboards { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public DbSet<DashboardTile> DashboardTiles { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } public DbSet<Tile> Tiles { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); } protected override void OnConfiguring(DbContextOptionsBuilder dbContextOptionsBuilder) { dbContextOptionsBuilder.UseInMemoryDatabase(databaseName: "AspNetCoreGettingStarted"); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Tenant>(b => { b.Property(t => t.TenantId) .HasDefaultValueSql("newsequentialid()"); }); } } }
using System; using System.Text; using Xunit; namespace Rwb { public class Base32ConverterTests { [Fact] public void ToBase32String_Null_ShouldThrow() { Assert.Throws<ArgumentNullException>(() => Base32Converter.ToBase32String(null)); } [Theory] [InlineData("", "")] [InlineData("f", "MY")] [InlineData("fo", "MZXQ")] [InlineData("foo", "MZXW6")] [InlineData("foob", "MZXW6YQ")] [InlineData("fooba", "MZXW6YTB")] [InlineData("foobar", "MZXW6YTBOI")] public void ToBase32String(string input, string expected) { byte[] bytes = Encoding.ASCII.GetBytes(input); string actual = Base32Converter.ToBase32String(bytes); Assert.Equal(expected, actual); } [Fact] public void FromBase32String_Null_ShouldThrow() { Assert.Throws<ArgumentNullException>(() => Base32Converter.FromBase32String(null)); } [Theory] [InlineData("", "")] [InlineData("f", "MY")] [InlineData("fo", "MZXQ")] [InlineData("foo", "MZXW6")] [InlineData("foob", "MZXW6YQ")] [InlineData("fooba", "MZXW6YTB")] [InlineData("foobar", "MZXW6YTBOI")] public void FromBase32String(string expected, string input) { byte[] expectedBytes = Encoding.ASCII.GetBytes(expected); byte[] actual = Base32Converter.FromBase32String(input); Assert.Equal(BitConverter.ToString(expectedBytes), BitConverter.ToString(actual)); } [Theory] [InlineData("A")] [InlineData("ABC")] [InlineData("ABCDEF")] [InlineData("ABCDEFGHI")] [InlineData("ABCDEFGHIJK")] public void FromBase32String_InvalidLength(string input) { Assert.Throws<ArgumentException>(() => Base32Converter.FromBase32String(input)); } [Theory] [InlineData('*')] [InlineData('0')] [InlineData('1')] [InlineData('8')] [InlineData('9')] [InlineData('@')] [InlineData('[')] [InlineData('a')] [InlineData('z')] [InlineData('=')] public void FromBase32String_InvalidCharacters(char input) { var exception = Assert.Throws<ArgumentException>(() => Base32Converter.FromBase32String(input + "A")); Assert.Contains("'" + input + "'", exception.Message); } [Fact] public void Base32RoundTrip() { var input = new byte[4096]; new Random().NextBytes(input); var base32 = Base32Converter.ToBase32String(input); var output = Base32Converter.FromBase32String(base32); Assert.Equal(input, output); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CS_350_Exam_3 { class Social_Network { public class Person { public string UserName { get; set; } public string Password { get; set; } public int UserID { get; set; } public List<int> Friends { get; set; } public List<string> Posts { get; set; } public static bool Create_User(String UserName, String Password, int ID) { try { Person person = new Person(); person.UserName = UserName; person.Password = Password; person.UserID = ID; string[] personInfo = { person.UserID.ToString(), person.UserName, person.Password }; System.IO.File.AppendAllText(@"C:\Users\Tyler\source\repos\CS 350 Exam 3\social_network_app\bin\user_list.csv", personInfo[0] + "," + personInfo[1] + "," + personInfo[2] + "\n"); return true; } catch { return false; } } public static Person Lookup_Person(int UserID) { Person person = new Person(); var Lines = File.ReadLines("C:/Users/Tyler/source/repos/CS 350 Exam 3/social_network_app/bin/user_list.csv"); foreach (var line in Lines) { if (line.Split(',')[0].Equals(UserID)) { person.UserID = Convert.ToInt32(line.Split(',')[0]); person.UserName = line.Split(',')[1]; person.Password = line.Split(',')[2]; person.Friends = new List<int> { }; person.Friends.Add(Convert.ToInt32(line.Split(',')[3])); return person; } } return person; } } public class Friend { public static bool Add_Friend(int FirstID, int SecondID) { try { Person PersonOne = Person.Lookup_Person(FirstID); Person PersonTwo = Person.Lookup_Person(SecondID); PersonOne.Friends = new List<int> { }; PersonTwo.Friends = new List<int> { }; PersonOne.Friends.Add(SecondID); PersonTwo.Friends.Add(FirstID); return true; } catch { return false; } } public static List<int> List_Friends(int LookupID) { Person person = Person.Lookup_Person(LookupID); return person.Friends; } public static bool Remove_Friend(int FirstID, int SecondID) { try { Person PersonOne = Person.Lookup_Person(FirstID); Person PersonTwo = Person.Lookup_Person(SecondID); PersonOne.Friends = new List<int> { }; PersonTwo.Friends = new List<int> { }; PersonOne.Friends.Remove(SecondID); PersonTwo.Friends.Remove(FirstID); return true; } catch { return false; } } } public class Post { public static List<string> List_Topics(int UserID) { Person person = new Person(); person = Person.Lookup_Person(UserID); return person.Posts; } public static bool AddTopic(int UserID, string Content) { try { Person person = new Person(); person = Person.Lookup_Person(UserID); person.Posts = new List<string> { }; person.Posts.Add(Content); return true; } catch { return false; } } public static bool RemoveTopic(int UserID, string Content) { try { Person person = new Person(); person = Person.Lookup_Person(UserID); person.Posts = new List<string> { }; person.Posts.Remove(Content); return true; } catch { return false; } } } public class MasterSystem { public static void MasterReset() { System.IO.File.WriteAllText(@"C:\Users\Tyler\source\repos\CS 350 Exam 3\social_network_app\bin\user_list.csv", string.Empty); } public static bool ExportData(String filepath) { try { File.Copy(@"C:\Users\Tyler\source\repos\CS 350 Exam 3\social_network_app\bin\user_list.csv", filepath, true); return true; } catch { return false; } } public static bool ImportData(String filepath) { try { File.Copy(filepath, @"C:\Users\Tyler\source\repos\CS 350 Exam 3\social_network_app\bin\user_list.csv", true); return true; } catch { return false; } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Model.Interfaces; using Utilities; namespace AccManagerKw.Common { public partial class FrmBase : Form { public ClsGlobalVarz.Mode Mode; public FrmBase() { InitializeComponent(); SetMode(ClsGlobalVarz.Mode.Add); } public void SetMode(ClsGlobalVarz.Mode mode) { Mode = mode; lblMode.Text = string.Format(@"Mode: {0}", mode); } private void btnCancel_Click(object sender, EventArgs e) { try { ((ICrud)MdiParent.ActiveMdiChild).ResetData(); } catch (Exception ex) { Console.WriteLine(ex); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformSpawner : MonoBehaviour { public GameObject Despawner; public GameObject SimplePlatformPrefab; public float PlatformMoveSpeed; public int Interval; private int Count; private Vector3 Forward; private GameObject NewPlatform; void Start() { Forward = this.transform.forward; } // Update is called once per frame void Update() { Count++; if (Count >= Interval) { Count = 0; NewPlatform = Instantiate(SimplePlatformPrefab, this.transform.position, this.transform.rotation); NewPlatform.GetComponent<PlatformStraight>().mSpeed = PlatformMoveSpeed; NewPlatform.GetComponent<PlatformStraight>().Despawner = Despawner; } } }
using System; using SpatialEye.Framework.Client; using Lite.Resources.Localization; namespace Lite { /// <summary> /// The lite print view model that holds the available templates /// </summary> public class LitePrintViewModel : PrintViewModel { #region Constructor /// <summary> /// The default constructor for the print viewModel /// </summary> public LitePrintViewModel() { AttachToMessenger(); SetupTemplates(); } #endregion #region Messenger /// <summary> /// Attaches the printViewModel to the Messenger, reacting to mapview model changes /// </summary> private void AttachToMessenger() { if (!IsInDesignMode) { Messenger.Register<PropertyChangedMessage<LiteMapViewModel>>(this, MapViewModelChanged); } } /// <summary> /// Callback from the the messenger /// </summary> /// <param name="geometryMessage"></param> private void MapViewModelChanged(PropertyChangedMessage<LiteMapViewModel> mapViewModelMessage) { if (mapViewModelMessage.PropertyName == LiteMapsViewModel.CurrentMapPropertyName) { var model = mapViewModelMessage.NewValue; if (model != null) { // Set the activate Map View for the printViewModel this.MapView = model; } } } #endregion #region Setup of Templates /// <summary> /// Sets up the templates /// </summary> private void SetupTemplates() { if (!IsInDesignMode) { SetupA4Template1(); SetupA4Template2(); SetupA4Template3(); } } /// <summary> /// Sets up the A4 Template1 template /// </summary> private void SetupA4Template1() { // Set up the Default Template Func<PrintContext> createContextModel = () => new LitePrintA4Template1SettingsContext(ViewModelLocator.LiteName); var template = new PrintTemplate(string.Format(ApplicationResources.PrintTemplateDefault, ViewModelLocator.LiteName), createContextModel, typeof(LitePrintA4Template1SettingsControl)) { Description = ApplicationResources.PrintTemplateDefaultDescription, DefaultPageOrientation = PrintPageOrientation.Landscape, DefaultPageSize = PrintPageSize.Letter, DefaultPageMargins = PrintPageMargins.None, DefaultPageQuality = PrintPageQuality.Dpi75 }; template.AllowedPageSizes.Clear(); template.AllowedPageSizes.Add(PrintPageSize.Letter); template.AllowedPageSizes.Add(PrintPageSize.A3); template.AllowedPageSizes.Add(PrintPageSize.A4); // DEFAULT PRINT TEMPLATE Func<PrintPageContext> createHeaderModel = () => new LitePrintA4Template1HeaderPageContext(); Func<PrintPageContext> createMainModel = () => new LitePrintA4Template1MainPageContext(); Func<PrintPageContext> createFooterModel = () => new LitePrintA4Template1FooterPageContext(); // The header page //template.Pages[PrintTemplatePageType.Header] = new PrintTemplatePage<LitePrintA4Template1HeaderPageView>(createHeaderModel) { ForcePageOrientation = PrintPageOrientation.Portrait }; // The main page template.Pages[PrintTemplatePageType.Main] = new PrintTemplatePage<LitePrintA4Template1MainPageView>(createMainModel);// { ForcePageOrientation = PrintPageOrientation.Landscape}; // The footer page //template.Pages[PrintTemplatePageType.Footer] = new PrintTemplatePage<LitePrintA4Template1FooterPageView>(createFooterModel) { ForcePageOrientation = PrintPageOrientation.Landscape }; // Add to the templates, to be picked up a Print dialog this.Templates.Add(template); } /// <summary> /// Sets up the A4 Template2 template /// </summary> private void SetupA4Template2() { // Set up the Default Template Func<PrintContext> createContextModel = () => new LitePrintA4Template2SettingsContext(ViewModelLocator.LiteName); var template = new PrintTemplate(string.Format(ApplicationResources.PrintTemplateDefaultWithLegend, ViewModelLocator.LiteName), createContextModel, typeof(LitePrintA4Template2SettingsControl)) { Description = ApplicationResources.PrintTemplateDefaultWithLegendDescription, DefaultPageOrientation = PrintPageOrientation.Landscape, DefaultPageSize = PrintPageSize.Letter, DefaultPageMargins = PrintPageMargins.None, DefaultPageQuality = PrintPageQuality.Dpi75 }; template.AllowedPageSizes.Clear(); template.AllowedPageSizes.Add(PrintPageSize.Letter); template.AllowedPageSizes.Add(PrintPageSize.A3); template.AllowedPageSizes.Add(PrintPageSize.A4); // DEFAULT PRINT TEMPLATE Func<PrintPageContext> createHeaderModel = () => new LitePrintA4Template2HeaderPageContext(); Func<PrintPageContext> createMainModel = () => new LitePrintA4Template2MainPageContext(); Func<PrintPageContext> createFooterModel = () => new LitePrintA4Template2FooterPageContext(); // The header page //template.Pages[PrintTemplatePageType.Header] = new PrintTemplatePage<LitePrintA4Template2HeaderPageView>(createHeaderModel) { ForcePageOrientation = PrintPageOrientation.Portrait }; // The main page template.Pages[PrintTemplatePageType.Main] = new PrintTemplatePage<LitePrintA4Template2MainPageView>(createMainModel);// { ForcePageOrientation = PrintPageOrientation.Landscape}; // The footer page //template.Pages[PrintTemplatePageType.Footer] = new PrintTemplatePage<LitePrintA4Template2FooterPageView>(createFooterModel) { ForcePageOrientation = PrintPageOrientation.Landscape }; // Add to the templates, to be picked up a Print dialog this.Templates.Add(template); } /// <summary> /// Sets up the A4 Template3 template /// </summary> private void SetupA4Template3() { // Set up the Default Template Func<PrintContext> createContextModel = () => new LitePrintA4Template3SettingsContext(ViewModelLocator.LiteName); var template = new PrintTemplate(string.Format(ApplicationResources.PrintTemplateLegendOnly, ViewModelLocator.LiteName), createContextModel, typeof(LitePrintA4Template3SettingsControl)) { Description = ApplicationResources.PrintTemplateLegendOnlyDescription, DefaultPageOrientation = PrintPageOrientation.Landscape, DefaultPageSize = PrintPageSize.Letter, DefaultPageMargins = PrintPageMargins.None, DefaultPageQuality = PrintPageQuality.Dpi75 }; template.AllowedPageSizes.Clear(); template.AllowedPageSizes.Add(PrintPageSize.Letter); template.AllowedPageSizes.Add(PrintPageSize.A3); template.AllowedPageSizes.Add(PrintPageSize.A4); // DEFAULT PRINT TEMPLATE Func<PrintPageContext> createHeaderModel = () => new LitePrintA4Template3HeaderPageContext(); Func<PrintPageContext> createMainModel = () => new LitePrintA4Template3MainPageContext(); Func<PrintPageContext> createFooterModel = () => new LitePrintA4Template3FooterPageContext(); // The header page //template.Pages[PrintTemplatePageType.Header] = new PrintTemplatePage<LitePrintA4Template3HeaderPageView>(createHeaderModel) { ForcePageOrientation = PrintPageOrientation.Portrait }; // The main page template.Pages[PrintTemplatePageType.Main] = new PrintTemplatePage<LitePrintA4Template3MainPageView>(createMainModel);// { ForcePageOrientation = PrintPageOrientation.Landscape}; // The footer page //template.Pages[PrintTemplatePageType.Footer] = new PrintTemplatePage<LitePrintA4Template3FooterPageView>(createFooterModel) { ForcePageOrientation = PrintPageOrientation.Landscape }; // Add to the templates, to be picked up a Print dialog this.Templates.Add(template); } #endregion #region Notification /// <summary> /// The active document is about to be sent to the printer /// </summary> protected override void OnSendToPrinter() { base.OnSendToPrinter(); LiteAnalyticsTracker.TrackMapPrint(); } #endregion } }
using UnityEngine; using UnityEngine.UI; public class HexCellUiView : MonoBehaviour { public Text label; public void Initialize(HexNode node) { label.rectTransform.SetParent(HexMap.instance.canvas.transform, false); label.rectTransform.anchoredPosition = new Vector2(node.position.x, node.position.z); label.text = node.index.x.ToString() + "\n" + node.index.z.ToString(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XH.Configurations { public class ConfigurationValidationResult : Dictionary<string, string> { } }
using System.Text; using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using Microsoft.SharePoint.WebControls; using System; using System.Linq; using System.Collections.Generic; namespace CustomLookupFieldWithAJAX { public class CustomLookupFieldEditor : UserControl, IFieldEditor { protected DropDownList ddlListNameLookup; // protected DropDownList ddlFieldNameLookup; protected CheckBoxList ddlRelatedFields; protected CheckBox cbxAllowMultiple; protected TextBox txtMasterFieldName; protected Label lblSelectedListLookup; protected Label lblMasterFieldName; protected RequiredFieldValidator RequiredFieldValidator1; private string listNameValue = ""; private string fieldNameValue = ""; private string dependentValue = ""; private string internalName = ""; private string masterFieldName = ""; private const string TEXT_FIELD = "Value"; private const string VALUE_FIELD = "Key"; /// <summary> /// Method called when the editor control gets loaded /// </summary> /// <param name="field"></param> public void InitializeWithField(SPField field) { CustomLookup myField = field as CustomLookup; if (myField != null) { this.listNameValue = myField.ListNameLookup; // this.fieldNameValue = myField.FieldNameLookup; this.dependentValue = myField.RelatedFields; this.internalName = myField.InternalName; // ddlListNameLookup.SelectedValue = myField.ListNameLookup; this.txtMasterFieldName.Text = myField.MasterFieldNameLookup; } //The field exists, so just show the list name and does not allow //the selection of another list //if (!IsPostBack) //{ // if (ddlListNameLookup.SelectedIndex != -1) // { // listNameValue = ddlListNameLookup.SelectedValue; // SPList list = Web.Lists[new Guid(listNameValue)]; // BindDisplayColumns(list); // ddlFieldNameLookup.Enabled = true; // ddlDependentFields.Enabled = true; // } // ListItem aggreitem = ddlFieldNameLookup.Items.FindByText(this.fieldNameValue); // if (aggreitem != null) // aggreitem.Selected = true; // if (dependentValue != "") // { // string[] dependentValueArray = this.dependentValue.Split('|'); // foreach (string str in dependentValueArray) // { // ListItem kk = ddlDependentFields.Items.FindByValue(str); // kk.Selected = true; // } // } //} } private void SetAsReadOnly(Label itemLabel, string itemText, DropDownList dropDownList) { itemLabel.Text = itemText; itemLabel.Visible = true; dropDownList.Visible = false; } public void OnSaveChange(SPField field, bool bNewField) { string dependentsValue = ""; foreach (ListItem li in ddlRelatedFields.Items) { if (li.Selected) { dependentsValue += li.Value + "|"; } } dependentsValue = dependentsValue.TrimEnd('|'); string listValue = this.ddlListNameLookup.SelectedValue; string masterFieldName = this.txtMasterFieldName.Text; CustomLookup CurrentLookupField = field as CustomLookup; if (bNewField) { CurrentLookupField.UpdateListNameLookup(listValue); CurrentLookupField.UpdateRelatedFields(dependentsValue); CurrentLookupField.UpdatedMasterFieldNameLookup(this.txtMasterFieldName.Text); } else { CurrentLookupField.ListNameLookup = listValue; CurrentLookupField.RelatedFields = dependentsValue; CurrentLookupField.MasterFieldNameLookup = txtMasterFieldName.Text; } } /// <summary> /// Just display the properties in the same section /// </summary> public bool DisplayAsNewSection { get { return false; } } protected override void CreateChildControls() { base.CreateChildControls(); if (!this.IsPostBack) { using (SPWeb Web = SPContext.Current.Site.OpenWeb()) { foreach (SPList List in Web.Lists) { if (!List.Hidden) ddlListNameLookup.Items.Add(new ListItem(List.Title, List.ID.ToString())); } if (this.listNameValue != "") { ddlListNameLookup.SelectedValue = this.listNameValue; SetAsReadOnly(lblSelectedListLookup, ddlListNameLookup.SelectedItem.Text, ddlListNameLookup); lblMasterFieldName.Text = txtMasterFieldName.Text; lblMasterFieldName.Visible = true; txtMasterFieldName.Visible = false; RequiredFieldValidator1.Enabled = false; } else { ddlListNameLookup.SelectedIndex = 0; } if (ddlListNameLookup.SelectedIndex != -1) { SPList list = Web.Lists[new Guid(ddlListNameLookup.SelectedValue)]; BindDisplayColumns(list); } } // ListItem aggreitem = ddlFieldNameLookup.Items.FindByText(this.fieldNameValue); //if (aggreitem != null) // aggreitem.Selected = true; ListItem listitem = ddlListNameLookup.Items.FindByValue(this.listNameValue); if (listitem != null) listitem.Selected = true; if (dependentValue != "") { string[] dependentValueArray = this.dependentValue.Split('|'); foreach (string str in dependentValueArray) { ListItem kk = ddlRelatedFields.Items.FindByValue(str); if (kk != null) kk.Selected = true; // kk.Selected =true; } } //} } } protected void ddlListNameLookup_SelectedIndexChanged(object sender, EventArgs e) { DropDownList dropDownList = sender as DropDownList; if (dropDownList.SelectedItem != null) { using (SPWeb web = SPContext.Current.Site.OpenWeb()) { Guid listId = new Guid(dropDownList.SelectedItem.Value); SPList list = web.Lists.GetList(listId, false); BindDisplayColumns(list); } //ddlFieldNameLookup.Enabled = true; ddlRelatedFields.Enabled = true; //lblSelectedLookupList.Visible = false; } else { //ddlFieldNameLookup.Enabled = false; ddlRelatedFields.Enabled = false; } } private void BindDisplayColumns(SPList list) { ddlRelatedFields.Items.Clear(); //ddlFieldNameLookup.Items.Clear(); foreach (SPField field in list.Fields) { if (!field.Hidden && !field.FromBaseType && (field.InternalName != txtMasterFieldName.Text || field.InternalName == this.internalName) || (!field.Hidden && field.InternalName == "Title")) { // ddlFieldNameLookup.Items.Add(new ListItem { Text = field.Title, Value = field.Id.ToString() }); ddlRelatedFields.Items.Add(new ListItem { Text = field.Title, Value = field.InternalName.ToString() }); } } } } }
using Microsoft.Web.WebPages.OAuth; using StarBastardCore.Website.Code; using StarBastardCore.Website.Filters; namespace StarBastardCore.Website.App_Start { public static class AuthConfig { public static void RegisterAuth() { var settings = new AppSettingsWrapper(); // For more information visit http://go.microsoft.com/fwlink/?LinkID=252166 //OAuthWebSecurity.RegisterMicrosoftClient(clientId: "", clientSecret: ""); OAuthWebSecurity.RegisterTwitterClient(consumerKey: settings.Get<string>("Twitter.AppId"), consumerSecret: settings.Get<string>("Twitter.AppSecret")); OAuthWebSecurity.RegisterFacebookClient(appId: settings.Get<string>("Facebook.AppId"), appSecret: settings.Get<string>("Facebook.AppSecret")); OAuthWebSecurity.RegisterGoogleClient(); InitializeSimpleMembershipAttribute.SimpleMembershipInitializer.Init(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum WaterState { UP, DOWN, CHANGING } public class Water : MonoBehaviour { //[HideInInspector] public WaterState state = WaterState.DOWN; public Gate left, right; public bool canUp, canDown; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void MoveUp() { state = WaterState.CHANGING; LeanTween.move(gameObject, transform.position + Vector3.up * 2.5f, 2.0f).setOnComplete(OnMoveUp); } public void OnMoveUp() { state = WaterState.UP; } public void MoveDown() { state = WaterState.CHANGING; LeanTween.move(gameObject, transform.position + Vector3.down * 2.5f, 2.0f).setOnComplete(OnMoveDown); } public void OnMoveDown() { state = WaterState.DOWN; } public void UpRequest() { CheckIfCanUp(); if (canUp) { MoveUp(); } else { left?.CloseRequest(); } } public void DownRequest() { CheckIfCanDown(); if (canDown) { MoveDown(); } else { right?.CloseRequest(); } } public void CheckIfCanUp() { bool leftClosed; if (left == null) leftClosed = false; else leftClosed = left.state == GateState.CLOSED; canUp = state == WaterState.DOWN && leftClosed; } public void CheckIfCanDown() { bool rightClosed; if (right == null) rightClosed = true; else rightClosed = right.state == GateState.CLOSED; canDown = state == WaterState.UP && rightClosed; } }
namespace RTSP_IPCam { using System; public delegate void PacketEventHandler(object sender, PacketEventArgs e); public class PacketEventArgs : EventArgs { public PacketEventArgs() { } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SincroPelis { static class KeyController { const UInt32 WM_KEYDOWN = 0x0100; const int VK_F5 = 0x20; [System.Runtime.InteropServices.DllImport("user32.dll")] static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam); public static void SendKey2Process(string name) { Process[] processes = Process.GetProcessesByName(name); foreach (Process proc in processes) PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0); } public static void logThis(string msg) { Console.WriteLine(msg); Program.myForm.SendDebug(msg); } } }
using Microsoft.AspNetCore.Mvc; using SFA.DAS.CommitmentsV2.Types; using SFA.DAS.PAS.Account.Api.Types; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; using System.Linq; namespace SFA.DAS.ProviderCommitments.Web.Extensions { public static class CohortSummaryExtension { public static CohortStatus GetStatus(this CohortSummary cohort) { if (cohort.IsDraft && cohort.WithParty == Party.Provider) return CohortStatus.Draft; if (!cohort.IsDraft && cohort.WithParty == Party.Provider) return CohortStatus.Review; if (!cohort.IsDraft && cohort.WithParty == Party.Employer) return CohortStatus.WithEmployer; if (!cohort.IsDraft && cohort.WithParty == Party.TransferSender) return CohortStatus.WithTransferSender; return CohortStatus.Unknown; } public static ApprenticeshipRequestsHeaderViewModel GetCohortCardLinkViewModel( this CohortSummary[] cohorts, IUrlHelper urlHelper, long providerId, CohortStatus selectedStatus, bool hasRelationship, ProviderAgreementStatus providerAgreementStatus) { return new ApprenticeshipRequestsHeaderViewModel { ProviderId = providerId, ShowDrafts = hasRelationship, CohortsInDraft = new ApprenticeshipRequestsTabViewModel( cohorts.Count(x => x.GetStatus() == CohortStatus.Draft), cohorts.Count(x => x.GetStatus() == CohortStatus.Draft) == 1 ? "Draft" : "Drafts", urlHelper.Action("Draft", "Cohort", new {providerId}), CohortStatus.Draft.ToString(), selectedStatus == CohortStatus.Draft), CohortsInReview = new ApprenticeshipRequestsTabViewModel( cohorts.Count(x => x.GetStatus() == CohortStatus.Review), "Ready for review", urlHelper.Action("Review", "Cohort", new {providerId}), CohortStatus.Review.ToString(), selectedStatus == CohortStatus.Review), CohortsWithEmployer = new ApprenticeshipRequestsTabViewModel( cohorts.Count(x => x.GetStatus() == CohortStatus.WithEmployer), "With employers", urlHelper.Action("WithEmployer", "Cohort", new {providerId}), CohortStatus.WithEmployer.ToString(), selectedStatus == CohortStatus.WithEmployer), CohortsWithTransferSender = new ApprenticeshipRequestsTabViewModel( cohorts.Count(x => x.GetStatus() == CohortStatus.WithTransferSender), "With transfer sending employers", urlHelper.Action("WithTransferSender", "Cohort", new {providerId}), CohortStatus.WithTransferSender.ToString(), selectedStatus == CohortStatus.WithTransferSender), IsAgreementSigned = providerAgreementStatus == ProviderAgreementStatus.Agreed }; } } public enum CohortStatus { Unknown, Draft, Review, WithEmployer, WithTransferSender } }
using gView.Core.Framework.Exceptions; using gView.Framework.system; using gView.MapServer; using gView.Server.AppCode.Extensions; using gView.Server.Services.MapServer; using Newtonsoft.Json; using System; using System.IO; using System.Linq; using System.Threading.Tasks; namespace gView.Server.AppCode { class MapService : IMapService { private string _filename = String.Empty, _folder = String.Empty, _name = String.Empty; private MapServiceType _type = MapServiceType.MXL; private MapServiceSettings _settings = null; private MapServiceSettings _folderSettings = null; private DateTime? _lastServiceRefresh = null; private readonly MapServiceManager _mss; public MapService() { } public MapService(MapServiceManager mss, string filename, string folder, MapServiceType type) { _mss = mss; _type = type; try { _filename = filename; if (type == MapServiceType.Folder) { DirectoryInfo di = new DirectoryInfo(_filename); _name = di.Name.ToLower(); } else { FileInfo fi = new FileInfo(filename); _name = fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length); } _folder = (folder ?? String.Empty).ToLower(); } catch { } } #region IMapService Member public string Name { get { return _name; } internal set { _name = value; } } public MapServiceType Type { get { return _type; } } public string Folder { get { return _folder; } } public string Fullname { get { return (String.IsNullOrEmpty(_folder) ? "" : _folder + "/") + _name; } } async public Task<IMapServiceSettings> GetSettingsAsync() { await ReloadServiceSettings(); return _settings; } async public Task SaveSettingsAsync() { FileInfo fi = new FileInfo(this.SettingsFilename); if (_settings == null && fi.Exists) { File.Delete(fi.FullName); } else { await File.WriteAllTextAsync(fi.FullName, JsonConvert.SerializeObject(_settings)); } } async public Task<bool> RefreshRequired() { await ReloadServiceSettings(); if (_settings.IsRunningOrIdle()) { return _lastServiceRefresh.HasValue == false || _settings.RefreshService > _lastServiceRefresh; } return false; } public void ServiceRefreshed() { _lastServiceRefresh = DateTime.UtcNow; } public DateTime? RunningSinceUtc { get { return _lastServiceRefresh; } } #endregion private string SettingsFilename { get { if (String.IsNullOrWhiteSpace(_filename)) { return String.Empty; } if (this.Type == MapServiceType.Folder) { return _filename + "/_folder.settings"; } else { if (_filename.Contains(".")) { return _filename.Substring(0, _filename.LastIndexOf(".")) + ".settings"; } return _filename + ".settings"; } } } private DateTime? _settingsLastWriteTime = null, _lastSettingsReload = null; async private Task ReloadServiceSettings(bool ifNewer = true) { try { // Performance: Do not load a every Request if (_lastSettingsReload.HasValue && (DateTime.UtcNow - _lastSettingsReload.Value).TotalSeconds > 10) { return; } FileInfo fi = new FileInfo(this.SettingsFilename); if (ifNewer == true) { if (_settingsLastWriteTime.HasValue && _settingsLastWriteTime.Value >= fi.LastWriteTimeUtc) { return; } } if (fi.Exists) { _settings = JsonConvert.DeserializeObject<MapServiceSettings>( await File.ReadAllTextAsync(fi.FullName)); _settingsLastWriteTime = fi.LastWriteTimeUtc; } } finally { if (_settings == null) { _settings = new MapServiceSettings(); } await ReloadParentFolderSettings(ifNewer); } _lastSettingsReload = DateTime.UtcNow; } async private Task ReloadParentFolderSettings(bool ifNewer = true) { try { if (this.Type == MapServiceType.Folder || String.IsNullOrWhiteSpace(this.Folder)) { return; } var folderMapService = _mss.MapServices .Where(s => s.Type == MapServiceType.Folder && this.Folder.Equals(s.Name, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault() as MapService; if (folderMapService == null) { return; } await folderMapService.ReloadServiceSettings(ifNewer); _folderSettings = folderMapService._settings; } finally { if (_folderSettings == null) { _folderSettings = new MapServiceSettings(); } } } async public Task CheckAccess(IServiceRequestContext context) { if (context == null) { throw new ArgumentNullException("context"); } await ReloadServiceSettings(); if (!_settings.IsRunningOrIdle()) { throw new Exception("Service not running: " + this.Fullname); } if (_folderSettings != null) { CheckAccess(context, _folderSettings); if (context.ServiceRequest != null) { if (!String.IsNullOrEmpty(_folderSettings.OnlineResource)) { context.ServiceRequest.OnlineResource = _folderSettings.OnlineResource; } if (!String.IsNullOrEmpty(_folderSettings.OutputUrl)) { context.ServiceRequest.OutputUrl = _folderSettings.OutputUrl; } } } CheckAccess(context, _settings); } private void CheckAccess(IServiceRequestContext context, IMapServiceSettings settings) { if (settings?.AccessRules == null || settings.AccessRules.Length == 0) // No Settings -> free service { return; } string userName = context.ServiceRequest?.Identity?.UserName; var accessRule = settings .AccessRules .Where(r => r.Username.Equals(userName, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); // if user not found, use rules for anonymous if (accessRule == null) { accessRule = settings .AccessRules .Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); } if (accessRule == null || accessRule.ServiceTypes == null) { throw new TokenRequiredException("forbidden (user:" + userName + ")"); } if (!accessRule.ServiceTypes.Contains("_all") && !accessRule.ServiceTypes.Contains("_" + context.ServiceRequestInterpreter.IdentityName.ToLower())) { throw new NotAuthorizedException(context.ServiceRequestInterpreter.IdentityName + " interface forbidden (user: " + userName + ")"); } var accessTypes = context.ServiceRequestInterpreter.RequiredAccessTypes(context); foreach (AccessTypes accessType in Enum.GetValues(typeof(AccessTypes))) { if (accessType != AccessTypes.None && accessTypes.HasFlag(accessType)) { if (!accessRule.ServiceTypes.Contains(accessType.ToString().ToLower())) { throw new NotAuthorizedException("Forbidden: " + accessType.ToString() + " access required (user: " + userName + ")"); } } } } async public Task CheckAccess(IIdentity identity, IServiceRequestInterpreter interpreter) { if (identity == null) { throw new ArgumentNullException("identity"); } if (interpreter == null) { throw new ArgumentNullException("interpreter"); } await ReloadServiceSettings(); if (!_settings.IsRunningOrIdle()) { throw new Exception("Service not running: " + this.Fullname); } if (_folderSettings != null) { CheckAccess(identity, interpreter, _folderSettings); } CheckAccess(identity, interpreter, _settings); } private void CheckAccess(IIdentity identity, IServiceRequestInterpreter interpreter, IMapServiceSettings settings) { if (settings?.AccessRules == null || settings.AccessRules.Length == 0) // No Settings -> free service { return; } string userName = identity.UserName; var accessRule = settings .AccessRules .Where(r => r.Username.Equals(userName, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); // if user not found, use rules for anonymous if (accessRule == null) { accessRule = settings .AccessRules .Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)) .FirstOrDefault(); } if (accessRule == null || accessRule.ServiceTypes == null) { throw new TokenRequiredException("forbidden (user:" + userName + ")"); } if (!accessRule.ServiceTypes.Contains("_all") && !accessRule.ServiceTypes.Contains("_" + interpreter.IdentityName.ToLower())) { throw new NotAuthorizedException(interpreter.IdentityName + " interface forbidden (user: " + userName + ")"); } } async public Task<bool> HasAnyAccess(IIdentity identity) { await ReloadServiceSettings(); if ((_folderSettings.AccessRules == null || _folderSettings.AccessRules.Length == 0) && (_settings.AccessRules == null || _settings.AccessRules.Length == 0)) { return true; } var accessRule = _folderSettings?.AccessRules?.Where(r => r.Username.Equals(identity.UserName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault() ?? _settings?.AccessRules?.Where(r => r.Username.Equals(identity.UserName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (accessRule == null) { accessRule = _folderSettings?.AccessRules?.Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault() ?? _settings?.AccessRules?.Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); } if (accessRule != null && accessRule.ServiceTypes != null && accessRule.ServiceTypes.Length > 0) { return true; } return false; } async public Task<AccessTypes> GetAccessTypes(IIdentity identity) { await ReloadServiceSettings(); var accessTypes = AccessTypes.None; if ((_folderSettings.AccessRules == null || _folderSettings.AccessRules.Length == 0) && (_settings.AccessRules == null || _settings.AccessRules.Length == 0)) // no rules -> service is open for everone { foreach (AccessTypes accessType in Enum.GetValues(typeof(AccessTypes))) { accessTypes |= accessType; } return accessTypes; } IMapServiceAccess folderAcccessRule = null; IMapServiceAccess accessRule = null; if (_folderSettings?.AccessRules != null && _folderSettings.AccessRules.Length > 0) { folderAcccessRule = _folderSettings?.AccessRules?.Where(r => r.Username.Equals(identity.UserName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (folderAcccessRule == null) { folderAcccessRule = _folderSettings?.AccessRules?.Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); } if (folderAcccessRule == null) { return accessTypes; } } accessRule = _settings?.AccessRules?.Where(r => r.Username.Equals(identity.UserName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); if (accessRule == null) { accessRule = _settings?.AccessRules?.Where(r => r.Username.Equals(Identity.AnonyomousUsername, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault(); } if (accessRule == null) // if there only folder settings use them for the service { accessRule = folderAcccessRule; } if (accessRule?.ServiceTypes == null || accessRule.ServiceTypes.Length == 0) { return AccessTypes.None; } foreach (var serviceType in accessRule.ServiceTypes.Where(s => !String.IsNullOrWhiteSpace(s) && !s.StartsWith("_"))) { if (Enum.TryParse<AccessTypes>(serviceType, true, out AccessTypes accessType)) { if (folderAcccessRule != null) // if folder settings exists use the service access thats also included in folder settings { if (folderAcccessRule.ServiceTypes.Where(r => serviceType.Equals(r, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault() != null) { accessTypes |= accessType; } } else // if no folder settings use the service access { accessTypes |= accessType; } } } return accessTypes; } async public Task<bool> HasPublishAccess(IIdentity identity) { if (!identity.IsAnonymous) // Never allow anonymous to publish/delete services { await ReloadServiceSettings(); if ((_folderSettings.AccessRules == null || _folderSettings.AccessRules.Length == 0) && (_settings.AccessRules == null || _settings.AccessRules.Length == 0)) // no rules -> service is open for everone { return true; } if (_folderSettings.AccessRules != null && _folderSettings.AccessRules.Length > 0) { if (_folderSettings.AccessRules.Where(r => r.Username == identity.UserName && r.ServiceTypes.Contains("publish")).Count() > 0) { return true; } } if (_type == MapServiceType.Folder && _settings.AccessRules != null && _settings.AccessRules.Length > 0) { if (_settings.AccessRules.Where(r => r.Username == identity.UserName && r.ServiceTypes.Contains("publish")).Count() > 0) { return true; } } } return false; } } public class MapServiceSettings : IMapServiceSettings { public MapServiceSettings() { this.Status = MapServiceStatus.Idle; this.RefreshServiceTicks = 0; } [JsonProperty("status")] public MapServiceStatus Status { get; set; } [JsonProperty("accessrules")] [JsonConverter(typeof(ConcreteTypeConverter<MapServiceAccess[]>))] public IMapServiceAccess[] AccessRules { get; set; } [JsonIgnore] public DateTime RefreshService { get; set; } [JsonProperty("refreshticks")] public long RefreshServiceTicks { get { return RefreshService.Ticks; } set { RefreshService = new DateTime(value, DateTimeKind.Utc); } } [JsonProperty("onlineresource", NullValueHandling = NullValueHandling.Ignore)] public string OnlineResource { get; set; } [JsonProperty("outputurl", NullValueHandling = NullValueHandling.Ignore)] public string OutputUrl { get; set; } #region Classes public class MapServiceAccess : IMapServiceAccess { [JsonProperty("username")] public string Username { get; set; } private string[] _serviceTypes = null; [JsonProperty("servicetypes")] public string[] ServiceTypes { get { return _serviceTypes; } internal set { _serviceTypes = value; } } public void AddServiceType(string serviceType) { if (String.IsNullOrWhiteSpace(serviceType)) { return; } serviceType = serviceType.ToLower(); if (_serviceTypes == null) { _serviceTypes = new string[] { serviceType.ToLower() }; } else { if (this.ServiceTypes?.Where(t => t.ToLower() == serviceType.ToLower()).Count() > 0) { return; } Array.Resize(ref _serviceTypes, _serviceTypes.Length + 1); _serviceTypes[_serviceTypes.Length - 1] = serviceType; } } public void RemoveServiceType(string serviceType) { if (_serviceTypes == null || this.ServiceTypes?.Where(t => t.ToLower() == serviceType.ToLower()).Count() == 0) { return; } _serviceTypes = _serviceTypes.Where(s => s.ToLower() != serviceType.ToLower()).ToArray(); } public bool IsAllowed(string serviceType) { if (_serviceTypes == null || _serviceTypes.Length == 0) { return false; } serviceType = serviceType.ToLower(); if (_serviceTypes.Contains(serviceType)) { return true; } if (serviceType.StartsWith("_") && _serviceTypes.Contains("_all")) { return true; } return false; } } #endregion #region Json Converter public class ConcreteTypeConverter<T> : JsonConverter { public override bool CanConvert(Type objectType) { return true; } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { return serializer.Deserialize<T>(reader); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, value); } } #endregion } }
using UnityEngine; using UnityEngine.SceneManagement; [CreateAssetMenu(fileName = "Scene Manager Asset", menuName = "Managers/Scene")] public class SceneManagerAsset : ScriptableObject { public void ResetScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } public void GoToScene(int sceneBuildIndex) { SceneManager.LoadScene(sceneBuildIndex); } public void GoToScene(string sceneName) { SceneManager.LoadScene(sceneName); } public void GoToNextScene() { SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } public void ExitGame() { Application.Quit(); } }
using System; namespace CourseHunter_32_Self_MaxValue { class Program { static void Main(string[] args) { Console.ForegroundColor = ConsoleColor.Green; Console.SetWindowSize(Console.WindowWidth, 40); Console.SetWindowSize(Console.WindowHeight, 30); int a = int.Parse(Console.ReadLine()); int b = int.Parse(Console.ReadLine()); Console.WriteLine(new string('_', 30)); int max = a; if (b > a) { max = b; } Console.WriteLine($"1. Max = {max}"); Console.WriteLine(new string('_', 30)); int mAx; if (a > b) { mAx = a; } else { mAx = b; } Console.WriteLine($"2. Max = {mAx}"); Console.WriteLine(new string('_', 30)); int maX = a > b ? a : b; Console.WriteLine($"3. Max = {maX}"); } } }
using System; using System.Collections.Generic; namespace POSServices.Models { public partial class Employee { public Employee() { LoginWeb = new HashSet<LoginWeb>(); UserLogin = new HashSet<UserLogin>(); } public int Id { get; set; } public int StoreId { get; set; } public string EmployeeName { get; set; } public DateTime? EffectiveDate { get; set; } public bool? Status { get; set; } public DateTime? LastUpdateDate { get; set; } public int PossitionId { get; set; } public string EmployeeCode { get; set; } public DateTime? ModifiedDatetime { get; set; } public virtual EmployeePossition Possition { get; set; } public virtual Store Store { get; set; } public virtual ICollection<LoginWeb> LoginWeb { get; set; } public virtual ICollection<UserLogin> UserLogin { get; set; } } }
using System.Collections.Generic; using Tomelt.ContentManagement; using Tomelt.ContentManagement.MetaData; using Tomelt.ContentManagement.MetaData.Builders; using Tomelt.ContentManagement.MetaData.Models; using Tomelt.ContentManagement.ViewModels; using Tomelt.Layouts.Helpers; namespace Tomelt.Layouts.Settings { public class ContentPartLayoutSettingsHooks : ContentDefinitionEditorEventsBase { public override IEnumerable<TemplateViewModel> PartEditor(ContentPartDefinition definition) { var model = definition.Settings.GetModel<ContentPartLayoutSettings>(); yield return DefinitionTemplate(model); } public override IEnumerable<TemplateViewModel> PartEditorUpdate(ContentPartDefinitionBuilder builder, IUpdateModel updateModel) { var model = new ContentPartLayoutSettings(); updateModel.TryUpdateModel(model, "ContentPartLayoutSettings", null, null); builder.Placeable(model.Placeable); yield return DefinitionTemplate(model); } } }
using System.IO.Pipelines; using SuperSocket.ProtoBase; namespace SuperSocket.Channel { /// <summary> /// /// </summary> public interface IPipeChannel { Pipe In { get; } Pipe Out { get; } IPipelineFilter PipelineFilter { get; } } }
using Alabo.App.Asset.Withdraws.Domain.Entities; using Alabo.Domains.Repositories; namespace Alabo.App.Asset.Withdraws.Domain.Repositories { public interface IWithdrawRepository : IRepository<Withdraw, long> { } }
using System; using System.ComponentModel.DataAnnotations; //TODO: Add other using statements here namespace com.Sconit.Entity.SYS { public partial class EntityPreference { #region Non O/R Mapping Properties public enum CodeEnum { DefaultPageSize = 10001, SessionCachedSearchStatementCount = 10002, ItemFilterMode = 10003, ItemFilterMinimumChars = 10004, InProcessIssueWaitingTime = 10005, CompleteIssueWaitingTime = 10006, SMTPEmailAddr = 10007, SMTPEmailHost = 10008, SMTPEmailPasswd = 10009, IsRecordLocatoinTransactionDetail = 10010, DecimalLength = 10011, DefaultPickStrategy = 10012, SIWebServiceUserName = 10013, SIWebServicePassword = 10014, SIWebServiceTimeOut = 10015, AllowManualCreateProcurementOrder = 10016, //WMSAnjiRegion = 10017, MaxRowSizeOnPage = 10018, DefaultBarCodeTemplate = 10019, ExceptionMailTo = 11020, IsAllowCreatePurchaseOrderWithNoPrice = 11021, IsAllowCreateSalesOrderWithNoPrice = 110210, GridDefaultMultiRowsCount = 11022, SAPSERVICEUSERNAME = 11001, SAPSERVICEPASSWORD = 11002, SAPSERVICETIMEOUT = 11003, SAPSERVICEIP = 11004, SAPSERVICEPORT = 11005, ProdLineWarningColors = 20001, MiCleanTime = 20002, MiFilterCapacity = 20003, MiContainerLocations = 20004, HistoryPasswordCount = 20007, //N次之内密码不能重复 PasswordExpiredDays = 20008, //密码过期日期 PasswordLength= 20009, //密码长度 PasswordComplexity = 20010, //是否启用密码复杂度 FordEdiBakFolder = 90001, FordEdiErrorFolder = 90002, FordEdiFileFolder = 90003, MaxRowSize = 90100, FordFlow = 90112, SystemFlag = 90102, SmartDeviceVersion = 90103, EKORG = 90105,//采购组织 BUKRS = 90106,//公司代码 WERKS = 90107,//工厂 //密码最长存留期 PassawordActive = 11071, //帐号锁定阀值 PasswordLockCount = 11072, //公司名称 CompanyName = 11073, //公司网址 WebAddress = 11074, //上报时间 StartUpTime = 11075, //默认配送标签模板 DefaultDeliveryBarCodeTemplate = 90114, //强制移库先进先出 IsForceFIFO = 110220, } [Display(Name = "EntityPreference_Desc", ResourceType = typeof(Resources.SYS.EntityPreference))] public string EntityPreferenceDesc { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TinyIoC.Tests.Fakes { public class FakeLifetimeProvider : TinyIoC.TinyIoCContainer.ITinyIoCObjectLifetimeProvider { public object TheObject { get; set; } public object GetObject() { return TheObject; } public void SetObject(object value) { TheObject = value; } public void ReleaseObject() { TheObject = null; } } }
using System; using System.Collections.Generic; namespace KSF_Surf.Models { // Classes for Steam API response JSON deserialization -------------------------------- public class SteamProfile { public string steamid { get; set; } public int communityvisibilitystate { get; set; } public int profilestate { get; set; } public string personaname { get; set; } public string profileurl { get; set; } public string avatar { get; set; } public string avatarmedium { get; set; } public string avatarfull { get; set; } public long lastlogoff { get; set; } public int personastate { get; set; } public string realname { get; set; } public string primaryclanid { get; set; } public long timecreated { get; set; } public int personastateflags { get; set; } public string loccountrycode { get; set; } } public class SteamProfileResponse { public List<SteamProfile> players { get; set; } } public class SteamProfileRootObject { public SteamProfileResponse response { get; set; } } public static class SteamIDConverter { public static string Steam32to64(string steam32) { string[] steam32_arr = steam32.Split(':'); if (steam32_arr.Length != 3) return ""; long convertedTo64Bit; try { convertedTo64Bit = long.Parse(steam32_arr[2]) * 2; convertedTo64Bit += 76561197960265728; // Valve's magic constant convertedTo64Bit += long.Parse(steam32_arr[1]); } catch (Exception) { return ""; } return convertedTo64Bit.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace wsApiEPayment.Models.Openpay { public class VentaOP { public string Cantidad { get; set; } public string Descripction { get; set; } public string OrderId { get; set; } //public string Moneda { get; set; } public InformacionClienteOP InformacionCliente { get; set; } public DatosTarjetaOP DatosTarjeta { get; set; } } public class InformacionClienteOP { public string Nombre { get; set; } public string ApellidoPaterno { get; set; } public string Correo { get; set; } public string Telefono { get; set; } } public class DatosTarjetaOP { public string NumeroTarjeta { get; set; } public string CVV { get; set; } public string NombreTarjeta { get; set; } public string AnioExpiracion { get; set; } public string MesExpiracion { get; set; } } }
using System; using System.Globalization; using System.Collections.Generic; using Kattis.IO; public class Program { public static List<edge>[] adj; public static EdgeComparer edgeComparer; public struct union_find { public int[] parent; public union_find(int n) { parent = new int[n]; for (int i = 0; i < n; i++) { parent[i] = i; } } public int find(int x) { if (parent[x] == x) { return x; } else { parent[x] = find(parent[x]); return parent[x]; } } public void unite(int x, int y) { parent[find(x)] = find(y); } } public struct edge { public int u, v; public float weight; public edge(int _u, int _v, float _w) { u = _u; v = _v; weight = _w; } } public class EdgeComparer: IComparer<edge>{ public int Compare(edge a, edge b){ if(a.weight < b.weight){ return 1; } else { return -1; } } } public bool edge_cmp(edge a, edge b) { return a.weight < b.weight; } public List<edge> mst(int n, List<edge> edges) { union_find uf = new union_find(n); //sort(edges.begin(), edges.end(), edge_cmp); edges.Sort(edgeComparer); List<edge> res = new List<edge>(); for (int i = 0; i < edges.Count; i++) { int u = edges[i].u, v = edges[i].v; if (uf.find(u) != uf.find(v)) { uf.unite(u, v); res.Add(edges[i]); } } return res; } static public void Main () { Scanner scanner = new Scanner(); BufferedStdoutWriter writer = new BufferedStdoutWriter(); edgeComparer = new EdgeComparer(); while(scanner.HasNext()){ int n = 1000; adj = new List<edge>[nIntersections]; for(int i = 0; i < n; i++){ adj[i] = new List<edge>(); } for(int i = 0; i < nCorridors; i++){ int x = 0; int y = 1; float f = 0.5; adj[x].Add(new edge(x, y, f)); } } writer.Flush(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CSVHandler { class Salary : Transaction{ protected String employer = "Real Journeys Ltd"; public Salary(String transDate, String transType, double transValue, double accBalance) : base(transDate, transType, transValue, accBalance){ // Constructor } public override string getVendor() { return employer; } public override String toString() { return "Salary Payment: $" + String.Format("{0:0,0.00}", this.transValue) + " on " + transDate; } } }
using GeoAPI.Geometries; using SharpMap.UI.Forms; namespace SharpMap.UI.Tools.Zooming { /// <summary> /// Zoom In / Out using mouse wheel, or rectangle. /// </summary> public abstract class ZoomTool : MapTool { protected ZoomTool(MapControl mapControl) : base(mapControl) { } } }
namespace SumIntegers { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main(string[] args) { Console.WriteLine(Execute()); } private static string Execute() { var args = Console.ReadLine().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); var nums = new List<int>(); for (int i = 0; i < args.Length; i++) { var val = 0; if (int.TryParse(args[i], out val)) { nums.Add(val); } } if (nums.Count == 0) { return "No match"; } return nums.Sum().ToString(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using PropertyChanged; using FuelRadar.Model; namespace FuelRadar.ViewModel { /// <summary> /// The viewmodel for the search result page /// </summary> [ImplementPropertyChanged] public class SearchResultVM : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public PriceInfoVM SelectedResult { get; set; } public List<PriceInfoVM> Results { get; set; } public SearchResultVM() { this.Results = new List<PriceInfoVM>(); } public void UpdateResults(List<PriceInfo> newResults) { this.Results = newResults.Select(priceInfo => new PriceInfoVM(priceInfo)).OrderBy(vm => vm.MainPrice).ToList(); this.SelectedResult = this.Results.First(); } } }
using NUnit.Framework; using System; using System.Collections.Generic; using System.Text; namespace MergeSort { public class MinAvgTwoSliceService { public void ConsoleRun() { ////Array //var array = string.Empty; //while (array.ToLower() != "exit") //{ // Console.WriteLine("Enter an array: "); // array = Console.ReadLine(); // if (array == "exit") // break; // Console.WriteLine("Enter number of times to shift: "); // var line2 = Console.ReadLine(); // if (line2 == "exit") // break; // else // { // int[] arr = Array.ConvertAll(array.Split(" "), int.Parse); // var outputArray = GetMinStartingPoint(arr, Convert.ToInt32(line2)); // string output = outputArray[0].ToString(); // for (int i = 1; i < arr.Length; i++) // { // output = output + ", " + outputArray[i].ToString(); // } // Console.WriteLine($"Output: {output}"); // } //} } public int GetMinStartingPoint(int[] arr) { var minStart = 0; decimal currentAverage = 10001; decimal minAverage = 10001; for (int i = 0; i < arr.Length - 1; i++) { currentAverage = (decimal) (arr[i] + arr[i+1]) / 2; if (currentAverage < minAverage) { minStart = i; minAverage = currentAverage; } if (i < arr.Length - 2) { currentAverage = (decimal)(arr[i] + arr[i + 1] + arr[i + 2]) / 3; if (currentAverage < minAverage) { minStart = i; minAverage = currentAverage; } } } return minStart; } public int GetMinStartingPointSlow(int[] arr) { var minStart = 0; decimal currentAverage = 10000; decimal minAverage = 10000; var prefixSum = new int[arr.Length]; prefixSum[0] = arr[0]; //Create and populate prefix sum array for (int i = 1; i < arr.Length; i++) { prefixSum[i] = prefixSum[i - 1] + arr[i]; } //loop through prefix sum, starting at 1, divide by i + 1. for (int i = 1; i < prefixSum.Length; i++) { currentAverage = (decimal) prefixSum[i] / (i + 1); //if currentAverage < minAverage then minStart equals 0? //minAverage = min of currentAverage vs minAverage if (currentAverage < minAverage) { minAverage = currentAverage; } } //loop through prefix sum, starting at 0, for (int i = 0; i < prefixSum.Length - 2; i++) { //inner loop through prefix sum starting at 2 for (int j = i + 2; j < prefixSum.Length; j++) { //currentAverage = sum j minus sum i, divide by j - i currentAverage = ((decimal) prefixSum[j] - prefixSum[i]) / (j - i); //if currentAverage < minAverage then minStart equals i+1? //minAverage = min of currentAverage vs minAverage if (currentAverage < minAverage) { minStart = i + 1; minAverage = currentAverage; } } } //return minStart; return minStart; } } [TestFixture] public class MinAvgTwoSliceServiceTests { public MinAvgTwoSliceService service = new MinAvgTwoSliceService(); [Test] public void GetMinStartingPointTest1() { var givenArray = new int[] { 4, 2, 2, 5, 1, 5, 8 }; var expectedArray = 1; Assert.AreEqual(expectedArray, service.GetMinStartingPoint(givenArray)); } } }
using System; using System.IO; using Microsoft.WindowsAPICodePack.Dialogs; using Prism.Mvvm; using Prism.Commands; using Prism.Interactivity.InteractionRequest; using HabMap.CanvasModule.Models; using Microsoft.Win32; namespace HabMap.CanvasModule.ViewModels { class CanvasCreationViewModel : BindableBase, IInteractionRequestAware { #region Private Fields /// <summary> /// Solution Name /// </summary> private string _sectionName; /// <summary> /// Solution Location path /// </summary> private string _sectionMap; private INewCanvasNotification _notification; /// <summary> /// Wheter or not the specified project settings is valid /// </summary> private bool _isValid; /// <summary> /// Message to be displayed if invalid properties entered /// </summary> private string _message; #endregion #region Public Properties /// <summary> /// Section Name /// </summary> public string SectionName { get { return _sectionName; } set { SetProperty(ref _sectionName, value); ValidateProperties(); } } /// <summary> /// Solution Location path /// </summary> public string SectionMap { get { return _sectionMap; } set { SetProperty(ref _sectionMap, value); ValidateProperties(); } } /// <summary> /// Command for browsing folder location /// </summary> public DelegateCommand BrowseLocationCommand { get; set; } /// <summary> /// Command for Accept command /// </summary> public DelegateCommand AcceptCommand { get; set; } /// <summary> /// Command for cancel command /// </summary> public DelegateCommand CancelCommand { get; set; } /// <summary> /// Action for indicating if interaction is finished /// </summary> public Action FinishInteraction { get; set; } public INotification Notification { get { return _notification; } set { SetProperty(ref _notification, (INewCanvasNotification)value); } } /// <summary> /// Wheter or not the specified project settings is valid /// <seealso cref="_isValid"/> /// </summary> public bool IsValid { get { return _isValid; } set { SetProperty(ref _isValid, value); } } /// <summary> /// Message to be displayed if invalid properties entered /// </summary> public string Message { get { return _message; } set { SetProperty(ref _message, value); } } #endregion #region Constructors public CanvasCreationViewModel() { BrowseLocationCommand = new DelegateCommand(OnBrowseSectionMapCommand); AcceptCommand = new DelegateCommand(() => { _notification.SectionName = this.SectionName; _notification.SectionMap = this.SectionMap; _notification.Confirmed = true; FinishInteraction?.Invoke(); }).ObservesCanExecute(() => IsValid); CancelCommand = new DelegateCommand(() => { _notification.SectionName = null; _notification.SectionMap = null; _notification.Confirmed = false; FinishInteraction?.Invoke(); }); } #endregion #region Methods /// <summary> /// For when the browse buttion is clicked /// </summary> private void OnBrowseSectionMapCommand() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "Bitmaps (.bmp)|*.bmp|All Files (*.*)|*.*"; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == true) { SectionMap = openFileDialog.FileName; } } /// <summary> /// Checks whether or not the specified section name is valid and unique /// </summary> private void ValidateProperties() { if (string.IsNullOrEmpty(SectionName) || string.IsNullOrEmpty(SectionMap)) { IsValid = false; return; } //if (Directory.Exists(SectionMap + @"\" + SectionName)) //{ // Message = "Project Solution Folder Already Exists!"; // IsValid = false; // return; //} Message = null; IsValid = true; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class GameManagement : MonoBehaviour { public static bool isGamePaused = false; public Player player; public GameObject pauseMenu; public GameObject gameOverMenu; public void Update() { if (Input.GetKeyDown(KeyCode.Escape)) { if (isGamePaused) { Resume(); } else { Paused(); } } if(player.GetComponent<Player>().Life == 0) { GameOver(); } } public void Resume() { pauseMenu.SetActive(false); Time.timeScale = 1; isGamePaused = false; } public void Paused() { pauseMenu.SetActive(true); Time.timeScale = 0; isGamePaused = true; } public void GameOver() { gameOverMenu.SetActive(true); Time.timeScale = 0; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class RespawnManager : MonoBehaviour { public GameObject[] players; private List<GameObject> spawnPoints; // Start is called before the first frame update void Start() { FillSpawnPointsList(); } void FillSpawnPointsList() { spawnPoints = new List<GameObject>(); foreach (Transform child in transform) { spawnPoints.Add(child.gameObject); } } // Update is called once per frame void Update() { } public void Respawn() { for (int i = 0; i < 4; ++i) { int spawnPoint = Random.Range(0, spawnPoints.Count); players[i].transform.position = spawnPoints[spawnPoint].transform.position; float initialRotation = Random.Range(0.0f, 360.0f); players[i].transform.eulerAngles = new Vector3(0.0f, initialRotation, 0.0f); spawnPoints.RemoveAt(spawnPoint); if (spawnPoints.Count <= 0) { FillSpawnPointsList(); } } } }
using UnityEngine; using System; public class AudioEffectsController : MonoBehaviour { public GameSound[] sounds; // Use this for initialization void Start () { foreach(GameSound s in sounds) { s.source = gameObject.AddComponent<AudioSource>(); s.source.clip = s.clip; s.source.volume = s.volume; s.source.pitch = s.pitch; s.source.loop = s.loop; if(s.playOnAwake) { Play(s.name); } } foreach(GameSound s in sounds) { if(s.playOnAwake) { Play(s.name); } } } public void Play(string name) { GameSound s = Array.Find(sounds, sound => sound.name == name); if(s == null) { Debug.LogWarning("Audio missing!!!!!"); return; } s.source.Play(); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace UnitTestProject1 { [TestClass] public class Tests { const string folderPath = @"C:\SolutionDirectory"; [TestMethod] public void EatComments_Test() { var codeCleaner = new CodeCleaner(folderPath); codeCleaner.EatComments(); } [TestMethod] public void EatRegions_Test() { var codeCleaner = new CodeCleaner(folderPath); codeCleaner.EatRegions(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BibleBrowserUWP { /// <summary> /// Constant node names for Zefania XML markup. /// </summary> public static class Zefania { public static string NDE_BIBLEBOOK = "BIBLEBOOK"; public static string NDE_LANG = "language"; public static string NDE_INFO = "INFORMATION"; public static string NDE_TITLE = "title"; public static string ATTR_BOOKNAME = "bname"; public static string ATTR_BOOKSHORTNAME = "bsname"; public static string ATTR_BOOKNUM = "bnumber"; public static string ATTR_BIBLENAME = "biblename"; public static string VERSION_ABBR = "identifier"; } public static class Chars { public static string NBSPACE = " "; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class GameManager : MonoBehaviour { public int crewmatesFound = 0; public int crewmatesTotal = 5; public Text crewmatesFoundText; public Text returnToSpaceShipText; public Text winLoseText; public bool allCrewmatesFound = false; public bool hasReturnedToShip = false; public bool playerIsDead = false; private static GameManager _instance; public static GameManager Instance { get { return _instance; } } private void Awake() { if (_instance != null && _instance != this) { Destroy(gameObject); } else { _instance = this; } } private void Start() { StartGame(); } private void Update() { if (hasReturnedToShip) { WinGame(); } else if (playerIsDead) { LoseGame(); } } public void StartGame() { crewmatesFound = 0; crewmatesFoundText.text = crewmatesTotal.ToString(); CleanUI(); StartTime(); } private void LoseGame() { CleanUI(); winLoseText.text = "Game Over\nPress Enter / Pause to play again"; winLoseText.enabled = true; StopTime(); } private void WinGame() { CleanUI(); winLoseText.text = "You win!\nPress Enter / Pause to play again"; winLoseText.enabled = true; StopTime(); } private void StopTime() { Time.timeScale = 0.0f; } private void StartTime() { Time.timeScale = 1.0f; } private void CleanUI() { winLoseText.enabled = false; returnToSpaceShipText.enabled = false; } public void FoundCrewmate() { crewmatesFound++; crewmatesFoundText.text = (crewmatesTotal - crewmatesFound).ToString(); if (crewmatesFound >= crewmatesTotal) { // Separate audio for finding all crewmates? allCrewmatesFound = true; returnToSpaceShipText.enabled = true; } else { // PLay default audio Debug.Log("Henlo"); } } public static void RestartGame() { if (Time.timeScale <= 0.01f) { SceneManager.LoadScene(SceneManager.GetActiveScene().name); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine.EventSystems; using UnityEngine.UI; using UnityEngine.SceneManagement; using UnityEngine; public class LoadGameButton : MonoBehaviour, IPointerClickHandler, IPointerEnterHandler, IPointerExitHandler { public Texture highlight; public Texture original; private bool mouseover = false; // Start is called before the first frame update /* NAME: Start SYNOPSIS: DESCRIPTION: Start is called before the first frame update RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ void Start() { } // /* NAME: Update SYNOPSIS: DESCRIPTION: This update function is used to call the replace and putimageback functions. This is needed because it indicated in real time that the player is hovering over the load button on the main menu. When the load button is hovered it is then highlighted by replacing the original image with a lighter version so that the player can see were they are about to click so there is less room for error. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ void Update() { if (mouseover) { replaceImage(); } if (!mouseover) { putImageBack(); } } /* NAME: OnPointerClick SYNOPSIS: DESCRIPTION: This function is used to load a previously saved game state so that the player can continue were they left off. This is important because the player does not have to start from the begging of game everytime they want to play. This function is not currently working. In the function I removed the bad code and have sudo code with how I would do it. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ public void OnPointerClick(PointerEventData eventData) { SceneManager.LoadScene("Load State"); // Click the button // Get the saved game file and parce it in. // Use the game file that was parced into load the saved scene that was the last // player position and area. // Saves positions of npcs and enemies / bosses // } /* NAME: OnPointerEnter SYNOPSIS: DESCRIPTION: This is used to detect when the player is hovering the mouse over the Load button to highlight the button for click verification. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ public void OnPointerEnter(PointerEventData eventData) { mouseover = true; Debug.Log("Mouse enter"); } /* NAME: OnPointerExit SYNOPSIS: DESCRIPTION: This is used to deactive the highlighted button when the player moves the mouse away from the button so that it goes back to the default button look. This indicates that the button is not being hovered so it can not be clicked on accident. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ public void OnPointerExit(PointerEventData eventData) { mouseover = false; Debug.Log("Mouse exit"); } /* NAME: replaceImage SYNOPSIS: DESCRIPTION: This function is used to grab the raw image file and replace it with the highlighted image file to get the effect when mouseing over the button. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ void replaceImage() { RawImage current = this.gameObject.GetComponent<RawImage>(); current.texture = highlight; } /* NAME: putImageBack SYNOPSIS: DESCRIPTION: This function is used to put the stock image back after the button is no longer being hovered so that it goes back to the default image. RETURNS: AUTHOR: Thomas Furletti DATE: 07/08/2020 */ void putImageBack() { RawImage current = this.gameObject.GetComponent<RawImage>(); current.texture = original; } }
using System.Linq; using UcenikShuffle.Common; using UcenikShuffle.Common.Exceptions; using Xunit; namespace UcenikShuffle.UnitTests.CommonTests { public class ParserTests { [Theory] //Spaces [InlineData("1, 2, 3", new[] { 1, 2, 3 })] //Multiple delimiters in a row [InlineData("5,20,,1", new[] { 5, 20, 1 })] //Single group size [InlineData("1", new[] { 1 })] public void StringToGroupSizes_ShouldWork(string value, int[] expected) { expected = expected.OrderBy(s => s).ToArray(); var actual = Parsers.StringToGroupSizes(value).OrderBy(s => s).ToArray(); Assert.Equal(expected.Length, actual.Length); for (int i = 0; i < expected.Count(); i++) { Assert.Equal(expected, actual); } } [Theory] //Empty values [InlineData(null)] [InlineData("")] //<=0 group size [InlineData("0")] [InlineData("-3")] //Invalid delimiter [InlineData("1;;4")] //Decimal group size [InlineData("1.5,4")] public void StringToGroupSizes_ShouldThrowGroupSizeException(string value) { Assert.Throws<GroupSizeException>(() => Parsers.StringToGroupSizes(value).ToList()); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace Entities.DTOs.CreationDtos { public class RelatedPersonForCreationDto { public int RelatedFromId { get; set; } public int RelatedToId { get; set; } [MaxLength(8, ErrorMessage = "Maximum length for the number type is 8 characters.")] [RegularExpression(@"კოლეგა|ნაცნობი|ნათესავი|სხვა", ErrorMessage = "You can only choose from these values: \"კოლეგა\", \"ნაცნობი\", \"ნათესავი\"\", \"სხვა\" ")] public string RelationType { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialWorld.Business.DTOs.ApplicantDtos { public class AddApplicantDto { public int UserId { get; set; } public int JobId { get; set; } } }
using System; using Uintra.Features.LinkPreview.Models; namespace Uintra.Features.Comments.Models { public class CommentEditViewModel { public string UpdateElementId { get; set; } public Guid Id { get; set; } public string Text { get; set; } public LinkPreviewModel LinkPreview { get; set; } } }
using System.Data.Entity; namespace Uintra.Persistence.Context { public abstract class IntranetDbContext : DbContext { protected IntranetDbContext() : this("umbracoDbDSN") { } protected IntranetDbContext(string nameOrConnectionString) : base(nameOrConnectionString) { Configuration.AutoDetectChangesEnabled = false; Configuration.ProxyCreationEnabled = false; Configuration.LazyLoadingEnabled = false; } } }
using System; namespace Crystal.Plot2D.Charts { /// <summary> /// Describes axis as having ticks type. /// Provides access to some typed properties. /// </summary> /// <typeparam name="T">Axis tick's type.</typeparam> public interface ITypedAxis<T> { /// <summary> /// Gets the ticks provider. /// </summary> /// <value>The ticks provider.</value> ITicksProvider<T> TicksProvider { get; } /// <summary> /// Gets the label provider. /// </summary> /// <value>The label provider.</value> LabelProviderBase<T> LabelProvider { get; } /// <summary> /// Gets or sets the convertion of tick from double. /// Should not be null. /// </summary> /// <value>The convert from double.</value> Func<double, T> ConvertFromDouble { get; set; } /// <summary> /// Gets or sets the convertion of tick to double. /// Should not be null. /// </summary> /// <value>The convert to double.</value> Func<T, double> ConvertToDouble { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cracking { class Urilify { public static string urilify(string str) { int n = str.Length; int spaces = 0; //first pass count the blanks for (int i = 0; i < str.Length; i++) { if (str[i] == ' ') {//use str as char array spaces++; } } // compute the new length int newLength = (n + spaces * 2); char [] newString = new char[newLength]; // from tail to head, fill spaces guided by original string for (int i = n - 1; i >= 0; i--) { if (str[i] == ' ') { newString[newLength - 1] = '0'; newString[newLength - 2] = '2'; newString[newLength - 3] = '%'; newLength = newLength - 3; } else { newString[newLength - 1] = str[i]; newLength--; } } return string.Join("", newString); } public static string urilify2(string str) { int n = str.Length; int spaces = 0; //first pass count the blanks for (int i = 0; i < str.Length; i++) { if (str[i] == ' ') {//use str as char array spaces++; } } // compute the new length int newLength = 0; char[] newString = new char[n+(2*spaces)]; // from tail to head, fill spaces guided by original string for (int i = 0; i<n; i++) { if (str[i] == ' ') { newString[newLength++] = '0'; newString[newLength++] = '2'; newString[newLength++] = '%'; } else { newString[newLength++] = str[i]; } } return string.Join("", newString); } } }
using System; using System.Collections.Generic; using System.Text; namespace AimaTeam.WebFormLightAPI.httpCore { /// <summary> /// http_service_handler.cs 调用某些函数的参数对象 add by OceanHo 2015-08-25 17:41:15 /// </summary> public class RunHandlerEvent { /// <summary> /// 获取或者设置一个值,该值表示当前请求的是否已经处理过。如果处理过,程序将不再执行往后的代码 /// </summary> public bool Handled { get; set; } /// <summary> /// 获取一个值,该值表示当前请求的义务方法名称(如:getUserInfo) /// </summary> public string ActionName { get; internal set; } /// <summary> /// 获取或者设置一个值,该值表示当前请求的义务方法自定义属性,如(UnAllowCallMethodAttribute标记) /// </summary> public object[] CustomAttributes { get; internal set; } /// <summary> /// 获取或者设置一个值,该值表示当前请求的义务方法参数信息 /// </summary> public System.Reflection.ParameterInfo[] ActionParameters { get; internal set; } } }
namespace Rhino.Mocks.Tests.FieldsProblem { using System; using System.Globalization; using System.Threading; using Xunit; public class FieldProblem_Henrik { [Fact] public void Trying_to_mock_null_instance_should_fail_with_descriptive_error_message() { var culture = Thread.CurrentThread.CurrentUICulture; try { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var ex = Assert.Throws<ArgumentNullException>(() => RhinoMocksExtensions.Expect<object>(null, x => x.ToString())); Assert.Equal("You cannot mock a null instance\r\nParameter name: mock", ex.Message); } finally { Thread.CurrentThread.CurrentUICulture = culture; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GoogleMapsComponents.Maps.Data { public class SetPropertyEvent { } }
using UnityEngine; using System.Collections; [RequireComponent(typeof(Collider2D))] public class Lane : MonoBehaviour { public int LaneIndex = 0; private Collider2D myCollider = null; // Use this for initialization void Start () { myCollider = this.GetComponent<Collider2D>(); } // Update is called once per frame void Update () { if (GameManager.Instance.IsPaused) return; #if UNITY_STENGERT if (Input.GetMouseButtonDown(0)) { TryRaycast(Input.mousePosition); } #else if (Input.touchCount > 0) { foreach (Touch t in Input.touches) { if (t.phase != TouchPhase.Began) continue; TryRaycast(t.position); } } #endif } private void TryRaycast(Vector3 screenPoint) { RaycastHit2D hit; Ray ray = Camera.main.ScreenPointToRay(screenPoint); int mask = ~(1 << 8); hit = Physics2D.Raycast(ray.origin, ray.direction,float.MaxValue,mask); if(hit != null && hit.collider != null) { if(hit.collider == this.myCollider) { if(RightPanelController.instance.GetPotToThrow()) { PotPool.Instance.SpawnPot(this.LaneIndex); } } } } }