text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Binding; namespace BinderTests.MockingInterfaces { public class SimpleViewModel : ISimpleViewModel { #region ISimpleViewModel Members public string EmployeeName { get; set; } public List<Child> ChildrensNames { get; set; } #endregion #region INotifyPropertyChanged Members public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; #endregion } public interface ISimpleViewModel { string EmployeeName {get; set;} List<Child> ChildrensNames { get; set; } } public class Child { public string Name { get; set; } } }
using MaterialSurface; using System.Collections.Generic; using System.Threading.Tasks; using TutteeFrame2.DataAccess; using TutteeFrame2.Model; using TutteeFrame2.View; namespace TutteeFrame2.Controller { class SubjectController { readonly SubjectView subjectView; public List<Subject> subjects; public SubjectController(SubjectView subjectView) { this.subjectView = subjectView; } public async void LoadSubjects() { subjectView.homeView.SetLoad(true, "Đang tải thông tin danh sách môn học.."); await Task.Delay(600); await Task.Run(()=> { subjects = SubjectDA.Instance.GetSubjects(); }); subjectView.ShowData(); subjectView.homeView.SetLoad(false); } public async void AddSubject(Subject subject) { subjectView.homeView.SetLoad(true, "Đang thực hiện, vui lòng đợi trong giây lát.."); await Task.Delay(600); await Task.Run(()=> { SubjectDA.Instance.AddSubject(subject); }); LoadSubjects(); } public async void DeleteSubject(Subject subject) { bool progressResult = true; subjectView.homeView.SetLoad(true, "Đang thực hiện, vui lòng đợi trong giây lát.."); await Task.Delay(600); await Task.Run(() => { progressResult = SubjectDA.Instance.DeleteSubject(subject); }); subjectView.homeView.SetLoad(false); if (progressResult) { LoadSubjects(); } else { Dialog.Show(subjectView.homeView, "Thao tác thất bại, vui lòng kiểm tra lại kết nối," + " hoặc chắc chắn rằng không có giáo viên nào đang giảng dạy môn này.",tittle:"Thông báo"); } } public async void UpdateSubject(Subject subject) { subjectView.homeView.SetLoad(true, "Đang thực hiện, vui lòng đợi trong giây lát.."); await Task.Delay(600); await Task.Run(() => { SubjectDA.Instance.UpdateSubject(subject); }); LoadSubjects(); } } }
using System.Collections.Generic; using System.Linq; namespace LSystemsPlants.Core.L_Systems { public static class SymbolHelper { private static readonly Dictionary<Symbol, string> _symbolsStrings = new Dictionary<Symbol, string>() { {Symbol.FORWARD_DRAW , "F"}, {Symbol.FORWARD_NO_DRAW , "f"}, {Symbol.POP_STATE , "]"}, {Symbol.PUSH_STATE , "["}, {Symbol.TURN_LEFT , "+"}, {Symbol.TURN_RIGHT , "-"}, {Symbol.L , "L"}, {Symbol.R , "R"}, }; public static string GetRepresentation(this Symbol s) { return _symbolsStrings[s]; } public static string GetString(params Symbol[] symbols) { return string.Concat(symbols.Select(s => s.GetRepresentation())); } } }
using System.Data.Entity.ModelConfiguration; using Logs.Models; namespace Logs.Data.Mappings { public class LogEntryMap : EntityTypeConfiguration<LogEntry> { public LogEntryMap() { // Primary Key this.HasKey(t => t.LogEntryId); // Properties this.Property(t => t.UserId) .HasMaxLength(128); // Table & Column Mappings this.ToTable("LogEntries"); this.Property(t => t.LogEntryId).HasColumnName("LogEntryId"); this.Property(t => t.EntryDate).HasColumnName("EntryDate"); this.Property(t => t.Content).HasColumnName("Content"); this.Property(t => t.LogId).HasColumnName("LogId"); this.Property(t => t.UserId).HasColumnName("UserId"); // Relationships this.HasOptional(t => t.User) .WithMany(t => t.LogEntries) .HasForeignKey(d => d.UserId); this.HasOptional(t => t.TrainingLog) .WithMany(t => t.LogEntries) .HasForeignKey(d => d.LogId); } } }
using System; using System.Collections.Generic; using TrainingPrep.collections; public class FilteringEntryPoint<TItem, TField> { public readonly Func<TItem, TField> _fieldSelector; private readonly bool _isNegate; public FilteringEntryPoint(Func<TItem, TField> fieldSelector) : this(fieldSelector, false) { } private FilteringEntryPoint(Func<TItem, TField> fieldSelector, bool isNegate) { _fieldSelector = fieldSelector; _isNegate = isNegate; } public FilteringEntryPoint<TItem, TField> Not() { return new FilteringEntryPoint<TItem, TField>(_fieldSelector, !_isNegate) ; } public ICriteria<TItem> ApplyNegation(ICriteria<TItem> criteria) { if (_isNegate) return new Negation<TItem>(criteria); else return criteria; } } public static class FilteringEntryPointExtensions { public static ICriteria<TItem> EqualTo<TItem, TField>(this FilteringEntryPoint<TItem, TField> filteringEntryPoint, TField fieldValue) { var criteria = new PropertyCriteria<TItem, TField>(filteringEntryPoint._fieldSelector, new EqualToCriteria<TField>(fieldValue)); return filteringEntryPoint.ApplyNegation(criteria); } public static ICriteria<TItem> GreaterThan<TItem, TField>(this FilteringEntryPoint<TItem, TField> filteringEntryPoint, TField fieldValue) where TField : IComparable<TField> { return filteringEntryPoint.ApplyNegation( new PropertyCriteria<TItem, TField>(filteringEntryPoint._fieldSelector, new GreaterThanCriteria<TField>(fieldValue))); } public static ICriteria<TItem> Between<TItem, TField>(this FilteringEntryPoint<TItem, TField> filteringEntryPoint, TField from, TField to) where TField : IComparable<TField> { var criteria = new PropertyCriteria<TItem, TField>(filteringEntryPoint._fieldSelector, new BetweenCriteria<TField>(from, to)); return filteringEntryPoint.ApplyNegation(criteria); } public static ICriteria<TItem> EqualToAny<TItem, TField>( this FilteringEntryPoint<TItem, TField> filteringEntryPoint, params TField[] fieldValue) { var fieldList = new List<TField>(fieldValue); var criteria = new PropertyCriteria<TItem, TField>(filteringEntryPoint._fieldSelector, new EqualToAnyCriteria<TField>(fieldList)); return filteringEntryPoint.ApplyNegation(criteria); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ReportesCLIN2.Reports { public static class LiquidFilters { /// <summary> /// Funcion que da formato a un objeto de entrada /// </summary> /// <param name="input"></param> /// <param name="format"></param> /// <returns></returns> public static string Format(object input, string format) { if (input == null) return null; else if (string.IsNullOrWhiteSpace(format)) return input.ToString(); if (format.ToLower() == "roman") return IntToRoman(input, format.Equals("ROMAN")); return string.Format("{0:" + format + "}", input); } /// <summary> /// Funcion que convierte entero a romano /// </summary> /// <param name="input"></param> /// <param name="uppercase"></param> /// <returns></returns> public static string IntToRoman(object input, bool uppercase) { if (input == null) return null; int num = int.Parse(input.ToString()); // storing roman values of digits from 0-9 // when placed at different places string[] m = { "", "M", "MM", "MMM" }; string[] c = {"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"}; string[] x = {"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"}; string[] i = {"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"}; // Converting to roman string thousands = m[num / 1000]; string hundereds = c[(num % 1000) / 100]; string tens = x[(num % 100) / 10]; string ones = i[num % 10]; string ans = thousands + hundereds + tens + ones; return ( uppercase ? ans : ans.ToLower()); } } }
using System; using Toppler.Core; using Xunit; namespace Toppler.Tests.Unit.Api { public class TopplerClientTest { [Fact] public void TopplerClient_WhenNoSetup_ShouldNoBeConnected() { Assert.False(Top.IsConnected); } [Fact] public void Counter_WhenNoSetup_ShouldThrowException() { Assert.Throws<InvalidOperationException>(() => { Top.Counter.HitAsync(new string[] { "blabla" }); }); } [Fact] public void Leaderboard_WhenNoSetup_ShouldThrowException() { Assert.Throws<InvalidOperationException>(() => { Top.Ranking.AllAsync(Granularity.Day, 1); }); } } }
using Microsoft.EntityFrameworkCore; using Skaitykla.Domains; using Skaitykla.EF; using Skaitykla.Services.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Skaitykla.Services { public class AuthorService : IAuthorService { private readonly BookContext _db; private readonly IBookService _bookService; public AuthorService(BookContext db, IBookService bookService) { _db = db; _bookService = bookService; } public async Task<IEnumerable<Author>> GetAuthorsAsync() { return _db.Authors.Include(x => x.WrittenBooks); } public Author GetAuthorById(Guid id) { return _db.Authors.Where(a => a.Id == id).FirstOrDefault(); } public Task<int> CreateAuthorAsync(string name, string surname) { var newAuthor = new Author(name, surname); _db.Authors.Add(newAuthor); return _db.SaveChangesAsync(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using Utilities.NET.Enums; // ReSharper disable MemberCanBePrivate.Global namespace Utilities.NET.Helpers { /// <summary> Reflection utilities. </summary> public static class ReflectionUtilities { /// <summary> /// Returns a collection of objects of type <typeparamref name="T"/> of none public fields a target object may /// have. /// </summary> public static IList<T> GetAllPrivateFields<T>(object target) { return target .GetType() .GetFields(BindingFlags.Instance | BindingFlags.NonPublic) .Where(x => typeof(T) == x.FieldType) .Select(x => x.GetValue(target)) .Cast<T>() .ToList(); } /// <summary> Gets property information. </summary> /// <typeparam name="T"> Generic type parameter. </typeparam> /// <param name="propertyName"> Name of the property. </param> /// <returns> The property. </returns> public static PropertyInfo GetPropertyInfo<T>(string propertyName) { var type = typeof(T); var propertyInfo = type.GetRuntimeProperty(propertyName); return propertyInfo; } /// <summary> Gets property information. </summary> /// <exception cref="ArgumentException"> /// Thrown when one or more arguments have unsupported or /// illegal values. /// </exception> /// <typeparam name="TSource"> Type of the source. </typeparam> /// <typeparam name="TProperty"> Type of the property. </typeparam> /// <param name="propertyLambda"> The property lambda. </param> /// <returns> The property information. </returns> public static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda) { if (!(propertyLambda.Body is MemberExpression member)) throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property."); var propInfo = member.Member as PropertyInfo; if (propInfo == null) throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property."); return propInfo; } /// <summary> An object extension method that query if 'obj' is of simple type. </summary> /// <param name="obj"> The obj to act on. </param> /// <returns> true if simple type, false if not. </returns> public static bool IsSimpleType(this object obj) { var type = obj.GetType(); return type.IsPrimitive || type == typeof(string); } /// <summary> An object extension method that query if 'obj' is of a collection type. </summary> /// <param name="obj"> The obj to act on. </param> /// <returns> true if collection type, false if not. </returns> public static bool IsCollectionType(this object obj) { return obj is IEnumerable collection && !(collection is string); } /// <summary> An object extension method that returns the classification of its type. </summary> /// <param name="obj"> The obj to act on. </param> /// <returns> A Type. </returns> public static ObjectType TypeOfObject(this object obj) { if (obj.IsSimpleType()) return ObjectType.Simple; if (obj.IsCollectionType()) return ObjectType.Collection; return ObjectType.Complex; } } }
using UnityEngine; using System.Collections; public class MyCamera : MonoBehaviour { // Variables public Transform lookAt; public float lerpSpeed; public float xOffset; public float yOffset; public float zOffset; void Start () { } void LateUpdate () { //Vector3 offset = new Vector3(xOffset, yOffset, zOffset); //Vector3 desiredPos = lookAt.transform.position + offset; //transform.position = Vector3.Lerp(transform.position, desiredPos, (lerpSpeed * Time.deltaTime)); Vector3 desiredPos = new Vector3((lookAt.transform.position.x + xOffset), yOffset, zOffset); transform.position = desiredPos; }// End LateUpdate }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Idenz.Core.Windows; namespace Idenz.Modules.Patient { public partial class frmAppointmentList : frmSimpleBaseForm { public frmAppointmentList() { InitializeComponent(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Web; namespace Photogf.common { public static class unity { public static Int64 GetTime() { var s = Int64.Parse(Math.Round((DateTime.Now - Convert.ToDateTime("1970-1-1")).TotalSeconds, 0).ToString()); return s; } public static string MD5(string str) { MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider(); byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(str)); StringBuilder sBuilder = new StringBuilder(); for (int i = 0; i < data.Length; i++) { sBuilder.Append(data[i].ToString("x2") + "1"); } return sBuilder.ToString(); } } }
using UnityEngine; using UnityEditor; public class HUD : MonoBehaviour { public Inventory inventory; public void OpenMessagePanel(string text) { } public void CloseMessagePanel() { } }
using System.Collections; using UnityEngine; using DG.Tweening; using System; public class TitleDisplayer : MonoBehaviour { public CanvasGroup titleLogoCanvas; // Start is called before the first frame update void Start() { // 表示が気持ち悪かったので0.1s待つ StartCoroutine(DelayMethod(0.1f, () => { titleLogoCanvas.DOFade(0.7f, 1.0f).SetEase(Ease.OutSine); })); } // Update is called once per frame void Update() { } private IEnumerator DelayMethod(float waitTime, Action action) { yield return new WaitForSeconds(waitTime); action(); } }
using Platformer.Mechanics; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BulletAnimationHit : MonoBehaviour { public int damage = 25; void Start(){ } private void OnTriggerEnter2D(Collider2D other){ if (other.tag =="enemy"){ Debug.Log(damage); other.GetComponent<EnemyController>().HealthDecrement(damage); Destroy(this.gameObject); } if (other.tag =="Boss"){ other.GetComponent<BossController>().HealthDecrement(damage); Destroy(this.gameObject); } if (other.tag =="Ground"){ Destroy(this.gameObject); } } }
using System; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.AI; public class EnemyMixAIV3 : MonoBehaviour, IDamageable, IHarpoonable { //NavMeshStuff private NavMeshAgent _navMeshAgent; private GameObject _player; private float _enemySpeed = 4.5f; private float _enemyStoppedSpeed = 0f; private Animator _animator; private int _maxHealth = 130; private int _currentHealth; private IDamageable _playerHealth; //Shoot stuff public GameObject projectilePrefab; public Transform bulletPoint; public float constant; public float fireRate = 0.5f; private float _nextFire; //Distance to the player stuff private bool _playerIsInSight; public float distanceFromPlayer; private bool _playerIsInMeleeRange => Vector3.Distance(transform.position, _player.transform.position) < 3; private bool _playerIsOnWalkingDistance => Vector3.Distance(transform.position, _player.transform.position) < 10; private bool _playerIsInRangeAttack => Vector3.Distance(transform.position, _player.transform.position) > 20; private bool _hasAttacked; public bool isGrabbed; private Coroutine attack; private State _currentState; private bool _isAlive; public DoorScript Door; float unhookedSince = 0; private AudioSource _audio; public AudioClip CacToDist; public AudioClip Frappe; public AudioClip ProjectileLaunched; public AudioClip Mort; public ParticleSystem blood, deathGeyser; private enum State { Idle, Walking, Melee, Distance, Hooked, Stunned, Dead } void Awake() { _player = GameObject.FindWithTag("Player"); _playerHealth = _player.GetComponent<IDamageable>(); _animator = GetComponentInChildren<Animator>(); _navMeshAgent = GetComponent<NavMeshAgent>(); _audio = GetComponent<AudioSource>(); } private void Start() { _currentHealth = _maxHealth; _isAlive = true; isGrabbed = false; _hasAttacked = false; _playerIsInSight = true; _currentState = State.Idle; _nextFire = fireRate * UnityEngine.Random.Range(0.8f, 1.2f); } private void Update() { if (_isAlive) { unhookedSince += Time.deltaTime; if (_currentHealth <= 0) { _currentHealth = 0; Die(); } } switch (_currentState) { case State.Idle: SetAnimation("IsIdle"); if (_playerIsInRangeAttack) { _currentState = State.Distance; } if (_playerIsOnWalkingDistance) { _currentState = State.Walking; } if (_playerIsInMeleeRange) { _currentState = State.Melee; } if (!_playerIsInSight) { _currentState = State.Idle; } /*if (isGrabbed) { _currentState = State.Hooked; }*/ break; case State.Walking: ChasePlayer(); SetAnimation("IsChasing"); if (!_playerIsInSight) { _currentState = State.Idle; } if (_playerIsInRangeAttack && unhookedSince>2f) { _currentState = State.Distance; } if (_playerIsInMeleeRange && unhookedSince>2f) { _currentState = State.Melee; } break; case State.Melee: MeleeAttack(); SetAnimation("IsMelee"); if (_playerIsInRangeAttack) { _currentState = State.Distance; _audio.PlayOneShot(CacToDist); } if (_playerIsOnWalkingDistance) { _currentState = State.Walking; } if (_playerIsInMeleeRange) { _currentState = State.Melee; } break; case State.Distance: WaitToShoot(); if (_playerIsInMeleeRange) { _currentState = State.Melee; _audio.PlayOneShot(CacToDist); } if (_playerIsOnWalkingDistance) { _currentState = State.Melee; _audio.PlayOneShot(CacToDist); } break; case State.Hooked: SetAnimation("IsIdle"); InHarpoon(); break; case State.Stunned: SetAnimation("IsIdle"); break; case State.Dead: Die(); break; default: throw new ArgumentOutOfRangeException(); } } private void MeleeAttack() { SetAnimation("IsMelee"); if (unhookedSince > 2f) { if (attack == null) { _audio.PlayOneShot(Frappe); attack = StartCoroutine(Attack()); } } } IEnumerator Attack() { _navMeshAgent.speed = 0; _navMeshAgent.SetDestination(transform.position); yield return new WaitForSeconds(1f); _playerHealth.TakeDamage(10); yield return new WaitForSeconds(0.25f); _currentState = State.Idle; attack = null; } private void WaitToShoot() { if (ShootProjectileRoutine==null) SetAnimation("IsIdle"); if (unhookedSince > 2f) { if (Time.time > _nextFire && ShootProjectileRoutine==null) { Shoot(); } } } void Shoot() { _navMeshAgent.speed = 0f; SetAnimation("IsDistance"); if (ShootProjectileRoutine!=null) StopCoroutine(ShootProjectileRoutine); ShootProjectileRoutine = StartCoroutine(ShootProjectile()); _nextFire = Time.time + fireRate * UnityEngine.Random.Range(0.8f,1.2f); } private Coroutine ShootProjectileRoutine; IEnumerator ShootProjectile() { if (_isAlive) { yield return new WaitForSeconds(0.5f); GameObject bullet = Instantiate(projectilePrefab, bulletPoint.position, bulletPoint.rotation); Rigidbody bulletRb = bullet.GetComponent<Rigidbody>(); _audio.PlayOneShot(ProjectileLaunched); bulletRb.velocity = (_player.transform.position - bullet.transform.position).normalized * constant; yield return new WaitForSeconds(1f); ShootProjectileRoutine = null; } } private void ChasePlayer() { if (unhookedSince > 2f) { _navMeshAgent.speed = _enemySpeed; Vector3 dirToPlayer = transform.position - _player.transform.position; Vector3 newPos = transform.position - dirToPlayer; _navMeshAgent.SetDestination(newPos); } } private void Die() { if (_isAlive == false) return; _isAlive = false; _navMeshAgent.isStopped = true; foreach (BoxCollider box in GetComponentsInChildren<BoxCollider>()) { box.isTrigger = true; } _audio.PlayOneShot(Mort); _animator.SetTrigger("Die"); deathGeyser.Play(); Door.RemoveEnemy(); } public void TakeDamage(int amount) { _currentHealth = _currentHealth - amount; blood.Play(); } public void Harpooned() // LE MOMENT OÙ IL EST HARPONNÉ { if (!_isAlive) return; _navMeshAgent.isStopped = true; unhookedSince = 0; _currentState = State.Hooked; isGrabbed = true; } public void Released() // LE MOMENT OÙ IL EST RELÂCHÉ { if (!_isAlive) return; isGrabbed = false; transform.position = PlayerHandler.releasedEnemy.position; _navMeshAgent.isStopped = false; _currentState = State.Stunned; StopAllCoroutines(); StartCoroutine(WaitToEndStun()); } IEnumerator WaitToEndStun() { while (unhookedSince < 2f) { yield return null; } _navMeshAgent.isStopped = false; _currentState = State.Idle; } void InHarpoon() // CHAQUE UPDATE QUAND IL EST DANS LE HARPON { transform.position = PlayerHandler.Pointe.transform.position; } void SetAnimation(string animationSelected) { _animator.SetBool("IsIdle", false); _animator.SetBool("IsChasing", false); _animator.SetBool("IsMelee", false); _animator.SetBool("IsDistance", false); _animator.SetBool("IsDead", false); _animator.SetBool(animationSelected, true); } }
using NoScope360Engine.Core.Entites.Items; using System.Collections.Generic; namespace NoScope360Engine.Core.Entites.Creatures { /// <summary> /// Inventory of a <see cref="Creature"/> /// </summary> public class Inventory { /// <summary> /// List of Items of this <see cref="Creature"/> /// </summary> public List<Item> Items { get; set; } = new List<Item>(); public Inventory() { } } }
using AdoLibrary; using PickUp.Dal.Interfaces; using PickUp.Dal.Models; using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; namespace PickUp.Dal.Services { public class EventServices : IEventServices<Event> { private readonly IConnection connection; public EventServices(IConnection co) { connection = co; } public Event Converter(SqlDataReader reader) { return new Event( (int)reader["EventId"], (int)reader["ProUserId"], reader["Name"].ToString(), reader["Description"].ToString(), reader["Logo"].ToString(), (decimal)reader["Rating"]); } public IEnumerable<Event> GetAll() { Command cmd = new Command("GetAllEvent", true); return connection.ExecuteReader<Event>(cmd, Converter); } public Event GetById(int key) { Command cmd = new Command("GetEventById", true); cmd.AddParameter("EventId", key); return connection.ExecuteReader<Event>(cmd, Converter).FirstOrDefault(); } } }
using System; namespace Aqueduct.Configuration.Loaders { public class SettingEventArgs : EventArgs { private Setting m_setting; /// <summary> /// Initializes a new instance of the SettingEventArgs class. /// </summary> /// <param name="m_setting"></param> public SettingEventArgs (Setting m_setting) { this.m_setting = m_setting; } public bool Cancel { get; set; } } }
using System.Collections.Generic; class JsonStructure { public Dictionary<string,string> inclineScalingFunctions { get; set; } public Dictionary<string,string> speedScalingFunctions { get; set; } public Dictionary<string,string> resistanceScalingFunctions { get; set; } }
using System; using System.Net; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace SoftwareEngineeringProject_1 { static class StatisticDownloader { public static List<StatisticEvent> GetStatisticsEvent() { WebClient webClient = new WebClient(); var statisticEventsString = webClient.DownloadString("http://api.lod-misis.ru/testassignment"); if (statisticEventsString.Trim('"') == "") { Console.WriteLine("Nothing happened"); return null; } var statisticEventArray = statisticEventsString.Trim('"').Split(';'); List<StatisticEvent> listOfEvents = new List<StatisticEvent>(); foreach (var statEvent in statisticEventArray) { string[] genderAndCondition = statEvent.Split(':'); if (genderAndCondition.Length == 2) { StatisticEvent statisticEvent = new StatisticEvent { Gender = genderAndCondition[0], Condition = genderAndCondition[1] }; listOfEvents.Add(statisticEvent); }; Console.WriteLine(statEvent); } return listOfEvents; } } }
using System; using System.Reactive.Concurrency; using System.Reactive.Disposables; using System.Reactive.Linq; using System.Threading.Tasks; using Microsoft.Reactive.Testing; using ReactiveUI.Testing; using RxTools; using RxTools.IO; namespace RxPlayground { public static class G { public static IWriter Writer = NullWriter.Default; } public class Application { public static async Task MainAsync() { var sched = new TestScheduler(); var test = sched.CreateColdObservable( sched.OnNextAt(200, 1), sched.OnNextAt(400, 1), sched.OnNextAt(600, 2), sched.OnNextAt(800, 3), sched.OnNextAt(1000, 1), sched.OnNextAt(1200, 1), sched.OnNextAt(1400, 4), sched.OnNextAt(1600, 1), sched.OnNextAt(1800, 4), sched.OnNextAt(2000, 2), sched.OnNextAt(2200, 1), sched.OnNextAt(2400, 3), sched.OnNextAt(2600, 1), sched.OnNextAt(3000, 1), sched.OnNextAt(6000, 4) ); test .Dump(G.Writer) .Trigger(i => i == 1, o => o.Where(i => i > 1 && i < 4), () => TimeSpan.FromSeconds(2), sched) .Subscribe( _ => { G.Writer.WriteLine("launched"); }); var count = 0; do { count += 100; sched.AdvanceToMs(count); Console.WriteLine("Time " + count); } while (string.IsNullOrWhiteSpace(Console.ReadLine())); } } }
using Enrollment.XPlatform.ViewModels.Validatables; using System.Collections.Generic; namespace Enrollment.XPlatform.Validators.Rules { public record IsMatchRule<T> : ValidationRuleBase<T> { public IsMatchRule(string fieldName, string validationMessage, ICollection<IValidatable> allProperties, string otherFieldName) : base(fieldName, validationMessage, allProperties) { OtherFieldName = otherFieldName; } public override string ClassName { get => nameof(IsMatchRule<T>); } public string OtherFieldName { get; } private ValidatableObjectBase<T> OtherValidatable => (ValidatableObjectBase<T>)PropertiesDictionary[OtherFieldName]; public override bool Check() { if (!EqualityComparer<T>.Default.Equals(Value, OtherValidatable.Value)) return false; if (!OtherValidatable.Errors.ContainsKey(nameof(IsMatchRule<T>))) return true; //Clear the error in this control first (otherwise results in circular logic calling OtherValidatable.Validate()) if (PropertiesDictionary[FieldName].Errors.ContainsKey(nameof(IsMatchRule<T>))) PropertiesDictionary[FieldName].Errors.Remove(nameof(IsMatchRule<T>)); //Then check for validity in the other control (updates the UI for the other control). OtherValidatable.Validate(); return true; } } }
using System; using System.Collections.Generic; using ListasObjetos.Classes; namespace ListasObjetos { class Program { static void Main(string[] args) { List<Produto> produtos = new List<Produto>(); //adicionar itens/objetos Create // Construindo na hora produtos.Add(new Produto(1, "Apple watch", 3829.55f)); produtos.Add(new Produto(2, "Mi band", 200.95f)); produtos.Add(new Produto(3, "Samsung fit 2", 260.98f)); produtos.Add(new Produto(4, "Amazfit", 494.95f)); produtos.Add(new Produto(5, "Huawei watch fit", 768.23f)); // produto já construido Produto SamsungActive = new Produto(); SamsungActive.Nome = "Samgung watch active"; SamsungActive.Codigo = 6; SamsungActive.Preco = 1248.90f; produtos.Add(SamsungActive); //Mostrar Read Console.WriteLine("\n Lista \n"); foreach (Produto item in produtos) { Console.WriteLine($"{item.Nome} custa {item.Preco:C2}"); } // Update atualizar Produto atualizar = produtos.Find(item => item.Nome == "Amazfit"); atualizar.Preco = 240f; produtos.RemoveAll(item => item.Nome == "Amazfit"); produtos.Insert(3, atualizar); //delete produtos.RemoveAt(0); produtos.RemoveAll(item => item.Nome == "Mi band"); // mostrar de novo Console.WriteLine("\n Lista \n"); foreach (Produto item in produtos) { Console.WriteLine($"{item.Nome} custa {item.Preco:C2}"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace hex { class Program { string sot,ox; long dec; static void Main(string[] args) { Program Ox = new Program(); Ox.read(); } void read() { Console.Write("Octal value:"); sot = Console.ReadLine(); convToDec(); Console.Read(); } void convToDec() { long iox = Int64.Parse(sot); dec=0; int i = 0; while(iox != 0) { dec = dec + (iox % 10) * (long)Math.Pow(8, i); iox = iox / 10; i++; } //Console.WriteLine(dec); hex(); } void hex() { string temp; long t; ox=""; while(dec != 0) { t = dec % 16; //Console.Write("Hexa value: ",ox); if(t < 10) { temp = t.ToString(); temp = temp + ox; ox = temp; //Console.WriteLine(ox); } else { temp = alpha(t); temp = temp + ox; ox = temp; } dec = dec / 16; } Console.WriteLine("Hexa value: {0}",ox); } string alpha(long num) { switch(num){ case 10: return "A"; case 11: return "B"; case 12: return "C"; case 13: return "D"; case 14: return "E"; case 15: return "F"; } return "a"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SmallHouseManagerBLL; using SmallHouseManagerModel; namespace SmallHouseManagerWeb.Admin { public partial class AddChargeFee : System.Web.UI.Page { ChargeFreeTypeBLL freetypebll = new ChargeFreeTypeBLL(); RoomBLL roombll = new RoomBLL(); PavilionBLL pabll = new PavilionBLL(); TypeBLL typebll = new TypeBLL(); UserModel user = new UserModel(); protected void Page_Load(object sender, EventArgs e) { user = (UserModel)Session["User"]; if (Session["User"] == null || Session["User"].ToString() == "" || user.UserType != 1) Response.Redirect("../Login.aspx"); else { if (!IsPostBack) { DDLType.DataSource = freetypebll.GetChargeFreeType(); DDLType.DataBind(); DDLPa.DataSource = pabll.GetAllPavilion(); DDLPa.DataBind(); DDLCell.DataSource = typebll.GetType("Cell"); DDLCell.DataBind(); string str=DDLPa.SelectedValue; int i=Convert.ToInt32(DDLCell.SelectedValue); if(i<10) str+="0"+i.ToString(); else str+=i.ToString(); List<RoomModel> list = roombll.GetAllRoomUsed(str); if (list.Count != 0) { DDLRoomID.DataSource = list; DDLRoomID.DataBind(); Panel1.Visible = true; Panel2.Visible = false; } else { Panel1.Visible = false; Panel2.Visible = true; } } } } protected void Add_Click(object sender, EventArgs e) { HomeFreeBLL bll = new HomeFreeBLL(); HomeFreeModel homeFree = new HomeFreeModel(); homeFree.Code = DDLRoomID.SelectedValue; homeFree.TypeID = Convert.ToInt32(DDLType.SelectedValue); homeFree.Number = Convert.ToDouble(txtNumber.Text.Trim()); homeFree.StartDate = Convert.ToDateTime(txtBuildDate.Value); homeFree.PayDate = DateTime.Now; homeFree.AddName = user.Name; bool flag = bll.InsertHomeFree(homeFree); if (flag) { Page.ClientScript.RegisterStartupScript(GetType(), "OnSubmit", "<script>alert('添加成功');location.href='ChargeFeeInfo.aspx';</script>"); } else { Page.ClientScript.RegisterStartupScript(GetType(), "OnSubmit", "<script>alert('添加失败');</script>"); } } protected void Cancel_Click(object sender, EventArgs e) { Response.Redirect("ChargeFeeInfo.aspx"); } protected void DDLPa_SelectedIndexChanged(object sender, EventArgs e) { string str = DDLPa.SelectedValue; int i = Convert.ToInt32(DDLCell.SelectedValue); if (i < 10) str += "0" + i.ToString(); else str += i.ToString(); List<RoomModel> list = roombll.GetAllRoomUsed(str); if (list.Count != 0) { DDLRoomID.DataSource = list; DDLRoomID.DataBind(); Panel1.Visible = true; Panel2.Visible = false; } else { Panel1.Visible = false; Panel2.Visible = true; } } } }
using Ghost.Utility; using System; using System.Collections.Generic; using UnityEngine; namespace RO { [CustomLuaClass] public class RolePartMaterialInfo : IReuseableObject<Material, int>, IReuseableObjectBase { public int maxCountInPool; public Material originMat; public List<Material> instanceUsedMatList; public List<Material> instancePool; public int refCount; public bool outlineEnable; public bool toonEnable; public int multiColorNumber; public bool reused { get; set; } public void DisableOutline() { if (this.outlineEnable && null != this.originMat) { Shader rolePart = SingleTonGO<ShaderManager>.Me.rolePart; this.originMat.set_shader(rolePart); if (this.instanceUsedMatList != null) { for (int i = 0; i < this.instanceUsedMatList.get_Count(); i++) { this.instanceUsedMatList.get_Item(i).set_shader(rolePart); } } if (this.instancePool != null) { for (int j = 0; j < this.instancePool.get_Count(); j++) { this.instancePool.get_Item(j).set_shader(rolePart); } } } } public void DisableToon() { if (this.toonEnable && null != this.originMat) { RolePart.SetToonEnable(this.originMat, false); if (this.instanceUsedMatList != null) { for (int i = 0; i < this.instanceUsedMatList.get_Count(); i++) { RolePart.SetToonEnable(this.instanceUsedMatList.get_Item(i), false); } } if (this.instancePool != null) { for (int j = 0; j < this.instancePool.get_Count(); j++) { RolePart.SetToonEnable(this.instancePool.get_Item(j), false); } } } } public void RestoreOutline() { if (this.outlineEnable && null != this.originMat) { Shader shader = (!(null != SingleTonGO<ShaderManager>.Me)) ? Shader.Find("RO/Role/PartOutline") : SingleTonGO<ShaderManager>.Me.rolePartOutline; this.originMat.set_shader(shader); if (this.instanceUsedMatList != null) { for (int i = 0; i < this.instanceUsedMatList.get_Count(); i++) { this.instanceUsedMatList.get_Item(i).set_shader(shader); } } if (this.instancePool != null) { for (int j = 0; j < this.instancePool.get_Count(); j++) { this.instancePool.get_Item(j).set_shader(shader); } } } } public void RestoreToon() { if (this.toonEnable && null != this.originMat) { RolePart.SetToonEnable(this.originMat, true); if (this.instanceUsedMatList != null) { for (int i = 0; i < this.instanceUsedMatList.get_Count(); i++) { RolePart.SetToonEnable(this.instanceUsedMatList.get_Item(i), true); } } if (this.instancePool != null) { for (int j = 0; j < this.instancePool.get_Count(); j++) { RolePart.SetToonEnable(this.instancePool.get_Item(j), true); } } } } public void SetMaskColor(Color maskColor) { if (null != this.originMat) { RolePart.SetMaskColor(this.originMat, maskColor); if (this.instanceUsedMatList != null) { for (int i = 0; i < this.instanceUsedMatList.get_Count(); i++) { RolePart.SetMaskColor(this.instanceUsedMatList.get_Item(i), maskColor); } } if (this.instancePool != null) { for (int j = 0; j < this.instancePool.get_Count(); j++) { RolePart.SetMaskColor(this.instancePool.get_Item(j), maskColor); } } } } public Material CreateInstance() { Material material; if (this.instancePool != null && 0 < this.instancePool.get_Count()) { material = this.instancePool.get_Item(this.instancePool.get_Count() - 1); this.instancePool.RemoveAt(this.instancePool.get_Count() - 1); RolePart.SetBlendMode(material, RolePart.GetBlendMode(this.originMat)); if (RolePart.IsChangeColorEnable(this.originMat)) { RolePart.SetChangeColorEnable(material, true); RolePart.SetChangeColor(material, RolePart.GetChangeColor(this.originMat)); } else { RolePart.SetChangeColorEnable(material, false); } if (RolePart.IsToonEnable(this.originMat)) { RolePart.SetToonEnable(material, true); for (int i = 1; i < 4; i++) { RolePart.SetToonLightColor(material, RolePart.GetToonLightColor(this.originMat, i), i); RolePart.SetToonLightExposure(material, RolePart.GetToonLightExposure(this.originMat, i), i); } } else { RolePart.SetToonEnable(material, false); } RolePart.SetAlpha(material, RolePart.GetAlpha(this.originMat)); } else { material = Object.Instantiate<Material>(this.originMat); } if (this.instanceUsedMatList == null) { this.instanceUsedMatList = new List<Material>(); } this.instanceUsedMatList.Add(material); return material; } public void DestroyInstance(Material instance) { this.instanceUsedMatList.Remove(instance); if (0 <= this.maxCountInPool) { int num = (this.instancePool == null) ? 0 : this.instancePool.get_Count(); if (num >= this.maxCountInPool) { Object.Destroy(instance); return; } } if (this.instancePool == null) { this.instancePool = new List<Material>(); } this.instancePool.Add(instance); } public void Construct(Material mat, int count) { this.originMat = mat; this.maxCountInPool = count; this.refCount = 0; this.outlineEnable = (SingleTonGO<ShaderManager>.Me.rolePartOutline == this.originMat.get_shader()); this.toonEnable = RolePart.IsToonEnable(this.originMat); this.multiColorNumber = RolePart.GetMultiColorNumber(this.originMat); } public void Destruct() { this.RestoreOutline(); this.RestoreToon(); this.originMat = null; if (this.instanceUsedMatList != null) { this.instanceUsedMatList.Clear(); } if (this.instancePool != null) { for (int i = 0; i < this.instancePool.get_Count(); i++) { Object.Destroy(this.instancePool.get_Item(i)); } this.instancePool.Clear(); } this.refCount = 0; } public void Destroy() { this.Destruct(); } } }
// <copyright file="ConnectionState.cs" company="David Eiwen"> // Copyright (c) David Eiwen. All rights reserved. // </copyright> namespace IndiePortable.Communication.Core.Devices { public enum ConnectionState { Initializing = 0, Initialized = 1, Activating = 2, Activated = 3, Disconnecting = 4, Disconnected = 5, Lost = 6, Disposing = 7, Disposed = 8 } }
using System; using System.Data.Objects; using System.Linq; namespace KT.DB.CRUD { public class CategoriesRepository:ICrud<Category> { public Category Create(Category entity) { using (var db = new KTEntities()) { db.Categories.AddObject(entity); db.SaveChanges(); return entity; } } public Category Read(Predicate<Category> predicate, string[] relatedObjects = null) { using (var db = new KTEntities()) { var val = db.Categories.Include(relatedObjects).AsEnumerable().DefaultIfEmpty(null).FirstOrDefault(a => predicate(a)); return val; } } public Category[] ReadArray(Predicate<Category> predicate, string[] relatedObjects = null) { using (var db = new KTEntities()) { var val = db.Categories.Include(relatedObjects).AsEnumerable().Where(a => predicate(a)); return val.ToArray(); } } public Category Update(Category entity) { using (var db = new KTEntities()) { var val = db.Categories.DefaultIfEmpty(null).FirstOrDefault(a => a.Id == entity.Id); if (val != null) { val.Name = entity.Name; val.CreatedByUser = entity.CreatedByUser; db.SaveChanges(); } return val; } } public void Delete(Predicate<Category> predicate) { using (var db = new KTEntities()) { var values = db.Categories.AsEnumerable().Where(a => predicate(a)); foreach (var val in values) { db.Categories.DeleteObject(val); } db.SaveChanges(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel.DataAnnotations; namespace ExercicesListGenerator.Models { [Table("Entrainements")] public class Entrainement { public int ID { get; set; } [Required] public virtual string Description { get; set; } public virtual DateTime? CreationDate { get; set; } public virtual DateTime? ExecutionDate { get; set; } public virtual List<Exo> ListeExo { get; set; } } }
using System; using BiPolarTowerDefence.Utilities; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using OpenTK; using Vector2 = Microsoft.Xna.Framework.Vector2; using Vector3 = Microsoft.Xna.Framework.Vector3; namespace BiPolarTowerDefence.Entities { public abstract class BaseButton : BaseObject { private Color buttonColor; private Color hoverButtonColor; private Color currentbuttonColor; protected string text; public BaseButton(Game1 game, Vector3 position, string text) : base(game, position) { this.text = text; this.buttonColor = Color.LightGray; this.hoverButtonColor = Color.DarkGray; } public void ChangeSize(Vector2 size) { width = size.X; height = size.Y; } public override void Update(GameTime gameTime) { var mouseState = Mouse.GetState(); var pos = mouseState.Position; var rect = this.GetRect(); currentbuttonColor = buttonColor; if (rect.Contains(pos)) { currentbuttonColor = hoverButtonColor; } if (rect.Contains(pos) && mouseState.LeftButton == ButtonState.Pressed) { this.HandleClick(); } } public void Draw(GameTime gameTime) { var spriteBatch = Game1.Game.spriteBatch; var graphics = Game1.Game.GraphicsDevice; var font = Game1.Game.Font; var pos = GetPosition2(); int stringX = (int)(((width/2)-(font.MeasureString(text).X / 2)) +pos.X); int stringY = (int)(((height/2)-(font.MeasureString(text).Y / 2)) +pos.Y); Vector2 stringPosition = new Vector2 (stringX,stringY); Rectangle destination = GetRect(); Texture2D pixel = new Texture2D (graphics, 1,1,false, SurfaceFormat.Color); pixel.SetData(new[] { Color.White }); spriteBatch.Begin(); spriteBatch.Draw(pixel, destination, Rectangle.Empty, currentbuttonColor, 0f, Vector2.Zero, SpriteEffects.None, 0f); spriteBatch.DrawString(font,text, stringPosition,Color.Black); spriteBatch.End(); } public virtual void HandleClick() { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoreComponents { public interface IReferenceValueContainer<T> : IValueContainer<T>, IReadonlyReferenceValueContainer<T> where T : class { } }
using System; using System.IO; namespace LogsSearchServer { public class TempDir { public static readonly string Label = "_temp"; public string Name { get; set; } public string FullPath { get; set; } public string ParentPath { get; set; } public TempDir() { } private TempDir(string name, string fullPath, string parentPath) { Name = name; FullPath = fullPath; ParentPath = parentPath; } private TempDir(string path) { Name = Guid.NewGuid().ToString("N") + Label; FullPath = System.IO.Path.Combine(path, Name); ParentPath = path; } public static TempDir Create(string path) { return new TempDir(path); } public static TempDir CreateFromFullPath(string fullPath) { var path = Path.GetDirectoryName(fullPath); return new TempDir( Path.GetFileName(path), path, Path.GetDirectoryName(path) ); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using Grisaia.Categories; using Grisaia.Categories.Sprites; namespace Grisaia.SpriteViewer.Controls { /// <summary> /// A combo box and label for selecting from a <see cref="ISpritePartGroup"/>. /// </summary> public class SpritePartGroupComboBox : Control { #region Fields //private TextBlock PART_TextBlock; //private ComboBox PART_ComboBox; //private Thumb PART_Thumb; /// <summary> /// Supresses property changed events while another event is taking palce. /// </summary> private bool supressEvents; #endregion #region Dependency Properties /// <summary> /// The property for the sprite part group that this combo box makes a selection from. /// </summary> public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register( "ItemsSource", typeof(ISpritePartGroup), typeof(SpritePartGroupComboBox), new FrameworkPropertyMetadata( OnItemsSourceChanged)); /// <summary> /// The property for the selected sprite part group part. /// </summary> public static readonly DependencyProperty SelectedItemProperty = DependencyProperty.Register( "SelectedItem", typeof(ISpritePartGroupPart), typeof(SpritePartGroupComboBox), new FrameworkPropertyMetadata( null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemChanged)); /// <summary> /// The property for the selected sprite part group part.<para/> /// Used to coerce of the <see cref="SelectedItemProperty"/> and only propagate the new value. /// </summary> public static readonly DependencyProperty SelectedItemInternalProperty = DependencyProperty.Register( "SelectedItemInternal", typeof(ISpritePartGroupPart), typeof(SpritePartGroupComboBox), new FrameworkPropertyMetadata( null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, OnSelectedItemInternalChanged)); private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SpritePartGroupComboBox control = (SpritePartGroupComboBox) d; control.CoerceSelectedItem(control.SelectedItem); } private static void OnSelectedItemChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SpritePartGroupComboBox control = (SpritePartGroupComboBox) d; control.CoerceSelectedItem(control.SelectedItem); } private static void OnSelectedItemInternalChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { SpritePartGroupComboBox control = (SpritePartGroupComboBox) d; control.CoerceSelectedItem(control.SelectedItemInternal); } private void CoerceSelectedItem(ISpritePartGroupPart groupPart, [CallerMemberName] string callerName = null) { if (supressEvents) return; string propName = "null"; if (GetBindingExpression(ItemsSourceProperty) != null) propName = GetBindingExpression(ItemsSourceProperty).ResolvedSourcePropertyName; Console.WriteLine($"{propName} SpritePartGroupComboBox.{callerName} coerce"); supressEvents = true; ISpritePartGroup source = ItemsSource; if (source == null) { groupPart = null; } else if (groupPart != null && source.TryGetValue(groupPart.Id, out ISpritePartGroupPart newGroupPart)) { groupPart = newGroupPart; } else if (source.IsEnabledByDefault && source.GroupParts.Count > 1) { groupPart = source.GroupParts[1]; } else { groupPart = source.GroupParts[0]; } SelectedItem = groupPart; SelectedItemInternal = groupPart; supressEvents = false; } /// <summary> /// Gets or sets the sprite part group that this combo box makes a selection from. /// </summary> public ISpritePartGroup ItemsSource { get => (ISpritePartGroup) GetValue(ItemsSourceProperty); set => SetValue(ItemsSourceProperty, value); } /// <summary> /// Gets or sets the selected sprite part group part. /// </summary> public ISpritePartGroupPart SelectedItem { get => (ISpritePartGroupPart) GetValue(SelectedItemProperty); set => SetValue(SelectedItemProperty, value); } /// <summary> /// Gets or sets the selected sprite part group part.<para/> /// Used to coerce of the <see cref="SelectedItemProperty"/> and only propagate the new value. /// </summary> public ISpritePartGroupPart SelectedItemInternal { get => (ISpritePartGroupPart) GetValue(SelectedItemInternalProperty); set => SetValue(SelectedItemInternalProperty, value); } #endregion #region Static Constructor static SpritePartGroupComboBox() { DefaultStyleKeyProperty.AddOwner(typeof(SpritePartGroupComboBox), new FrameworkPropertyMetadata(typeof(SpritePartGroupComboBox))); } #endregion #region Control Overrides /*public override void OnApplyTemplate() { base.OnApplyTemplate(); PART_ComboBox = GetTemplateChild("PART_ComboBox") as ComboBox; PART_TextBlock = GetTemplateChild("PART_TextBlock") as TextBlock; }*/ #endregion } }
using UnityEngine; using System.Collections; public class BullCharge : Ability { public BullCharge(Unit owner) : base("Bull Charge", "A ferocious charge, granting the owner +2 movement and double damage for 1 turn.", owner, 1, true, "PowerBull") { cast_before_attack = true; effects_of_ability.Add(new ChangeMovement(owner, 2, 1)); effects_of_ability.Add(new ChangeDamage(owner, 0, 1, 1)); effects_of_ability.Add(new ChangePiercingDamage(owner, 0, 1, 1)); } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using SimpleService.Model; namespace SimpleService.Infrastructure { internal class BookRatingEntityTypeConfiguration : IEntityTypeConfiguration<BookRating> { public void Configure(EntityTypeBuilder<BookRating> builder) { builder.ToTable("BookRating"); builder.HasKey(bi => bi.Id); } } }
using System; namespace ToDoItem.Common { public class Class1 { } }
/* Project Prologue * Name: Spencer Carter * Class: CS 1400 Section 003 * Project: Wagon Wheel Odometer (Project_03) * Date: 02/16/2015 * * I declare that the following code was written by me, provided * by the instrustor, assisted via the lovely people in the drop * in lab, or provided in the textbook for this project. I also * understand that copying source code from any other sourece * constitutes cheating, and that I will recieve a zero on this * project if I am found in violation of this policy. * * I also declare that the image used for this project, was used * as a stock image. The content owner "wintersmagicstock" published * their work on DeviantART under "Resources & Stock Images" and * declared in their description "Unrestricted Stock". The following URL * is where the image can be located: http://fav.me/d6jrtgl * Fair Use: The image above is only to be used for educational, non- * commercial purposes. There is to be no redistribution outside the * bounds of this assignment. All other purposes will be for example only. */ 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 Project_03 { public partial class FrmTravelDistance : Form { /* --- Information Stuffs --- * Goal: * Design a GUI App that allows the user to enter in a sheel diameter in inches * into a textbox. Then display the number of turns reguired for the wheel to * travel one mile in a second textbox (no user entry allowed). * * Interface: * 1 Menu Strip with: About, Instructions Clear, Exit * 2 Textboxes: Wheel Diameter (in inches), and Turns per Mile * 2 Lables for each text box * 1 Picture Box with the image mentioned above * 2 Buttons: Clear, Exit * * Things I will need: * Circumfrance = Pi * Diameter * double wagonDia in inches * double wagonCir in inches * int mile = 63360 inches * mile / circumfrance = turns * // Psudocode: // 1) on enter stroke read data entered, store in _diameter // 2) circumfrance = pi * diameter // 3) wheelTurns = mile / circumfrance // 4) display wheel turns in txtBxTurns // 5) On clear, put focus back on txtBxDiameter */ #region Const private const int MILE_INCHES = 63360; #endregion Const /// <summary> /// Purpose: the entry point into the program /// </summary> public FrmTravelDistance() { InitializeComponent(); } /// <summary> /// Purpose: To display information about the author. /// </summary> /// <param name="sender">aboutMnu_Click</param> /// <param name="e">EventArgs</param> private void AboutMnu_Click(object sender, EventArgs e) { // when clicked, it will have a popup window that displays the creator's name and class // it will close when either a yes or a no is clicked. string aboutMsg = "Spencer Carter\nCS1400\nProject 03"; string headerMsg = "About Dialog Box"; MessageBox.Show(aboutMsg, headerMsg, MessageBoxButtons.YesNo, MessageBoxIcon.Information); } /// <summary> /// Purpose: To exit the program when clicked /// </summary> /// <param name="sender">exitMnu_Click</param> /// <param name="e">not used</param> private void ExitMnu_Click(object sender, EventArgs e) { Close(); // ends the program } /// <summary> /// Purpose: To display how the program works to the user. /// Also to display the limitations or restrictions of the program. /// </summary> /// <param name="sender">instructionsMnu_Click</param> /// <param name="e">EventArgs</param> private void InstructionsMnu_Click(object sender, EventArgs e) { // when clicked, it will have a popup window that displays the instructions // it will close when either a yes or a no is clicked. string aboutMsg = "Instructions:\nPlease enter the diameter of the wheel in inches.\nPlease note, that letters, zero, or negative numbers will not work.\nThen press enter on the keyboard.\nThe number of revolutions for a mile will be displayed below."; string headerMsg = "Instructions Dialog Box"; MessageBox.Show(aboutMsg, headerMsg, MessageBoxButtons.OK, MessageBoxIcon.Information); } /// <summary> /// Purpose: on key press enter, it will find out how many turns of the wheel it takes to make a mile /// </summary> /// <param name="sender">txtBdDiameter_KeyPress</param> /// <param name="e">not used</param> private void TxtBoxDiameter_KeyPress(object sender, KeyPressEventArgs e) { #region Variables double _circumfrance = 0.0; double _diameter = 0.0; double _wheelTurns = 0.0; #endregion Variables if (e.KeyChar==(char)Keys.Enter) { // 1) on enter stroke read data entered, store in _diameter double.TryParse(TxtDiameter.Text, out _diameter); if (_diameter <= 0) // some simple error correction { MessageBox.Show("That is an invalad entry, try again."); TxtDiameter.Clear(); TxtTurns.Clear(); TxtDiameter.Focus(); return; } // 2) circumfrance = pi * diameter _circumfrance = Math.PI * _diameter; // 3) wheelTurns = mile / circumfrance _wheelTurns = MILE_INCHES / _circumfrance; // 4) display wheel turns in txtBxTurns TxtTurns.Text = string.Format("{0:f3}", _wheelTurns); } } /// <summary> /// Purpose: to end the program /// </summary> /// <param name="sender">btnExit_Click</param> /// <param name="e">not used</param> private void BtnExit_Click(object sender, EventArgs e) { Close(); // ends the program } /// <summary> /// Purpose: to clear the values in both text boxes and return the focus /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ClearMnu_Click(object sender, EventArgs e) { TxtDiameter.Clear(); TxtTurns.Clear(); TxtDiameter.Focus(); return; } /// <summary> /// Purpose: to clear the values in both text boxes and return the focus /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void BtnClear_Click(object sender, EventArgs e) { TxtDiameter.Clear(); TxtTurns.Clear(); TxtDiameter.Focus(); return; } } // end FrmTravelDistance : Form } // end namespace Project_03
/********************************************************** CoxlinCore - Copyright (c) 2023 Lindsay Cox / MIT License **********************************************************/ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Reflection; using System.Text; namespace CoxlinCore { public static class CSVUtils { /// <summary> /// Not for use on update loops etc as uses /// Reflection underneath for value T so will not be the fastest possible solution /// but is quite flexible /// </summary> /// <typeparam name="T"></typeparam> public static T[] ParseCSVFile<T>(string csvFilePath) { var lines = File.ReadAllLines(csvFilePath); var lineCount = lines.Length; var properties = typeof(T).GetProperties(); var propertyCount = properties.Length; var result = new List<T>(); for (int i = 1; i < lineCount; ++i) //skip the first one { var line = lines[i]; var values = line.Split(','); if (values.Length != properties.Length) { throw new InvalidOperationException("CSV columns do not match object properties"); } var instance = Activator.CreateInstance<T>(); for (int j = 0; j < propertyCount; ++j) { var property = properties[j]; var value = Convert.ChangeType(values[j], property.PropertyType, CultureInfo.InvariantCulture); property.SetValue(instance, value); } result.Add(instance); } return result.ToArray(); } public static void WriteCsvFile<T>(T[] data, string filePath, Action onSuccess, Action<string> onError) { try { var dataCount = data.Length; using var writer = new StreamWriter(filePath); var properties = typeof(T).GetProperties(); var propertyCount = properties.Length; var header = JoinWithComma(GetPropertyNames(properties)); writer.WriteLine(header); for (int i = 0; i < dataCount; ++i) { var item = data[i]; var values = new string[propertyCount]; for (var j = 0; j < properties.Length; ++j) { var property = properties[j]; var value = property.GetValue(item); values[j] = value.ToString(); } var line = JoinWithComma(values); writer.WriteLine(line); } onSuccess(); } catch (Exception e) { onError(e.ToString()); throw; } } private static string JoinWithComma(string[] values) { var sb = new StringBuilder(); var isFirst = true; for (var i = 0; i < values.Length; ++i) { var value = values[i]; if (!isFirst) { sb.Append(','); } sb.Append(value); isFirst = false; } return sb.ToString(); } private static string[] GetPropertyNames(PropertyInfo[] properties) { var propertyNames = new string[properties.Length]; for (int i = 0; i < properties.Length; ++i) { propertyNames[i] = properties[i].Name; } return propertyNames; } } }
using Microsoft.AspNet.Mvc; using NonFactors.Mvc.Grid.Web.Context; using System.Threading; namespace NonFactors.Mvc.Grid.Web.Controllers { public class JavascriptController : Controller { [HttpGet] public ActionResult RowClicked() { return View(PeopleRepository.GetPeople()); } [HttpGet] public ActionResult Reload() { return View(); } [HttpGet] public ActionResult ReloadGrid() { return PartialView("_ReloadGrid", PeopleRepository.GetPeople()); } [HttpGet] public ActionResult ReloadEvents() { return View(); } [HttpGet] public ActionResult ReloadEventsGrid() { Thread.Sleep(500); return PartialView("_ReloadGrid", PeopleRepository.GetPeople()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Model; namespace Dao.Mercadeo { public class TipoVentaDao : GenericDao<crmTipoVenta>, ITipoVentaDao { } }
using Hotel.Data.Models; using Microsoft.AspNetCore.Mvc.Rendering; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Hotel.Web.Areas.ModulRecepcija.ViewModels { public class DodajStavkuVM { public int Id { set; get; } public int Kolicina { get; set; } public int ProizvodId { get; set; } public SelectList Proizvodi { get; set; } public Proizvodi Proizvod{ get; set; } public int NarudzbaId { get; set; } } }
using Contoso.Domain.Entities; using LogicBuilder.RulesDirector; using LogicBuilder.Workflow.Activities.Rules; using System; using System.Collections; using System.Globalization; using System.IO; using System.Linq; using System.Resources; using System.Threading.Tasks; namespace Contoso.Bsl.Flow.Rules { public class RulesLoader : IRulesLoader { public Task LoadRules(RulesModuleModel module, IRulesCache cache) { return Task.Run ( () => { string moduleName = module.Name.ToLowerInvariant(); RuleSet ruleSet = module.DeserializeRuleSetFile() ?? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.invalidRulesetFormat, moduleName)); if (cache.RuleEngines.ContainsKey(moduleName)) cache.RuleEngines[moduleName] = new RuleEngine(ruleSet, RulesSerializer.GetValidation(ruleSet)); else cache.RuleEngines.Add(moduleName, new RuleEngine(ruleSet, RulesSerializer.GetValidation(ruleSet))); using IResourceReader reader = new ResourceReader(new MemoryStream(module.ResourceSetFile)); reader.OfType<DictionaryEntry>() .ToList() .ForEach(entry => { string resourceKey = (string)entry.Key; if (cache.ResourceStrings.ContainsKey(resourceKey)) cache.ResourceStrings[resourceKey] = (string)(entry.Value ?? ""); else cache.ResourceStrings.Add(resourceKey, (string)(entry.Value ?? "")); }); } ); } public Task LoadRulesOnStartUp(RulesModuleModel module, IRulesCache cache) { return Task.Run ( () => { string moduleName = module.Name.ToLowerInvariant(); RuleSet ruleSet = module.DeserializeRuleSetFile() ?? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.invalidRulesetFormat, moduleName)); cache.RuleEngines.Add(moduleName, new RuleEngine(ruleSet, RulesSerializer.GetValidation(ruleSet))); using IResourceReader reader = new ResourceReader(new MemoryStream(module.ResourceSetFile)); reader.OfType<DictionaryEntry>() .ToList() .ForEach(entry => cache.ResourceStrings.Add((string)entry.Key, (string)entry.Value)); } ); } } }
using System; using System.Collections.Generic; using System.CommandLine; using System.Linq; using ProjectFinder.Manager; using System.IO; namespace ProjectFinder.Command { public class MainCommand : CommandBase { public AddCommand AddCommand { get; } = new AddCommand(); public DeleteCommand DeleteCommand { get; } = new DeleteCommand(); public ListCommand ListCommand { get; } = new ListCommand(); private string alias; public string Alias => alias; private bool globalSearch; public bool GlobalSearch => globalSearch; public sealed override void Execute() { // Solution search mode // In a solution without -g option if (!GlobalSearch && SolutionManager.IsInSolution(Directory.GetCurrentDirectory(), out var manager)) { var path = manager.GetTargetPath(Alias); if (path != null) { Console.WriteLine(path); Environment.Exit(0); } else ReportError("No such project!"); } // Global search mode : // - Out of a solution // - In a solution with -g option else { if (Alias == null) ReportError("At least one alias is required in global search mode"); else if(CacheManager.CachedDirectories.ContainsKey(Alias)) { Console.WriteLine(CacheManager.CachedDirectories[Alias].Path); Environment.Exit(0); } else ReportError("Unrecognized aliases."); } } protected override void ParseCommands(ArgumentSyntax syntax) { syntax.DefineCommand("add", new AddCommand()).Help = "Save a directory path as the aliases."; syntax.DefineCommand("delete", new DeleteCommand()).Help = "Delete directories by their aliases. The full names of the alias are required."; syntax.DefineCommand("list", new ListCommand()).Help = "List all saved directories."; } protected override void ParseParameters(ArgumentSyntax syntax) { syntax.DefineOption("g|global", ref globalSearch, "Force global search"); syntax.DefineParameter("alias", ref alias, "The alias of a directory"); } protected override void ShowResultInfo() { } } }
//namespace OmniGui.Xaml //{ // using System; // using System.Collections.Generic; // using System.Reactive.Disposables; // using System.Reactive.Linq; // using System.Reflection; // using OmniXaml; // public class OmniGuiXamlBuilder : ExtendedObjectBuilder // { // private readonly IDictionary<BindDefinition, IDisposable> bindings = new Dictionary<BindDefinition, IDisposable>(); // public OmniGuiXamlBuilder(IInstanceCreator creator, ObjectBuilderContext objectBuilderContext, // IContextFactory contextFactory) : base(creator, objectBuilderContext, contextFactory) // { // } // protected override void PerformAssigment(Assignment assignment, BuildContext buildContext) // { // var od = assignment.Value as ObserveDefinition; // var bd = assignment.Value as BindDefinition; // if (od != null) // { // BindToObservable(od); // } // else if (bd != null) // { // ClearExistingBinding(bd); // var bindingSubscription = BindToProperty(buildContext, bd); // AddExistingBinding(bd, bindingSubscription); // } // else // { // base.PerformAssigment(assignment, buildContext); // } // } // private void AddExistingBinding(BindDefinition bd, IDisposable subs) // { // bindings.Add(bd, subs); // } // private void ClearExistingBinding(BindDefinition bd) // { // if (bindings.ContainsKey(bd)) // { // bindings[bd].Dispose(); // bindings.Remove(bd); // } // } // private IDisposable BindToProperty(BuildContext buildContext, BindDefinition bd) // { // if (bd.Source == BindingSource.DataContext) // { // return BindToDataContext(bd); // } // else // { // return BindToTemplatedParent(buildContext, bd); // } // } // private static IDisposable BindToTemplatedParent(BuildContext buildContext, BindDefinition bd) // { // var source = (Layout) buildContext.Bag["TemplatedParent"]; // if (bd.TargetFollowsSource) // { // var property = source.GetProperty(bd.SourceProperty); // var sourceObs = source.GetChangedObservable(property).StartWith(source.GetValue(property)); // var targetLayout = (Layout) bd.TargetInstance; // var observer = targetLayout.GetObserver(targetLayout.GetProperty(bd.TargetMember.MemberName)); // sourceObs.Subscribe(observer); // } // return Disposable.Empty; // } // private IDisposable BindToDataContext(BindDefinition bd) // { // return new DataContextSubscription(bd); // } // private static void BindToObservable(ObserveDefinition definition) // { // var targetObj = (Layout) definition.TargetInstance; // var obs = targetObj.GetChangedObservable(Layout.DataContextProperty); // obs.Where(o => o != null) // .Subscribe(context => // { // BindSourceObservableToTarget(definition, context, targetObj); // //BindTargetToSource(definition, context, targetObj); // }); // } // private static void BindSourceObservableToTarget(ObserveDefinition assignment, object context, Layout targetObj) // { // var sourceProp = context.GetType().GetRuntimeProperty(assignment.ObservableName); // var sourceObs = (IObservable<object>) sourceProp.GetValue(context); // var targetProperty = targetObj.GetProperty(assignment.AssignmentMember.MemberName); // var observer = targetObj.GetObserver(targetProperty); // sourceObs.Subscribe(observer); // } // private static void BindTargetToSource(ObserveDefinition assignment, object context, Layout targetObj) // { // var sourceProp = context.GetType().GetRuntimeProperty(assignment.ObservableName); // var sourceObs = (IObserver<object>) sourceProp.GetValue(context); // var targetProperty = targetObj.GetProperty(assignment.AssignmentMember.MemberName); // var observer = targetObj.GetChangedObservable(targetProperty); // observer.Subscribe(sourceObs); // } // } //}
using System; using System.Windows.Forms; using System.Threading; namespace ASCOM.USB_Focus { public partial class Form1 : Form { private ASCOM.DriverAccess.Rotator driver; private Thread updateTextThread; public Form1() { InitializeComponent(); SetUIState(); updateTextThread = new Thread(new ThreadStart(updateCurrentPASteps)); updateTextThread.Start(); } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (IsConnected) driver.Connected = false; Properties.Settings.Default.Save(); } private void buttonChoose_Click(object sender, EventArgs e) { Properties.Settings.Default.DriverId = ASCOM.DriverAccess.Rotator.Choose(Properties.Settings.Default.DriverId); SetUIState(); } private void buttonConnect_Click(object sender, EventArgs e) { if (IsConnected) { driver.Connected = false; } else { driver = new ASCOM.DriverAccess.Rotator(Properties.Settings.Default.DriverId); driver.Connected = true; } SetUIState(); } private void SetUIState() { buttonConnect.Enabled = !string.IsNullOrEmpty(Properties.Settings.Default.DriverId); buttonChoose.Enabled = !IsConnected; buttonConnect.Text = IsConnected ? "Disconnect" : "Connect"; } private bool IsConnected { get { return ((this.driver != null) && (driver.Connected == true)); } } private void updateCurrentPASteps() { string textPA; string textSteps = "d/c"; while (true) { if (IsConnected) { if (driver.IsMoving) { textPA = "Moving"; textSteps = "Moving"; } else { textPA = driver.Position.ToString(); textSteps = driver.Action("PAToStepsPublic",textPA); } } else { textPA = "d/c"; textSteps = "d/c"; } updateCurrentPAText(textPA); updateCurrentStepsText(textSteps); Thread.Sleep(1000); } } private void updateCurrentPAText(string textPA) { if (InvokeRequired) { this.Invoke(new Action<string>(updateCurrentPAText), new object[] { textPA }); return; } currentPA.Text = textPA; } private void updateCurrentStepsText(string textSteps) { if (InvokeRequired) { this.Invoke(new Action<string>(updateCurrentStepsText), new object[] { textSteps }); return; } currentSteps.Text = textSteps; } private void button1_Click(object sender, EventArgs e) { float positionAngle; if (float.TryParse(goToPA.Text, out positionAngle)) { driver.MoveAbsolute(positionAngle); } else { MessageBox.Show("Need a Position Angle!"); } } private void but1c_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(1); } } private void but5c_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(5); } } private void but10c_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(10); } } private void but15c_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(15); } } private void but15ac_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(-15); } } private void but10ac_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(-10); } } private void but5ac_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(-5); } } private void but1ac_Click(object sender, EventArgs e) { if (IsConnected) if (!driver.IsMoving) { driver.Move(-1); } } } }
namespace Kit { public static class DecimalExtensions { public static int CountDecimalDigits(this decimal n) { return n.ToString(System.Globalization.CultureInfo.InvariantCulture) //.TrimEnd('0') uncomment if you don't want to count trailing zeroes .SkipWhile(c => c != '.') .Skip(1) .Count(); } } }
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 ozn_prackt { public partial class traap_ugol : Form { public traap_ugol() { InitializeComponent(); } private void traap_ugol_Load(object sender, EventArgs e) { pictureBox2.Image = Image.FromFile("C:\\Users\\sdd\\source\\repos\\ozn_prackt\\trap_ug.png"); } private void button2_Click(object sender, EventArgs e) { trapecia trap = new trapecia(); double alf = Convert.ToDouble(textBox1.Text); trap.UG(alf); textBox2.Text = Convert.ToString(trap.L); } } }
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore; using ServiceHost.Models; using ServiceHost.Repository; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using ServiceHost.Services; namespace ServiceHost { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMvc(config => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); config.Filters.Add(new AuthorizeFilter(policy)); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_2); services.AddApiVersioning(); services.AddDbContext<ServiceHostContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ServiceHostContext"))); services.AddScoped<IRepository<Country>, BaseRepository<Country>>(); services.AddScoped<IRepository<Currency>, BaseRepository<Currency>>(); services.AddScoped<IAccountRepository, AccountRepository>(); services.AddScoped<IRepository<MetaType>, BaseRepository<MetaType>>(); services.AddScoped<ITransactionRepository, TransactionRepository>(); services.AddScoped<IRepository<GlobalFee>, BaseRepository<GlobalFee>>(); services.AddScoped<IEventlogRepsoitory, EventlogRepository>(); services.AddScoped<IRepository<ContactEmail>, BaseRepository<ContactEmail>>(); services.AddScoped<IRepository<ContactPhone>, BaseRepository<ContactPhone>>(); services.AddScoped<IRepository<ApplicationUser>, BaseRepository<ApplicationUser>>(); services.AddScoped<IRepository<ApplicationRole>, BaseRepository<ApplicationRole>>(); services.AddScoped<IRepository<ApplicationUserRole>, BaseRepository<ApplicationUserRole>>(); services.AddScoped<IInititializeService, InititializeService>(); services.AddScoped<IEventlogService, EventlogService>(); services.AddScoped<IAccountService, AccountService>(); services.AddDefaultIdentity<ApplicationUser>() .AddRoles<ApplicationRole>() .AddEntityFrameworkStores<ServiceHostContext>() .AddDefaultTokenProviders(); JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear(); JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear(); services.AddAuthentication( x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer( x=> { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Token:Key"])), ValidIssuer = Configuration["Token:Issuer"], ValidAudience = Configuration["Token:Audience"], ValidateActor = false, ValidateLifetime = true, ValidateAudience = true, ValidateIssuer = true }; }); services.AddCors(Options => { Options.AddPolicy("CorsPolicy", builderCors => builderCors.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); app.UseAuthentication(); app.UseMvc(); } } }
using LogicBuilder.Expressions.Utils.Strutures; namespace Contoso.Common.Configuration.ExpressionDescriptors { public class OrderByOperatorDescriptor : SelectorMethodOperatorDescriptorBase { public ListSortDirection SortDirection { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using MahApps.Metro.Controls; using System.Data.OleDb; using System.Data; namespace Proyecto_Integrador { /// <summary> /// Lógica de interacción para frmRecargas.xaml /// </summary> public partial class frmRecargas : MetroWindow { /// <summary> /// /// </summary> public frmRecargas() { InitializeComponent(); Conexion = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source='C:\Users\Mondro\Documents\GitHub\PI_3er_Semestre\Proyecto_Integrador\Proyecto_Integrador\BaseDeDatos.accdb'"); cmd = new OleDbCommand("Select Id_Tarjeta, UserNombre, UserApPa, UserApMa, UserFechaNac, UserSaldo FROM Usuario UserNombre", Conexion); //Se crea el comando da = new OleDbDataAdapter(cmd); } OleDbConnection Conexion; OleDbCommand cmd; OleDbDataAdapter da; decimal saldo = 0; //private void Buscar() //{ // OleDbCommand Instruccion = new OleDbCommand("Select * from Usuario where UserNombre Like @Nombre ", Conexion); // Instruccion.Parameters.AddWithValue("@Nombre", Nombre); // DataTable busqueda = new DataTable(); // OleDbDataAdapter data = new OleDbDataAdapter(Instruccion.CommandText, Conexion.ConnectionString); // data.SelectCommand = Instruccion; // data.Fill(busqueda); // dtgBusqueda.ItemsSource = (from row in busqueda.Rows select row); //} /// <summary> /// Busca en la base de datos cuando es por nombre y se le da enter /// </summary> private void TextBox_KeyUp_1(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { string Nombre = txtNombre.Text; Conexion.Open(); DataTable tabla = new DataTable(); // Creamos el objeto Tabla da.Fill(tabla); //Crea la tabla DataView DV = new DataView(tabla); DV.RowFilter = string.Format("UserNombre LIKE '%{0}%'", Nombre); //Filtro para lo que se va a mostrar dtgBusqueda.ItemsSource = DV; Conexion.Close(); } } /// <summary> /// Busca en la base de datos cuando es por ID y se le da enter /// </summary> private void txtID_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { string Num_Tarjeta = txtNombre.Text; Conexion.Open(); DataTable tabla = new DataTable(); // Creamos el objeto Tabla da.Fill(tabla); //Crea la tabla DataView DV = new DataView(tabla); DV.RowFilter = string.Format("Id_Tarjeta LIKE '%{0}%'", Num_Tarjeta); //Filtro para lo que se va a mostrar dtgBusqueda.ItemsSource = DV; Conexion.Close(); } } /// <summary> /// Se hace la actualizacion del registro en la base de datos /// </summary> private void Button_Click_1(object sender, RoutedEventArgs e) { saldo += decimal.Parse(txtCantidad.Text); OleDbCommand actualizar = new OleDbCommand("UPDATE Usuario SET UserSaldo = @UserSaldo WHERE Id_Tarjeta = @Id_Tarjeta ", Conexion); actualizar.Parameters.AddWithValue("@UserSaldo", saldo); actualizar.Parameters.AddWithValue("@Id_Tarjeta", txtID.Text); if (txtCantidad.Text == "") MessageBox.Show("Ingrese una cantidad a abonar"); else { Conexion.Open(); actualizar.ExecuteNonQuery(); Conexion.Close(); if (MessageBox.Show("Desea abonar a otro usuario?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.No) { MessageBox.Show("Gracias, usted regresara al menu."); this.Close(); } else { txtNombre.Clear(); txtID.Clear(); txtCantidad.Clear(); dtgBusqueda.Items.Clear(); } } } /// <summary> /// Se agregan los campos necesarios para generar la recarga /// </summary> private void dtgBusqueda_MouseDoubleClick(object sender, MouseButtonEventArgs e) { DataRowView DR = dtgBusqueda.SelectedItem as DataRowView; txtNombre.Text = DR[1].ToString(); txtID.Text = DR[0].ToString(); saldo = (decimal)DR[5]; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace bitirme.Models { public class otelresim { [Key] public int otelresimId { get; set; } public string otelresimAdi { get; set; } public Nullable<int> otelID { get; set; } public virtual otel otel { get; set; } } }
using Android.App; using Android.Widget; using Android.OS; namespace S03_LayoutsAndBasicUI_3TextViews { [Activity(Label = "S03_LayoutsAndBasicUI_3TextViews", MainLauncher = true)] public class MainActivity : Activity { protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); Button myButton = FindViewById<Button>(Resource.Id.myButton); TextView textView1 = FindViewById<TextView>(Resource.Id.textView1); EditText editText1 = FindViewById<EditText>(Resource.Id.editText1); myButton.Click += delegate { textView1.Text = editText1.Text; editText1.Text = string.Empty; }; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FaceMaker.Classes { class Face { private string[] faceHairArray = new string[4]; private string[] faceEyesArray = new string[5]; private string[] faceNoseArray = new string[4]; private string[] faceMouthArray = new string[5]; private string[] faceChinArray = new string[3]; private int[] currentFace = new int[5]; // Keeps record of current face piece ID for each slot Random faceRandom = new Random(); // Seed random number for SetFaceToRandom() public Face() { SetFaceToBlank(); } // Constructor public void DisplayCurrentFace() { Console.Clear(); for (int i = 0; i < faceHairArray.Length; i++) { Console.WriteLine(faceHairArray[i]); } for (int i = 0; i < faceEyesArray.Length; i++) { Console.WriteLine(faceEyesArray[i]); } for (int i = 0; i < faceNoseArray.Length; i++) { Console.WriteLine(faceNoseArray[i]); } for (int i = 0; i < faceMouthArray.Length; i++) { Console.WriteLine(faceMouthArray[i]); } for (int i = 0; i < faceChinArray.Length; i++) { Console.WriteLine(faceChinArray[i]); } } // Draw the current face public void ChangeFace(int choice) { switch (choice) { case 1: SetFaceToRandom(); break; case 2: NextHair(); break; case 3: NextEyes(); break; case 4: NextNose(); break; case 5: NextMouth(); break; case 6: NextChin(); break; case 7: SetFaceToBlank(); break; } } public void SetFaceToBlank() { SetHair(0); SetEyes(0); SetNose(0); SetMouth(0); SetChin(0); } // Reset to default face features public void SetFaceToRandom() { int randomZeroToFive = faceRandom.Next(0, 5); currentFace[0] = randomZeroToFive; SetHair(randomZeroToFive); randomZeroToFive = faceRandom.Next(0, 5); currentFace[1] = randomZeroToFive; SetEyes(randomZeroToFive); randomZeroToFive = faceRandom.Next(0, 5); currentFace[2] = randomZeroToFive; SetNose(randomZeroToFive); randomZeroToFive = faceRandom.Next(0, 5); currentFace[3] = randomZeroToFive; SetMouth(randomZeroToFive); randomZeroToFive = faceRandom.Next(0, 5); currentFace[4] = randomZeroToFive; SetChin(randomZeroToFive); } // Randomize each feature public void NextHair() { currentFace[0]++; if (currentFace[0] > 5) { currentFace[0] = 0; } SetHair(currentFace[0]); } public void NextEyes() { currentFace[1]++; if (currentFace[1] > 4) { currentFace[1] = 0; } SetEyes(currentFace[1]); } public void NextNose() { currentFace[2]++; if (currentFace[2] > 4) { currentFace[2] = 0; } SetNose(currentFace[2]); } public void NextMouth() { currentFace[3]++; if (currentFace[3] > 4) { currentFace[3] = 0; } SetMouth(currentFace[3]); } public void NextChin() { currentFace[4]++; if (currentFace[4] > 4) { currentFace[4] = 0; } SetChin(currentFace[4]); } public void SetHair(int choice) { switch (choice) { case 0: faceHairArray[0] = " ooo OOO OOO ooo "; faceHairArray[1] = " oOO OOo "; faceHairArray[2] = " oOO OOo "; faceHairArray[3] = " oOO OOo "; break; case 1: faceHairArray[0] = " /=/=/ "; faceHairArray[1] = " /=/=/=/=/=/=/=/=/=/=/=/=/=/ "; faceHairArray[2] = " /=/=/=/=/=/=/=/=/=/=/=/=/=/=/=/ "; faceHairArray[3] = " /=/ /=/ "; break; case 2: faceHairArray[0] = " _______________ "; faceHairArray[1] = " ____/ \\____ "; faceHairArray[2] = " ___/ GO CAVS! \\___ "; faceHairArray[3] = " ___/_________________________________\\___ "; break; case 3: faceHairArray[0] = " ooo OOO OOO ooo "; faceHairArray[1] = " ooO Ooo "; faceHairArray[2] = " ### ### "; faceHairArray[3] = " ###### ###### "; break; case 4: faceHairArray[0] = " ||||||||||||||||||||||||||||||||||||| "; faceHairArray[1] = " ||||||||||||||||||||||||||||||||||||| "; faceHairArray[2] = " ||||||||||||||||||||||||||||||||||||| "; faceHairArray[3] = " ||||||||||||||||||||||||||||||||||||| "; break; case 5: faceHairArray[0] = " _______________ "; faceHairArray[1] = " ____/ \\____ "; faceHairArray[2] = " ___/ Cleveland Browns \\___ "; faceHairArray[3] = " ___/_________________________________\\___ "; break; } } public void SetEyes(int choice) { switch (choice) { case 0: faceEyesArray[0] = " oOO OOo "; faceEyesArray[1] = " oOO OOo "; faceEyesArray[2] = " oOO o o OOo "; faceEyesArray[3] = " oOO OOo "; faceEyesArray[4] = " oOO OOo "; break; case 1: faceEyesArray[0] = " oOO OOo "; faceEyesArray[1] = " oOO |-----| |-----| OOo "; faceEyesArray[2] = " oOO/-------| O |-----------| O |-------\\OOo "; faceEyesArray[3] = " oOO |-----| |-----| OOo "; faceEyesArray[4] = " oOO OOo "; break; case 2: faceEyesArray[0] = " oOO OOo "; faceEyesArray[1] = " oOO \\ / \\ / OOo "; faceEyesArray[2] = " oOO X X OOo "; faceEyesArray[3] = " oOO / \\ / \\ OOo "; faceEyesArray[4] = " oOO OOo "; break; case 3: faceEyesArray[0] = " oOO OOo "; faceEyesArray[1] = " oOO ______ ______ OOo "; faceEyesArray[2] = " oOO | \\ / | OOo "; faceEyesArray[3] = " oOO _|__o__\\_ _/__o__|_ OOo "; faceEyesArray[4] = " oOO OOo "; break; case 4: faceEyesArray[0] = " oOO OOo "; faceEyesArray[1] = " oOO_______.________._x^x_.________._______OOo "; faceEyesArray[2] = " oOO \\ / \\ / OOo "; faceEyesArray[3] = " oOO \\____/ \\____/ OOo "; faceEyesArray[4] = " oOO OOo "; break; } } public void SetNose(int choice) { switch (choice) { case 0: faceNoseArray[0] = " oOO __/ OOo "; faceNoseArray[1] = " oOO __/ OOo "; faceNoseArray[2] = " oOO / OOo "; faceNoseArray[3] = " oOO /_______ OOo "; break; case 1: faceNoseArray[0] = " oOO | | OOo "; faceNoseArray[1] = " oOO | | OOo "; faceNoseArray[2] = " oOO / \\ OOo "; faceNoseArray[3] = " oOO /_o_o_\\ OOo "; break; case 2: faceNoseArray[0] = " oOO OOo "; faceNoseArray[1] = " oOO / \\ OOo "; faceNoseArray[2] = " oOO | O O | OOo "; faceNoseArray[3] = " oOO \\ / OOo "; break; case 3: faceNoseArray[0] = " oOO ___ OOo "; faceNoseArray[1] = " oOO \\ / OOo "; faceNoseArray[2] = " oOO '._:_.' OOo "; faceNoseArray[3] = " oOO OOo "; break; case 4: faceNoseArray[0] = " oOO /-----\\ OOo "; faceNoseArray[1] = " oOO / \\ OOo "; faceNoseArray[2] = " oOO \\/\\___/\\/ OOo "; faceNoseArray[3] = " oOO OOo "; break; } } public void SetMouth(int choice) { switch (choice) { case 0: faceMouthArray[0] = " oOO ____ ____ OOo "; faceMouthArray[1] = " oOO / \\_/ \\ OOo "; faceMouthArray[2] = " oOO >-------------< OOo "; faceMouthArray[3] = " oOO \\___________/ OOo "; faceMouthArray[4] = " oOO OOo "; break; case 1: faceMouthArray[0] = " oOO _ _ _ _ _ OOo "; faceMouthArray[1] = " oOO /|_|_|_|_|_|\\ OOo "; faceMouthArray[2] = " oOO ( _ _ _ _ _ ) OOo "; faceMouthArray[3] = " oOO \\|_|_|_|_|_|/ OOo "; faceMouthArray[4] = " oO OOo "; break; case 2: faceMouthArray[0] = " oOO OOo "; faceMouthArray[1] = " oOO OOo "; faceMouthArray[2] = " oOO __________ OOo "; faceMouthArray[3] = " oOO \\ / \\ / OOo "; faceMouthArray[4] = " oO ' ' OOo "; break; case 3: faceMouthArray[0] = " oOO ///|\\\\\\ OOo "; faceMouthArray[1] = " oOO /////|||\\\\\\\\\\\\ OOo "; faceMouthArray[2] = " oOO //// _____ \\\\\\\\ OOo "; faceMouthArray[3] = " oOO ||| OOo "; faceMouthArray[4] = " oO | OOo "; break; case 4: faceMouthArray[0] = " oOO OOo "; faceMouthArray[1] = " oOO _________ OOo "; faceMouthArray[2] = " oOO / _______ \\ OOo "; faceMouthArray[3] = " oOO /_/ \\_\\ OOo "; faceMouthArray[4] = " oO OOo "; break; } } public void SetChin(int choice) { switch (choice) { case 0: faceChinArray[0] = " oOO OOo "; faceChinArray[1] = " oOO OOo "; faceChinArray[2] = " ooo OOO OOO ooo "; break; case 1: faceChinArray[0] = " oOO OOo "; faceChinArray[1] = " oOO _|_ OOo "; faceChinArray[2] = " ooo O) (O ooo "; break; case 2: faceChinArray[0] = " oOO ' . ' . ' . ' . ' OOo "; faceChinArray[1] = " oOO . ' . ' . OOo "; faceChinArray[2] = " \\ooo'O__'__O'ooo/ "; break; case 3: faceChinArray[0] = " ___ | ___ "; faceChinArray[1] = " \\___ ___|___ ___/ "; faceChinArray[2] = " \\___/ \\___/ "; break; case 4: faceChinArray[0] = " vVVv vVVv "; faceChinArray[1] = " vVVv v vVVv "; faceChinArray[2] = " vvv VVV VVV vvv "; break; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class JointScript : MonoBehaviour { [SerializeField] private SpringJoint posMuscle = null; [SerializeField] private SpringJoint negMuscle = null; [SerializeField] private Renderer jointRender = null; [SerializeField] private Base baseScript = null; [SerializeField] private Edge edgeScript = null; [SerializeField] private Bone boneScript = null; private float A; private float B; private float C; private bool musclesOn; private bool renderersOn; private float initSpring; // Start is called before the first frame update void Awake() { musclesOn = false; renderersOn = false; initSpring = posMuscle.spring; } public void FixedUpdate() { if(musclesOn) { // UpdateMuscles(Mathf.Sin(A * Mathf.Cos(B * Time.fixedTime) + C)); UpdateMuscles(Mathf.Sin(A * Mathf.Cos(2.9f * Time.fixedTime))); } } public void SetSineFactors(Vector3 v) { A = v.x; B = v.y; C = v.z; } public void ToggleMuscle() { musclesOn = !musclesOn; } public void ToggleRenderer() { renderersOn = !renderersOn; if(renderersOn) { edgeScript.ToggleRenderer(); baseScript.ToggleRenderer(); boneScript.ToggleRenderer(); jointRender.enabled = true; } } public void UpdateMuscles(float val) { posMuscle.spring = initSpring + val*initSpring; negMuscle.spring = initSpring - val*initSpring; UpdateJointRender(val); } public Vector3 GetSineFactors() { return new Vector3(A, B, C); } private void UpdateJointRender(float col) { float x = (col + 1) / 2; jointRender.material.color = new Color(x,x,x); } public void SetBoneSize(float length) { boneScript.SetBoneLength(length); } public void ConnectBaseToNode(GameObject baseNode) { baseScript.ConnectToNode(baseNode); } public void ConnectEdgeToNode(GameObject edgeNode) { edgeScript.ConnectToNode(edgeNode); } }
using UnityEngine; using System.Collections.Generic; public static class UniqueIDManager { private static List<int> next_id; static UniqueIDManager() { next_id = new List<int>(); NextGroup(); } public static int NextGroup() { next_id.Add(0); return next_id.Count-1; } public static int NextID() { return next_id[0]++; } public static int NextID(UIDGroup group) { return next_id[group.Value]++; } } public class UID { public int Value { get; private set; } public UID() { Value = UniqueIDManager.NextID(); } public UID(UIDGroup group) { Value = UniqueIDManager.NextID(group); } public override string ToString() { return Value.ToString(); } } public class UIDGroup { public int Value { get; private set; } public UIDGroup() { Value = UniqueIDManager.NextGroup(); } public override string ToString() { return Value.ToString(); } }
using Plus.HabboHotel.Items; namespace Plus.Communication.Packets.Outgoing.Rooms.Engine { internal class ItemUpdateComposer : MessageComposer { public Item Item { get; } public int UserId { get; } public ItemUpdateComposer(Item item, int userId) : base(ServerPacketHeader.ItemUpdateMessageComposer) { Item = item; UserId = userId; } public override void Compose(ServerPacket packet) { WriteWallItem(Item, UserId, packet); } private void WriteWallItem(Item item, int userId, ServerPacket packet) { packet.WriteString(item.Id.ToString()); packet.WriteInteger(item.GetBaseItem().SpriteId); packet.WriteString(item.WallCoord); switch (item.GetBaseItem().InteractionType) { case InteractionType.PostIt: packet.WriteString(item.ExtraData.Split(' ')[0]); break; default: packet.WriteString(item.ExtraData); break; } packet.WriteInteger(-1); packet.WriteInteger((item.GetBaseItem().Modes > 1) ? 1 : 0); packet.WriteInteger(userId); } } }
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 Proje { public partial class Login : Form { public Login() { InitializeComponent(); } private void Login_Load(object sender, EventArgs e) { } private void btn_GirisYap_Click(object sender, EventArgs e) { //kullanıcının giriş yapması try { Giris g = new Giris(); g.Kulad = txt_KuladGiris.Text; g.Sifre = Convert.ToInt32(txt_SifreGiris.Text); g.GirisYap(); GirisEkraniTemizle(); } catch (Exception hata) { MessageBox.Show("Lütfen Alanları Boş Bırakmayın.\nBilgileri Doğru Girdiğinizden Emin Olun."+ hata.Message); } } private void btn_KayitOl_Click(object sender, EventArgs e) { //kullanıcının kayıt olması Kayit k = new Kayit(); k.Ad = txt_AdKayitOl.Text; k.Soyad = txt_SoyadKayitOl.Text; k.Kulad = txt_KuladKayitOl.Text; k.Sifre = Convert.ToInt32(txt_SifreKayitOl.Text); k.TCKimlikNo = Convert.ToInt32(txt_TCKimlikNoKayitOl.Text); k.TelNo = Convert.ToInt32(txt_TelefonNoKayitOl.Text); k.Email = txt_EmailKayitOl.Text; k.Adres = rtxt_AdresKayitOl.Text; k.Para = 0; k.KayitOl(); KayitEkraniTemizle(); } private void GirisEkraniTemizle() { //ekranın güzel gözükmesi için textbox'ları temizle txt_KuladGiris.Text = ""; txt_SifreGiris.Text = ""; } private void KayitEkraniTemizle() { //ekranın güzel gözükmesi için textbox'ları temizle txt_AdKayitOl.Text = ""; txt_SoyadKayitOl.Text = ""; txt_KuladKayitOl.Text = ""; txt_SifreKayitOl.Text = ""; txt_EmailKayitOl.Text = ""; txt_TCKimlikNoKayitOl.Text = ""; txt_TelefonNoKayitOl.Text = ""; rtxt_AdresKayitOl.Text = ""; } } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("TargetAnimUtils2")] public class TargetAnimUtils2 : MonoBehaviour { public TargetAnimUtils2(IntPtr address) : this(address, "TargetAnimUtils2") { } public TargetAnimUtils2(IntPtr address, string className) : base(address, className) { } public void ActivateHierarchy2() { base.method_8("ActivateHierarchy2", Array.Empty<object>()); } public void DeactivateHierarchy2() { base.method_8("DeactivateHierarchy2", Array.Empty<object>()); } public void DestroyHierarchy2() { base.method_8("DestroyHierarchy2", Array.Empty<object>()); } public void FadeIn2(float FadeSec) { object[] objArray1 = new object[] { FadeSec }; base.method_8("FadeIn2", objArray1); } public void FadeOut2(float FadeSec) { object[] objArray1 = new object[] { FadeSec }; base.method_8("FadeOut2", objArray1); } public void KillParticlesInChildren2() { base.method_8("KillParticlesInChildren2", Array.Empty<object>()); } public void PlayAnimation2() { base.method_8("PlayAnimation2", Array.Empty<object>()); } public void PlayAnimationsInChildren2() { base.method_8("PlayAnimationsInChildren2", Array.Empty<object>()); } public void PlayDefaultSound2() { base.method_8("PlayDefaultSound2", Array.Empty<object>()); } public void PlayNewParticles2() { base.method_8("PlayNewParticles2", Array.Empty<object>()); } public void PlayParticles2() { base.method_8("PlayParticles2", Array.Empty<object>()); } public void PlayParticlesInChildren2() { base.method_8("PlayParticlesInChildren2", Array.Empty<object>()); } public void PrintLog2(string message) { object[] objArray1 = new object[] { message }; base.method_8("PrintLog2", objArray1); } public void PrintLogError2(string message) { object[] objArray1 = new object[] { message }; base.method_8("PrintLogError2", objArray1); } public void PrintLogWarning2(string message) { object[] objArray1 = new object[] { message }; base.method_8("PrintLogWarning2", objArray1); } public void SetAlphaHierarchy2(float alpha) { object[] objArray1 = new object[] { alpha }; base.method_8("SetAlphaHierarchy2", objArray1); } public void StopAnimation2() { base.method_8("StopAnimation2", Array.Empty<object>()); } public void StopAnimationsInChildren2() { base.method_8("StopAnimationsInChildren2", Array.Empty<object>()); } public void StopNewParticles2() { base.method_8("StopNewParticles2", Array.Empty<object>()); } public void StopParticles2() { base.method_8("StopParticles2", Array.Empty<object>()); } public void StopParticlesInChildren2() { base.method_8("StopParticlesInChildren2", Array.Empty<object>()); } public GameObject m_Target { get { return base.method_3<GameObject>("m_Target"); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PHNeutral.PackageHandler { /** * Virtual representation of a file in the package. This is the base class for all items in the Package Structure **/ class PackageFile : PackageItem { #region Constants #endregion #region Fields // Windows File System Metadata Collection - this will be all properties windows knows about the file. TODO: Create function to search for property. private FileInfo windowsFileInfo; #endregion Fields #region Constructors // Base File Constructor. Use only for root node as it will generate a new package ID. public PackageFile() { } // For creating a file in the Package. public PackageFile(string packageID, PackageDirectory parentPackageFile, FileInfo _windowsFileInfo) { windowsFileInfo = _windowsFileInfo; ParentItem = parentPackageFile; // GenerateMetadata(packageID); } #endregion #region Delegates #endregion #region Events #endregion #region Properties public FileInfo WindowsFileInfo { get { return windowsFileInfo; } } #endregion Properties #region Methods private void GenerateMetadata(string _packageID) { PackageID = _packageID; ItemID = Guid.NewGuid().ToString("N"); ItemName = windowsFileInfo.Name + windowsFileInfo.Extension; ItemPath = ""; // This will be set by the PackageHandler; WindowsPath = windowsFileInfo.FullName; } // To be used with watch functionality - to be called on filechange event private void UpdateFile() { } #endregion } }
public abstract class CommandKisi { protected ReceiverKisi _receiverKisi; public CommandKisi(ReceiverKisi receiverKisi) { this._receiverKisi = receiverKisi; } public abstract void Execute(); }
using System; using Microsoft.SPOT; using Microsoft.SPOT.Presentation.Media; namespace SimpleFace { public class Painter { private Bitmap bitmap; public Painter(Bitmap Canvas) { bitmap = Canvas; } public int MeasureString(string text, Font font) { if (text == null || text.Trim() == "") return 0; int size = 0; for (int i = 0; i < text.Length; i++) { size += font.CharWidth(text[i]); } return size; } public void PaintCentered(string Text, Font Font, Color Color, int y) { int x, y1 = 0; FindCenter(Text, Font, out x, out y1); bitmap.DrawText(Text, Font, Color, x, y); } public void PaintCentered(string Text, Font Font, Color Color) { int x, y = 0; FindCenter(Text, Font, out x, out y); bitmap.DrawText(Text, Font, Color, x, y); } public void FindCenter(string Text, Font Font, out int x, out int y) { int charWidth = (Font.CharWidth(' ') + Font.CharWidth('0'))/2; int size = Text.Length*charWidth; int center = Device.AgentSize/2; int centerText = size/2 - 2; x = center - centerText; y = center - (Font.Height/2); } public void PaintCentered(byte[] ImageData, Bitmap.BitmapImageType ImageType) { var img = new Bitmap(ImageData, ImageType); int x = (Device.AgentSize / 2) - (img.Width / 2); int y = (Device.AgentSize / 2) - (img.Height / 2); bitmap.DrawImage(x, y, img, 0, 0, img.Width, img.Height); } const int TRANSLATE_RADIUS_SECONDS = 47; const int TRANSLATE_RADIUS_MINUTES = 40; const int TRANSLATE_RADIUS_HOURS = 30; public void DrawMinuteHand(Color color, int thickness, int minute, int second) { int min = (int)((6 * minute) + (0.1 * second)); // Jump to Minute and add offset for 6 degrees over 60 seconds' Point p = PointOnCircle(TRANSLATE_RADIUS_MINUTES, min + (-90), Device.Center); DrawLine(color, thickness, Device.Center, p); } public void DrawSecondHand(Color color, int thickness, int second) { int sec = 6 * second; Point p = PointOnCircle(TRANSLATE_RADIUS_SECONDS, sec + (-90), Device.Center); DrawLine(color, thickness, Device.Center, p); } public void DrawHourHand(Color color, int thickness, int hour, int minute) { int hr = (int)((30 * (hour % 12)) + (0.5 * minute)); // Jump to Hour and add offset for 30 degrees over 60 minutes Point p = PointOnCircle(TRANSLATE_RADIUS_HOURS, hr + (-90), Device.Center); DrawLine(color, thickness, Device.Center, p); } public void DrawLine(Color color, int thickness, Point start, Point end) { bitmap.DrawLine(color, thickness, start.X, start.Y, end.X, end.Y); } private Point PointOnCircle(float radius, float angleInDegrees, Point origin) { return new Point( (int)(radius * System.Math.Cos(angleInDegrees * System.Math.PI / 180F)) + origin.X, (int)(radius * System.Math.Sin(angleInDegrees * System.Math.PI / 180F)) + origin.Y ); } } }
using HouseParty.Client.Contracts.Questions; using System.Collections.Generic; namespace HouseParty.Client.Services.QuestionService { public interface IQuestionService { List<Question> GetQuestions(string userQuestionType); int SubmitQuestion(QuestionInputViewModel viewModel); void SubmitSolution(QuestionUpdateViewModel viewModel); void SubmitShubhiSolution(int questionId); void SubmitAdityaSolution(int questionId); void WontDoThisQuestion(int questionId); int[] GetScore(); } }
using System; using System.Data.OleDb; using System.IO; using System.Xml; using exportXml.Validari; namespace exportXml.Exporturi { public class CAP4c { public static bool make_CAP4cxml(string strIdRol) { try { int codNomenclator=254; string strGosp = strIdRol.Substring(0, strIdRol.Length - 3); if (File.Exists(AppDomain.CurrentDomain.BaseDirectory.ToString() + "XML\\CAP4c\\" + AjutExport.numefisier(strIdRol) + "xml") == true) { Ajutatoare.scrielinie("eroriXML.log", " există deja: " + AjutExport.numefisier(strIdRol) + "xml"); return false; } //siruta-- string strSQL = "SELECT * FROM datgen;"; OleDbCommand cmdDateGenerale = new OleDbCommand(strSQL, BazaDeDate.conexiune); OleDbDataReader drDateGenerale = cmdDateGenerale.ExecuteReader(); if (drDateGenerale.Read() == false){return false;} Sirute datgenSirute=new Sirute(drDateGenerale["localitate"].ToString(), drDateGenerale["judet"].ToString()); if (datgenSirute.Siruta == "" | datgenSirute.SirutaJudet == "" | datgenSirute.SirutaSuperioara == "") { Console.WriteLine(datgenSirute.SirutaJudet+ " " + datgenSirute.SirutaSuperioara + " " + datgenSirute.Siruta); return false; } //-- //baza de date-- strSQL = "SELECT ROL.nrcrt, CAP4c.sup FROM CAP4c LEFT JOIN (SELECT * FROM NOMCAP4c) AS ROL ON CAP4c.NrCrt = ROL.NrCrt WHERE CAP4c.IDROL=\"" + strIdRol + "\" ORDER BY ROL.nrcrt;"; OleDbCommand cmdXML = new OleDbCommand(strSQL, BazaDeDate.conexiune); OleDbDataReader drXML = cmdXML.ExecuteReader(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = false; settings.OmitXmlDeclaration = true; settings.NewLineOnAttributes = true; //-- //DOCUMENT_RAN XmlWriter xmlWriter = XmlWriter.Create(AppDomain.CurrentDomain.BaseDirectory.ToString() + "XML\\CAP4c\\" + strGosp + "xml", settings); xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("DOCUMENT_RAN"); //DOCUMENT_RAN //-- //header xmlWriter.WriteStartElement("HEADER"); //HEADER xmlWriter.WriteStartElement("codXml"); //codXml xmlWriter.WriteAttributeString("value", AjutExport.genereazaGUID()); xmlWriter.WriteEndElement(); //inchid codXml xmlWriter.WriteElementString("dataExport", AjutExport.dataexportxml()); xmlWriter.WriteElementString("indicativ", "ADAUGA_SI_INLOCUIESTE"); xmlWriter.WriteElementString("sirutaUAT", datgenSirute.SirutaSuperioara); xmlWriter.WriteEndElement(); //inchid HEADER //-- //BODY xmlWriter.WriteStartElement("BODY"); //BODY xmlWriter.WriteStartElement("gospodarie"); //gospodarie xmlWriter.WriteAttributeString("identificator", strGosp); xmlWriter.WriteStartElement("anRaportare"); //anRaportare xmlWriter.WriteAttributeString("an", "2020"); xmlWriter.WriteStartElement("capitol_4c"); //capitol xmlWriter.WriteAttributeString("codCapitol", "CAP4c"); xmlWriter.WriteAttributeString("denumire", "Suprafața cultivată cu legume și cartofi în grădinile familiale pe raza localității"); //-- //parcurg-- while (drXML.Read()) { xmlWriter.WriteStartElement("cultura_in_gradini"); //rand xmlWriter.WriteAttributeString("codNomenclator", (codNomenclator+Convert.ToInt32(drXML["nrcrt"].ToString())).ToString() ); xmlWriter.WriteAttributeString("codRand", drXML["nrcrt"].ToString()); switch (drXML["nrcrt"].ToString()) { case "1": xmlWriter.WriteAttributeString("denumire", "Legume în grădini familiale -total (exclusiv sămânţă) (02+03+...+06+08+...+23)"); break; case "2": xmlWriter.WriteAttributeString("denumire", "Varza alba"); break; case "3": xmlWriter.WriteAttributeString("denumire", "Salata verde"); break; case "4": xmlWriter.WriteAttributeString("denumire", "Spanac"); break; case "5": xmlWriter.WriteAttributeString("denumire", "Tomate"); break; case "6": xmlWriter.WriteAttributeString("denumire", "Castraveti"); break; case "7": xmlWriter.WriteAttributeString("denumire", "din care: cornison"); break; case "8": xmlWriter.WriteAttributeString("denumire", "Ardei"); break; case "9": xmlWriter.WriteAttributeString("denumire", "Vinete"); break; case "10": xmlWriter.WriteAttributeString("denumire", "Dovleci"); break; case "11": xmlWriter.WriteAttributeString("denumire", "Dovlecei"); break; case "12": xmlWriter.WriteAttributeString("denumire", "Morcovi"); break; case "13": xmlWriter.WriteAttributeString("denumire", "Telina (radacina)"); break; case "14": xmlWriter.WriteAttributeString("denumire", "Usturoi"); break; case "15": xmlWriter.WriteAttributeString("denumire", "Ceapa"); break; case "16": xmlWriter.WriteAttributeString("denumire", "Sfecla rosie"); break; case "17": xmlWriter.WriteAttributeString("denumire", "Ridichi de luna"); break; case "18": xmlWriter.WriteAttributeString("denumire", "Alte legume radacinoase (hrean, ridichi negre, patrunjel, pastârnac etc.) "); break; case "19": xmlWriter.WriteAttributeString("denumire", "Legume pentru frunze (patrunjel, marar, leustean etc.)"); break; case "20": xmlWriter.WriteAttributeString("denumire", "Mazare pastai"); break; case "21": xmlWriter.WriteAttributeString("denumire", "Fasole pastai"); break; case "22": xmlWriter.WriteAttributeString("denumire", "Porumb zaharat"); break; case "23": xmlWriter.WriteAttributeString("denumire", "Alte legume"); break; case "24": xmlWriter.WriteAttributeString("denumire", "Capsuni"); break; case "25": xmlWriter.WriteAttributeString("denumire", "Plante medicinale si aromatice "); break; case "26": xmlWriter.WriteAttributeString("denumire", "Flori, plante ornamentale si dendrologice"); break; case "27": xmlWriter.WriteAttributeString("denumire", "Cartofi total (28+29+30)"); break; case "28": xmlWriter.WriteAttributeString("denumire", "a) - timpurii si semitimpurii"); break; case "29": xmlWriter.WriteAttributeString("denumire", "b) - de vara"); break; case "30": xmlWriter.WriteAttributeString("denumire", "c) - de toamna"); break; } xmlWriter.WriteStartElement("nrMP"); //nrMP xmlWriter.WriteAttributeString("value",drXML["sup"].ToString()); xmlWriter.WriteEndElement(); //inchid suprafata exprimata diferit xmlWriter.WriteEndElement(); //inchid rand } //-- //-- xmlWriter.WriteEndElement(); //capitol xmlWriter.WriteEndElement(); //anraportare xmlWriter.WriteEndElement(); //gospodarie xmlWriter.WriteEndElement(); //BODY //-- //DOCUMENT_RAN-- xmlWriter.WriteEndElement(); //DOCUMENT_RAN xmlWriter.Close(); drXML.Close(); //-- return true; } catch (System.Exception ex) { Console.WriteLine(AjutExport.numefisier(strIdRol) + "xml " + ex.Message); Ajutatoare.scrielinie("eroriXML.log", AjutExport.numefisier(strIdRol) + "xml " + ex.Message); return false; } } } }
using System; namespace Nmli.CollectionAgnostic { /// <summary> /// Standard LAPACK (http://www.netlib.org/lapack/) /// </summary> /// <typeparam name="AT">Generic array type (eg pointer, managed array, etc)</typeparam> public interface ILapack<AT> { #region Real, Symmetric, Positive-Definite (Cholesky) /// <summary> /// _POTRF computes the Cholesky factorization of a real symmetric positive definite matrix A. /// The factorization has the form /// A = U**T * U, if UpLo = 'U', or /// A = L * L**T, if UpLo = 'L', where U is an upper triangular matrix and L is lower triangular. /// This is the block version of the algorithm, calling Level 3 BLAS. /// </summary> /// <param name="uplo">'U': Upper triangle of A is stored; /// 'L': Lower triangle of A is stored.</param> /// <param name="n">The order of the matrix A. N >= 0.</param> /// <param name="a">On entry, the symmetric matrix A. If UpLo = 'U', the leading /// N-by-N upper triangular part of A contains the upper /// triangular part of the matrix A, and the strictly lower /// triangular part of A is not referenced. If UpLo = 'L', the /// leading N-by-N lower triangular part of A contains the lower /// triangular part of the matrix A, and the strictly upper /// triangular part of A is not referenced. /// /// On exit, if INFO = 0, the factor U or L from the Cholesky /// factorization A = U**T*U or A = L*L**T.</param> /// <param name="lda">The leading dimension of the array A. LDA >= max(1,N).</param> /// <returns>0: successful exit /// negative: if INFO = -i, the i-th argument had an illegal value /// postive: if INFO = i, the leading minor of order i is not /// positive definite, and the factorization could not be completed.</returns> int potrf(UpLo uplo, int n, AT a, int lda); /// <summary> /// _POTRI computes the inverse of a real symmetric positive definite matrix A /// using the Cholesky factorization A = U**T*U or A = L*L**T computed by POTRF. /// </summary> /// <param name="uplo">'U': Upper triangle of A is stored; /// 'L': Lower triangle of A is stored.</param> /// <param name="n">The order of the matrix A. N >= 0.</param> /// <param name="a">On entry, the triangular factor U or L from the /// Cholesky factorization A = U**T*U or A = L*L**T, as computed by DPOTRF. /// On exit, the upper or lower triangle of the (symmetric) inverse of A, /// overwriting the input factor U or L.</param> /// <param name="lda">The leading dimension of the array A. LDA >= max(1,N).</param> /// <returns>0: successful exit /// negative: if INFO = -i, the i-th argument had an illegal value /// postive: if INFO = i, the (i,i) element of the factor U or L is /// zero, and the inverse could not be computed.</returns> int potri(UpLo uplo, int n, AT a, int lda); /// <summary> /// SPOSV computes the solution to a real system of linear equations /// A * X = B, /// where A is an N-by-N symmetric positive definite matrix and X and B /// are N-by-NRHS matrices. /// /// The Cholesky decomposition is used to factor A as /// A = U**T* U, if UPLO = 'U', or /// A = L * L**T, if UPLO = 'L', /// where U is an upper triangular matrix and L is a lower triangular /// matrix. The factored form of A is then used to solve the system of /// equations A * X = B. /// </summary> /// <param name="uplo"> U: Upper triangle of A is stored; /// L: Lower triangle of A is stored.</param> /// <param name="n">The number of linear equations, i.e., the order of the matrix A. N >= 0.</param> /// <param name="nrhs">The number of right hand sides, i.e., the number of columns of the matrix B. NRHS >= 0.</param> /// <param name="a">REAL array, dimension (LDA,N) /// On entry, the symmetric matrix A. If UPLO = 'U', the leading /// N-by-N upper triangular part of A contains the upper /// triangular part of the matrix A, and the strictly lower /// triangular part of A is not referenced. If UPLO = 'L', the /// leading N-by-N lower triangular part of A contains the lower /// triangular part of the matrix A, and the strictly upper /// triangular part of A is not referenced. /// /// On exit, if INFO = 0, the factor U or L from the Cholesky /// factorization A = U**T*U or A = L*L**T.</param> /// <param name="lda">The leading dimension of the array A. LDA >= max(1,N).</param> /// <param name="b">(input/output) REAL array, dimension (LDB,NRHS) /// On entry, the N-by-NRHS right hand side matrix B. /// On exit, if INFO = 0, the N-by-NRHS solution matrix X.</param> /// <param name="ldb">The leading dimension of the array B. LDB >= max(1,N).</param> /// <returns> 0: successful exit /// lt 0: if INFO = -i, the i-th argument had an illegal value /// gt 0: if INFO = i, the leading minor of order i of A is not /// positive definite, so the factorization could not be /// completed, and the solution has not been computed.</returns> int posv(UpLo uplo, int n, int nrhs, AT a, int lda, AT b, int ldb); #endregion #region Linear least-squares int gels(Transpose trans, int m, int n, int nrhs, AT a, int lda, AT b, int ldb, AT work, int lwork); #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief ネットワーク。ダミー。 */ #if USE_PUN #else /** NNetwork */ namespace NNetwork { /** Connect_Auto */ public class Connect_Auto { /** Main */ public bool Main(){return false;} } /** Photon.Pun */ namespace Photon.Pun { /** MonoBehaviourPun */ public class MonoBehaviourPun : UnityEngine.MonoBehaviour { } /** PunRPC */ class PunRPC : System.Attribute { } } } #endif
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace solution1 { public partial class AjouterClient : Form { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString; string requete = null; public AjouterClient() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { ajouterClient(); } private void ajouterClient() { string messageErreur = controlSaisie(); if (messageErreur == null) //pas d'erreur de saisie { requete = "INSERT INTO Client (nom,spécialité,adresse,ville,wilaya,pays,registreDeCommerce,NIF,Téléphone1,Téléphone2,fax,email, etat) VALUES ( '" + tBRaisonSociale.Text + "', '" + tBSpécialité.Text + "', '" + tBAdresse.Text.Replace("'", "''") + "', '" + tBVille.Text + "', '" + tBWilaya.Text + "', '" + tBPays.Text + "', '" + tBRegistreDeCommerce.Text + "', '" + tBNIF.Text + "', '" + tBTél1.Text + "', '" + tBTél2.Text + "', '" + tBFax.Text + "', '" + tBEmail.Text + "','Non supprimé');"; Console.WriteLine(requete); if (MaConnexion.ExecuteUpdate(connectionString, requete) == 1) { MessageBox.Show("Le client est ajouté avec succès", "Opération réussie", MessageBoxButtons.OK, MessageBoxIcon.None); this.Close(); } else { MessageBox.Show("L'insertion a échoué", "Erreur d'insertion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } else { MessageBox.Show(messageErreur, "Saisie incomplète ou erronée", MessageBoxButtons.OK, MessageBoxIcon.Information); } } string controlSaisie() { string messageErreur = null; if (tBRaisonSociale.Text != "") { } else { messageErreur = "Veuillez entrer tous les chapms obligatoires"; } if (tBAdresse.Text != "") { } else { messageErreur = "Veuillez entrer tous les chapms obligatoires"; } // if (tBEmail.Text != "") if (tBRegistreDeCommerce.Text !="") // if (tBTél1.Text !="") { } else { messageErreur = "Veuillez entrer tous les chapms obligatoires"; } return messageErreur; } private void button2_Click(object sender, EventArgs e) { this.Close(); } private void AjouterClient_Load(object sender, EventArgs e) { } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; namespace NetDaemon.Common.Fluent { internal enum FluentActionType { TurnOn, TurnOff, Toggle, SetState, Play, Pause, PlayPause, Stop, Speak, DelayUntilStateChange } /// <summary> /// Actions to execute on entity /// </summary> public interface IAction : IExecuteAsync { /// <summary> /// Use attribute when perform action /// </summary> /// <param name="name">The name of attribute</param> /// <param name="value">The value of attribute</param> IAction WithAttribute(string name, object value); } /// <summary> /// When state change /// </summary> public interface IDelayStateChange { /// <summary> /// When state change from or to a state /// </summary> /// <param name="to">The state change to, or null if any state</param> /// <param name="from">The state changed from or null if any state</param> /// <param name="allChanges">Get all changed, even only attribute changes</param> [SuppressMessage("Microsoft.Naming", "CA1716")] IDelayResult DelayUntilStateChange(object? to = null, object? from = null, bool allChanges = false); /// <summary> /// When state change, using a lambda expression /// </summary> /// <param name="stateFunc">The lambda expression used to track changes</param> IDelayResult DelayUntilStateChange(Func<EntityState?, EntityState?, bool> stateFunc); } /// <summary> /// Represents an entity /// </summary> public interface IEntity : ITurnOff<IAction>, ITurnOn<IAction>, IToggle<IAction>, IStateChanged, ISetState<IAction>, IDelayStateChange { } /// <summary> /// Expressions that ends with execute /// </summary> public interface IExecute { /// <summary> /// Executes the expression /// </summary> void Execute(); } /// <summary> /// Expressions that ends with async execution /// </summary> public interface IExecuteAsync { /// <summary> /// Execute action async /// </summary> Task ExecuteAsync(); } /// <summary> /// Represents a script entity /// </summary> public interface IScript { /// <summary> /// Executes scripts async /// </summary> Task ExecuteAsync(); } /// <summary> /// Represent state change actions /// </summary> [SuppressMessage("Microsoft.Naming", "CA1716")] public interface IState { /// <summary> /// The state has not changed for a period of time /// </summary> /// <param name="timeSpan">Period of time state should not change</param> IState AndNotChangeFor(TimeSpan timeSpan); /// <summary> /// Call a callback function or func expression /// </summary> /// <param name="func">The action to call</param> IExecute Call(Func<string, EntityState?, EntityState?, Task> func); /// <summary> /// Run script /// </summary> /// <param name="entityIds">Ids of the scripts that should be run</param> IExecute RunScript(params string[] entityIds); /// <summary> /// Use entities with lambda expression for further actions /// </summary> /// <param name="func">Lambda expression to filter out entities</param> IStateEntity UseEntities(Func<IEntityProperties, bool> func); /// <summary> /// Use entities from list /// </summary> /// <param name="entities">The entities to perform actions on</param> IStateEntity UseEntities(IEnumerable<string> entities); /// <summary> /// Use entity or multiple entities /// </summary> /// <param name="entityId">Unique id of the entity provided</param> IStateEntity UseEntity(params string[] entityId); } /// <summary> /// Actions you can use when state change /// </summary> public interface IStateAction : IExecute { /// <summary> /// Use attribute when perform action on state change /// </summary> /// <param name="name">The name of attribute</param> /// <param name="value">The value of attribute</param> IStateAction WithAttribute(string name, object value); } /// <summary> /// When state change /// </summary> [SuppressMessage("Microsoft.Naming", "CA1716")] public interface IStateChanged { /// <summary> /// When state change from or to a state /// </summary> /// <param name="to">The state change to, or null if any state</param> /// <param name="from">The state changed from or null if any state</param> /// <param name="allChanges">Get all changed, even only attribute changes</param> IState WhenStateChange(object? to = null, object? from = null, bool allChanges = false); /// <summary> /// When state change, using a lambda expression /// </summary> /// <param name="stateFunc">The lambda expression used to track changes</param> IState WhenStateChange(Func<EntityState?, EntityState?, bool> stateFunc); } /// <summary> /// Track states on entities /// </summary> public interface IStateEntity : ITurnOff<IStateAction>, ITurnOn<IStateAction>, IToggle<IStateAction>, ISetState<IStateAction> { } #region Media, Play, Stop, Pause, PlayPause, Speak /// <summary> /// Generic interface for pause /// </summary> /// <typeparam name="T">Return type of pause operation</typeparam> public interface IPause<T> { /// <summary> /// Pauses entity /// </summary> T Pause(); } /// <summary> /// Generic interface for play /// </summary> /// <typeparam name="T">Return type of play operation</typeparam> public interface IPlay<T> { /// <summary> /// Plays entity /// </summary> T Play(); } /// <summary> /// Generic interface for playpause /// </summary> /// <typeparam name="T">Return type of playpause operation</typeparam> public interface IPlayPause<T> { /// <summary> /// Play/Pause entity /// </summary> T PlayPause(); } /// <summary> /// Generic interface for speak /// </summary> /// <typeparam name="T">Return type of speak operation</typeparam> public interface ISpeak<T> { /// <summary> /// Speak using entity /// </summary> T Speak(string message); } /// <summary> /// Generic interface for stop /// </summary> /// <typeparam name="T">Return type of stop operation</typeparam> [SuppressMessage("Microsoft.Naming", "CA1716")] public interface IStop<T> { /// <summary> /// Stops entity /// </summary> T Stop(); } #endregion Media, Play, Stop, Pause, PlayPause, Speak #region Entities, TurnOn, TurnOff, Toggle /// <summary> /// Generic interface for SetState /// </summary> /// <typeparam name="T">Return type of SetState operation</typeparam> public interface ISetState<T> { /// <summary> /// Set entity state /// </summary> /// <param name="state">The state to set</param> T SetState(dynamic state); } /// <summary> /// Generic interface for Toggle /// </summary> /// <typeparam name="T">Return type of Toggle operation</typeparam> public interface IToggle<T> { /// <summary> /// Toggles entity /// </summary> T Toggle(); } /// <summary> /// Generic interface for TurnOff /// </summary> /// <typeparam name="T">Return type of TurnOff operation</typeparam> public interface ITurnOff<T> { /// <summary> /// Turn off entity /// </summary> T TurnOff(); } /// <summary> /// Generic interface for TurnOn /// </summary> /// <typeparam name="T">Return type of TurnOn operation</typeparam> public interface ITurnOn<T> { /// <summary> /// Turn on entity /// </summary> T TurnOn(); } #endregion Entities, TurnOn, TurnOff, Toggle }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MenuController : MonoBehaviour { GameObject _mainMenu; GameObject _helpPage; GameManager _gameManager; AudioSource _buttonClick; void Start() { _mainMenu = GameObject.FindGameObjectWithTag("MainMenu"); _helpPage = GameObject.FindGameObjectWithTag("HelpPage"); _helpPage.SetActive(false); // neaktyvaus objekto neranda, todel suradus isjungiamas _gameManager = GameObject.FindGameObjectWithTag("GameManager").GetComponent<GameManager>(); _buttonClick = GetComponent<AudioSource>(); } public void MenuButtonClick(int index) { switch (index) { case 0: //print("Clicked button: " + index); // Set difficulty to easy //GameManager.SetDifficulty(GameManager.Difficulty.EASY); _gameManager.StartGame(GameManager.Difficulty.EASY); _mainMenu.SetActive(false); //print("Difficulty set to: " + GameManager.CurrentDifficulty); break; case 1: //print("Clicked button: " + index); // Set difficulty to normal //GameManager.SetDifficulty(GameManager.Difficulty.NORMAL); _gameManager.StartGame(GameManager.Difficulty.NORMAL); _mainMenu.SetActive(false); //print("Difficulty set to: " + GameManager.CurrentDifficulty); break; case 2: //print("Clicked button: " + index); _gameManager.StartGame(GameManager.Difficulty.HARD); _mainMenu.SetActive(false); // Set difficulty to hard //GameManager.SetDifficulty(GameManager.Difficulty.HARD); //print("Difficulty set to: " + GameManager.CurrentDifficulty); break; case 3: //print("Clicked button: " + index); // Show help page _mainMenu.SetActive(false); _helpPage.SetActive(true); break; case 4: //print("Clicked button: " + index); // Close game Application.Quit(); break; case 5: //print("Clicked button: " + index); // Go back to menu _helpPage.SetActive(false); _mainMenu.SetActive(true); break; default: break; } _buttonClick.Play(); } }
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; using System.Text; using System.Threading.Tasks; namespace llcom.Model { class Settings { public event EventHandler MainWindowTop; private string _dataToSend = Properties.Settings.Default.dataToSend; private int _baudRate = Properties.Settings.Default.BaudRate; private bool _autoReconnect = Properties.Settings.Default.autoReconnect; private bool _autoSaveLog = Properties.Settings.Default.autoSaveLog; private bool _showHex = Properties.Settings.Default.showHex; private int _parity = Properties.Settings.Default.parity; private int _timeout = Properties.Settings.Default.timeout; private int _dataBits = Properties.Settings.Default.dataBits; private int _stopBit = Properties.Settings.Default.stopBit; private string _sendScript = Properties.Settings.Default.sendScript; private string _runScript = Properties.Settings.Default.runScript; private bool _topmost = Properties.Settings.Default.topmost; private string _quickData = Properties.Settings.Default.quickData; public static List<string> toSendDatas = new List<string>(); public static void UpdateQuickSend() { toSendDatas.Clear(); JObject jo = (JObject)JsonConvert.DeserializeObject(Tools.Global.setting.quickData); foreach (var i in jo["data"]) { if (i["commit"] == null) i["commit"] = "发送"; if ((bool)i["hex"]) toSendDatas.Add("H" + (string)i["text"]); else toSendDatas.Add("S" + (string)i["text"]); } } public string quickData { get { return _quickData; } set { _quickData = value; Properties.Settings.Default.quickData = value; Properties.Settings.Default.Save(); //更新快捷发送区参数 UpdateQuickSend(); } } public string dataToSend { get { return _dataToSend; } set { _dataToSend = value; Properties.Settings.Default.dataToSend = value; Properties.Settings.Default.Save(); } } public int baudRate { get { return _baudRate; } set { _baudRate = value; Properties.Settings.Default.BaudRate = value; Tools.Global.uart.serial.BaudRate = value; Properties.Settings.Default.Save(); } } public bool autoReconnect { get { return _autoReconnect; } set { _autoReconnect = value; Properties.Settings.Default.autoReconnect = value; Properties.Settings.Default.Save(); } } public bool autoSaveLog { get { return _autoSaveLog; } set { _autoSaveLog = value; Properties.Settings.Default.autoSaveLog = value; Properties.Settings.Default.Save(); } } public bool showHex { get { return _showHex; } set { _showHex = value; Properties.Settings.Default.showHex = value; Properties.Settings.Default.Save(); } } public int parity { get { return _parity; } set { _parity = value; Properties.Settings.Default.parity = value; Tools.Global.uart.serial.Parity = (Parity)value; Properties.Settings.Default.Save(); } } public int timeout { get { return _timeout; } set { _timeout = value; Properties.Settings.Default.timeout = value; Properties.Settings.Default.Save(); } } public int dataBits { get { return _dataBits; } set { _dataBits = value; Properties.Settings.Default.dataBits = value; Tools.Global.uart.serial.DataBits = value; Properties.Settings.Default.Save(); } } public int stopBit { get { return _stopBit; } set { _stopBit = value; Properties.Settings.Default.stopBit = value; Tools.Global.uart.serial.StopBits = (StopBits)value; Properties.Settings.Default.Save(); } } public string sendScript { get { return _sendScript; } set { _sendScript = value; Properties.Settings.Default.sendScript = value; Properties.Settings.Default.Save(); } } public string runScript { get { return _runScript; } set { _runScript = value; Properties.Settings.Default.runScript = value; Properties.Settings.Default.Save(); } } public bool topmost { get { return _topmost; } set { _topmost = value; Properties.Settings.Default.topmost = value; MainWindowTop(value, EventArgs.Empty); Properties.Settings.Default.Save(); } } } }
using UnityEngine; using System.Collections; public class FishEventFunctions : MonoBehaviour { public EventManagement eventController; public ResourceManager resourceManager; public GameObject defaultConversation; public ConversationManager conManager; public ChoicesManager choiceManager; public GameObject failureConversation; // Use this for initialization void Start () { resourceManager = GameObject.FindGameObjectWithTag("Player").GetComponent<ResourceManager>(); choiceManager = GameObject.Find("Choices").GetComponent<ChoicesManager>(); conManager = defaultConversation.GetComponent<ConversationManager>(); eventController = GameObject.FindGameObjectWithTag("EventController").GetComponent<EventManagement>(); } // Update is called once per frame void Update () { } public void fish(){ // random number from 1 to 100 for checking sucess int sucessCheck = Random.Range(1,101); if(sucessCheck > 50) { choiceManager.Continue_Conversation(); resourceManager.food = resourceManager.food + 10 + Random.Range(0,21); } else if(sucessCheck > 0 && sucessCheck <=50) { choiceManager.Change_Conversation(failureConversation.GetComponent<ConversationManager>()); } } public void End() { eventController.EndEvent(); } }
using Android.OS; using Android.Runtime; using Android.Views; using MvvmCross.Binding.Droid.BindingContext; using MvvmCross.Droid.Shared.Attributes; using MvvmCross.Droid.Support.V4; using Tekstomania.Mobile.Core.ViewModels; namespace Tekstomania.Mobile.Droid.Fragments { [MvxFragment(typeof(HomeViewModel), Resource.Id.content_frame)] [Register("tekstomania.fragments.LastViewedFragment")] public class LastViewedFragment : MvxFragment<LastViewedViewModel> { public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { base.OnCreateView(inflater, container, savedInstanceState); var view = this.BindingInflate(Resource.Layout.fragment_lastviewed, null); return view; } public override void OnResume() { base.OnResume(); ViewModel.RefreshData(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using BASTA_dynamics_Userlib_db; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.WindowsAzure.Storage.Table; namespace BastaCRM.CustomerService.Api.Controllers { [Route("api/[controller]")] [Authorize] public class CustomerController : Controller { private readonly ICosmosConnector _customerAccess; public CustomerController(ICosmosConnector customerAccess) { _customerAccess = customerAccess; } // GET api/values [HttpGet] public async Task<IActionResult> Get() { try { var allCustomers = await _customerAccess.GetEmployee(""); return Ok(allCustomers); } catch (Exception ex) { return BadRequest(ex); } } // GET api/values/5 [HttpGet("{id}")] public async Task<IActionResult> Get(int id) { try { var customer = await _customerAccess.GetEmployee(id.ToString()); return Ok(customer); } catch (Exception ex) { return BadRequest(ex); } } // POST api/values [HttpPost] public async Task<IActionResult> Post([FromBody]BASTA_dynamics_Userlib_db.EmployeeObject value) { try { await _customerAccess.SetEmployee(value); return Ok(value); } catch (Exception ex) { return BadRequest(ex); } } // PUT api/values/5 [HttpPut("{id}")] public async Task<IActionResult> Put(int id, [FromBody]EmployeeObject value) { try { await _customerAccess.SetEmployee(value); return Ok(value); } catch (Exception ex) { return BadRequest(ex); } } // DELETE api/values/5 [HttpDelete("{id}")] public async Task<IActionResult> Delete(int id) { try { await _customerAccess.DelEmployee(id.ToString()); return Ok(id); } catch (Exception ex) { return BadRequest(ex); } } } }
using SinavSistemi.DataAccessLayer; using SinavSistemi.Entity; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SinavSistemi.BusinessLogicLayer { public class OgretmenBLL { OgretmenDAL ogretmenDAL; public OgretmenBLL() { ogretmenDAL = new OgretmenDAL(); } public DataTable GetAllItems(OgretmenEntity ogretmen) { return ogretmenDAL.GetAllItems(ogretmen); } public bool GirisKontrolu(string kullaniciAd, string parola) { return ogretmenDAL.GirisKontrolu(kullaniciAd, parola); } } }
namespace AddisonWesley.Michaelis.EssentialCSharp.Chapter03.Listing03_44 { public class Program { public static void Main() {} } }
/// Copyright 2012-2013 Delft University of Technology, BEMNext Lab and contributors /// /// Licensed under the Apache License, Version 2.0 (the "License"); /// you may not use this file except in compliance with the License. /// You may obtain a copy of the License at /// /// http://www.apache.org/licenses/LICENSE-2.0 /// /// Unless required by applicable law or agreed to in writing, software /// distributed under the License is distributed on an "AS IS" BASIS, /// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. /// See the License for the specific language governing permissions and /// limitations under the License. /// using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SustainabilityOpen.Framework { /// <summary> /// Designer entity /// </summary> public class SODesigner : SOBase { // Properties private List<SOPhysicalObject> m_ResultingObjects; /// <summary> /// Constructor /// </summary> /// <param name="name">Name of the designer</param> public SODesigner(string name) : base(name) { this.m_ResultingObjects = new List<SOPhysicalObject>(); } /// <summary> /// Add a physical object to the design solution /// </summary> /// <param name="physicalObject">Physical object to add</param> public void AddObject(SOPhysicalObject physicalObject) { if (this.m_ResultingObjects == null) { this.m_ResultingObjects = new List<SOPhysicalObject>(); } this.m_ResultingObjects.Add(physicalObject); } /// <summary> /// Clears the physical objects from the designers /// </summary> public void ClearObjects() { if (this.m_ResultingObjects == null) { return; } this.m_ResultingObjects.Clear(); } /// <summary> /// Runs the designer. Override this method to make the designer do some work. /// </summary> public virtual void RunDesigner() { } /// <summary> /// Returns all physical objects part of this designer /// </summary> public SOPhysicalObject[] PhysicalObjects { get { return this.m_ResultingObjects.ToArray(); } } } }
// // 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; namespace Dnn.ExportImport.Components.Entities { [Serializable] public class ExportImportSetting { public string SettingName { get; set; } public string SettingValue { get; set; } public bool SettingIsSecure { get; set; } public int CreatedByUserId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using PrimeNumberPrinter.Program.Interfaces; namespace UnitTests.MockClasses { public class FakeInputReader : IUserInput { public string GetUserInput(string prompt) { return "This is working"; } } }
using GameProj.Model; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace GameProj.View { class CharacterView { Texture2D CharacterTexture; CharacterMovement m_charMovement; SpriteBatch spriteBatch; Character character; public Rectangle m_destinationRectangle; private Texture2D m_tileTexture; private Texture2D m_BoxTexture; private Texture2D m_BackTexture; private Texture2D m_SunTexture; private Texture2D m_Tile; private Texture2D m_EnemyLevel2Texture; private Texture2D m_Flag; private SpriteFont lifeSprite; private Model.Model model; public CharacterView(GraphicsDevice GraphicsDevice, ContentManager Content, Model.Model m_model) { spriteBatch = new SpriteBatch(GraphicsDevice); CharacterTexture = Content.Load<Texture2D>("player"); m_BackTexture = Content.Load<Texture2D>("trans"); m_SunTexture = Content.Load<Texture2D>("sun"); m_EnemyLevel2Texture = Content.Load<Texture2D>("angrySun"); m_Tile = Content.Load<Texture2D>("tile1"); m_Flag = Content.Load<Texture2D>("arrow"); m_BoxTexture = Content.Load<Texture2D>("cloud1"); lifeSprite = Content.Load<SpriteFont>("levelTime"); this.model = m_model; character = new Character(); //TODO:Scale camera. //9= currentFrame, 32= spriteWidth, 48= spriteHeight: scale in camera. m_charMovement = new CharacterMovement(CharacterTexture, 9, 32, 48); m_charMovement.Position = new Vector2(100, 350); } public enum Movement { RIGHTMOVE = 0, LEFTMOVE }; public void AnimateRight(float timeElapsedMilliSeconds, Movement movement) { m_charMovement.AnimationSprite(timeElapsedMilliSeconds, movement); } internal void AnimateLeft(float timeElapsedMilliSeconds, Movement movement) { m_charMovement.AnimationSprite(timeElapsedMilliSeconds, movement); } internal void AnimateStill(float timeElapsedMilliSeconds, Movement movement) { m_charMovement.AnimationSprite(timeElapsedMilliSeconds, movement); } internal bool PressedQuit() { return m_charMovement.PlayerPressedQuit(); } internal bool PressedJump() { return m_charMovement.PlayerPressedJump(); } internal bool PressedRight() { return m_charMovement.PlayerPressedRight(); } internal bool PressedLeft() { return m_charMovement.PlayerPressedLeft(); } internal bool PressedRun() { return m_charMovement.PlayerPressedRun(); } /// <summary> /// Draws the level map. /// </summary> /// <param name="viewport"></param> /// <param name="m_camera"></param> /// <param name="level"></param> /// <param name="playerPosition"></param> internal void DrawMap(Viewport viewport, Camera m_camera, Model.Level level, Vector2 playerPosition) { Vector2 viewPortSize = new Vector2(viewport.Width, viewport.Height); float scale = m_camera.GetScale(); spriteBatch.Begin(); for (int x = 0; x < Level.g_levelWidth; x++) { for (int y = 0; y < Level.g_levelHeight; y++) { Vector2 viewPosition = m_camera.GetViewPosition(x, y, viewPortSize); DrawTile(viewPosition.X, viewPosition.Y, level.m_tiles[x, y], scale); } } Vector2 characterViewPosition = m_camera.GetViewPosition(playerPosition.X, playerPosition.Y, viewPortSize); DrawCharacterPos(characterViewPosition, scale); spriteBatch.End(); DrawLife(character); } /// <summary> /// Draws the current life left. /// </summary> /// <param name="character"></param> private void DrawLife(Character character) { Vector2 position = new Vector2(5, 5); int test2 = model.Lifes(); spriteBatch.Begin(); spriteBatch.DrawString(lifeSprite, "Life: " + test2, position, Color.White); spriteBatch.End(); } /// <summary> /// Draws the map tiles. /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="tile"></param> /// <param name="scale"></param> private void DrawTile(float x, float y, Model.Level.Tile tile, float scale) { if (tile == Level.Tile.FILLED) { m_tileTexture = m_BoxTexture; } else if (tile == Level.Tile.SUN) { m_tileTexture = m_SunTexture; } else if (tile == Level.Tile.ENEMY1) { m_tileTexture = m_EnemyLevel2Texture; } else if (tile == Level.Tile.TILE) { m_tileTexture = m_Tile; } else if (tile == Level.Tile.FLAG) { m_tileTexture = m_Flag; } else { m_tileTexture = m_BackTexture; } Rectangle destinationRectangle = new Rectangle((int)x, (int)y, (int)scale, (int)scale); spriteBatch.Draw(m_tileTexture, destinationRectangle, Color.White); } /// <summary> /// Draws the character. /// </summary> /// <param name="characterViewPosition"></param> /// <param name="scale"></param> public void DrawCharacterPos(Vector2 characterViewPosition, float scale) { m_destinationRectangle = new Rectangle((int)(characterViewPosition.X - scale / 2.0f), (int)(characterViewPosition.Y - scale), (int)scale, (int)scale); spriteBatch.Draw(CharacterTexture, m_destinationRectangle, m_charMovement.SourceRect, Color.White); } } }
using System; using System.Threading; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace OmniSharp.Extensions.JsonRpc { public class DelegatingRequestHandler<T, TResponse> : IJsonRpcRequestHandler<DelegatingRequest<T>, JToken> { private readonly Func<T, CancellationToken, Task<TResponse>> _handler; private readonly ISerializer _serializer; public DelegatingRequestHandler(ISerializer serializer, Func<T, CancellationToken, Task<TResponse>> handler) { _handler = handler; _serializer = serializer; } public async Task<JToken> Handle(DelegatingRequest<T> request, CancellationToken cancellationToken) { var response = await _handler.Invoke(request.Value.ToObject<T>(_serializer.JsonSerializer), cancellationToken).ConfigureAwait(false); return JToken.FromObject(response, _serializer.JsonSerializer); } } public class DelegatingRequestHandler<T> : IJsonRpcRequestHandler<DelegatingRequest<T>, JToken> { private readonly Func<T, CancellationToken, Task> _handler; private readonly ISerializer _serializer; public DelegatingRequestHandler(ISerializer serializer, Func<T, CancellationToken, Task> handler) { _handler = handler; _serializer = serializer; } public async Task<JToken> Handle(DelegatingRequest<T> request, CancellationToken cancellationToken) { await _handler.Invoke(request.Value.ToObject<T>(_serializer.JsonSerializer), cancellationToken).ConfigureAwait(false); return JValue.CreateNull(); } } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_RenderMode : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.RenderMode"); LuaObject.addMember(l, 0, "ScreenSpaceOverlay"); LuaObject.addMember(l, 1, "ScreenSpaceCamera"); LuaObject.addMember(l, 2, "WorldSpace"); LuaDLL.lua_pop(l, 1); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // #region Usings using DotNetNuke.Collections.Internal; #endregion namespace DotNetNuke.ComponentModel { internal class ComponentBuilderCollection : SharedDictionary<string, IComponentBuilder> { internal IComponentBuilder DefaultBuilder { get; set; } internal void AddBuilder(IComponentBuilder builder, bool setDefault) { if (!ContainsKey(builder.Name)) { this[builder.Name] = builder; if (setDefault && DefaultBuilder == null) { DefaultBuilder = builder; } } } } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; using BlockchainAppAPI.Models.Configuration; namespace BlockchainAppAPI.Controllers.Configuration { [Authorize] [Route("api/NavMenu")] public class NavigationMenuController: Controller { // GET api/NavMenu [HttpGet] [Route("")] public async Task<JArray> GetNavigationMenu() { return await Task.FromResult<JArray>( JArray.FromObject(new [] { new { path = "/", name = "Home", icon = "home" }, new { path = "/view/patent/test page?application=F19F133B-FCA1-4348-84DF-471DC74E1981", name = "Submittal Page", icon = "edit" }, new { path = "/demo/reportWizard", name = "Report Wizard", icon = "chart-bar" }, new { path = "/chart-builder", name = "Chart Builder", icon = "chart-bar" }, new { path = "/demo/search", name = "Search All", icon = "search" } }) ); } } }
//============================================================================= // // Copyright (c) 2017 QUALCOMM Technologies Inc. // All Rights Reserved. // //============================================================================== #if UNITY_EDITOR using UnityEngine; using System.Collections; using UnityEditor; [CustomEditor(typeof(Q3DAudioSource))] [CanEditMultipleObjects] public class Q3DAudioSourceEditor : Editor { [MenuItem("GameObject/Audio/Q3DAudioSource")] static void CreateQ3DAudioSource() { string Q3DAudioSource = "Q3DAudioSource"; GameObject go = new GameObject(Q3DAudioSource); Undo.RegisterCreatedObjectUndo(go, "Created " + Q3DAudioSource);//this must be done before adding the component for undo to work! go.AddComponent<AudioSource>(); go.AddComponent<Q3DAudioSource>(); } [MenuItem("GameObject/Audio/Q3DTools/AudioSourcesToQ3DAudioSources")] static void AudioSourcesToQ3DAudioRooms() { string Q3DAudioSource = "Q3DAudioSource"; AudioSource[] audioSources = Q3DAudioManager.FindObjectsOfTypeAllWrapper<AudioSource>(); foreach (AudioSource audioSource in audioSources) { if (!audioSource.GetComponent<Q3DAudioSource>()) { Undo.RegisterCreatedObjectUndo(audioSource, "Created " + Q3DAudioSource);//this must be done before adding the component for undo to work! audioSource.gameObject.AddComponent<Q3DAudioSource>(); } } } SerializedProperty mGainSerializedProperty, mDistanceRolloffOverrideAudioSourcesRangeSerializedProperty, mDistanceRolloffMinSerializedProperty, mDistanceRolloffMaxSerializedProperty, mDistanceRolloffModelSerializedProperty; void OnEnable() { mGainSerializedProperty = serializedObject.FindProperty("mGain"); mDistanceRolloffOverrideAudioSourcesRangeSerializedProperty = serializedObject.FindProperty("mDistanceRolloffOverrideAudioSourcesRange"); mDistanceRolloffMinSerializedProperty = serializedObject.FindProperty("mDistanceRolloffMin"); mDistanceRolloffMaxSerializedProperty = serializedObject.FindProperty("mDistanceRolloffMax"); mDistanceRolloffModelSerializedProperty = serializedObject.FindProperty("mDistanceRolloffModel"); } private void DistanceRolloffRangeValuesGUI(Q3DAudioSource q3dAudioSource) { mDistanceRolloffOverrideAudioSourcesRangeSerializedProperty.boolValue = EditorGUILayout.Toggle( new GUIContent ( "Distance Rolloff Range Override AudioSource", "If true, then the Q3DAudioSource will have its own distance rolloff min/max distances; otherwise it will inherit its underlying AudioSource's values" ), q3dAudioSource.DistanceRolloffOverrideAudioSourcesRange); if (!q3dAudioSource.DistanceRolloffOverrideAudioSourcesRange) { GUI.enabled = false; } float mDistanceRolloffMinSerializedPropertyFloatValue = EditorGUILayout.FloatField( new GUIContent ( "Distance Rolloff Minimum", "If the listener is this far away (in meters) from the sound then distance rolloff will not attenuate the sound"//see #Q3DAudioSourceInSync ), q3dAudioSource.DistanceRolloffOverrideAudioSourcesRange ? q3dAudioSource.DistanceRolloffMin : q3dAudioSource.mAudioSource.minDistance); float mDistanceRolloffMaxSerializedPropertyFloatValue = EditorGUILayout.FloatField( new GUIContent ( "Distance Rolloff Maximum", "If the listener is this far away (in meters) from the sound then distance rolloff will attenuate the sound to silence"//see #Q3DAudioSourceInSync ), q3dAudioSource.DistanceRolloffOverrideAudioSourcesRange ? q3dAudioSource.DistanceRolloffMax : q3dAudioSource.mAudioSource.maxDistance); //duplicate range enforcement logic, since Unity's serialization code can only reference raw datafields, not C# get/set properties Q3DAudioSource.DistanceRolloffEnforceRange( ref mDistanceRolloffMinSerializedPropertyFloatValue, ref mDistanceRolloffMaxSerializedPropertyFloatValue); mDistanceRolloffMinSerializedProperty.floatValue = mDistanceRolloffMinSerializedPropertyFloatValue; mDistanceRolloffMaxSerializedProperty.floatValue = mDistanceRolloffMaxSerializedPropertyFloatValue; if (!q3dAudioSource.DistanceRolloffOverrideAudioSourcesRange) { GUI.enabled = true; } } public override void OnInspectorGUI() { Q3DAudioSource q3dAudioSource = (Q3DAudioSource)target; q3dAudioSource.InitializeAudioSource();//maintain invariant of Q3DAudioSource accessing its underlying AudioSource AudioSource audioSource = q3dAudioSource.mAudioSource; int numChannels = (audioSource && audioSource.clip) ? audioSource.clip.channels : 0; bool isObjectSound = Q3DAudioSource.IsSoundObject(numChannels); bool isSoundfield = Q3DAudioSource.IsFirstOrSecondOrderAmbisonic(numChannels); Q3DAudioSource[] q3dAudioSources = q3dAudioSource.GetComponents<Q3DAudioSource>(); AudioSource[] audioSources = q3dAudioSource.GetComponents<AudioSource>(); Q3DAudioSource.LogIfQ3DAudioSourceNumIsNotCorrect(q3dAudioSources.Length, audioSources.Length, q3dAudioSource.gameObject.name); if (audioSource) { if (audioSource) { GUI.enabled = false; string takenFromUnderlyingAudioSource = "Taken from underlying AudioSource"; { EditorGUILayout.TextField( new GUIContent ( "AudioClip", takenFromUnderlyingAudioSource ), audioSource.clip ? audioSource.clip.name : "None" ); EditorGUILayout.Toggle( new GUIContent ( "Mute", takenFromUnderlyingAudioSource ), audioSource.mute ); if(isObjectSound) { #if !UNITY_5 EditorGUILayout.Toggle( new GUIContent ( "Spatialize Post Effects", takenFromUnderlyingAudioSource ), audioSource.spatializePostEffects ); #endif//#if !UNITY_5 EditorGUILayout.Toggle( new GUIContent ( "Bypass Effects", takenFromUnderlyingAudioSource ), audioSource.bypassEffects ); } EditorGUILayout.Toggle( new GUIContent ( "Play On Awake", takenFromUnderlyingAudioSource ), audioSource.playOnAwake ); EditorGUILayout.Toggle( new GUIContent ( "Loop", takenFromUnderlyingAudioSource ), audioSource.loop ); EditorGUILayout.IntField( new GUIContent ( "Priority", takenFromUnderlyingAudioSource ), audioSource.priority ); EditorGUILayout.FloatField( new GUIContent ( "Volume", takenFromUnderlyingAudioSource ), audioSource.volume ); EditorGUILayout.FloatField( new GUIContent ( "Pitch", takenFromUnderlyingAudioSource ), audioSource.pitch ); } GUI.enabled = true; } if (isObjectSound || isSoundfield) { /* #Q3DAudioSourceInSync: keep GUIContent.tooltip text in sync with the description strings in * Q3DAudioPlugin.cpp:InternalRegisterEffectDefinitionSoundShared() */ mGainSerializedProperty.floatValue = EditorGUILayout.Slider(new GUIContent ( "Gain", "Linear volume attenuation; 0 means silence"//see #Q3DAudioSourceQ3DAudioSourceInSync ), mGainSerializedProperty.floatValue, Q3DAudioSource.GainMin, Q3DAudioSource.GainMax); if (isSoundfield) { EditorGUILayout.LabelField("SoundField (First Order Ambisonics)", "4 channels found"); } else if (isObjectSound) { DistanceRolloffRangeValuesGUI(q3dAudioSource); GUIContent[] distanceRolloffOptions = new GUIContent[] { //keep in sync with Q3DAudioSource.vr_audio_distance_rolloff_model new GUIContent("Logarithmic", "distance attenuation follows a curve that loses roughly 80% of the sound's volume when " + "distanceFromSound is roughly 15% of the way from minDistance to maxDistance, and loses " + "roughly 90% of the sound's volume when distanceFromSound is roughly 28% of the way from " + "minDistance to maxDistance, and gradually loses the rest of the sound's remaining 10% of " + "volume as distanceFromSound approaches maxDistance"), new GUIContent("Linear", "distanceAttenuation = 1 - (distanceFromSound - min)/(max-min)"), new GUIContent("None", "Distance rolloff never attenuates this sound") }; mDistanceRolloffModelSerializedProperty.intValue = EditorGUILayout.Popup( new GUIContent ( "Distance Rolloff Interpolation", "If the listener's distance from the sound is between the maximum and minimum limits, then distance rolloff will attenuate the sound according to this function"//see #Q3DAudioSourceInSync ), (int)q3dAudioSource.DistanceRolloffModel, distanceRolloffOptions ); EditorGUILayout.LabelField("SoundObject", "1 channel found"); } } else { EditorGUILayout.LabelField("Disabled", "AudioSource's clip does not have 1, 4 or 9 channels, so it can't be for a sound object, first-order-ambisonics soundfield or second-order-ambisonics soundfield!"); } serializedObject.ApplyModifiedProperties(); } else { EditorGUILayout.LabelField("Disabled", "Must be placed on a GameObject that has an AudioSource, but no AudioSource is found"); } } } #endif//#if UNITY_EDITOR
using System; using OpenTK; namespace Calcifer.Engine.Particles.Emitters { /// <summary> /// Basic point emitter, spreads particles randomly /// </summary> public class PointEmitter : IEmitter { private class Behavior : IBehavior { private PointEmitter parent; public Behavior(PointEmitter parent) { this.parent = parent; } public void Update(Particle p, float time) { p.Force = parent.Position - p.Position; } } private Random random = new Random(); private IBehavior behavior; /// <summary> /// Particles lifetime /// </summary> public float Lifetime { get; set; } /// <summary> /// Particles per second output of this emitter /// </summary> public float Intensity { get; set; } /// <summary> /// Maximum particle velocity /// </summary> public float MaxVelocity { get; set; } /// <summary> /// Emitter position /// </summary> public Vector3 Position { get; set; } private ParticlePool pool; public void SetPool(ParticlePool p) { pool = p; } private float cachedTime; public PointEmitter() { behavior = new Behavior(this); } public void Update(float time) { cachedTime += time; var genCount = (int) (cachedTime*Intensity); if (genCount <= 0) return; cachedTime -= genCount/Intensity; for (var i = 0; i < genCount; i++) { var p = pool.GetNew(); p.Position = Position; p.Behavior = behavior; p.TTL = (float) (Lifetime * (1f - 0.5f * random.NextDouble())); var phi = random.NextDouble() * 2f * Math.PI; var rho = (float)(1f - 0.5f * random.NextDouble()) * MaxVelocity; p.Velocity = new Vector3((float)Math.Sin(phi), (float)Math.Cos(phi), 0f) * rho; p.Rotation = 0f; p.AngularVelocity = 0f; } } } }
using System; using System.Collections.Generic; using System.Net.Mail; using System.Text.RegularExpressions; using StructureMap; using System.Linq; using System.Data.Linq; using SubSonic.Security; using SubSonic.Extensions; namespace Pes.Core.Impl { public class Email : IEmail { string TO_EMAIL_ADDRESS; string FROM_EMAIL_ADDRESS; private IConfiguration _configuration; private IUserSession _userSession; private IEmailService _emailService; private IAlertService _alertService; private IMessageService _messageService; public Email() { _configuration = ObjectFactory.GetInstance<IConfiguration>(); _alertService = ObjectFactory.GetInstance<IAlertService>(); _userSession = ObjectFactory.GetInstance<IUserSession>(); _emailService = ObjectFactory.GetInstance<IEmailService>(); TO_EMAIL_ADDRESS = _configuration.ToEmailAddress; FROM_EMAIL_ADDRESS = _configuration.FromEmailAddress; } public void SendNewMessageNotification(Account sender, string ToEmail) { foreach (string s in ToEmail.Split(new char[] { ',', ';' })) { string message = sender.FirstName + " " + sender.LastName + " bạn có một tin nhấn trên " + _configuration.SiteName + "! Xin vui lòng đăng nhập vào <a href='http://tieuhoc.net'>" + _configuration.SiteName + "</a> để xem.<HR>"; SendEmail(s, "", "", sender.FirstName + " " + sender.LastName + " bạn có một tin nhắn từ " + _configuration.SiteName + "!", message); } } public string SendInvitations(Account sender, string ToEmailArray, string Message) { string resultMessage = Message; foreach (string s in ToEmailArray.Split(new char[] { ',', ';' })) { FriendInvitation friendInvitation = new FriendInvitation(); friendInvitation.AccountID = sender.AccountID; friendInvitation.Email = s; friendInvitation.GUID = Guid.NewGuid(); friendInvitation.BecameAccountID = 0; FriendInvitation.SaveFriendInvitation(friendInvitation); //add alert to existing users alerts Account account = Account.GetAccountByEmail(s); if (account != null) { _alertService.AddFriendRequestAlert(_userSession.CurrentUser, account, friendInvitation.GUID, Message); } //CHAPTER 6 //TODO: MESSAGING - if this email is already in our system add a message through messaging system //if(email in system) //{ // add message to messaging system //} //else //{ // send email SendFriendInvitation(s, sender.FirstName, sender.LastName, friendInvitation.GUID.ToString(), Message); //send into mailbox Message = sender.FirstName + " " + sender.LastName + "Muốn kết bạn với bạn!<HR><a href=\"" + _configuration.RootURL + "Friends/ConfirmFriendInSite.aspx?InvitationKey=" + friendInvitation.GUID.ToString() + "\">" + _configuration.RootURL + "Friends/ConfirmFriendInSite.aspx?InvitationKey=" + friendInvitation.GUID.ToString() + "</a><HR>" + Message; Messages m = new Messages(); m.Body = Message; m.Subject = "Thư mời kết bạn"; m.CreateDate = DateTime.Now; m.MessageTypeID = (int)MessageTypes.FriendRequest; m.SentByAccountID = _userSession.CurrentUser.AccountID; m.MessageID = 0; m.Save(); Int64 messageID = m.MessageID; MessageRecipient sendermr = new MessageRecipient(); sendermr.AccountID = _userSession.CurrentUser.AccountID; sendermr.MessageFolderID = (int)MessageFolders.Sent; sendermr.MessageRecipientTypeID = (int)MessageRecipientTypes.TO; sendermr.MessageID = messageID; sendermr.MessageStatusTypeID = (int)MessageStatusTypes.Unread; sendermr.MessageRecipientID = 0; sendermr.Save(); Account toAccount = Account.GetAccountByEmail(s); if (toAccount != null) { MessageRecipient mr = new MessageRecipient(); mr.AccountID = toAccount.AccountID; mr.MessageFolderID = (int)MessageFolders.Inbox; mr.MessageID = messageID; mr.MessageRecipientTypeID = (int)MessageRecipientTypes.TO; mr.MessageRecipientID = 0; mr.MessageStatusTypeID = 1; mr.Save(); //_email.SendNewMessageNotification(toAccount, toAccount.Email); } //} resultMessage += "• " + s + "<BR>"; } return resultMessage; } //CHAPTER 5 public List<string> ParseEmailsFromText(string text) { List<string> emails = new List<string>(); string strRegex = @"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"; Regex re = new Regex(strRegex, RegexOptions.Multiline); foreach (Match m in re.Matches(text)) { string email = m.ToString(); if (!emails.Contains(email)) emails.Add(email); } return emails; } //CHAPTER 5 public void SendFriendInvitation(string toEmail, string fromFirstName, string fromLastName, string GUID, string Message) { Message = fromFirstName + " " + fromLastName + "đã mời gia nhập vào " + _configuration.SiteName + "!<HR><a href=\"" + _configuration.RootURL + "Friends/ConfirmFriendshipRequest.aspx?InvitationKey=" + GUID + "\">" + _configuration.RootURL + "Friends/ConfirmFriendshipRequest.aspx?InvitationKey=" + GUID + "</a><HR>" + Message; SendEmail(toEmail, "", "", fromFirstName + " " + fromLastName + " có một thư mời gia nhập vào " + _configuration.SiteName + "!", Message); } public void SendPasswordReminderEmail(string To, string EncryptedPassword, string Username) { string Message = "mật khẩu: " + Cryptography.Decrypt(EncryptedPassword, Username); SendEmail(To, "", "", "Mật khẩu", Message); } public void SendEmailAddressVerificationEmail(string Username, string To) { string msg = "Nhấn vào liên kết bên dưới để chứng thực tài khoản.<BR><BR>" + "<a href=\"" + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a=" + Username.Encrypt("verify") + "\">" + _configuration.RootURL + "Accounts/VerifyEmail.aspx?a=" + Username.Encrypt("verify") + "</a>"; SendEmail(To, "", "", "Tài khoản đã được tạo! Yêu cầu bạn chứng thực bằng Email.", msg); } public void SendEmail(string From, string Subject, string Message) { MailMessage mm = new MailMessage(From, TO_EMAIL_ADDRESS); mm.Subject = Subject; mm.Body = Message; _emailService.Send(mm); } public void SendEmail(string To, string CC, string BCC, string Subject, string Message) { MailMessage mm = new MailMessage(FROM_EMAIL_ADDRESS, To); if (!string.IsNullOrEmpty(CC)) mm.CC.Add(CC); if (!string.IsNullOrEmpty(BCC)) mm.Bcc.Add(BCC); mm.Subject = Subject; mm.Body = Message; mm.IsBodyHtml = true; _emailService.Send(mm); } public void SendEmail(string[] To, string[] CC, string[] BCC, string Subject, string Message) { MailMessage mm = new MailMessage(); foreach (string to in To) { mm.To.Add(to); } foreach (string cc in CC) { mm.CC.Add(cc); } foreach (string bcc in BCC) { mm.Bcc.Add(bcc); } mm.From = new MailAddress(FROM_EMAIL_ADDRESS); mm.Subject = Subject; mm.Body = Message; mm.IsBodyHtml = true; _emailService.Send(mm); } public void SendIndividualEmailsPerRecipient(string[] To, string Subject, string Message) { foreach (string to in To) { MailMessage mm = new MailMessage(FROM_EMAIL_ADDRESS, to); mm.Subject = Subject; mm.Body = Message; mm.IsBodyHtml = true; _emailService.Send(mm); } } } }
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the source repository root for license information. using System; using System.IO; using System.Linq; using Vipr.T4TemplateWriter.Settings; using Vipr.T4TemplateWriter.TemplateProcessor; using Vipr.T4TemplateWriter; using Vipr.Core.CodeModel; namespace Vipr.T4TemplateWriter.Output { public class JavaPathWriter : PathWriterBase { public override String WritePath(TemplateFileInfo template, String entityTypeName) { var theNamespace = CreateNamespace(template.TemplateType.ToString().ToLower()); var namespacePath = CreatePathFromNamespace(theNamespace); var fileName = TransformFileName(template, entityTypeName); String filePath = Path.Combine(namespacePath, fileName); return filePath; } private string CreateNamespace(string folderName) { var @namespace = Model.GetNamespace(); var prefix = ConfigurationService.Settings.NamespacePrefix; if (String.IsNullOrEmpty(ConfigurationService.Settings.NamespaceOverride)) { if (string.IsNullOrEmpty(folderName)) { return string.IsNullOrEmpty(prefix) ? @namespace : string.Format("{0}.{1}", prefix, @namespace); } return string.IsNullOrEmpty(prefix) ? string.Format("{0}.{1}", @namespace, folderName) : string.Format("{0}.{1}.{2}", prefix, @namespace, folderName); } @namespace = ConfigurationService.Settings.NamespaceOverride; return folderName != "model" ? string.Format("{0}.{1}", @namespace, folderName) : @namespace; } private string CreatePathFromNamespace(string @namespace) { var splittedPaths = @namespace.Split('.'); var destinationPath = splittedPaths.Aggregate(string.Empty, (current, path) => current + string.Format("{0}{1}", path, Path.DirectorySeparatorChar)); return destinationPath; } } }
// LE TON NANG - 20194339 using System; using System.Collections.Generic; using System.Windows.Forms; using DTO; using BUS; namespace GUI { public partial class frmThongKeKhachHang : Form { public frmThongKeKhachHang() { InitializeComponent(); } private void bunifuDataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void frmThongKeKhachHang_Load(object sender, EventArgs e) { List<KhachHangDTO> khachHangs = new List<KhachHangDTO>(); khachHangs = KhachHangBUS.Instance.LayDanhSachKhachHang(); dataKhachHang.Rows.Add(khachHangs.Count); for(int i = 0; i < khachHangs.Count; i++) { dataKhachHang.Rows[i].Cells[0].Value = khachHangs[i].MaKhachHang; dataKhachHang.Rows[i].Cells[1].Value = khachHangs[i].Ten; dataKhachHang.Rows[i].Cells[2].Value = khachHangs[i].DiaChi; dataKhachHang.Rows[i].Cells[3].Value = khachHangs[i].MaGianHang; dataKhachHang.Rows[i].Cells[4].Value = khachHangs[i].ThoiGianBatDauThue.Day + "/" + khachHangs[i].ThoiGianBatDauThue.Month + "/" + khachHangs[i].ThoiGianBatDauThue.Year; dataKhachHang.Rows[i].Cells[5].Value = khachHangs[i].ThoiGianKetThucThue.Day + "/" + khachHangs[i].ThoiGianKetThucThue.Month + "/" + khachHangs[i].ThoiGianKetThucThue.Year; dataKhachHang.Rows[i].Cells[6].Value = khachHangs[i].TienDatCoc; } } } }
using System; using System.Linq; using System.Text.Json; namespace csharp { public static class Examples { class Person { public string FirstName { get; set; } public string LastName { get; set; } public DateTime DateOfBirth { get; set; } } public static void Projection() { var persons = new[] { new Person{ FirstName="Alice", LastName="Smith", DateOfBirth = new DateTime(2000,12,12) }, new Person{ FirstName="Bob", LastName="Green", DateOfBirth = new DateTime(2001,10,10) } }; var names = from p in persons select new { Name = p.FirstName }; foreach (var n in names) Console.WriteLine(n); } /// /// This would require a custom converter to insantiate an anonymous type /// A similar one that is in FSharp example public static void Deserialization() { var input = @" { ""success"": true, ""message"" : ""Processed!"", ""code"" : 0, ""id"": ""89e8f9a1-fedb-440e-a596-e4277283fbcf"" }"; T Deserialize<T>(T template) => JsonSerializer.Deserialize<T>(input); var result = Deserialize(template: new { success = false, id = Guid.Empty }); if (result.success) Console.WriteLine(result.id); else throw new Exception("Error"); } public static void CopyAndUpdate() { var dob = new DateTime(2000, 12, 12); var data = new { FirstName = "Alice", LastName = "Smith", DateOfBirth = dob }; Console.WriteLine(new { data.FirstName, LastName = "Jones", data.DateOfBirth }); } public static void StructuralEquality() { var dob = new DateTime(2000, 12, 12); var r1 = new { FirstName = "Alice", LastName = "Smith", DateOfBirth = dob }; var r2 = new { FirstName = "Alice", LastName = "Smith", DateOfBirth = dob }; Console.WriteLine($"Referential equality: {nameof(r1)} == {nameof(r2)} : {r1 == r2}"); Console.WriteLine($"Structural equality: {nameof(r1)}.Equals({nameof(r2)}) : {r1.Equals(r2)}"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using UberFrba.Abm_Cliente; namespace UberFrba.Facturacion { public partial class GrillaCliente_Facturacion : Form { public Facturacion formularioFacturacion; public GrillaCliente_Facturacion(Facturacion formulario) { InitializeComponent(); this.formularioFacturacion = formulario; } private Boolean validarFiltros(String nombre, String apellido, String dni) { //Valido DNI sea numerico Decimal dniDecimal; if (dni != "" && !Decimal.TryParse(dni, out dniDecimal)) { errorDni.Text = "El DNI debe ser numérico"; return false; } return true; } private void btnBuscar_Click(object sender, EventArgs e) { try { if (!validarFiltros(txtNombre.Text, txtApellido.Text, txtDni.Text)) { MessageBox.Show("Error en los filtros de búsqueda", "Error", MessageBoxButtons.OK); } else { //Limpio la tabla de clientes grillaCliente.Columns.Clear(); //Busco los clientes en la base de datos DataTable dtClientes = Cliente.buscarClientes(txtNombre.Text, txtApellido.Text, (txtDni.Text == "") ? 0 : Decimal.Parse(txtDni.Text)); //Le asigno a la grilla los roles grillaCliente.DataSource = dtClientes; //Agrego botones para Modificar y Eliminar Rol DataGridViewButtonColumn btnSeleccionar = new DataGridViewButtonColumn(); btnSeleccionar.HeaderText = "Seleccionar"; btnSeleccionar.Text = "Seleccionar"; btnSeleccionar.UseColumnTextForButtonValue = true; grillaCliente.Columns.Add(btnSeleccionar); grillaCliente.Columns["Cliente_Persona"].Visible = false; errorDni.Text = ""; } } catch (Exception ex) { MessageBox.Show("Error inesperado: " + ex.Message, "Error", MessageBoxButtons.OK); } } private void btnRegresar_Click(object sender, EventArgs e) { this.Hide(); } private void btnLimpiar_Click(object sender, EventArgs e) { grillaCliente.DataSource = null; grillaCliente.Columns.Clear(); limpiarFiltrosYErrores(); } private void limpiarFiltrosYErrores() { txtNombre.Text = ""; txtApellido.Text = ""; txtDni.Text = ""; errorDni.Text = ""; } private void grillaCliente_CellContentClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; //En caso de que se presiono el boton "Seleccionar" de algun cliente, se crea un objeto Cliente con los datos de la grilla y se lo manda a modificar if (senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn && senderGrid.CurrentCell.Value.ToString() == "Seleccionar" && e.RowIndex >= 0) { try { //Solo puedo seleccionar clientes activos para rendir if ((Byte)senderGrid.CurrentRow.Cells["Cliente_Activo"].Value == 1) { Cliente clienteSeleccionado = new Cliente(); clienteSeleccionado.Nombre = senderGrid.CurrentRow.Cells["Cliente_Nombre"].Value.ToString(); clienteSeleccionado.Apellido = senderGrid.CurrentRow.Cells["Cliente_Apellido"].Value.ToString(); clienteSeleccionado.Dni = (Decimal)senderGrid.CurrentRow.Cells["Cliente_Dni"].Value; clienteSeleccionado.Telefono = (Decimal)senderGrid.CurrentRow.Cells["Cliente_Telefono"].Value; clienteSeleccionado.Direccion = senderGrid.CurrentRow.Cells["Cliente_Direccion"].Value.ToString(); clienteSeleccionado.FechaNacimiento = (DateTime)(senderGrid.CurrentRow.Cells["Cliente_Fecha_Nac"].Value); clienteSeleccionado.Mail = senderGrid.CurrentRow.Cells["Cliente_Mail"].Value.ToString(); clienteSeleccionado.CodigoPostal = (Decimal)senderGrid.CurrentRow.Cells["Cliente_Codigo_Postal"].Value; clienteSeleccionado.Activo = (Byte)senderGrid.CurrentRow.Cells["Cliente_Activo"].Value; this.formularioFacturacion.clienteElegido = clienteSeleccionado; this.formularioFacturacion.cambiarCliente(); this.Hide(); } else { MessageBox.Show("No puede seleccionar este cliente ya que no esta activo", "Error", MessageBoxButtons.OK); } } catch (Exception ex) { MessageBox.Show("Ha ocurrido un error al realizar la seleccion del cliente: " + ex.Message, "Error", MessageBoxButtons.OK); } } } private void groupBox1_Enter(object sender, EventArgs e) { } } }
using System.Collections; using UnityEngine.UI; using UnityEngine; public class PlayerController : MonoBehaviour { #region Private Members [SerializeField] private Slider _gasMeter; [SerializeField] private int _gasReleaseDelay; [SerializeField] private int _gasReleasePower; [SerializeField] private int _maxGasAmount; [SerializeField] private float _speed; [SerializeField] private float _tiltSpeed; [SerializeField] private Animator _spriteAnimator; [SerializeField] private GameObject _bulletPrefab; [SerializeField] private Transform _bulletSpawn; [SerializeField] private float _sufterTilt; [SerializeField] private int _boundaryColumnLeft; [SerializeField] private int _boundaryColumnRight; [SerializeField] private int _invincibilityTime; [SerializeField] private int _bulletPoolSize; private int _gasAmount = 0; private WaitForSeconds _waitForGasRelease; private bool _isInvincible; private Collider2D _collider; private WaitForSeconds _waitForInvincibilityDone; private ObjectPool<BulletController> _bulletsPool; private bool _isShooting = false; private int _shootHash; private bool _bounadryInitialised = false; private float _lowerYBoundary; private float _upperYBoundary; private float _leftXBoundary; private float _rightXBoundary; private int _currentColumn; #endregion #region Private Methods private void Awake() { _collider = GetComponent<Collider2D> (); } private void Start() { _shootHash = Animator.StringToHash("Shooting"); _waitForGasRelease = new WaitForSeconds(_gasReleaseDelay); _waitForInvincibilityDone = new WaitForSeconds(_invincibilityTime); _bulletsPool = new ObjectPool<BulletController>(_bulletPoolSize, InstantiateBullet); _gasMeter.maxValue = _maxGasAmount; } private void Update() { if (!_bounadryInitialised) { Camera cam = Camera.main; Vector3 camPosition = cam.transform.position; _lowerYBoundary = camPosition.y - cam.orthographicSize + 0.5f; _upperYBoundary = camPosition.y + cam.orthographicSize - 0.5f; _leftXBoundary = camPosition.x - cam.orthographicSize * cam.aspect; _rightXBoundary = camPosition.x + cam.orthographicSize * cam.aspect; _currentColumn = GetCurrentColumn(cam.transform.position.x); _bounadryInitialised = true; } float vert = Input.GetAxis("Vertical"); float newYPos = transform.position.y + (vert * Time.deltaTime * _speed); Vector3 newPos = new Vector3(transform.position.x, Mathf.Clamp(newYPos, _lowerYBoundary, _upperYBoundary), 0.0f); transform.position = newPos; if (_bulletsPool != null) { if (Input.GetButton("Fire1") && !_isShooting) { _isShooting = true; _spriteAnimator.SetTrigger("Shoot"); } else if (_isShooting) { // Check whether we almost finished with the shooting animation if (_spriteAnimator.GetCurrentAnimatorStateInfo(0).shortNameHash == _shootHash && _spriteAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime > 0.9) { BulletController bulletCtrl = _bulletsPool.GetPooledObject(); if (bulletCtrl != null) { bulletCtrl.transform.transform.position = _bulletSpawn.transform.position; bulletCtrl.transform.transform.rotation = _bulletSpawn.transform.rotation; bulletCtrl.gameObject.SetActive(true); } _isShooting = false; } } } } private BulletController InstantiateBullet() { GameObject bullet = Instantiate(_bulletPrefab); bullet.SetActive(false); return bullet.GetComponent<BulletController>(); } private int GetCurrentColumn(float camX) { float minXPlayerPosition = _leftXBoundary + 0.5f; float maxXPlayerPosition = _rightXBoundary - 0.5f; // substract 1 because we count the columns from 0 int numOfCols = (int)(maxXPlayerPosition - minXPlayerPosition); return (int)(Mathf.InverseLerp(minXPlayerPosition, maxXPlayerPosition, transform.position.x) * numOfCols); } private IEnumerator MoveToColumn(int column) { float finalPositionX = _leftXBoundary + 0.5f + column; float startingPositionX = transform.position.x; float tilt = _currentColumn > column ? _sufterTilt : -_sufterTilt; Quaternion tiltTo = Quaternion.Euler(0, 0, tilt); Quaternion tiltBack = Quaternion.Euler(0, 0, 0); while (Mathf.Abs(transform.position.x - finalPositionX) >= float.Epsilon) { Vector3 finalPos = new Vector3(finalPositionX, transform.position.y, 0.0f); transform.position = Vector3.MoveTowards(transform.position, finalPos, _speed * Time.deltaTime); float rotationLerp = Mathf.InverseLerp(startingPositionX, finalPositionX, transform.position.x); transform.rotation = Quaternion.Lerp(transform.rotation, tiltTo, rotationLerp); yield return null; } _currentColumn = column; while (Mathf.Abs(transform.rotation.z) >= float.Epsilon) { transform.rotation = Quaternion.RotateTowards(transform.rotation, tiltBack, _tiltSpeed * Time.deltaTime); yield return null; } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.CompareTag("Enemy")) { Enemy enemy = collision.gameObject.GetComponent<Enemy>(); if (enemy != null && !_isInvincible) { MoveColumns(-(enemy.size + 1)); StartCoroutine(HitByEnemy()); } } else if (collision.CompareTag("Pickup")) { Pickup pickup = collision.gameObject.GetComponent<Pickup>(); if (pickup != null) { _gasAmount += pickup.value + 1; _gasMeter.value = _gasAmount; Destroy (pickup.gameObject); if (_gasAmount >= _maxGasAmount) { StartCoroutine(ReleaseFart()); } } } } private IEnumerator HitByEnemy() { _spriteAnimator.SetBool("IsInvincible", true); _isInvincible = true; _collider.enabled = false; yield return _waitForInvincibilityDone; _collider.enabled = true; _isInvincible = false; _spriteAnimator.SetBool("IsInvincible", false); } private IEnumerator ReleaseFart() { _spriteAnimator.SetBool("GasOverload", true); yield return _waitForGasRelease; _spriteAnimator.SetBool("GasOverload", false); MoveColumns(_gasReleasePower); _gasAmount -= _maxGasAmount; if (_gasAmount < 0) { _gasAmount = 0; } _gasMeter.value = _gasAmount; } #endregion #region Public Methods public void MoveColumns(int value) { int colToMoveTo = _currentColumn + value; if (colToMoveTo >= _boundaryColumnLeft && colToMoveTo <= _boundaryColumnRight) { StartCoroutine(MoveToColumn(_currentColumn + value)); } } // todo: remove these public void TriggerFart() { StartCoroutine(ReleaseFart()); } public void TriggerInvi() { StartCoroutine(HitByEnemy()); } public void PickupSomething() { _gasAmount += 3; _gasMeter.value = _gasAmount; if (_gasAmount >= _maxGasAmount) { StartCoroutine(ReleaseFart()); } } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using WebPresentation.Models; namespace WebPresentation.Controllers { public class EuclideanController : ApiController { public ExtendedEuclideanResult GetResult(decimal a, decimal b) { var eucl = new UnidebRSA.ExtendedEuclidean(a, b); eucl.Calculate(); return new ExtendedEuclideanResult { n = eucl.n, rn = eucl.rn, x = eucl.x, y = eucl.y }; } } }
using CinemaA.Mails; using CinemaA.Models; using System.Threading.Tasks; /* * Service used for sending emails. */ namespace CinemaA.Services { public interface IMailService { Task SendEmailMessageAsync(string userName, string userEmail, string newTicketStatus, SessionTickets viewModel); } }
using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlueSportApp.Services.API { public interface IAPIService { public IRestResponse GetDataFromAPI(string path); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using kemuyi.DAL; using kemuyi.Models; namespace kemuyi.BLL { public class QuestionManager { public static void Add(int QuestionID, string Content, string Answer) { QuestionService.Add(QuestionID,Content,Answer); } public static bool Delete(int QuestionID) { QuestionService.Delete(QuestionID); return false; } public static bool Updata(int QuestionID, string Content, string Answer) { QuestionService.Updata(QuestionID, Content, Answer); return false; } public static bool TransactionScope(int QuestionID) { QuestionService.TransactionScope(QuestionID); return false; } public static bool Selects(int QuestionID) { QuestionService.Selects(QuestionID); return true; } public static Question GetQues(int QuesID) { var ques= QuestionService.GetQues(QuesID); return ques; } } }
using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; namespace Eventual.EventStore.Readers.Tracking { public class EventStreamTrackedReaderDbConcurrencyException : EventStreamTrackedReaderDbException { public const string DefaultMessage = "A concurrency problem has occurred. Data has been changed since it was loaded from the origin database."; public EventStreamTrackedReaderDbConcurrencyException() : base() { } public EventStreamTrackedReaderDbConcurrencyException(string message) : base(message) { } public EventStreamTrackedReaderDbConcurrencyException(string message, Exception innerException) : base(message, innerException) { } public EventStreamTrackedReaderDbConcurrencyException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
using System; using kolekcje; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass()] public class GraczTests { [TestMethod()] public void ToStringTest() { try { var gracz = new Gracz("Zdzislawa", "Kowalska"); Console.WriteLine(gracz); } catch (Exception) { Assert.Fail("Wystapil nieoczekiwany wyjatek"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class ProgressBar : MonoBehaviour { public Image bar; /// <summary> /// 设置进度条填充百分比 value为填充百分比 /// </summary> /// <param name="value"></param> public void SetValue(float value) { bar.fillAmount = value; //bar.DOFillAmount(value, 0.2f); } }
namespace Phonebook { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ConsolePrinterVisitorWithoutNewLine : IPrinterVisitor { public void Visit(string currentText) { Console.Write(currentText); } } }
using System.Collections; using UnityEngine; public class ChildGenerator : MonoBehaviour { public GameObject childPrefab; public GameObject childOriginPrefab; private GameObject enemiesHolder; public int childsPerRound; public float timeBetweenRounds; public void Start() { enemiesHolder = GameObject.Find("EnemiesHolder"); } public void GenerateChild(Vector2 pos) { GameObject childOrigin = Instantiate(childOriginPrefab, pos, Quaternion.identity); Destroy(childOrigin, 1f); StartCoroutine(InstantiateChild(pos)); } private IEnumerator InstantiateChild(Vector2 pos) { yield return new WaitForSeconds(0.8f); GameObject child = Instantiate(childPrefab, pos, Quaternion.identity); child.transform.SetParent(enemiesHolder.transform); } }