text
stringlengths
13
6.01M
using UnityEngine; using System.Collections; public class BlacksmithAI : MonoBehaviour { //AI für den Schmied, der für den Spieler gegen Seelen dessen Ausrüstung aufwertet bool inRange; public GameObject upgrade; string dialog; GameObject upgradeInstance; void Start(){ inRange = false; dialog = "Hello " + Persistent.persist.playerName + ", would you like me to take a look over your equipment?"; } void OnTriggerEnter(Collider collider){ //Spieler ist in der Nähe des Schmieds if (collider.tag == "Player") { inRange = true; } } void OnTriggerExit(Collider collider){ //Spieler ist nicht in der Nähe des Schmieds if (collider.tag == "Player") { inRange = false; } } void OnGUI(){ //zeige Dialog wenn der Spieler in der Nähe ist if (inRange && upgradeInstance == null) { GUI.Box (new Rect (0, 0, Screen.width, 30), dialog); } } void Update(){ //wenn der Spieler in der Nähe des Schmieds ist, kommt er durch Drücken von I zum Upgrade-Menü if (Input.GetKey (KeyCode.I) && inRange && upgradeInstance == null) { upgradeInstance = (GameObject)Instantiate (upgrade, new Vector3(0.5f,0.5f,0.5f), Quaternion.identity); } //verlässt der Spieler den Range-Collider des Schmieds, wird das Upgrade-Menu wieder geschlossen else if (!inRange) { Destroy(upgradeInstance); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InterviewCodings.DynamicProgramming { /// <summary> /// #1 - Find Sets Of Numbers That Add Up To 16 /// </summary> class FindNumberSetsSumToN { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PushoverQ { /// <summary> /// The bit bucket logger. /// </summary> class BitBucketLogger : ILog { /// <inheritdoc/> public void Trace(string format, params object[] args) { } /// <inheritdoc/> public void Trace(Exception exception, string format, params object[] args) { } /// <inheritdoc/> public void Debug(string format, params object[] args) { } /// <inheritdoc/> public void Debug(Exception exception, string format, params object[] args) { } /// <inheritdoc/> public void Info(string format, params object[] args) { } /// <inheritdoc/> public void Info(Exception exception, string format, params object[] args) { } /// <inheritdoc/> public void Warn(string format, params object[] args) { } /// <inheritdoc/> public void Warn(Exception exception, string format, params object[] args) { } /// <inheritdoc/> public void Error(string format, params object[] args) { } /// <inheritdoc/> public void Error(Exception exception, string format, params object[] args) { } /// <inheritdoc/> public void Fatal(string format, params object[] args) { } /// <inheritdoc/> public void Fatal(Exception exception, string format, params object[] args) { } } }
using System.Collections.Generic; using StudyEspanol.Data.Managers; using StudyEspanol.Data.Models; namespace StudyEspanol.UI.Screens { public partial class StudentScreen { #region Const Fields public const string STUDENT_SCREEN = "student_screen"; #endregion #region Initialization #endregion } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace LePapeo.Models { public class OpinionViewModel { [ScaffoldColumn(false)] public int id { get; set; } [Display(Prompt = "Valoracion", Description = "Valoracion", Name = "Valoracion ")] [Required(ErrorMessage = "Debe indicar una valoracion para el usuario")] [Range(1,5)] public LePapeoGenNHibernate.Enumerated.LePapeo.ValoracionEnum Valoracion { get; set; } [Required(ErrorMessage = "Debe proporcionar un titulo")] //[DataType(DataType.Password)] [Display(Prompt = "Titulo de la opinion", Description = "Titulo de la opinion", Name = "Titulo ")] public string Titulo { get; set; } [Required(ErrorMessage = "Debe proporcionar un comentario")] //[DataType(DataType.Password)] [Display(Prompt = "Comentario de la opinion", Description = "Comentario de la opinion", Name = "Comentario ")] public string Comentario { get; set; } [Display(Prompt = "Fecha de la opinion", Description = "Fecha de la opinion", Name = "Fecha ")] [DataType(DataType.Date, ErrorMessage = "La fecha introducida debe tener un formato dd/mm/aaaa")] public DateTime Fecha { get; set; } [Required(ErrorMessage = "Debe proporcionar un usuario registrado")] //[DataType(DataType.Password)] [Display(Prompt = "Autor de la opinion", Description = "Autor de la opinion", Name = "Registrado ")] public int Registrado { get; set; } [Required(ErrorMessage = "Debe proporcionar un restaurante")] //[DataType(DataType.Password)] [Display(Prompt = "Objeto de la opinion", Description = "Objeto de la opinion", Name = "Restaurante ")] public int Restaurante { get; set; } } }
using Microsoft.VisualBasic; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace HeladacWeb.Models { public class EmailLogEntry { bool _isRead { get; set; } = false; HelmUser _receiver { get; set; } public bool isDeleted { get { return this.isDeleted_DB; } } public bool isArchived { get { return this.isArchived_DB; } } public Email email { get { return email_DB; } } public virtual HelmUser receiver { get { return _receiver; } } public bool isRead { get { return this.isRead_DB; } } #region dbEntries public string _id = Guid.NewGuid().ToString(); public string id { get { return _id; } set { _id = value; } } public long creationTime_DB { get; set; } = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); [Required] public string userId { get; set; } [ForeignKey("userId")] public HelmUser receiver_DB { get { return _receiver; } set { _receiver = value; } } [Required] public string heladacUserId { get; set; } [ForeignKey("heladacUserId")] public HeladacUser heladacUser_DB { get; set; } [Required] public string senderEmail_DB { get; set; } [Required] public string emailId { get; set; } [ForeignKey("emailId")] public Email email_DB { get; set; } public bool isDeleted_DB { get; set; } = false; public long timeOfDeletionMs_DB { get; set; } public bool isArchived_DB { get; set; } = false; public long timeOfLastArchiveMs_DB { get; set; } public bool isRead_DB { get { return _isRead; } set { _isRead = value; } } JArray _readToggleHistory = null; [NotMapped] public JArray readToggleHistory { get { return (_readToggleHistory ?? (_readToggleHistory = new JArray())); } set { _readToggleHistory = value; } } public string readToggleHistory_DB { get { return this.readToggleHistory.ToString(); } set { this.readToggleHistory = JArray.Parse(value); } } JArray _archiveToggleHistory = null; [NotMapped] public JArray archiveToggleHistory { get { return (_archiveToggleHistory ?? (_archiveToggleHistory = new JArray())); } set { _archiveToggleHistory = value; } } public string archiveToggleHistory_DB { get { return this.archiveToggleHistory.ToString(); } set { this.archiveToggleHistory = JArray.Parse(value); } } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace game { class MapLocation : Point { // Constructor validate if point is on the map // Give constructor instance of the map object // This is done so we can check if map object is indeed on the map public MapLocation(int x, int y, Map map) : base(x, y) { // We want to do something if false so we use ! // If not on the map if (!map.OnMap(this)) { // Throw an exception throw new OutOfBoundsException(x + "," + y + " is outside of the bounds of the map."); } } } }
namespace PmSoft.Utilities { using System; public enum SymmetricEncryptType : byte { DES = 0, RC2 = 1, Rijndael = 2, TripleDES = 3 } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// This script controls non-playable character (NPC) walking behaviour. /// Certain NPCs will wander back and forth at the homebase. /// </summary> public class NPCWalk : MonoBehaviour { public float paceSpeed; Rigidbody2D rb; public float timer; public float directionx; // Use this for initialization void Start() { rb = GetComponent<Rigidbody2D>(); StartCoroutine(Move(timer)); } IEnumerator Move(float timer) { while (true) { Vector2 targetVelocity = new Vector2(directionx, 0); GetComponent<SpriteRenderer>().flipX = true; rb.velocity = targetVelocity * paceSpeed; yield return new WaitForSeconds(timer); Vector2 targetVelocity1 = new Vector2(-directionx, 0); GetComponent<SpriteRenderer>().flipX = false; rb.velocity = targetVelocity1 * paceSpeed; yield return new WaitForSeconds(timer); //yield break; } } }
namespace FirstWebApp.Data { public class Sound { public int Id { get; set; } public string Loudspeaker { get; set; } public string TreeFiveMMJack { get; set; } public string Other { get; set; } } }
using UnityEngine; using UnityEditor; using System.IO; using System; namespace CoreEditor.AssemblyPacker { public static class SaveImageAsSource { const string ScriptTemplate = @" public static partial class TextureByteArray {{ public static readonly byte[] {0} = new byte[]{{0x{1}}}; }} "; [MenuItem("Assets/Save Image as Source", true)] public static bool Validate() { return Selection.objects.Length>0; } [MenuItem("Assets/Save Image as Source",false)] public static void Run() { foreach( var obj in Selection.objects ) { if ( obj is Texture2D ) { var path = AssetDatabase.GetAssetPath( obj ); var bytes = File.ReadAllBytes( path ); string hex = BitConverter.ToString(bytes); hex = hex.Replace("-",",0x"); var name = Path.GetFileNameWithoutExtension( path ).Replace( " ", "_"); var fullSource = string.Format( ScriptTemplate, name, hex ); var destination = Path.GetDirectoryName( path) + "/" + Path.GetFileNameWithoutExtension(path) + ".cs"; File.WriteAllText( destination, fullSource ); AssetDatabase.ImportAsset( destination ); } } } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Amazon.DynamoDBv2.DataModel; using NotesApp.Complete.Model; namespace NotesApp.Complete.Repository { public class NoteRepository : INoteRepository { private readonly IDynamoDBContext context; public NoteRepository(IDynamoDBContext context) { this.context = context; } public async Task<IEnumerable<Note>> GetNotes() { var notes = new List<Note>(); var search = context.ScanAsync<Note>(Enumerable.Empty<ScanCondition>()); while(!search.IsDone) { notes.AddRange(await search.GetNextSetAsync()); } return notes; } public Task Save(Note note) { return context.SaveAsync(note); } } }
using UnityEngine; using System.Collections; public class MoveRex1 : MonoBehaviour { Animator anim; public GameObject firePrefab; //flamethrower prefab public Rigidbody wall; //wall of fire prefab public Rigidbody projectile; //projectile prefab public Transform fbSpawn;//spawn the projectile public Transform fireSpawn;//spawn the flamethrower IEnumerator fireproj(){ yield return new WaitForSeconds(0.75f); Rigidbody fb = GetComponent<Rigidbody>(); fb = Instantiate(projectile,fbSpawn.position,fbSpawn.rotation) as Rigidbody; fb.AddForce (-fbSpawn.forward * 1000); Destroy (fb.gameObject,2.5f); } IEnumerator firesprd2(){ yield return new WaitForSeconds (1.5f); Rigidbody fb1 = GetComponent<Rigidbody> (); fb1 = Instantiate (wall, new Vector3 (503.0f, 1.0f, 490.0f), Quaternion.Euler(0,90,0)) as Rigidbody; Rigidbody fb2 = GetComponent<Rigidbody> (); fb2 = Instantiate (wall, new Vector3 (503.0f, 1.0f, 500.0f), Quaternion.Euler(0,90,0)) as Rigidbody; Rigidbody fb3 = GetComponent<Rigidbody> (); fb3 = Instantiate (wall, new Vector3 (503.0f, 1.0f, 507.0f), Quaternion.Euler(0,90,0)) as Rigidbody; Destroy (fb1.gameObject, 7.5f); Destroy (fb2.gameObject, 7.5f); Destroy (fb3.gameObject, 7.5f); } IEnumerator firesprd1(){ yield return new WaitForSeconds (0.5f); GameObject spreadfire; spreadfire = Instantiate (firePrefab, fireSpawn.position,Quaternion.Euler(0,180,0)) as GameObject; Destroy (spreadfire.gameObject,1.5f); StartCoroutine ("firesprd2"); } void Start () { anim = GetComponent<Animator>(); } void Fireball(){ anim.SetTrigger ("spitFireball"); StartCoroutine ("fireproj"); //Damage code } void Bite(){ anim.SetTrigger ("bite"); } void SpreadFire(){ anim.SetTrigger ("spreadFire"); StartCoroutine ("firesprd1"); } void TailAttack(){ anim.SetTrigger ("tailAttack"); } // Update is called once per frame void Update () { if (Input.GetKey ("up")) Fireball (); if (Input.GetKey ("down")) Bite (); if (Input.GetKey ("right")) SpreadFire (); if (Input.GetKey ("left")) TailAttack (); } }
using NutritionalResearchBusiness.DAL; using System; using System.Collections.Generic; using System.Linq; using System.Text; using NutritionalResearchBusiness.Dtos; namespace NutritionalResearchBusiness { public interface INRDataProcessService { //void CreateFoodNutritionsForTesting(List<FoodNutritionsPostDto> datas); //List<Foods> GetFoodsList(); NutritionalResearchStatisticalReportViewDto GetSomeoneRecordStatisticalReport(Guid recordId); int ExportNutritionalResearchReport2Excel(InvestigationRecordQueryConditions conditions,string fileName); int ExportNutritionalInvestigationRecords2Excel(InvestigationRecordQueryConditions conditions, string fileName); void ExportNutritionalAnalysisReport2Excel(Guid recordId, string fileName); void ImportIntakeRecordsExcel(string fileName, out int insertRow, out int existRow); void ExportNutritionalAnalysisReport2Print(Guid recordId); } public class FoodNutritionsPostDto { public Guid FoodId { get; set; } public Guid NutritiveElementId { get; set; } public double Value { get; set; } } }
using System; namespace Arch.Data.Orm.sql { public interface IDataBridge { Boolean Readable { get; } Boolean Writeable { get; } Object Read(Object obj); void Write(Object obj, Object value); Type DataType { get; } } }
using FindSelf.Domain.SeedWork; using System; namespace FindSelf.Domain.Entities.UserAggregate { public class UserTransferSuccessEvent : IDomainEvent { public User User { get; } public User Recevier { get; } public decimal Amount { get; } public DateTime OccurredOn { get; } = DateTime.Now; public UserTransferSuccessEvent(User user, User recevier, decimal amount) { User = user; Recevier = recevier; Amount = amount; } } }
using PurificationPioneer.Const; using PurificationPioneer.Scriptable; using ReadyGamerOne.Utility; using ReadyGamerOne.View; using UnityEngine; namespace PurificationPioneer.Script { public class HomeSceneMgr : PpSceneMgr<HomeSceneMgr> { public Transform m_GenPoint; private GameObject m_CurrentHero; protected override void Start() { base.Start(); PanelMgr.PushPanel(PanelName.HomePanel); } public RenderTexture UpdateHeroPreview(HeroConfigAsset heroConfigAsset) { if (m_CurrentHero) { Destroy(m_CurrentHero); } m_CurrentHero = Instantiate(heroConfigAsset.PreviewPrefab); m_CurrentHero.transform.position = m_GenPoint.position; var mainc = Camera.main; var rt = mainc.targetTexture; if (rt == null) { rt = RenderTexture.GetTemporary(1024, 1024); mainc.targetTexture = rt; } return rt; } } }
using System; using System.Collections.Generic; #nullable disable namespace DesiClothing4u.Common.Models { public partial class StorePickupPoint { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public int AddressId { get; set; } public decimal PickupFee { get; set; } public string OpeningHours { get; set; } public int DisplayOrder { get; set; } public int StoreId { get; set; } public decimal? Latitude { get; set; } public decimal? Longitude { get; set; } public int? TransitDays { get; set; } } }
using System; using StudyEspanol.Data; using StudyEspanol.Data.Managers; using StudyEspanol.UI.Views; namespace StudyEspanol.UI.Screens { public partial class SearchScreen : Screen { #region Const Fields public const string QUERY = "query"; public const string CONJUGATION = "conjugation"; public const string TRANSLATE = "translate"; public const string MAX_NUMBER = "max_number"; #endregion #region Fields private bool randomize = false; private int maxWords = 0; private int translationDirection; private Type nextScreen; #endregion #region Delegate public delegate void CreateQueryHandler(Query query); #endregion #region Events public event CreateQueryHandler OnCreateQuery; #endregion #region Initialization protected override void Initialization() { base.Initialization(); FindViews(); InitializeViews(); OnCreateQuery += CreateQuery; } #endregion #region Partial Methods partial void FindViews(); partial void InitializeViews(); partial void CreateQuery(Query query); #endregion #region Methods private Query SendSearchEvent() { if (OnCreateQuery != null) { Query query = new Query(); OnCreateQuery(query); Query.OrderBy order = Query.OrderBy.Random; if (!randomize) { if (translationDirection == 0) { order = Query.OrderBy.AlphabeticalEnglish; } else { order = Query.OrderBy.AlphabeticalSpanish; } } query.EndStatement(order); return query; } return null; } #endregion } }
namespace Plus.Communication.Packets.Outgoing.Messenger { internal class FindFriendsProcessResultComposer : MessageComposer { public bool Found { get; } public FindFriendsProcessResultComposer(bool found) : base(ServerPacketHeader.FindFriendsProcessResultMessageComposer) { Found = found; } public override void Compose(ServerPacket packet) { packet.WriteBoolean(Found); } } }
using System; using System.Collections.Generic; using System.Xml.Linq; using System.Linq; using UnityEngine; namespace Yasl { public class Vector4Serializer : StructSerializer<Vector4> { public Vector4Serializer() { } public override void SerializeConstructor(ref Vector4 value, ISerializationWriter writer) { writer.Write<float>("W", value.w); writer.Write<float>("X", value.x); writer.Write<float>("Y", value.y); writer.Write<float>("Z", value.z); } public override void DeserializeConstructor(out Vector4 value, int version, ISerializationReader reader) { value.w = reader.Read<float>("W"); value.x = reader.Read<float>("X"); value.y = reader.Read<float>("Y"); value.z = reader.Read<float>("Z"); } } }
using System; namespace Tff.Panzer.Models.Geography { public enum WeatherZoneEnum { Desert = 0, Mediterrian = 1, WesternEurope = 2, EasternEurope = 3 } }
using System.Collections.Generic; namespace scrape_getfpv_com { public class Category { public string Name { get; set; } public string Link { get; set; } public List<Category> Children { get; set; } = new List<Category>(); public bool Checked { get; set; } = false; public int HowManyItems { get; set; } = 0; } }
/* * 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> /// All the partnership info that&#39;s fit to expose externally, if we care to do so. /// </summary> [DataContract] public partial class PartnershipsPublicPartnershipDetail : IEquatable<PartnershipsPublicPartnershipDetail>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="PartnershipsPublicPartnershipDetail" /> class. /// </summary> /// <param name="PartnerType">PartnerType.</param> /// <param name="Identifier">Identifier.</param> /// <param name="Name">Name.</param> /// <param name="Icon">Icon.</param> public PartnershipsPublicPartnershipDetail(PartnershipsPartnershipType PartnerType = default(PartnershipsPartnershipType), string Identifier = default(string), string Name = default(string), string Icon = default(string)) { this.PartnerType = PartnerType; this.Identifier = Identifier; this.Name = Name; this.Icon = Icon; } /// <summary> /// Gets or Sets PartnerType /// </summary> [DataMember(Name="partnerType", EmitDefaultValue=false)] public PartnershipsPartnershipType PartnerType { get; set; } /// <summary> /// Gets or Sets Identifier /// </summary> [DataMember(Name="identifier", EmitDefaultValue=false)] public string Identifier { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets Icon /// </summary> [DataMember(Name="icon", EmitDefaultValue=false)] public string Icon { 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 PartnershipsPublicPartnershipDetail {\n"); sb.Append(" PartnerType: ").Append(PartnerType).Append("\n"); sb.Append(" Identifier: ").Append(Identifier).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Icon: ").Append(Icon).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 PartnershipsPublicPartnershipDetail); } /// <summary> /// Returns true if PartnershipsPublicPartnershipDetail instances are equal /// </summary> /// <param name="input">Instance of PartnershipsPublicPartnershipDetail to be compared</param> /// <returns>Boolean</returns> public bool Equals(PartnershipsPublicPartnershipDetail input) { if (input == null) return false; return ( this.PartnerType == input.PartnerType || (this.PartnerType != null && this.PartnerType.Equals(input.PartnerType)) ) && ( this.Identifier == input.Identifier || (this.Identifier != null && this.Identifier.Equals(input.Identifier)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Icon == input.Icon || (this.Icon != null && this.Icon.Equals(input.Icon)) ); } /// <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.PartnerType != null) hashCode = hashCode * 59 + this.PartnerType.GetHashCode(); if (this.Identifier != null) hashCode = hashCode * 59 + this.Identifier.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.Icon != null) hashCode = hashCode * 59 + this.Icon.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 System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LostAndFound.Models { interface IUserModel { string name { get; set; } string lastName { get; set; } string username { get; set; } string email { get; set; } string password { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Utils { public class MicrosCheck { public string Pcws { get; set; } public string CheckNumber { get; set; } public string EdiNumber { get; set; } public string Fecha { get; set; } public string Hora { get; set; } public int Alimentos { get; set; } public int BebidasCAlcohol { get; set; } public int BebidasSAlcohol { get; set; } public int Tabacos { get; set; } public int Otros { get; set; } public int TotalNeto { get; set; } public int TotalExento { get; set; } public int Iva { get; set; } public int Descuentos { get; set; } public int Propinas { get; set; } public int VentasTotales { get; set; } public Dictionary<int, int> Payments { get; set; } public MicrosCheck() { Alimentos = BebidasCAlcohol = BebidasSAlcohol = Tabacos = Otros = TotalNeto = TotalExento = Iva = VentasTotales = 0; } } }
using SQLite; namespace OPAM.Interface { public interface ISQLite { string PrepareAppPath(string fileName); SQLiteConnection GetConnection(); SQLiteConnection GetConnection(string filePath); } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("HeroCoin")] public class HeroCoin : PegUIElement { public HeroCoin(IntPtr address) : this(address, "HeroCoin") { } public HeroCoin(IntPtr address, string className) : base(address, className) { } public void Awake() { base.method_8("Awake", Array.Empty<object>()); } public void EnableInput() { base.method_8("EnableInput", Array.Empty<object>()); } public void FinishIntroScaling() { base.method_8("FinishIntroScaling", Array.Empty<object>()); } public string GetLessonAssetName() { return base.method_13("GetLessonAssetName", Array.Empty<object>()); } public int GetMissionId() { return base.method_11<int>("GetMissionId", Array.Empty<object>()); } public void HideTooltip() { base.method_8("HideTooltip", Array.Empty<object>()); } public void OnDestroy() { base.method_8("OnDestroy", Array.Empty<object>()); } public void OnGameLoaded(SceneMgr.Mode mode, Scene scene, object userData) { object[] objArray1 = new object[] { mode, scene, userData }; base.method_8("OnGameLoaded", objArray1); } public void OnOut(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnOut", objArray1); } public void OnOver(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnOver", objArray1); } public void OnPress(UIEvent e) { object[] objArray1 = new object[] { e }; base.method_8("OnPress", objArray1); } public void OnUpdateAlphaVal(float val) { object[] objArray1 = new object[] { val }; base.method_8("OnUpdateAlphaVal", objArray1); } public void SetCoinInfo(Vector2 goldTexture, Vector2 grayTexture, Vector2 crackTexture, int missionID) { object[] objArray1 = new object[] { goldTexture, grayTexture, crackTexture, missionID }; base.method_8("SetCoinInfo", objArray1); } public void SetLessonAssetName(string lessonAssetName) { object[] objArray1 = new object[] { lessonAssetName }; base.method_8("SetLessonAssetName", objArray1); } public void SetProgress(CoinStatus status) { object[] objArray1 = new object[] { status }; base.method_8("SetProgress", objArray1); } public void ShowTooltip() { base.method_8("ShowTooltip", Array.Empty<object>()); } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void StartNextTutorial() { base.method_8("StartNextTutorial", Array.Empty<object>()); } public GameObject m_coin { get { return base.method_3<GameObject>("m_coin"); } } public UberText m_coinLabel { get { return base.method_3<UberText>("m_coinLabel"); } } public GameObject m_coinX { get { return base.method_3<GameObject>("m_coinX"); } } public GameObject m_cracks { get { return base.method_3<GameObject>("m_cracks"); } } public Vector2 m_crackTexture { get { return base.method_2<Vector2>("m_crackTexture"); } } public CoinStatus m_currentStatus { get { return base.method_2<CoinStatus>("m_currentStatus"); } } public GameObject m_explosionPrefab { get { return base.method_3<GameObject>("m_explosionPrefab"); } } public Vector2 m_goldTexture { get { return base.method_2<Vector2>("m_goldTexture"); } } public Material m_grayMaterial { get { return base.method_3<Material>("m_grayMaterial"); } } public Vector2 m_grayTexture { get { return base.method_2<Vector2>("m_grayTexture"); } } public HighlightState m_highlight { get { return base.method_3<HighlightState>("m_highlight"); } } public bool m_inputEnabled { get { return base.method_2<bool>("m_inputEnabled"); } } public GameObject m_leftCap { get { return base.method_3<GameObject>("m_leftCap"); } } public string m_lessonAssetName { get { return base.method_4("m_lessonAssetName"); } } public Vector2 m_lessonCoords { get { return base.method_2<Vector2>("m_lessonCoords"); } } public Material m_material { get { return base.method_3<Material>("m_material"); } } public GameObject m_middle { get { return base.method_3<GameObject>("m_middle"); } } public int m_missionID { get { return base.method_2<int>("m_missionID"); } } public bool m_nextTutorialStarted { get { return base.method_2<bool>("m_nextTutorialStarted"); } } public float m_originalMiddleWidth { get { return base.method_2<float>("m_originalMiddleWidth"); } } public Vector3 m_originalPosition { get { return base.method_2<Vector3>("m_originalPosition"); } } public Vector3 m_originalXPosition { get { return base.method_2<Vector3>("m_originalXPosition"); } } public GameObject m_rightCap { get { return base.method_3<GameObject>("m_rightCap"); } } public GameObject m_tooltip { get { return base.method_3<GameObject>("m_tooltip"); } } public UberText m_tooltipText { get { return base.method_3<UberText>("m_tooltipText"); } } public enum CoinStatus { ACTIVE, DEFEATED, UNREVEALED, UNREVEALED_TO_ACTIVE, ACTIVE_TO_DEFEATED } } }
using UnityEngine; using System.Collections; public class TitleMenu : MonoBehaviour { // GUI Style for the background public GUIStyle backgroundStyle; // GUI Style for the play button public GUIStyle playButtonStyle; // GUI Style for the instructions button public GUIStyle instructionButtonStyle; void OnGUI() { GUI.Box(new Rect(0, 0, Screen.width, Screen.height), "", backgroundStyle); if (GUI.Button(new Rect( Screen.width - 636, Screen.height - 304, 256, 96), "", playButtonStyle)) { Application.LoadLevel("loading"); } if (GUI.Button(new Rect( Screen.width - 636, Screen.height - 192, 256, 96), "", instructionButtonStyle)) { // Go to the instructions screen Application.LoadLevel("instructions"); } } }
namespace JetBrains.Annotations { using System; using System.Runtime.CompilerServices; [BaseTypeRequired(typeof(Attribute)), AttributeUsage(AttributeTargets.Class, AllowMultiple=true, Inherited=true)] public sealed class BaseTypeRequiredAttribute : Attribute { [CompilerGenerated] private Type[] type_0; public BaseTypeRequiredAttribute(Type baseType) { this.BaseTypes = new Type[] { baseType }; } public Type[] BaseTypes { [CompilerGenerated] get { return this.type_0; } [CompilerGenerated] private set { this.type_0 = value; } } } }
using Moq; using System; using System.Linq; using TreeStore.Model; using TreeStore.PsModule.PathNodes; using Xunit; namespace TreeStore.PsModule.Test.PathNodes { public class CategoryNodeTest : NodeTestBase { #region P2F node structure [Fact] public void CategoryNode_has_name_and_ItemMode() { // ACT var result = new CategoryNode(DefaultCategory()); // ASSERT Assert.Equal("c", result.Name); } [Fact] public void CategoryNode_provides_Value() { // ACT var result = new CategoryNode(DefaultCategory()); // ASSERT Assert.Equal("c", result.Name); Assert.True(result.IsContainer); } #endregion P2F node structure #region IGetItem [Fact] public void CategoryNode_provides_Item() { // ARRANGE var c = DefaultCategory(); // ACT var result = new CategoryNode(c).GetItem(this.ProviderContextMock.Object); // ASSERT Assert.Equal(c.Id, result.Property<Guid>("Id")); Assert.Equal(c.Name, result.Property<string>("Name")); Assert.Equal(TreeStoreItemType.Category, result.Property<TreeStoreItemType>("ItemType")); Assert.IsType<CategoryNode.Item>(result.ImmediateBaseObject); } #endregion IGetItem #region IGetItemProperties [Fact] public void CategoryNode_retrieves_all_properties() { // ARRANGE var c = DefaultCategory(); // ACT var result = new CategoryNode(c).GetItemProperties(this.ProviderContextMock.Object, Enumerable.Empty<string>()).ToArray(); // ASSERT Assert.Equal(new[] { "Id", "Name", "ItemType" }, result.Select(r => r.Name)); } [Fact] public void CategoryNode_retrieves_specified_property() { // ARRANGE var c = DefaultCategory(); // ACT var result = new CategoryNode(c).GetItemProperties(this.ProviderContextMock.Object, "NAME".Yield()).ToArray(); // ASSERT Assert.Equal("Name", result.Single().Name, StringComparer.OrdinalIgnoreCase); } #endregion IGetItemProperties #region IGetChildItem [Fact] public void CategoryNode_retrieves_categories_and_entities_as_childnodes() { // ARRANGE var subcategory = DefaultCategory(c => c.Name = "cc"); var category = DefaultCategory(WithSubCategory(subcategory)); var entity = DefaultEntity(e => e.Category = category); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(p => p.FindByParent(category)) .Returns(subcategory.Yield()); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategory(category)) .Returns(entity.Yield()); var node = new CategoryNode(category); // ACT var result = node.GetChildNodes(this.ProviderContextMock.Object).ToArray(); // ASSERT Assert.Equal(2, result.Length); } #endregion IGetChildItem #region Resolve [Theory] [InlineData("e")] [InlineData("E")] public void CategoryNode_resolves_child_name_as_Entity(string name) { // ARRANGE var category = DefaultCategory(); var entity = DefaultEntity(e => e.Category = category); this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(category, name)) .Returns(entity); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(p => p.FindByParentAndName(category, name)) .Returns((Category?)null); var node = new CategoryNode(category); // ACT var result = node.Resolve(this.ProviderContextMock.Object, name).Single(); // ASSERT Assert.Equal(entity.Id, ((EntityNode.Item)result.GetItem(this.ProviderContextMock.Object).ImmediateBaseObject).Id); } [Theory] [InlineData("cc")] [InlineData("CC")] public void CategoryNode_resolves_child_name_as_Category(string name) { // ARRANGE var subCategory = DefaultCategory(c => c.Name = "cc"); var category = DefaultCategory(WithSubCategory(subCategory)); this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, name)) .Returns(subCategory); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(category, name)) .Returns((Entity?)null); var node = new CategoryNode(category); // ACT var result = node.Resolve(this.ProviderContextMock.Object, name).Single(); // ASSERT Assert.Equal(subCategory.Id, ((CategoryNode.Item)result.GetItem(this.ProviderContextMock.Object).ImmediateBaseObject).Id); } #endregion Resolve #region INewItem [Fact] public void CategoryNode_provides_NewItemTypesNames() { // ARRANGE var node = new CategoryNode(DefaultCategory()); // ACT var result = node.NewItemTypeNames; // ASSERT Assert.Equal(new[] { nameof(TreeStoreItemType.Category), nameof(TreeStoreItemType.Entity) }, result); } [Theory] [InlineData(null)] [InlineData(nameof(TreeStoreItemType.Entity))] public void CategoryNode_creates_entity(string itemTypeName) { // ARRANGE //todo: create entity with tag //this.ProviderContextMock // .Setup(c => c.DynamicParameters) // .Returns((object?)null); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Categories) .Returns(this.CategoryRepositoryMock.Object); var category = DefaultCategory(); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, "Entity")) .Returns((Category?)null); this.PersistenceMock .Setup(m => m.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(category, "Entity")) .Returns((Entity?)null); Entity createdEntity = null; this.EntityRepositoryMock .Setup(r => r.Upsert(It.Is<Entity>(t => t.Name.Equals("Entity")))) .Callback<Entity>(e => createdEntity = e) .Returns<Entity>(e => e); var node = new CategoryNode(category); // ACT var result = node.NewItem(this.ProviderContextMock.Object, newItemName: "Entity", itemTypeName: itemTypeName, newItemValue: null!); // ASSERT Assert.IsType<EntityNode>(result); Assert.Equal("Entity", createdEntity!.Name); Assert.Same(category, createdEntity!.Category); } [Fact] public void CategoryNode_rejects_creating_EntityNodeValue_with_duplicate_entity_name() { // ARRANGE //todo: create entity with tag //this.ProviderContextMock // .Setup(c => c.DynamicParameters) // .Returns((object?)null); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); var category = DefaultCategory(); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, "Entity")) .Returns((Category?)null); this.PersistenceMock .Setup(m => m.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(category, "Entity")) .Returns(DefaultEntity()); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: "Entity", itemTypeName: nameof(TreeStoreItemType.Entity), newItemValue: null!)); // ASSERT Assert.Equal($"Name is already used by and item of type '{nameof(TreeStoreItemType.Entity)}'", result.Message); } [Fact] public void CategoryNode_rejects_creating_EntityNodeValue_with_duplicate_category_name() { // ARRANGE //todo: create entity with tag //this.ProviderContextMock // .Setup(c => c.DynamicParameters) // .Returns((object?)null); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); var category = DefaultCategory(); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, "Entity")) .Returns(DefaultCategory()); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: "Entity", itemTypeName: nameof(TreeStoreItemType.Entity), newItemValue: null!)); // ASSERT Assert.Equal($"Name is already used by and item of type '{nameof(TreeStoreItemType.Category)}'", result.Message); } [Fact] public void CategoryNode_creates_category() { // ARRANGE this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Categories) .Returns(this.CategoryRepositoryMock.Object); var category = DefaultCategory(); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, "c")) .Returns((Category?)null); this.CategoryRepositoryMock .Setup(r => r.Upsert(It.Is<Category>(c => c.Name.Equals("c")))) .Returns<Category>(c => c); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(category, "c")) .Returns((Entity?)null); var node = new CategoryNode(category); // ACT var result = node.NewItem(this.ProviderContextMock.Object, newItemName: "c", itemTypeName: nameof(TreeStoreItemType.Category), newItemValue: null!); // ASSERT Assert.IsType<CategoryNode>(result); } [Fact] public void CategoryNode_creating_category_fails_on_duplicate_entity_name() { // ARRANGE this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Categories) .Returns(this.CategoryRepositoryMock.Object); var category = DefaultCategory(); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, "c")) .Returns((Category?)null); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(category, "c")) .Returns(DefaultEntity()); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: "c", itemTypeName: nameof(TreeStoreItemType.Category), newItemValue: null!)); // ASSERT Assert.Equal($"Name is already used by and item of type '{nameof(TreeStoreItemType.Entity)}'", result.Message); } [Fact] public void CategoryNode_creating_category_fails_on_duplicate_category_name() { // ARRANGE this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Categories) .Returns(this.CategoryRepositoryMock.Object); var category = DefaultCategory(); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(category, "c")) .Returns(DefaultCategory()); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: "c", itemTypeName: nameof(TreeStoreItemType.Category), newItemValue: null!)); // ASSERT Assert.Equal($"Name is already used by and item of type '{nameof(TreeStoreItemType.Category)}'", result.Message); } [Theory] [MemberData(nameof(InvalidNameChars))] public void CategoryNode_creating_rejects_invalid_name_chararcters(char invalidChar) { // ARRANGE var category = DefaultCategory(c => c.Name = "c"); var invalidName = new string("p".ToCharArray().Append(invalidChar).ToArray()); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, invalidName, itemTypeName: nameof(TreeStoreItemType.Category), newItemValue: null)); // ASSERT Assert.Equal($"category(name='{invalidName}' wasn't created: it contains invalid characters", result.Message); } [Theory] [MemberData(nameof(InvalidNodeNames))] public void CategoryNode_creating_item_rejects_entity_with_reserved_name(string nodeName) { // ARRANGE var category = DefaultCategory(c => c.Name = "c"); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: nodeName, itemTypeName: nameof(TreeStoreItemType.Entity), newItemValue: null!)); // ASSERT Assert.Equal($"category(name='{nodeName}' wasn't created: Name '{nodeName}' is reserved for future use.", result.Message); } [Theory] [MemberData(nameof(InvalidNodeNames))] public void CategoryNode_creating_item_rejects_category_with_reserved_name(string nodeName) { // ARRANGE var category = DefaultCategory(c => c.Name = "c"); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.NewItem(this.ProviderContextMock.Object, newItemName: nodeName, itemTypeName: nameof(TreeStoreItemType.Category), newItemValue: null!)); // ASSERT Assert.Equal($"category(name='{nodeName}' wasn't created: Name '{nodeName}' is reserved for future use.", result.Message); } #endregion INewItem #region ICopyItem [Fact] public void CategoryNode_copies_itself_as_new_category() { // ARRANGE this.ArrangeSubCategory(out var rootCategory, out var subCategory); this.CategoryRepositoryMock .Setup(r => r.Root()) .Returns(rootCategory); this.CategoryRepositoryMock // destination name is unused .Setup(r => r.FindByParentAndName(rootCategory, "cc")) .Returns((Category?)null); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock // destination name is unused .Setup(r => r.FindByCategoryAndName(rootCategory, "cc")) .Returns((Entity?)null); this.ProviderContextMock .Setup(p => p.Recurse) .Returns(false); this.PersistenceMock .Setup(p => p.CopyCategory(subCategory, rootCategory, false)); var entityContainer = new EntitiesNode(); // ACT new CategoryNode(subCategory).CopyItem(this.ProviderContextMock.Object, "c", "cc", entityContainer); } [Theory] [InlineData("e-src", (string?)null, "e-src")] [InlineData("e-src", "e-dst", "e-dst")] public void CategoryNode_copies_itself_to_category(string initialName, string destinationName, string resultName) { // ARRANGE this.ArrangeSubCategory(out var rootCategory, out var subCategory); this.CategoryRepositoryMock .Setup(r => r.FindById(subCategory.Id)) .Returns(subCategory); var category = DefaultCategory(c => rootCategory.AddSubCategory(c)); this.CategoryRepositoryMock // destination name is unused .Setup(r => r.FindByParentAndName(subCategory, resultName)) .Returns((Category?)null); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock // detsinatin name is unused .Setup(r => r.FindByCategoryAndName(subCategory, resultName)) .Returns((Entity?)null); this.ProviderContextMock .Setup(p => p.Recurse) .Returns(true); this.PersistenceMock .Setup(p => p.CopyCategory(category, subCategory, true)); var categoryContainer = new CategoryNode(subCategory); // ACT new CategoryNode(category) .CopyItem(this.ProviderContextMock.Object, initialName, destinationName, categoryContainer); } [Theory] [InlineData("e-src", (string?)null, "e-src")] [InlineData("e-src", "e-dst", "e-dst")] public void CategoryNode_copying_fails_if_entity_name_already_exists(string initialName, string destinationName, string resultName) { // ARRANGE this.ArrangeSubCategory(out var rootCategory, out var subCategory); this.CategoryRepositoryMock .Setup(r => r.Root()) .Returns(rootCategory); this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(rootCategory, resultName)) .Returns((Category?)null); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(rootCategory, resultName)) .Returns(DefaultEntity(e => e.Name = resultName)); var entitiesNode = new EntitiesNode(); var category = DefaultCategory(c => subCategory.AddSubCategory(c)); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>( () => node.CopyItem(this.ProviderContextMock.Object, initialName, destinationName, entitiesNode)); // ASSERT Assert.Equal($"Destination container contains already an entity with name '{resultName}'", result.Message); } [Theory] [InlineData("e-src", (string?)null, "e-src")] [InlineData("e-src", "e-dst", "e-dst")] public void CategoryNode_copying_fails_if_category_name_already_exists(string initialName, string destinationName, string resultName) { // ARRANGE this.ArrangeSubCategory(out var rootCategory, out var subCategory); this.CategoryRepositoryMock .Setup(r => r.Root()) .Returns(rootCategory); this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(rootCategory, resultName)) .Returns(DefaultCategory()); var entitiesNode = new EntitiesNode(); var category = DefaultCategory(c => subCategory.AddSubCategory(c)); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>( () => node.CopyItem(this.ProviderContextMock.Object, initialName, destinationName, entitiesNode)); // ASSERTS Assert.Equal($"Destination container contains already a category with name '{resultName}'", result.Message); } [Theory] [MemberData(nameof(InvalidNameChars))] public void CategoryNode_copying_rejects_invalid_name_chararcters(char invalidChar) { // ARRANGE var category = DefaultCategory(c => c.Name = "c"); var invalidName = new string("p".ToCharArray().Append(invalidChar).ToArray()); var entitiesNode = new EntitiesNode(); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.CopyItem(this.ProviderContextMock.Object, "c", invalidName, entitiesNode)); // ASSERT Assert.Equal($"category(name='{invalidName}' wasn't created: it contains invalid characters", result.Message); } #endregion ICopyItem #region IRenameItem [Fact] public void CategoryNode_renames_itself() { // ARRANGE var category = DefaultCategory(); var parentCategory = DefaultCategory(WithSubCategory(category)); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(m => m.Categories) .Returns(this.CategoryRepositoryMock.Object); Category? renamedCategory = null; this.CategoryRepositoryMock .Setup(r => r.Upsert(It.IsAny<Category>())) .Callback<Category>(c => renamedCategory = c) .Returns(category); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(parentCategory, "cc")) .Returns((Category)null); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(p => p.FindByCategoryAndName(parentCategory, "cc")) .Returns((Entity?)null); var categoryNode = new CategoryNode(category); // ACT categoryNode.RenameItem(this.ProviderContextMock.Object, "c", "cc"); // ASSERT Assert.Equal("cc", renamedCategory!.Name); } [Theory] [InlineData("e")] [InlineData("E")] public void CategoryNode_renaming_rejects_duplicate_entity_name(string existingName) { // ARRANGE var category = DefaultCategory(); var parentCategory = DefaultCategory(WithSubCategory(category)); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); var entity = DefaultEntity(e => e.Name = existingName); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(p => p.FindByCategoryAndName(parentCategory, existingName)) .Returns(entity); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(parentCategory, existingName)) .Returns((Category?)null); var categoryNode = new CategoryNode(category); // ACT categoryNode.RenameItem(this.ProviderContextMock.Object, "c", existingName); // ASSERT Assert.Equal("c", category.Name); } [Theory] [InlineData("cc")] [InlineData("CC")] public void CategoryNode_renaming_rejects_duplicate_category_name(string existingName) { // ARRANGE var category = DefaultCategory(c => c.Name = "c"); var duplicateCategory = DefaultCategory(c => c.Name = existingName); var parentCategory = DefaultCategory( WithSubCategory(category), WithSubCategory(duplicateCategory)); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(parentCategory, existingName)) .Returns(duplicateCategory); var categoryNode = new CategoryNode(category); // ACT categoryNode.RenameItem(this.ProviderContextMock.Object, "c", existingName); // ASSERT Assert.Equal("c", category.Name); } [Theory] [MemberData(nameof(InvalidNameChars))] public void CategoryNode_renaming_rejects_invalid_name_chararcters(char invalidChar) { // ARRANGE var category = DefaultCategory(c => c.Name = "c"); var invalidName = new string("p".ToCharArray().Append(invalidChar).ToArray()); var entitiesNode = new EntitiesNode(); var node = new CategoryNode(category); // ACT var result = Assert.Throws<InvalidOperationException>(() => node.RenameItem(this.ProviderContextMock.Object, "c", invalidName)); // ASSERT Assert.Equal($"category(name='{invalidName}' wasn't renamed: it contains invalid characters", result.Message); } #endregion IRenameItem #region IRemoveItem [Theory] [InlineData(true)] [InlineData(false)] public void CategoryNode_removes_itself(bool recurse) { // ARRANGE var category = DefaultCategory(); this.ProviderContextMock .Setup(c => c.Persistence) .Returns(this.PersistenceMock.Object); this.ProviderContextMock .Setup(p => p.Recurse) .Returns(recurse); this.PersistenceMock .Setup(r => r.DeleteCategory(category, recurse)) .Returns(true); var node = new CategoryNode(category); // ACT node.RemoveItem(this.ProviderContextMock.Object, "c"); } #endregion IRemoveItem #region IMoveItem [Theory] [InlineData("c-src", (string?)null, "c-src")] [InlineData("c-src", "c-dst", "c-dst")] public void CategoryNode_moves_itself_to_category(string initialName, string destinationName, string resultName) { // ARRANGE this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); var destination = DefaultCategory(); var c2 = DefaultCategory(c => c.Name = initialName); this.CategoryRepositoryMock .Setup(r => r.FindById(destination.Id)) .Returns(destination); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(destination, resultName)) .Returns((Category?)null); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(destination, resultName)) .Returns((Entity?)null); this.CategoryRepositoryMock .Setup(r => r.Upsert(c2)) .Returns<Category>(c => c); var destinationNode = new CategoryNode(destination); var node = new CategoryNode(c2); // ACT node.MoveItem(this.ProviderContextMock.Object, "", destinationName, destinationNode); // ASSERT Assert.Equal(destination, c2.Parent); Assert.Equal(resultName, c2.Name); } [Theory] [InlineData("c-src", (string?)null, "c-src")] [InlineData("c-src", "c-dst", "c-dst")] public void CategoryNode_rejects_moving_itself_to_category_if_entity_name_already_exists(string initialName, string destinationName, string resultName) { // ARRANGE this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); var c = DefaultCategory(); var c2 = DefaultCategory(c => c.Name = initialName); this.CategoryRepositoryMock .Setup(r => r.FindById(c.Id)) .Returns(c); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(c, resultName)) .Returns((Category?)null); this.PersistenceMock .Setup(p => p.Entities) .Returns(this.EntityRepositoryMock.Object); this.EntityRepositoryMock .Setup(r => r.FindByCategoryAndName(c, resultName)) .Returns(DefaultEntity()); var categoryNode = new CategoryNode(c); var node = new CategoryNode(c2); // ACT var result = Assert.Throws<InvalidOperationException>( () => node.MoveItem(this.ProviderContextMock.Object, "", destinationName, categoryNode)); // ASSERT Assert.Equal($"Destination container contains already an entity with name '{resultName}'", result.Message); } [Theory] [InlineData("c-src", (string?)null, "c-src")] [InlineData("c-src", "c-dst", "c-dst")] public void CategoryNode_rejects_moving_itself_to_category_if_category_name_already_exists(string initialName, string destinationName, string resultName) { // ARRANGE this.ProviderContextMock .Setup(p => p.Persistence) .Returns(this.PersistenceMock.Object); this.PersistenceMock .Setup(p => p.Categories) .Returns(this.CategoryRepositoryMock.Object); var c = DefaultCategory(); var c2 = DefaultCategory(c => c.Name = initialName); this.CategoryRepositoryMock .Setup(r => r.FindById(c.Id)) .Returns(c); this.CategoryRepositoryMock .Setup(r => r.FindByParentAndName(c, resultName)) .Returns(DefaultCategory()); var categoryNode = new CategoryNode(c); var node = new CategoryNode(c2); // ACT var result = Assert.Throws<InvalidOperationException>( () => node.MoveItem(this.ProviderContextMock.Object, "", destinationName, categoryNode)); // ASSERT Assert.Equal($"Destination container contains already a category with name '{resultName}'", result.Message); } #endregion IMoveItem } }
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 PrototypeSAD { public partial class eventDateDialog : Form { public event_add reftoevent_add {get; set;} public eventDateDialog() { InitializeComponent(); } public string[] tMonths = { "JANUARY", "FEBRUARY", "MARCH", "APRIL", "MAY", "JUNE", "JULY", "AUGUST", "SEPTEMBER", "OCTOBER", "NOVEMBER", "DECEMBER" }; public int evYear = int.Parse(DateTime.Now.ToString("yyyy")); public int evmonth = int.Parse(DateTime.Now.ToString("MM")); public int evday = int.Parse(DateTime.Now.ToString("dd")); public int evhour = int.Parse(DateTime.Now.ToString("hh")); public int evmin = int.Parse(DateTime.Now.ToString("mm")); public string evtt = DateTime.Now.ToString("hh:mm tt"); public string day, month, year, hour, min, tt; private void eventDateDialog_Load(object sender, EventArgs e) { dayUpdate(evYear, evmonth); for (int j = evYear; j <= evYear + 100; j++) { comboBox3.Items.Add(""+ j +""); } for (int i = 0; i < 60; i++) { comboBox5.Items.Add(i.ToString("00")); } comboBox1.SelectedIndex = evday - 1; comboBox2.SelectedIndex = evmonth - 1; comboBox3.SelectedItem = evYear.ToString(); comboBox4.SelectedIndex = evhour - 1; comboBox5.SelectedIndex = evmin - 1; comboBox6.SelectedItem = evtt.Substring(6, 2); //MessageBox.Show(evtt.Substring(6, 2)); } public void dayUpdate(int year, int month) { comboBox1.Items.Clear(); if (year % 4 != 0) { //common year if (month == 2) { //february for(int i = 1; i <= 28; i++) { comboBox1.Items.Add(""+i+""); } } else if (month % 2 == 0) { //day 30 for (int i = 1; i <= 30; i++) { comboBox1.Items.Add("" + i + ""); } } else { //day 31 for (int i = 1; i <= 31; i++) { comboBox1.Items.Add("" + i + ""); } } } else if (year % 100 != 0) { //leap year if (month == 2) { //february for (int i = 1; i <= 29; i++) { comboBox1.Items.Add("" + i + ""); } } else if (month % 2 == 0) { //day 30 for (int i = 1; i <= 30; i++) { comboBox1.Items.Add("" + i + ""); } } else { //day 31 for (int i = 1; i <= 31; i++) { comboBox1.Items.Add("" + i + ""); } } } else if (year % 400 != 0) { //common year if (month == 2) { //february for (int i = 1; i <= 28; i++) { comboBox1.Items.Add("" + i + ""); } } else if (month % 2 == 0) { //day 30 for (int i = 1; i <= 30; i++) { comboBox1.Items.Add("" + i + ""); } } else { //day 31 for (int i = 1; i <= 31; i++) { comboBox1.Items.Add("" + i + ""); } } } else { //leap year if (month == 2) { //february for (int i = 1; i <= 29; i++) { comboBox1.Items.Add("" + i + ""); } } else if (month % 2 == 0) { //day 30 for (int i = 1; i <= 30; i++) { comboBox1.Items.Add("" + i + ""); } } else { //day 31 for (int i = 1; i <= 31; i++) { comboBox1.Items.Add("" + i + ""); } } } } private void comboBox3_SelectionChangeCommitted(object sender, EventArgs e) { int num = Array.IndexOf(tMonths, comboBox2.Text) + 1; //MessageBox.Show(comboBox3.Text); dayUpdate(int.Parse(comboBox3.Text), num); } private void comboBox2_SelectionChangeCommitted(object sender, EventArgs e) { int num = Array.IndexOf(tMonths, comboBox2.Text) + 1; //MessageBox.Show(comboBox3.Text); dayUpdate(int.Parse(comboBox3.Text), num); } private void button1_Click(object sender, EventArgs e) { int num = Array.IndexOf(tMonths, comboBox2.Text) + 1; string whichdialog = reftoevent_add.whichDialog; if(whichdialog == "eventdetail") { day = comboBox1.Text; month = num.ToString("00"); year = comboBox3.Text; hour = comboBox4.Text; min = comboBox5.Text; tt = comboBox6.Text; reftoevent_add.dialogDay = day; reftoevent_add.dialogMonth = month; reftoevent_add.dialogYear = year; reftoevent_add.dialogHour = hour; reftoevent_add.dialogMin = min; reftoevent_add.dialogtt = tt; //MessageBox.Show("Dito sa details"); } else if(whichdialog == "eventRemind") { day = comboBox1.Text; month = num.ToString("00"); year = comboBox3.Text; hour = comboBox4.Text; min = comboBox5.Text; tt = comboBox6.Text; reftoevent_add.dialogDayR = day; reftoevent_add.dialogMonthR = month; reftoevent_add.dialogYearR = year; reftoevent_add.dialogHourR = hour; reftoevent_add.dialogMinR = min; reftoevent_add.dialogttR = tt; //MessageBox.Show("Dito sa remind"); } this.DialogResult = DialogResult.OK; } } }
using UnityEngine; using System.Collections; public class moving : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { transform.Translate(Vector3.up * 30 * Time.deltaTime); if (this.transform.position.y > 20 ) { Destroy(this.gameObject); } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using Application.Command; using Application.DTO; using EFDataAccess; using Application.Exceptions; namespace EFCommands { public class EfAddTagCommand : EfBaseCommand, IAddTagCommand { public EfAddTagCommand(BlogContext context) : base(context) { } public void Execute(AddTagDto request) { var tag = new Domain.Tag { Content = request.Content }; if (Context.Tag.Any(t => t.Content == request.Content)) { throw new EntityAllreadyExits("Tag"); } Context.Tag.Add(tag); try { Context.SaveChanges(); } catch (Exception) { throw new Exception(); } } } }
using System.IO; namespace ArtCom.Logging { public enum LogMessageType { /// <summary> /// A debug-only message that should be absent in non-development builds. /// </summary> Debug, /// <summary> /// A regular log message. /// </summary> Message, /// <summary> /// A warning indicates that something might be wrong, though the /// application can potentially continue to function as intended. /// </summary> Warning, /// <summary> /// An error indicates a recoverable failure that may, however, /// lead to limited program functionality or undefined behavior. /// </summary> Error, /// <summary> /// A fatal error indicates a non-recoverable failure that will /// likely cause the application to crash or reach a state where /// no meaningful operation is possible. /// </summary> Fatal } }
namespace FundManagerDashboard.Core.DataServices { public interface ITotalSummaryService { long TotalNumber { get; set; } decimal TotalMarketValue { get; set; } float TotalStockWeight { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using LSKYGuestAccountControl.Model; using LSKYGuestAccountControl.Repositories; namespace LSKYGuestAccountControl.Batch { public partial class BatchInfo : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // get batch ID from querystring string batchID = Request.QueryString["batchid"]; litHeading.Text = "<p style=\"text-align: center;\">Missing Batch ID</p>"; if (!string.IsNullOrEmpty(batchID)) { LogRepository logRepo = new LogRepository(); List<LoggedActivation> batchActivations = logRepo.GetBatchID(batchID); if (batchActivations.Count > 0) { tblAccounts.Visible = true; litHeading.Text = "<p><b>Batch:</b> " + batchID + "<br><b>Accounts in this batch:</b> " + batchActivations.Count + "</p>"; tblAccounts.Rows.Clear(); tblAccounts.Rows.Add(addHeadingRow()); foreach (LoggedActivation guest in batchActivations) { tblAccounts.Rows.Add(addAccountrow(guest)); } } } } private TableHeaderRow addHeadingRow() { TableHeaderRow newRow = new TableHeaderRow(); newRow.Cells.Add(new TableHeaderCell() { Text = "Activation date" }); newRow.Cells.Add(new TableHeaderCell() { Text = "Guest account" }); newRow.Cells.Add(new TableHeaderCell() { Text = "Password" }); newRow.Cells.Add(new TableHeaderCell() { Text = "Requested by" }); return newRow; } private TableRow addAccountrow(LoggedActivation guest) { TableRow newRow = new TableRow(); newRow.Cells.Add(new TableCell() { Text = guest.Date.ToString() }); newRow.Cells.Add(new TableCell() { Text = guest.GuestAccountName }); newRow.Cells.Add(new TableCell() { Text = guest.Password }); newRow.Cells.Add(new TableCell() { Text = guest.RequestingUser }); return newRow; } } }
using System; using BasketTest.Discounts.Enums; namespace BasketTest.Discounts.Items { public sealed class OfferVoucher : Voucher { public readonly decimal Threshold; public readonly ProductCategory? CategoryRestriction; public OfferVoucher(decimal value, decimal threshold, ProductCategory? categoryRestriction = null) : base(value) { if (threshold < 0) { throw new ArgumentException("Value cannot be negative."); } Threshold = threshold; CategoryRestriction = categoryRestriction; } } }
using JKMWindowsService.Utility.Log; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace JKMWindowsService.Utility { public class APIHelper : IAPIHelper { private readonly ClientHelper clientHelper; private readonly IResourceManagerFactory resourceManager; private readonly ILogger logger; /// <summary> /// Constructor Name : APIHelper /// Author : Pratik Soni /// Creation Date : 14 Feb 2018 /// Purpose : To create instant of ClientHelper class /// Revision : /// </summary> public APIHelper(ClientHelper clientHelper, IResourceManagerFactory resourceManager, ILogger logger) { this.clientHelper = clientHelper; this.resourceManager = resourceManager; this.logger = logger; } /// <summary> /// Method Name : InvokeGetAPI /// Author : Pratik Soni /// Creation Date : 14 Feb 2018 /// Purpose : Invokes the get API request. /// Revision : /// </summary> /// <param name="apiName">API name.</param> public HttpResponseMessage InvokeGetAPI(string apiName) { HttpClient httpClient = clientHelper.GetAuthenticateClient(); HttpRequestMessage request; request = new HttpRequestMessage(HttpMethod.Get, apiName); HttpResponseMessage httpResponseMessage = httpClient.SendAsync(request).Result; return httpResponseMessage; } /// <summary> /// Method Name : InvokePutAPi /// Author : Pratik Soni /// Creation Date : 14 Feb 2018 /// Purpose : Invokes the put API request for update. /// Revision : /// </summary> /// <returns>HttpResponseMessage</returns> /// <param name="apiName">API name.</param> /// <param name="body">Body.</param> /// <typeparam name="T">The 1st type parameter.</typeparam> public async Task<HttpResponseMessage> InvokePutAPI<T>(string apiName, T body) { using (var httpClient = clientHelper.GetAuthenticateClient()) { logger.Info("Put request invoked"); var content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(body), Encoding.UTF8, resourceManager.GetString("msgAppJson")); return await httpClient.PutAsync(apiName, content); } } /// <summary> /// Method Name : InvokePostAPI /// Author : Pratik Soni /// Creation Date : 23 Feb 2018 /// Purpose : Invokes the post API request for insert. /// Revision : /// </summary> /// <returns>HttpResponseMessage</returns> /// <param name="apiName">API name.</param> /// <param name="body">Body.</param> public HttpResponseMessage InvokePostAPI(string apiName, string requestBody) { HttpRequestMessage request; HttpResponseMessage httpResponseMessage; HttpClient httpClient = clientHelper.GetAuthenticateClient(); var content = new StringContent(requestBody, Encoding.UTF8, resourceManager.GetString("msgAppJson")); logger.Info("Post request invoked"); request = new HttpRequestMessage(HttpMethod.Post, apiName) { Content = content }; httpResponseMessage = httpClient.SendAsync(request).Result; return httpResponseMessage; } /// <summary> /// Method Name : InvokeDeleteAPI /// Author : Pratik Soni /// Creation Date : 14 Feb 2018 /// Purpose : Invoke API Request for delete /// Revision : /// </summary> /// <returns>HttpResponseMessage</returns> /// <param name="apiName">API name.</param> public async Task<HttpResponseMessage> InvokeDeleteAPI(string apiName) { using (var httpClient = clientHelper.GetAuthenticateClient()) { logger.Info("Delete request invoked"); return await httpClient.DeleteAsync(apiName); } } /// <summary> /// Method Name : GetAPIResponseStatusCodeMessage /// Author : Pratik Soni /// Creation Date : 14 Feb 2018 /// Purpose : common method to return response message common for selected status codes /// Revision : /// Gets the API Response status code. /// <returns>The APIR esponse status code.</returns> /// <param name="responseMessage">Response message.</param> public string GetAPIResponseStatusCodeMessage(HttpResponseMessage responseMessage) { string message = string.Empty; if (responseMessage.StatusCode == HttpStatusCode.ServiceUnavailable || responseMessage.StatusCode == HttpStatusCode.InternalServerError || responseMessage.StatusCode == HttpStatusCode.Unauthorized) { message = resourceManager.GetString("msgServiceUnavailable"); } else { message = resourceManager.GetString("msgDefaultServieMessage"); } return message; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace REQFINFO.Domain { public class WorkFlowModel { public int IDWorkflow { get; set; } public string Name { get; set; } public Nullable<int> IDProjectTemplate { get; set; } public string DisplayName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SKT.WMS.Web.AjaxServices.WMSVouchCode; using SKT.WMS.WMSBasicfile.BLL; using SKT.WMS.WMSBasicfile.Model; namespace SKT.MES.Web.WMSBasicfile { public partial class WMSVouchCodeEdit : BasePage { protected void Page_Load(object sender, EventArgs e) { AjaxPro.Utility.RegisterTypeForAjax(typeof(AjaxServiceWMSVouchCode)); Int32 vouchID = Convert.ToInt32(Request.QueryString["ID"]); if (vouchID == -1) { vouchID = (Convert.ToInt32(Request.Form["hdnTIDString"]) == 0) ? -1 : Convert.ToInt32(Request.Form["hdnTIDString"]); } this.Master.PageGridView = this.GridView1; this.GridView1.DataSourceID = this.ObjectDataSource1.ID; this.Master.PageObjectDataSource = this.ObjectDataSource1; this.Master.RecordIDField = "Id"; this.Master.DefaultSortExpression = "Id"; this.Master.DefaultSortDirection = SortDirection.Ascending; SKT.MES.Model.SearchSettings searchSettings = new SKT.MES.Model.SearchSettings(); searchSettings.AddCondition("VouchCode", vouchID.ToString()); this.Master.SearchSettings = searchSettings; if (this.IsPostBack) { //删除 if (Request.Form["hdnOperate"].ToLower() == "delete") { try { WMSVouchCodeS vouchCoudeSBll = new WMSVouchCodeS(); vouchCoudeSBll.Delete(Request.Form["hdnIdString"].ToString(), AccountController.GetCurrentUser().LoginID); WebHelper.ShowMessage(Resources.Messages.DeleteSuccess); } catch (Exception ex) { WebHelper.HandleException(AccountController.GetCurrentUser().LoginID, ex, true); } } } if (vouchID != -1) { WMSVouchCode vouchCodeBll = new WMSVouchCode(); WMSVouchCodeInfo vouchCodeInfo = null; vouchCodeInfo = vouchCodeBll.GetInfo(vouchID); if (vouchCodeInfo != null) { this.VouchCodeData = vouchCodeInfo; //this.txtName.Enabled = false; } } } protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { ////数据类型 int temp = Int32.Parse(e.Row.Cells[2].Text); switch (temp) { case 1: e.Row.Cells[2].Text = Resources.lang.WMSStaticType; break; case 2: e.Row.Cells[2].Text = Resources.lang.WMSCustomerdocument; break; case 3: e.Row.Cells[2].Text = Resources.lang.WMSWarehousedocument; break; case 4: e.Row.Cells[2].Text = Resources.lang.Date; break; case 5: e.Row.Cells[2].Text = Resources.lang.WMSSortNumber; break; default: temp = 0; break; } //是否流水 if (e.Row.Cells[5].Text == "1") { e.Row.Cells[5].Text = Resources.Pages.wmsItemsStatus0; } else { e.Row.Cells[5].Text = Resources.Pages.wmsItemsStatus1; } } } /// <summary> /// 编辑状态下获得对应ID的数据 /// </summary> protected WMSVouchCodeInfo VouchCodeData { set { this.txtName.Text = value.VouchName.ToString(); this.txtDesc.Text = value.Remark.ToString(); this.hdnVouchID.Value = value.VouchType.ToString(); //this.txtVouchType.Text = value.VouchType.ToString(); if (value.VouchType != -1) { WMSVouchTypeInfo vouchCode = (new WMSVouchType()).GetInfo(value.VouchType); this.txtVouchType.Text = (vouchCode == null) ? "" : vouchCode.Id + "|" + vouchCode.VouchName; } else { this.txtVouchType.Text = ""; } } } } }
using System; using System.Collections.Generic; namespace Planning { class MacroAction : Action { public static int counter = 1; //public Dictionary<string, bool[]> satNowVectors; //public Dictionary<string, bool[]> negSatNowVectors; public Dictionary<string, int> parentIndex; public Dictionary<string, int> childIndex; public List<string> preIndex = null; public int cost = 0; public int dellLandmarkCounter = 0; public List<string> lastpreIndex = null; public int heuristicDelta = 0; public bool[] landmarkVector = null; public bool[] NeglandmarkVector = null; public bool[] anyTimeVector = null; public bool[] rOrder = null; public List<Action> microActions = null; //public string name = ""; /* public MacroAction() : base("MacroAction"+counter) { counter++; }*/ public MacroAction(MapsVertex parentVertex, MapsVertex childVertex) : base("MacroAction" + counter) { // if (Name.Equals("MacroAction46")) // Console.WriteLine("ss"); lastpreIndex = new List<string>(); preIndex = new List<string>(); parentIndex = new Dictionary<string, int>(parentVertex.stateIndexes); childIndex = new Dictionary<string, int>(childVertex.stateIndexes); counter++; isPublic = false; Action lastPublicAction = childVertex.lplan[childVertex.lplan.Count - 1]; //if (lastPublicAction == null) // Console.WriteLine("ss"); agent = lastPublicAction.agent; int k = 0; foreach (var indexItem in parentVertex.stateIndexes) { //parentIndex[k]=indexItem.Value; //childIndex[k] = childVertex.stateIndexes[indexItem.Key]; if (!indexItem.Value.Equals(childVertex.stateIndexes[indexItem.Key])) { lastpreIndex.Add(indexItem.Key); } k++; } cost = 0; microActions = new List<Action>(); List<Action> pubActions = new List<Action>(); for (int i = parentVertex.lplan.Count; i < childVertex.lplan.Count; i++) { microActions.Add(childVertex.lplan[i]); if (childVertex.lplan[i] is MacroAction) { foreach (string a in ((MacroAction)childVertex.lplan[i]).preIndex) { if (!preIndex.Contains(a)) preIndex.Add(a); } cost += ((MacroAction)childVertex.lplan[i]).cost; } else { if (!preIndex.Contains(childVertex.lplan[i].agent)) preIndex.Add(childVertex.lplan[i].agent); cost += 1; } if (childVertex.lplan[i].isPublic || childVertex.lplan[i] is MacroAction) { pubActions.Add(childVertex.lplan[i]); } } HashEffects = new List<Predicate>(); HashPrecondition = new List<Predicate>(); // if (parentVertex.isComplex) // Console.WriteLine("**"); foreach (Action pAct in pubActions) { foreach (GroundedPredicate pre in pAct.HashPrecondition) { if (MapsPlanner.allPublicFacts.Contains(pre)) { if (!HashEffects.Contains(pre) && !HashPrecondition.Contains(pre)) HashPrecondition.Add(pre); } } foreach (GroundedPredicate eff in pAct.HashEffects) { if (MapsPlanner.allPublicFacts.Contains(eff)) { if (!HashEffects.Contains(eff)) { if (HashEffects.Contains(eff.Negate())) HashEffects.Remove(eff.Negate()); HashEffects.Add(eff); } } } } CompoundFormula prec = new CompoundFormula("and"); foreach (GroundedPredicate precGp in HashPrecondition) prec.AddOperand(precGp); Preconditions = prec; CompoundFormula effe = new CompoundFormula("and"); foreach (GroundedPredicate effeGp in HashEffects) effe.AddOperand(effeGp); Effects = effe; if (Program.highLevelPlanerType == Program.HighLevelPlanerType.MafsLandmark) { heuristicDelta = parentVertex.h - childVertex.h; landmarkVector = new bool[parentVertex.SatisfactionLandmarks.Length]; NeglandmarkVector = new bool[parentVertex.SatisfactionLandmarks.Length]; for (int i = 0; i < parentVertex.SatisfactionLandmarks.Length; i++) { if (!parentVertex.SatisfactionLandmarks[i] && childVertex.SatisfactionLandmarks[i]) { landmarkVector[i] = true; } } for (int i = 0; i < parentVertex.SatisfactionLandmarks.Length; i++) { if (parentVertex.SatisfactionLandmarks[i] && !childVertex.SatisfactionLandmarks[i]) { NeglandmarkVector[i] = true; dellLandmarkCounter++; } } //if (microActions.Count > 1) // Console.WriteLine("GnGaa"); rOrder = new bool[parentVertex.vectors[agent][1].Length]; foreach (string agnt in preIndex) { for (int i = 0; i < parentVertex.vectors[agnt][1].Length; i++) { if (!parentVertex.vectors[agnt][1][i] && childVertex.vectors[agnt][1][i]) { rOrder[i] = true; } } } anyTimeVector = new bool[parentVertex.anyTimeSatisfactionLandmarks.Length]; for (int i = 0; i < parentVertex.SatisfactionLandmarks.Length; i++) { if (!parentVertex.anyTimeSatisfactionLandmarks[i] && childVertex.anyTimeSatisfactionLandmarks[i]) { anyTimeVector[i] = true; } } /*satNowVectors = new Dictionary<string, bool[]>(); negSatNowVectors=new Dictionary<string, bool[]>(); foreach (string agnt in preIndex) { satNowVectors.Add(agnt, new bool[childVertex.satisfiedVector[agnt].Length]); negSatNowVectors.Add(agnt, new bool[childVertex.satisfiedVector[agnt].Length]); for (int i = 0; i < childVertex.satisfiedVector[agnt].Length; i++) { if (childVertex.satisfiedVector[agnt][i] == true && parentVertex.satisfiedVector[agnt][i] == false) { satNowVectors[agnt][i] = true; } if (childVertex.satisfiedVector[agnt][i] == false && parentVertex.satisfiedVector[agnt][i] == true) { negSatNowVectors[agnt][i] = true; } } }*/ } } public override bool Equals(object obj) { if (obj is MacroAction) return Equals((MacroAction)obj); return false; } int code = -1; public override int GetHashCode() { if (code != -1) return code; int fa = 0; int se = 0; foreach (string index in preIndex) { fa += parentIndex[index]; se += childIndex[index]; } code = (int)(Math.Pow(fa, se)); return code; } public bool Equals(MacroAction a2) { if (this.preIndex.Count != a2.preIndex.Count) return false; if (HashPrecondition.Count != a2.HashPrecondition.Count) return false; if (HashEffects.Count != a2.HashEffects.Count) return false; foreach (var index in preIndex) { if (!a2.parentIndex[index].Equals(parentIndex[index])) return false; if (!a2.childIndex[index].Equals(childIndex[index])) return false; } foreach (GroundedPredicate gp in HashPrecondition) { if (!a2.HashPrecondition.Contains(gp)) return false; } foreach (GroundedPredicate gp in HashEffects) { if (!a2.HashEffects.Contains(gp)) return false; } return true; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public enum TypeUnit { German1, German2, British1 } public class ManagerUnits : MonoSingleton<ManagerUnits> { [SerializeField] Node[] m_Units = null; Transform m_RootUnits; [Serializable] class Node { public TypeUnit Type = TypeUnit.British1; public GameObject Prefab = null; } protected override void OnAwake() { m_RootUnits = new GameObject("ROOT_UNITS").transform; } protected override void Destroy() { m_RootUnits.DestroyGO(); } public static GameObject CreateRandom() { if (!Can) return null; var units = m_I.m_Units; if (units == null || units.Length <= 0) return null; int rand = UnityEngine.Random.Range(0, units.Length); return CreateUnit((TypeUnit)rand); } public static GameObject CreateUnit(TypeUnit type) { return Can ? m_I.InnerCreateUnit(type) : null; } GameObject InnerCreateUnit(TypeUnit type) { GameObject go = null; var units = m_Units; for (int i = 0; i < units.Length; i++) { if (units[i].Type == type) { go = units[i].Prefab.Instantiate(); break; } } if (go == null && units.Length > 0) go = units[0].Prefab.Instantiate(); if (go != null) go.transform.SetParent(m_RootUnits); return go; } //List<UnitContainer> m_Units = new List<UnitContainer>(10); }
using System; using System.Collections.Generic; using System.Text; namespace PnrAnalysis.Model { /// <summary> /// 经停信息 /// </summary> /// [Serializable] public class LegStop { private string _CarrayCode; /// <summary> /// 承运人 CA /// </summary> public string CarrayCode { get { return _CarrayCode; } set { _CarrayCode = value; } } private string _CarrayName; /// <summary> /// 承运人名称 /// </summary> public string CarrayName { get { return _CarrayName; } set { _CarrayName = value; } } private string _AirShortName; /// <summary> /// 承运人简称 /// </summary> public string AirShortName { get { return _AirShortName; } set { _AirShortName = value; } } private string _FlightNum; /// <summary> /// 航班号 1406 /// </summary> public string FlightNum { get { return _FlightNum; } set { _FlightNum = value; } } private string _CarrayCodeFlightNum; /// <summary> /// 承运人航班号 CA1406 /// </summary> public string CarrayCodeFlightNum { get { return _CarrayCodeFlightNum; } set { _CarrayCodeFlightNum = value; } } private string _StrStopDate; /// <summary> /// 经停日期字符串 12NOV12 /// </summary> public string StrStopDate { get { return _StrStopDate; } set { _StrStopDate = value; } } private string _StopDate; /// <summary> /// 经停日期 2012-12-12 /// </summary> public string StopDate { get { return _StopDate; } set { _StopDate = value; } } private string _Model; /// <summary> /// 机型 731 /// </summary> public string Model { get { return _Model; } set { _Model = value; } } private string _FromCityCode; /// <summary> /// 出发城市三字码 CTU /// </summary> public string FromCityCode { get { return _FromCityCode; } set { _FromCityCode = value; } } private string _FromCity; /// <summary> /// 出发城市名称 /// </summary> public string FromCity { get { return _FromCity; } set { _FromCity = value; } } private string _MiddleCityCode; /// <summary> /// 经停城市(即中专城市)三字码 HGH /// </summary> public string MiddleCityCode { get { return _MiddleCityCode; } set { _MiddleCityCode = value; } } private string _MiddleCity; /// <summary> /// 经停城市(即中专城市) /// </summary> public string MiddleCity { get { return _MiddleCity; } set { _MiddleCity = value; } } private string _ToCityCode; /// <summary> /// 到达城市三字码 PEK /// </summary> public string ToCityCode { get { return _ToCityCode; } set { _ToCityCode = value; } } private string _ToCity; /// <summary> /// 到达城市 /// </summary> public string ToCity { get { return _ToCity; } set { _ToCity = value; } } private string _FromTime; /// <summary> /// 出发时间 08:00 /// </summary> public string FromTime { get { return _FromTime; } set { _FromTime = value; } } private string _MiddleTime1; /// <summary> /// 中专城市时间1 12:00 /// </summary> public string MiddleTime1 { get { return _MiddleTime1; } set { _MiddleTime1 = value; } } private string _MiddleTime2; /// <summary> /// 中专城市时间2 13:00 /// </summary> public string MiddleTime2 { get { return _MiddleTime2; } set { _MiddleTime2 = value; } } private string _ToTime; /// <summary> /// 到达时间 15:00 /// </summary> public string ToTime { get { return _ToTime; } set { _ToTime = value; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Donner; using System.IO; using System; public class NeutrinoWallet : LndRpcBridge { public LndConfig config; public NeutrinoTest lnd; public string[] seed; public bool getInfoTrigger; public string cert; public string mac; // Use this for initialization async void Start () { config = new LndConfig() { Hostname = "localhost", Port = "10013", MacaroonFile = "/Neutrino/neutrinoadmin.macaroon", TlsFile = "/Neutrino/neutrino.cert" }; lnd.StartLnd(config); try { cert = File.ReadAllText(Application.dataPath + "/Resources/" + config.TlsFile); } catch (Exception e) { cert = ""; UnityEngine.Debug.Log(e); } try { mac = LndHelper.ToHex(File.ReadAllBytes(Application.dataPath + "/Resources/" + config.MacaroonFile)); } catch(Exception e) { UnityEngine.Debug.Log(e); mac = ""; } await ConnectToLndWithMacaroon(config.Hostname + ":" + config.Port, cert, mac); var seed = await GenerateSeed(); var s = await UnlockWallet("suchwowmuchhey", seed); await ConnectToLndWithMacaroon(config.Hostname + ":" + config.Port, cert, mac); var getinfo = await GetInfo(); Debug.Log(getinfo.IdentityPubkey); } // Update is called once per frame async void Update () { if(getInfoTrigger) { getInfoTrigger = false; var getinfo = await GetInfo(); Debug.Log(getinfo.ToString()); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using GalaSoft.MvvmLight.CommandWpf; using Nito.AsyncEx; using TemporaryEmploymentCorp.DataAccess; using TemporaryEmploymentCorp.Helpers.ReportViewer; using TemporaryEmploymentCorp.Models.Editable; using TemporaryEmploymentCorp.Models.Opening; using TemporaryEmploymentCorp.Reports.Company; namespace TemporaryEmploymentCorp.Models.Company { public class CompanyModel:ModelBase<DataAccess.EF.Company>, IEditableModel<DataAccess.EF.Company> { public ObservableCollection<OpeningModel> Openings { get; } = new ObservableCollection<OpeningModel>(); private IRepository _repository; private int _numberOfOpenings; public void LoadRelatedInfo() { //LoadOpenings(); LoadNumberOfOpenings(); } public void LoadOpenings() { NotifyTaskCompletion.Create(() => LoadOpeningsAsync()); } public void LoadNumberOfOpenings() { NotifyTaskCompletion.Create(() => LoadNumberOfOpeningsAsync()); } public int NumberOfOpenings { get { return _numberOfOpenings; } set { _numberOfOpenings = value; RaisePropertyChanged(nameof(NumberOfOpenings)); } } public int NumberOfAssigned { get { return _numberOfAssigned; } set { _numberOfAssigned = value; RaisePropertyChanged(nameof(NumberOfAssigned)); } } private async Task LoadNumberOfOpeningsAsync() { var openings = await Task.Run(() => _repository.Opening.GetRangeAsync(c => c.CompanyId == Model.CompanyId)); NumberOfOpenings = openings.Count; } private async Task LoadOpeningsAsync() { // CancellationToken token = new CancellationToken(); // token.ThrowIfCancellationRequested(); // // CancellationTokenSource.CreateLinkedTokenSource() Openings.Clear(); var openings = await Task.Run(() => _Repository.Opening.GetRange(c => c.CompanyId == Model.CompanyId )); foreach (var opening in openings) { var qual = await Task.Run(() => _repository.Qualification.Get(c => c.QualificationId == opening.QualificationId)); opening.Qualification = qual; Openings.Add(new OpeningModel(opening, _repository )); Task.Delay(10); } } private bool _isEditing; private EditModelBase<DataAccess.EF.Company> _editModel; private int _numberOfAssigned; public CompanyModel(DataAccess.EF.Company model) : base(model) { } public CompanyModel(DataAccess.EF.Company model, IRepository repository) : base(model, repository) { _repository = repository; } public bool isEditing { get { return _isEditing; } set { _isEditing = value; RaisePropertyChanged(nameof(isEditing)); } } public EditModelBase<DataAccess.EF.Company> EditModel { get { return _editModel; } set { _editModel = value; RaisePropertyChanged(nameof(EditModel)); } } public ICommand EditCommand => new RelayCommand(EditProc); private void EditProc() { isEditing = true; EditModel?.Dispose(); EditModel = new CompanyEditModel(Model); } public ICommand SaveEditCommand => new RelayCommand(SaveEditProc, SaveEditCondition); private bool SaveEditCondition() { return (EditModel != null) && EditModel.HasChanges && !EditModel.HasErrors; } private void SaveEditProc() { NotifyTaskCompletion.Create(SaveEditCompanyAsync); } private async Task SaveEditCompanyAsync() { if (EditModel == null) return; if (!EditModel.HasChanges) return; try { await _Repository.Company.UpdateAsync(EditModel.ModelCopy); //replace the model with the edited copy Model = EditModel.ModelCopy; isEditing = false; } catch (Exception e) { MessageBox.Show("Unable to save. Reason" + e.Message); } } public ICommand CancelEditCommand => new RelayCommand(CancelEditProc); private void CancelEditProc() { isEditing = false; EditModel?.Dispose(); } } }
namespace Core.Swagger.Tests { using System; using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Swashbuckle.AspNetCore.Swagger; using Swashbuckle.AspNetCore.SwaggerGen; using Xunit; using static System.Net.HttpStatusCode; public class SecurityRequirementsOperationFilterTests { private readonly Operation _operation; public SecurityRequirementsOperationFilterTests() { _operation = new Operation { OperationId = $"{Guid.NewGuid()}", Responses = new Dictionary<string, Response>() }; } [Fact] public void ApplyMethodRoles() { // Arrange var context = GetContext(typeof(Controller), nameof(Controller.MethodWithRoles)); var filter = new SecurityRequirementsOperationFilter(); // Act filter.Apply(_operation, context); // Assert AssertAuthorizeResponses(); var security = Assert.IsAssignableFrom<List<IDictionary<string, IEnumerable<string>>>>(_operation.Security); var attributes = Assert.Single(security); Assert.NotNull(attributes); var role = Assert.Single(attributes["Bearer"]); Assert.Equal("AdminRole", role); } [Fact] public void ApplyMethodPolicies() { // Arrange var context = GetContext(typeof(Controller), nameof(Controller.MethodWithPolicies)); var filter = new SecurityRequirementsOperationFilter(); // Act filter.Apply(_operation, context); // Assert AssertAuthorizeResponses(); var security = Assert.IsAssignableFrom<List<IDictionary<string, IEnumerable<string>>>>(_operation.Security); var attributes = Assert.Single(security); Assert.NotNull(attributes); var policy = Assert.Single(attributes["Bearer"]); Assert.Equal("AdminPolicy", policy); } [Fact] public void ApplyMethodAllowAnonymousAttribute() { // Arrange var context = GetContext(typeof(Controller), nameof(Controller.MethodWithAllowAnonymous)); var filter = new SecurityRequirementsOperationFilter(); // Act filter.Apply(_operation, context); // Assert Assert.Empty(_operation.Responses); Assert.Null(_operation.Security); } [Fact] public void ApplyControllerRoles() { // Arrange var context = GetContext(typeof(ControllerWithRoles), nameof(ControllerWithRoles.Method)); var filter = new SecurityRequirementsOperationFilter(); // Act filter.Apply(_operation, context); // Assert AssertAuthorizeResponses(); var security = Assert.IsAssignableFrom<List<IDictionary<string, IEnumerable<string>>>>(_operation.Security); var attributes = Assert.Single(security); Assert.NotNull(attributes); var policy = Assert.Single(attributes["Bearer"]); Assert.Equal("UserRole", policy); } [Fact] public void ApplyControllerPolicies() { // Arrange var context = GetContext(typeof(ControllerWithPolicies), nameof(ControllerWithPolicies.Method)); var filter = new SecurityRequirementsOperationFilter(); // Act filter.Apply(_operation, context); // Assert AssertAuthorizeResponses(); var security = Assert.IsAssignableFrom<List<IDictionary<string, IEnumerable<string>>>>(_operation.Security); var attributes = Assert.Single(security); Assert.NotNull(attributes); var policy = Assert.Single(attributes["Bearer"]); Assert.Equal("UserPolicy", policy); } [Fact] public void ApplyControllerAllowAnonymousAttribute() { // Arrange var context = GetContext(typeof(ControllerWithAllowAnonymous), nameof(ControllerWithAllowAnonymous.Method)); var filter = new SecurityRequirementsOperationFilter(); // Act filter.Apply(_operation, context); // Assert Assert.Empty(_operation.Responses); Assert.Null(_operation.Security); } [Fact] public void ApplyThrowsForNullOperation() { // Arrange var context = new OperationFilterContext(default, default, default); var filter = new SecurityRequirementsOperationFilter(); void TestCode() => filter.Apply(default, context); // Act / Assert var exception = Assert.Throws<ArgumentNullException>(TestCode); Assert.Equal("operation", exception.ParamName); } [Fact] public void ApplyThrowsForNullContext() { // Arrange var filter = new SecurityRequirementsOperationFilter(); void TestCode() => filter.Apply(_operation, default); // Act / Assert var exception = Assert.Throws<ArgumentNullException>(TestCode); Assert.Equal("context", exception.ParamName); } private static OperationFilterContext GetContext(IReflect controllerType, string methodName) { var methodInfo = controllerType.GetMethod( name: methodName, bindingAttr: BindingFlags.NonPublic | BindingFlags.Static); return new OperationFilterContext( apiDescription: new ApiDescription(), schemaRegistry: default, methodInfo: methodInfo); } private void AssertAuthorizeResponses() { Assert.Collection( _operation.Responses, response1 => { var (key, value) = response1; Assert.Equal($"{(int)Unauthorized}", key); var response = Assert.IsType<Response>(value); Assert.Equal($"{Unauthorized}", response.Description); }, response2 => { var (key, value) = response2; Assert.Equal($"{(int)Forbidden}", key); var response = Assert.IsType<Response>(value); Assert.Equal($"{Forbidden}", response.Description); }); } private static class Controller { [Authorize(Roles = "AdminRole")] internal static void MethodWithRoles() { } [Authorize(Policy = "AdminPolicy")] internal static void MethodWithPolicies() { } [AllowAnonymous] internal static void MethodWithAllowAnonymous() { } } [Authorize(Roles = "UserRole")] private static class ControllerWithRoles { internal static void Method() { } } [Authorize(Policy = "UserPolicy")] private static class ControllerWithPolicies { internal static void Method() { } } [AllowAnonymous] private static class ControllerWithAllowAnonymous { internal static void Method() { } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace BearKMPServer { class Main { private NetClientHandler ch; public Main() { StartSingletons(); ch = new NetClientHandler(); } public void StartSingletons() { Debugger.Start(); } public void Dispose() { ch.Dispose(); } } }
 namespace PICSimulator.Model.Commands { /// <summary> /// The contents of register 'f' are incre- /// mented. If 'd' is 0 the result is placed in /// the W register. If 'd' is 1 the result is /// placed back in register 'f'. /// If the result is 1, the next instruction is /// executed. If the result is 0, a NOP is exe- /// cuted instead making it a 2T CY instruc- /// tion . /// </summary> class PICCommand_INCFSZ : PICCommand { public const string COMMANDCODE = "00 1111 dfff ffff"; public readonly bool Target; public readonly uint Register; public PICCommand_INCFSZ(string sct, uint scl, uint pos, uint cmd) : base(sct, scl, pos, cmd) { Target = Parameter.GetBoolParam('d').Value; Register = Parameter.GetParam('f').Value; } private bool TestCondition(PICController controller) // Returns True if Skip { return controller.GetBankedRegister(Register) == 0xFF; // skip if 0xFF -> After DEC will be Zero } public override void Execute(PICController controller) { bool Cond = TestCondition(controller); uint Result = controller.GetBankedRegister(Register); Result += 1; Result %= 0x100; if (Target) controller.SetBankedRegister(Register, Result); else controller.SetWRegister(Result); if (Cond) { controller.SetPC_13Bit(controller.GetPC() + 1); } } public override string GetCommandCodeFormat() { return COMMANDCODE; } public override uint GetCycleCount(PICController controller) { return TestCondition(controller) ? 2u : 1u; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CandlePickUp : Interactable { public override bool Interact(PlayerController _playerController) { GameController.instance.m_playerHasCandle = true; GameController.instance.ToggleCandleUI(true); Destroy(gameObject); return true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; using Applicate.Behavior; using Applicate.Data; using Applicate.Helpers; namespace Applicate.ViewModels { public class AppViewModel : ViewModelBase { private ICommand changeViewModelCommand; private IPageViewModel currentViewModel; private bool loggedInUser = false; private ICommand logoutCommand; private string username; public AppViewModel() { this.ViewModels = new List<IPageViewModel>(); this.ViewModels.Add(new TodoListsViewModel()); //this.ViewModels.Add(new AppointmentsViewModel()); var loginVM = new LoginRegisterFormViewModel(); loginVM.LoginSuccess += this.LoginSuccessful; this.LoginRegisterVM = loginVM; this.CurrentViewModel = this.LoginRegisterVM; } public bool LoggedInUser { get { return this.loggedInUser; } set { this.loggedInUser = value; this.OnPropertyChanged("LoggedInUser"); } } public string Username { get { return this.username; } set { this.username = value; OnPropertyChanged("Username"); } } public IPageViewModel CurrentViewModel { get { return this.currentViewModel; } set { this.currentViewModel = value; this.OnPropertyChanged("CurrentViewModel"); } } public LoginRegisterFormViewModel LoginRegisterVM { get; set; } public List<IPageViewModel> ViewModels { get; set; } public ICommand ChangeViewModel { get { if (this.changeViewModelCommand == null) { this.changeViewModelCommand = new RelayCommand(this.HandleChangeViewModelCommand); } return this.changeViewModelCommand; } } public ICommand Logout { get { if (this.logoutCommand == null) { this.logoutCommand = new RelayCommand(this.HandleLogoutCommand); } return this.logoutCommand; } } private void HandleLogoutCommand(object parameter) { bool isUserLoggedOut = DataPersister.LogoutUser(); if (isUserLoggedOut) { this.Username = ""; this.LoggedInUser = false; //this.CurrentViewModel = this.LoginRegisterVM; this.HandleChangeViewModelCommand(this.LoginRegisterVM); } } private void HandleChangeViewModelCommand(object parameter) { var newCurrentViewModel = parameter as IPageViewModel; this.CurrentViewModel = newCurrentViewModel; } public void LoginSuccessful(object sender, LoginSuccessArgs e) { this.Username = e.Username; this.LoggedInUser = true; this.HandleChangeViewModelCommand(this.ViewModels[0]); } } }
using Sitecore.Data.Items; using Sitecore.Diagnostics; using Sitecore.Security.AccessControl; namespace Aqueduct.SitecoreLib.Search.DynamicFields { public class HasExplicitDeniesField : BaseDynamicField { public override string ResolveValue(Item item) { Assert.ArgumentNotNull(item, "item"); return HasExplicitDenies(item).ToString().ToLowerInvariant(); } protected virtual bool HasExplicitDenies(Item item) { Assert.ArgumentNotNull(item, "item"); foreach (var rule in item.Security.GetAccessRules()) { if (rule.SecurityPermission == SecurityPermission.DenyAccess) { return true; } } return false; } } }
using GameForOurProject.GameHandler; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GameForOurProject.Buttons { public class Button { public int ButtonX { get; set; } public int ButtonY { get; set; } public Texture2D Texture { get; set; } public string Name { get; set; } public Color BtnColor { get; set; } public TextCreator txt { get; set; } public int Height { get; set; } public int Width { get; set; } public Button() { } public Button(TextCreator txtCreator,int width,int height,Color btnColor,int buttonX,int buttonY,string name,GraphicsDevice graphic) { Texture = new Texture2D(graphic, 1, 1, false, SurfaceFormat.Color); Texture.SetData(new[] { Color.White }); txt = txtCreator; Width = width; Height = height; BtnColor = btnColor; ButtonX = buttonX; ButtonY = buttonY; Name = name; } public bool enterButton(MouseState MouseInput) { if (Vector2.Distance(new Vector2(ButtonX + 30 , ButtonY + 3), new Vector2(MouseInput.X , MouseInput.Y)) < 50f) { return true; } return false; } public void UpdateRtgDataButtons(MouseState MouseInput, List<CircleWithText> Circles, GraphicsDevice graphic, string label) { if (enterButton(MouseInput)) { foreach (var circle in Circles.FindAll((X) => X.Data["label"].ToString() == label)) { string prevText = circle.text.Text; circle.text.Text = circle.Data[Name].ToString(); circle.text.ShownText = circle.Data[Name].ToString(); circle.text.AdjustTextToShow(); circle.text.Text = prevText; } } } public void UpdateLabelButtons(MouseState MouseInput, List<CircleWithText> Circles) { if (enterButton(MouseInput) && !txt.Text.Equals("(0)")) { CircleWithText circle = Circles.First((X) => X.Data["label"].ToString() == Name); GameLogic.SelectedCircle = circle; GameLogic.IsSelectedCircle = true; } } public void UpdateCircleSize(MouseState MouseInput, List<CircleWithText> Circles, GraphicsDevice graphic, string label) { if (enterButton(MouseInput) && label != "none") { List<CircleWithText> MiniCircles = Circles.FindAll((X) => X.Data["label"].ToString() == label); switch (Name) { case "Small": //the name of the button foreach (CircleWithText circle in MiniCircles) { circle.SetSize(GlobalHandler.Sizes.Small, graphic); } break; case "Medium": //the name of the button foreach (CircleWithText circle in MiniCircles) { circle.SetSize(GlobalHandler.Sizes.Medium, graphic); } break; case "Large": //the name of the button foreach (CircleWithText circle in MiniCircles) { circle.SetSize(GlobalHandler.Sizes.Large, graphic); } break; case "XLarge": //the name of the button foreach (CircleWithText circle in MiniCircles) { circle.SetSize(GlobalHandler.Sizes.XLarge, graphic); } break; case "Macdonlands": //the name of the button foreach (CircleWithText circle in Circles) { circle.SetSize(GlobalHandler.Sizes.Macdonlands, graphic); } break; default: break; } } } public void UpdateCircleColor(MouseState MouseInput, List<CircleWithText> Circles, GraphicsDevice graphic, string label) { if (enterButton(MouseInput) && label != "none") { foreach (var circle in Circles.FindAll((X) => X.Data["label"].ToString() == label)) { circle.ChangeValueColors(BtnColor); } GlobalHandler.SetColor(label, BtnColor); } } public void DrawBorder(SpriteBatch spriteBatch,int thicknessOfBorder) { // Draw top line spriteBatch.Draw(Texture, new Rectangle(ButtonX,ButtonY, Width, thicknessOfBorder), BtnColor); // Draw left line spriteBatch.Draw(Texture, new Rectangle(ButtonX, ButtonY, thicknessOfBorder, Height), BtnColor); // Draw right line spriteBatch.Draw(Texture, new Rectangle((ButtonX + Width - thicknessOfBorder), ButtonY, thicknessOfBorder, Height), BtnColor); // Draw bottom line spriteBatch.Draw(Texture, new Rectangle(ButtonX, ButtonY + Height - thicknessOfBorder, Width, thicknessOfBorder), BtnColor); txt.Draw(spriteBatch); } public void Draw(SpriteBatch batch) { batch.Draw(Texture, new Rectangle((int)ButtonX, (int)ButtonY, Texture.Width, Texture.Height), (BtnColor != new Color(0, 0, 0, 0)) ? BtnColor : Color.Gray); } } }
using Application.Errors; using Application.Interfaces; using AutoMapper; using Domain; using FluentValidation; using MediatR; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Application.User { public class List { public class Query : IRequest<QueryObject<UserResource>> { public int? Page { get; set; } public int? Size { get; set; } } public class QueryValidator : AbstractValidator<Query> { public QueryValidator() { RuleFor(x => x.Page).NotEmpty(); } } public class Handler : IRequestHandler<Query, QueryObject<UserResource>> { //private readonly UserManager<AppUser> _userManager; //private readonly SignInManager<AppUser> _signInManager; private readonly IJwtGenerator _jwtGenerator; private readonly DataContext _context; private readonly IMapper _mapper; private readonly IHostingEnvironment _hostingEnvironment; public Handler(DataContext context, IJwtGenerator jwtGenerator, IMapper mapper, IHostingEnvironment hostingEnvironment) { _jwtGenerator = jwtGenerator; _context = context; _mapper = mapper; _hostingEnvironment = hostingEnvironment; //_signInManager = signInManager; //_userManager = userManager; } public async Task<QueryObject<UserResource>> Handle(Query request, CancellationToken cancellationToken) { var env = _hostingEnvironment.EnvironmentName; var root = env == "Development" ? _hostingEnvironment.ContentRootPath + "\\images" : _hostingEnvironment.WebRootPath; var page = request.Page ?? 0; var size = request.Size ?? 20; var users = await _context.Users.Skip(page * size).Take(size).ToListAsync(); var data = _mapper.Map<List<AppUser>, List<UserResource>>(users); foreach (var item in data) { string path = $"{root}\\profile.png"; byte[] b = System.IO.File.ReadAllBytes(path); var img = users.Where(x => x.UserName == item.UserName).FirstOrDefault(); item.Photo = "data:image/png;base64," + (img.Photo == null ? Convert.ToBase64String(b) : Convert.ToBase64String(img.Photo)); } var count = _context.Users.Count(); return new QueryObject<UserResource> { ItemsPerPage = size, Data = data, Page = page, ItemsCount = count }; throw new RestException(HttpStatusCode.Unauthorized); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace processKR { class CIni { [DllImport("kernel32")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); [DllImport("kernel32")] private static extern IntPtr CreateFile(string fileName, uint DesiredAccess, uint ShareMode, uint SecurityAttributes, uint CreateDisposition, uint FlagAndAttributes, int hTemplateFile); public static string Save(string sec, string key, string val, string path) { long rt = 0; string strR; WritePrivateProfileString(sec, key, val, path); strR = rt.ToString(); return strR; } public static string Load(string sec, string key, string def, string path) { int rt = 0; string strRt; StringBuilder sb = new StringBuilder(1024); rt = GetPrivateProfileString(sec, key, def, sb, 1024, path); strRt = sb.ToString(); return strRt; } public static bool Load(string sec, string key, bool def, string path) { string sRs = Load(sec, key, def.ToString(), path); if (sRs.ToUpper() == "FALSE") return false; return true; } public static int Load(string sec, string key, int def, string path) { string sRs = Load(sec, key, def.ToString(), path); int nRs = 0; try { nRs = int.Parse(sRs); } catch (Exception) { nRs = 0; } return nRs; } } }
using System.Threading.Tasks; using Tindero.Api.Responses; namespace Tindero.Api { public class UsersApi : BaseCachedApiService, IUsersApi { public Task<GetUsersResponse> GetUsersAsync(int page, bool forceRefresh = false) { return GetAsync<GetUsersResponse>($"users?page={page}", forceRefresh: forceRefresh); } public Task<GetUserResponse> GetUserAsync(int id, bool forceRefresh = false) { return GetAsync<GetUserResponse>($"users/{id}", forceRefresh: forceRefresh); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class VelocityVector : MonoBehaviour { public void VelocityVectorRescale(float v, float v_min, float v_max, float v_scale, float v_size){ Vector3 scale = gameObject.transform.localScale; scale.Set(v_size, v_scale * (v - v_min)/(v_max - v_min) + v_size - v_scale, v_size); gameObject.transform.localScale = scale; } public void VelocityVectorPosition(float h){ gameObject.transform.position = new Vector3(0f, h, 0f); } public void VelocityVectorOrientation(float theta, float phi){ gameObject.transform.eulerAngles = new Vector3(0f, -phi, -theta); } }
/// Player - The user-controlled character /* Part of Saboteur Remake * * Changes: * 0.18, 31-may-2018, Nacho: Can move left, right, up & down in big map * 0.17, 31-may-2018, Nacho: Room.CheckIfNewRoom disabled * 0.14, 25-may-2018, Nacho: Ducking in the right position; * magic numbers in Player removed * 0.13, 24-may-2018, Nacho: Player can move upstairs and downstairs, * even to different rooms (remaining: collisions on end of stairs) * 0.12, 23-may-2018, Nacho: * Added TryToMoveUp, TryToMoveDown, climbing sequence & control boolean * 0.11, 22-may-2018, Nacho: Added TryToMoveLeft, TryToMoveRight * 0.09, 18-may-2018, Nacho: Added gravity * 0.08, 17-may-2018, Nacho: * Correct width and height (for the standard image) * 0.05, 11-may-2018,Marcos Cervantes, Jose Vilaplana, Jump * 0.03, 10-may-2018, Luis and Cesar, Loading the ImageSequence of the player. * 0.02, 09-may-2018, Luis and Cesar, corrections by Nacho: * Constructor + MoveLeft, MoveRight * 0.01, 09-may-2018, Nacho: First version, empty skeleton */ class Player : Sprite { int jumpFrame; int standardHeight; protected bool jumping, climbing, ducking; protected int gravitySpeed = 4; protected int heightOfDuckImage = 100, heightOfWalkingImage = 160, heightOfClimbingImage = 244, jumpSize = 50 ; protected int framesInJump = 40; /* string[] rightJump = { "data/imgRetro/playerJump1r.png", "data/imgRetro/playerJump2r.png",}; string[] leftJump = {"data/imgRetro/playerJump1l.png", "data/imgRetro/playerJump2l.png",};*/ public Player() { LoadImage("data/imgRetro/playerStaticr.png"); x = 50; y = 200; width = 128; height = heightOfWalkingImage; standardHeight = heightOfWalkingImage; // used when trying to leave a vertical stair xSpeed = 4; ySpeed = 4; jumpFrame = 1; jumping = false; climbing = false; ducking = false; LoadSequence(RIGHT, new string[] { "data/imgRetro/playerWalking1r.png", "data/imgRetro/playerWalking2r.png", "data/imgRetro/playerWalking3r.png"}); LoadSequence(LEFT, new string[] { "data/imgRetro/playerWalking1l.png", "data/imgRetro/playerWalking2l.png", "data/imgRetro/playerWalking3l.png"}); LoadSequence(UP, new string[] { "data/imgRetro/playerClimb1.png", "data/imgRetro/playerClimb2.png", }); LoadSequence(JUMPING, new string[] { "data/imgRetro/playerJump1l.png", "data/imgRetro/playerJump2l.png", "data/imgRetro/playerJump1r.png", "data/imgRetro/playerJump2r.png", }); currentDirection = RIGHT; LoadSequence(DOWN, new string[] { "data/imgRetro/playerDuck.png" }); SetGameUpdatesPerFrame(5); } public void MoveRight() { if (!jumping) { climbing = false; if (ducking) { ducking = false; y -= (heightOfWalkingImage - heightOfDuckImage); } height = heightOfWalkingImage; x += xSpeed; ChangeDirection(RIGHT); NextFrame(); } } public void MoveLeft() { if (!jumping) { climbing = false; if (ducking) { ducking = false; y -= (heightOfWalkingImage - heightOfDuckImage); } height = heightOfWalkingImage; x -= xSpeed; ChangeDirection(LEFT); NextFrame(); } } public void MoveUp() { y -= (heightOfClimbingImage - height); height = heightOfClimbingImage; y -= ySpeed; ChangeDirection(UP); NextFrame(); } public void MoveDown() { height = heightOfClimbingImage; y += ySpeed; ChangeDirection(UP); NextFrame(); } public void Jump() { if (!jumping) { ChangeDirection(JUMPING); y -= (heightOfClimbingImage - heightOfWalkingImage); height = heightOfWalkingImage; jumping = true; } } public void Move(Room r) { if (jumping) { jumpFrame++; if (jumpFrame > framesInJump) { jumping = false; y += jumpSize; ChangeDirection(RIGHT); jumpFrame = 1; } } // If not jumping nor climbing, let's check gravity else if (!climbing) { if (r.CanMoveTo(x, y + gravitySpeed, x + width, y + height + gravitySpeed)) MoveTo(x, y + gravitySpeed); } } public void Duck() { if (ducking || climbing || jumping) return; ducking = true; y += (heightOfWalkingImage - heightOfDuckImage); height = heightOfDuckImage; ChangeDirection(DOWN); } public void TryToMoveRight(Room r) { // If we can move right, let's do it if (r.CanMoveTo(x + xSpeed, y, x + xSpeed + width,y + standardHeight)) { MoveRight(); } else { // If there is a side stair to climb, let's do it if (r.CanMoveTo(x + xSpeed, y - 32, x + xSpeed + width, y + height - 32)) { y -= 32; MoveRight(); } } int nextRoom = r.CheckIfNewRoom(this); if (nextRoom != -1) { r.MoveToRoomRight(); MoveTo(0, y); } } public void TryToMoveLeft(Room r) { // If we can move left, let's do it if (r.CanMoveTo(x - xSpeed, y, x - xSpeed + width, y + standardHeight)) { MoveLeft(); } else { // If there is a side stair to climb, let's do it if (r.CanMoveTo(x - xSpeed, y - 32, x - xSpeed + width, y + height - 32)) { y -= 32; MoveLeft(); } } int nextRoom = r.CheckIfNewRoom(this); if (nextRoom != -1) { r.MoveToRoomLeft(); MoveTo(1024-width, y); } } public void TryToMoveUp(Room r) { // If there is a stair upwards, let's climb it if (r.IsThereVerticalStair(x, y - ySpeed, x + width, y + height - ySpeed)) { // TO DO: Check if there is ground over the stair climbing = true; MoveUp(); } else { climbing = false; Jump(); } int nextRoom = r.CheckIfNewRoom(this); if (nextRoom != -1) { r.MoveToRoomUp(); MoveTo(x, 17*32-height); } } public void TryToMoveDown(Room r) { // If there is a stair downwards, let's use it if (r.IsThereVerticalStair(x, y + ySpeed, x + width, y + height + ySpeed)) { // TO DO: Check if there is ground under the stair climbing = true; MoveDown(); } else { climbing = false; Duck(); } int nextRoom = r.CheckIfNewRoom(this); if (nextRoom != -1) { r.MoveToRoomDown(); MoveTo(x, 0); } } }
using System.Collections; using System.Collections.Generic; public class AckRoleLoginOk { private string _uname; public AckRoleLoginOk(Packet packet) { this._uname = packet.ReadString(); } public string uname { get { return this._uname; } set { this._uname = value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace CoreComponents.Threading { /// <summary> /// Incase you don't want to use a queue to pass data between threads. /// </summary> /// <typeparam name="T"></typeparam> public sealed class GetSet<T> { T myItem; readonly SpinLock mySpinLock = new SpinLock(false); readonly bool myUseMemoryBarrier; public GetSet(bool useMemoryBarrier = false) { myUseMemoryBarrier = useMemoryBarrier; } public GetSet(T item, bool useMemoryBarrier = false) { myItem = item; myUseMemoryBarrier = useMemoryBarrier; } public T Get() { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); return myItem; } finally { if(lockTaken) mySpinLock.Exit(myUseMemoryBarrier); } } public bool Get(T previous, Func<T, T, bool> func) { T item = Get(); return func(item, previous); } /// <summary> /// Use if reference type /// </summary> /// <param name="item"></param> /// <returns></returns> public bool TryGet(out T item) { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); item = myItem; } finally { if(lockTaken) mySpinLock.Exit(myUseMemoryBarrier); } return item != null; } public void Set(T item) { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); myItem = item; } finally { if(lockTaken) mySpinLock.Exit(myUseMemoryBarrier); } } public void SetDefault() { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); myItem = default(T); } finally { if(lockTaken) mySpinLock.Exit(myUseMemoryBarrier); } } public bool IsNull { get { bool lockTaken = false; try { mySpinLock.Enter(ref lockTaken); return myItem == null; } finally { if(lockTaken) mySpinLock.Exit(myUseMemoryBarrier); } } } public bool UseMemoryBarrier { get { return myUseMemoryBarrier; } } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("DisableMesh_Intensity")] public class DisableMesh_Intensity : MonoBehaviour { public DisableMesh_Intensity(IntPtr address) : this(address, "DisableMesh_Intensity") { } public DisableMesh_Intensity(IntPtr address, string className) : base(address, className) { } public void Start() { base.method_8("Start", Array.Empty<object>()); } public void Update() { base.method_8("Update", Array.Empty<object>()); } public Material m_material { get { return base.method_3<Material>("m_material"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DataObject; namespace Service.Interface { public interface INhanTraPhong { int Them(NhanTraPhong ntp); int Xoa(int maNTP); int CapNhat(NhanTraPhong ntp); } }
namespace PlatformRacing3.Server.Game.Communication.Messages.Incoming.Json; internal sealed class JsonConfirmConnectionIncomingMessage : JsonPacket { }
using System; using System.IO; using System.Linq; namespace ZhouliGenerateCode { class Program { static void Main(string[] args) { //扫描 Console.WriteLine("正在自动生成BLL,DAL层代码,请稍候......"); DirectoryInfo directoryInfo = new DirectoryInfo($"{AppContext.BaseDirectory}../../../../Zhouli.DbEntity/Models"); FileInfo[] modelFileInfos = directoryInfo.GetFiles().Where(t => !t.Name.Equals("ZhouLiContext.cs")).ToArray(); CreateCode createCode = new CreateCode(); foreach (var fileInfo in modelFileInfos) { createCode.CreateDAL(fileInfo.Name.Replace(".cs", "")); createCode.CreateBLL(fileInfo.Name.Replace(".cs", "")); } Console.WriteLine("全部生成成功!"); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using NewsMooseClassLibrary.Interfaces; using NewsMooseClassLibrary.Models; using System.Data.SQLite; using System.IO; namespace NewsMooseClassLibrary.DataBase { public class DatabaseStorage : IDataBase { private string DATA_SOURCE = "DataBase.sqlite"; SQLiteConnection connection; public DatabaseStorage() { connection = new SQLiteConnection("Data Source=" + DATA_SOURCE); connection.Open(); InitializeDatabase(); } private void InitializeDatabase() { SQLiteCommand command = new SQLiteCommand(connection); command.CommandText = "CREATE TABLE IF NOT EXISTS Publisher (publisher_id varchar(20), publishername varchar(50))"; command.ExecuteNonQuery(); command.CommandText = "CREATE TABLE IF NOT EXISTS Newspaper (newspapername varchar(50), publisher_id varchar(20))"; command.ExecuteNonQuery(); } public void DeleteNewsLetters(List<NewsPaper> newsPaper) { throw new NotImplementedException(); } public void DeletePublishers(List<Publisher> publishers) { throw new NotImplementedException(); } public List<NewsPaper> GetNewsPapers() { throw new NotImplementedException(); } public List<NewsPaper> GetNewsPapers(Publisher publisher) { Array publishers = this.LoadDataBase()?.Publishers; if (publishers != null) { foreach (Publisher xpublisher in publishers) { if (xpublisher.Name == publisher.Name) { return xpublisher.NewsPapers.ToList(); } } } return new List<NewsPaper>(); } public List<Publisher> GetPublishers() { throw new NotImplementedException(); } public void InsertNewsletters(List<NewsPaper> newsPapers) { throw new NotImplementedException(); } public void InsertPublishers(List<Publisher> publishers) { throw new NotImplementedException(); } public XmlDataBase LoadDataBase() { SQLiteCommand command = new SQLiteCommand(connection); command.CommandText = "SELECT * FROM Publisher"; SQLiteDataReader reader = command.ExecuteReader(); List<NewsPaper> newspapers = new List<NewsPaper>(); List<Publisher> publishers = new List<Publisher>(); if (reader.HasRows) { while (reader.Read()) { Publisher xpublisher = new Publisher(); xpublisher.Name = reader.GetString(1); string publisherid = reader.GetString(0); SQLiteCommand command2 = new SQLiteCommand(connection); command2.CommandText = "SELECT * FROM Newspaper WHERE publisher_id = '" + publisherid + "'"; SQLiteDataReader newsreader = command2.ExecuteReader(); List<NewsPaper> xnewspapers = new List<NewsPaper>(); if (newsreader.HasRows) { while (newsreader.Read()) { NewsPaper newspaper = new NewsPaper(); newspaper.Name = newsreader.GetString(0); xnewspapers.Add(newspaper); } } newspapers.AddRange(xnewspapers); publishers.Add(xpublisher); } } return new XmlDataBase(newspapers.ToArray(), publishers.ToArray()); } public void SaveDataBase(XmlDataBase database) { ClearDatabase(); Dictionary<string, int> publisherNameAndId = new Dictionary<string, int>(); using (SQLiteCommand command = new SQLiteCommand(connection)) { int counter = 0; foreach (Publisher publisher in database.Publishers) { command.CommandText = $"INSERT INTO Publisher(publisher_id, publishername) VALUES ('{counter}', '{publisher.Name}')"; command.ExecuteNonQuery(); publisherNameAndId.Add(publisher.Name, counter); foreach(NewsPaper paper in publisher.NewsPapers) { command.CommandText = $"INSERT INTO Newspaper(newspapername, publisher_id) VALUES('{paper.Name}', '{counter}')"; command.ExecuteNonQuery(); } ++counter; } foreach (NewsPaper paper in database.NewsPapers) { string publisherID = "NULL"; if (paper.Publisher != null && publisherNameAndId.Keys.Contains(paper.Publisher?.Name)) { publisherID = publisherNameAndId[paper.Publisher.Name].ToString(); } try { command.CommandText = $"INSERT INTO Newspaper(newspapername, publisher_id) VALUES('{paper.Name}', '{publisherID}');"; command.ExecuteNonQuery(); } catch { } } } } private void ClearDatabase() { using (SQLiteCommand command = new SQLiteCommand(connection)) { command.CommandText = "DELETE FROM Publisher"; command.ExecuteNonQuery(); command.CommandText = "DELETE FROM Newspaper"; command.ExecuteNonQuery(); } } public void UpdateNewsletters(List<NewsPaper> newsPapers) { throw new NotImplementedException(); } public void UpdatePublishers(List<Publisher> publishers) { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MouseClickScript : MonoBehaviour { public GameObject sphere; Vector3 targetPos; // Use this for initialization void Start () { sphere = GameObject.Find ("CreationTarget"); targetPos = transform.position; } // Update is called once per frame void Update () { //code used from coffeebreakcodes.com/move-object-to-mouse-click-position-unity3d/ if (Input.GetMouseButtonDown (0)) { Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); RaycastHit hit; if(Physics.Raycast(ray,out hit)){ targetPos = hit.point; targetPos.y = 0.25f; sphere.transform.position = targetPos; } } //end copy code } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossLeftTurret : MonoBehaviour { private Player _player; [SerializeField] private GameObject _explosionPrefab; [SerializeField] private GameObject _tinyExplosionPrefab; [SerializeField] private Transform target; [SerializeField] private float _fireRate = 1.0f; [SerializeField] private GameObject _enemyLaserPrefab; private int _leftTurretLife = 10; private int _smallPointValue = 5; private int _bigPointValue = 50; private float _canFire; private float _movementSpeed; private void Start() { _player = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); target = _player.transform; } private void Update() { if (_leftTurretLife <= 0) { if (_player != null) { _player.AddScore(_bigPointValue); } Instantiate(_explosionPrefab, transform.position, Quaternion.identity); Destroy(gameObject); } TurretMovement(); FireTurretLaser(); } private void TurretMovement() { transform.Translate(Vector3.right * _movementSpeed * Time.deltaTime); if (target != null) { transform.right = target.position - transform.position; } } private void FireTurretLaser() { if (Time.time > _canFire) { _fireRate = Random.Range(1f, 5f); _canFire = Time.time + _fireRate; GameObject enemyLaser = Instantiate(_enemyLaserPrefab, transform.position, Quaternion.Euler(new Vector3(0, 0, (transform.localEulerAngles.z + 90)))); Laser[] lasers = enemyLaser.GetComponentsInChildren<Laser>(); for (int i = 0; i < lasers.Length; i++) { lasers[i].AssignEnemyLaser(); } } } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") { _leftTurretLife--; if (_player != null) { _player.Damage(); } } if (other.tag == "Laser") { Laser lasers = other.transform.GetComponentInChildren<Laser>(); if (!lasers._isEnemyLaser) { _leftTurretLife--; if (_player != null) { _player.AddScore(_smallPointValue); } Instantiate(_tinyExplosionPrefab, other.transform.position, Quaternion.identity); Destroy(other.gameObject); } } if (other.tag == "SuperBeam") { _leftTurretLife--; if (_player != null) { _player.AddScore(_smallPointValue); } } if (other.tag == "SuperMissile") { _leftTurretLife--; if (_player != null) { _player.AddScore(_smallPointValue); } } } }
using MediatR; using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; // ReSharper disable once CheckNamespace namespace OmniSharp.Extensions.DebugAdapter.Protocol { namespace Events { [Parallel] [Method(EventNames.Process, Direction.ServerToClient)] [GenerateHandler] [GenerateHandlerMethods] [GenerateRequestMethods] public record ProcessEvent : IRequest { /// <summary> /// The logical name of the process. This is usually the full path to process's executable file. Example: /home/example/myproj/program.js. /// </summary> public string Name { get; init; } = null!; /// <summary> /// The system process id of the debugged process. This property will be missing for non-system processes. /// </summary> [Optional] public long? SystemProcessId { get; init; } /// <summary> /// If true, the process is running on the same computer as the debug adapter. /// </summary> [Optional] public bool IsLocalProcess { get; init; } /// <summary> /// Describes how the debug engine started debugging this process. /// 'launch': Process was launched under the debugger. /// 'attach': Debugger attached to an existing process. /// 'attachForSuspendedLaunch': A project launcher component has launched a new process in a suspended state and then asked the debugger to attach. /// </summary> [Optional] public ProcessEventStartMethod? StartMethod { get; init; } /// <summary> /// The size of a pointer or address for this process, in bits. This value may be used by clients when formatting addresses for display. /// </summary> [Optional] public long? PointerSize { get; init; } } [StringEnum] public readonly partial struct ProcessEventStartMethod { public static ProcessEventStartMethod Launch { get; } = new ProcessEventStartMethod("launch"); public static ProcessEventStartMethod Attach { get; } = new ProcessEventStartMethod("attach"); public static ProcessEventStartMethod AttachForSuspendedLaunch { get; } = new ProcessEventStartMethod("attachForSuspendedLaunch"); } } }
namespace Cooking.Ingredients { using System; using System.Text; public abstract class Vegetable { public Vegetable() { this.IsRotten = false; this.IsPeeled = false; this.IsCut = false; this.IsCooked = false; } public bool IsRotten { get; set; } public bool IsPeeled { get; set; } public bool IsCut { get; set; } public bool IsCooked { get; set; } public void Peel() { this.IsPeeled = true; } public void Cut() { this.IsCut = true; } public void Cook() { this.IsCooked = true; } public override string ToString() { var result = new StringBuilder(); result.AppendFormat("{0}", this.GetType().Name).AppendLine(); result.AppendFormat("{0},", this.IsPeeled ? "peeled" : "not peeled"); result.AppendFormat("{0},", this.IsCut ? "cut" : "not cut"); result.AppendFormat("{0}", this.IsCooked ? "cooked" : "not cooked"); result.AppendLine(); return result.ToString(); } } }
using NLog; using OpenQA.Selenium; namespace Framework.Elements { public class Button : BaseElement { Logger logger = LogManager.GetCurrentClassLogger(); public Button(By locator, IWebDriver driver) { Locator = locator; Driver = driver; } public bool IsClickButton() { logger.Debug("Click Button"); bool test = IsElementAvailability(Locator); if (test) { logger.Debug("Success Click Button"); Driver.FindElement(Locator).Click(); return true; } else { logger.Debug("Failed Click Button"); return false; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; //Work in progress base class for heroes/students //All heroes will inherit from this class //Added by Tom Moreton 18/05/2017 public class Hero : MonoBehaviour { public string m_heroName; public int m_health; public int m_damage; public enum m_heroStatus { Slowed, Stunned, Default, DamageAmplified, HealthAmplified } public m_heroStatus m_myHeroStatus; public enum m_heroType { Bully, Nerd, Jock } public m_heroType m_myHeroType; public Sprite m_heroSprite; public float m_movementSpeed; public float m_jumpStrength; [System.Serializable] public struct m_heroStats { public int m_heroXP; public int m_heroGold; public int m_heroKills; public int m_heroAssits; public int m_heroHealing; public int m_heroDamage; } public Ability[] m_heroAbilities; // Use this for initialization void Start () { gameObject.GetComponent<SpriteRenderer>().sprite = m_heroSprite; } // Update is called once per frame void Update () { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace TinyURL.ViewModels { public class URLMapViewModel { public string URL { get; set; } public string EncodedURL { get; set; } } }
 namespace Bindable.Linq.Tests.TestLanguage.Helpers { /// <summary> /// Specifies the levels of compatability between a Bindable LINQ query and /// standard LINQ to Objects. /// </summary> internal enum CompatabilityLevel { /// <summary> /// The queries, including items, groups and order, should be the same. /// </summary> FullyCompatible, /// <summary> /// The queries should be the same, but differences in the ordering of items /// or child items should be ignored, so long as all items are present. /// </summary> FullyCompatibleExceptOrdering } }
using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using ZXing.Net.Mobile.Forms; namespace App1 { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class Page1 : ContentPage { ZXingBarcodeImageView barcode; public Page1() { InitializeComponent(); } //qr 코드 만들기 private void Button_Clicked(object sender, EventArgs e) { try { if (contentEntry.Text != string.Empty) { barcode = new ZXingBarcodeImageView { HorizontalOptions = LayoutOptions.FillAndExpand, VerticalOptions = LayoutOptions.FillAndExpand, AutomationId = "zxingBarcodeImageView", }; barcode.BarcodeFormat = ZXing.BarcodeFormat.QR_CODE; barcode.BarcodeOptions.Width = 500; barcode.BarcodeOptions.Height = 500; barcode.BarcodeOptions.Margin = 10; barcode.BarcodeValue = contentEntry.Text.Trim(); qrResult.Content = barcode; } } catch{} } } }
using System; using System.Collections.Generic; using System.Text; namespace TQVaultAE.Domain.Results { public class GamePathEntry { public readonly string Path; public readonly string DisplayName; public GamePathEntry(string path, string displayName) { this.Path = path; this.DisplayName = displayName; } public override string ToString() => DisplayName ?? Path ?? "Empty"; } }
using System; namespace ConsoleApp { class method { public string ChuanHoa(string s) { s = s.Trim().ToLower(); while (s.Contains(" ")) { s.Replace(" ", " "); } string[] s1 = s.Split(" "); s = ""; foreach (string item in s1) { s += item.Substring(0, 1).ToUpper() + item.Substring(1) + " "; } return s.TrimEnd(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class XformLoader : MonoBehaviour { public enum Direction { UP, RIGHT, FORWARD}; public Direction dir = 0; // to support slow rotation about the y-axis public float kRotateDelta = 45; // per second private float IncSign = 1; // Use this for initialization void Start() { } // Update is called once per frame void Update() { IncrementXform(); } Vector3 GetDir(Direction d) { switch(d) { case Direction.UP: return Vector3.up; case Direction.FORWARD: return Vector3.forward; case Direction.RIGHT: return Vector3.right; } return transform.up; } void IncrementXform() { // rotation if ((transform.localRotation.eulerAngles.x < 0) || (transform.localRotation.eulerAngles.x > 180) || (transform.localRotation.eulerAngles.y < 0) || (transform.localRotation.eulerAngles.y > 180) || (transform.localRotation.eulerAngles.z < 0) || (transform.localRotation.eulerAngles.z > 180)) IncSign *= -1; Quaternion q = Quaternion.AngleAxis(IncSign * kRotateDelta * Time.fixedDeltaTime, GetDir(dir)); transform.localRotation = q * transform.localRotation; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; namespace Discovery.Core.UI.AttachedProperties { public class PasswordBoxMonitor : DependencyObject { public static readonly DependencyProperty IsMonitoringProperty = DependencyProperty.RegisterAttached( "IsMonitoring", typeof(bool), typeof(PasswordBoxMonitor), new UIPropertyMetadata(false, OnIsMonitoringChanged)); public static readonly DependencyProperty PasswordLengthProperty = DependencyProperty.RegisterAttached( "PasswordLength", typeof(int), typeof(PasswordBoxMonitor), new UIPropertyMetadata(0)); public static int GetPasswordLength(DependencyObject element) => (int)element.GetValue(PasswordLengthProperty); public static void SetPasswordLength(DependencyObject element, int value) => element.SetValue(PasswordLengthProperty, value); public static bool GetIsMonitoring(DependencyObject element) => (bool)element.GetValue(IsMonitoringProperty); public static void SetIsMonitoring(DependencyObject element, bool value) => element.SetValue(IsMonitoringProperty, value); private static void OnIsMonitoringChanged( DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is PasswordBox passwordBox) { if ((bool)e.NewValue) { passwordBox.PasswordChanged += PasswordChanged; return; } passwordBox.PasswordChanged -= PasswordChanged; } void PasswordChanged(object sender, RoutedEventArgs _) { if (sender is PasswordBox pwdBox) { SetPasswordLength(pwdBox, pwdBox.Password.Length); } } } } }
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 PIT_Server.Resources { public partial class ControlPanel : Form { Timer _updater; public ControlPanel() { InitializeComponent(); } private void _updater_Tick(object sender, EventArgs e) { var gos = Lobby.scene.GameObjects.Keys.ToList(); object[] arr = new object[listBox1.Items.Count]; listBox1.Items.CopyTo(arr, 0); var list = new List<string>(arr.Select(x=>(string)x)); foreach (var go in gos) { if (!list.Contains(go.ToString())) listBox1.Items.Add(go.ToString()); } } private void ControlPanel_Load(object sender, EventArgs e) { //MessageBox.Show(Lobby.scene.GameObjects.Count.ToString()); _updater = new Timer(); _updater.Interval = 200; _updater.Tick += _updater_Tick; _updater.Start(); } } }
using System; using UserStorageServices.Validation.Attributes; namespace UserStorageServices { /// <summary> /// Represents a user. /// </summary> [Serializable] public class User { /// <summary> /// Gets or sets a user id. /// </summary> public Guid Id { get; set; } /// <summary> /// Gets or sets a user first name. /// </summary> [ValidateNotNullOrWhiteSpace] [ValidateMaxLength(20)] [ValidateRegex("^[A-Za-z]+$")] public string FirstName { get; set; } /// <summary> /// Gets or sets a user last name. /// </summary> [ValidateNotNullOrWhiteSpace] [ValidateMaxLength(25)] [ValidateRegex("^[A-Za-z]+$")] public string LastName { get; set; } /// <summary> /// Gets or sets a user age. /// </summary> [ValidateMinMax(3, 130)] public int Age { get; set; } } }
using PDV.DAO.Custom; using PDV.DAO.DB.Controller; using PDV.DAO.Entidades; using PDV.DAO.Enum; using System; using System.Collections.Generic; using System.Data; namespace PDV.CONTROLER.Funcoes { public class FuncoesTransportadora { public static bool ExisteTransportadora(decimal IDTransportadora) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT 1 FROM TRANSPORTADORA WHERE IDTRANSPORTADORA = @IDTRANSPORTADORA"; oSQL.ParamByName["IDTRANSPORTADORA"] = IDTransportadora; oSQL.Open(); return !oSQL.IsEmpty; } } public static Transportadora GetTransportadora(decimal IDTransportadora) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT IDTRANSPORTADORA, RAZAOSOCIAL, CNPJ, CPF, NOME, INSCRICAOESTADUAL, ISENTO, IDENDERECO, TIPODOCUMENTO FROM TRANSPORTADORA WHERE IDTRANSPORTADORA = @IDTRANSPORTADORA"; oSQL.ParamByName["IDTRANSPORTADORA"] = IDTransportadora; oSQL.Open(); if (oSQL.IsEmpty) return null; return EntityUtil<Transportadora>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static Transportadora GetTransportadoraPorCNPJ(string CNPJ) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT IDTRANSPORTADORA, RAZAOSOCIAL, CNPJ, CPF, NOME, INSCRICAOESTADUAL, ISENTO, IDENDERECO, TIPODOCUMENTO FROM TRANSPORTADORA WHERE IDTRANSPORTADORA = @IDTRANSPORTADORA"; oSQL.ParamByName["CNPJ"] = CNPJ; oSQL.Open(); if (oSQL.IsEmpty) return null; return EntityUtil<Transportadora>.ParseDataRow(oSQL.dtDados.Rows[0]); } } public static DataTable GetTransportadoras(string Nome_RazaoSocial, string CPF_CNPJ, string InscricaoEstadual) { using (SQLQuery oSQL = new SQLQuery()) { List<string> Filtros = new List<string>(); if (!string.IsNullOrEmpty(Nome_RazaoSocial)) Filtros.Add(string.Format("(UPPER(RAZAOSOCIAL) LIKE UPPER('%{0}%') OR UPPER(NOME) LIKE UPPER('%{0}%'))", Nome_RazaoSocial)); if (!string.IsNullOrEmpty(CPF_CNPJ)) Filtros.Add(string.Format("(CNPJ LIKE UPPER('%{0}%') OR CPF LIKE UPPER('%{0}%'))", CPF_CNPJ)); if (!string.IsNullOrEmpty(InscricaoEstadual)) Filtros.Add(string.Format("(INSCRICAOESTADUAL::VARCHAR LIKE '%{0}%')", InscricaoEstadual)); oSQL.SQL = string.Format(@"SELECT TRANSPORTADORA.IDTRANSPORTADORA, CASE WHEN TIPODOCUMENTO = 0 THEN RAZAOSOCIAL ELSE NOME END AS NOME, CASE WHEN TIPODOCUMENTO = 0 THEN CNPJ ELSE CPF END AS NUMERODOCUMENTO FROM TRANSPORTADORA {0} ORDER BY RAZAOSOCIAL, NOME", Filtros.Count > 0 ? "WHERE " + string.Join(" AND ", Filtros.ToArray()) : string.Empty); oSQL.Open(); return oSQL.dtDados; } } public static DataTable GetTransportadoras(string Nome_RazaoSocial) { using (SQLQuery oSQL = new SQLQuery()) { List<string> Filtros = new List<string>(); if (!string.IsNullOrEmpty(Nome_RazaoSocial)) Filtros.Add(string.Format("(UPPER(RAZAOSOCIAL) LIKE UPPER('%{0}%') OR UPPER(NOME) LIKE UPPER('%{0}%'))", Nome_RazaoSocial)); oSQL.SQL = string.Format(@"SELECT TRANSPORTADORA.IDTRANSPORTADORA, CASE WHEN TIPODOCUMENTO = 0 THEN RAZAOSOCIAL ELSE NOME END AS NOME, CASE WHEN TIPODOCUMENTO = 0 THEN CNPJ ELSE CPF END AS NUMERODOCUMENTO, TRANSPORTADORA.IDENDERECO FROM TRANSPORTADORA {0} ORDER BY RAZAOSOCIAL, NOME", Filtros.Count > 0 ? "WHERE " + string.Join(" AND ", Filtros.ToArray()) : string.Empty); oSQL.Open(); return oSQL.dtDados; } } public static bool Salvar(Transportadora _Transportadora, TipoOperacao _Operacao) { using (SQLQuery oSQL = new SQLQuery()) { switch (_Operacao) { case TipoOperacao.INSERT: oSQL.SQL = @"INSERT INTO TRANSPORTADORA (IDTRANSPORTADORA, RAZAOSOCIAL, CNPJ, CPF, NOME, INSCRICAOESTADUAL, ISENTO, IDENDERECO, TIPODOCUMENTO) VALUES (@IDTRANSPORTADORA, @RAZAOSOCIAL, @CNPJ, @CPF, @NOME, @INSCRICAOESTADUAL, @ISENTO, @IDENDERECO, @TIPODOCUMENTO)"; break; case TipoOperacao.UPDATE: oSQL.SQL = @"UPDATE TRANSPORTADORA SET RAZAOSOCIAL = @RAZAOSOCIAL, CNPJ = @CNPJ, CPF = @CPF, NOME = @NOME, INSCRICAOESTADUAL = @INSCRICAOESTADUAL, ISENTO = @ISENTO, IDENDERECO = @IDENDERECO, TIPODOCUMENTO = @TIPODOCUMENTO WHERE IDTRANSPORTADORA = @IDTRANSPORTADORA"; break; } oSQL.ParamByName["IDTRANSPORTADORA"] = _Transportadora.IDTransportadora; oSQL.ParamByName["RAZAOSOCIAL"] = _Transportadora.RazaoSocial; oSQL.ParamByName["CNPJ"] = _Transportadora.CNPJ; oSQL.ParamByName["CPF"] = _Transportadora.CPF; oSQL.ParamByName["NOME"] = _Transportadora.Nome; oSQL.ParamByName["INSCRICAOESTADUAL"] = DBNull.Value; if (_Transportadora.InscricaoEstadual.HasValue) oSQL.ParamByName["INSCRICAOESTADUAL"] = _Transportadora.InscricaoEstadual; oSQL.ParamByName["ISENTO"] = _Transportadora.Isento; oSQL.ParamByName["IDENDERECO"] = _Transportadora.IDEndereco; oSQL.ParamByName["TIPODOCUMENTO"] = _Transportadora.TipoDocumento; return oSQL.ExecSQL() == 1; } } public static bool Remover(decimal IDTransportadora) { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = "SELECT IDENDERECO FROM TRANSPORTADORA WHERE IDTRANSPORTADORA = @IDTRANSPORTADORA"; oSQL.ParamByName["IDTRANSPORTADORA"] = IDTransportadora; oSQL.Open(); if (!oSQL.IsEmpty) { decimal IDEndereco = Convert.ToDecimal(oSQL.dtDados.Rows[0]["IDENDERECO"]); oSQL.ClearAll(); oSQL.SQL = "DELETE FROM ENDERECO WHERE IDENDERECO = @IDENDERECO"; oSQL.ParamByName["IDENDERECO"] = IDEndereco; if (oSQL.ExecSQL() != 1) throw new Exception(); } oSQL.SQL = "DELETE FROM TRANSPORTADORA WHERE IDTRANSPORTADORA = @IDTRANSPORTADORA"; oSQL.ParamByName["IDTRANSPORTADORA"] = IDTransportadora; return oSQL.ExecSQL() == 1; } } public static List<Transportadora> GetTransportadoras() { using (SQLQuery oSQL = new SQLQuery()) { oSQL.SQL = @"SELECT IDTRANSPORTADORA, COALESCE(CPF, CNPJ) AS DOCUMENTO, COALESCE(NOME, RAZAOSOCIAL) AS NOME, COALESCE(CPF, CNPJ)||' - '||COALESCE(NOME, RAZAOSOCIAL) AS DESCRICAOTRANSPORTADORA FROM TRANSPORTADORA"; oSQL.Open(); return new DataTableParser<Transportadora>().ParseDataTable(oSQL.dtDados); } } } }
using System; using System.Collections.Generic; namespace Paralect.Schematra { public class RecordTypeBuilder : RecordType { public RecordTypeBuilder(TypeContext typeContext) : base(typeContext) { } /// <summary> /// Define name by name and @namespace /// </summary> public RecordTypeBuilder SetName(String name, String @namespace) { SetNameInternal(name, @namespace); return this; } /// <summary> /// Define name by full name /// </summary> public RecordTypeBuilder SetName(String fullName) { SetNameInternal(fullName); return this; } /// <summary> /// Define tag /// </summary> public RecordTypeBuilder SetTag(Guid tag) { _tag = tag; return this; } /// <summary> /// Define base record type /// </summary> public RecordTypeBuilder SetBaseType(String baseType) { _baseTypeResolver = new TypeResolver(baseType); return this; } /// <summary> /// Define base record type /// </summary> public RecordTypeBuilder SetBaseType(TypeResolver baseTypeResolver) { _baseTypeResolver = baseTypeResolver; return this; } public RecordTypeBuilder AddField(Int32 index, String name, TypeResolver typeResolver, FieldQualifier qualifier, Object defaultValue) { AddFieldInternal(index, name, typeResolver, qualifier, defaultValue); return this; } public RecordTypeBuilder AddField(Int32 index, String name, String typeName, FieldQualifier qualifier, Object defaultValue) { AddFieldInternal(index, name, new TypeResolver(typeName), qualifier, defaultValue); return this; } public RecordTypeBuilder SetUsings(List<String> usings) { SetUsingsInternal(usings); return this; } /// <summary> /// Create instance of RecordType. In case it was bult incorrect - throws exception. /// </summary> public RecordType Create() { // Defined in parent class as a clone-like function. return CreateRecordTypeInternal(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace CommonCore { public abstract class CCModule { //kinda-RAII: constructor=onapplicationstart //other lifecycle events public virtual void OnApplicationQuit() { } public virtual void OnGameStart() { } public virtual void OnSceneLoaded() { } public virtual void OnSceneUnloaded() { } public virtual void OnGameEnd() { } } public class CCExplicitModule : System.Attribute { } }
using System; namespace calendar { public class Calendar { public int Month { get; set; } = DateTime.Now.Month; public int Year { get; set; } = DateTime.Now.Year; public void Show() { Console.WriteLine($"********* Month: {this.Month}, {this.Year} *********"); Console.WriteLine("Mo \t Tu \t We \t Th \t Fr \t Sa \t Su"); var start = new DateTime(this.Year, this.Month, 1); var end = start.AddMonths(1).AddDays(-1); int numberDayOfWeek = (int) start.DayOfWeek; for (int i = 1; i < numberDayOfWeek; i++) { Console.Write("\t"); } for (DateTime day = start; day <= end; day = day.AddDays(1)) { if (day.DayOfWeek == DayOfWeek.Monday) { Console.WriteLine(); } if (day.DayOfWeek == DayOfWeek.Saturday || day.DayOfWeek == DayOfWeek.Sunday || day.Date == DateTime.Now.Date) { Console.ForegroundColor = ConsoleColor.Red; Console.Write(day.Day + "\t"); Console.ResetColor(); }else{ Console.Write(day.Day + "\t"); } } Console.WriteLine(); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; using System.Net; using System.Net.Http; using System.Web.Http; using Dnn.PersonaBar.Library; using Dnn.PersonaBar.Library.Attributes; using Dnn.PersonaBar.Servers.Components.WebServer; using DotNetNuke.Instrumentation; namespace Dnn.PersonaBar.Servers.Services { [MenuPermission(Scope = ServiceScope.Host)] public class SystemInfoWebController : PersonaBarApiController { private static readonly ILog Logger = LoggerSource.Instance.GetLogger(typeof(SystemInfoWebController)); [HttpGet] public HttpResponseMessage GetWebServerInfo() { try { var serverInfo = new ServerInfo(); return Request.CreateResponse(HttpStatusCode.OK, new { osVersion = serverInfo.OSVersion, iisVersion = serverInfo.IISVersion, framework = serverInfo.Framework, identity = serverInfo.Identity, hostName = serverInfo.HostName, physicalPath = serverInfo.PhysicalPath, url = serverInfo.Url, relativePath = serverInfo.RelativePath, serverTime = serverInfo.ServerTime }); } catch (Exception exc) { Logger.Error(exc); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exc); } } } }
using System; using System.Text; using Cogent.IoC.Generators.Errors; using Cogent.IoC.Generators.Extensions; using Cogent.IoC.Generators.Models; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Text; namespace Cogent.IoC.Generators { [Generator] internal class ContainerGenerator : ISourceGenerator { public void Initialize(GeneratorInitializationContext context) { //System.Diagnostics.Debugger.Launch(); } public void Execute(GeneratorExecutionContext context) { try { var registrationSymbols = RegistrationSymbols.FromCompilation(context.Compilation); var containerClasses = context.LocateContainerSymbols(registrationSymbols.ContainerSymbol); var generator = new ContainerClassContentGenerator(context, registrationSymbols); foreach(var containerClass in containerClasses) { var hintName = $"Generated.{containerClass.FullyQualifiedName}"; var content = generator.GenerateClassString(containerClass); WriteOutDebugFile(hintName, content, context); context.AddSource(hintName, SourceText.From(content, Encoding.UTF8)); } } catch (DiagnosticException ex) { context.ReportDiagnostic(ex.Diagnostic); } catch (Exception ex) { var descriptor = new DiagnosticDescriptor(DiagnosticConstants.UnknownExceptionId, "Unexpected error", $"Unknown error during generation: {ex.GetType()} {ex.Message}", DiagnosticConstants.Category, DiagnosticSeverity.Error, true); context.ReportDiagnostic(Diagnostic.Create(descriptor, Location.None)); } } // TODO : Remove when possible to peek into generated code private void WriteOutDebugFile(string hintName, string content, GeneratorExecutionContext context) { #if DEBUG try { var tempFile = $"{System.IO.Path.GetTempPath()}{hintName}.cs"; System.IO.File.WriteAllText(tempFile, content); context.ReportDiagnostic(Diagnostic.Create(new DiagnosticDescriptor("GDBG", "Write out debug file", tempFile, DiagnosticConstants.Category, DiagnosticSeverity.Warning, true), Location.None)); } catch { throw; } #endif } } }
using System; using System.Collections.ObjectModel; using System.Linq; using System.Windows; using System.Windows.Input; using UserInterface.Command; namespace UserInterface.ViewModel { public class PatientViewModel : ViewModelBase { public ObservableCollection<DoctorViewModel.Prescription> PatientsPrescriptions { get; set; } = new ObservableCollection<DoctorViewModel.Prescription>(); public ICommand LoadPatientsPrescriptionsCommand => new RelayCommand(GetUsersPrescriptions, () => true); private async void GetUsersPrescriptions() { PatientsPrescriptions.Clear(); var allPrescriptions = blockChainHandler.GetAllPrescriptionsByPatient(CurrentUserId.ToString()); var realisedPrescriptions = blockChainHandler.GetAllRealizedPrescriptionsByPatient(CurrentUserId.ToString()); if (allPrescriptions == null || realisedPrescriptions == null) { MessageBox.Show("Blockchain unavailable, signing out.."); MainViewModel.LogOut(); } foreach (var prescription in allPrescriptions) { PatientsPrescriptions.Add(new DoctorViewModel.Prescription { Date = prescription.Date, ValidSince = prescription.ValidSince, Doctor = await userService.GetUser(Convert.ToInt32(prescription.doctorId)), Id = prescription.prescriptionId }); if (realisedPrescriptions.Select(x => x.prescriptionId).Contains(prescription.prescriptionId)) { PatientsPrescriptions.Last().Realised = true; } else PatientsPrescriptions.Last().Realised = false; foreach (var prescriptionMedicine in prescription.medicines) { var medicine = (await medicineModule.SearchMedicineById(prescriptionMedicine.id.ToString())).SingleOrDefault(); if (medicine != null) { PatientsPrescriptions.Last().Medicines.Add(new DoctorViewModel.PrescriptionMedicine(medicine)); PatientsPrescriptions.Last().Medicines.Last().Amount = prescriptionMedicine.amount; } } } OnPropertyChanged("PatientsPrescriptions"); } } }
namespace W3ChampionsStatisticService.CommonValueObjects { public static class ServerProvider { public static string Flo = "FLO"; public static string Bnet = "BNET"; } }
using Fiap.Microservices.Pedidos.Api.Models; using Fiap.Microservices.Pedidos.Api.Persistence.Repository; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Fiap.Microservices.Pedidos.Api.Controllers { [Route("api/[controller]")] [ApiController] public class ClientesController : ControllerBase { private readonly ILogger<ClientesController> _logger; private readonly IClienteRepository _clienteRepository; public ClientesController(ILogger<ClientesController> logger, IClienteRepository clienteRepository) { _logger = logger; _clienteRepository = clienteRepository; } [HttpGet] public async Task<IActionResult> SelecionarTodos() { var clientes = await _clienteRepository.SelecionarTodos(); return Ok(clientes); } [HttpGet("{id}")] public async Task<IActionResult> SelecionarPorId(int id) { var cliente = await _clienteRepository.SelecionarPorId(id); if (cliente == null) return NotFound(); return Ok(cliente); } [HttpPost] public async Task<IActionResult> Criar(Cliente cliente) { var clienteCriado = await _clienteRepository.Criar(cliente); return CreatedAtAction(nameof(SelecionarPorId), new { id = clienteCriado.Id }, clienteCriado); } [HttpPut] public async Task<IActionResult> Atualizar(Cliente cliente) { await _clienteRepository.Atualizar(cliente); return NoContent(); } [HttpDelete] public async Task<IActionResult> Excluir(Cliente cliente) { await _clienteRepository.Excluir(cliente.Id); return NoContent(); } } }
using Lotus.Client.Data.Models; using System.Collections.Generic; namespace Lotus.Client.Data { public class LocalDatabaseContext : DataContext { public List<MessageBlock> MessageBlockList; //.Data layer model } }
using System; using ReadyGamerOne.View.PanelSystem; using UnityEngine; namespace SecondGame.Interfaces { public static class Interface { /// <summary> /// 角色,上楼,进门,换位置,换场景效果 /// </summary> /// <param name="moveWho">移动的人物,这里应该是主角的Transform</param> /// <param name="targetPos">目标位置</param> /// <param name="time">在多少秒之内移动过去</param> /// <param name="callBack">移动完成的回调</param> public static void MoveTo(Transform moveWho,Vector3 targetPos, float time, Action callBack) { PanelMgr.FadeOut(time/2,Color.black, () => { moveWho.position = targetPos; PanelMgr.FadeIn(time/2,callBack); }); } } }
using System.Collections.Generic; using System.Linq; using PurificationPioneer.Const; using PurificationPioneer.Global; using PurificationPioneer.Network.ProtoGen; using PurificationPioneer.Scriptable; using PurificationPioneer.Utility; using ReadyGamerOne.MemorySystem; using ReadyGamerOne.Utility; using UnityEngine.Assertions; using System.Text; using ReadyGamerOne.Common; using UnityEngine; namespace PurificationPioneer.Script { public class PpCharacterController: MonoBehaviour, IPpController { #region const private const string AniSpeedScale = "AniSpeed"; #endregion #region SerializeFields [Tooltip("以本地模式运行")] [SerializeField] protected bool m_WorkAsLocal = false; [Tooltip("摄像机看向的点")] [SerializeField]private Transform m_CameraLookPoint; [Tooltip("玩家移动速度")] [HideInInspector] [SerializeField]private float m_MoveSpeed = 3; [Tooltip("玩家旋转速度")] [SerializeField] protected float m_DesiredRotationSpeed = 0.3f; [Tooltip("跳跃初始速度")] [SerializeField] protected float m_JumpSpeed = 10f; [Tooltip("重力比率")] [SerializeField] protected float m_GravatyScale = 1.0f; [Header("Animation Smoothing")] [SerializeField] private float m_AnimationSpeedScale = 1.0f; [Range(0,1f)] [SerializeField]private float m_StartAnimTime = 0.3f; [Range(0, 1f)] [SerializeField]private float m_StopAnimTime = 0.15f; [SerializeField]private float m_AllowPlayerRotation = 0.1f; [SerializeField]private float m_VerticalVel = -0.5f; #endregion #region No SerializeFields private bool m_Initialized = false; private bool m_IsGrounded; private bool m_BlockRotationPlayer; private bool m_LastAttack; // component refs private Animator m_Animator; private Camera m_Camera; private CharacterController m_CharacterController; protected LocalCameraHelper m_LocalCameraHelper; // sync private CharacterState m_LogicState = CharacterState.Idle; private CharacterState m_AniState = CharacterState.Idle; private int m_StickX, m_StickY, m_FaceX, m_FaceY, m_FaceZ; protected bool m_Attacking, m_Jumping; private float m_LogicYVelocity; #if DebugMode private float timer = 0; private float time = 1; private Vector3 lastPosition; #endif #endregion public float MoveSpeed { get => m_MoveSpeed; set => m_MoveSpeed = value; } public float PaintEfficiencyScale { get => HeroConfig.basePaintEfficiency/100f; } #region Events protected virtual void Start() { if (m_WorkAsLocal) { UnityAPI.LockMouse(); m_Animator = this.GetComponent<Animator> (); if (m_Animator) { m_Animator.SetFloat(AniSpeedScale, m_AnimationSpeedScale); } m_CharacterController = this.GetComponent<CharacterController> (); m_LocalCameraHelper = ResourceMgr.InstantiateGameObject(LocalAssetName.LocalCamera) .GetComponent<LocalCameraHelper>(); m_LocalCameraHelper.Init(transform,this.m_CameraLookPoint); m_Camera = m_LocalCameraHelper.ActivateCamera; } else { CEventCenter.AddListener<PlayerInput>(Message.OnInputPredict, OnInputPredict); } } protected virtual void Update() { if (m_WorkAsLocal) { m_Attacking = Input.GetKey(GameSettings.Instance.AttackKey); if (!m_LastAttack && m_Attacking) { m_BlockRotationPlayer = true; }else if (m_LastAttack && !m_Attacking) { m_BlockRotationPlayer = false; } if (m_Attacking) { RotateToCamera(transform); var face = m_Camera.transform.forward; OnCommonAttack(face.x.ToInt(), face.y.ToInt(), face.z.ToInt()); } UpdateAnimation(); m_IsGrounded = m_CharacterController.isGrounded; if (m_IsGrounded) m_VerticalVel -= 0; else m_VerticalVel -= 1; var moveVector = new Vector3(0, m_VerticalVel * .2f * Time.deltaTime, 0); m_CharacterController.Move(moveVector); m_LastAttack = m_Attacking; return; void UpdateAnimation() { //Calculate Input Vectors var InputX = GlobalVar.IsPlayerInControl ? Input.GetAxis ("Horizontal") : 0; var InputZ = GlobalVar.IsPlayerInControl ?Input.GetAxis ("Vertical") : 0; //Calculate the Input Magnitude var Speed = new Vector2(InputX, InputZ).sqrMagnitude; if (m_Animator) { //Change animation mode if rotation is blocked m_Animator.SetBool("shooting", m_BlockRotationPlayer); //Physically move player if (Speed > m_AllowPlayerRotation) { m_Animator.SetFloat ("Blend", Speed, m_StartAnimTime, Time.deltaTime); m_Animator.SetFloat("X", InputX, m_StartAnimTime/3, Time.deltaTime); m_Animator.SetFloat("Y", InputZ, m_StartAnimTime/3, Time.deltaTime); PlayerMoveAndRotation (); } else if (Speed < m_AllowPlayerRotation) { m_Animator.SetFloat ("Blend", Speed, m_StopAnimTime, Time.deltaTime); m_Animator.SetFloat("X", InputX, m_StopAnimTime/ 3, Time.deltaTime); m_Animator.SetFloat("Y", InputZ, m_StopAnimTime/ 3, Time.deltaTime); } } else if (Speed > m_AllowPlayerRotation) { PlayerMoveAndRotation (); } void PlayerMoveAndRotation() { var InputX = GlobalVar.IsPlayerInControl ? Input.GetAxis ("Horizontal"):0; var InputZ = GlobalVar.IsPlayerInControl ?Input.GetAxis ("Vertical"):0; var forward = m_Camera.transform.forward; var right = m_Camera.transform.right; forward.y = 0f; right.y = 0f; forward.Normalize(); right.Normalize(); var desiredMoveDirection = forward * InputZ + right * InputX; if (m_BlockRotationPlayer == false) { //Camera transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(desiredMoveDirection), m_DesiredRotationSpeed); var motion = desiredMoveDirection * Time.deltaTime * MoveSpeed; m_CharacterController.Move(motion); } else { //Strafe var motion = (transform.forward * InputZ + transform.right * InputX) * Time.deltaTime * MoveSpeed; m_CharacterController.Move(motion); } } } } if (!m_Initialized) return; #region Network #region Network Input #if UNITY_EDITOR if (Input.GetKeyDown(GameSettings.Instance.JumpKey)) { InputMgr.jump = true; } if (!GameSettings.Instance.WorkAsAndroid) { //用户输入 if (Input.GetKey(GameSettings.Instance.AttackKey)) InputMgr.attack = true; } #elif UNITY_STANDALONE_WIN //用户输入 if (Input.GetKeyDown(GameSettings.Instance.JumpKey)) { InputMgr.jump = true; } if (Input.GetKey(GameSettings.Instance.AttackKey)) InputMgr.attack = true; #endif #endregion //如果逻辑状态是击飞,眩晕,死亡的状态的话,表现层不变 if (m_LogicState != CharacterState.Idle && m_LogicState != CharacterState.Move) return; // Camera if (m_Attacking) { RotateToCamera(transform); } #region Animation if (m_Animator) { //Calculate the Input Magnitude var inputX = m_StickX.ToFloat(); var inputZ = m_StickY.ToFloat(); var inputMagnitude = new Vector2(inputX, inputZ).sqrMagnitude; //Change animation mode if rotation is blocked m_Animator.SetBool("shooting", m_BlockRotationPlayer); //Physically move player if (inputMagnitude > m_AllowPlayerRotation) { m_Animator.SetFloat ("Blend", inputMagnitude, m_StartAnimTime, Time.deltaTime); m_Animator.SetFloat("X", inputX, m_StartAnimTime/3, Time.deltaTime); m_Animator.SetFloat("Y", inputZ, m_StartAnimTime/3, Time.deltaTime); } else if (inputMagnitude < m_AllowPlayerRotation) { m_Animator.SetFloat ("Blend", inputMagnitude, m_StopAnimTime, Time.deltaTime); m_Animator.SetFloat("X", inputX, m_StopAnimTime/ 3, Time.deltaTime); m_Animator.SetFloat("Y", inputZ, m_StopAnimTime/ 3, Time.deltaTime); } } #endregion //没有移动的话,直接Idle不用管别的 if (this.m_StickX==0 && this.m_StickY==0 && !m_Jumping) { if (m_AniState == CharacterState.Move) { m_AniState=CharacterState.Idle; } return; } //有移动的话,切换状态,执行手柄逻辑 if (m_AniState == CharacterState.Idle) { m_AniState = CharacterState.Move; } DoSimulateY(Time.deltaTime); DoJoystick(Time.deltaTime); #if DebugMode //debug if(GameSettings.Instance.EnableMoveLog) { timer += Time.deltaTime; if (timer > time) { timer = 0; var move = transform.position - lastPosition; // Debug.Log($"[PpCharacterController] Move: {move.magnitude} {move}"); lastPosition = transform.position; } } #endif #endregion } protected virtual void OnDestroy() { if(!m_WorkAsLocal) CEventCenter.RemoveListener<PlayerInput>(Message.OnInputPredict, OnInputPredict); } #endregion private void DoJoystick(float deltaTime) { //没有移动,将逻辑状态置为Idle if (this.m_StickX == 0 && this.m_StickY == 0 && !m_Jumping) { m_LogicState = CharacterState.Idle; return; } //有移动,将逻辑状态置为Walk m_LogicState = CharacterState.Move; var desiredMotion = GetDesiredMotion(deltaTime); //Camera if (!m_BlockRotationPlayer) { transform.rotation = Quaternion.Slerp(transform.rotation, Quaternion.LookRotation(desiredMotion.normalized), m_DesiredRotationSpeed); } m_CharacterController.Move(desiredMotion); } private bool DoSimulateY(float deltaTime) { var hit = false; var currentPos = transform.position; var distance = 10; var dir = Mathf.Sign(m_LogicYVelocity) * Vector3.up; var start = currentPos + dir * -0.001f; var end = start + dir * distance; if (Mathf.Abs(m_LogicYVelocity) <= Mathf.Epsilon) { // Debug.Log("Direct return"); var tempAns = Physics.RaycastAll( currentPos + 0.001f * Vector3.up, Vector3.down , GameSettings.Instance.MinDetectableDistance, gameObject.GetUnityDetectLayer()); if (!tempAns.Any()) { return false; } return tempAns.Any(raycastHit => raycastHit.collider.gameObject != gameObject); } var desiredMotion = GetDesiredMotion(deltaTime); desiredMotion.y = m_LogicYVelocity * deltaTime; Debug.DrawLine(start, end, Color.red); var ans = Physics.RaycastAll(start, dir , distance, gameObject.GetUnityDetectLayer()); if (ans.Any()) { var desiredDistance = desiredMotion.magnitude; foreach (var raycastHit in ans) { if (raycastHit.collider.gameObject != gameObject && raycastHit.distance < desiredDistance) { desiredMotion.y = raycastHit.point.y-currentPos.y; // Debug.Log($"撞到: {raycastHit.collider.name}"); hit = true; break; } } } var perfectLogicPos = currentPos + Vector3.up * desiredMotion.y; // Debug.Log($"Move: {desiredMotion.y}"); transform.position = perfectLogicPos; //Vector3.Lerp(currentPos, perfectLogicPos, 0.5f); return hit; } #region IFrameSyncCharacter public int SeatId { get; private set; } public void SkipCharacterInput(IEnumerable<PlayerInput> inputs) { SyncLastCharacterInput(inputs); } public virtual void SyncLastCharacterInput(IEnumerable<PlayerInput> inputs) { foreach (var playerInput in inputs) { #if DebugMode if (GameSettings.Instance.EnableInputLog) { var msg = new StringBuilder(); msg.Append($"[InputMsg][FrameId-{FrameSyncMgr.FrameId}]"); msg.Append($"[Move-({playerInput.moveX},{playerInput.moveY}]"); msg.Append($"[Attack-{playerInput.attack}][Jump-{playerInput.jump}]"); msg.Append($"[Face-({playerInput.faceX},{playerInput.faceY})]"); msg.Append($"[Mouse-({playerInput.mouseX},{playerInput.mouseY})]"); Debug.Log(msg); } #endif this.m_StickX = playerInput.moveX; this.m_StickY = playerInput.moveY; this.m_FaceX = playerInput.faceX; this.m_FaceY = playerInput.faceY; this.m_FaceZ = playerInput.faceZ; this.m_Attacking = playerInput.attack; // Attack if (!m_LastAttack && m_Attacking) { m_BlockRotationPlayer = true; } else if (m_LastAttack && !m_Attacking) { m_BlockRotationPlayer = false; } m_LastAttack = m_Attacking; var deltaTime = GlobalVar.LogicFrameDeltaTime.ToFloat(); // Jump // if (m_CharacterController.isGrounded) { // print(1); if (!m_Jumping && playerInput.jump) { m_Jumping = true; m_LogicYVelocity = m_JumpSpeed; } } if (DoSimulateY(deltaTime))// 撞到东西 { m_Jumping = false; m_LogicYVelocity = 0; // Debug.Log("Reset"); } else// 更新速度 { var acceleration = Physics.gravity.y * m_GravatyScale; var newVel = m_LogicYVelocity + acceleration * deltaTime; m_LogicYVelocity = newVel; // Debug.Log($"Update: {m_LogicYVelocity}"); } var beforePos = transform.position; DoJoystick(deltaTime); var newPos = transform.position; if (playerInput.attack) { OnCommonAttack(this.m_FaceX,this.m_FaceY,this.m_FaceZ); } #if DebugMode if(GameSettings.Instance.EnableMoveLog) Debug.Log($"[GetInput-SyncLast] [Time {deltaTime}] ({this.m_StickX},{this.m_StickY}), 前进:{(newPos - beforePos).magnitude}"); #endif } } public void OnHandleCurrentCharacterInput(IEnumerable<PlayerInput> inputs) { foreach (var playerInput in inputs) { this.m_StickX = playerInput.moveX; this.m_StickY = playerInput.moveY; this.m_FaceX = playerInput.faceX; this.m_FaceY = playerInput.faceY; this.m_FaceZ = playerInput.faceZ; this.m_Attacking = playerInput.attack; #if DebugMode if(GameSettings.Instance.EnableMoveLog) Debug.Log($"[GetInput-Current-{FrameSyncMgr.FrameId}] ({this.m_StickX},{this.m_StickY})"); #endif if (this.m_StickX == 0 && this.m_StickY == 0 && !m_Jumping) { m_LogicState = CharacterState.Idle; } else { m_LogicState = CharacterState.Move; } } } #endregion #region IPpController public HeroConfigAsset HeroConfig { get; private set; } public void InitCharacterController(int seatId, HeroConfigAsset config) { m_Initialized = true; SeatId = seatId; HeroConfig = config; FrameSyncMgr.AddFrameSyncCharacter(this); //初始化内部参数 this.m_StickX = 0; this.m_StickY = 0; m_LogicState = CharacterState.Idle; m_Animator = this.GetComponent<Animator> (); m_CharacterController = this.GetComponent<CharacterController> (); Assert.IsTrue(m_CharacterController); if (m_Animator) { m_Animator.SetFloat(AniSpeedScale, m_AnimationSpeedScale); } InitCharacter(GlobalVar.LocalSeatId==SeatId); #if DebugMode //debug lastPosition = transform.position; #endif } #endregion #region protected protected virtual void InitCharacter(bool isLocal) { m_MoveSpeed = HeroConfig.moveSpeed; if (isLocal) { m_LocalCameraHelper = ResourceMgr.InstantiateGameObject(LocalAssetName.LocalCamera) .GetComponent<LocalCameraHelper>(); m_LocalCameraHelper.Init(transform,this.m_CameraLookPoint); m_Camera = m_LocalCameraHelper.ActivateCamera; #if UNITY_EDITOR if(GameSettings.Instance.AutoSelectLocalPlayer) UnityEditor.Selection.activeInstanceID = this.gameObject.GetInstanceID(); #endif } else { var headCanvasUi = ResourceMgr.InstantiateGameObject(LocalAssetName.CharacterHeadCanvas,transform) .GetComponent<CharacterHeadCanvas>(); headCanvasUi.transform.localPosition = Vector3.up * m_CharacterController.height; headCanvasUi.Init(Camera.main, GlobalVar.SeatId_MatcherInfo[SeatId].Unick); } } protected virtual void OnCommonAttack(int faceX, int faceY, int faceZ) { } #endregion #region private private void OnInputPredict(PlayerInput input) { if (SeatId != GlobalVar.LocalSeatId) return; m_StickX = input.moveX; m_StickY = input.moveY; m_FaceX = input.faceX; m_FaceY = input.faceY; m_FaceZ = input.faceZ; m_Attacking = input.attack; } private void RotateToCamera(Transform t) { var forward = m_Camera.transform.forward; Quaternion lookAtRotation = Quaternion.LookRotation(forward); Quaternion lookAtRotationOnly_Y = Quaternion.Euler(transform.rotation.eulerAngles.x, lookAtRotation.eulerAngles.y, transform.rotation.eulerAngles.z); t.rotation = Quaternion.Slerp(transform.rotation, lookAtRotationOnly_Y, m_DesiredRotationSpeed); } private Vector3 GetDesiredMotion(float deltaTime) { if (m_StickX == 0 && m_StickY == 0) { return Vector3.zero; } var inputX = m_StickX.ToFloat(); var inputZ = m_StickY.ToFloat(); var expectedForward = new Vector2(this.m_FaceX, this.m_FaceZ).normalized; var inputDir = new Vector2( inputX, inputZ); var angle = Mathf.Sign(inputDir.x) * Vector2.Angle(Vector2.up, inputDir); var moveDir = expectedForward.RotateDegree(angle); var desiredMoveDirection = new Vector3(moveDir.x, 0, moveDir.y); var desiredMotion = Vector3.zero; if (m_BlockRotationPlayer == false) { desiredMotion = desiredMoveDirection * (deltaTime * MoveSpeed); // Debug.Log($"Face:{expectedForward}, Input:{inputDir}, Angle:{angle}, Final: {desiredMoveDirection}"); } else { //Strafe desiredMotion = (transform.forward * inputZ + transform.right * inputX) * (deltaTime * MoveSpeed); // Debug.Log($"DesireDir: {(transform.forward * inputZ + transform.right * inputX)}"); } return desiredMotion; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; public class Pause_Script : MonoBehaviour { public UnityEvent OnPauseConv, OnPause, OnUnPause, OnInventoryEnter, OnInventoryExit; public KeyCodeData Pause_Keys, Inventory_Keys; private bool paused, inventory; private void Start() { paused = false; inventory = false; } private void Update() { if (Pause_Keys.KeyDown()) { if (!paused) { paused = true; Time.timeScale = 0; OnPause.Invoke(); } else { paused = false; Time.timeScale = 1; OnUnPause.Invoke(); } } } private void FixedUpdate() { if (Inventory_Keys.KeyDown()) { if (!inventory) { inventory = true; OnInventoryEnter.Invoke(); } else { inventory = false; OnInventoryExit.Invoke(); } } } public void ConversationPause() { OnPauseConv.Invoke(); } }
using System; using System.Runtime.InteropServices; namespace SharpPcap { public class PcapStatistics { /// <value> /// Number of packets received /// </value> private int receivedPackets; public int ReceivedPackets { get { return receivedPackets; } set { receivedPackets = value; } } /// <value> /// Number of packets dropped /// </value> private int droppedPackets; public int DroppedPackets { get { return droppedPackets; } set { droppedPackets = value; } } /// <value> /// Number of interface dropped packets /// </value> private int interfaceDroppedPackets; public int InterfaceDroppedPackets { get { return interfaceDroppedPackets; } set { interfaceDroppedPackets = value; } } /// <summary> /// Retrieve pcap statistics from the adapter /// </summary> /// <param name="pcap_t"> /// pcap_t* for the adapter /// A <see cref="IntPtr"/> /// </param> internal PcapStatistics(IntPtr pcap_t) { IntPtr stat; if (Environment.OSVersion.Platform == PlatformID.Unix) { // allocate memory for the struct stat = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.pcap_stat_unix))); } else { // allocate memory for the struct stat = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PcapUnmanagedStructures.pcap_stat_windows))); } // retrieve the stats PcapUnmanagedStructures.PcapStatReturnValue result = (PcapUnmanagedStructures.PcapStatReturnValue)SafeNativeMethods.pcap_stats(pcap_t, stat); // process the return value switch (result) { case PcapUnmanagedStructures.PcapStatReturnValue.Error: // retrieve the error information string error = PcapDevice.GetLastError(pcap_t); // free the stats memory so we don't leak before we throw Marshal.FreeHGlobal(stat); throw new PcapStatisticsException(error); case PcapUnmanagedStructures.PcapStatReturnValue.Success: // nothing to do upon success break; } // marshal the unmanaged memory into an object of the proper type if (Environment.OSVersion.Platform == PlatformID.Unix) { PcapUnmanagedStructures.pcap_stat_unix managedStat = (PcapUnmanagedStructures.pcap_stat_unix)Marshal.PtrToStructure(stat, typeof(PcapUnmanagedStructures.pcap_stat_unix)); // copy the values this.ReceivedPackets = (int)managedStat.ps_recv; this.DroppedPackets = (int)managedStat.ps_drop; // this.InterfaceDroppedPackets = (int)managedStat.ps_ifdrop; } else { PcapUnmanagedStructures.pcap_stat_windows managedStat = (PcapUnmanagedStructures.pcap_stat_windows)Marshal.PtrToStructure(stat, typeof(PcapUnmanagedStructures.pcap_stat_windows)); // copy the values this.ReceivedPackets = (int)managedStat.ps_recv; this.DroppedPackets = (int)managedStat.ps_drop; // this.InterfaceDroppedPackets = (int)managedStat.ps_ifdrop; } // NOTE: Not supported on unix or winpcap, no need to // put a bogus value in this field this.InterfaceDroppedPackets = 0; // free the stats Marshal.FreeHGlobal(stat); } public override string ToString() { return string.Format("[PcapStatistics: ReceivedPackets={0}, DroppedPackets={1}, InterfaceDroppedPackets={2}]", ReceivedPackets, DroppedPackets, InterfaceDroppedPackets); } } }
using System; namespace exe_5 { class Program { static void Main(string[] args) { Console.Clear(); System.Console.Write("Insira um valor para A: "); int A = int.Parse(Console.ReadLine()); System.Console.Write("Insira um valor para B: "); int B = int.Parse(Console.ReadLine()); System.Console.WriteLine("Os valores foram trocados!!!"); System.Console.WriteLine("Valor de A agora é: "+B); System.Console.WriteLine("E o valor de B agora é: "+A); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab3_4 { class Program { static void Main(string[] args) { List<Employee> employees = new List<Employee>() { //"Jakob", "Per", "Magnus", "Daniel", "Kurk", "Picard", "Spoc", "Sante" new Employee() {ID = 1, FirstName = "Jakob", LastName = "Persson", HireDate = DateTime.Today, Department = "School", Age = 21}, new Employee() {ID = 1, FirstName = "Per", LastName = "Santesson", HireDate = DateTime.Today, Department = "School", Age = 31}, new Employee() {ID = 1, FirstName = "Magnus", LastName = "Jakobsson", HireDate = DateTime.Today, Department = "School", Age = 24}, new Employee() {ID = 1, FirstName = "Daniel", LastName = "Kvist", HireDate = DateTime.Today, Department = "School", Age = 19}, new Employee() {ID = 1, FirstName = "Kurk", LastName = "Kurksson", HireDate = DateTime.Today, Department = "School", Age = 43}, new Employee() {ID = 1, FirstName = "Picard", LastName = "Magnusson", HireDate = DateTime.Today, Department = "School", Age = 38}, new Employee() {ID = 1, FirstName = "Spoc", LastName = "Free", HireDate = DateTime.Today, Department = "School", Age = 33}, new Employee() {ID = 1, FirstName = "Sante", LastName = "Karlsson", HireDate = DateTime.Today, Department = "School", Age = 34}, new Employee() {ID = 1, FirstName = "Ander", LastName = "Kvot", HireDate = DateTime.Today, Department = "School", Age = 41}, }; Console.WriteLine( @"1. List all names by First Name 2. List all names by Last name 3. List all names that contains an 'A' 4. List all names that starts with 'A' and does not contain an 'S' 5. Search by department 6. Search from keyword" ); switch (Console.ReadLine()) { case "1": var saveSlot1 = employees.OrderBy(e=> e.FirstName); foreach (var employee in saveSlot1) { Console.WriteLine(employee); } break; case "2": var saveSlot2 = employees.OrderBy(e => e.LastName); foreach (var employee in saveSlot2) { Console.WriteLine(employee); } break; case "3": var saveSlot3 = employees.Where(e => e.FirstName.Contains("a") || e.LastName.Contains("a")); foreach (var employee in saveSlot3) { Console.WriteLine(employee); } break; case "4": var saveSlot4 = employees.Where(e => e.FirstName.StartsWith("A") && !(e.FirstName.Contains("s") || e.LastName.Contains("s"))); foreach (var employee in saveSlot4) { Console.WriteLine(employee); } break; case "5": Console.WriteLine(@"1. School 2. Nothing"); string department = ""; switch (Console.ReadLine()) { case "1": department = "School"; break; case "2": department = "Nothing"; break; } var saveSlot5 = employees.Where(e => e.Department == department ); foreach (var employee in saveSlot5) { Console.WriteLine(employee); } break; case "6": Console.Write("Search: "); string searchInput = Console.ReadLine(); var saveSlot6 = employees.Where(e => e.FirstName.Contains(searchInput) || e.LastName.Contains(searchInput)); foreach (var employee in saveSlot6) { Console.WriteLine(employee); } break; default: break; } } } }
/* .-' '--./ / _.---. '-, (__..-` \ \ . | `,.__. ,__.--/ '._/_.'___.-` FREE WILLY */ using Automatisation.Model; using System; namespace Automatisation.Commands { public static class Spectrum { private static NLog.Logger Log = NLog.LogManager.GetCurrentClassLogger(); private static string _logTarget = Automatisation.Logging.TargetNames.SPECTRUM; #region Commands /* Channel */ /// <summary> /// [:SENSe]:FREQuency:CENTer(?) p455 /// </summary> public static string FREQ_CENTER = ":SENS:FREQ:CENT"; /// <summary> /// [:SENSe]:FREQuency:STARt(?) p461 /// </summary> public static string FREQ_START = ":SENS:FREQ:STAR"; /// <summary> /// [:SENSe]:FREQuency:STOP(?) p461 /// </summary> public static string FREQ_STOP = ":SENS:FREQ:STOP"; /// <summary> /// [:SENSe]:FREQuency:CHANnel(?) p458 /// </summary> public static string FREQ_CHAN = ":SENS:FREQ:CHAN"; /// <summary> /// [:SENSe]:FREQuency:CTABle:CATalog? (Query Only) p458 /// </summary> public static string FREQ_CHAN_TAB_CAT = ":SENS:FREQ:CTAB:CAT?"; /// <summary> /// [:SENSe]:FREQuency:CTABle[:SELect](?) p459 /// </summary> public static string FREQ_CHAN_TAB_SEL = ":SENS:FREQ:CTAB:SEL"; /// <summary> /// [:SENSe]:FREQuency:CENTer:STEP:AUTO(?) p456 /// </summary> public static string FREQ_STEP_AUTO = ":SENS:FREQ:CENT:STEP:AUTO"; /// <summary> /// [:SENSe]:FREQuency:CENTer:STEP:AUTO(?) p456 /// </summary> public static string FREQ_STEP_AUTO_ON = ":SENS:FREQ:CENT:STEP:AUTO ON"; /// <summary> /// [:SENSe]:FREQuency:CENTer:STEP:AUTO(?) p456 /// </summary> public static string FREQ_STEP_AUTO_OFF = ":SENS:FREQ:CENT:STEP:AUTO OFF"; /// <summary> /// [:SENSe]:FREQuency:CENTer:STEP[:INCRement](?) p457 /// Note: doesn't affect frontpanel /// </summary> public static string STEP_AUTO_INCR = ":SENS:FREQ:CENT:STEP:INCR"; /*Span*/ /// <summary> /// [:SENSe]:FREQuency:SPAN(?) p460 /// </summary> public static string SPAN = ":SENS:FREQ:SPAN"; /* Trigger */ /// <summary> /// :INITiate:CONTinuous (?) p328 /// Note: NOTE. When the analyzer receives a :FETCh command while operating in the continuous mode, it returns an execution error. /// If you want to run a :FETCh, use the :INITiate[:IMMediate] command. /// </summary> public static string INIT_CONT = ":INIT:CONT?"; public static string REPEAT_CONTINUOUS = ":INIT:CONT ON"; public static string REPEAT_SINGLE = ":INIT:CONT OFF"; public static string TRIGGER_MODE_AUTO = ":TRIG:SEQ:MODE AUTO"; public static string TRIGGER_MODE_NORM = ":TRIG:SEQ:MODE NORM"; /* amplitude */ /// <summary> /// :INPut:MLEVel (?) p336 /// </summary> public static string AMP_REF_LEVEL = ":INP:MLEV"; /// <summary> /// :INPut:ALEVel (No Query Form) p332 /// </summary> public static string AMP_AUTO_LEVEL = ":INP:ALEV"; /// <summary> /// :INPut:ATTenuation:AUTO (?) p333 /// </summary> public static string AMP_ATT_AUTO = ":INP:ATT:AUTO?"; /// <summary> /// :INPut:ATTenuation:AUTO (?) p333 /// </summary> public static string AMP_ATT_AUTO_ON = ":INP:ATT:AUTO ON"; /// <summary> /// :INPut:ATTenuation:AUTO (?) p333 /// </summary> public static string AMP_ATT_AUTO_OFF = ":INP:ATT:AUTO OFF"; /// <summary> /// :INPut:ATTenuation (?) p332 /// </summary> public static string AMP_RF_ATT_DB = ":INP:ATT"; /// <summary> /// :INPut:MIXer (?) p335 /// </summary> public static string AMP_MIX_LVL = ":INP:MIX"; /// <summary> /// :DISPlay:SPECtrum:Y[:SCALe]:PDIVision(?) p220 /// </summary> public static string AMP_VERT_SCALE = ":DISP:SPEC:Y:SCAL:PDIV"; /*RBW/FFT*/ /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth[:RESolution]:AUTO(?) p507 /// </summary> public static string RBW_AUTO = ":SENS:SPEC:BAND:RES:AUTO?"; /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth[:RESolution]:AUTO(?) p507 /// </summary> public static string RBW_AUTO_ON = ":SENS:SPEC:BAND:RES:AUTO ON"; /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth[:RESolution]:AUTO(?) p507 /// </summary> public static string RBW_AUTO_OFF = ":SENS:SPEC:BAND:RES:AUTO OFF"; /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe(?) p508 /// </summary> public static string RBW_STATE = ":SENS:SPEC:BAND:STAT?"; /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe(?) p508 /// </summary> public static string RBW_STATE_ON = ":SENS:SPEC:BAND:STAT ON"; /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe(?) p508 /// </summary> public static string RBW_STATE_OFF = ":SENS:SPEC:BAND:STAT OFF"; /// <summary> /// [:SENSe]:SPECtrum:BANDwidth|:BWIDth[:RESolution](?) p507 /// </summary> public static string RBW_MAN = ":SENS:SPEC:BAND:RES"; /// <summary> /// [:SENSe]:SPECtrum:FILTer:TYPE(?) p512 /// </summary> public static string RBW_FILTER = ":SENS:SPEC:FILT:TYPE"; //{ RECTangle | GAUSsian | NYQuist | RNYQuist } /// <summary> /// [:SENSe]:SPECtrum:FFT:LENGth(?) p514 /// </summary> public static string FFT_POINTS = ":SENS:SPEC:FFT:LENG"; /// <summary> /// [:SENSe]:SPECtrum:FFT:WINDow[:TYPE](?) p515 /// </summary> public static string FFT_WINDOW_TYPE = ":SENS:SPEC:FFT:WIND:TYPE"; /// <summary> /// [:SENSe]:SPECtrum:FFT:ERESolution(?) p513 /// </summary> public static string FFT_EXTENDED = ":SENS:SPEC:FFT:ERES?"; /// <summary> /// [:SENSe]:SPECtrum:FFT:ERESolution(?) p513 /// </summary> public static string FFT_EXTENDED_ON = ":SENS:SPEC:FFT:ERES ON"; /// <summary> /// [:SENSe]:SPECtrum:FFT:ERESolution(?) p513 /// </summary> public static string FFT_EXTENDED_OFF = ":SENS:SPEC:FFT:ERES OFF"; /* TRACE */ /// <summary> /// :TRACe<x>|:DATA<x>:MODE (?) p574 /// </summary> public static string TRACE_1_MODE = ":TRAC1:MODE"; //MODE { NORMal | AVERage | MAXHold | MINHold | FREeze | OFF } /// <summary> /// :TRACe<x>|:DATA<x>:MODE (?) p574 /// </summary> public static string TRACE_2_MODE = ":TRAC2:MODE"; //MODE { NORMal | AVERage | MAXHold | MINHold | FREeze | OFF } /// <summary> /// :TRACe<x>|:DATA<x>:AVERage:COUNt (?) p572 /// </summary> public static string TRACE_1_COUNT = "TRAC1:AVER:COUN"; //enkel in AVER, MAXH, MINH /// <summary> /// :TRACe<x>|:DATA<x>:AVERage:COUNt (?) p572 /// </summary> public static string TRACE_2_COUNT = "TRAC2:AVER:COUN"; //enkel in AVER, MAXH, MINH /// <summary> /// :TRACe<x>|:DATA<x>:AVERage:CLEar (No Query Form) p572 /// </summary> public static string TRACE_1_CLEAR = "TRAC1:AVER:CLE"; //enkel in AVER, MAXH, MINH /// <summary> /// :TRACe<x>|:DATA<x>:AVERage:CLEar (No Query Form) p572 /// </summary> public static string TRACE_2_CLEAR = "TRAC2:AVER:CLE"; //enkel in AVER, MAXH, MINH //[:SENSe]:SPECtrum:AVERage:TYPE(?) //[:SENSe]:SPECtrum:AVERage[:STATe](?) //[:SENSe]:SPECtrum:AVERage:COUNt(?) //[:SENSe]:SPECtrum:AVERage:CLEar(NoQueryForm) /*Meas*/ /// <summary> /// [:SENSe]:SPECtrum:MEASurement(?) p517 /// </summary> public static string MEAS = ":SENS:SPEC:MEAS"; /*Meas Setup*/ /* CHP */ /// <summary> /// [:SENSe]:CHPower:FILTer:COEFficient(?) p420 /// </summary> public static string CHP_ROLLOFF = ":SENS:CHP:FILT:COEF"; /// <summary> /// [:SENSe]:CHPower:FILTer:TYPE(?) p512 /// </summary> public static string CHP_FILTER_TYPE = ":SENS:CHP:FILT:TYPE"; //{ RECTangle | GAUSsian | NYQuist | RNYQuist } /// <summary> /// [:SENSe]:CHPower:BANDwidth|:BWIDth:INTegration(?) p419 /// </summary> public static string CHP_BANDWIDTH = ":SENS:CHP:BAND:INT"; /* Other */ /// <summary> /// :INSTrument[:SELect] (?) p339 /// </summary> public static string INSTRUMENT_SELECT = ":INST:SEL"; /// <summary> /// :READ:SPECtrum? (Query Only) p384 /// </summary> public static string READ_SPECTRUM = ":READ:SPEC?"; /// <summary> /// :READ:SPECtrum:CHPower? (Query Only) p386 /// </summary> public static string READ_SPECTRUM_CHP = ":READ:SPEC:CHP?"; /// <summary> /// :FETCh:SPECtrum? (Query Only) p303 /// </summary> public static string FETCH_SPECTRUM = ":FETC:SPEC?"; /// <summary> /// :FETCh:SPECtrum:CHPower? (Query Only) p305 /// </summary> public static string FETCH_SPECTRUM_CHP = "FETC:SPEC:CHP?"; #endregion Commands /* FREQUENCY */ #region FREQ_CENTER /// <summary> /// Sets or queries the center frequency. /// </summary> /// <param name="s"></param> /// <returns></returns> public static string GetFreqCenter(SpectrumMeterModel s) { string res = string.Empty; try { res = s.WriteCommandRes(FREQ_CENTER + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FREQ_CENTER: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the center frequency. /// </summary> /// <param name="s"></param> /// <param name="par"><freq>::=<NRf> specifies the center frequency. For the setting range</param> public static void SetFreqCenter(SpectrumMeterModel s, string par) { try { s.WriteCommand(FREQ_CENTER + " " + par + "hz"); } catch (Exception e) { Log.Error(_logTarget + "Set FREQ_CENTER: " + e.ToString(), e); } } #endregion FREQ_CENTER #region FREQ_START /// <summary> /// Sets or queries the start frequency. /// </summary> /// <param name="s"></param> /// <returns>Specifies the start frequency. For the setting range, refer to Table 2--52 on page 2--428.</returns> public static string GetFreqStart(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FREQ_START + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FQ_Center: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the start frequency. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the start frequency. For the setting range, refer to Table 2--52 on page 2--428.</param> public static void SetFreqStart(SpectrumMeterModel s, string par) { s.WriteCommand(FREQ_START + " " + par + "hz"); } #endregion FREQ_START #region FREQ_STOP /// <summary> /// Sets or queries the start frequency. /// </summary> /// <param name="s"></param> /// <returns>Specifies the stop frequency. For the setting range, refer to Table 2--52 on page 2--428</returns> public static string GetFreqStop(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FREQ_STOP + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FREQ_STOP: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the start frequency. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the stop frequency. For the setting range, refer to Table 2--52 on page 2--428</param> public static void SetFreqStop(SpectrumMeterModel s, string par) { s.WriteCommand(FREQ_STOP + " " + par + "hz"); } #endregion FREQ_STOP /* CHANNELS */ #region ChannelFrequency /// <summary> /// Sets or queries a channel number in the channel table specified with the [:SENSe]:FREQuency:CTABle[:SELect] command. /// </summary> /// <param name="s"></param> /// <returns>specifies a channel number in the channel table.</returns> public static string GetFreqChan(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FREQ_CHAN + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FREQ_CHAN: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries a channel number in the channel table specified with the [:SENSe]:FREQuency:CTABle[:SELect] command. /// </summary> /// <param name="s"></param> /// <param name="par">specifies a channel number in the channel table.</param> public static void SetFreqChan(SpectrumMeterModel s, string par) { s.WriteCommand(FREQ_CHAN + " " + par); } #endregion ChannelFrequency #region ChannelTable /// <summary> /// Queries the available channel tables. QUERY ONLY! /// </summary> /// <param name="s"></param> /// <returns>the available channel table name(s). /// If more than one table is available, the table names are separated with comma</returns> public static string GetFreqChanCatAll(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FREQ_CHAN_TAB_CAT); } catch (Exception e) { Log.Error(_logTarget + "Get FREQ_CHAN_TAB_CAT: " + e.ToString(), e); } return res; } /// <summary> /// Selects the channel table. The query command returns the selected channel table. /// </summary> /// <param name="s"></param> /// <returns>specifies a channel table. /// The table name is represented with the communication standard name followed by “-FL” (forward link), “-RL” (reverse link), “-UL” (uplink), or “-DL” (downlink).</returns> public static string GetFreqChanCatSelected(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FREQ_CHAN_TAB_SEL + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FREQ_CHAN_TAB_SEL: " + e.ToString(), e); } return res; } /// <summary> /// Selects the channel table. The query command returns the selected channel table. /// </summary> /// <param name="s"></param> /// <param name="par">specifies a channel table. /// The table name is represented with the communication standard name followed by “-FL” (forward link), “-RL” (reverse link), “-UL” (uplink), or “-DL” (downlink).</param> public static void SetFreqChanCat(SpectrumMeterModel s, string par) { s.WriteCommand(FREQ_CHAN_TAB_SEL + " " + par); } #endregion ChannelTable #region FrequencyAutoStep /// <summary> /// Determines whether to automatically set the step size (amount per click by which the up and down keys change a setting value) of the center frequency by the span setting. /// </summary> /// <param name="s"></param> /// <returns>OFF or 0 specifies that the step size of the center frequency is not set automatically. /// To set it, use the [:SENSe]:FREQuency:CENTer:STEP[:INCRement] command. /// ON or 1 specifies that the step size of the center frequency is set automatically by the span.</returns> public static string GetFreqCenterStepAuto(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FREQ_STEP_AUTO + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FREQ_STEP_AUTO: " + e.ToString(), e); } return res; } /// <summary> /// Determines whether to automatically set the step size (amount per click by which the up and down keys change a setting value) of the center frequency by the span setting. /// OFF or 0 specifies that the step size of the center frequency is not set automatically. /// To set it, use the [:SENSe]:FREQuency:CENTer:STEP[:INCRement] command. /// ON or 1 specifies that the step size of the center frequency is set automatically by the span. /// </summary> /// <param name="s"></param> public static void SetFreqCenterStepAutoOn(SpectrumMeterModel s) { s.WriteCommand(FREQ_STEP_AUTO_ON); } /// <summary> /// Determines whether to automatically set the step size (amount per click by which the up and down keys change a setting value) of the center frequency by the span setting. /// OFF or 0 specifies that the step size of the center frequency is not set automatically. /// To set it, use the [:SENSe]:FREQuency:CENTer:STEP[:INCRement] command. /// ON or 1 specifies that the step size of the center frequency is set automatically by the span. /// </summary> /// <param name="s"></param> public static void SetFreqCenterStepAutoOff(SpectrumMeterModel s) { s.WriteCommand(FREQ_STEP_AUTO_OFF); } #endregion FrequencyAutoStep #region FrequencyStep /// <summary> /// Sets or queries the step size (amount per click by which the up and down keys change a setting value) of the center frequency when [:SENSe]:FREQuency:CENTer:STEP:AUTO is OFF. /// Note: doesn't affect frontpanel /// </summary> /// <param name="s"></param> /// <returns>the step size of the center frequency</returns> public static string GetFreqCenterStepAutoIncr(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(STEP_AUTO_INCR + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get STEP_AUTO_INCR: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the step size (amount per click by which the up and down keys change a setting value) of the center frequency when [:SENSe]:FREQuency:CENTer:STEP:AUTO is OFF. /// Note: doesn't affect frontpanel /// </summary> /// <param name="s"></param> /// <param name="par">the step size of the center frequency</param> public static void SetFreqCenterStepAutoIncr(SpectrumMeterModel s, string par) { s.WriteCommand(STEP_AUTO_INCR + " " + par); } #endregion FrequencyStep /* SPAN */ #region SpanFrequency /// <summary> /// Sets or queries the span. /// </summary> /// <param name="s"></param> /// <returns>specifies the span. The valid range depends on the measurement mode as listed in Table 2--53</returns> public static string GetFreqSpan(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(SPAN + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get SPAN: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the span. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the span. The valid range depends on the measurement mode as listed in Table 2--53</param> public static void SetFreqSpan(SpectrumMeterModel s, string par) { s.WriteCommand(SPAN + " " + par + "hz"); } #endregion SpanFrequency //missing start & stop span frequency - same as freq_start en stop from frequency /* TRIGGER */ #region init|repeat continuous / single /// <summary> /// Determines whether to use the continuous mode to acquire the input signal /// OFF or 0 specifies that the single mode, rather than the continuous mode, is used for data acquisition. To initiate the acquisition, use the :INITiate[:IMMediate] /// To stop the acquisition because the trigger is not generated in single mode, send the following command: :INITiate:CONTinuous OFF /// ON or 1 initiates data acquisition in the continuous mode. /// To stop the acquisition in the continuous mode, send the following command::INITiate:CONTinuous OFF /// NOTE. When the analyzer receives a :FETCh command while operating in the continuous mode, it returns an execution error. If you want to run a :FETCh, use the :INITiate[:IMMediate] command. /// </summary> /// <param name="s"></param> /// <returns>OFF or 0 = single mode, ON or 1 = continuous mode</returns> public static string GetInitCont(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(INIT_CONT + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get INIT_CONT: " + e.ToString(), e); } return res; } /// <summary> /// Determines whether to use the continuous mode to acquire the input signal /// OFF or 0 specifies that the single mode, rather than the continuous mode, is used for data acquisition. To initiate the acquisition, use the :INITiate[:IMMediate] /// To stop the acquisition because the trigger is not generated in single mode, send the following command: :INITiate:CONTinuous OFF /// ON or 1 initiates data acquisition in the continuous mode. /// To stop the acquisition in the continuous mode, send the following command::INITiate:CONTinuous OFF /// NOTE: When the analyzer receives a :FETCh command while operating in the continuous mode, it returns an execution error. /// If you want to run a :FETCh, use the :INITiate[:IMMediate] command. /// </summary> /// <param name="s"></param> public static void SetInitContOn(SpectrumMeterModel s) { s.WriteCommand(REPEAT_CONTINUOUS); } /// <summary> /// Determines whether to use the continuous mode to acquire the input signal /// OFF or 0 specifies that the single mode, rather than the continuous mode, is used for data acquisition. To initiate the acquisition, use the :INITiate[:IMMediate] /// To stop the acquisition because the trigger is not generated in single mode, send the following command: :INITiate:CONTinuous OFF /// ON or 1 initiates data acquisition in the continuous mode. /// To stop the acquisition in the continuous mode, send the following command::INITiate:CONTinuous OFF /// </summary> /// <param name="s"></param> public static void SetInitContOff(SpectrumMeterModel s) { s.WriteCommand(REPEAT_SINGLE); } #endregion init|repeat continuous / single #region TriggerMode #endregion TriggerMode /* AMPLITUDE */ #region AmplitudeReferenceLevel /// <summary> /// Sets or queries the reference level. Using this command to set the reference level is equivalent to pressing the AMPLITUDE key and then the Ref Level side key on the front panel. /// </summary> /// <param name="s"></param> /// <returns>specifies the reference level. The valid settings depend on the measurement frequency band as shown in Table 2--43</returns> public static string GetAmplRefLvl(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(AMP_REF_LEVEL + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get AMP_REF_LEVEL: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the reference level. Using this command to set the reference level is equivalent to pressing the AMPLITUDE key and then the Ref Level side key on the front panel. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the reference level. The valid settings depend on the measurement frequency band as shown in Table 2--43</param> public static void SetAmplRefLvl(SpectrumMeterModel s, string par) { s.WriteCommand(AMP_REF_LEVEL + " " + par); } #endregion AmplitudeReferenceLevel #region AmplitudeAutoLevel /// <summary> /// Adjusts amplitude automatically for the best system performance using the input signal as a guide. /// </summary> /// <param name="s"></param> public static void SetAmplAutoLvl(SpectrumMeterModel s) { s.WriteCommand(AMP_REF_LEVEL); } #endregion AmplitudeAutoLevel #region Amplitude Auto|RF|Mixer #region AmplitudeAttenuationAuto /// <summary> /// Determines whether to automatically set the input attenuation according to the reference level /// </summary> /// <param name="s"></param> /// <returns>OFF or 0 specifies that the input attenuation is not set automatically. To set it, use the :INPut:ATTenuation command. ON or 1 specifies that the input attenuation is set automatically.</returns> public static string GetAmplAutoAtt(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(AMP_ATT_AUTO); } catch (Exception e) { Log.Error(_logTarget + "Get AMP_ATT_AUTO: " + e.ToString(), e); } return res; } /// <summary> /// Determines whether to automatically set the input attenuation according to the reference level /// ON or 1 specifies that the input attenuation is set automatically. /// </summary> /// <param name="s"></param> public static void SetAmplAutoAttOn(SpectrumMeterModel s) { s.WriteCommand(AMP_ATT_AUTO_ON); } /// <summary> /// Determines whether to automatically set the input attenuation according to the reference level /// OFF or 0 specifies that the input attenuation is not set automatically. To set it, use the :INPut:ATTenuation command. /// </summary> /// <param name="s"></param> public static void SetAmplAutoAttOff(SpectrumMeterModel s) { s.WriteCommand(AMP_ATT_AUTO_OFF); } #endregion AmplitudeAttenuationAuto #region AmplitudeReferenceAttenuation /// <summary> /// When you have selected OFF or 0 in the :INPut:ATTenuation:AUTO command, use this command to set the input attenuation. The query version of this command returns the input attenuation setting. /// </summary> /// <param name="s"></param> /// <returns>specifies the input attenuation. The valid settings depend on the measurement frequency band as shown in Table 2--41.</returns> public static string GetAmplRefAtt(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(AMP_RF_ATT_DB + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get AMP_RF_ATT_DB: " + e.ToString(), e); } return res; } /// <summary> /// When you have selected OFF or 0 in the :INPut:ATTenuation:AUTO command, use this command to set the input attenuation. The query version of this command returns the input attenuation setting. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the input attenuation. The valid settings depend on the measurement frequency band as shown in Table 2--41.</param> public static void SetAmplRefAtt(SpectrumMeterModel s, string par) { s.WriteCommand(AMP_RF_ATT_DB + " " + par); } #endregion AmplitudeReferenceAttenuation #region AmplitudeMixerLevel /// <summary> /// Selects or queries the mixer level. /// NOTE. To set the mixer level, you must have selected On in the :INPut:ATTenuation:AUTO command. /// </summary> /// <param name="s"></param> /// <returns>specifies the mixer level. The valid settings depend on the measurement frequency band as shown in Table 2--42.</returns> public static string GetAmpMixerLvl(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(AMP_MIX_LVL + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get AMP_MIX_LVL: " + e.ToString(), e); } return res; } /// <summary> /// Selects or queries the mixer level. /// To set the mixer level, you must have selected On in the :INPut:ATTenuation:AUTO command. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the mixer level. The valid settings depend on the measurement frequency band as shown in Table 2--42.</param> public static void SetAmpMixerLvl(SpectrumMeterModel s, string par) { s.WriteCommand(AMP_MIX_LVL + " " + par); } #endregion AmplitudeMixerLevel #endregion Amplitude Auto|RF|Mixer #region AmplitudeVerticalScale /// <summary> /// Sets or queries the vertical, or amplitude, scale (per division) in the spectrum view. /// </summary> /// <param name="s"></param> /// <returns>specifies the horizontal scale in the spectrum view. Range: 0 to 10 dB/div.</returns> public static string GetAmpVertScale(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(AMP_VERT_SCALE + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get AMP_VERT_SCALE: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the vertical, or amplitude, scale (per division) in the spectrum view. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the horizontal scale in the spectrum view. Range: 0 to 10 dB/div.</param> public static void SetAmpVertScale(SpectrumMeterModel s, string par) { s.WriteCommand(AMP_VERT_SCALE + " " + par); } #endregion AmplitudeVerticalScale /* RBW / FFT */ #region RBWAuto /// <summary> /// Determines whether to automatically set the resolution bandwidth (RBW) by the span setting. /// </summary> /// <param name="s"></param> /// <returns>OFF or 0 specifies that the RBW is not set automatically. /// To set it, use the [:SENSe]:SPECtrum:BANDwidth|:BWIDth[:RESolution] command. /// ON or 1 specifies that the RBW is set automatically.</returns> public static string GetRBWAuto(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(RBW_AUTO); } catch (Exception e) { Log.Error(_logTarget + "Get RBW_AUTO: " + e.ToString(), e); } return res; } /// <summary> /// Determines whether to automatically set the resolution bandwidth (RBW) by the span setting. /// ON or 1 specifies that the RBW is set automatically. /// </summary> /// <param name="s"></param> public static void SetRBWAutoOn(SpectrumMeterModel s) { s.WriteCommand(RBW_AUTO_ON); } /// <summary> /// Determines whether to automatically set the resolution bandwidth (RBW) by the span setting. /// OFF or 0 specifies that the RBW is not set automatically. To set it, use the [:SENSe]:SPECtrum:BANDwidth|:BWIDth[:RESolution] command /// </summary> /// <param name="s"></param> public static void SetRBWAutoOff(SpectrumMeterModel s) { s.WriteCommand(RBW_AUTO_OFF); } #endregion RBWAuto #region SpectrumBandStateForFFT /// <summary> /// Determines whether to perform the resolution bandwidth (RBW) process /// </summary> /// <param name="s"></param> /// <returns>OFF or 0 specifies that the RBW process is not performed so that a spectrum immediately after the FFT process is displayed on screen. /// ON or 1 specifies that the RBW process is performed.</returns> public static string GetRBWState(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(RBW_STATE); } catch (Exception e) { Log.Error(_logTarget + "Get RBW_STATE: " + e.ToString(), e); } return res; } /// <summary> /// Determines whether to perform the resolution bandwidth (RBW) process /// ON or 1 specifies that the RBW process is performed. /// </summary> /// <param name="s"></param> public static void SetRBWStateOn(SpectrumMeterModel s) { s.WriteCommand(RBW_STATE_ON); } /// <summary> /// Determines whether to perform the resolution bandwidth (RBW) process /// OFF or 0 specifies that the RBW process is not performed so that a spectrum immediately after the FFT process is displayed on screen. /// </summary> /// <param name="s"></param> public static void SetRBWStateOff(SpectrumMeterModel s) { s.WriteCommand(RBW_STATE_OFF); } #endregion SpectrumBandStateForFFT #region RBWMan /// <summary> /// Sets or queries the resolution bandwidth (RBW) when [:SENSe]:SPECtrum: BANDwidth|:BWIDth[:RESolution]:AUTO is set to Off. /// </summary> /// <param name="s"></param> /// <returns>specifies the RBW. For the setting range, refer to Table D--4 in Appendix D.</returns> public static string GetRBWMan(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(RBW_MAN + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get RBW_MAN: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the resolution bandwidth (RBW) when [:SENSe]:SPECtrum: BANDwidth|:BWIDth[:RESolution]:AUTO is set to Off. /// </summary> /// <param name="s"></param> /// <param name="par">specifies the RBW. For the setting range, refer to Table D--4 in Appendix D.</param> public static void SetRBWMan(SpectrumMeterModel s, string par) { s.WriteCommand(RBW_MAN + " " + par + "Hz"); } #endregion RBWMan #region RbwFilter /// <summary> /// Selects or queries the RBW filter. /// </summary> /// <param name="s"></param> /// <returns>RECTangle selects the rectangular filter. /// GAUSsian selects the Gaussian filter. /// NYQuist selects the Nyquist filter (default). /// RNYQuist selects the Root Nyquist filter.</returns> public static string GetRBWFilter(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(RBW_FILTER + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get RBW_FILTER: " + e.ToString(), e); } return res; } /// <summary> /// Selects or queries the RBW filter. /// </summary> /// <param name="s"></param> /// <param name="par">RECTangle selects the rectangular filter. /// GAUSsian selects the Gaussian filter. /// NYQuist selects the Nyquist filter (default). /// RNYQuist selects the Root Nyquist filter.</param> public static void SetRBWFilter(SpectrumMeterModel s, string par) { s.WriteCommand(RBW_FILTER + " " + par); } #endregion RbwFilter #region FFTPoints /// <summary> /// Sets or queries the number of FFT points. This command is valid when [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe is OFF. /// </summary> /// <param name="s"></param> /// <returns>sets the number of FFT points. Range: 64 to 65536 in powers of 2.</returns> public static string GetFFTPoints(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FFT_POINTS + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FFT_POINTS: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the number of FFT points. This command is valid when [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe is OFF. /// </summary> /// <param name="s"></param> /// <param name="par">sets the number of FFT points. Range: 64 to 65536 in powers of 2.</param> public static void SetFFTPoints(SpectrumMeterModel s, string par) { s.WriteCommand(FFT_POINTS + " " + par); } #endregion FFTPoints #region FFTWindowType //{ BH3A | BH3B | BH4A | BH4B | BLACkman | HAMMing | HANNing | PARZen | ROSenfield | WELCh | SLOBe | SCUBed | ST4T | FLATtop | RECT } /// <summary> /// Selects or queries the FFT window function. This command is valid when [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe is OFF. /// </summary> /// <param name="s"></param> /// <returns>{ BH3A | BH3B | BH4A | BH4B | BLACkman | HAMMing | HANNing | PARZen | ROSenfield | WELCh | SLOBe | SCUBed | ST4T | FLATtop | RECT }</returns> public static string GetFFTWindowType(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FFT_WINDOW_TYPE + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get FFT_WINDOW_TYPE: " + e.ToString(), e); } return res; } /// <summary> /// Selects or queries the FFT window function. This command is valid when [:SENSe]:SPECtrum:BANDwidth|:BWIDth:STATe is OFF. /// </summary> /// <param name="s"></param> /// <param name="par">{ BH3A | BH3B | BH4A | BH4B | BLACkman | HAMMing | HANNing | PARZen | ROSenfield | WELCh | SLOBe | SCUBed | ST4T | FLATtop | RECT }</param> public static void SetFFTWindowType(SpectrumMeterModel s, string par) { s.WriteCommand(FFT_WINDOW_TYPE + " " + par); } #endregion FFTWindowType #region RBWFFTExtended /// <summary> /// Determines whether to enable the extended resolution that eliminates the limit on the number of FFT points (it is normally limited internally). /// ON or 1 allows you to set the number of FFT points up to 65536. Use the [:SENSe]:SPECtrum:FFT:LENGth command to set the number. /// OFF or 0 disables the extended resolution. The number of FFT points is limited internally. /// </summary> /// <param name="s"></param> /// <returns></returns> public static string GetExtended(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FFT_EXTENDED); } catch (Exception e) { Log.Error(_logTarget + "Get FFT_EXTENDED: " + e.ToString(), e); } return res; } /// <summary> /// Determines whether to enable the extended resolution that eliminates the limit on the number of FFT points (it is normally limited internally). /// ON or 1 allows you to set the number of FFT points up to 65536. Use the [:SENSe]:SPECtrum:FFT:LENGth command to set the number. /// </summary> /// <param name="s"></param> public static void SetExtendedOn(SpectrumMeterModel s) { s.WriteCommand(FFT_EXTENDED_ON); } /// <summary> /// Determines whether to enable the extended resolution that eliminates the limit on the number of FFT points (it is normally limited internally). /// OFF or 0 disables the extended resolution. The number of FFT points is limited internally. /// </summary> /// <param name="s"></param> public static void SetExtendedOff(SpectrumMeterModel s) { s.WriteCommand(FFT_EXTENDED_OFF); } #endregion RBWFFTExtended /* trace */ /*Measurement */ #region MEAS /// <summary> /// Selects and runs the measurement item in the S/A (spectrum analysis) mode. The query version of this command returns the current measurement item. /// </summary> /// <param name="s"></param> /// <returns></returns> public static string GetMeas(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(MEAS + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get MEAS: " + e.ToString(), e); } return res; } /// <summary> /// Selects and runs the measurement item in the S/A (spectrum analysis) mode. Thequery version of this command returns the current measurement item. /// </summary> /// <param name="s"></param> /// <param name="par"></param> public static void SetMeas(SpectrumMeterModel s, string par) { s.WriteCommand(MEAS + " " + par); } #endregion MEAS /* Meas Setup */ #region CHANNELPOWERBANDWIDTH /// <summary> /// Sets or queries the channel bandwidth for the channel power measurement (seeFigure 2--18). /// </summary> /// <param name="s"></param> /// <returns>specifies the channel bandwidth for the channel power measurement. Range: (Bin bandwidth)×8 to full span [Hz]</returns> public static string GetChannelBand(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(CHP_BANDWIDTH + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get CHP_BANDWIDTH: " + e.ToString(), e); } return res; } /// <summary> /// Sets or queries the channel bandwidth for the channel power measurement (seeFigure 2--18). /// </summary> /// <param name="s"></param> /// <param name="par">specifies the channel bandwidth for the channel power measurement. Range: (Bin bandwidth)×8 to full span [Hz]</param> public static void SetChannelBand(SpectrumMeterModel s, string par) { s.WriteCommand(CHP_BANDWIDTH + " " + par + "hz"); } #endregion CHANNELPOWERBANDWIDTH #region CHANNELPOWERFILTER /// <summary> /// Selects or queries the filter for the channel power measurement /// </summary> /// <param name="s"></param> /// <returns>RECTangle selects the rectangular filter. /// GAUSsian selects the Gaussian filter. /// NYQuist selects the Nyquist filter (default). /// RNYQuist selects the Root Nyquist filter.</returns> public static string GetCHPFilterType(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(CHP_FILTER_TYPE + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get CHP_FILTER_TYPE: " + e.ToString(), e); } return res; } /// <summary> /// Selects or queries the filter for the channel power measurement /// </summary> /// <param name="s"></param> /// <param name="par">RECTangle selects the rectangular filter. /// GAUSsian selects the Gaussian filter. /// NYQuist selects the Nyquist filter (default). /// RNYQuist selects the Root Nyquist filter.</param> public static void SetCHPFilterType(SpectrumMeterModel s, string par) { s.WriteCommand(CHP_FILTER_TYPE + " " + par); } #endregion RbwFilter #region CHANNELPOWERROLLOFF /// <summary> /// Selects or queries the filter for the channel power measurement /// Sets or queries the roll-off rate of the filter for the channel power measurement when you have selected either NYQuist (Nyquist filter) or RNYQuist (Root Nyquist filter) in the [:SENSe]:CHPower:FILTer:TYPE command /// </summary> /// <param name="s"></param> /// <returns>Range: 0.0001 to 1</returns> public static string GetCHPRollOff(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(CHP_ROLLOFF + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get CHP_ROLLOFF: " + e.ToString(), e); } return res; } /// <summary> /// Selects or queries the filter for the channel power measurement /// Sets or queries the roll-off rate of the filter for the channel power measurement when you have selected either NYQuist (Nyquist filter) or RNYQuist (Root Nyquist filter) in the [:SENSe]:CHPower:FILTer:TYPE command /// </summary> /// <param name="s"></param> /// <param name="par">Range: 0.0001 to 1</param> public static void SetCHPRollOff(SpectrumMeterModel s, string par) { s.WriteCommand(CHP_ROLLOFF + " " + par); } #endregion CHANNELPOWERROLLOFF #region other /* The :FETCh commands retrieve the measurements from the data taken by the latest INITiate command. If you want to perform a FETCh operation on fresh data, use the :READ commands, which acquire a new input signal and fetch the measurement results from that data. */ /* Other */ #region INSTRUMENTSELECT /// <summary> /// Selects or queries the measurement mode /// NOTE. If you want to change the measurement mode, stop the data acquisition with the :INITiate:CONTinuous OFF command. /// </summary> /// <param name="s"></param> /// <returns></returns> public static string GetInstrumentSelect(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(INSTRUMENT_SELECT + "?"); } catch (Exception e) { Log.Error(_logTarget + "Get INSTRUMENT_SELECT: " + e.ToString(), e); } return res; } /// <summary> /// Selects or queries the measurement mode /// NOTE. If you want to change the measurement mode, stop the data acquisition with the :INITiate:CONTinuous OFF command. /// </summary> /// <param name="s"></param> /// <param name="par">measurement mode</param> public static void SetInstrumentSelect(SpectrumMeterModel s, string par) { s.WriteCommand(INSTRUMENT_SELECT + " " + par); } #endregion INSTRUMENTSELECT /// <summary> /// Obtains spectrum waveform data in the S/A (spectrum analysis) mode. /// </summary> /// <param name="s"></param> /// <returns>#Num_digit Num_byte Data(1)Data(2)...Data(n) /// Where /// Num_digit is the number of digits in <Num_byte>. /// Num_byte is the number of bytes of the data that follow. /// Data(n) is the amplitude spectrum in dBm. /// 4-byte little endian floating-point format specified in IEEE 488.2 /// n: Max 240001</returns> public static string ReadSpectrum(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(READ_SPECTRUM); } catch (Exception e) { Log.Error(_logTarget + "Get READ_SPECTRUM: " + e.ToString(), e); } return res; } /// <summary> /// Obtains the results of the carrier frequency measurement in the S/A mode. /// </summary> /// <param name="s"></param> /// <returns><cfreq>::=<NRf> is the measured value of the carrier frequency in Hz.</returns> public static string ReadSpectrumCHP(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(READ_SPECTRUM_CHP); } catch (Exception e) { Log.Error(_logTarget + "Get READ_SPECTRUM_CHP: " + e.ToString(), e); } return res; } /// <summary> /// Returns spectrum waveform data in the S/A (spectrum analysis) mode. /// </summary> /// <param name="s"></param> /// <returns>#Num_digit Num_byte Data(1)Data(2)...Data(n) /// Where /// Num_digit is the number of digits in <Num_byte>. /// Num_byte is the number of bytes of the data that follow. /// Data(n) is the amplitude spectrum in dBm. /// 4-byte little endian floating-point format specified in IEEE 488.2 /// n: Max 240001</returns> public static string FetchSpectrum(SpectrumMeterModel s) { string res = String.Empty; try { s.WriteCommand(FETCH_SPECTRUM); } catch (Exception e) { Log.Error(_logTarget + "Get FETCH_SPECTRUM: " + e.ToString(), e); } return res; } /// <summary> /// Returns the results of the channel power measurement in the S/A (spectrum analysis) mode. /// </summary> /// <param name="s"></param> /// <returns><chpower>::=<NRf> is the channel power measured value in dBm.</returns> public static string FetchSpectrumCHP(SpectrumMeterModel s) { string res = String.Empty; try { res = s.WriteCommandRes(FETCH_SPECTRUM_CHP); } catch (Exception e) { Log.Error(_logTarget + "Get FETCH_SPECTRUM_CHP: " + e.ToString(), e); } return res; } #endregion other } }
using System; using System.Collections.Generic; using System.IO; using SalaryUpdate.Models; using SalaryUpdate.Persistance; using SalaryUpdate.Properties; namespace SalaryUpdate.Services { public class ExportService : IDisposable { private readonly DataAccess _data; public ExportService(DataAccess data) { _data = data; } public bool Export() { var recordsToUpdate = _data.GetExportDataForSalaryUpdate(); if (recordsToUpdate.Count == 0) throw new Exception("No data to Export"); var path = Settings.Default.ExportFilePath; SaveBackUpFile(path); return WriteRecordsToFile(recordsToUpdate, path); } private static void SaveBackUpFile(string path) { if (!File.Exists(path)) return; var newPath = path + "_" + DateTime.Now.ToString("yyyyMMdd"); if (File.Exists(newPath)) File.Delete(newPath); using (var sw = new StreamWriter(File.OpenWrite(newPath))) { using (var sr = new StreamReader(File.OpenRead(path))) { sw.Write(sr.ReadToEnd()); // read from old file and write to new file } } } private bool WriteRecordsToFile(IEnumerable<ReturnedSalary> records, string path) { if (File.Exists(path)) File.Delete(path); bool success; using (var streamWriter = new StreamWriter(new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))) { var employeesToUpdate = new List<string>(); foreach (var returnedSalary in records) { var output = returnedSalary.EmployeeId + "," + returnedSalary.NewTotalSalary.RoundToDollars() + "," + HandleBasicCash(returnedSalary.NewBasicCash) + "," + returnedSalary.NewMealsProvided.RoundToDollars() + "," + returnedSalary.NewCashMealAllowance.RoundToDollars() + "," + returnedSalary.NewCashCellphoneAllowance.RoundToDollars() + "," + returnedSalary.NewHoursPerWeek; streamWriter.WriteLine(output); employeesToUpdate.Add(returnedSalary.EmployeeId); } success = _data.UpdateExportedSalaryRecords(employeesToUpdate); streamWriter.Close(); } return success; } private static decimal HandleBasicCash(decimal basicCash) { return basicCash == 0.01M || basicCash == 0 ? 0.01M : basicCash.RoundToDollars(); } public void Dispose() { _data?.Dispose(); } } }
namespace Otchi.BitOperations { public static partial class BitOperations { public static bool AreAllBitsSet(this sbyte t) { return t == -1; } public static bool AreAllBitsSet(this byte t) { return t == byte.MaxValue; } public static bool AreAllBitsSet(this short t) { return t == -1; } public static bool AreAllBitsSet(this ushort t) { return t == ushort.MaxValue; } public static bool AreAllBitsSet(this int t) { return t == -1; } public static bool AreAllBitsSet(this uint t) { return t == uint.MaxValue; } public static bool AreAllBitsSet(this long t) { return t == -1; } public static bool AreAllBitsSet(this ulong t) { return t == ulong.MaxValue; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Exercise10 { /* 10. Write a program to calculate n! for each n in the range [1..100]. * Hint: Implement first a method that multiplies a number represented * as array of digits by given integer number. */ class Program { static void Main(string[] args) { int num; bool null_digit = false; int[] calculated_array = new int[10]; do { Console.WriteLine("Please enter num in range [0 - 100]"); num = Convert.ToInt32(Console.ReadLine()); } while (num < 0 || num > 100); calculated_array = Facotorial(num); for (int i = calculated_array.Length - 1; i >= 0; i--) { if (calculated_array[i] != 0) { null_digit = true; } if (null_digit == true ) { Console.Write("{0}", calculated_array[i]); } } Console.WriteLine(); } static int[] Facotorial(int number) { int[] array = new int[10]; int carrage; int temp; temp = number; array[0] = temp % 10; temp -= array[0]; temp /= 10; array[1] = temp % 10; temp -= array[1]; temp /= 10; array[2] = temp % 10; for (int i = 1; i < number; i++) { carrage = 0; array[0] *= i; if (array[0] > 9) { carrage = array[0]; array[0] = carrage % 10; carrage -= array[0]; carrage /= 10; } array[1] *= i; array[1] += carrage; carrage = 0; if (array[1] > 9) { carrage = array[1]; array[1] = carrage % 10; carrage -= array[1]; carrage /= 10; } array[2] *= i; array[2] += carrage; carrage = 0; if (array[2] > 9) { carrage = array[2]; array[2] = carrage % 10; carrage -= array[2]; carrage /= 10; } array[3] *= i; array[3] += carrage; carrage = 0; if (array[3] > 9) { carrage = array[3]; array[3] = carrage % 10; carrage -= array[3]; carrage /= 10; } array[4] *= i; array[4] += carrage; carrage = 0; if (array[4] > 9) { carrage = array[4]; array[4] = carrage % 10; carrage -= array[4]; carrage /= 10; } array[5] *= i; array[5] += carrage; carrage = 0; if (array[5] > 9) { carrage = array[5]; array[5] = carrage % 10; carrage -= array[5]; carrage /= 10; } array[6] *= i; array[6] += carrage; carrage = 0; if (array[6] > 9) { carrage = array[6]; array[6] = carrage % 10; carrage -= array[6]; carrage /= 10; } array[7] *= i; array[7] += carrage; carrage = 0; if (array[7] > 9) { carrage = array[7]; array[7] = carrage % 10; carrage -= array[7]; carrage /= 10; } array[8] *= i; array[8] += carrage; carrage = 0; if (array[8] > 9) { carrage = array[8]; array[8] = carrage % 10; carrage -= array[8]; carrage /= 10; } array[9] *= i; array[9] += carrage; carrage = 0; if (array[9] > 9) { carrage = array[9]; array[9] = carrage % 10; carrage -= array[9]; carrage /= 10; } } return array; } } }