text
stringlengths
13
6.01M
using System; using UnityEngine; using UnityEngine.UI; namespace _Internal { public class ToggleAnimator : MonoBehaviour { private float f; private Toggle toggle; public Image Icon, Circle; public Color backgroundColor, white, dark, transparent; private void Awake() { toggle = GetComponentInParent<Toggle>(); } private void Update() { if (toggle.isOn) { f += Time.deltaTime * 5; } else { f -= Time.deltaTime * 5; } f = Mathf.Clamp01(f); Circle.color = Color.Lerp(transparent, dark, f); Icon.color = Color.Lerp(white, backgroundColor, f); Icon.transform.rotation = Quaternion.Lerp(Quaternion.identity, Quaternion.Euler(0, 0, 90), f); } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace C9Native { /// <summary> /// RAII get information on all display monitors that this system knows about. /// </summary> // ReSharper disable once UnusedMember.Global public class DisplayMonitors { // Store list of monitors we have information on. private readonly List<DisplayMonitor> _monitors = new(); /// <summary> /// Retrieve the information about one of the monitors we know about. /// </summary> /// <param name="index">Which item do we want information on.</param> /// <returns>Immutable block of information on this monitor.</returns> public DisplayMonitor this[int index] => _monitors[index]; /// <summary> /// Return the number of monitors that we have information on. /// </summary> public int Count => _monitors.Count; /// <summary> /// RAII enumerate available monitors on this system and make their information available. /// </summary> public DisplayMonitors() { // ReSharper disable once UnusedVariable var result = EnumDisplayMonitors(IntPtr.Zero, IntPtr.Zero, // ReSharper disable once IdentifierTypo delegate(IntPtr hMonitor, IntPtr _, ref Rect _, IntPtr _) { MonitorInfoEx informationRaw = new MonitorInfoEx(); informationRaw.Size = Marshal.SizeOf(informationRaw); bool success = GetMonitorInfo(hMonitor, ref informationRaw); if (success) { var screen = new DisplayRectangle(informationRaw.Monitor.left, informationRaw.Monitor.top, informationRaw.Monitor.right, informationRaw.Monitor.bottom); var working = new DisplayRectangle(informationRaw.Work.left, informationRaw.Work.top, informationRaw.Work.right, informationRaw.Work.bottom); // Check the primary monitor flag. bool primary = (informationRaw.Flags & MonitorInformationPrimary) != 0; // Assemble the immutable monitor information that we'll provide to external clients. var information = new DisplayMonitor(hMonitor, screen, working, primary, informationRaw.DeviceName); _monitors.Add(information); } return true; },IntPtr.Zero); } [DllImport("user32.dll", CharSet = CharSet.Auto)] // ReSharper disable once IdentifierTypo private static extern bool GetMonitorInfo(IntPtr hMonitor, ref MonitorInfoEx lpmi); // ReSharper disable once IdentifierTypo private delegate bool MonitorEnumDelegate(IntPtr hMonitor, IntPtr hdcMonitor, ref Rect lprcMonitor, IntPtr dwData); [DllImport("user32.dll")] private static extern bool EnumDisplayMonitors(IntPtr hdc, IntPtr clip, MonitorEnumDelegate enumerationDelegate, IntPtr dwData); [StructLayout(LayoutKind.Sequential)] private readonly struct Rect { public readonly int left; public readonly int top; public readonly int right; public readonly int bottom; } // size of a device name string // ReSharper disable once IdentifierTypo // ReSharper disable once InconsistentNaming private const int CCHDEVICENAME = 32; // Bit mask for MonitorInfEx flags indicating this monitor is the primary monitor. private const int MonitorInformationPrimary = 0x1; /// <summary> /// The MONITORINFOEX structure contains information about a display monitor. /// The GetMonitorInfo function stores information into a MONITORINFOEX structure or a MONITORINFO structure. /// The MONITORINFOEX structure is a superset of the MONITORINFO structure. The MONITORINFOEX structure adds a string member to contain a name /// for the display monitor. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)] [SuppressMessage("ReSharper", "CommentTypo")] private struct MonitorInfoEx { /// <summary> /// The size, in bytes, of the structure. Set this member to sizeof(MONITORINFOEX) (72) before calling the GetMonitorInfo function. /// Doing so lets the function determine the type of structure you are passing to it. /// </summary> public int Size; /// <summary> /// A RECT structure that specifies the display monitor rectangle, expressed in virtual-screen coordinates. /// Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values. /// </summary> public readonly Rect Monitor; /// <summary> /// A RECT structure that specifies the work area rectangle of the display monitor that can be used by applications, /// expressed in virtual-screen coordinates. Windows uses this rectangle to maximize an application on the monitor. /// The rest of the area in rcMonitor contains system windows such as the task bar and side bars. /// Note that if the monitor is not the primary display monitor, some of the rectangle's coordinates may be negative values. /// </summary> public readonly Rect Work; /// <summary> /// The attributes of the display monitor. /// /// This member can be the following value: /// 1 : MONITORINFOF_PRIMARY /// </summary> public readonly uint Flags; /// <summary> /// A string that specifies the device name of the monitor being used. Most applications have no use for a display monitor name, /// and so can save some bytes by using a MONITORINFO structure. /// </summary> [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCHDEVICENAME)] public string DeviceName; // ReSharper disable once UnusedMember.Global // ReSharper disable once UnusedMember.Local public void Init() { this.Size = 40 + 2 * CCHDEVICENAME; this.DeviceName = string.Empty; } } } }
namespace HotelReservationSystem.Migrations { using System; using System.Data.Entity.Migrations; public partial class rmfacilties1 : DbMigration { public override void Up() { RenameTable(name: "dbo.RoomFacilty", newName: "RoomFacility"); } public override void Down() { RenameTable(name: "dbo.RoomFacility", newName: "RoomFacilty"); } } }
using System; using UnityEngine; using UnityEngine.UI; public class UnlockedAbilityDisplay : MonoBehaviour { public void Init(Sprite sprite, Action onClick) { var image = GetComponent<Image>(); image.sprite = sprite; var button = GetComponent<Button>(); button.onClick.RemoveAllListeners(); button.onClick.AddListener(() => onClick?.Invoke()); } }
using System; using System.Collections; using System.Linq; namespace Print_Even_Numbers { class Program { static void Main(string[] args) { var input = Console.ReadLine() .Split() .Select(x => int.Parse(x)); var queue = new Queue(); foreach (var number in input) { if (number % 2 == 0) { queue.Enqueue(number); } } while (queue.Count > 0) { if (queue.Count == 1) { Console.Write(queue.Dequeue()); break; } Console.Write(queue.Dequeue() + ", "); } } } }
using OpenQA.Selenium; using Com.Test.SamuelOkunusi.Settings; namespace Com.Test.SamuelOkunusi.ComponentHelpers { public class NavigationHelper { public static readonly string ChromeSettingsURL = ObjectRepository.Config.ChromeSettingsUrl; public static void NavigateToUrl(string URL) { ObjectRepository.Driver.Navigate().GoToUrl(URL); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Playables; public class SubtitleBehaviour : PlayableBehaviour { //public Subtitles subtitle; public string text; public override void ProcessFrame(Playable playable, FrameData info, object playerData) { Subtitles subtitle = playerData as Subtitles; if(subtitle != null) { subtitle.UpdateSub(text); } } }
using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using UnityEngine; using UnityEngine.PlayerLoop; public class WolfMoving : StateMachineBehaviour { Sheep target; Wolf_StateVars wolf_vars; Wolf wolf; bool triggered; bool waypoint_set; /** * Updates sheep objective */ public void update_sheep_obj(Animator animator) { if ((wolf_vars.move_to_pos - wolf.transform.position).sqrMagnitude < wolf_vars.near_dest * wolf_vars.near_dest) { //TODAVIA NO if (wolf_vars.current_chasing_sheep != null) { wolf_vars.current_chasing_sheep = null; } else { wolf_vars.move_to_pos = Instances.GetSheepWaveManager().getRandomWavepoint(); } } if (wolf_vars.current_chasing_sheep != null) { return; } /* Searches the nearest non-burning sheep */ Collider[] colliders = Physics.OverlapSphere (wolf.transform.position, wolf_vars.sheep_detect_range, wolf_vars.sheep_mask); int i = 0; for (; i < colliders.Length;++i) { AnimatorStateInfo state_info = colliders[i].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0); if (!state_info.IsName("EffectFire")) { break; } } /* If there's a sheep within range, chases it. If it's not, goes to a random waypoint */ if (i < colliders.Length) { wolf_vars.move_to_pos = colliders[i].transform.position; wolf_vars.current_chasing_sheep = colliders[i].GetComponent<Sheep>(); } else { if (!waypoint_set) { Debug.Log("Waypoint set"); wolf_vars.move_to_pos = Instances.GetSheepWaveManager().getRandomClosest (wolf.transform.position); wolf_vars.current_chasing_sheep = null; waypoint_set = true; } } } public void check_near_sheeps() { Collider[] colliders = Physics.OverlapSphere ( wolf.transform.position , wolf_vars.sheep_eat_range , wolf_vars.sheep_mask ); foreach (var c in colliders) { Animator other_anim = c.GetComponent<Animator>(); /* The sheep manages its own death */ other_anim.SetTrigger ("Dead"); } } // OnStateEnter is called when a transition starts and the state machine starts to evaluate this state public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { wolf = animator.GetComponent<Wolf>(); wolf_vars = wolf.GetComponent<Wolf_StateVars>(); triggered = false; waypoint_set = false; } // OnStateUpdate is called on each Update frame between OnStateEnter and OnStateExit callbacks public override void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { update_sheep_obj (animator); check_near_sheeps (); wolf.MoveTo ( wolf_vars.move_to_pos, wolf_vars.wolf_vel, wolf_vars.wolf_max_force, wolf_vars.near_dest, 0, ForceMode.Acceleration ); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Linq; using System.Windows.Forms; using System.Reflection; using System.IO; using System.Configuration; using System.Threading; using DevExpress.XtraEditors; using DevExpress.XtraBars; using DevExpress.XtraBars.Helpers; using DevExpress.XtraBars.Ribbon; using IRAP.Global; using IRAP.Client.Global; using IRAP.Client.Global.GUI; using IRAP.Client.User; using IRAP.Client.SubSystem; using IRAP.Entity.SSO; using IRAP.WCF.Client.Method; using IRAP.Client.Global.Resources.Properties; namespace IRAP { public partial class frmIRAPMain : DevExpress.XtraBars.Ribbon.RibbonForm { private static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName; /// <summary> /// 关闭系统时是否需要询问 /// </summary> private bool isQuitSilent = false; private List<MenuInfo> menuInfos = new List<MenuInfo>(); private string message = ""; private string caption = ""; private Dictionary<string, string> skins = new Dictionary<string, string>(); public frmIRAPMain() { InitializeComponent(); skins.Add("DevExpress Style", "DevExpress Style"); skins.Add("DevExpress Dark Style", "DevExpress Dark Style"); skins.Add("Office 2016 Colorful", "Office 2016 Colorful"); skins.Add("Office 2016 Dark", "Office 2016 Dark"); skins.Add("Office 2013 White", "Office 2013"); skins.Add("Office 2013 Dark Gray", "Office 2013 Dark Gray"); skins.Add("Office 2013 Light Gray", "Office 2013 Light Gray"); skins.Add("Office 2010 Blue", "Office 2010 Blue"); skins.Add("Office 2010 Black", "Office 2010 Black"); skins.Add("Office 2010 Silver", "Office 2010 Silver"); skins.Add("Visual Studio 2013 Blue", "Visual Studio 2013 Blue"); skins.Add("Visual Studio 2013 Dark", "Visual Studio 2013 Dark"); skins.Add("Visual Studio 2013 Light", "Visual Studio 2013 Light"); skins.Add("Seven Classic", "Seven Classic"); skins.Add("Visual Studio 2010", "VS2010"); skins.Add("Black", "Black"); skins.Add("Blue", "Blue"); skins.Add("Caramel", "Caramel"); skins.Add("Coffee", "Coffee"); skins.Add("Dark Side", "Dark Side"); skins.Add("Darkroom", "Darkroom"); skins.Add("Foggy", "Foggy"); skins.Add("Glass Oceans", "Glass Oceans"); skins.Add("High Contrast", "High Contrast"); skins.Add("iMaginary", "iMaginary"); skins.Add("Lilian", "Lilian"); skins.Add("Liquid Sky", "Liquid Sky"); skins.Add("London Liquid Sky", "London Liquid Sky"); skins.Add("Metropolis", "Metropolis"); skins.Add("Metropolis Dark", "Metropolis Dark"); skins.Add("Money Twins", "Money Twins"); skins.Add("Office 2007 Black", "Office 2007 Black"); skins.Add("Office 2007 Blue", "Office 2007 Blue"); skins.Add("Office 2007 Green", "Office 2007 Green"); skins.Add("Office 2007 Pink", "Office 2007 Pink"); skins.Add("Office 2007 Silver", "Office 2007 Silver"); skins.Add("Seven", "Seven"); skins.Add("Sharp", "Sharp"); skins.Add("Sharp Plus", "Sharp Plus"); skins.Add("Stardust", "Stardust"); skins.Add("The Asphalt World", "The Asphalt World"); skins.Add("Pumpkin", "Pumpkin"); skins.Add("Springtime", "Springtime"); skins.Add("Summer", "Summer 2008"); skins.Add("Valentine", "Valentine"); skins.Add("Xmas (Blue)", "Xmas 2008 Blue"); skins.Add("McSkin", "McSkin"); skins.Add("Blueprint", "Blueprint"); skins.Add("Whiteprint", "Whiteprint"); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") caption = "System tip"; else caption = "系统信息"; string skinName = ""; skinName = IniFile.ReadString( "AppSetting", "Skin", "Blue", string.Format( @"{0}\IRAP.ini", AppDomain.CurrentDomain.SetupInformation.ApplicationBase)); defaultLookAndFeel.LookAndFeel.SetSkinStyle(skinName); } private RibbonPage GetRibbonPageWithItemID(int itemID) { foreach (RibbonPage page in ribbonControl.Pages) { if (((SystemMenuInfoMenuStyle)page.Tag).ItemID == itemID) { return page; } } return null; } private RibbonPageGroup GetRibbonPageGroupWithItemID(int itemID) { foreach (RibbonPage page in ribbonControl.Pages) { foreach (RibbonPageGroup group in page.Groups) { if (((SystemMenuInfoMenuStyle)group.Tag).ItemID == itemID) { return group; } } } return null; } private BarButtonItem GenerateRibbonMenuButton(MenuInfo menuInfo) { BarButtonItem menuItem = new BarButtonItem() { Caption = menuInfo.HotKey.Trim() == "" ? menuInfo.ItemText : string.Format( "{0}(&{1})", menuInfo.ItemText, menuInfo.HotKey), Tag = menuInfo, PaintStyle = BarItemPaintStyle.CaptionGlyph, Hint = menuInfo.MicroHelp, }; object pic = Resources.ResourceManager.GetObject(menuInfo.ToolBarIconFile); if (pic == null) { pic = Resources.ResourceManager.GetObject("DefaultMenuImage"); } menuItem.Glyph = pic as Bitmap; menuItem.LargeGlyph = pic as Bitmap; menuItem.ItemClick += MenuButtonItemClick; return menuItem; } private void GenerateRibbonMenu(int menuCacheID) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 从数据库中获取菜单项 menuInfos.Clear(); int errCode = 0; string errText = ""; try { IRAPSystemClient.Instance.sfn_AvailableCSFunctions( IRAPUser.Instance.CommunityID, CurrentSubSystem.Instance.SysInfo.SystemID, menuCacheID, IRAPConst.Instance.IRAP_PROGLANGUAGEID, true, ref menuInfos, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { throw new Exception(errText); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); throw error; } #endregion if (menuInfos.Count <= 0) { WriteLog.Instance.Write("没有菜单项可供系统生成!", strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "User [{0}] do not have the function to use in [{1}], " + "please contact the system to support the maintenance personnel " + "to solve!"; else message = "{0}用户在[{1}]中没有可以使用的功能,请联系系统支持维护人员解决!"; throw new Exception( string.Format( message, IRAPUser.Instance.UserName, CurrentSubSystem.Instance.SysInfo.SystemName)); } else { #region 生成 Ribbon 菜单 RibbonPage ribbonPage = new RibbonPage() { Text = CurrentSubSystem.Instance.SysInfo.SystemName, }; ribbonControl.Pages.Add(ribbonPage); RibbonPageGroup group = null; for (int i = 0; i < menuInfos.Count; i++) { SystemMenuInfoButtonStyle buttonInfo = (SystemMenuInfoButtonStyle)menuInfos[i]; if (buttonInfo.ItemID < 0) { if ((buttonInfo.ToolBarNewSpace) || (group == null)) { group = new RibbonPageGroup(); ribbonPage.Groups.Add(group); } group.ItemLinks.Add(GenerateRibbonMenuButton(buttonInfo)); } } #endregion } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void GenerateRibbonMenuWithRibbonStyle(int menuCacheID) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { #region 从数据库中获取菜单项 menuInfos.Clear(); int errCode = 0; string errText = ""; try { IRAPSystemClient.Instance.sfn_AvailableCSMenus( IRAPUser.Instance.CommunityID, CurrentSubSystem.Instance.SysInfo.SystemID, menuCacheID, IRAPConst.Instance.IRAP_PROGLANGUAGEID, true, ref menuInfos, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); if (errCode != 0) { throw new Exception(errText); } } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); throw error; } #endregion if (menuInfos.Count <= 0) { WriteLog.Instance.Write("没有菜单项可供系统生成!", strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "User [{0}] do not have the function to use in [{1}], " + "please contact the system to support the maintenance personnel " + "to solve!"; else message = "{0}用户在[{1}]中没有可以使用的功能,请联系系统支持维护人员解决!"; throw new Exception( string.Format( message, IRAPUser.Instance.UserName, CurrentSubSystem.Instance.SysInfo.SystemName)); } else { try { #region 生成 Ribbon 菜单 RibbonPage currentPage = null; RibbonPageGroup currentGroup = null; int j = 0; for (int i = 0; i < menuInfos.Count; i++) { SystemMenuInfoMenuStyle menuInfo = (SystemMenuInfoMenuStyle)menuInfos[i]; if (i == 0) { if (menuInfo.NodeDepth == 1) j = 0; else j = menuInfo.NodeDepth - 2; } switch (menuInfo.NodeDepth - j) { case 1: break; case 2: RibbonPage ribbonPage = new RibbonPage() { Text = menuInfo.HotKey.Trim() == "" ? menuInfo.ItemText : string.Format( "{0}(&{1})", menuInfo.ItemText, menuInfo.HotKey), Tag = menuInfo, }; ribbonControl.Pages.Add(ribbonPage); break; case 3: if (menuInfo.ItemID >= 0) { if ((currentPage == null) || (((MenuInfo)currentPage.Tag).ItemID != menuInfo.ItemID)) currentPage = GetRibbonPageWithItemID(menuInfo.Parent); if (currentPage != null) { RibbonPageGroup newGroup = new RibbonPageGroup() { Text = menuInfo.HotKey.Trim() == "" ? menuInfo.ItemText : string.Format( "{0}(&{1})", menuInfo.ItemText, menuInfo.HotKey), Tag = menuInfo, }; currentPage.Groups.Add(newGroup); } } else { // 先查找是否存在 ItemID==Parent的组 if ((currentGroup == null) || ((MenuInfo)currentGroup.Tag).ItemID != menuInfo.ItemID) currentGroup = GetRibbonPageGroupWithItemID(menuInfo.Parent); if (currentGroup == null) { currentPage = GetRibbonPageWithItemID(menuInfo.Parent); if (currentPage != null) { currentGroup = new RibbonPageGroup() { Text = "", Tag = currentPage.Tag, }; currentPage.Groups.Add(currentGroup); } } if (currentGroup != null) { currentGroup.ItemLinks.Add(GenerateRibbonMenuButton(menuInfo)); } } break; case 4: if ((currentGroup == null) || ((SystemMenuInfoMenuStyle)currentGroup.Tag).ItemID != menuInfo.ItemID) currentGroup = GetRibbonPageGroupWithItemID(menuInfo.ItemID); if (currentGroup != null) { currentGroup.ItemLinks.Add(GenerateRibbonMenuButton(menuInfo)); } break; default: WriteLog.Instance.Write("当前系统不支持 4 层以上的菜单结构!", strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "The platform does not support more than 4 layers " + "of menu structure!"; else message = "当前系统不支持 4 层以上的菜单结构!"; IRAPMessageBox.Instance.ShowErrorMessage( message, caption); break; } } #endregion } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); throw error; } } } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void MenuButtonItemClick(object sender, ItemClickEventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); BarButtonItem menuItem = null; frmCustomFuncBase childForm = null; bool activeMDIChildForm = false; if (e.Item is BarButtonItem) { WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { menuItem = e.Item as BarButtonItem; #region 记录用户运行功能的动作 try { IRAPUser.Instance.RecordRunAFunction( ((MenuInfo)menuItem.Tag).ItemID); activeMDIChildForm = true; } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); IRAPMessageBox.Instance.ShowErrorMessage( error.Message, caption); activeMDIChildForm = false; } #endregion for (int i = 0; i < MdiChildren.Length; i++) { if (MdiChildren[i].Tag == menuItem.Tag) { ((frmCustomFuncBase)MdiChildren[i]).RefreshGUIOptions = IRAPUser.Instance.RefreshGUIOptions; MdiChildren[i].Activate(); MdiChildren[i].Focus(); return; } } #if DEBUG if (ConfigurationManager.AppSettings["FileBuiltin"] != null && ConfigurationManager.AppSettings["FileBuiltin"] != "") ((MenuInfo)menuItem.Tag).FileBuiltin = ConfigurationManager.AppSettings["FileBuiltin"]; if (ConfigurationManager.AppSettings["FormName"] != null && ConfigurationManager.AppSettings["FormName"] != "") ((MenuInfo)menuItem.Tag).FormName = ConfigurationManager.AppSettings["FormName"]; #endif #region 加载类库,并创建 Form 对象 string fileBuiltin = ((MenuInfo)menuItem.Tag).FileBuiltin.Replace("IRAP", ""); try { string classFileName = string.Format( @"{0}\IRAP.Client.GUI.{1}.dll", Application.StartupPath, fileBuiltin); if (!File.Exists(classFileName)) { if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "The class library file [{0}] does not exist!"; else message = "类库文件[{0}]不存在!"; IRAPMessageBox.Instance.ShowErrorMessage( string.Format( message, classFileName), caption); return; } Assembly asm = Assembly.LoadFile(classFileName); if (asm == null) { if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "Unable to load class library file [{0}]"; else message = "无法加载类库文件[{0}]"; IRAPMessageBox.Instance.ShowErrorMessage( string.Format( message, classFileName), caption); return; } object obj = Activator.CreateInstance( asm.GetType( string.Format( "IRAP.Client.GUI.{0}.{1}", fileBuiltin, ((MenuInfo)menuItem.Tag).FormName))); childForm = (frmCustomFuncBase)obj; } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "[{0}(IRAP.Client.GUI.{1}.{2})] is under construction..."; else message = "[{0}(IRAP.Client.GUI.{1}.{2})]目前正在建设中......"; IRAPMessageBox.Instance.ShowErrorMessage( string.Format( message, ((MenuInfo)menuItem.Tag).ItemText, fileBuiltin, ((MenuInfo)menuItem.Tag).FormName), caption); } #endregion #region 显示新创建的功能窗体 if (childForm != null) { childForm.Text = ((MenuInfo)menuItem.Tag).ItemText; childForm.MdiParent = this; childForm.Tag = menuItem.Tag; childForm.Options = ucOptions; childForm.RefreshGUIOptions = IRAPUser.Instance.RefreshGUIOptions; if (childForm is frmCustomKanbanBase) { ((frmCustomKanbanBase)childForm).OnSwitch += new SwitchToNextFunctionHandler(PerformClickMenuWithItemID); ((frmCustomKanbanBase)childForm).SystemMenu = ribbonControl; ((frmCustomKanbanBase)childForm).SysLogID = IRAPUser.Instance.SysLogID; } try { childForm.Show(); childForm.Activate(); childForm.Enabled = activeMDIChildForm; } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); WriteLog.Instance.Write(error.StackTrace, strProcedureName); IRAPMessageBox.Instance.ShowErrorMessage( error.Message, caption); } } #endregion } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } } /// <summary> /// 通过功能标识号,模拟对象菜单按钮的点击动作 /// </summary> /// <param name="itemID">菜单功能标识号</param> private void PerformClickMenuWithItemID(int itemID) { for (int i = 0; i < ribbonControl.Items.Count; i++) { if (ribbonControl.Items[i] is BarButtonItem) { BarButtonItem menuItem = (BarButtonItem)ribbonControl.Items[i]; if (menuItem.Tag is MenuInfo) { MenuInfo menuInfo = menuItem.Tag as MenuInfo; if (Math.Abs(menuInfo.ItemID) == Math.Abs(itemID)) { ItemClickEventArgs eAction = new ItemClickEventArgs(menuItem, null); MenuButtonItemClick(ribbonControl, eAction); return; } } } } } private void frmIRAPMain_Load(object sender, EventArgs e) { if (!CurrentSubSystem.Instance.IsSystemSelected) { if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "There is no option to use the subsystem."; else message = "还没有选择需要使用的子系统!"; throw new Exception(message); } string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); int menuCacheID = 0; WindowState = FormWindowState.Maximized; WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { SkinHelper.InitSkinGallery(skinBarItem); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "{0}-[Login user:{1}{2}]-[{3}]-[{4}]"; else message = "{0}-[登录用户:{1}{2}]-[{3}]-[{4}]"; Text = string.Format( message, CurrentSubSystem.Instance.SysInfo.SystemName, IRAPUser.Instance.UserName, IRAPUser.Instance.UserCode, IRAPUser.Instance.Agency.AgencyName, IRAPUser.Instance.HostName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "Quit [{0}]"; else message = "退出[{0}]"; cmdQuitSubSystem.Caption = string.Format( message, CurrentSubSystem.Instance.SysInfo.SystemName); int errCode = 0; string errText = ""; #region 调用 ssp_OnSelectionASystem try { IRAPSystemClient.Instance.ssp_OnSelectionASystem( IRAPUser.Instance.CommunityID, CurrentSubSystem.Instance.SysInfo.SystemID, IRAPConst.Instance.IRAP_PROGLANGUAGEID, false, IRAPUser.Instance.SysLogID, ref menuCacheID, out errCode, out errText); if (errCode == 0) WriteLog.Instance.Write( string.Format( "获得 ManuCacheID = {0}", menuCacheID), strProcedureName); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); IRAPMessageBox.Instance.ShowErrorMessage( error.Message, caption); } #endregion if (menuCacheID == 0) menuCacheID = 0 - Convert.ToInt32(IRAPUser.Instance.SysLogID); else menuCacheID = 0 - menuCacheID; #region 生产动态菜单 switch (CurrentSubSystem.Instance.SysInfo.MenuStyle) { case 1: WriteLog.Instance.Write( string.Format( "根据 MenuCacheID={0} 的结果生成菜单", menuCacheID), strProcedureName); try { GenerateRibbonMenuWithRibbonStyle(menuCacheID); WriteLog.Instance.Write("动态菜单生成完毕", strProcedureName); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "{0}\n\nClick \"OK\" button to quit."; else message = "{0}\n\n点击“确定”退出。"; IRAPMessageBox.Instance.ShowErrorMessage( string.Format( message, error.Message), caption); isQuitSilent = true; Close(); } break; case 5: WriteLog.Instance.Write( string.Format( "根据 MenuCacheID={0} 的结果生成菜单", menuCacheID), strProcedureName); try { GenerateRibbonMenu(menuCacheID); WriteLog.Instance.Write("动态菜单生成完毕", strProcedureName); } catch (Exception error) { WriteLog.Instance.Write(error.Message, strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "{0}\n\nClick \"OK\" button to quit."; else message = "{0}\n\n点击“确定”退出。"; IRAPMessageBox.Instance.ShowErrorMessage( string.Format( message, error.Message), caption); isQuitSilent = true; Close(); } break; default: if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "The system does not support the style of [{0}] from menu"; else message = "系统不支持[{0}]形式的菜单!"; errText = string.Format( message, CurrentSubSystem.Instance.SysInfo.MenuStyle); WriteLog.Instance.Write(errText, strProcedureName); if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "{0}\n\nClick \"OK\" button to quit."; else message = "{0}\n\n点击“确定”按钮后退出。"; IRAPMessageBox.Instance.ShowErrorMessage( string.Format( message, errText), caption); isQuitSilent = true; Close(); break; } #endregion AvailableWIPStations.Instance.Options = ucOptions; } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void frmIRAPMain_Shown(object sender, EventArgs e) { string strProcedureName = string.Format( "{0}.{1}", className, MethodBase.GetCurrentMethod().Name); WriteLog.Instance.WriteBeginSplitter(strProcedureName); try { int errCode = 0; string errText = ""; int defaultFunctionID = 0; #region 获取当前子系统自动运行的功能标识号 IRAPSystemClient.Instance.sfn_DefaultFunctionToRun( IRAPUser.Instance.CommunityID, CurrentSubSystem.Instance.SysInfo.SystemID, IRAPUser.Instance.SysLogID, ref defaultFunctionID, out errCode, out errText); WriteLog.Instance.Write( string.Format("({0}){1}", errCode, errText), strProcedureName); #endregion if (defaultFunctionID == 0) return; else // 自动运行配置的功能 PerformClickMenuWithItemID(defaultFunctionID); } finally { WriteLog.Instance.WriteEndSplitter(strProcedureName); } } private void frmIRAPMain_FormClosing(object sender, FormClosingEventArgs e) { if (!isQuitSilent) { if (Thread.CurrentThread.CurrentUICulture.Name.Substring(0, 2) == "en") message = "Please make sure you want to exit [{0}] ?"; else message = "请确定是否要退出[{0}]?"; if (IRAPMessageBox.Instance.Show( string.Format( message, CurrentSubSystem.Instance.SysInfo.SystemName), caption, MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes) { e.Cancel = false; } else { e.Cancel = true; } } } private void cmdQuitSubSystem_ItemClick(object sender, BackstageViewItemEventArgs e) { Close(); } private void skinBarItem_GalleryItemClick(object sender, GalleryItemClickEventArgs e) { defaultLookAndFeel.LookAndFeel.SetSkinStyle(e.Item.Caption); string skinName = "DevExpress Style"; if (skins.ContainsKey(e.Item.Caption)) { skins.TryGetValue(e.Item.Caption, out skinName); } IniFile.WriteString( "AppSetting", "Skin", skinName, string.Format( @"{0}\IRAP.ini", AppDomain.CurrentDomain.SetupInformation.ApplicationBase)); } private void btnItemParams_ItemClick(object sender, ItemClickEventArgs e) { using (frmSysParams formSysParams = new frmSysParams()) { formSysParams.ShowDialog(); } } } }
using DatVentas; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace VentasD1002 { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Application.Run(new frmLogin()); // Application.Run(new frmMenuPrincipal()); //Application.Run(new frmUsuarioAutorizado()); // Application.Run(new frmProductos()); //Application.Run(new Reportes.frmInventario()); // Application.Run(new frmEncriptar()); //pplication.Run(new frmAperturaCaja()); //Application.Run(new frmInventarioKardex()); // Application.Run(new frmInstalacionServidor()); Application.Run(new frmMenuPrincipal()); } } }
namespace Rhino.Mocks.Tests.FieldsProblem { using Xunit; /// <summary> /// Problem discussed in google forum. /// </summary> /// <remarks> /// See https://groups.google.com/d/topic/rhinomocks/tMAbfs2qBec/discussion. /// </remarks> public class FieldProblem_Honggoff { /// <summary> /// Only a dummy interface used by the test. /// </summary> public interface IDummy { /// <summary> /// Dummy property. /// </summary> /// <returns>Whatever you like.</returns> bool GetValue(); } /// <summary> /// Simple test illustrating the problem. /// </summary> [Fact] public void TestBackToRecordAll() { IDummy test = MockRepository.GenerateStrictMock<IDummy>(); test.Expect(x => x.GetValue()).Return(true).Repeat.AtLeastOnce(); Assert.True(test.GetValue()); test.VerifyAllExpectations(); test.BackToRecord(BackToRecordOptions.All); test.Expect(x => x.GetValue()).Return(false).Repeat.AtLeastOnce(); test.Replay(); Assert.False(test.GetValue()); test.VerifyAllExpectations(); } } }
using System.Collections.Generic; namespace CouponMerchant.Models.ViewModel { public class MerchantsListViewModel { public List<Merchant> Merchants { get; set; } public PagingInfo PagingInfo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using PROnline.Models.Users; using System.Web.Mvc; namespace PROnline.Models.Notices { //公告类型 public class NoticeType { //公告类型ID public Guid NoticeTypeID { get; set; } //类型名称 [Remote("NoticeTypeNameAvailable", "NoticeType", AdditionalFields = "NoticeTypeID",ErrorMessage="类型不能重复")] [MaxLength(20)] [Required] [Display(Name = "公告类型名称")] public String TypeName { get; set; } //介绍 [MaxLength(100)] [Required] [Display(Name = "介绍")] public String Introduction { get; set; } //公告列表(包含删除的) public virtual ICollection<Notice> NoticeList { get; set; } //创建者ID public Guid CreatorID { get; set; } //创建时间 [Display(Name = "创建日期")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] [Required] public DateTime CreateDate { get; set; } //修改者ID public Guid ModifierID { get; set; } //修改时间 [Display(Name = "修改日期")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM-dd}")] public DateTime? ModifyDate { get; set; } //是否删除 [Display(Name = "是否删除")] public Boolean isDeleted { get; set; } } }
using Newtonsoft.Json; using Rebalance.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; namespace Rebalance.Services { public class StockService : IStockService { private readonly IStockRepository stockRepository; public StockService(IStockRepository stockRepository) { this.stockRepository = stockRepository; } public string GetStockPrices() { var stocks = string.Empty; var symbols = GetSymbols(); using (var client = new HttpClient()) { var responseTask = client.GetAsync($"https://financialmodelingprep.com/api/v3/quote/AAPL,{symbols}"); responseTask.Wait(); var result = responseTask.Result; if (result.IsSuccessStatusCode) { var readTask = result.Content.ReadAsStringAsync(); readTask.Wait(); stocks = readTask.Result; } } return stocks; } public IEnumerable<Stock> GetPortfolio() { var stocks = stockRepository.GetPortfolio(); var stockPrices = GetStockPrices(); var currentPrices = JsonConvert.DeserializeObject<List<Stock>>(stockPrices); double portfolioTotal = 0; foreach(var price in currentPrices) { var position = stocks.Where(s => s.Symbol == price.Symbol).Select(s => s.Position).FirstOrDefault(); portfolioTotal += price.Price * position; } foreach (var stock in stocks) { double price = currentPrices.Where(s => s.Symbol == stock.Symbol).Select(s => s.Price).FirstOrDefault(); double total = price * stock.Position; if (stock.Percent > 0) { double allocation = portfolioTotal * (stock.Percent / 100f); stock.NewPosition = Convert.ToInt32(allocation / price); stock.Buy = stock.NewPosition > stock.Position ? stock.NewPosition - stock.Position : 0; stock.Sell = stock.Position > stock.NewPosition ? stock.Position = stock.NewPosition : 0; } else { stock.Sell = stock.Position; } } return stocks; } private string GetSymbols() { var stocks = stockRepository.GetPortfolio().Select(s => s.Symbol).ToList(); return string.Join(",", stocks); } } }
namespace Zesty.Core.Entities { public class ApiResourceHistoryOutput { public ApiResourceHistoryPolicy ResourceHistoryPolicy { get; set; } public HistoryItem Item { get; set; } } }
using DashBoard.Business; using DashBoard.Business.CustomExceptions; using DashBoard.Business.DTOs.Users; using DashBoard.Business.Services; using DashBoard.Web.Helpers; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using System; using System.Threading.Tasks; namespace DashBoard.Web.Controllers { [Authorize] [ApiController] [Route("[controller]")] public class UsersController : ControllerBase { private readonly IUserService _userService; private readonly ITokenService _tokenService; private readonly AppSettings _appSettings; public string LoggedInUser => User.Identity.Name; //this gets current user ID. It doesn't work in controller. We have to pass it from here. public UsersController(IUserService userService, IOptions<AppSettings> appSettings, ITokenService tokenService) { _tokenService = tokenService; _userService = userService; _appSettings = appSettings.Value; } [AllowAnonymous] [HttpPost("authenticate")] public async Task<IActionResult> Authenticate([FromBody]AuthenticateModelDto model) { var user = _userService.Authenticate(model.Username, model.Password); if (user == null) return BadRequest(new { message = "Username or password is incorrect" }); var token = _tokenService.GenerateToken(user, _appSettings.Secret); var newRefreshToken = _tokenService.GenerateRefreshToken(); await _userService.UpdateUserRefreshToken(user, newRefreshToken); // return basic user info and authentication token return Ok(new { Id = user.Id, Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Role = user.Role, Token = token, RefreshToke = newRefreshToken }); } [AllowAnonymous] [HttpPost("refresh")] public async Task<IActionResult> Refresh(TokenRefresh tokenRefresh) { var principal = _tokenService.GetPrincipalFromExpiredToken(tokenRefresh.Token, _appSettings.Secret); var userID = principal.Identity.Name; //this is mapped to the Name claim by default var user = await _userService.GetUserModel(userID); if (user == null || user.RefreshToken != tokenRefresh.RefreshToken || user.RefreshTokenValidDate < DateTime.Now) return BadRequest(); var newJwtToken = _tokenService.GenerateToken(user, _appSettings.Secret); var newRefreshToken = _tokenService.GenerateRefreshToken(); if (await _userService.UpdateUserRefreshToken(user, newRefreshToken)) return new ObjectResult(new { token = newJwtToken, refreshToken = newRefreshToken }); return BadRequest(); } [AllowAnonymous] [HttpPost("register")] public IActionResult Register([FromBody]RegisterModelDto model) { try { var userId = LoggedInUser; //this will be null, since method is Anonymous. model.CreatedByAdmin = false; // create user var user = _userService.Create(model, model.Password, userId); return Ok(new {id = user.Id, username = user.Username}); } catch (AppException ex) { // return error message if there was an exception return BadRequest(new { message = ex.Message }); } } [Authorize(Roles = Role.Admin)] [HttpPost("admin/register")] public IActionResult RegisterByAdmin([FromBody]RegisterModelDto model) { try { var userId = LoggedInUser; model.CreatedByAdmin = true; // create user var user = _userService.Create(model, model.Password, userId); return Ok(new { Id = user.Id, Username = user.Username, FirstName = user.FirstName, LastName = user.LastName, Role = user.Role }); } catch (AppException ex) { // return error message if there was an exception return BadRequest(new { message = ex.Message }); } } [Authorize(Roles = Role.Admin)] [HttpGet] public IActionResult GetAll() { var userId = LoggedInUser; var usersDto = _userService.GetAll(userId); return Ok(usersDto); } [HttpGet("{id}")] public IActionResult GetById(int id) //this might be missing not found actionResult. { var userId = LoggedInUser; var userDto = _userService.GetById(id, userId); if (userDto != null) { return Ok(userDto); } else { return NotFound(); } } [HttpPut("{id}")] public IActionResult Update(int id, [FromBody]UpdateModelDto model) { try { var userId = LoggedInUser; // update user var result = _userService.Update(id, model, userId); if (result == "notAllowed") { return StatusCode(403); } else { return Ok(); } } catch (AppException ex) { // return error message if there was an exception return BadRequest(new { message = ex.Message }); } } [Authorize(Roles = Role.Admin)] [HttpDelete("{id}")] //this might be missing not found actionResult. public IActionResult Delete(int id) { var userId = LoggedInUser; var result = _userService.Delete(id, userId); if (result == "ok") { return Ok(); } else if (result == "notFound") { return NotFound(); } else if (result == "notAllowed") { return StatusCode(403); } return NotFound(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio15 { class TriangulosRectangulos { static void Main(string[] args) { { const char C = '*'; int A = 6; int Triangulos = 5; string Trian = ""; for (int Linha = 1; Linha <= A; Linha++) { for (int T = 1; T <= Triangulos; T++) { for (int Caract = 1; Caract <= Linha; Caract++) { Trian += C; Trian += "\t"; } Trian += "\n"; Console.WriteLine(Trian); } } } } } }
using Xamarin.Forms; namespace XamJam.Nav.Root { public class RootDestination<TViewModel> : PageDestination<RootScheme> { public RootDestination(RootScheme navScheme, TViewModel viewModel, View view) : base(navScheme, viewModel, view) { } public RootDestination(RootScheme navScheme, TViewModel viewModel, Page page) : base(navScheme, viewModel, page) { } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Coldairarrow.Entity.Sto_ProManage { /// <summary> /// Pro_ProjectMateriel /// </summary> [Table("Pro_ProjectMateriel")] public class Pro_ProjectMateriel { /// <summary> /// Id /// </summary> [Key] public String Id { get; set; } /// <summary> /// ProCode /// </summary> public String ProCode { get; set; } /// <summary> /// ProName /// </summary> public String ProName { get; set; } /// <summary> /// MatNo /// </summary> public String MatNo { get; set; } /// <summary> /// MatName /// </summary> public String MatName { get; set; } /// <summary> /// GuiGe /// </summary> public String GuiGe { get; set; } /// <summary> /// UnitNo /// </summary> public String UnitNo { get; set; } /// <summary> /// PlanQuantity /// </summary> public Decimal? PlanQuantity { get; set; } /// <summary> /// Context /// </summary> public String Context { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace uk.andyjohnson.ImageBulkRenamer { public class RenameItem { public string InputImageFileName { get; set; } public DateTime InputImageExifTimestamp { get; set; } public DateTime InputImageFileCreatonTimestamp { get; set; } public DateTime InputImageFileModificationTimestamp { get; set; } public string OutputImageFileName { get; set; } public DateTime OutputImageFileTimestamp { get; set; } public string InputSidecarFileName { get; set; } public string OutputSidecarFileName { get; set; } public string RenameStatus { get; set; } public static string BuildFileName(DateTime dt) { return dt.ToString("yyyyMMdd_HHmmss"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using System.Threading.Tasks; namespace API.Model { [Table("Technologie")] public class Technologie { [Key] public int Id { get; set; } [Required] [MaxLength(50)] public string Nom { get; set; } [ForeignKey("IdCategorie")] public Categorie Categorie { get; set; } [Required] [MaxLength(50)] public string PathImage { get; set; } [Required] [MaxLength(5000)] public string Intitule { get; set; } public int IdCategorie { get; set; } } }
namespace m_tools.Models { public enum Base64CodeType { Encode = 0, Decode = 1 } public class Base64RawData<T> { public Base64CodeType Type { get; set; } public T RawData { get; set; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using ZendeskSell.Models; namespace ZendeskSell.Contacts { public class ContactRequest { public ContactRequest() { Tags = new string[] { }; Address = ShippingAddress = BillingAddress = new Address(); CustomFields = new ContactCustomFields(); } [JsonProperty("owner_id")] public int? OwnerID { get; set; } [JsonProperty("is_organization")] public bool IsOrganization { get; set; } [JsonProperty("contact_id")] public int ContactID { get; set; } [JsonProperty("parent_organization_id")] public int? ParentOrganizationID { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("first_name")] public string FirstName { get; set; } [JsonProperty("last_name")] public string LastName { get; set; } [JsonProperty("title")] public string Title { get; set; } [JsonProperty("customer_status")] public string CustomerStatus { get; set; } [JsonProperty("prospect_status")] public string ProspectStatus { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("industry")] public string Industry { get; set; } [JsonProperty("website")] public string Website { get; set; } [JsonProperty("email")] public string Email { get; set; } [JsonProperty("phone")] public string Phone { get; set; } [JsonProperty("mobile")] public string Mobile { get; set; } [JsonProperty("fax")] public string Fax { get; set; } [JsonProperty("twitter")] public string Twitter { get; set; } [JsonProperty("facebook")] public string Facebook { get; set; } [JsonProperty("linkedin")] public string Linkedin { get; set; } [JsonProperty("skype")] public string Skype { get; set; } [JsonProperty("address")] public Address Address { get; set; } [JsonProperty("billing_address")] public Address BillingAddress { get; set; } [JsonProperty("shipping_address")] public Address ShippingAddress { get; set; } [JsonProperty("tags")] public IEnumerable<string> Tags { get; set; } [JsonProperty("custom_fields")] public ContactCustomFields CustomFields { get; set; } } public class ContactResponse : ContactRequest { [JsonProperty("id")] public int ID { get; set; } [JsonProperty("creator_id")] public int CreatorID { get; set; } [JsonProperty("created_at")] public DateTimeOffset CreatedAt { get; set; } [JsonProperty("updated_at")] public DateTimeOffset UpdatedAt { get; set; } } public class ContactCustomFields { [JsonProperty("referral_website")] public string ReferralWebsite { get; set; } [JsonProperty("known_via")] public string KnownVia { get; set; } } }
using System; using Plugin.Settings; using Plugin.Settings.Abstractions; namespace LorikeetMApp.Helpers { public static class Settings { private static ISettings AppSettings => CrossSettings.Current; public static bool IsInitialized { get => AppSettings.GetValueOrDefault(nameof(IsInitialized), false); set => AppSettings.AddOrUpdateValue(nameof(IsInitialized), value); } public static string Password { get => AppSettings.GetValueOrDefault(nameof(Password), string.Empty); set => AppSettings.AddOrUpdateValue(nameof(Password), value); } public static string Pin { get => AppSettings.GetValueOrDefault(nameof(Pin), string.Empty); set => AppSettings.AddOrUpdateValue(nameof(Pin), value); } public static string typeOfLogin { get => AppSettings.GetValueOrDefault(nameof(typeOfLogin), string.Empty); set => AppSettings.AddOrUpdateValue(nameof(typeOfLogin), value); } } }
using gView.Framework.Carto; using gView.Framework.Globalisation; using gView.Framework.system; using gView.Framework.UI; using System.Threading.Tasks; using System.Windows.Forms; namespace gView.Plugins.MapTools { [RegisterPlugInAttribute("F4F7F60D-B560-4233-96F7-89012FD856A8")] public class RefreshMap : ITool, IShortCut { IMapDocument _doc = null; #region ITool Member public string Name { get { return LocalizedResources.GetResString("Tools.RefreshMap", "Refresh Map"); } } public bool Enabled { get { return (_doc != null && _doc.FocusMap != null); } } public string ToolTip { get { return ""; } } public ToolType toolType { get { return ToolType.command; } } public object Image { get { return gView.Win.Plugin.Tools.Properties.Resources.Refresh; } } public void OnCreate(object hook) { if (hook is IMapDocument) { _doc = hook as IMapDocument; } } public Task<bool> OnEvent(object MapEvent) { if (_doc != null && _doc.Application is IMapApplication) { ((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.All); } return Task.FromResult(true); } #endregion #region IShortCut Member public Keys ShortcutKeys { get { return Keys.F5; } } public string ShortcutKeyDisplayString { get { return "F5"; } } #endregion } }
using LightBoxRectSubForm.comm; using LightBoxRectSubForm.dll; using System; using System.Windows; namespace LightBoxRectSubForm { /// <summary> /// WidTest.xaml 的交互逻辑 /// </summary> public partial class WidTest : Window { public WidTest() { InitializeComponent(); //DataComm.ins.eventReceived += Ins_eventReceived; //DataComm.ins.eventSended += Ins_eventSended; ECANHelper.ins.eventReceived += Ins_eventReceived; ECANHelper.ins.eventSended += Ins_eventSended; } //串口收到数据 private void Ins_eventSended(object sender, ByteEventArgs e) { txtSend.Dispatcher.Invoke(new Action(() => { txtSend.Text = txtSend.Text + "\n" + e.ToString(); })); } //串口发出数据 private void Ins_eventReceived(object sender, ByteEventArgs e) { txtReceived.Dispatcher.Invoke(new Action(() => { txtReceived.Text = txtReceived.Text + "\n" + e.ToString(); })); } private void btnCleanSend_Click(object sender, RoutedEventArgs e) { txtSend.Text = ""; } private void btnCleanReceive_Click(object sender, RoutedEventArgs e) { txtReceived.Text = ""; } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { DataComm.ins.eventReceived -= Ins_eventReceived; DataComm.ins.eventSended -= Ins_eventSended; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Asvargr { /// <summary> /// Interaktionslogik für MainWindow.xaml /// </summary> public partial class MainWindow : Window { Combat combat = new Combat("Oger Überfall"); public MainWindow() { InitializeComponent(); lbOpponents.ItemsSource = combat.Opponents; spDetailInfo.DataContext = combat.GetActiveOpponent(); spHeader.DataContext = combat; } private void Grid_MouseDown(object sender, MouseButtonEventArgs e) { Grid myX = (System.Windows.Controls.Grid)sender; combat.SetOpponent( (Opponent)myX.DataContext); this.spDetailInfo.DataContext = combat.GetActiveOpponent(); } private void LoadDemo1_MouseDown(object sender, MouseButtonEventArgs e) { combat = new Combat("Oger Überfall"); combat.AddOpponent(new Opponent(1, "Grubenunhold", 24, 36) { LP = 20, AP = 10 }); combat.AddOpponent(new Opponent(2, "Grubenunhold", 24, 36) { LP = 18, AP = 30 }); combat.AddOpponent(new Opponent(3, "Grubenunhold", 24, 36) { LP = 23, AP = 36 }); combat.AddOpponent(new Opponent(4, "Oger", 44, 36) { LP = 23, AP = 36 }); combat.AddOpponent(new Opponent(5, "Oger", 44, 36) { LP = 23, AP = 36 }); combat.AddOpponent(new Opponent(6, "Höllenhund", 64, 0) { LP = 50, AP = 0 }); combat.AddOpponent(new Opponent(7, "Höllenhund", 64, 0) { LP = 60, AP = 0 }); combat.AddOpponent(new Opponent(8, "Höllenhund", 64, 0) { LP = 64, AP = 0 }); combat.Opponents[2].AddBuff(new Buff(Bufftype.Angriff, -2, 6)); combat.Opponents[2].AddBuff(new Buff(Bufftype.Abwehr, -2, 6)); combat.Opponents[2].AddBuff(new Buff(Bufftype.Schaden, 4, 3)); combat.Opponents[4].AddBuff(new Buff(Bufftype.Angriff, 2, 6)); combat.Opponents[4].AddBuff(new Buff(Bufftype.Abwehr, 2, 6)); combat.Opponents[5].AddBuff(new Buff(Bufftype.Aktionen, -2, 6)); combat.Opponents[5].AddBuff(new Buff(Bufftype.Schaden, -2, 4)); combat.Opponents[5].AddBuff(new Buff(Bufftype.AP, -3, 2)); combat.Opponents[6].AddBuff(new Buff(Bufftype.Aktionen, 1, 6)); lbOpponents.ItemsSource = combat.Opponents; spDetailInfo.DataContext = combat.Opponents[0]; spHeader.DataContext = combat; } private void LoadDemo2_MouseDown(object sender, MouseButtonEventArgs e) { combat = new Combat("Sir Adalbert treibt steuern ein"); combat.AddOpponent(new Opponent(1, "Sir Adalbert", 24, 46) { LP = 20, AP = 40 }); combat.AddOpponent(new Opponent(2, "Knecht", 24, 36) { LP = 18, AP = 30 }); combat.AddOpponent(new Opponent(3, "Knecht", 24, 36) { LP = 23, AP = 36 }); combat.AddOpponent(new Opponent(4, "Knecht", 44, 36) { LP = 23, AP = 36 }); combat.AddOpponent(new Opponent(5, "Bogenschütze", 19, 36) { LP = 17, AP = 36 }); combat.AddOpponent(new Opponent(6, "Bogenschütze", 19, 30) { LP = 10, AP = 13 }); combat.AddOpponent(new Opponent(7, "Bogenschütze", 19, 30) { LP = 10, AP = 6 }); combat.AddOpponent(new Opponent(8, "Jagdhund", 17, 20) { LP = 2, AP = 0 }); combat.AddOpponent(new Opponent(9, "Jagdhund", 17, 20) { LP = 6, AP = 2 }); //combat.Opponents[1].AddBuff(new Buff(Bufftype.Angriff, -2, 6)); //combat.Opponents[2].AddBuff(new Buff(Bufftype.Abwehr, -2, 6)); //combat.Opponents[2].AddBuff(new Buff(Bufftype.Schaden, 4, 3)); //combat.Opponents[4].AddBuff(new Buff(Bufftype.Angriff, 2, 6)); //combat.Opponents[4].AddBuff(new Buff(Bufftype.Abwehr, 2, 6)); //combat.Opponents[5].AddBuff(new Buff(Bufftype.Aktionen, -2, 6)); //combat.Opponents[5].AddBuff(new Buff(Bufftype.Schaden, -2, 4)); //combat.Opponents[5].AddBuff(new Buff(Bufftype.AP, -3, 2)); //combat.Opponents[6].AddBuff(new Buff(Bufftype.Aktionen, 1, 6)); //combat.Opponents[0].AddBuff(new Buff(Bufftype.Angriff, -2, 2)); //combat.Opponents[7].AddBuff(new Buff(Bufftype.Aktionen, 1, 6)); //combat.Opponents[8].AddBuff(new Buff(Bufftype.Aktionen, 1, 3)); //combat.Opponents[8].AddBuff(new Buff(Bufftype.Angriff, 1, 4)); lbOpponents.ItemsSource = combat.Opponents; spDetailInfo.DataContext = combat.Opponents[0]; spHeader.DataContext = combat; } private void Scene1_MouseDown(object sender, MouseButtonEventArgs e) { //combat.NextRound(); combat.Opponents[2].HasAction = false; combat.Opponents[2].LP = 0; combat.Opponents[2].IsAlive = false; } private void Scene2_MouseDown(object sender, MouseButtonEventArgs e) { combat.NextRound(); combat.Opponents[3].HasAction = false; combat.Opponents[4].HasAction = false; } private void btnNextRound_Click(object sender, RoutedEventArgs e) { combat.NextRound(); } private void btnWeapon1_Click(object sender, RoutedEventArgs e) { } private void btnSetDamage_Click(object sender, RoutedEventArgs e) { combat.DamageOrHeal(-5, -5, combat.GetActiveOpponent()); } private void btnSetBuff_Click(object sender, RoutedEventArgs e) { combat.AddBuff(new Buff(Bufftype.Angriff, -2, 4), combat.GetActiveOpponent()); combat.AddBuff(new Buff(Bufftype.LP, -2, 4), combat.GetActiveOpponent()); } private void btnSetHeal_Click(object sender, RoutedEventArgs e) { combat.DamageOrHeal(7, 7, combat.GetActiveOpponent()); } private void btnResetBattle_Click(object sender, RoutedEventArgs e) { combat.Reset(); } } }
namespace Yaringa.Models.Token { public class TokenInfo { public long UserId { get; set; } } }
using ecommerce.DAO; using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ecommerce.ecommerceClasses { class ClientDAO : clientInterface { public Client GetClient(string code) { SqlConnection conn = connection.GetConnection(); conn.Open(); DataTable dt = new DataTable(); Client cl = null; try { string req = "select * from client where code=@code"; SqlCommand cmd = new SqlCommand(req, conn); cmd.Parameters.AddWithValue("@code", code); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); DataRow row = (from client in dt.AsEnumerable() where client.Field<string>("code") == code select client).First(); if (row != null) { cl = new Client(); cl.Adress = row.Field<string>("adress"); cl.Code = row.Field<string>("code"); cl.Email = row.Field<string>("email"); cl.LastName = row.Field<string>("lastName"); cl.Name = row.Field<string>("name"); cl.Tel = row.Field<int>("tel"); } } catch (Exception e) { } finally { conn.Close(); } return cl; } public List<Client> getClientsList() { SqlConnection conn = connection.GetConnection(); conn.Open(); DataTable dt = new DataTable(); List<Client> list = null; try { string req = "select * from client"; SqlCommand cmd = new SqlCommand(req, conn); SqlDataAdapter adapter = new SqlDataAdapter(cmd); adapter.Fill(dt); dt.AsEnumerable(); if (dt.Rows.Count > 0) { list = new List<Client>(); foreach (DataRow row in dt.AsEnumerable()) { Client cl = new Client(); cl.Adress = row.Field<string>("adress"); cl.Code = row.Field<string>("code"); cl.Email = row.Field<string>("email"); cl.LastName = row.Field<string>("lastName"); cl.Name = row.Field<string>("name"); cl.Tel = row.Field<int>("tel"); list.Add(cl); } } } catch(Exception e) { } finally { conn.Close(); } return list; } public void removeClient(string code) { SqlConnection conn = connection.GetConnection(); conn.Open(); try { string req = "DELETE FROM client where code=@code"; SqlCommand cmd = new SqlCommand(req, conn); cmd.Parameters.AddWithValue("@code", code); int rows = cmd.ExecuteNonQuery(); if (rows > 0) { Console.WriteLine("Client was successfully removed"); } else { Console.WriteLine("An error has occured while removing the client"); } } catch (Exception e) { } finally { conn.Close(); } } public Boolean setClient(Client client) { SqlConnection conn = connection.GetConnection(); conn.Open(); Boolean clientAdded = false; try { if (GetClient(client.Code) == null) { string req = "insert into client(code,adress,email,name,lastName,tel) values(@code,@adress,@email,@name,@lastName,@tel)"; SqlCommand cmd = new SqlCommand(req, conn); cmd.Parameters.AddWithValue("@code", client.Code); cmd.Parameters.AddWithValue("@adress", client.Adress); cmd.Parameters.AddWithValue("@email", client.Email); cmd.Parameters.AddWithValue("@name", client.Name); cmd.Parameters.AddWithValue("@lastName", client.LastName); cmd.Parameters.AddWithValue("@tel", client.Tel); int rows = cmd.ExecuteNonQuery(); if (rows > 0) { Console.WriteLine("Client was added with success"); clientAdded = true; } else { Console.WriteLine("An error has occured while adding the client"); } } else { throw (new ClIENT_EXISTE_EXCEPTION("There's already a client with the mentioned ID")); } } catch (Exception e) { Console.WriteLine(e); } finally { conn.Close(); } return clientAdded; } public Boolean updateClient(Client client) { SqlConnection conn = connection.GetConnection(); conn.Open(); Boolean updatedClient = false; try { string req = "update client set adress=@adress, email=@email, name=@name, lastName=@lastName, tel=@tel where code=@code"; SqlCommand cmd = new SqlCommand(req, conn); cmd.Parameters.AddWithValue("@code", client.Code); cmd.Parameters.AddWithValue("@adress", client.Adress); cmd.Parameters.AddWithValue("@email", client.Email); cmd.Parameters.AddWithValue("@name", client.Name); cmd.Parameters.AddWithValue("@lastName", client.LastName); cmd.Parameters.AddWithValue("@tel", client.Tel); int rows = cmd.ExecuteNonQuery(); if (rows > 0) { Console.WriteLine("Client was successfully updated"); updatedClient = true; } else { Console.WriteLine("An error has occured while updating the client"); } } catch (Exception e) { } finally { conn.Close(); } return updatedClient; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Les7Exercise1 { public partial class FWF_Udvoitel : Form { public FWF_Udvoitel() { InitializeComponent(); btnCommand1.Text = "+1"; btnCommand2.Text = "x2"; btnReset.Text = "Сброс"; lblNumber.Text = "0"; lblCount.Text = "0"; this.Text = "Удвоитель"; rnd = new Random(); numbers = new Stack<int>(); BtnEnable(false); numbers.Push(rez); } int count = 0; int rez = 1; int setValue; Random rnd; Stack<int> numbers; /// <summary> /// Включение/Отключение кнопок /// </summary> /// <param name="enable"></param> void BtnEnable(bool enable) { btnCommand1.Enabled = enable; btnCommand2.Enabled = enable; btnReset.Enabled = enable; btnCansel.Enabled = enable; } /// <summary> /// Минимальное кол-во ходов /// </summary> /// <param name="setValue"></param> /// <returns></returns> int MinCount(int setValue) { int temp = 0; while (setValue !=1) { if (setValue % 2 == 0) setValue /= 2; else setValue--; temp++; } return temp; } /// <summary> /// Сверка текущего значения и заданного числа /// </summary> /// <param name="rez"></param> /// <param name="setValue"></param> /// <param name="count"></param> void EndGAme(int rez, int setValue, int count) { if (rez == setValue) { MessageBox.Show($"Вы получили заданное число.\nКоличество ваших ходов - {count}.\nИдеальный вариант - {MinCount(setValue)}"); BtnEnable(false); } else if (rez > setValue) { MessageBox.Show("Вы проиграли, Ваше число больше загаданного."); BtnEnable(false); } } private void btnCommand1_Click(object sender, EventArgs e) { rez = int.Parse(lblNumber.Text) + 1; numbers.Push(rez); lblNumber.Text = rez.ToString(); lblCount.Text = Convert.ToString(++count); EndGAme(rez, setValue, count); } private void btnCommand2_Click(object sender, EventArgs e) { rez = int.Parse(lblNumber.Text) * 2; numbers.Push(rez); lblNumber.Text = rez.ToString(); lblCount.Text = Convert.ToString(++count); EndGAme(rez, setValue, count); } private void btnReset_Click(object sender, EventArgs e) { lblCount.Text = "0"; //Ресет это тоже команда, но пусть сбрасывает счетчик. count = 0; lblNumber.Text = "1"; numbers.Clear(); numbers.Push(1); } private void tsmiExit_Click(object sender, EventArgs e) { this.Close(); } private void tsmiAbout_Click(object sender, EventArgs e) { MessageBox.Show("Игра \"Удвоитель\".\nНеобходимо получить заданное число за минимальное количество ходов."); } private void tsmiGame_Click(object sender, EventArgs e) { BtnEnable(true); lblCount.Text = "0"; //Сброс всех параметров. count = 0; lblNumber.Text = "1"; numbers.Clear(); numbers.Push(1); setValue = rnd.Next(100); MessageBox.Show($"Вым необходимо получить {setValue}."); } private void btnCansel_Click(object sender, EventArgs e) { lblCount.Text = Convert.ToString(++count); if(numbers.Count != 1) numbers.Pop(); lblNumber.Text = Convert.ToString(numbers.Peek()); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PinkStorm : MonoBehaviour { public Vector3 rotSpeed; public float followSpeed; public GameObject player; public float waitTime; public float colliderTime; bool colliderEnabled; // Start is called before the first frame update void Start() { waitTime = 4f; } // Update is called once per frame void Update() { //transform.Rotate(rotSpeed * Time.deltaTime); if (colliderTime != 0 && Time.time > colliderTime) { colliderTime = 0; GetComponent<SphereCollider>().enabled = true; Debug.Log("enable collider"); } if (transform.position != player.transform.position) { transform.position = Vector3.MoveTowards(transform.position, player.transform.position, followSpeed * Time.deltaTime); } else { transform.Rotate(rotSpeed * Time.deltaTime); } } void OnTriggerEnter(Collider other) { //if(other.gameObject != player && !other.gameObject.GetComponent<EnemyFollowingScript>().manDown) if (other.gameObject != player) { Debug.Log("detected"); //other.gameObject.GetComponent<EnemyFollowingScript>().FallDown(); } } }
using log4net.Config; using Abhs.App_Start; using Abhs.Application.IService; using Abhs.Application.Service; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using StructureMap.Attributes; using System.Threading.Tasks; using Abhs.Common.Enums; using Abhs.Cache.Redis; using Abhs.Common; using System.Timers; using System.Collections.Concurrent; using Abhs.Model.MonitorMiddle; using Abhs.Model.Common; using Abhs.Application.IService.Business; namespace Abhs { public class WebApiApplication : System.Web.HttpApplication { private log4net.ILog _logNet = log4net.LogManager.GetLogger(typeof(WebApiApplication)); protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); //GlobalConfiguration.Configuration.Filters.Add(new WebApiExceptionFilterAttribute()); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; FileInfo configFile = new FileInfo(HttpContext.Current.Server.MapPath("/Configs/log4net.config")); log4net.Config.XmlConfigurator.Configure(configFile); //var container = StructuremapMvc.StructureMapDependencyScope.Container; //var studentService = container.GetInstance<IDataCheckService>(); //studentService.CheckLessonData(); } protected void Application_End(object sender,EventArgs e) { } } }
using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using pluralsight_bot.Models; using System; namespace pluralsight_bot.Services { // Info : 03.01 - Create a State Service (Bot State Class - UserState) // Info : 03.02 - Create a class <StateService> (UserState, StateProperty, StatePropertyAccessor) public class StateService { // Info : 03.03 - Create a UserState & ConversationState property public UserState UserState { get; } public ConversationState ConversationState { get; set; } // Info : 03.05 - Create a property <UserProfileId> & <ConversationDataId> public static string UserProfileId { get; } = $"{nameof(StateService)}.UserProfile"; public static string ConversationDataId { get; } = $"{nameof(StateService)}.ConversationData"; public static string DialogStateId { get; } = $"{nameof(StateService)}.DialogState"; // Info : 03.06 - Create a accessor for UserProfile & ConversationData (Get, Set, Delete) public IStatePropertyAccessor<UserProfile> UserProfileAccessor { get; set; } public IStatePropertyAccessor<ConversationData> ConversationDataAccessor { get; set; } public IStatePropertyAccessor<DialogState> DialogStateAccessor { get; set; } // Info : 03.04 - Create a constructor with injection of UserState & ConversationState public StateService(UserState UserState, ConversationState ConversationState) { this.UserState = UserState ?? throw new ArgumentNullException(nameof(UserState)); this.ConversationState = ConversationState ?? throw new ArgumentNullException(nameof(ConversationState)); // Info : 03.08 - Call <InitializeAccessors> InitializeAccessors(); } // Info : 03.07 - Create a method to initialize the accessor public void InitializeAccessors() { // Initialize Conversation State Accessors ConversationDataAccessor = ConversationState.CreateProperty<ConversationData>(ConversationDataId); DialogStateAccessor = ConversationState.CreateProperty<DialogState>(DialogStateId); // Initialize User State UserProfileAccessor = UserState.CreateProperty<UserProfile>(UserProfileId); } } }
using System; using Crossroads.Web.Common.MinistryPlatform; using Newtonsoft.Json; namespace MinistryPlatform.Translation.Models.DTO { [MpRestApiTable(Name = "Participants")] public class MpParticipantDto { [JsonProperty(PropertyName = "Event_Participant_ID")] public int EventParticipantId { get; set; } [JsonProperty(PropertyName = "Participant_ID")] public int ParticipantId { get; set; } [JsonProperty(PropertyName = "Contact_ID")] public int ContactId { get; set; } [JsonProperty("Year_Grade")] public int? YearGrade { get; set; } [JsonProperty(PropertyName = "Household_ID")] public int HouseholdId { get; set; } [JsonProperty(PropertyName = "Household_Position_ID")] public int HouseholdPositionId { get; set; } [JsonProperty(PropertyName = "Call_Number")] public int CallNumber { get; set; } [JsonProperty(PropertyName = "First_Name")] public string FirstName { get; set; } [JsonProperty(PropertyName = "Last_Name")] public string LastName { get; set; } [JsonProperty(PropertyName = "Nickname")] public string Nickname { get; set; } [JsonProperty(PropertyName = "Date_of_Birth")] public DateTime? DateOfBirth { get; set; } [JsonProperty(PropertyName = "Participation_Status_ID")] public int ParticipationStatusId { get; set; } [JsonProperty(PropertyName = "Group_ID")] public int? GroupId { get; set; } [JsonProperty(PropertyName = "Participant_Type_ID")] public int ParticipantTypeId { get; set; } [JsonProperty(PropertyName = "Participant_Start_Date")] public DateTime ParticipantStartDate { get; set; } [JsonProperty(PropertyName = "Primary_Household")] public bool PrimaryHousehold { get; set; } [JsonProperty(PropertyName = "Gender_ID")] public int? GenderId { get; set; } } }
using RomashkaBase.ViewModel; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; namespace RomashkaBase.Model { public class ContractStatus : BasePropertyChanged { [Key] public string Status { get; set; } public List<Company> Companies { get; set; } } }
using UnityEngine; using System.Collections; //背景 public class BackGround : MonoBehaviour { private MainCamera mainCamera; private Renderer _renderer; private GameObject obj_camera = null; private Vector3 offset = Vector3.zero; // Use this for initialization void Start () { mainCamera = GameObject.Find("MainCamera").GetComponent<MainCamera>(); _renderer = this.GetComponent<Renderer>(); obj_camera = GameObject.FindGameObjectWithTag("MainCamera"); offset = transform.position - obj_camera.transform.position; } public float speed = 0.01f; // スクロールするスピード void Update () { switch (GameManager.gameState) { case GameManager.GameState.Title: break; case GameManager.GameState.Play: if (!isMove()) return ; break; case GameManager.GameState.GameOver: if (!isMove()) return ; break; case GameManager.GameState.GameClear: if (!isMove()) return ; break; } float scroll = Mathf.Repeat (Time.time * speed, 1); // 時間によってYの値が0から1に変化していく.1になったら0に戻り繰り返す. Vector2 offset = new Vector2 (scroll, 0); // Xの値がずれていくオフセットを作成. _renderer.sharedMaterial.SetTextureOffset ("_MainTex", offset); // マテリアルにオフセットを設定する. } void LateUpdate(){ Vector3 new_position = transform.position; new_position = obj_camera.transform.position + offset; transform.position = new_position; } // Update is called once per frame //void Update () { //SetPosition(); //} private bool isMove() { Vector2 pos = mainCamera.GetMovePosition(); if (pos.x <= 0) return false; return true; } /*public float speed = 0.1f; void Update () { float y = Mathf.Repeat (Time.time * speed, 1); Vector2 offset = new Vector2 (0,y); _renderer.sharedMaterial.SetTextureOffset ("_MainTex", offset); }*/ }
using System; using System.Collections.Generic; using Lecture06.BlogPosts.EntityFramework.Domain; namespace Lecture06.BlogPosts.EntityFramework.Repositories { public interface IBlogPostRepository { IEnumerable<BlogPost> GetBlogPosts(); void AddBlogPost(String title, IEnumerable<String> authors, String content); void EditBlogPost(Int32 id, String title, IEnumerable<String> authors, String content); } }
using University.Repository; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using University.Service.Interface; using University.Repository.Interface; namespace University.Service { public class UserTestService: IUserTestService { private IUserTestRepository _userTestRepository; public UserTestService(IUserTestRepository userTestRepository) { _userTestRepository = userTestRepository; } public int GetUserTestId() { return _userTestRepository.GetUserTestId(); } } }
using System; using System.Threading; using System.Threading.Tasks; using Justa.Job.Backend.Api.Application.MediatR.Requests; using Justa.Job.Backend.Api.Application.Services.DataValidation.Interfaces; using Justa.Job.Backend.Api.Application.Services.DataValidation.Models; using Microsoft.AspNetCore.Mvc; namespace Justa.Job.Backend.Api.Application.MediatR.Handlers { public class QueryValidateCnpjHandler : ActionResultRequestHandler<QueryValidateCnpj> { private readonly ICnpjValidator _cnpjValidator; public QueryValidateCnpjHandler(ICnpjValidator cnpjValidator) { _cnpjValidator = cnpjValidator; } public override Task<IActionResult> Handle(QueryValidateCnpj request, CancellationToken cancellationToken) => Task.Run(() => { var isCnpjValid = _cnpjValidator.Validate(request.Cnpj); var response = new ValidatorResponse { Type = "cpf", IsValid = isCnpjValid, Value = request.Cnpj, Formated = isCnpjValid ? Convert.ToUInt64(request.Cnpj).ToString(@"00\.000\.000\/0000\-00") : string.Empty }; return Ok(response); }); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace QLNhaTro { class Data { public SqlConnection GetConnection() { return new SqlConnection(@"Data Source=DESKTOP-QIQ8G50;Initial Catalog=QLNhaTro;Integrated Security=True"); } public void ExcuteNonQuery(string sql) { SqlConnection conn = GetConnection(); SqlCommand cmd = new SqlCommand(sql, conn); conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); cmd.Dispose(); } public SqlDataReader ExecuteReader(string sql) { SqlConnection conn = GetConnection(); conn.Open(); SqlCommand cmd = new SqlCommand(sql, conn); SqlDataReader reader = cmd.ExecuteReader(); return reader; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using System.Security.Claims; using Microsoft.Extensions.Logging; using AHAO.TPLMS.Service; using System.Runtime.InteropServices.WindowsRuntime; using AHAO.TPLMS.Web.Models; using Microsoft.Extensions.Caching.Memory; using AHAO.TPLMS.Util.Helpers; using AHAO.TPLMS.Util; using Newtonsoft.Json.Linq; namespace AHAO.TPLMS.Web.Controllers { [ApiController] [Route("[controller]")] public class HomeController : BaseController { AuthoriseService auth; public HomeController(AuthoriseService authorise) { auth = authorise; } public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; return View(); } public IActionResult Contact() { ViewData["Message"] = "Your contact page."; return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } public IActionResult Login() { return View(); } #region 登录与登出 public ActionResult SubmitLogin(string userName, string password) { MemoryCacheHelper memHelper = new MemoryCacheHelper(); int count = 0; AjaxResult res = null; if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { res = Error("账号或密码不能为空!"); } var obj = memHelper.Get(userName); if (!(obj is null)) { int.TryParse(obj.ToString(), out count); } if (count > 3) { res = Error("你已经登录三次出错了,请在一个小时之后再试!"); } else { bool theUser = auth.Check(userName, password); if (theUser) { res = Success(); } else { res = Error("账号或密码不正确!"); } memHelper.Add(userName, count + 1); } return Content(res.ToJson()); } /// <summary> /// 注销 /// </summary> /// <returns></returns> public AjaxResult Logout() { return Success("注销成功!"); } #endregion /// <summary> /// 返回成功 /// </summary> /// <param name="msg">消息</param> /// <returns></returns> public AjaxResult Success(string msg) { AjaxResult res = new AjaxResult { Success = true, Msg = msg, Data = null }; return res; } } }
using Microsoft.Win32.SafeHandles; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace PEImageDebugSampleLib { internal static class NativeMethods { [return: MarshalAs(UnmanagedType.Bool)] [DllImport("Imagehlp.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)] public static extern bool MapAndLoad( [MarshalAs(UnmanagedType.LPStr)]string ImageName, [MarshalAs(UnmanagedType.LPStr)]string DllPath, [MarshalAs(UnmanagedType.SysInt)]IntPtr LoadedImage, [MarshalAs(UnmanagedType.Bool)]bool DotDll, [MarshalAs(UnmanagedType.Bool)]bool ReadOnly ); [return: MarshalAs(UnmanagedType.Bool)] [DllImport("Imagehlp.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)] public static extern bool UnMapAndLoad( [MarshalAs(UnmanagedType.SysInt)]IntPtr LoadedImage ); [return: MarshalAs(UnmanagedType.SysInt)] [DllImport("Dbghelp.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)] public static extern IntPtr ImageRvaToVa( [MarshalAs(UnmanagedType.SysInt)]IntPtr NtHeaders, [MarshalAs(UnmanagedType.SysInt)]IntPtr Base, [MarshalAs(UnmanagedType.U4)]UInt32 Rva, [MarshalAs(UnmanagedType.SysInt)]IntPtr LastRvaSection ); [return: MarshalAs(UnmanagedType.SysInt)] [DllImport("Dbghelp.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)] public static extern IntPtr ImageNtHeader( [MarshalAs(UnmanagedType.SysInt)]IntPtr ImageBase ); [return: MarshalAs(UnmanagedType.SysInt)] [DllImport("Dbghelp.dll", CharSet = CharSet.Unicode, SetLastError = true, ThrowOnUnmappableChar = true, BestFitMapping = false)] public static extern IntPtr ImageDirectoryEntryToDataEx( [MarshalAs(UnmanagedType.SysInt)]IntPtr Base, [MarshalAs(UnmanagedType.Bool)]bool MappedAsImage, [MarshalAs(UnmanagedType.U4)]UInt32 DirectoryEntry, [MarshalAs(UnmanagedType.U4)]out UInt32 Size, [MarshalAs(UnmanagedType.SysInt)]out IntPtr FoundHeader ); } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LOADED_IMAGE { //[MarshalAs(UnmanagedType.LPTStr)] //public string ModuleName; [MarshalAs(UnmanagedType.SysInt)] public IntPtr ModuleName; [MarshalAs(UnmanagedType.SysInt)] public IntPtr hFile; [MarshalAs(UnmanagedType.SysInt)] public IntPtr MappedAddress; [MarshalAs(UnmanagedType.SysInt)] public IntPtr FileHeader; [MarshalAs(UnmanagedType.SysInt)] public IntPtr LastRvaSection; [MarshalAs(UnmanagedType.U4)] public UInt32 NumberOfSections; [MarshalAs(UnmanagedType.SysInt)] public IntPtr Sections; [MarshalAs(UnmanagedType.U4)] public UInt32 Characteristics; [MarshalAs(UnmanagedType.U1)] public byte fSystemImage; [MarshalAs(UnmanagedType.U1)] public byte fDOSImage; [MarshalAs(UnmanagedType.U1)] public byte fReadOnly; [MarshalAs(UnmanagedType.U1)] public byte Version; [MarshalAs(UnmanagedType.Struct)] public LIST_ENTRY Links; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfImage; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IMAGE_NT_HEADERS { [MarshalAs(UnmanagedType.U4)] public UInt32 Signature; [MarshalAs(UnmanagedType.Struct)] public IMAGE_FILE_HEADER FileHeader; [MarshalAs(UnmanagedType.Struct)] public IMAGE_OPTIONAL_HEADER OptionalHeader; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IMAGE_NT_HEADERS64 { [MarshalAs(UnmanagedType.U4)] public UInt32 Signature; [MarshalAs(UnmanagedType.Struct)] public IMAGE_FILE_HEADER FileHeader; [MarshalAs(UnmanagedType.Struct)] public IMAGE_OPTIONAL_HEADER64 OptionalHeader; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IMAGE_FILE_HEADER { [MarshalAs(UnmanagedType.U2)] public UInt16 Machine; [MarshalAs(UnmanagedType.U2)] public UInt16 NumberOfSections; [MarshalAs(UnmanagedType.U4)] public UInt32 TimeDateStamp; [MarshalAs(UnmanagedType.U4)] public UInt32 PointerToSymbolTable; [MarshalAs(UnmanagedType.U4)] public UInt32 NumberOfSymbols; [MarshalAs(UnmanagedType.U2)] public UInt16 SizeOfOptionalHeader; [MarshalAs(UnmanagedType.U2)] public UInt16 Characteristics; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IMAGE_OPTIONAL_HEADER { [MarshalAs(UnmanagedType.U2)] public UInt16 Magic; [MarshalAs(UnmanagedType.U1)] public byte MajorLinkerVersion; [MarshalAs(UnmanagedType.U1)] public byte MinorLinkerVersion; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfCode; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfInitializedData; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfUninitializedData; [MarshalAs(UnmanagedType.U4)] public UInt32 AddressOfEntryPoint; [MarshalAs(UnmanagedType.U4)] public UInt32 BaseOfCode; [MarshalAs(UnmanagedType.U4)] public UInt32 BaseOfData; [MarshalAs(UnmanagedType.U4)] public UInt32 ImageBase; [MarshalAs(UnmanagedType.U4)] public UInt32 SectionAlignment; [MarshalAs(UnmanagedType.U4)] public UInt32 FileAlignment; [MarshalAs(UnmanagedType.U2)] public UInt16 MajorOperatingSystemVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MinorOperatingSystemVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MajorImageVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MinorImageVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MajorSubsystemVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MinorSubsystemVersion; [MarshalAs(UnmanagedType.U4)] public UInt32 Win32VersionValue; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfImage; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfHeaders; [MarshalAs(UnmanagedType.U4)] public UInt32 CheckSum; [MarshalAs(UnmanagedType.U2)] public ImageSubsystem Subsystem; [MarshalAs(UnmanagedType.U2)] public UInt16 DllCharacteristics; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfStackReserve; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfStackCommit; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfHeapReserve; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfHeapCommit; [MarshalAs(UnmanagedType.U4)] public UInt32 LoaderFlags; [MarshalAs(UnmanagedType.U4)] public UInt32 NumberOfRvaAndSizes; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 16/*IMAGE_NUMBEROF_DIRECTORY_ENTRIES*/)] public IMAGE_DATA_DIRECTORY[] DataDirectory; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IMAGE_OPTIONAL_HEADER64 { [MarshalAs(UnmanagedType.U2)] public UInt16 Magic; [MarshalAs(UnmanagedType.U1)] public byte MajorLinkerVersion; [MarshalAs(UnmanagedType.U1)] public byte MinorLinkerVersion; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfCode; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfInitializedData; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfUninitializedData; [MarshalAs(UnmanagedType.U4)] public UInt32 AddressOfEntryPoint; [MarshalAs(UnmanagedType.U4)] public UInt32 BaseOfCode; [MarshalAs(UnmanagedType.U8)] public UInt64 ImageBase; [MarshalAs(UnmanagedType.U4)] public UInt32 SectionAlignment; [MarshalAs(UnmanagedType.U4)] public UInt32 FileAlignment; [MarshalAs(UnmanagedType.U2)] public UInt16 MajorOperatingSystemVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MinorOperatingSystemVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MajorImageVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MinorImageVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MajorSubsystemVersion; [MarshalAs(UnmanagedType.U2)] public UInt16 MinorSubsystemVersion; [MarshalAs(UnmanagedType.U4)] public UInt32 Win32VersionValue; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfImage; [MarshalAs(UnmanagedType.U4)] public UInt32 SizeOfHeaders; [MarshalAs(UnmanagedType.U4)] public UInt32 CheckSum; [MarshalAs(UnmanagedType.U2)] public ImageSubsystem Subsystem; [MarshalAs(UnmanagedType.U2)] public UInt16 DllCharacteristics; [MarshalAs(UnmanagedType.U8)] public UInt64 SizeOfStackReserve; [MarshalAs(UnmanagedType.U8)] public UInt64 SizeOfStackCommit; [MarshalAs(UnmanagedType.U8)] public UInt64 SizeOfHeapReserve; [MarshalAs(UnmanagedType.U8)] public UInt64 SizeOfHeapCommit; [MarshalAs(UnmanagedType.U4)] public UInt32 LoaderFlags; [MarshalAs(UnmanagedType.U4)] public UInt32 NumberOfRvaAndSizes; [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.Struct, SizeConst = 16/* IMAGE_NUMBEROF_DIRECTORY_ENTRIES */)] public IMAGE_DATA_DIRECTORY[] DataDirectory; } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct IMAGE_SECTION_HEADER { [MarshalAs(UnmanagedType.ByValArray, ArraySubType = UnmanagedType.U1, SizeConst = 8/* IMAGE_SIZEOF_SHORT_NAME */)] [FieldOffset(0)] public byte[] Name; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public UInt32 PhysicalAddress; [MarshalAs(UnmanagedType.U4)] [FieldOffset(8)] public UInt32 VirtualSize; [MarshalAs(UnmanagedType.U4)] [FieldOffset(12)] public UInt32 VirtualAddress; [MarshalAs(UnmanagedType.U4)] [FieldOffset(16)] public UInt32 SizeOfRawData; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public UInt32 PointerToRawData; [MarshalAs(UnmanagedType.U4)] [FieldOffset(24)] public UInt32 PointerToRelocations; [MarshalAs(UnmanagedType.U4)] [FieldOffset(28)] public UInt32 PointerToLinenumbers; [MarshalAs(UnmanagedType.U2)] [FieldOffset(32)] public UInt16 NumberOfRelocations; [MarshalAs(UnmanagedType.U2)] [FieldOffset(34)] public UInt16 NumberOfLinenumbers; [MarshalAs(UnmanagedType.U4)] [FieldOffset(36)] public UInt32 Characteristics; } [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] internal struct IMAGE_COR20_HEADER { // Header versioning [MarshalAs(UnmanagedType.U4)] [FieldOffset(0)] public UInt32 cb; [MarshalAs(UnmanagedType.U2)] [FieldOffset(4)] public UInt16 MajorRuntimeVersion; [MarshalAs(UnmanagedType.U2)] [FieldOffset(6)] public UInt16 MinorRuntimeVersion; // Symbol table and startup information [MarshalAs(UnmanagedType.Struct)] [FieldOffset(8)] public IMAGE_DATA_DIRECTORY MetaData; [MarshalAs(UnmanagedType.U4)] [FieldOffset(16)] public UInt32 Flags; // The main program if it is an EXE (not used if a DLL?) // If COMIMAGE_FLAGS_NATIVE_ENTRYPOINT is not set, EntryPointToken represents a managed entrypoint. // If COMIMAGE_FLAGS_NATIVE_ENTRYPOINT is set, EntryPointRVA represents an RVA to a native entrypoint // (depricated for DLLs, use modules constructors intead). [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public UInt32 EntryPointToken; [MarshalAs(UnmanagedType.U4)] [FieldOffset(20)] public UInt32 EntryPointRVA; // This is the blob of managed resources. Fetched using code:AssemblyNative.GetResource and // code:PEFile.GetResource and accessible from managed code from // System.Assembly.GetManifestResourceStream. The meta data has a table that maps names to offsets into // this blob, so logically the blob is a set of resources. [MarshalAs(UnmanagedType.Struct)] [FieldOffset(24)] public IMAGE_DATA_DIRECTORY Resources; // IL assemblies can be signed with a public-private key to validate who created it. The signature goes // here if this feature is used. [MarshalAs(UnmanagedType.Struct)] [FieldOffset(32)] public IMAGE_DATA_DIRECTORY StrongNameSignature; [MarshalAs(UnmanagedType.Struct)] [FieldOffset(40)] public IMAGE_DATA_DIRECTORY CodeManagerTable; // Depricated, not used // Used for manged codee that has unmaanaged code inside it (or exports methods as unmanaged entry points) [MarshalAs(UnmanagedType.Struct)] [FieldOffset(48)] public IMAGE_DATA_DIRECTORY VTableFixups; [MarshalAs(UnmanagedType.Struct)] [FieldOffset(56)] public IMAGE_DATA_DIRECTORY ExportAddressTableJumps; // null for ordinary IL images. NGEN images it points at a code:CORCOMPILE_HEADER structure [MarshalAs(UnmanagedType.Struct)] [FieldOffset(64)] public IMAGE_DATA_DIRECTORY ManagedNativeHeader; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct IMAGE_DATA_DIRECTORY { [MarshalAs(UnmanagedType.U4)] public UInt32 VirtualAddress; [MarshalAs(UnmanagedType.U4)] public UInt32 Size; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] internal struct LIST_ENTRY { [MarshalAs(UnmanagedType.SysInt)] public IntPtr Flink; [MarshalAs(UnmanagedType.SysInt)] public IntPtr Blink; } internal enum ImageSubsystem : ushort { IMAGE_SUBSYSTEM_UNKNOWN = 0, IMAGE_SUBSYSTEM_NATIVE = 1, IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, IMAGE_SUBSYSTEM_OS2_CUI = 5, IMAGE_SUBSYSTEM_POSIX_CUI = 7, IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, IMAGE_SUBSYSTEM_EFI_ROM = 13, IMAGE_SUBSYSTEM_XBOX = 14, IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16, } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using WebUI.Data.Abstract; using WebUI.Entity; namespace WebUI.Controllers { public class SocialSettingController : Controller { private ISocialRepository _socialRepository; public SocialSettingController(ISocialRepository socialRepo) { _socialRepository = socialRepo; } [Route("panel/setting/social")] public IActionResult Index() { return View(_socialRepository.GetAll()); } [Route("panel/setting/social/edit")] [HttpGet] public IActionResult Edit(int id) { var data = _socialRepository.GetById(id); return View(data); } [Route("panel/setting/social/edit")] [HttpPost] public IActionResult Edit(SocialSetting social) { if (ModelState.IsValid) { _socialRepository.SaveSocialSetting(social); return RedirectToAction("Index"); } return View(social); } [Route("panel/setting/social/delete")] [HttpGet] public IActionResult Delete(int id) { return View(_socialRepository.GetById(id)); } [Route("panel/setting/social/delete")] [HttpPost, ActionName("Delete")] public IActionResult DeleteConfirmed(int SocialId) { _socialRepository.DeleteSocialSetting(SocialId); return RedirectToAction("Index"); } [Route("panel/setting/social/create")] [HttpGet] public IActionResult Create() { return View(); } [Route("panel/setting/social/create")] [HttpPost] public IActionResult Create(SocialSetting entity) { if (ModelState.IsValid) { _socialRepository.SaveSocialSetting(entity); return RedirectToAction("Index"); } return View(entity); } } }
namespace Ofl.Atlassian.Jira.V3 { public class Status { public bool Resolved { get; set; } public Icon? Icon { get; set; } } }
using gView.Framework.Carto; using gView.Framework.Data; using gView.Framework.Geometry; using gView.Framework.Globalisation; using gView.Framework.UI; using gView.Framework.UI.Controls.Filter; using gView.Framework.UI.Dialogs; using gView.Framework.UI.Events; using System.Collections.Generic; using System.Threading.Tasks; namespace gView.Plugins.MapTools { [gView.Framework.system.RegisterPlugIn("11BA5E40-A537-4651-B475-5C7C2D65F36E")] public class AddData : ITool, IMapContextMenuItem { IMapDocument _doc = null; #region ITool Member public bool Enabled { get { if (_doc == null || _doc.Application == null) { return false; } if (_doc.Application is IMapApplication && ((IMapApplication)_doc.Application).ReadOnly == true) { return false; } //LicenseTypes lt = _doc.Application.ComponentLicenseType("gview.desktop;gview.map"); //return (lt == LicenseTypes.Licensed || lt == LicenseTypes.Express); return true; } } public string Name { get { return LocalizedResources.GetResString("Tools.AddData", "Add Data..."); } } public void OnCreate(object hook) { if (hook is IMapDocument) { _doc = hook as IMapDocument; } } async public Task<bool> OnEvent(object MapEvent) { if (!(MapEvent is MapEvent)) { return false; } IMap map = ((MapEvent)MapEvent).Map; bool firstDataset = (map[0] == null); List<ExplorerDialogFilter> filters = new List<ExplorerDialogFilter>(); filters.Add(new OpenDataFilter()); ExplorerDialog dlg = new ExplorerDialog("Add data...", filters, true); if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { List<IDataset> datasets = await dlg.Datasets(); FormDatasetProperties datasetProps = await FormDatasetProperties.CreateAsync(null, datasets); try { if (((MapEvent)MapEvent).UserData == null) { if (datasetProps.ShowDialog() != System.Windows.Forms.DialogResult.OK) { return true; } } } catch // Kann ObjectDisposed Exception werfen... { return true; } Envelope env = null; foreach (ILayer layer in datasetProps.Layers) { ISpatialReference sRef = null; IEnvelope classEnv = null; if (layer is IFeatureLayer && ((IFeatureLayer)layer).FeatureClass != null && ((IFeatureLayer)layer).FeatureClass.Envelope != null) { sRef = ((IFeatureLayer)layer).FeatureClass.SpatialReference; classEnv = ((IFeatureLayer)layer).FeatureClass.Envelope; } else if (layer is IRasterLayer && ((IRasterLayer)layer).RasterClass != null && ((IRasterLayer)layer).RasterClass.Polygon != null && ((IRasterLayer)layer).RasterClass.Polygon.Envelope != null) { sRef = ((IRasterLayer)layer).RasterClass.SpatialReference; classEnv = ((IRasterLayer)layer).RasterClass.Polygon.Envelope; } else if (layer is IWebServiceLayer && ((IWebServiceLayer)layer).WebServiceClass != null && ((IWebServiceLayer)layer).WebServiceClass.Envelope != null) { sRef = ((IWebServiceLayer)layer).WebServiceClass.SpatialReference; classEnv = ((IWebServiceLayer)layer).WebServiceClass.Envelope; } if (classEnv != null) { if (sRef != null && !sRef.Equals(map.Display.SpatialReference)) { bool found = false; foreach (string p in map.Display.SpatialReference.Parameters) { if (p.ToLower().Trim() == "+nadgrids=@null") { found = false; } } if (found) { classEnv = null; } else { IGeometry geom = GeometricTransformerFactory.Transform2D(classEnv.ToPolygon(0), sRef, map.Display.SpatialReference); if (geom != null) { classEnv = geom.Envelope; } else { classEnv = null; } } } if (classEnv != null) { if (env == null) { env = new Envelope(classEnv); } else { env.Union(classEnv); } } } map.AddLayer(layer); } //map.AddDataset(dataset, 0); if (env != null && map.Display != null) { if (firstDataset) { map.Display.Limit = env; map.Display.ZoomTo(env); } else { IEnvelope limit = map.Display.Limit; limit.Union(env); map.Display.Limit = limit; } } ((MapEvent)MapEvent).drawPhase = DrawPhase.All; ((MapEvent)MapEvent).refreshMap = true; } return true; } public string ToolTip { get { return ""; } } public object Image { get { return gView.Win.Plugin.Tools.Properties.Resources.add_data; } } public ToolType toolType { get { return ToolType.command; } } #endregion #region IContextMenuTool Member public bool Enable(object element) { return true; } public bool Visible(object element) { return true; } async public Task<bool> OnEvent(object element, object parent) { if (element is IMap) { MapEvent mapEvent = new MapEvent((IMap)element); await this.OnEvent(mapEvent); if (mapEvent.refreshMap && _doc != null && _doc.Application is IMapApplication) { await ((IMapApplication)_doc.Application).RefreshActiveMap(mapEvent.drawPhase); } } return true; } #endregion #region IOrder Member public int SortOrder { get { return 55; } } #endregion } }
using Microsoft.Extensions.Configuration; using Newtonsoft.Json; using ShopBridgeWeb.Helpers; using ShopBridgeWeb.Pages; using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Threading.Tasks; using io = System.IO; namespace ShopBridgeWeb.Data { public interface IProductService { Task<List<Prod>> GetAllProducts(); Task<Prod> GetProductById(long id); Task<int> ManageProduct(Prod product,string file); Task<Prod> DeleteProduct(long id); } public class ProductService : IProductService { private readonly IConfiguration _configuration; public static string _baseUrl,_getAllProducts, _getProductById, _createProduct, _updateProduct, _deleteProduct; public ProductService(IConfiguration configuration) { _configuration = configuration; _baseUrl = configuration.GetSection("ApiConfig").GetValue("BaseUrl",""); _getAllProducts = io.Path.Combine(_baseUrl, configuration.GetSection("ApiConfig").GetSection("Product").GetSection("GetAllProducts").Value); _getProductById =io.Path.Combine(_baseUrl,configuration.GetSection("ApiConfig").GetSection("Product").GetSection("GetProductById").Value); _createProduct = io.Path.Combine(_baseUrl,configuration.GetSection("ApiConfig").GetSection("Product").GetSection("CreateProduct").Value); _updateProduct = io.Path.Combine(_baseUrl,configuration.GetSection("ApiConfig").GetSection("Product").GetSection("UpdateProduct").Value); _deleteProduct = io.Path.Combine(_baseUrl, configuration.GetSection("ApiConfig").GetSection("Product").GetSection("DeleteProduct").Value); } public async Task<List<Prod>> GetAllProducts() { var _apiResponse = await ApiHelper.CallApi(_getAllProducts, HttpMethod.Get, null, "getAllProducts", null,null); if (_apiResponse != null && _apiResponse.StatusCode == HttpStatusCode.OK) { return JsonConvert.DeserializeObject<List<Prod>>(_apiResponse.Content.ReadAsStringAsync().Result); } return null; } public async Task<Prod> GetProductById(long id) { var _apiResponse = await ApiHelper.CallApi(string.Format(_getProductById, id), HttpMethod.Get, null, "getProductById", null,null); if (_apiResponse != null && _apiResponse.StatusCode == HttpStatusCode.OK) { return JsonConvert.DeserializeObject<Prod>(_apiResponse.Content.ReadAsStringAsync().Result); } return null; } /// <summary> /// Descrition : file upload pending /// </summary> /// <param name="product"></param> /// <param name="file"></param> /// <returns></returns> public async Task<int> ManageProduct(Prod product,string file) { //if (!String.IsNullOrEmpty(product.ProductImage) && file != null && file.Length > 0) //{ // product.ProductImage = product.ProductImage.Substring(product.ProductImage.ToString().LastIndexOf('\\')).Trim('\\'); //} //else //{ // product.ProductImage = string.Empty; // file = null; //} product.ProductImage = string.Empty; file = null; var json = JsonConvert.SerializeObject(product, Formatting.Indented).ToString(); byte[] content = Encoding.ASCII.GetBytes(json); var bytes = new ByteArrayContent(content); dynamic _apiResponse; if (product.ProductId == 0) { _apiResponse = await ApiHelper.CallApi(_createProduct, HttpMethod.Put, bytes, "product", file == null ? null : Convert.FromBase64String(file),product.ProductImage); } else { _apiResponse = await ApiHelper.CallApi(_updateProduct, HttpMethod.Post, bytes, "product",file == null? null : Convert.FromBase64String(file), product.ProductImage); } if (_apiResponse != null && _apiResponse.StatusCode == HttpStatusCode.OK) { return 1; } return 0; } public async Task<Prod> DeleteProduct(long id) { var _apiResponse = await ApiHelper.CallApi(string.Format(_deleteProduct, id), HttpMethod.Delete, null, "_deleteProduct", null,null); if (_apiResponse != null && _apiResponse.StatusCode == HttpStatusCode.OK) { return new Prod(); } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Integer.Domain.Agenda.Exceptions { public class EventoParoquialExistenteException : Exception { private readonly IEnumerable<Evento> eventosParoquiais; public EventoParoquialExistenteException(IEnumerable<Evento> eventosParoquiais) { this.eventosParoquiais = eventosParoquiais; } public override string Message { get { StringBuilder msgErro = new StringBuilder(); foreach (Evento eventoParoquial in eventosParoquiais) { msgErro.AppendLine(String.Format("O evento paroquial '{0}' já está cadastrado para o horário: {1}.", eventoParoquial.Nome, eventoParoquial.Horario)); } return msgErro.ToString(); } } } }
using System.Collections.Generic; namespace DealOrNoDeal.Data.Rounds { /// <summary> /// Holds the cases to open for each round /// /// Author: Alex DeCesare /// Version: 03-September-2021 /// </summary> public static class CasesToOpenForEachRound { /// <summary> /// Holds the cases to open for a five round game /// </summary> public static List<int> FiveRoundGame = new List<int> { 6, 5, 3, 2 }; /// <summary> /// Holds the cases to open for a seven round game /// </summary> public static List<int> SevenRoundGame = new List<int> { 8, 6, 4, 3, 2, 1 }; /// <summary> /// Holds the cases to open for a ten round game /// </summary> public static List<int> TenRoundCases = new List<int> {6, 5, 4, 3, 2, 1, 1, 1, 1}; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ifelseextra { class Program { static void Main(string[] args) { atividade3(); Console.ReadKey(); #region Atividade void atividade1() { int hora; Console.Write("Digite uma hora (número inteiro): "); hora = int.Parse(Console.ReadLine()); if ((hora>=6)&&(hora<=11)) { Console.Write("Manhã "); } else if ((hora>=12)&&(hora<=17)) { Console.Write("Tarde "); } else if ((hora>=18)&&(hora<23)) { Console.Write("Noite"); } else if ((hora>=0)&&(hora<=5)) { Console.Write("Madrugada"); } { Console.Write("????"); } } #endregion #region Atividade2 void atividade2() { double num, num2; string sinal; Console.Write("Um número: "); num = double.Parse(Console.ReadLine()); Console.Write("Outro número: "); num2 = double.Parse(Console.ReadLine()); Console.Write("Digite a operação matematica: "); sinal = Console.ReadLine(); if (sinal=="+") { Console.Write("Resultado: "+(num+num2)); } else if (sinal=="-") { Console.Write("Resultado: " + (num - num2)); } else if (sinal == "*") { Console.Write("Resultado: " + (num * num2)); } else if (sinal=="/") { Console.Write("Resultado: " + (num / num2)); } else { Console.Write("Sinal não reconhecido"); } } #endregion #region Atividade 3 void atividade3() { float preco; string codigo; Console.Write("VV -- Venda a vista -- desconto de 10%"); Console.Write(" \nVP30 --Venda a Prazo 30 dias -- acréscimo de 5%"); Console.Write(" \nVP60 -- Venda a Prazo 60 dias-- acréscimo de 7%"); Console.Write(" \nVP90 -- Venda a Prazo 90 dias-- acréscimo de 9%"); Console.Write(" \nCD -- Venda com cartão de débito -- desconto de 10%"); Console.Write(" \nCC -- Venda com cartão de crédito-- mesmo valor"); Console.Write("\n"); Console.Write(" \nvalor: "); preco = float.Parse(Console.ReadLine()); Console.Write("\nCódigo: "); codigo = Console.ReadLine(); Console.Write("\n"); if (codigo=="VV"||codigo=="vv") { Console.Write("Preço:"+(preco-(preco*10/100))); } else if (codigo=="VP30"||codigo=="vp30") { Console.Write("Preço:" + (preco + (preco * 5 / 100))); } else if (codigo == "VP60" || codigo == "vp60") { Console.Write("Preço:" + (preco + (preco * 7 / 100))); } else if (codigo == "VP90" || codigo == "vp90") { Console.Write("Preço:" + (preco + (preco * 9 / 100))); } else if (codigo == "CD" || codigo == "cd") { Console.Write("Preço:" + (preco - (preco * 10 / 100))); } else if (codigo == "cc" || codigo == "CC") { Console.Write("Mesmo valor" ); } else { Console.Write("código invalido"); } } #endregion #region Atividade 4 void atividade4() { int quantidade, codigo; Console.Write("código do produto: "); codigo = int.Parse(Console.ReadLine()); Console.Write("quantidade: "); quantidade = int.Parse(Console.ReadLine()); if (codigo==1001) { Console.Write("Preço total: "+(quantidade*5.30)); } else if (codigo==1020) { Console.Write("Preço total: " + (quantidade * 7.50)); } else if (codigo == 3029) { Console.Write("Preço total: " + (quantidade * 1.90)); } else if (codigo == 00234) { Console.Write("Preço total: " + (quantidade * 20.40)); } else if (codigo == 3492) { Console.Write("Preço total: " + (quantidade * 4.35)); } else { Console.Write("Código invalido" ); } } #endregion } } }
using _7DRL_2021.Behaviors; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021.Results { class ActionAlignGrid : IActionHasOrigin, ITickable { public bool Done => Time.Done; public ICurio Origin { get; set; } Slider Time; public ActionAlignGrid(ICurio origin, float time) { Origin = origin; Time = new Slider(time); } public void Run() { Origin.MoveVisual(Origin.GetMainTile(), LerpHelper.CubicIn, Time); } public void Tick(SceneGame scene) { Time += 1; } } }
using PhotonInMaze.Common.Flow; using PhotonInMaze.Provider; using UnityEngine; namespace PhotonInMaze.Photon { internal partial class PhotonAnimationController : FlowUpdateBehaviour { private PhotonAnimationManager animationManager; public override void OnInit() { Animator animator = GetComponent<Animator>(); PhotonConfiguration configuration = GetComponent<PhotonConfiguration>(); animationManager = new PhotonAnimationManager(); } public override IInvoke OnLoop() { return GameFlowManager.Instance.Flow .When(State.ShowPhoton) .Then(() => { animationManager.ShowPhoton(); GameFlowManager.Instance.Flow.NextState(); }) .OrElseWhen(State.TurnOnPhotonLight) .Then(() => { animationManager.TurnOnLight(); GameFlowManager.Instance.Flow.NextState(); }) .OrElseWhen(State.HidePhoton) .Then(() => { if(animationManager.IsNotHidingAndTurningLightOff()) { GameFlowManager.Instance.Flow.NextState(); } }) .Build(); } public override int GetInitOrder() { return (int)InitOrder.PhotonAnimation; } } }
using gView.Framework.Data; using gView.Framework.IO; using gView.Framework.UI; using System; using System.Linq; using System.Threading.Tasks; namespace gView.Cmd.MxlInfo { internal class Program { private static async Task<int> Main(string[] args) { try { string inFile = args.FirstOrDefault(); for (int i = 1; i < args.Length; i++) { if (args[i] == "-??" && i < args.Length - 1) { } } if (String.IsNullOrWhiteSpace(inFile)) { Console.WriteLine("Usage: gView.Cmd.MxlInfo mxl-file [Options]"); } XmlStream stream = new XmlStream(""); stream.ReadStream(inFile); MapDocument doc = new MapDocument(); await stream.LoadAsync("MapDocument", doc); foreach (var map in doc.Maps) { if (map?.MapElements == null) { continue; } Console.WriteLine($"Map: {map.Name}"); Console.WriteLine("=========================================================="); var featureLayers = map.TOC.Layers.Where(l => l is IFeatureLayer) .Select(l => (IFeatureLayer)l); Console.WriteLine("FeatureLayers:"); Console.WriteLine("-------------------------------------------------------------"); if (map.Datasets != null) { int datasetID = 0; foreach (var dataset in map.Datasets) { Console.WriteLine($"Dataset: {dataset.DatasetName}"); Console.WriteLine($" {dataset.GetType().ToString()}"); Console.WriteLine("-------------------------------------------------------"); foreach (var dsElement in map.MapElements.Where(e => e.DatasetID == datasetID)) { if (dsElement?.Class == null) { continue; } var featureLayer = featureLayers.Where(l => l.DatasetID == datasetID && l.Class == dsElement.Class) .FirstOrDefault(); if (featureLayer == null) { continue; } Console.WriteLine($"FeatureLayer: {featureLayer.Title}"); Console.WriteLine($" Class: {dsElement.Class.Name}"); Console.WriteLine($" {dsElement.Class.GetType().ToString()}"); } } } } return 0; } catch (Exception ex) { Console.WriteLine("Exception:"); Console.WriteLine(ex.Message); return 1; } } } }
using AutoMapper; using ReactClientVideoWithMVC_API.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ReactClientVideoWithMVC_API.Mappings { public class Mapp : Profile { public Mapp() { CreateMap<Category, Category>(); CreateMap<Video, Video>(); } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class PlayerTransition : MonoBehaviour { public GameObject[] Monkey; // Stores the two Monkeys public Text leftActive; // Text that shows left Monkey is in use public Text rightActive; // Text that shows right Monkey is in use public Text timeText; public Text leftWarning; // Text that warns player game will end during the last 6 seconds public Text rightWarning; // Text that warns player game will end during the last 6 seconds public float targetTime = 30.0f; public GameObject godTree; // main center Tree public GameObject timeCoconut; // intersectable Coconut object that adds time public GameObject pointClown; // intersectable Clown object that takes away Bananas // Use this for initialization void Start () { // make all texts initially empty leftActive.text = ""; rightActive.text = ""; leftWarning.text = ""; rightWarning.text = ""; } // Update is called once per frame void Update () { float leftMonkeyY = Monkey[0].GetComponent<PlayerMovement> ().yPos; // y pos of left Monkey float rightMonkeyY = Monkey[1].GetComponent<PlayerMovement> ().yPos; // y pos of right Monkey if (leftMonkeyY > rightMonkeyY) { // if left Monkey is higher up than right Monkey Monkey [0].GetComponent<PlayerMovement> ().active = true; // set left Monkey active Monkey [1].GetComponent<PlayerMovement> ().active = false; // set right Monkey inactive leftActive.text = "Active"; // display active text for left Monkey rightActive.text = ""; // hide active text for right Monkey } else { // if right Monkey is higher up than left Monkey Monkey [1].GetComponent<PlayerMovement> ().active = true; // set right Monkey active Monkey [0].GetComponent<PlayerMovement> ().active = false; // set left Monkey inactive rightActive.text = "Active"; // display active text for right Monkey leftActive.text = ""; // hide active text for left Monkey } if (targetTime < 6 && targetTime > 5) { // in 6th second left leftWarning.text = "Dance Monkey,"; } else if (targetTime < 5 && targetTime > 4) { // in 5th second left rightWarning.text = "Dance!"; leftWarning.text = ""; } else if (targetTime < 4 && targetTime > 3) { // in 4th second left leftWarning.text = "Dance Monkey,"; rightWarning.text = ""; } else if (targetTime < 3 && targetTime > 2) { // in 3rd second left rightWarning.text = "Dance!"; leftWarning.text = ""; } else if (targetTime < 2 && targetTime > 1) { // in 2nd second left leftWarning.text = "Dance Monkey,"; rightWarning.text = ""; } else if (targetTime < 1) { // in last second left leftWarning.text = ""; rightWarning.text = "Dance!"; } else { // if higher than 6, do not display leftWarning.text = ""; rightWarning.text = ""; } if (timeCoconut.GetComponent<CoconutMovement> ().Token == true) { // if Coconut token is avaliable, take and add 15 sec to gameplay targetTime = targetTime + 15; timeCoconut.GetComponent<CoconutMovement> ().Token = false; } if (pointClown.GetComponent<ClownMovement> ().Token == true) { // if Clown token is avaliable, take and remove 10 Bananas (Points) int oldPoints = godTree.GetComponent<BananaPool> ().pointTally; if (oldPoints <= 10) { godTree.GetComponent<BananaPool> ().pointTally = 0; } else { godTree.GetComponent<BananaPool> ().pointTally = oldPoints - 10; } pointClown.GetComponent<ClownMovement> ().Token = false; } if (targetTime > 0) // display text countdown if greater than 0 { timeText.text = targetTime.ToString("N4"); }else{ // end game if timer has hit 0 timeText.text = "0.0000"; if (godTree.GetComponent<BananaPool> ().pointTally < 10) { // if less than 10 Bananas were collected, go to sad ending Application.LoadLevel ("DeathSad"); } else { // if more than 10 Bananas were collected, go to happy ending Application.LoadLevel ("DeathHappy"); } } targetTime -= Time.deltaTime; // subtract time every update Debug.Log(targetTime); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace Question1 { class Program { static void Main(string[] args) { char[] _splitCharacter = { ' ' }; string _searchParam = string.Empty; List<string> _searchLst = new List<string>(); _searchLst.Add("Users"); _searchLst.Add("User Groups"); _searchLst.Add("User Activity Log"); _searchLst.Add("Report Designer"); _searchLst.Add("Report Activity Log"); Console.WriteLine("Please enter the search word"); _searchParam = Console.ReadLine(); _searchParam = Regex.Replace(_searchParam, @"\s+", ""); char[] _charSearchParam = _searchParam.ToCharArray(); List<string> _firstWordStartWith = new List<string>(); List<string> _secondWordStartWith = new List<string>(); List<string> _output = new List<string>(); if (_charSearchParam.Count() <= 1) { _firstWordStartWith = (from p in _searchLst where p.ToLower().StartsWith(_charSearchParam[0].ToString()) select p).ToList(); _output = _firstWordStartWith; } else { _firstWordStartWith = (from p in _searchLst where p.ToLower().StartsWith(_charSearchParam[0].ToString()) select p).ToList(); foreach (string item in _firstWordStartWith) { string[] _breakUp = item.Split(_splitCharacter); _secondWordStartWith = (from s in _breakUp where s.ToLower().StartsWith(_charSearchParam[1].ToString()) select s).ToList(); if(_secondWordStartWith.Count > 0) { _output.Add(item); } } } for(int i =0; i < _output.Count;i++) { Console.WriteLine(_output[i]); } Console.ReadLine(); } } }
using Assistenza.BufDalsi.Data.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Assistenza.BufDalsi.Web.Models.GenericoViewModels { public class InsertGenericoViewModel { public InsertGenericoViewModel(int gnr_Id, string gnr_Nome, DateTime gnr_UltimaInstallazione, DateTime gnr_UltimoIntervento, float gnr_OreUltimoIntervento, string gnr_Marca, string gnr_Modello, string gnr_Serie, bool gnr_Rimosso, string gnr_Descrizione, int gnr_Impianto) { this.gnr_Id = gnr_Id; this.gnr_Nome = gnr_Nome; this.gnr_UltimaInstallazione = gnr_UltimaInstallazione; this.gnr_UltimoIntervento = gnr_UltimoIntervento; this.gnr_OreUltimoIntervento = gnr_OreUltimoIntervento; this.gnr_Marca = gnr_Marca; this.gnr_Modello = gnr_Modello; this.gnr_Serie = gnr_Serie; this.gnr_Rimosso = gnr_Rimosso; this.gnr_Descrizione = gnr_Descrizione; this.gnr_Impianto = gnr_Impianto; } public InsertGenericoViewModel() { gnr_UltimaInstallazione = new DateTime(1900, 01, 01); gnr_UltimoIntervento = new DateTime(1900, 01, 01); } public int gnr_Id { get; set; } public string gnr_Nome { get; set; } public string gnr_Marca { get; set; } public string gnr_Modello { get; set; } public string gnr_Serie { get; set; } public string gnr_Descrizione { get; set; } [DataType(DataType.Date)] public DateTime gnr_UltimaInstallazione { get; set; } [DataType(DataType.Date)] public DateTime gnr_UltimoIntervento { get; set; } public float gnr_OreUltimoIntervento { get; set; } public int gnr_Impianto { get; set; } public Boolean gnr_Rimosso { get; set; } public int clt_Id { get; set; } public int ipt_Id { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Threading.Tasks; using System.Security.Cryptography; namespace HelperClassAll { class HelperClass { public class SessionClass { public static object SessionVoid() { return HttpContext.Current.Session["id"]; } } public static int ReturnGetId() { return Convert.ToInt32(HttpContext.Current.Request.QueryString["id"]); } public static void UrlKategori() { HttpContext.Current.Response.Redirect("~/AdminPanel/kategori.aspx?slet=true"); } public static void UrlKategoriError() { HttpContext.Current.Response.Redirect("~/AdminPanel/kategori.aspx?error=true"); } public static void Error404() { HttpContext.Current.Response.Redirect("~/error.aspx?fejl=true"); } } public static class HelperStatic { public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> source, Random rng) { T[] elements = source.ToArray(); for (int i = elements.Length - 1; i >= 0; i--) { // Swap element "i" with a random earlier element it (or itself) // ... except we don't really need to swap it fully, as we can // return it immediately, and afterwards it's irrelevant. int swapIndex = rng.Next(i + 1); yield return elements[swapIndex]; elements[swapIndex] = elements[i]; } } } public static class Hash { public static string getHashSha256(string text) { byte[] key = Encoding.UTF8.GetBytes("a1515@€)A-83*2cQ1mlZaU"); byte[] bytes = Encoding.UTF8.GetBytes(text); HMACSHA256 hashstring = new HMACSHA256(key); byte[] hash = hashstring.ComputeHash(bytes); string hashString = string.Empty; foreach (byte x in hash) { hashString += String.Format("{0:x2}", x); } return hashString; } } }
using DSG东莞路测客户端; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace 电磁信息云服务CSharp { class BMap: WebBrowser { private string url = "http://123.207.31.37:8082/baidumap.html"; public string TZBQIco = "http://123.207.31.37:8082/bmapico/TZBQ.png" + "?t=" + DateTime.Now.Ticks; public string TSSIco = "http://123.207.31.37:8082/bmapico/TSS.png" + "?t=" + DateTime.Now.Ticks; public string disOnlineIco= "http://123.207.31.37:8082/bmapico/SH57_DisOnline.png" + "?t=" + DateTime.Now.Ticks; public string busIco= "http://123.207.31.37:8082/bmapico/bus.png" + "?t=" + DateTime.Now.Ticks; public delegate void dOnWebReady(); public event dOnWebReady OnWebReady; public bool isReady = false; private Control mControl; public BMap(Control control) { url= url + "?t=" + DateTime.Now.Ticks; this.mControl = control; this.ObjectForScripting = control; this.Dock = DockStyle.Fill; this.DocumentCompleted += Web_DocumentCompleted; this.Navigate(url); } private void Web_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { isReady = true; // SetCenter(Module.centerLng, Module.centerLat, Module.defaultMapSize); OnWebReady?.Invoke(); } public void SetCenter(double lng,double lat,int size) { if (!isReady) return; setGisCenter3(lng.ToString(), lat.ToString(), size); } public void AddPoint(double lng, double lat, string txt, DeviceInfo info) { if (!isReady) return; if (lng <= 0 || lat <= 0) return; string ico = TSSIco; if (info.Kind == "TZBQ") ico = TZBQIco; if (!info.IsOnline) ico = disOnlineIco; AddPoint(lng, lat, txt, ico); } public void AddPoint(double lng,double lat,string txt,string imgUrl="") { if (!isReady) return; if (string.IsNullOrEmpty(imgUrl)) { AddPoint(lng.ToString(), lat.ToString(), txt); } else { AddNewIco(lng.ToString(), lat.ToString(), txt, imgUrl); } } public void AddJumpPoint(double lng, double lat, string txt) { if (!isReady) return; AddJumpPoint(lng.ToString(), lat.ToString(), txt); } public void ClearAll() { if (!isReady) return; CleanGis(); } public void RemovePoint(string label) { if (!isReady) return; script("deletePoint", new string[] { label }); } public void ShowWarnWindow(double lng,double lat,string txt,bool flag=true) { if (!isReady) return; script("cleanall", new string[] { }); script("addpoint", new object[] { lng, lat, "", flag }); script("showWindowMsg", new object[] { lng, lat, txt, flag }); script("setcenter", new object[] { lng, lat }); } public void InitFreqGisParam() { freqGisOldLng = 0; freqFisOldLat = 0; freqGisOldPointInfo = ""; } private double freqGisOldLng, freqFisOldLat; private string freqGisOldPointInfo; public void AddFreqGisPoint(double lng,double lat,string showLabel,string lineName,string deviceId,bool isLockGisView,string colorName="blue") { if (!isReady) return; if (lng == 0 || lat == 0) return; if(freqGisOldLng==0 || freqFisOldLat == 0) { freqGisOldLng = lng; freqFisOldLat = lat; string jsNameTmp = "addFreqGisPoint"; object[] objTmp = new object[] { lng,lat,showLabel,true,isLockGisView,14,freqGisOldLng,freqFisOldLat,false,colorName,lineName,"",10,0.5 }; script(jsNameTmp, objTmp); freqGisOldPointInfo = showLabel; return; } string jsName = "addFreqGisPoint"; object[] obj = new object[] { lng,lat,showLabel,true,isLockGisView,14,freqGisOldLng,freqFisOldLat,true,colorName,lineName,"",10,0.5 }; script(jsName, obj); if (string.IsNullOrEmpty(freqGisOldPointInfo)) { freqGisOldPointInfo = showLabel; } else { jsName = "deletePoint"; obj = new object[] { freqGisOldPointInfo }; script(jsName, obj); freqGisOldPointInfo = showLabel; } freqGisOldLng = lng; freqFisOldLat = lat; } #region"浏览器与js交互" delegate void wt_cleanGis(); private void CleanGis() { wt_cleanGis d = new wt_cleanGis(th_CleanGis); this.mControl.Invoke(d, null); } private void th_CleanGis() { HtmlDocument doc = this.Document; if (doc==null) return; object[] ObjArr = new object[1]; doc.InvokeScript("cleanall", ObjArr); } delegate void wt_script(string scriptName, object[] str); private void script(string scriptName, object[] str) { if (!isReady) return; wt_script d = new wt_script(th_script); object[] b = new object[2]; b[0] = scriptName; b[1] = str; this.mControl.Invoke(d, b); } private void th_script(string scriptName, object[] str) { try { HtmlDocument doc = this.Document; object[] O = new object[str.Count()]; for (var i = 0; i <= str.Length - 1; i++) O[i] = (object)str[i]; doc.InvokeScript(scriptName, O); string kk = "0"; } catch (Exception ex) { string err = ex.ToString(); string kk = "0"; } } delegate void wt_setGisCenter(string lng, string lat); private void setGisCenter(string lng, string lat) { wt_setGisCenter d = new wt_setGisCenter(th_setGisCenter); object[] b = new object[2]; b[0] = lng; b[1] = lat; this.mControl.Invoke(d, b); } private void th_setGisCenter(string lng, string lat) { // 70410045 // 421127199303212592 // 梅子怀 HtmlDocument doc = this.Document; if (doc==null) return; object[] ObjArr = new object[3]; ObjArr[0] = (object)lng; ObjArr[1] = (object)lat; doc.InvokeScript("setcenter", ObjArr); } delegate void wt_setGisCenter3(string lng, string lat, int size); private void setGisCenter3(string lng, string lat, int size) { try { wt_setGisCenter3 d = new wt_setGisCenter3(th_setGisCenter3); object[] b = new object[3]; b[0] = lng; b[1] = lat; b[2] = size; this.mControl.Invoke(d, b); } catch (Exception) { } } private void th_setGisCenter3(string lng, string lat, int size) { // 70410045 // 421127199303212592 // 梅子怀 HtmlDocument doc = this.Document; if (doc==null) return; object[] ObjArr = new object[3]; ObjArr[0] = (object)lng; ObjArr[1] = (object)lat; ObjArr[2] = (object)size; doc.InvokeScript("setcenter3", ObjArr); } private void AddJumpPoint(string lng, string lat, string label) { wt_AddPoint d = new wt_AddPoint(th_AddJumpPoint); object[] b = new object[3]; b[0] = lng; b[1] = lat; b[2] = label; this.mControl.Invoke(d, b); } private void th_AddJumpPoint(string lng, string lat, string label) { HtmlDocument doc = this.Document; object[] ObjArr = new object[3]; ObjArr[0] = (object)lng; ObjArr[1] = (object)lat; ObjArr[2] = (object)label; doc.InvokeScript("addpoint", ObjArr); } delegate void wt_AddPoint(string lng, string lat, string label); private void AddPoint(string lng, string lat, string label) { wt_AddPoint d = new wt_AddPoint(th_AddPoint); object[] b = new object[3]; b[0] = lng; b[1] = lat; b[2] = label; this.mControl.Invoke(d, b); } private void AddNewIco(string lng, string lat, string label, string icoUrl) { script("addNewIcoPoint", new string[] { lng, lat, label, icoUrl }); } private void th_AddPoint(string lng, string lat, string label) { HtmlDocument doc = this.Document; if (doc==null) return; object[] ObjArr = new object[3]; ObjArr[0] = (object)lng; ObjArr[1] = (object)lat; ObjArr[2] = (object)label; doc.InvokeScript("addBz", ObjArr); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.AI; namespace RPG.SceneManagement { public class Portal : MonoBehaviour { enum DestinationIdentifiers { A,B,C } [SerializeField] private int sceneToLoadId = -1; [SerializeField] private Transform spawnPoint; [SerializeField] private DestinationIdentifiers destination; [SerializeField] private float fadeOutTime=1f; [SerializeField] private float fadeInTime = 1f; [SerializeField] private float waitTimeWhileFaded = 1f; private SavingWrapper savingWrapper; private void OnTriggerEnter(Collider other) { if (other.tag == "Player") { StartCoroutine(Transition()); } } private IEnumerator Transition() { if (sceneToLoadId < 0) { Debug.LogError("Scene to load not set"); yield break; } DontDestroyOnLoad(gameObject); Fader fader = FindObjectOfType<Fader>(); yield return fader.FadeOut(fadeOutTime); savingWrapper = FindObjectOfType<SavingWrapper>(); savingWrapper.Save(); yield return SceneManager.LoadSceneAsync(sceneToLoadId); savingWrapper.Load(); Portal otherPortal = GetOtherPortal(); UpdatePlayer(otherPortal); savingWrapper.Save(); yield return new WaitForSeconds(waitTimeWhileFaded); yield return fader.FadeIn(fadeInTime); Destroy(gameObject); } private void UpdatePlayer(Portal otherPortal) { var player = GameObject.FindGameObjectWithTag("Player"); player.GetComponent<NavMeshAgent>().Warp(otherPortal.spawnPoint.position); player.transform.rotation = otherPortal.spawnPoint.rotation; } private Portal GetOtherPortal() { foreach(var portal in FindObjectsOfType<Portal>()) { if (portal != this && portal.destination==destination) { return portal; } } return null; } } }
using UnityEngine; using UnityEditor; [CustomEditor(typeof(NoiseVisualizer))] public class NoiseVisualizerEditor : Editor { public override void OnInspectorGUI () { if(GUILayout.Button("Generate")) { (target as NoiseVisualizer).Generate (); } if (DrawDefaultInspector ()) { (target as NoiseVisualizer).Generate (); } } }
using System; using System.Collections; using UnityEngine; using UnityEngine.UI; using TMPro; using CodeMonkey.Utils; public class UI_Inventory : MonoBehaviour{ public Inventory inventory; private Transform itemSlotContainer; private Transform itemSlotTemplate; private PlayerMovement player; private Transform Player; private Animator ArmsAnimator; private Animator BodyAnimator; public static bool inventoryFull; public Transform shootTarget; private void Awake() { itemSlotContainer = transform.Find("itemSlotContainer"); itemSlotTemplate = itemSlotContainer.Find("itemSlotTemplate"); Player = GameObject.FindWithTag("Player").transform; ArmsAnimator = Player.Find("MC_Arms").GetComponent<Animator>(); BodyAnimator = Player.Find("MC_Body").GetComponent<Animator>(); shootTarget = GameObject.Find("ShootPoint").transform; } public void SetPlayer(PlayerMovement player) { this.player = player; } public void SetInventory(Inventory inventory) { this.inventory = inventory; inventory.OnItemListChanged += Inventory_OnItemListChanged; RefreshInventoryItems(); } private void Inventory_OnItemListChanged(object sender, System.EventArgs e) { RefreshInventoryItems(); } public void RefreshInventoryItems() { //delete existing inventory items foreach (Transform child in itemSlotContainer) { if (child == itemSlotTemplate) continue; Destroy(child.gameObject); } int x = 0; int y = 0; float itemSlotCellSize = 125f; foreach (Item item in inventory.GetItemList()) { RectTransform itemSlotRectTransform = Instantiate(itemSlotTemplate, itemSlotContainer).GetComponent<RectTransform>(); itemSlotRectTransform.gameObject.SetActive(true); itemSlotRectTransform.GetComponent<Button_UI>().ClickFunc = () => { inventory.UseItem(item); if (item.IsHoldable()) { ArmsAnimator.SetBool("Holding", true); BodyAnimator.SetBool("Holding", true); player.holdItem(item); } if (item.ranged()) { shootTarget.GetComponent<SpriteRenderer>().sprite = ItemAssets.Instance.lookTarget; } else { shootTarget.GetComponent<SpriteRenderer>().sprite = null; } }; itemSlotRectTransform.GetComponent<Button_UI>().MouseRightClickFunc = () => { //drop item Item duplicateItem = new Item { itemType = item.itemType, amount = item.amount }; inventory.RemoveItem(item); ItemWorld.DropItem(player.GetPosition(), duplicateItem); }; itemSlotRectTransform.anchoredPosition = new Vector2(x * itemSlotCellSize, y * itemSlotCellSize); Image image = itemSlotRectTransform.Find("sprite").GetComponent<Image>(); image.sprite = item.GetSprite(); TextMeshProUGUI uiText = itemSlotRectTransform.Find("Text").GetComponent<TextMeshProUGUI>(); if (item.amount > 1) { uiText.SetText(item.amount.ToString()); } else { uiText.SetText(""); } x++; if(x > 5) { inventoryFull = true; } else { inventoryFull = false; } } } }
using System; using System.Web.UI; using BLL.DLib; public partial class Controls_Library_LibraryInput : System.Web.UI.Page { #region vars public int LibID { get { return Request["LibID"] == "" ? 0 : Convert.ToInt32(Request["LibID"]); } } #endregion protected void Page_Load(object sender, EventArgs e) { if (!Access.IsAdmin()) Page.Response.Redirect("~/login.aspx"); if (!IsPostBack) FormInit(); } protected void FormInit() { if (LibID > 0) { Library lib = Library.GetLibrary(LibID); TXT_Title.Text = lib.Title; txtDomain.Text = lib.Domain; } } protected void BTN_Save_Click(object sender, EventArgs e) { Library.Save(LibID, TXT_Title.Text, txtDomain.Text, false, Access.GetCurrentUserID(), DateTime.Now); ScriptManager.RegisterStartupScript(this, this.GetType(), "mykey", "CloseAndRebind();", true); } }
using System; using Microsoft.HealthVault.ItemTypes; namespace HealthVault.Sample.Xamarin.Core.ViewModels { public static class DataTypeFormatter { public static DateTime EmptyDate { get; } = new DateTime(1900, 1, 1); public static string ApproximateDateTimeToString(ApproximateDateTime medicationDateStarted) { var current = ApproximateDateTimeToDateTime(medicationDateStarted); return current.ToString(System.Globalization.DateTimeFormatInfo.CurrentInfo.ShortDatePattern); } public static DateTime ApproximateDateTimeToDateTime(ApproximateDateTime medicationDateStarted) { ApproximateDate date = medicationDateStarted?.ApproximateDate; DateTime current; if (date == null) { current = EmptyDate; } else { var year = date.Year; var month = (date.Month != null) ? date.Month.Value : 1; var day = (date.Day != null) ? date.Day.Value : 1; current = new DateTime(year, month, day); } return current; } public static string FormatMedicationDetail(GeneralMeasurement medicationStrength, GeneralMeasurement medicationDose) { if (medicationStrength == null) { return medicationDose?.Display ?? ""; } if (medicationDose == null) { return medicationStrength?.Display ?? ""; } return $"{medicationStrength.Display}, {medicationDose.Display}"; } } }
using StardewValley; namespace Entoarox.Framework.Interface { internal interface IItemContainer { /********* ** Accessors *********/ Item CurrentItem { get; set; } bool IsGhostSlot { get; } /********* ** Methods *********/ bool AcceptsItem(Item item); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HW_4C_Farm_Part_2 { class Pig { private string animalName; public Pig() => Console.WriteLine("The pig's name was not provided"); public Pig(string name) { animalName = name; Console.WriteLine($"Hello, my name is {animalName}. "); } public string speak() { string sound = "Oink"; return sound; } public string eat() { string food = "slop"; return food; } public string movie() { string film = "Animal Farm"; return film; } public string product() { string service = "bacon"; return service; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CameraStart : MonoBehaviour { void Start() { CameraController.instance.SetMiddle(transform.position); } }
using Chess.v4.Engine.Interfaces; using EngineTests.Models; using Microsoft.Extensions.DependencyInjection; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EngineTests.Tests.EngineTests { [TestClass] public class CoordinateTests : TestBase { private readonly IAttackService _attackService; private readonly IGameStateService _gameStateService; private readonly IMoveService _moveService; private readonly IOrthogonalService _orthogonalService; public CoordinateTests() { _orthogonalService = ServiceProvider.GetService<IOrthogonalService>(); _attackService = ServiceProvider.GetService<IAttackService>(); _gameStateService = ServiceProvider.GetService<IGameStateService>(); _moveService = ServiceProvider.GetService<IMoveService>(); } [TestMethod] public void RankFileTests() { var a1RookAttackRank = _orthogonalService.GetEntireRank(0); Assert.IsTrue(a1RookAttackRank.Contains(0)); Assert.IsTrue(a1RookAttackRank.Contains(1)); Assert.IsTrue(a1RookAttackRank.Contains(2)); Assert.IsTrue(a1RookAttackRank.Contains(3)); Assert.IsTrue(a1RookAttackRank.Contains(4)); Assert.IsTrue(a1RookAttackRank.Contains(5)); Assert.IsTrue(a1RookAttackRank.Contains(6)); Assert.IsTrue(a1RookAttackRank.Contains(7)); var a1RookAttackFile = _orthogonalService.GetEntireFile(0); Assert.IsTrue(a1RookAttackFile.Contains(0)); Assert.IsTrue(a1RookAttackFile.Contains(8)); Assert.IsTrue(a1RookAttackFile.Contains(16)); Assert.IsTrue(a1RookAttackFile.Contains(24)); Assert.IsTrue(a1RookAttackFile.Contains(32)); Assert.IsTrue(a1RookAttackFile.Contains(40)); Assert.IsTrue(a1RookAttackFile.Contains(48)); Assert.IsTrue(a1RookAttackFile.Contains(56)); } } }
// <copyright file="TurnBasedEventHandlers.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2020 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using FiroozehGameService.Models; using FiroozehGameService.Models.Enums.GSLive; using FiroozehGameService.Models.GSLive; using FiroozehGameService.Models.GSLive.Command; using FiroozehGameService.Models.GSLive.Providers; using FiroozehGameService.Models.GSLive.TB; /** * @author Alireza Ghodrati */ namespace FiroozehGameService.Handlers { /// <inheritdoc /> /// <summary> /// Represents TurnBasedEventHandlers In MultiPlayer System /// </summary> public class TurnBasedEventHandlers : CommandEventHandlers { internal static EventHandler<string> TurnBasedAuthorized; internal static EventHandler<GTcpConnection> TurnBasedClientConnected; internal static EventHandler<GameServiceException> GsTurnBasedClientError; internal static EventHandler<Packet> TurnBasedMirror; internal static EventHandler TurnBasedPing; internal static EventHandler LeftDispose; internal static EventHandler GsTurnBasedClientConnected; /// <summary> /// Calls When SomeOne Join To Current Room /// It Maybe Current Player or Another /// This Event Handler Called By Following Functions : /// <see cref="GsLiveTurnBasedProvider.JoinRoom" /> /// <see cref="GsLiveTurnBasedProvider.CreateRoom" /> /// <see cref="GsLiveTurnBasedProvider.AutoMatch" /> /// </summary> public static EventHandler<JoinEvent> JoinedRoom; /// <summary> /// Calls When Current Player Reconnect to Server /// </summary> public static EventHandler<ReconnectStatus> Reconnected; /// <summary> /// Calls When SomeOne Left the Current Room /// This Event Handler Called By Following Function : /// <see cref="GsLiveTurnBasedProvider.LeaveRoom" /> /// </summary> public static EventHandler<Member> LeftRoom; /// <summary> /// Calls When SomeOne Send Message In Current Room /// This Event Handler Called By Following Functions : /// <see cref="GsLiveTurnBasedProvider.SendPublicMessage" /> /// <see cref="GsLiveTurnBasedProvider.SendPrivateMessage" /> /// </summary> public static EventHandler<MessageReceiveEvent> NewMessageReceived; /// <summary> /// Returns New Turn With Data From Another Players When Call The Following Function : /// <see cref="GsLiveTurnBasedProvider.TakeTurn" /> /// </summary> public static EventHandler<Turn> TakeTurn; /// <summary> /// Returns New Turn From Another Players When Call The Following Function : /// <see cref="GsLiveTurnBasedProvider.ChooseNext" /> /// </summary> public static EventHandler<Member> ChoosedNext; /// <summary> /// Returns NewOrUpdate Property From Another Players When Call The Following Functions : /// <see cref="GsLiveTurnBasedProvider.SetOrUpdateProperty" /> /// <see cref="GsLiveTurnBasedProvider.RemoveProperty" /> /// </summary> public static EventHandler<PropertyPayload> PropertyUpdated; /// <summary> /// Returns Properties From Another Players When Call The Following Function : /// <see cref="GsLiveTurnBasedProvider.GetMemberProperties" /> /// </summary> public static EventHandler<List<PropertyData>> MemberPropertiesReceived; /// <summary> /// Returns Room Info When Call The Following Function : /// <see cref="GsLiveTurnBasedProvider.GetCurrentRoomInfo" /> /// </summary> public static EventHandler<RoomData> CurrentRoomInfoReceived; /// <summary> /// Calls When SomeOne Announced To Finish Game /// This Event Handler Called By Following Function : /// <see cref="GsLiveTurnBasedProvider.Vote" /> /// </summary> public static EventHandler<Vote> VoteReceived; /// <summary> /// Calls When Accept Vote Received From Other Players /// This Event Handler Called By Following Function : /// <see cref="GsLiveTurnBasedProvider.AcceptVote" /> /// </summary> public static EventHandler<AcceptVote> AcceptVoteReceived; /// <summary> /// Returns Current Room Members Detail When Call The Following Function : /// <see cref="GsLiveTurnBasedProvider.GetRoomMembersDetail" /> /// </summary> public static EventHandler<List<Member>> RoomMembersDetailReceived; /// <summary> /// Returns Current Turn Member Received When Call The Following Function : /// <see cref="GsLiveTurnBasedProvider.GetCurrentTurnMember" /> /// </summary> public static EventHandler<Member> CurrentTurnMemberReceived; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; /// <summary> /// Description résumée de TypeFinitionRepository /// </summary> public class TypeFinitionRepository { public TypeFinitionRepository() { // // TODO: Add constructor logic here // } public TypeFinition GetOne(int id) { TypeFinition dto = new TypeFinition(); using (var db = new maderaEntities()) { var query = from a in db.TYPE_FINITION where a.TYPE_FINITION_ID.Equals(id) select a; dto.Id = query.First().TYPE_FINITION_ID; dto.Nom = query.First().TYPE_FINITION_NOM; } return dto; } }
using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using MQTTnet.Adapter; using MQTTnet.Client; using MQTTnet.Client.Connecting; using MQTTnet.Client.Options; using MQTTnet.Formatter; using MQTTnet.Protocol; namespace MQTTnet.Tests.Server { [TestClass] public sealed class Server_Reference_Tests : BaseTestClass { [TestMethod] public async Task Server_Reports_With_Reference_Server() { using (var testEnvironment = CreateTestEnvironment()) { testEnvironment.IgnoreClientLogErrors = true; await testEnvironment.StartServer(o => { o.WithConnectionValidator(v => { v.ReasonCode = MqttConnectReasonCode.ServerMoved; v.ServerReference = "new_server"; }); }); try { var client = testEnvironment.CreateClient(); await client.ConnectAsync(new MqttClientOptionsBuilder() .WithProtocolVersion(MqttProtocolVersion.V500) .WithTcpServer("127.0.0.1", testEnvironment.ServerPort) .Build()); Assert.Fail(); } catch (MqttConnectingFailedException e) { Assert.AreEqual(MqttClientConnectResultCode.ServerMoved, e.ResultCode); Assert.AreEqual("new_server", e.Result.ServerReference); } } } } }
using System.Collections.Generic; using Assets.Scripts.Models.ResourceObjects; namespace Assets.Scripts.Models.Common { public class GardenBedStone : BaseObject, IPlacement { public string PrefabTemplatePath { get; set; } public string PrefabPath { get; set; } public GardenBedStone() { LocalizationName = "garden_bed"; Description = "garden_bed_descr"; IconName = "garden_bed_stone"; IsStackable = false; PrefabTemplatePath = "Prefabs/Items/PlacedItems/GardenBed/GardenBedStoneTemplate"; PrefabPath = "Prefabs/Items/PlacedItems/GardenBed/GardenBedStone"; CraftRecipe = new List<HolderObject>(); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(StoneResource), 30)); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(Manure), 20)); CraftRecipe.Add(HolderObjectFactory.GetItem(typeof(GroundResource), 30)); } } }
using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Persons { public class AdminPersonImportType : Entity { public virtual string AdminPersonImportTypeName { get; set; } public virtual bool Archive { get; set; } public virtual string Notes { get; set; } public override string ToString() { return this.AdminPersonImportTypeName; } } }
using System.Collections.Generic; using DealOrNoDeal.Model; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace DealOrNoDeal.Tests.GameManagerTests { [TestClass] public class TestRemoveBriefcaseFromPlay { [TestMethod] public void ShouldNotRemoveBriefcaseIfBriefcaseIsNotPresentInListOfManyItems() { var manager = new GameManager(new List<int> { 1, 2, 3 }, new List<int> { 10, 20, 30 }); Assert.AreEqual(-1, manager.RemoveBriefcaseFromPlay(4)); Assert.AreEqual(0, manager.RoundManager.CasesLeftForCurrentRound); } [TestMethod] public void ShouldRemoveFirstBriefcase() { var manager = new GameManager(new List<int> { 2, 1 }, new List<int> { 10, 20, 30, 40 }); Assert.AreNotEqual(-1, manager.RemoveBriefcaseFromPlay(0)); Assert.AreEqual(1, manager.RoundManager.CasesLeftForCurrentRound); } [TestMethod] public void ShouldRemoveMiddleBriefcase() { var manager = new GameManager(new List<int> { 2, 1 }, new List<int> { 10, 20, 30, 40 }); Assert.AreNotEqual(-1, manager.RemoveBriefcaseFromPlay(1)); Assert.AreEqual(1, manager.RoundManager.CasesLeftForCurrentRound); } [TestMethod] public void ShouldRemoveLastBriefcase() { var manager = new GameManager(new List<int> { 2, 1 }, new List<int> { 10, 20, 30, 40 }); Assert.AreNotEqual(-1, manager.RemoveBriefcaseFromPlay(2)); Assert.AreEqual(1, manager.RoundManager.CasesLeftForCurrentRound); } } }
using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Threading; using KartObjects.Entities.Documents; namespace AxisEq { public class SRP:SoftwarePrinter { protected SerialPort sp; //com порт для связи //protected SRPCommand cmd; public override int Open(string portName, string Baud, string OpName, string Psw, params object[] arg) { try { sp = new SerialPort(portName, Convert.ToInt32(Baud), Parity.None, 8, StopBits.One); //sp.Handshake = Handshake.None; sp.Handshake = Handshake.RequestToSend; sp.NewLine = Environment.NewLine; sp.Open(); base.Open(portName, "", "", "", "SRP"); ScrollToCut(); CutOff(); } catch (Exception) { Close(); return (int)PrinterError.ERR_WINDOWS; } return 0; } protected virtual byte[] SRPOpenDrawerCommand { get { return new byte[] { 27, 112, 48, 100, 100 }; } } protected virtual byte[] SRPGetStateCommand { get { return new byte[] { 16, 4, 2 }; } } protected virtual byte[] SRPGetStatusCommand { get { return new byte[] { 16, 4, 3 }; } } protected virtual byte[] SRPCutCommand { get { return new byte[] { 29, 86, 0 }; } } protected List<byte> SRPSendCommand(byte[] dataToSend, bool needResponse) { sp.Write(dataToSend, 0, dataToSend.Length); List<byte> buf = new List<byte>(); if (needResponse) { sp.ReadTimeout = 5000; Thread.Sleep(100); while (sp.BytesToRead > 0) { buf.Add((byte)sp.ReadByte()); } } return buf; } public override int OpenCashDrawer() { /*cmd = new SRPG_GeneratePulse(); cmd.Send(sp); */ SRPSendCommand(SRPOpenDrawerCommand, false); return 0; } public override int PrintFreeDoc(KartObjects.Receipt receipt) { int res=base.PrintFreeDoc(receipt); ScrollToCut(); CutOff(); return res; } public override int XReport() { base.XReport(); ScrollToCut(); CutOff(); return 0; } public override int ZReport(ZReport z) { base.ZReport(z); ScrollToCut(); CutOff(); return 0; } public override void PrintHeader() { //cmd = new SRP_WriteLine(" ".PadRight(42)); //cmd.Send(sp); SRPSendCommand(Encoding.GetEncoding(1251).GetBytes(" ".PadRight(42)), false); if (HeaderStrings.Length > 0) { SRPSendCommand(Encoding.GetEncoding(1251).GetBytes(HeaderStrings[0].PadRight(42) + "\n\r"),false); WriteToLog(HeaderStrings[0].PadRight(42)); } if (HeaderStrings.Length > 1) { SRPSendCommand(Encoding.GetEncoding(1251).GetBytes(HeaderStrings[1].PadRight(42) + "\n\r"),false); WriteToLog(HeaderStrings[1].PadRight(42)); } if (HeaderStrings.Length > 2) { SRPSendCommand(Encoding.GetEncoding(1251).GetBytes(HeaderStrings[2].PadRight(42) + "\n\r"), false); WriteToLog(HeaderStrings[2].PadRight(42)); } if (HeaderStrings.Length > 3) { SRPSendCommand(Encoding.GetEncoding(1251).GetBytes(HeaderStrings[3].PadRight(42) + "\n\r"), false); WriteToLog(HeaderStrings[3].PadRight(42)); } } public override string ParseString(string st) { if (st.Contains("^cut")) { PrintHeader(); CutOff(); st = st.Replace("^cut", ""); } else if (st.Contains("^")) { printBarCode(st.Replace("^", String.Empty)); st = ""; } return st; } public override int PrintString(string Text) { string[] strs = Text.Split('\n'); foreach (string t in strs) { string str = t; ParseString(str); str = str.Replace("\r", ""); int l = str.Length; if (l <= 42) { for (int i = 1; i < 43 - l; i++) str = str + ' '; } else { str = str.Substring(0, 42); } /*cmd = new SRP_WriteLine(str); cmd.Send(sp);*/ SRPSendCommand(Encoding.GetEncoding(1251).GetBytes(str),false); } return base.PrintString(Text); } public override int CashOut(long Sum) { base.CashOut(Sum); ScrollToCut(); CutOff(); return 0; } public override int CutOff() { //cmd = new SRP_CutPaper(0); //cmd.Send(sp); SRPSendCommand(SRPCutCommand, false); return 0; } public override int CashIn(long Sum) { base.CashIn(Sum); ScrollToCut(); CutOff(); return 0; } public override int Close() { if (sp != null) { sp.Close(); } return base.Close(); } protected void ScrollToCut() { if (HeaderStrings!=null) PrintHeader(); else for (int i = 0; i < 4; i++) { PrintString(" "); } } /// <summary> /// Получить состояние регистратора /// </summary> /// <returns>Код ошибки</returns> public override PrinterState GetState() { PrinterState res = PrinterState.STATE_NORMAL; /*cmd = new SRP_StatusTransmission(2); cmd.Send(sp);*/ byte[] Answer=SRPSendCommand(SRPGetStateCommand,true).ToArray(); if (Answer.Length == 0) { res = PrinterState.STATE_NOTCONNECTED; return res; } if ((Answer[0] & (1 << 2)) >= 1) res = PrinterState.STATE_COVEROPEN; if ((Answer[0] & (1 << 3)) >= 1) res = PrinterState.STATE_FEEDING; Answer = SRPSendCommand(SRPGetStatusCommand, true).ToArray(); //cmd.Send(sp); if (((Answer[0] & (1 << 2)) >= 1) || ((Answer[0] & (1 << 3)) >= 1) || ((Answer[0] & (1 << 5)) >= 1) || ((Answer[0] & (1 << 6)) >= 1)) res = PrinterState.STATE_DAMAGED; /* cmd = new SRP_StatusTransmission(4); //paper status cmd.Send(sp); if ((cmd.Answer[0] & (1 << 2)) >= 1) res = PrinterState.STATE_PAPERENDING; if ((cmd.Answer[0] & (1 << 5)) >= 1) res = PrinterState.STATE_PAPEREND; */ return res; } public SRP() { this.logDir = ""; } public SRP(string logDir) { // TODO: Complete member initialization this.logDir = logDir; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DPYM; namespace DPYM_DEBUG { public class AboutRayCastAndCollider2D : MonoBehaviour { /* * 1、Rigidbody2D + Collider2D + Physics2D + RayCastHit2D 完成操作 * 3D的有3D的版本,2D的有2D的版本,必须对应 * 2、在进行Destroy的时候,如果Destroy的是 collider,那么只会将Collider组件销毁,而gameObject还在 * */ // Use this for initialization void Start() { line = gameObject.AddComponent<LineRenderer>(); line.startWidth = 0.1f; line.endWidth = 0.1f; } LineRenderer line; // Update is called once per frame void Update() { if (Input.GetMouseButtonDown(0)) { Vector3 org = Camera.main.ScreenToWorldPoint(Input.mousePosition); RaycastHit2D[] hits = Physics2D.RaycastAll(org, Vector2.zero, 1000); foreach(RaycastHit2D hit in hits) { Debug.LogFormat("Hit {0} !!!", hit.collider.name); Destroy(hit.collider.gameObject); } line.SetPosition(0, org); line.SetPosition(1, org + 10 * Vector3.forward); } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using GooglePlayGames; using UnityEngine.SocialPlatforms; public class CombatManager : MonoBehaviour { public int lenght; public List<GameObject> partyHeroes = new List<GameObject>(); public List<List<GameObject>> enemies = new List<List<GameObject>>(); public List<GameObject> deadHeroes = new List<GameObject>(); public bool inReward; public bool inCombat; public bool playersLost; public GameObject giftBox; public GameObject reward; public GameObject effect; public GameObject defeated; public GameObject victory; public Light caveLight; public float gameLenght; public float endPlayWaiter; void Update() { if (Camera.main.GetComponent<StateKeeper>().inPlay) { gameLenght += Time.deltaTime; if (partyHeroes.Count > 0 && !inCombat) Camera.main.transform.position = new Vector3(Camera.main.transform.position.x, Camera.main.transform.position.y, partyHeroes[0].transform.position.z - 32.5f); if (!inCombat && Camera.main.transform.position.z > lenght - 20) { int combatCounter = 0; for (int i = 0; i < partyHeroes.Count; i++) { if (partyHeroes[i].transform.position.z < -20 && partyHeroes[i].transform.position.z >= lenght && partyHeroes[i].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("idle")) { combatCounter++; } } if (combatCounter == partyHeroes.Count && partyHeroes.Count > 0) { for (int i = 0; i < partyHeroes.Count; i++) { partyHeroes[i].GetComponent<HeroCombatManager>().timeSinceAttacked = 0f; } inCombat = true; } } if (inCombat) { if (partyHeroes.Count == 0) { inCombat = false; playersLost = true; for (int i = 0; i < enemies[0].Count; i++) { enemies[0][i].GetComponent<HeroCombatManager>().isAttacking = false; enemies[0][i].GetComponent<HeroCombatManager>().isShooting = false; enemies[0][i].GetComponent<HeroCombatManager>().isCasting = false; enemies[0][i].GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f)); } } if (enemies.Count > 0) { if (enemies[0].Count == 0) { for (int i = 0; i < partyHeroes.Count; i++) { partyHeroes[i].GetComponent<HeroCombatManager>().isAttacking = false; partyHeroes[i].GetComponent<HeroCombatManager>().isShooting = false; partyHeroes[i].GetComponent<HeroCombatManager>().isCasting = false; } bool mayProceed = true; for (int i = 0; i < partyHeroes.Count; i++) { if (!partyHeroes[i].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("idle")) mayProceed = false; } if (mayProceed) { inCombat = false; enemies.RemoveAt(0); for (int i = 0; i < partyHeroes.Count; i++) { partyHeroes[i].GetComponent<Animator>().Play("walk", -1, Random.Range(0f, 1f)); } } } } } if (gameLenght > 300 && enemies.Count > 0) { gameLenght = 0f; for (int i = 0; i < partyHeroes.Count; i++) { partyHeroes[i].GetComponent<HeroAttributes>().heroHealth = 0; } inCombat = false; playersLost = true; for (int i = 0; i < enemies[0].Count; i++) { enemies[0][i].GetComponent<HeroCombatManager>().isAttacking = false; enemies[0][i].GetComponent<HeroCombatManager>().isShooting = false; enemies[0][i].GetComponent<HeroCombatManager>().isCasting = false; enemies[0][i].GetComponent<Animator>().Play("idle", -1, Random.Range(0f, 1f)); } } if (playersLost) { if (deadHeroes[deadHeroes.Count - 1].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("die")) { effect.GetComponent<SpriteRenderer>().color = new Color(1f, 0f, 0f, Mathf.Min(0.5f, deadHeroes[deadHeroes.Count - 1].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).normalizedTime / 2f)); } if (deadHeroes[deadHeroes.Count - 1].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).IsName("die") && deadHeroes[deadHeroes.Count - 1].GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).normalizedTime > 0.99) { if (defeated.transform.localPosition.x < 0) { defeated.transform.Translate(Time.deltaTime * 20f, 0f, 0f); if (defeated.transform.localPosition.x >= 0) { defeated.transform.localPosition = new Vector3(0f, 0f, -25f); endPlayWaiter = 0f; } } if (defeated.transform.localPosition.x == 0) { endPlayWaiter += Time.deltaTime; if (endPlayWaiter > 5 || Input.GetMouseButtonUp(0)) { inCombat = false; playersLost = false; gameLenght = 0f; effect.GetComponent<SpriteRenderer>().color = new Color(0f, 0f, 0f, 0f); defeated.transform.localPosition = new Vector3(-15f, 0f, -25f); Camera.main.GetComponent<StateKeeper>().inPlay = false; Camera.main.GetComponent<StateKeeper>().inMultiPlay = false; Camera.main.transform.position = new Vector3(0f, 0f, -10f); Camera.main.transform.rotation = Quaternion.Euler(0f, 0f, 0f); Camera.main.orthographicSize = 5f; caveLight.intensity = 0f; Camera.main.GetComponent<MenuTransitionHandler>().sunLight.intensity = 1f; Camera.main.GetComponent<MenuTransitionHandler>().sunLight.shadows = LightShadows.Hard; Camera.main.GetComponent<MenuTransitionHandler>().sunLight.transform.rotation = Quaternion.Euler(0f, 45f, 0f); } } } } if (inReward) { giftBox.transform.GetChild(0).localRotation = Quaternion.Lerp(giftBox.transform.GetChild(0).localRotation, Quaternion.Euler(270f, 180f, 180f), Time.deltaTime * 2f); reward.transform.position = Vector3.Lerp(reward.transform.position, new Vector3(reward.transform.position.x, -23f, reward.transform.position.z), Time.deltaTime * 1f); reward.transform.Rotate(0f, 0f, Time.deltaTime * -45f); giftBox.transform.GetChild(1).transform.localPosition = Vector3.Lerp(giftBox.transform.GetChild(1).transform.localPosition, new Vector3(giftBox.transform.GetChild(1).transform.localPosition.x, giftBox.transform.GetChild(1).transform.localPosition.y, 2.5f), Time.deltaTime * 1f); if (Vector3.Distance(reward.transform.position, new Vector3(reward.transform.position.x, -23f, reward.transform.position.z)) < 0.1) { effect.GetComponent<SpriteRenderer>().color = Color.Lerp(effect.GetComponent<SpriteRenderer>().color, new Color(0f, 1f, 0f, 0.5f), Time.deltaTime * 1f); } if (effect.GetComponent<SpriteRenderer>().color.a > 0.4 && victory.transform.localPosition.x < 0) { victory.transform.Translate(Time.deltaTime * 20f, 0f, 0f); if (victory.transform.localPosition.x >= 0) { victory.transform.localPosition = new Vector3(0f, 0f, -25f); endPlayWaiter = 0f; } } if (victory.transform.localPosition.x == 0) { endPlayWaiter += Time.deltaTime; if (endPlayWaiter > 5 || Input.GetMouseButtonUp(0)) { bool alreadyInCollection = false; foreach (GameObject hero in Camera.main.GetComponent<PlayerDataController>().partyHeroGameObjects) { if (hero.GetComponent<HeroAttributes>().heroMatchId == reward.GetComponent<HeroAttributes>().heroMatchId && reward.GetComponent<HeroAttributes>().heroMatchId != "") alreadyInCollection = true; } foreach (GameObject hero in Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects) { if (hero.GetComponent<HeroAttributes>().heroMatchId == reward.GetComponent<HeroAttributes>().heroMatchId && reward.GetComponent<HeroAttributes>().heroMatchId != "") alreadyInCollection = true; } if (!alreadyInCollection) { Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.Add(Instantiate(reward)); if (Camera.main.GetComponent<StateKeeper>().inMultiPlay) { PlayerPrefs.SetInt("duelVictories", PlayerPrefs.GetInt("duelVictories", 0) + 1); Social.ReportScore(PlayerPrefs.GetInt("duelVictories"), "CgkIoMyMiuAREAIQBw", (bool success) => {}); } Social.ReportProgress("CgkIoMyMiuAREAIQAQ", (double)Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.Count / 0.05, (bool success) => {}); Social.ReportProgress("CgkIoMyMiuAREAIQAg", (double)Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.Count / 0.1, (bool success) => {}); Social.ReportProgress("CgkIoMyMiuAREAIQBA", (double)Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.Count / 0.2, (bool success) => {}); Social.ReportProgress("CgkIoMyMiuAREAIQBQ", (double)Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.Count / 0.5, (bool success) => {}); Social.ReportProgress("CgkIoMyMiuAREAIQBg", (double)Camera.main.GetComponent<PlayerDataController>().allHeroGameObjects.Count / 1.0, (bool success) => {}); } Camera.main.GetComponent<PlayerDataController>().UpdateHeroStrings(); Camera.main.GetComponent<PlayerDataController>().UpdateHeroPlacesFast(); inReward = false; inCombat = false; gameLenght = 0f; effect.GetComponent<SpriteRenderer>().color = new Color(0f, 0f, 0f, 0f); victory.transform.localPosition = new Vector3(-15f, 0f, -25f); Camera.main.GetComponent<StateKeeper>().inPlay = false; Camera.main.GetComponent<StateKeeper>().inMultiPlay = false; Camera.main.transform.position = new Vector3(0f, 0f, -10f); Camera.main.transform.rotation = Quaternion.Euler(0f, 0f, 0f); Camera.main.orthographicSize = 5f; caveLight.intensity = 0f; Camera.main.GetComponent<MenuTransitionHandler>().sunLight.intensity = 1f; Camera.main.GetComponent<MenuTransitionHandler>().sunLight.shadows = LightShadows.Hard; Camera.main.GetComponent<MenuTransitionHandler>().sunLight.transform.rotation = Quaternion.Euler(0f, 45f, 0f); } } } } } public GameObject GetTarget(GameObject attacker) { int bestTarget = 0; GameObject target = null; if (partyHeroes.Contains(attacker) || (enemies[0].Contains(attacker) && attacker.GetComponent<HeroCombatManager>().attackSkill.Split('-')[0] == "Heal")) { target = enemies[0][0]; for(int i = 0; i < enemies[0].Count; i++) { if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "strenght") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroStrenght; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroStrenght > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroStrenght; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroStrenght < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroStrenght; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "dexterity") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroDexterity; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroDexterity > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroDexterity; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroDexterity < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroDexterity; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "magic") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroMagic; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroMagic > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroMagic; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroMagic < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroMagic; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "constitution") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroConstitution; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroConstitution > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroConstitution; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroConstitution < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroConstitution; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "reaction") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroReaction; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroReaction > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroReaction; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroReaction < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroReaction; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "magic resist") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroMagicResist; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroMagicResist > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroMagicResist; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroMagicResist < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroMagicResist; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "health") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroHealth; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroHealth > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroHealth; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroHealth < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroHealth; target = enemies[0][i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "cooldown") { if (i == 0) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroSpeed; target = enemies[0][i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (enemies[0][i].GetComponent<HeroAttributes>().heroSpeed > bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroSpeed; target = enemies[0][i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (enemies[0][i].GetComponent<HeroAttributes>().heroSpeed < bestTarget) { bestTarget = enemies[0][i].GetComponent<HeroAttributes>().heroSpeed; target = enemies[0][i]; } } } } } } if (enemies[0].Contains(attacker) || (partyHeroes.Contains(attacker) && attacker.GetComponent<HeroCombatManager>().attackSkill.Split('-')[0] == "Heal")) { target = partyHeroes[0]; for(int i = 0; i < partyHeroes.Count; i++) { if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "strenght") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroStrenght; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroStrenght > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroStrenght; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroStrenght < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroStrenght; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "dexterity") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroDexterity; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroDexterity > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroDexterity; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroDexterity < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroDexterity; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "magic") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroMagic; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroMagic > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroMagic; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroMagic < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroMagic; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "constitution") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroConstitution; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroConstitution > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroConstitution; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroConstitution < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroConstitution; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "reaction") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroReaction; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroReaction > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroReaction; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroReaction < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroReaction; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "magic resist") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroMagicResist; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroMagicResist > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroMagicResist; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroMagicResist < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroMagicResist; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "health") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroHealth; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroHealth > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroHealth; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroHealth < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroHealth; target = partyHeroes[i]; } } } } if(attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(1) == "cooldown") { if (i == 0) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroSpeed; target = partyHeroes[i]; } else { if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "+") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroSpeed > bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroSpeed; target = partyHeroes[i]; } } if (attacker.GetComponent<HeroAttributes>().heroAttackTarget.Substring(0, 1) == "-") { if (partyHeroes[i].GetComponent<HeroAttributes>().heroSpeed < bestTarget) { bestTarget = partyHeroes[i].GetComponent<HeroAttributes>().heroSpeed; target = partyHeroes[i]; } } } } } } return target; } }
namespace DM7_PPLUS_Integration.Daten { public readonly struct Datenstand { public readonly ulong Value; public Datenstand(ulong value) { Value = value; } public string Serialisiert() { return Value.ToString(); } public static Datenstand Aus_serialisiertem_Wert(string serialisiert) { return new Datenstand(ulong.Parse(serialisiert)); } } }
using Ricky.Infrastructure.Core.Configuration; namespace VnStyle.Services.Business.Settings { public class AppSetting : ISetting { public string ApplicationName { get; set; } public string HomepageContact1 { get; set; } public string HomepageContact2 { get; set; } public string Facebook { get; set; } public string Youtube { get; set; } public string Instagram { get; set; } public string FbAppId { get; set; } public string FbAppSecret { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ILogging { public interface ILogger { #region Debug /// <summary> /// Logs a debug message. /// </summary> /// <param name="message">The message to log.</param> void Debug(string message); /// <summary> /// Logs an exception with a logging level of <see cref="System.Diagnostics.Debug"/>. /// </summary> /// <param name="exception">The exception to log.</param> void Debug(Exception exception); /// <summary> /// Logs an exception and an additional message with a logging level of Debug /// </summary> /// <param name="exception"> The exception to log.</param> /// <param name="message">Additional information regarding the /// logged exception.</param> void Debug(Exception exception, string message); #endregion #region Info /// <summary> /// Logs an informational message /// </summary> /// <param name="message">The message to log.</param> void Info(string message); /// <summary> /// Logs an exception with a logging level of Info. /// </summary> /// <param name="exception">The exception to log.</param> void Info(Exception exception); /// <summary> /// Logs an exception and an additional message with a logging level of Info /// </summary> /// <param name="exception"> The exception to log.</param> /// <param name="message">Additional information regarding the /// logged exception.</param> void Info(Exception exception, string message); #endregion #region Warn /// <summary> /// Logs a warning message /// </summary> /// <param name="message">The message to log.</param> void Warn(string message); /// <summary> /// Logs an exception with a logging level of Warn /// </summary> /// <param name="exception">The exception to log.</param> void Warn(Exception exception); /// <summary> /// Logs an exception and an additional message with a logging level of Warn /// </summary> /// <param name="exception"> The exception to log.</param> /// <param name="message">Additional information regarding the /// logged exception.</param> void Warn(Exception exception, string message); #endregion #region Error /// <summary> /// Logs an error message /// </summary> /// <param name="message">The message to log.</param> void Error(string message); /// <summary> /// Logs an exception with a logging level of Error /// </summary> /// <param name="exception">The exception to log.</param> void Error(Exception exception); /// <summary> /// Logs an exception and an additional message with a logging level of /// <see cref="LogLevel.Error"/>. /// </summary> /// <param name="exception"> The exception to log.</param> /// <param name="message">Additional information regarding the /// logged exception.</param> void Error(Exception exception, string message); #endregion #region Fatal /// <summary> /// Logs a fatal error message /// </summary> /// <param name="message">The message to log.</param> void Fatal(string message); /// <summary> /// Logs an exception with a logging level of Fatal /// </summary> /// <param name="exception">The exception to log.</param> void Fatal(Exception exception); /// <summary> /// Logs an exception and an additional message with a logging level of Fatal /// </summary> /// <param name="exception"> The exception to log.</param> /// <param name="message">Additional information regarding the /// logged exception.</param> void Fatal(Exception exception, string message); #endregion } }
using System.Collections.Generic; using StardewModdingAPI; namespace Entoarox.Framework.Core.Utilities { internal class DictionaryAssetInfo<TKey, TValue> { /********* ** Accessors *********/ public IContentHelper ContentHelper { get; } public IDictionary<TKey, TValue> Data { get; } /********* ** Public methods *********/ public DictionaryAssetInfo(IContentHelper contentHelper, IDictionary<TKey, TValue> data) { this.ContentHelper = contentHelper; this.Data = data; } } }
using System; using System.Collections; using System.ComponentModel; using System.Linq; using DelftTools.Utils; using DelftTools.Utils.Collections; using DelftTools.Utils.Data; using log4net; namespace DelftTools.Functions { [Serializable] public class MultiDimensionalArray : Unique<long>, IMultiDimensionalArray { private static readonly ILog log = LogManager.GetLogger(typeof(MultiDimensionalArray)); protected IList values; protected virtual bool IsReferenceTyped { get { return true; } } private int[] shape; private int[] stride; private int rank; private int count; private bool fireEvents = true; private object defaultValue; public MultiDimensionalArray() : this(new[] { 0 }) { } public MultiDimensionalArray(params int[] shape) : this(null, shape) { } public MultiDimensionalArray(object defaultValue, params int[] shape) : this(false, false, defaultValue, shape) { } public MultiDimensionalArray(bool isReadOnly, bool isFixedSize, object defaultValue, IMultiDimensionalArray array) : this(isReadOnly, isFixedSize, defaultValue, array.Shape) { int i = 0; foreach (object value in array) { values[i++] = value; } } /// <summary> /// Creates a new multidimensional array using provided values as 1D array. /// Values in the provided list will used in a row-major order. /// </summary> /// <param name="isReadOnly"></param> /// <param name="isFixedSize"></param> /// <param name="defaultValue"></param> /// <param name="values"></param> /// <param name="shape"></param> public MultiDimensionalArray(bool isReadOnly, bool isFixedSize, object defaultValue, IList values, int[] shape) { if (values.Count != MultiDimensionalArrayHelper.GetTotalLength(shape)) throw new ArgumentException("Copy constructor shape does not match values"); IsReadOnly = isReadOnly; IsFixedSize = isFixedSize; DefaultValue = defaultValue; Shape = (int[])shape.Clone(); SetValues(CreateClone(values)); } public MultiDimensionalArray(bool isReadOnly, bool isFixedSize, object defaultValue, params int[] shape) { IsFixedSize = isFixedSize; DefaultValue = defaultValue; Shape = new[] { 0 }; SetValues(CreateValuesList()); Resize(shape); //set readonly at last IsReadOnly = isReadOnly; } /// <summary> /// Gets or sets owner. For optimization purposes only. /// This should go! Sound like a bad thing MDA knows about IVariable /// </summary> //public IVariable Owner { get; set; } #region IMultiDimensionalArray Members public virtual int Count { get { return count; } } public virtual object SyncRoot { get { return values.SyncRoot; } } public virtual bool IsSynchronized { get { return values.IsSynchronized; } } /// <summary> /// Determines whether the array maintains a sort by modifying inserts and updates to values. /// Only works in 1D situations for now /// </summary> public virtual bool IsAutoSorted { get; set; } public virtual bool IsReadOnly { get; set; } public virtual bool IsFixedSize { get; set; } public virtual object DefaultValue { get { return defaultValue; } set { defaultValue = value; } } public virtual int[] Shape { get { return shape; } set { shape = value; count = MultiDimensionalArrayHelper.GetTotalLength(shape); stride = MultiDimensionalArrayHelper.GetStride(shape); rank = shape.Length; singleValueLength = new int[rank]; for (var i = 0; i < singleValueLength.Length; i++) { singleValueLength[i] = 1; } } } public virtual int Rank { get { return rank; } } public virtual int[] Stride { get { return stride; } } object IList.this[int index] { get { return this[index]; } set { this[index] = value; } } #if MONO object IMultiDimensionalArray.this[int index] { get { return this[index]; } set { this[index] = value; } } #endif public virtual object this[params int[] index] { get { if (index.Length != rank) { if (index.Length == 1) // use 1D { return values[index[0]]; } throw new ArgumentException("Invalid number of indexes"); } if(index.Length == 1) // performance improvement { return values[index[0]]; } return values[MultiDimensionalArrayHelper.GetIndex1d(index, stride)]; } set { VerifyIsNotReadOnly(); //exception single dimensional access to More dimensional array used 1d array if (index.Length != rank) { /* if (index.Length == 1) // use 1D { ((IList)this)[index[0]] = value; dirty = true; //todo: collectionchanged etc return; } */ throw new ArgumentException("Invalid number of indexes"); } var index1d = MultiDimensionalArrayHelper.GetIndex1d(index, stride); var newValue = value; var newIndex = index1d; if(values[index1d] == value) { return; // do nothing, value is the same as old value } // log.DebugFormat("Value before Replace: {0}", this); if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Replace, value, index1d); if (args != null) { if (args.Cancel) { return; } newValue = args.Items[0]; newIndex = args.Index; } } if (IsAutoSorted) { if(newIndex != index1d) { throw new InvalidOperationException("Updating indexes in collectionChanging is not supported for AutoSortedArrays"); } //value or newValue (possible changed by changingEvent...) var oldIndex = index1d; newIndex = MultiDimensionalArrayHelper.GetInsertionIndex((IComparable)value, values.Cast<IComparable>().ToList()); if (newIndex > oldIndex) { newIndex--; //if value is currently left of the new index so our insert should be on index one less.. } } //actual set values... SetValue1D(newValue,index1d); //move values to correct location if necessary if (newIndex != index1d) { Move(0, index1d, 1, newIndex, false); } dirty = true; if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Replace, value, newIndex, index1d ); } // log.DebugFormat("Value after Replace: {0}", this); } } /*private void UpdateInsertionIndex(FunctionValuesChangingEventArgs e, IList<T> values) { if ((typeof(T) == typeof(string))) { return; // doesn't matter, it is always unique + we don't care about objects } var oldIndex = e.Index; e.Index = MultiDimensionalArrayHelper.GetInsertionIndex((T)e.Item, values); if (e.Action == NotifyCollectionChangeAction.Replace) { if (e.Index > oldIndex) // !@#@#?????? { e.Index--; } } } */ public virtual IEnumerator GetEnumerator() { return values.GetEnumerator(); // return new MultiDimensionalArrayEnumerator(this); } public virtual void CopyTo(Array array, int index) { values.CopyTo(array, index); } public virtual int Add(object value) { //add is and insert at dim 0,count if (Rank != 1) { throw new NotSupportedException("Use Resize() and this[] to work with array where number of dimensions > 1"); } return InsertAt(0, count, 1, new[] { value }); } private void VerifyIsNotReadOnly() { if (IsReadOnly) throw new InvalidOperationException("Illegal attempt to modify readonly array"); } void ItemPropertyChanging(object sender, PropertyChangingEventArgs e) { if (PropertyChanging != null) { PropertyChanging(sender, e); } } void ItemPropertyChanged(object sender, PropertyChangedEventArgs e) { if(PropertyChanged != null) { PropertyChanged(sender, e); } } public virtual bool Contains(object value) { if (rank == 1) { // performance optimization, edge case if (IsAutoSorted && count != 0 && (value as IComparable).IsBigger(MaxValue as IComparable)) { return false; } return values.Contains(value); } throw new NotImplementedException(); } public virtual void Clear() { VerifyIsNotReadOnly(); if (rank == 1) { while (Shape[0] > 0) { //TODO : increase performance by deleting all. Now events dont match up. Get one changed event when the whole //TODO : array is empty. Change events and batch delete. RemoveAt(0, Shape[0] - 1); } } else { Resize(new int[rank]); } } public virtual int IndexOf(object value) { return values.IndexOf(value); } public virtual void Remove(object value) { VerifyIsNotReadOnly(); if (rank == 1) { var index = values.IndexOf(value); if (index == -1) return; var valueToRemove = value; if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Remove, valueToRemove, index); if (args != null && args.Cancel) { return; } } RemoveValue1D(valueToRemove); shape[0]--; count = MultiDimensionalArrayHelper.GetTotalLength(shape); if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Remove, valueToRemove, index, -1); } } else { throw new NotSupportedException("Use Resize"); } } //TODO: rewrite this to use RemoveAt(index,dimension,length) public virtual void RemoveAt(int index) { VerifyIsNotReadOnly(); if (rank == 1) { var valueToRemove = values[index]; if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Remove, valueToRemove, index); if (args != null && args.Cancel) { return; } } RemoveAt1D(index); shape[0]--; count = MultiDimensionalArrayHelper.GetTotalLength(shape); if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Remove, valueToRemove, index, -1); } } else { throw new NotSupportedException("Use Resize"); } } public virtual void RemoveAt(int dimension, int index) { RemoveAt(dimension, index, 1); } private int[] singleValueLength; public virtual void RemoveAt(int dimension, int index, int length) { VerifyIsNotReadOnly(); if (rank == 1) { var elementsToRemove = length; while (elementsToRemove != 0) { RemoveAt(index); elementsToRemove--; } } else { //move items if (dimension > 0 || index != shape[dimension] - 1) // don't copy when 1st dimension and delete at the end (note: performance) { for (var i = 0; i < count; i++) // TODO: optimize this, probably it is better to iterate in nD array instead of 1d { var currentIndex = MultiDimensionalArrayHelper.GetIndex(i, stride); if ((currentIndex[dimension] < index) || (currentIndex[dimension] >= (shape[dimension] - length))) { continue; } // value is to be moved to a new spot in the array var oldIndexes = (int[]) currentIndex.Clone(); oldIndexes[dimension] += length; values[i] = values[MultiDimensionalArrayHelper.GetIndex1d(oldIndexes, stride)]; } } //trim the array var newShape = (int[])shape.Clone(); if (newShape[dimension] > 0) { newShape[dimension] -= length; } Resize(newShape); } } public virtual object Clone() { return new MultiDimensionalArray(IsReadOnly, IsFixedSize, DefaultValue, values, Shape); } /// <summary> /// Resizes array using new lengths of dimensions. /// </summary> /// <param name="newShape"></param> public virtual void Resize(params int[] newShape) { VerifyIsNotReadOnly(); //speed using inserts and remove at the bounds of dimensions... /*if (newShape.Length == Rank) { for (int i =0;i<Rank;i++) { var delta = newShape[i] - shape[i]; if (delta > 0) { InsertAt(i, shape[i], delta); } else if (delta < 0) { RemoveAt(i,shape[i]+delta); } } } */ // special case when only the first dimension is altered if (MultiDimensionalArrayHelper.ShapesAreEqualExceptFirstDimension(shape, newShape)) { // just in case, check if we really resizing if (shape[0] == newShape[0]) { return; } ResizeFirstDimension(newShape); return; } var oldShape = shape; var oldStride = stride; // TODO: optimize copy, currently it is very slow and unscalable // create a new defaultValue filled arrayList var newTotalLength = MultiDimensionalArrayHelper.GetTotalLength(newShape); var newValues = CreateValuesList(); for (int i = 0; i < newTotalLength; i++) { newValues.Add(defaultValue); } //var newValues = Enumerable.Repeat(defaultValue, newTotalLength).ToList(); var newStride = MultiDimensionalArrayHelper.GetStride(newShape); // copy old values to newValues if they are within a new shape, otherwise send Changing event for all *removed* values for (var i = 0; i < values.Count; i++) { var oldIndex = MultiDimensionalArrayHelper.GetIndex(i, stride); var isOldIndexWithinNewShape = MultiDimensionalArrayHelper.IsIndexWithinShape(oldIndex, newShape); if (!isOldIndexWithinNewShape) { if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Remove, values[i], i); if (args != null && args.Cancel) { return; } } continue; } var newValueIndex = MultiDimensionalArrayHelper.GetIndex1d(oldIndex, newStride); newValues[newValueIndex] = values[i]; } // set a new value and send Changing event for all *newly added* values for (var i = 0; i < newValues.Count; i++) { var newIndex = MultiDimensionalArrayHelper.GetIndex(i, newStride); var isNewIndexWithinOldShape = MultiDimensionalArrayHelper.IsIndexWithinShape(newIndex, shape); if (isNewIndexWithinOldShape) { continue; } var newValue = defaultValue; if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Add, newValue, i); if (args != null) { if (args.Cancel) { return; } newValue = args.Items[0]; } } newValues[i] = newValue; } var oldValues = values; // replace old values by new values SetValues(newValues); Shape = newShape; if (FireEvents) { // send Changed even for all *removed* values for (var i = 0; i < oldValues.Count; i++) { var oldIndex = MultiDimensionalArrayHelper.GetIndex(i, oldStride); var isIndexWithinNewShape = MultiDimensionalArrayHelper.IsIndexWithinShape(oldIndex, newShape); if (!isIndexWithinNewShape) { FireCollectionChanged(NotifyCollectionChangeAction.Remove, oldValues[i], i, -1); } } // send Changing event for all *newly added* values for (var i = 0; i < newValues.Count; i++) { var newIndex = MultiDimensionalArrayHelper.GetIndex(i, oldStride); var isNewIndexWithinOldShape = MultiDimensionalArrayHelper.IsIndexWithinShape(newIndex, oldShape); if (isNewIndexWithinOldShape) { continue; } FireCollectionChanged(NotifyCollectionChangeAction.Add, newValues[i], i, -1); } } } /// <summary> /// Sets underlying storage to a given array. No events are sent! Backdoor to internal storage. /// </summary> /// <param name="values"></param> public virtual void SetValues(IList values) { if (rank == 1) // Only for 1d { foreach (var o in values) { Subscribe(o); } } this.values = values; } private void ResizeFirstDimension(int[] newShape) { var valuesToAddCount = MultiDimensionalArrayHelper.GetTotalLength(newShape) - MultiDimensionalArrayHelper.GetTotalLength(shape); if (valuesToAddCount > 0) { /* bool generateUniqueValueForDefaultValue = false; if (null != Owner) { generateUniqueValueForDefaultValue = Owner.GenerateUniqueValueForDefaultValue; // newly added function should be unique Owner.GenerateUniqueValueForDefaultValue = true; }s*/ AddValuesToFirstDimension(newShape, valuesToAddCount); /*if (null != Owner) { Owner.GenerateUniqueValueForDefaultValue = generateUniqueValueForDefaultValue; }*/ } else if (valuesToAddCount < 0)// remove values at the end. { RemoveValuesFromFirstDimension(newShape, valuesToAddCount); } else { Shape = newShape; } } private void RemoveValuesFromFirstDimension(int[] newShape, int valuesToAddCount) { var valuesToRemoveCount = Math.Abs(valuesToAddCount); // remove all values if (valuesToRemoveCount == values.Count) { Clear(); //Set the shape because clear makes it 0,0...other dimensions might not be 0 Shape = newShape; } else { if (FireEvents) { // send Changing evenrs for (var index1d = values.Count - 1; index1d < values.Count - 1 - valuesToRemoveCount; index1d--) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Remove, values[index1d], index1d); if (args != null && args.Cancel) { return; } } } // remove values for (var i = 0; i < valuesToRemoveCount; i++) { values.RemoveAt(values.Count - 1); } Shape = newShape; if (FireEvents) { // send Changed events for (var index1d = values.Count; index1d < values.Count + valuesToRemoveCount; index1d++) { var removedValue = defaultValue; // TODO: this should be real value FireCollectionChanged(NotifyCollectionChangeAction.Remove, removedValue, index1d, -1); } } } } private void AddValuesToFirstDimension(int[] newShape, int valuesToAddCount) { var valuesToInsertShape = (int[])newShape.Clone(); //we can copy everything but the first dimension valuesToInsertShape[0] = newShape[0] - shape[0]; //take the delta for first dimension var valuesToAdd = new object[valuesToAddCount]; int insertIndex = values.Count; for (var i = 0; i < valuesToAddCount; i++) { valuesToAdd[i] = defaultValue; } if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Add, valuesToAdd, insertIndex, valuesToInsertShape); if (args != null && args.Cancel) { return; } } foreach (var o in valuesToAdd) { values.Add(o); } Shape = newShape; if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Add, valuesToAdd, insertIndex, -1, valuesToInsertShape); } } public virtual void Insert(int index, object value) { VerifyIsNotReadOnly(); if (rank != 1) { throw new NotSupportedException("Use SetValue to set values"); } var newValue = value; if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Add, newValue, index); if (args != null) { if (args.Cancel) { return; } newValue = args.Items[0]; } } //InsertValues1D(index, newValue); InsertValues1D(newValue, index); shape[0]++; count = MultiDimensionalArrayHelper.GetTotalLength(shape); dirty = true;//update min/max after insert..maybe check if the value we inserted is > max or < min if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Add, newValue, index, -1); } } public virtual void InsertAt(int dimension, int index) { InsertAt(dimension, index, 1); } public virtual void InsertAt(int dimension, int index, int length) { // THE REST IS VERY SLOW BECAUSE ALL VALUES ARE COPIED! // compute number of values to be added object[] valuesToAdd = GetDefaultValuesToAdd(dimension, length); //no values are added ..just a resize with some dimensions at 0 if (valuesToAdd.Length == 0) { var newShape = (int[])shape.Clone(); newShape[dimension] += length; Resize(newShape); } else { InsertAt(dimension, index, length, valuesToAdd); } } private object[] GetDefaultValuesToAdd(int dimension, int length) { var valuesToAddShape = (int[])shape.Clone(); valuesToAddShape[dimension] = length; var newValuesCount = MultiDimensionalArrayHelper.GetTotalLength(valuesToAddShape); var valuesToAdd = new object[newValuesCount]; for (var i = 0; i < newValuesCount; i++) { valuesToAdd[i]= defaultValue; } return valuesToAdd; } //TODO: change this signature of values object[] this will cause boxing and bad performance probably.. //push the functionality down to the generic subclass. /// <summary> /// Insert a slices of value(s) for a given dimension /// </summary> /// <param name="dimension">Dimensen at which to insert</param> /// <param name="index">Index of insert for dimension</param> /// <param name="length">Length (in the dimensions). In 1D this is ValuesToInsert.Count but not in n-D</param> /// <param name="valuesToInsert">Total values</param> /// <returns></returns> public virtual int InsertAt(int dimension, int index, int length, IList valuesToInsert) { if (length == 0) return -1; //resize the array. This can cause a change of stride //copy values etc. Refactor resize and copy data operation? //increment the correct dimensions var newShape = (int[])shape.Clone(); newShape[dimension] += length; // THE REST IS VERY SLOW BECAUSE ALL VALUES ARE COPIED! // compute number of values to be added var valuesToInsertShape = (int[])shape.Clone(); valuesToInsertShape[dimension] = length; MultiDimensionalArrayHelper.VerifyValuesCountMatchesShape(valuesToInsertShape, valuesToInsert); var newStride = MultiDimensionalArrayHelper.GetStride(newShape); var valueToAddIndex = new int[rank]; valueToAddIndex[dimension] = index; int insertionStartIndex = MultiDimensionalArrayHelper.GetIndex1d(valueToAddIndex, newStride); // send Changing events if (FireEvents) { var args = FireCollectionChanging(NotifyCollectionChangeAction.Add, valuesToInsert, insertionStartIndex, valuesToInsertShape); //TODO: handle changes from changing event..allows for sorting (a little bit) if (args != null) { if (args.Cancel) { return -1; } if (args.Index != insertionStartIndex && IsAutoSorted) { throw new InvalidOperationException("Sorted array does not allow update of Indexes in CollectionChanging"); } } } if (IsAutoSorted) { //values values to insert have values smaller than MaxValue throw var comparables = valuesToInsert.Cast<IComparable>(); var monotonous =comparables.IsMonotonousAscending(); // first is the smallest value since comparables is monotonous ascending :) var allBiggerThanMaxValue = ((MaxValue == null) || ((MaxValue as IComparable).IsSmaller(comparables.First()))); if (comparables.Count()>1 && (!allBiggerThanMaxValue || !monotonous)) { throw new InvalidOperationException( "Adding range of values for sorted array is only possible if these values are all bigger than the current max and sorted"); } //get the 'real' insertion indexes..first for 1 value //omg this must be slow...get this faster by //A : using the knowledge that the array was sorted (binarysort) //B : using the type of T by moving this into a virtual method and push it down to a subclass insertionStartIndex = GetInsertionStartIndex(valuesToInsert); index = insertionStartIndex;//review and fix all these indexes..it is getting unclear..work in MDA style.. } //performance increase when adding to the first dimension...no stuff will be moved so not need to go throught the whole array later on bool insertIsAtBoundsOfFirstDimension = dimension == 0 && index == shape[0]; var eventsAreFired = fireEvents; fireEvents = false; Resize(newShape); // TODO: dangerous, Shape and Stride will already change here fireEvents = eventsAreFired; dirty = true;//make sure min/max are set dirty //simple insert...at bounds of first index if (insertIsAtBoundsOfFirstDimension) { var addedValueIndex = 0; do { int newIndex1d = MultiDimensionalArrayHelper.GetIndex1d(valueToAddIndex, newStride); var newValue = valuesToInsert[addedValueIndex]; SetValue1D(newValue, newIndex1d); addedValueIndex++; } while (MultiDimensionalArrayHelper.IncrementIndex(valueToAddIndex, newShape, rank - 1)); //fill it up until the whole new shape is filled..because we are are at the bounds of the first dimension if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Add, valuesToInsert, insertionStartIndex, -1, valuesToInsertShape); } } else //complex...insert could be everywhere and might have to move stuff in the underlying array.. { //walk down the values in the underlying array //copy the values to a new spot if the value is to be moved int addedValueIndex = valuesToInsert.Count - 1; var newIndex = MultiDimensionalArrayHelper.GetIndex(count - 1, stride); //start at end for (var i = count - 1; i >= 0; i--) { // value is to be moved if (newIndex[dimension] >= index + length) { var oldIndex = (int[])newIndex.Clone(); oldIndex[dimension] -= length; values[MultiDimensionalArrayHelper.GetIndex1d(newIndex, stride)] = values[MultiDimensionalArrayHelper.GetIndex1d(oldIndex, stride)]; //set the 'old' copy to 'null' to prevent unsubscribtion when we replace it by the new value values[MultiDimensionalArrayHelper.GetIndex1d(oldIndex, stride)] = defaultValue; } // new value added if ((newIndex[dimension] >= index) && (newIndex[dimension] < index + length)) { var index1d = MultiDimensionalArrayHelper.GetIndex1d(newIndex, stride); var newValue = valuesToInsert[addedValueIndex]; SetValue1D(newValue,index1d); addedValueIndex--;//walk down because we start at the end } if (i > 0) //decrementing last time won't work { MultiDimensionalArrayHelper.DecrementIndexForShape(newIndex,newShape); } } if (FireEvents) { FireCollectionChanged(NotifyCollectionChangeAction.Add, valuesToInsert,insertionStartIndex,-1,valuesToInsertShape); } } return index;//this might be wrong..the index might have changed } /// <summary> /// Removes value and does unsubscribe /// </summary> /// <param name="valueToRemove"></param> private void RemoveValue1D(object valueToRemove) { Unsubscribe(valueToRemove); values.Remove(valueToRemove); } private void Subscribe(object item) { if (!IsReferenceTyped) return; if (item is INotifyPropertyChanged) { ((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged; } if (item is INotifyPropertyChanging) { ((INotifyPropertyChanging)item).PropertyChanging += ItemPropertyChanging; } } private void Unsubscribe(object item) { if (!IsReferenceTyped) return; if (item is INotifyPropertyChanged) { ((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged; } if (item is INotifyPropertyChanging) { ((INotifyPropertyChanging)item).PropertyChanging -= ItemPropertyChanging; } } /// <summary> /// Sets value in underlying array and subscribes to changes if possible /// </summary> /// <param name="newValue"></param> /// <param name="newIndex1D"></param> private void SetValue1D(object newValue, int newIndex1D) { if (IsReferenceTyped) { var oldValue = values[newIndex1D]; Unsubscribe(oldValue); Subscribe(newValue); } values[newIndex1D] = newValue; } private void InsertValues1D(object newValue, int index) { Subscribe(newValue); values.Insert(index, newValue); } private void RemoveAt1D(int index1D) { var oldValue = values[index1D]; RemoveValue1D(oldValue); } protected virtual int GetInsertionStartIndex(IList valuesToInsert) { return MultiDimensionalArrayHelper.GetInsertionIndex((IComparable)valuesToInsert[0], values.Cast<IComparable>().ToList()); } /// <summary> /// In 1d case, move vales at index 1, length = 2 to index 2: /// /// <code> /// 1 [2 3] 4 5 => 1 4 [2 3] 5 /// </code> /// </summary> /// <param name="dimension"></param> /// <param name="index"></param> /// <param name="length"></param> /// <param name="newIndex"></param> public virtual void Move(int dimension, int index, int length, int newIndex) { Move(dimension, index, length, newIndex, true); } /// <summary> /// In 1d case, move vales at index 1, length = 2 to index 2: /// /// <code> /// 1 [2 3] 4 5 => 1 4 [2 3] 5 /// </code> /// </summary> /// <param name="dimension"></param> /// <param name="index"></param> /// <param name="length"></param> /// <param name="newIndex"></param> /// <param name="fireEvents"></param> private void Move(int dimension, int index, int length, int newIndex, bool fireEvents) { //where is the changing event in this case??? only changed is made and fired? VerifyIsNotReadOnly(); // 1 [2 3][4 5] // view1 view2 //1 store the value(s) to move in a tmp array var valuesToMoveView = Select(dimension, index, index + length - 1); var tmpValueToMove = new object[valuesToMoveView.Count]; valuesToMoveView.CopyTo(tmpValueToMove, 0); bool eventsAreToBeFired = FireEvents && fireEvents; if (eventsAreToBeFired) { var minIndex = Math.Min(index, newIndex); var maxIndex = Math.Max(index, newIndex) + length - 1; for (int i = minIndex; i <= maxIndex; i++) { //TODO: add value..it is needed in UNDO? FireCollectionChanging(NotifyCollectionChangeAction.Replace, null, i); } } bool oldIsSorted = IsAutoSorted; var oldFireEvents = FireEvents; FireEvents = false; IsAutoSorted = false; // 2 Move values between index en newindex in the correct direction if (newIndex > index) { CopyLeft(dimension, index + length, newIndex - index, length); } else { CopyRight(dimension, newIndex, index - newIndex, length); } //3 Place the tmp values at the target var targetLocation1 = Select(dimension, newIndex, newIndex + length - 1); for (int i =0 ;i<targetLocation1.Count;i++) { targetLocation1[i] = tmpValueToMove[i]; } //FireEvents = true; FireEvents = oldFireEvents; IsAutoSorted = oldIsSorted; // 4 Get replace events for everything between index and newindex if(eventsAreToBeFired) { var minIndex = Math.Min(index , newIndex ); var maxIndex = Math.Max(index, newIndex) + length - 1; for (int i = minIndex; i <= maxIndex; i++) { FireCollectionChanged(NotifyCollectionChangeAction.Replace, this[i], i, -1); } } } /// <summary> /// Copies a block of the array to the right /// </summary> /// <param name="startIndex">Source index for copy</param> /// <param name="length">Length of block to copy</param> /// <param name="positions">Number of positions to move the block</param> private void CopyRight(int dimension,int startIndex, int length, int positions) { var sourceView = Select(dimension, startIndex, startIndex + length - 1); var targetView = Select(dimension, startIndex + positions, startIndex + positions + length - 1); for (int i = sourceView.Count-1; i >= 0 ; i--) { targetView[i] = sourceView[i]; } } /// <summary> /// Copies a block of the array to the left /// </summary> /// <param name="startIndex">Source index for copy</param> /// <param name="length">Length of block to copy</param> /// <param name="positions">Number of positions to move the block</param> private void CopyLeft(int dimension,int startIndex, int length, int positions) { var sourceView = Select(dimension, startIndex, startIndex + length - 1); var targetView = Select(dimension, startIndex - positions, startIndex - positions + length-1); for (int i=0;i<sourceView.Count;i++) { targetView[i] = sourceView[i]; } } public virtual bool FireEvents { get { return fireEvents; } set { fireEvents = value; } } public virtual void AddRange(IList values) { InsertAt(0, Count, values.Count, values); } public virtual IMultiDimensionalArrayView Select(int dimension, int start, int end) { return new MultiDimensionalArrayView(this, dimension, start, end); } public virtual IMultiDimensionalArrayView Select(int[] start, int[] end) { return new MultiDimensionalArrayView(this, start, end); } public virtual IMultiDimensionalArrayView Select(int dimension, int[] indexes) { return new MultiDimensionalArrayView(this, dimension, indexes); } public virtual event EventHandler<MultiDimensionalArrayChangingEventArgs> CollectionChanging; public virtual event EventHandler<MultiDimensionalArrayChangingEventArgs> CollectionChanged; #endregion public override string ToString() { return MultiDimensionalArrayHelper.ToString(this); } private MultiDimensionalArrayChangingEventArgs FireCollectionChanging(NotifyCollectionChangeAction action, IList values, int index1d, int[] itemsShape) { if (CollectionChanging == null) { return null; } var eventArgs = new MultiDimensionalArrayChangingEventArgs(action, values, index1d, -1, stride,itemsShape); CollectionChanging(this, eventArgs); return eventArgs; } private MultiDimensionalArrayChangingEventArgs FireCollectionChanging(NotifyCollectionChangeAction action, object value, int index1d) { return FireCollectionChanging(action, new[] {value}, index1d, new[] {1}); } private void FireCollectionChanged(NotifyCollectionChangeAction action, IList values, int index1d,int oldIndex1d, int[] shape) { if (CollectionChanged == null) { return; } var eventArgs = new MultiDimensionalArrayChangingEventArgs(action, values, index1d, oldIndex1d, stride, shape); CollectionChanged(this,eventArgs); } private void FireCollectionChanged(NotifyCollectionChangeAction action, object value, int index1d, int oldIndex1d) { FireCollectionChanged(action, new[] { value }, index1d, oldIndex1d, new[] { 1 }); /*if(CollectionChanged == null) { return; } CollectionChanged(this, new MultiDimensionalArrayChangingEventArgs(action, value, index1d, oldIndex1d, stride));*/ } private bool dirty = true; private object minValue; private object maxValue; private void UpdateMinMax() { object maxValue = null; object minValue = null; // todo use linq? does not work on IList or ArrayList, List<object> and List<double> are not // interchangeable // object min = Where(v => !ignoreValues.Contains(v)); foreach (object value in this) { if (value as IComparable == null) continue; if (((maxValue == null) || (((IComparable)value).CompareTo(maxValue) > 0))) { maxValue = value; } if (((minValue == null) || (((IComparable)value).CompareTo(minValue) < 0))) { minValue = value; } } this.maxValue = maxValue; this.minValue = minValue; dirty = false; } /// <summary> /// Gets the maximal value in the array or throws an exception if the array type is not supported /// TODO: move it to Variable<>? /// </summary> public virtual object MaxValue { get { if (dirty) { if ((IsAutoSorted) && (values.Count != 0)) { return values[values.Count-1]; } UpdateMinMax(); } return maxValue; } } /// <summary> /// Gets the minimal value in the array or throws an exception if the array type is not supported /// TODO: move it to Variable<>? /// </summary> public virtual object MinValue { get { if (dirty) { UpdateMinMax(); } return minValue; } } /// <summary> /// Returns a new instance for the internal 'flat' list. /// Returns a generic version if possible /// </summary> /// <returns></returns> protected virtual IList CreateValuesList() { return new ArrayList {}; } /// <summary> /// Creates a new values list and copies the values in values. /// </summary> /// <param name="values"></param> /// <returns></returns> protected virtual IList CreateClone(IList values) { return new ArrayList(values); } public virtual event PropertyChangingEventHandler PropertyChanging; public virtual event PropertyChangedEventHandler PropertyChanged; public static IMultiDimensionalArray Parse(string text) { throw new NotImplementedException(""); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Text.RegularExpressions; using System.Data.SqlClient; namespace ExscelOpenSQL { class DataGridSetting { /// <summary> /// ввод данных в базу из таблицы 1 /// </summary> /// <param name="connectionString"></param> /// <param name="dgv"></param> public void dataGridToDataBase(string connectionString, DataGridView dgv) { try { SqlConnection con = new SqlConnection(connectionString); con.Open(); for (int i = 0; i < dgv.RowCount; i++) { using (SqlCommand com = new SqlCommand("INSERT INTO FittingROZMA(name, size, sum, price) VALUES(@name, @size, @sum, @price)", con)) { com.Parameters.AddWithValue("@name", dgv.Rows[i].Cells[0].Value); com.Parameters.AddWithValue("@size", dgv.Rows[i].Cells[1].Value); com.Parameters.AddWithValue("@sum", dgv.Rows[i].Cells[2].Value); com.Parameters.AddWithValue("@price", dgv.Rows[i].Cells[3].Value); com.ExecuteNonQuery(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// добавление строки в итоговую таблицу /// </summary> public void addRows(DataGridView dgv1, DataGridView dgv2, Label rates, int indexRowDataGrid2, int index, string nameTable) { try { dgv2.Rows.Add(); dgv2.Rows[indexRowDataGrid2].Cells[3].Value = '1'; if (nameTable == "Price") { for (int i = 0; i < 3; i++) dgv2.Rows[indexRowDataGrid2].Cells[i].Value = dgv1.Rows[index].Cells[i + 1].Value; } if (nameTable == "ROZMA") { dgv2.Rows[indexRowDataGrid2].Cells[0].Value = dgv1.Rows[index].Cells[1].Value.ToString() + " Размер(" + dgv1.Rows[index].Cells[2].Value.ToString() + ')'; dgv2.Rows[indexRowDataGrid2].Cells[1].Value = Math.Round(double.Parse(dgv1.Rows[index].Cells[3].Value.ToString()) / (double.Parse(rates.Text) / 10000), 2).ToString(); dgv2.Rows[indexRowDataGrid2].Cells[2].Value = dgv1.Rows[index].Cells[3].Value.ToString(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// изменение стоимости послее изменения строки кол-ва товара /// </summary> /// <param name="dgv"></param> /// <param name="usd"></param> /// <param name="byr"></param> /// <param name="index"></param> public void editPrice(DataGridView dgv, Label usd, Label byr, int index) { try { for (int i = 0; i < dgv.Rows[index].Cells[3].Value.ToString().Length; i++) { if (!Char.IsDigit(dgv.Rows[index].Cells[3].Value.ToString()[i])) { MessageBox.Show("Строка '" + dgv.Rows[index].Cells[3].Value + "' не является числом. Повторите ввод!"); dgv.Rows[index].Cells[index].Value = "1"; return; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// считаем сумму в столбцах /// </summary> /// <param name="dgv"></param> /// <param name="indexCollumn"></param> /// <returns></returns> public string priceCount(DataGridView dgv, int indexCollumn) { try { double Count = 0; for (int i = 0; i < dgv.RowCount; i++) { Count += double.Parse(dgv.Rows[i].Cells[indexCollumn].Value.ToString()) * double.Parse(dgv.Rows[i].Cells[3].Value.ToString()); } return Count.ToString(); } catch (Exception ex) { return ex.Message; } } /// <summary> /// увеличиваем стоимость на 30 процентов /// </summary> /// <param name="dgv"></param> public void NDS(DataGridView dgv, int percent) { try { for (int i = 0; i < dgv.RowCount; i++) { dgv.Rows[i].Cells[3].Value = (Math.Round(double.Parse(dgv.Rows[i].Cells[3].Value.ToString()) + (double.Parse(dgv.Rows[i].Cells[3].Value.ToString()) / 100 * percent), 2)).ToString(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// корректировка столбцов с бел рублями по актуальному курсу /// </summary> public void dataBasePriceUSD(DataGridView dgv, string rates) { try { for (int i = 0; i < dgv.RowCount; i++) { string str = dgv.Rows[i].Cells[2].Value.ToString(); dgv.Rows[i].Cells[3].Value = Math.Round((double.Parse(str) * double.Parse(rates) / 10000), 2).ToString(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// вывод таблицы из бд /// </summary> /// <param name="dgv"></param> /// <param name="connectionString"></param> /// <param name="nameTable"></param> /// <param name="head0"></param> /// <param name="head1"></param> /// <param name="head2"></param> /// <param name="head3"></param> public void dataBaseToDataGrid(DataGridView dgv, string connectionString, string nameTable, string head0, string head1, string head2, string head3) { try { dgv.ColumnCount = 4; dgv.RowCount = 0; dgv.Columns[0].Width = 40; dgv.Columns[1].Width = 440; dgv.Columns[2].Width = 55; dgv.Columns[3].Width = 65; dgv.Columns[0].HeaderText = head0; dgv.Columns[1].HeaderText = head1; dgv.Columns[2].HeaderText = head2; dgv.Columns[3].HeaderText = head3; using (SqlConnection con = new SqlConnection(connectionString)) { con.Open(); using (SqlCommand com = new SqlCommand("SELECT * FROM " + nameTable, con)) { using (SqlDataReader reader = com.ExecuteReader()) { int index = 0; while (reader.Read()) { dgv.Rows.Add(); dgv.Rows[index].Cells[1].Value = reader.GetString(0); dgv.Rows[index].Cells[2].Value = reader.GetString(1); dgv.Rows[index].Cells[3].Value = reader.GetString(2); dgv.Rows[index].Cells[0].Value = reader.GetInt32(3).ToString(); index++; } com.Dispose(); reader.Close(); } } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// вывод размера столбцов и имена шапки dgv2 /// </summary> /// <param name="dgv"></param> /// <param name="head0"></param> /// <param name="head1"></param> /// <param name="head2"></param> /// <param name="head3"></param> public void dataGrid2Size(DataGridView dgv, string head0, string head1, string head2, string head3) { try { dgv.ColumnCount = 4; dgv.Columns[0].Width = 440; dgv.Columns[1].Width = 60; dgv.Columns[2].Width = 80; dgv.Columns[3].Width = 50; dgv.Columns[0].HeaderText = head0; dgv.Columns[1].HeaderText = head1; dgv.Columns[2].HeaderText = head2; dgv.Columns[3].HeaderText = head3; dgv.Columns[0].ReadOnly = true; dgv.Columns[1].ReadOnly = true; dgv.Columns[2].ReadOnly = true; dgv.Columns[3].ReadOnly = false; } catch (Exception ex) { MessageBox.Show(ex.Message); } } /// <summary> /// поиск по индексу /// </summary> /// <param name="dgv"></param> /// <param name="tb"></param> public void searchId(DataGridView dgv, TextBox tb) { try { for (int i = 0; i < dgv.RowCount; i++) { if (dgv.Rows[i].Cells[0].Value.ToString() == tb.Text) { dgv.CurrentCell = dgv.Rows[i].Cells[0]; } } } catch (Exception ex) { MessageBox.Show(ex.Message); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuRotation : MonoBehaviour { public float tiltAroundX, tiltAroundY, tiltAroundZ; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { //tiltAroundX += 2; tiltAroundZ += 0.1f; //tiltAroundY += 8; Quaternion target = Quaternion.Euler(tiltAroundX, tiltAroundY, tiltAroundZ); gameObject.transform.rotation = target; } }
namespace Tutorial.LinqToSql { using System.Data.Linq; using System.Diagnostics; using System.Linq; internal static class Tracking { internal static void EntitiesFromSameDataContext() { using (AdventureWorks adventureWorks = new AdventureWorks()) { Product productById = adventureWorks.Products.Single(product => product.ProductID == 999); Product productByName = adventureWorks.Products.Single(product => product.Name == "Road-750 Black, 52"); Trace.WriteLine(object.ReferenceEquals(productById, productByName)); // True. } } internal static void ObjectsFromSameDataContext() { using (AdventureWorks adventureWorks = new AdventureWorks()) { var productById = adventureWorks.Products .Where(product => product.ProductID == 999) .Select(product => new { Name = product.Name, ListPrice = product.ListPrice }) .Single(); var productByName = adventureWorks.Products .Where(product => product.Name == "Road-750 Black, 52") .Select(product => new { Name = product.Name, ListPrice = product.ListPrice }) .Single(); Trace.WriteLine(object.ReferenceEquals(productById, productByName)); // False. } } internal static void EntitiesFromDataContexts() { Product productById; Product productByName; using (AdventureWorks adventureWorks = new AdventureWorks()) { productById = adventureWorks.Products.Single(product => product.ProductID == 999); } using (AdventureWorks adventureWorks = new AdventureWorks()) { productByName = adventureWorks.Products.Single(product => product.Name == "Road-750 Black, 52"); } Trace.WriteLine(object.ReferenceEquals(productById, productByName)); // False. } internal static void EntityChanges() { using (AdventureWorks adventureWorks = new AdventureWorks()) { Product insert = new UniversalProduct() { Name = "Insert", ListPrice = 123 }; // Product insert = new Product() causes InvalidOperationException for InsertOnSubmit: // InvalidOperationException: Instance of type 'Tutorial.LinqToSql.Product' could not be added. This type is not part of the mapped type system. adventureWorks.Products.InsertOnSubmit(insert); IQueryable<Product> update = adventureWorks.Products .Where(product => product.Name.Contains("HL")); update.ForEach(product => product.ListPrice += 50); IQueryable<Product> delete = adventureWorks.Products .Where(product => product.Name.Contains("ML")); adventureWorks.Products.DeleteAllOnSubmit(delete); ChangeSet changeSet = adventureWorks.GetChangeSet(); Trace.WriteLine(changeSet.Inserts.Any()); // True. Trace.WriteLine(changeSet.Updates.Any()); // True. Trace.WriteLine(changeSet.Deletes.Any()); // True. changeSet.Inserts.OfType<Product>().ForEach(product => Trace.WriteLine( $"{nameof(ChangeSet.Inserts)}: ({product.ProductID}, {product.Name}, {product.ListPrice})")); changeSet.Updates.OfType<Product>().ForEach(product => { Product original = adventureWorks.Products.GetOriginalEntityState(product); Trace.WriteLine($"{nameof(ChangeSet.Updates)}: ({original.ProductID}, {original.Name}, {original.ListPrice}) -> ({product.ProductID}, {product.Name}, {product.ListPrice})"); }); changeSet.Deletes.OfType<Product>().ForEach(product => Trace.WriteLine( $"{nameof(ChangeSet.Deletes)}: ({product.ProductID}, {product.Name}, {product.ListPrice})")); // Inserts: (0, Insert, 123) // Updates: (951, HL Crankset, 404.9900) -> (951, HL Crankset, 454.9900) // Updates: (996, HL Bottom Bracket, 121.4900) -> (996, HL Bottom Bracket, 171.4900) // Deletes: (950, ML Crankset, 256.4900) // Deletes: (995, ML Bottom Bracket, 101.2400) } } internal static void Attach() { Product product = new UniversalProduct() { Name = "On the fly", ListPrice = 1 }; using (AdventureWorks adventureWorks = new AdventureWorks()) { product.ListPrice = 2; Trace.WriteLine(adventureWorks.GetChangeSet().Updates.Any()); // False. adventureWorks.Products.Attach(product); product.ListPrice = 3; adventureWorks.GetChangeSet().Updates.OfType<Product>().ForEach(attached => Trace.WriteLine( $"{adventureWorks.Products.GetOriginalEntityState(attached).ListPrice} -> {attached.ListPrice}")); // 2 -> 3. } } internal static void RelationshipChanges() { using (AdventureWorks adventureWorks = new AdventureWorks()) { DataLoadOptions loadOptions = new DataLoadOptions(); loadOptions.LoadWith<ProductCategory>(entity => entity.ProductSubcategories); adventureWorks.LoadOptions = loadOptions; ProductCategory category = adventureWorks.ProductCategories.First(); Trace.WriteLine(category.ProductSubcategories.Count); // 12. ProductSubcategory[] subcategories = category.ProductSubcategories.ToArray(); Trace.WriteLine(subcategories.All(subcategory => subcategory.ProductCategory == category)); // True. category.ProductSubcategories.Clear(); Trace.WriteLine(category.ProductSubcategories.Count); // 0. Trace.WriteLine(adventureWorks.GetChangeSet().Updates.Count); // 12. Trace.WriteLine(subcategories.All(subcategory => subcategory.ProductCategory == null)); // True. } } internal static void DisableObjectTracking() { using (AdventureWorks adventureWorks = new AdventureWorks()) { adventureWorks.ObjectTrackingEnabled = false; Product product = adventureWorks.Products.First(); product.ListPrice += 100; Trace.WriteLine(adventureWorks.GetChangeSet().Updates.Any()); // False adventureWorks.ObjectTrackingEnabled = true; // System.InvalidOperationException: Data context options cannot be modified after results have been returned from a query. } } } }
namespace Command { public class RemoveProductCommand : ICommand { private readonly Product _product; private readonly InvoiceService _invoiceService; private readonly InventoryService _inventoryService; public RemoveProductCommand(Product product, InvoiceService invoiceService, InventoryService inventoryService) { _product = product; _invoiceService = invoiceService; _inventoryService = inventoryService; } public void Execute() { _invoiceService.RemoveProductFromInvoice(_product); _inventoryService.RemoveProductFromDelivery(_product); } } }
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 System.Numerics; namespace CryptographyTemplate { public partial class SchnorrForm : Form { private DomainParameters domain; private Schnorr schnorr; private SchorrProver prover; private SchorrVerifier verifier; private BigInteger call; private BigInteger challenge; public SchnorrForm() { InitializeComponent(); } private void SchnorrForm_Load(object sender, EventArgs e) { } private void btnGenerateSchnorr_Click(object sender, EventArgs e) { domain = DomainParameters.GenerateDomainParameters(100000, 999999); schnorr = new Schnorr(domain); tbP.Text = domain.P.ToString(); tbQ.Text = domain.Q.ToString(); tbH.Text = domain.H.ToString(); tbG.Text = domain.G.ToString(); tbT.Text = schnorr.T.ToString(); ResetForm(); } private void btnGenerateKeys_Click(object sender, EventArgs e) { prover.GenerateKeys(); tbS.Text = prover.Secret.ToString(); tbA.Text = prover.PublicKey.ToString(); } private void btnGenerateCall_Click(object sender, EventArgs e) { prover.Call(); tbR.Text = prover.R.ToString(); tbX.Text = prover.X.ToString(); } private void btnGenerateChallenge_Click(object sender, EventArgs e) { challenge = verifier.Challenge(); tbE.Text = challenge.ToString(); } private void btnVerify_Click(object sender, EventArgs e) { BigInteger x = BigInteger.Parse(tbX.Text); BigInteger res = BigInteger.Parse(tbY.Text); BigInteger pub = BigInteger.Parse(tbA.Text); verifier.X = x; bool result = verifier.VerifyResponse(pub, res); tbZ.Text = verifier.Z.ToString(); if (result) { MessageBox.Show("Доказано"); } else { MessageBox.Show("НЕ доказано"); } } private void btnOk_Click(object sender, EventArgs e) { DialogResult = System.Windows.Forms.DialogResult.OK; } private void btnRespond_Click(object sender, EventArgs e) { BigInteger secret = BigInteger.Parse(tbS.Text); prover.Secret = secret; BigInteger ch = BigInteger.Parse(tbE.Text); prover.Response(ch); tbY.Text = prover.Y.ToString(); } private void tbT_TextChanged(object sender, EventArgs e) { ResetForm(); } private void ResetForm() { schnorr.T = BigInteger.Parse(tbT.Text); prover = new SchorrProver(schnorr); verifier = new SchorrVerifier(schnorr); tbS.Text = ""; tbA.Text = ""; tbR.Text = ""; tbX.Text = ""; tbE.Text = ""; tbY.Text = ""; tbZ.Text = ""; } } }
using System; using ClassLibrary1.Fundamentals; using NUnit.Framework; namespace ClassLibrary1.UnitTests { [TestFixture] public class DemeritPointsCalculatorTests { private DemeritPointsCalculator _calculator; [SetUp] public void SetUp() { _calculator = new DemeritPointsCalculator(); } [Test] [TestCase(0, 0)] [TestCase(64, 0)] [TestCase(65, 0)] [TestCase(66, 0)] [TestCase(70, 1)] [TestCase(75, 2)] [TestCase(76, 2)] public void CalculateDemeritPoints_WhenCalled_ReturnDemeritPoints(int speed, int expectedPoint) { var point = _calculator.CalculateDemeritPoints(speed); Assert.That(point, Is.EqualTo(expectedPoint)); } [Test] [TestCase(-1)] [TestCase(301)] public void CalculateDemeritPoints_SpeedIsOutOfRange_ThrowArgumentOutOfRangeException(int speed) { Assert.That(() => _calculator.CalculateDemeritPoints(speed), Throws.Exception.TypeOf<ArgumentOutOfRangeException>()); } } }
namespace VnStyle.Web.Infrastructure { public static class ApplicationSettings { public const string ImageStoragePath = "contents/uploads/images"; public const string VideoStoragePath = "contents/uploads/videos"; public const string EditorStoragePath = "contents/uploads/editor"; public const int ImageSizeNoneResize = 0; public const int ImageSizeSmallSize = 320; public const int ImageSizeMediumSize = 480; public const int ImageSizeLargeSize = 1024; public const string NoImagePath = "/contents/images/no-images.png"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class MainMenu : MonoBehaviour { public string m_LevelToLoad; public SceneFader m_SceneFader; public void PlayLevel() { m_SceneFader.FadeTo(m_LevelToLoad); } public void QuitLevel() { Application.Quit (); } }
using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; namespace SpaceHosting.Index.Benchmarks { public class AllStatisticsColumnAttribute : ColumnConfigBaseAttribute { public AllStatisticsColumnAttribute() : base( StatisticColumn.Mean, StatisticColumn.StdErr, StatisticColumn.StdDev, StatisticColumn.Q3, StatisticColumn.P95, StatisticColumn.OperationsPerSecond) { } } }
using LinqKit; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using WxShop.DBManager.EF; using WxShop.Model; using WxShop.Service.Interface; namespace WxShop.Service { public class WxShopService : IWxShopService { private readonly WxShopContext _context; public WxShopService(WxShopContext context) { _context = context; } public IList<ProductTypeModel> GetProductTypes() { return _context.ProductTypes.ToList(); } /// <summary> /// 根据筛选条件查询商品 /// </summary> /// <param name="where">筛选条件</param> /// <returns></returns> public IList<ProductModel> GetProducts(Expression<Func<ProductModel, bool>> where) { return (from i in _context.Products where @where.Invoke(i) select i).ToList(); } /// <summary> /// 根据筛选条件查询商品图片 /// </summary> /// <param name="where">筛选条件</param> /// <returns></returns> public IList<ProductImageModel> GetProductImages(Expression<Func<ProductImageModel, bool>> where) { return (from i in _context.ProductImages where @where.Invoke(i) select i).ToList(); } /// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="query"></param> /// <param name="orderColumn"></param> /// <param name="totalCount"></param> /// <param name="orderType"></param> /// <param name="orderColumns"></param> /// <param name="pageNo"></param> /// <param name="pageSize"></param> /// <returns></returns> private IEnumerable<T> getTQuery<T>(IQueryable<T> query, string orderColumn, out int totalCount, string orderType = "desc", Dictionary<string, string> orderColumns = null, int pageNo = 0, int pageSize = 0) { bool isDesc = orderType == "desc" ? true : false; query = query.OrderBy(orderColumn, isDesc); if (orderColumns != null) { foreach (string key in orderColumns.Keys) { bool isKeyDesc = orderColumns[key] == "desc" ? true : false; query = query.ThenOrderBy(key, isKeyDesc); } } totalCount = query.Count(); if (pageNo > 0) { return query.Skip((pageNo - 1) * pageSize).Take(pageSize); } else { return query; } } } /// <summary> /// /// </summary> public static class QueryableExtension { public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> query, string propertyName, bool isDesc) { return _OrderBy(query, propertyName, isDesc); } public static IOrderedQueryable<T> ThenOrderBy<T>(this IQueryable<T> query, string propertyName, bool isDesc) { return _ThenOrderBy(query, propertyName, isDesc); } static IOrderedQueryable<T> _OrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc) { string methodname = (isDesc) ? "OrderByDescendingInternal" : "OrderByInternal"; var memberProp = typeof(T).GetProperty(propertyName); var method = typeof(QueryableExtension).GetMethod(methodname).MakeGenericMethod(typeof(T), memberProp.PropertyType); return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp }); } static IOrderedQueryable<T> _ThenOrderBy<T>(IQueryable<T> query, string propertyName, bool isDesc) { string methodname = (isDesc) ? "ThenOrderByDescendingInternal" : "ThenOrderByInternal"; var memberProp = typeof(T).GetProperty(propertyName); var method = typeof(QueryableExtension).GetMethod(methodname).MakeGenericMethod(typeof(T), memberProp.PropertyType); return (IOrderedQueryable<T>)method.Invoke(null, new object[] { query, memberProp }); } public static IOrderedQueryable<T> OrderByInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty) { return query.OrderBy(_GetLamba<T, TProp>(memberProperty)); } public static IOrderedQueryable<T> OrderByDescendingInternal<T, TProp>(IQueryable<T> query, PropertyInfo memberProperty) { return query.OrderByDescending(_GetLamba<T, TProp>(memberProperty)); } public static IOrderedQueryable<T> ThenOrderByInternal<T, TProp>(IOrderedQueryable<T> query, PropertyInfo memberProperty) { return query.ThenBy(_GetLamba<T, TProp>(memberProperty)); } public static IOrderedQueryable<T> ThenOrderByDescendingInternal<T, TProp>(IOrderedQueryable<T> query, PropertyInfo memberProperty) { return query.ThenByDescending(_GetLamba<T, TProp>(memberProperty)); } static Expression<Func<T, TProp>> _GetLamba<T, TProp>(PropertyInfo memberProperty) { if (memberProperty.PropertyType != typeof(TProp)) throw new Exception(); var thisArg = Expression.Parameter(typeof(T)); var lamba = Expression.Lambda<Func<T, TProp>>(Expression.Property(thisArg, memberProperty), thisArg); return lamba; } } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.ViewFeatures; using Newtonsoft.Json; namespace SFA.DAS.ProviderCommitments.Web.Extensions { public static class ITempDataDictionaryExtensions { public static readonly string FlashMessageTempDataKey = "FlashMessage"; public static readonly string FlashMessageTitleTempDataKey = "FlashMessageTitle"; public static readonly string FlashMessageLevelTempDataKey = "FlashMessageLevel"; public enum FlashMessageLevel { Info, Warning, Success } public static void AddFlashMessage(this ITempDataDictionary tempData, string message, FlashMessageLevel level) { tempData[FlashMessageTempDataKey] = message; tempData[FlashMessageLevelTempDataKey] = level; } public static void AddFlashMessage(this ITempDataDictionary tempData, string title, string message, FlashMessageLevel level) { tempData[FlashMessageTitleTempDataKey] = title; tempData[FlashMessageTempDataKey] = message; tempData[FlashMessageLevelTempDataKey] = level; } public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T : class { tempData[key] = JsonConvert.SerializeObject(value); } public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class { object o; tempData.TryGetValue(key, out o); return o == null ? null : JsonConvert.DeserializeObject<T>((string)o); } public static T GetButDontRemove<T>(this ITempDataDictionary tempData, string key) where T : class { var result = tempData.Peek(key); return result == null ? null : JsonConvert.DeserializeObject<T>((string)result); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Mvc; using Meshop.Framework.Model; using Meshop.Framework.Module; using Meshop.Framework.Services; namespace Meshop.Core.Areas.Admin.Controllers { [Menu(Name = "Settings")] public class SettingsController : AdminController { // GET: /Admin/Settings/ public SettingsController(IAdmin adminsvc,ICommon commonsvc) : base(adminsvc,commonsvc) { } public ActionResult Index() { var list = db.Settings.ToList(); return View(list); } [HttpPost] public ActionResult Index(IList<Setting> settings,FormCollection collection) { if (ModelState.IsValid) { foreach (var setting in settings) { db.Entry(setting).State = EntityState.Modified; } db.SaveChanges(); _commonService.Message = "Success!"; return RedirectToAction("Index"); } return View(settings); } } }
using System; using System.Collections; using UnityEngine; //************************************************************************* //@header FlowMediator //@abstract The mediator of flow in game. //@discussion It is a father class. //@author Felix Zhang //@copyright Copyright (c) 2017-2018 FFTAI Co.,Ltd.All rights reserved. //@version v1.0.0 //************************************************************************** namespace FZ.HiddenObjectGame { public abstract class FlowMediator { protected FlowMediator() { } static FlowMediator _instance; public static FlowMediator Instance { get { return _instance; } } public abstract int Flow { get; } public static void SetTo<T>() where T : FlowMediator, new() { _instance = new T(); } public abstract void Initialize(); /// <summary> /// Begin specified flow. /// </summary> /// <param name="flow">The flow you want to start.</param> public abstract void Begin(int flow); /// <summary> /// Complete specified flow. /// </summary> /// <param name="flow">The flow you want to complete.</param> public abstract void Complete(int flow); /// <summary> /// Complete current flow and goto next flow. /// </summary> public abstract void Next(); /// <summary> /// Interrupt and Exit flow. /// </summary> public abstract void BreakFlow(bool isNormalEnd); protected abstract IEnumerator FlowLoop(); public virtual Coroutine StartCoroutine(IEnumerator iterator) { throw new NotImplementedException("FlowMediator.StartCoroutine(IEnumerator): Need to be implemented by derived class of FlowMediator"); } public virtual void StopCoroutine(IEnumerator iterator) { throw new NotImplementedException("FlowMediator.StopCoroutine(IEnumerator): Need to be implemented by derived class of FlowMediator"); } public virtual void StopAllCoroutines() { throw new NotImplementedException("FlowMediator.StopAllCoroutines(): Need to be implemented by derived class of FlowMediator"); } public virtual void InvokeInSecs(Action method, float time) { throw new NotImplementedException("FlowMediator.InvokeInSecs(): Need to be implemented by derived class of FlowMediator"); } } }
using ReactMusicStore.Core.Domain.Entities; using ReactMusicStore.Core.Domain.Interfaces.Repository.Common; namespace ReactMusicStore.Core.Domain.Interfaces.Repository { public interface IOrderDetailRepository : IRepository<OrderDetail> { } }
using System; using System.Collections.Generic; using LightingBook.Tests.Api.Helper; using TechTalk.SpecFlow; using LightingBook.Test.Api.Common; namespace LightingBook.Tests.Api.Steps { [Binding] public class GuestTravellerCarBookingSteps { private ScenarioContext scenarioContext; public GuestTravellerCarBookingSteps(ScenarioContext scenarioContext) { if (scenarioContext == null) throw new ArgumentNullException("scenarioContext"); this.scenarioContext = scenarioContext; this.AppConfigDetails = ConfigurationBase.AppConfigDetails; } public Dictionary<string, string> AppConfigDetails { get; set; } [Then(@"The GuestTraveller should match below details:")] public void ThenTheGuestTravellerShouldMatchBelowDetails(Table table) { var tokenResponse = scenarioContext.Get<TokenResponse>("TokenDetails"); } } }
namespace OptionalTypes.JsonConverters.Tests.TestDtos { public class BoolDto { public Optional<bool> Value { get; set; } } }
using NUnit.Framework; namespace SudokuSolver.Unit.Tests { [TestFixture] public class ValueSetupTests { [Test] public void Should_add_prefilled_cell_value_to_grid() { var grid = new Grid(); const int value = 4; const int row = 1; const int col = 1; grid.PutValue(row, col, value); var cell = grid.GetCell(row, col); Assert.That(cell.Value, Is.EqualTo(value)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LightTest : MonoBehaviour { public Light light; public Color black; public Color white; void Update () { light.color = Color.Lerp(white, black, Time.time * .02f); } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Score.Models; using System.Collections.Generic; using System.Linq; namespace Score.Tests { [TestClass] public class PointsTests { [TestMethod] public void ScrabbleConstructor_SetsInstanceOfWord_Points() { Points newWord = new Points("test"); Assert.AreEqual(typeof(Points), newWord.GetType()); } [TestMethod] public void CollectWord_ReturnWord_String() { string word = "hello"; Points newWord = new Points(word); string result = newWord.CollectWord(); Assert.AreEqual(word, result); } [TestMethod] public void LowerCase_MakeWordLowerCase_String() { string word = "HELLO"; Points newWord = new Points(word); string updatedWord = newWord.LowerCase(); string expectedWord = "hello"; Assert.AreEqual(updatedWord, expectedWord); } [TestMethod] public void ConvertString_ReturnArray_CharArray() { Points newWord = new Points("hello"); char[] resultExpected = new char[] {'h', 'e', 'l', 'l', 'o'}; CollectionAssert.AreEqual(resultExpected, newWord.ConvertString("hello")); } [TestMethod] public void AssignValue_AssignValueToOnePointLetters_Int() { Points newWord = new Points("a"); Assert.AreEqual(1, newWord.AssignValue()); } [TestMethod] public void AssignValue_AssignValueToTwoPointLetters_Int() { Points newWord = new Points("d"); char[] character = newWord.ToCharArray(); Assert.AreEqual(2, character.AssignValue()); } } }