text
stringlengths
13
6.01M
using SDL2; using SharpDL.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SharpDL.Events { public enum KeyState { Pressed = SDL.SDL_PRESSED, Released = SDL.SDL_RELEASED } public class KeyboardEventArgs : GameEventArgs { private byte repeat; public KeyInformation KeyInformation { get; set; } public KeyState State { get; set; } public UInt32 WindowID { get; set; } public bool IsRepeat { get { if (repeat != 0) return true; else return false; } } public KeyboardEventArgs(SDL.SDL_Event rawEvent) : base(rawEvent) { RawTimeStamp = rawEvent.key.timestamp; repeat = rawEvent.key.repeat; KeyInformation = new KeyInformation(rawEvent.key.keysym.scancode, rawEvent.key.keysym.sym, rawEvent.key.keysym.mod); State = (KeyState)rawEvent.key.state; WindowID = rawEvent.key.windowID; } } }
using System.Collections.Generic; using DutchTreat.Data.Entities; namespace WebApplication4.Data { public interface IDutchRepository { IEnumerable<Product> GetAllProducts(); IEnumerable<Product> GetProductByCategory(string Category); IEnumerable<Order> GetAllOrders(); bool SaveAll(); Order GetOrderById(int id); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LH_Sprite : MonoBehaviour { /* the player is going to be a circle for now */ // Use this for initialization private Animator mAnimator; private SpriteRenderer mSpriteRenderer; void Start () { mAnimator = GetComponent<Animator>(); //mSpriteRenderer = GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update () { if (Input.GetAxis("Horizontal") < 0 ) { mAnimator.SetTrigger("westKey"); } else if (Input.GetAxis("Horizontal") > 0 ) { mAnimator.SetTrigger("eastKey"); } else if (Input.GetAxis("Vertical") < 0 ) { mAnimator.SetTrigger("southKey"); } else if (Input.GetAxis("Vertical") > 0) { mAnimator.SetTrigger("northKey"); } else mAnimator.SetTrigger("noKey"); } void FixedUpdate() { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class EnemySpawer_script : MonoBehaviour { public GameObject[] EnemyPrefabs; public float Offsett; void Start() { SpawnEnemies(5,5); } public void SpawnEnemies(int w, int h) { for (int x = 0; x <= w; x++) { for (int y = 0; y < h; y++) { GameObject e = Instantiate(EnemyPrefabs[0], this.transform.position, Quaternion.identity, this.transform); Vector2 pos = new Vector2(this.transform.position.x +(x*Offsett), this.transform.position.y + (y *Offsett)); e.transform.position = pos; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Capstone.Web.Models; using System.Data.SqlClient; namespace Capstone.Web.DAL { public class SurveySqlDAL : ISurveyDAL { readonly string connectionString; const string SQL_GetSurveyResultsCount = "SELECT COUNT(*) FROM survey_result WHERE parkCode = @parkCode;"; const string SQL_SaveSurveyForm = "INSERT INTO survey_result VALUES (@parkCode, @emailAddress, @state, @activityLevel);"; const string SQL_GetParkActivityCount = "SELECT COUNT(*) FROM survey_result WHERE parkCode = @parkCode AND activityLevel = "; public SurveySqlDAL(string connectionString) { this.connectionString = connectionString; } public SurveyResultModel GetParkSurveyResults(string parkCode) { try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); // Get total number of surveys completed for park SqlCommand cmd = new SqlCommand(SQL_GetSurveyResultsCount, conn); cmd.Parameters.AddWithValue("parkCode", parkCode); int surveyCount = Convert.ToInt32(cmd.ExecuteScalar()); // Get count of activity levels listed on this park's surveys Dictionary<string, int> activityTypeCount = new Dictionary<string, int>(); List<string> activityType = new List<string>() { "inactive", "sedentary", "active", "extremely active" }; foreach (string s in activityType) { string finalQuery = SQL_GetParkActivityCount + "'" + s + "';"; cmd = new SqlCommand(finalQuery, conn); cmd.Parameters.AddWithValue("parkCode", parkCode); activityTypeCount[s] = Convert.ToInt32(cmd.ExecuteScalar()); } // Populate and return SurveyResultModel SurveyResultModel completedSurveyResult = new SurveyResultModel(); completedSurveyResult.ParkCode = parkCode; completedSurveyResult.NumSurveys = surveyCount; completedSurveyResult.NumInactive = activityTypeCount["inactive"]; completedSurveyResult.NumSedentary = activityTypeCount["sedentary"]; completedSurveyResult.NumActive = activityTypeCount["active"]; completedSurveyResult.NumExtremelyActive = activityTypeCount["extremely active"]; return completedSurveyResult; } } catch (SqlException) { throw; } } public bool SaveSurveyForm(SurveyFormModel surveyForm) { try { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); SqlCommand cmd = new SqlCommand(SQL_SaveSurveyForm, conn); cmd.Parameters.AddWithValue("parkCode", surveyForm.ParkCode); cmd.Parameters.AddWithValue("emailAddress", surveyForm.Email); cmd.Parameters.AddWithValue("state", surveyForm.State); cmd.Parameters.AddWithValue("activityLevel", surveyForm.ActivityLevel); int numRowsAffected = cmd.ExecuteNonQuery(); return numRowsAffected > 0; } } catch (SqlException) { throw; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Game.Utils; using Game.Kernel; using Game.Facade; using Game.Entity.NativeWeb; using System.Data; namespace Game.Web.Match { public partial class ActivityInfo : UCPageBase { public string title = string.Empty; public string content = string.Empty; protected void Page_Load(object sender, EventArgs e) { Game.Entity.NativeWeb.Activity model = FacadeManage.aideNativeWebFacade.GetActivity(IntParam); if (model != null) { title = model.Title; content = Utility.HtmlDecode(model.Describe); } } } }
namespace Whale.DAL.Models { public enum NotificationTypeEnum { TextNotification, AddContactNotification, MeetingInviteNotification, UnreadMessage, UnreadGroupMessage } }
using System; class Tests { static void Main() { // Translate the double into sign, exponent and mantissa. long bits = BitConverter.DoubleToInt64Bits(-27.25); // Note that the shift is sign-extended, hence the test against -1 not 1 bool negative = (bits < 0); int exponent = (int)((bits >> 52) & 0x7ffL); long mantissa = bits & 0xfffffffffffffL; // Subnormal numbers; exponent is effectively one higher, // but there's no extra normalisation bit in the mantissa if (exponent == 0) { exponent++; } // Normal numbers; leave exponent as it is but add extra // bit to the front of the mantissa else { mantissa = mantissa | (1L << 52); } // Bias the exponent. It's actually biased by 1023, but we're // treating the mantissa as m.0 rather than 0.m, so we need // to subtract another 52 from it. exponent -= 1075; /* Normalize */ while ((mantissa & 1) == 0) { /* i.e., Mantissa is even */ mantissa >>= 1; exponent++; } Console.WriteLine(mantissa); } }
using System; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Client.WorkDone { public static class WorkDoneProxyExtensions { public static TResult ObserveWorkDone<T, TResult>( this IClientLanguageClient proxy, T @params, Func<IClientLanguageClient, T, TResult> func, IObserver<WorkDoneProgress> observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IClientLanguageClient proxy, T @params, Func<IClientLanguageClient, T, TResult> func, IWorkDoneProgressObserver observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IGeneralLanguageClient proxy, T @params, Func<IGeneralLanguageClient, T, TResult> func, IObserver<WorkDoneProgress> observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IGeneralLanguageClient proxy, T @params, Func<IGeneralLanguageClient, T, TResult> func, IWorkDoneProgressObserver observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this ITextDocumentLanguageClient proxy, T @params, Func<ITextDocumentLanguageClient, T, TResult> func, IObserver<WorkDoneProgress> observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this ITextDocumentLanguageClient proxy, T @params, Func<ITextDocumentLanguageClient, T, TResult> func, IWorkDoneProgressObserver observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IWindowLanguageClient proxy, T @params, Func<IWindowLanguageClient, T, TResult> func, IObserver<WorkDoneProgress> observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IWindowLanguageClient proxy, T @params, Func<IWindowLanguageClient, T, TResult> func, IWorkDoneProgressObserver observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IWorkspaceLanguageClient proxy, T @params, Func<IWorkspaceLanguageClient, T, TResult> func, IObserver<WorkDoneProgress> observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } public static TResult ObserveWorkDone<T, TResult>( this IWorkspaceLanguageClient proxy, T @params, Func<IWorkspaceLanguageClient, T, TResult> func, IWorkDoneProgressObserver observer ) where T : IWorkDoneProgressParams { DoObserveWorkDone(proxy, @params, observer); return func(proxy, @params); } private static void DoObserveWorkDone(ILanguageProtocolProxy proxy, IWorkDoneProgressParams @params, IObserver<WorkDoneProgress> observer) { var token = SetWorkDoneToken(@params); proxy.GetRequiredService<IClientWorkDoneManager>().Monitor(token).Subscribe(observer); } private static void DoObserveWorkDone(ILanguageProtocolProxy proxy, IWorkDoneProgressParams @params, IWorkDoneProgressObserver observer) { var token = SetWorkDoneToken(@params); var observable = proxy.GetRequiredService<IClientWorkDoneManager>().Monitor(token); observable.Subscribe( v => { switch (v) { case WorkDoneProgressBegin begin: observer.OnBegin(begin); break; case WorkDoneProgressReport report: observer.OnReport(report); break; case WorkDoneProgressEnd end: observer.OnEnd(end); break; } }, observer.OnError, observer.OnCompleted ); } private static readonly PropertyInfo WorkDoneTokenProperty = typeof(IWorkDoneProgressParams).GetProperty(nameof(IWorkDoneProgressParams.WorkDoneToken))!; private static ProgressToken SetWorkDoneToken(IWorkDoneProgressParams @params) { if (@params.WorkDoneToken is not null) return @params.WorkDoneToken; WorkDoneTokenProperty.SetValue(@params, new ProgressToken(Guid.NewGuid().ToString())); return @params.WorkDoneToken!; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Parse; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; namespace XamChat.Droid { [Application (Theme ="@android:style/Theme.Holo.Light")] public class AppController : Application { public AppController(IntPtr javaReference,JniHandleOwnership tranfer):base(javaReference,tranfer) { } public override void OnCreate () { base.OnCreate (); ServiceContainer.Register<FriendViewModel> (() => new FriendViewModel ()); ServiceContainer.Register<LoginViewModel> (() => new LoginViewModel ()); ServiceContainer.Register<ConversationViewModel> (()=>new ConversationViewModel()); ServiceContainer.Register<RegisterViewModel> (() => new RegisterViewModel ()); //Service ServiceContainer.Register<IWebServices> (() => new ParseServices ()); ServiceContainer.Register<ISetting> (() => new FakeSetting()); ParseClient.Initialize ("v5lLpyneLopQfiepI52AsdDlM1pR8YutPCBihxmy","JpzclP34JWemDAo6fTioz1l12gGbAHl6fpJiHcvT"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; namespace BagBag.Models { [MetadataType(typeof(Employee.EmployeeMetaData))] public partial class Employee { internal sealed class EmployeeMetaData { [Display(Name ="Mã Nhân Viên")] [Required(ErrorMessage = "Không được rỗng")] public string EmployeeCode { get; set; } [Display(Name = "Password")] [Required(ErrorMessage = "Không được rỗng")] public string EmployeePass { get; set; } [Required(ErrorMessage = "Không được rỗng")] [Display(Name = "Tên")] public string LastName { get; set; } [Required(ErrorMessage = "Không được rỗng")] [Display(Name = "Họ")] public string FirstName { get; set; } [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)] [DataType(DataType.DateTime, ErrorMessage = "Dữ liệu phải là kiểu ngày tháng")] [Required(ErrorMessage = "Vui lòng điền ngày sinh")] public Nullable<System.DateTime> BirthDate { get; set; } [Display(Name = "Hình đại diện")] public string EmployeImg { get; set; } [Required(ErrorMessage = "Không được rỗng")] [Display(Name = "Email")] [DataType(DataType.EmailAddress,ErrorMessage ="Email phải đúng định dạng")] public string EmployeeEmail { get; set; } [Required(ErrorMessage = "Không được rỗng")] [Display(Name = "Địa chỉ")] [DataType(DataType.MultilineText)] public string EmployeeAddress { get; set; } public Nullable<int> RoleId { get; set; } } } }
/* Store the contents for ListBoxes to display. */ using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class ListBank : MonoBehaviour { public static ListBank Instance; public List<Item> items = new List<Item> (); private ItemDatabase database; public Item itemToBuy; public RectTransform canvasRect; public GameBehavior behave; private int[] contents = { 1, 2, 3, 4, 5 }; void Start(){ behave = GameObject.FindGameObjectWithTag("Behaviour").GetComponent<GameBehavior>(); canvasRect = this.GetComponentInParent<Canvas> ().GetComponent<RectTransform>(); database = GetComponent<ItemDatabase> (); for (int i = 0; i < database.getItemDataLength() ; i++) { items.Add (new Item()); } for (int i = 0; i < database.getItemDataLength(); i++) { AddItem(i); } } public void AddItem(int id){ Item itemToAdd = database.FetchItemByID (id); items[id] = itemToAdd; } void Awake() { Instance = this; } public int getListContent( int index ) { return contents[ index ]; } public Item getItem(int index){ return items [index]; } // public void updateDetail( int index ) // { // title.text = "Section " + contents[ index ].ToString(); // detail.text = details[ index ]; // } public int getListLength() { return items.Count; } }
using HardwareInventoryManager.Filters; using HardwareInventoryManager.Models; using HardwareInventoryManager.Repository; using HardwareInventoryManager.Helpers; using HardwareInventoryManager.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using HardwareInventoryManager.Helpers.Assets; using System.IO; using Newtonsoft.Json.Linq; using HardwareInventoryManager.Helpers.Dashboard; using System.Web.Security; using Microsoft.AspNet.Identity; namespace HardwareInventoryManager.Controllers { [AllowAnonymous] public class HomeController : AppController { public ActionResult Index() { if (User.Identity.IsAuthenticated) { return RedirectToAction("Dashboard"); } return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } [CustomAuthorize] [ConfirmedFilter] public ActionResult Dashboard() { DashboardViewModel dashboad = new DashboardViewModel(); string userId = User.Identity.GetUserId(); DashboardService dashboardService = new DashboardService(User.Identity.Name); IList<TwoColumnChartData> fourMonthExpiryData = dashboardService.AssetsByExpiry4Months(); dashboad.AssetExpiryData = JArray.FromObject(fourMonthExpiryData); IList<TwoColumnChartData> pieChartData = dashboardService.AssetsByCategoryPieChart(); dashboad.AssetsByCategory = JArray.FromObject(pieChartData); IList<TwoColumnChartData> warrantyExpiryData = dashboardService.AssetsWarrantyExpiry4Months(); dashboad.WarrantyExpiryData = JArray.FromObject(warrantyExpiryData); int[] wishListStatus = dashboardService.WishListSummary(); dashboad.TotalWishlistPending = wishListStatus[0]; dashboad.TotalWishlistProcessing = wishListStatus[1]; dashboad.TotalWishlistSupplied = wishListStatus[2]; dashboad.TotalWishlistComplete = wishListStatus[3]; dashboad.TotalWishlist = wishListStatus[0] + wishListStatus[1] + wishListStatus[2] + wishListStatus[3]; var dashboardCollection = dashboardService.DisplayPanels(userId); dashboad.DisplayButtonsPanel = bool.Parse(dashboardCollection[EnumHelper.ApplicationSettingKeys.DashboardButtonsPanel.ToString()]); dashboad.DisplayNotificationsPanel = bool.Parse(dashboardCollection[EnumHelper.ApplicationSettingKeys.DashboardNotificationsPanel.ToString()]); dashboad.DisplayAssetPieChartPanel = bool.Parse(dashboardCollection[EnumHelper.ApplicationSettingKeys.DashboardAssetsPieChartPanel.ToString()]); dashboad.DisplayAssetObsoletePanel = bool.Parse(dashboardCollection[EnumHelper.ApplicationSettingKeys.DashboardAssetsObsoleteChartPanel.ToString()]); dashboad.DisplayAssetWarrantyPanel= bool.Parse(dashboardCollection[EnumHelper.ApplicationSettingKeys.DashboardAssetsWarrantyExpiryChartPanel.ToString()]); dashboad.DisplayWatchlistStatsPanel = bool.Parse(dashboardCollection[EnumHelper.ApplicationSettingKeys.DashboardAssetsWishlistStatsPanel.ToString()]); return View(dashboad); } private AssetService _assetService; public AssetService AssetService { get { if(_assetService == null) { return new AssetService(User.Identity.Name); } return _assetService; } set { _assetService = value; } } } public class DataForChart { public string DateString { get; set; } public int CountOfAssets { get; set; } } public class AssetByCategoryForChart { public string Category { get; set; } public int CountOfAssets { get; set; } } }
namespace NDDDSample.Interfaces.HandlingService.Host.IoC { #region Usings using System; using System.ServiceModel; using Application; using Application.Impl; using Castle.Facilities.WcfIntegration; using Castle.Facilities.WcfIntegration.Behaviors; using Castle.MicroKernel.Registration; using Castle.Windsor; using Castle.Windsor.Configuration.Interpreters; using Domain.Model.Handlings; using Infrastructure.Messaging; using Infrastructure.Utils; using Messaging; using Wcf; using WebService; #endregion public static class ContainerBuilder { private static string handlingServiceWorkerRoleEndpoint = "localhost:8089"; public static IWindsorContainer Build(string endPoint) { handlingServiceWorkerRoleEndpoint = endPoint; return Build(); } public static IWindsorContainer Build() { var container = new WindsorContainer(new XmlInterpreter("Windsor.config")); //Init components and services RegisterComponents(container); // For Rhino Commons Rhino.Commons.IoC.Initialize(container); //Register messages and handlers new MessageHandlerRegister(container, typeof (CargoHandledMessage).Assembly, typeof (CargoHandledHandler).Assembly); return container; } private static void RegisterComponents(IWindsorContainer container) { container.Register( AllTypes.Pick() //Scan repository assembly for domain model interfaces implementation .FromAssemblyNamed("NDDDSample.Persistence.NHibernate") .WithService.FirstNonGenericCoreInterface("NDDDSample.Domain.Model")); container.Register(Component.For<IMessageBus>() .ImplementedBy<MessageBus>() .LifeStyle.Singleton); container.Register(Component.For<IWindsorContainer>() .Instance(container)); container.Register(Component.For<IApplicationEvents>() .ImplementedBy<EsbApplicationEventsImpl>()); container.Register(Component.For<IHandlingEventService>() .ImplementedBy<HandlingEventService>()); container.Register(Component.For<HandlingEventFactory>() .ImplementedBy<HandlingEventFactory>()); container.Register(Component.For<ICargoInspectionService>() .ImplementedBy<CargoInspectionService>()); container.AddFacility<WcfFacility>(); container.Register( Component.For<MessageLifecycleBehavior>(), Component.For<UnitOfWorkBehavior>(), Component .For<IHandlingReportService>() .ImplementedBy<HandlingReportService>() .Named("HandlingReportService") .LifeStyle.Transient .ActAs(new DefaultServiceModel() .AddEndpoints(WcfEndpoint .BoundTo(new BasicHttpBinding()) //.At("http://localhost:8089/HandlingReportServiceFacade") .At(new Uri(String.Format("http://{0}/HandlingReportServiceFacade", handlingServiceWorkerRoleEndpoint))) // adds this message action to this endpoint .AddExtensions(new LifestyleMessageAction() ) )) ); } } }
using JumpAndRun.API; using JumpAndRun.Content.Blocks; using JumpAndRun.TerrainGeneration; using System; using System.Collections.Generic; namespace JumpAndRun.Content.TerrainGeneration.Bioms { public class TestBiom : IBiom { public int BaseHeight => -20; public IBlock Filler => new DirtBlock(); public IBlock Surface => new GrassBlock(); public int GetHeight(int x) { return (int)(Math.Sin(x * 0.1) * 10 + Math.Sin(x * 0.5 + 1) * 2 + Math.Sin(x * 0.001 + 1) * 50 + Math.Sin(x * 0.05 + 1) * 20 + 20); } public float Size => 0.5f; public List<Tuple<ILandscapeObject, float>> LandscapeObjects => new List<Tuple<ILandscapeObject, float>> { new Tuple<ILandscapeObject, float>(null, 1.0f) }; public string Name => "JumpAndRun.TestBiom"; } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ovan_P1 { class Constant { public string storeName = "ラーメン世代"; public string dbName = "obanp1"; public string yesStr = "はい"; public string noStr = "いいえ"; public string unit = "円"; public string amountUnit = "枚"; public string amountUnit1 = "点"; public string yearLabel = "年"; public string monthLabel = "月"; public string dayLabel = "日"; public string hourLabel = "時"; public string minuteLabel = "分"; public string cancelLabel = "キャンセル"; public string cancelRun = "取消実行"; public string categoryListPrintMessage = "全てのカテゴリーを印刷 しても宜しいですか?"; public string categoryListPrintTitle = "カテゴリー一覧印刷"; public string categoryListTitleLabel = "表示位置/カテゴリーNo"; public string categoryDiplayLabel = "表示位置"; public string categoryLabel = "カテゴリー"; public string groupListTitleLabel = "グループ名"; public string groupTitleLabel = "グループ"; public string groupListPrintMessage = "全てのグループを印刷 しても宜しいですか?"; public string groupListPrintTitle = "グループ一覧"; public string TimeLabel = "販売時間"; public string SaleTimeLabel = "販売時刻"; public string prevButtonLabel = "プレビュー"; public string printButtonLabel = "一覧印刷"; public string printProductNameField = "印刷品目名"; public string salePriceField = "販売価格"; public string saleLimitField = "限定数"; public string saleStatusLabel = "販売中"; public string saleStopLabel = "中止"; public string saleStopText = "利用停止"; public string saleStopStatusText = "販売停止"; public string currentDateLabel = "現在の日付"; public string currentTimeLabel = "現在の時刻"; public string timeSettingLabel = "時刻設定"; public string dateSettingTitle = "日付設定"; public string timeSettingTitle = "時間設定"; public string passwordSettingLabel = "暗証番号設定"; public string oldPasswordLabel = "旧暗証番号"; public string newPasswordLabel = "新暗証番号"; public string confirmPasswordLabel = "新暗証番号(確認用)"; public string charClearLabel = "一文字クリア"; public string allClearLabel = "全クリア"; public string settingLabel = "設定"; public string passwordInputTitle = "パスワードを入力"; public string receiptionTitle = "領収書発行一覧"; public string receiptionField = "印刷日時"; public string dailyReportTitle = "売上日報"; public string priceField = "金額"; public string closingProcessTitle = "締め処理"; public string timeRangeLabel = "時台"; public string logReportLabel = "ログ表示"; public string falsePurchaseTitle = "誤購入取消 / 取消"; public string falsePurchaseSubTitle1 = "誤購入取消 / 取消"; public string falsePurchaseSubContent1 = "誤購入の取消を行う場合は下記のボタンを\nタッチしてください。"; public string falsePurchaseSubTitle2 = "誤購入一覧表示"; public string falsePurchaseButton = "誤購入取消"; public string falsePurchaseStartLabel = "開始"; public string falsePurchaseEndLabel = "終了"; public string falsePurchaseListLabel = "一覧表示"; public string falsePurchasePageTitle = "取り消す注文を選択"; public string orderTimeField = "注文日付"; public string prodNameField = "品名"; public string saleNumberField = "売上連番"; public string openTimeChangeTitle = "営業変更"; public string dayType = "曜日タイプ"; public string startTimeLabel = "営業開始時刻"; public string endTimeLabel = "営業終了時刻"; public string menuReadingTitle = "メニュー読込"; public string menuReadingSubContent1 = "USBメモリをセットしてメニュー読込ボタンを押して、別ウィンドウが開いたら読み込むメニューを選択してください。"; public string menuReadingSubContent2 = "中止する場合は、取消ボタンを押してください。"; public string menuReadingButton = "メニュー読込"; public string menuReadingErrorTitle = "データに問題があります。"; public string menuReadingErrorContent = "設定ソフトウェアより「USBメモリへ の書込」を行った後に再度試してください。"; public string restEmptyMessage = "注文商品の在庫がありません。"; public string orderDialogRunText = "注文内容確認"; public string sumLabel = "合計"; public string receiptInstruction = "上記金額正に領収しました。"; public string soldoutSettingTitle = "売り切れ設定"; public string categorylistLabel = "カテゴリー選択"; public string prdNameField = "品目名"; public string saleStateSettingField = "状態"; public string sumProgressAlert = "締め処理中です。終わるまでお待ちください"; public string orderCancelDialogTitle = "取消確認"; public string orderDate = "注文日"; public string orderTime = "注文時間"; public string orderProductList = "品目"; public string orderSumPrice = "合計金額"; public string cancelErrorMessage = "締め処理を行った後は取消出来ません"; public string cancelResultErrorMessage = "データが無いか、日付が誤っています"; public string prdCategoryField = "所属カテゴリー"; public string prdPriceFieldIncludTax = "販売価格(税込)"; public string prdSaleTimeField = "販売時刻設定"; public string prdScreenText = "画面メッセージ"; public string prdPrintText = "印刷メッセージ"; public string errorMsgTitle = "係員をお呼びください。"; public string systemErrorMsg = "システムエラーが発生しました。"; public string systemSubErrorMsg = "マニュアルに従ってサービスをご依頼ください。"; public string printErrorMsg = "レシート用紙切れです。\nロール紙を補充してください。"; public string printSubErrorMsg = "完了しましたらエラー解除ボタンを押してください。"; public string printOfflineErrorMsg = "プリンタは現在オフラインです。"; public string dbErrorTitle = "資料基地大湯です。"; public string dbErrorContent = "メニュー読込に行って、まずデータをロード受けてください。"; public string bankNoteErrorMsg = "紙幣識別機1エラー収納部異常"; public string bankNoteSubErrorMsg = "完了しましたらエラー解除ボタンを押してください。"; public string bankNoteDepositeErrorMsg = "紙幣識別機エラー挿入部異常"; public string bankNoteWithdrawErrorMsg = "紙幣排出機エラーメイン搬送路異常"; public string unChanged = "未変更"; public string dayTypeBefore = "デフォルトの曜日タイプ"; public string dayTypeAfter = "変更後の曜日タイプ"; public string startTimeBefore = "デフォルトの開始時間"; public string startTimeAfter = "変更御の開始時間"; public string endTimeBefore = "デフォルトの終了時間"; public string endTimeAfter = "変更後の終了時間"; public string openTimeInstruction1 = "曜日タイプが変更された場合、指定された曜日の販売時間設定、\n商品構成に切り替わります。"; public string openTimeInstruction2 = "デフォルトの開始時間より前に設定された場合、\nデフォルトの販売開始時間に販売される商品が早期開始対象になります。"; public string openTimeInstruction3 = "デフォルトの終了時間より後に変更された場合、\nデフォルトの販売終了時間の直前に販売されている商品が延長対象になります。\n(売り切れ商品はそのまま)"; public string openTimeSettingMessageTitle = "営業変更"; public string openTimeSettingMessageContent = "設定内容を保存し前の画面に戻ります。変更内容は即時反映されます。宜しいですか?"; public string openTimeCancelMessageTitle = "営業変更取消"; public string openTimeCancelMessageContent = "設定内容を元に戻して前の画面に戻ります。宜しいですか?"; public string gettingLabel = "了解"; public int singleticketPrintPaperWidth = 203; public int singleticketPrintPaperHeight = 35 * 9; public int multiticketPrintPaperWidth = 203; public int multiticketPrintPaperHeight = 35 * 8; public int receiptPrintPaperWidth = 203; public int receiptPrintPaperHeight = 35 * 9; public int dailyReportPrintPaperWidth = 203; public int dailyReportPrintPaperHeight = 560; public int receiptReportPrintPaperWidth = 203; public int receiptReportPrintPaperHeight = 560; public int categorylistPrintPaperWidth = 203; public int categorylistPrintPaperHeight = 560; public int grouplistPrintPaperWidth = 203; public int grouplistPrintPaperHeight = 560; public int fontSizeBig = 14; public int fontSizeMedium = 10; public int fontSizeSmall = 8; public int fontSizeSmaller = 6; public string[] tbNames = new string[] { "CategoryTB", "ProductTB", "CategoryDetailTB", "SaleTB", "TableSetTicket", "TableSetReceipt", "TableSetStore", "DaySaleTB", "ReceiptTB", "CancelOrderTB", "TableGroupName", "TableGroupDetail", "GeneralTB", "TableSetAudio" }; public string[] dayTypeValue = new string[] { "平日", "土曜", "日曜" }; public string[] months1 = new string[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" }; public string[] dates1 = new string[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }; public string[] months2 = new string[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" }; public string[] dates2 = new string[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }; public string[] times = new string[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public string[] end_times = new string[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23" }; public string[] minutes = new string[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public string[] end_minutes = new string[] { "00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59" }; public string[] main_Menu = new string[3] { "メンテナンス", "販売画面", "メニュー読込" }; public string[] main_Menu_Name = new string[3] { "maintenance", "salescreen", "readingmenu" }; public string[] saleCategories = new string[] { "定番ラーメン", "替わり唾ラーメン", "トッピング", "ご飯、餃子", "ドリンク" }; public int[] saleCategoryLayout = new int[] { 16, 25, 9, 13, 21 }; public string[] saleCategories_btnName = new string[] { "category_1", "category_2", "category_3", "category_4", "category_5" }; public string[] transactionLabelName = new string[] { "投入 金額", "購入 金額", "釣銭" }; public string[] productAmount = new string[] { "1 枚", "2 枚", "3 枚", "4 枚", "5 枚", "6 枚", "7 枚", "8 枚", "9 枚" }; public string dialogTitle = "注文メニュー"; public string dialogInstruction = "複数注文時はプルダウンで選ん\n決定ボタンを押して下さい。"; public string saleScreenTopTitle = "いらっしゃいませ\n定番メニューがおすすめです。"; public string main_Menu_Title = "処理を選択して下さい。"; public string upButtonName = "upButton"; public string downButtonName = "downButton"; public string ticketingButtonText = "発券"; public string cancelButtonText = "取消"; public string receiptButtonText = "領収書"; public string deleteText = "削除"; public string backText = "戻る"; public string[] maintanenceLabel = new string[] { "各種処理", "内容表示", "設 定" }; public string[][] maintanenceButton = new string[][] { new string[] { "売切れ設定", "締め処理", "誤購入取消" }, new string[] { "商品品目", "カテゴリー", "グループ" }, new string[] { "時刻設定", "暗証番号", "営業変更" } }; public Image upButtonImage = Image.FromFile(@"resources\\upButton.png"); public Image downButtonImage = Image.FromFile(@"resources\\downButton.png"); public Image increaseButtonImage = Image.FromFile(@"resources\\increaseButton.png"); public Image decreaseButtonImage = Image.FromFile(@"resources\\decreaseButton.png"); public string[] maitanenceButtonImage = new string[] { @"resources\\menubutton1.png", @"resources\\menubutton2.png", @"resources\\menubutton3.png" }; public string[] closingProcessLabel = new string[] { "手動での締め処理", "日報の処理", "領収書の処理", "ログ表示" }; public string[][] closingProcessButton = new string[][] { new string[] { "手動締め処理開始", "締め処理解除" }, new string[] { "表示", "印刷" }, new string[] { "表示", "印刷" }, new string[] { "表示", "" } }; public string[] closingProcessButtonImage = new string[] { @"resources\\menubutton1.png", @"resources\\menubutton2.png", @"resources\\menubutton3.png", @"resources\\menubutton1.png" }; public string dropdownArrowUpIcon = @"resources\\arrow_up.png"; public string dropdownArrowDownIcon = @"resources\\arrow_down.png"; public string backButton = @"resources\\back_new.png"; public string powerButton = @"resources\\power_button.png"; public string soldoutBadge = @"resources\\soldout.png"; public string dropdownarrowImage = @"resources\\dropdownarrow.png"; // public string dropdownArrowDownIcon = @"D:\\ovan\\Ovan_P1\\images\\arrow_down_icon.png"; public string keyboardButtonImage = @"resources/keyboard.png"; public string numberButtonImage = @"resources/numberbutton.png"; public string prevkeyButtonImage = @"resources/prevkey.png"; public string nextkeyButtonImage = @"resources/nextkey.png"; public string clearkeyButtonImage = @"resources/clearkey.png"; public string soldoutButtonImage1 = @"resources/soldoutbutton.png"; public string soldoutButtonImage2 = @"resources/soldoutbutton_2.png"; public string menureadingButtonImage = @"resources/menureadingbutton.png"; public string disableButtonImage = @"resources/disablebutton.png"; public string cancelButton = @"resources\\cancelbutton.png"; public string roundedFormImage = @"resources\\roundedpanel.png"; public string dialogFormImage = @"resources\\dialogpanel.png"; public string errordialogImage = @"resources\\errordialogpanel.png"; public string rectBlueButton = @"resources\\rectblue.png"; public string rectRedButton = @"resources\\rectred.png"; public string rectGreenButton = @"resources\\rectgreen.png"; public string rectLightBlueButton = @"resources\\rectlightblue.png"; //public string greenGradient = @"resources\\greengradientbg.png"; //public string blueGradient = @"resources\\bluegradientbg.png"; Color[] saleCategoryButtonColor = new Color[5] { Color.FromArgb(255, 255, 192, 0), Color.FromArgb(255, 255, 204, 255), Color.FromArgb(255, 204, 255, 153), Color.FromArgb(255, 204, 255, 255), Color.FromArgb(255, 255, 255, 204) }; Color[] saleCategoryButtonBorderColor = new Color[5] { Color.FromArgb(255, 255, 148, 0), Color.FromArgb(255, 255, 153, 204), Color.FromArgb(255, 51, 204, 51), Color.FromArgb(255, 0, 176, 240), Color.FromArgb(255, 255, 192, 0) }; public Color[][] pattern_Clr = new Color[][] { new Color[] { Color.FromArgb(255, 255, 192, 0), Color.FromArgb(255, 255, 153, 204), Color.FromArgb(255, 50, 204, 50),Color.FromArgb(255, 0, 176, 240),Color.FromArgb(255, 255, 255, 204),Color.FromArgb(255, 255, 204, 255),Color.FromArgb(255, 204, 255, 153),Color.FromArgb(255, 204, 255, 255)}, new Color[] { Color.FromArgb(255, 255, 153, 51), Color.FromArgb(255, 255, 102, 153), Color.FromArgb(255, 0, 153,0),Color.FromArgb(255, 0, 0, 255),Color.FromArgb(255, 255, 192, 0),Color.FromArgb(255, 255, 153, 204),Color.FromArgb(255, 51, 204, 51),Color.FromArgb(255, 0, 176, 240)}, new Color[] { Color.FromArgb(255, 0, 0, 255), Color.FromArgb(255, 0, 176, 240), Color.FromArgb(255, 0, 0, 255),Color.FromArgb(255, 0, 204, 255),Color.FromArgb(255, 147, 219, 255),Color.FromArgb(255, 204, 255, 255),Color.FromArgb(255, 147, 219, 255),Color.FromArgb(255, 204, 255, 255)}, new Color[] { Color.FromArgb(255, 255, 102, 0), Color.FromArgb(255, 251, 151, 0), Color.FromArgb(255, 255, 102, 0),Color.FromArgb(255, 251, 151, 0),Color.FromArgb(255, 253, 232, 141),Color.FromArgb(255, 255, 255, 204),Color.FromArgb(255, 253, 232, 141),Color.FromArgb(255, 255, 255, 204)}, new Color[] { Color.FromArgb(255, 0, 176, 240), Color.FromArgb(255, 253, 241, 0), Color.FromArgb(255, 0, 204, 255),Color.FromArgb(255, 253, 241, 0),Color.FromArgb(255, 204, 255, 255),Color.FromArgb(255, 255, 255, 204),Color.FromArgb(255, 204, 255, 255),Color.FromArgb(255, 255, 255, 204)}, new Color[] { Color.FromArgb(255, 51, 204, 51), Color.FromArgb(255, 253, 241, 0), Color.FromArgb(255, 50, 204, 50),Color.FromArgb(255, 253, 241, 0),Color.FromArgb(255, 204, 255, 153),Color.FromArgb(255, 255, 255, 204),Color.FromArgb(255, 204, 255, 153),Color.FromArgb(255, 255, 255, 204)}, new Color[] { Color.FromArgb(255, 192, 0, 0), Color.FromArgb(255, 120, 147, 60), Color.FromArgb(255, 228, 108, 10),Color.FromArgb(255, 55, 96, 146),Color.FromArgb(255, 242, 220, 220),Color.FromArgb(255, 215, 228, 190),Color.FromArgb(255, 252, 213, 181),Color.FromArgb(255, 142, 180, 227)} }; public Color[] getSaleCategoryButtonColor() { return saleCategoryButtonColor; } public Color[] getSaleCategoryButtonBorderColor() { return saleCategoryButtonBorderColor; } public DateTime sumDayTimeStart(string storeEndTime) { DateTime sumDayTime = DateTime.Now; if (String.Compare("00:00", storeEndTime) == 0) { sumDayTime = new DateTime(int.Parse(DateTime.Now.ToString("yyyy")), int.Parse(DateTime.Now.ToString("MM")), int.Parse(DateTime.Now.ToString("dd")), 00, 00, 00); } else { if(int.Parse(DateTime.Now.ToString("HH")) < int.Parse(storeEndTime.Split(':')[0])) { sumDayTime = new DateTime(int.Parse(DateTime.Now.AddDays(-1).ToString("yyyy")), int.Parse(DateTime.Now.AddDays(-1).ToString("MM")), int.Parse(DateTime.Now.AddDays(-1).ToString("dd")), int.Parse(storeEndTime.Split(':')[0]), int.Parse(storeEndTime.Split(':')[1]), 00); } else { sumDayTime = new DateTime(int.Parse(DateTime.Now.ToString("yyyy")), int.Parse(DateTime.Now.ToString("MM")), int.Parse(DateTime.Now.ToString("dd")), int.Parse(storeEndTime.Split(':')[0]), int.Parse(storeEndTime.Split(':')[1]), 00); } } return sumDayTime; } public DateTime sumDayTimeEnd(string storeEndTime) { DateTime sumDayTime = DateTime.Now; sumDayTime = new DateTime(int.Parse(DateTime.Now.ToString("yyyy")), int.Parse(DateTime.Now.ToString("MM")), int.Parse(DateTime.Now.ToString("dd")), int.Parse(storeEndTime.Split(':')[0]), int.Parse(storeEndTime.Split(':')[1]), 00); if(storeEndTime.Split(':')[0] == "00") { sumDayTime = sumDayTime.AddDays(1).AddSeconds(-1); } else { if (int.Parse(DateTime.Now.ToString("HH")) < int.Parse(storeEndTime.Split(':')[0])) { sumDayTime = sumDayTime.AddSeconds(-1); } else { sumDayTime = sumDayTime.AddDays(1).AddSeconds(-1); } } return sumDayTime; } public DateTime currentDateTimeFromTime(string time) { DateTime sumDayTime = DateTime.Now; sumDayTime = new DateTime(int.Parse(DateTime.Now.ToString("yyyy")), int.Parse(DateTime.Now.ToString("MM")), int.Parse(DateTime.Now.ToString("dd")), int.Parse(time.Split(':')[0]), int.Parse(time.Split(':')[1]), 00); //sumDayTime = sumDayTime.AddSeconds(-1); return sumDayTime; } public string sumDate(string storeEndTime) { DateTime now = DateTime.Now; string sumDate = now.ToString("yyyy-MM-dd"); if (String.Compare("00:00", storeEndTime) <= 0 && String.Compare("06:00", storeEndTime) >= 0) { if (int.Parse(DateTime.Now.ToString("HH")) < int.Parse(storeEndTime.Split(':')[0])) { sumDate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); } else { sumDate = DateTime.Now.ToString("yyyy-MM-dd"); } } else { if (int.Parse(DateTime.Now.ToString("HH")) < int.Parse(storeEndTime.Split(':')[0])) { sumDate = DateTime.Now.ToString("yyyy-MM-dd"); } else { sumDate = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); } } return sumDate; } public DateTime openDateTime(string openTime, string storeEndTime) { DateTime openDateTime = DateTime.Now; if (int.Parse(openTime.Split(':')[0]) >= int.Parse(storeEndTime.Split(':')[0])) { openDateTime = new DateTime(sumDayTimeStart(storeEndTime).Year, sumDayTimeStart(storeEndTime).Month, sumDayTimeStart(storeEndTime).Day, int.Parse(openTime.Split(':')[0]), int.Parse(openTime.Split(':')[1]), 00); } else { openDateTime = new DateTime(sumDayTimeEnd(storeEndTime).Year, sumDayTimeEnd(storeEndTime).Month, sumDayTimeEnd(storeEndTime).Day, int.Parse(openTime.Split(':')[0]), int.Parse(openTime.Split(':')[1]), 00); } return openDateTime; } } }
using System; namespace Shango.Commands { using System.IO; using System.Net; using System.Text; using ConsoleProcessRedirection; using Shango.CommandProcessor; /// <summary> /// Summary description for Page. /// </summary> public class ShowpageCommand : MultiInstanceCommand { public ShowpageCommand( ICommandProcessor ParentCommandProcessor, ITerminal Terminal ) : base ( ParentCommandProcessor, Terminal ) { } public override int PerformCommand( ICommandArgument[] Arguments, out ICommandResult CommandResult ) { CommandResult = null; if ( Arguments.Length < 2 ) { throw new CommandException(); } Stream sourceStream = null; if ( Arguments[1].GetArgument() is string ) { sourceStream = (Stream) new FileStream( (string) Arguments[1].GetArgument(), FileMode.Open, FileAccess.Read ); } else { sourceStream = (Stream) Arguments[1].GetArgument(); } string resultString = GetHtml( sourceStream ); _Terminal.WriteTo( new StringBuilder( resultString ), ConsoleProcessRedirection.OutputType.StandardOutput ); TextCommandResult result = new TextCommandResult( new StringBuilder( resultString ) ); CommandResult = result; return 0; } string GetHtml( Stream sourceStream ) { StringBuilder resultBuilder = new StringBuilder( 49152 ); byte[] inBuffer = new byte[8192]; int currentResultLength = 0; _Terminal.WriteTo( new StringBuilder( "Creating html\n" ), OutputType.StandardOutput ); for ( ;; ) { int bytesRead = sourceStream.Read( inBuffer, 0, inBuffer.Length); if ( 0 == bytesRead ) { break; } //resultBuilder.Insert( currentResultLength, inBuffer, 0, bytesRead ); //currentResultLength += bytesRead; for ( int currentChar = 0; currentChar < bytesRead; currentChar++ ) { resultBuilder.Insert( currentResultLength++, (char) inBuffer[ currentChar ] ); } } _Terminal.WriteTo( new StringBuilder( "Finished html\n" ), OutputType.StandardOutput ); return resultBuilder.ToString(); } } }
using OfficeOpenXml; using System; using System.IO; using System.Linq; using System.Threading.Tasks; namespace CleanUpCSVFiles { public delegate void MessageChangedHandler(string value); public delegate void ErrorOcurHandler(string message); public delegate void WorkFinishedHandler(); public delegate void WorkStartedHandler(); public class CleanUpLogic { public event MessageChangedHandler MessageChanged; public event WorkFinishedHandler WorkFinished; public event WorkStartedHandler WorkStarted; public event ErrorOcurHandler ErrorOcured; public FileInfo SettingsFile { get; private set; } public DirectoryInfo HoldingFiles { get; private set; } public string InfoMessage { get; private set; } private void OnWorkStarted() { (WorkStarted as WorkStartedHandler)?.Invoke(); } private void OnErrorOcured(string message) { var del = ErrorOcured as ErrorOcurHandler; if (del != null) { InfoMessage = message; del(message); } } private void OnWorkFinished() { (WorkFinished as WorkFinishedHandler)?.Invoke(); } public void RunProcess() { if (SettingsFile == null) { if (string.IsNullOrEmpty(Properties.Settings.Default.SettingsFile)) { OnErrorOcured("You cannot start without choosen settings file!"); return; } InitSettingsFilePath(Properties.Settings.Default.SettingsFile); } if (HoldingFiles == null) { if (string.IsNullOrEmpty(Properties.Settings.Default.HoldingFiles)) { OnErrorOcured("You cannot start without choosen holdings file!"); return; } InitHoldingFilesPath(Properties.Settings.Default.HoldingFiles); } Task.Factory.StartNew(new Action(StartProcessing)); } private void OnMessageChanged(string value) { var del = MessageChanged as MessageChangedHandler; if (del != null) { InfoMessage = value; del(value); } } private void StartProcessing() { OnWorkStarted(); OnMessageChanged("Start processing..."); try { FileInfo[] Files = HoldingFiles.GetFiles("*.csv"); using (var pck = new ExcelPackage(SettingsFile)) { var ws = pck.Workbook.Worksheets[1]; for (int i = 0; i < ws.Dimension.Rows; i++) { var cellValue = ws.Cells[$"B{i + 2}"].GetValue<int>(); var fileName = ws.Cells[$"A{i + 2}"].Text; FileInfo file = Files.FirstOrDefault(x => x.Name.Contains(fileName+"_") && !string.IsNullOrEmpty(fileName)); if (file != null) { var remainData = File.ReadAllLines(file.FullName).Skip(cellValue - 1); File.WriteAllLines(file.FullName, remainData); } OnMessageChanged($"Processed: {i + 1}/{ws.Dimension.Rows + 1}"); } } } catch (Exception ex) { OnMessageChanged(ex.Message); OnErrorOcured(ex.Message); } OnMessageChanged("Finished"); OnWorkFinished(); } public bool CheckIsAppCanStartProcess() { return Directory.Exists(HoldingFiles?.FullName) && File.Exists(SettingsFile?.FullName); } public void InitHoldingFilesPath(string str) { if (string.IsNullOrWhiteSpace(str)) str = FilesHelper.SelectFolder(); if (string.IsNullOrWhiteSpace(str)) return; HoldingFiles = new DirectoryInfo(str); Properties.Settings.Default.HoldingFiles = str; Properties.Settings.Default.Save(); } public void InitSettingsFilePath(string str) { if (string.IsNullOrWhiteSpace(str)) str = FilesHelper.SelectFile(); if (string.IsNullOrWhiteSpace(str)) return; SettingsFile = new FileInfo(str); Properties.Settings.Default.SettingsFile = str; Properties.Settings.Default.Save(); } } }
using System; using System.Collections.Generic; [Serializable] public class CapturaDados { public string emailJogador; public string sexo; public string faixaEtaria; public string dataHora; public int fasesDesbloqueadas = 0; public float tempoTotalJogado = 0; public List<CapturaFase> capturaFases = new List<CapturaFase>(); public void inicializarFase(int numFase) { CapturaFase capturaFase = new CapturaFase(); capturaFase.fase = numFase; capturaFase.status = "bloqueado"; capturaFase.quantVezesTentadas = 0; capturaFases.Add(capturaFase); } public void incrementaTentativas(int fase) { for(int i = 0; i < capturaFases.Count; i++) { if(capturaFases[i].fase == fase) { capturaFases[i].quantVezesTentadas += 1; break; } } } public void adicionarNovaSessao(int faseAtual, List<String> plataformasPuladas, string resultado, float tempoemFase) { // Busca a fase para adicionar a sessao for (int i = 0; i < capturaFases.Count; i++) { if (capturaFases[i].fase == faseAtual) { CapturaSecoes capturaSecoes = new CapturaSecoes(); capturaSecoes.resultadoTrajetoria = resultado; capturaSecoes.trajetoria = plataformasPuladas; capturaSecoes.tempoEmFase = tempoemFase; capturaFases[i].capturaSecoes.Add(capturaSecoes); } } } public void adicionarNovaSessao(int faseAtual, List<String> plataformasPuladas, string resultado, float tempoemFase, String motivoDerrota) { // Busca a fase para adicionar a sessao for(int i = 0; i < capturaFases.Count; i++) { if(capturaFases[i].fase == faseAtual) { CapturaSecoes capturaSecoes = new CapturaSecoes(); capturaSecoes.resultadoTrajetoria = resultado; capturaSecoes.trajetoria = plataformasPuladas; capturaSecoes.tempoEmFase = tempoemFase; capturaSecoes.motivoDerrota = motivoDerrota; capturaFases[i].capturaSecoes.Add(capturaSecoes); } } } }
using PDV.CONTROLER.Funcoes; using PDV.DAO.Entidades; using System; using System.Collections.Generic; using System.Windows.Forms; using System.Linq; using PDV.DAO.Enum; using PDV.DAO.DB.Utils; using PDV.VIEW.App_Context; using MetroFramework.Forms; using MetroFramework; using System.Net; using PDV.DAO.Entidades.Cep; using System.Web.Script.Serialization; using PDV.UTIL; using DevExpress.XtraGrid.Views.Grid; using System.Drawing; using DevExpress.XtraCharts; using System.Data; using DevExpress.XtraPrinting; namespace PDV.VIEW.Forms.Cadastro { public partial class GER_FluxoFinanceiro : DevExpress.XtraEditors.XtraForm { private string tabSelecionado = "1"; public GER_FluxoFinanceiro() { InitializeComponent(); int mesindex = DateTime.Now.Month - 1; anoTextEdit.Text = DateTime.Now.Year.ToString(); CarregarCaixa(DateTime.Now.Month.ToString(), anoTextEdit.Text); chartRecebimentos(); charPagamentos(); metroTabControl1.SelectedIndex = mesindex; } public void CarregarCaixa(string ANO, string MES) { //CarregarGrafico(); gridControl1.DataSource = GetFluxoCaixa(); gridView1.OptionsBehavior.Editable = false; gridView1.OptionsSelection.EnableAppearanceFocusedCell = false; gridView1.FocusRectStyle = DevExpress.XtraGrid.Views.Grid.DrawFocusRectStyle.RowFocus; gridView1.BestFitColumns(); gridControl1.ForceInitialize(); gridView1.OptionsView.ColumnAutoWidth = false; gridView1.OptionsView.ShowAutoFilterRow = true; gridView1.OptionsView.ShowFooter = true; gridView1.Columns[0].Caption = "ID"; gridView1.Columns[1].Caption = "DATA DE EMISSÃO"; gridView1.Columns[2].Caption = "VENCIMENTO"; gridView1.Columns[3].Caption = "PESSOA"; gridView1.Columns[4].Caption = "ORIGEM"; gridView1.Columns[5].Caption = "DESCRIÇÂO"; gridView1.Columns[6].Caption = "SALDO"; gridView1.Columns[7].Caption = "PAGO"; gridView1.Columns[8].Caption = "STATUS"; gridView1.Columns[9].Caption = "TIPO"; gridView1.Columns[6].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; gridView1.Columns[6].DisplayFormat.FormatString = "n2"; gridView1.Columns[7].DisplayFormat.FormatType = DevExpress.Utils.FormatType.Numeric; gridView1.Columns[7].DisplayFormat.FormatString = "n2"; //gridView1.Columns[9].Caption = "SITUAÇÃO"; //gridView1.Columns[8].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Sum; //gridView1.Columns[2].SummaryItem.SummaryType = DevExpress.Data.SummaryItemType.Count; //gridView1.Columns[8].SummaryItem.DisplayFormat = "Total R$ : {0:n2}"; //gridView1.Columns[2].SummaryItem.DisplayFormat = "Registros : {0}"; } private void FCA_Transportadora_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Escape: this.Close(); break; } } private void metroTabControl1_SelectedIndexChanged(object sender, EventArgs e) { tabSelecionado = Convert.ToString(metroTabControl1.SelectedIndex +1); CarregarCaixa(anoTextEdit.Text, tabSelecionado.ToString()); CarregarGrafico(); CarregarTotais(); } private void simpleButton1_Click(object sender, EventArgs e) { tabSelecionado = (metroTabControl1.SelectedIndex + 1).ToString(); CarregarCaixa(anoTextEdit.Text, tabSelecionado.ToString()); CarregarGrafico(); CarregarTotais(); chartRecebimentos(); charPagamentos(); } public void chartRecebimentos() { //ChartControl recebimentosChartControl.Controls.Clear(); recebimentosChartControl.Series.Clear(); recebimentosChartControl.Titles.Clear(); recebimentosChartControl.AnimationStartMode = DevExpress.XtraCharts.ChartAnimationMode.OnLoad; recebimentosChartControl.BorderOptions.Visibility = DevExpress.Utils.DefaultBoolean.False; recebimentosChartControl.AutoLayout = true; recebimentosChartControl.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True; ChartTitle chartTitle = new ChartTitle(); chartTitle.Text = "Recebimentos"; chartTitle.Font = new System.Drawing.Font("Tahoma", 8F); chartTitle.Alignment = StringAlignment.Center; recebimentosChartControl.Titles.Add(chartTitle); //Series Series series = new Series("Legenda", ViewType.Doughnut); series.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True; series.Label.TextPattern = "{A} :{V:c2}"; series.LegendTextPattern = "{A} : {V:c2}"; //Obtem dados do banco de dados series.DataSource = FuncoesDuplicataNFe.GetDuplicatasTudo(); series.ArgumentDataMember = "descricao"; series.ValueDataMembers.AddRange(new string[] { "valor" }); series.ValueScaleType = ScaleType.Numerical; series.ToolTipSeriesPattern = "{c2}"; recebimentosChartControl.Series.Add(series); } public void charPagamentos() { //ChartControl pagamentosChartControl.Controls.Clear(); pagamentosChartControl.Series.Clear(); pagamentosChartControl.Titles.Clear(); pagamentosChartControl.AnimationStartMode = DevExpress.XtraCharts.ChartAnimationMode.OnLoad; pagamentosChartControl.BorderOptions.Visibility = DevExpress.Utils.DefaultBoolean.False; pagamentosChartControl.AutoLayout = true; pagamentosChartControl.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True; ChartTitle chartTitle = new ChartTitle(); chartTitle.Text = "Recebimentos"; chartTitle.Font = new System.Drawing.Font("Tahoma", 8F); chartTitle.Alignment = StringAlignment.Center; pagamentosChartControl.Titles.Add(chartTitle); //Series Series series = new Series("Legenda", ViewType.Doughnut); series.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True; series.Label.TextPattern = "{A} :{V:c2}"; series.LegendTextPattern = "{A} : {V:c2}"; //Obtem dados do banco de dados series.DataSource = FuncoesDuplicataNFe.GetDuplicatasCompraTudo(); series.ArgumentDataMember = "descricao"; series.ValueDataMembers.AddRange(new string[] { "valor" }); series.ValueScaleType = ScaleType.Numerical; series.ToolTipSeriesPattern = "{c2}"; pagamentosChartControl.Series.Add(series); } private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e) { GridView view = sender as GridView; //if (e.Column.FieldName == "tipo") //{ //e.Appearance.Font = new Font("Tahoma", 9, FontStyle.Bold); var value = view.GetRowCellValue(e.RowHandle, "tipo"); if (value != null) { if (value.ToString().Contains("C")) { e.Appearance.ForeColor = Color.Green; } else { e.Appearance.ForeColor = Color.Red; } } //} } private void GER_FluxoDeCaixa_Load(object sender, EventArgs e) { CarregarGrafico(); CarregarTotais(); } private void CarregarGrafico() { //ChartControl chartControl1.Controls.Clear(); chartControl1.Series.Clear(); chartControl1.Titles.Clear(); chartControl1.AnimationStartMode = DevExpress.XtraCharts.ChartAnimationMode.OnLoad; chartControl1.BorderOptions.Visibility = DevExpress.Utils.DefaultBoolean.False; chartControl1.AutoLayout = true; chartControl1.Legend.Visibility = DevExpress.Utils.DefaultBoolean.True; chartControl1.DataSource = null; chartControl1.Series.Clear(); chartControl1.Titles.Clear(); ChartTitle chartTitle = new ChartTitle(); chartTitle.Text = "Fluxo Caixa Entrada X SAIDA"; chartTitle.Font = new System.Drawing.Font("Tahoma", 8F); chartTitle.Alignment = StringAlignment.Center; chartControl1.Titles.Add(chartTitle); //Series Series series = new Series("Legenda", ViewType.Doughnut); series.LabelsVisibility = DevExpress.Utils.DefaultBoolean.True; series.Label.TextPattern = "{A} :{V:c2}"; series.LegendTextPattern = "{A} : {V:c2}"; //Obtem dados do banco de dados series.DataSource = null; series.DataSource = GetFluxoCaixaAgrupado(); series.ArgumentDataMember = "origem"; series.ValueDataMembers.AddRange(new string[] { "pago" }); series.ValueScaleType = ScaleType.Numerical; series.ToolTipSeriesPattern = "{c2}"; chartControl1.Series.Add(series); } private bool[] SituacoesSelecionadas() { return new bool[] { checkEditCancelado.Checked, checkEditAberto.Checked, checkEditParcial.Checked, checkEditBaixado.Checked }; } private void CarregarTotais() { DataTable dataTable = GetFluxoCaixa(); decimal totalPagar = 0.00M; decimal totalPago = 0.00M; decimal totalReceber = 0.00M; decimal totalRecebido = 0.00M; for(int i = 0; i < dataTable.Rows.Count; i++) { if (dataTable.Rows[i]["Tipo"].ToString() == "D") { totalPagar += Convert.ToDecimal(dataTable.Rows[i]["Valor"]); totalPago += Convert.ToDecimal(dataTable.Rows[i]["Pago"]); } else { totalReceber += Convert.ToDecimal(dataTable.Rows[i]["Valor"]); totalRecebido += Convert.ToDecimal(dataTable.Rows[i]["Pago"]); } } //ovTXT_TotalAPagar.Text = "Total a Pagar " + Environment.NewLine +"R$ " + totalPagar.ToString("n2"); //ovTXT_TotalAReceber.Text = "Total a Receber" + Environment.NewLine + "R$ " + totalReceber.ToString("n2"); //ovTXT_TotalPago.Text = "Total Pago" + Environment.NewLine + "R$ " + totalPago.ToString("n2"); //ovTXT_TotalRecebido.Text = "Total Recebido" + Environment.NewLine + "R$ " + totalRecebido.ToString("n2"); ovTXT_TotalAPagar.Text = "Total a Pagar " + " R$ " + totalPagar.ToString("n2"); ovTXT_TotalAReceber.Text = "Total a Receber" + " R$ " + totalReceber.ToString("n2"); ovTXT_TotalPago.Text = "Total Pago" + " R$ " + totalPago.ToString("n2"); ovTXT_TotalRecebido.Text = "Total Recebido"+ " R$ " + totalRecebido.ToString("n2"); } private DataTable GetFluxoCaixa() { return FuncoesCaixa.GetFluxoCaixa(anoTextEdit.Text, tabSelecionado, GetOrganizarPor(), SituacoesSelecionadas()); } private DataTable GetFluxoCaixaAgrupado() { return FuncoesCaixa.GetFluxoCaixaAgrupado(anoTextEdit.Text, tabSelecionado, GetOrganizarPor(), SituacoesSelecionadas()); } private string GetOrganizarPor() { if (spinEditOrganizarPor.SelectedIndex == 0) return "emissao"; else return "vencimento"; } private void simpleButton2_Click(object sender, EventArgs e) { gridControl1.ShowPrintPreview(); } private void gridView1_PrintInitialize(object sender, DevExpress.XtraGrid.Views.Base.PrintInitializeEventArgs e) { PrintingSystemBase pb = e.PrintingSystem as PrintingSystemBase; pb.PageSettings.Landscape = true; } } }
using System; using Photon.Pun; using UnityEngine; public class Character : MonoBehaviour { public Material[] characterMaterials; private void Start() { PhotonView view = this.GetComponent<PhotonView>(); MeshRenderer renderer = this.GetComponent<MeshRenderer>(); int characterType = (int) view.Owner.CustomProperties["character"]; switch (characterType) { case (int) Types.CharacterEnum.Iron: renderer.material = this.getMaterialByName(Types.CharacterEnum.Iron.ToString()); break; case (int) Types.CharacterEnum.Knuckles: renderer.material = this.getMaterialByName(Types.CharacterEnum.Knuckles.ToString()); break; } } private Material getMaterialByName(string name) { foreach (Material material in this.characterMaterials) { if (material.name == name) { return material; } } return this.characterMaterials[0]; } }
using System; using System.Collections.Generic; using System.IO; 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 JabberPoint; namespace JabberPoint.View { /// <summary> /// Interaction logic for JabberPointView.xaml /// </summary> public partial class JabberPointView : Window { public JabberPointView() { InitializeComponent(); foreach (FileInfo file in new DirectoryInfo("./").EnumerateFiles().Where(x => x.Name.StartsWith("theme"))) { var menuItem = new MenuItem() { Header = file.Name, Name= file.Name.Split('.')[0] }; menuItem.SetBinding(MenuItem.CommandProperty, new Binding("LoadTheme")); menuItem.CommandParameter = file.Name; themes.Items.Add(menuItem); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; namespace CinemalyticsCSharpSDK.Util { internal class UrlUtil { public static String MakeGetCall(String url) { var request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 10000; using (var response = request.GetResponse()) { Stream responseStream = ((HttpWebResponse)response).GetResponseStream(); if (responseStream == null) { return "{}"; } StreamReader streamReader = new StreamReader(responseStream); String responseJson = streamReader.ReadToEnd(); streamReader.Close(); return responseJson; } } public static String MakeGetCall(String url, String postData) { var request = (HttpWebRequest)WebRequest.Create(url); request.Timeout = 10000; var data = Encoding.ASCII.GetBytes(postData); request.Method = "POST"; request.ContentType = "application/json"; request.ContentLength = data.Length; using (var stream = request.GetRequestStream()) { stream.Write(data, 0, data.Length); } using (var response = request.GetResponse()) { Stream responseStream = ((HttpWebResponse)response).GetResponseStream(); if (responseStream == null) { return "{}"; } StreamReader streamReader = new StreamReader(responseStream); String responseJson = streamReader.ReadToEnd(); streamReader.Close(); return responseJson; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EjercicioInterfaces { public class Comercial:Avion,IARBA { private int _capacidadPasajeros; public Comercial(double precio,double velocidad,int pasajeros) : base(precio, velocidad) { this._capacidadPasajeros = pasajeros; } public double CalcularImpuesto() { return (this._precio * 25) / 100; } } }
namespace catalog.merger.api.Features.CatalogMerger.Models { public class CatalogItem { public string SKU { get; set; } public string Description { get; set; } } }
using System.Collections.Generic; using KRF.Core.Entities.AccessControl; namespace KRF.Core.FunctionalContracts { public interface IRoleManagement { /// <summary> /// Create a new role based on user defined role name. /// </summary> /// <param name="roleName">Name of the role.</param> /// <returns>True - if creation successful; False - if creation step failed</returns> bool CreateRole(string roleName); /// <summary> /// Edit a role based on user's updated to role object /// </summary> /// <param name="role">Updated role object</param> /// <returns>Returns the updated role object post successful updation</returns> Role EditRole(Role role); /// <summary> /// Deletes role based on role id. /// </summary> /// <param name="roleId">Role's unique identifier</param> /// <returns>True - If deletion successful; False - If failure.</returns> bool DeleteRole(int roleId); /// <summary> /// List All registered roles within the system /// </summary> /// <returns>Roles list</returns> IList<Role> ListAllRoles(); /// <summary> /// List all registered permission within the system /// </summary> /// <returns>Permission list</returns> IList<Permissions> ListAllPermissions(); /// <summary> /// Assign permission to a specific role Id /// </summary> /// <param name="roleId">Role's unique identifier</param> /// <param name="permission">permission details</param> /// <returns>True - If successful; False - If failed</returns> bool AssignPermissionToRole(int roleId, Permissions permission); /// <summary> /// Search role based on user mentioned role name. /// </summary> /// <param name="roleName">Name of the role.</param> /// <returns>Role list</returns> IList<Role> SearchRole(string roleName); } }
using System; using System.Collections.Generic; namespace SLua { [LuaBinder(1)] public class BindUnityUI { public static Action<IntPtr>[] GetBindList() { Action<IntPtr>[] list= { Lua_UnityEngine_UI_AnimationTriggers.reg, Lua_UnityEngine_EventSystems_UIBehaviour.reg, Lua_UnityEngine_UI_Selectable.reg, Lua_UnityEngine_UI_Button.reg, Lua_UnityEngine_UI_CanvasUpdate.reg, Lua_UnityEngine_UI_ICanvasElement.reg, Lua_UnityEngine_UI_CanvasUpdateRegistry.reg, Lua_UnityEngine_UI_ColorBlock.reg, Lua_UnityEngine_UI_ClipperRegistry.reg, Lua_UnityEngine_UI_Clipping.reg, Lua_UnityEngine_UI_IClipper.reg, Lua_UnityEngine_UI_IClippable.reg, Lua_UnityEngine_UI_DefaultControls.reg, Lua_UnityEngine_UI_Dropdown.reg, Lua_UnityEngine_UI_FontData.reg, Lua_UnityEngine_UI_FontUpdateTracker.reg, Lua_UnityEngine_UI_Graphic.reg, Lua_UnityEngine_EventSystems_BaseRaycaster.reg, Lua_UnityEngine_UI_GraphicRaycaster.reg, Lua_UnityEngine_UI_GraphicRegistry.reg, Lua_UnityEngine_UI_MaskableGraphic.reg, Lua_UnityEngine_UI_Image.reg, Lua_UnityEngine_UI_IMaskable.reg, Lua_UnityEngine_UI_InputField.reg, Lua_UnityEngine_UI_AspectRatioFitter.reg, Lua_UnityEngine_UI_CanvasScaler.reg, Lua_UnityEngine_UI_ContentSizeFitter.reg, Lua_UnityEngine_UI_LayoutGroup.reg, Lua_UnityEngine_UI_GridLayoutGroup.reg, Lua_UnityEngine_UI_HorizontalOrVerticalLayoutGroup.reg, Lua_UnityEngine_UI_HorizontalLayoutGroup.reg, Lua_UnityEngine_UI_ILayoutElement.reg, Lua_UnityEngine_UI_ILayoutController.reg, Lua_UnityEngine_UI_ILayoutGroup.reg, Lua_UnityEngine_UI_ILayoutSelfController.reg, Lua_UnityEngine_UI_ILayoutIgnorer.reg, Lua_UnityEngine_UI_LayoutElement.reg, Lua_UnityEngine_UI_LayoutRebuilder.reg, Lua_UnityEngine_UI_LayoutUtility.reg, Lua_UnityEngine_UI_VerticalLayoutGroup.reg, Lua_UnityEngine_UI_Mask.reg, Lua_UnityEngine_UI_MaskUtilities.reg, Lua_UnityEngine_UI_IMaterialModifier.reg, Lua_UnityEngine_UI_Navigation.reg, Lua_UnityEngine_UI_RawImage.reg, Lua_UnityEngine_UI_RectMask2D.reg, Lua_UnityEngine_UI_Scrollbar.reg, Lua_UnityEngine_UI_ScrollRect.reg, Lua_UnityEngine_UI_Slider.reg, Lua_UnityEngine_UI_SpriteState.reg, Lua_UnityEngine_UI_StencilMaterial.reg, Lua_UnityEngine_UI_Text.reg, Lua_UnityEngine_UI_Toggle.reg, Lua_UnityEngine_UI_ToggleGroup.reg, Lua_UnityEngine_UI_VertexHelper.reg, Lua_UnityEngine_UI_BaseMeshEffect.reg, Lua_UnityEngine_UI_IMeshModifier.reg, Lua_UnityEngine_UI_Shadow.reg, Lua_UnityEngine_UI_Outline.reg, Lua_UnityEngine_UI_PositionAsUV1.reg, Lua_UnityEngine_EventSystems_AbstractEventData.reg, Lua_UnityEngine_EventSystems_BaseEventData.reg, Lua_UnityEngine_EventSystems_AxisEventData.reg, Lua_UnityEngine_EventSystems_PointerEventData.reg, Lua_UnityEngine_EventSystems_EventHandle.reg, Lua_UnityEngine_EventSystems_IEventSystemHandler.reg, Lua_UnityEngine_EventSystems_IPointerEnterHandler.reg, Lua_UnityEngine_EventSystems_IPointerExitHandler.reg, Lua_UnityEngine_EventSystems_IPointerDownHandler.reg, Lua_UnityEngine_EventSystems_IPointerUpHandler.reg, Lua_UnityEngine_EventSystems_IPointerClickHandler.reg, Lua_UnityEngine_EventSystems_IBeginDragHandler.reg, Lua_UnityEngine_EventSystems_IInitializePotentialDragHandler.reg, Lua_UnityEngine_EventSystems_IDragHandler.reg, Lua_UnityEngine_EventSystems_IEndDragHandler.reg, Lua_UnityEngine_EventSystems_IDropHandler.reg, Lua_UnityEngine_EventSystems_IScrollHandler.reg, Lua_UnityEngine_EventSystems_IUpdateSelectedHandler.reg, Lua_UnityEngine_EventSystems_ISelectHandler.reg, Lua_UnityEngine_EventSystems_IDeselectHandler.reg, Lua_UnityEngine_EventSystems_IMoveHandler.reg, Lua_UnityEngine_EventSystems_ISubmitHandler.reg, Lua_UnityEngine_EventSystems_ICancelHandler.reg, Lua_UnityEngine_EventSystems_EventSystem.reg, Lua_UnityEngine_EventSystems_EventTrigger.reg, Lua_UnityEngine_EventSystems_EventTriggerType.reg, Lua_UnityEngine_EventSystems_ExecuteEvents.reg, Lua_UnityEngine_EventSystems_BaseInput.reg, Lua_UnityEngine_EventSystems_BaseInputModule.reg, Lua_UnityEngine_EventSystems_PointerInputModule.reg, Lua_UnityEngine_EventSystems_StandaloneInputModule.reg, Lua_UnityEngine_EventSystems_MoveDirection.reg, Lua_UnityEngine_EventSystems_PhysicsRaycaster.reg, Lua_UnityEngine_EventSystems_Physics2DRaycaster.reg, Lua_UnityEngine_EventSystems_RaycastResult.reg, Lua_UnityEngine_UI_Button_ButtonClickedEvent.reg, Lua_UnityEngine_UI_DefaultControls_IFactoryControls.reg, Lua_UnityEngine_UI_DefaultControls_Resources.reg, Lua_UnityEngine_UI_Dropdown_OptionData.reg, Lua_UnityEngine_UI_Dropdown_OptionDataList.reg, Lua_UnityEngine_UI_Dropdown_DropdownEvent.reg, Lua_UnityEngine_UI_GraphicRaycaster_BlockingObjects.reg, Lua_UnityEngine_UI_Image_Type.reg, Lua_UnityEngine_UI_Image_FillMethod.reg, Lua_UnityEngine_UI_Image_OriginHorizontal.reg, Lua_UnityEngine_UI_Image_OriginVertical.reg, Lua_UnityEngine_UI_Image_Origin90.reg, Lua_UnityEngine_UI_Image_Origin180.reg, Lua_UnityEngine_UI_Image_Origin360.reg, Lua_UnityEngine_UI_InputField_ContentType.reg, Lua_UnityEngine_UI_InputField_InputType.reg, Lua_UnityEngine_UI_InputField_CharacterValidation.reg, Lua_UnityEngine_UI_InputField_LineType.reg, Lua_UnityEngine_UI_InputField_SubmitEvent.reg, Lua_UnityEngine_UI_InputField_OnChangeEvent.reg, Lua_UnityEngine_UI_AspectRatioFitter_AspectMode.reg, Lua_UnityEngine_UI_CanvasScaler_ScaleMode.reg, Lua_UnityEngine_UI_CanvasScaler_ScreenMatchMode.reg, Lua_UnityEngine_UI_CanvasScaler_Unit.reg, Lua_UnityEngine_UI_ContentSizeFitter_FitMode.reg, Lua_UnityEngine_UI_GridLayoutGroup_Corner.reg, Lua_UnityEngine_UI_GridLayoutGroup_Axis.reg, Lua_UnityEngine_UI_GridLayoutGroup_Constraint.reg, Lua_UnityEngine_UI_MaskableGraphic_CullStateChangedEvent.reg, Lua_UnityEngine_UI_Navigation_Mode.reg, Lua_UnityEngine_UI_Scrollbar_Direction.reg, Lua_UnityEngine_UI_Scrollbar_ScrollEvent.reg, Lua_UnityEngine_UI_ScrollRect_MovementType.reg, Lua_UnityEngine_UI_ScrollRect_ScrollbarVisibility.reg, Lua_UnityEngine_UI_ScrollRect_ScrollRectEvent.reg, Lua_UnityEngine_UI_Selectable_Transition.reg, Lua_UnityEngine_UI_Slider_Direction.reg, Lua_UnityEngine_UI_Slider_SliderEvent.reg, Lua_UnityEngine_UI_Toggle_ToggleTransition.reg, Lua_UnityEngine_UI_Toggle_ToggleEvent.reg, Lua_UnityEngine_EventSystems_PointerEventData_InputButton.reg, Lua_UnityEngine_EventSystems_PointerEventData_FramePressState.reg, Lua_UnityEngine_EventSystems_EventTrigger_TriggerEvent.reg, Lua_UnityEngine_EventSystems_EventTrigger_Entry.reg, Lua_UnityEngine_EventSystems_PointerInputModule_MouseButtonEventData.reg, }; return list; } } }
using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Web.Http; using CloneDeploy_App.Controllers.Authorization; using CloneDeploy_Entities; using CloneDeploy_Entities.DTOs; using CloneDeploy_Services; namespace CloneDeploy_App.Controllers { public class ImageClassificationController : ApiController { private readonly ImageClassificationServices _imageClassificationServices; public ImageClassificationController() { _imageClassificationServices = new ImageClassificationServices(); } [CustomAuth(Permission = "GlobalDelete")] public ActionResultDTO Delete(int id) { var result = _imageClassificationServices.DeleteImageClassification(id); if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); return result; } [Authorize] public ImageClassificationEntity Get(int id) { var result = _imageClassificationServices.GetImageClassification(id); if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); return result; } [Authorize] public IEnumerable<ImageClassificationEntity> Get() { return _imageClassificationServices.GetAll(); } [CustomAuth(Permission = "GlobalRead")] public ApiStringResponseDTO GetCount() { return new ApiStringResponseDTO {Value = _imageClassificationServices.TotalCount()}; } [CustomAuth(Permission = "GlobalCreate")] public ActionResultDTO Post(ImageClassificationEntity imageClassification) { return _imageClassificationServices.AddImageClassification(imageClassification); } [CustomAuth(Permission = "GlobalUpdate")] public ActionResultDTO Put(int id, ImageClassificationEntity imageClassification) { imageClassification.Id = id; var result = _imageClassificationServices.UpdateImageClassification(imageClassification); if (result == null) throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound)); return result; } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using StackExchange.Redis; namespace Utils { public class RedisLocker { private readonly IDatabase db; public RedisLocker(IDatabase db) { this.db = db; } public async Task<DistributedLock> GetLockAsync(string lockName, TimeSpan lockTimeout, TimeSpan? requireTimeout = null) { var requireAt = DateTime.Now + (requireTimeout ?? TimeSpan.Zero); while (requireTimeout == null || DateTime.Now < requireAt) { var value = Guid.NewGuid(); var res = await db.StringSetAsync(lockName, value.ToString(), lockTimeout, When.NotExists); if (res == true) return new DistributedLock(value, lockName, DateTime.Now + lockTimeout); await Task.Delay(5); } return null; } public async Task<bool> ReleaseLockAsync(DistributedLock theLock) { var transcation = db.CreateTransaction(); transcation.AddCondition(Condition.StringEqual(theLock.LockName, theLock.Id.ToString())); var resTask = transcation.KeyDeleteAsync(theLock.LockName); var r = await transcation.ExecuteAsync(); return await resTask; } } }
using System.Linq; using System.Web.Mvc; using Dentist.Controllers.Base; using Dentist.Models.Doctor; using Dentist.ViewModels; using Dentist.Models; namespace Dentist.Controllers { public class ProceduresController : PageCrudController<Procedure> { public ProceduresController() : base("Procedures") {} } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace EnergyDataRetriever.Models { public class ProjectData { const double PRICE_PER_SHARE = 1000; static int currentId = 0; public double pricePerShare { get; set; } public int projectId { get; set; } public int projectSize { get; set; } public List<EnergyData> listEnergyData { get; set; } public DateTime startDate { get; set; } public ProjectData() { projectId = currentId++; pricePerShare = PRICE_PER_SHARE; startDate = new DateTime(2017, 10, 1); } } }
//玩家橫條的控制腳本 using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerBarBehavior : MonoBehaviour { //-----------變數宣告------------------------------------------------ private static PlayerBarBehavior _instance; //單例物件 public static PlayerBarBehavior Instance { get { return _instance; } } public float moveSpeed; //移動速度 public float dragAcc; //拖曳加速度 public float dragSpeed; //拖曳加成速度 public List<GameObject> adhereBalls; //附著球列表 private RectTransform rectTransform; private float stretchLength; //延伸長度 private float bufferRange; //緩衝範圍(在更靠近牆時做精準判斷,遠離時則不做判斷,節省資源用) private float wallPos_right; //右牆位置 private float wallPos_left; //左牆位置 private bool rightLimit = false; //是否達右方盡頭 private bool leftLimit = false; //是否達左方盡頭 //-----------內建方法------------------------------------------------ void Awake() { _instance = this; //單例模式 } void Start() { rectTransform = this.GetComponent<RectTransform>(); stretchLength = this.transform.parent.localScale.x * (rectTransform.sizeDelta.x / 2); } //-----------自訂方法------------------------------------------------ //定位 public void Locate(GameObject[] objs) { wallPos_right = objs[0].transform.position.x; wallPos_left = objs[1].transform.position.x; bufferRange = (objs[0].GetComponent<RectTransform>().sizeDelta.x / 2) + (moveSpeed / 10); //switch (name) //{ // case "wallPos_right": // wallPos_right = (float)value; // break; // case "wallPos_left": // wallPos_left = (float)value; // break; // case "bufferRange": // bufferRange = (float)value; // break; // default: // break; //} } //移動 public void Move(string dir) { switch (dir) { case "右": if (!rightLimit) //若達右方盡頭則不再移動 { if (leftLimit) //解除左方盡頭狀態 { leftLimit = false; } if (rectTransform.position.x + stretchLength <= wallPos_right - bufferRange) //在緩衝區外時簡單判定(效能取向) { this.transform.Translate(Vector3.right * Time.deltaTime * moveSpeed); for (int i = 0; i < adhereBalls.Count; i++) //拖曳附著的球移動 { adhereBalls[i].transform.position += Vector3.right * Time.deltaTime * moveSpeed; } } else { float origin = rectTransform.position.x + stretchLength; if (rectTransform.position.x + stretchLength + (Vector3.right * Time.deltaTime * moveSpeed).x >= wallPos_right) //在緩衝區內精確判定(效果取向) { this.transform.position = new Vector3(wallPos_right - stretchLength, this.transform.position.y, this.transform.position.z); for (int i = 0; i < adhereBalls.Count; i++) //拖曳附著的球移動(精確計算) { adhereBalls[i].transform.position += Vector3.right * (wallPos_right - origin); } rightLimit = true; } else { this.transform.Translate(Vector3.right * Time.deltaTime * moveSpeed); for (int i = 0; i < adhereBalls.Count; i++) //拖曳附著的球移動 { adhereBalls[i].transform.position += Vector3.right * Time.deltaTime * moveSpeed; } } } } break; case "左": if (!leftLimit) //若達左方盡頭則不再移動 { if (rightLimit) //解除右方盡頭狀態 { rightLimit = false; } if (rectTransform.position.x - stretchLength >= wallPos_left + bufferRange) //在緩衝區外時簡單判定(效能取向) { this.transform.Translate(-Vector3.right * Time.deltaTime * moveSpeed); for (int i = 0; i < adhereBalls.Count; i++) //拖曳附著的球移動 { adhereBalls[i].transform.position += -Vector3.right * Time.deltaTime * moveSpeed; } } else { float origin = rectTransform.position.x - stretchLength; if (rectTransform.position.x - stretchLength - (Vector3.right * Time.deltaTime * moveSpeed).x <= wallPos_left) //在緩衝區內精確判定(效果取向) { this.transform.position = new Vector3(wallPos_left + stretchLength, this.transform.position.y, this.transform.position.z); for (int i = 0; i < adhereBalls.Count; i++) //拖曳附著的球移動(精確計算) { adhereBalls[i].transform.position += Vector3.right * (wallPos_left - origin); } leftLimit = true; } else { this.transform.Translate(-Vector3.right * Time.deltaTime * moveSpeed); for (int i = 0; i < adhereBalls.Count; i++) //拖曳附著的球移動 { adhereBalls[i].transform.position += -Vector3.right * Time.deltaTime * moveSpeed; } } } } break; } } //速度加成計算 public void AccelerationEffect(float v) { if ((v > 0 && rightLimit) || (v < 0 && leftLimit)) { dragSpeed = 0; } else { dragSpeed = dragAcc * v; } } //附著 public void Adhere(ref GameObject b) { b.GetComponent<BallBehavior>().staying = true; adhereBalls.Add(b); } //擊發(多載1/2) public void Shoot() { adhereBalls[adhereBalls.Count - 1].SendMessage("InitialMove", new Vector2(dragSpeed == 0 ? 0 : (dragSpeed > 0 ? moveSpeed : -moveSpeed), 0)); adhereBalls.RemoveAt(adhereBalls.Count - 1); } //擊發(多載2/2) public void Shoot(Vector2 v2) { adhereBalls[adhereBalls.Count - 1].SendMessage("InitialMove", v2); adhereBalls.RemoveAt(adhereBalls.Count - 1); } //全部擊發 public void ShootAll(Vector2 v2) { for (int i = 0; i < adhereBalls.Count; i++) { adhereBalls[i].SendMessage("InitialMove", v2); } adhereBalls.RemoveRange(0, adhereBalls.Count); } }
using System.Threading.Tasks; using TRM_data_manager_wpf.Library.Models; namespace TRM_data_manager_wpf.Library.Api { public interface IAPIHelper { Task<AuthenticatedUser> Authenticate(string username, string password); Task GetLoggedInUserInfo(string token); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "ConfigData/SoundLibrary")] public class SoundLib : ScriptableObject { [System.Serializable] public struct sSoundEvent { public AudioClip m_clip; [Range(0,1)] public float m_volume; } [Header("----------- ROUND -----------")] [Header("BKG Musics")] public sSoundEvent m_matchBkgMusic; [Header("Player SFX")] public sSoundEvent m_fistAttkSFX; public sSoundEvent m_saberAttkSFX; public sSoundEvent m_pistolAttkSFX; public sSoundEvent m_dashSFX; public sSoundEvent m_deathSFX; [Header("----------- MENU -----------")] [Header("BKG Musics")] public sSoundEvent m_menuBkgMusic; [Header("SFX")] public sSoundEvent m_menuClickSFX; public sSoundEvent m_menuSwapSFX; }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace LojaWeb.Models { public class Carrinho { public int Id { get; set; } public double PrecoFinal { get; set; } public Usuario Usuario { get; set; } public int UsuarioId { get; set; } public IList<ItemCarrinho> itemCarrinhos { get; set; } public bool Estado { get; set; } } }
using AspNetCoreSample.Models.Message; using AspNetCoreSample.Services; using Microsoft.AspNetCore.Mvc; using System.Threading.Tasks; namespace AspNetCoreSample.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class MessageController : ControllerBase { private readonly IMessageService _messageService; public MessageController(IMessageService messageService) { _messageService = messageService; } /// <summary> /// 获取随机数 /// </summary> /// <returns></returns> [HttpGet] public int GetRandomNum() { return _messageService.RandomNum(); } /// <summary> /// 添加 /// </summary> /// <param name="context"></param> /// <returns></returns> [HttpPost] public async Task<Message> Create(string context) { var entity = new Message() { Context = context }; return await _messageService.CreateAsync(entity); } /// <summary> /// 添加 /// </summary> /// <param name="name"></param> /// <returns></returns> [HttpPost] public async Task<Message> Add() { return await _messageService.Add(); } } }
using System; using System.Configuration; namespace Quintsys.EnviromentConfigurationManager { // ReSharper disable UnusedMember.Global public interface IEnviromentConfigManager { string Get(string key); } public class EnviromentConfigManager : IEnviromentConfigManager { public string Get(string key) { string fromConfig = ConfigurationManager.AppSettings[key]; return String.Equals(fromConfig, "{ENV}", StringComparison.InvariantCultureIgnoreCase) ? Environment.GetEnvironmentVariable(key) : fromConfig; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OnlineTabletop.DTOs { public class BasicCharacterDTO { public string id { get; set; } public string name { get; set; } public string playerAccountName { get; set; } public List<RpgClassDTO> classes { get; set; } public string race { get; set; } public BasicCharacterDTO() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [SelectionBase] public class SawHazard : GameTimeObject { // Configurable Parameters [Header("Setup")] [SerializeField] GameObject sawMesh = null; [SerializeField] BoxCollider hazardTrigger = null; [Header("Damage")] [SerializeField] float damageAmount = 0.7f; [SerializeField] float cuttingForce = 30.0f; [Header("Animation")] [SerializeField] float cosmeticTurnsPerSecond = 1.0f; [Header("Particle Effects")] [SerializeField] ParticleSystem sparks = null; [Header("Sound Effects")] [SerializeField] float sawHitVolume = 0.5f; // Cached References AudioSource audioSource = null; DamageDealer damageDealer = null; private void Awake() { audioSource = GetComponent<AudioSource>(); damageDealer = GetComponent<DamageDealer>(); } void Update() { if(sawMesh) sawMesh.transform.Rotate(cosmeticTurnsPerSecond * 360.0f * Time.deltaTime, 0.0f, 0.0f); } private void OnTriggerStay(Collider other) { Rigidbody otherBody = other.attachedRigidbody; if(!otherBody) return; otherBody.AddForceAtPosition(cuttingForce * transform.forward, transform.position, ForceMode.Impulse); } private void OnTriggerEnter(Collider other) { PlayParticleEffect(); PlaySawHitSound(); if(damageDealer) damageDealer.DealDamage(other.gameObject, damageAmount, false); } private void PlayParticleEffect() { if(sparks) sparks.Play(); } private void PlaySawHitSound() { if(!audioSource) return; if(audioSource.isPlaying) return; audioSource.volume = sawHitVolume; audioSource.Play(); } /// <summary> /// Pause game object activity. /// </summary> public override void OnPause() { // Disable Update() and FixedUpdate() this.enabled = false; // Disable trigger volume if(hazardTrigger) hazardTrigger.enabled = false; // Pause Particles if(sparks && sparks.isPlaying) sparks.Pause(); // Pause Audio if(audioSource && audioSource.isPlaying) audioSource.Pause(); } /// <summary> /// Un-pause game object activity. /// </summary> public override void OnResume() { // Enable Update() this.enabled = true; // Enable trigger volume if(hazardTrigger) hazardTrigger.enabled = true; // Resume Particles if(sparks && sparks.isPaused) sparks.Play(); // Resume Audio if(audioSource) audioSource.UnPause(); } /// <summary> /// Prepare game object for game end. /// </summary> public override void OnGameOver() { // Disable Update() and FixedUpdate() this.enabled = false; // Disable trigger volume if(hazardTrigger) hazardTrigger.enabled = false; } }
using System; using System.Collections.Generic; namespace SANTI_WEB.Models { public partial class Products { public Products() { ProductsDescription = new HashSet<ProductsDescription>(); ProductsItems = new HashSet<ProductsItems>(); ProductsSeo = new HashSet<ProductsSeo>(); ProductsSuccessStories = new HashSet<ProductsSuccessStories>(); } public string Name { get; set; } public string Logo { get; set; } public string Color { get; set; } public int PkProducts { get; set; } public string Route { get; set; } public string FullRoute { get; set; } public string Language { get; set; } public ICollection<ProductsDescription> ProductsDescription { get; set; } public ICollection<ProductsItems> ProductsItems { get; set; } public ICollection<ProductsSeo> ProductsSeo { get; set; } public ICollection<ProductsSuccessStories> ProductsSuccessStories { get; set; } } }
using AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WebApi.Models; using WebApi.Repository.ViewModels; namespace WebApi.Repository.Helpers { public class AutomaperProfile : Profile { public AutomaperProfile() { CreateMap<Todo, TodoViewModel>().ReverseMap(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Calculate_Click(object sender, EventArgs e) { int yearStarted = Convert.ToInt32(YearInput.Text); int courseLength = Convert.ToInt32(LengthList.SelectedValue); int maintenanceLoan = MaintenanceInput.Text == "" ? 0 : Convert.ToInt32(MaintenanceInput.Text); int salary = Convert.ToInt32(Salary.Text); int loanAmount = 0; int payBackSalary = 0; double payBackTimeInYears = 0; double payBackMonths = 0; double payBackPerYear = 0; if (yearStarted <= 2011 && yearStarted >= 2004) { loanAmount = 3465; payBackSalary = 15000; } else { loanAmount = 9000; payBackSalary = 21000; } int totalLoan = (loanAmount * courseLength) + (maintenanceLoan * courseLength); if(yearStarted >= 2004) { if (salary < payBackSalary) { Result.Text = "You are earning under the payback threshold and so do not repay any loan on your current salary."; } else { payBackPerYear = (salary - payBackSalary) * 0.09; payBackTimeInYears = Math.Floor(totalLoan / payBackPerYear); if (payBackTimeInYears > 25) { Result.Text = "Your total loan is £" + totalLoan + ". There is a cut-off of 25 years on paying back a student loan." + "<br/>" + " So if you stay on your current salary, you will pay £" + payBackPerYear + " per year." + "<br/>" + " You will have paid off £" + 25 * payBackPerYear + " before your debt is wiped."; drawChart(payBackPerYear, totalLoan); } else { double payBackMonthsRounded = Math.Floor(totalLoan / payBackPerYear); payBackMonths = Math.Ceiling((totalLoan - (payBackMonthsRounded * payBackPerYear)) / (payBackPerYear / 12)); Result.Text = "Your total loan is £" + totalLoan + ". On a salary of £" + salary + ", you will pay back £" + payBackPerYear + " per year." + "<br/>" + " Therefore it will take you " + payBackTimeInYears + " years, " + payBackMonths + " month(s) to pay off your loan."; drawChart(payBackPerYear, totalLoan); } } } else { Result.Text = "There were no student loans issued by the Student Loans Company before 2004."; } } private void drawChart(double payBackPerYear, int totalLoan) { ClientScript.RegisterStartupScript(GetType(), "draw", "draw(" + payBackPerYear + "," + totalLoan + ");", true); } protected void Reset_Click(object sender, EventArgs e) { YearInput.Text = " "; LengthList.SelectedValue = "1"; MaintenanceInput.Text = ""; Salary.Text = " "; Result.Text = " "; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using EnumController; using System; /// <summary> /// Base class to store runtime cat info; /// </summary> public class CatInfoBase : MonoBehaviour { public CatMovingState MovingState { get; set; } public CatHealthState HealthState { get; set; } public CatHungryState HungryState { get; set; } public CatSatisState SatisState { get; set; } protected float satis_val; protected float health_val; protected float hungry_val; protected ValueWraperBase satis_VW; //Value wraper class; protected ValueWraperBase health_VW; protected ValueWraperBase hungry_VW; protected CatHealthState[] health_itos; //Value index to state dictionary; protected CatHungryState[] hungry_itos; protected CatSatisState[] satis_itos; private void Awake() { MovingState = default(CatMovingState); HealthState = default(CatHealthState); HungryState = default(CatHungryState); SatisState = default(CatSatisState); health_val = 0.0f; hungry_val = 0.0f; satis_val = 0.0f; satis_VW = null; health_VW = null; hungry_VW = null; } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } protected virtual void Init_values() { satis_val = satis_VW.Init_val; SatisState = (CatSatisState)Get_curr_satis_state(); hungry_val = hungry_VW.Init_val; HungryState = (CatHungryState)Get_curr_hungry_state(); health_val = health_VW.Init_val; HealthState = (CatHealthState)Get_curr_health_state(); } #region public methods; public void Parse_setting_data(GameSettingDataBase data) { satis_VW = data.Satis_VW; hungry_VW = data.Hungry_VW; health_VW = data.Health_VW; satis_itos = data.Satis_itos; hungry_itos = data.Hungry_itos; health_itos = data.Health_itos; Init_catinfo(); } public void Init_catinfo() { Init_values(); } public int Get_curr_health_state() { int val_index = health_VW.State_index_cal(health_val); return Utilities.State_index_cal<CatHealthState>(health_itos, val_index); } public int Get_curr_hungry_state() { int val_index = hungry_VW.State_index_cal(hungry_val); return Utilities.State_index_cal<CatHungryState>(hungry_itos, val_index); } public int Get_curr_satis_state() { int val_index = satis_VW.State_index_cal(satis_val); return Utilities.State_index_cal<CatSatisState>(satis_itos, val_index); } #endregion }
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 System.Data.SqlClient; using System.Configuration; namespace HotelManagement { public static class SelectedMaHD { public static string StrmaHD { get; set; } } public partial class InvoiceSearching : Form { public string smaHD; public InvoiceSearching() { InitializeComponent(); } private void loadMaKH(SqlConnection conn) { // Load ma KH string query = "SELECT maKH FROM KhachHang"; SqlDataAdapter da = new SqlDataAdapter(query, conn); DataSet ds = new DataSet(); da.Fill(ds, "maKH"); makhcbb.DisplayMember = "maKH"; makhcbb.DataSource = ds.Tables["maKH"]; } private void InvoiceSearching_Load(object sender, EventArgs e) { // tao chuoi ket noi string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); using (conn) { try { conn.Open(); // mo ket noi // Load Lua chon MaKH can tim trong combo box loadMaKH(conn); conn.Close(); // dong ket noi } catch (Exception ex) { MessageBox.Show("Error!"); } } } private void TimKiemHoaDon_Option_Click(object sender, EventArgs e) { try { string strConn = ConfigurationManager.ConnectionStrings["Demo"].ToString(); SqlConnection conn = new SqlConnection(strConn); // kết nối conn.Open(); String procname = "SP_SearchBill"; SqlDataAdapter adapter = new SqlDataAdapter(procname, conn); adapter.SelectCommand.CommandType = CommandType.StoredProcedure; //Truyền tham số //Ma KH if (makhcbb.Text != "") //kiem tra <> NULL adapter.SelectCommand.Parameters.Add("@ConsID", SqlDbType.Int).Value = Int32.Parse(makhcbb.Text); else adapter.SelectCommand.Parameters.Add("@ConsID", SqlDbType.Int).Value = DBNull.Value; // Ngay if (ngayttcb.Checked == true) // Co tim theo ngay adapter.SelectCommand.Parameters.Add("@Day", SqlDbType.DateTime).Value = DateTime.Parse(ngaythanhtoandt.Value.ToShortDateString()); else adapter.SelectCommand.Parameters.Add("@Day", SqlDbType.DateTime).Value = DBNull.Value; // Tien if (tientucbb.Text != "") adapter.SelectCommand.Parameters.Add("@minTotal", SqlDbType.Money).Value = Int32.Parse(tientucbb.Text); else adapter.SelectCommand.Parameters.Add("@minTotal", SqlDbType.Money).Value = DBNull.Value; if (dentiencbb.Text != "") adapter.SelectCommand.Parameters.Add("@maxTotal", SqlDbType.Money).Value = Int32.Parse(dentiencbb.Text); else adapter.SelectCommand.Parameters.Add("@maxTotal", SqlDbType.Money).Value = DBNull.Value; //load dữ liệu lên datagridview DataTable table = new DataTable(); adapter.Fill(table); danhsachtimhoadon.DataSource = table; } catch (Exception ex) { throw ex; // MessageBox.Show("Có lỗi xảy ra"); } } private void ngaythanhtoandt_ValueChanged(object sender, EventArgs e) { ngaythanhtoandt.Format = DateTimePickerFormat.Short; } private void danhsachtimhoadon_CellContentClick(object sender, DataGridViewCellEventArgs e) { // lấy mã HD đang chọn SelectedMaHD.StrmaHD = danhsachtimhoadon.Rows[e.RowIndex].Cells[1].Value.ToString(); // mở form Chi tiết new InvoiceDetail().Show(); } private void QuayLaisv_Option_Click(object sender, EventArgs e) { new Option_sv().Show(); this.Hide(); } } }
using System; namespace Arch.Data.Common.Vi { public interface ITimeoutMarkDownBean { Boolean EnableTimeoutMarkDown { get; set; } Int32 SamplingDuration { get; set; } Int32 ErrorPercentReferCount { get; set; } Int32 ErrorCountThreshold { get; set; } Double ErrorPercentThreshold { get; set; } String SqlServerErrorCodes { get; set; } String MySqlErrorCodes { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Serrate.Infrastructure; using Serrate.Commands.Sales; using Serrate.Contract.Sales; namespace Serrate.Sales { public class CancelOrderHandler : IHandle<CancelOrder> { private readonly IBus bus; public CancelOrderHandler(IBus bus) { this.bus = bus; } public void Handle(CancelOrder msg) { // do other things this.bus.Publish(new OrderCancelled { OrderId = msg.OrderId }); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using Common.Config; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using Migration.Common.Log; namespace Migration.Common.Config { public class ConfigReaderJson : IConfigReader { private readonly string FilePath; private string JsonText; public ConfigReaderJson(string filePath) { FilePath = filePath; } public ConfigJson Deserialize() { LoadFromFile(FilePath); return DeserializeText(JsonText); } public void LoadFromFile(string filePath) { try { JsonText = GetJsonFromFile(filePath); } catch (FileNotFoundException) { Logger.Log(LogLevel.Error, $"Required JSON configuration file '{filePath}' was not found. Please ensure that this file is in the correct location."); throw; } catch (PathTooLongException) { Logger.Log(LogLevel.Error, $"Required JSON configuration file '{filePath}' could not be accessed because the file path is too long. Please store your files for this application in a folder location with a shorter path name."); throw; } catch (UnauthorizedAccessException) { Logger.Log(LogLevel.Error, $"Cannot read from the JSON configuration file '{filePath}' because you are not authorized to access it. Please try running this application as administrator or moving it to a folder location that does not require special access."); throw; } catch (Exception) { Logger.Log(LogLevel.Error, $"Cannot read from the JSON configuration file '{filePath}'. Please ensure it is formatted properly."); throw; } } public string GetJsonFromFile(string filePath) { return File.ReadAllText(filePath); } public ConfigJson DeserializeText(string input) { ConfigJson result = null; try { result = JsonConvert.DeserializeObject<ConfigJson>(input); var obj = JObject.Parse(input); var fields = obj.SelectToken("field-map.field").Select(jt => jt.ToObject<Field>()).ToList(); if (result.FieldMap.Fields == null) { result.FieldMap.Fields = new List<Field>(); } result.FieldMap.Fields.AddRange(fields); var links = obj.SelectToken("link-map.link").Select(li => li.ToObject<Link>()).ToList(); if(result.LinkMap.Links == null) { result.LinkMap.Links = new List<Link>(); } result.LinkMap.Links.AddRange(links); var types = obj.SelectToken("type-map.type").Select(li => li.ToObject<Type>()).ToList(); if (result.TypeMap.Types == null) { result.TypeMap.Types = new List<Type>(); } result.TypeMap.Types.AddRange(types); } catch (Exception) { Logger.Log(LogLevel.Error, "Cannot deserialize the JSON text from configuration file. Please ensure it is formatted properly."); throw; } return result; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Oef2.Models{ public class Registration{ public int RegisterId { get; set; } [Required(ErrorMessage = "Het veld Naam is vereist")] public string Naam { get; set; } [Required(ErrorMessage = "Het veld Voornaam is vereist")] public string Voornaam { get; set; } public int Leeftijd { get; set; } [Required(ErrorMessage = "Het veld Email is vereist")] [EmailAddress] public string Email { get; set; } public int SelectedSlot1 { get; set; } public int SelectedSlot2 { get; set; } public int SelectedSlot3 { get; set; } public int SelectedOrganization { get; set; } public bool ClosingParty { get; set; } public int[] Accessoires { get; set; } } }
using AutoMapper; using Contoso.Forms.Parameters.Common; using Contoso.Forms.View; using Contoso.Forms.View.Common; using Contoso.Spa.Flow.Cache; using Contoso.Spa.Flow.ScreenSettings.Views; using LogicBuilder.Forms.Parameters; using System; using System.Collections.Generic; namespace Contoso.Spa.Flow { public class CustomDialogs : ICustomDialogs { public CustomDialogs(IMapper mapper, FlowDataCache flowDataCache) { this.flowDataCache = flowDataCache; this.mapper = mapper; } #region Fields private readonly FlowDataCache flowDataCache; private readonly IMapper mapper; #endregion Fields public void DisplayGrid(GridSettingsParameters setting, ICollection<ConnectorParameters> buttons) => this.flowDataCache.ScreenSettings = new ScreenSettings<GridSettingsView> ( mapper.Map<GridSettingsView>(setting), mapper.Map<IEnumerable<ConnectorParameters>, IEnumerable<CommandButtonView>>(buttons), ViewType.Grid ); public void DisplayEditForm(EditFormSettingsParameters setting, ViewType viewType, ICollection<ConnectorParameters> buttons) { this.flowDataCache.ScreenSettings = viewType switch { ViewType.Edit or ViewType.Create => new ScreenSettings<EditFormSettingsView> ( mapper.Map<EditFormSettingsView>(setting), mapper.Map<IEnumerable<ConnectorParameters>, IEnumerable<CommandButtonView>>(buttons), viewType ), _ => throw new ArgumentException($"{nameof(viewType)}: {{B3B3788E-738A-4E6B-8B95-C6DDC2C4AA5D}}"), }; } public void DisplayDetailForm(DetailFormSettingsParameters setting, ViewType viewType, ICollection<ConnectorParameters> buttons) { this.flowDataCache.ScreenSettings = viewType switch { ViewType.Detail or ViewType.Delete => new ScreenSettings<DetailFormSettingsView> ( mapper.Map<DetailFormSettingsView>(setting), mapper.Map<IEnumerable<ConnectorParameters>, IEnumerable<CommandButtonView>>(buttons), viewType ), _ => throw new ArgumentException($"{nameof(viewType)}: {{097C0872-CC75-4772-9570-64D9868DF970}}"), }; } public void DisplayHtmlForm(HtmlPageSettingsParameters setting, ICollection<ConnectorParameters> buttons) => this.flowDataCache.ScreenSettings = new ScreenSettings<HtmlPageSettingsView> ( mapper.Map<HtmlPageSettingsView>(setting), mapper.Map<IEnumerable<ConnectorParameters>, IEnumerable<CommandButtonView>>(buttons), ViewType.Html ); public void DisplayListForm(ListFormSettingsParameters setting, ICollection<ConnectorParameters> buttons) => this.flowDataCache.ScreenSettings = new ScreenSettings<ListFormSettingsView> ( mapper.Map<ListFormSettingsView>(setting), mapper.Map<IEnumerable<ConnectorParameters>, IEnumerable<CommandButtonView>>(buttons), ViewType.List ); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MyGeneration.UnitTests { public class CSharpTests { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraFollow : MonoBehaviour { public Transform target; public float smoothSpeed = 0.125f; public Vector3 offset; private Vector3 velocity = Vector3.zero; //TRANSITIONS public float offsetTransitionTime = 2.0f; public float rotationTransitionTime = 2.0f; private void LateUpdate() { Vector3 desiredPosition = target.position + offset; Vector3 smoothedPosition = Vector3.SmoothDamp(transform.position, desiredPosition, ref velocity, smoothSpeed); transform.position = smoothedPosition; } public IEnumerator ChangeOffset(Vector3 targetOffset) { Vector3 initialOffset = offset; float elapsedTime = 0.0f; float maxTime = offsetTransitionTime; while (offset != targetOffset) { elapsedTime += Time.deltaTime; offset = Vector3.Lerp(initialOffset, targetOffset, elapsedTime / maxTime); yield return new WaitForEndOfFrame(); } yield return 0; } public IEnumerator ChangeRotation(Quaternion targetRotation) { Quaternion initialRotation = Camera.main.transform.rotation; float elapsedTime = 0.0f; float maxTime = offsetTransitionTime; while (initialRotation != targetRotation) { elapsedTime += Time.deltaTime; Camera.main.transform.rotation = Quaternion.Slerp(initialRotation, targetRotation, elapsedTime / maxTime); yield return new WaitForEndOfFrame(); } yield return 0; } }
using bot_backEnd.BL.Interfaces; using bot_backEnd.DAL.Interfaces; using bot_backEnd.Models.DbModels; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.BL { public class CommentImageBL : ICommentImageBL { private readonly ICommentImageDAL _iCommentImageDAL; private readonly IWebHostEnvironment _environment; public CommentImageBL(ICommentImageDAL iCommentImageDAL, IWebHostEnvironment enviroment) { _iCommentImageDAL = iCommentImageDAL; _environment = enviroment; } public bool DeleteCommentImages(int commentID, int postID) { var images = _iCommentImageDAL.GetAllCommentImages(commentID, postID).Result.Value; foreach (var image in images) File.Delete(_environment.WebRootPath + Path.Combine(image.Path, image.Name)); return true; } public async Task<ActionResult<bool>> UploadCommentImages(IFormFile[] images, int commentID, int PostID, int typeID) { int subFolderID; //number of subFolder string subFolder; //name of subfolder with ID on the END if (images == null || images.Length == 0) return false; string folder = "/comment/"; if (!Directory.Exists(_environment.WebRootPath + folder)) Directory.CreateDirectory(_environment.WebRootPath + folder); foreach (IFormFile img in images) //foreach sent image { string imgext = Path.GetExtension(img.FileName); if (imgext == ".jpg" || imgext == ".png" || imgext == ".jpeg") { CommentImage newImage = new CommentImage { CommentID = commentID, PostID = PostID, Path = folder, //+ subFolder, Name = img.FileName }; await _iCommentImageDAL.AddCommentImage(newImage); subFolderID = newImage.Id / 3000 + 1; subFolder = string.Format("{0:D4}", subFolderID) + "/"; await _iCommentImageDAL.UpdateImage(newImage.Id, imgext, folder + subFolder); if (!Directory.Exists(_environment.WebRootPath + folder + subFolder)) Directory.CreateDirectory(_environment.WebRootPath + folder + subFolder); using FileStream fileStream = System.IO.File.Create(_environment.WebRootPath + folder + subFolder + newImage.Id.ToString() + imgext); await img.CopyToAsync(fileStream); fileStream.Flush(); } else return false; } return true; } public async Task<ActionResult<bool>> UploadInstitutionCommentImage(int commentID, int postID, string image) { try { string mainFolder = "/comment/"; int subFolderID; string subFolderName; if (image == "" || image == null) return null; if (!Directory.Exists(_environment.WebRootPath + mainFolder)) Directory.CreateDirectory(_environment.WebRootPath + mainFolder); CommentImage newImage = new CommentImage { CommentID = commentID, PostID = postID, Path = mainFolder, //+ subFolder, Name = "image" }; await _iCommentImageDAL.AddCommentImage(newImage); //adds image to database table subFolderID = newImage.Id / 3000 + 1; subFolderName = string.Format("{0:D4}", subFolderID) + "/"; await _iCommentImageDAL.UpdateImage(newImage.Id, ".jpg", mainFolder +subFolderName); //updates path and name after adding image to database if (!Directory.Exists(_environment.WebRootPath + mainFolder + subFolderName)) Directory.CreateDirectory(_environment.WebRootPath + mainFolder + subFolderName); //adding to server byte[] bytes = Convert.FromBase64String(image); var path = mainFolder + subFolderName + newImage.Id.ToString() + ".jpg"; var filePath = Path.Combine(_environment.WebRootPath + path); System.IO.File.WriteAllBytes(filePath, bytes); return true; } catch (Exception e) { throw e; } } } }
using ServerKinect.Shape; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ServerKinect.HandTracking { internal class FingerBaseDetector { private float indexOffset; private float offsetDistance; public FingerBaseDetector(HandDataSourceSettings settings) { this.indexOffset = settings.FingerBaseIndexOffset; this.offsetDistance = settings.FingerBaseOffsetDistance; } public void Detect(Contour contour, IList<FingerPoint> fingerTips) { foreach (var fingerPoint in fingerTips) { FindBasePoints(contour, fingerPoint); } } private void FindBasePoints(Contour contour, FingerPoint fingerPoint) { var fingerPointIndex = FindIndex(fingerPoint.Fingertip, contour); var distanceAdjustedOffset = (int)(offsetDistance * indexOffset / fingerPoint.Fingertip.Z); fingerPoint.BaseLeft = contour.GetPointAt(Rollover(fingerPointIndex - distanceAdjustedOffset, contour.Count)); fingerPoint.BaseRight = contour.GetPointAt(Rollover(fingerPointIndex + distanceAdjustedOffset, contour.Count)); var baseCenter = Point.Center(fingerPoint.BaseLeft, fingerPoint.BaseRight); fingerPoint.DirectionVector = Point.Subtract(fingerPoint.Fingertip, baseCenter).GetNormalizedVector(); } private int Rollover(int index, int maxIndex) { if (index < 0) { return index + maxIndex; } if (index >= maxIndex) { return index - maxIndex; } return index; } private int FindIndex(Point point, Contour contour) { return Point.FindIndexOfNearestPoint(point, contour.Points); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Configuration; using Microsoft.Bot.Connector.Authentication; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using JIoffe.BIAD.Bots; using Microsoft.Bot.Builder.AI.QnA; namespace JIoffe.BIAD.QnABot { public class Startup { private ILoggerFactory _loggerFactory; public IConfiguration Configuration { get; } private IHostingEnvironment Environment { get; } public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); Environment = env; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //Instantiate the bot configuration for use in the bot //Traffic coming through to your app is protected by the app ID and app secret //credentials applied to your Bot Registration on Azure. //If you are running locally, these can be blank. var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey); if (botConfig == null) throw new InvalidOperationException($"The .bot config file could not be loaded from [{botFilePath}]"); //Step 1) We can pass bot-related dependencies to the bot and dialogs via DI. Start with the bot configuration //Add the bot configuration as something we can retrieve through DI //TODO - Add the BotConfiguration to the services container //Step 2) Configure the QnA services // - (Optional) Throw an exception if the service is null or if any required fields are empty //TODO - Retrieve the first service from the configuration of type ServiceTypes.QnA //TODO - Create a new instance of QnAMaker and add it to the services container as a singleton //The extension to add a bot to our services container //can be found in Microsoft.Bot.Builder.Integration.AspNet.Core //Whichever type is passed will be the bot that is created services.AddBot<QnAMakerBot>(options => { //The bot configuration can map different endpoints for different environments var serviceName = Environment.EnvironmentName.ToLowerInvariant(); var service = botConfig.FindServiceByNameOrId(serviceName) as EndpointService; if(service == null) throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{serviceName}'."); options.CredentialProvider = new SimpleCredentialProvider(service.AppId, service.AppPassword); //Memory storage is only used for this example. //In a production application, you should always rely on //a more persistant storage mechanism, such as CosmosDB IStorage dataStore = new MemoryStorage(); //Whichever datastore we're working with, we will need to use it //to actually store the conversation state. var conversationState = new ConversationState(dataStore); options.State.Add(conversationState); //Step 3) Add a callback for "OnTurnError" that logs any bot or middleware errors to the console // - (Optional) Send a message to the user indicating there was a problem ILogger logger = _loggerFactory.CreateLogger<QnAMakerBot>(); //TODO - Set options.OnTurnError to an async Task that accepts a ITurnContext and Exception }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; app.UseDefaultFiles() .UseStaticFiles() .UseBotFramework(); //Automatically maps endpoint handlers related to bots } } }
using System; using System.Reflection; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Vipr; namespace T4TemplateWriterTests { class IntegrationTest { private Vipr.Bootstrapper bootstrapper; private String inputFile = @"http://services.odata.org/V4/OData/OData.svc/$metadata"; private String readerName = @"--reader=Vipr.Reader.OData.v4"; private String writerName = @"--writer=Vipr.T4TemplateWriter"; private String outputPath = @"--outputPath=.\output"; public IntegrationTest() { bootstrapper = new Vipr.Bootstrapper(); } public void Run(Boolean interactive) { bootstrapper.Start(new String[] { inputFile, readerName, writerName, outputPath }); if (interactive) Console.ReadKey(); } } }
namespace RealEstate.ViewModels { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class CommentViewModels { public CommentViewModels() { CreatedOn = DateTimeOffset.Now; } public int Id { get; set; } public int? PostId { get; set; } public int? PropertyId { get; set; } [Range(1, 5)] public int Rating { get; set; } [EmailAddress(ErrorMessage = "Địa chỉ Email không hợp lệ")] [Required(ErrorMessage = "Vui lòng điền địa chỉ Email")] public string EmailAddress { get; set; } [Required(ErrorMessage = "Vui lòng điền tên")] public string Owner { get; set; } [Required(ErrorMessage = "Vui lòng điền nội dung")] public string Description { get; set; } public DateTimeOffset CreatedOn { get; set; } public int? ParentId { get; set; } public CommentViewModels Parent { get; set; } public ICollection<CommentViewModels> Child { get; set; } } public class ReadCommentViewModels : _Pager { public int Id { get; set; } public string Owner { get; set; } [DataType(DataType.EmailAddress)] public string EmailAddress { get; set; } public string Content { get; set; } public bool IsVerify { get; set; } public int? Rating { get; set; } public string UrlLinked { get; set; } public DateTimeOffset CreatedOn { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace com.defrobo.salamander.gui { public partial class MainForm : Form { private CommandService infoService; private Dictionary<Currency, Balance> balances; private OrderBook orderBook; private IAlerter alerter; private Predictor predictor; public MainForm() { InitializeComponent(); } private async void Startup() { var backtest = true; infoService = new CommandService(); var balancesResult = infoService.GetBalances(); if (backtest) { alerter = new BackTestReplayer(".\\..\\..\\..\\salamander.backtestrecorder\\bin\\debug\\recording0.bts"); } else { alerter = new Alerter(); } alerter.ExecutionCreated += ExecutionAlerter_Created; alerter.OrderBookSnapshot += OrderBookUpdater_Snapshot; alerter.OrderBookUpdated += OrderBookUpdater_Update; alerter.TickerUpdated += Ticker_Updated; orderBook = new OrderBook(alerter); predictor = new Predictor(alerter); alerter.Start(); balances = await balancesResult; RefreshBalances(balances); } private void OrderBookUpdater_Update(object sender, OrderBookUpdateEventArgs e) { BeginInvoke(new Action(() => { lstOrderBookBids.Items.Clear(); lstOrderBookAsks.Items.Clear(); foreach (var order in orderBook.Bids.Take(orderBook.Bids.Count >= 10 ? 10 : orderBook.Bids.Count)) { lstOrderBookBids.Items.Add(String.Format("{0} {1}", order.Price, order.Size)); } foreach (var order in orderBook.Asks.Take(orderBook.Asks.Count >= 10 ? 10 : orderBook.Asks.Count)) { lstOrderBookAsks.Items.Add(String.Format("{0} {1}", order.Price, order.Size)); } })); } private void OrderBookUpdater_Snapshot(object sender, OrderBookSnapshotEventArgs e) { BeginInvoke(new Action(() => { lstOrderBookBids.Items.Clear(); lstOrderBookAsks.Items.Clear(); foreach (var order in orderBook.Bids.Take(10)) { lstOrderBookBids.Items.Add(String.Format("{0} {1}", order.Price, order.Size)); } foreach (var order in orderBook.Asks.Take(10)) { lstOrderBookAsks.Items.Add(String.Format("{0} {1}", order.Price, order.Size)); } })); } private void Ticker_Updated(object sender, MarketTickEventArgs e) { BeginInvoke(new Action(() => { lblBestBid.Text = e.Tick.BestBid.ToString(); lblBestBidSize.Text = e.Tick.BestBidSize.ToString(); lblLastTradedPrice.Text = e.Tick.LastTradedPrice.ToString(); lblBestAsk.Text = e.Tick.BestAsk.ToString(); lblBestAskSize.Text = e.Tick.BestAskSize.ToString(); lblDirection.Text = predictor.PriceDirection.ToString(); })); } private void ExecutionAlerter_Created(object sender, ExecutionEventArgs e) { BeginInvoke(new Action(() => { foreach (var execution in e.Executions) { lstExecutions.Items.Add(String.Format("{0} {1} {2}", execution.Side, execution.Price, execution.Size)); } })); } private void UpdateExecutions(ExecutionEventArgs e) { foreach (var execution in e.Executions) { lstExecutions.Items.Add(String.Format("{0} {1} {2}", execution.Side, execution.Price, execution.Size)); } } private void RefreshBalances(Dictionary<Currency, Balance> balances) { lblBalanceJPYAmount.Text = balances[Currency.JPY].Amount.ToString(); lblBalanceBTCAmount.Text = balances[Currency.BTC].Amount.ToString(); } private void MainForm_Load(object sender, EventArgs e) { Startup(); } private void MainForm_FormClosed(object sender, FormClosedEventArgs e) { infoService.Close(); alerter.Stop(); } } }
using AutoMapper; using ImmedisHCM.Data.Entities; using ImmedisHCM.Services.Models.Core; namespace ImmedisHCM.Services.Mapping { public class SalaryMapping : Profile { public SalaryMapping() { CreateMap<Salary, SalaryServiceModel>().ReverseMap(); } } }
using System; using System.Linq; namespace BusinessLayer.SortingAlgorithms { /// <summary> /// Provides functionality that sort elements in an ascending order by Quick sort type. /// </summary> /// <owner>Anton Petrenko</owner> /// <typeparam name="T">Certain input type.</typeparam> /// <seealso cref="BusinessLayer.SortingAlgorithms.CollectionSorterBase{T}" /> public class QuickSorter<T> : CollectionSorterBase<T> where T : IComparable { /// <summary> /// Stores value for first element to find in array. /// </summary> /// <owner>Anton Petrenko</owner> private const int StartElement = 0; /// <summary> /// Sorts the specified input collection. /// </summary> /// <owner>Anton Petrenko</owner> /// <param name="inputCollection">The input collection.</param> public override void Sort(T[] inputCollection) { if (inputCollection is null || !inputCollection.Any()) throw new ArgumentNullException(nameof(inputCollection)); this.Sort(inputCollection, StartElement, inputCollection.Length - 1); } /// <summary> /// Sorts the specified input collection by start and end elements. /// </summary> /// <owner>Anton Petrenko</owner> /// <param name="inputCollection">The input collection.</param> /// <param name="startElement">The start element.</param> /// <param name="endElement">The end element.</param> private void Sort(T[] inputCollection, int startElement, int endElement) { if (startElement > endElement) return; int wall = this.Separate(inputCollection, startElement, endElement); this.Sort(inputCollection, startElement, wall - 1); this.Sort(inputCollection, wall + 1, endElement); } /// <summary> /// Separates the array by "wall" value. /// </summary> /// <owner>Anton Petrenko</owner> /// <param name="inputCollection">The input collection.</param> /// <param name="start">The first index of array.</param> /// <param name="end">The last index of array.</param> private int Separate(T[] inputCollection, int start, int end) { var pivot = end; int wall = start - 1; for (int currentIndex = start; currentIndex < end; currentIndex++) { if (inputCollection[currentIndex].CompareTo(inputCollection[pivot]) <= 0) { wall++; this.SwapElements(inputCollection, currentIndex, wall); } } this.SwapElements(inputCollection, ++wall, pivot); return wall; } /// <summary> /// Swaps the elements. /// </summary> /// <owner>Anton Petrenko</owner> /// <param name="collection">The collection.</param> /// <param name="leftIndex">Index of left element in array.</param> /// <param name="rightIndex">Index of right element in array.</param> private void SwapElements(T[] collection, int leftIndex, int rightIndex) { var temp = collection[rightIndex]; collection[rightIndex] = collection[leftIndex]; collection[leftIndex] = temp; } } }
using System; using System.Collections.Generic; using System.Text; using System.Data; using Zhouli.DAL.Interface; using Zhouli.DbEntity.Models; using Microsoft.Extensions.Configuration; namespace Zhouli.DAL.Implements { public class BlogNavigationImgDAL : BaseDAL<BlogNavigationImg>, IBlogNavigationImgDAL { public BlogNavigationImgDAL(ZhouLiContext db, IDbConnection dbConnection) : base(db, dbConnection) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class reward_contrl : MonoBehaviour { // Use this for initialization void Start () { Main._instance.Game_state = Main.state_game.run; } // Update is called once per frame void Update () { } private void OnTriggerEnter2D(Collider2D collision) { if(collision.tag=="Player") { int index = SceneManager.GetActiveScene().buildIndex; //player_state.player_state_instance.set_levelcount(index+1); SceneManager.LoadScene(index + 1); Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; namespace Microsoft.DataStudio.Services.MachineLearning.Contracts { public class WebServiceCreationStatusInfo { public Guid ActivityId { get; set; } public WebServiceCreationStatus Status { get; set; } public string WebServiceGroupId { get; set; } public string EndpointId { get; set; } } }
using REQFINFO.Repository; using REQFINFO.Domain; using REQFINFO.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using REQFINFO.Repository.Infrastructure.Contract; namespace REQFINFO.Business.Interfaces { public interface IWorkFlowUserGroupBusiness { List<WorkFlowUserGroupModel> GetWorkFlowUserGroup(Int32 IDWorkFlow); } }
using Microsoft.VisualStudio.TestTools.UnitTesting; using Savaged.HasMyPasswordBeenPwned.CLI; using System; namespace Savaged.HasMyPasswordBeenPwned.Test { [TestClass] public class CliTests { [TestMethod] public void TestMain() { var program = new Program(); var feedback = program .Run(new string[] { "password" }); Assert.AreEqual( $"{Environment.NewLine} Pwned! Change it!", feedback); } } }
using System; namespace Socialease.ViewModels { public class NoteViewModel { public int Id { get; set; } public string Description { get; set; } public DateTime Created { get; set; } public int PersonId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using ENTITY; using Openmiracle.BLL; using Openmiracle.DAL; using System.Data; namespace Openmiracle.BLL { public class CreditNoteMasterBll { CreditNoteMasterInfo InfoCreditNoteMaster = new CreditNoteMasterInfo(); CreditNoteMasterSP SpCreditNoteMaster = new CreditNoteMasterSP(); public decimal CreditNoteMasterGetMaxPlusOne(decimal decVoucherTypeId) { decimal decMId = 0; try { decMId = SpCreditNoteMaster.CreditNoteMasterGetMaxPlusOne(decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("CNB:1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decMId; } public string CreditNoteMasterGetMax(decimal decVoucherTypeId) { string strgetmax = "0"; try { strgetmax = SpCreditNoteMaster.CreditNoteMasterGetMax(decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("CNB:2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return strgetmax; } public bool CreditNoteCheckExistence(string strInvoiceNo, decimal voucherTypeId, decimal decMasterId) { bool isResult = false; try { isResult = SpCreditNoteMaster.CreditNoteCheckExistence(strInvoiceNo, voucherTypeId, decMasterId); } catch (Exception ex) { MessageBox.Show("CNB:3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return isResult; } internal DataSet CreditNotePrinting(decimal decCreditNoteMasterId, decimal decCompanyId) { DataSet ds = new DataSet(); try { ds = SpCreditNoteMaster.CreditNotePrinting(decCreditNoteMasterId, decCompanyId); } catch (Exception) { throw; } return ds; } public void CreditNoteVoucherDelete(decimal decCreditNoteMasterId, decimal decVoucherTypeId, string strVoucherNo) { try { SpCreditNoteMaster.CreditNoteVoucherDelete(decCreditNoteMasterId, decVoucherTypeId, strVoucherNo); } catch (Exception) { } } public decimal CreditNoteMasterAdd(CreditNoteMasterInfo creditnotemasterinfo) { decimal decId = 0; try { decId = SpCreditNoteMaster.CreditNoteMasterAdd(creditnotemasterinfo); } catch (Exception ex) { MessageBox.Show("CNB:4:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public decimal CreditNoteMasterEdit(CreditNoteMasterInfo creditnotemasterinfo) { decimal decResult = 0; try { decResult = SpCreditNoteMaster.CreditNoteMasterEdit(creditnotemasterinfo); } catch (Exception ex) { MessageBox.Show("CNB:5:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decResult; } public CreditNoteMasterInfo CreditNoteMasterView(decimal creditNoteMasterId) { CreditNoteMasterInfo InfoCreditNoteMaster = new CreditNoteMasterInfo(); try { InfoCreditNoteMaster = SpCreditNoteMaster.CreditNoteMasterView(creditNoteMasterId); } catch (Exception ex) { MessageBox.Show("SB6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return InfoCreditNoteMaster; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class movement : MonoBehaviour { public CharacterController controller; //Crea colisiones de una vez public float speed = 10f; public float gravity = -7.0f; public Transform groundCheck; public float groundDistance = .4f; public LayerMask groundMask; private Vector3 velocity; private bool isGrounded; //Recordemos que las variables que sean publicas Unity te las agrega al inspector de elementos // Start no es necesario para esto del movimiento // Update is called once per frame void Update() { isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); //Verifica si estamos realmente en el suelo parados if(isGrounded && velocity.y < 0) { velocity.y = -2f; } float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 movement = transform.right * x + transform.forward * z; //transform convierte nuestros inutiles numeros en manejadores que Unity puede entender/utilizar controller.Move(movement * speed * Time.deltaTime); //qué movimiento, a qué velocidad y Time.deltaTime -> tiempo desde ultimo frame velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); //Se encarga de moverse hacia abajo (por la gravedad) } }
namespace OCP { /** * @since 8.2.0 */ // class SabrePluginException extends Exception { // // /** // * Returns the HTTP statuscode for this exception // * // * @return int // * @since 8.2.0 // */ // public function getHTTPCode() { // return this.code; // } // } }
using Prism.Mvvm; using Prism.Regions; using Reactive.Bindings; using System; namespace RegionMngDemo.ViewModels { public class MainWindowViewModel : BindableBase { private string _title = "Prism Application"; public string Title { get { return _title; } set { SetProperty(ref _title, value); } } public ReactiveCommand<string> NavigationCommand { get; } = new ReactiveCommand<string>(); public IRegionManager RegionManager { get; private set; } public MainWindowViewModel(IRegionManager regionManager) { this.RegionManager = regionManager; NavigationCommand.Subscribe<string>(viewName => { this.RegionManager.RequestNavigate("ContentRegion", viewName); }); } } }
using System; using Application.Controllers; using Application.Data.Models; using Microsoft.EntityFrameworkCore; using Microsoft.VisualStudio.TestTools.UnitTesting; using Application.Frameworks; using Application.Models; using Application.Repo; using AutoMapper; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Moq; using ActionResult = Microsoft.AspNetCore.Mvc.ActionResult; using DatabaseModel = Application.Data.Models.DatabaseModel; using ITempDataProvider = Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataProvider; using TempDataDictionary = Microsoft.AspNetCore.Mvc.ViewFeatures.TempDataDictionary; using Microsoft.AspNetCore.Mvc; namespace UnitTesting { /** * * name : MemberRepositories.cs * author : Aleksy Ruszala * date : 29/04/2019 * * */ /// <summary> /// The task of this class is to test the functionality of the Member controller /// </summary> [TestClass] public class MemberUnitTest { DbContextOptions<DatabaseModel> _dbOptions = new DbContextOptionsBuilder<DatabaseModel>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .EnableSensitiveDataLogging() .Options; public MemberUnitTest() { Mapper.Initialize(cfg => { cfg.AddProfile<AutomapperProfile>(); }); } /// <summary> /// Method check is editing mode is triggered after passing an member to form /// </summary> [TestMethod] public void TestMemberFormInEditMode() { //Arrange ITempDataProvider tempDataProvider = Mock.Of<ITempDataProvider>(); TempDataDictionaryFactory tempDataDictionaryFactory = new TempDataDictionaryFactory(tempDataProvider); ITempDataDictionary tempData = tempDataDictionaryFactory.GetTempData(new DefaultHttpContext()); MemberController controller = new MemberController(new UnitOfWork(new DatabaseModel())) { TempData = tempData }; //Act var viewResult = controller.CreateUpdate("0001") as ViewResult; var isEditMode = (bool) viewResult.TempData["EditMember"]; var model = viewResult.Model as MemberViewModel; //Assert Assert.IsInstanceOfType(viewResult, typeof(ViewResult)); Assert.IsTrue(isEditMode); Assert.IsInstanceOfType(viewResult.Model, typeof(MemberViewModel)); Assert.AreEqual(model.Type, MemberType.Member); Assert.AreEqual(model.Name, "Kim"); } /// <summary> /// Method check is controller give back empty form to add new member /// </summary> [TestMethod] public void TestMemberFormInAddNewMode() { //Arrange ITempDataProvider tempDataProvider = Mock.Of<ITempDataProvider>(); TempDataDictionaryFactory tempDataDictionaryFactory = new TempDataDictionaryFactory(tempDataProvider); ITempDataDictionary tempData = tempDataDictionaryFactory.GetTempData(new DefaultHttpContext()); MemberController controller = new MemberController(new UnitOfWork(new DatabaseModel())) { TempData = tempData }; //Act var viewResult = controller.CreateUpdate() as ViewResult; var isEditMode = (bool) viewResult.TempData["EditMember"]; var model = viewResult.Model as MemberViewModel; //Assert Assert.IsFalse(isEditMode); Assert.IsInstanceOfType(viewResult.Model, typeof(MemberViewModel)); Assert.AreEqual(model.SRU, null); Assert.AreEqual(model.Name, null); } /// <summary> /// Method check is new user is added to database correctly and its type is match to Data Model /// </summary> [TestMethod] public void TestAddingMember() { //Arrange ITempDataProvider tempDataProvider = Mock.Of<ITempDataProvider>(); TempDataDictionaryFactory tempDataDictionaryFactory = new TempDataDictionaryFactory(tempDataProvider); ITempDataDictionary tempData = tempDataDictionaryFactory.GetTempData(new DefaultHttpContext()); var unitOfWork = new UnitOfWork(new DatabaseModel(_dbOptions)); MemberController controller = new MemberController(unitOfWork) { TempData = tempData }; var testMember = new MemberViewModel() { SRU = "TestSRU", Name = "TestName", Surname = "TestSurname", Address = new AddressViewModel() { City = "TestCity" } }; //Act controller.CreateUpdate(testMember); var memberInDatabase = unitOfWork.MemberRepositories.FindBySRU("TestSRU"); //Assert Assert.IsInstanceOfType(memberInDatabase, typeof(Member)); Assert.AreEqual(memberInDatabase.SRU, "TestSRU"); Assert.AreEqual(memberInDatabase.Name, "TestName"); Assert.AreEqual(memberInDatabase.Surname, "TestSurname"); Assert.IsInstanceOfType(memberInDatabase.Address, typeof(Address)); Assert.AreEqual(memberInDatabase.Address.City, "TestCity"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Sunny.Lib.DllHelper; using Sunny.Lib; using Sunny.Lib.Xml; using Sunny.Assistant.BaseForm; using System.IO; namespace Sunny.Assistant { public partial class Main : Form { public Main() { InitializeComponent(); RegisterHotKeys(); SetTabStyle(); LoadAllPageContent(); } private void SetTabStyle() { tabContainer.Alignment = TabAlignment.Right; } /// <summary> /// 1. Load the top child window /// 2. Load tap pages from xml /// </summary> private void LoadAllPageContent() { // Load the top //panelTop.Controls.Clear(); //panelTop.Controls.Add(new Top() { TopLevel = false, Dock = DockStyle.Fill }); //ShowChildForm("Top", panelTop); // Load the tab pages this.tabContainer.TabPages.Clear(); string xmlFilePath = string.Format(Const.Root_ConfigFile_FullPath, Const.RootXmlName); List<XMLFileInfo> list = XMLSerializerHelper.DeserializeListByXPath<XMLFileInfo>(XMLFileInfo.XPath2, xmlFilePath); list.ForEach(pp => { string tbName = pp.FileName; LoadTabPageContent(tbName); }); } private void LoadTabPageContent(string tabName) { TabPage tb = tabContainer.TabPages[tabName]; if (tb == null) { tb = new TabPage(tabName) { Name = tabName }; tabContainer.TabPages.Add(tb); } else { tb.Controls.Clear(); } tb.Controls.Add(new TabPageTemplate(tabName) { TopLevel = false, Dock = DockStyle.Fill }); ShowChildForm(tabName, tb); tb.ContextMenuStrip = this.contextMenuStrip2; } private void ShowChildForm(string key, Panel page) { foreach (Control ctrl in page.Controls) { if (ctrl.Name.ToString() == key) { ctrl.Show(); } else { ctrl.Visible = false; } } } protected override void WndProc(ref Message m) { const int WM_HOTKEY = (int)WindowsMessages.WM_HOTKEY; switch (m.Msg) { case WM_HOTKEY: switch (m.WParam.ToInt32()) { case 100: // Alt+A ShowWindow(); break; case 101: // Alt+B HideWindow(); break; case 102: // Alt+D if (MessageBox.Show("Are you sure to exit 'Sunny Assistant'?", "Exit tip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) { } else { UnRegisterHotKeys(); Application.Exit(); } break; case 103: SetSelectTab(false); break; case 104: SetSelectTab(true); break; case 105: case 106: this.MySelectNextControl(true); break; case 107: this.MySelectNextControl(false); break; case 108: this.RunTool(); break; } break; } const int WM_SYSCOMMAND = (int)WindowsMessages.WM_SYSCOMMAND; const int SC_CLOSE = 0xF060; const int SC_MINIMIZE = 0xF020; if (m.Msg == WM_SYSCOMMAND && ((int)m.WParam == SC_MINIMIZE || (int)m.WParam == SC_CLOSE)) { this.Hide(); return; } base.WndProc(ref m); } private void Main_Activated(object sender, EventArgs e) { RegisterHotKeys(false); } private void Main_Deactivate(object sender, EventArgs e) { UnRegisterHotKeys(false); } /// <summary> /// /// </summary> /// <param name="isAll">是否注册所有热键,如果是获取焦点的时候为false,窗体创建的时候为true。</param> private void RegisterHotKeys(bool isAll = true) { List<HotKey> hotKeyInfoList = hotKeyInfoList = XMLSerializerHelper.DeserializeListByXPath<HotKey>(HotKey.XPath, Const.HotKey_ConfigFile_FullPath); if (null != hotKeyInfoList) { hotKeyInfoList.Where(h => h.Enabled == true).ToList().ForEach(h => { User32.KeyModifiers primaryKey = User32.KeyModifiers.Alt; Keys secondKey = Keys.A; Enum.TryParse(h.PrimaryKey, out primaryKey); Enum.TryParse(h.SecondKey, out secondKey); // 当前窗体重新获得焦点,注册以下快捷键 if (h.KeyType == "2") { User32.RegisterHotKey(Handle, h.KeyId, primaryKey, secondKey); } else if (h.KeyType == "1" && isAll) { User32.RegisterHotKey(Handle, h.KeyId, primaryKey, secondKey); } }); } } /// <summary> /// /// </summary> /// <param name="isAll">是否注销所有热键,如果是失去焦点的时候为false,窗体注销的时候为true。</param> private void UnRegisterHotKeys(bool isAll = true) { List<HotKey> hotKeyInfoList = hotKeyInfoList = XMLSerializerHelper.DeserializeListByXPath<HotKey>(HotKey.XPath, Const.HotKey_ConfigFile_FullPath); if (null != hotKeyInfoList) { hotKeyInfoList.Where(h => h.Enabled == true).ToList().ForEach(h => { User32.KeyModifiers primaryKey = User32.KeyModifiers.Alt; Keys secondKey = Keys.A; Enum.TryParse(h.PrimaryKey, out primaryKey); Enum.TryParse(h.SecondKey, out secondKey); // 全局热键:不管窗体是否获取焦点,都有效,直到窗体注销 if (h.KeyType == "2") { User32.UnregisterHotKey(Handle, h.KeyId); } else if (h.KeyType == "1" && isAll) { User32.UnregisterHotKey(Handle, h.KeyId); } }); } } #region Context menu event method private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { ShowWindow(); } private void conMenuShow_Click(object sender, EventArgs e) { ShowWindow(); } private void conMenuHide_Click(object sender, EventArgs e) { HideWindow(); } private void conMenuExit_Click(object sender, EventArgs e) { if (MessageBox.Show("Are you sure quit?", "Question", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.Cancel) { return; } Application.Exit(); } #endregion #region Menu event method private void menuRefresh_Click(object sender, EventArgs e) { LoadTabPageContent(this.tabContainer.SelectedTab.Text); } private void menuRefreshAll_Click(object sender, EventArgs e) { LoadAllPageContent(); } private void menuViewLog_Click(object sender, EventArgs e) { Sunny.Assistant.Menu.Configuration.ViewLog.ViewLog vl = new Assistant.Menu.Configuration.ViewLog.ViewLog(); vl.Show(); } //private void menuXmlDataEdit_Click(object sender, EventArgs e) //{ // Demo.XML.XMLMain operateXML = new Demo.XML.XMLMain(); // operateXML.Show(); //} private void menuSettings_Click(object sender, EventArgs e) { Sunny.Assistant.UI.Menu.Configuration.Settings.SettingsMain setting = new UI.Menu.Configuration.Settings.SettingsMain(); setting.Show(); } #endregion #region Tab context menu event method private void contextMenuStrip2_Opening(object sender, CancelEventArgs e) { if (Clipboard.ContainsData(typeof(ToolInfo).FullName)) { this.menuPast.Enabled = true; } else { this.menuPast.Enabled = false; } } private void menuTabAdd_Click(object sender, EventArgs e) { UI.TabPage.DialogContext context = new UI.TabPage.DialogContext() { OperationType = UI.TabPage.OperationType.Add, OriginalTabName = this.tabContainer.SelectedTab.Text }; UI.TabPage.TabPageEdit tabAdd = new UI.TabPage.TabPageEdit(context); if (tabAdd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { TabPage tb = new TabPage(context.OriginalTabName); tb.Controls.Add(new TabPageTemplate(context.OriginalTabName) { TopLevel = false, Dock = DockStyle.Fill }); ShowChildForm(context.OriginalTabName, tb); tabContainer.TabPages.Add(tb); tb.ContextMenuStrip = this.contextMenuStrip2; } } private void menuTabModify_Click(object sender, EventArgs e) { if (Const.ReadOnlyTabList.Contains("," + this.tabContainer.SelectedTab.Text + ",")) { MessageBox.Show(string.Format("Can't modify Tab \"{0}\"", Const.ReadOnlyTabList.Trim(','))); return; } UI.TabPage.DialogContext context = new UI.TabPage.DialogContext() { OperationType = UI.TabPage.OperationType.Modify, OriginalTabName = this.tabContainer.SelectedTab.Text }; UI.TabPage.TabPageEdit tabModify = new UI.TabPage.TabPageEdit(context); if (tabModify.ShowDialog() == System.Windows.Forms.DialogResult.OK) { this.tabContainer.SelectedTab.Text = context.OriginalTabName; } } private void menuTabDelete_Click(object sender, EventArgs e) { if (Const.ReadOnlyTabList.Contains("," + this.tabContainer.SelectedTab.Text + ",")) { MessageBox.Show(string.Format("Can't delete Tab \"{0}\"", Const.ReadOnlyTabList.Trim(','))); return; } if (this.tabContainer.Controls.Count <= 1) { MessageBox.Show("Must left one tab."); return; } if (MessageBox.Show("Are you sure to delete?", "delete tip", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK) { ResultMessage result = XMLHelper.Delete(Const.Root_ConfigFile_FullPath, string.Format(XMLFileInfo.XPath, tabContainer.SelectedTab.Name)); if (result.Status == true) { string filePath = string.Format(Const.Tool_ConfigFile_FullPath_Format, tabContainer.SelectedTab.Name); if (File.Exists(filePath)) { File.Delete(filePath); } LoadAllPageContent(); } else { MessageBox.Show(result.ResultDescription); } } } private void menuPast_Click(object sender, EventArgs e) { if (Clipboard.ContainsData(typeof(ToolInfo).FullName)) { this.menuPast.Enabled = true; ToolInfo tool = (ToolInfo)Clipboard.GetData(typeof(ToolInfo).FullName); TabPage tab = this.contextMenuStrip2.SourceControl as TabPage; if (tab != null) { XMLFileInfo xmlFileInfo = new XMLFileInfo(tab.Text); tab.Controls[0].Controls.Add(new Sunny.Assistant.BaseForm.ShortCuts(tool, xmlFileInfo, true)); TabPageTemplate tbTemplate = tab.Controls[0] as TabPageTemplate; if (tbTemplate != null) { tbTemplate.AddShortCutsToUI(tool); } } } else { this.menuPast.Enabled = false; } } #endregion private void ShowWindow() { this.Show(); User32.SetWindowPos(this.Handle.ToInt32(), (int)User32.SetWindowPosFlags1.HWND_TOP, 0, 0, 0, 0, (uint)User32.SetWindowPosFlags2.SWP_NOSIZE | (uint)User32.SetWindowPosFlags2.SWP_NOMOVE); this.Activate(); } private void HideWindow() { this.Hide(); } private void SetSelectTab(bool isAfterward) { int currentSelectIndex = tabContainer.SelectedIndex; int nextSelectIndex = currentSelectIndex; if (isAfterward) { nextSelectIndex += 1; } else { nextSelectIndex -= 1; if (nextSelectIndex < 0) { nextSelectIndex += tabContainer.TabCount; } } nextSelectIndex = nextSelectIndex % tabContainer.TabCount; this.tabContainer.SelectTab(nextSelectIndex); } private void MySelectNextControl(bool isAfterward = true) { TabPageTemplate tab = this.tabContainer.SelectedTab.Controls[0] as TabPageTemplate; if (tab != null) { tab.SelectNextControl(tab.ActiveControl, isAfterward, true, true, true); } } private void RunTool() { TabPageTemplate tab = this.tabContainer.SelectedTab.Controls[0] as TabPageTemplate; if (tab != null) { ShortCuts sc = tab.ActiveControl as ShortCuts; if (sc != null) { sc.Run(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataCenter.Data { public class Event { // Numbers data public Dictionary<string, _ProductData> ProductsDatas { get; set; } public Dictionary<string, _WeatherData> WeatherDatas { get; set; } public Dictionary<string, _ForexData> ForexDatas { get; set; } public Dictionary<string, _GoogleData> GoogleDatas { get; set; } public Dictionary<string, _WikiTrendsData> WikiTrendsDatas { get; set; } public Dictionary<string, _FuturesData> FuturesDatas { get; set; } public Dictionary<string, _FundamentalsData> FundamentalsData { get; set; } public Event(List<Product> products) { ProductsDatas = new Dictionary<string, _ProductData>(); foreach (Product p in products) ProductsDatas.Add(p.Symbol, new _ProductData()); WeatherDatas = new Dictionary<string, _WeatherData>(); ForexDatas = new Dictionary<string, _ForexData>(); GoogleDatas = new Dictionary<string, _GoogleData>(); WikiTrendsDatas = new Dictionary<string, _WikiTrendsData>(); FuturesDatas = new Dictionary<string, _FuturesData>(); FundamentalsData = new Dictionary<string, _FundamentalsData>(); } } }
using System; namespace RememberMyTrip.Core { public class Trip { public Guid Id { get; set; } public Address From {get;set;} public Address To {get;set;} public long? OdometerStart { get; set; } public long? OdometerFinish { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OOP_LAB1 { class Program { static void Main(string[] args) { double a = 20; double b = 60; double arif, geom; arif = (a + b) / 2; geom = Math.Sqrt(a * b); Console.WriteLine("Среднее арифметическое из {0} и {1} = {2}", a, b, arif); Console.WriteLine("Среднее геометрическое из {0} и {1} = {2}", a, b, geom); Console.WriteLine("Разница между данными средним арифметическим и геометрическим = {0} ", arif-geom); Console.ReadKey(); } } }
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 System.Data.SqlClient; namespace Kørselslogbog { public partial class Opret : Form { SqlConnection con = new SqlConnection("Data Source=WIN-3755O2PKQ95;Initial Catalog=KØRSELSLOGBOG;Integrated Security=True"); public Opret() { InitializeComponent(); } private void button2_Click(object sender, EventArgs e) { this.Hide(); Form_Chauffør opret = new Form_Chauffør(); opret.Show(); } private void b_KMINPUT_Click(object sender, EventArgs e) { this.Hide(); KM_Input km = new KM_Input(); km.Show(); } private void button1_Click(object sender, EventArgs e) { this.Close(); } private void b_UDTRÆK_Click(object sender, EventArgs e) { this.Hide(); Form_udtræk fu = new Form_udtræk(); fu.Show(); } private void b_RETTE_Click(object sender, EventArgs e) { this.Hide(); Form_bil bil = new Form_bil(); bil.Show(); } private void pictureBox1_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } } }
using System; namespace Arrays { class Program { static void Main() { var numberOfElements = int.Parse(Console.ReadLine()); var numbers = new int[numberOfElements]; //saving values for (int i = 0; i < numbers.Length; i++) { numbers[i] = i + 1; } //reading values foreach (var number in numbers) { Console.WriteLine(number); } } } }
using System; using System.Data.Entity; using System.Linq; using System.Linq.Expressions; using AtmDb.Data; using StudentSystem.Data.Repositories; namespace AtmDb.ConsoleClient.Repositories { class GenericRepository<T> : IGenericRepository<T> where T : class { private IAtmDbContext dbContext; public GenericRepository(IAtmDbContext atmDbContext) { this.dbContext = atmDbContext; } public GenericRepository() : this(new AtmDbContext()) { } public IQueryable<T> GetAll() { return this.dbContext.Set<T>(); } public IQueryable<T> Find(Expression<Func<T, bool>> expression) { return this.GetAll().Where(expression); } public void Add(T entry) { this.SetState(entry, EntityState.Added); } public T Remove(T entry) { this.SetState(entry, EntityState.Deleted); return entry; } public void Update(T entry) { this.SetState(entry, EntityState.Modified); } public void Detach(T entry) { this.SetState(entry, EntityState.Detached); } public void SaveChanges() { this.dbContext.SaveChanges(); } private void SetState(T entry, EntityState state) { this.dbContext.Set<T>().Attach(entry); this.dbContext.Entry(entry).State = state; } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game; using Triton.Game.Mono; [Attribute38("TurnStartManager")] public class TurnStartManager : MonoBehaviour { public TurnStartManager(IntPtr address) : this(address, "TurnStartManager") { } public TurnStartManager(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void BeginListeningForTurnEvents() { base.method_8("BeginListeningForTurnEvents", Array.Empty<object>()); } public void BeginPlayingTurnEvents() { base.method_8("BeginPlayingTurnEvents", Array.Empty<object>()); } public void DisplayTwoScoops() { base.method_8("DisplayTwoScoops", Array.Empty<object>()); } public static TurnStartManager Get() { return MonoClass.smethod_15<TurnStartManager>(TritonHs.MainAssemblyPath, "", "TurnStartManager", "Get", Array.Empty<object>()); } public List<Card> GetCardsToDraw() { Class267<Card> class2 = base.method_14<Class267<Card>>("GetCardsToDraw", Array.Empty<object>()); if (class2 != null) { return class2.method_25(); } return null; } public int GetNumCardsToDraw() { return base.method_11<int>("GetNumCardsToDraw", Array.Empty<object>()); } public SpellController GetSpellController() { return base.method_14<SpellController>("GetSpellController", Array.Empty<object>()); } public void HandleExhaustedChanges() { base.method_8("HandleExhaustedChanges", Array.Empty<object>()); } public bool HasActionsAfterCardDraw() { return base.method_11<bool>("HasActionsAfterCardDraw", Array.Empty<object>()); } public bool IsBlockingInput() { return base.method_11<bool>("IsBlockingInput", Array.Empty<object>()); } public bool IsCardDrawHandled(Card card) { object[] objArray1 = new object[] { card }; return base.method_11<bool>("IsCardDrawHandled", objArray1); } public bool IsListeningForTurnEvents() { return base.method_11<bool>("IsListeningForTurnEvents", Array.Empty<object>()); } public void NotifyOfCardDrawn(Triton.Game.Mapping.Entity drawnEntity) { object[] objArray1 = new object[] { drawnEntity }; base.method_8("NotifyOfCardDrawn", objArray1); } public void NotifyOfExhaustedChange(Card card, TagDelta tagChange) { object[] objArray1 = new object[] { card, tagChange }; base.method_8("NotifyOfExhaustedChange", objArray1); } public void NotifyOfManaCrystalFilled(int amount) { object[] objArray1 = new object[] { amount }; base.method_8("NotifyOfManaCrystalFilled", objArray1); } public void NotifyOfManaCrystalGained(int amount) { object[] objArray1 = new object[] { amount }; base.method_8("NotifyOfManaCrystalGained", objArray1); } public void NotifyOfSpellController(SpellController spellController) { object[] objArray1 = new object[] { spellController }; base.method_8("NotifyOfSpellController", objArray1); } public void NotifyOfTriggerVisual() { base.method_8("NotifyOfTriggerVisual", Array.Empty<object>()); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnGameOver(object userData) { object[] objArray1 = new object[] { userData }; base.method_8("OnGameOver", objArray1); } public bool m_blockingInput { get { return base.method_2<bool>("m_blockingInput"); } } public List<Card> m_cardsToDraw { get { Class267<Card> class2 = base.method_3<Class267<Card>>("m_cardsToDraw"); if (class2 != null) { return class2.method_25(); } return null; } } public List<CardChange> m_exhaustedChangesToHandle { get { Class267<CardChange> class2 = base.method_3<Class267<CardChange>>("m_exhaustedChangesToHandle"); if (class2 != null) { return class2.method_25(); } return null; } } public bool m_listeningForTurnEvents { get { return base.method_2<bool>("m_listeningForTurnEvents"); } } public int m_manaCrystalsFilled { get { return base.method_2<int>("m_manaCrystalsFilled"); } } public int m_manaCrystalsGained { get { return base.method_2<int>("m_manaCrystalsGained"); } } public SpellController m_spellController { get { return base.method_3<SpellController>("m_spellController"); } } public TurnStartIndicator m_turnStartInstance { get { return base.method_3<TurnStartIndicator>("m_turnStartInstance"); } } public TurnStartIndicator m_turnStartPrefab { get { return base.method_3<TurnStartIndicator>("m_turnStartPrefab"); } } public bool m_twoScoopsDisplayed { get { return base.method_2<bool>("m_twoScoopsDisplayed"); } } [Attribute38("TurnStartManager.CardChange")] public class CardChange : MonoClass { public CardChange(IntPtr address) : this(address, "CardChange") { } public CardChange(IntPtr address, string className) : base(address, className) { } public Card m_card { get { return base.method_3<Card>("m_card"); } } public TagDelta m_tagDelta { get { return base.method_3<TagDelta>("m_tagDelta"); } } } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; using EasySteamLeaderboard; public class ESL_LeaderboardEntryUI : MonoBehaviour { //ase public Text RankText; public Text PlayerNameText; public Text ScoreText; public GameObject Usuario; public GameObject borde; public void Update() { if(Usuario == null) { Usuario = GameObject.Find("UserRank"); }else { if(Usuario.GetComponent<Text>().text == RankText.text && gameObject.name != "YourEntry") { borde.SetActive(true); } } } public void Initialize(ESL_LeaderboardEntry entry) { if (entry == null) { Reset(); return; } PlayerNameText.text = entry.PlayerName; RankText.text = entry.GlobalRank.ToString(); ScoreText.text = entry.Score; } public void Initialize(string pname, int rank, string score) { PlayerNameText.text = pname; RankText.text = rank.ToString(); ScoreText.text = score; } public void Reset() { RankText.text = "-"; PlayerNameText.text = "-"; ScoreText.text = "-"; } }
using MvvmCross.Platform.Converters; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; using System.IO; using UIKit; using Foundation; using EsMo.Common.UI; namespace EsMo.MvvmCross.iOS.Support.Converter { public abstract class Converter : MvxValueConverter { public static readonly StreamUIImageConverter StreamToUIImage = new StreamUIImageConverter(); public static readonly UIColorConverter ColorToUIColor = new UIColorConverter(); } public class StreamUIImageConverter : MvxValueConverter { public override object Convert(object value, Type targetType=null, object parameter = null, CultureInfo culture = null) { Stream stream = value as Stream; if (stream != null) { UIImage image = UIImage.LoadFromData(NSData.FromStream(stream), 1); return image; } return null; } public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return base.ConvertBack(value, targetType, parameter, culture); } } public class UIColorConverter : MvxValueConverter { public override object Convert(object value, Type targetType = null, object parameter = null, CultureInfo culture = null) { Color color = value as Color; if (color != null) { return UIColor.FromRGBA(color.R, color.G, color.B, color.A); } return null; } public override object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return base.ConvertBack(value, targetType, parameter, culture); } } }
using System; namespace BusinessRuleEngine { public class BookRule : PackingSlipRule { public override void Pay() { Console.WriteLine("generating duplicate packing slip for royalty department"); GenerateAgentCommision(); } } }
using ApplicationApp.Interfaces; using Entities.Entities; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Exabyteshop.Controllers { public class MontaMenu : BaseController { private readonly InterfaceMontaMenu _InterfaceMontaMenu; public MontaMenu(UserManager<Usuario> userManager, ILogger<ProdutosController> logger, InterfaceLogSistemaApp InterfaceLogSistemaApp, InterfaceMontaMenu InterfaceMontaMenu) : base(logger, userManager, InterfaceLogSistemaApp) { _InterfaceMontaMenu = InterfaceMontaMenu; } [AllowAnonymous] [HttpGet("/api/ListarMenu")] public async Task<IActionResult> ListarMenu() { var listaMenu = new List<MenuSite>(); var usuario = await RetornarIdUsuarioLogado(); listaMenu = await _InterfaceMontaMenu.MontaMenuPorPerfil(usuario); return Json(new { listaMenu }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace transGraph { public partial class editWay : Form { dbFacade db = new dbFacade(); string id; public editWay(string id) { this.id = id; InitializeComponent(); DataTable data = db.FetchAllSql("SELECT title FROM regs"); foreach (DataRow rr in data.Rows) { comboBox1.Items.Add(rr[0]); } data = db.FetchAllSql("SELECT title,reg FROM ways WHERE id = '" + this.id + "'"); try { this.textBox1.Text = data.Rows[0][0].ToString(); this.comboBox1.SelectedItem = data.Rows[0][1].ToString(); } catch (Exception) { } } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click(object sender, EventArgs e) { string reg = ""; try { DataTable data = db.FetchAllSql("SELECT id FROM regs WHERE title = '" + this.comboBox1.SelectedItem.ToString() + "'"); reg = data.Rows[0][0].ToString(); } catch (Exception) { } try { db.FetchAllSql("UPDATE `ways` SET `title` = '" + Convert.ToString(this.textBox1.Text) + "',`reg` = '" + reg + "' WHERE id = '" + Convert.ToString(this.id) + "'"); this.Close(); } catch (Exception) { MessageBox.Show("Ошибка при записи БД! Неверные значения!"); } } } }
using System.Threading.Tasks; using Meziantou.Analyzer.Rules; using TestHelper; using Xunit; namespace Meziantou.Analyzer.Test.Rules; public sealed class EventsShouldHaveProperArgumentsAnalyzerTests { private static ProjectBuilder CreateProjectBuilder() { return new ProjectBuilder() .WithAnalyzer<EventsShouldHaveProperArgumentsAnalyzer>(); } [Fact] public async Task InvalidArguments_InstanceEvent_ConditionalAccess() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent?.Invoke([|null|], EventArgs.Empty); } }"; const string Fix = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent?.Invoke(this, EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .WithCodeFixProvider<EventsShouldHaveProperArgumentsFixer>() .ShouldFixCodeWith(Fix) .ValidateAsync(); } [Fact] public async Task ValidArguments_InstanceEvent() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke(this, EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task InvalidSender_Instance() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke([|null|], EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task InvalidSender_Static() { const string SourceCode = @" using System; class Test { public static event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke([|this|], EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .ValidateAsync(); } [Fact] public async Task InvalidEventArgs() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke(this, [|null|]); } }"; const string Fix = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke(this, EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .WithCodeFixProvider<UseEventArgsEmptyFixer>() .ShouldFixCodeWith(Fix) .ValidateAsync(); } [Fact] public async Task InvalidEventArgs_NamedArgument() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke(this, e: [|null|]); } }"; const string Fix = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { MyEvent.Invoke(this, e: EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .WithCodeFixProvider<UseEventArgsEmptyFixer>() .ShouldFixCodeWith(Fix) .ValidateAsync(); } [Fact] public async Task EventIsStoredInVariable() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { var ev = MyEvent; if (ev != null) { ev.Invoke(this, [|null|]); } } }"; const string Fix = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { var ev = MyEvent; if (ev != null) { ev.Invoke(this, EventArgs.Empty); } } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .WithCodeFixProvider<UseEventArgsEmptyFixer>() .ShouldFixCodeWith(Fix) .ValidateAsync(); } [Fact] public async Task EventIsStoredInVariableInVariable() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { var a = MyEvent; var ev = a; if (ev != null) { ev.Invoke(this, [|null|]); } } }"; const string Fix = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { var a = MyEvent; var ev = a; if (ev != null) { ev.Invoke(this, EventArgs.Empty); } } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .WithCodeFixProvider<UseEventArgsEmptyFixer>() .ShouldFixCodeWith(Fix) .ValidateAsync(); } [Fact] public async Task EventIsStoredInVariableAndConditionalAccess() { const string SourceCode = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { var ev = MyEvent; ev?.Invoke(this, [|null|]); } }"; const string Fix = @" using System; class Test { public event EventHandler MyEvent; void OnEvent() { var ev = MyEvent; ev?.Invoke(this, EventArgs.Empty); } }"; await CreateProjectBuilder() .WithSourceCode(SourceCode) .WithCodeFixProvider<UseEventArgsEmptyFixer>() .ShouldFixCodeWith(Fix) .ValidateAsync(); } }
namespace CharacterWizardRepository.Models { public class Skills { public int Id { get; set; } public int CharacterId { get; set; } public Skill Skill { get; set; } public bool HasProficiency { get; set; } public bool HasExpertise { get; set; } public bool HasBonus { get; set; } public int Bonus { get; set; } } }
using DiagnostivoTecnicoBasico.Model.ResponseAPI; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace MS_DiagnosticoTecnicoBasico.Domain.Constants { public static class Constants { private static int seed = Environment.TickCount; private static Random r = new Random(seed); public static string GenerarIdUnicoDiagnostico() { string idUnico = DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + DateTime.Now.Day.ToString().PadLeft(2, '0') + DateTime.Now.Hour.ToString().PadLeft(2, '0') + DateTime.Now.Minute.ToString().PadLeft(2, '0') + DateTime.Now.Second.ToString().PadLeft(2, '0') + r.Next(0001, 9999).ToString().PadLeft(4, '0') + r.Next(0001, 9999).ToString().PadLeft(4, '0'); return idUnico; } public static Response MapResponseDataMock() { return new Response() { client = new Client() { id = 125412, name = "Jose", lastName = "Argento", addressId = 41213, telephone = "1598765432", mail = "jose_argento@gmail.com", addresses = new List<Address>() { new Address() { address = "Viamonte 2273", addressId = 1232, city = "Monte Grande", state = "Buenos Aires", selected = true }, new Address() { address = "Rodriguez Peña 223", addressId = 1233, city = "Villa Adelina", state = "Buenos Aires", selected = false } } }, products = new List<DiagnostivoTecnicoBasico.Model.ResponseAPI.Product>() { new DiagnostivoTecnicoBasico.Model.ResponseAPI.Product() { id = 154360760, name = "toip_free_calls", label = "Fija", type = "telefoniaFija", code = "0", codeStatus = "OK", descriptionCode = "Sin problemas", components = new List<Component>() { new Component() { code = "0", codeStatus = "OK", name = "toip_huawei_h_D7583_v3", label = "(011) 4968-7200", details = new List<Detail>() { new Detail(){ label = "Línea", value = "11 4968-7200" }, new Detail(){ label = "IMSI", value = "552152729" }, new Detail(){ label = "Roaming", value = "No" } }, workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Diagnóstico de Telefonía", name = "nombre_smp_1", link = "https://webgestionmoviltesting/Consultas_Modem_HDM.aspx?signed=true&legajo=wdi585714" }, } } } }, new DiagnostivoTecnicoBasico.Model.ResponseAPI.Product() { id = 14213171, name = "TV POR CABLE", label = "TV POR CABLE", type = "video", code = "0", codeStatus = "OK", descriptionCode = "Sin problemas", components = new List<Component>() { new Component() { code = "0", codeStatus = "OK", name = "tv_flow_hd_pack_plus", label = "Flow", details = new List<Detail>() { new Detail(){ label = "MAC", value = "00:1d:e5:55:1e:0a" }, new Detail(){ label = "Serial", value = "552152729" }, new Detail(){ label = "Port", value = "u2/w2" }, new Detail(){ label = "US", value = ""} }, workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Administracion de Flow", name = "nombre_smp_1", link = "https://webgestionmoviltesting/Consultas_Modem_HDM.aspx?signed=true&legajo=wdi585714" }, } }, new Component() { code = "0", codeStatus = "OK", name = "app_flow_hd_pack_plus", label = "Flow App", details = new List<Detail>() { new Detail(){ label = "MAC", value = "00:1d:e5:55:1e:0a" }, new Detail(){ label = "Serial", value = "552152729" }, new Detail(){ label = "Port", value = "u2/w2" }, new Detail(){ label = "US", value = ""} }, workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Administracion de Flow App", name = "nombre_smp_1", link = "https://webgestionmoviltesting/Consultas_Modem_HDM.aspx?signed=true&legajo=wdi585714" }, } } } }, new DiagnostivoTecnicoBasico.Model.ResponseAPI.Product() { id = 229106272, name = "internet_adsl_10mbps", label = "INTERNET", type = "internet", code = "0", codeStatus = "OK", descriptionCode = "Sin problemas", components = new List<Component>() { new Component() { code = "0", codeStatus = "OK", label = "Sagem G372547", name = "sagem_g_372547_v45", details = new List<Detail>() { new Detail(){ label = "MAC", value = "??:??:??:??:??" }, new Detail(){ label = "Serial", value = "M61410IA2425" }, new Detail(){ label = "Config", value = "config_xxxxxxx.cm" }, new Detail(){ label = "Ver HW", value = "2"}, new Detail(){ label = "CM Status", value = "Registered" }, new Detail(){ label = "Port US", value = "3/3" }, }, workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Administración de Firmware", name = "nombre_smp_1", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=HC-CPEWifiOptimize" }, new WorkFlow() { label = "Flujo de Resolución de Problemas STBIP (automático)", name = "nombre_smp_2", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=HC-CPEWifiOptimize" }, new WorkFlow() { label = "Reinicio", name = "nombre_smp_3", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=HC-CPEWifiOptimize" }, new WorkFlow() { label = "Reinicio a valores de fábrica", name = "nombre_smp_4", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=HC-CPEWifiOptimize" }, new WorkFlow() { label = "Información General", name = "nombre_smp_5", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=HC-CPEWifiOptimize" }, new WorkFlow() { label = "STBIP_troubleshoooting", name = "nombre_smp_6", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=STBIP_troubleshooting" }, new WorkFlow() { label = "Test de Velocidad", name = "nombre_smp_7", link = "https://portaldiagnosticouat.telecom.com.ar/SpeedTest.html" } } }, new Component() { code = "0", codeStatus = "OK", label = "Huawei HG8245U", name = "huawei_HG8245U", details = new List<Detail>() { new Detail(){ label = "MAC", value = "00:1d:d5:69:1e:08" }, new Detail(){ label = "Serial", value = "434234434" }, new Detail(){ label = "Config", value = "d11_2g3848v2.cm" }, new Detail(){ label = "Ver HW", value = "2" }, new Detail(){ label = "Estado CM", value = "Registrado" }, new Detail(){ label = "Port US", value = "3/3" }, }, workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Administración de Huawei", name = "nombre_smp_1", link = "https://webgestionmoviltesting/consulta_WF.aspx?signed=true&legajo=wdi585714&wf=HC-CPEWifiOptimize" } } }, new Component() { code = "0", codeStatus = "OK", label = "WIFI", name = "wifi", workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Administración de WIFI", name = "nombre_smp_1", link = "https://webgestionmoviltesting/Consultas_Modem_HDM.aspx?signed=true&legajo=wdi585714" } } } } }, new DiagnostivoTecnicoBasico.Model.ResponseAPI.Product() { id = 154360760, name = "movil_3g", label = "Móvil", type = "telefoniaMovil", code = "0", codeStatus = "OK", descriptionCode = "Sin problemas", components = new List<Component>() { new Component() { code = "0", codeStatus = "OK", name = "motorola_one_3857", label = "(15) 6859-1445", details = new List<Detail>() { new Detail(){ label = "Línea", value = "011 5555-7200" }, new Detail(){ label = "IMSI", value = "775664388859" }, }, workFlows = new List<WorkFlow>() { new WorkFlow() { label = "Inconvenientes servicio de Datos", name = "nombre_smp_1", link = "https://webgestionmoviltesting/Signed_Request.aspx?signed_request=tGkQ3mrOvtEYhTFx26ylS0INCWQDgXw4qsTmo/5GmeM=.eyJucm9DYXNvU1QiOiIxMTY4NSIsIm51bWVyb0xpbmVhIjoiMTE2ODU5MTQ0NSIsImxlZ2FqbyI6IndkaTUwMDAwMCIsImNvZFNlcnZpY2lvIjoiZGF0b3MiLCJtb3Rpdm9Db250YWN0byI6IkluY29udmVuaWVudGVzIHNlcnZpY2lvIGRlIGRhdG9zIiwibHN0U1ZBIjpudWxsfQ==" }, new WorkFlow() { label = "Inconvenientes servicio de Voz", name = "nombre_smp_2", link = "https://webgestionmoviltesting/Signed_Request.aspx?signed_request=eKJKSG6HFx4Hyzuu7kGC1QRp3bjvoZTy0I0frDpC0BM=.eyJucm9DYXNvU1QiOiIxMTY4NSIsIm51bWVyb0xpbmVhIjoiMTE2ODU5MTQ0NSIsImxlZ2FqbyI6IndkaTUwMDAwMCIsImNvZFNlcnZpY2lvIjoicm9hbWluZyIsIm1vdGl2b0NvbnRhY3RvIjoiSW5jb252ZW5pZW50ZXMgc2VydmljaW8gZGUgdm96IiwibHN0U1ZBIjpudWxsfQ==" }, new WorkFlow() { label = "Inconvenientes servicio de Roaming", name = "nombre_smp_3", link = "https://webgestionmoviltesting/Signed_Request.aspx?signed_request=6bIN9ZjGMt3jMgIba2f5SkWlEccdArb/PGmK3zopGAk=.eyJucm9DYXNvU1QiOiIxMTY4NSIsIm51bWVyb0xpbmVhIjoiMTE2ODU5MTQ0NSIsImxlZ2FqbyI6IndkaTUwMDAwMCIsImNvZFNlcnZpY2lvIjoicm9hbWluZyIsIm1vdGl2b0NvbnRhY3RvIjoiSW5jb252ZW5pZW50ZXMgc2VydmljaW8gZGUgUm9hbWluZyIsImxzdFNWQSI6bnVsbH0=" }, new WorkFlow() { label = "Inconvenientes con SVA", name = "nombre_smp_4", link = "https://webgestionmoviltesting/Signed_Request.aspx?signed_request=ynlOyHDuLUxHNJI3lScM/ABOJ/pry8ZW51nNBh/vkhI=.eyJucm9DYXNvU1QiOiIxMTY4NSIsIm51bWVyb0xpbmVhIjoiMTE2ODU5MTQ0NSIsImxlZ2FqbyI6IndkaTUwMDAwMCIsImNvZFNlcnZpY2lvIjoic3ZhIiwibW90aXZvQ29udGFjdG8iOiJJbmNvbnZlbmllbnRlcyBjb24gU1ZBIiwibHN0U1ZBIjpudWxsfQ==" }, } } } }, } }; } public static string urlConsulta = "http://apicore31-pdd-portaldiagnostico-dev.apps-rp.cloudteco.com.ar/swagger"; public static string urlOpen = "http://esbp.corp.cablevision.com.ar:8000/customerManagement/"; public static string urlInfomracionComercial = "https://localhost:44312/api/client/"; } }
namespace Hik.Sps { /// <summary> /// This interface is implemented all plugins. /// PlugIns does not directly implement this interface, but they implement by inheriting PlugIn class. /// </summary> public interface IPlugIn : IPluggable { /// <summary> /// Name of the plugin. /// </summary> string Name { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ControlValveMaintenance.Services; using System.Windows.Media; using System.Windows.Media.Imaging; using WpfAnimatedGif; using ControlValveMaintenance.Models; using GalaSoft.MvvmLight.Messaging; namespace ControlValveMaintenance.ViewModels { class SyncViewModel : BaseViewModel { #region variables // CLASS VARIABLES private SiteDataService dataService; #endregion /// <summary> /// DEFAULT CONSTRUCTOR /// </summary> public SyncViewModel( ) { dataService = new SiteDataService(); } /// <summary> /// use the dataservice to sync the View Model /// </summary> public void syncRoutine() { dataService.syncAll(); // Use lookup tables StatusCodesService cs = new StatusCodesService(); MaintTypeDataService types = new MaintTypeDataService(); cs.getStatusCodes(); types.getMaintTypes(); // switch back to previous view model var page = new PageMessage() { Name = "Switch back to previous VM"}; Messenger.Default.Send<PageMessage>(page); } } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Globalization; using NuGet.Versioning; namespace NuGet.Protocol.Core.v3.DependencyInfo { internal class PackageInfo { public RegistrationInfo Registration { get; set; } public bool Listed { get; set; } public NuGetVersion Version { get; set; } public Uri PackageContent { get; set; } public IList<DependencyInfo> Dependencies { get; private set; } public PackageInfo() { Dependencies = new List<DependencyInfo>(); } public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "{0} {1}", Registration.Id, Version.ToNormalizedString()); } } }
using Catalog.API.Entities; using System.Collections.Generic; using System.Threading.Tasks; namespace Catalog.API.Repositories.Interfaces { public interface IProductRepository : IRepository<Product> { Task<IEnumerable<Product>> getProductByCategory(string category); } }
using MMLib.Extensions; using Payroll.Common; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq.Expressions; namespace Payroll.Models { public class Company : Addressable { [Display(ResourceType = typeof(Resource), Name = "PersonalJuridicalName")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public string PersonalJuridicalName { get; set; } [Display(ResourceType = typeof(Resource), Name = "SocialReason")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public string SocialReason { get; set; } [Display(ResourceType = typeof(Resource), Name = "OccupationArea")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public string OccupationArea { get; set; } [Display(ResourceType = typeof(Resource), Name = "FoundationDate")] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = "RequiredField")] public DateTime? FoundationDate { get; set; } [Display(ResourceType = typeof(Resource), Name = nameof(Nacionality))] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = nameof(Resource.RequiredField))] public string Nacionality { get; set; } [Display(ResourceType = typeof(Resource), Name = nameof(HasStrangers))] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = nameof(Resource.RequiredField))] public bool HasStrangers { get; set; } [Display(ResourceType = typeof(Resource), Name = nameof(Currency))] [Required(ErrorMessageResourceType = typeof(Resource), ErrorMessageResourceName = nameof(Resource.RequiredField))] public Guid CurrencyId { get; set; } [ForeignKey(nameof(CurrencyId))] public virtual Currency PaymentCurrency { get; set; } public virtual IEnumerable<Workplace> Workplaces { get; set; } public virtual IEnumerable<JobRole> JobRoles { get; set; } public virtual IEnumerable<Department> Departments { get; set; } } }
using ReadyGamerOne.EditorExtension; using ReadyGamerOne.Utility; using UnityEditor; using UnityEngine; namespace DialogSystem.Model.Editor { [CustomPropertyDrawer(typeof(SkipChoice))] public class SkipChoiceDrawer:PropertyDrawer { public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 4 * EditorGUIUtility.singleLineHeight; } public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var index = 0; var r = position.GetRectAtIndex(index++); EditorGUI.LabelField(r.GetLeft(.4f),"enable"); var enableProp = property.FindPropertyRelative("enable"); EditorGUI.PropertyField(r.GetRight(0.6f), enableProp); if(ValueChooser.GetArgType(property.FindPropertyRelative("enable"))!=ArgType.Bool) EditorGUILayout.HelpBox("这里必须为Bool类型",MessageType.Error); var text = property.FindPropertyRelative("text"); var targetDialogInfoAssetProp = property.FindPropertyRelative("targetDialogInfoAsset"); EditorGUI.PropertyField(position.GetRectAtIndex(index++), text); EditorGUI.PropertyField(position.GetRectAtIndex(index++), targetDialogInfoAssetProp); EditorGUI.PropertyField(position.GetRectAtIndex(index++), property.FindPropertyRelative("willBack")); } } }
using UnityEngine; using System.Collections; public class AlleySprites : MonoBehaviour { private Animator animator; private GameObject otherEnd; void Start () { animator = GetComponent<Animator>(); otherEnd = GetComponent<Alley>().otherEnd; Vector3 offset = otherEnd.transform.position - transform.position; float angle = Vector3.Angle(offset, transform.right); if (offset.z < 0) { angle = 360 - angle; } animator.SetFloat("angle", angle); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Baloncontroller : MonoBehaviour { public GameObject patlama; GameController gameControllerS; private void Start() { gameControllerS = GameObject.Find("GameObject").GetComponent<GameController>(); } void OnMouseDown() { GameObject go = Instantiate(patlama, transform.position, transform.rotation) as GameObject; Destroy(this.gameObject); Destroy(go,0.333f); gameControllerS.BalonEkle(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNet.Mvc; using runnertrails.Models; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace runnertrails.Controllers { [Route("api/[controller]")] public class RunnersController : Controller { // GET: api/values [HttpGet] public Runner[] Get() { var runners = new List<Runner>(); runners.Add(new Runner() {Id=1,First="Matthew",Last="Baskey", Age=44,FavoriteBeer="Pabst"}); runners.Add(new Runner() {Id=2,First="Joe",Last="Baskey", Age=23,FavoriteBeer="guniess"}); runners.Add(new Runner() {Id=3,First="Butch",Last="Baskey", Age=33,FavoriteBeer="pilsner"}); // return new string[] { "value1", "value2" }; // dsfgsdfg return runners.ToArray(); } // GET api/values/5 [HttpGet("{id}")] public Runner Get(int id) { return Get().Where(r=>r.Id==id).FirstOrDefault(); } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
using System; using System.Collections.Generic; namespace Zhouli.DbEntity.Models { public partial class BlogArticleDto { public int ArticleId { get; set; } public string ArticleTitle { get; set; } public string ArticleThrink { get; set; } public string ArticleBodySummary { get; set; } public string ArticleBody { get; set; } public int ArticleSortValue { get; set; } public bool ArticleTop { set; get; } = false; public DateTime CreateTime { get; set; } public string CreateUser { set; get; } public string Note { get; set; } public int[] LableId { set; get; } public string[] LableName { set; get; } public int ArticleBrowsingNum { set; get; } public int ArticleCommentNum { set; get; } public int ArticleLikeNum { set; get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RomperCaguama2 : MonoBehaviour { public Image Caguama2; public GameObject CaguamaRota2; //public Image CaguamaRota2; void Start() { Caguama2 = GetComponent<Image>(); if (Vida._vida == 1) { CaguamaRota2.SetActive(true); Caguama2.enabled = false; } } }
namespace Strategy { interface IOperacion { double RealizarOperacion(double a, double b); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Photoshop.Common { public class MainConfiguration : BaseConfiguration { public static string DatabaseConnection {get; private set;} static MainConfiguration() { DatabaseConnection = ReadConnectionString("Mongo"); } } }
namespace SFA.DAS.Notifications.Domain.Entities { public enum NotificationFormat { Email = 0, Sms } }