text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using TMPro; public class Spawner : MonoBehaviour { public TMP_Text enemiesTxt; public Transform[] Enemies; public Transform[] SpawnPoints; public float StartTime = 5f; public float delayBetweenSpawn = .75f; bool onDelay = false; public int numEnemies = 5; public int enemiesRemaining = 0; // Start is called before the first frame update void Start() { Invoke("StartWave", StartTime); } private void OnEnable() { GameTriggers.OnPlayerAssigned += IncrementWave; } private void OnDisable() { GameTriggers.OnPlayerAssigned -= IncrementWave; } public void StartWave() { enemiesRemaining = 0; UpdateEnemyText(); InvokeRepeating("SpawnEnemy", delayBetweenSpawn, delayBetweenSpawn); } //private void Update() //{ // Time.timeScale = 1; // if (Input.GetKeyDown(KeyCode.Alpha0)) // { // int randEnemy = Random.Range(0, Enemies.Length); // Instantiate(Enemies[randEnemy], SpawnPoints[0].position, Quaternion.identity); // } // if (Input.GetKeyDown(KeyCode.Alpha1)) // { // int randEnemy = Random.Range(0, Enemies.Length); // Instantiate(Enemies[randEnemy], SpawnPoints[1].position, Quaternion.identity); // } // if (Input.GetKeyDown(KeyCode.Alpha2)) // { // int randEnemy = Random.Range(0, Enemies.Length); // Instantiate(Enemies[randEnemy], SpawnPoints[2].position, Quaternion.identity); // } // if (Input.GetKeyDown(KeyCode.Alpha3)) // { // int randEnemy = Random.Range(0, Enemies.Length); // Instantiate(Enemies[randEnemy], SpawnPoints[3].position, Quaternion.identity); // } // if (Input.GetKeyDown(KeyCode.Alpha4)) // { // int randEnemy = Random.Range(0, Enemies.Length); // Instantiate(Enemies[randEnemy], SpawnPoints[4].position, Quaternion.identity); // } //} void SpawnEnemy() { if (enemiesRemaining <= numEnemies) { //TODO this can cause a bug where we kill someone before the spawning is finished and cause spawing to never end. may not be a problem with the real level design enemiesRemaining++; int randEnemy = Random.Range(0, Enemies.Length); int randSpawnPoints = Random.Range(0, SpawnPoints.Length); Instantiate(Enemies[randEnemy], SpawnPoints[randSpawnPoints].position, Quaternion.identity); UpdateEnemyText(); } else { CancelInvoke(); } } public void DestroyEnemy() { enemiesRemaining--; UpdateEnemyText(); if (enemiesRemaining <= 0 ) { GameTriggers.OnWaveEnd(); print("New Wave"); } } void IncrementWave() { numEnemies = Mathf.CeilToInt(numEnemies * 1.5f); Invoke("StartWave", StartTime); } void UpdateEnemyText() { enemiesTxt.text = $"Enemies: { Mathf.Clamp( enemiesRemaining, 0, numEnemies).ToString()}"; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AudioManager : MonoBehaviour { [FMODUnity.EventRef] public string AppearFire; [FMODUnity.EventRef] public string ArmorPickup; [FMODUnity.EventRef] public string AttackFire; [FMODUnity.EventRef] public string ClothMovement; [FMODUnity.EventRef] public string DeathPlayer; [FMODUnity.EventRef] public string EnemyDeathFire; [FMODUnity.EventRef] public string HealthPickup; [FMODUnity.EventRef] public string LasherWalk; [FMODUnity.EventRef] public string PixieWalk; [FMODUnity.EventRef] public string StaticFire; [FMODUnity.EventRef] public string StepsPlayer; [FMODUnity.EventRef] public string TakeDamagePlayer; [FMODUnity.EventRef] public string Wisp; [FMODUnity.EventRef] public string DeathPlayerFire; [FMODUnity.EventRef] public string PixieAttack; [FMODUnity.EventRef] public string TerraCollide; [FMODUnity.EventRef] public string TerraDeath; [FMODUnity.EventRef] public string TerraSpawn; [FMODUnity.EventRef] public string PortalActivate; [FMODUnity.EventRef] public string LasherAttack; [FMODUnity.EventRef] public string XpGain; [FMODUnity.EventRef] public string PickupFire; [FMODUnity.EventRef] public string CantChangeFire; [FMODUnity.EventRef] public string BarrierSpawn; [FMODUnity.EventRef] public string MapToggle; //FMOD.Studio.EventInstance Music; //private void Awake() //{ // Music = FMODUnity.RuntimeManager.CreateInstance("event:/Music"); //} //private void Start() //{ // FMODUnity.RuntimeManager.AttachInstanceToGameObject(Music, GetComponent<Transform>(), GetComponent<Rigidbody2D>()); // Music.start(); //} public void AppearFireSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.AppearFire); } public void ArmorPickupSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.ArmorPickup); } public void AttackFireSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.AttackFire); } public void ClothMovementSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.ClothMovement); } public void DeathPlayerSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.DeathPlayer); } public void EnemyDeathFireSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.EnemyDeathFire); } public void HealthPickupSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.HealthPickup); } public void LasherWalkSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.LasherWalk); } public void PixieWalkSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.PixieWalk); } public void StaticFireSound() // { FMOD.Studio.EventInstance StaticFire; StaticFire = FMODUnity.RuntimeManager.CreateInstance("event:/StaticFire"); StaticFire.start(); } public void PortalActivateSound() { FMOD.Studio.EventInstance portalActive; portalActive = FMODUnity.RuntimeManager.CreateInstance("event:/PortalActivate"); portalActive.start(); } public void PortalDeactivateSound() { FMOD.Studio.EventInstance portalActive; portalActive = FMODUnity.RuntimeManager.CreateInstance("event:/PortalActivate"); portalActive.stop(FMOD.Studio.STOP_MODE.ALLOWFADEOUT); } public void StepsPlayerSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.StepsPlayer); } public void TakeDamagePlayerSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.TakeDamagePlayer); } public void WispSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.Wisp); } public void DeathPlayerFireSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.DeathPlayerFire); } public void PixieAttackSound() // { FMODUnity.RuntimeManager.PlayOneShot(this.PixieAttack); } public void CantChangeFireSound() { FMODUnity.RuntimeManager.PlayOneShot(this.CantChangeFire); } public void PickupFireSound() { FMODUnity.RuntimeManager.PlayOneShot(this.PickupFire); } public void LasherAttackSound() { FMODUnity.RuntimeManager.PlayOneShot(this.LasherAttack); } public void GainXpSound() { FMODUnity.RuntimeManager.PlayOneShot(this.XpGain); } public void TerraSpawnSound() { FMODUnity.RuntimeManager.PlayOneShot(this.TerraSpawn); } public void TerraDeathSound() { FMODUnity.RuntimeManager.PlayOneShot(this.TerraDeath); } public void TerraCollideSound() { FMODUnity.RuntimeManager.PlayOneShot(this.TerraCollide); } public void BarrierSpawnSound() { FMODUnity.RuntimeManager.PlayOneShot(this.BarrierSpawn); } public void MapToggleSound() { FMODUnity.RuntimeManager.PlayOneShot(this.MapToggle); } }
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 WindowsFormsApplication1 { public partial class oPomoc : Form { public oPomoc() { InitializeComponent(); richTextBox1.Enabled = false; richTextBox1.Text = "Powtarzaj ruchy pokazane na wideo. Na polu ze strzałkami żółty obwód wskazuje, że to pole powinno się nacisnąć na macie. Różowe wypełnienie, oznacza, że nacisk został odczytany. W celu powrotu do ćwiczenia naciśnij pierwszy z guzików lub START na macie. W celu powrotu do menu naciśnij drugi z guzików lub SELECT na macie."; } private void bPowrot_Click(object sender, EventArgs e) { status.kurs.uruchom(); this.Hide(); } private void oPomoc_FormClosing(object sender, FormClosingEventArgs e) { status.kurs.uruchom(); this.Hide(); } private void bMenu_Click(object sender, EventArgs e) { string caption = "Powrót do menu"; MessageBoxButtons button = MessageBoxButtons.YesNo; DialogResult result = MessageBox.Show("Czy na pewno chcesz wrócić do menu i skończyć kurs?", caption, button, MessageBoxIcon.Question); if (result == DialogResult.Yes) { // DANE?! status.kurs.stop(); this.Hide(); status.menu.Show(); status.menu.film(); } else { } } } }
namespace Bindable.Linq.Samples.MessengerClient.MessengerService.Simulator.Behaviors { using System; using Bindable.Linq.Samples.MessengerClient.Helpers; using Domain; /// <summary> /// A behavior that changes the contacts status to a boring quote every minute or so. /// </summary> internal class QuoteBehavior : TimerBehavior { private readonly string[] _quotes = new string[] {"Another boring day in the office.", "*yawn*.", "Looking forward to the weekend", "@Docklands", "I'm a little teapot...", "Windows Server 2008!", "BRB, pizza is here", "supakalafragilisticexpialidosius", "in Melbourne", "What can: can; what no can: no can!"}; /// <summary> /// Initializes a new instance of the <see cref="QuoteBehavior"/> class. /// </summary> public QuoteBehavior() : base(TimeSpan.FromSeconds(1)) {} /// <summary> /// Triggers this instance. /// </summary> protected override void Trigger(Contact contact) { var chance = Random.Next(0, 70); if (chance == 1) { contact.TagLine = _quotes.SelectRandom(); } else if (chance == 2) { contact.TagLine = ""; } } } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Net.Mail; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ProjSendMailHTML { public partial class WebForm1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private string createEmailBody(string userName, string title, string message) { string body = string.Empty; //using streamreader for reading my htmltemplate using (StreamReader reader = new StreamReader(Server.MapPath("~/HtmlPage.html"))) { body = reader.ReadToEnd(); } body = body.Replace("{UserName}", userName); //replacing the required things body = body.Replace("{Title}", title); body = body.Replace("{message}", message); return body; } private void SendHtmlFormattedEmail(string subject, string body) { using (MailMessage mailMessage = new MailMessage()) { mailMessage.From = new MailAddress(ConfigurationManager.AppSettings["UserName"]); mailMessage.Subject = subject; mailMessage.Body = body; mailMessage.IsBodyHtml = true; mailMessage.To.Add(new MailAddress(txtEmail.Text)); SmtpClient smtp = new SmtpClient(); smtp.Host = ConfigurationManager.AppSettings["Host"]; smtp.EnableSsl = Convert.ToBoolean(ConfigurationManager.AppSettings["EnableSsl"]); System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential(); NetworkCred.UserName = ConfigurationManager.AppSettings["UserName"]; //reading from web.config NetworkCred.Password = ConfigurationManager.AppSettings["Password"]; //reading from web.config smtp.UseDefaultCredentials = true; smtp.Credentials = NetworkCred; smtp.Port = int.Parse(ConfigurationManager.AppSettings["Port"]); //reading from web.config smtp.Send(mailMessage); } } protected void btnmail_Click(object sender, EventArgs e) { string body = this.createEmailBody(txtName.Text, "Please check your account Information", txtmsg.Text); this.SendHtmlFormattedEmail("New article published!", body); } } }
using Microsoft.Xna.Framework; using MonoGame.Extended.Screens.Transitions; namespace MonoGame.Extended.Screens { public class ScreenManager : SimpleDrawableGameComponent { public ScreenManager() { } private Screen _activeScreen; //private bool _isInitialized; //private bool _isLoaded; private Transition _activeTransition; public void LoadScreen(Screen screen, Transition transition) { if(_activeTransition != null) return; _activeTransition = transition; _activeTransition.StateChanged += (sender, args) => LoadScreen(screen); _activeTransition.Completed += (sender, args) => { _activeTransition.Dispose(); _activeTransition = null; }; } public void LoadScreen(Screen screen) { _activeScreen?.UnloadContent(); _activeScreen?.Dispose(); screen.ScreenManager = this; screen.Initialize(); screen.LoadContent(); _activeScreen = screen; } public override void Initialize() { base.Initialize(); _activeScreen?.Initialize(); //_isInitialized = true; } protected override void LoadContent() { base.LoadContent(); _activeScreen?.LoadContent(); //_isLoaded = true; } protected override void UnloadContent() { base.UnloadContent(); _activeScreen?.UnloadContent(); //_isLoaded = false; } public override void Update(GameTime gameTime) { _activeScreen?.Update(gameTime); _activeTransition?.Update(gameTime); } public override void Draw(GameTime gameTime) { _activeScreen?.Draw(gameTime); _activeTransition?.Draw(gameTime); } } }
using System; using System.Collections.Generic; using System.Text; namespace Football.DAL.Entities { public enum MatchLocation { Home, Visiting, Neutral } }
using System; namespace TestApplicationDomain.Entities { public class Booking : AuditEntity<string> { public Room Room { get; set; } public User User { get; set; } public double Price { get; set; } public double DiscountedPrice { get; set; } public double TotalPrice { get; set; } public double VATPrice { get; set; } public DateTime Start { get; set; } public DateTime End { get; set; } public int AdultGuestCOunt { get; set; } public int KidsGuestCOunt { get; set; } public int InfantGuestCOunt { get; set; } } }
// ===== Enhanced Editor - https://github.com/LucasJoestar/EnhancedEditor ===== // // // Notes: // // ============================================================================ // using System.Collections.Generic; using UnityEditor; using UnityEditorInternal; using UnityEngine; namespace EnhancedEditor.Editor { /// <summary> /// Static class used to draw over the project window for better layout and icons. /// </summary> [InitializeOnLoad] public static class EnhancedProjectBrowser { #region Item Infos private class ItemInfos { public const string PackageDisplayNameHeader = "\"displayName\""; public const char PackageDisplayNameSeparator = '\"'; public HierarchyProperty Property = null; public readonly string PackageName = string.Empty; public readonly string GUID = string.Empty; public readonly bool IsAssetsFolder = false; public readonly bool IsPackageSubfolder = false; public string ParentFolderGUID = string.Empty; public bool IsFolder = false; public bool HasSubfolders = false; private int drawCount = -1; private int count = 0; public virtual string Name { get { if (IsPackageSubfolder) { return PackageName; } return Property.name; } } public virtual int InstanceID { get { return Property.instanceID; } } public virtual bool HasChildren { get { return Property.hasChildren; } } public virtual Texture Icon { get { return Property.icon; } } // ----------------------- public ItemInfos(string _guid) { string _path = AssetDatabase.GUIDToAssetPath(_guid); GUID = _guid; GetParentFolder(); Property = new HierarchyProperty(HierarchyType.Assets, _path, true); IsAssetsFolder = AssetDatabase.GUIDToAssetPath(Property.guid) == "Assets"; HasSubfolders = AssetDatabase.GetSubFolders(_path).Length != 0; IsFolder = Property.isFolder; // Package folder. if (IsFolder) { TextAsset _textAsset = AssetDatabase.LoadAssetAtPath($"{_path}/package.json", typeof(TextAsset)) as TextAsset; if (_textAsset != null) { string _text = _textAsset.text; int _index = _text.IndexOf(PackageDisplayNameHeader); if (_index != -1) { _index += PackageDisplayNameHeader.Length; int _startIndex = _text.IndexOf(PackageDisplayNameSeparator, _index, _text.Length - _index) + 1; int _endIndex = _text.IndexOf(PackageDisplayNameSeparator, _startIndex, _text.Length - _startIndex); IsPackageSubfolder = true; PackageName = _text.Substring(_startIndex, _endIndex - _startIndex); } } } } protected ItemInfos() { } // ----------------------- public void OnDraw() { if (IsFolder) { return; } switch (Event.current.type) { // Get children property. case EventType.Repaint: if (drawCount != 0) { Property.Next(expandedProjectWindowItems); } drawCount++; break; // Reset property. case EventType.Layout: if (drawCount != 0) { if (drawCount > 1) { Property.Reset(); } count = drawCount; } drawCount = 0; break; default: return; } } public void GetParentFolder() { if (IsAssetsFolder || string.IsNullOrEmpty(GUID)) { return; } string _path = AssetDatabase.GUIDToAssetPath(GUID); string _folderPath = ProjectWindowUtil.GetContainingFolder(_path); if (!string.IsNullOrEmpty(_folderPath)) { ParentFolderGUID = AssetDatabase.AssetPathToGUID(_folderPath); } } public virtual bool IsExpanded(bool _isTreeView) { return (count > 1) || (_isTreeView && HasChildren && ArrayUtility.Contains(expandedProjectWindowItems, Property.instanceID)); } } private class PackageItemInfos : ItemInfos { public override string Name { get { return "Packages"; } } public override int InstanceID { get { return 0; } } public override bool HasChildren { get { return true; } } public override Texture Icon { get { return null; } } private bool isExpanded = false; // ----------------------- public PackageItemInfos() { IsFolder = true; HasSubfolders = true; } // ----------------------- public override bool IsExpanded(bool _isTreeView) { bool _isExpanded = isExpanded; isExpanded = false; return _isExpanded; } public void SetExpanded() { isExpanded = true; } } #endregion #region Global Members private static readonly Dictionary<string, ItemInfos> itemInfos = new Dictionary<string, ItemInfos>(); private static readonly PackageItemInfos packageFolderItemInfo = new PackageItemInfos(); private static int[] expandedProjectWindowItems = null; private static string[] selectedObjects = null; // ----------------------- static EnhancedProjectBrowser() { EditorApplication.projectWindowItemOnGUI += OnProjectItemGUI; EditorApplication.projectChanged += OnProjectChanged; EditorApplication.update += RefreshProjectState; RefreshProjectState(); } #endregion #region Editor GUI private static readonly HashSet<string> selectedTreeViewItems = new HashSet<string>(); private static readonly List<Rect> indentPositions = new List<Rect>() { Rect.zero }; private static readonly Color dragPreviewColor = new Color(1f, 1f, 1f, .1f); private static readonly Color selectionColor = new Color(1f, 1f, 1f, .12f); private static Rect assetsPosition = Rect.zero; // ----------------------- private static void OnProjectItemGUI(string _guid, Rect _position) { // Activation. EnhancedProjectBrowserEnhancedSettings _settings = EnhancedProjectBrowserEnhancedSettings.Settings; if (!_settings.Enabled) { return; } ItemInfos _item; // Ignore empty items (like favorites). if (string.IsNullOrEmpty(_guid)) { if ((_position.x != assetsPosition.x) || (_position.y < assetsPosition.y)) { return; } // Detect package folder item using the assets folder position. _item = packageFolderItemInfo; } else if (!itemInfos.TryGetValue(_guid, out _item)) { // Item registration. _item = new ItemInfos(_guid); itemInfos.Add(_guid, _item); } if (_item.IsAssetsFolder) { assetsPosition = _position; } // Item callback. _item.OnDraw(); // Position. var _positionInfos = GetItemPosition(ref _position); bool _isTreeView = _positionInfos._isTreeView; bool _isSmall = _positionInfos._isSmall; // Expanded state. bool _isExpanded = _item.IsExpanded(_isTreeView); if (_item.IsPackageSubfolder && _isTreeView) { packageFolderItemInfo.SetExpanded(); } // Get non tree view items parent. if (!_isTreeView) { selectedTreeViewItems.Add(_item.ParentFolderGUID); } if (_isSmall && (!EditorGUIUtility.editingTextField || !IsSelected(_guid))) { Rect _full = new Rect(0f, _position.y, Screen.width, _position.height); // Line background. bool _isOdd = (int)(_position.y / _position.height) % 2 == 0; Color _backgroundColor = _isOdd ? EnhancedEditorGUIUtility.GUIPeerLineColor : EnhancedEditorGUIUtility.GUIThemeBackgroundColor; EditorGUI.DrawRect(_full, _backgroundColor); // Feedback background. if (IsSelected(_guid) && (!_isTreeView || selectedTreeViewItems.Contains(_item.GUID))) { _backgroundColor = EnhancedEditorGUIUtility.GUISelectedColor; EditorGUI.DrawRect(_full, _backgroundColor); } else if ((DragAndDrop.visualMode == DragAndDropVisualMode.Move) && _full.Contains(Event.current.mousePosition)) { EditorGUI.DrawRect(_full, dragPreviewColor); } else if (_isTreeView && selectedTreeViewItems.Contains(_item.GUID)) { EditorGUI.DrawRect(_full, selectionColor); } // Item name. bool _isRoot = _position.x == assetsPosition.x; if (_isTreeView) { _full.x = _position.xMax + (_isRoot ? 2f : 1f); _full.y -= 1f; } else { _full.x = _position.xMax + 1f; } GUIStyle _labelStyle = _isRoot ? EditorStyles.boldLabel : EditorStyles.label; EditorGUI.LabelField(_full, EnhancedEditorGUIUtility.GetLabelGUI(_item.Name), _labelStyle); // Indent position. Rect _indentPosition = new Rect(){ x = _position.x - 20f, y = _position.y + (_position.height / 2f), width = 20f, height = 1f }; // Item foldout. if ((_isTreeView && _item.HasSubfolders) || (!_item.IsFolder && _item.HasChildren)) { _full.x = _position.x - 14f; _full.width = 15f; _full.y += 1f; EditorGUI.Foldout(_full, _isExpanded, GUIContent.none); _indentPosition.width -= 12f; } // Indent dotted lines. if (_isTreeView && (Event.current.type == EventType.Repaint)) { // Ignore root folders. if (_position.x > assetsPosition.x) { EnhancedEditorGUI.HorizontalDottedLine(_indentPosition, 1f, 1f); while (_position.x < indentPositions.Last().x) { indentPositions.RemoveLast(); } // Vertical line. if (!indentPositions.Last(out Rect _lastIndentPosition) || (_lastIndentPosition.y >= _position.y)) { _lastIndentPosition = new Rect(_position.x, 0f, 1f, 1f); } _indentPosition = new Rect() { x = _indentPosition.x - 2f, y = _lastIndentPosition.y + 8f, yMax = _indentPosition.y + 2f, width = 1f }; if (_position.x != _lastIndentPosition.x) { _indentPosition.yMin += 8f; } EnhancedEditorGUI.VerticalDottedLine(_indentPosition, 1f, 1f); // Only keep the last position for the same indent value. if (_position.x == _lastIndentPosition.x) { indentPositions.RemoveLast(); } } indentPositions.Add(_position); } } else { // Draw over base large icons. EditorGUI.DrawRect(_position, EnhancedEditorGUIUtility.GUIPeerLineColor); } // Get icon informations. Texture _icon = _item.Icon; Color _color = Color.white; if (_item.IsFolder) { _icon = _isExpanded ? _settings.DefaultOpenFolderIcon : (_item.HasChildren ? _settings.DefaultFolderIcon : _settings.DefaultEmptyFolderIcon); _color = _settings.FolderColor.Get(); } // Draw icon. using (var _scope = EnhancedGUI.GUIColor.Scope(_color)) { GUI.DrawTexture(_position, _icon); } } #endregion #region Utility private static (bool _isSmall, bool _isTreeView) GetItemPosition(ref Rect _position) { // Position indent is 14 pixels width. // Tree view starts with a x position of 16, against 14 for the other project column. bool _isTreeView = (_position.x - 16f) % 14f == 0f; bool _isSmall = _position.width > _position.height; if (_isSmall) { _position.width = _position.height; if (!_isTreeView) { _position.x += 3f; } } else { _position.height = _position.width; } return (_isSmall, _isTreeView); } private static bool IsSelected(string _guid) { return ArrayUtility.Contains(selectedObjects, _guid); } // ----------------------- private static void OnProjectChanged() { itemInfos.Clear(); foreach (var _item in itemInfos) { _item.Value.GetParentFolder(); } } private static void RefreshProjectState() { expandedProjectWindowItems = InternalEditorUtility.expandedProjectWindowItems; selectedObjects = Selection.assetGUIDs; // Tree view selection folder update. selectedTreeViewItems.Clear(); string _activeFolder = EnhancedEditorGUIUtility.GetActiveFolderPath(); if (!string.IsNullOrEmpty(_activeFolder)) { selectedTreeViewItems.Add(AssetDatabase.AssetPathToGUID(_activeFolder)); } } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using BundleTransformer.Core.Assets; using BundleTransformer.Core.Translators; using BundleTransformer.SassAndScss.HttpHandlers; using BundleTransformer.SassAndScss.Translators; using ClientDependency.Core; using ClientDependency.Core.Controls; using umbraco; using umbraco.BasePages; using umbraco.uicontrols; namespace CWS.Sassy.developer.Sassy { public partial class SassyFileEditor : UmbracoEnsuredPage { protected override void OnInit(EventArgs e) { base.OnInit(e); if (!UmbracoPanel.hasMenu) { return; } var imageButton = UmbracoPanel.Menu.NewImageButton(); imageButton.AlternateText = "Save File"; imageButton.ImageUrl = GlobalSettings.Path + "/images/editor/save.gif"; imageButton.Click += MenuSaveClick; } protected override void OnLoad(EventArgs e) { //Register SASS file ClientDependencyLoader.Instance.RegisterDependency(2, "CodeMirror/js/mode/sass/sass.js", "UmbracoClient", ClientDependencyType.Javascript); var file = Request.QueryString["file"]; var path = LoadSassyTree.SassPath + file; TxtName.Text = file; var appPath = Request.ApplicationPath; if (appPath == "/") { appPath = string.Empty; } LtrlPath.Text = appPath + path; if (IsPostBack) { return; } string fullPath = Server.MapPath(path); if (File.Exists(fullPath)) { string content; using (var streamReader = File.OpenText(fullPath)) { content = streamReader.ReadToEnd(); } if (string.IsNullOrEmpty(content)) { return; } EditorSource.Text = content; } else { Feedback.Text = (string.Format("The file '{0}' does not exist.", file)); Feedback.type = Feedback.feedbacktype.error; Feedback.Visible = true; UmbracoPanel.hasMenu = NamePanel.Visible = PathPanel.Visible = EditorPanel.Visible = false; } } private bool SaveConfigFile(string filename, string contents) { try { var path = Server.MapPath(LoadSassyTree.SassPath + filename); using (var text = File.CreateText(path)) { //Save the SASS file text.Write(contents); text.Close(); //Try to auto generate the compiled CSS & minified compiled CSS IAsset cssFile = new Asset(path); SassAndScssTranslator sassTranslator = new SassAndScssTranslator(); var compiledSass = sassTranslator.Translate(cssFile); //normal Path var normalCSS = path.Replace(".scss", ".css"); using (var compiledCSS = File.CreateText(normalCSS)) { compiledCSS.Write(compiledSass.Content); compiledCSS.Close(); } } return true; } catch (AssetTranslationException ex) { Feedback.type = Feedback.feedbacktype.error; Feedback.Text = ex.Message; Feedback.Visible = true; return false; } } private void MenuSaveClick(object sender, ImageClickEventArgs e) { if (SaveConfigFile(TxtName.Text, EditorSource.Text)) { ClientTools.ShowSpeechBubble(speechBubbleIcon.save, ui.Text("speechBubbles", "fileSavedHeader"), ui.Text("speechBubbles", "fileSavedText")); } else { ClientTools.ShowSpeechBubble(speechBubbleIcon.error, ui.Text("speechBubbles", "fileErrorHeader"), ui.Text("speechBubbles", "fileErrorText")); } } } }
// Author: // Evan Thomas Olds // // Creation Date: // November 23, 2014 using System; using System.IO; namespace ETOF.IO { /// <summary> /// Simulates the concatenation of two streams together. The two streams are NOT actually /// concatenated in memory. The ConcatStream keeps references to both underlying streams /// and dynamically serves their functionality as if there were just one large stream. /// The functionality of the ConcatStream is limited by the lesser-functional of the two /// underlying streams. It can seek only if BOTH underlying streams can seek, it can /// write only if BOTH underlying streams can write, and so on. /// </summary> public class ConcatStream : Stream { private Stream m_a, m_b; /// <summary> /// Only used when the second stream (stream B) does not support seeking. Keeps track /// of the position that we are in within stream B. Works under the assumption that /// on construction we are at position 0 in B. /// </summary> private long m_bPos = 0; private long m_pos = 0; /// <summary> /// The fixed stream length or -1 if the stream length is not to be fixed at a particular /// value. /// </summary> private long r_len = -1; /// <summary> /// Constructs the ConcatStream from two streams. Both streams must be non-null. The /// first stream must support seeking and querying the Length property. /// </summary> public ConcatStream(Stream first, Stream second) { if (null == first || null == second) { throw new ArgumentNullException(); } if (!first.CanSeek) { throw new ArgumentException( "First stream in a ConcatStream must support seeking"); } m_a = first; m_b = second; m_a.Position = 0; } /// <summary> /// Constructs the ConcatStream from two streams and a fixed length. Both streams must be /// non-null. The first stream must support seeking and querying the Length property. The /// stream will be read-only. /// </summary> private ConcatStream(Stream first, Stream second, long fixedLength) { if (null == first || null == second) { throw new ArgumentNullException(); } if (!first.CanSeek) { throw new ArgumentException( "First stream in a ConcatStream must support seeking"); } if (!first.CanRead || !second.CanRead) { throw new ArgumentException( "Cannot construct a fixed-length, read-only ConcatStream unless " + "both streams support reading."); } m_a = first; m_b = second; m_a.Position = 0; r_len = fixedLength; } public override bool CanRead { // We can read only if BOTH underlying streams can read get { return m_a.CanRead && m_b.CanRead; } } public override bool CanSeek { // We can seek only if BOTH underlying streams can seek get { return m_a.CanSeek && m_b.CanSeek; } } public override bool CanWrite { get { if (r_len >= 0) { // This means it's fixed-length and read-only return false; } // We can write only if BOTH underlying streams can write return m_a.CanWrite && m_b.CanWrite; } } public static ConcatStream CreateReadOnlyWithFixedLength(Stream first, Stream second, long lengthInBytes) { return new ConcatStream(first, second, lengthInBytes); } public override void Flush() { // We don't try to do anything fancy like keep track of which of the two streams // have been modified, so in the case when we're asked to flush we just flush // both streams. m_a.Flush(); m_b.Flush(); } public bool IsFixedLength { get { return (r_len >= 0); } } public override long Length { get { if (r_len >= 0) { // This means it's fixed-length and read-only return r_len; } return m_a.Length + m_b.Length; } } public override long Position { get { return m_pos; } set { // Take only non-negative values if (value >= 0) { m_pos = value; if (m_pos < m_a.Length) { m_a.Position = m_pos; } else { // We're somewhere in the second stream m_b.Position = m_pos - m_a.Length; } } } } public override int Read(byte[] buffer, int offset, int count) { // For fixed-length streams we need to stop reading when the position == the length if (r_len >= 0) { if (m_pos == r_len) { // End of stream, so we return 0 return 0; } // Lower the count if need be so we don't go over the length if (m_pos + count > r_len) { count = (int)(r_len - m_pos); } } int requestedCount = count; while (count > 0) { int bytesRead; // If we're in the first stream then we can read from it, passing the // remaining number of bytes as the count. if (m_pos < m_a.Length) { bytesRead = m_a.Read(buffer, offset, count); count -= bytesRead; m_pos += bytesRead; offset += bytesRead; } else { // The second stream is a bit trickier because of the fact that we want // to support non-seekable streams. We'll start with the easy case // though, where the second stream DOES support seeking. if (m_b.CanSeek) { m_b.Position = m_pos - m_a.Length; } else { // In this case we might still be able to do the read, but we need // to verify that we are in the exactly correct position within // stream B. if (m_bPos != m_pos - m_a.Length) { throw new NotSupportedException( "Reading at location " + m_pos.ToString() + " would " + "require seeking within the second stream. Since the second" + " stream doesn't support seeking, this action cannot be " + "completed."); } } // We're at the correct position if we come here, so now do the read bytesRead = m_b.Read(buffer, offset, count); count -= bytesRead; m_pos += bytesRead; offset += bytesRead; m_bPos += bytesRead; } // To avoid infinite loops we need to break after reading 0 bytes if (0 == bytesRead) { break; } } return requestedCount - count; } public override long Seek(long offset, SeekOrigin origin) { switch (origin) { case SeekOrigin.Begin: Position = offset; break; case SeekOrigin.Current: Position += offset; break; case SeekOrigin.End: Position = Length - offset; break; default: throw new InvalidOperationException(); } return Position; } /// <summary> /// Not supported for the ConcatStream class. /// </summary> public override void SetLength(long value) { throw new NotSupportedException(); } public Stream StreamA { get { return m_a; } } public Stream StreamB { get { return m_b; } } /// <summary> /// The ConcatStream write functionality is such that it never expands the length of StreamA. It /// can potentially overwrite existing contents in StreamA, but should it get to the end and have /// more data to write, then it moves on to the beginning of StreamB. /// </summary> public override void Write(byte[] buffer, int offset, int count) { if (r_len >= 0) { // This means it's fixed-length and read-only so we cannot write throw new InvalidOperationException( "ConcatStream cannot be written to because it was instantiated as read-only."); } while (count > 0) { int bytesWritten; // If we're in the first stream then we can write to it, but we need to make // sure that we don't go beyond the end. if (m_pos < m_a.Length) { int writeCount = count; if ((long)writeCount + m_pos > m_a.Length) { writeCount = (int)(m_a.Length - m_pos); } long posBefore = m_a.Position; m_a.Write(buffer, offset, writeCount); bytesWritten = (int)(m_a.Position - posBefore); count -= bytesWritten; m_pos += bytesWritten; offset += bytesWritten; } else { // The second stream is a bit trickier because of the fact that we want // to support non-seekable streams. We'll start with the easy case // though, where the second stream DOES support seeking. long posBefore; if (m_b.CanSeek) { m_b.Position = m_pos - m_a.Length; posBefore = m_b.Position; } else { // In this case we might still be able to do the write, but we need // to verify that we are in the exactly correct position within // stream B. if (m_bPos != m_pos - m_a.Length) { throw new NotSupportedException( "Writing at location " + m_pos.ToString() + " would " + "require seeking within the second stream. Since the second" + " stream doesn't support seeking, this action cannot be " + "completed."); } posBefore = m_bPos; } // We're at the correct position if we come here, so now do the write m_b.Write(buffer, offset, count); // Determine how many bytes were written if (m_b.CanSeek) { bytesWritten = (int)(m_b.Position - posBefore); } else { // Assume in this case that we wrote everything bytesWritten = count; } count -= bytesWritten; m_pos += bytesWritten; offset += bytesWritten; m_bPos += bytesWritten; } // To avoid infinite loops we need to break after writing 0 bytes if (0 == bytesWritten) { break; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.Collections.Generic; using System.Drawing; namespace ClassLotto { public class LottoMGM { private List<int> losungsListe = new List<int>(); private List<int> ziehungsListe = new List<int>(); private List<string> ergebnisListe = new List<string>(); private string dieseZahl = ""; private string ergebnisText = ""; private int hitCount = 0; private string fazit = ""; public List<int> LosungsListe { get => losungsListe; set => losungsListe = value; } public List<int> ZiehungsListe { get => ziehungsListe; set => ziehungsListe = value; } public List<string> ErgebnisListe { get => ergebnisListe; set => ergebnisListe = value; } public string ErgebnisText { get => ergebnisText; set => ergebnisText = value; } public string Ziehung() { if (this.losungsListe.Count == 6) { while (this.ziehungsListe.Count < 6) { Random r = new Random(); int thisRand = r.Next(1, 50); if (!(this.ziehungsListe.Contains(thisRand))) { this.ziehungsListe.Add(thisRand); } } this.ergebnisText += "Gezogene Zahlen:\n"; foreach (var x in this.ziehungsListe) { this.ergebnisText += Convert.ToString(x) + " "; } this.ergebnisText += "\nDeine Auswahl:\n"; foreach (var x in this.losungsListe) { if (ziehungsListe.Contains(x)) { this.ergebnisText += Convert.ToString(x) + "-Blumentopf! "; this.ergebnisListe.Add("-" + Convert.ToString(x) + "-"); } else { this.ergebnisText += Convert.ToString(x) + "-Niete! "; this.ergebnisListe.Add("-" + Convert.ToString(x) + "-"); } } if (hitCount > 0) { this.fazit = "\nIts something o/"; } else if (hitCount < 2) { this.fazit = "\nMehr Glück beim nächsten mal!"; } else if(hitCount <5) { this.fazit = "\nDamn das pretty good!"; } else { this.fazit = "\nYou should literally spend money on this!"; } this.ergebnisText += this.fazit; return this.ergebnisText; } else { string wentbad = "wat"; return wentbad; } } } }
using bot_backEnd.Models.AppModels; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace bot_backEnd.Models { public class AppPost { [Key] public int Id { get; set; } public string Title { get; set; } public string Description { get; set; } public int UserEntityID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public int CityID { get; set; } public string CityName { get; set; } public List<ImagePath> ImageURLS { get; set; } public DateTime Date { get; set; } public int Likes { get; set; } public int Comments { get; set; } public string CategoryName { get; set; } public double Rating { get; set; } public double? Latitude { get; set; } public double? Longitude { get; set; } public bool LikedByUser { get; set; } public DateTime? EndDate { get; set; } public string UserProfilePhotoURL { get; set; } public bool AcceptedByTheUser { get; set; } public int SolvedByTheUser { get; set; } public int TypeID { get; set; } } }
using UnityEngine; using System.Collections; public class FSM_Test : MonoBehaviour { public enum STATE { INIT, STATE1, STATE2, STATE3, } FSM<STATE> _fsm = new FSM<STATE>(); void Awake() { _fsm.AddState(STATE.INIT); _fsm.AddState(STATE.STATE1); _fsm.AddState(STATE.STATE3); _fsm.AddState(STATE.STATE3); _fsm.AddTransition(STATE.INIT, STATE.STATE1); _fsm.AddTransition(STATE.STATE1, STATE.STATE2); _fsm.AddTransition(STATE.STATE1, STATE.STATE3); _fsm.AddTransition(STATE.STATE2, STATE.STATE1); _fsm.AddTransition(STATE.STATE2, STATE.STATE3); _fsm.AddTransition(STATE.STATE3, STATE.STATE1); _fsm.currentState = STATE.INIT; } void Start() { InitToState1Handler(); } void Update() { if (Input.GetKeyDown(("1"))) { _fsm.Transition(STATE.STATE1); } if (Input.GetKeyDown(("2"))) { if(_fsm.Transition(STATE.STATE2)) StartCoroutine(Move()); } if (Input.GetKeyDown(("3"))) { if (_fsm.Transition(STATE.STATE3)) StartCoroutine(Jump()); } } void InitToState1Handler() { _fsm.Transition(STATE.STATE1); } void State1ToState2Handler() { _fsm.Transition(STATE.STATE2); } void State2ToState1Handler() { _fsm.Transition(STATE.STATE1); } void State2ToState3Handler() { _fsm.Transition(STATE.STATE3); } public IEnumerator Move() { float delay = 10; float timer = 0; while (timer < delay) { transform.position += transform.forward * Time.deltaTime; timer += Time.deltaTime; yield return null; } _fsm.Transition(STATE.STATE1); } public IEnumerator Jump() { bool isUp = false; while (!isUp) { transform.position += transform.up * Time.deltaTime; if (transform.position.y > 1) isUp = true; yield return null; } while (isUp && transform.position.y > 0) { transform.position -= transform.up * Time.deltaTime; yield return null; } } }
// You are given a cable TV company. The company needs to lay cable to a new neighborhood (for every house). If it is constrained // to bury the cable only along certain paths, then there would be a graph representing which points are connected by those paths. // But the cost of some of the paths is more expensive because they are longer. If every house is a node and every path from house // to house is an edge, find a way to minimize the cost for cables. namespace CableCompanyProblem { using System; using System.Collections.Generic; using System.Linq; using Wintellect.PowerCollections; internal class EntryPoint { private static void Main() { ICollection<Path> neighborhood = GetNeighborhood(); ICollection<Path> minSpanningTree = GetMinimumSpanningTree(neighborhood); long minCost = 0; Console.WriteLine("All paths that form the minimum spanning tree are:"); foreach (Path path in minSpanningTree) { Console.WriteLine(path); minCost += path.Distance; } Console.WriteLine("The minimal cost is: {0}", minCost); } private static ICollection<Path> GetMinimumSpanningTree(ICollection<Path> neighborhood) { OrderedBag<Path> minimumSpanningTree = new OrderedBag<Path>(); List<HashSet<House>> vertexSets = GetSetWithOneVertex(neighborhood); foreach (var path in neighborhood) { HashSet<House> startHouseGropu = GetVertexSet(path.StartHouse, vertexSets); HashSet<House> endHouseGroup = GetVertexSet(path.EndHouse, vertexSets); if (startHouseGropu == null) { minimumSpanningTree.Add(path); if (endHouseGroup == null) { HashSet<House> newVertexSet = new HashSet<House>(); newVertexSet.Add(path.StartHouse); newVertexSet.Add(path.EndHouse); vertexSets.Add(newVertexSet); } else { endHouseGroup.Add(path.StartHouse); } } else { if (endHouseGroup == null) { startHouseGropu.Add(path.EndHouse); minimumSpanningTree.Add(path); } else if (startHouseGropu != endHouseGroup) { startHouseGropu.UnionWith(endHouseGroup); vertexSets.Remove(endHouseGroup); minimumSpanningTree.Add(path); } } } return minimumSpanningTree; } private static HashSet<House> GetVertexSet(House house, List<HashSet<House>> vertexSets) { foreach (var vertexSet in vertexSets) { if (vertexSet.Contains(house)) { return vertexSet; } } return null; } private static List<HashSet<House>> GetSetWithOneVertex(ICollection<Path> neighborhood) { List<HashSet<House>> allSetsWithOneVertex = new List<HashSet<House>>(); foreach (var path in neighborhood) { bool startHouseAdded = true; bool endHouseAdded = true; foreach (var set in allSetsWithOneVertex) { if (startHouseAdded && set.Contains(path.StartHouse)) { startHouseAdded = false; } if (endHouseAdded && set.Contains(path.EndHouse)) { endHouseAdded = false; } if (!startHouseAdded && !endHouseAdded) { break; } } if (startHouseAdded) { HashSet<House> newSet = new HashSet<House>(); newSet.Add(path.StartHouse); allSetsWithOneVertex.Add(newSet); } } return allSetsWithOneVertex; } private static ICollection<Path> GetNeighborhood() { OrderedBag<Path> neighborhood = new OrderedBag<Path>(); // check the picture neighborhood.Add(new Path(new House("1"), new House("2"), 10)); neighborhood.Add(new Path(new House("1"), new House("3"), 2)); neighborhood.Add(new Path(new House("2"), new House("4"), 5)); neighborhood.Add(new Path(new House("2"), new House("6"), 19)); neighborhood.Add(new Path(new House("3"), new House("4"), 3)); neighborhood.Add(new Path(new House("3"), new House("5"), 2)); neighborhood.Add(new Path(new House("4"), new House("5"), 11)); neighborhood.Add(new Path(new House("4"), new House("6"), 9)); neighborhood.Add(new Path(new House("6"), new House("7"), 1)); return neighborhood; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LoseTrigger : MonoBehaviour { private void OnTriggerEnter2D(Collider2D collision) { var sceneLoader = FindObjectOfType<SceneLoader>(); sceneLoader.LoadGameOver(); } }
namespace MvcApplication.Business { public interface IEnvironment { #region Properties string MachineName { get; } string NewLine { get; } #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ListNote { public partial class CldWeek : Form { private List<Button> TbHead; public List<Button> TbHead1 { get => TbHead; set => TbHead = value; } private List<List<Button>> matrix; public List<List<Button>> Matrix { get => matrix; set => matrix = value; } public CldWeek() { InitializeComponent(); } void LoadTime() { DateTime check = dtpkDate.Value; Button oldBtn = new Button() { Width = 0, Height = 0, Location = new Point(-Cons.Margin, 0) }; TbHead = new List<Button>(); for (int i = 0; i < 7; i++) { Button a = new Button() { Height = Cons.Height, Width = Cons.Width - 10 }; a.FlatAppearance.BorderSize = 1; a.FlatAppearance.BorderColor = Color.LightSkyBlue; a.TextAlign = ContentAlignment.TopLeft; a.FlatStyle = FlatStyle.Flat; a.Location = new Point(oldBtn.Location.X + oldBtn.Width + Cons.Margin, oldBtn.Location.Y); this.pnDayOfMonth.Controls.Add(a); TbHead.Add(a); oldBtn = a; } LoadMatrix(); SetDefaultDate(); } // ham add ngay cua cac thu trong tuan void AddNumberTbHead(DateTime date) { ClearTbhead(); DateTime check = date; if(check.DayOfWeek.ToString()!="Monday") { bool bl = true; while (bl) { check = check.AddDays(-1); if (check.DayOfWeek.ToString() == "Monday") { bl = false; } } } for (int i = 0; i < TbHead.Count; i++) { Button btn = TbHead[i]; btn.Text = check.Month.ToString() + " / " + check.Day.ToString(); check = check.AddDays(1); } //DateTime useDate = new DateTime(date.Year, date.Month, 1); //int line = 0; //for (int i = 1; i <= DayofMonth(date); i++) //{ // int column = dateOfWeek.IndexOf(useDate.DayOfWeek.ToString()); // Button btn = Matrix[line][column]; // btn.Text = i.ToString(); // if (column >= 6) // line++; // if (checkEvent(useDate, InUser)) // { // btn.BackColor = Color.Red; // } // else if (isEqualDate(useDate, date)) // { // btn.BackColor = Color.Blue; // } // else if (isEqualDate(useDate, DateTime.Now)) // { // btn.BackColor = Color.Yellow; // } // useDate = useDate.AddDays(1); //} } void ClearTbhead() { for (int i = 0; i < TbHead.Count; i++) { Button x = TbHead[i]; x.Text = ""; } } void ClearMatrix() { for(int i = 0; i<matrix.Count;i++) { for(int j = 0; j<matrix[i].Count; j++) { Button x = Matrix[i][j]; x.Text = ""; //x.BackColor = Color.WhiteSmoke; } } } void LoadMatrix() { Matrix = new List<List<Button>>(); Button oldBtn = new Button() { Width = 0, Height = 0, Location = new Point(-Cons.Margin+55, 0) }; for (int i = 0; i < Cons.CountTimeofDay*2; i++) { Matrix.Add(new List<Button>()); for (int j = 0; j < Cons.DayOfweek; j++) { Button a = new Button() { Height = Cons.Height/3, Width = Cons.Width-10 }; a.FlatAppearance.BorderSize = 1; a.FlatAppearance.BorderColor = Color.LightSkyBlue; a.TextAlign = ContentAlignment.TopLeft; a.FlatStyle = FlatStyle.Flat; a.Location = new Point(oldBtn.Location.X + oldBtn.Width + Cons.Margin, oldBtn.Location.Y); a.Text = i.ToString(); a.Click += A_Click; pnMatrix.Controls.Add(a); Matrix[i].Add(a); oldBtn = a; } oldBtn = new Button() { Width = 0, Height = 0, Location = new Point(-Cons.Margin+55, oldBtn.Location.Y + Cons.Height/3) }; } SetDefaultDate(); } void AddNumberMatrix(DateTime date) { ClearMatrix(); DateTime check = date; if (check.DayOfWeek.ToString() != "Monday") { bool bl = true; while (bl) { check = check.AddDays(-1); if (check.DayOfWeek.ToString() == "Monday") { bl = false; } } } for(int i = 0;i<matrix.Count; i++) { DateTime temp = check; for(int j = 0; j<matrix[i].Count; j++) { Button x = matrix[i][j]; x.Text = temp.Month.ToString() + "//" + temp.Day.ToString(); temp = temp.AddDays(1); } } } private void A_Click(object sender, EventArgs e) { //throw new NotImplementedException(); } void SetDefaultDate() { dtpkDate.Value = DateTime.Now; } private void CldWeek_Load(object sender, EventArgs e) { LoadTime(); } private void button26_Click(object sender, EventArgs e) { } private void MonthATer_Click(object sender, EventArgs e) { dtpkDate.Value = dtpkDate.Value.AddDays(7); } private void MonthBF_Click(object sender, EventArgs e) { dtpkDate.Value = dtpkDate.Value.AddDays(-7); } private void dtpkDate_ValueChanged(object sender, EventArgs e) { AddNumberTbHead((sender as DateTimePicker).Value); AddNumberMatrix((sender as DateTimePicker).Value); } private void btnDayNow_Click(object sender, EventArgs e) { SetDefaultDate(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TestInheritance.DomainModels { public class PersonOnly : TestInheritance.DomainModels.ThePerson.Person { } }
 #region Usings using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Zengo.WP8.FAS.Controls; using Zengo.WP8.FAS.Helpers; using Zengo.WP8.FAS.Models; using Zengo.WP8.FAS.Resources; using Zengo.WP8.FAS.WebApi.Responses; using Zengo.WP8.FAS.WepApi; using System; using System.Windows; using System.Windows.Navigation; #endregion namespace Zengo.WP8.FAS { public partial class SettingsPage : PhoneApplicationPage { #region Fields UserApi userApi; ApplicationBarIconButton saveChanges; #endregion #region Constructors public SettingsPage() { InitializeComponent(); // Register for the pivot selection changed event PivotControl.SelectionChanged += PivotControl_SelectionChanged; // Register for sub control events MyAccountControl.UpdateAccountStarting += MyAccountControl_UpdateAccountStarting; MyAccountControl.UpdateAccountCompleted += MyAccountControl_UpdateAccountCompleted; //MyAccountControl.RemoveKeyboard += MyAccountControl_RemoveKeyboard; // Register for the control events that tell us the team selector button has been pressed MyAccountControl.FirstFavouriteTeamPressed += RegisterControl_FirstFavouriteTeamPressed; MyAccountControl.SecondFavouriteTeamPressed += RegisterControl_SecondFavouriteTeamPressed; MyAccountControl.MyCountryPressed += MyAccountControl_MyCountryPressed; TeamHistory.pitchHistoryLongList.SelectionChanged += pitchHistoryLongList_SelectionChanged; // Create an app bar ApplicationBar = new ApplicationBar(); userApi = new UserApi(); userApi.ResendActivationEmailCompleted += userApi_ResendValidationEmailCompleted; // Populate our lists PopulateList(); PurchasesPage.PageName = AppResources.PurchasesTitle; AccountPage.PageName = AppResources.AccountsTitle; VotesPage.PageName = AppResources.VotesTitle; TeamPage.PageName = "my teams"; } #endregion void pitchHistoryLongList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { PitchRecord pitch = TeamHistory.pitchHistoryLongList.SelectedItem as PitchRecord; if (pitch != null) { this.NavigationService.Navigate(new Uri("/Views/PitchPage.xaml?Pitch=" + pitch.PitchId, UriKind.Relative)); } } #region Page Event Handlers /// <summary> /// This also gets run when we navigate back from the clubs list and from the activate page /// </summary> protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); TeamHistory.pitchHistoryLongList.SelectedItem = null; // Set the data context for the Profile view. MyAccountControl.DataContext = App.ViewModel.DbViewModel.CurrentUser; DataContext = App.ViewModel.DbViewModel; // From the hidden team and country convert them to team names MyAccountControl.SetFavouriteTeamFromHiddenId(App.AppConstants.FirstFavTeam, App.AppConstants.SecondFavTeam, App.AppConstants.MyCountry); // Set up the default app bar CreateApplicationBarMyAccount(); // Enable disable the activate button if (!App.ViewModel.DbViewModel.CurrentUser.IsValidated) { HyperlinkValidate.Visibility = System.Windows.Visibility.Visible; HyperlinkResendValidationEmail.Visibility = System.Windows.Visibility.Visible; TextblockNid.Visibility = System.Windows.Visibility.Collapsed; } else { HyperlinkValidate.Visibility = System.Windows.Visibility.Collapsed; HyperlinkResendValidationEmail.Visibility = System.Windows.Visibility.Collapsed; TextblockNid.Visibility = System.Windows.Visibility.Visible; } } #endregion #region Event Handlers private void HyperlinkResendValidationEmail_Click(object sender, RoutedEventArgs e) { // Turn on the progress bar SetProgressIndicator(AppResources.ResendEmailMessage, true); // Turn off the button to stop multiple presses HyperlinkResendValidationEmail.IsEnabled = false; // Disable the app bar button - its already disabled if the acount isn't activated //saveChanges.IsEnabled = false; // Do the api call userApi.ResendActivationEmail(App.ViewModel.DbViewModel.CurrentUser.Email, App.ViewModel.DbViewModel.CurrentUser.UserId); } /// <summary> /// They have pressed the button to select a first favourite team on the sub control /// </summary> void RegisterControl_FirstFavouriteTeamPressed(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/FavouriteClubPage.xaml?Team=1", UriKind.Relative)); } /// <summary> /// They have pressed the button to select a second favourite team on the sub control /// </summary> void RegisterControl_SecondFavouriteTeamPressed(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/FavouriteClubPage.xaml?Team=2", UriKind.Relative)); } /// <summary> /// User wants to alter country /// </summary> void MyAccountControl_MyCountryPressed(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/MyCountryPage.xaml", UriKind.Relative)); } /// <summary> /// When the pivot selection changes we want to alter the app bar /// </summary> void PivotControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e) { // close the keyboard if its open this.Focus(); // enable disable app bar depending on the pivot switch (((Pivot)sender).SelectedIndex) { case 0: CreateApplicationBarMyAccount(); break; case 1: CreateApplicationBarForHistory(); break; case 2: CreateApplicationBarForHistory(); break; } } /// <summary> /// The sub control tells us that a save is about to start /// </summary> void MyAccountControl_UpdateAccountStarting(object sender, Controls.UpdateAccountStartingEventArgs e) { ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0]; b.IsEnabled = false; // Get rid of the keyboard this.Focus(); // turn on the progress bar SetProgressIndicator(true); } /// <summary> /// The sub control tells us that a save has finished /// </summary> void MyAccountControl_UpdateAccountCompleted(object sender, Controls.UpdateAccountCompletedEventArgs e) { SetProgressIndicator(false); // If update successful, go to another page if (e.Success) { // show a success message App.PopupHelper.PopupMessages.Enqueue(new PopupMessage(new PopupMessageControl() { Message = e.Message }, new TimeSpan(0, 0, 3))); // Send back a page - which should now be to the home page NavigationService.GoBack(); } else { // Show the error message MessageBox.Show(e.Message, AppResources.UpdateAccountFailed, MessageBoxButton.OK); ApplicationBarIconButton b = (ApplicationBarIconButton)ApplicationBar.Buttons[0]; b.IsEnabled = true; } } void MyAccountControl_RemoveKeyboard(object sender, EventArgs e) { this.Focus(); } #endregion #region App Bar Events /// <summary> /// Save changes /// </summary> void AppBarMenuItemUpdate_Click(object sender, EventArgs e) { // Save is called from the account control MyAccountControl.Save(RegisterScrollViewer); } /// <summary> /// logout /// </summary> void AppBarMenuItemLogout_Click(object sender, EventArgs e) { // Log them out App.ViewModel.DbViewModel.Logout(); // show a success message App.PopupHelper.PopupMessages.Enqueue(new PopupMessage(new PopupMessageControl() { Message = AppResources.LoggedOutMessage}, new TimeSpan(0, 0, 3))); // Send them to the main page //if (NavigationService.CanGoBack) //{ // NavigationService.GoBack(); //} // Now on logout we send them to the login page with instructions to remove the settings page from the back stack this.NavigationService.Navigate(new Uri("/Views/LoginPage.xaml?removeBackStack=yes", UriKind.Relative)); } /// <summary> /// Change password /// </summary> void AppBarMenuItemChangePassword_Click(object sender, EventArgs e) { this.NavigationService.Navigate(new Uri("/Views/PasswordUpdatePage.xaml", UriKind.Relative)); } ///// <summary> ///// Request pin ///// </summary> //void AppBarMenuItemRequestPasswordResetPin_Click(object sender, EventArgs e) //{ // NavigationService.Navigate(new Uri("/PasswordResetPinRequestPage.xaml", UriKind.Relative)); //} ///// <summary> ///// I have pin ///// </summary> //private void AppBarMenuItemEnterPasswordResetPin_Click(object sender, System.EventArgs e) //{ // NavigationService.Navigate(new Uri("/PasswordResetPinEnterPage.xaml", UriKind.Relative)); //} #endregion #region Helpers /// <summary> /// Populate our vote history and purchase history /// </summary> private void PopulateList() { VotingHistory.playersLongList.ItemsSource = (System.Collections.IList)App.ViewModel.DbViewModel.VotingHistory(); TransactionHistory.transactionLongList.ItemsSource = (System.Collections.IList)App.ViewModel.DbViewModel.TransactionHistory(); TeamHistory.pitchHistoryLongList.ItemsSource = (System.Collections.IList)App.ViewModel.DbViewModel.PitchHistory(); } void SetProgressIndicator(bool enabled) { ProgressIndicator progress = new ProgressIndicator { IsVisible = enabled, IsIndeterminate = true, Text = AppResources.UpdatingAccount }; SystemTray.SetProgressIndicator(this, progress); } #endregion #region App Bar Creation /// <summary> /// Create our application bar for my account pivot /// </summary> void CreateApplicationBarMyAccount() { // clear the app bar ApplicationBar.MenuItems.Clear(); ApplicationBar.Buttons.Clear(); ApplicationBar.Mode = ApplicationBarMode.Default; ApplicationBar.Opacity = 1.0; ApplicationBar.IsVisible = true; ApplicationBar.IsMenuEnabled = true; // The save button saveChanges = new ApplicationBarIconButton(); saveChanges.IconUri = new Uri("/Images/AppBar/save.png", UriKind.Relative); saveChanges.Text = AppResources.SaveChanges; saveChanges.Click += new EventHandler(AppBarMenuItemUpdate_Click); if (!App.ViewModel.DbViewModel.CurrentUser.IsValidated) { saveChanges.IsEnabled = false; } ApplicationBar.Buttons.Add(saveChanges); CreateStandardMenuItems(); } /// <summary> /// Create app bar for my votes and my purchases /// </summary> void CreateApplicationBarForHistory() { //ApplicationBar = new ApplicationBar(); // clear the app bar ApplicationBar.MenuItems.Clear(); ApplicationBar.Buttons.Clear(); ApplicationBar.Mode = ApplicationBarMode.Default; ApplicationBar.Opacity = 1.0; ApplicationBar.IsVisible = true; ApplicationBar.IsMenuEnabled = true; // The save button ApplicationBarIconButton saveChanges = new ApplicationBarIconButton(); saveChanges.IsEnabled = false; saveChanges.IconUri = new Uri("/Images/AppBar/save.png", UriKind.Relative); saveChanges.Text = AppResources.SaveChanges; saveChanges.Click += new EventHandler(AppBarMenuItemUpdate_Click); ApplicationBar.Buttons.Add(saveChanges); CreateStandardMenuItems(); } private void CreateStandardMenuItems() { ApplicationBarMenuItem changePassword = new ApplicationBarMenuItem(); changePassword.Text = AppResources.ChangeMyPassword; ApplicationBar.MenuItems.Add(changePassword); changePassword.Click += new EventHandler(AppBarMenuItemChangePassword_Click); // Only show the "activate account" menu bar item when the user isn't activated //if (!App.ViewModel.DbViewModel.CurrentUser.IsValidated) //{ // ApplicationBarMenuItem activateAccount = new ApplicationBarMenuItem(); // activateAccount.Text = "activate account"; // ApplicationBar.MenuItems.Add(activateAccount); // activateAccount.Click += new EventHandler(AppBarMenuItemActivateAccount_Click); //} //ApplicationBarMenuItem sendMePin = new ApplicationBarMenuItem(); //sendMePin.Text = "send me a password reset pin"; //ApplicationBar.MenuItems.Add(sendMePin); //sendMePin.Click += new EventHandler(AppBarMenuItemRequestPasswordResetPin_Click); //ApplicationBarMenuItem iHavePin = new ApplicationBarMenuItem(); //iHavePin.Text = "i have a password reset pin"; //ApplicationBar.MenuItems.Add(iHavePin); //iHavePin.Click += new EventHandler(AppBarMenuItemEnterPasswordResetPin_Click); ApplicationBarMenuItem logout = new ApplicationBarMenuItem(); logout.Text = "logout"; ApplicationBar.MenuItems.Add(logout); logout.Click += AppBarMenuItemLogout_Click; } #endregion #region Resend Email Events void userApi_ResendValidationEmailCompleted(object sender, ResendPinEventArgs e) { // Turn off the progress bar SetProgressIndicator("", false); // Turn back on the button and the app bar menu HyperlinkResendValidationEmail.IsEnabled = true; // Disable the app bar button - its already disabled if the acount isn't activated - no need to re-enable it //saveChanges.IsEnabled = true; // Show a message if (e.ConnectionError == ApiConnectionResult.Good) { // On successful re send, we disable the button to deter rapid presses //TextBlockResendDescription.Visibility = System.Windows.Visibility.Collapsed; HyperlinkResendValidationEmail.Visibility = System.Windows.Visibility.Collapsed; App.PopupHelper.PopupMessages.Enqueue(new PopupMessage(new PopupMessageControl() { Message = e.ServerResponse.Error.Message }, new TimeSpan(0, 0, 3))); } else { MessageBox.Show(e.FriendlyMessage, AppResources.ResendEmailFailed, MessageBoxButton.OK); } } #endregion void SetProgressIndicator(string text, bool enabled) { ProgressIndicator progress = new ProgressIndicator { IsVisible = enabled, IsIndeterminate = true, Text = text }; SystemTray.SetProgressIndicator(this, progress); } } }
using UnityEngine; public class PushPullObj : MonoBehaviour { //=======================| Variables |======================================== //Rigidbody2D rb; Collider2D col; const float radius = 0.6f; bool pushed = false; //=======================| Start() |======================================== private void Start() { //rb = GetComponent<Rigidbody2D>(); //rb.isKinematic = true; col = GetComponent<Collider2D>(); //col.isTrigger = true; } //=======================| Update() |======================================== private void Update() { if (pushed) RaycastOntoTerrain.RaycastOnto2dTerrain(transform, radius); } //=======================| Activate() |======================================== public void Activate() { //rb.isKinematic = false; col.enabled = false; //col.isTrigger = false; pushed = true; } //=======================| Deactivate() |======================================== public void Deactivate() { //rb.isKinematic = true; col.enabled = true; //col.isTrigger = true; pushed = false; } /* * Cannot walk through crates * Can push/drag or jump over * movement_lateral raycast ignores crates * RaycastOntoTerrain includes crates */ }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace RFID_Inventarization { public partial class Catalog : Form { private dbFacade db = new dbFacade(); public Catalog() { InitializeComponent(); } private void Catalog_Load(object sender, EventArgs e) { DataTable table = new DataTable(); table.Columns.Add(new DataColumn("ID", typeof(string))); table.Columns.Add(new DataColumn("Уровень 1", typeof(string))); table.Columns.Add(new DataColumn("Уровень 2", typeof(string))); table.Columns.Add(new DataColumn("Уровень 3", typeof(string))); table.Columns.Add(new DataColumn("Название", typeof(string))); table.Columns.Add(new DataColumn("RFID", typeof(string))); table.Columns.Add(new DataColumn("Комм.", typeof(string))); table.Columns.Add(new DataColumn("Значение", typeof(string))); table.Columns.Add(new DataColumn("Тип знач.", typeof(string))); DataTable table2 = this.db.FetchAllSql("SELECT * FROM data ORDER BY b_id"); foreach (DataRow row2 in table2.Rows) { DataRow row = table.NewRow(); row[0] = row2[8].ToString(); row[1] = row2[2].ToString() + " (" + row2[1].ToString() + ")"; row[2] = row2[4].ToString() + " (" + row2[2].ToString() + ")"; row[3] = row2[6].ToString() + " (" + row2[5].ToString() + ")"; row[4] = row2[7].ToString(); row[5] = row2[9].ToString(); row[6] = row2[10].ToString(); if (row2[11].ToString() == "1") { row[7] = "Найден"; } else { row[7] = " - "; } if (row2[12].ToString() == "1") { row[8] = "Сканер"; } else if (row2[12].ToString() == "2") { row[8] = "Ручной"; } else { row[8] = " - "; } table.Rows.Add(row); } this.dataGrid1.DataSource = table; } private void timer1_Tick(object sender, EventArgs e) { try { base.Text = "Просмотр БД " + Global.getBattary(); } catch (Exception) { } } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("MeshRenderer")] public class MeshRenderer : Renderer { public MeshRenderer(IntPtr address) : base(address, "MeshRenderer") { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using XRTTicket.Contexts; namespace XRTTicket.DAO { public class ActionDao : BaseContext<XRTTicket.Models.Ticket.Action>, IUnitOfWork<XRTTicket.Models.Ticket.Action> { public int Next() { var result = 1;// DbSet.Where(x => x.DescriptionId); //DbSet.Max(x => x.IterationId) + 1; return result; } } }
using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; namespace InspectPlusNamespace { public delegate void ProjectWindowSelectionChangedDelegate( IList<int> newSelection ); [System.Serializable] public class CustomProjectWindow { [SerializeField] private TreeViewState treeViewState; [SerializeField] private string rootDirectory; private CustomProjectWindowDrawer treeView; private SearchField searchField; private GUIContent createButtonContent; public ProjectWindowSelectionChangedDelegate OnSelectionChanged; public void Show( string directory ) { if( treeView != null && rootDirectory == directory ) { Refresh(); return; } if( treeViewState == null || rootDirectory != directory ) treeViewState = new TreeViewState(); treeView = new CustomProjectWindowDrawer( treeViewState, directory ) { OnSelectionChanged = ( newSelection ) => { if( OnSelectionChanged != null ) OnSelectionChanged( newSelection ); } }; searchField = new SearchField(); searchField.downOrUpArrowKeyPressed += treeView.SetFocusAndEnsureSelectedItem; createButtonContent = new GUIContent( "Create" ); rootDirectory = directory; } public CustomProjectWindowDrawer GetTreeView() { return treeView; } public void Refresh() { if( treeView != null ) treeView.Reload(); } public void OnGUI() { GUILayout.BeginHorizontal( EditorStyles.toolbar ); Rect rect = GUILayoutUtility.GetRect( createButtonContent, EditorStyles.toolbarDropDown, GUILayout.ExpandWidth( false ) ); if( EditorGUI.DropdownButton( rect, createButtonContent, FocusType.Passive, EditorStyles.toolbarDropDown ) ) { GUIUtility.hotControl = 0; treeView.ChangeUnitySelection(); EditorUtility.DisplayPopupMenu( rect, "Assets/Create", null ); } GUILayout.Space( 8f ); treeView.searchString = searchField.OnToolbarGUI( treeView.searchString ); GUILayout.EndHorizontal(); rect = GUILayoutUtility.GetRect( 0, 100000, 0, 100000 ); treeView.OnGUI( rect ); } } public class CustomProjectWindowDrawer : TreeView { private class CacheEntry { private Hash128 hash; public int[] ChildIDs; public string[] ChildNames; public Texture2D[] ChildThumbnails; public CacheEntry( string path ) { Refresh( path ); } public void Refresh( string path ) { Hash128 hash = AssetDatabase.GetAssetDependencyHash( path ); if( this.hash != hash ) { this.hash = hash; Object[] childAssets = AssetDatabase.LoadAllAssetRepresentationsAtPath( path ); ChildIDs = new int[childAssets.Length]; ChildNames = new string[childAssets.Length]; ChildThumbnails = new Texture2D[childAssets.Length]; for( int i = 0; i < childAssets.Length; i++ ) { Object childAsset = childAssets[i]; ChildIDs[i] = childAsset.GetInstanceID(); ChildNames[i] = childAsset.name; ChildThumbnails[i] = AssetPreview.GetMiniThumbnail( childAsset ); } } } } private readonly string rootDirectory; private readonly List<TreeViewItem> rows = new List<TreeViewItem>( 100 ); private readonly Dictionary<int, CacheEntry> childAssetsCache = new Dictionary<int, CacheEntry>( 256 ); private readonly MethodInfo instanceIDFromGUID; private readonly CompareInfo textComparer; private readonly CompareOptions textCompareOptions; private bool isSearching; public ProjectWindowSelectionChangedDelegate OnSelectionChanged; public bool SyncSelection; public CustomProjectWindowDrawer( TreeViewState state, string rootDirectory ) : base( state ) { this.rootDirectory = rootDirectory; instanceIDFromGUID = typeof( AssetDatabase ).GetMethod( "GetInstanceIDFromGUID", BindingFlags.NonPublic | BindingFlags.Static ); textComparer = new CultureInfo( "en-US" ).CompareInfo; textCompareOptions = CompareOptions.IgnoreCase | CompareOptions.IgnoreNonSpace; Reload(); } protected override TreeViewItem BuildRoot() { if( AssetDatabase.IsValidFolder( rootDirectory ) ) return new TreeViewItem { id = GetInstanceIDFromPath( rootDirectory ), depth = -1 }; return new TreeViewItem { id = -1, depth = -1 }; } protected override IList<TreeViewItem> BuildRows( TreeViewItem root ) { rows.Clear(); isSearching = !string.IsNullOrEmpty( searchString ); string[] entries; if( FolderHasEntries( rootDirectory, out entries ) ) { AddChildrenRecursive( rootDirectory, 0, entries ); if( isSearching ) rows.Sort( ( x, y ) => EditorUtility.NaturalCompare( x.displayName, y.displayName ) ); } SetupParentsAndChildrenFromDepths( root, rows ); return rows; } private void AddChildrenRecursive( string directory, int depth, string[] entries ) { for( int i = 0; i < entries.Length; i++ ) { string entry = entries[i]; if( string.IsNullOrEmpty( entry ) ) continue; int instanceID = GetInstanceIDFromPath( entry ); string displayName = Path.GetFileNameWithoutExtension( entry ); TreeViewItem item = null; if( !isSearching || textComparer.IndexOf( displayName, searchString, textCompareOptions ) >= 0 ) { item = new TreeViewItem( instanceID, !isSearching ? depth : 0, displayName ) { icon = AssetDatabase.GetCachedIcon( entry ) as Texture2D }; rows.Add( item ); } if( Directory.Exists( entry ) ) { if( isSearching || IsExpanded( instanceID ) ) { string[] entries2; if( FolderHasEntries( entry, out entries2 ) ) AddChildrenRecursive( entry, depth + 1, entries2 ); } else if( FolderHasEntries( entry ) ) item.children = CreateChildListForCollapsedParent(); } else { CacheEntry cacheEntry = GetCacheEntry( instanceID, entry ); int[] childAssets = cacheEntry.ChildIDs; if( childAssets.Length > 0 ) { if( isSearching || IsExpanded( instanceID ) ) { string[] childNames = cacheEntry.ChildNames; Texture2D[] childThumbnails = cacheEntry.ChildThumbnails; if( !isSearching ) { for( int j = 0; j < childAssets.Length; j++ ) rows.Add( new TreeViewItem( childAssets[j], depth + 1, childNames[j] ) { icon = childThumbnails[j] } ); } else { for( int j = 0; j < childAssets.Length; j++ ) { if( textComparer.IndexOf( childNames[j], searchString, textCompareOptions ) >= 0 ) rows.Add( new TreeViewItem( childAssets[j], 0, childNames[j] ) { icon = childThumbnails[j] } ); } } } else item.children = CreateChildListForCollapsedParent(); } } } } protected override IList<int> GetAncestors( int id ) { List<int> ancestors = new List<int>(); string path = AssetDatabase.GetAssetPath( id ); if( string.IsNullOrEmpty( path ) ) return ancestors; if( !AssetDatabase.IsMainAsset( id ) ) ancestors.Add( GetInstanceIDFromPath( path ) ); while( !string.IsNullOrEmpty( path ) ) { path = Path.GetDirectoryName( path ); if( !StringStartsWithFast( path, rootDirectory ) || !AssetDatabase.IsValidFolder( path ) ) break; ancestors.Add( GetInstanceIDFromPath( path ) ); } return ancestors; } protected override IList<int> GetDescendantsThatHaveChildren( int id ) { string path = AssetDatabase.GetAssetPath( id ); if( string.IsNullOrEmpty( path ) ) return new List<int>( 0 ); if( !StringStartsWithFast( path, rootDirectory ) ) { if( StringStartsWithFast( rootDirectory, path ) ) { path = rootDirectory; id = rootItem.id; } else return new List<int>( 0 ); } string[] entries; if( !FolderHasEntries( path, out entries ) ) { if( File.Exists( path ) && AssetDatabase.IsMainAsset( id ) ) { if( GetCacheEntry( id, path ).ChildIDs.Length > 0 ) return new List<int>( 1 ) { id }; } return new List<int>( 0 ); } Stack<string> pathsStack = new Stack<string>(); Stack<string[]> entriesStack = new Stack<string[]>(); pathsStack.Push( path ); entriesStack.Push( entries ); List<int> parents = new List<int>(); while( pathsStack.Count > 0 ) { string current = pathsStack.Pop(); string[] currentEntries = entriesStack.Pop(); parents.Add( GetInstanceIDFromPath( current ) ); for( int i = 0; i < currentEntries.Length; i++ ) { string currentEntry = currentEntries[i]; if( string.IsNullOrEmpty( currentEntry ) ) continue; if( FolderHasEntries( currentEntry, out entries ) ) { pathsStack.Push( currentEntry ); entriesStack.Push( entries ); } else if( File.Exists( currentEntry ) ) { int instanceID = GetInstanceIDFromPath( currentEntry ); if( GetCacheEntry( instanceID, currentEntry ).ChildIDs.Length > 0 ) parents.Add( instanceID ); } } } return parents; } protected override bool CanBeParent( TreeViewItem item ) { return AssetDatabase.IsValidFolder( AssetDatabase.GetAssetPath( item.id ) ); } protected override void SelectionChanged( IList<int> selectedIds ) { try { if( OnSelectionChanged != null ) OnSelectionChanged( selectedIds ); } catch( System.Exception e ) { Debug.LogException( e ); } if( !SyncSelection || selectedIds == null ) return; int[] selectionArray = new int[selectedIds.Count]; selectedIds.CopyTo( selectionArray, 0 ); Selection.instanceIDs = selectionArray; } protected override bool CanRename( TreeViewItem item ) { return true; } protected override void RenameEnded( RenameEndedArgs args ) { if( args.acceptedRename ) AssetDatabase.RenameAsset( AssetDatabase.GetAssetPath( args.itemID ), args.newName ); } protected override void DoubleClickedItem( int id ) { AssetDatabase.OpenAsset( id ); } protected override void ContextClicked() { Selection.activeObject = AssetDatabase.LoadAssetAtPath<Object>( rootDirectory ); EditorUtility.DisplayPopupMenu( new Rect( Event.current.mousePosition, new Vector2( 0f, 0f ) ), "Assets/", null ); Event.current.Use(); } protected override void ContextClickedItem( int id ) { ChangeUnitySelection(); EditorUtility.DisplayPopupMenu( new Rect( Event.current.mousePosition, new Vector2( 0f, 0f ) ), "Assets/", null ); Event.current.Use(); } protected override void CommandEventHandling() { Event e = Event.current; if( ( e.type == EventType.ValidateCommand || e.type == EventType.ExecuteCommand ) && HasSelection() ) { if( ( e.commandName == "Delete" || e.commandName == "SoftDelete" ) ) { if( e.type == EventType.ExecuteCommand ) DeleteAssets( GetSelection(), e.commandName == "SoftDelete" ); e.Use(); return; } else if( e.commandName == "Duplicate" ) { if( e.type == EventType.ExecuteCommand ) DuplicateAssets( GetSelection() ); e.Use(); return; } } base.CommandEventHandling(); } protected override bool CanStartDrag( CanStartDragArgs args ) { return HasSelection(); } protected override void SetupDragAndDrop( SetupDragAndDropArgs args ) { DragAndDrop.PrepareStartDrag(); IList<int> sortedDraggedIDs = SortItemIDsInRowOrder( args.draggedItemIDs ); List<Object> objList = new List<Object>( sortedDraggedIDs.Count ); List<string> paths = new List<string>( sortedDraggedIDs.Count ); for( int i = 0; i < sortedDraggedIDs.Count; i++ ) { int instanceID = sortedDraggedIDs[i]; Object obj = EditorUtility.InstanceIDToObject( instanceID ); if( obj != null ) { objList.Add( obj ); string path = AssetDatabase.GetAssetPath( obj ); if( !string.IsNullOrEmpty( path ) && paths.IndexOf( path ) < 0 ) paths.Add( path ); } } DragAndDrop.objectReferences = objList.ToArray(); DragAndDrop.paths = paths.ToArray(); DragAndDrop.StartDrag( objList.Count > 1 ? "<Multiple>" : objList[0].name ); } protected override DragAndDropVisualMode HandleDragAndDrop( DragAndDropArgs args ) { string parentFolder = null; switch( args.dragAndDropPosition ) { case DragAndDropPosition.UponItem: case DragAndDropPosition.BetweenItems: if( args.parentItem != null && ( !hasSearch || args.dragAndDropPosition == DragAndDropPosition.UponItem ) ) parentFolder = AssetDatabase.GetAssetPath( args.parentItem.id ); break; case DragAndDropPosition.OutsideItems: parentFolder = rootDirectory; break; } if( hasSearch && ( args.parentItem == rootItem || parentFolder == rootDirectory ) ) return DragAndDropVisualMode.None; if( string.IsNullOrEmpty( parentFolder ) || !AssetDatabase.IsValidFolder( parentFolder ) ) return DragAndDropVisualMode.None; if( args.performDrop ) MoveAssets( DragAndDrop.objectReferences, parentFolder ); return DragAndDropVisualMode.Move; } private bool MoveAssets( IList<Object> assets, string parentFolder ) { bool containsAsset = false; bool containsSceneObject = false; List<string> paths = new List<string>( assets.Count ); List<bool> directoryStates = new List<bool>( assets.Count ); for( int i = 0; i < assets.Count; i++ ) { string path = AssetDatabase.GetAssetPath( assets[i] ); // Can't make a folder a subdirectory of itself if( path == parentFolder ) return false; if( string.IsNullOrEmpty( path ) ) containsSceneObject = true; else if( paths.IndexOf( path ) < 0 ) { paths.Add( path ); directoryStates.Add( Directory.Exists( path ) ); containsAsset = true; } } if( containsAsset && containsSceneObject ) return false; if( containsSceneObject ) { // Convert all scene objects to Transforms int invalidObjectCount = 0; for( int i = 0; i < assets.Count; i++ ) { if( assets[i] is GameObject ) assets[i] = ( (GameObject) assets[i] ).transform; else if( assets[i] is Component ) assets[i] = ( (Component) assets[i] ).transform; else { assets[i] = null; invalidObjectCount++; } } if( invalidObjectCount == assets.Count ) return false; // Remove child Transforms whose parents are also included in drag&drop for( int i = assets.Count - 1; i >= 0; i-- ) { if( assets[i] == null ) continue; Transform transform = (Transform) assets[i]; for( int j = 0; j < assets.Count; j++ ) { if( i == j || assets[j] == null ) continue; if( transform.IsChildOf( (Transform) assets[j] ) ) { assets[i] = null; break; } } } List<int> instanceIDs = new List<int>( assets.Count ); AssetDatabase.StartAssetEditing(); try { for( int i = assets.Count - 1; i >= 0; i-- ) { if( assets[i] == null ) continue; Transform transform = (Transform) assets[i]; string path = AssetDatabase.GenerateUniqueAssetPath( Path.Combine( parentFolder, transform.name + ".prefab" ) ); #if UNITY_2018_3_OR_NEWER GameObject prefab = PrefabUtility.SaveAsPrefabAssetAndConnect( transform.gameObject, path, InteractionMode.UserAction ); #else GameObject prefab = PrefabUtility.CreatePrefab( path, transform.gameObject, ReplacePrefabOptions.ConnectToPrefab ); #endif if( prefab ) instanceIDs.Add( prefab.GetInstanceID() ); } } finally { AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); } SetSelection( instanceIDs, TreeViewSelectionOptions.RevealAndFrame ); return true; } // Remove descendant paths for( int i = paths.Count - 1; i >= 0; i-- ) { string path = paths[i]; for( int j = 0; j < paths.Count; j++ ) { if( i == j || !directoryStates[j] ) continue; if( StringStartsWithFast( path, paths[j] ) ) { paths.RemoveAt( i ); break; } } } if( paths.Count == 0 ) return false; string[] entries = Directory.GetFileSystemEntries( parentFolder ); for( int i = 0; i < entries.Length; i++ ) { // Don't allow move if an asset is already located inside parentFolder if( paths.IndexOf( entries[i].Replace( '\\', '/' ) ) >= 0 ) return false; entries[i] = Path.GetFileName( entries[i] ); } // Check if there are files in parentFolder with conflicting names string[] newPaths = new string[paths.Count]; for( int i = 0; i < paths.Count; i++ ) { string filename = Path.GetFileName( paths[i] ); for( int j = 0; j < entries.Length; j++ ) { if( filename == entries[j] ) return false; } newPaths[i] = Path.Combine( parentFolder, filename ); } string error = null; AssetDatabase.StartAssetEditing(); try { for( int i = 0; i < paths.Count; i++ ) { error = AssetDatabase.MoveAsset( paths[i], newPaths[i] ); if( !string.IsNullOrEmpty( error ) ) break; } } finally { AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); } if( !string.IsNullOrEmpty( error ) ) { Debug.LogError( error ); return false; } else { int[] instanceIDs = new int[newPaths.Length]; for( int i = 0; i < newPaths.Length; i++ ) instanceIDs[i] = GetInstanceIDFromPath( newPaths[i] ); SetSelection( instanceIDs, TreeViewSelectionOptions.RevealAndFrame ); return true; } } // Credit: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ProjectWindow/ProjectWindowUtil.cs private bool DeleteAssets( IList<int> instanceIDs, bool askIfSure ) { if( instanceIDs.Count == 0 ) return true; if( instanceIDs.IndexOf( GetInstanceIDFromPath( "Assets" ) ) >= 0 ) { EditorUtility.DisplayDialog( "Cannot Delete", "Deleting the 'Assets' folder is not allowed", "Ok" ); return false; } List<string> paths = GetPathsOfMainAssets( instanceIDs ); if( paths.Count == 0 ) return false; if( askIfSure ) { int maxCount = 3; StringBuilder infotext = new StringBuilder(); for( int i = 0; i < paths.Count && i < maxCount; ++i ) infotext.AppendLine( " " + paths[i] ); if( paths.Count > maxCount ) infotext.AppendLine( " ..." ); infotext.AppendLine( "You cannot undo this action." ); if( !EditorUtility.DisplayDialog( paths.Count > 1 ? "Delete selected assets?" : "Delete selected asset?", infotext.ToString(), "Delete", "Cancel" ) ) return false; } bool success = true; AssetDatabase.StartAssetEditing(); try { for( int i = 0; i < paths.Count; i++ ) { if( ( File.Exists( paths[i] ) || Directory.Exists( paths[i] ) ) && !AssetDatabase.MoveAssetToTrash( paths[i] ) ) success = false; } } finally { AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); } if( !success ) { string message = "Some assets could not be deleted.\n" + "If you are using Version Control server, make sure you are connected to your VCS or \"Work Offline\" is enabled.\n" + "Otherwise, make sure nothing is keeping a hook on the deleted assets, like a loaded DLL for example."; EditorUtility.DisplayDialog( "Cannot Delete", message, "Ok" ); } return success; } // Credit: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Editor/Mono/ProjectWindow/ProjectWindowUtil.cs private void DuplicateAssets( IList<int> instanceIDs ) { AssetDatabase.Refresh(); List<string> paths = GetPathsOfMainAssets( instanceIDs ); if( paths.Count == 0 ) return; List<string> copiedPaths = new List<string>( paths.Count ); AssetDatabase.StartAssetEditing(); try { for( int i = 0; i < paths.Count; i++ ) { string newPath = AssetDatabase.GenerateUniqueAssetPath( paths[i] ); if( !string.IsNullOrEmpty( newPath ) && AssetDatabase.CopyAsset( paths[i], newPath ) ) copiedPaths.Add( newPath ); } } finally { AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(); } int[] newInstanceIDs = new int[copiedPaths.Count]; for( int i = 0; i < copiedPaths.Count; i++ ) newInstanceIDs[i] = GetInstanceIDFromPath( copiedPaths[i] ); SetSelection( newInstanceIDs, TreeViewSelectionOptions.RevealAndFrame ); } public void ChangeUnitySelection() { IList<int> selection = GetSelection(); if( selection.Count == 0 ) Selection.activeObject = AssetDatabase.LoadAssetAtPath<Object>( rootDirectory ); else { int[] selectionArray = new int[selection.Count]; selection.CopyTo( selectionArray, 0 ); Selection.instanceIDs = selectionArray; } } private List<string> GetPathsOfMainAssets( IList<int> instanceIDs ) { List<string> result = new List<string>( instanceIDs.Count ); for( int i = 0; i < instanceIDs.Count; i++ ) { if( AssetDatabase.IsMainAsset( instanceIDs[i] ) ) result.Add( AssetDatabase.GetAssetPath( instanceIDs[i] ) ); } return result; } private bool FolderHasEntries( string path ) { if( !AssetDatabase.IsValidFolder( path ) ) return false; string[] entries = Directory.GetFileSystemEntries( path ); for( int i = 0; i < entries.Length; i++ ) { string entry = entries[i]; if( !StringEndsWithFast( entry, ".meta" ) && !string.IsNullOrEmpty( AssetDatabase.AssetPathToGUID( entry ) ) ) return true; } return false; } private bool FolderHasEntries( string path, out string[] entries ) { if( !AssetDatabase.IsValidFolder( path ) ) { entries = null; return false; } bool hasValidEntries = false; entries = Directory.GetFileSystemEntries( path ); for( int i = 0, lastFileIndex = -1; i < entries.Length; i++ ) { string entry = entries[i]; if( !StringEndsWithFast( entry, ".meta" ) && !string.IsNullOrEmpty( AssetDatabase.AssetPathToGUID( entry ) ) ) hasValidEntries = true; else { entries[i] = null; continue; } // Sort the entries to ensure that directories come first if( Directory.Exists( entry ) ) { if( lastFileIndex >= 0 ) { for( int j = i; j > lastFileIndex; j-- ) entries[j] = entries[j - 1]; entries[lastFileIndex] = entry; lastFileIndex++; } } else if( lastFileIndex < 0 ) lastFileIndex = i; } return hasValidEntries; } private int GetInstanceIDFromPath( string path ) { if( instanceIDFromGUID != null ) return (int) instanceIDFromGUID.Invoke( null, new object[1] { AssetDatabase.AssetPathToGUID( path ) } ); else return AssetDatabase.LoadMainAssetAtPath( path ).GetInstanceID(); } private CacheEntry GetCacheEntry( int instanceID, string path ) { CacheEntry cacheEntry; if( !childAssetsCache.TryGetValue( instanceID, out cacheEntry ) ) { cacheEntry = new CacheEntry( path ); childAssetsCache[instanceID] = cacheEntry; } else cacheEntry.Refresh( path ); return cacheEntry; } private bool StringStartsWithFast( string str, string prefix ) { int length1 = str.Length; int length2 = prefix.Length; int index1 = 0; int index2 = 0; while( index1 < length1 && index2 < length2 && str[index1] == prefix[index2] ) { index1++; index2++; } return index2 == length2; } private bool StringEndsWithFast( string str, string suffix ) { int index1 = str.Length - 1; int index2 = suffix.Length - 1; while( index1 >= 0 && index2 >= 0 && str[index1] == suffix[index2] ) { index1--; index2--; } return index2 < 0; } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; using ServiceDesk.Core.Entities.RequestSystem; using ServiceDesk.Core.Interfaces.Common; namespace ServiceDesk.Core.Entities.DirectorySystem { public class SoftwareModule : IEntity { public int Id { get; set; } public string Title { get; set; } public int SoftwareId { get; set; } public virtual Software Software { get; set; } [IgnoreDataMember] public virtual ICollection<Request> Requests { get; set; } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Dynamic; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using Voronov.Nsudotnet.BuildingCompanyIS.Entities; using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces; namespace Voronov.Nsudotnet.BuildingCompanyIS.UI.ViewModels { public class WorkTypeViewModel : PropertyChangedBase { public WorkTypeViewModel() { WorkTypeEntity = new WorkType(); } public WorkTypeViewModel(WorkType entity) { WorkTypeEntity = entity; } public WorkType WorkTypeEntity { get; private set; } public String WorkTypeName { get { return WorkTypeEntity.Name; } set { if (value == WorkTypeEntity.Name) return; if (value.Length == 0) return; WorkTypeEntity.Name = value; NotifyOfPropertyChange(() => WorkTypeName); } } } public class WorkTypeDetailedView : PropertyChangedBase { public WorkTypeDetailedView(ICrudService<WorkType> service) { _service = service; MyRefresh(); } public WorkTypeViewModel NewWorkType { get; private set; } private ICrudService<WorkType> _service; public BindableCollection<WorkTypeViewModel> WorkTypes { get; private set; } private WorkTypeViewModel _selectedWorkType; public WorkTypeViewModel SelectedWorkType { get { return _selectedWorkType;} set { if (value == _selectedWorkType) return; _selectedWorkType = value; NotifyOfPropertyChange(()=>SelectedWorkType); } } public String NewWorkTypeName { get { return NewWorkType.WorkTypeName; } set { if (value == NewWorkType.WorkTypeName) return; NewWorkType.WorkTypeName = value; NotifyOfPropertyChange(()=>NewWorkTypeName); } } public void Add() { try { var obj = WorkTypes.FirstOrDefault(e => e.WorkTypeName == NewWorkTypeName); if (obj != null) return; _service.CreateAndSave(NewWorkType.WorkTypeEntity); NewWorkType = new WorkTypeViewModel(); NotifyOfPropertyChange(() => NewWorkTypeName); } catch (DbException e) { Console.Out.WriteLine(e); Error = Messages.ErrorMessageOnAddingEntity; } } public void Delete() { try { _service.DeleteAndSave(_selectedWorkType.WorkTypeEntity); WorkTypes.Remove(_selectedWorkType); NotifyOfPropertyChange(() => WorkTypes); } catch (DbException e) { Console.Out.WriteLine(e); Error = Messages.ErrorMessageOnDeleteEntity; } } public void MyRefresh() { NewWorkType = new WorkTypeViewModel(); NotifyOfPropertyChange(()=>NewWorkTypeName); WorkTypes = new BindableCollection<WorkTypeViewModel>(); foreach (var workType in _service.All) { WorkTypes.Add(new WorkTypeViewModel(workType)); } NotifyOfPropertyChange(()=>WorkTypes); } private String _error; public String Error { get { return _error; } private set { _error = value; NotifyOfPropertyChange(()=>Error); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Loadcfg : MonoBehaviour { IEnumerator Start () { NpcCfgMgr.LoadConfig(); while (!NpcCfgMgr.IsDone) yield return null; print( NpcCfgMgr.GetcfgName(2)); print(NpcCfgMgr.GetcfgIntroduce(2)); RushCfgMgr.LoadRushConfig(); while (!RushCfgMgr.IsDone) yield return null; print(RushCfgMgr.GetMapCfg(1)); print(RushCfgMgr.GetMapPosCfg(002, 002)); print(RushCfgMgr.GetMapPosCfgValue(002, 002, "Count")); print(RushCfgMgr.GetMapPosCfgValue(002, 002, "Scale")); //这里刷怪参数名称如下和对应意义 //_Name = Count/数量 NpcID/npcID FirstTime/刷怪初始时间 Intervals/刷怪间隔时间 Scale/缩放比(10为一倍大小) } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading; namespace Planning { class ExternalPlanners { public static string ffPath = @"ff.exe"; public static string ffPath2 = @"ff.exe"; public static string cygwinPath = @"C:\cygwin\"; public static string fdOutputPath = @"C:\cygwin\home\shlomi\"; //****************************************************************************************************************************************************** public static string rotemCygwinPath = @"C:\cygwin64"; //My computer path //public static string rotemCygwinPath = @"D:\Rotem\Cygwin"; //Left server path //public static string rotemCygwinPath = @"D:\rotem\Cygwin"; //Right server path public static string fdPath = rotemCygwinPath + @"\home\Fast-Downward-af6295c3dc9b\src\garbage\"; //change this to your FD pddl files folder path public static string fdPython27Path = rotemCygwinPath + @"\bin\python2.7.exe"; //change this to your FD python path public static string fdRunningPath = rotemCygwinPath + @"\home\Fast-Downward-af6295c3dc9b\fast-downward.py"; //change this to your FD running path //****************************************************************************************************************************************************** public static bool unsolvableProblem = false; private CancellationToken token; private string SymPATempPDDLFolder = null; public static List<Process> processesCreated = new List<Process>(); public static TimeSpan PlannerTimeout = new TimeSpan(0, 5, 0); public ExternalPlanners() { // Console.WriteLine(" * "); this.token = default(CancellationToken); } public ExternalPlanners(CancellationToken token) { this.token = token; } public ExternalPlanners(CancellationToken token, string SymPATempPDDLFolder) { this.token = token; this.SymPATempPDDLFolder = SymPATempPDDLFolder; } private void ThrowIfCancellationRequested() { Program.cancellationTokenSource.Token.ThrowIfCancellationRequested(); token.ThrowIfCancellationRequested(); } public List<string> PlanFiles(bool bUseFF, bool bUseFD, string domainPath, string problemPath, int cMaxMilliseconds, out bool bUnsolvable) { List<string> lPlan = null; unsolvableProblem = false; // string sFDPath = @"C:\cygwin\home\shlomi\FastDownward\src\"; string domainStr = MakeDomainCompatible(File.ReadAllText(domainPath)); string problemStr = MakeProblemCompatible(File.ReadAllText(problemPath)); Process pFF = null, pFD = null; if (bUseFF) pFF = RunFF(domainStr, problemStr); if (bUseFD) { //pFD = RunFD(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState)); pFD = RunFDPlannerWithFiles(domainStr, problemStr); } bUnsolvable = false; bool bFFDone = false, bFDDone = false; Process[] process; if (bUseFF && !bUseFD) process = new Process[] { pFF }; else if (!bUseFF && bUseFD) process = new Process[] { pFD }; else process = new Process[] { pFF, pFD }; if (WaitForProcesses(process, cMaxMilliseconds, out bFFDone, out bFDDone)) { if (bFFDone) { //Console.WriteLine("Plan found by FF"); Thread.Sleep(150); lPlan = ReadFFPlan(process[0].Id, null, out bUnsolvable); KillAll(process.ToList()); Thread.Sleep(50); } else if (bFDDone) { //Console.WriteLine("Plan found by FD"); Thread.Sleep(100); int pFD_id = 0; if (bUseFF) pFD_id = 1; int exitCode = process[pFD_id].ExitCode; if (exitCode == 22) { Console.WriteLine("The search was terminated due to memory limitation"); } if (exitCode == 12) { Console.WriteLine("There is no solution for this problem (exusted all possabilities)"); unsolvableProblem = true; } lPlan = ReadPlan(fdPath); KillAll(process.ToList()); Thread.Sleep(50); } return lPlan; } return null; } private string MakeProblemCompatible(string problemStr) { return RemovePrivateStuff(problemStr); } private string MakeDomainCompatible(string domainStr) { domainStr = domainStr.Replace(" :factored-privacy", ""); domainStr = RemovePrivateStuff(domainStr); return domainStr; } private string RemovePrivateStuff(string pddlFile) { string res = pddlFile; if (pddlFile.Contains("(:private")) { string[] split = pddlFile.Split(new string[] { "(:private" }, StringSplitOptions.None); string afterPrivate = split[1]; int openNum = 0; int endPrivateIndex = -1; for (int i = 0; i < afterPrivate.Length; i++) { char curr = afterPrivate[i]; if(curr == ')') { if(openNum == 0) { endPrivateIndex = i; break; } openNum--; } else if(curr == '(') { openNum++; } } if(endPrivateIndex == -1) { throw new Exception("The private block does not end..."); } string privateStuff = afterPrivate.Substring(0, endPrivateIndex); string afterWithoutPrivateStuff = afterPrivate.Substring(endPrivateIndex + 1); res = split[0] + privateStuff + afterWithoutPrivateStuff; } return res; } public List<string> Plan(bool bUseFF, bool bUseFD, bool bUseSymPA, Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable, string SymPAFilename, bool useSecondFFPath = false) { bUseFD = false; if(bUseSymPA && SymPAFilename == null) { throw new ArgumentNullException("SymPA Filename", "Indicated that we want to use SymPA planner, but did not indicate where is the planner located"); } //Program.KillPlanners(); List<string> lPlan = null; unsolvableProblem = false; if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; // string sFDPath = @"C:\cygwin\home\shlomi\FastDownward\src\"; Process pFF = null, pFD = null, pSymPA = null; string FFdomainName = null, FFproblemName = null, FFOutputPath = null; if (bUseFF) { if (Program.runningOnLinux) { pFF = RunFFWithFiles(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState), out FFdomainName, out FFproblemName, out FFOutputPath, useSecondFFPath); } else { pFF = RunFF(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState)); } processesCreated.Add(pFF); } if (bUseFD) { //pFD = RunFD(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState)); pFD = RunFDPlannerWithFiles(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState)); processesCreated.Add(pFD); } if (bUseSymPA) { pSymPA = RunSymPAPlannerWithFiles(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState), SymPAFilename); processesCreated.Add(pSymPA); } bUnsolvable = false; bool bFFDone = false, bFDDone = false, bSymPADone = false; List<Process> process = new List<Process>(); if (bUseFF) process.Add(pFF); if (bUseFD) process.Add(pFD); if (bUseSymPA) process.Add(pSymPA); //Console.WriteLine("0"); if (WaitForProcessesWithSymPA(process, pFF, pFD, pSymPA, cMaxMilliseconds, out bFFDone, out bFDDone, out bSymPADone)) { //Console.WriteLine("1"); if (bFFDone) { //Console.WriteLine("2"); //Console.WriteLine("Plan found by FF"); Thread.Sleep(150); lPlan = ReadFFPlan(pFF.Id, FFOutputPath, out bUnsolvable); KillAll(process.ToList()); Thread.Sleep(50); //Console.WriteLine("3"); if (Program.runningOnLinux) { // Delete domain and problem files: File.Delete(FFdomainName); File.Delete(FFproblemName); File.Delete(FFproblemName + ".ff"); File.Delete(FFOutputPath); } } else if (bFDDone) { //Console.WriteLine("Plan found by FD"); Thread.Sleep(100); int exitCode = pFD.ExitCode; if (exitCode == 22) { Console.WriteLine("The search was terminated due to memory limitation"); } if(exitCode == 12) { Console.WriteLine("There is no solution for this problem (exusted all possabilities)"); unsolvableProblem = true; } lPlan = ReadPlan(fdPath); KillAll(process.ToList()); Thread.Sleep(50); } else if (bSymPADone) { Thread.Sleep(100); lPlan = ReadSymPAPlan(SymPATempPDDLFolder, out bUnsolvable); KillAll(process.ToList()); Thread.Sleep(50); } return lPlan; } //Console.WriteLine("4"); return null; } public List<string> Plan(string agent, bool bUseFF, bool bUseFD, Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { //Program.KillPlanners(); List<string> lPlan = null; if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; string sFDPath = @"C:\cygwin\home\shlomi\FastDownward\src\"; Process pFF = null, pFD = null; if (bUseFF) pFF = RunFF(d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState)); if (bUseFD) pFD = RunFD(agent, sFDPath, d.WriteSimpleDomain(), p.WriteSimpleProblem(curentState)); bUnsolvable = false; bool bFFDone = false, bFDDone = false; Process[] process; if (bUseFF && !bUseFD) process = new Process[] { pFF }; else if (!bUseFF && bUseFD) process = new Process[] { pFD }; else process = new Process[] { pFF, pFD }; if (WaitForProcesses(process, cMaxMilliseconds, out bFFDone, out bFDDone)) { if (bFFDone) { // Console.WriteLine("Plan found by FF"); Thread.Sleep(200); lPlan = ReadFFPlan(process[0].Id, null, out bUnsolvable); KillAll(process.ToList()); } else if (bFDDone) { Console.WriteLine("Plan found by FD"); Thread.Sleep(100); lPlan = ReadPlan(@"C:\cygwin\home\shlomi\"); KillAll(process.ToList()); } return lPlan; } return null; } private List<string> ReadSymPAPlan(string symPATempPDDLFolder, out bool bUnsolvable) { string[] lines = File.ReadAllLines(symPATempPDDLFolder + "/log"); string lastLine = lines[lines.Length - 1]; string secondToLastLine = lines[lines.Length - 2]; if(lastLine.Contains("unsolvable") || secondToLastLine.Contains("unsolvable")) { unsolvableProblem = true; bUnsolvable = true; return null; } else if(lastLine.Contains("solvable") || secondToLastLine.Contains("solvable")) { unsolvableProblem = false; bUnsolvable = false; return FindSymPAPlan(symPATempPDDLFolder + "/log"); } bUnsolvable = false; return null; } private List<string> FindSymPAPlan(string planFile) { throw new NotImplementedException(); } public List<string> ReadFFPlan(int iPID, string ffOutputPath, out bool bUnsolvable) { string sOutput; if (Program.runningOnLinux) { sOutput = File.ReadAllText(ffOutputPath); } else { sOutput = FFOutput[iPID]; } //Console.WriteLine("Writing FF output:"); //Console.WriteLine(sOutput); MemoryStream planMs = new MemoryStream(); if (sOutput.Contains("found legal plan as follows")) { string sPlan = sOutput.Substring(sOutput.IndexOf("found legal plan as follows")); sPlan = sPlan.Replace("found legal plan as follows", "").Trim(); string[] asPlan = sPlan.Split('\n'); string sFinalPlan = ""; for (int i = 0; i < asPlan.Length; i++) { if (!asPlan[i].Contains(":")) break; if (asPlan[i].Contains("time spent:")) break; sFinalPlan += asPlan[i].Substring(asPlan[i].IndexOf(':') + 2).Trim() + "\n"; } StreamWriter sw = new StreamWriter(planMs); sw.WriteLine(sFinalPlan); sw.Close(); bUnsolvable = false; } else { if (sOutput.Contains("best first search space empty! problem proven unsolvable.") || sOutput.Contains("ff: goal can be simplified to FALSE. No plan will solve it")) { Console.WriteLine("FF found that the problem is unsolvable"); unsolvableProblem = true; } if (sOutput.Contains("goal can be simplified to TRUE")) { bUnsolvable = false; return new List<string>(); } else if (sOutput.Contains("goal can be simplified to FALSE")) { bUnsolvable = true; return null; } else { bUnsolvable = false; return null; } } List<string> lPlan = ReadPlan(new MemoryStream(planMs.ToArray())); return lPlan; } public bool WaitForProcesses(Process[] a, int cMaxMilliseconds, out bool bFFDone, out bool bFDDone) { DateTime dtStart = DateTime.Now; bool bDone = false; bFFDone = false; bFDDone = false; Process[] workingProcesses = new Process[a.Length]; for(int i = 0; i < a.Length; i++) { workingProcesses[i] = a[i]; } int indexOfWorkingProcess = 0; while (!bDone) { ThrowIfCancellationRequested(); bDone = false; workingProcesses[indexOfWorkingProcess].WaitForExit(200); //List<Process> l = GetPlanningProcesses(); foreach (Process p in workingProcesses) { if (p != null) { if (p.HasExited) { if (p.StartInfo.FileName == ffPath) { string sOutput = FFOutput[p.Id]; if (sOutput.Contains("too many consts in type ARTFICIAL-ALL-OBJECTS! increase MAX_TYPE (currently 2000)") && a.Length > 1 && workingProcesses[1] != null) { Console.WriteLine("The FF search was terminated due to const limitation, continuing with FD and trying to find a valid plan with it."); workingProcesses[0] = null; indexOfWorkingProcess = 1; continue; } bFFDone = true; bFDDone = false; } else { int exitCode = p.ExitCode; if (exitCode == 22 && a.Length > 1 && workingProcesses[0] != null) //if it is not the only process (we are running FF too), than try to wait for FF { Console.WriteLine("The FD search was terminated due to memory limitation, continuing with FF and trying to find a valid plan with it."); workingProcesses[1] = null; continue; } bFFDone = false; bFDDone = true; } bDone = true; } } } if (!bDone) { try { TimeSpan ts = (DateTime.Now - dtStart); if (ts.TotalMilliseconds > cMaxMilliseconds) { bDone = true; } bool bMemSizeLimitReached = false; foreach (Process pPlanning in GetPlanningProcesses()) { if (pPlanning.WorkingSet64 > 2 * Math.Pow(2, 30)) { bMemSizeLimitReached = true; } } if (bMemSizeLimitReached) { bDone = true; } } catch (Exception e) { } } } KillAll(a.ToList()); List<Process> lPlanningProcesses = GetPlanningProcesses(); KillAll(lPlanningProcesses); ThrowIfCancellationRequested(); return bFDDone || bFFDone; } public int GetNextNonNullProcess(Process[] workingProcesses, int currP) { for(int i = 0; i < workingProcesses.Length; i++) { if (i != currP && workingProcesses[i] != null) return currP; } return -1; //all other processes are null... } public bool WaitForProcessesWithSymPA(List<Process> a, Process pFF, Process pFD, Process pSymPA, int cMaxMilliseconds, out bool bFFDone, out bool bFDDone, out bool bSymPADone) { DateTime dtStart = DateTime.Now; bool bDone = false; bFFDone = false; bFDDone = false; bSymPADone = false; Process[] workingProcesses = new Process[a.Count]; Dictionary<Process, int> placeInArray = new Dictionary<Process, int>(); for (int i = 0; i < a.Count; i++) { workingProcesses[i] = a[i]; placeInArray[a[i]] = i; } int indexOfWorkingProcess = 0; while (!bDone) { ThrowIfCancellationRequested(); bDone = false; workingProcesses[indexOfWorkingProcess].WaitForExit(200); //List<Process> l = GetPlanningProcesses(); foreach (Process p in workingProcesses) { if (p != null) { if (p.HasExited) { int currI = placeInArray[p]; int nextP = GetNextNonNullProcess(workingProcesses, currI); if (p == pFF) { string sOutput = FFOutput[p.Id]; if (sOutput.Contains("too many consts in type ARTFICIAL-ALL-OBJECTS! increase MAX_TYPE (currently 2000)") && a.Count > 1 && nextP != -1) { Console.WriteLine("The FF search was terminated due to const limitation, continuing with other planners and trying to find a valid plan with them."); workingProcesses[currI] = null; indexOfWorkingProcess = nextP; continue; } bFFDone = true; } else if(p == pFD) { int exitCode = p.ExitCode; if (exitCode == 22 && a.Count > 1 && nextP != -1) //if it is not the only process (we are running FF too), than try to wait for FF { Console.WriteLine("The FD search was terminated due to memory limitation, continuing with other planners and trying to find a valid plan with them."); workingProcesses[currI] = null; indexOfWorkingProcess = nextP; continue; } bFDDone = true; } else // if (p == pSymPA) { //need to check this exitCode; int exitCode = p.ExitCode; if (exitCode == 22 && a.Count > 1 && nextP != -1) //if it is not the only process (we are running FF too), than try to wait for FF { Console.WriteLine("The SymPA search was terminated due to memory limitation, continuing with other planners and trying to find a valid plan with them."); workingProcesses[currI] = null; indexOfWorkingProcess = nextP; continue; } bSymPADone = true; } bDone = true; } } } if (!bDone) { try { TimeSpan ts = (DateTime.Now - dtStart); if (ts.TotalMilliseconds > cMaxMilliseconds) { bDone = true; } bool bMemSizeLimitReached = false; //foreach (Process pPlanning in GetPlanningProcesses()) foreach (Process pPlanning in a) { if (pPlanning.WorkingSet64 > 2 * Math.Pow(2, 30)) { bMemSizeLimitReached = true; } } if (bMemSizeLimitReached) { bDone = true; } } catch (Exception e) { } } } KillAll(a.ToList()); //List<Process> lPlanningProcesses = GetPlanningProcesses(); //KillAll(lPlanningProcesses); ThrowIfCancellationRequested(); return bFDDone || bFFDone || bSymPADone; } public static void KillPlanners() { List<Process> lPlanningProcesses = GetPlanningProcesses(); KillAll(lPlanningProcesses); } public Process RunFD(MemoryStream msDomain, MemoryStream msProblem) { File.Delete(fdPath + "plan.txt"); File.Delete(fdPath + "sas_plan"); //for now, saving files in the working directory msProblem.Position = 0; msDomain.Position = 0; StreamWriter swDomainFile = new StreamWriter(fdPath + "dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(fdPath + "pFD.pddl"); StreamReader srProblem = new StreamReader(msProblem); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); Process pFD = new Process(); pFD.StartInfo.FileName = cygwinPath+@"bin\bash.exe"; pFD.StartInfo.Arguments = "-l "+ fdPath+"plan "; pFD.StartInfo.Arguments += fdPath+"dFD.pddl "+ fdPath + "pFD.pddl"; pFD.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; pFD.StartInfo.UseShellExecute = false; pFD.StartInfo.RedirectStandardOutput = true; pFD.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); FDProcesses = new HashSet<Process>(); pFD.Start(); pFD.BeginOutputReadLine(); return pFD; } public Process RunFD(string sFDPath, MemoryStream msDomain, MemoryStream msProblem) { File.Delete(sFDPath + "plan.txt"); File.Delete(sFDPath + "sas_plan"); //for now, saving files in the working directory msProblem.Position = 0; msDomain.Position = 0; StreamWriter swDomainFile = new StreamWriter(sFDPath + "dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(sFDPath + "pFD.pddl"); StreamReader srProblem = new StreamReader(msProblem); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); Process pFD = new Process(); // pFD.StartInfo.WorkingDirectory = @"C:\cygwin\bin\"; pFD.StartInfo.FileName = @"C:\cygwin\bin\bash.exe"; //pFD.StartInfo.Arguments = " -i /Cygwin-Terminal.ico -";// /Cygwin-Terminal.ico -"; pFD.StartInfo.Arguments = "-l c:/cygwin/home/shlomi/FastDownward/src/plan "; //pFD.StartInfo.Arguments += "'--exec 'c:/cygwin/home/shlomi/FastDownward/src/plan' 'C:/cygwin/home/shlomi/FastDownward/src/dFD.pddl' 'C:/cygwin/home/shlomi/FastDownward/src/pFD.pddl'"; pFD.StartInfo.Arguments += "C:/cygwin/home/shlomi/FastDownward/src/dFD.pddl C:/cygwin/home/shlomi/FastDownward/src/pFD.pddl"; pFD.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; //p.StartInfo.Arguments += " --heuristic \"hFF=ff(cost_type=1)\" " + // " --search \"lazy_greedy(hff, preferred=hff)\" "; pFD.StartInfo.UseShellExecute = false; // pFD.StartInfo.RedirectStandardInput = true; pFD.StartInfo.RedirectStandardOutput = true; pFD.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); FDProcesses = new HashSet<Process>(); pFD.Start(); // Thread.Sleep(10000); // StreamWriter myStreamWriter = pFD.StandardInput; // myStreamWriter.WriteLine(); // myStreamWriter.WriteLine("cd cygwin");//home/shlomi/FastDownward/src/plan"); // myStreamWriter.Close(); pFD.BeginOutputReadLine(); // string sr = pFD.StandardOutput.ReadLine(); return pFD; } /*public Process RunFDUsingUbuntoSubSystemForWindows(MemoryStream msDomain, MemoryStream msProblem) { System.Diagnostics.Process process = new System.Diagnostics.Process(); System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo(); startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; startInfo.FileName = "cmd.exe"; startInfo.Arguments = "/C copy /b Image1.jpg + Archive.rar Image2.jpg"; todo change the arguments to be the command of running bash command of the ubunto process.StartInfo = startInfo; process.Start(); }*/ private Process RunFDPlannerWithFiles(string domainStr, string problemStr) { File.Delete(fdPath + "plan.txt"); File.Delete(fdPath + "mipsSolution.soln"); File.Delete(fdPath + "output.sas"); File.Delete(fdPath + "output"); File.Delete(fdPath + "sas_plan"); StreamWriter swDomainFile = new StreamWriter(fdPath + "dFD.pddl"); swDomainFile.Write(domainStr); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(fdPath + "pFD.pddl"); swProblemFile.Write(problemStr); swProblemFile.Close(); Process pFD = new Process(); //MFFProcesses[Thread.CurrentThread] = pFD; pFD.StartInfo.WorkingDirectory = fdPath; //this.pythonPath = @"C:\Users\OWNER\AppData\Local\Programs\Python\Python37-32\python.exe"; //this.FDpath = @"D:\cygwin\home\Fast-Downward-af6295c3dc9b\fast-downward.py"; pFD.StartInfo.FileName = fdPython27Path; pFD.StartInfo.Arguments += fdRunningPath; pFD.StartInfo.Arguments += " dFD.pddl pFD.pddl "; //pFD.StartInfo.Arguments += " --search \"lazy_greedy([ff()], preferred =[ff()])\""; //pFD.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + // " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; //pFD.StartInfo.Arguments += " --heuristic \"hdiv_pot=diverse_potentials(num_samples=1000, max_num_heuristics=infinity, max_potential=1e8, lpsolver=CPLEX, transform=no_transform(), cache_estimates=true, random_seed=-1)\"" + // " --search \"astar(hdiv_pot)\""; //pFD.StartInfo.Arguments += " --heuristic \"hzo_pdb=zopdbs(patterns=systematic(1), transform=no_transform(), cache_estimates=true)\"" + // " --search \"lazy_greedy([hzo_pdb])\""; //pFD.StartInfo.Arguments += " --heuristic \"hipdb=ipdb(pdb_max_size=2000000, collection_max_size=20000000, num_samples=1000, min_improvement=10, max_time=infinity, random_seed=-1, max_time_dominance_pruning=infinity, transform=no_transform(), cache_estimates=true)\"" + // " --search \"astar(hipdb)\""; //pFD.StartInfo.Arguments += " --heuristic \"hc=cegar(subtasks=[landmarks(),goals()], max_states=infinity, max_transitions=1M, max_time=infinity, pick=MAX_REFINED, use_general_costs=true, debug=false, transform=no_transform(), cache_estimates=true, random_seed=-1)\"" + // " --search \"astar(hc)\""; //pFD.StartInfo.Arguments += " --search \"lazy_wastar(evals, preferred=[], reopen_closed=true, boost=1000, w=1, randomize_successors=false, preferred_successors_first=false, random_seed=-1, cost_type=NORMAL, bound=infinity, max_time=infinity, verbosity=normal)\""; //pFD.StartInfo.Arguments += " --heuristic \"hipdb=ipdb(pdb_max_size=2000000, collection_max_size=20000000, num_samples=1000, min_improvement=10, max_time=infinity, random_seed=-1, max_time_dominance_pruning=infinity, transform=no_transform(), cache_estimates=true)\"" + // " --search \"lazy_greedy([hipdb])\""; // " --search \"astar(hipdb)\""; //pFD.StartInfo.Arguments += " --search \"lazy_wastar([ipdb()], w=2)\""; //pFD.StartInfo.Arguments += " --search \"astar(ff())\""; //pFD.StartInfo.Arguments += " --overall-memory-limit \"3584M\""; pFD.StartInfo.Arguments += " --search \"lazy_greedy([ff(), lmcut()])\""; pFD.StartInfo.UseShellExecute = false; pFD.StartInfo.RedirectStandardOutput = true; pFD.StartInfo.RedirectStandardInput = true; FDOutput = ""; pFD.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); FDProcesses = new HashSet<Process>(); pFD.Start(); pFD.BeginOutputReadLine(); MemoryStream msModels = new MemoryStream(); msModels.Position = 0; BinaryReader srModels = new BinaryReader(msModels); while (srModels.PeekChar() >= 0) pFD.StandardInput.BaseStream.WriteByte(srModels.ReadByte()); pFD.StandardInput.Close(); return pFD; /* if (!pFD.WaitForExit((int)PlannerTimeout.TotalMilliseconds))//5 minutes max { pFD.Kill(); return null; } pFD.WaitForExit(); List<string> lPlan = null; if (FDOutput.Contains("goal can be simplified to TRUE")) { return new List<string>(); } if (FDOutput.Contains("Solution found")) { lPlan = readFDplan(sPath); } else { lPlan = null; } //MFFProcesses[Thread.CurrentThread] = null; return lPlan; */ } private Process RunSymPAPlannerWithFiles(MemoryStream msDomain, MemoryStream msProblem, string symPAFilename) { File.Delete(SymPATempPDDLFolder + "/plan.txt"); File.Delete(SymPATempPDDLFolder + "/mipsSolution.soln"); File.Delete(SymPATempPDDLFolder + "/output.sas"); File.Delete(SymPATempPDDLFolder + "/output"); File.Delete(SymPATempPDDLFolder + "/sas_plan"); File.Delete(SymPATempPDDLFolder + "/log"); File.Delete(SymPATempPDDLFolder + "/err"); msProblem.Position = 0; msDomain.Position = 0; StreamWriter swDomainFile = new StreamWriter(SymPATempPDDLFolder + "/dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(SymPATempPDDLFolder + "/pFD.pddl"); StreamReader srProblem = new StreamReader(msProblem); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); Process pSymPA = new Process(); pSymPA.StartInfo.WorkingDirectory = SymPATempPDDLFolder; pSymPA.StartInfo.FileName = symPAFilename; pSymPA.StartInfo.Arguments = "dFD.pddl pFD.pddl"; pSymPA.StartInfo.UseShellExecute = false; //pSymPA.StartInfo.RedirectStandardOutput = true; //pSymPA.StartInfo.RedirectStandardInput = true; //FDOutput = ""; //pSymPA.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); //FDProcesses = new HashSet<Process>(); pSymPA.Start(); //pSymPA.BeginOutputReadLine(); /* MemoryStream msModels = new MemoryStream(); msModels.Position = 0; BinaryReader srModels = new BinaryReader(msModels); while (srModels.PeekChar() >= 0) pSymPA.StandardInput.BaseStream.WriteByte(srModels.ReadByte()); pSymPA.StandardInput.Close(); */ return pSymPA; } public Process RunFDPlannerWithFiles(MemoryStream msDomain, MemoryStream msProblem) { File.Delete(fdPath + "plan.txt"); File.Delete(fdPath + "mipsSolution.soln"); File.Delete(fdPath + "output.sas"); File.Delete(fdPath + "output"); File.Delete(fdPath + "sas_plan"); msProblem.Position = 0; msDomain.Position = 0; StreamWriter swDomainFile = new StreamWriter(fdPath + "dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(fdPath + "pFD.pddl"); StreamReader srProblem = new StreamReader(msProblem); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); Process pFD = new Process(); //MFFProcesses[Thread.CurrentThread] = pFD; pFD.StartInfo.WorkingDirectory = fdPath; //this.pythonPath = @"C:\Users\OWNER\AppData\Local\Programs\Python\Python37-32\python.exe"; //this.FDpath = @"D:\cygwin\home\Fast-Downward-af6295c3dc9b\fast-downward.py"; pFD.StartInfo.FileName = fdPython27Path; pFD.StartInfo.Arguments += fdRunningPath; pFD.StartInfo.Arguments += " dFD.pddl pFD.pddl "; //pFD.StartInfo.Arguments += " --search \"lazy_greedy([ff()], preferred =[ff()])\""; //pFD.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + // " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; //pFD.StartInfo.Arguments += " --heuristic \"hdiv_pot=diverse_potentials(num_samples=1000, max_num_heuristics=infinity, max_potential=1e8, lpsolver=CPLEX, transform=no_transform(), cache_estimates=true, random_seed=-1)\"" + // " --search \"astar(hdiv_pot)\""; //pFD.StartInfo.Arguments += " --heuristic \"hzo_pdb=zopdbs(patterns=systematic(1), transform=no_transform(), cache_estimates=true)\"" + // " --search \"lazy_greedy([hzo_pdb])\""; //pFD.StartInfo.Arguments += " --heuristic \"hipdb=ipdb(pdb_max_size=2000000, collection_max_size=20000000, num_samples=1000, min_improvement=10, max_time=infinity, random_seed=-1, max_time_dominance_pruning=infinity, transform=no_transform(), cache_estimates=true)\"" + // " --search \"astar(hipdb)\""; //pFD.StartInfo.Arguments += " --heuristic \"hc=cegar(subtasks=[landmarks(),goals()], max_states=infinity, max_transitions=1M, max_time=infinity, pick=MAX_REFINED, use_general_costs=true, debug=false, transform=no_transform(), cache_estimates=true, random_seed=-1)\"" + // " --search \"astar(hc)\""; //pFD.StartInfo.Arguments += " --search \"lazy_wastar(evals, preferred=[], reopen_closed=true, boost=1000, w=1, randomize_successors=false, preferred_successors_first=false, random_seed=-1, cost_type=NORMAL, bound=infinity, max_time=infinity, verbosity=normal)\""; //pFD.StartInfo.Arguments += " --heuristic \"hipdb=ipdb(pdb_max_size=2000000, collection_max_size=20000000, num_samples=1000, min_improvement=10, max_time=infinity, random_seed=-1, max_time_dominance_pruning=infinity, transform=no_transform(), cache_estimates=true)\"" + // " --search \"lazy_greedy([hipdb])\""; // " --search \"astar(hipdb)\""; //pFD.StartInfo.Arguments += " --search \"lazy_wastar([ipdb()], w=2)\""; //pFD.StartInfo.Arguments += " --search \"astar(ff())\""; //pFD.StartInfo.Arguments += " --overall-memory-limit \"3584M\""; pFD.StartInfo.Arguments += " --search \"lazy_greedy([ff(), lmcut()])\""; pFD.StartInfo.UseShellExecute = false; pFD.StartInfo.RedirectStandardOutput = true; pFD.StartInfo.RedirectStandardInput = true; FDOutput = ""; pFD.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); FDProcesses = new HashSet<Process>(); pFD.Start(); pFD.BeginOutputReadLine(); MemoryStream msModels = new MemoryStream(); msModels.Position = 0; BinaryReader srModels = new BinaryReader(msModels); while (srModels.PeekChar() >= 0) pFD.StandardInput.BaseStream.WriteByte(srModels.ReadByte()); pFD.StandardInput.Close(); return pFD; /* if (!pFD.WaitForExit((int)PlannerTimeout.TotalMilliseconds))//5 minutes max { pFD.Kill(); return null; } pFD.WaitForExit(); List<string> lPlan = null; if (FDOutput.Contains("goal can be simplified to TRUE")) { return new List<string>(); } if (FDOutput.Contains("Solution found")) { lPlan = readFDplan(sPath); } else { lPlan = null; } //MFFProcesses[Thread.CurrentThread] = null; return lPlan; */ } private List<string> readFDplan(string sPath) { List<string> lPlan = new List<string>(); if (File.Exists(sPath + "sas_plan")) { StreamReader sr = new StreamReader(sPath + "sas_plan"); while (!sr.EndOfStream) { string sLine = sr.ReadLine().Trim().ToLower(); sLine = sLine.Replace("(", ""); sLine = sLine.Replace(")", ""); if (sLine.Count() > 0 && !sLine.StartsWith(";")) { int iStart = sLine.IndexOf("("); sLine = sLine.Substring(iStart + 1).Trim(); lPlan.Add(sLine); } //else if (sLine.Count() > 0 && sLine.StartsWith(";")) //{ // lPlan.Add(sLine); //} } sr.Close(); } return lPlan; } public Process RunFD(string name, string sFDPath, MemoryStream msDomain, MemoryStream msProblem) { try { name = name.Replace(" ", ""); name = name.Replace(":", ""); sFDPath = sFDPath + name + @"\"; if (Directory.Exists(sFDPath)) { File.Delete(sFDPath + "plan.txt"); File.Delete(sFDPath + "sas_plan"); } else { Directory.CreateDirectory(sFDPath); } //for now, saving files in the working directory msProblem.Position = 0; msDomain.Position = 0; StreamWriter swDomainFile = new StreamWriter(sFDPath + "dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(sFDPath + "pFD.pddl"); StreamReader srProblem = new StreamReader(msProblem); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); Process pFD = new Process(); // pFD.StartInfo.WorkingDirectory = @"C:\cygwin\bin\"; // pFD.StartInfo.WorkingDirectory = @"C:\teeeemmp"; pFD.StartInfo.FileName = @"C:\cygwin\bin\bash.exe"; //pFD.StartInfo.Arguments = " -i /Cygwin-Terminal.ico -";// /Cygwin-Terminal.ico -"; pFD.StartInfo.Arguments = "-l c:/cygwin/home/shlomi/FastDownward/src/plan "; //pFD.StartInfo.Arguments += "'--exec 'c:/cygwin/home/shlomi/FastDownward/src/plan' 'C:/cygwin/home/shlomi/FastDownward/src/dFD.pddl' 'C:/cygwin/home/shlomi/FastDownward/src/pFD.pddl'"; pFD.StartInfo.Arguments += "C:/cygwin/home/shlomi/FastDownward/src/" + name + "/" + "dFD.pddl C:/cygwin/home/shlomi/FastDownward/src/" + name + "/" + "pFD.pddl"; pFD.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; //p.StartInfo.Arguments += " --heuristic \"hFF=ff(cost_type=1)\" " + // " --search \"lazy_greedy(hff, preferred=hff)\" "; pFD.StartInfo.UseShellExecute = false; // pFD.StartInfo.RedirectStandardInput = true; pFD.StartInfo.RedirectStandardOutput = true; pFD.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); FDProcesses = new HashSet<Process>(); pFD.Start(); // Thread.Sleep(10000); // StreamWriter myStreamWriter = pFD.StandardInput; // myStreamWriter.WriteLine(); // myStreamWriter.WriteLine("cd cygwin");//home/shlomi/FastDownward/src/plan"); // myStreamWriter.Close(); pFD.BeginOutputReadLine(); // string sr = pFD.StandardOutput.ReadLine(); return pFD; } catch (Exception ex) { Console.WriteLine(ex.ToString()); } return null; } public static Mutex m = new Mutex(); private Process RunFF(string domainStr, string problemStr) { //m.WaitOne(); Process pFF; lock (m) { pFF = new Process(); pFF.StartInfo.FileName = ffPath; pFF.StartInfo.UseShellExecute = false; pFF.StartInfo.RedirectStandardInput = true; pFF.StartInfo.RedirectStandardOutput = true; pFF.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); pFF.Start(); FFOutput[pFF.Id] = ""; pFF.BeginOutputReadLine(); } //m.ReleaseMutex(); string domain = domainStr; pFF.StandardInput.Write(domain); BinaryWriter b = new BinaryWriter(pFF.StandardInput.BaseStream); b.Write('\0'); string problem = problemStr; pFF.StandardInput.Write(problem); b.Write('\0'); pFF.StandardInput.Close(); return pFF; } public Process RunFF(MemoryStream msDomain, MemoryStream msProblem) { msProblem.Position = 0; msDomain.Position = 0; Process pFF; //m.WaitOne(); lock (m) { pFF = new Process(); pFF.StartInfo.FileName = ffPath; pFF.StartInfo.UseShellExecute = false; pFF.StartInfo.RedirectStandardInput = true; pFF.StartInfo.RedirectStandardOutput = true; pFF.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); pFF.Start(); FFOutput[pFF.Id] = ""; pFF.BeginOutputReadLine(); } //m.ReleaseMutex(); StreamReader srOps = new StreamReader(msDomain); string domain = srOps.ReadToEnd(); //Console.WriteLine("pFF output:"); //Console.WriteLine(FFOutput[pFF.Id]); pFF.StandardInput.Write(domain); srOps.Close(); BinaryWriter b = new BinaryWriter(pFF.StandardInput.BaseStream); b.Write('\0'); StreamReader srFct = new StreamReader(msProblem); string problem = srFct.ReadToEnd(); pFF.StandardInput.Write(problem); srFct.Close(); b.Write('\0'); //planer.StandardInput.Flush(); pFF.StandardInput.Close(); return pFF; } public Process RunFFWithFiles(MemoryStream msDomain, MemoryStream msProblem, out string domainName, out string problemName, out string outputPath, bool useSecondFFPath) { msProblem.Position = 0; msDomain.Position = 0; Process pFF; StreamReader srOps = new StreamReader(msDomain); long timestamp; lock (m) { timestamp = DateTime.Now.Ticks; } string domain = srOps.ReadToEnd(); domainName = "domain_" + Program.currentFFProcessName + "_" + timestamp + ".pddl"; StreamWriter domainWriter = new StreamWriter(domainName); domainWriter.Write(domain); srOps.Close(); domainWriter.Close(); problemName = "problem_" + Program.currentFFProcessName + "_" + timestamp + ".pddl"; StreamReader srFct = new StreamReader(msProblem); string problem = srFct.ReadToEnd(); StreamWriter problemWriter = new StreamWriter(problemName); problemWriter.Write(problem); srFct.Close(); problemWriter.Close(); outputPath = "output_" + Program.currentFFProcessName + "_" + timestamp + ".out"; string ffPathToUse = ffPath; if (useSecondFFPath) ffPathToUse = ffPath2; //m.WaitOne(); lock (m) { pFF = new Process(); //pFF.StartInfo.FileName = ffPath; //pFF.StartInfo.Arguments = "-o " + domainName + " -f " + problemName; pFF.StartInfo.FileName = "run_ff_script.sh"; pFF.StartInfo.Arguments = domainName + " " + problemName + " " + outputPath + " " + ffPathToUse; pFF.StartInfo.UseShellExecute = false; //pFF.StartInfo.RedirectStandardInput = true; //pFF.StartInfo.RedirectStandardOutput = true; //pFF.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); pFF.Start(); FFOutput[pFF.Id] = ""; //pFF.BeginOutputReadLine(); } //m.ReleaseMutex(); //planer.StandardInput.Flush(); //pFF.StandardInput.Close(); return pFF; } public List<string> FFPlan(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { try { //Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; MemoryStream msDomain = d.WriteSimpleDomain(); MemoryStream problem_M_S = p.WriteSimpleProblem(curentState); /* StreamWriter swDomainFile = new StreamWriter(@"D:\tmp\testd.pddl",false); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter(@"D:\tmp\testp.pddl", false); StreamReader srProblem = new StreamReader(problem_M_S); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); */ problem_M_S.Position = 0; msDomain.Position = 0; Process planer = new Process(); //planer.StartInfo.WorkingDirectory = @"C:\project\Planning 2 new\PDDLTEST\temp"; planer.StartInfo.FileName = ffPath; //planer.StartInfo.Arguments += " - o dT.pddl -f pT.pddl"; planer.StartInfo.UseShellExecute = false; planer.StartInfo.RedirectStandardInput = true; planer.StartInfo.RedirectStandardOutput = true; planer.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); planer.Start(); if (!FFOutput.ContainsKey(planer.Id)) FFOutput.Add(planer.Id, ""); FFOutput[planer.Id] = ""; planer.BeginOutputReadLine(); StreamReader srOps = new StreamReader(msDomain); string domain = srOps.ReadToEnd(); planer.StandardInput.Write(domain); srOps.Close(); BinaryWriter b = new BinaryWriter(planer.StandardInput.BaseStream); b.Write('\0'); StreamReader srFct = new StreamReader(problem_M_S); string problem = srFct.ReadToEnd(); planer.StandardInput.Write(problem); srFct.Close(); b.Write('\0'); //planer.StandardInput.Flush(); planer.StandardInput.Close(); if (cMaxMilliseconds != -1) { if (!planer.WaitForExit(cMaxMilliseconds))//2 minutes max { planer.Kill(); bUnsolvable = false; return null; } } planer.WaitForExit(); //string sOutput = planer.StandardOutput.ReadToEnd(); //Thread.Sleep(1000); string sOutput = FFOutput[planer.Id]; planer.Close(); //throw new NotImplementedException(); //Console.WriteLine(sOutput); MemoryStream planMs = new MemoryStream(); if (sOutput.Contains("found legal plan as follows")) { string sPlan = sOutput.Substring(sOutput.IndexOf("found legal plan as follows")); sPlan = sPlan.Replace("found legal plan as follows", "").Trim(); string[] asPlan = sPlan.Split('\n'); string sFinalPlan = ""; for (int i = 0; i < asPlan.Length; i++) { if (!asPlan[i].Contains(":")) break; if (asPlan[i].Contains("time spent:")) break; sFinalPlan += asPlan[i].Substring(asPlan[i].IndexOf(':') + 2).Trim() + "\n"; } StreamWriter sw = new StreamWriter(planMs); sw.WriteLine(sFinalPlan); sw.Close(); bUnsolvable = false; } else { if (sOutput.Contains("goal can be simplified to TRUE")) { ffLplan = new List<string>(); bUnsolvable = false; return ffLplan; } else if (sOutput.Contains("goal can be simplified to FALSE")) { ffLplan = null; bUnsolvable = true; return null; } else { ffLplan = null; bUnsolvable = false; return null; } } lPlan = ReadPlan(new MemoryStream(planMs.ToArray())); ffLplan = lPlan; return lPlan; } catch(Exception ex) { bUnsolvable = true; return null; } } public List<string> PdbFFPlan(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; MemoryStream msDomain = d.WriteSimpleDomain(); MemoryStream problem_M_S = p.WriteSimpleProblem(curentState); //StreamWriter swDomainFile = new StreamWriter(@"C:\Dropbox-users\shlomi\Dropbox\Dropbox\privacyPreserving\Competition\all\factored\testd.pddl"); // StreamReader srDomain = new StreamReader(msDomain); // swDomainFile.Write(srDomain.ReadToEnd()); // swDomainFile.Close(); // StreamWriter swProblemFile = new StreamWriter(@"C:\Dropbox-users\shlomi\Dropbox\Dropbox\privacyPreserving\Competition\all\factored\testp.pddl"); // StreamReader srProblem = new StreamReader(problem_M_S); // swProblemFile.Write(srProblem.ReadToEnd()); // swProblemFile.Close(); problem_M_S.Position = 0; msDomain.Position = 0; Process planer = new Process(); //planer.StartInfo.WorkingDirectory = @"C:\project\Planning 2 new\PDDLTEST\temp"; planer.StartInfo.FileName = ffPath; //planer.StartInfo.Arguments += "-o dT.pddl -f pT.pddl"; FFOutput[planer.Id] = ""; planer.StartInfo.UseShellExecute = false; planer.StartInfo.RedirectStandardInput = true; planer.StartInfo.RedirectStandardOutput = true; planer.OutputDataReceived += new DataReceivedEventHandler(FFOutputHandler); planer.Start(); planer.BeginOutputReadLine(); StreamReader srOps = new StreamReader(msDomain); string domain = srOps.ReadToEnd(); planer.StandardInput.Write(domain); srOps.Close(); BinaryWriter b = new BinaryWriter(planer.StandardInput.BaseStream); b.Write('\0'); StreamReader srFct = new StreamReader(problem_M_S); string problem = srFct.ReadToEnd(); planer.StandardInput.Write(problem); srFct.Close(); b.Write('\0'); //planer.StandardInput.Flush(); planer.StandardInput.Close(); if (cMaxMilliseconds != -1) { if (!planer.WaitForExit(cMaxMilliseconds))//2 minutes max { planer.Kill(); bUnsolvable = false; return null; } } else planer.WaitForExit(); planer.Close(); //string sOutput = planer.StandardOutput.ReadToEnd(); // planer.WaitForExit(); string sOutput = FFOutput[planer.Id]; //throw new NotImplementedException(); //Console.WriteLine(sOutput); MemoryStream planMs = new MemoryStream(); if (sOutput.Contains("found legal plan as follows")) { string sPlan = sOutput.Substring(sOutput.IndexOf("found legal plan as follows")); sPlan = sPlan.Replace("found legal plan as follows", "").Trim(); string[] asPlan = sPlan.Split('\n'); string sFinalPlan = ""; for (int i = 0; i < asPlan.Length; i++) { if (!asPlan[i].Contains(":")) break; if (asPlan[i].Contains("time spent:")) break; sFinalPlan += asPlan[i].Substring(asPlan[i].IndexOf(':') + 2).Trim() + "\n"; } StreamWriter sw = new StreamWriter(planMs); sw.WriteLine(sFinalPlan); sw.Close(); bUnsolvable = false; } else { if (sOutput.Contains("goal can be simplified to TRUE")) { ffLplan = new List<string>(); bUnsolvable = false; return ffLplan; } else if (sOutput.Contains("goal can be simplified to FALSE")) { ffLplan = null; bUnsolvable = true; return null; } else { ffLplan = null; bUnsolvable = false; return null; } } lPlan = ReadPlan(new MemoryStream(planMs.ToArray())); ffLplan = lPlan; return lPlan; } Dictionary<int, string> FFOutput = new Dictionary<int, string>(); private void FFOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { //Console.WriteLine(outLine.Data); Process p = (Process)sendingProcess; if (!String.IsNullOrEmpty(outLine.Data)) { FFOutput[p.Id] += outLine.Data + Environment.NewLine; } } private HashSet<Process> FDProcesses = null; string FDOutput = ""; private void FDOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { FDProcesses.Add((Process)sendingProcess); Process p = (Process)sendingProcess; if (!String.IsNullOrEmpty(outLine.Data)) { FDOutput += outLine.Data + Environment.NewLine; } } public static List<Process> GetPlanningProcesses() { List<Process> l = new List<Process>(); Process[] processes = Process.GetProcesses(); foreach (Process p in processes) { if ((p.ProcessName.ToLower().Contains("downward") || p.ProcessName.ToLower().Contains(Program.currentFFProcessName)) && (!p.ProcessName.ToLower().Contains("office"))) l.Add(p); } return l; } public bool RunProcessII(Process p, int cMaxMilliseconds) { p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); DateTime dtStart = DateTime.Now; p.Start(); p.BeginOutputReadLine(); if (!p.WaitForExit(cMaxMilliseconds)) p.Kill(); p.Close(); return true; } public bool RunProcess(Process p, int cMaxMilliseconds) { p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += new DataReceivedEventHandler(FDOutputHandler); DateTime dtStart = DateTime.Now; bool bDone = false; FDProcesses = new HashSet<Process>(); p.Start(); p.BeginOutputReadLine(); while (!bDone) { if (!p.HasExited) bDone = p.WaitForExit(10000); else bDone = true; if (!bDone) { try { TimeSpan ts = (DateTime.Now - dtStart); List<Process> l = GetPlanningProcesses(); if (ts.TotalMilliseconds > cMaxMilliseconds) { l.Add(p); KillAll(l); return false; } bool bMemSizeLimitReached = false; foreach (Process pPlanning in GetPlanningProcesses()) { if (pPlanning.WorkingSet64 > 2 * Math.Pow(2, 30)) { bMemSizeLimitReached = true; } } if (bMemSizeLimitReached) { l.Add(p); KillAll(l); return false; } } catch (Exception e) { Console.WriteLine("fd-fails"); } } } p.Close(); return true; } public static void KillAll(List<Process> l) { foreach (Process p in l) { try { if (!p.HasExited) { p.Kill(); // p.WaitForExit(); Thread.Sleep(300); //p.WaitForExit(); p.Close(); } } catch (Exception e) { //Console.WriteLine("*"); } } } public bool RunFD(string sPath, int cMaxMilliseconds) { Process p = new Process(); p.StartInfo.WorkingDirectory = sPath; //p.StartInfo.FileName = Program.BASE_PATH + @"\PDDL\Planners\ff.exe"; p.StartInfo.FileName = @"C:\cygwin\bin\bash.exe"; p.StartInfo.Arguments = @"C:\cygwin\home\shlomi\FastDownward\src\plan"; // p.StartInfo.Arguments = @"C:\cygwin\home\shlomi\FastDownward\src\plan"; p.StartInfo.Arguments += @" dFD.pddl pFD.pddl"; p.StartInfo.Arguments += " --heuristic \"hlm,hff=lm_ff_syn(lm_rhw(reasonable_orders=true,lm_cost_type=ONE,cost_type=ONE))\" " + " --search \"lazy_greedy([hff,hlm],preferred=[hff,hlm],cost_type=ONE)\""; //p.StartInfo.Arguments += " --heuristic \"hFF=ff(cost_type=1)\" " + // " --search \"lazy_greedy(hff, preferred=hff)\" "; if (!RunProcess(p, cMaxMilliseconds)) return false; return true; } public List<string> FDPlan(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); File.Delete("plan.txt"); File.Delete("sas_plan"); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; MemoryStream msDomain = d.WriteSimpleDomain(); MemoryStream problem_M_S = p.WriteSimpleProblem(curentState); //for now, saving files in the working directory StreamWriter swDomainFile = new StreamWriter("dFD.pddl"); StreamReader srDomain = new StreamReader(msDomain); swDomainFile.Write(srDomain.ReadToEnd()); swDomainFile.Close(); StreamWriter swProblemFile = new StreamWriter("pFD.pddl"); StreamReader srProblem = new StreamReader(problem_M_S); swProblemFile.Write(srProblem.ReadToEnd()); swProblemFile.Close(); problem_M_S.Position = 0; msDomain.Position = 0; bUnsolvable = false; if (RunFD("./", cMaxMilliseconds)) return ReadPlan("./"); return null; } private List<string> ReadPlan(string sPath) { List<string> lPlan = new List<string>(); string sPlanFile = "plan.txt"; if (File.Exists(sPath + sPlanFile)) { StreamReader sr = new StreamReader(sPath + sPlanFile); while (!sr.EndOfStream) { string sAction = sr.ReadLine().Trim().ToLower(); if (sAction != "") lPlan.Add(sAction); } sr.Close(); } else if (File.Exists(sPath + "mipsSolution.soln")) { StreamReader sr = new StreamReader(sPath + "mipsSolution.soln"); while (!sr.EndOfStream) { string sLine = sr.ReadLine().Trim().ToLower(); if (sLine.Count() > 0 && !sLine.StartsWith(";")) { int iStart = sLine.IndexOf("("); int iEnd = sLine.IndexOf(")"); sLine = sLine.Substring(iStart + 1, iEnd - iStart - 1).Trim(); lPlan.Add(sLine); } } sr.Close(); } else if (File.Exists(sPath + "sas_plan")) { StreamReader sr = new StreamReader(sPath + "sas_plan"); while (!sr.EndOfStream) { string sLine = sr.ReadLine().Trim().ToLower(); sLine = sLine.Replace("(", ""); sLine = sLine.Replace(")", ""); if (sLine.Count() > 0 && !sLine.StartsWith(";")) { int iStart = sLine.IndexOf("("); sLine = sLine.Substring(iStart + 1).Trim(); lPlan.Add(sLine); } } sr.Close(); } else { return null; } List<string> lFilteredPlan = new List<string>(); foreach (string sAction in lPlan) { if (sAction.Contains("-remove") || sAction.Contains("-translate")) continue; if (sAction.Contains("-add")) lFilteredPlan.Add(sAction.Replace("-add", "")); else lFilteredPlan.Add(sAction); } return lFilteredPlan; } public List<string> ReadPlan(MemoryStream ms) { List<string> lPlan = new List<string>(); StreamReader sr = new StreamReader(ms); while (!sr.EndOfStream) { string sAction = sr.ReadLine().Trim().ToLower(); if (sAction != "") lPlan.Add(sAction); } sr.Close(); return lPlan; List<string> lFilteredPlan = new List<string>(); foreach (string sAction in lPlan) { if (sAction.Contains("-remove") || sAction.Contains("-translate")) continue; if (sAction.Contains("-add")) lFilteredPlan.Add(sAction.Replace("-add", "")); else lFilteredPlan.Add(sAction); } return lFilteredPlan; } public List<string> ManualSolve(Domain d, Problem p, State curentState, Formula goal, List<Action> privateActions, int cMaxMilliseconds, out bool bUnsolvable) { Program.KillPlanners(); List<string> ffLplan = new List<string>(); List<string> lPlan = new List<string>(); if (privateActions != null) d.Actions = privateActions; if (goal != null) p.Goal = goal; bUnsolvable = false; return ManualSolve(p, d); } public List<string> ManualSolve(Problem p, Domain d) { List<string> lPlan = new List<string>(); State sStart = new State(p); foreach (GroundedPredicate gp in p.Known) sStart.AddPredicate(gp); State sCurrent = null, sNext = null; Dictionary<State, Action> dMapStateToGeneratingAction = new Dictionary<State, Action>(); dMapStateToGeneratingAction[sStart] = null; Dictionary<State, State> dParents = new Dictionary<State, State>(); dParents[sStart] = null; int cProcessed = 0; List<string> lActionNames = new List<string>(); sCurrent = sStart; while (!p.IsGoalState(sCurrent)) { List<Action> lActions = new List<Action>(d.GroundAllActions(sCurrent.Predicates, true)); Console.WriteLine("Available actions:"); for (int i = 0; i < lActions.Count; i++) { Console.WriteLine(i + ") " + lActions[i].Name); } Console.Write("Choose action number: "); int iAction = int.Parse(Console.ReadLine()); Action a = lActions[iAction]; sNext = sCurrent.Apply(a); lPlan.Add(a.Name); foreach (Predicate pNew in sNext.Predicates) if (!sCurrent.Predicates.Contains(pNew)) Console.WriteLine(pNew); if (!dParents.Keys.Contains(sNext)) { dParents[sNext] = sCurrent; dMapStateToGeneratingAction[sNext] = a; } sCurrent = sNext; cProcessed++; } return lPlan; //return GeneratePlan(sCurrent, null, dParents, dMapStateToGeneratingAction); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Media; using NAudio.Wave; namespace MuzsikaTS_Rendező { public partial class Player2 : Form { List<MusicFile> _musicFiles; MusicFile _currentMusic; private MusicPlayer FirstPlayer { get { return (MusicPlayer)ltbPlayers.Items[0]; } } private MusicPlayer SelectedPlayer { get { return (MusicPlayer)ltbPlayers.SelectedItem; } } private MusicFile SelectedFile { get { return (MusicFile)ltbSongs.SelectedItem; } } private List<MusicPlayer> _musicPlayers { get { return ltbPlayers.Items.OfType<MusicPlayer>().ToList(); } set { ltbPlayers.Items.Add(value); } } public Player2(List<MusicFile> musicFiles) { InitializeComponent(); int waveOutDevices = WaveOut.DeviceCount; for (int waveOutDevice = 0; waveOutDevice < waveOutDevices; waveOutDevice++) { WaveOutCapabilities deviceInfo = WaveOut.GetCapabilities(waveOutDevice); cbAudio.Items.Add(deviceInfo.ProductName); } _musicFiles = musicFiles; if (_musicFiles.Count == 0) this.Dispose(); ltbPlayers.Items.Add(new MusicPlayer()); if (cbAudio.Items.Contains("Muzsika TS (Virtual Audio Cable")) ((MusicPlayer)ltbPlayers.Items[0]).DeviceId = cbAudio.Items.IndexOf("Muzsika TS (Virtual Audio Cable"); ltbPlayers.SelectedIndex = 0; ltbSongs.DataSource = _musicFiles; tmRefreshing.Start(); } private void PlaySelected() { if (_musicFiles == null) return; if (ltbSongs.Items.IndexOf(_currentMusic) < ltbSongs.Items.Count - 2) ltbSongs.SelectedIndex = ltbSongs.Items.IndexOf(_currentMusic) + 2; ltbSongs.SelectedIndex = ltbSongs.Items.IndexOf(_currentMusic); _musicPlayers.ForEach(p => p.Play(_currentMusic.File.Name)); } private void NextSong() { if (_currentMusic == null) return; int index = ltbSongs.Items.IndexOf(_currentMusic); if (index != ltbSongs.Items.Count - 1) _currentMusic = (MusicFile)ltbSongs.Items[index + 1]; else _currentMusic = (MusicFile)ltbSongs.Items[0]; PlaySelected(); } private void Player_Load(object sender, EventArgs e) { } private void trbVol_Scroll(object sender, EventArgs e) { if (ltbPlayers.SelectedIndices.Count == 0) return; SelectedPlayer.Volume = trbVol.Value / 100f; } private void trbCuttentTime_Scroll(object sender, EventArgs e) { _musicPlayers.ForEach(p => p.CurrentTime = new TimeSpan(0, 0, trbCuttentTime.Value)); } private void btnPlay_Click(object sender, EventArgs e) { if (ltbSongs.SelectedIndices.Count == 0) return; _currentMusic = (MusicFile)ltbSongs.SelectedItem; PlaySelected(); } private void btnStop_Click(object sender, EventArgs e) { _musicPlayers.ForEach(p => p.Stop()); } private void Player_FormClosed(object sender, FormClosedEventArgs e) { _musicPlayers.ForEach(p => p.Dispose()); } private void tmRefreshing_Tick(object sender, EventArgs e) { if (!trbCuttentTime.Enabled) trbCuttentTime.Enabled = true; if (trbCuttentTime.Maximum != (int)FirstPlayer.TotalTime.TotalSeconds) trbCuttentTime.Maximum = (int)FirstPlayer.TotalTime.TotalSeconds; trbCuttentTime.Value = (int)FirstPlayer.CurrentTime.TotalSeconds; tbTime.Text = FirstPlayer.CurrentTime.Hours.ToString().PadLeft(2, '0') + ":" + FirstPlayer.CurrentTime.Minutes.ToString().PadLeft(2, '0') + ":" + FirstPlayer.CurrentTime.Seconds.ToString().PadLeft(2, '0'); if (FirstPlayer.CurrentTime >= FirstPlayer.TotalTime - new TimeSpan(0, 0, 0, 0, 250)) NextSong(); } private void btnNext_Click(object sender, EventArgs e) { NextSong(); } private void btnPrev_Click(object sender, EventArgs e) { if (_currentMusic == null) return; int index = ltbSongs.Items.IndexOf(_currentMusic); if (index != 0) _currentMusic = (MusicFile)ltbSongs.Items[index - 1]; PlaySelected(); } private void cbAudio_SelectedIndexChanged(object sender, EventArgs e) { if (ltbPlayers.SelectedIndices.Count == 0) return; SelectedPlayer.DeviceId = cbAudio.SelectedIndex; trbVol.Value = (int)SelectedPlayer.Volume * 100; } private void btnAddPlayer_Click(object sender, EventArgs e) { MusicPlayer p = new MusicPlayer(); if (_currentMusic != null) { p.Play(_currentMusic.File.Name); p.CurrentTime = FirstPlayer.CurrentTime; if (!FirstPlayer.Playing) p.Stop(); } ltbPlayers.Items.Add(p); ltbPlayers.SelectedItem = p; } private void btnDeletePlayer_Click(object sender, EventArgs e) { if (ltbPlayers.SelectedIndices.Count == 0 || ltbPlayers.Items.Count <= 1) return; SelectedPlayer.Dispose(); ltbPlayers.Items.Remove(SelectedPlayer); } private void btnMutePlayer_Click(object sender, EventArgs e) { if (ltbPlayers.SelectedIndices.Count == 0) return; SelectedPlayer.Volume = 0; trbVol.Value = 0; } private void ltbPlayers_SelectedIndexChanged(object sender, EventArgs e) { if (ltbPlayers.SelectedItems.Count == 0) { trbVol.Enabled = false; cbAudio.Enabled = false; } else { trbVol.Enabled = true; cbAudio.Enabled = true; trbVol.Value = (int)(SelectedPlayer.Volume * 100); cbAudio.SelectedIndex = SelectedPlayer.DeviceId; } } private void tbSearch_KeyPress(object sender, KeyPressEventArgs e) { if ((int)e.KeyChar != 13) return; if (tbSearch.Text == "" && _currentMusic != null) { if (ltbSongs.Items.IndexOf(_currentMusic) < ltbSongs.Items.Count - 2) ltbSongs.SelectedIndex = ltbSongs.Items.IndexOf(_currentMusic) + 2; ltbSongs.SelectedIndex = ltbSongs.Items.IndexOf(_currentMusic); } else { int startIndex; bool found = false; if (ltbSongs.SelectedIndices.Count == 0 || !SelectedFile.Searcher(tbSearch.Text)) startIndex = 0; else startIndex = ltbSongs.SelectedIndex+1; for (int i = startIndex; i < ltbSongs.Items.Count; i++) { if(((MusicFile)ltbSongs.Items[i]).Searcher(tbSearch.Text)) { ltbSongs.SelectedIndex = i; found = true; break; } } if(startIndex != 0 && !found) { for (int i = 0; i <= startIndex; i++) { if (((MusicFile)ltbSongs.Items[i]).Searcher(tbSearch.Text)) { ltbSongs.SelectedIndex = i; found = true; break; } } } if (!found) ltbSongs.SelectedItem = null; } } } class MusicPlayer { static int ID = 1; WaveOut _waveOut; Mp3FileReader _reader; bool _playing = false; int _id; public bool Playing { get { return _playing && CurrentTime < TotalTime - new TimeSpan(0, 0, 0, 0, 250); } } public override string ToString() { return _id.ToString() + ". Player"; } public int DeviceId { get { return _waveOut.DeviceNumber; } set { if (value == DeviceId) return; if (value >= WaveOut.DeviceCount) return; _waveOut.Dispose(); _waveOut = new WaveOut(); _waveOut.DeviceNumber = value; if (_reader != null) { _waveOut.Init(_reader); _waveOut.Play(); } } } public MusicPlayer(int deviceId = 0) { _id = ID++; _waveOut = new WaveOut(); if (deviceId < WaveOut.DeviceCount) _waveOut.DeviceNumber = deviceId; } public float Volume { get { return _waveOut.Volume; } set { _waveOut.Volume = value <= 1 ? value : 1f; } } public void Play() { if(_reader != null)_waveOut.Play(); _playing = true; } public void Play(string path) { _waveOut.Stop(); if (_reader != null) _reader.Dispose(); _reader = new Mp3FileReader(path); _waveOut.Init(_reader); _waveOut.Play(); _playing = true; } public void Stop() { _waveOut.Stop(); _playing = false; } public TimeSpan CurrentTime { get { return _reader != null?_reader.CurrentTime : new TimeSpan(0); } set { if (_reader != null)_reader.CurrentTime = value <= _reader.TotalTime ? value : _reader.TotalTime; Play(); } } public void Dispose() { _waveOut.Dispose(); if(_reader != null)_reader.Dispose(); } public TimeSpan TotalTime { get { return _reader != null?_reader.TotalTime:new TimeSpan(0); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Exercise1 { /* 1. Write a method that asks the user for his * name and prints “Hello, <name>” (for example, “Hello, Peter!”). * Write a program to test this method. */ class Program { static void Main(string[] args) { Congratulation(); Console.WriteLine("Nice to meet you!"); } static void Congratulation() { string name; Console.WriteLine("What is your name ?"); name = Console.ReadLine(); Console.WriteLine("Hello, {0}!", name); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Configuration; using InfirmerieDAL; using InfirmerieBO; namespace InfirmerieBLL { public class GestionInfirmerie { private static GestionInfirmerie uneGestionInfirmerie; // Objet BLL // Accesseur en lecture public static GestionInfirmerie GetGestionInfirmerie() { if (uneGestionInfirmerie == null) { uneGestionInfirmerie = new GestionInfirmerie(); } return uneGestionInfirmerie; } // Définit la chaine de connexion grâce à la méthode SetChaineConnexion de la DAL public static void SetChaineConnexion(ConnectionStringSettings chset) { string chaine = chset.ConnectionString; ConnexionBD.GetConnexionBD().SetchaineConnexion(chaine); } // Méthode qui créer un nouvel élève à partir de ses attributs et qui le renvoi en l'ajoutant à la BD avec la méthode AjoutEleve de la DAL public static int CreerEleve(????) { Eleve el; el = new Eleve(????); return InfirmerieDAO.AjoutEleve(el); } public static int ModifierEleve(int id, string nom, string prenom, DateTime naissance, string sante, string telEleve, string telParent, bool archive, bool tierstemps, bool visite) { Eleve el; el = new Eleve(id, nom, prenom, naissance, sante, telEleve, telParent, archive, tierstemps, visite); return InfirmerieDAO.UpdateEleve(el); } } }
using Library.DataAccess.Interface; using Library.DomainModels; using Library.Services.Interface; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Library.Services { public class AuthorService : IAuthorService { private readonly IAuthorRepository _authorRepository; public AuthorService(IAuthorRepository authorRepository) { _authorRepository = authorRepository; } //Create a new author public async Task<Author> Create(string name) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Author name is mandatory"); Author newAuthor = new Author() { Name = name }; return await _authorRepository.Create(newAuthor); } //Delete author using Id in repository public async Task DeleteAuthorById(int id) { var author=await GetById(id); await _authorRepository.DeleteAuthorById(id); } //Get list of all authors from repository layer and return it to controller public async Task<IEnumerable<Author>> GetAll() { return await _authorRepository.GetAll(); } //Same as GetAll but just a single author and needs author ID public async Task<Author> GetById(int id) { return await _authorRepository.GetById(id); } //Same as GetById but needs author name instead of ID public async Task<Author> GetByName(string name) { return await _authorRepository.GetByName(name); } //UpdateAuthor object public async Task<Author> UpdateAuthor(Author author) { //ValidationforName //String class has helper methods to operate on string values if (string.IsNullOrWhiteSpace(author.Name)) { var exception = new Exception("Author name is mandatory"); throw exception; } return await _authorRepository.UpdateAuthor(author); } //Update the isAlive property public async Task<Author> UpdateIsAlive(int id, bool isAlive) { var author = await _authorRepository.GetById(id); author.IsAlive = isAlive; return await _authorRepository.UpdateAuthor(author); } } }
using System; using System.Collections.Generic; using Logs.Models; using Logs.Web.Models.Logs; using NUnit.Framework; using PagedList; namespace Logs.Web.Tests.ViewModelsTests.Logs.LogDetailsViewModelTests { [TestFixture] public class ConstructorTests { [TestCase("description")] [TestCase("me be very interesting")] public void TestConstructor_ShouldSetDescriptionCorrectly(string description) { // Arrange var trainingLog = new TrainingLog { Description = description }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, null); // Assert Assert.AreEqual(description, model.Description); } [TestCase("my name")] [TestCase("logs")] [TestCase("test")] public void TestConstructor_ShouldSetNameCorrectly(string name) { // Arrange var trainingLog = new TrainingLog { Name = name }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, null); // Assert Assert.AreEqual(name, model.Name); } [Test] public void TestConstructor_ShouldSetDateCreatedCorrectly() { // Arrange var date = new DateTime(); var trainingLog = new TrainingLog { DateCreated = date }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, null); // Assert Assert.AreEqual(date, model.DateCreated); } [TestCase("pesho")] [TestCase("john skeet")] [TestCase("stamat")] public void TestConstructor_ShouldSetUserCorrectly(string owner) { // Arrange var trainingLog = new TrainingLog { Owner = owner }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, null); // Assert Assert.AreEqual(owner, model.User); } [Test] public void TestConstructor_ShouldSetVotesCountCorrectly() { // Arrange var votes = new List<Vote> { new Vote(), new Vote() }; var trainingLog = new TrainingLog { Votes = votes }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, false, null); // Assert Assert.AreEqual(votes.Count, model.VotesCount); } [TestCase(1)] [TestCase(423)] [TestCase(519)] public void TestConstructor_ShouldSetLogIdCorrectly(int logId) { // Arrange var trainingLog = new TrainingLog { LogId = logId }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, false, null); // Assert Assert.AreEqual(logId, model.LogId); } [TestCase(false)] [TestCase(true)] public void TestConstructor_ShouldSetIsAuthenticatedCorrectly(bool isAuthenticated) { // Arrange var trainingLog = new TrainingLog(); // Act // Act var model = new LogDetailsViewModel(trainingLog, isAuthenticated, true, false, null); // Assert Assert.AreEqual(isAuthenticated, model.IsAuthenticated); } [TestCase(true)] [TestCase(false)] public void TestConstructor_ShouldSetCanEditCorrectly(bool canEdit) { // Arrange var trainingLog = new TrainingLog(); // Act // Act var model = new LogDetailsViewModel(trainingLog, true, canEdit, false, null); // Assert Assert.AreEqual(canEdit, model.CanEdit); } [TestCase(true)] [TestCase(false)] public void TestConstructor_ShouldSetCanVoteCorrectly(bool canVote) { // Arrange var trainingLog = new TrainingLog(); // Act var model = new LogDetailsViewModel(trainingLog, true, false, canVote, null); // Assert Assert.AreEqual(canVote, model.CanVote); } [Test] public void TestConstructor_ShouldSetEntriesCorrectly() { // Arrange var trainingLog = new TrainingLog(); var entries = new List<LogEntryViewModel>().ToPagedList(1, 1); // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, entries); // Assert CollectionAssert.AreEqual(entries, model.Entries); } [Test] public void TestConstructor_LogUserIsNull_ShouldSetProfileImageUrlNull() { // Arrange var trainingLog = new TrainingLog(); // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, null); // Assert Assert.IsNull(model.ProfileImageUrl); } [TestCase("http://pnge.org/hd-wallpapers/image-2359")] [TestCase("https://camo.mybb.com/e01de90be6012adc1b1701dba899491a9348ae79/687474703a2f2f7777772e6a71756572797363726970742e6e65742f696d616765732f53696d706c6573742d526573706f6e736976652d6a51756572792d496d6167652d4c69676874626f782d506c7567696e2d73696d706c652d6c69676874626f782e6a7067")] [TestCase("https://www.w3schools.com/css/trolltunga.jpg")] public void TestConstructor_LogUserIsNotNull_ShouldSetProfileImageUrlCorrectly(string imageUrl) { // Arrange var user = new User { ProfileImageUrl = imageUrl }; var trainingLog = new TrainingLog { User = user }; // Act var model = new LogDetailsViewModel(trainingLog, true, true, true, null); // Assert Assert.AreEqual(imageUrl, model.ProfileImageUrl); } } }
namespace Speed_Racing { using System; public class Car { public string model; public double fuelAmount; public double costPerKm; public double distanceTraveled; public Car(string model, double fuelAmount, double costPerKm) { this.model = model; this.fuelAmount = fuelAmount; this.costPerKm = costPerKm; this.distanceTraveled = 0; } public static void Drive(Car model, double distance) { if (model.fuelAmount < distance * model.costPerKm) { Console.WriteLine($"Insufficient fuel for the drive"); } else { model.fuelAmount -= distance * model.costPerKm; model.distanceTraveled += distance; } } } }
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace chapter2 { [Activity (Label = "chapter2", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); SetContentView (Resource.Layout.Main); var helpButton = FindViewById<ImageButton> (Resource.Id.loginQuestion); helpButton.Click += (sender, e) => { var builder = new AlertDialog.Builder (this) .SetTitle ("Need Help?") .SetMessage ("Here What you Should Do") .SetPositiveButton ("Ok", (innerSender, innere) => { }); var dialog = builder.Create (); dialog.Show (); }; } protected override void OnStart(){ base.OnStart (); TextView aTextView = FindViewById<TextView> (Resource.Id.myTextView); aTextView.Text = "Hello !"; } protected override void OnResume(){ base.OnResume (); // Some init code } protected override void OnPause(){ base.OnPause (); // Save data to persistent storage // Desallocate big objects // Free Hardware like Bluetooth } protected override void OnStop(){ base.OnStop (); StopService (new Intent (this, typeof(Service))); } protected override void OnRestart(){ base.OnRestart (); } protected override void OnDestroy(){ base.OnDestroy (); } } }
using System.Web.Http; namespace EP.CursoMvc.Services.ClienteAPI.Controllers { public class ApiBase : ApiController { public IHttpActionResult Response(object obj) { if (ModelState.IsValid) { return Ok(new { success = true, obj = obj }); } return BadRequest(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AddressBook.EditingForm { class EditFormModel { public DateTime LastTimeAccessed { get; set; } } }
using Assets.Scripts.RobinsonCrusoe_Game.GameAttributes; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Assets.Scripts.RobinsonCrusoe_Game.Cards.EventCards.Collection { public class Wreckage_CaptainsChest : ICard, IEventCard { public bool CanCompleteQuest() { return true; } public void ExecuteEvent() { //Has none } public void ExecuteSuccessEvent() { //TODO: Card has an option for two actions Wood.IncreaseWoodBy(2); } public int GetActionCosts() { return 2; } public string GetCardDescription() { return "TODO"; } public int GetMaterialNumber() { return 2; } public QuestionMark GetQuestionMark() { return QuestionMark.None; } public RessourceCosts GetRessourceCosts() { return new RessourceCosts(0, 0, 0); } public bool IsCardTypeBook() { return false; } public override string ToString() { return "Captain'sChest"; } public bool HasDiscardOption() { return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Modelo; using Servico; namespace Apresentacao { public partial class FormConsulta : Form { private MedicamentoServico servicoMedicamento = new MedicamentoServico(); private MedicamentoConsultaServico medicamentoConsultaServico = new MedicamentoConsultaServico(); private Cliente clienteConsulta = new Cliente(); private Consulta consultaEdit = new Consulta(); private AnimalServico animalServico = new AnimalServico(); private ClienteServico clienteServico = new ClienteServico(); private VeterinarioServico veterinarioServico = new VeterinarioServico(); private ConsultaServico consultaServico = new ConsultaServico(); private Consulta consultaArmazenada = new Consulta(); private long idConsulta; float valorTotal = 0; List<string> statusString = new List<string>(new string[] { "Marcado", "Cancelado", "Atendido" }); List<string> statusPagamento = new List<string>(new string[] { "Pago", "Nao Pago"}); public FormConsulta(Cliente cliente) { this.clienteConsulta = cliente; InitializeComponent(); refreshGrid(); refreshGridCarrinho(); refreshGridMedicamentos(); txtIdClienteConsulta.Text = clienteConsulta.ClienteId.ToString(); txtNomeClienteConsulta.Text = clienteConsulta.Nome; txtNomeClienteConsulta.Enabled = false; txtIdClienteConsulta.Enabled = false; button1.Enabled = false; bntExcluirCarrinho.Enabled = false; } private void refreshGridMedicamentos() { dgvMedicamentos.DataSource = servicoMedicamento.TodosOsMedicamentos(); } private void refreshGridCarrinho() { dgvCarrinho.DataSource = medicamentoConsultaServico.TodasAsConsultasMedicamentosPorId(Convert.ToInt64(idConsulta)); } private void refreshGrid() { try { List<Animal> animais = new List<Animal>(); comboBox2.DataSource = veterinarioServico.TodosOsVeterinarios(); comboBox2.ValueMember = "VeterinarioId"; comboBox2.DisplayMember = "Nome"; comboBoxStatus.DataSource = statusString; comboBoxPagamento.DataSource = statusPagamento; animais = animalServico.ObterPorId(Convert.ToInt64(txtIdClienteConsulta.Text = clienteConsulta.ClienteId.ToString())).ToList(); comboBox1.DataSource = animais; comboBox1.ValueMember = "AnimalId"; comboBox1.DisplayMember = "Nome"; } catch (NullReferenceException exp) { MessageBox.Show("Nao existe animal cadastrado para este usuario, cadastre-o"); } } private void btnNovoAnimal_Click_1(object sender, EventArgs e) { FormaAnimal formAnimal = new FormaAnimal(txtIdClienteConsulta.Text = clienteConsulta.ClienteId.ToString()); formAnimal.Show(); } private void btnAtualizar_Click(object sender, EventArgs e) { refreshGrid(); } private void btnSalvar_Click(object sender, EventArgs e) { try { this.idConsulta = consultaServico.GravarConsulta(new Modelo.Consulta() { ClienteId = Convert.ToInt64(txtIdClienteConsulta.Text), AnimalId = Convert.ToInt32(comboBox1.SelectedValue.ToString()), DataConsulta = Convert.ToDateTime(dateTimeConsulta.Text), EstatusConsulta = comboBoxStatus.SelectedValue.ToString(), VeterinarioId = Convert.ToInt64(comboBox2.SelectedValue.ToString()), EstatusPagamento = comboBoxPagamento.SelectedValue.ToString(), ValorTotalConsulta = valorTotal, Observacao = txtObservacao.Text, }); this.consultaArmazenada = new Consulta() { ConsultaId = idConsulta, ClienteId = Convert.ToInt64(txtIdClienteConsulta.Text), AnimalId = Convert.ToInt32(comboBox1.SelectedValue.ToString()), DataConsulta = Convert.ToDateTime(dateTimeConsulta.Text), EstatusConsulta = comboBoxStatus.SelectedValue.ToString(), VeterinarioId = Convert.ToInt64(comboBox2.SelectedValue.ToString()), EstatusPagamento = comboBoxPagamento.SelectedValue.ToString(), ValorTotalConsulta = valorTotal, Observacao = txtObservacao.Text, }; dateTimeConsulta.Enabled = false; comboBoxPagamento.Enabled = false; comboBoxStatus.Enabled = false; comboBox2.Enabled = false; comboBox1.Enabled = false; btnSalvar.Enabled = false; txtObservacao.Enabled = false; txtValorTotal.Enabled=false; refreshGrid(); refreshGridCarrinho(); refreshGridMedicamentos(); button1.Enabled = true; bntExcluirCarrinho.Enabled = true; } catch (Exception exp) { MessageBox.Show(exp.ToString()); } } private void button1_Click(object sender, EventArgs e) { try { medicamentoConsultaServico.GravarConsultaMedicamento(new ConsultaMedicamento() { ConsultaId = Convert.ToInt64(idConsulta), MedicamentoId = Convert.ToInt64(dgvMedicamentos.CurrentRow.Cells["MedicamentoId"].Value.ToString()), Quantidade = Convert.ToInt32(txtQuantidade.Text), ValorUnitario = (float)Convert.ToDouble(dgvMedicamentos.CurrentRow.Cells["ValorUnitario"].Value.ToString()), }); valorTotal = valorTotal + (Convert.ToInt32(txtQuantidade.Text) * (float)Convert.ToDouble(dgvMedicamentos.CurrentRow.Cells["ValorUnitario"].Value.ToString())); txtValorTotal.Text = String.Format("{0:0.00}", valorTotal); consultaServico.AtualizarPrecoConsulta(new Consulta() { ConsultaId = consultaArmazenada.ConsultaId, ClienteId = consultaArmazenada.ClienteId, AnimalId = consultaArmazenada.AnimalId, DataConsulta = consultaArmazenada.DataConsulta, EstatusConsulta = consultaArmazenada.EstatusConsulta, EstatusPagamento = consultaArmazenada.EstatusPagamento, Observacao = consultaArmazenada.Observacao, VeterinarioId = consultaArmazenada.VeterinarioId, ValorTotalConsulta = Convert.ToDouble(txtValorTotal.Text), }); refreshGridCarrinho(); } catch(Exception exp) { MessageBox.Show(exp.ToString()); } } private void bntExcluirCarrinho_Click(object sender, EventArgs e) { try { medicamentoConsultaServico.ExcluirConsultaMedicamento(Convert.ToInt64(dgvCarrinho.CurrentRow.Cells["ConsultaMedicamentoId"].Value.ToString())); String.Format("{0:0.00}", dgvMedicamentos.CurrentRow.Cells["ValorUnitario"].Value.ToString()); float testeste = (Convert.ToInt32(dgvCarrinho.CurrentRow.Cells["Quantidade"].Value.ToString()) * (float)Convert.ToDouble(dgvCarrinho.CurrentRow.Cells["ValorUnitario"].Value.ToString())); valorTotal = valorTotal - (Convert.ToInt32(dgvCarrinho.CurrentRow.Cells["Quantidade"].Value.ToString()) * (float)Convert.ToDouble(dgvCarrinho.CurrentRow.Cells["ValorUnitario"].Value.ToString())); txtValorTotal.Text = String.Format("{0:0.00}", valorTotal); refreshGridCarrinho(); consultaServico.AtualizarPrecoConsulta(new Consulta() { ConsultaId = consultaArmazenada.ConsultaId, ClienteId = consultaArmazenada.ClienteId, AnimalId = consultaArmazenada.AnimalId, DataConsulta = consultaArmazenada.DataConsulta, EstatusConsulta = consultaArmazenada.EstatusConsulta, EstatusPagamento = consultaArmazenada.EstatusPagamento, Observacao = consultaArmazenada.Observacao, VeterinarioId = consultaArmazenada.VeterinarioId, ValorTotalConsulta = Convert.ToDouble(txtValorTotal.Text), }); } catch (Exception exp) { MessageBox.Show(exp.ToString()); } } private void button2_Click(object sender, EventArgs e) { this.Close(); } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// Characters can not only have Inventory buckets (containers of items that are generally matched by their type or functionality), they can also have Equipment Slots. The Equipment Slot is an indicator that the related bucket can have instanced items equipped on the character. For instance, the Primary Weapon bucket has an Equipment Slot that determines whether you can equip primary weapons, and holds the association between its slot and the inventory bucket from which it can have items equipped. An Equipment Slot must have a related Inventory Bucket, but not all inventory buckets must have Equipment Slots. /// </summary> [DataContract] public partial class DestinyDefinitionsDestinyEquipmentSlotDefinition : IEquatable<DestinyDefinitionsDestinyEquipmentSlotDefinition>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyDefinitionsDestinyEquipmentSlotDefinition" /> class. /// </summary> /// <param name="DisplayProperties">DisplayProperties.</param> /// <param name="EquipmentCategoryHash">These technically point to \&quot;Equipment Category Definitions\&quot;. But don&#39;t get excited. There&#39;s nothing of significant value in those definitions, so I didn&#39;t bother to expose them. You can use the hash here to group equipment slots by common functionality, which serves the same purpose as if we had the Equipment Category definitions exposed..</param> /// <param name="BucketTypeHash">The inventory bucket that owns this equipment slot..</param> /// <param name="ApplyCustomArtDyes">If True, equipped items should have their custom art dyes applied when rendering the item. Otherwise, custom art dyes on an item should be ignored if the item is equipped in this slot..</param> /// <param name="Hash">The unique identifier for this entity. Guaranteed to be unique for the type of entity, but not globally. When entities refer to each other in Destiny content, it is this hash that they are referring to..</param> /// <param name="Index">The index of the entity as it was found in the investment tables..</param> /// <param name="Redacted">If this is true, then there is an entity with this identifier/type combination, but BNet is not yet allowed to show it. Sorry!.</param> public DestinyDefinitionsDestinyEquipmentSlotDefinition(DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition DisplayProperties = default(DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition), uint? EquipmentCategoryHash = default(uint?), uint? BucketTypeHash = default(uint?), bool? ApplyCustomArtDyes = default(bool?), uint? Hash = default(uint?), int? Index = default(int?), bool? Redacted = default(bool?)) { this.DisplayProperties = DisplayProperties; this.EquipmentCategoryHash = EquipmentCategoryHash; this.BucketTypeHash = BucketTypeHash; this.ApplyCustomArtDyes = ApplyCustomArtDyes; this.Hash = Hash; this.Index = Index; this.Redacted = Redacted; } /// <summary> /// Gets or Sets DisplayProperties /// </summary> [DataMember(Name="displayProperties", EmitDefaultValue=false)] public DestinyDefinitionsCommonDestinyDisplayPropertiesDefinition DisplayProperties { get; set; } /// <summary> /// These technically point to \&quot;Equipment Category Definitions\&quot;. But don&#39;t get excited. There&#39;s nothing of significant value in those definitions, so I didn&#39;t bother to expose them. You can use the hash here to group equipment slots by common functionality, which serves the same purpose as if we had the Equipment Category definitions exposed. /// </summary> /// <value>These technically point to \&quot;Equipment Category Definitions\&quot;. But don&#39;t get excited. There&#39;s nothing of significant value in those definitions, so I didn&#39;t bother to expose them. You can use the hash here to group equipment slots by common functionality, which serves the same purpose as if we had the Equipment Category definitions exposed.</value> [DataMember(Name="equipmentCategoryHash", EmitDefaultValue=false)] public uint? EquipmentCategoryHash { get; set; } /// <summary> /// The inventory bucket that owns this equipment slot. /// </summary> /// <value>The inventory bucket that owns this equipment slot.</value> [DataMember(Name="bucketTypeHash", EmitDefaultValue=false)] public uint? BucketTypeHash { get; set; } /// <summary> /// If True, equipped items should have their custom art dyes applied when rendering the item. Otherwise, custom art dyes on an item should be ignored if the item is equipped in this slot. /// </summary> /// <value>If True, equipped items should have their custom art dyes applied when rendering the item. Otherwise, custom art dyes on an item should be ignored if the item is equipped in this slot.</value> [DataMember(Name="applyCustomArtDyes", EmitDefaultValue=false)] public bool? ApplyCustomArtDyes { get; set; } /// <summary> /// The unique identifier for this entity. Guaranteed to be unique for the type of entity, but not globally. When entities refer to each other in Destiny content, it is this hash that they are referring to. /// </summary> /// <value>The unique identifier for this entity. Guaranteed to be unique for the type of entity, but not globally. When entities refer to each other in Destiny content, it is this hash that they are referring to.</value> [DataMember(Name="hash", EmitDefaultValue=false)] public uint? Hash { get; set; } /// <summary> /// The index of the entity as it was found in the investment tables. /// </summary> /// <value>The index of the entity as it was found in the investment tables.</value> [DataMember(Name="index", EmitDefaultValue=false)] public int? Index { get; set; } /// <summary> /// If this is true, then there is an entity with this identifier/type combination, but BNet is not yet allowed to show it. Sorry! /// </summary> /// <value>If this is true, then there is an entity with this identifier/type combination, but BNet is not yet allowed to show it. Sorry!</value> [DataMember(Name="redacted", EmitDefaultValue=false)] public bool? Redacted { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyDefinitionsDestinyEquipmentSlotDefinition {\n"); sb.Append(" DisplayProperties: ").Append(DisplayProperties).Append("\n"); sb.Append(" EquipmentCategoryHash: ").Append(EquipmentCategoryHash).Append("\n"); sb.Append(" BucketTypeHash: ").Append(BucketTypeHash).Append("\n"); sb.Append(" ApplyCustomArtDyes: ").Append(ApplyCustomArtDyes).Append("\n"); sb.Append(" Hash: ").Append(Hash).Append("\n"); sb.Append(" Index: ").Append(Index).Append("\n"); sb.Append(" Redacted: ").Append(Redacted).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyDefinitionsDestinyEquipmentSlotDefinition); } /// <summary> /// Returns true if DestinyDefinitionsDestinyEquipmentSlotDefinition instances are equal /// </summary> /// <param name="input">Instance of DestinyDefinitionsDestinyEquipmentSlotDefinition to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyDefinitionsDestinyEquipmentSlotDefinition input) { if (input == null) return false; return ( this.DisplayProperties == input.DisplayProperties || (this.DisplayProperties != null && this.DisplayProperties.Equals(input.DisplayProperties)) ) && ( this.EquipmentCategoryHash == input.EquipmentCategoryHash || (this.EquipmentCategoryHash != null && this.EquipmentCategoryHash.Equals(input.EquipmentCategoryHash)) ) && ( this.BucketTypeHash == input.BucketTypeHash || (this.BucketTypeHash != null && this.BucketTypeHash.Equals(input.BucketTypeHash)) ) && ( this.ApplyCustomArtDyes == input.ApplyCustomArtDyes || (this.ApplyCustomArtDyes != null && this.ApplyCustomArtDyes.Equals(input.ApplyCustomArtDyes)) ) && ( this.Hash == input.Hash || (this.Hash != null && this.Hash.Equals(input.Hash)) ) && ( this.Index == input.Index || (this.Index != null && this.Index.Equals(input.Index)) ) && ( this.Redacted == input.Redacted || (this.Redacted != null && this.Redacted.Equals(input.Redacted)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.DisplayProperties != null) hashCode = hashCode * 59 + this.DisplayProperties.GetHashCode(); if (this.EquipmentCategoryHash != null) hashCode = hashCode * 59 + this.EquipmentCategoryHash.GetHashCode(); if (this.BucketTypeHash != null) hashCode = hashCode * 59 + this.BucketTypeHash.GetHashCode(); if (this.ApplyCustomArtDyes != null) hashCode = hashCode * 59 + this.ApplyCustomArtDyes.GetHashCode(); if (this.Hash != null) hashCode = hashCode * 59 + this.Hash.GetHashCode(); if (this.Index != null) hashCode = hashCode * 59 + this.Index.GetHashCode(); if (this.Redacted != null) hashCode = hashCode * 59 + this.Redacted.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
namespace HCLAcademy.Util { public static class IngEnum { public enum TrainingCategory { Internal, External } public enum AssessmentCategory { Internal, External } public enum Status { Initiated, Completed, Rejected } } }
// Accord Imaging Library // The Accord.NET Framework // http://accord-framework.net // // Copyright © César Souza, 2009-2015 // cesarsouza at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // namespace Accord.Imaging.Filters { using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using AForge; using Accord.Imaging; using Accord.Imaging.Filters; /// <summary> /// Filter to mark (highlight) pairs of points in a image. /// </summary> /// public class PairsMarker : BaseInPlaceFilter { private Color markerColor = Color.White; private IntPoint[] points1; private IntPoint[] points2; private Dictionary<PixelFormat, PixelFormat> formatTranslations = new Dictionary<PixelFormat, PixelFormat>(); /// <summary> /// Color used to mark pairs. /// </summary> /// public Color MarkerColor { get { return markerColor; } set { markerColor = value; } } /// <summary> /// The first set of points. /// </summary> /// public IntPoint[] Points1 { get { return points1; } set { points1 = value; } } /// <summary> /// The corresponding points to the first set of points. /// </summary> /// public IntPoint[] Points2 { get { return points2; } set { points2 = value; } } /// <summary> /// Format translations dictionary. /// </summary> /// public override Dictionary<PixelFormat, PixelFormat> FormatTranslations { get { return formatTranslations; } } /// <summary> /// Initializes a new instance of the <see cref="PairsMarker"/> class. /// </summary> /// /// <param name="points1">Set of starting points.</param> /// <param name="points2">Set of corresponding points.</param> /// public PairsMarker(IntPoint[] points1, IntPoint[] points2) : this(points1, points2, Color.White) { } /// <summary> /// Initializes a new instance of the <see cref="PairsMarker"/> class. /// </summary> /// /// <param name="points1">Set of starting points.</param> /// <param name="points2">Set of corresponding points.</param> /// <param name="markerColor">The color of the lines to be marked.</param> /// public PairsMarker(IntPoint[] points1, IntPoint[] points2, Color markerColor) { this.points1 = points1; this.points2 = points2; this.markerColor = markerColor; formatTranslations[PixelFormat.Format8bppIndexed] = PixelFormat.Format8bppIndexed; formatTranslations[PixelFormat.Format24bppRgb] = PixelFormat.Format24bppRgb; } /// <summary> /// Process the filter on the specified image. /// </summary> /// /// <param name="image">Source image data.</param> /// protected override void ProcessFilter(UnmanagedImage image) { // mark all lines for (int i = 0; i < points1.Length; i++) { Drawing.Line(image, points1[i], points2[i], markerColor); } } } }
using OmniSharp.Extensions.LanguageServer.Protocol.Models; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; namespace OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities { public class WorkspaceServerCapabilities : CapabilitiesBase, IWorkspaceServerCapabilities { /// <summary> /// The server supports workspace folder. /// /// Since 3.6.0 /// </summary> [Optional] public DidChangeWorkspaceFolderRegistrationOptions.StaticOptions? WorkspaceFolders { get; set; } /// <summary> /// The server is interested in file notifications/requests. /// /// @since 3.16.0 /// </summary> [Optional] public FileOperationsWorkspaceServerCapabilities? FileOperations { get; set; } } }
using System; using System.Diagnostics; using System.Linq; using System.Reflection; using MediatR; namespace OmniSharp.Extensions.JsonRpc { [DebuggerDisplay("{ToString()}")] internal class HandlerTypeDescriptor : IHandlerTypeDescriptor, IEquatable<HandlerTypeDescriptor> { public HandlerTypeDescriptor(Type handlerType) { var method = MethodAttribute.From(handlerType)!; Method = method.Method; Direction = method.Direction; if (handlerType.IsGenericTypeDefinition && handlerType.IsPublic) { var parameter = handlerType.GetTypeInfo().GenericTypeParameters[0]; var constraints = parameter.GetGenericParameterConstraints(); if (constraints.Length == 1) { handlerType = handlerType.MakeGenericType(handlerType.GetTypeInfo().GenericTypeParameters[0].GetGenericParameterConstraints()[0]); } } HandlerType = handlerType; InterfaceType = HandlerTypeDescriptorHelper.GetHandlerInterface(handlerType); // This allows for us to have derived types // We are making the assumption that interface given here // if a GTD will have a constraint on the first generic type parameter // that is the real base type for this interface. if (InterfaceType.IsGenericType) { ParamsType = InterfaceType.GetGenericArguments()[0]; } HasParamsType = ParamsType != null; IsNotification = handlerType .GetInterfaces() .Any(z => z.IsGenericType && typeof(IJsonRpcNotificationHandler<>).IsAssignableFrom(z.GetGenericTypeDefinition())); IsRequest = !IsNotification; var requestInterface = ParamsType? .GetInterfaces() .FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IRequest<>)); if (requestInterface != null) ResponseType = requestInterface.GetGenericArguments()[0]; HasResponseType = ResponseType != null && ResponseType != typeof(Unit); var processAttributes = HandlerType .GetCustomAttributes(true) .Concat(HandlerType.GetCustomAttributes(true)) .Concat(InterfaceType.GetInterfaces().SelectMany(x => x.GetCustomAttributes(true))) .Concat(HandlerType.GetInterfaces().SelectMany(x => x.GetCustomAttributes(true))) .OfType<ProcessAttribute>() .ToArray(); RequestProcessType = processAttributes .FirstOrDefault()?.Type; } public string Method { get; } public Direction Direction { get; } public RequestProcessType? RequestProcessType { get; } public bool IsRequest { get; } public Type HandlerType { get; } public Type InterfaceType { get; } public bool IsNotification { get; } public bool HasParamsType { get; } public Type? ParamsType { get; } public bool HasResponseType { get; } public Type? ResponseType { get; } public override string ToString() => $"{Method}:{HandlerType.FullName}"; public bool Equals(HandlerTypeDescriptor? other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return Method == other.Method && HandlerType == other.HandlerType && InterfaceType == other.InterfaceType; } public override bool Equals(object? obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((HandlerTypeDescriptor) obj); } public override int GetHashCode() { unchecked { var hashCode = Method.GetHashCode(); hashCode = ( hashCode * 397 ) ^ HandlerType.GetHashCode(); hashCode = ( hashCode * 397 ) ^ InterfaceType.GetHashCode(); return hashCode; } } public static bool operator ==(HandlerTypeDescriptor left, HandlerTypeDescriptor right) => Equals(left, right); public static bool operator !=(HandlerTypeDescriptor left, HandlerTypeDescriptor right) => !Equals(left, right); } }
using System; using System.Windows.Media; using System.Windows.Media.Imaging; namespace ClaudiaIDE.Helpers { static class Utils { public static BitmapImage EnsureMaxWidthHeight(BitmapImage original, int maxWidth, int maxHeight) { BitmapImage bitmap = null; if (maxWidth > 0 && maxHeight > 0 && original.PixelWidth > maxWidth && original.PixelHeight > maxHeight) { bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.UriSource = original.UriSource; bitmap.DecodePixelWidth = maxWidth; bitmap.DecodePixelHeight = maxHeight; bitmap.EndInit(); bitmap.Freeze(); return bitmap; } else if (maxWidth > 0 && original.PixelWidth > maxWidth) { bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.UriSource = original.UriSource; bitmap.DecodePixelWidth = maxWidth; bitmap.EndInit(); bitmap.Freeze(); return bitmap; } else if (maxHeight > 0 && original.PixelHeight > maxHeight) { bitmap = new BitmapImage(); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.UriSource = original.UriSource; bitmap.DecodePixelHeight = maxHeight; bitmap.EndInit(); bitmap.Freeze(); return bitmap; } else { return original; } } public static BitmapSource ConvertToDpi96(BitmapSource source) { var dpi = 96; var width = source.PixelWidth; var height = source.PixelHeight; var stride = width * 4; var pixelData = new byte[stride * height]; source.CopyPixels(pixelData, stride, 0); return BitmapSource.Create(width, height, dpi, dpi, PixelFormats.Bgra32, null, pixelData, stride); } static byte[] pixelByteArray; public static BitmapSource SoftenEdges(BitmapSource original, int softedgex, int softedgey) { if (softedgex <= 0 && softedgey <= 0) return original; try { //System.Windows.Forms.MessageBox.Show(string.Format("SoftenEdges,soft={0},bpp={1}", softedge, original.Format.BitsPerPixel)); //32bit assumption if (original.Format.BitsPerPixel != 32) { return original; } //limit softedge range by half image size softedgex = Math.Min(softedgex, (int)(original.Width / 2)); softedgey = Math.Min(softedgey, (int)(original.Height / 2)); int height = original.PixelHeight; int width = original.PixelWidth; int bytesPerPixel = (original.Format.BitsPerPixel + 7) / 8; int nStride = width * bytesPerPixel; pixelByteArray = new byte[height * nStride]; original.CopyPixels(pixelByteArray, nStride, 0); //alpha and color for (int y = 0; y < height; y++) { float fAlphaByY = 1f; int nDistToEdgeY = Math.Min(y, height - 1 - y); fAlphaByY = (float)nDistToEdgeY / softedgey; fAlphaByY = Math.Min(fAlphaByY, 1.0f); for (int x = 0; x < width; x++) { float fAlphaByX = 1f; int nDistToEdgeX = Math.Min(x, width - 1 - x); fAlphaByX = (float)nDistToEdgeX / softedgex; fAlphaByX = Math.Min(fAlphaByX, 1.0f); for (int iPix = 0; iPix < 4; iPix++) { int alpha_offset_in_array = bytesPerPixel * (x + y * width) + iPix; int alphaOld = (int)pixelByteArray[alpha_offset_in_array]; int alphaNew = (int)Math.Floor(alphaOld * fAlphaByX * fAlphaByY); pixelByteArray[alpha_offset_in_array] = (byte)alphaNew; } } } WriteableBitmap newbm = new WriteableBitmap(width, height, original.DpiX, original.DpiY, PixelFormats.Pbgra32, null); newbm.WritePixels(new System.Windows.Int32Rect(0, 0, width, height), pixelByteArray, nStride, 0); return newbm; } catch (System.Exception exp) { System.Windows.Forms.MessageBox.Show(exp.ToString() + exp.StackTrace); } return original; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class pause : MonoBehaviour { public static bool gameispaused = false; public GameObject pauseui; void Start() { gameispaused = false; } // Update is called once per frame void Update () { if (Input.GetKeyDown (KeyCode.Escape)) { if (gameispaused) { Resume(); } else { Pause(); } } } public void Resume() { pauseui.SetActive(false); Time.timeScale=1f; gameispaused=false; } void Pause() { pauseui.SetActive(true); Time.timeScale= 0f; gameispaused = true; } public void quitgame() { #if UNITY_EDITOR UnityEditor.EditorApplication.isPlaying=false; #else Application.Quit(); #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Reflection; namespace WebIBOST1 { public partial class SummaryDashboard : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { GenerateTable(); //IBOrderTrackingEntities oConnect = new IBOrderTrackingEntities(); //grdworking.DataSource = oConnect.SOHeaders.ToList(); //grdworking.DataBind(); } private void GenerateTable() { //Header //Add header to table TableRow oRow = new TableRow(); oRow.TableSection = TableRowSection.TableHeader; int noCol = 0; foreach (var item in getSOHeader()) { if (noCol < 9) { TableCell oH1 = new TableCell(); oH1.Text = item; oRow.Cells.Add(oH1); } noCol++; } //Finish Header tblData.Rows.Add(oRow); //Rows WebIBOST1.IBOrderTrackingEntities oConnect = new IBOrderTrackingEntities(); if(oConnect.SOHeaders.Count() > 0) { var soItem = oConnect.SOHeaders.ToList(); foreach (var row in soItem) { noCol = 0; //Add Detail to table TableRow oDetail = new TableRow(); oDetail.TableSection = TableRowSection.TableBody; Type oType = row.GetType(); PropertyInfo[] props = oType.GetProperties(); foreach (var prop in props) { //Row 1 Col 1 if (noCol < 9) { TableCell oR1 = new TableCell(); if (prop.Name == "SO") { oR1.Text = prop.GetValue(row) != null ? SetLinkSOUrl( prop.GetValue(row).ToString()) : "'/>"; } else if(prop.Name =="PO") { oR1.Text = prop.GetValue(row) != null ? SetLinkPOUrl( prop.GetValue(row).ToString() ): "'/>"; } else { oR1.Text = prop.GetValue(row) != null ? prop.GetValue(row).ToString() : ""; } oDetail.Cells.Add(oR1); } noCol++; } // Finish 1 Row tblData.Rows.Add(oDetail); } // Add class tblData.Attributes.Add("class", "table table-striped table-bordered table-hover"); } } private string SetLinkPOUrl(string value) { return "<a href='" + this.Request.Url.AbsoluteUri.Replace(this.Request.Url.AbsolutePath.ToString(), "") + "/SOForm.aspx?PO=" + value + "'>" + value; } private string SetLinkSOUrl(string value) { return "<a href='" + this.Request.Url.AbsoluteUri.Replace(this.Request.Url.AbsolutePath.ToString(), "") + "/SOForm.aspx?SO=" + value + "'>" + value; } private List<String> getSOHeader() { List<String> oResult = new List<string>(); Type soType = typeof(SOHeader); foreach (var item in soType.GetProperties()) { oResult.Add(item.Name); } return oResult; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Xml.Linq; using System.Net; using System.Reflection; namespace AutoUpdate.MainService { public class Updater { public void CheckUpdateStatus(string appName, string url) { UpdateInfo updateInfo = new UpdateInfo(); updateInfo.ConfigurationName = "Version.txt"; updateInfo.AppName = appName; updateInfo.Url = url; updateInfo.LocalFilePath = Assembly.GetExecutingAssembly().Location.Substring(0, Assembly.GetExecutingAssembly().Location.LastIndexOf(Path.DirectorySeparatorChar)); StreamReader streamReader = new StreamReader(Path.Combine(updateInfo.LocalFilePath, updateInfo.ConfigurationName)); string localVersion = streamReader.ReadToEnd(); streamReader.Close(); updateInfo.ServerVersion = CheckServerVersion(url, localVersion); if (string.IsNullOrEmpty(updateInfo.ServerVersion) || updateInfo.ServerVersion == "F") return; this.StartUpdate(updateInfo); } string CheckServerVersion(string url, string localVersion) { string serverUrl = string.Format("{0}/Home/CheckUpdate?version={1}", url, localVersion); return serverUrl.Get(); } private void StartUpdate(UpdateInfo info) { //更新程序复制到缓存文件夹 string updateFileDir = info.LocalFilePathTemp; if (!Directory.Exists(updateFileDir)) { Directory.CreateDirectory(updateFileDir); } App app = new App(); MainWindow mainWindow = new MainWindow(info); app.Run(mainWindow); } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using SprintFour.Utilities; using System; namespace SprintFour.Sprites { public class FlagpoleSprite : SpriteBase { #region Private Members private static readonly Texture2D texture; #endregion #region Constructors static FlagpoleSprite() { if (SprintFourGame.GetInstance().GraphicsDevice != null) texture = texture ?? SprintFourGame.GetInstance().Content.Load<Texture2D>(Utility.POLE); } public FlagpoleSprite(Tuple<int, int>[] frames) : base(frames, Utility.ONE, Utility.ONE, texture) { } #endregion #region Methods Inherited from ISprite public override void Update() { // Do Mario Stuff } public override void Draw(Vector2 position) { SpriteBatch spriteBatch = SprintFourGame.GetInstance().SpriteBatch; int width = texture.Width / Columns; int height = texture.Height / Rows; Rectangle destinationRectangle = new Rectangle((int)position.X, (int)position.Y, width, height); spriteBatch.Draw(texture, destinationRectangle, Color.White); } #endregion } }
using System; using System.Linq; using System.Collections.Generic; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace GeoNavigator { /// <summary> /// Okno s filtry cache /// </summary> public partial class Filter : Form { // Filtry private int[] filter; /// <summary> /// Vytvori okno s filtry /// </summary> public Filter(int[] appFilter) { InitializeComponent(); filter = appFilter; // Zobrazi formularove prvky podle aktualniho nastaveni if (filter[0] == 1) checkBox1.Checked = true; if (filter[1] == 1) checkBox2.Checked = true; if (filter[2] == 1) checkBox3.Checked = true; if (filter[3] == 1) checkBox4.Checked = true; if (filter[4] == 1) checkBox5.Checked = true; if (filter[5] == 1) checkBox6.Checked = true; if (filter[6] == 1) checkBox7.Checked = true; if (filter[7] == 1) checkBox8.Checked = true; if (filter[8] == 1) checkBox9.Checked = true; if (filter[9] == 1) checkBox10.Checked = true; if (filter[10] == 1) checkBox11.Checked = true; if (filter[11] == 1) checkBox12.Checked = true; if (filter[12] == 1) checkBox13.Checked = true; numericUpDown1.Value = filter[13]; numericUpDown2.Value = filter[14]; numericUpDown3.Value = filter[15]; numericUpDown4.Value = filter[16]; } /// <summary> /// Stisknuti tlacitka OK /// </summary> private void menuItem1_Click(object sender, EventArgs e) { // Pole s obtiznosti a terenem vyplneno spravne if (numericUpDown1.Value <= numericUpDown2.Value && numericUpDown3.Value <= numericUpDown4.Value) { // Nastavi filtr filter[0] = Convert.ToInt32(checkBox1.Checked); filter[1] = Convert.ToInt32(checkBox2.Checked); filter[2] = Convert.ToInt32(checkBox3.Checked); filter[3] = Convert.ToInt32(checkBox4.Checked); filter[4] = Convert.ToInt32(checkBox5.Checked); filter[5] = Convert.ToInt32(checkBox6.Checked); filter[6] = Convert.ToInt32(checkBox7.Checked); filter[7] = Convert.ToInt32(checkBox8.Checked); filter[8] = Convert.ToInt32(checkBox9.Checked); filter[9] = Convert.ToInt32(checkBox10.Checked); filter[10] = Convert.ToInt32(checkBox11.Checked); filter[11] = Convert.ToInt32(checkBox12.Checked); filter[12] = Convert.ToInt32(checkBox13.Checked); filter[13] = (int)numericUpDown1.Value; filter[14] = (int)numericUpDown2.Value; filter[15] = (int)numericUpDown3.Value; filter[16] = (int)numericUpDown4.Value; // Uzavreni okna this.DialogResult = DialogResult.OK; this.Close(); } else { // Obtiznost nebo teren spatne nastaveny string message = "Cannot set filter! Set correct interval for difficulty and terrain!"; string caption = "Error"; MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } } /// <summary> /// Stisknuti tlacitka Cancel /// </summary> private void menuItem2_Click(object sender, EventArgs e) { // Uzavreni okna this.DialogResult = DialogResult.Cancel; this.Close(); } /// <summary> /// Stisknuti tlacitka Reset /// </summary> private void button1_Click(object sender, EventArgs e) { // Implicitni nastaveni checkBox1.Checked = true; checkBox2.Checked = true; checkBox3.Checked = true; checkBox4.Checked = true; checkBox5.Checked = true; checkBox6.Checked = true; checkBox7.Checked = true; checkBox8.Checked = true; checkBox9.Checked = true; checkBox10.Checked = true; checkBox11.Checked = true; checkBox12.Checked = true; checkBox13.Checked = true; numericUpDown1.Value = 1; numericUpDown2.Value = 5; numericUpDown3.Value = 1; numericUpDown4.Value = 5; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using SaleShop.Data.Infrastructure; using SaleShop.Data.Repositories; using SaleShop.Model.Models; namespace SaleShop.UnitTest.RepositoryTest { [TestClass] public class PostCategoryRepositoryTest { private IDbFactory dbFactory; private IPostCategoryRepository objRepository; private IUnitOfWork unitOfWork; [TestInitialize] public void Initialize() { dbFactory = new DbFactory(); objRepository = new PostCategoryRepository(dbFactory); unitOfWork = new UnitOfWork(dbFactory); } [TestMethod] public void PostCategory_Repository_GetAll() { var list = objRepository.GetAll().ToList(); Assert.AreEqual(3,list.Count); } [TestMethod] public void PostCategory_Repository_Create() { PostCategory postCategory = new PostCategory(); postCategory.Name = "Test Category"; postCategory.Alias = "Test-Category"; postCategory.Status = true; var result = objRepository.Add(postCategory); unitOfWork.Commit(); Assert.IsNotNull(result); Assert.AreEqual(4,result.ID); } } }
namespace DDDSouthWest.Website.Features.Admin.Account.ManageTalks { public class ViewTalkDetailViewModel { public int Id { get; set; } public string TalkTitle { get; set; } public string TalkBodyHtml { get; set; } public string SpeakerGivenName { get; set; } public string SpeakerFamilyName { get; set; } public string SpeakerFullName => $"{SpeakerGivenName} {SpeakerFamilyName}"; public string SpeakerBioHtml { get; set; } public int SpeakerId { get; set; } public string TalkBodyMarkdown { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PM.Library.Firebase; namespace FirebaseConsoleApplication { public class Program { public static void Main(string[] args) { // Instanciating with base URL FirebaseDB firebaseDB = new FirebaseDB("https://c-sharpcorner-2d7ae.firebaseio.com"); // Referring to Node with name "Teams" FirebaseDB firebaseDBTeams = firebaseDB.Node("Teams"); var data = @"{ 'Team-Awesome': { 'Members': { 'M1': { 'City': 'Hyderabad', 'Name': 'Ashish' }, 'M2': { 'City': 'Cyberabad', 'Name': 'Vivek' }, 'M3': { 'City': 'Secunderabad', 'Name': 'Pradeep' } } } }"; Console.WriteLine("GET Request"); FirebaseResponse getResponse = firebaseDBTeams.Get(); Console.WriteLine(getResponse.Success); if (getResponse.Success) Console.WriteLine(getResponse.JSONContent); Console.WriteLine(); Console.WriteLine("PUT Request"); FirebaseResponse putResponse = firebaseDBTeams.Put(data); Console.WriteLine(putResponse.Success); Console.WriteLine(); Console.WriteLine("POST Request"); FirebaseResponse postResponse = firebaseDBTeams.Post(data); Console.WriteLine(postResponse.Success); Console.WriteLine(); Console.WriteLine("PATCH Request"); FirebaseResponse patchResponse = firebaseDBTeams // Use of NodePath to refer path lnager than a single Node .NodePath("Team-Awesome/Members/M1") .Patch("{\"Designation\":\"CRM Consultant\"}"); Console.WriteLine(patchResponse.Success); Console.WriteLine(); Console.WriteLine("DELETE Request"); FirebaseResponse deleteResponse = firebaseDBTeams.Delete(); Console.WriteLine(deleteResponse.Success); Console.WriteLine(); Console.WriteLine(firebaseDBTeams.ToString()); Console.ReadLine(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [DisallowMultipleComponent] public class PlayerMove2 : PlayerMoveBase { // Doesn't work smoothly. protected override void teleport(Vector2 pos) { _rigidbody.interpolation = RigidbodyInterpolation2D.None; _rigidbody.position = pos; _rigidbody.interpolation = RigidbodyInterpolation2D.Interpolate; } }
using ClientAdmin.AdminLib; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClientAdmin { class Program { private static string ERROR_MESSAGE = "Wrong input. Type \"help\" for the list of commands\n"; static void Main(string[] args) { AdminCommandsClient client = new AdminCommandsClient(); string commands = "help: Display the help\n" + "city <Months>: Change the duration of the cache for the cities (in months)\n" + "stations <Minutes> : Change the duration of the cache for the stations (in minutes)\n" + "exit: quit the program\n"; Console.WriteLine("Type \"help\" for help"); string s = ""; while (s != "exit") { Console.WriteLine("What do you want ?"); s = Console.ReadLine(); if (s.Split(' ').Length == 1) { switch (s) { case "help": Console.WriteLine(commands); break; case "exit": break; default: Console.WriteLine(ERROR_MESSAGE); break; } } else if (s.Split(' ').Length == 2) { int x = 0; if (Int32.TryParse(s.Split(' ')[1], out x)) { switch (s.Split(' ')[0]) { case "city": Console.WriteLine(client.updateCacheDurationCitites(x)); break; case "station": Console.WriteLine(client.updateCacheDurationStations(x)); break; default: Console.WriteLine(ERROR_MESSAGE); break; } } else { Console.WriteLine("Wrong parameter, need an integer"); } } else { Console.WriteLine("Wrong input arguments. Type \"help\" for the list of commands\n"); } } } } }
using System.Drawing; namespace ClockClassLibrary { public class AnalogClock { public Point SsHandPosition { get; set; } public Point MmHandPosition { get; set; } public Point HhHandPosition { get; set; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TaskControll { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { PopulateData(); } } private void PopulateData() { using(MyDatabaseEntities dc = new MyDatabaseEntities()) { GridView1.DataSource = dc.FXDPlans. OrderBy(a => a.name). ThenBy(a => a.responsible). ThenBy(a => a.executor). ThenBy(a => a.department). ThenBy(a => a.report). //ThenBy(a => a.reportfile). //ThenBy(a => a.status). ToList(); GridView1.DataBind(); } } protected void Button1_Click(object sender, EventArgs e) { //Export selected rows to Excel //need to check is any row selected bool isSelected = false; foreach(GridViewRow i in GridView1.Rows) { CheckBox cb = (CheckBox)i.FindControl("chkSelect"); if(cb != null && cb.Checked) { isSelected = true; break; } } //export here if (isSelected) { GridView gvExport = GridView1; //this bellow line for not export to Excel gvExport.Columns[0].Visible = false; gvExport.Columns[6].Visible = false; foreach (GridViewRow i in GridView1.Rows) { gvExport.Rows[i.RowIndex].Visible = false; CheckBox cb = (CheckBox)i.FindControl("chkSelect"); if (cb != null && cb.Checked) { gvExport.Rows[i.RowIndex].Visible = true; } } Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=ExportGridData.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htW = new HtmlTextWriter(sw); gvExport.RenderControl(htW); Response.Output.Write(sw.ToString()); Response.End(); } } public override void VerifyRenderingInServerForm(Control control) { //this is added for error : GridView must be placed inside a form tag with runat=server } protected void bExportWord_Click(object sender, EventArgs e) { //Export selected rows to Word //need to check is any row selected bool isSelected = false; foreach (GridViewRow i in GridView1.Rows) { CheckBox cb = (CheckBox)i.FindControl("chkSelect"); if (cb != null && cb.Checked) { isSelected = true; break; } } //export here if (isSelected) { GridView gvExport = GridView1; //this bellow line for not export to Excel gvExport.Columns[0].Visible = false; gvExport.Columns[6].Visible = false; foreach (GridViewRow i in GridView1.Rows) { gvExport.Rows[i.RowIndex].Visible = false; CheckBox cb = (CheckBox)i.FindControl("chkSelect"); if (cb != null && cb.Checked) { gvExport.Rows[i.RowIndex].Visible = true; } } Response.Clear(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment;filename=FXDPlanTasks.doc"); Response.Charset = ""; Response.ContentType = "application/vnd.ms-word"; StringWriter sw = new StringWriter(); HtmlTextWriter htW = new HtmlTextWriter(sw); gvExport.RenderControl(htW); Response.Output.Write(sw.ToString()); Response.End(); } } } }
using LogicBuilder.Attributes; using System; using System.Collections.Generic; using System.Text; namespace Enrollment.Forms.Parameters.Common { public class AggregateTemplateFieldsParameters { public AggregateTemplateFieldsParameters(string label, [Domain("average,count,max,min,sum")] [ParameterEditorControl(ParameterControlType.DropDown)] string aggregateFunction) { Label = label; Function = aggregateFunction; } public string Label { get; set; } public string Function { get; set; } } }
using System; namespace CoreEngine.Math { [Serializable] public abstract class BaseVector3<TImpl,T> : BaseVector2<TImpl,T> where T:struct, IConvertible where TImpl: BaseVector3<TImpl,T>, new() { public T z = default(T); public BaseVector3() { Dimensions = 3; } public BaseVector3( T x, T y, T z ) : this() { this.x = x; this.y = y; this.z = z; } public override T this[int i] { get { switch( i ) { case 0: return x; case 1: return y; case 2: return z; default: return default(T); } } set { switch( i ) { case 0: x = value; break; case 1: y = value; break; case 2: z = value; break; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Wallet { class DluhToList { public string Nazev { get; set; } public string PocatekPujcky { get; set; } public string KonecPujcky { get; set; } public string Sazba { get; set; } public string VysePujcky { get; set; } } }
//_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. // VisualNovelToolkit /_/_/_/_/_/_/_/_/_/. // Copyright ©2013 - Sol-tribe. /_/_/_/_/_/_/_/_/_/. //_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/_/. using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// Animation Manager. /// Collect AnimationNode and PlayAnimation by Key. /// </summary> [ System.Serializable ] public class ViNoAnimationManager : MonoBehaviour { static private ViNoAnimationManager m_Instance; public static ViNoAnimationManager Instance { get { return ViNoAnimationManager.m_Instance; } } public string[] animNames; private AnimationNode[] animations; private Dictionary<string,int> m_AnimTable; void Awake(){ if( m_Instance == null ){ m_Instance = this; CollectAnimationNames(); } else{ Destroy( gameObject ); } } // Collect AnimationNodes in this object and this Children Components. public void CollectAnimationNames(){ m_AnimTable = new Dictionary<string,int>(); animations = GetComponentsInChildren<AnimationNode>(); List<string> animNameList = new List<string>(); for(int i=0;i<animations.Length;i++){ string key = animations[ i ].animationName; if( animations[ i ].enabled ){ if( animations[ i ].animTarget != null ){ if( ! string.IsNullOrEmpty( key ) ){ animNameList.Add( key ); m_AnimTable.Add( key , i ); } } /* else{ Debug.LogError( "animation Named: "+ key + " target not Set." ); } //*/ } } animNames = animNameList.ToArray(); } public void PlayAnimation( int index ){ ViNoDebugger.Log( "ANIMATION" , "Play Animation at Index: " + index.ToString() + "=" + animations[ index ].animationName ); animations[ index ].Preview(); } public AnimationNode PlayAnimation( string animName ){ if( m_AnimTable.ContainsKey( animName ) ){ int animationIndex = m_AnimTable[ animName ]; animations[ animationIndex ].Preview(); return animations[ animationIndex ]; } else{ return null; } } // if not found return -1. public int GetAnimationIDBy( string animName ){ for( int i=0;i<animNames.Length;i++){ if( animNames[ i ].Equals( animName ) ){ return i; } } return -1; } }
using MongoDB.Bson.Serialization.Attributes; namespace BillingTracker.Models { public class Cars { [BsonElement("Model")] public string Model { get; set; } [BsonElement("Make")] public string Make { get; set; } // [BsonElement("Car_bills")] // public CarBills Bills { get; set; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace EnterpriseDistributedApplication { [DataContract(Name = "Customer")] public class Customer { [DataMember(Name = "_id")] [BsonId] [BsonRepresentation(BsonType.ObjectId)] public string _id; [DataMember(Name = "Email")] public string Email { get; set; } [DataMember(Name = "Name")] public string Name { get; set; } [DataMember(Name = "Address")] public string Address { get; set; } [DataMember(Name = "Password")] public string Password { get; set; } public Customer(string email, string name, string address, string password) { _id = new ObjectId(DateTime.Now, Process.GetCurrentProcess().SessionId, (short)Process.GetCurrentProcess().Id, 1).ToJson(); Email = email; Name = name; Address = address; Password = password; } public Customer(string id, string email, string name, string address, string password) { _id = id; Email = email; Name = name; Address = address; } } }
namespace _10.HardSequenceOperaions { public class Operation { public Operation(int value, Operation previousOperation = null) { this.Value = value; this.PreviousOperation = previousOperation; } public int Value { get; private set; } public Operation PreviousOperation { get; set; } } }
using NSubstitute; using NUnit.Framework; using System; using TestDemo.Teleport; using UnityEngine; namespace TestDemo.Tests { public class PortalTests { [Test] public void TestInitialization() { // Arrange Portal portal = new GameObject().AddComponent<Portal>(); IPortalAnimator portalAnimator = Substitute.For<IPortalAnimator>(); ITeleportableDetector teleportableDetector = Substitute.For<ITeleportableDetector>(); IPortal pairedPortal = Substitute.For<IPortal>(); // Act portal.Initialize(portalAnimator, teleportableDetector, pairedPortal); // Assert Assert.IsFalse(portal.Enabled); Assert.AreEqual(pairedPortal, portal.PairedPortal); } [Test] public void TestEnable() { // Arrange Portal portal = new GameObject().AddComponent<Portal>(); IPortalAnimator portalAnimator = Substitute.For<IPortalAnimator>(); ITeleportableDetector teleportableDetector = Substitute.For<ITeleportableDetector>(); IPortal pairedPortal = Substitute.For<IPortal>(); pairedPortal.Enabled = false; // Act portal.Initialize(portalAnimator, teleportableDetector, pairedPortal); portal.Enabled = true; // Assert Assert.IsTrue(pairedPortal.Enabled); } [Test] public void TestDisable() { // Arrange Portal portal = new GameObject().AddComponent<Portal>(); IPortalAnimator portalAnimator = Substitute.For<IPortalAnimator>(); ITeleportableDetector teleportableDetector = Substitute.For<ITeleportableDetector>(); IPortal pairedPortal = Substitute.For<IPortal>(); pairedPortal.Enabled = true; // Act portal.Initialize(portalAnimator, teleportableDetector, pairedPortal); portal.Enabled = true; portal.Enabled = false; // Assert Assert.IsFalse(pairedPortal.Enabled); } [Test] public void TestDisableCycle() { // Arrange Portal portal = new GameObject().AddComponent<Portal>(); IPortalAnimator portalAnimator = Substitute.For<IPortalAnimator>(); ITeleportableDetector teleportableDetector = Substitute.For<ITeleportableDetector>(); IPortal pairedPortal = Substitute.For<IPortal>(); bool enabledWasSet = false; pairedPortal.Enabled = Arg.Do<bool>(x => { enabledWasSet = true; }); // Act portal.Initialize(portalAnimator, teleportableDetector, pairedPortal); portal.Enabled = false; // Assert Assert.IsFalse(enabledWasSet); } [Test] public void TestTeleportationOff() { // Arrange Portal portal = new GameObject().AddComponent<Portal>(); IPortalAnimator portalAnimator = Substitute.For<IPortalAnimator>(); ITeleportableDetector teleportableDetector = Substitute.For<ITeleportableDetector>(); IPortal pairedPortal = Substitute.For<IPortal>(); ITeleportable teleportable = Substitute.For<ITeleportable>(); Vector3? teleportationPosition = null; teleportable.TeleportTo(Arg.Do<Vector3>(x => { teleportationPosition = x; })); // Act portal.Initialize(portalAnimator, teleportableDetector, pairedPortal); teleportableDetector.OnEnter += Raise.Event<Action<ITeleportable>>(teleportable); // Assert Assert.IsNull(teleportationPosition); } [Test] public void TestTeleportationOn() { // Arrange Portal portal = new GameObject().AddComponent<Portal>(); IPortalAnimator portalAnimator = Substitute.For<IPortalAnimator>(); ITeleportableDetector teleportableDetector = Substitute.For<ITeleportableDetector>(); IPortal pairedPortal = Substitute.For<IPortal>(); pairedPortal.Postion.Returns(new Vector3(34f, 1111f, 1.2232f)); ITeleportable teleportable = Substitute.For<ITeleportable>(); Vector3? teleportationPosition = null; teleportable.TeleportTo(Arg.Do<Vector3>(x => { teleportationPosition = x; })); // Act portal.Initialize(portalAnimator, teleportableDetector, pairedPortal); portal.Enabled = true; teleportableDetector.OnEnter += Raise.Event<Action<ITeleportable>>(teleportable); // Assert Assert.AreEqual(pairedPortal.Postion, teleportationPosition); } [Test] public void TestAnimatorEnable() { Assert.Fail("The test is not implemented"); } [Test] public void TestAnimatorDisable() { Assert.Fail("The test is not implemented"); } [Test] public void TestAnimatorTeleportation() { Assert.Fail("The test is not implemented"); } // Event should be called when the object have been teleported [Test] public void TestTeleportEvent() { Assert.Fail("The test is not implemented"); } // When the object is teleported it should not be teleported back till it leaves portal [Test] public void TestTeleportCycle() { Assert.Fail("The test is not implemented"); } // When the object was teleported, left portal and enter again it should be teleported [Test] public void TestTeleportBack() { Assert.Fail("The test is not implemented"); } } }
using UnityEngine; using System.Collections; using UnityEngine.UI; public class Audio : MonoBehaviour { public static AudioSource component; void Start() { component = gameObject.GetComponent<AudioSource>(); InitialMessage.setInitialAudio(); } }
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; #nullable disable namespace API_Test.Models { public partial class project1Context : DbContext { public project1Context() { } public project1Context(DbContextOptions<project1Context> options) : base(options) { } public virtual DbSet<TblCart> TblCarts { get; set; } public virtual DbSet<TblCategory> TblCategories { get; set; } public virtual DbSet<TblOrder> TblOrders { get; set; } public virtual DbSet<TblProduct> TblProducts { get; set; } public virtual DbSet<TblRetailer> TblRetailers { get; set; } public virtual DbSet<TblUser> TblUsers { get; set; } public virtual DbSet<Tblcompare> Tblcompares { get; set; } public virtual DbSet<Tblwishlist> Tblwishlists { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration - see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263. optionsBuilder.UseSqlServer("Server=DESKTOP-UO1SOET;Database=project1;Trusted_Connection=True;"); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CI_AS"); modelBuilder.Entity<TblCart>(entity => { entity.HasKey(e => new { e.Cartid, e.Productid }) .HasName("PK__tblCart__73B74D1366A49963"); entity.ToTable("tblCart"); entity.Property(e => e.Cartid) .ValueGeneratedOnAdd() .HasColumnName("cartid"); entity.Property(e => e.Productid).HasColumnName("productid"); entity.Property(e => e.Cartquantity).HasColumnName("cartquantity"); entity.Property(e => e.Useremail) .HasMaxLength(255) .HasColumnName("useremail"); entity.HasOne(d => d.Product) .WithMany(p => p.TblCarts) .HasForeignKey(d => d.Productid) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__tblCart__product__44FF419A"); entity.HasOne(d => d.UseremailNavigation) .WithMany(p => p.TblCarts) .HasForeignKey(d => d.Useremail) .HasConstraintName("FK__tblCart__userema__440B1D61"); }); modelBuilder.Entity<TblCategory>(entity => { entity.HasKey(e => e.Categoryid) .HasName("PK__tblCateg__23CDE59029DDFFB9"); entity.ToTable("tblCategory"); entity.Property(e => e.Categoryid).HasColumnName("categoryid"); entity.Property(e => e.Categorydescription).HasColumnName("categorydescription"); entity.Property(e => e.Categoryname) .IsRequired() .HasColumnName("categoryname"); }); modelBuilder.Entity<TblOrder>(entity => { entity.HasKey(e => new { e.Orderid, e.Productid }) .HasName("PK__tblOrder__3ADF45A6D3CF4E4F"); entity.ToTable("tblOrder"); entity.Property(e => e.Orderid) .ValueGeneratedOnAdd() .HasColumnName("orderid"); entity.Property(e => e.Productid).HasColumnName("productid"); entity.Property(e => e.Orderdate) .IsRequired() .HasColumnName("orderdate"); entity.Property(e => e.Orderquantity).HasColumnName("orderquantity"); entity.Property(e => e.Retailerid).HasColumnName("retailerid"); entity.Property(e => e.Useremail) .HasMaxLength(255) .HasColumnName("useremail"); entity.HasOne(d => d.Product) .WithMany(p => p.TblOrders) .HasForeignKey(d => d.Productid) .OnDelete(DeleteBehavior.ClientSetNull) .HasConstraintName("FK__tblOrder__produc__48CFD27E"); entity.HasOne(d => d.Retailer) .WithMany(p => p.TblOrders) .HasForeignKey(d => d.Retailerid) .HasConstraintName("FK__tblOrder__retail__49C3F6B7"); entity.HasOne(d => d.UseremailNavigation) .WithMany(p => p.TblOrders) .HasForeignKey(d => d.Useremail) .HasConstraintName("FK__tblOrder__userem__47DBAE45"); }); modelBuilder.Entity<TblProduct>(entity => { entity.HasKey(e => e.Productid) .HasName("PK__tblProdu__2D172D32307A0AB4"); entity.ToTable("tblProduct"); entity.Property(e => e.Productid).HasColumnName("productid"); entity.Property(e => e.Categoryid).HasColumnName("categoryid"); entity.Property(e => e.Productbrand) .HasMaxLength(45) .IsUnicode(false) .HasColumnName("productbrand"); entity.Property(e => e.Productdescription).HasColumnName("productdescription"); entity.Property(e => e.Productimage1).HasColumnName("productimage1"); entity.Property(e => e.Productname) .HasMaxLength(40) .HasColumnName("productname"); entity.Property(e => e.Productprice).HasColumnName("productprice"); entity.Property(e => e.Productquantity).HasColumnName("productquantity"); entity.Property(e => e.Retailerid).HasColumnName("retailerid"); entity.HasOne(d => d.Category) .WithMany(p => p.TblProducts) .HasForeignKey(d => d.Categoryid) .HasConstraintName("FK__tblProduc__categ__412EB0B6"); entity.HasOne(d => d.Retailer) .WithMany(p => p.TblProducts) .HasForeignKey(d => d.Retailerid) .HasConstraintName("FK__tblProduc__retai__403A8C7D"); }); modelBuilder.Entity<TblRetailer>(entity => { entity.HasKey(e => e.Retailerid) .HasName("PK__tblRetai__7A12C3E0C1F19F0C"); entity.ToTable("tblRetailer"); entity.HasIndex(e => e.Retaileremail, "UQ__tblRetai__F3B103331D9BAEE1") .IsUnique(); entity.Property(e => e.Retailerid).HasColumnName("retailerid"); entity.Property(e => e.Approved) .HasColumnName("approved") .HasDefaultValueSql("((0))"); entity.Property(e => e.Retaileremail) .IsRequired() .HasMaxLength(40) .HasColumnName("retaileremail"); entity.Property(e => e.Retailername) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("retailername"); entity.Property(e => e.Retailerpassword) .IsRequired() .HasMaxLength(40) .HasColumnName("retailerpassword"); }); modelBuilder.Entity<TblUser>(entity => { entity.HasKey(e => e.Useremail) .HasName("PK__tblUser__870EAE607FEF69ED"); entity.ToTable("tblUser"); entity.HasIndex(e => e.Userphone, "UQ__tblUser__310EC0A112003C3F") .IsUnique(); entity.Property(e => e.Useremail) .HasMaxLength(255) .HasColumnName("useremail"); entity.Property(e => e.Userapartment) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("userapartment"); entity.Property(e => e.Usercountry) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("usercountry"); entity.Property(e => e.Username) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("username"); entity.Property(e => e.Userpassword) .IsRequired() .HasColumnName("userpassword"); entity.Property(e => e.Userphone) .IsRequired() .HasMaxLength(15) .IsUnicode(false) .HasColumnName("userphone"); entity.Property(e => e.Userpincode) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("userpincode"); entity.Property(e => e.Userstate) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("userstate"); entity.Property(e => e.Userstreet) .HasMaxLength(40) .IsUnicode(false) .HasColumnName("userstreet"); entity.Property(e => e.Usertown) .IsRequired() .HasMaxLength(40) .IsUnicode(false) .HasColumnName("usertown"); }); modelBuilder.Entity<Tblcompare>(entity => { entity.HasKey(e => e.Compareid) .HasName("PK__tblcompa__6C2D579E3A9DF488"); entity.ToTable("tblcompare"); entity.Property(e => e.Compareid).HasColumnName("compareid"); entity.Property(e => e.Productid).HasColumnName("productid"); entity.Property(e => e.Useremail) .HasMaxLength(255) .HasColumnName("useremail"); entity.HasOne(d => d.Product) .WithMany(p => p.Tblcompares) .HasForeignKey(d => d.Productid) .HasConstraintName("FK__tblcompar__produ__71D1E811"); entity.HasOne(d => d.UseremailNavigation) .WithMany(p => p.Tblcompares) .HasForeignKey(d => d.Useremail) .HasConstraintName("FK__tblcompar__usere__70DDC3D8"); }); modelBuilder.Entity<Tblwishlist>(entity => { entity.HasKey(e => e.Wishid) .HasName("PK__tblwishl__D2E049D1553A0966"); entity.ToTable("tblwishlist"); entity.Property(e => e.Wishid).HasColumnName("wishid"); entity.Property(e => e.Productid).HasColumnName("productid"); entity.Property(e => e.Useremail) .HasMaxLength(255) .HasColumnName("useremail"); entity.HasOne(d => d.Product) .WithMany(p => p.Tblwishlists) .HasForeignKey(d => d.Productid) .HasConstraintName("FK__tblwishli__produ__75A278F5"); entity.HasOne(d => d.UseremailNavigation) .WithMany(p => p.Tblwishlists) .HasForeignKey(d => d.Useremail) .HasConstraintName("FK__tblwishli__usere__74AE54BC"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; namespace Model { /// <summary> /// /// </summary> public class Sys_RoleModel { #region private string _Id; [DisplayName("")] public string Id { get { return this._Id; } set { this._Id = value; } } #endregion #region 角色名称 private string _Name; [DisplayName("角色名称")] public string Name { get { return this._Name; } set { this._Name = value; } } #endregion #region 备注 private string _Memo; [DisplayName("备注")] public string Memo { get { return this._Memo; } set { this._Memo = value; } } #endregion #region 操作日期 private DateTime _PubDate; [DisplayName("操作日期")] public DateTime PubDate { get { return this._PubDate; } set { this._PubDate = value; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SFP.SIT.SERV.Model.RESP { public class SIT_RESP_RESPUESTA { public Int64 repcantidad { set; get; } public int? megclave { set; get; } public Int64? docclave { set; get; } public string repoficio { set; get; } public DateTime repedofec { set; get; } public int? rtpclave { set; get; } public Int64 repclave { set; get; } public SIT_RESP_RESPUESTA () {} } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace IBM.HybridRelayPlugin.Relay { using Microsoft.Xrm.Sdk; using System; using System.Threading.Tasks; /// <summary> /// The SharedAccessSignatureTokenProvider generates tokens using a shared access key or existing signature. /// </summary> public class SharedAccessSignatureTokenProvider : TokenProvider { private readonly byte[] _encodedSharedAccessKey; private readonly string _keyName; private readonly string _sharedAccessSignature; static IOrganizationService OrganizationService { get; set; } public SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey) : this(keyName, sharedAccessKey, MessagingTokenProviderKeyEncoder, OrganizationService) { } protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, Func<string, byte[]> customKeyEncoder, IOrganizationService orgService) { OrganizationService = orgService; if (string.IsNullOrEmpty(keyName) || string.IsNullOrEmpty(sharedAccessKey)) { throw new ArgumentNullException(nameof(keyName)); } if (keyName.Length > SharedAccessSignatureToken.MaxKeyNameLength) { throw new ArgumentOutOfRangeException(); } if (sharedAccessKey.Length > SharedAccessSignatureToken.MaxKeyLength) { throw new ArgumentOutOfRangeException(); } _keyName = keyName; _encodedSharedAccessKey = customKeyEncoder != null ? customKeyEncoder(sharedAccessKey) : MessagingTokenProviderKeyEncoder(sharedAccessKey); } protected override Task<SharedAccessSignatureToken> OnGetTokenAsync(string resource, TimeSpan validFor) { string tokenString = this.BuildSignature(resource, validFor); var securityToken = new SharedAccessSignatureToken(tokenString, OrganizationService); return Task.FromResult(securityToken); } protected virtual string BuildSignature(string resource, TimeSpan validFor) { if (string.IsNullOrWhiteSpace(_sharedAccessSignature)) { return SharedAccessSignatureBuilder.BuildSignature(_keyName, _encodedSharedAccessKey, resource, validFor); } return _sharedAccessSignature; } } }
#region Copyright (C) // --------------------------------------------------------------------------------------------------------------- // <copyright file="ManagementForm.cs" company="Smurf-IV"> // // Copyright (C) 2011-2012 Smurf-IV // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <summary> // Url: http://amalgam.codeplex.com // Email: http://www.codeplex.com/site/users/view/smurfiv // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion using System; using System.Diagnostics; using System.IO; using System.Windows.Forms; using System.Xml.Serialization; using AmalgamClientTray.Dokan; using NLog; using Shared; using Starksoft.Net.Ftp; namespace AmalgamClientTray.ClientForms { public partial class ManagementForm : Form { static private readonly Logger Log = LogManager.GetCurrentClassLogger(); private ClientPropertiesDisplay cpd; internal static readonly string userAppData = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"AmalgamClientTray"); internal static readonly string configFile = Path.Combine(userAppData, @"Client.Properties.config.xml"); private ClientConfigDetails csd; private ClientConfigDetails ClientConfigDetails { get { return csd; } set { csd = value; if (csd.SharesToRestore.Count == 0) csd.SharesToRestore.Add(new ClientShareDetail()); cpd = new ClientPropertiesDisplay(csd.SharesToRestore[0]); propertyGrid1.SelectedObject = cpd; propertyGrid1.Refresh(); } } public ManagementForm() { InitializeComponent(); WindowLocation.GeometryFromString(Properties.Settings.Default.WindowLocation, this); FileInfo fi = new FileInfo(configFile); if (!fi.Exists) { DirectoryInfo di = fi.Directory; if (!di.Exists) di.Create(); // The file will now be created when the ReadConfig is called } ReadConfigDetails(out csd); ClientConfigDetails = csd; } private void ManagementForm_Load(object sender, EventArgs e) { // Stolen from Utils try { System.Reflection.PropertyInfo pi = propertyGrid1.GetType().GetProperty("Controls"); Control.ControlCollection cc = (Control.ControlCollection)pi.GetValue(propertyGrid1, null); foreach (Control c in cc) { Type ct = c.GetType(); string sName = ct.Name; if (sName == "DocComment") { pi = ct.GetProperty("Lines"); if (pi != null) { #pragma warning disable 168 int i = (int)pi.GetValue(c, null); #pragma warning restore 168 pi.SetValue(c, 6, null); } if (ct.BaseType != null) { System.Reflection.FieldInfo fi = ct.BaseType.GetField("userSized", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic); if (fi != null) fi.SetValue(c, true); } break; } } } catch( Exception ex ) { Log.WarnException("ManagementForm_Load", ex); } } #region Button Actions private void btnConnect_Click(object sender, EventArgs e) { string help = null, system = null, status = null; try { UseWaitCursor = true; Enabled = false; // create a new ftpclient object with the host and port number to use using (FtpClient ftp = new FtpClient(cpd.TargetMachineName, cpd.Port, cpd.SecurityProtocol)) { ftp.Open(cpd.UserName, cpd.Password); // ftp.IsConnected; help = ftp.GetHelp(); system = ftp.GetSystemType(); status = ftp.GetStatus(); ftp.Close(); } btnSave.Enabled = true; } catch (Exception ex) { Log.ErrorException("btnConnect_Click", ex); MessageBoxExt.Show(this, ex.Message, "Failed to contact Target", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { UseWaitCursor = false; Enabled = true; } if (!string.IsNullOrWhiteSpace(help)) { MessageBoxExt.Show(this, string.Format("Help: {0}\nSystem: {1}\nStatus: {2}", help, system, status), @"Target server information", MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void btnSave_Click(object sender, EventArgs e) { try { UseWaitCursor = true; Enabled = false; Log.Info("Get the details from the page into the share object"); csd.SharesToRestore[0].TargetMachineName = cpd.TargetMachineName; csd.SharesToRestore[0].Port = cpd.Port; csd.SharesToRestore[0].SecurityProtocol = cpd.SecurityProtocol; csd.SharesToRestore[0].UserName = cpd.UserName; csd.SharesToRestore[0].Password = cpd.Password; csd.SharesToRestore[0].TargetShareName = cpd.TargetShareName; string oldDriveLetter = csd.SharesToRestore[0].DriveLetter; csd.SharesToRestore[0].DriveLetter = cpd.DriveLetter; csd.SharesToRestore[0].VolumeLabel = cpd.VolumeLabel; csd.SharesToRestore[0].BufferWireTransferSize = cpd.BufferWireTransferSize; csd.SharesToRestore[0].CacheFileMaxSize = cpd.CacheFileMaxSize; csd.SharesToRestore[0].CacheInfoExpireSeconds = cpd.CacheInfoExpireSeconds; csd.SharesToRestore[0].FileNamesToIgnore = cpd.FileNamesToIgnore; csd.SharesToRestore[0].DokanThreadCount = cpd.DokanThreadCount; csd.SharesToRestore[0].DokanDebugMode = cpd.DokanDebugMode; csd.SharesToRestore[0].ApplicationLogLevel = cpd.ApplicationLogLevel; csd.SharesToRestore[0].TargetIsReadonly = cpd.TargetIsReadonly; csd.SharesToRestore[0].IgnoreSetTimeStampFailure = cpd.IgnoreSetTimeStampFailure; csd.SharesToRestore[0].TargetRequiresSplitDirs = cpd.TargetRequiresSplitDirs; Log.Info("Write the values to the Service config file"); WriteOutConfigDetails(csd); if (DialogResult.Yes == MessageBoxExt.Show(this, "This is about to stop then start the \"Share Enabler Service\".\nDo you want to this to happen now ?", "Stop then Start the Service Now..", MessageBoxButtons.YesNo, MessageBoxIcon.Question)) { try { Log.Info("Now toggle the service"); if (Handlers.ClientMappings.ContainsKey(oldDriveLetter)) { if (Handlers.ClientMappings[oldDriveLetter].Stop()) Handlers.ClientMappings.Remove(oldDriveLetter); } HandleMappingThread newMapping = new HandleMappingThread(); Handlers.ClientMappings[csd.SharesToRestore[0].DriveLetter] = newMapping; newMapping.Start(csd.SharesToRestore[0]); } catch (Exception ex) { Log.ErrorException("btnSend_Click", ex); MessageBoxExt.Show(this, ex.Message, "Failed, Check the logs", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } finally { UseWaitCursor = false; Enabled = true; } } private void btnLogView_Click(object sender, EventArgs e) { try { OpenFileDialog openFileDialog = new OpenFileDialog { InitialDirectory = Path.Combine(userAppData, @"Logs"), Filter = "Log files (*.log)|*.log|Archive logs (*.*)|*.*", FileName = "*.log", FilterIndex = 2, Title = "Select name to view contents" }; if (openFileDialog.ShowDialog() == DialogResult.OK) { Process word = Process.Start("Wordpad.exe", '"' + openFileDialog.FileName + '"'); if (word != null) { word.WaitForInputIdle(); SendKeys.SendWait("^{END}"); } } } catch (Exception ex) { Log.ErrorException("OpenFile has an exception: ", ex); MessageBoxExt.Show(this, ex.Message, "Failed to open the client log view", MessageBoxButtons.OK, MessageBoxIcon.Error); } } #endregion private void ManagementForm_Shown(object sender, EventArgs e) { try { ReadConfigDetails( out csd); ClientConfigDetails = csd; } catch (Exception ex) { Log.ErrorException("Unable to ReadConfigDetails", ex); } } internal static void ReadConfigDetails( out ClientConfigDetails csd) { csd = null; try { // Initialise a default to allow type get ! csd = new ClientConfigDetails(); XmlSerializer x = new XmlSerializer(csd.GetType()); Log.Info("Attempting to read ClientConfigDetails from: [{0}]", configFile); using (TextReader textReader = new StreamReader(configFile)) { csd = x.Deserialize(textReader) as ClientConfigDetails; } } catch (Exception ex) { Log.ErrorException("Cannot read the configDetails: ", ex); csd = null; } finally { if (csd == null) { Log.Info("Creating new ClientConfigDetails"); csd = new ClientConfigDetails(); try { if (File.Exists(configFile)) File.Move(configFile, configFile + Guid.NewGuid()); } catch( Exception ex ) { Log.WarnException("ReadConfigDetails", ex); } WriteOutConfigDetails( csd); } } } private static void WriteOutConfigDetails( ClientConfigDetails csd) { if (csd != null) try { XmlSerializer x = new XmlSerializer(csd.GetType()); using (TextWriter textWriter = new StreamWriter(configFile)) { x.Serialize(textWriter, csd); } } catch (Exception ex) { Log.ErrorException("Cannot save configDetails: ", ex); } } private void ManagementForm_FormClosing(object sender, FormClosingEventArgs e) { // persist our geometry string. Properties.Settings.Default.WindowLocation = WindowLocation.GeometryToString(this); Properties.Settings.Default.Save(); } } }
using System; using System.Collections.Generic; using System.IO; using Common; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; namespace Redux.Controllers { [Produces("application/json")] [Route("api/[controller]")] public class BuildsController : Controller { // GET api/builds [HttpGet] //[Authorize(Roles = "User")] public object GetBuilds(int page = 1, int pageSize = 100, string sort = "rating") { int total = (int)Program.Control.Builds.Count; dynamic rows = Program.Control.Builds.GetBuilds(page, pageSize, sort); return new Dictionary<string, object> { { "total", total }, { "page", page }, { "pageCount", total / pageSize + 1 }, { "pageSize", pageSize }, { "rows", rows } }; } // POST api/builds [HttpPost] //[Authorize(Roles = "User")] public object Submit() { try { StreamReader reader = new StreamReader(Request.Body); JObject obj = JObject.Parse(reader.ReadToEnd()); Program.Control.Builds.Submit(obj); } catch (Exception ex) { Logger.WriteToTrace($"Ошибка при добавлении билда: {ex}", TraceMessageKind.Error); } return null; } // POST api/builds/vote [HttpPost("vote")] //[Authorize(Roles = "User")] public void Vote() { try { StreamReader reader = new StreamReader(Request.Body); JObject obj = JObject.Parse(reader.ReadToEnd()); Program.Control.Builds.Vote(obj); } catch (Exception ex) { Logger.WriteToTrace($"Ошибка при голосовании за билд: {ex}", TraceMessageKind.Error); } } // POST api/builds/favorite [HttpPost("favorite")] //[Authorize(Roles = "User")] public void AddToFavorite() { try { StreamReader reader = new StreamReader(Request.Body); JObject obj = JObject.Parse(reader.ReadToEnd()); Program.Control.Builds.Favorites(obj); } catch (Exception ex) { Logger.WriteToTrace($"Ошибка при добавлении в избранное: {ex}", TraceMessageKind.Error); } } } }
using BigEndian.IO; namespace nuru.IO.NUI.Cell.Metadata { public interface IMetadataWriter { void Write(BigEndianBinaryWriter writer, ushort metadata); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ParejasCartas_UI.Utils { public class clsTablero { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class AnimationsMG : MonoBehaviour { public Animator animator; string _currentDirection = "right"; //EFECTOS public GameObject sangre; public GameObject polv; //----AGUA public GameObject splash; bool inwater; public GameObject Ondas; public Transform PasoD; public Transform PasoI; public GameObject pasopolvo; public GameObject pasopolvo2; public GameObject strike; public GameObject strikearma; public GameObject strikeescopeta; public GameObject strikegun; public Transform strikeSpawn; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(animator.GetCurrentAnimatorStateInfo(0).IsName("paracaidasS")) { animator.SetBool("paracaidas", true); }else { animator.SetBool("paracaidas", false); } //QUIETO AL AZAR if(animator.GetCurrentAnimatorStateInfo(0).IsName("MGNormal")) { animator.SetBool("walking", false); animator.SetBool("paracaidas", false); } if(animator.GetCurrentAnimatorStateInfo(0).IsName("walk")) { animator.SetBool("walking", true); } if(animator.GetCurrentAnimatorStateInfo(0).IsName("paracaidasS")) { animator.SetBool("paracaidas", true); } //MUERTE if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillSimple") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillSimple2") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillBackJump") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillEX") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillEX2") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillQuemado")) { animator.SetBool("muerto", true); animator.SetInteger("muerte", 0); gameObject.layer = LayerMask.NameToLayer("muerto"); //gameObject.tag = "Untagged"; } if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillSimple3")) { animator.SetBool("muerto", true); animator.SetBool("headShot", false); gameObject.layer = LayerMask.NameToLayer("muerto"); //gameObject.tag = "Untagged"; } if(animator.GetCurrentAnimatorStateInfo(0).IsName("KillKnife") || animator.GetCurrentAnimatorStateInfo(0).IsName("KillKnife2")) { animator.SetBool("muerto", true); animator.SetBool("acuchillado", false); animator.SetInteger("muerte", 0); } //CASCADO if(animator.GetCurrentAnimatorStateInfo(0).IsName("Hit") || animator.GetCurrentAnimatorStateInfo(0).IsName("HitKnife")|| animator.GetCurrentAnimatorStateInfo(0).IsName("MGHit")) { animator.SetBool("walk", false); animator.SetInteger("cascado", 0); } if(inwater) { Ondass.activas = true; Ondas.SetActive(true); }else { Ondass.activas = false; Ondas.SetActive(false); } } void OnTriggerEnter (Collider col) { if(col.gameObject.tag == "Water") { if(GetComponent<Rigidbody>().velocity.y <= -4f) { var efect = (GameObject)Instantiate(splash, new Vector3(PasoD.transform.position.x, col.gameObject.transform.position.y+0.1f, PasoD.transform.position.z), Quaternion.Euler(90,0,0)); } Ondass.posOndas = col.gameObject.transform.position.y; inwater = true; } } void OnTriggerExit (Collider col) { if(col.gameObject.tag == "Water") { if(GetComponent<Rigidbody>().velocity.y >= 4f) { var efect = (GameObject)Instantiate(splash, new Vector3(PasoD.transform.position.x, col.gameObject.transform.position.y+0.1f, PasoD.transform.position.z), Quaternion.Euler(90,0,0)); } inwater = false; } } //EVENTOS SPINE void blood () { if(PlayerPrefs.GetInt("violencia") == 1) { var efect = (GameObject)Instantiate(sangre, transform.position, transform.rotation); } } void muerto () { Destroy(gameObject); } void polvo () { if(!inwater) { var efect = (GameObject)Instantiate(polv, transform.position, transform.rotation); Destroy(efect, 1.0f); } } void paso() { if(!inwater) { var efect = (GameObject)Instantiate(pasopolvo, PasoD.transform.position, PasoD.transform.rotation); }else { var efect = (GameObject)Instantiate(splash, transform.position, transform.rotation); } } void paso2() { if(!inwater) { var efect = (GameObject)Instantiate(pasopolvo2, PasoI.transform.position, PasoI.transform.rotation); }else { var efect = (GameObject)Instantiate(splash, transform.position, transform.rotation); } } void rafaga () { if(transform.localScale.x == 1) { var efect = (GameObject)Instantiate(strike, strikeSpawn.transform.position, transform.rotation); }else { var efect = (GameObject)Instantiate(strike, strikeSpawn.transform.position, Quaternion.Euler(0,0,strikeSpawn.transform.rotation.z-180)); } } void rafagaarma () { if(transform.localScale.x == 1) { var efect = (GameObject)Instantiate(strikearma, strikeSpawn.transform.position, strikeSpawn.rotation); }else { var efect = (GameObject)Instantiate(strikearma, strikeSpawn.transform.position, Quaternion.Euler(0,0,strikeSpawn.transform.rotation.z-180)); } } void rafagaarmametra () { if(transform.localScale.x == 1) { var efect = (GameObject)Instantiate(strikearma, strikeSpawn.transform.position, Quaternion.Euler(0,0,strikeSpawn.transform.rotation.z)); }else { var efect = (GameObject)Instantiate(strikearma, strikeSpawn.transform.position, Quaternion.Euler(0,0,strikeSpawn.transform.rotation.z-180)); } //var efect = (GameObject)Instantiate(strikearma, strikeSpawn.transform.position, strikeSpawn.rotation); } void rafagagun () { if(transform.localScale.x == 1) { var efect = (GameObject)Instantiate(strikegun, strikeSpawn.transform.position,strikeSpawn.rotation); }else { var efect = (GameObject)Instantiate(strikegun, strikeSpawn.transform.position, Quaternion.Euler(0,0,strikeSpawn.transform.rotation.z-180)); } } void rafagaescopeta () { if(transform.localScale.x == 1) { var efect = (GameObject)Instantiate(strikeescopeta, strikeSpawn.transform.position, strikeSpawn.rotation); }else { var efect = (GameObject)Instantiate(strikeescopeta, strikeSpawn.transform.position, Quaternion.Euler(0,0,strikeSpawn.transform.rotation.z-180)); } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; namespace Grisaia.Categories.Sprites { /// <summary> /// The interface for all sprite elements contained by <see cref="ISpriteCategory"/>'s. /// </summary> public interface ISpriteElement { #region Properties /// <summary> /// Gets the Id of the sprite element. /// </summary> object Id { get; } #endregion } /// <summary> /// The interface for all <see cref="ISpriteElement"/> containers. /// </summary> public interface ISpriteCategory : ISpriteElement, IEnumerable { #region Properties /// <summary> /// Gets the sprite category entry for this category. /// </summary> SpriteCategoryInfo Category { get; } /// <summary> /// Gets the sorted list of elements in the category. /// </summary> IReadOnlyList<ISpriteElement> List { get; } /// <summary> /// Gets the number of elements in the category. /// </summary> int Count { get; } /// <summary> /// Gets if this category is the last category and contains sprite part lists. /// </summary> bool IsLastCategory { get; } /// <summary> /// Gets the display name of the category. /// </summary> string DisplayName { get; } #endregion #region Accessors /*/// <summary> /// Gets the element at the specified index in the category. /// </summary> /// <param name="index">The index of the element to get.</param> /// <returns>The element at the specified index.</returns> ISpriteElement this[int index] { get; }*/ /// <summary> /// Gets the element with the specified Id in the category. /// </summary> /// <param name="id">The Id of the element to get.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="id"/> is null. /// </exception> /// <exception cref="KeyNotFoundException"> /// The element with the <paramref name="id"/> was not found. /// </exception> ISpriteElement this[object id] { get; } /*/// <summary> /// Gets the element with the specified Id in the category. /// </summary> /// <param name="id">The Id of the element to get.</param> /// <returns>The element with the specified Id.</returns> /// /// <exception cref="KeyNotFoundException"> /// The element with the <paramref name="id"/> was not found. /// </exception> ISpriteElement Get(object id);*/ /// <summary> /// Tries to get the element with the specified Id in the category. /// </summary> /// <param name="id">The Id of the element to get.</param> /// <param name="value">The output element if one was found, otherwise null.</param> /// <returns>True if an element with the Id was found, otherwise null.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="id"/> is null. /// </exception> bool TryGetValue(object id, out ISpriteElement value); /// <summary> /// Tries to get the category with the specified Id in the category. /// </summary> /// <param name="id">The Id of the category to get.</param> /// <param name="value">The output category if one was found, otherwise null.</param> /// <returns>True if a category with the Id was found, otherwise null.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="id"/> is null. /// </exception> bool TryGetValue(object id, out ISpriteCategory value); /// <summary> /// Tries to get the part list with the specified Id in the category. /// </summary> /// <param name="id">The Id of the part list to get.</param> /// <param name="value">The output part list if one was found, otherwise null.</param> /// <returns>True if a part list with the Id was found, otherwise null.</returns> bool TryGetValue(int id, out ISpritePartList value); /// <summary> /// Gets if the category contains an element with the specified Id. /// </summary> /// <param name="id">The Id to check for an element with.</param> /// <returns>True if an element exists with the specified Id, otherwise null.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="id"/> is null. /// </exception> bool ContainsKey(object id); #endregion #region CreateGroups /// <summary> /// Creates sprite part groups used to categorize the sprite parts during selection. /// </summary> /// <param name="game">The game info associated with this sprite category.</param> /// <param name="character">The character info associated with this sprite category.</param> /// <returns>An array of sprite part groups for use in sprite part selection.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="game"/> or <paramref name="character"/> is null. /// </exception> ISpritePartGroup[] CreateGroups(GameInfo game, CharacterInfo character); #endregion } /// <summary> /// The additional interface for the game <see cref="ISpriteCategory"/>. /// </summary> public interface ISpriteGame : ISpriteCategory, INotifyPropertyChanged { /// <summary> /// Gets the index of the game info in the database. /// </summary> int GameIndex { get; } /// <summary> /// Gets the game info associated with this category. /// </summary> GameInfo GameInfo { get; } } /// <summary> /// The additional interface for the character <see cref="ISpriteCategory"/>. /// </summary> public interface ISpriteCharacter : ISpriteCategory, INotifyPropertyChanged { /// <summary> /// Gets the character info associated with this category. /// </summary> CharacterInfo CharacterInfo { get; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using Kers.Models.Abstract; using Kers.Models.Contexts; using Kers.Models.Entities.KERScore; using Kers.Models.Entities.KERSmain; using Kers.Models.Repositories; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using SkiaSharp; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.Caching.Distributed; using System.Text.RegularExpressions; namespace Kers.Controllers { [Route("api/[controller]")] public class PdfLadderController : PdfBaseController { const int width = 792; const int height = 612; const int margin = 42; const int textLineHeight = 14; int[] trainingsTableLines = new int[]{ 0, 100, 143, 440, 500, 530}; int trainingsTableLineHight = 14; int trainingsTableCellMargin = 2; string pageTitle = "Professional Career Ladder Promotion Application"; IFiscalYearRepository _fiscalYearRepo; public PdfLadderController( KERScoreContext _context, IKersUserRepository userRepo, KERSmainContext mainContext, IMemoryCache _cache, IFiscalYearRepository _fiscalYearRepo ): base(_context, userRepo, mainContext, _cache){ this._fiscalYearRepo = _fiscalYearRepo; } [HttpGet("application/{id}")] public IActionResult Application(int id) { using (var stream = new SKDynamicMemoryWStream ()) using (var document = SKDocument.CreatePdf (stream, this.metadata( "Kers, Career Ladder, Reporting", "Career Ladder Application", "Professional Career Ladder Promotion Application") )) { var application = _context.LadderApplication .Where(a => a.Id == id) .Include( a => a.KersUser).ThenInclude( u => u.RprtngProfile).ThenInclude( u => u.PlanningUnit).ThenInclude( n => n.ExtensionArea) .Include( a => a.KersUser).ThenInclude( u => u.PersonalProfile) .Include( a => a.KersUser).ThenInclude( u => u.Specialties ).ThenInclude( s => s.Specialty) .Include( a => a.LadderLevel) .Include( a => a.LadderEducationLevel) .Include( a => a.Images).ThenInclude( i => i.UploadImage) .Include( a => a.Stages).ThenInclude( s => s.LadderStage) .Include( a => a.Stages).ThenInclude( s => s.KersUser ).ThenInclude( u => u.RprtngProfile) .Include( a => a.Ratings) .FirstOrDefault(); if( application != null){ var pdfCanvas = document.BeginPage(height, width); var pageNum = 1; AddPageInfo(pdfCanvas, pageNum, 0, application.KersUser, DateTime.Now, pageTitle); var positionX = margin; var runningY = 31; AddUkLogo(pdfCanvas, 16, runningY); pdfCanvas.DrawText("Professional Career Ladder", 223, 62, getPaint(20.0f, 1)); pdfCanvas.DrawText("Promotion Application", 223, 82, getPaint(20.0f, 1)); pdfCanvas.DrawText("For Outstanding Job Performance and Experiences Gained Through Program Development", 223, 95, getPaint(7.5f)); runningY += 115; pdfCanvas.DrawText(application.KersUser.PersonalProfile.FirstName + " " +application.KersUser.PersonalProfile.LastName, positionX, runningY, getPaint(18f, 1)); var textCounty = application.KersUser.RprtngProfile.PlanningUnit.Name; if( textCounty.Count() > 15 ){ textCounty = textCounty.Substring(0, application.KersUser.RprtngProfile.PlanningUnit.Name.Count() - 11); } pdfCanvas.DrawText("County: " + textCounty, 350, runningY - 5, getPaint(10f)); var textArea = ""; if( application.KersUser.RprtngProfile.PlanningUnit.ExtensionArea != null){ textArea = application.KersUser.RprtngProfile.PlanningUnit.ExtensionArea.Name; } pdfCanvas.DrawText("Extension Area: " + textArea, 350, runningY + 10, getPaint(10f)); var rightColumnY = 191; pdfCanvas.DrawText("Performance Ratings: ", 350, rightColumnY, getPaint(10.0f, 1)); foreach( var rtng in application.Ratings){ rightColumnY += textLineHeight; pdfCanvas.DrawText(rtng.Year + ": " + rtng.Ratting, 350, rightColumnY, getPaint(10.0f)); } runningY += 12; pdfCanvas.DrawText("UK/person ID: " + application.KersUser.RprtngProfile.PersonId, positionX, runningY, getPaint(8.5f)); runningY += 32; pdfCanvas.DrawText("Start Date: " + application.StartDate.ToString("MM/dd/yyyy"), positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Number of years of Extension service: " + application.NumberOfYears, positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Program Area/Responsibility: ", positionX, runningY, getPaint(10.0f)); foreach( var spclty in application.KersUser.Specialties){ runningY += textLineHeight; pdfCanvas.DrawText(spclty.Specialty.Name, positionX, runningY, getPaint(10.0f, 3)); } runningY += 28; pdfCanvas.DrawText("Track: " + (application.Track == 0 ? 'A' : 'B'), positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Promotion to Level: " + application.LadderLevel.Name, positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Date of last Career Ladder Promotion: " + application.LastPromotion.ToString("MM/dd/yyyy"), positionX, runningY, getPaint(10.0f)); runningY += textLineHeight * 2; pdfCanvas.DrawText("Highest level of education: " + application.LadderEducationLevel.Name, positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Program of Study: " + application.ProgramOfStudy, positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Evidence of Further Professional or academic Training: " , positionX, runningY, getPaint(10.0f)); var evedenceLines = SplitLineToMultiline( StripHTML(application.Evidence), 120); foreach( var evd in evedenceLines ){ runningY += textLineHeight; pdfCanvas.DrawText(evd , positionX, runningY, getPaint(10.0f, 3)); } document.EndPage(); // !!!!!!!!!!!!!!!!!!! Refine actual start of the year !!!!!!!!!!!!!!!!!! var fiscalYear = this._fiscalYearRepo.byDate(application.Created, FiscalYearType.ServiceLog); var startOfTheYear = new DateTime( fiscalYear.End.Year, 1, 1); var startOfTheYearOfTheLastPromotion = new DateTime(application.LastPromotion.Year, 1, 1); var trainings = TrainingsByUser(application.KersUserId, startOfTheYearOfTheLastPromotion, startOfTheYear); var hours = HourssByUser(application.KersUserId, startOfTheYearOfTheLastPromotion, startOfTheYear); var coreHours = HourssByUser(application.KersUserId, startOfTheYearOfTheLastPromotion, startOfTheYear, true); pdfCanvas = document.BeginPage(height, width); pageNum++; runningY = margin + 5; AddPageInfo(pdfCanvas, pageNum, 0, application.KersUser, DateTime.Now, pageTitle); pdfCanvas.DrawText("InService Hours Earned from " + startOfTheYearOfTheLastPromotion.ToString("MM/dd/yyyy") + " till " + startOfTheYear.ToString("MM/dd/yyyy") + ": " + hours.ToString() , positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; pdfCanvas.DrawText("Core Training Hours: " + coreHours.ToString() , positionX, runningY, getPaint(10.0f)); runningY += 24; TrainingsTableHeader(pdfCanvas, runningY); runningY += trainingsTableLineHight; foreach( var trnng in trainings ){ runningY += (trainingsTableLineHight * TrainingRow(trnng, pdfCanvas, runningY, application.KersUser)); if( runningY > height ){ runningY = margin + 5; document.EndPage(); pdfCanvas = document.BeginPage(height, width); TrainingsTableHeader(pdfCanvas, runningY); runningY += trainingsTableLineHight; pageNum++; AddPageInfo(pdfCanvas, pageNum, 0, application.KersUser, DateTime.Now, pageTitle); } } if( application.Stages.Count() > 1 ){ runningY = margin + 5; document.EndPage(); pdfCanvas = document.BeginPage(height, width); pageNum++; AddPageInfo(pdfCanvas, pageNum, 0, application.KersUser, DateTime.Now, pageTitle); pdfCanvas.DrawText( "Reviews: " , margin, runningY, getPaint(12.0f, 1)); runningY += textLineHeight * 2; var count = 1; foreach( var review in application.Stages){ runningY += (TrainingReview( pdfCanvas, review, runningY) * textLineHeight); count++; // Skip the last review as it is by design empty if( count >= application.Stages.Count()) break; if( runningY > height - margin ){ runningY = margin + 5; document.EndPage(); pdfCanvas = document.BeginPage(height, width); pageNum++; AddPageInfo(pdfCanvas, pageNum, 0, application.KersUser, DateTime.Now, pageTitle); } } } foreach( var im in application.Images.OrderBy( i => i.UploadImageId)){ runningY = margin + 5; document.EndPage(); pdfCanvas = document.BeginPage(height, width); pageNum++; AddPageInfo(pdfCanvas, pageNum, 0, application.KersUser, DateTime.Now, pageTitle); runningY = margin + 5; var imageDescription = SplitLineToMultiline( im.Description, 120); foreach( var dscr in imageDescription ){ pdfCanvas.DrawText(dscr, positionX, runningY, getPaint(10.0f)); runningY += textLineHeight; } this.addBitmap(pdfCanvas,im.UploadImage.Name, margin, runningY, height - margin, width - margin); } document.EndPage(); }else{ Log(id,"LadderApplication", "Career Ladder Error", "int", "Error"); return new StatusCodeResult(500); } document.Close(); Log(application,"LadderApplication", "Career Ladder Pdf Created", "LadderApplication"); return File(stream.DetachAsData().AsStream(), "application/pdf", "CareerLadderApplication.pdf"); } } private int TrainingReview( SKCanvas pdfCanvas, LadderApplicationStage review, int positionY ){ var numLines = 1; var reviewLine = review.LadderStage.Name + " on " + review.Reviewed.ToString() + " by "; if( review.KersUser != null ){ reviewLine += review.KersUser.RprtngProfile.Name; } pdfCanvas.DrawText( reviewLine , margin, positionY, getPaint(10.0f, 1)); if( review.Note != null & review.Note != ""){ var note = SplitLineToMultiline( review.Note, 120); foreach( var dscr in note ){ pdfCanvas.DrawText(dscr, margin, positionY + numLines * textLineHeight, getPaint(10.0f)); numLines++; } } return numLines; } private void TrainingsTableHeader( SKCanvas pdfCanvas, int positionY){ DrawTrainingTableLines(pdfCanvas, positionY); TrainingsTableHorizontalLine( pdfCanvas, positionY); pdfCanvas.DrawText("Training Date(s)" , margin + trainingsTableLines[0] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(10.0f)); pdfCanvas.DrawText("Hours" , margin + trainingsTableLines[1] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(10.0f)); pdfCanvas.DrawText("Title" , margin + trainingsTableLines[2] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(10.0f)); pdfCanvas.DrawText("Attendance" , margin + trainingsTableLines[3] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(10.0f)); pdfCanvas.DrawText("Core" , margin + trainingsTableLines[4] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(10.0f)); TrainingsTableHorizontalLine( pdfCanvas, positionY + trainingsTableLineHight); } private int TrainingRow( Training Training, SKCanvas pdfCanvas, int positionY, KersUser user){ int numRows = 0; var datesString = Training.Start.ToString("MM/dd/yyyy"); if( Training.End != null){ datesString += " - " + Training.Start.ToString("MM/dd/yyyy"); } pdfCanvas.DrawText(datesString , margin + trainingsTableLines[0] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(8.5f)); if(Training.iHour != null){ pdfCanvas.DrawText(Training.iHour.iHoursTxt, margin + trainingsTableLines[1] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(9.0f)); } var enrollment = Training.Enrollment.Where( e => e.Attendie == user).FirstOrDefault(); var attended = "NO"; if( enrollment != null & enrollment.attended??false) attended = "YES"; pdfCanvas.DrawText(attended , margin + trainingsTableLines[3] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(8.5f)); var core = "NO"; if( Training.IsCore == true ) core = "YES"; pdfCanvas.DrawText(core , margin + trainingsTableLines[4] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(8.5f)); var SubjectLines = SplitLineToMultiline(Training.Subject, 57); foreach( var ln in SubjectLines){ numRows++; DrawTrainingTableLines(pdfCanvas, positionY); pdfCanvas.DrawText(ln , margin + trainingsTableLines[2] + trainingsTableCellMargin, positionY + trainingsTableLineHight - trainingsTableCellMargin, getPaint(10.0f, 3)); positionY += trainingsTableLineHight; } TrainingsTableHorizontalLine( pdfCanvas, positionY); return numRows; } private void TrainingsTableHorizontalLine( SKCanvas pdfCanvas, int positionY){ pdfCanvas.DrawLine(margin + trainingsTableLines[0], positionY, margin + trainingsTableLines[5], positionY, thinLinePaint); } private void DrawTrainingTableLines(SKCanvas pdfCanvas, int positionY){ foreach( var pos in this.trainingsTableLines){ pdfCanvas.DrawLine(margin + pos, positionY, margin + pos, positionY + trainingsTableLineHight, thinLinePaint); } } private List<Training> TrainingsByUser( int id, DateTime Start, DateTime End){ var trainings = from training in _context.Training from enfolment in training.Enrollment where enfolment.AttendieId == id select training; trainings = trainings.Where( t => t.Start > Start && t.Start < End); trainings = trainings.Include( t => t.Enrollment).Include(t => t.iHour) .Include( t => t.SurveyResults); var tnngs = trainings.OrderBy(t => t.Start).ToList(); return tnngs; } private int HourssByUser( int id, DateTime start, DateTime end, bool onlyCore = false){ IQueryable<Training> trainings = from training in _context.Training from enfolment in training.Enrollment where enfolment.AttendieId == id && enfolment.attended == true select training; trainings = trainings.Where( t => t.Start > start && t.Start < end); if( onlyCore ) trainings = trainings.Where( t => t.IsCore == true ); trainings = trainings.Include(t => t.iHour); var hours = trainings.Sum( t => t.iHour == null ? 0 : t.iHour.iHourValue ); return hours; } } }
using Microsoft.AspNetCore.Mvc.RazorPages; namespace aspnetcore22mvc { public class Profile : PageModel { public void OnGet() { } } }
using System; using System.Windows.Forms; namespace QuanLyTiemGiatLa.Danhmuc { public partial class frmCTCatDo : Form { private Entity.PhieuSlotEntity _phieuslot = null; public OnSaved onsaved; public frmCTCatDo(Entity.PhieuSlotEntity pslot) { InitializeComponent(); _phieuslot = pslot; this.Load += new EventHandler(frmCTCatDo_Load); } private void frmCTCatDo_Load(object sender, EventArgs e) { txtGhiChu.Text = _phieuslot.GhiChu; txtKieuGiat.Text = _phieuslot.TenKieuGiat; txtKho.Text = _phieuslot.Kho; txtMaDo.Text = _phieuslot.MaHienThi; txtMaVach.Text = _phieuslot.MaVach.ToString(); txtSlot.Text = _phieuslot.Slot.ToString(); txtTenDo.Text = _phieuslot.TenHang; if (_phieuslot.DaTra) btnGhi.Enabled = false; } private void btnThoat_Click(object sender, EventArgs e) { this.Close(); } private Boolean CheckForm() { Int32 slot; if (!Int32.TryParse(txtSlot.Text, out slot)) { MessageBox.Show("Slot phải là số", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtSlot.Focus(); txtSlot.SelectAll(); return false; } _phieuslot.Slot = slot; _phieuslot.Kho = txtKho.Text; _phieuslot.GhiChu = txtGhiChu.Text; return true; } private void btnGhi_Click(object sender, EventArgs e) { if (!this.CheckForm()) return; _phieuslot.ThoiDiemLuu = DateTime.Now.ToString("dd/MM/yyyy HH:mm") + " " + BienChung.userCurrent.UserName; if (Business.PhieuSlotBO.Update(_phieuslot) != 1) { MessageBox.Show("Số bản ghi update không bằng 1", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { onsaved(); this.Close(); } } private void btnLayGioHienTai_Click(object sender, EventArgs e) { try { txtGhiChu.Text = txtGhiChu.Text + DateTime.Now.ToString("dd/MM/yyyy HH:mm"); } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; //Maximo Michael //28 de outubro de 2018 01:34hs public class UnityEvent_Padrinho : MonoBehaviour { //Array capturar Caminho; public Transform [] C4_P = new Transform[0]; //Contar o caminho percorrido; public int countCaminho = 0; //Impontar valores abaixo; NavMeshAgent navMeshAgente; Transform transformPersonagem; Collider colliderPersonagem; void Start() { navMeshAgente = GetComponent<NavMeshAgent>(); transformPersonagem = GetComponent<Transform>(); colliderPersonagem = GetComponent<Collider>(); } public void movePadrinho() { if (C4_P.Length-1 >= countCaminho) { countCaminhoDef(); //Movimentar para o ponto expecificado pelo countCaminho navMeshAgente.destination = C4_P[countCaminho].position; } } public void countCaminhoDef() { //Verificar se o npc chegou no ponto expecificado; if (C4_P[countCaminho].position.x == transformPersonagem.position.x && C4_P[countCaminho].position.z == transformPersonagem.position.z && C4_P.Length - 1 >= countCaminho) { //Somar mais um; countCaminho++; //enabledCollider(); } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// Mostly for historical purposes, we segregate Faction progressions from other progressions. This is just a DestinyProgression with a shortcut for finding the DestinyFactionDefinition of the faction related to the progression. /// </summary> [DataContract] public partial class DestinyProgressionDestinyFactionProgression : IEquatable<DestinyProgressionDestinyFactionProgression>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyProgressionDestinyFactionProgression" /> class. /// </summary> /// <param name="FactionHash">The hash identifier of the Faction related to this progression. Use it to look up the DestinyFactionDefinition for more rendering info..</param> /// <param name="ProgressionHash">The hash identifier of the Progression in question. Use it to look up the DestinyProgressionDefinition in static data..</param> /// <param name="DailyProgress">The amount of progress earned today for this progression..</param> /// <param name="DailyLimit">If this progression has a daily limit, this is that limit..</param> /// <param name="WeeklyProgress">The amount of progress earned toward this progression in the current week..</param> /// <param name="WeeklyLimit">If this progression has a weekly limit, this is that limit..</param> /// <param name="CurrentProgress">This is the total amount of progress obtained overall for this progression (for instance, the total amount of Character Level experience earned).</param> /// <param name="Level">This is the level of the progression (for instance, the Character Level)..</param> /// <param name="LevelCap">This is the maximum possible level you can achieve for this progression (for example, the maximum character level obtainable).</param> /// <param name="StepIndex">Progressions define their levels in \&quot;steps\&quot;. Since the last step may be repeatable, the user may be at a higher level than the actual Step achieved in the progression. Not necessarily useful, but potentially interesting for those cruising the API. Relate this to the \&quot;steps\&quot; property of the DestinyProgression to see which step the user is on, if you care about that. (Note that this is Content Version dependent since it refers to indexes.).</param> /// <param name="ProgressToNextLevel">The amount of progression (i.e. \&quot;Experience\&quot;) needed to reach the next level of this Progression. Jeez, progression is such an overloaded word..</param> /// <param name="NextLevelAt">The total amount of progression (i.e. \&quot;Experience\&quot;) needed in order to reach the next level..</param> public DestinyProgressionDestinyFactionProgression(uint? FactionHash = default(uint?), uint? ProgressionHash = default(uint?), int? DailyProgress = default(int?), int? DailyLimit = default(int?), int? WeeklyProgress = default(int?), int? WeeklyLimit = default(int?), int? CurrentProgress = default(int?), int? Level = default(int?), int? LevelCap = default(int?), int? StepIndex = default(int?), int? ProgressToNextLevel = default(int?), int? NextLevelAt = default(int?)) { this.FactionHash = FactionHash; this.ProgressionHash = ProgressionHash; this.DailyProgress = DailyProgress; this.DailyLimit = DailyLimit; this.WeeklyProgress = WeeklyProgress; this.WeeklyLimit = WeeklyLimit; this.CurrentProgress = CurrentProgress; this.Level = Level; this.LevelCap = LevelCap; this.StepIndex = StepIndex; this.ProgressToNextLevel = ProgressToNextLevel; this.NextLevelAt = NextLevelAt; } /// <summary> /// The hash identifier of the Faction related to this progression. Use it to look up the DestinyFactionDefinition for more rendering info. /// </summary> /// <value>The hash identifier of the Faction related to this progression. Use it to look up the DestinyFactionDefinition for more rendering info.</value> [DataMember(Name="factionHash", EmitDefaultValue=false)] public uint? FactionHash { get; set; } /// <summary> /// The hash identifier of the Progression in question. Use it to look up the DestinyProgressionDefinition in static data. /// </summary> /// <value>The hash identifier of the Progression in question. Use it to look up the DestinyProgressionDefinition in static data.</value> [DataMember(Name="progressionHash", EmitDefaultValue=false)] public uint? ProgressionHash { get; set; } /// <summary> /// The amount of progress earned today for this progression. /// </summary> /// <value>The amount of progress earned today for this progression.</value> [DataMember(Name="dailyProgress", EmitDefaultValue=false)] public int? DailyProgress { get; set; } /// <summary> /// If this progression has a daily limit, this is that limit. /// </summary> /// <value>If this progression has a daily limit, this is that limit.</value> [DataMember(Name="dailyLimit", EmitDefaultValue=false)] public int? DailyLimit { get; set; } /// <summary> /// The amount of progress earned toward this progression in the current week. /// </summary> /// <value>The amount of progress earned toward this progression in the current week.</value> [DataMember(Name="weeklyProgress", EmitDefaultValue=false)] public int? WeeklyProgress { get; set; } /// <summary> /// If this progression has a weekly limit, this is that limit. /// </summary> /// <value>If this progression has a weekly limit, this is that limit.</value> [DataMember(Name="weeklyLimit", EmitDefaultValue=false)] public int? WeeklyLimit { get; set; } /// <summary> /// This is the total amount of progress obtained overall for this progression (for instance, the total amount of Character Level experience earned) /// </summary> /// <value>This is the total amount of progress obtained overall for this progression (for instance, the total amount of Character Level experience earned)</value> [DataMember(Name="currentProgress", EmitDefaultValue=false)] public int? CurrentProgress { get; set; } /// <summary> /// This is the level of the progression (for instance, the Character Level). /// </summary> /// <value>This is the level of the progression (for instance, the Character Level).</value> [DataMember(Name="level", EmitDefaultValue=false)] public int? Level { get; set; } /// <summary> /// This is the maximum possible level you can achieve for this progression (for example, the maximum character level obtainable) /// </summary> /// <value>This is the maximum possible level you can achieve for this progression (for example, the maximum character level obtainable)</value> [DataMember(Name="levelCap", EmitDefaultValue=false)] public int? LevelCap { get; set; } /// <summary> /// Progressions define their levels in \&quot;steps\&quot;. Since the last step may be repeatable, the user may be at a higher level than the actual Step achieved in the progression. Not necessarily useful, but potentially interesting for those cruising the API. Relate this to the \&quot;steps\&quot; property of the DestinyProgression to see which step the user is on, if you care about that. (Note that this is Content Version dependent since it refers to indexes.) /// </summary> /// <value>Progressions define their levels in \&quot;steps\&quot;. Since the last step may be repeatable, the user may be at a higher level than the actual Step achieved in the progression. Not necessarily useful, but potentially interesting for those cruising the API. Relate this to the \&quot;steps\&quot; property of the DestinyProgression to see which step the user is on, if you care about that. (Note that this is Content Version dependent since it refers to indexes.)</value> [DataMember(Name="stepIndex", EmitDefaultValue=false)] public int? StepIndex { get; set; } /// <summary> /// The amount of progression (i.e. \&quot;Experience\&quot;) needed to reach the next level of this Progression. Jeez, progression is such an overloaded word. /// </summary> /// <value>The amount of progression (i.e. \&quot;Experience\&quot;) needed to reach the next level of this Progression. Jeez, progression is such an overloaded word.</value> [DataMember(Name="progressToNextLevel", EmitDefaultValue=false)] public int? ProgressToNextLevel { get; set; } /// <summary> /// The total amount of progression (i.e. \&quot;Experience\&quot;) needed in order to reach the next level. /// </summary> /// <value>The total amount of progression (i.e. \&quot;Experience\&quot;) needed in order to reach the next level.</value> [DataMember(Name="nextLevelAt", EmitDefaultValue=false)] public int? NextLevelAt { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyProgressionDestinyFactionProgression {\n"); sb.Append(" FactionHash: ").Append(FactionHash).Append("\n"); sb.Append(" ProgressionHash: ").Append(ProgressionHash).Append("\n"); sb.Append(" DailyProgress: ").Append(DailyProgress).Append("\n"); sb.Append(" DailyLimit: ").Append(DailyLimit).Append("\n"); sb.Append(" WeeklyProgress: ").Append(WeeklyProgress).Append("\n"); sb.Append(" WeeklyLimit: ").Append(WeeklyLimit).Append("\n"); sb.Append(" CurrentProgress: ").Append(CurrentProgress).Append("\n"); sb.Append(" Level: ").Append(Level).Append("\n"); sb.Append(" LevelCap: ").Append(LevelCap).Append("\n"); sb.Append(" StepIndex: ").Append(StepIndex).Append("\n"); sb.Append(" ProgressToNextLevel: ").Append(ProgressToNextLevel).Append("\n"); sb.Append(" NextLevelAt: ").Append(NextLevelAt).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyProgressionDestinyFactionProgression); } /// <summary> /// Returns true if DestinyProgressionDestinyFactionProgression instances are equal /// </summary> /// <param name="input">Instance of DestinyProgressionDestinyFactionProgression to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyProgressionDestinyFactionProgression input) { if (input == null) return false; return ( this.FactionHash == input.FactionHash || (this.FactionHash != null && this.FactionHash.Equals(input.FactionHash)) ) && ( this.ProgressionHash == input.ProgressionHash || (this.ProgressionHash != null && this.ProgressionHash.Equals(input.ProgressionHash)) ) && ( this.DailyProgress == input.DailyProgress || (this.DailyProgress != null && this.DailyProgress.Equals(input.DailyProgress)) ) && ( this.DailyLimit == input.DailyLimit || (this.DailyLimit != null && this.DailyLimit.Equals(input.DailyLimit)) ) && ( this.WeeklyProgress == input.WeeklyProgress || (this.WeeklyProgress != null && this.WeeklyProgress.Equals(input.WeeklyProgress)) ) && ( this.WeeklyLimit == input.WeeklyLimit || (this.WeeklyLimit != null && this.WeeklyLimit.Equals(input.WeeklyLimit)) ) && ( this.CurrentProgress == input.CurrentProgress || (this.CurrentProgress != null && this.CurrentProgress.Equals(input.CurrentProgress)) ) && ( this.Level == input.Level || (this.Level != null && this.Level.Equals(input.Level)) ) && ( this.LevelCap == input.LevelCap || (this.LevelCap != null && this.LevelCap.Equals(input.LevelCap)) ) && ( this.StepIndex == input.StepIndex || (this.StepIndex != null && this.StepIndex.Equals(input.StepIndex)) ) && ( this.ProgressToNextLevel == input.ProgressToNextLevel || (this.ProgressToNextLevel != null && this.ProgressToNextLevel.Equals(input.ProgressToNextLevel)) ) && ( this.NextLevelAt == input.NextLevelAt || (this.NextLevelAt != null && this.NextLevelAt.Equals(input.NextLevelAt)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.FactionHash != null) hashCode = hashCode * 59 + this.FactionHash.GetHashCode(); if (this.ProgressionHash != null) hashCode = hashCode * 59 + this.ProgressionHash.GetHashCode(); if (this.DailyProgress != null) hashCode = hashCode * 59 + this.DailyProgress.GetHashCode(); if (this.DailyLimit != null) hashCode = hashCode * 59 + this.DailyLimit.GetHashCode(); if (this.WeeklyProgress != null) hashCode = hashCode * 59 + this.WeeklyProgress.GetHashCode(); if (this.WeeklyLimit != null) hashCode = hashCode * 59 + this.WeeklyLimit.GetHashCode(); if (this.CurrentProgress != null) hashCode = hashCode * 59 + this.CurrentProgress.GetHashCode(); if (this.Level != null) hashCode = hashCode * 59 + this.Level.GetHashCode(); if (this.LevelCap != null) hashCode = hashCode * 59 + this.LevelCap.GetHashCode(); if (this.StepIndex != null) hashCode = hashCode * 59 + this.StepIndex.GetHashCode(); if (this.ProgressToNextLevel != null) hashCode = hashCode * 59 + this.ProgressToNextLevel.GetHashCode(); if (this.NextLevelAt != null) hashCode = hashCode * 59 + this.NextLevelAt.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
using Common.EntityFramework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MoneyBack.Repositories { public class CompanyRepository : RepositoryBase<Company, MoneyEntities>, ICompanyRepository { public CompanyRepository(MoneyEntities context) : base(context) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Wall : MonoBehaviour { private Rigidbody2D rigidBody2D; void Start() { rigidBody2D = GetComponent<Rigidbody2D>(); } }
namespace Triton.Game { using Buddy.Coroutines; using log4net; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; using Triton.Game.Mapping; public class HSCard { [CompilerGenerated] private Triton.Game.Mapping.Entity entity_0; private static readonly ILog ilog_0 = Logger.GetLoggerInstanceForType(); internal HSCard(Triton.Game.Mapping.Card card) { this.Entity_0 = card.GetEntity(); } internal HSCard(Triton.Game.Mapping.Entity entity) { this.Entity_0 = entity; } public void CancelTarget() { this.Card.Cancel(); } [AsyncStateMachine(typeof(Struct98))] public Task DoAttack(HSCard attackee) { Struct98 struct2; struct2.hscard_0 = this; struct2.hscard_1 = attackee; struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create(); struct2.int_0 = -1; struct2.asyncTaskMethodBuilder_0.Start<Struct98>(ref struct2); return struct2.asyncTaskMethodBuilder_0.Task; } [AsyncStateMachine(typeof(S=fyJ2zEw6^2OPg41D`1f\*yF$))] public Task DoTarget(HSCard target) { Struct97 struct2; struct2.hscard_0 = this; struct2.hscard_1 = target; struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create(); struct2.int_0 = -1; struct2.asyncTaskMethodBuilder_0.Start<Struct97>(ref struct2); return struct2.asyncTaskMethodBuilder_0.Task; } public int GetTag(GAME_TAG tag) { return this.Entity_0.GetTag(tag); } public TAG_ZONE GetZone() { return this.Entity_0.GetZone(); } public bool IsNull() { return (this.Entity_0 == null); } [AsyncStateMachine(typeof(Struct93))] public Task Pickup(int timeout = 500) { Struct93 struct2; struct2.hscard_0 = this; struct2.int_1 = timeout; struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create(); struct2.int_0 = -1; struct2.asyncTaskMethodBuilder_0.Start<Struct93>(ref struct2); return struct2.asyncTaskMethodBuilder_0.Task; } public void ToggleMulliganState() { Client.LeftClickAt(Client.CardInteractPoint(this.Card)); } [AsyncStateMachine(typeof(#kl3BmB<\*j%D^eJssr1n?B=F"))] public Task Use() { Struct94 struct2; struct2.hscard_0 = this; struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create(); struct2.int_0 = -1; struct2.asyncTaskMethodBuilder_0.Start<Struct94>(ref struct2); return struct2.asyncTaskMethodBuilder_0.Task; } [AsyncStateMachine(typeof(Struct96))] public Task UseAt(int slot) { Struct96 struct2; struct2.int_1 = slot; struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create(); struct2.int_0 = -1; struct2.asyncTaskMethodBuilder_0.Start<Struct96>(ref struct2); return struct2.asyncTaskMethodBuilder_0.Task; } [AsyncStateMachine(typeof(Struct95))] public Task UseOn(Triton.Game.Mapping.Card target) { Struct95 struct2; struct2.card_0 = target; struct2.asyncTaskMethodBuilder_0 = AsyncTaskMethodBuilder.Create(); struct2.int_0 = -1; struct2.asyncTaskMethodBuilder_0.Start<Struct95>(ref struct2); return struct2.asyncTaskMethodBuilder_0.Task; } public List<string> AttachedCardIds { get { return this.Entity_0.GetAttachments().Select<Triton.Game.Mapping.Entity, string>((Class238.<>9__108_0 ?? (Class238.<>9__108_0 = new Func<Triton.Game.Mapping.Entity, string>(Class238.<>9.method_1)))).ToList<string>(); } } public List<HSCard> AttachedCards { get { return this.Entity_0.GetAttachments().Where<Triton.Game.Mapping.Entity>((Class238.<>9__110_0 ?? (Class238.<>9__110_0 = new Func<Triton.Game.Mapping.Entity, bool>(Class238.<>9.method_2)))).Select<Triton.Game.Mapping.Entity, HSCard>((Class238.<>9__110_1 ?? (Class238.<>9__110_1 = new Func<Triton.Game.Mapping.Entity, HSCard>(Class238.<>9.method_3)))).ToList<HSCard>(); } } public List<int> AttachedEntitiesIds { get { return this.Entity_0.GetAttachments().Select<Triton.Game.Mapping.Entity, int>((Class238.<>9__106_0 ?? (Class238.<>9__106_0 = new Func<Triton.Game.Mapping.Entity, int>(Class238.<>9.method_0)))).ToList<int>(); } } public int Attack { get { return this.Entity_0.GetRealTimeAttack(); } } public bool CanAttack { get { return this.Entity_0.CanAttack(); } } public bool CanBeAttacked { get { return this.Entity_0.CanBeAttacked(); } } public bool CanBeDamaged { get { return this.Entity_0.CanBeDamaged(); } } public bool CanBeTargeted { get { Actor actor = this.Card.GetActor(); if (actor == null) { return false; } if (actor.GetActorStateType() != ActorStateType.CARD_VALID_TARGET) { return (actor.GetActorStateType() == ActorStateType.CARD_VALID_TARGET_MOUSE_OVER); } return true; } } public bool CanBeTargetedByAbilities { get { return this.Entity_0.CanBeTargetedByAbilities(); } } public bool CanBeTargetedByHeroPowers { get { return this.Entity_0.CanBeTargetedByHeroPowers(); } } public bool CanBeTargetedByOpponents { get { return this.Entity_0.CanBeTargetedByOpponents(); } } public bool CanBeUsed { get { Actor actor = this.Card.GetActor(); if (actor == null) { return false; } if (((actor.GetActorStateType() != ActorStateType.CARD_PLAYABLE) && (actor.GetActorStateType() != ActorStateType.CARD_COMBO)) && (actor.GetActorStateType() != ActorStateType.CARD_PLAYABLE_MOUSE_OVER)) { return (actor.GetActorStateType() == ActorStateType.CARD_COMBO_MOUSE_OVER); } return true; } } public Triton.Game.Mapping.Card Card { get { return this.Entity_0.GetCard(); } } public TAG_CLASS Class { get { return this.Entity_0.GetClass(); } } public int ControllerId { get { return this.Entity_0.GetControllerId(); } } public int Cost { get { return this.Entity_0.GetRealTimeCost(); } } public int CreatorId { get { return this.Entity_0.GetCreatorId(); } } public string DebugName { get { return this.Entity_0.GetDebugName(); } } public int Durability { get { return this.Entity_0.GetDurability(); } } internal Triton.Game.Mapping.Entity Entity_0 { [CompilerGenerated] get { return this.entity_0; } [CompilerGenerated] private set { this.entity_0 = value; } } public int EntityId { get { return this.Entity_0.GetEntityId(); } } public bool HasBattlecry { get { return this.Entity_0.HasBattlecry(); } } public bool HasCharge { get { return this.Entity_0.HasCharge(); } } public bool HasCombo { get { return this.Entity_0.HasCombo(); } } public bool HasDeathrattle { get { return this.Entity_0.HasDeathrattle(); } } public bool HasDivineShield { get { return this.Entity_0.HasDivineShield(); } } public bool HasOverload { get { return this.Entity_0.HasOverload(); } } public bool HasSpellPower { get { return this.Entity_0.HasSpellPower(); } } public bool HasTaunt { get { if (!this.Entity_0.IsMinion()) { return false; } if (this.Card.GetZone() == GameState.Get().GetFriendlySidePlayer().GetHandZone()) { return this.Entity_0.HasTaunt(); } if ((this.Card.GetActor() == null) || (!this.Card.GetActor().IsSpellActive(SpellType.TAUNT) && !this.Card.GetActor().IsSpellActive(SpellType.TAUNT_PREMIUM))) { return false; } return true; } } public bool HasWindfury { get { return this.Entity_0.HasWindfury(); } } public int Health { get { return this.Entity_0.GetRealTimeRemainingHP(); } } public string Id { get { return this.Entity_0.GetCardId(); } } public bool IsAffectedBySpellPower { get { return this.Entity_0.IsAffectedBySpellPower(); } } public bool IsAsleep { get { return this.Entity_0.IsAsleep(); } } public bool IsAttached { get { return this.Entity_0.IsAttached(); } } public bool IsDamaged { get { return this.Entity_0.IsDamaged(); } } public bool IsElite { get { return this.Entity_0.IsElite(); } } public bool IsEnchantment { get { return this.Entity_0.IsEnchantment(); } } public bool IsEnraged { get { return this.Entity_0.IsEnraged(); } } public bool IsExhausted { get { return this.Entity_0.IsExhausted(); } } public bool IsFreeze { get { return this.Entity_0.IsFreeze(); } } public bool IsFrozen { get { return this.Entity_0.IsFrozen(); } } public bool IsHero { get { return this.Entity_0.IsHero(); } } public bool IsHeroPower { get { return this.Entity_0.IsHeroPower(); } } public bool IsImmune { get { return this.Entity_0.IsImmune(); } } public bool IsMagnet { get { return this.Entity_0.IsMagnet(); } } public bool IsMinion { get { return this.Entity_0.IsMinion(); } } public bool IsPoisonous { get { return this.Entity_0.IsPoisonous(); } } public bool IsRecentlyArrived { get { return this.Entity_0.IsRecentlyArrived(); } } public bool IsSecret { get { return this.Entity_0.IsSecret(); } } public bool IsSilenced { get { return this.Entity_0.IsSilenced(); } } public bool IsSpell { get { return this.Entity_0.IsSpell(); } } public bool IsStealthed { get { return this.Entity_0.IsStealthed(); } } public bool IsWeapon { get { return this.Entity_0.IsWeapon(); } } public int MaxHp { get { return this.Entity_0.GetOriginalHealth(); } } public string Name { get { return this.Entity_0.GetName(); } } public int NumAttackThisTurn { get { return this.Entity_0.GetNumAttacksThisTurn(); } } public int OriginalATK { get { return this.Entity_0.GetOriginalATK(); } } public bool OriginalCharge { get { return this.Entity_0.GetOriginalCharge(); } } public int OriginalCost { get { return this.Entity_0.GetOriginalCost(); } } public int OriginalDurability { get { return this.Entity_0.GetOriginalDurability(); } } public int OriginalHealth { get { return this.Entity_0.GetOriginalHealth(); } } public TAG_RACE Race { get { return this.Entity_0.GetRace(); } } public TAG_RARITY Rarity { get { return this.Entity_0.GetRarity(); } } public int ZonePosition { get { return this.Entity_0.GetZonePosition(); } } [Serializable, CompilerGenerated] private sealed class Class238 { public static readonly HSCard.Class238 <>9 = new HSCard.Class238(); public static Func<Triton.Game.Mapping.Entity, int> <>9__106_0; public static Func<Triton.Game.Mapping.Entity, string> <>9__108_0; public static Func<Triton.Game.Mapping.Entity, bool> <>9__110_0; public static Func<Triton.Game.Mapping.Entity, HSCard> <>9__110_1; internal int method_0(Triton.Game.Mapping.Entity entity_0) { return entity_0.GetEntityId(); } internal string method_1(Triton.Game.Mapping.Entity entity_0) { return entity_0.GetCardId(); } internal bool method_2(Triton.Game.Mapping.Entity entity_0) { return (entity_0 > null); } internal HSCard method_3(Triton.Game.Mapping.Entity entity_0) { return new HSCard(entity_0); } } [CompilerGenerated] private struct Struct93 : IAsyncStateMachine { public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0; private bool bool_0; public HSCard hscard_0; public int int_0; public int int_1; private Stopwatch stopwatch_0; private TaskAwaiter taskAwaiter_0; private void MoveNext() { int num = this.int_0; try { TaskAwaiter awaiter; if (num != 0) { if (num != 1) { awaiter = this.hscard_0.Card.DoGrab().GetAwaiter(); if (!awaiter.IsCompleted) { num = 0; this.int_0 = 0; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct93>(ref awaiter, ref this); return; } goto Label_008A; } awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; goto Label_00C3; } awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; Label_008A: awaiter.GetResult(); awaiter = new TaskAwaiter(); this.stopwatch_0 = Stopwatch.StartNew(); this.bool_0 = false; while (this.stopwatch_0.ElapsedMilliseconds < this.int_1) { awaiter = Coroutine.Sleep(100).GetAwaiter(); if (!awaiter.IsCompleted) { goto Label_00F4; } Label_00C3: awaiter.GetResult(); awaiter = new TaskAwaiter(); if (InputManager.Get().GetHeldCard() != null) { goto Label_0114; } } goto Label_011B; Label_00F4: num = 1; this.int_0 = 1; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct93>(ref awaiter, ref this); return; Label_0114: this.bool_0 = true; Label_011B: if (this.bool_0) { HSCard.ilog_0.InfoFormat("[Pickup] The card was picked up in {0} ms.", this.stopwatch_0.ElapsedMilliseconds); } else { HSCard.ilog_0.InfoFormat("[Pickup] The card was not able to be picked up in {0} ms.", this.int_1); } } catch (Exception exception) { this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetException(exception); return; } this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine); } } [CompilerGenerated] private struct Struct94 : IAsyncStateMachine { public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0; public HSCard hscard_0; public int int_0; private TaskAwaiter taskAwaiter_0; private void MoveNext() { int num = this.int_0; try { TaskAwaiter awaiter; if (num != 0) { awaiter = this.hscard_0.UseOn(GameState.Get().GetFriendlySidePlayer().GetHeroCard()).GetAwaiter(); if (!awaiter.IsCompleted) { num = 0; this.int_0 = 0; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct94>(ref awaiter, ref this); return; } } else { awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; } awaiter.GetResult(); awaiter = new TaskAwaiter(); } catch (Exception exception) { this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetException(exception); return; } this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine); } } [CompilerGenerated] private struct Struct95 : IAsyncStateMachine { public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0; public Card card_0; public int int_0; private TaskAwaiter taskAwaiter_0; private Vector3 vector3_0; private void MoveNext() { int num = this.int_0; try { TaskAwaiter awaiter; if (num != 0) { this.vector3_0 = Client.CardInteractPoint(this.card_0); awaiter = Client.MoveCursorHumanLike(this.vector3_0).GetAwaiter(); if (!awaiter.IsCompleted) { num = 0; this.int_0 = 0; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct95>(ref awaiter, ref this); return; } } else { awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; } awaiter.GetResult(); awaiter = new TaskAwaiter(); Client.LeftClickAt(this.vector3_0); } catch (Exception exception) { this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetException(exception); return; } this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine); } } [CompilerGenerated] private struct Struct96 : IAsyncStateMachine { public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0; public int int_0; public int int_1; private int int_2; private TaskAwaiter taskAwaiter_0; private Vector3 vector3_0; private Vector3 vector3_1; private Vector3 vector3_2; private ZonePlay zonePlay_0; private void MoveNext() { int num = this.int_0; try { TaskAwaiter awaiter; switch (num) { case 0: break; case 1: goto Label_01FD; case 2: goto Label_0264; case 3: goto Label_029F; case 4: goto Label_0303; default: { HSCard.ilog_0.InfoFormat("[UseAt] {0}", this.int_1); this.zonePlay_0 = GameState.Get().GetFriendlySidePlayer().GetBattlefieldZone(); List<Card> cards = this.zonePlay_0.m_cards; this.int_2 = cards.Count; if (this.int_2 == 0) { this.vector3_0 = this.zonePlay_0.GetCardPosition(0); awaiter = Client.MoveCursorHumanLike(this.vector3_0).GetAwaiter(); if (awaiter.IsCompleted) { goto Label_01DE; } num = 0; this.int_0 = 0; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct96>(ref awaiter, ref this); } else if (this.int_1 > this.int_2) { this.vector3_1 = this.zonePlay_0.GetCardPosition((int) (this.int_2 - 1)); this.vector3_1.X += this.zonePlay_0.m_slotWidth / 2f; awaiter = Client.MoveCursorHumanLike(this.vector3_1).GetAwaiter(); if (awaiter.IsCompleted) { goto Label_0219; } num = 1; this.int_0 = 1; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct96>(ref awaiter, ref this); } else { this.vector3_2 = this.zonePlay_0.GetCardPosition((int) (this.int_1 - 1)); this.vector3_2.X -= this.zonePlay_0.m_slotWidth / 2f; awaiter = Client.MoveCursorHumanLike(this.vector3_2).GetAwaiter(); if (awaiter.IsCompleted) { goto Label_02BB; } num = 3; this.int_0 = 3; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct96>(ref awaiter, ref this); } return; } } awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; Label_01DE: awaiter.GetResult(); awaiter = new TaskAwaiter(); Client.LeftClickAt(this.vector3_0); goto Label_0352; Label_01FD: awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; Label_0219: awaiter.GetResult(); awaiter = new TaskAwaiter(); awaiter = Coroutine.Sleep(250).GetAwaiter(); if (awaiter.IsCompleted) { goto Label_0280; } num = 2; this.int_0 = 2; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct96>(ref awaiter, ref this); return; Label_0264: awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; Label_0280: awaiter.GetResult(); awaiter = new TaskAwaiter(); Client.LeftClickAt(this.vector3_1); goto Label_0352; Label_029F: awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; Label_02BB: awaiter.GetResult(); awaiter = new TaskAwaiter(); awaiter = Coroutine.Sleep(250).GetAwaiter(); if (awaiter.IsCompleted) { goto Label_031F; } num = 4; this.int_0 = 4; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct96>(ref awaiter, ref this); return; Label_0303: awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; Label_031F: awaiter.GetResult(); awaiter = new TaskAwaiter(); Client.LeftClickAt(this.vector3_2); } catch (Exception exception) { this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetException(exception); return; } Label_0352: this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine); } } [CompilerGenerated] private struct Struct97 : IAsyncStateMachine { public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0; public HSCard hscard_0; public HSCard hscard_1; public int int_0; private TaskAwaiter taskAwaiter_0; private void MoveNext() { int num = this.int_0; try { TaskAwaiter awaiter; if (num != 0) { awaiter = this.hscard_0.Card.DoTargeting(this.hscard_1.Card).GetAwaiter(); if (!awaiter.IsCompleted) { num = 0; this.int_0 = 0; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct97>(ref awaiter, ref this); return; } } else { awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; } awaiter.GetResult(); awaiter = new TaskAwaiter(); } catch (Exception exception) { this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetException(exception); return; } this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine); } } [CompilerGenerated] private struct Struct98 : IAsyncStateMachine { public AsyncTaskMethodBuilder asyncTaskMethodBuilder_0; public HSCard hscard_0; public HSCard hscard_1; public int int_0; private TaskAwaiter taskAwaiter_0; private void MoveNext() { int num = this.int_0; try { TaskAwaiter awaiter; if (num != 0) { awaiter = this.hscard_0.Card.DoAttack(this.hscard_1.Card).GetAwaiter(); if (!awaiter.IsCompleted) { num = 0; this.int_0 = 0; this.taskAwaiter_0 = awaiter; this.asyncTaskMethodBuilder_0.AwaitUnsafeOnCompleted<TaskAwaiter, HSCard.Struct98>(ref awaiter, ref this); return; } } else { awaiter = this.taskAwaiter_0; this.taskAwaiter_0 = new TaskAwaiter(); num = -1; this.int_0 = -1; } awaiter.GetResult(); awaiter = new TaskAwaiter(); } catch (Exception exception) { this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetException(exception); return; } this.int_0 = -2; this.asyncTaskMethodBuilder_0.SetResult(); } [DebuggerHidden] private void SetStateMachine(IAsyncStateMachine stateMachine) { this.asyncTaskMethodBuilder_0.SetStateMachine(stateMachine); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; public class MapManager : MonoBehaviour { [SerializeField] private Tilemap map; [SerializeField] private List<TileData> tileDatas; private Dictionary<TileBase, TileData> dataFromTiles; public BoxMovement[] boxes; private void Awake() { dataFromTiles = new Dictionary<TileBase, TileData>(); foreach (var tileData in tileDatas) { foreach (var tile in tileData.tiles) { dataFromTiles.Add(tile, tileData); } } } private void OnEnable() { boxes = FindObjectsOfType<BoxMovement>(); } public bool WallBlock(Vector2 worldPosition) { Vector3Int gridPos = map.WorldToCell(worldPosition); TileBase tile = map.GetTile(gridPos); if (tile == null) { return false; } bool blocked = dataFromTiles[tile].wall; return blocked; } }
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.UI; using System.Web.UI.WebControls; public partial class Purchase : System.Web.UI.Page { public string ConnString = WebConfigurationManager.ConnectionStrings["connect"].ConnectionString; public SqlCommand cmd = new SqlCommand(); public SqlConnection Conn = new SqlConnection(); SqlDataReader red; ConfigSettings _settings = new ConfigSettings(); DataSet st; protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string hostName = Dns.GetHostName(); // Retrive the Name of HOST Console.WriteLine(hostName); // Get the IP txtIpAddress.Text = Dns.GetHostByName(hostName).AddressList[0].ToString(); Random rand = new Random(); txtMachineId.Text = rand.Next(9999, 999999).ToString(); grid(); } } protected void grid() { Conn = new SqlConnection(ConnString); Conn.Open(); SqlDataAdapter adp = new SqlDataAdapter("select * from backupcode ", Conn); st = new DataSet(); adp.Fill(st); lblbackcode1.Text = st.Tables[0].Rows[0]["FirstPassword"].ToString(); lblbackcode2.Text = st.Tables[0].Rows[0]["SecondPassword"].ToString(); Conn.Close(); } protected void btnClear_Click(object sender, EventArgs e) { txt1stPassword.Text = ""; txt2stPassword.Text = ""; txtCardNo.Text = ""; txtPassword.Text = ""; txtPruchaseAmount.Text = ""; } protected void btnSubmit_Click(object sender, EventArgs e) { if ((txt2stPassword.Text == lbl2stPassword.Text) || (txt2stPassword.Text == lblbackcode2.Text)) { try { Conn = new SqlConnection(ConnString); Conn.Close(); Conn.Open(); string qry = "insert into Payment (Purchase_from,Cardno,DateTime,Amount) values('" + txtMachineId.Text + "','" + txtCardNo.Text + "','" + DateTime.Now.ToString() +"','" + txtPruchaseAmount.Text + "')"; SqlCommand cmd2 = new SqlCommand(qry, Conn); cmd2.ExecuteNonQuery(); lblMessage.Text = "Purchased Successfully"; lblMessage.ForeColor = System.Drawing.Color.Green; Conn.Close(); sendSMS(lblMobile.Text, "Purchase Successful for RS : " + txtPruchaseAmount.Text); btnClear_Click(sender, e); } catch (Exception ex) { lblMessage.Text = ex.Message.Replace("'", ""); lblMessage.ForeColor = System.Drawing.Color.Red; } finally { Conn.Close(); } } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "2 St Password incorrect"; UpdatehackerListOTP2_Tried(txt2stPassword.Text); } } void Generate1StPssword() { //Conn.Open(); Random ran = new Random(); lbl1stPassword.Text = ran.Next(1111, 999999).ToString(); string qry = "Update AccountDetails set FirstPassword='" + lbl1stPassword.Text + "' where accno='" + lblAccountNo.Text + "'"; SqlCommand cmd2 = new SqlCommand(qry, Conn); cmd2.ExecuteNonQuery(); lblMessage.Text = "First Password Successfully Created."; lblMessage.ForeColor = System.Drawing.Color.Green; sendSMS(lblMobile.Text, "Card 1 st Password : " + lbl1stPassword.Text); } void Generate2StPssword() { Conn = new SqlConnection(ConnString); Conn.Open(); Random ran = new Random(); lbl2stPassword.Text = ran.Next(1111, 999999).ToString(); string qry = "Update AccountDetails set SecondPassword='" + lbl2stPassword.Text + "' where accno='" + lblAccountNo.Text + "'"; SqlCommand cmd2 = new SqlCommand(qry, Conn); cmd2.ExecuteNonQuery(); lblMessage.Text = "Second Password Successfully Created."; lblMessage.ForeColor = System.Drawing.Color.Green; sendSMS(lblmobilealt.Text, "Card 2 st Password : " + lbl2stPassword.Text); } protected void btnCheckPassword_Click(object sender, EventArgs e) { Conn = new SqlConnection(ConnString); Conn.Open(); SqlDataAdapter adp = new SqlDataAdapter("Select A.Accno,A.status,A.Phoneno,A.altphoneno from AccountDetails A join Creditcard C on a.Accno = c.Accno where a.Password='" + txtPassword.Text + "'", Conn); st = new DataSet(); adp.Fill(st); if (st.Tables[0].Rows.Count == 0) { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Password or Card Details incorrect"; UpdatehackerListPin_Tried(txtPassword.Text); } else { if (st.Tables[0].Rows[0]["status"].ToString() != "Blocked") { lblAccountNo.Text = st.Tables[0].Rows[0]["Accno"].ToString(); lblMobile.Text = st.Tables[0].Rows[0]["Phoneno"].ToString(); lblmobilealt.Text = st.Tables[0].Rows[0]["altphoneno"].ToString(); Generate1StPssword(); txt1stPassword.Visible = true; btn1stPassword.Visible = true; } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "Account is Block.Please contact Bank."; } } Conn.Close(); } protected void btn1stPassword_Click(object sender, EventArgs e) { if ((txt1stPassword.Text == lbl1stPassword.Text) || (txt1stPassword.Text == lblbackcode1.Text)) { Generate2StPssword(); txt2stPassword.Visible = true; btnSubmit.Visible = true; } else { lblMessage.ForeColor = System.Drawing.Color.Red; lblMessage.Text = "1 St Password incorrect"; UpdatehackerListOTP_Tried(txt1stPassword.Text); } } void UpdatehackerListPin_Tried(string pwd) { try { Conn = new SqlConnection(ConnString); Conn.Open(); string qry = "insert into [HackerList] (Cardno,DateTime,Amount,DeviceId,Pin_Tried,IP_Address) values('" + txtCardNo.Text + "','" + DateTime.Now + "','" + txtPruchaseAmount.Text + "','" + txtMachineId.Text + "','" + pwd + "','" + txtIpAddress.Text + "')"; SqlCommand cmd2 = new SqlCommand(qry, Conn); cmd2.ExecuteNonQuery(); //lblMessage.Text = "Details Added Successfully"; //lblMessage.ForeColor = System.Drawing.Color.Green; Conn.Close(); } catch (Exception ex) { lblMessage.Text = ex.Message.Replace("'", ""); lblMessage.ForeColor = System.Drawing.Color.Red; } finally { Conn.Close(); } } void UpdatehackerListOTP_Tried(string pwd) { try { Conn = new SqlConnection(ConnString); Conn.Open(); string qry = "insert into [HackerList] (Cardno,DateTime,Amount,DeviceId,OTP_Tried,IP_Address) values('" + txtCardNo.Text + "','" + DateTime.Now + "','" + txtPruchaseAmount.Text + "','" + txtMachineId.Text + "','" + pwd + "','" + txtIpAddress.Text + "')"; SqlCommand cmd2 = new SqlCommand(qry, Conn); cmd2.ExecuteNonQuery(); //lblMessage.Text = "Details Added Successfully"; //lblMessage.ForeColor = System.Drawing.Color.Green; Conn.Close(); } catch (Exception ex) { lblMessage.Text = ex.Message.Replace("'", ""); lblMessage.ForeColor = System.Drawing.Color.Red; } finally { Conn.Close(); } } void UpdatehackerListOTP2_Tried(string pwd) { try { Conn = new SqlConnection(ConnString); Conn.Open(); string qry = "insert into [HackerList] (Cardno,DateTime,Amount,DeviceId,OTP2_Tried,IP_Address) values('" + txtCardNo.Text + "','" + DateTime.Now + "','" + txtPruchaseAmount.Text + "','" + txtMachineId.Text + "','" + pwd + "','" + txtIpAddress.Text + "')"; SqlCommand cmd2 = new SqlCommand(qry, Conn); cmd2.ExecuteNonQuery(); //lblMessage.Text = "Details Added Successfully"; //lblMessage.ForeColor = System.Drawing.Color.Green; Conn.Close(); } catch (Exception ex) { lblMessage.Text = ex.Message.Replace("'", ""); lblMessage.ForeColor = System.Drawing.Color.Red; } finally { Conn.Close(); } } public string sendSMS(string MobileNo, string smsText) { string SmsStatusMsg = string.Empty; try { WebClient client = new WebClient(); StringBuilder sb = new StringBuilder(); sb.Append(_settings.SmsBegin); sb.Append(_settings.SmsUserName); sb.Append(_settings.SmsSecond); sb.Append(_settings.SmsPassword); sb.Append(_settings.SmsThird); sb.Append(_settings.SmsSenderIDPromotional); sb.Append(_settings.SmsFouth); sb.Append(_settings.SmsRoutePro); sb.Append(_settings.SmsFifth); sb.Append(MobileNo); sb.Append(_settings.SmsLast); sb.Append(smsText); string URL = sb.ToString(); SmsStatusMsg = new TimedWebClient { Timeout = 600000 }.DownloadString(URL); string datetime = DateTime.Now.ToString("yyyyMMdd"); DataTable dt = new DataTable(); dt.Columns.AddRange(new DataColumn[5] { new DataColumn("sms_Broadcast_id"), new DataColumn("sms_Status"), new DataColumn("sms_mobileNo"), new DataColumn("sms_text"), new DataColumn("sms_dateFormat") }); string sentsmsList = MobileNo; string[] words = sentsmsList.Split(','); foreach (string MObileNo in words) { dt.Rows.Add("sss", null, MObileNo, smsText, datetime); } return "Message Sent Successful."; } catch (WebException e1) { return e1.Message + " " + "WebException" + " " + e1.InnerException; } catch (Exception e2) { return e2.Message + " " + "WebException" + " " + e2.InnerException; } } }
 using System; namespace PDTech.OA.Model { /// <summary> /// 公文项目关联表 /// </summary> [Serializable] public partial class ARCHIVE_PROJECT_MAP { public ARCHIVE_PROJECT_MAP() {} #region Model private decimal? _archive_id; private decimal? _project_id; /// <summary> /// 公文ID /// </summary> public decimal? ARCHIVE_ID { set{ _archive_id=value;} get{return _archive_id;} } /// <summary> /// 项目ID /// </summary> public decimal? PROJECT_ID { set{ _project_id=value;} get{return _project_id;} } #endregion Model } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class MyCylMesh : MonoBehaviour { LineSegment[] mNormals; void InitNormals(Vector3[] v, Vector3[] n) { mNormals = new LineSegment[v.Length]; for (int i = 0; i < v.Length; i++) { GameObject o = GameObject.CreatePrimitive(PrimitiveType.Cylinder); mNormals[i] = o.AddComponent<LineSegment>(); mNormals[i].SetWidth(0.05f); mNormals[i].transform.SetParent(this.transform); } UpdateNormals(v, n); } void UpdateNormals(Vector3[] v, Vector3[] n) { for (int i = 0; i < v.Length; i++) { mNormals[i].SetEndPoints(v[i], v[i] - 1.0f * n[i]); } } Vector3 FaceNormal(Vector3[] v, int i0, int i1, int i2) { Vector3 a = v[i1] - v[i0]; Vector3 b = v[i2] - v[i0]; return Vector3.Cross(a, b).normalized; } void ComputeNormals(Vector3[] v, Vector3[] n) { Vector3[] triNormal = new Vector3[triangles]; for (int i = 0; i < triangles; i++) { int t1 = t[i * 3]; int t2 = t[i * 3 + 1]; int t3 = t[i * 3 + 2]; triNormal[i] = FaceNormal(v, t1, t2, t3); } // top left n[0] = (triNormal[0] + triNormal[1]).normalized; // top right n[N] = triNormal[N * 2 - 1].normalized; // bottom left n[vertices-(N+1)] = triNormal[(N * 2) * (M - 1)].normalized; // bottom right n[vertices - 1] = (triNormal[triangles - 1] + triNormal[triangles - 2]).normalized; // top and bottom int topTri = 1; int btmTri = triangles - (2 * N); for (int tb = 1; tb < N; tb++) { n[tb] = (triNormal[topTri] + triNormal[topTri + 1] + triNormal[topTri + 2]).normalized; n[vertices - (N+1) + tb] = (triNormal[btmTri] + triNormal[btmTri + 1] + triNormal[btmTri + 2]).normalized; topTri += 2; btmTri += 2; } // right and left int startRight = (N * 2) - 1; int startLeft = 0; for (int a = N + 1; a < (N + 1) * M; a += (N + 1)) { n[a] = (triNormal[startLeft] + triNormal[startLeft + (N * 2)] + triNormal[startLeft + (N * 2) + 1]).normalized; startLeft += (N * 2); n[a + N] = (triNormal[startRight] + triNormal[startRight - 1] + triNormal[startRight + (N * 2)]).normalized; startRight += (N * 2); } // inner int startI = 0; for (int d = 1; d < M; d++) { for (int c = 1; c < N; c++) { n[c+(d*(N+1))] = (triNormal[startI] + triNormal[startI + 1] + triNormal[startI + 2] + triNormal[startI + (N * 2) + 1] + triNormal[startI + (N * 2) + 2] + triNormal[startI + (N * 2) + 3]).normalized; startI += 2; } startI += 2; } UpdateNormals(v, n); } }
/* Copyright (c) 2010, Direct Project All rights reserved. Authors: Umesh Madan umeshma@microsoft.com Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of The Direct Project (directproject.org) nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using Health.Direct.Common.DnsResolver; namespace Health.Direct.DnsResponder { /// <summary> /// A trivial Memory Dns Store. /// </summary> public class MemoryStore : IDnsStore { DnsRecordTable m_records; public MemoryStore() : this(0) { } public MemoryStore(int capacity) { m_records = new DnsRecordTable(capacity); } public DnsRecordTable Records { get { return m_records; } } public DnsResponse Get(DnsRequest request) { if (request == null) { throw new ArgumentNullException(); } DnsQuestion question = request.Question; if (question == null || question.Class != DnsStandard.Class.IN) { return null; } IEnumerable<DnsResourceRecord> matches = m_records[request.Question.Domain]; if (matches == null) { return null; } return this.CreateResponse(request, matches); } DnsResponse CreateResponse(DnsRequest request, IEnumerable<DnsResourceRecord> matches) { DnsStandard.RecordType questionType = request.Question.Type; DnsResponse response = new DnsResponse(request); int matchCount = 0; foreach (DnsResourceRecord record in matches) { if (record.Type == questionType) { ++matchCount; switch (record.Type) { default: response.AnswerRecords.Add(record); break; case DnsStandard.RecordType.NS: case DnsStandard.RecordType.SOA: response.AnswerRecords.Add(record); break; } } } if (matchCount == 0) { throw new DnsServerException(DnsStandard.ResponseCode.NameError); } return response; } } }
using System; using System.Collections.Generic; using System.Text; namespace CD { /// <summary> /// Data structure for a CD /// Holds CD name, artist, genre, price and a list of tracks /// </summary> class CompactDisk { public String name; public String artist; public String genre; public String price; private Track[] tracks; public CompactDisk(String name, String artist, String genre, String price) { this.name = name; this.artist = artist; this.genre = genre; this.price = price; this.tracks = new Track[0]; //TODO not implemented } /// <summary> /// Get the track listing /// </summary> /// <returns>an array of Track objects</returns> public Track[] TrackList() { return (Track[])tracks.Clone(); } /// <summary> /// Get the desired track /// </summary> /// <param name="number">the number of the track, indexed from 1</param> /// <returns>the track asked for</returns> public Track Track(int number) { if (number < 1 || number > tracks.Length) { return null; } else return tracks[number - 1]; } public override String ToString() { return "Name: " + name +"\nArtist: " + artist +"\nGenre: " + genre +"\nPrice: " + price +"\nTracks: " + tracks.Length +"\n"; } } }
using UnityEngine; using System.Collections; using System; namespace Ai { public class SleepBehaviour : IAiBehaviour { public SleepBehaviour(ICharacterAi ai) : base(ai) { AiState = AiState.Sleep; } public override int GetBehaviourPoint() { return 0; } public override void DoBehaviour() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace PowerShapeDotNet.Objects { /// <summary> /// class for colour /// style.colour.red /// style.colour.green /// style.colour.blue /// style.colour.rgb /// style.colour.r /// style.colour.g /// style.colour.b /// </summary> public class PSDNRGB { #region PROPIERTIES /// <summary> /// Gets or sets the Red /// </summary> /// <value> /// The Red /// </value> public float R { get; private set; } /// <summary> /// Gets or sets the Green /// </summary> /// <value> /// The Green /// </value> public float G { get; private set; } /// <summary> /// Gets or sets the Blue /// </summary> /// <value> /// The Blue /// </value> public float B { get; private set; } #endregion #region CONSTRUCTORS /// <summary> /// Initializes a new instance of the <see cref="PSDNRGB"/> class. /// </summary> /// <param name="r">Red</param> /// <param name="g">Green</param> /// <param name="b">Blue</param> public PSDNRGB(float r, float g, float b) { this.R = r; this.G = g; this.B = b; } /// <summary> /// Initializes a new instance of the <see cref="PSDNRGB"/> class. /// </summary> /// <param name="rgb">The RGB.</param> public PSDNRGB(object rgb) { //TODO probar a ver k devuelve } /// <summary> /// Initializes a new instance of the <see cref="PSDNRGB"/> class. /// </summary> /// <param name="rgb">The RGB.</param> public PSDNRGB(float[] rgb) { this.R = rgb[0]; this.G = rgb[1]; this.B = rgb[2]; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OnlineTabletop.DTOs { public class FullPlayerDTO { public string _id { get; set; } public string name { get; set; } public string displayName { get; set; } public DateTime joinDate { get; set; } public string email { get; set; } public IList<BasicCharacterDTO> basicCharacters { get; set; } public FullPlayerDTO() { basicCharacters = new List<BasicCharacterDTO>(); } } }
using Catalogo.Domain.ValueObjects; using System.Collections.Generic; namespace Catalogo.Domain.Entities { public class Categoria : EntityBase { protected Categoria() { } public Categoria(string nome, Imagem imagem) { Nome = nome; Imagem = imagem; } public string Nome { get; private set; } public Imagem Imagem { get; private set; } public IEnumerable<Produto> Produtos { get; private set; } public void SetUpdate(string nome, Imagem imagem) { Nome = nome; Imagem = imagem; } } }
using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; using MVC.Models; using System.Collections.Immutable; using System.Collections.ObjectModel; using MySqlX.XDevAPI; namespace MVC.Controllers { [Route("/file")] public class FileController : ControllerBase { [HttpPost] [Route("Get1/{parameter}")] public String GetMessage(string kind,string region) { if (region == "All") { MessagerDb db = new MessagerDb(); List<Message> msList = db.GetAllMessage(); string a = "["; foreach (Message message in msList) { a += message.toJson(); if (msList.IndexOf(message) < msList.Count - 1) { a += ","; } } a += "]"; return a; } else { MessagerDb db = new MessagerDb(); List<Message> msList = db.GetMessage(region); string a = "["; foreach (Message message in msList) { a += message.toJson(); if (msList.IndexOf(message) < msList.Count - 1) { a += ","; } } a += "]"; return a; } } [Route("Get2/{parameter}")] public string GetReplies(string msid) { MessagerDb db = new MessagerDb(); List<Reply> rpList = db.GetReply(msid); string a = "["; foreach (Reply reply in rpList) { a += reply.toJson(); if (rpList.IndexOf(reply) < rpList.Count - 1) { a += ","; } } a += "]"; return a; } [Route("Get3/{parameter}")] public string MyReplies(string wxid) { MessagerDb db = new MessagerDb(); List<Reply> rpList = db.GetMyReply(wxid); string a = "["; foreach (Reply reply in rpList) { a += reply.toJson(); if (rpList.IndexOf(reply) < rpList.Count - 1) { a += ","; } } a += "]"; return a; } [Route("Get4/{parameter}")] public string GetId(string wxid) { MessagerDb db = new MessagerDb(); return db.GetId(wxid); } [Route("Upload1/{parameter}")] public void UpMessage(string name, string content, string wxId, string region, string imageId) { Message a = new Message(name, content, wxId, region, imageId); MessagerDb db = new MessagerDb(); db.UploadMessage(a); } [Route("Upload2/{parameter}")] public void UpReply(string name, string content, string wxId, string replyTo, string imageId, string replytowx) { Reply a = new Reply(name,content,wxId,replyTo,imageId, replytowx); MessagerDb db = new MessagerDb(); db.UploadReply(a); } [Route("Upload3/{parameter}")] public void UpName(string name, string imageid,string wxid) { MessagerDb db = new MessagerDb(); db.UploadId(name,imageid, wxid); } [Route("DelMs/{parameter}")] public void DelMs(string msid) { MessagerDb db = new MessagerDb(); db.DeleteMessage(msid); } [Route("DelRp/{parameter}")] public void DelRp(string rpid) { MessagerDb db = new MessagerDb(); db.DeleteReply(rpid); } } }
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Ninject; using Webcorp.Dal; using Webcorp.Model; using System.Threading.Tasks; using System.Linq; using Webcorp.Business; namespace Webcorp.erp.tests { /// <summary> /// Description résumée pour TestDal /// </summary> [TestClass] public class TestDal { public TestDal() { // // TODO: ajoutez ici la logique du constructeur // } private TestContext testContextInstance; /// <summary> ///Obtient ou définit le contexte de test qui fournit ///des informations sur la série de tests active, ainsi que ses fonctionnalités. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Attributs de tests supplémentaires // // Vous pouvez utiliser les attributs supplémentaires suivants lorsque vous écrivez vos tests : // // Utilisez ClassInitialize pour exécuter du code avant d'exécuter le premier test de la classe // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Utilisez ClassCleanup pour exécuter du code une fois que tous les tests d'une classe ont été exécutés // [ClassCleanup()] // public static void MyClassCleanup() { } // // Utilisez TestInitialize pour exécuter du code avant d'exécuter chaque test // [TestInitialize()] // public void MyTestInitialize() { } // // Utilisez TestCleanup pour exécuter du code après que chaque test a été exécuté // [TestCleanup()] // public void MyTestCleanup() { } // static IKernel kernel; [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { kernel = new StandardKernel(new TestModule(), new DalIoc(),new BusinessIoc()); var auth = kernel.Get<IAuthenticationService>(); var uh = kernel.Get<IUtilisateurBusinessHelper<Utilisateur>>(); uh.DeleteAll().Wait(); uh.Create("999", "jcambert", "korben90", "Ambert", "Jean-Christophe", "jc.ambert@gmail.com") .ContinueWith(x => { uh.AddRole(x.Result, "Administrateur"); }) .ContinueWith(x => { uh.Save(); }).ContinueWith(x => { var islogin = auth.Login("999", "jcambert", "korben90"); Assert.IsTrue(islogin.Result); }).Wait() ; } #endregion [TestMethod] public async Task TestDal1() { var repo = kernel.Get<IRepository<Societe>>(); await repo.DeleteAll(); Assert.AreEqual(await repo.CountAll(), 0); await repo.Upsert(new Societe() { Nom = "Soc test",Adresse=new Addresse() }); Assert.AreEqual(await repo.CountAll(), 1); } [TestMethod] public void TestDBContext() { var ctx = kernel.Get<IDbContext>(); ctx.Repository<Article>().DeleteAll().Wait(); var article = new Article() { Code = "Code", Societe = "999" }; var entry=ctx.Upsert(article); Assert.IsTrue(entry.State == EntityState.Added); ctx.SaveChangesAsync().Wait(); Assert.IsTrue(entry.State == EntityState.Unchanged); ((Article)entry.Entity).Libelle = "Nouveau libelle"; Assert.IsTrue(entry.State == EntityState.Modified); ctx.SaveChangesAsync().Wait(); Assert.IsTrue(entry.State == EntityState.Unchanged); ctx.Remove(article); ctx.SaveChangesAsync().Wait(); Assert.AreEqual(ctx.Count<Article>(), 0); } [TestMethod] public async Task TestDBContext1() { var ctx = kernel.Get<IDbContext>(); ctx.Repository<Article>().DeleteAll().Wait(); var ah = kernel.Get<IArticleBusinessHelper<Article>>(); var art0 = await ah.Create("Code Article",ArticleType.FraisGeneraux); var entry = ctx.Entry(art0); Assert.IsNotNull(entry); Assert.IsTrue(entry.State == EntityState.Added); art0.Save().Wait(); Assert.IsTrue(entry.State == EntityState.Unchanged); Assert.AreEqual(ctx.Count<Article>(), 1); } } }
namespace TQVaultAE.GUI.Components { using System.Windows.Forms; public class BufferedTableLayoutPanel : TableLayoutPanel { public BufferedTableLayoutPanel() { DoubleBuffered = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Dapper; using EpicenterV2.Data.Dtos; namespace EpicenterV2.Data.Queries { public class GetAllEpisodesQuery : Base { private const string SelectQuery = @"SELECT * FROM Episode"; public IEnumerable<EpisodeDto> Execute() { return Connection.Query<EpisodeDto>(SelectQuery); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AsmGenerator { public enum OutputMode { Default, ByteArray, FullCSharpArray } }