text
stringlengths
13
6.01M
using AutoMapper; using ImmedisHCM.Data.Entities; using ImmedisHCM.Services.Models.Core; namespace ImmedisHCM.Services.Mapping { public class CityMapping : Profile { public CityMapping() { CreateMap<City, CityServiceModel>().ReverseMap(); } } }
using GestDep.Entities; using GestDep.Persistence; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GestDepLib.Services1 { class GestDepService : IGestDepService { private readonly IDAL dal; public GestDepService(IDAL dal) { this.dal = dal; } public void RemoveAllData() { dal.RemoveAllData(); throw new ServiceException(); } public void Commit() { dal.Commit(); throw new ServiceException(); } public void AddCityHall(CityHall city) { dal.Insert<CityHall>(city); dal.Commit(); throw new ServiceException(); } public CityHall FindCityHallByName(string name) { List<CityHall> cityhalls = new List<CityHall>(dal.GetAll<CityHall>()); foreach(CityHall city in cityhalls) { if (city.Name == name) { return city; } } Console.WriteLine("no se ha encontrado un ayuntamiento"); return null; throw new ServiceException(); } public List<CityHall> GetAllCityHalls() { List<CityHall> cityhalls = new List<CityHall>(dal.GetAll<CityHall>()); return cityhalls; } public void AddGym(Gym gym) //hecho { dal.Insert<Gym>(gym); dal.Commit(); throw new ServiceException(); } public Gym FindGymByName(string name) //hecho { List<Gym> gyms = new List<Gym>(dal.GetAll<Gym>()); foreach (Gym mygym in gyms) { if (mygym.Name == name) { return mygym; } } //Console.WriteLine("no se ha encontrado el gym"); throw new ServiceException("No se ha encontrado el gym"); } public void AddRoom(Room room) //hecho { dal.Insert<Room>(room); dal.Commit(); } public void GetFreeRooms(Room room) //hecho { dal.Insert<Room>(room); dal.Commit(); throw new ServiceException(); } public Room FindRoom(int Number) //hecho { List<Room> room = new List<Room>(dal.GetAll<Room>()); foreach (Room myroom in room) { if (myroom.Number == Number) { return myroom; } } //Console.WriteLine("no se ha encontrado la habitación"); throw new ServiceException("no se ha encontrado la habitación"); } public Activity FindActivityByName(string name) //hecho { List<Activity> activities = new List<Activity>(dal.GetAll<Activity>()); foreach (Activity myact in activities) { if (myact.Description == name) { return myact; } } //Console.WriteLine("no se ha encontrado la actividad"); throw new ServiceException("no se ha encontrado la actividad"); } public void AddInstructor(Instructor m) { dal.Insert<Instructor>(m); dal.Commit(); throw new ServiceException(); } public void SetInstructor(Instructor i) { throw new ServiceException(); } public Instructor FindInstructorById(int m) //hecho { try { return dal.GetById<Instructor>(m); } catch (ServiceException) { Console.WriteLine("no existe el instructor"); } return null; } public void AddActivity(Activity activity) //hecho { if (dal.GetById<Activity>(activity.Id) == null) { dal.Insert<Activity>(activity); dal.Commit(); } else throw new ServiceException("Dicha actividad ya existe :c"); throw new ServiceException(); } public void AddUser(User usuario) { if (dal.GetById<User>(usuario.Id) == null) { dal.Insert<User>(usuario); dal.Commit(); } throw new ServiceException("Dicho usuario ya existe, eres tonto?"); } public void AddUser(User usuario, Activity activity) { if (dal.GetById<User>(usuario.Id) == null) { dal.Insert<User>(usuario); dal.Commit(); } throw new ServiceException("Dicho usuario ya existe, eres tonto?"); } public int GetPriceForUser(Gym g, User u) { throw new ServiceException(); } public void AddEnrollment(Enrollment enrollment) { if (dal.GetById<Enrollment>(enrollment.Id) == null) { dal.Insert<Enrollment>(enrollment); dal.Commit(); } else throw new ServiceException("Dicho enrollment ya existe :c"); throw new ServiceException(); } public void AddPayment(Payment payment) { if (dal.GetById<Payment>(payment.Id) == null) { dal.Insert<Payment>(payment); dal.Commit(); } else throw new ServiceException("Dicha persona ya existe :c"); throw new ServiceException(); } public void AddPerson(Person person) { if (dal.GetById<Person>(person.Id) == null) { dal.Insert<Person>(person); dal.Commit(); } else throw new ServiceException("Dicha persona ya existe :c"); } } }
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class RotateScript : MonoBehaviour { public float speed = 100.0f; private float maxSpeed = 300.0f; public bool turnLeft = true; public bool xAxis = false; public bool yAxis = false; public bool zAxis = true; private int x; private int y; private int z; private int direction; private Transform _transform; private float speedUpTime = 10f; void Start(){ _transform = transform; direction = turnLeft ? 1 : -1; } void Update () { x = xAxis ? 1 : 0; y = yAxis ? 1 : 0; z = zAxis ? 1 : 0; _transform.Rotate (x * direction * speed * Time.deltaTime, y * direction * speed * Time.deltaTime, z * direction * speed * Time.deltaTime); } public void speedUpPowerup(){ StartCoroutine (speedUpRotation(5f)); } IEnumerator speedUpRotation(float seconds){ float initialSpeed = speed; print("BEFORE " + speed); while (speed < maxSpeed - 1) { speed = Mathf.Lerp (speed, maxSpeed, .1f); yield return new WaitForSeconds (.02f); } yield return new WaitForSeconds (seconds); while (initialSpeed < speed -1 ){ print("after " + (initialSpeed < speed -1 )); speed = Mathf.Lerp (speed, initialSpeed, .1f); yield return new WaitForSeconds (.02f); } //make sure it goes back to the exact value speed = initialSpeed; } }
using Assets.Scripts.RobinsonCrusoe_Game.GameAttributes; using Assets.Scripts.RobinsonCrusoe_Game.GameAttributes.Inventions_and_Terrain; using Assets.Scripts.RobinsonCrusoe_Game.RoundSystem; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Analytics; using UnityEngine.UI; public class PopUp_Mission_Show : MonoBehaviour { public Text round; public Text wood; public Text fire; public GameObject roundGoal; public GameObject woodGoal; public GameObject fireGoal; public Button closeBtn; public GameObject popup; // Start is called before the first frame update void Start() { UpdateText(); closeBtn.onClick.AddListener(TaskOnClick); } public void UpdateText() { round.text = RoundSystem.instance.currentRound.ToString(); if (RoundSystem.instance.currentRound >= 10) roundGoal.SetActive(true); int value = PopUp_Mission_StackOfWood.GetTotalValue(); wood.text = value.ToString(); Debug.Log(value); if (value >= 15) woodGoal.SetActive(true); if (InventionStorage.IsAvailable(Invention.Fire)) { fire.text = "1"; fireGoal.SetActive(true); } } private void TaskOnClick() { Destroy(popup); if (!RoundSystem.instance.started) { RoundSystem.instance.StartGame(); Analytics.CustomEvent("Game Start"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; namespace solution1.gestion_utilisateur { public partial class modifier_utilisateur : DevExpress.XtraEditors.XtraUserControl { string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["connectString1"].ConnectionString; string requete,login,mot_pass; public int id_utilisateur; int i=0; public modifier_utilisateur(string mot_passe,string login) { InitializeComponent(); this.mot_pass = mot_passe; this.login = login; } private void modifier_utilisateur_Load(object sender, EventArgs e) { charger_utilisateur(); } private void charger_utilisateur() { requete = "select * from Utilisateur where pseudo='"+login.ToString()+"' and motDePasse='"+mot_pass.ToString()+"'"; DataSet utilisateur = MaConnexion.ExecuteSelect(connectionString, requete); if (utilisateur != null) { foreach (DataRow row in utilisateur.Tables[0].Rows) { Login.Text = row[1].ToString(); Password.Text = row[2].ToString(); NOM.Text = row[3].ToString(); Prenom.Text = row[4].ToString(); id_utilisateur = int.Parse(row[0].ToString()); } } requete = "select priv,droit from attribuer join privilege on attribuer.id_priv= privilege.id_priv join droit on droit.id_droit=attribuer.id_droit and id_utilisateur=" + id_utilisateur; DataSet privilege = MaConnexion.ExecuteSelect(connectionString, requete); dgvDroits.DataSource = privilege.Tables[0]; DataGridViewButtonColumn col = new DataGridViewButtonColumn(); dgvDroits.Columns.Add(col); } private void Modifier_enregistrement_Click(object sender, EventArgs e) { requete = "update utilisateur set pseudo='"+Login.Text+"',motDePasse='"+Password.Text+"',Administrateur='"+NOM.Text+"',etat='"+Prenom.Text+"' where idUtilisateur="+id_utilisateur; int modif = MaConnexion.ExecuteUpdate(connectionString, requete); if (modif != -1) { MessageBox.Show("modification réussite!!"); }else{MessageBox.Show("modification non effectuer");} } private void dgvDroits_CellContentClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex < 0) return; //click sur le bouton de suppression if (e.RowIndex != dgvDroits.RowCount - 1) //bouton de suppression { dgvDroits.Rows.RemoveAt(e.RowIndex); } } } }
using UnityEngine; using System.Collections; public class LoadingScreen : MonoBehaviour { // GUI style for the background public GUIStyle backgroundStyle; void OnGUI() { GUI.Box(new Rect(0, 0, Screen.width, Screen.height), "LOADING", backgroundStyle); } }
namespace Card_Game { enum Colors : uint { Red = 1, Blue = 2, Green = 3, Yellow = 4, Gold = 5 } class Card { public Colors color {get;} public uint number {get;} public Card(Colors c, uint num) { this.color = c; this.number = num; } } }
using System; using System.Collections.Generic; using W3ChampionsStatisticService.CommonValueObjects; using W3ChampionsStatisticService.ReadModelBase; namespace W3ChampionsStatisticService.PlayerProfiles.MmrRankingStats { public class PlayerMmrRpTimeline : IIdentifiable { public PlayerMmrRpTimeline(string battleTag, Race race, GateWay gateWay, int season, GameMode gameMode) { Id = $"{season}_{battleTag}_@{gateWay}_{race}_{gameMode}"; MmrRpAtDates = new List<MmrRpAtDate>(); } public string Id { get; set; } public List<MmrRpAtDate> MmrRpAtDates { get; set; } public void UpdateTimeline(MmrRpAtDate mmrRpAtDate) { // Empty? if (MmrRpAtDates.Count == 0) { MmrRpAtDates.Add(mmrRpAtDate); return; } // Insert at last pos? int index = MmrRpAtDates.Count - 1; if (MmrRpAtDates[index].Date <= mmrRpAtDate.Date) { if (CheckDateExists(index, mmrRpAtDate)) { HandleDateExists(index, mmrRpAtDate); return; } MmrRpAtDates.Add(mmrRpAtDate); return; } // Insert at first pos? index = 0; { if (MmrRpAtDates[index].Date >= mmrRpAtDate.Date) { if (CheckDateExists(index, mmrRpAtDate)) { HandleDateExists(index, mmrRpAtDate); return; } MmrRpAtDates.Insert(index, mmrRpAtDate); return; } } int bsIndex = MmrRpAtDates.BinarySearch(mmrRpAtDate); if (bsIndex < 0) bsIndex = ~bsIndex; // Check if date already exists // if so, use the mmrRpAtDate with later Date for (int i = 0; i <= 1; i++) { index = bsIndex - i; if (index >= 0 && index < MmrRpAtDates.Count) { if (CheckDateExists(index, mmrRpAtDate)) { HandleDateExists(index, mmrRpAtDate); return; } } } MmrRpAtDates.Insert(bsIndex, mmrRpAtDate); } private Boolean CheckDateExists(int oldId, MmrRpAtDate mmrRpAtDate) { var neighbour = MmrRpAtDates[oldId]; if (mmrRpAtDate.HasSameYearMonthDayAs(neighbour)) { return true; } return false; } private void HandleDateExists(int oldId, MmrRpAtDate mmrRpAtDate) { var neighbour = MmrRpAtDates[oldId]; //if (mmrRpAtDate.Mmr > neighbour.Mmr) if (mmrRpAtDate.Date > neighbour.Date) { MmrRpAtDates[oldId] = mmrRpAtDate; } } } public class MmrRpAtDate : IComparable { public MmrRpAtDate(int mmr, int? rp, DateTimeOffset date) { Mmr = mmr; Rp = rp; Date = date; } public int Mmr { get; set; } public int? Rp { get; set; } public DateTimeOffset Date { get; set; } public Boolean HasSameYearMonthDayAs(MmrRpAtDate mRAT2) { return this.Date.Year == mRAT2.Date.Year && this.Date.Month == mRAT2.Date.Month && this.Date.Day == mRAT2.Date.Day; } public int CompareTo(object obj) { DateTimeOffset mmrTime_obj = ((MmrRpAtDate)obj).Date; if (this.Date < mmrTime_obj) return -1; if (this.Date > mmrTime_obj) return 1; return 0; } } }
public class EqualToCriteria<TItem> : ICriteria<TItem> { private readonly TItem _value; public EqualToCriteria(TItem value) { _value = value; } public bool IsSatisfiedBy(TItem item) { return item.Equals(_value); } }
using System; namespace GraphQLSampleAPI.Models { public class Gadget { public string id { get; set; } public string productName { get; set; } public string brandName { get; set; } public decimal cost { get; set; } public string type { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using System; public class panelView : MonoBehaviour { [SerializeField] private TextMeshProUGUI displayName; [SerializeField] private TextMeshProUGUI serialNumber; [SerializeField] private TextMeshProUGUI highScore; private GameObject upPosition; private RectTransform downPosition; private void Awake() { upPosition = GameObject.FindGameObjectWithTag("upPosition"); } public void setPanelValue(int sNo,string name,int score) { displayName.text = name; serialNumber.text = sNo.ToString(); highScore.text = score.ToString(); } //public void goUp() //{ // float dist = Vector3.Distance(upPosition.transform.position, transform.position); // this.transform.DOMove(upPosition.transform.position, 0.001f * dist); //} }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Advertisements; public class PromoButton : MonoBehaviour { [SerializeField] private string placementID; private Button button; private Text text; private void Awake() { this.button = GetComponent<Button>(); this.text = GetComponentInChildren<Text>(); } private void Start() { this.button.onClick.AddListener(this.ShowPromotion); StartCoroutine("checkPlacement"); } private IEnumerator checkPlacement() { while (true) { if (!Advertisement.isInitialized || !Advertisement.IsReady(this.placementID)) { this.text.fontStyle = FontStyle.Normal; } else { this.text.fontStyle = FontStyle.Bold; } yield return new WaitForSeconds(1); } } public void ShowPromotion() { Advertisement.Show(this.placementID); } }
using Application.Interfaces.Repositories; using Domain.Entities; using Infrastructure.Persistence.Contexts; using Microsoft.EntityFrameworkCore; using System.Threading.Tasks; namespace Infrastructure.Persistence.Repositories { public class ProductRepositoryAsync : GenericRepositoryAsync<Product>, IProductRepositoryAsync { private readonly DbSet<Product> products; public ProductRepositoryAsync(ApplicationDbContext dbContext) : base(dbContext) { products = dbContext.Set<Product>(); } public Task<bool> IsUniqueBarcodeAsync(string barcode) { return products .AllAsync(p => p.Barcode != barcode); } } }
using System; using System.Web.UI; using NopSolutions.NopCommerce.BusinessLogic.Configuration.Settings; using NopSolutions.NopCommerce.Web.Templates.Payment; namespace NopSolutions.NopCommerce.Web.Administration.Payment.EasyPay { public partial class ConfigurePaymentMethod : BaseNopAdministrationUserControl, IConfigurePaymentMethodModule { protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { var secretKey = SettingManager.GetSettingByName("PaymentMethod.EasyPay.UseSandbox"); if (secretKey == null) { SettingManager.AddSetting("PaymentMethod.EasyPay.UseSandbox", "true", string.Empty); } BindData(); } } private void BindData() { chbUseSandbox.Checked = SettingManager.GetSettingValueBoolean("PaymentMethod.EasyPay.UseSandbox"); } public void Save() { SettingManager.SetParam("PaymentMethod.EasyPay.UseSandBox", chbUseSandbox.Checked.ToString()); } } }
namespace Integer_Insertion { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class IntegerInsertion { public static void Main(string[] args) { //read the input, split and convert to integer list; var input = Console.ReadLine().Split(' ').ToList(); //list for temporary result; var tempList = new List<string>(); //read the integer from console to the command end; var number = Console.ReadLine(); while (number != "end") { //var for index to insert the number; int insertIndex = (int)char.GetNumericValue(number[0]); //fill the temporary result to insertIndex; for (int i = 0; i < insertIndex; i++) { tempList.Add(input[i]); } //add the number in insert index; tempList.Add(number); //fill the temporary result from insert index; for (int i = insertIndex; i < input.Count; i++) { tempList.Add(input[i]); } //clear the input; input.Clear(); //fill the input with temp list; for (int i = 0; i < tempList.Count; i++) { input.Add(tempList[i]); } //clear the temporary list; tempList.Clear(); number = Console.ReadLine(); } Console.WriteLine(string.Join(" ", input)); } } }
 using System; namespace ORTRulesEngine.Entities { public abstract class BaseRule<T> { public RuleEngine<T> RulesEngine; public BaseRule() { RulesEngine = new RuleEngine<T>(); } } }
using FMOD; using Steamworks; using System; using System.Collections.Concurrent; using System.IO; using System.Threading; using UnityEngine; using System.Linq; using System.Collections; using System.Collections.Generic; using UnityEngine.AzureSky; using HarmonyLib; using Debug = UnityEngine.Debug; using Newtonsoft.Json.Linq; using TMPro; using Random = System.Random; public class TwitchItegration : Mod { private static readonly Random RAND = new Random(); private static SO_ColorValue[] Colors; public static int CHANNEL_ID = 2349; public static Messages MESSAGE_TYPE_SET_NAME = (Messages)2349; private ChatManager chat; private readonly Dictionary<string, Sound> sounds = new Dictionary<string, Sound>(); private ChannelGroup channels; private FMOD.System system = FMODUnity.RuntimeManager.LowlevelSystem; public static ConcurrentQueue<RewardData> rewardsQueue = new ConcurrentQueue<RewardData>(); public static List<StatData> statsEdited = new List<StatData>(); public static List<TempEntity> tempEntities = new List<TempEntity>(); public static List<Meteor> meteors = new List<Meteor>(); public static List<PushData> pushData = new List<PushData>(); public static long trashResetTime = -1; private StoneDrop stoneDropPrefab = null; private Harmony harmonyInstance; private static AssetBundle assets; private float spawnRateIntervalMin; private float spawnRateIntervalMax; // The Start() method is being called when your mod gets loaded. public IEnumerator Start() { Debug.Log("Twitch Integration has been loaded!"); AssetBundleCreateRequest request = AssetBundle.LoadFromMemoryAsync(GetEmbeddedFileBytes("twitchintegrations.assets")); yield return request; assets = request.assetBundle; harmonyInstance = new Harmony("dev.theturkey.twitchintegration"); harmonyInstance.PatchAll(); Colors = Resources.LoadAll<SO_ColorValue>("Colors"); channels = new ChannelGroup(); system.getMasterChannelGroup(out channels); if (!Directory.Exists("mods/ModData/TwitchIntegration")) Directory.CreateDirectory("mods/ModData/TwitchIntegration"); foreach (string f in Directory.GetFiles("mods/ModData/TwitchIntegration")) { string fileName = f.Replace("mods/ModData/TwitchIntegration\\", ""); system.createSound(f, MODE.DEFAULT, out Sound newSound); sounds.Add(fileName, newSound); Debug.Log("Added sound: " + fileName); } chat = ComponentManager<ChatManager>.Value; IntegationSocket.Start("raft", 23491); ObjectSpawnerManager spawnerManager = ComponentManager<ObjectSpawnerManager>.Value; var settings = Traverse.Create(spawnerManager.itemSpawner).Field("currentSettings").GetValue<ObjectSpawnerAssetSettings>(); spawnRateIntervalMin = settings.spawnRateInterval.minValue; spawnRateIntervalMax = settings.spawnRateInterval.maxValue; } public override void WorldEvent_WorldLoaded() { chat = ComponentManager<ChatManager>.Value; } // The OnModUnload() method is being called when your mod gets unloaded. public void OnModUnload() { Debug.Log("Twitch Itegration has been unloaded!"); Shutdown(); Destroy(gameObject); // Please do not remove that line! } // The Update() method is being called every frame. Have fun! public void Update() { DateTime currentTime = DateTime.UtcNow; Network_Player player = RAPI.GetLocalPlayer(); Network_Host_Entities nhe = ComponentManager<Network_Host_Entities>.Value; Raft raft = ComponentManager<Raft>.Value; Rigidbody body = Traverse.Create(raft).Field("body").GetValue() as Rigidbody; if (rewardsQueue.TryDequeue(out RewardData reward)) { if ((currentTime - reward.added).TotalMilliseconds < reward.delay) { rewardsQueue.Enqueue(reward); } else { string userName = (string)reward.data["metadata"]["user"]; var values = reward.data["values"]; switch (reward.action) { case "PlaySound": system.playSound(sounds[(string)values["sound"]], channels, false, out Channel _); break; case "ChatMessage": chat.SendChatMessage((string)values["message"], SteamUser.GetSteamID()); break; case "SpawnItem": Item_Base item = ItemManager.GetItemByName((string)values["item"]); int amount = (int)values["amount"]; Helper.DropItem(new ItemInstance(item, amount, item.MaxUses), player.transform.position, player.CameraTransform.forward, player.transform.ParentedToRaft()); break; case "InventoryBomb": chat.SendChatMessage("Inventory Bomb!", SteamUser.GetSteamID()); foreach (Slot s in player.Inventory.allSlots) player.Inventory.DropItem(s); foreach (Slot s in player.Inventory.equipSlots) player.Inventory.DropItem(s); break; case "StatEdit": //TODO //player.PersonController.gravity = 20; //player.PersonController.swimSpeed = 2; //player.PersonController.normalSpeed = 3; //player.PersonController.jumpSpeed = 8; //player.Stats.stat_thirst.Value -= 5; string action = (string)values["action"]; string stat = (string)values["stat"]; float changeAmount = (float)values["changeAmount"]; int duration = (int)values["duration"]; bool contained = false; foreach (StatData data in statsEdited) { if (data.stat.Equals(stat)) { data.duration += duration; contained = true; } } if (!contained) { StatData data = GetStatData(player, stat, action, changeAmount); data.duration = duration * 1000; data.timeStarted = DateTime.UtcNow; SetStatVal(player, stat, data.currentValue); if (duration != -1) statsEdited.Add(data); } break; case "PushPlayer": float force = (float)(values["force"] ?? 8); int dur = (int)(values["duration"] ?? 500); pushData.Add(new PushData(GetBoundedRandVector(0.5f, 1, true) * force, dur)); break; case "SpawnEntity": float scale = (float)values["scale"]; int amountFromEntries = (int)values["amount"]; int spawnDuration = (int)values["spawnDuration"]; TempEntity tempEnt; foreach (AI_NetworkBehaviourType value in Enum.GetValues(typeof(AI_NetworkBehaviourType))) { if (!value.ToString().Contains((string)values["entity"], StringComparison.OrdinalIgnoreCase)) continue; for (int i = 0; i < amountFromEntries; i++) { Vector3 spawnPosition = player.FeetPosition + player.transform.forward * 2f; switch (value) { case AI_NetworkBehaviourType.Shark: spawnPosition = nhe.GetSharkSpawnPosition(); break; case AI_NetworkBehaviourType.PufferFish: spawnPosition = player.FeetPosition + player.transform.forward * 4f; if (spawnPosition.y > -1f) spawnPosition.y = -1f; break; case AI_NetworkBehaviourType.StoneBird: case AI_NetworkBehaviourType.StoneBird_Caravan: spawnPosition = player.FeetPosition + new Vector3(UnityEngine.Random.Range(3f, 10f), 10f, UnityEngine.Random.Range(3f, 10f)); if (spawnPosition.y < 15f) spawnPosition.y = 15f; break; case AI_NetworkBehaviourType.Llama: case AI_NetworkBehaviourType.Goat: case AI_NetworkBehaviourType.Chicken: spawnPosition = player.FeetPosition + player.transform.forward; break; case AI_NetworkBehaviourType.Dolphin: case AI_NetworkBehaviourType.Turtle: case AI_NetworkBehaviourType.Stingray: case AI_NetworkBehaviourType.Whale: if (!nhe.GetSpawnPositionDontCollideWithChunkPoint(ref spawnPosition, 50f)) return; break; case AI_NetworkBehaviourType.BirdPack: if (!nhe.GetBirdpackSpawnPosition(ref spawnPosition)) return; break; } AI_NetworkBehaviour ainb = nhe.CreateAINetworkBehaviour(value, spawnPosition, scale, SaveAndLoad.GetUniqueObjectIndex(), SaveAndLoad.GetUniqueObjectIndex(), null); if (ainb is AI_NetworkBehaviour_Domestic) { (ainb as AI_NetworkBehaviour_Domestic).QuickTameLate(); (ainb as AI_NetworkBehaviour_Domestic).SetNameTagEnabled(true); (ainb as AI_NetworkBehaviour_Domestic).nameTag.SetText(((string)(values["name"] ?? "")).Replace("${username}", userName)); } int health = (int)(values["health"] ?? -1); if (health != -1) { ainb.networkEntity.stat_health.SetMaxValue(health); ainb.networkEntity.stat_health.Value = health; } tempEnt = new TempEntity(ainb); if (tempEnt != null && spawnDuration != -1) { tempEnt.spawned = DateTime.UtcNow; tempEnt.duration = spawnDuration * 1000; tempEntities.Add(tempEnt); } } break; } break; case "ChangeWeather": string weatherName = (string)values["weather"]; bool instant = (bool)values["instant"]; WeatherManager wm = ComponentManager<WeatherManager>.Value; wm.SetWeather(weatherName, instant); break; case "SetTime": AzureSkyController skyController = ComponentManager<AzureSkyController>.Value; int hours = (int)(values["hours"] ?? 0); int minutes = (int)(values["minutes"] ?? 0); skyController.timeOfDay.GotoTime(hours, minutes); break; case "PickupTrash": WaterFloatSemih2[] floatingObjects = FindObjectsOfType<WaterFloatSemih2>(); float radius = (float)values["radius"]; foreach (WaterFloatSemih2 trash in floatingObjects) { try { if (!trash.GetComponent<PickupItem>().isDropped && Vector3.Distance(trash.transform.position, player.FeetPosition) < radius) { PickupItem_Networked pickup = trash.GetComponentInParent<PickupItem_Networked>(); PickupObjectManager.RemovePickupItemNetwork(pickup, SteamUser.GetSteamID()); } } catch { } } break; case "RunCommand": Traverse.Create(HMLLibrary.HConsole.instance).Method("SilentlyRunCommand", new Type[] { typeof(string) }, new object[] { (string)values["command"] }).GetValue<string>(); break; case "MeteorShower": int meteorsToSpawn = (int)values["meteors"]; int spawnRadius = (int)values["spawnRadius"]; int meteorDamage = (int)values["meteorDamage"]; int delay = (int)values["meteorInterval"]; if (stoneDropPrefab == null) { AI_NetworkBehaviour_StoneBird ainbsb = (AI_NetworkBehaviour_StoneBird)nhe.CreateAINetworkBehaviour(AI_NetworkBehaviourType.StoneBird, player.FeetPosition, 0, SaveAndLoad.GetUniqueObjectIndex(), SaveAndLoad.GetUniqueObjectIndex(), null); stoneDropPrefab = Traverse.Create(ainbsb.stateMachineStoneBird.dropStoneState).Field("stoneDropPrefab").GetValue() as StoneDrop; ainbsb.Kill(); } meteors.Add(new Meteor(meteorsToSpawn, spawnRadius, meteorDamage, delay)); break; case "PushRaft": float pushForce = (float)values["force"]; body.AddForce(GetBoundedRandVector(0.5f, 1) * pushForce, ForceMode.Impulse); break; case "RotateRaft": float rotationForce = (float)values["force"]; body.AddTorque(new Vector3(0, rotationForce, 0), ForceMode.Impulse); break; case "NameShark": AI_NetworkBehaviour[] array = NetworkIDManager.GetNetworkdIDs<AI_NetworkBehaviour>().Where(a => a is AI_NetworkBehavior_Shark).ToArray(); if (array == null || array.Length == 0) break; bool added = false; foreach (AI_NetworkBehavior_Shark shark in array) { var nametag = shark.stateMachineShark.GetComponentInChildren<TextMeshPro>(); if (nametag == null) { AddNametag(shark.stateMachineShark, userName); added = true; break; } } if (!added) AddNametag(((AI_NetworkBehavior_Shark)array[RAND.Next(array.Length)]).stateMachineShark, userName); break; case "InventoryShuffle": ShuffleInv(player.Inventory.allSlots.Where(s => s.slotType == SlotType.Normal || s.slotType == SlotType.Hotbar).ToList()); break; case "ExplodingPufferfish": AI_NetworkBehaviour_PufferFish pfainb = (AI_NetworkBehaviour_PufferFish)nhe.CreateAINetworkBehaviour(AI_NetworkBehaviourType.PufferFish, player.transform.position + new Vector3(0, 5, 0), 1, SaveAndLoad.GetUniqueObjectIndex(), SaveAndLoad.GetUniqueObjectIndex(), null); pfainb.stateMachinePufferFish.state_explode.Explode(player.transform.position); break; case "PaintRaft": SO_ColorValue primary = Colors[RAND.Next(Colors.Length)]; SO_ColorValue secondary = RAND.NextDouble() > 0.5 ? Colors[RAND.Next(Colors.Length)] : primary; int paintSide = 3; SO_Pattern[] patterns = Traverse.Create(typeof(ColorMenu)).Field("patterns").GetValue<SO_Pattern[]>(); uint patternIndex = patterns[RAND.Next(patterns.Length)].uniquePatternIndex; Transform lockedPivot = SingletonGeneric<GameManager>.Singleton.lockedPivot; Dictionary<Block, int> blockToIndex = Traverse.Create(raft.blockCollisionConsolidator).Field("blockToIndex").GetValue<Dictionary<Block, int>>(); foreach (Block b in blockToIndex.Keys) { Vector3 vector3_1 = player.Camera.transform.position - b.pivotOffset; Vector3 vector3_2 = lockedPivot.InverseTransformPoint(b.pivotOffset + vector3_1.normalized * 0.25f); if (!b.buildableItem.settings_buildable.Paintable || b.HasColor(primary, secondary, paintSide, patternIndex)) return; Message_PaintBlock messagePaintBlock = new Message_PaintBlock(Messages.PaintBlock, player, b.ObjectIndex, vector3_2, primary, secondary, paintSide, patternIndex); if (Raft_Network.IsHost) { player.Network.RPC(messagePaintBlock, Target.Other, EP2PSend.k_EP2PSendReliable, NetworkChannel.Channel_Game); b.SetInstanceColorAndPattern(primary, secondary, paintSide, patternIndex); } else player.SendP2P(messagePaintBlock, EP2PSend.k_EP2PSendReliable, NetworkChannel.Channel_Game); } break; case "TrashAmount": ObjectSpawnerManager spawnerManager = ComponentManager<ObjectSpawnerManager>.Value; var settings = Traverse.Create(spawnerManager.itemSpawner).Field("currentSettings").GetValue<ObjectSpawnerAssetSettings>(); settings.spawnRateInterval.minValue = (int)values["min"]; settings.spawnRateInterval.maxValue = (int)values["max"]; trashResetTime = (trashResetTime == -1 ? new DateTime().Millisecond : trashResetTime) + (int)values["duration"]; break; } } } for (int i = statsEdited.Count - 1; i >= 0; i--) { StatData data = statsEdited[i]; if ((currentTime - data.timeStarted).TotalMilliseconds > data.duration) { SetStatVal(player, data.stat, data.originalValue); statsEdited.RemoveAt(i); chat.SendChatMessage(data.stat + " back to normal!", SteamUser.GetSteamID()); } } for (int i = tempEntities.Count - 1; i >= 0; i--) { TempEntity ent = tempEntities[i]; if ((currentTime - ent.spawned).TotalMilliseconds > ent.duration) { if (ent.ent != null) { var network_Entity = ent.ent.networkEntity; ComponentManager<Network_Host>.Value.DamageEntity(network_Entity, network_Entity.transform, 9999f, network_Entity.transform.position, Vector3.up, EntityType.Player); } tempEntities.RemoveAt(i); } } if (meteors.Count > 0) { for (int m = meteors.Count - 1; m >= 0; m--) { Meteor me = meteors[m]; if ((currentTime - me.lastSpawned).TotalMilliseconds > me.delay) { Vector3 dropPosition = player.FeetPosition + new Vector3(UnityEngine.Random.Range(-me.radius, me.radius), 200, UnityEngine.Random.Range(-me.radius, me.radius)); StoneDrop stone = Instantiate(stoneDropPrefab, dropPosition, Quaternion.identity); float scale = UnityEngine.Random.Range(0.5f, 4f); stone.rigidBody.transform.localScale = new Vector3(scale, scale, scale); stone.rigidBody.AddForce(Vector3.down * meteors.ElementAt(0).damage, ForceMode.Impulse); me.count--; if (me.count == 0) meteors.RemoveAt(0); } } } if (pushData.Count > 0) { var push = pushData[0]; if (push.startTime == DateTime.MinValue) push.startTime = currentTime; player.PersonController.transform.position += push.push * Time.deltaTime; if ((currentTime - push.startTime).TotalMilliseconds > push.duration) pushData.Remove(push); } if (trashResetTime != -1 && currentTime.Millisecond < trashResetTime) { trashResetTime = -1; ObjectSpawnerManager spawnerManager = ComponentManager<ObjectSpawnerManager>.Value; var settings = Traverse.Create(spawnerManager.itemSpawner).Field("currentSettings").GetValue<ObjectSpawnerAssetSettings>(); settings.spawnRateInterval.minValue = spawnRateIntervalMin; settings.spawnRateInterval.maxValue = spawnRateIntervalMax; } } public void ShuffleInv<T>(List<T> slots) where T : Slot { List<ItemInstance> items = new List<ItemInstance>(); foreach (T s in slots) items.Add(s.itemInstance?.Clone()); items.Shuffle(); for (int i = 0; i < slots.Count(); i++) { if (items[i] != null) slots[i].SetItem(items[i]); else slots[i].SetItem(null, 0); } } public async void logItems() { using (StreamWriter file = new StreamWriter("items.txt")) { foreach (var it in ItemManager.GetAllItems()) { await file.WriteLineAsync(it.name); } } } public async void logMobs() { using (StreamWriter file = new StreamWriter("mobs.txt")) { foreach (AI_NetworkBehaviourType value in Enum.GetValues(typeof(AI_NetworkBehaviourType))) { await file.WriteLineAsync(value.ToString()); } } } public Vector3 GetBoundedRandVector(float min, float max, bool inclY = false) { float x; if (UnityEngine.Random.value > 0.5) x = UnityEngine.Random.Range(-max, -min); else x = UnityEngine.Random.Range(min, max); float y = 0; if (inclY) y = UnityEngine.Random.Range(min, max); float z; if (UnityEngine.Random.value > 0.5) z = UnityEngine.Random.Range(-max, -min); else z = UnityEngine.Random.Range(min, max); return new Vector3(x, y, z); } public void SetStatVal(Network_Player player, string stat, float amount) { switch (stat) { case "gravity": player.PersonController.gravity = amount; break; case "swim_speed": player.PersonController.swimSpeed = amount; break; case "walk_speed": player.PersonController.normalSpeed = amount; break; case "jump_speed": player.PersonController.jumpSpeed = amount; break; case "thirst": player.Stats.stat_thirst.Normal.Value = amount; break; case "hunger": player.Stats.stat_hunger.Normal.Value = amount; break; case "oxygen": player.Stats.stat_oxygen.Value = amount; break; case "health": player.Stats.stat_health.Value = amount; break; } } public StatData GetStatData(Network_Player player, string stat, string action, float amount) { StatData data = new StatData(stat); float val = 1; switch (stat) { case "gravity": val = player.PersonController.gravity; break; case "swim_speed": val = player.PersonController.swimSpeed; break; case "walk_speed": val = player.PersonController.normalSpeed; break; case "jump_speed": val = player.PersonController.jumpSpeed; break; case "thirst": val = player.Stats.stat_thirst.Normal.Value; break; case "hunger": val = player.Stats.stat_hunger.Normal.Value; break; case "oxygen": val = player.Stats.stat_oxygen.Value; break; case "health": val = player.Stats.stat_health.Value; break; } data.originalValue = val; data.currentValue = GetAdjustedValue(val, action, amount); return data; } public float GetAdjustedValue(float val, string action, float amount) { switch (action) { case "set": return amount; case "add": return val + amount; case "subtract": return val - amount; default: return amount; } } public IEnumerator Spawner(Network_Player player) { yield return new WaitForSeconds(0.05f); Instantiate(FindObjectOfType<AI_NetworkBehavior_Shark>().transform.gameObject, FindObjectOfType<Network_Player>().transform.position, player.transform.rotation); } private static readonly CancellationTokenSource source = new CancellationTokenSource(); //Tells the connection to shut down public static void Shutdown() { source.Cancel(); } public void FixedUpdate() { var message = RAPI.ListenForNetworkMessagesOnChannel(CHANNEL_ID); if (message != null) { if (message.message.Type == MESSAGE_TYPE_SET_NAME && !Raft_Network.IsHost) { if (message.message is UpdateSharkNameMessage msg) { var maybeShark = NetworkIDManager.GetNetworkIDFromObjectIndex<AI_NetworkBehaviour>(msg.sharkId); if (maybeShark is AI_NetworkBehavior_Shark shark) { var nameTag = shark.stateMachineShark.GetComponentInChildren<TextMeshPro>(); nameTag.text = msg.name; } } } } } public static TextMeshPro AddNametag(AI_StateMachine_Shark shark, string name) { var nameTag = Instantiate(assets.LoadAsset<GameObject>("Name Tag")); nameTag.AddComponent<Billboard>(); nameTag.transform.SetParent(shark.transform); nameTag.transform.localPosition = new Vector3(0, 2f, 0); nameTag.transform.localRotation = Quaternion.identity; var text = nameTag.GetComponentInChildren<TextMeshPro>(); if (Raft_Network.IsHost) text.text = name; return text; } [ConsoleCommand(name: "killall", docs: "Kill all mobs")] public static void KillAllCommand(string[] args) { Network_Entity[] array = FindObjectsOfType<Network_Entity>(); if (array.Length != 0) { Network_Entity[] array2 = array; foreach (Network_Entity network_Entity in array2) { if (network_Entity.entityType == EntityType.Enemy) { ComponentManager<Network_Host>.Value.DamageEntity(network_Entity, network_Entity.transform, 9999f, network_Entity.transform.position, Vector3.up, EntityType.Player); } } } } public class RewardData { public string action; public JObject data; public DateTime added; public int delay; public RewardData(string action, JObject data, int delay, DateTime added) { this.action = action; this.data = data; this.delay = delay; this.added = added; } } public class StatData { public string stat; public float originalValue; public float currentValue; public DateTime timeStarted; public int duration; public StatData(string stat) { this.stat = stat; } } public class TempEntity { public AI_NetworkBehaviour ent; public DateTime spawned; public int duration; public TempEntity(AI_NetworkBehaviour ent) { this.ent = ent; } } public class Meteor { public int count; public int radius; public int damage; public int delay; public DateTime lastSpawned; public Meteor(int count, int radius, int damage, int delay) { this.count = count; this.radius = radius; this.damage = damage; this.delay = delay; } } public class PushData { public Vector3 push; public DateTime startTime = DateTime.MinValue; public int duration; public PushData(Vector3 push, int duration) { this.push = push; this.duration = duration; } } } static class MyExtensions { private static Random rng = new Random(); public static void Shuffle<T>(this IList<T> list) { int n = list.Count; while (n > 1) { n--; int k = rng.Next(n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } } }
using System; namespace Protogame.SHMUP { public class ShmupGame<T> : CoreGame<T> where T : ShmupWorld, new() { } }
using App.Data; using App.Entity; using System.Collections.Generic; namespace App.Logic { public class LogLC { private LogDAC DataAccessCLass = new LogDAC(); public void CreateTable() { DataAccessCLass.CreateTable(); } public void Delete(string filterText) { DataAccessCLass.Delete(filterText); } public void Insert(List<LogBE> tBeClass) { DataAccessCLass.Insert(tBeClass); } public void Insert(LogBE tBeClass) { DataAccessCLass.Insert(tBeClass); } public List<LogBE> SelectAll() { return DataAccessCLass.SelectAll(); } public LogBE Select(string filter) { return DataAccessCLass.Select(filter); } public List<LogBE> SelectList(string filterText) { return DataAccessCLass.SelectList(filterText); } public void Update(string setText, string filter) { DataAccessCLass.Update(setText, filter); } } }
namespace Howff.Navigation.Tests { public class NavigationItemIdFake : INavigationItemId { public NavigationItemIdFake(string id) { Id = id; } public string Id { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Chpoi.SuitUp.Service { public interface ImageService { double[] TakeBodyMeasurements(string frontImageName, string sideImageName, double height); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime; using Xamarin.Forms; using g = GSShared; namespace GS_FinanceAndAnalytics_Sample { public class MainPage : ContentPage { Label mlLabelLoanAmount; Label mlLabelLoanYears; Label mlLabelLoanAPR; Label mlLabelLoanPayment; Label mlLabelLoanPaymentOptions; Label mlLabelLoanOptionsAPR; Label mlLabelLoanOptionsYears; Label mlNumberArray; Label mlMean; Label mlMedian; Label mlMode; Label mlRange; int mintButtonHeight = 25; int mintLabelWidth = 75; int mintFieldWidth = 75; int mintFinLabelWidth = 125; int mintFinFieldWidth = 350; int mintPaymentOptionsHeight = 100; int mintSpacing = 0; int mintHeaderFontSize = 30; int mintPadding = 5; string mstrNumberArray = ""; string mstrAPROptions = ""; string mstrYearsOptions = ""; double mdblPayment; List<List<double>> mlPaymentOptions; double mdblMean; double mdblMedian; List<double[]> mlModes; double mdblRange; double[] mdblArray = new double[] { 3, 74, 9, 1, 750, -54, 3, 7, 8, 1, 74, 10, 2, 3, 3, 74, 74 }; double mdblLoanAmount = 250000; double mdblLoanYears = 30; double mdblLoanAPR = .0425; double[] mdblAPROptions = new double[] { .0375, .0425 }; double[] mdblYearsOptions = new double[] { (180), (360) }; //15 and 30 years public MainPage() { NavigationPage.SetHasNavigationBar(this, false); BackgroundColor = Color.White; switch (Device.OS.ToString()) { case "WinPhone": mintButtonHeight = 75; break; case "iOS": mintFinLabelWidth = 100; mintFinFieldWidth = 375; break; } //parse number array for display for (int i = 0; i < mdblArray.Length; i++) { mstrNumberArray = mstrNumberArray + mdblArray[i].ToString() + ","; } //parse APR array for display for (int i = 0; i < mdblAPROptions.Length; i++) { mstrAPROptions = mstrAPROptions + mdblAPROptions[i].ToString() + ", "; } //parse Term array for display for (int i = 0; i < mdblYearsOptions.Length; i++) { mstrYearsOptions = mstrYearsOptions + mdblYearsOptions[i].ToString() + ", "; } //Begin-Analytics Section Label lAnalyticsHeader = new Label { //Spacer for iOS screen Text = " ", FontSize = mintHeaderFontSize, FontAttributes = FontAttributes.Bold, TextColor = Color.Green, HorizontalOptions = LayoutOptions.CenterAndExpand, }; Button btnTestAnalytics = new Button { Text = "Test GS Analytics Functions", Font = Font.SystemFontOfSize(NamedSize.Small), BorderWidth = 1, HeightRequest = mintButtonHeight, BackgroundColor = Color.Green, TextColor = Color.White, MinimumHeightRequest = mintButtonHeight, HorizontalOptions = LayoutOptions.Center, }; btnTestAnalytics.Clicked += btnTestAnalytics_Clicked; Label lNumberArray = new Label { Text = "Input Array:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintFinLabelWidth, BackgroundColor = Color.Silver, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start, }; mlNumberArray = new Label { Text = mstrNumberArray, TextColor = Color.Black, BackgroundColor = Color.Silver, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.EndAndExpand, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, }; StackLayout slAnalyticsInputFields = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lNumberArray, mlNumberArray } }; Label lMeanLabel = new Label { Text = "Mean:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintLabelWidth, MinimumWidthRequest = mintLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlMean = new Label { Text = " ", TextColor = Color.Black, BackgroundColor = Color.White, WidthRequest = mintFieldWidth, MinimumWidthRequest = mintFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; Label lMedianLabel = new Label { Text = "Median:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintLabelWidth, MinimumWidthRequest = mintLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlMedian = new Label { Text = " ", TextColor = Color.Black, BackgroundColor = Color.White, WidthRequest = mintFieldWidth, MinimumWidthRequest = mintFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slMedian = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lMeanLabel, mlMean, lMedianLabel, mlMedian, } }; Label lModeLabel = new Label { Text = "Mode(s):", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintLabelWidth, MinimumWidthRequest = mintLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlMode = new Label { Text = "", TextColor = Color.Black, BackgroundColor = Color.White, WidthRequest = mintFieldWidth, MinimumWidthRequest = mintFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; Label lRangeLabel = new Label { Text = "Range:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintLabelWidth, MinimumWidthRequest = mintLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlRange = new Label { Text = " ", TextColor = Color.Black, BackgroundColor = Color.White, WidthRequest = mintFieldWidth, MinimumWidthRequest = mintFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slRange = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lModeLabel, mlMode, lRangeLabel, mlRange, } }; //End-Analytics Section //Begin-Finance Section Label lSpace = new Label { Text = " ", FontSize = 10, FontAttributes = FontAttributes.Bold, HorizontalOptions = LayoutOptions.CenterAndExpand, }; Button btnTestFinance = new Button { Text = "Test GS Finance Functions", Font = Font.SystemFontOfSize(NamedSize.Small), BorderWidth = 1, BackgroundColor = Color.Green, TextColor = Color.White, HeightRequest = mintButtonHeight, MinimumHeightRequest = mintButtonHeight, HorizontalOptions = LayoutOptions.Center, //VerticalOptions = LayoutOptions.CenterAndExpand }; btnTestFinance.Clicked += btnTestFinance_Clicked; Label lLoanAmount = new Label { Text = "Loan Amount:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintFinLabelWidth, BackgroundColor = Color.Silver, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanAmount = new Label { Text = String.Format("{0:C}", mdblLoanAmount), TextColor = Color.Black, BackgroundColor = Color.Silver, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanAmount = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanAmount, mlLabelLoanAmount, } }; Label lLoanYears = new Label { Text = "Loan Years:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), MinimumWidthRequest = mintFinLabelWidth, BackgroundColor = Color.Silver, WidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanYears = new Label { Text = mdblLoanYears.ToString(), TextColor = Color.Black, BackgroundColor = Color.Silver, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanYears = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanYears, mlLabelLoanYears, } }; Label lLoanAPR = new Label { Text = "Loan APR:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintFinLabelWidth, BackgroundColor = Color.Silver, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanAPR = new Label { Text = mdblLoanAPR.ToString(), TextColor = Color.Black, BackgroundColor = Color.Silver, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanAPR = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanAPR, mlLabelLoanAPR, } }; Label lLoanPayment = new Label { Text = "Loan Payment:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintFinLabelWidth, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanPayment = new Label { Text = "", TextColor = Color.Black, BackgroundColor = Color.White, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanPayment = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanPayment, mlLabelLoanPayment, } }; Label lLoanOptionsAPR = new Label { Text = "APR Options:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintFinLabelWidth, BackgroundColor = Color.Silver, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanOptionsAPR = new Label { Text = mstrAPROptions, TextColor = Color.Black, BackgroundColor = Color.Silver, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanOptionsAPR = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanOptionsAPR, mlLabelLoanOptionsAPR, } }; Label lLoanOptionsYears = new Label { Text = "Term Options:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), WidthRequest = mintFinLabelWidth, BackgroundColor = Color.Silver, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanOptionsYears = new Label { Text = mstrYearsOptions, TextColor = Color.Black, BackgroundColor = Color.Silver, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanOptionsYears = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanOptionsYears, mlLabelLoanOptionsYears, } }; Label lLoanPaymentOptions = new Label { Text = "Loan Options:", TextColor = Color.Black, FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)), HeightRequest = mintPaymentOptionsHeight, WidthRequest = mintFinLabelWidth, MinimumWidthRequest = mintFinLabelWidth, HorizontalOptions = LayoutOptions.Start }; mlLabelLoanPaymentOptions = new Label { Text = "", TextColor = Color.Black, HeightRequest = mintPaymentOptionsHeight, BackgroundColor = Color.White, WidthRequest = mintFinFieldWidth, MinimumWidthRequest = mintFinFieldWidth, FontSize = Device.GetNamedSize(NamedSize.Micro, typeof(Label)), HorizontalOptions = LayoutOptions.StartAndExpand, }; StackLayout slLoanPaymentOptions = new StackLayout { Spacing = mintSpacing, Padding = mintPadding, Orientation = StackOrientation.Horizontal, Children = { lLoanPaymentOptions, mlLabelLoanPaymentOptions, } }; //End-Finance Section // Build the page from the elements assembled above this.Content = new StackLayout { Spacing = mintSpacing, VerticalOptions = LayoutOptions.FillAndExpand, Children = { lAnalyticsHeader, btnTestAnalytics, slAnalyticsInputFields, btnTestAnalytics, slMedian, slRange, lSpace, btnTestFinance, slLoanAmount, slLoanYears, slLoanAPR, slLoanPayment, slLoanOptionsAPR, slLoanOptionsYears, slLoanPaymentOptions, }, }; } //display analytics functions results void btnTestAnalytics_Clicked(object sender, EventArgs e) { mdblMean = g.MathServices.MeanFromDoubleList(g.Conversions.DoubleArrayToList(mdblArray)); mdblMedian = g.MathServices.MedianFromDoubleList(g.Conversions.DoubleArrayToList(mdblArray)); mlModes = g.MathServices.ModeFromDoubleList(g.Conversions.DoubleArrayToList(mdblArray)); mdblRange = g.MathServices.RangeFromDoubleList(g.Conversions.DoubleArrayToList(mdblArray)); string strModes = ""; for (int i = 0; i < mlModes.Count; i++) { strModes = strModes + mlModes[i][0].ToString() + "(" + mlModes[i][1].ToString() + "),"; } mlMean.Text = Math.Round(mdblMean, 2).ToString(); mlMedian.Text = mdblMedian.ToString(); mlMode.Text = strModes; mlRange.Text = mdblRange.ToString(); } //display financial functions results void btnTestFinance_Clicked(object sender, EventArgs e) { mdblPayment = g.MathServices.CalculatePayments(mdblLoanYears, mdblLoanAPR, mdblLoanAmount); mlPaymentOptions = g.MathServices.CalculatePaymentOptions(mdblLoanAmount, mdblAPROptions, mdblYearsOptions); mlLabelLoanPayment.Text = String.Format("{0:C}", mdblPayment); string strOptions = ""; for (int i = 0; i < mlPaymentOptions.Count; i++) { strOptions = strOptions + String.Format("{0:C}", mlPaymentOptions[i][2]) + "/mo @ " + mlPaymentOptions[i][1].ToString() + " % for " + (mlPaymentOptions[i][0] / 12).ToString() + " yr." + System.Environment.NewLine.ToString(); } mlLabelLoanPaymentOptions.Text = strOptions; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //Task 6 namespace Find_Bigger_Number { class Program { static void Main(string[] args) { Console.Write("Enter num 1: "); int num1 = int.Parse(Console.ReadLine()); Console.Write("Enter num 2: "); int num2 = int.Parse(Console.ReadLine()); int biggerNum = Math.Max(num1, num2); Console.WriteLine("The bigger number is: {0}", biggerNum); } } }
using AutoMapper; using CryptoInvestor.Core.Domain; using CryptoInvestor.Core.Repositories; using CryptoInvestor.Infrastructure.DTO; using CryptoInvestor.Infrastructure.Services.Interfaces; using System.Collections.Generic; using System.Threading.Tasks; namespace CryptoInvestor.Infrastructure.Services { public class CoinService : ICoinService { private readonly ICoinRepository _coinRepository; private readonly IMapper _mapper; public CoinService(ICoinRepository coinRepository, IMapper mapper) { _coinRepository = coinRepository; _mapper = mapper; } public async Task<CoinDto> GetAsync(string symbol) { var coin = await _coinRepository.GetAsync(symbol); return _mapper.Map<CoinDto>(coin); } public async Task<IEnumerable<CoinDto>> BrowseAsync() { var coins = await _coinRepository.BrowseAsync(); return _mapper.Map<IEnumerable<Coin>, IEnumerable<CoinDto>>(coins); } public async Task<IEnumerable<CoinShortDto>> BrowseShortAsync() { var coins = await _coinRepository.BrowseAsync(); return _mapper.Map<IEnumerable<Coin>, IEnumerable<CoinShortDto>>(coins); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SummonController : MonoBehaviour { public GameObject SpawnPoints; public GameObject bridge; public GameObject bigBridge; public GameObject portalEnter; public GameObject portalExit; public GameObject stairs; private List<GameObject> spawn = new List<GameObject>(); private GameObject closestSpawn; private Vector3 position; void Start() { foreach (Transform child in SpawnPoints.transform) spawn.Add(child.gameObject); } // Update is called once per frame void Update() { position = transform.position; summon(); } void summon() { if (Input.anyKey) { check(); } if (Input.GetKeyDown(KeyCode.J)) { if (closestSpawn.tag == "BridgeOnly") { summonBridge(); } } else if (Input.GetKeyDown(KeyCode.U)) { if (closestSpawn.tag == "BigB_Portal") { summonBigBridge(); } } //SUMMON STAIRS else if (Input.GetKeyDown(KeyCode.K)) { if (closestSpawn.tag == "Stairs_Portal") { Quaternion rotation = Quaternion.Euler(-90, 180, 0); summonStairs(rotation); } else if (closestSpawn.tag == "Stairs_PortalL") { Quaternion rotation = Quaternion.Euler(-90, 270, 0); summonStairs(rotation); } else if (closestSpawn.tag == "Stairs_PortalR") { Quaternion rotation = Quaternion.Euler(-90, 90, 0); summonStairs(rotation); } } else if (Input.GetKeyDown(KeyCode.I)) { int isRotated = 0; // Stairs and Raised Portal if (closestSpawn.tag == "Stairs_Portal") { Quaternion rotation = Quaternion.Euler(-90, 90, 0); summonPortal(rotation, isRotated); } else if (closestSpawn.tag == "Stairs_PortalL") { isRotated = 1; Quaternion rotation = Quaternion.Euler(-90, 0, 0); summonPortal(rotation, isRotated); } else if (closestSpawn.tag == "Stairs_PortalR") { isRotated = 2; Quaternion rotation = Quaternion.Euler(-90, 180, 0); summonPortal(rotation, isRotated); } } } void check(){ float range = 30.0f; float closestDistance = float.MaxValue; foreach (GameObject obj in spawn) { float distance = Vector3.Distance(obj.transform.position, position); if (distance < closestDistance && distance <= range) { closestDistance = distance; //Debug.Log(closestDistance); closestSpawn = obj; } } //loop through all spawn points to find closest spawn point } void summonStairs(Quaternion rotation) { GameObject clone; Debug.Log("stairs"); Vector3 stairsLoc = closestSpawn.transform.position; clone = Instantiate(stairs, stairsLoc, rotation); clone.SetActive(true); } void summonBridge() { GameObject clone; Debug.Log("bridge only"); Vector3 bridgeLoc = closestSpawn.transform.position; clone = Instantiate(bridge, bridgeLoc, Quaternion.Euler(-90, 0, 0)); clone.SetActive(true); } void summonBigBridge() { GameObject clone; Debug.Log("big bridge"); Vector3 bigBridgeLoc = closestSpawn.transform.position; bigBridgeLoc.y += 4; clone = Instantiate(bigBridge, bigBridgeLoc, Quaternion.Euler(-90, 180, 0)); clone.SetActive(true); } void summonPortal(Quaternion rotation, int isRotated) { GameObject clone1, clone2; Debug.Log("raised portal"); //portal enter Vector3 portalEnterLoc = closestSpawn.transform.position; Vector3 portalExitLoc = closestSpawn.transform.position; if (isRotated == 1) { portalEnterLoc.z += 11.0f; portalEnterLoc.y += 2.5f; portalExitLoc.z -= 12.0f; portalExitLoc.y += 11.0f; } else if (isRotated == 2) { portalEnterLoc.z -= 11.0f; portalEnterLoc.y += 2.5f; portalExitLoc.z += 12.0f; portalExitLoc.y += 11.0f; } else { portalEnterLoc.x -= 11.0f; portalEnterLoc.y += 2.0f; portalExitLoc.x += 11.0f; portalExitLoc.y += 10.5f; } clone1 = Instantiate(portalEnter, portalEnterLoc, rotation); clone1.SetActive(true); clone2 = Instantiate(portalExit, portalExitLoc, rotation); clone2.SetActive(true); //TELEPORT float distEnter = Vector3.Distance(portalEnterLoc, position); float distExit = Vector3.Distance(portalExitLoc, position); if (distEnter < distExit) { transform.position = portalExitLoc; } else { transform.position = portalEnterLoc; } } }
using LuaInterface; using SLua; using System; public class Lua_JetBrains_Annotations_ImplicitUseKindFlags : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "JetBrains.Annotations.ImplicitUseKindFlags"); LuaObject.addMember(l, 1, "Access"); LuaObject.addMember(l, 2, "Assign"); LuaObject.addMember(l, 4, "InstantiatedWithFixedConstructorSignature"); LuaObject.addMember(l, 7, "Default"); LuaObject.addMember(l, 8, "InstantiatedNoFixedConstructorSignature"); LuaDLL.lua_pop(l, 1); } }
using UnityEngine; using UnityEditor; using System.IO; using System.Reflection; using System.Collections; using System.Collections.Generic; public class XBuild_Audio : CBuild_Base { public override string GetDirectory() { return "Audio"; } public override string GetExtention() { return "dir"; } public override void Export(string path) { if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.StandaloneWindows) { ExportPkg(path); } else if (EditorUserBuildSettings.activeBuildTarget == BuildTarget.Android || EditorUserBuildSettings.activeBuildTarget == BuildTarget.iPhone) { //ExportMobile(path); ExportPkg(path); } else { CDebug.LogError("Error Build Audio {0}", path); } } void ExportPkg(string path) { path = path.Replace('\\', '/'); DirectoryInfo dirInfo = new DirectoryInfo(path); FileInfo[] fileInfoList = dirInfo.GetFiles(); foreach (FileInfo fileInfo in fileInfoList) { string file = string.Format("{0}/{1}", path, fileInfo.Name); if (!BuildPkg(file)) continue; } } public bool BuildPkg(string file) { //if (!CBuildTools.CheckNeedBuild(file)) //{ // return false; //} AudioClip audioClip = AssetDatabase.LoadAssetAtPath(file, typeof(AudioClip)) as AudioClip; if (audioClip != null) { string subDirName = Path.GetFileName(Path.GetDirectoryName(file)); string exportFile = string.Format("Audio/{0}/{1}_Audio{2}", subDirName, Path.GetFileNameWithoutExtension(file), CCosmosEngine.GetConfig("AssetBundleExt")); CBuildTools.BuildAssetBundle(audioClip, exportFile); //CBuildTools.MarkBuildVersion(file); } return true; } //void ExportMobile(string path) //{ // path = path.Replace('\\', '/'); // DirectoryInfo dirInfo = new DirectoryInfo(path); // FileInfo[] fileInfoList = dirInfo.GetFiles(); // foreach (FileInfo fileInfo in fileInfoList) // { // string file = string.Format("{0}/{1}", path, fileInfo.Name); // if (!XBuildTools.CheckNeedBuild(file)) // continue; // XBuildTools.MarkBuildVersion(file); // } // string srcPath = GetDirectory() + path.Substring(path.LastIndexOf('/')); // string destPath = XBuildTools.MakeSureExportPath(srcPath, EditorUserBuildSettings.activeBuildTarget); // XBuildTools.CopyFolder(path, destPath); //} }
using Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Admin.Helpers { public class DataHelper { #region Enums public enum CarStatus { Active = 1, Sold = 2, Deleted = 3 } public enum CarTransmission { Automatic = 1, Manual = 2 } public enum CarCondition { New = 1, Used = 2 } #endregion #region User public string UserID { get { if (HttpContext.Current.Session["Global_UserID"] != null) return HttpContext.Current.Session["Global_UserID"].ToString(); else return null; } set { HttpContext.Current.Session["Global_UserID"] = value; } } public Boolean User_IsLoggedIn { get { if (HttpContext.Current.Session["Global_UserIsLoggedIn"] != null) return Convert.ToBoolean(HttpContext.Current.Session["Global_UserIsLoggedIn"]); else return false; } set { HttpContext.Current.Session["Global_UserIsLoggedIn"] = value; } } public string UserFullName { get { if (HttpContext.Current.Session["Global_UserFullName"] != null) return HttpContext.Current.Session["Global_UserFullName"].ToString(); else return ""; } set { HttpContext.Current.Session["Global_UserFullName"] = value; } } #endregion #region Currency public List<Currency> CurrencyList { get { Entities _ctx = new Entities(); if (HttpContext.Current.Session["Global_CurrencyList"] == null) HttpContext.Current.Session["Global_CurrencyList"] = (from cur in _ctx.Currencies where cur.IsActive == true && cur.IsDeleted == false select cur).ToList(); return HttpContext.Current.Session["Global_CurrencyList"] as List<Currency>; } set { HttpContext.Current.Session["Global_CurrencyList"] = value; } } #endregion #region Car public string Car_SmallImage { get { if (HttpContext.Current.Session["Global_CarSmallImage"] != null) return HttpContext.Current.Session["Global_CarSmallImage"].ToString(); else return null; } set { HttpContext.Current.Session["Global_CarSmallImage"] = value; } } public string Car_LargeImage { get { if (HttpContext.Current.Session["Global_CarLargeImage"] != null) return HttpContext.Current.Session["Global_CarLargeImage"].ToString(); else return null; } set { HttpContext.Current.Session["Global_CarLargeImage"] = value; } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Cors; namespace WebApplication1.Controllers { [EnableCors(methods: "*", headers: "*", origins: "*")] public class categoryController : ApiController { [HttpGet] public IHttpActionResult GettAllCategory() { return Ok(DB.categoryList); } [HttpPost] public Category FindCategory(Category name) { foreach (Category c in DB.categoryList) if (c.CategoryName == name.CategoryName) return c; return null; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Data; using UGCS.Example.Properties; namespace UGCS.Example.Helpers { public class StringMetersConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return "N/A"; } Double val = (Double)value; if (Double.IsNaN(val)) { val = 0; } return Math.Round(val, 1) + " m"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException("StringMetersConverter, ConvertBack not implemented"); } } public class MetersConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return "N/A"; } float val = (float)value; if (float.IsNaN(val)) { val = 0; } return Math.Round(val, 1) + " m"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException("MetersConverter, ConvertBack not implemented"); } } public class MetersSecConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value == null) { return "N/A"; } float val = (float)value; if (float.IsNaN(val)) { val = 0; } return Math.Round(val, 1) + " m"; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException("MetersSecConverter, ConvertBack not implemented"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MJGame { abstract class Place { //Vars protected string introText; public List<Item> groundItems = new List<Item>(); //Methods public void Arrived() { Program.curPlace = this; Console.Clear(); Console.WriteLine( GetIntroText() ); Console.WriteLine("On the ground:"); int i = 0; while (i < groundItems.Count) { Console.WriteLine(groundItems[i].label); i = i + 1; } } protected virtual string GetIntroText() { return introText; } public abstract bool HandleInput_Place(string inp); } }
using System; using System.Diagnostics; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; using Vaccination.Models.DTO; using Vaccination.Models.ViewModel; using Vaccination.Services; using Vaccination.Services.Exceptions; namespace Vaccination.Controllers { public class VaccineController : Controller { private readonly VaccineService _vaccineService; public VaccineController(VaccineService vaccineService) { _vaccineService = vaccineService; } [Authorize] public async Task<IActionResult> Index() { var list = await _vaccineService.FindAllAsync(); return View(list); } [Authorize] public IActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create(VaccineDTO dto) { if(!ModelState.IsValid) return View(); await _vaccineService.InsertAsync(dto); Response.StatusCode = 200; return RedirectToAction(nameof(Index)); } [Authorize] public async Task<IActionResult> Edit(int? id) { if (id == null) return RedirectToAction(nameof(Error), new { message = "Id not provided"}); var obj = await _vaccineService.FindByIdAsync(id.Value); if (obj == null) return RedirectToAction(nameof(Error), new { message = "Id not found"}); return View(obj); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, VaccineDTO dto) { if (!ModelState.IsValid) return View(dto); if (id != dto.Id) return RedirectToAction(nameof(Error), new { message = "Id mismatch" }); try { await _vaccineService.UpdateAsync(dto); return RedirectToAction(nameof(Index)); } catch (ApplicationException e) { return RedirectToAction(nameof(Error), new { message = e.Message}); } } [Authorize] public async Task<IActionResult> Delete(int? id) { if (id == null) return RedirectToAction(nameof(Error), new { message = "Id not provided"}); var obj = await _vaccineService.FindByIdAsync(id.Value); if (obj == null) return RedirectToAction(nameof(Error), new { message = "Id not found"}); return View(obj); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Delete(int id) { try { await _vaccineService.RemoveAsync(id); return RedirectToAction(nameof(Index)); } catch (IntegrityException e) { return RedirectToAction(nameof(Error), new { message = e.Message }); } } public IActionResult Error(string message) { var viewModel = new ErrorViewModel { Message = message, RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }; return View(viewModel); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using PlayTennis.Bll; using PlayTennis.Model; using PlayTennis.Model.Dto; namespace PlayTennis.WebApi.Controllers { public class UserInformationController : ApiController { private static readonly Guid _defaultValue = Guid.Empty; public UserInformationService UserInformationService { get; set; } public UserInformationController() { UserInformationService = new UserInformationService(); } // GET: api/UserInformation //public IEnumerable<string> Get() //{ // return new string[] { "value1", "value2" }; //} // GET: api/UserInformation/5 /// <summary> /// 获取用户信息 /// </summary> /// <param name="id">wxUserid</param> /// <param name="idType">0:默认,微信id;1: userinfor id</param> /// <param name="initiatorId">发起者id</param> /// <returns></returns> public UserInformationDto Get(Guid id, string initiatorId = null, int idType = 0) { if (idType == 0) { return UserInformationService.GetUserInformationById(id); } else { return UserInformationService.GetUserInformationByuserInformationId(id, new Guid(initiatorId)); } } // POST: api/UserInformation public void Post([FromBody]string value) { } // PUT: api/UserInformation/5 public void Put(int id, [FromBody]string value) { } // DELETE: api/UserInformation/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BPiaoBao.Web.SupplierManager.Models { public class NoticeQueryEntity { public string Title { get; set; } public string Code { get; set; } public bool? State { get; set; } public DateTime? StartTime { get; set; } public DateTime? EndTime { get; set; } public int page { get; set; } public int rows { get; set; } } }
using System; using System.Collections.Generic; using Xunit; using CompoundInterest; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; namespace MyXUnitTests { public class CompoundInterestUnitTest { //[Fact] //public void TestConvertStringToValues_0() //{ // Tuple<double, double, int> actual = Balance.ConvertStringToValues("100.00 12 1"); // Tuple<double, double, int> expected = new Tuple<double, double, int>(100.0, 12.0, 1); // Assert.Equal(expected, actual); //} [Fact] public void TestConvertStringToValues_1() { Tuple<double, double, int> actual = Balance.ConvertStringToValues("100,00 12 1"); Tuple<double, double, int> expected = new Tuple<double, double, int>(100.0, 12.0, 1); Assert.Equal(expected, actual); } [Fact] public void TestCalculate_0() { double actual = Balance.Calculate("100,00 12 0"); double expected = 100.0; Assert.Equal(expected, actual); } [Fact] public void TestCalculate_1() { double actual = Balance.Calculate("100,00 12 1"); double expected = 101.0; Assert.Equal(expected, actual); } [Fact] public void TestCalculate_3() { double actual = Balance.Calculate("1000,1 1,2 1"); double expected = 1001.1001; Assert.Equal(expected, actual, 4); } [Fact] public void TestCalculate_2() { double actual = Balance.Calculate("100,00 12 2"); double expected = 102.01; Assert.Equal(expected, actual); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace BobSquad.CustomClasses { /// <summary> /// Interaction logic for FloorPage.xaml /// </summary> public partial class FloorPage : Page { private string floorId; public FloorPage(string floorId) { this.floorId = floorId; InitializeComponent(); try { navigationStack.Orientation = Orientation.Horizontal; DataTable _floors = Services.DB.RunSelectCommand("select top 1 * from Floors where Id = @FloorId", new List<System.Data.SqlClient.SqlParameter>() { new System.Data.SqlClient.SqlParameter("FloorId", this.floorId) }); foreach (DataRow floor in _floors.Rows) { BitmapSource bSource = new BitmapImage(new Uri(@"Resources\" + floor["Layout"], UriKind.Relative)); LayoutCanvas.Background = new ImageBrush(bSource); Label header = new Label() { FontSize = 20, Foreground = new SolidColorBrush(Colors.Black), Height = double.NaN, Width = double.NaN, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center }; header.Content = "Piętro " + floor["Number"]; Button previonsButton = new Button() { Height = 40, Width = 40, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Background = new SolidColorBrush(Colors.White), Content = "<", Margin = new Thickness(10, 5, 5, 5) }; if (floorId == "1") previonsButton.IsEnabled = false; Button nextButton = new Button() { Height = 40, Width = 40, HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Center, Background = new SolidColorBrush(Colors.White), Content = ">", Margin = new Thickness(5) }; if (floorId == "2") nextButton.IsEnabled = false; previonsButton.Click += PrevionsButton_Click; nextButton.Click += NextButton_Click; navigationStack.Children.Add(header); navigationStack.Children.Add(previonsButton); navigationStack.Children.Add(nextButton); } DataTable _rooms = Services.DB.RunSelectCommand("select * from Rooms where Floor = @FloorId", new List<System.Data.SqlClient.SqlParameter>() { new System.Data.SqlClient.SqlParameter("FloorId", this.floorId) }); foreach (DataRow _room in _rooms.Rows) { CustomClasses.RoomControl room = new CustomClasses.RoomControl(new System.Drawing.Point(Convert.ToInt32(_room["LocalizationX"]), Convert.ToInt32(_room["LocalizationY"])), new System.Drawing.Size(Convert.ToInt32(_room["SizeX"]), Convert.ToInt32(_room["SizeY"])), _room["Id"].ToString()); room.Width = Convert.ToInt32(_room["SizeX"]); room.Height = Convert.ToInt32(_room["SizeY"]); Canvas.SetLeft(room, Convert.ToInt32(_room["LocalizationX"])); Canvas.SetTop(room, Convert.ToInt32(_room["LocalizationY"])); LayoutCanvas.Children.Add(room); } } catch (Exception ex) { } } private void NextButton_Click(object sender, RoutedEventArgs e) { this.NavigationService?.Navigate(new FloorPage((Convert.ToInt32(floorId) + 1).ToString())); } private void PrevionsButton_Click(object sender, RoutedEventArgs e) { this.NavigationService?.Navigate(new FloorPage((Convert.ToInt32(floorId) - 1).ToString())); } } }
using LaserMaze.Enums; using LaserMaze.Models; using System.Collections.Generic; using System.Linq; namespace LaserMaze { public class LaserMazeRunner { public List<IRoom> Rooms { get; set; } private GridCoordinates _gridSize; private List<Mirror> _mirrors; private LaserPoint _startingLaserPoint; private LaserPoint _previousLaserPoint; private bool hasExited; public LaserMazeRunner(LaserMazeConfiguration config) { _mirrors = config.Mirrors; _startingLaserPoint = config.LaserStartingPoint; _gridSize = config.GridSize; Rooms = BuildRooms(_gridSize); } public LaserPoint GetLaserExitPoint() { _previousLaserPoint = _startingLaserPoint; while (!hasExited) { var nextPoint = GetNextLaserPoint(_previousLaserPoint); if (nextPoint == null) { hasExited = true; } } return _previousLaserPoint; } private LaserPoint GetNextLaserPoint(LaserPoint _currentLaserPoint) { var currentRoom = Rooms.Where(a => a.Coordinates.X == _currentLaserPoint.Coordinates.X && a.Coordinates.Y == _currentLaserPoint.Coordinates.Y).FirstOrDefault(); if (currentRoom == null) { return null; } else { _previousLaserPoint = _currentLaserPoint; var nextPoint = currentRoom.GetNextLaserPosition(_currentLaserPoint.Direction); return GetNextLaserPoint(nextPoint); } } private List<IRoom> BuildRooms(GridCoordinates gridSize) { var rooms = new List<IRoom>(); for (int y = 0; y <= gridSize.Y; y++) { for (int x = 0; x <= gridSize.X; x++) { var currentCoordinates = new GridCoordinates(x, y); var mirror = _mirrors.Where(a => a.Coordinates.X == currentCoordinates.X && a.Coordinates.Y == currentCoordinates.Y).FirstOrDefault(); if (mirror == null) { rooms.Add(new EmptyRoom { Coordinates = new GridCoordinates(x, y) }); } else { if (mirror.MirrorOrientation == MirrorOrientation.Right) rooms.Add(new RightAngleMirrorRoom(mirror)); else rooms.Add(new LeftAngleMirrorRoom(mirror)); } } } return rooms; } } }
using System; using System.Data; using System.Text; using System.Collections.Generic; using Maticsoft.DBUtility;//Please add references namespace PDTech.OA.DAL { public class VIEW_ARCHIVE_STEMP { public VIEW_ARCHIVE_STEMP() { } #region BasicMethod /// <summary> /// 获取公文相关信息列表 /// </summary> /// <param name="where"></param> /// <returns></returns> public IList<Model.VIEW.VIEW_ARCHIVE_STEMP> get_ViewArchiveStep(Model.VIEW.VIEW_ARCHIVE_STEMP where) { string condition = DAL_Helper.GetWhereCondition(where); string selSQL = string.Format(@"SELECT * FROM VIEW_ARCHIVE_STEMP WHERE 1=1 {0}",condition); DataTable dt = DbHelperSQL.GetTable(selSQL); return DAL_Helper.CommonFillList<Model.VIEW.VIEW_ARCHIVE_STEMP>(dt); } /// <summary> /// 获取公文相关信息 /// </summary> /// <param name="where"></param> /// <returns></returns> public Model.VIEW.VIEW_ARCHIVE_STEMP get_viewarchivestepInfo(Model.VIEW.VIEW_ARCHIVE_STEMP where) { string condition = DAL_Helper.GetWhereCondition(where); string selSQL = string.Format(@"SELECT * FROM VIEW_ARCHIVE_STEMP WHERE 1=1 {0}", condition); DataTable dt = DbHelperSQL.GetTable(selSQL); if (dt.Rows.Count > 0) { return DAL_Helper.CommonFillList<Model.VIEW.VIEW_ARCHIVE_STEMP>(dt)[0]; } else { return null; } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GlueScript : MonoBehaviour { //private float Seconds = 0.05f; private float breakForce = 150f; private FixedJoint fj; private List <GameObject> previousHits = new List<GameObject>(); public float fixedBodyCount; public bool justLoaded; void Update() { foreach(FixedJoint _fixedJoint in gameObject.GetComponents<FixedJoint>()) { if(_fixedJoint.connectedBody == null) { Destroy(_fixedJoint); } } if (justLoaded) { if(fixedBodyCount == gameObject.GetComponents<FixedJoint>().Length) { gameObject.GetComponent<BlockSaveManager>().LoadPhysics(); justLoaded = false; } } } void OnCollisionEnter(Collision collision) { bool canGlue = true; foreach(GameObject hit in previousHits) { if(hit == collision.gameObject) canGlue = false; else canGlue = true; } // if it has a rigid body and is on a tower if ( canGlue == true && collision.rigidbody != null && collision.gameObject.tag == "Tower" || collision.gameObject.tag == "Foundation") { //StartCoroutine(Glue(Seconds, collision)); gameObject.tag = "Tower"; fj = gameObject.AddComponent<FixedJoint>(); fj.connectedBody = collision.rigidbody; fj.breakForce = breakForce; previousHits.Add(collision.gameObject); } // no leftover gluescripts 4 me else if (collision.gameObject.GetComponent<GlueScript>() == null) { DestroyFixedJoints(); Destroy(this); } } IEnumerator Glue(float Seconds, Collision collision) { yield return new WaitForSeconds(Seconds); if (collision.rigidbody != this.gameObject.GetComponent<Rigidbody>()) { } } public void DestroyFixedJoints() { foreach (FixedJoint _fj in gameObject.GetComponents<FixedJoint>()) { Destroy(_fj); } } public void DetachConnectedGameObjects() { foreach (FixedJoint _fj in gameObject.GetComponents<FixedJoint>()) { if (_fj.connectedBody != null) { if (_fj.connectedBody.gameObject.GetComponent<GlueScript>() != null) { //Debug.Log(_fj.connectedBody.name); _fj.connectedBody.gameObject.GetComponent<GlueScript>().DetachGameobject(gameObject); } } // Destroy(_fj); } } public void DetachGameobject(GameObject _detachedGameObject) { foreach (FixedJoint _fixedJoint in gameObject.GetComponents<FixedJoint>()) { if(_fixedJoint.connectedBody == _detachedGameObject.GetComponent<Rigidbody>()) { //Debug.Log("Destroy"); Destroy(_fixedJoint); } } } }
using System.Windows.Forms; using System; using System.Drawing; namespace QuanLyTiemGiatLa.HeThong { public partial class frmCauHinhHeThong : Form { public frmCauHinhHeThong() { InitializeComponent(); this.Load += new System.EventHandler(frmCauHinhHeThong_Load); } private void frmCauHinhHeThong_Load(object sender, System.EventArgs e) { try { nudTreEmGiamGia.Value = Xuly.ThaoTacIniCauHinhPhanMem.ReadTreEmGiamGia(); nudGiatNhanhTangGia.Value = Xuly.ThaoTacIniCauHinhPhanMem.ReadGiatNhanhTangGia(); nudPhiVanChuyen.Value = Xuly.ThaoTacIniCauHinhPhanMem.ReadPhiVanChuyen(); nudNgayLapTra.Value = Xuly.ThaoTacIniCauHinhPhanMem.ReadNgayLapNgayHenTra(); nudViecCanLam.Value = Xuly.ThaoTacIniCauHinhPhanMem.ReadViecCanLam(); cboCatDoFocus.SelectedIndex = Xuly.ThaoTacIniCauHinhPhanMem.ReadCatdoFocus(); nudSoLanIn.Value = Xuly.ThaoTacIniCauHinhPhanMem.ReadSoLanIn(); chkDungMaVach.Checked = Xuly.ThaoTacIniCauHinhPhanMem.ReadDungMaVach(); chkToanManHinh.Checked = BienChung.isToanManHinh; txtTenCuaHang.Text = Xuly.ThaoTacIniCauHinhPhanMem.ReadTenCuaHang(); txtDiaChi.Text = Xuly.ThaoTacIniCauHinhPhanMem.ReadDiaChiCuaHang(); txtDienThoaiCuaHang.Text = Xuly.ThaoTacIniCauHinhPhanMem.ReadSoDienThoai(); txtMaVach.Text = (Xuly.ThaoTacIniMaVach.Read() + 1).ToString(); txtXoayVongTu.Text = Xuly.ThaoTacIniMaVach.ReadMaVachBatDau().ToString(); txtXoayVongDen.Text = Xuly.ThaoTacIniMaVach.ReadMaVachKetThuc().ToString(); BienChung.mautrangthaido = Xuly.ThaoTacIniCauHinhPhanMem.ReadMauTrangThaiDo(); this.DoiMauButton(); if (BienChung.isTrienKhai) btnBackUp.Enabled = (BienChung.userCurrent != null) ? (BienChung.userCurrent.ChucVu == Entity.ChucVu.Admin) : false; } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void DoiMauButton() { btnMauDoChuaGiat.BackColor = BienChung.mautrangthaido.ChuaGiat; btnMauDoDaGiat.BackColor = BienChung.mautrangthaido.DaGiat; btnMauDoGhiChu.BackColor = BienChung.mautrangthaido.GhiChu; btnMauDoDaTra.BackColor = BienChung.mautrangthaido.DaTra; btnMauDoPhieuHuy.BackColor = BienChung.mautrangthaido.PhieuHuy; } private bool CheckForm() { txtMaVach.Text = txtMaVach.Text.Trim(); long mavach; if (!Int64.TryParse(txtMaVach.Text, out mavach)) { MessageBox.Show("Mã vạch phải là số", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtMaVach.Focus(); return false; } long mavachbd, mavachkt; mavachbd = Int64.Parse(txtXoayVongTu.Text); mavachkt = Int64.Parse(txtXoayVongDen.Text); if (mavachbd > mavachkt) { MessageBox.Show("Mã vạch bắt đầu phải nhỏ hơn mã vạch kết thúc", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); txtXoayVongTu.Focus(); return false; } if (mavachbd != mavachkt && !(mavachbd <= mavach && mavach <= mavachkt)) { MessageBox.Show("Mã vạch phải nằm trong khoảng bắt đầu đến kết thúc", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Warning); return false; } return true; } private void btnGhi_Click(object sender, System.EventArgs e) { try { if (!this.CheckForm()) return; Xuly.ThaoTacIniCauHinhPhanMem.Write(Convert.ToInt32(nudTreEmGiamGia.Value), Convert.ToInt32(nudGiatNhanhTangGia.Value), Convert.ToInt32(nudPhiVanChuyen.Value), Convert.ToInt32(nudNgayLapTra.Value), Convert.ToInt32(nudViecCanLam.Value), cboCatDoFocus.SelectedIndex, Convert.ToInt32(nudSoLanIn.Value), txtTenCuaHang.Text, txtDiaChi.Text, txtDienThoaiCuaHang.Text, BienChung.mautrangthaido, chkDungMaVach.Checked, chkToanManHinh.Checked ); Xuly.ThaoTacIniMaVach.Write(Int64.Parse(txtMaVach.Text) - 1); Xuly.ThaoTacIniMaVach.Write(Int64.Parse(txtXoayVongTu.Text), Int64.Parse(txtXoayVongDen.Text)); MessageBox.Show("Cập nhật thành công!", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Close(); } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnThoat_Click(object sender, System.EventArgs e) { this.Close(); } private frmBackUpDuLieu m_frmBackupDuLieu = null; private void btnBackUp_Click(object sender, EventArgs e) { try { if (m_frmBackupDuLieu == null || m_frmBackupDuLieu.IsDisposed) { m_frmBackupDuLieu = new frmBackUpDuLieu(); } m_frmBackupDuLieu.ShowDialog(this); } catch (System.Exception ex) { MessageBox.Show(ex.Message, "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void btnMauDoChuaGiat_Click(object sender, EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AllowFullOpen = true; // allow custom colors cd.FullOpen = true; // shows custom colors automatically cd.Color = BienChung.mautrangthaido.ChuaGiat; if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { btnMauDoChuaGiat.BackColor = cd.Color; BienChung.mautrangthaido.ChuaGiat = cd.Color; } } private void btnMauDoDaGiat_Click(object sender, EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AllowFullOpen = true; // allow custom colors cd.FullOpen = true; // shows custom colors automatically cd.Color = BienChung.mautrangthaido.DaGiat; if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { btnMauDoDaGiat.BackColor = cd.Color; BienChung.mautrangthaido.DaGiat = cd.Color; } } private void btnMauDoGhiChu_Click(object sender, EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AllowFullOpen = true; // allow custom colors cd.FullOpen = true; // shows custom colors automatically cd.Color = BienChung.mautrangthaido.GhiChu; if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { btnMauDoGhiChu.BackColor = cd.Color; BienChung.mautrangthaido.GhiChu = cd.Color; } } private void btnMauDoDaTra_Click(object sender, EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AllowFullOpen = true; // allow custom colors cd.FullOpen = true; // shows custom colors automatically cd.Color = BienChung.mautrangthaido.DaTra; if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { btnMauDoDaTra.BackColor = cd.Color; BienChung.mautrangthaido.DaTra = cd.Color; } } private void btnMauDoPhieuHuy_Click(object sender, EventArgs e) { ColorDialog cd = new ColorDialog(); cd.AllowFullOpen = true; // allow custom colors cd.FullOpen = true; // shows custom colors automatically cd.Color = BienChung.mautrangthaido.PhieuHuy; if (cd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { btnMauDoPhieuHuy.BackColor = cd.Color; BienChung.mautrangthaido.PhieuHuy = cd.Color; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Senai.Senatur.WebApi.Domains; using Senai.Senatur.WebApi.Interfaces; using Senai.Senatur.WebApi.Repositories; // For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Senai.Senatur.WebApi.Controllers { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class TiposUsuarioController : ControllerBase { private ITipoUsuarioRepository _tipoUsuarioRepository { get; set; } public TiposUsuarioController() { _tipoUsuarioRepository = new TipoUsuarioRepository(); } [Authorize(Roles = "1")] [HttpGet] public IActionResult Get() { return StatusCode(200, _tipoUsuarioRepository.Listar()); } [Authorize(Roles = "1")] [HttpGet("{Id}")] public IActionResult GetById(int Id) { return StatusCode(200, _tipoUsuarioRepository.BuscarPorID(Id)); } [Authorize(Roles = "1")] [HttpPost] public IActionResult Post(TiposUsuario novoTipo) { _tipoUsuarioRepository.Cadastrar(novoTipo); return StatusCode(201); } [Authorize(Roles = "1")] [HttpDelete("{Id}")] public IActionResult Delete(int Id) { _tipoUsuarioRepository.Deletar(Id); return StatusCode(204); } [Authorize(Roles = "1")] [HttpPut] public IActionResult Put(int Id,TiposUsuario tipoAtualizado) { _tipoUsuarioRepository.Atualizar(Id, tipoAtualizado); return StatusCode(200); } } }
using JqGridCodeGenerator.ViewModel; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JqGridCodeGenerator { public static class TypeWithNamespaceExtensions { public static string GetNamespaceForType(this List<TypeWithNamespace> list,string typeName) { foreach(var typeWithNamespace in list) { if (typeWithNamespace.Name == typeName) return typeWithNamespace.Nmspc; } return "unknownNamespaceForType_" + typeName; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using CaseReportal.Model.Entities; using CaseReportal.Models; using NHibernate; namespace CaseReportal.Controllers { [HandleError] public class HomeController : Controller { private readonly ISession _Session; public HomeController(ISession session) { this._Session = session; } public ActionResult ViewArticle(int? articleId) { if (articleId.HasValue == false) { return Index(); } Article article; using (var itx = _Session.BeginTransaction()) { article = _Session.QueryOver<Article>().Where(x => x.Id == articleId).SingleOrDefault(); } return View(article); } public ActionResult Index() { if (this.User.Identity.IsAuthenticated == false) { return View(); } var homeViewModel = new HomeViewModel(); using (var itx =_Session.BeginTransaction()) { var requiredReviewCount = _Session.QueryOver<Config>().SingleOrDefault().RevCount; homeViewModel.Articles = _Session.CreateQuery("select a from Article a where size(a.Reviews) >= :reviewCount") .SetInt32("reviewCount", requiredReviewCount) .List<Article>() .Where(x=>x.Reviews.Where(y=>y.Approved).Count() >= requiredReviewCount); itx.Commit(); } return View(homeViewModel); } public ActionResult About() { return View(); } } }
using UnityEngine; using System.Collections; public class Menu : MonoBehaviour { public SnakeGame Game; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetButtonDown("Menu")) { Canvas canv = GetComponent<Canvas>(); if (Game.Status == SnakeGame.STATUS_PLAY) { canv.enabled = true; Game.Status = SnakeGame.STATUS_PAUSED; } else if (Game.Status == SnakeGame.STATUS_PAUSED) { canv.enabled = false; Game.Status = SnakeGame.STATUS_PLAY; } } } public void BtnPlayClick(int level) { GameObject.Find("CanvasMenu").GetComponent<Canvas>().enabled = false; if (Game.Status == SnakeGame.STATUS_PAUSED) { Game.Status = SnakeGame.STATUS_PLAY; } else if (Game.Status == SnakeGame.STATUS_MAIN_MENU) { Game.ResetGame(); Game.Status = SnakeGame.STATUS_PLAY; } } public void BtnQuitClick() { Debug.Log("Application.Quit"); Application.Quit(); } }
using Application.Common.Interfaces; using Application.Common.Models; using MediatR; using System.Threading; using System.Threading.Tasks; namespace Application.V1.Users.Commands { public static class LoginUser { public record Command(string Email, string Password) : IRequest<CQRSResponse>; public class Handler : IRequestHandler<Command, CQRSResponse> { private readonly IAuthService _authService; public Handler(IAuthService authService) { _authService = authService; } public async Task<CQRSResponse> Handle(Command request, CancellationToken cancellationToken) { return await _authService.GenerateJwtTokens(request.Email); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using AutoMapper; using EpicenterV2.Data.Queries; using EpicenterV2.Models; namespace EpicenterV2.Controllers { public class ShowsController : Controller { // GET: Shows public ActionResult Index() { var shows = GetShows(); return PartialView(shows); } private IEnumerable<Show> GetShows() { var showDtos = new GetShowsQuery().Execute(); var showViewModels = new List<Show>(); foreach (var dto in showDtos) { showViewModels.Add(new Show { ShowId = dto.ShowId, ShowName = dto.ShowName }); } return showViewModels; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; namespace Web.SendToUser { public class UserHub : Hub { public void Send(string user, string message) { Clients.User(user).newMessage(message); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Assets.Scripts.GameLogic.TowerSystem { [System.Serializable] public class UpgradeSlot { public Upgrade m_Upgrade=null; public UpgradeSlot[] m_FollowingUpgrades; } }
using System.Collections.Generic; using IVeraControl.Model; using UpnpModels.Model.UpnpDevice.Base; using UpnpModels.Model.UpnpService; namespace UpnpModels.Model.UpnpDevice { // Spec: http://upnp.org/specs/ha/UPnP-ha-HVAC_ZoneThermostat-v1-Device.pdf public class HVAC_ZoneThermostat1: UpnpDeviceBase, IUpnpDevice { public string DeviceUrn => "urn:schemas-upnp-org:device:HVAC_ZoneThermostat:1"; public string DeviceName => nameof(HVAC_ZoneThermostat1); public HVAC_ZoneThermostat1(IVeraController controller) { Services = new List<IUpnpService> { new TemperatureSetpoint1(controller, this), new TemperatureSensor1Service(controller, this) }; } } }
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; using Evpro.Domain.Entities; namespace Evpro.Data.Models.Mapping { public class oureventMap : EntityTypeConfiguration<ourevent> { public oureventMap() { // Primary Key this.HasKey(t => t.idEvent); // Properties this.Property(t => t.category) .HasMaxLength(255); this.Property(t => t.cityAdress) .HasMaxLength(255); this.Property(t => t.countryAdress) .HasMaxLength(255); this.Property(t => t.description) .HasMaxLength(255); this.Property(t => t.eventType) .HasMaxLength(255); this.Property(t => t.facebookEventLink) .HasMaxLength(255); this.Property(t => t.name) .HasMaxLength(255); this.Property(t => t.slogan) .HasMaxLength(255); this.Property(t => t.tag) .HasMaxLength(255); this.Property(t => t.twitterEventLink) .HasMaxLength(255); this.Property(t => t.video) .HasMaxLength(255); // Table & Column Mappings this.ToTable("ourevent", "event"); this.Property(t => t.idEvent).HasColumnName("idEvent"); this.Property(t => t.category).HasColumnName("category"); this.Property(t => t.cityAdress).HasColumnName("cityAdress"); this.Property(t => t.countryAdress).HasColumnName("countryAdress"); this.Property(t => t.description).HasColumnName("description"); this.Property(t => t.eventFinishingDate).HasColumnName("eventFinishingDate"); this.Property(t => t.eventStartingDate).HasColumnName("eventStartingDate"); this.Property(t => t.eventType).HasColumnName("eventType"); this.Property(t => t.facebookEventLink).HasColumnName("facebookEventLink"); this.Property(t => t.image).HasColumnName("image"); this.Property(t => t.laltitude).HasColumnName("laltitude"); this.Property(t => t.longitude).HasColumnName("longitude"); this.Property(t => t.name).HasColumnName("name"); this.Property(t => t.price).HasColumnName("price"); this.Property(t => t.slogan).HasColumnName("slogan"); this.Property(t => t.tag).HasColumnName("tag"); this.Property(t => t.twitterEventLink).HasColumnName("twitterEventLink"); this.Property(t => t.video).HasColumnName("video"); this.Property(t => t.owner_idUser).HasColumnName("owner_idUser"); this.Property(t => t.reward_id).HasColumnName("reward_id"); // Relationships this.HasMany(t => t.features) .WithMany(t => t.ourevents) .Map(m => { m.ToTable("ourevent_feature", "event"); m.MapLeftKey("events_idEvent"); m.MapRightKey("features_id"); }); this.HasMany(t => t.orgnizers) .WithMany(t => t.ourevents) .Map(m => { m.ToTable("ourevent_orgnizer", "event"); m.MapLeftKey("events_idEvent"); m.MapRightKey("orgnizerEvents_idUser"); }); this.HasMany(t => t.participants) .WithMany(t => t.ourevents) .Map(m => { m.ToTable("ourevent_participant", "event"); m.MapLeftKey("events_idEvent"); m.MapRightKey("eventParticipants_idUser"); }); this.HasOptional(t => t.eventowner) .WithMany(t => t.ourevents) .HasForeignKey(d => d.owner_idUser); this.HasOptional(t => t.reward) .WithMany(t => t.ourevents) .HasForeignKey(d => d.reward_id); } } }
//using Code_First_Repository_Pattern.Models; using First_Api_Project.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; namespace First_Api_Project.Repositories { public class ProductRepository : Repository<Product> { public List<Product> GetTopProducts(int top) { return GetAll().OrderByDescending(x => x.Price).Take(top).ToList(); } public List<Product> GetProductsByCategory(int id) { return GetAll().Where(x => x.CategoryId==id).ToList(); } public List<Product> GetProductsByCatProd(int cid,int pid) { return GetAll().Where(x => x.CategoryId == cid && x.ProductId==pid).ToList(); } public List<Product> GetProductsCategory(int pid, int cid) { return GetAll().Where(x => x.ProductId == pid || x.CategoryId == cid).ToList(); } } }
using System.Collections.Generic; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using SonicRetro.SAModel; using SonicRetro.SAModel.Direct3D; using SonicRetro.SAModel.SAEditorCommon; using SonicRetro.SAModel.SAEditorCommon.SETEditing; namespace SADXObjectDefinitions.Level_Effects { class SkyChase : LevelDefinition { NJS_OBJECT carriermdl; Mesh[] carriermesh; public override void Init(IniLevelData data, byte act, Device dev) { carriermdl = ObjectHelper.LoadModel("Levels/Sky Chase/Egg Carrier model.sa1mdl"); carriermesh = ObjectHelper.GetMeshes(carriermdl, dev); } public override void Render(Device dev, EditorCamera cam) { List<RenderInfo> result = new List<RenderInfo>(); MatrixStack transform = new MatrixStack(); Texture[] texs = ObjectHelper.GetTextures("SHOOTING0"); result.AddRange(carriermdl.DrawModelTree(dev, transform, texs, carriermesh)); RenderInfo.Draw(result, dev, cam); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.EventSystems; using UnityEngine.SceneManagement; public class GameController : MonoBehaviour { private TextHandler textHandler; private Ranks ranks; private StateMachine stateMachine; private Randomize randomize; private AIController aiController; private GameObject dontDestroyOnLoadObjects; private WinCondition winCondition; public Timer timer; public GameObject inputeText; public TMP_InputField inputeAnswer; public int rounds; public float playerOneAnswerTime; public float playerTwoAnswerTime; private int answer; private void Start() { timer.isNewGameTime = true; randomize = GetComponent<Randomize>(); ranks = GetComponent<Ranks>(); stateMachine = GetComponent<StateMachine>(); aiController = GetComponent<AIController>(); winCondition = GetComponent<WinCondition>(); textHandler = GetComponent<TextHandler>(); timer.newGameTime = 10; dontDestroyOnLoadObjects = GameObject.Find("DontDestroyOnLoadObjects"); } private void Update() { timer.MyUpdate(); if (Input.GetKeyDown(KeyCode.Escape)) { SceneManager.LoadScene("Menu"); Destroy(dontDestroyOnLoadObjects); } EventSystem.current.SetSelectedGameObject(inputeAnswer.gameObject, null); inputeAnswer.OnPointerClick(new PointerEventData(EventSystem.current)); if (Input.GetKeyDown(KeyCode.Return) && inputeAnswer.ToString() != System.String.Empty) Answer(); if (timer.newGameTime <= 0 && timer.isNewGameTime) { NewQuestion(); timer.isNewGameTime = false; } if (timer.showingAnswerTime <= 0 && timer.isShowingAnswerTime) { RestartGame(); timer.isShowingAnswerTime = false; } if (timer.newQuestionTime <= 0 && timer.isNewQuestionTime) { DrawOutTextWinnerText(); timer.isNewQuestionTime = false; } if(timer.newQuestionTime <= 0 && rounds >= 5) { } } public void Answer() { iTween.PunchScale(inputeText, new Vector3(4,4,0), 0.8f); answer = int.Parse(inputeAnswer.text); playerOneAnswerTime = 5 - timer.newQuestionTime; aiController.CheckAi(); winCondition.EachRound(playerOneAnswerTime, answer, rounds, stateMachine.rightAnswer, textHandler.playerOne.name); winCondition.EachRound(playerTwoAnswerTime, aiController.aiAnswers, rounds, stateMachine.rightAnswer, textHandler.playerTwo.name); textHandler.PlayerOneAnswer(); } public void DrawOutTextWinnerText() { winCondition.RoundWinner(); timer.ShowingAnswers(); textHandler.EnablePlayerAnswerText(); } public void RestartGame() { NewQuestion(); } public void NewQuestion() { stateMachine.CheckState(ranks.yourElo, randomize.RandomizeArr()); textHandler.NewQuestion(stateMachine.questionString); timer.NewQuestionTime(); playerTwoAnswerTime = aiController.RandomTime(); rounds++; } }
using System; using System.Collections.Generic; namespace OCP.Comments { /** * Interface ICommentsManager * * This class manages the access to comments * * @package OCP\Comments * @since 9.0.0 */ public interface ICommentsManager { /** * @const DELETED_USER type and id for a user that has been deleted * @see deleteReferencesOfActor * @since 9.0.0 * * To be used as replacement for user type actors in deleteReferencesOfActor(). * * User interfaces shall show "Deleted user" as display name, if needed. */ // const string DELETED_USER = "deleted_users"; /** * returns a comment instance * * @param string id the ID of the comment * @return IComment * @throws NotFoundException * @since 9.0.0 */ IComment get(string id); /** * returns the comment specified by the id and all it's child comments * * @param string id * @param int limit max number of entries to return, 0 returns all * @param int offset the start entry * @return array * @since 9.0.0 * * The return array looks like this * [ * 'comment' => IComment, // root comment * 'replies' => * [ * 0 => * [ * 'comment' => IComment, * 'replies' => * [ * 0 => * [ * 'comment' => IComment, * 'replies' => [ … ] * ], * … * ] * ] * 1 => * [ * 'comment' => IComment, * 'replies'=> [ … ] * ], * … * ] * ] */ IList<string> getTree(string id, int limit = 0, int offset = 0); /** * returns comments for a specific object (e.g. a file). * * The sort order is always newest to oldest. * * @param string objectType the object type, e.g. 'files' * @param string objectId the id of the object * @param int limit optional, number of maximum comments to be returned. if * not specified, all comments are returned. * @param int offset optional, starting point * @param \DateTime|null notOlderThan optional, timestamp of the oldest comments * that may be returned * @return IComment[] * @since 9.0.0 */ IList<IComment> getForObject( string objectType, string objectId, int limit = 0, int offset = 0, DateTime? notOlderThan = null ); /** * @param string objectType the object type, e.g. 'files' * @param string objectId the id of the object * @param int lastKnownCommentId the last known comment (will be used as offset) * @param string sortDirection direction of the comments (`asc` or `desc`) * @param int limit optional, number of maximum comments to be returned. if * set to 0, all comments are returned. * @return IComment[] * @since 14.0.0 */ IList<string> getForObjectSince( string objectType, string objectId, int lastKnownCommentId, string sortDirection = "asc", int limit = 30 ); /** * Search for comments with a given content * * @param string search content to search for * @param string objectType Limit the search by object type * @param string objectId Limit the search by object id * @param string verb Limit the verb of the comment * @param int offset * @param int limit * @return IComment[] * @since 14.0.0 */ IList<IComment> search(string search, string objectType, string objectId, string verb, int offset, int limit = 50); /** * @param objectType string the object type, e.g. 'files' * @param objectId string the id of the object * @param \DateTime|null notOlderThan optional, timestamp of the oldest comments * that may be returned * @param string verb Limit the verb of the comment - Added in 14.0.0 * @return Int * @since 9.0.0 */ int getNumberOfCommentsForObject(string objectType, string objectId, DateTime? notOlderThan = null,string verb = ""); /** * Get the number of unread comments for all files in a folder * * @param int folderId * @param IUser user * @return array [fileId => unreadCount] * @since 12.0.0 */ IList<string> getNumberOfUnreadCommentsForFolder(int folderId, IUser user); /** * creates a new comment and returns it. At this point of time, it is not * saved in the used data storage. Use save() after setting other fields * of the comment (e.g. message or verb). * * @param string actorType the actor type (e.g. 'users') * @param string actorId a user id * @param string objectType the object type the comment is attached to * @param string objectId the object id the comment is attached to * @return IComment * @since 9.0.0 */ IComment create(string actorType,string actorId, string objectType, string objectId); /** * permanently deletes the comment specified by the ID * * When the comment has child comments, their parent ID will be changed to * the parent ID of the item that is to be deleted. * * @param string id * @return bool * @since 9.0.0 */ bool delete(string id); /** * saves the comment permanently * * if the supplied comment has an empty ID, a new entry comment will be * saved and the instance updated with the new ID. * * Otherwise, an existing comment will be updated. * * Throws NotFoundException when a comment that is to be updated does not * exist anymore at this point of time. * * @param IComment comment * @return bool * @throws NotFoundException * @since 9.0.0 */ bool save(IComment comment); /** * removes references to specific actor (e.g. on user delete) of a comment. * The comment itself must not get lost/deleted. * * A 'users' type actor (type and id) should get replaced by the * value of the DELETED_USER constant of this interface. * * @param string actorType the actor type (e.g. 'users') * @param string actorId a user id * @return boolean * @since 9.0.0 */ bool deleteReferencesOfActor(string actorType, string actorId); /** * deletes all comments made of a specific object (e.g. on file delete) * * @param string objectType the object type (e.g. 'files') * @param string objectId e.g. the file id * @return boolean * @since 9.0.0 */ bool deleteCommentsAtObject(string objectType, string objectId); /** * sets the read marker for a given file to the specified date for the * provided user * * @param string objectType * @param string objectId * @param \DateTime dateTime * @param \OCP\IUser user * @since 9.0.0 */ void setReadMark(string objectType, string objectId, DateTime dateTime, OCP.IUser user); /** * returns the read marker for a given file to the specified date for the * provided user. It returns null, when the marker is not present, i.e. * no comments were marked as read. * * @param string objectType * @param string objectId * @param \OCP\IUser user * @return \DateTime|null * @since 9.0.0 */ DateTime getReadMark(string objectType, string objectId, OCP.IUser user); /** * deletes the read markers for the specified user * * @param \OCP\IUser user * @return bool * @since 9.0.0 */ bool deleteReadMarksFromUser(OCP.IUser user); /** * deletes the read markers on the specified object * * @param string objectType * @param string objectId * @return bool * @since 9.0.0 */ bool deleteReadMarksOnObject(string objectType, string objectId); /** * registers an Entity to the manager, so event notifications can be send * to consumers of the comments infrastructure * * @param \Closure closure * @since 11.0.0 */ void registerEventHandler(Action closure); /** * registers a method that resolves an ID to a display name for a given type * * @param string type * @param \Closure closure * @throws \OutOfBoundsException * @since 11.0.0 * * Only one resolver shall be registered per type. Otherwise a * \OutOfBoundsException has to thrown. */ void registerDisplayNameResolver(string type, Action closure); /** * resolves a given ID of a given Type to a display name. * * @param string type * @param string id * @return string * @throws \OutOfBoundsException * @since 11.0.0 * * If a provided type was not registered, an \OutOfBoundsException shall * be thrown. It is upon the resolver discretion what to return of the * provided ID is unknown. It must be ensured that a string is returned. */ string resolveDisplayName(string type, string id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using JoveZhao.Framework.DDD; namespace BPiaoBao.SystemSetting.Domain.Models.Businessmen { public interface IBusinessmanRepository : IRepository<Businessman> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class IndicatedObject : MonoBehaviour { public Transform ObjectToIndicate; public string Title; IndicatorArrow arrow; void Start () { arrow = IndicatorArrowFactory.Instance.SpawnArrow(ObjectToIndicate, Title); } void OnDestroy () { if (arrow != null && arrow.gameObject != null) Destroy(arrow.gameObject); } }
using Swiddler.Utils; using System; using System.Collections.Generic; using System.Linq; using System.Management; using System.Windows; using System.Windows.Media; using System.Windows.Threading; using static Swiddler.Utils.ShellApi; namespace Swiddler.ViewModels { public class ProcessInfo { public static IconSizeEnum DefaultIconSize { get; set; } = IconSizeEnum.Small16; public int ProcessId { get; private set; } public string Name { get; private set; } public string Path { get; private set; } public ImageSource Icon { get; private set; } static readonly Dictionary<string, ImageSource> IconCache = new Dictionary<string, ImageSource>(StringComparer.OrdinalIgnoreCase); static readonly string DefaultExePath = ResolvePath("smss.exe"); private ProcessInfo() { } public static ProcessInfo Get(int? processId) { if ((processId ?? 0) == 0) return null; using (var searcher = new ManagementObjectSearcher($"Select * From Win32_Process Where ProcessID={processId}")) { var obj = searcher.Get().Cast<ManagementObject>().SingleOrDefault(); if (obj == null) return null; var pi = new ProcessInfo() { ProcessId = processId.Value, Name = (string)obj["Name"], Path = (string)obj["ExecutablePath"], }; pi.ResolveIcon(); return pi; } } static readonly Dispatcher Dispatcher = Application.Current.Dispatcher; private void ResolveIcon() { string iconKey = Path; if (string.IsNullOrEmpty(iconKey)) iconKey = DefaultExePath; lock (IconCache) { if (IconCache.TryGetValue(iconKey, out var img)) { Icon = img; return; } else { using (var bitmap = GetBitmapFromFilePath(iconKey, DefaultIconSize)) { Dispatcher.Invoke(new Action(() => { Icon = bitmap.ImageSourceForBitmap(); IconCache[iconKey] = Icon; })); } } } } public override string ToString() { return Name; } } }
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Console; namespace EntityFrameworkCore.BulkOperations.Tests { internal class Helper { public static ILogger RedirectLoggerToConsole() { ILoggerFactory loggerFactory = LoggerFactory.Create(builder => { builder.AddConsole((ConsoleLoggerOptions options) => { options.TimestampFormat = "yyyy-MM-ddTHH:mm:ss: "; options.Format = ConsoleLoggerFormat.Systemd; }); }); ILogger logger = loggerFactory.CreateLogger(string.Empty); return logger; } } }
using System; using System.Windows.Forms; using quanlysinhvien.authen; using quanlysinhvien.DTO.UIAuth; using quanlysinhvien.Models.DAO; using quanlysinhvien.Models.EF; namespace quanlysinhvien { public partial class frmResigter : Form { public frmResigter() { InitializeComponent(); } private void resigter_Load(object sender, EventArgs e) { } private void btnExit_Click(object sender, EventArgs e) { Application.Exit(); } private void lblCreated_Click(object sender, EventArgs e) { frmLogin login = new frmLogin(); login.Show(); this.Close(); } private void btnRegsiter_Click(object sender, EventArgs e) { Authen Au = new Authen(); frmLogin login = new frmLogin(); string user_ = txtUsername.Text.Trim(); string pass_ = txtPassword.Text.Trim(); string comf_pass = txtComfirmPassword.Text.Trim(); if (user_ == "" || pass_ == "" || comf_pass == "") { txtUsername.Focus(); if (pass_ == "") { txtPassword.Focus(); } if (comf_pass == "") { txtComfirmPassword.Focus(); } } else { frmMessageBox msb = new frmMessageBox(); bool checkRes = Au.checkRes(user_, pass_, comf_pass); if (checkRes) { msb.Show_("SignIn Success"); msb.ShowDialog(); frmLogin Login = new frmLogin(); this.Close(); login.Show(); login.txtUsername.Text = user_; login.txtPassword.Text = pass_; login.Activate(); } else { msb.Show_("SignIn Failed"); msb.ShowDialog(); } } } private void ttCheckUser_Popup(object sender, PopupEventArgs e) { } private void txtUsername_TextChanged(object sender, EventArgs e) { } private void ttCheckUser_Draw(object sender, DrawToolTipEventArgs e) { } } }
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 DAL; using DevExpress.XtraReports.UI; using BUS; using ControlLocalizer; using DevExpress.XtraEditors; using DevExpress.XtraSplashScreen; namespace GUI.Report.Nhap { public partial class f_doanhthu : Form { KetNoiDBDataContext db = new KetNoiDBDataContext(); Boolean doubleclick1 = false; Boolean doubleclick2 = false; public f_doanhthu() { InitializeComponent(); rTime.SetTime(thoigian); } private void f_chitietnhapkho_Load(object sender, EventArgs e) { LanguageHelper.Translate(this); this.Text = LanguageHelper.TranslateMsgString("." + Name + "_title", "BÁO CÁO DOANH THU BÁN HÀNG").ToString(); changeFont.Translate(this); //translate text labelControl1.Text = LanguageHelper.TranslateMsgString(".reportKhoangThoiGian", "Khoảng Thời Gian").ToString(); labelControl2.Text = LanguageHelper.TranslateMsgString(".reportTuNgay", "Từ Ngày").ToString(); labelControl3.Text = LanguageHelper.TranslateMsgString(".reportDenNgay", "Đến Ngày").ToString(); labelControl6.Text = LanguageHelper.TranslateMsgString(".reportDanhMuc", "Danh Mục").ToString(); tungay.ReadOnly = true; denngay.ReadOnly = true; danhmuc.Text = "Đơn vị - ຫົວໜ່ວຍ"; rTime.SetTime2(thoigian); var lst = from a in db.dk_rps where a.user == Biencucbo.idnv select a; db.dk_rps.DeleteAllOnSubmit(lst); db.SubmitChanges(); nhan.DataSource = lst; } private string LayMaTim(donvi d) { string s = "." + d.id + "." + d.iddv + "."; var find = db.donvis.FirstOrDefault(t => t.id == d.iddv); if (find != null) { string iddv = find.iddv; if (d.id != find.iddv) { if (!s.Contains(iddv)) s += iddv + "."; } while (iddv != find.id) { if (!s.Contains(find.id)) s += find.id + "."; find = db.donvis.FirstOrDefault(t => t.id == find.iddv); } } return s; } private void thoigian_SelectedIndexChanged(object sender, EventArgs e) { changeTime.thoigian_change3(thoigian, tungay, denngay); } private void danhmuc_SelectedIndexChanged(object sender, EventArgs e) { if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { try { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } catch { } } } private void simpleButton1_Click(object sender, EventArgs e) { try { dk_rp dk = new dk_rp(); dk.id = gridView1.GetFocusedRowCellValue("id").ToString(); dk.name = gridView1.GetFocusedRowCellValue("name").ToString(); dk.key = gridView1.GetFocusedRowCellValue("key").ToString(); dk.loai = danhmuc.Text; dk.user = Biencucbo.idnv; db.dk_rps.InsertOnSubmit(dk); db.SubmitChanges(); var lst = from a in db.dk_rps where a.user == Biencucbo.idnv select a; nhan.DataSource = lst; if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } else { gridView1.DeleteSelectedRows(); } } catch { } } private void gridView1_Click(object sender, EventArgs e) { doubleclick1 = false; } private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e) { if (doubleclick1 == true) { try { dk_rp dk = new dk_rp(); dk.id = gridView1.GetFocusedRowCellValue("id").ToString(); dk.name = gridView1.GetFocusedRowCellValue("name").ToString(); dk.key = gridView1.GetFocusedRowCellValue("key").ToString(); dk.loai = danhmuc.Text; dk.user = Biencucbo.idnv; db.dk_rps.InsertOnSubmit(dk); db.SubmitChanges(); var lst = from a in db.dk_rps where a.user == Biencucbo.idnv select a; nhan.DataSource = lst; if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } else { gridView1.DeleteSelectedRows(); } } catch { } } } private void gridView1_DoubleClick(object sender, EventArgs e) { doubleclick1 = true; } private void gridView2_DoubleClick(object sender, EventArgs e) { doubleclick2 = true; } private void gridView2_Click(object sender, EventArgs e) { doubleclick2 = false; } private void gridView2_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e) { if (doubleclick2 == true) { try { dk_rp dk = new dk_rp(); var lst = (from a in db.dk_rps where a.user==Biencucbo.idnv select a).Single(t => t.key == gridView2.GetFocusedRowCellValue("key").ToString()); db.dk_rps.DeleteOnSubmit(lst); db.SubmitChanges(); var lst2 = from a in db.dk_rps where a.user == Biencucbo.idnv select a; nhan.DataSource = lst2; } catch { } if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { try { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } catch { } } } } private void simpleButton3_Click(object sender, EventArgs e) { try { dk_rp dk = new dk_rp(); var lst = (from a in db.dk_rps where a.user==Biencucbo.idnv select a).Single(t => t.key == gridView2.GetFocusedRowCellValue("key").ToString()); db.dk_rps.DeleteOnSubmit(lst); db.SubmitChanges(); var lst2 = from a in db.dk_rps where a.user == Biencucbo.idnv select a; nhan.DataSource = lst2; } catch { } if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { try { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } catch { } } } private void simpleButton2_Click(object sender, EventArgs e) { try { for (int i = 0; i < gridView1.RowCount; i++) { dk_rp dk = new dk_rp(); dk.id = gridView1.GetRowCellValue(i, "id").ToString(); dk.name = gridView1.GetRowCellValue(i, "name").ToString(); dk.key = gridView1.GetRowCellValue(i, "key").ToString(); dk.loai = danhmuc.Text; dk.user = Biencucbo.idnv; db.dk_rps.InsertOnSubmit(dk); db.SubmitChanges(); var lst = from a in db.dk_rps where a.user == Biencucbo.idnv select a; nhan.DataSource = lst; } if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } else { for (int i = gridView1.RowCount; i > 0; i--) { gridView1.DeleteSelectedRows(); } } } catch { } } private void simpleButton4_Click(object sender, EventArgs e) { try { var lst = (from a in db.dk_rps where a.user==Biencucbo.idnv select a); db.dk_rps.DeleteAllOnSubmit(lst); db.SubmitChanges(); nhan.DataSource = lst; } catch { } if (danhmuc.Text == "Đơn vị - ຫົວໜ່ວຍ") { try { var list = (from a in db.donvis select new { id = a.id, name = a.tendonvi, key = a.id + danhmuc.Text + Biencucbo.idnv, MaTim = LayMaTim(a) }); var lst2 = list.ToList().Where(t => t.MaTim.Contains("." + Biencucbo.donvi + ".")); for (int j = 0; j < gridView2.DataRowCount; j++) { var lst3 = from a in lst2 where a.key != gridView2.GetRowCellValue(j, "key").ToString() select a; lst2 = lst3.ToList(); }; nguon.DataSource = lst2; } catch { } } } private void simpleButton5_Click(object sender, EventArgs e) { SplashScreenManager.ShowForm(this, typeof(SplashScreen2), true, true, false); try { Biencucbo.kho = ""; int check = 0; for (int i = 0; i < gridView2.DataRowCount; i++) { if (gridView2.GetRowCellValue(i, "loai").ToString() == "Đơn vị - ຫົວໜ່ວຍ") { check++; Biencucbo.kho = Biencucbo.kho + gridView2.GetRowCellValue(i, "id").ToString() + "-" + gridView2.GetRowCellValue(i, "name").ToString() + ", "; } } if (check == 0) { Lotus.MsgBox.ShowWarningDialog("Cần phải chọn 1 trường dữ liệu bắt buộc: Kho"); return; } else { if (Biencucbo.ngonngu.ToString() == "Vietnam") { if (thoigian.Text == "Tùy ý") { Biencucbo.time = "Từ ngày: " + tungay.Text + " Đến ngày: " + denngay.Text; } else if (thoigian.Text == "Cả Năm") { Biencucbo.time = thoigian.Text + " " + DateTime.Now.Year; } else { Biencucbo.time = thoigian.Text + ", năm " + DateTime.Now.Year; } } else { if (thoigian.Text == "ແລ້ວແຕ່") { Biencucbo.time = "ແຕ່: " + tungay.Text + " ເຖິງ: " + denngay.Text; } else if (thoigian.Text == "ໝົດປີ") { Biencucbo.time = thoigian.Text + " " + DateTime.Now.Year; } else { Biencucbo.time = thoigian.Text + ", ປີ " + DateTime.Now.Year; } } var lst2 = from a in db.r_pxuats join b in db.dk_rps on a.iddv equals b.id where a.loaixuat == "Xuất bán - ຈ່າຍອອກຂາຍ" && b.user == Biencucbo.idnv select a; var lst = from a in lst2 where a.ngayhd >= DateTime.Parse(tungay.Text) && a.ngayhd <= DateTime.Parse(denngay.Text) select new { id = a.id, ngayhd = a.ngayhd, idsanpham = a.idsanpham, tensp = a.tensp, dvt = a.dvt, soluong = a.soluong, dongia = a.dongia, chietkhau = a.chietkhau, dv = a.dv == "0" ? "Khách Nợ" : "Khách Trả tiền mặt", thanhtien = a.thanhtien, iddv = a.iddv, tendonvi = a.tendonvi, }; r_doanhthu xtra = new r_doanhthu(); xtra.DataSource = lst; xtra.ShowPreviewDialog(); } } catch (Exception ex) { XtraMessageBox.Show(ex.Message); } SplashScreenManager.CloseForm(false); } } }
namespace iCopy.Model.Response { public class City { public int ID { get; set; } public string Name { get; set; } public string ShortName { get; set; } public int PostalCode { get; set; } public Country Country { get; set; } public int CountryID { get; set; } public bool Active { get; set; } } }
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("TriodorArgeProject.Test")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TriodorArgeProject.Test")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("0cb4e046-780c-4467-8721-cbb7d04761d3")] // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
 using UnityEngine; using System.Collections; public class SuperMarioAnimation : MonoBehaviour { public float landBounceTime= 0.6f; private AnimationState lastJump; void Start (){ // We are in full control here - don't let any other animations play when we start // animation.Stop(); // By default loop all animations animation.wrapMode = WrapMode.Loop; // The jump animation is clamped and overrides all others AnimationState jump= animation["run"]; jump.layer = 1; jump.enabled = false; jump.wrapMode = WrapMode.Clamp; } void Update (){ SuperMarioController marioController = GetComponent<SuperMarioController>(); float currentSpeed= marioController.GetSpeed(); // Switch between idle and walk if (currentSpeed > 0.1f) animation.CrossFade("walk"); else animation.CrossFade("idle"); // When we jump we want the character start animate the landing bounce, exactly when he lands. So we do this: // - pause animation (setting speed to 0) when we are jumping and the animation time is at the landBounceTime // - When we land we set the speed back to 1 if (marioController.IsJumping()) { if (lastJump.time > landBounceTime) lastJump.speed = 0; } } void DidJump (){ // We want to play the jump animation queued, // so that we can play the jump animation multiple times, overlaying each other // We dont want to rewind the same animation to avoid sudden jerks! lastJump = animation.CrossFadeQueued("run", 0.3f, QueueMode.PlayNow); } void DidLand (){ lastJump.speed = 1; } }
// // 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.Web.UI.WebControls; namespace DotNetNuke.ExtensionPoints { public interface IGridColumnExtensionPoint : IExtensionPoint { int ColumnAt { get; } string UniqueName { get; } string DataField { get; } string HeaderText { get; } Unit HeaderStyleWidth { get; } bool ReadOnly { get; } bool Reorderable { get; } string SortExpression { get; } } }
using System.Collections.Generic; using System.Linq; using System; public class AOC07_2 { static List<string> ReadIpAddresses() { var lines = new List<string>(); string line; while (!String.IsNullOrEmpty(line = Console.ReadLine())) { lines.Add(line); } return lines; } static bool AddressSupportsSsl(string address) { var recentChars = new Queue<char>(); bool insideHypernetSequence = false; var supernetAbas = new List<string>(); var hypernetAbas = new List<string>(); foreach (char ch in address) { if (ch == '[') { insideHypernetSequence = true; recentChars.Clear(); } else if (ch == ']') { insideHypernetSequence = false; recentChars.Clear(); } else { recentChars.Enqueue(ch); while (recentChars.Count > 3) { recentChars.Dequeue(); } if (insideHypernetSequence) { if (IsAba(recentChars)) { hypernetAbas.Add(String.Concat(recentChars.ToArray())); } } else { if (IsAba(recentChars)) { supernetAbas.Add(String.Concat(recentChars.ToArray())); } } } } return supernetAbas.Any(aba => hypernetAbas.Contains(AbaToBab(aba))); } static bool IsAba(Queue<char> recentChars) { if (recentChars.Count != 3) { return false; } var array = recentChars.ToArray(); return array[0] == array[2] && array[0] != array[1]; } static string AbaToBab(string aba) { return $"{aba[1]}{aba[0]}{aba[1]}"; } public static void Main() { List<string> addresses = ReadIpAddresses(); int addressesSupportingSslCount = addresses.Count(address => AddressSupportsSsl(address)); Console.WriteLine(addressesSupportingSslCount.ToString()); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CheckPwd { /// <summary> /// 密码强度 /// </summary> public enum Strength { Invalid = 0, //无效密码 Weak = 1, //低强度密码 Normal = 2, //中强度密码 Strong = 3, //高强度密码 Valid = 4 //符合要求 } public class CheckPassword { String Pwd; public static Strength PasswordStrength(String pwd) { String Check_String = pwd; if (Check_String == "") return Strength.Invalid; if (Check_String.Length <= 8) { return Strength.Weak; } Char[] pwdChars = pwd.ToCharArray(); //字符统计 int iNum = 0, iLowLtt = 0, iUpperLtt = 0, iSym = 0; foreach (char items in pwdChars) { if (items >= '0' && items <= '9') iNum++; else if (items >= 'a' && items <= 'z') iLowLtt++; else if (items >= 'A' && items <= 'Z') iUpperLtt++; else iSym++; } //只含有一种 if (iLowLtt == 0 && iUpperLtt == 0 && iSym == 0) return Strength.Weak; //纯数字密码 if (iNum == 0 && iLowLtt == 0 && iUpperLtt == 0) return Strength.Weak; //纯符号密码 if (iNum == 0 && iSym == 0 && iLowLtt == 0) return Strength.Weak; //纯大写字母密码 if (iNum == 0 && iSym == 0 && iUpperLtt == 0) return Strength.Weak; //纯小写字母密码 //含有两种 if (iLowLtt == 0 && iUpperLtt == 0) return Strength.Normal; //数字和符号构成的密码 if (iSym == 0 && iLowLtt == 0) return Strength.Normal; //数字和大写字母构成的密码 if (iSym == 0 && iUpperLtt == 0) return Strength.Normal; //数字和小写字母构成的密码 if (iNum == 0 && iLowLtt == 0) return Strength.Normal; //符号和大写字母构成的密码 if (iNum == 0 && iUpperLtt == 0) return Strength.Normal; //符号和小写字母构成的密码 if (iNum == 0 && iSym == 0) return Strength.Normal; //大写字母和小写字母构成的密码 //缺少一种 if (iNum == 0) return Strength.Strong; // 不含数字 if (iSym == 0) return Strength.Strong; // 不含符号 if (iLowLtt == 0) return Strength.Strong; // 不含小写字母 if (iUpperLtt == 0) return Strength.Strong; // 不含大写字母 return Strength.Valid; //由数字、大写字母、小写字母符号构成的密码 } } }
using System.Collections.Generic; using Ecommerce.Dto; namespace Ecommerce.Service { public interface IProductService { ServiceResponse<List<ProductDto>> GetAll(); } }
namespace Whale.Shared.Exceptions { public sealed class NotFoundException : BaseCustomException { public NotFoundException() { } public NotFoundException(string name, string id) : base($"Entity {name} with id ({id}) was not found.") { _httpError = 404; } public NotFoundException(string name) : base($"Entity {name} was not found.") { _httpError = 404; } public NotFoundException(string message, System.Exception innerException) : base(message, innerException) { } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using TheRegistry.Model; using TheRegistry.Persistence; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace TheRegistry { public sealed partial class IssueReturnPage : Page { public IssueReturnPage() { this.InitializeComponent(); } private void btnSubmit_Click(object sender, RoutedEventArgs e) { var stock = DataContainer.GetInstance().StockList; var thething = stock.SingleOrDefault(x => x.ItemCode==cboItem.SelectedValue.ToString()); if (thething == null) { thething = new Stock() { ItemCode = cboItem.SelectedValue.ToString(), Quantity = decimal.Parse(txtQty.Text), StoreCode = cboStore.SelectedValue.ToString() }; stock.Add(thething); } else { thething.Quantity += decimal.Parse(txtQty.Text); } this.Frame.GoBack(); } private void Page_Loaded(object sender, RoutedEventArgs e) { cboItem.ItemsSource = DataContainer.GetInstance().ItemList; cboItem.DisplayMemberPath = "Description"; cboItem.SelectedValuePath = "ItemCode"; cboStore.ItemsSource = DataContainer.GetInstance().StoreList; cboStore.DisplayMemberPath = "Description"; cboStore.SelectedValuePath = "StoreCode"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.Results; using System.Xml; using System.Xml.Linq; using BookAppsWeb.Models; namespace BookAppsWeb.Controllers { // Web API for Book-data-searching public class SearchController : ApiController { // Id Search GET: /api/Search?idSrchStr=val1&caseSens=val2 [HttpGet] public IHttpActionResult GetSrchResultById(string idSrchStr, bool caseSens = false) { if (idSrchStr != null) { var t = Repository.SrchById(idSrchStr, caseSens); return Ok(t); } else { return null; // Alternative: NotFound(); } } // Title Search GET: /api/Search?titleSrchStr=val1&caseSens=val2 [HttpGet] public IHttpActionResult GetSrchResultByTitle(string titleSrchStr,bool caseSens = false) { if (titleSrchStr != null) { var t = Repository.SrchByKeyword(titleSrchStr,"title",caseSens); return Ok(t); } else { return null; } } // Author Search GET: /api/Search?authSrchStr=val1&caseSens=val2 [HttpGet] public IHttpActionResult GetSrchResultByAuthor(string authSrchStr, bool caseSens = false) { if (authSrchStr != null) { var t = Repository.SrchByKeyword(authSrchStr,"author",caseSens); return Ok(t); } else { return null; } } //[HttpGet] // Get All Books GET: /api/search //public IEnumerable<BookResults> GetAllBooks() //{ // var t = Repository.GetAllTitles(); // return t; //} } }
/// <summary> /// Author: Shiyang(Shirley) Li /// Date:01/20/2020 /// Copyright: Shiyang(Shirley) Li - This work may not be copied for use in Academic Coursework. /// /// I, Shiyang(Shirley) Li, certify that I wrote this code starting form "//Added test cases starts here" comment /// from scratch and did not copy it in part or whole from another source. All references used in the completion /// of the code are cited in my README file. /// /// This is a test class for DependencyGraphTest and is intended /// to contain all DependencyGraphTest Unit Tests /// /// </summary> using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using SpreadsheetUtilities; namespace DevelopmentTests { /// <summary> ///This is a test class for DependencyGraphTest and is intended ///to contain all DependencyGraphTest Unit Tests ///</summary> [TestClass()] public class DependencyGraphTest { /// <summary> ///Empty graph should contain nothing ///</summary> [TestMethod()] public void SimpleEmptyTest() { DependencyGraph t = new DependencyGraph(); Assert.AreEqual(0, t.Size); } /// <summary> ///Empty graph should contain nothing ///</summary> [TestMethod()] public void SimpleEmptyRemoveTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "y"); Assert.AreEqual(1, t.Size); t.RemoveDependency("x", "y"); Assert.AreEqual(0, t.Size); } /// <summary> ///Empty graph should contain nothing ///</summary> [TestMethod()] public void EmptyEnumeratorTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "y"); IEnumerator<string> e1 = t.GetDependees("y").GetEnumerator(); Assert.IsTrue(e1.MoveNext()); Assert.AreEqual("x", e1.Current); IEnumerator<string> e2 = t.GetDependents("x").GetEnumerator(); Assert.IsTrue(e2.MoveNext()); Assert.AreEqual("y", e2.Current); t.RemoveDependency("x", "y"); Assert.IsFalse(t.GetDependees("y").GetEnumerator().MoveNext()); Assert.IsFalse(t.GetDependents("x").GetEnumerator().MoveNext()); } /// <summary> ///Replace on an empty DG shouldn't fail ///</summary> [TestMethod()] public void SimpleReplaceTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "y"); Assert.AreEqual(t.Size, 1); t.RemoveDependency("x", "y"); t.ReplaceDependents("x", new HashSet<string>()); t.ReplaceDependees("y", new HashSet<string>()); } ///<summary> ///It should be possibe to have more than one DG at a time. ///</summary> [TestMethod()] public void StaticTest() { DependencyGraph t1 = new DependencyGraph(); DependencyGraph t2 = new DependencyGraph(); t1.AddDependency("x", "y"); Assert.AreEqual(1, t1.Size); Assert.AreEqual(0, t2.Size); } /// <summary> ///Non-empty graph contains something ///</summary> [TestMethod()] public void SizeTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); Assert.AreEqual(4, t.Size); } /// <summary> ///Non-empty graph contains something ///</summary> [TestMethod()] public void EnumeratorTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); IEnumerator<string> e = t.GetDependees("a").GetEnumerator(); Assert.IsFalse(e.MoveNext()); e = t.GetDependees("b").GetEnumerator(); Assert.IsTrue(e.MoveNext()); String s1 = e.Current; Assert.IsTrue(e.MoveNext()); String s2 = e.Current; Assert.IsFalse(e.MoveNext()); Assert.IsTrue(((s1 == "a") && (s2 == "c")) || ((s1 == "c") && (s2 == "a"))); e = t.GetDependees("c").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("a", e.Current); Assert.IsFalse(e.MoveNext()); e = t.GetDependees("d").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("b", e.Current); Assert.IsFalse(e.MoveNext()); } /// <summary> ///Non-empty graph contains something ///</summary> [TestMethod()] public void ReplaceThenEnumerate() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "b"); t.AddDependency("a", "z"); t.ReplaceDependents("b", new HashSet<string>()); t.AddDependency("y", "b"); t.ReplaceDependents("a", new HashSet<string>() { "c" }); t.AddDependency("w", "d"); t.ReplaceDependees("b", new HashSet<string>() { "a", "c" }); t.ReplaceDependees("d", new HashSet<string>() { "b" }); IEnumerator<string> e = t.GetDependees("a").GetEnumerator(); Assert.IsFalse(e.MoveNext()); e = t.GetDependees("b").GetEnumerator(); Assert.IsTrue(e.MoveNext()); String s1 = e.Current; Assert.IsTrue(e.MoveNext()); String s2 = e.Current; Assert.IsFalse(e.MoveNext()); Assert.IsTrue(((s1 == "a") && (s2 == "c")) || ((s1 == "c") && (s2 == "a"))); e = t.GetDependees("c").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("a", e.Current); Assert.IsFalse(e.MoveNext()); e = t.GetDependees("d").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("b", e.Current); Assert.IsFalse(e.MoveNext()); } /// <summary> ///Using lots of data ///</summary> [TestMethod()] public void StressTest() { // Dependency graph DependencyGraph t = new DependencyGraph(); // A bunch of strings to use const int SIZE = 200; string[] letters = new string[SIZE]; for (int i = 0; i < SIZE; i++) { letters[i] = ("" + (char)('a' + i)); } // The correct answers HashSet<string>[] dents = new HashSet<string>[SIZE]; HashSet<string>[] dees = new HashSet<string>[SIZE]; for (int i = 0; i < SIZE; i++) { dents[i] = new HashSet<string>(); dees[i] = new HashSet<string>(); } // Add a bunch of dependencies for (int i = 0; i < SIZE; i++) { for (int j = i + 1; j < SIZE; j++) { t.AddDependency(letters[i], letters[j]); dents[i].Add(letters[j]); dees[j].Add(letters[i]); } } // Remove a bunch of dependencies for (int i = 0; i < SIZE; i++) { for (int j = i + 4; j < SIZE; j += 4) { t.RemoveDependency(letters[i], letters[j]); dents[i].Remove(letters[j]); dees[j].Remove(letters[i]); } } // Add some back for (int i = 0; i < SIZE; i++) { for (int j = i + 1; j < SIZE; j += 2) { t.AddDependency(letters[i], letters[j]); dents[i].Add(letters[j]); dees[j].Add(letters[i]); } } // Remove some more for (int i = 0; i < SIZE; i += 2) { for (int j = i + 3; j < SIZE; j += 3) { t.RemoveDependency(letters[i], letters[j]); dents[i].Remove(letters[j]); dees[j].Remove(letters[i]); } } // Make sure everything is right for (int i = 0; i < SIZE; i++) { Assert.IsTrue(dents[i].SetEquals(new HashSet<string>(t.GetDependents(letters[i])))); Assert.IsTrue(dees[i].SetEquals(new HashSet<string>(t.GetDependees(letters[i])))); } } //Added test cases starts here /// <summary> ///Test the size of dependee of a dependent ///</summary> [TestMethod()] public void SizeofDependeeTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); Assert.AreEqual(1, t["c"]); Assert.AreEqual(2, t["b"]); } /// <summary> ///Test the size of dependee of a string that is not in the depent dictionary ///</summary> [TestMethod()] public void SizeofZeroDependeeTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); Assert.AreEqual(0, t["a"]); } /// <summary> ///Test a string that has dependents ///</summary> [TestMethod()] public void HasDependentTestFirstCase() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); Assert.IsTrue(t.HasDependents("a")); } /// <summary> ///Test if a string that is not in the dependee dictionary has a dependent or not ///</summary> [TestMethod()] public void NotHasDependentTestFirstCase() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); Assert.IsFalse(t.HasDependents("d")); } /// <summary> ///Test a string that dose not have a dependent ///</summary> [TestMethod()] public void NotHasDependentTestSecondCase() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); t.ReplaceDependents("a", new HashSet<string>()); Assert.IsFalse(t.HasDependents("a")); } /// <summary> ///Test if a string that is not in the dependent dictionary has a dependee or not ///</summary> [TestMethod()] public void NotHasDependeeTestFirstCase() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); Assert.IsFalse(t.HasDependees("a")); } /// <summary> ///Test a string that dose not have a dependee ///</summary> [TestMethod()] public void NotHasDependeeTestSecondCase() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.AddDependency("c", "b"); t.AddDependency("b", "d"); t.ReplaceDependees("c", new HashSet<string>()); Assert.IsFalse(t.HasDependees("c")); } /// <summary> ///Test for ReplaceDependents when the strings in the newDependents has already existed in the dependent dictionary ///</summary> [TestMethod()] public void ReplaceDependentsTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "b"); t.AddDependency("c", "b"); t.AddDependency("a", "z"); t.ReplaceDependees("z", new HashSet<string>()); t.ReplaceDependents("x", new HashSet<string> { "z" }); IEnumerator<string> e = t.GetDependents("x").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("z", e.Current); e = t.GetDependees("b").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("c", e.Current); e = t.GetDependees("z").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("x", e.Current); } /// <summary> ///Remove dependency when s or t is not in the dictionary ///</summary> [TestMethod()] public void RemoveDependencyTest() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "y"); t.RemoveDependency("a", "b"); Assert.IsTrue(t.HasDependees("y")); Assert.IsTrue(t.HasDependents("x")); } /// <summary> ///Test for replace when both s and the items in the newDependets(newDependees) are not in the dictionary ///</summary> [TestMethod()] public void ReplaceTest1() { DependencyGraph t = new DependencyGraph(); t.AddDependency("x", "y"); t.AddDependency("a", "b"); t.AddDependency("a", "c"); t.ReplaceDependents("m", new HashSet<string> { "v" }); IEnumerator<string> e = t.GetDependees("v").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("m", e.Current); e = t.GetDependents("m").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("v", e.Current); t.ReplaceDependees("l", new HashSet<string> { "s" }); e = t.GetDependees("l").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("s", e.Current); e = t.GetDependents("s").GetEnumerator(); Assert.IsTrue(e.MoveNext()); Assert.AreEqual("l", e.Current); } /// <summary> ///Test for size of adding duplicates ///</summary> [TestMethod()] public void SizeOfAddingDuplicates() { DependencyGraph t = new DependencyGraph(); t.AddDependency("a", "b"); t.AddDependency("a", "b"); Assert.AreEqual(1, t.Size); } } }
using Arch.Data.Common.Constant; using System; using System.Collections; using System.Text; namespace Arch.Data.DbEngine.MarkDown { class MarkUpInfo { public Boolean PreMarkUp { get; set; } public DateTime MarkDownTime { get; set; } public Int32 CurrentMarkUpIndex { get; set; } public BitArray MarkUpArray { get; set; } public Int32[] MarkUpSchedules { get; set; } public Int32[] MarkUpSuccess { get; set; } public Int32[] MarkUpFail { get; set; } public Int32 CurrentMarkUpSchedule { get; set; } /// <summary> /// 总的数据访问数 /// </summary> public Int32 CurrentBatch { get; set; } public override String ToString() { return new StringBuilder().AppendFormat("PreMarkUp:{0},", PreMarkUp) .AppendFormat("MarkDownTime:{0},", MarkDownTime) .AppendFormat("CurrentMarkUpIndex:{0},", CurrentMarkUpIndex) .AppendFormat("MarkUpArray:{0},", String.Join(",", MarkUpArray)) .ToString(); } public static BitArray InitMarkUpArray(Int32 markUpPercent) { BitArray array = new BitArray(Constants.MarkUpReferCount); Int32 threshold = Constants.MarkUpReferCount - markUpPercent; for (Int32 i = 0; i < Constants.MarkUpReferCount; i++) { array[i] = i >= threshold; } return array; } } }
namespace PurificationPioneer.Const { public partial class LocalAssetName { public static readonly string CharacterHeadCanvas = @"CharacterHeadCanvas"; public static readonly string LocalCamera = @"LocalCamera"; public static readonly string ThirdPersonCameraVariant = @"ThirdPersonCamera Variant"; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CyberPunkRPG { class Constants { public static int ScreenWidth = 1920; public static int ScreenHeight = 1080; } }
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Mono.Cecil; using NUnit.Framework; using StructureAssertions.Test.TestTypes; namespace StructureAssertions.Test { [TestFixture] public class TypeDefinitionExtensionsTest { readonly AssemblyDefinition _thisAssembly = AssemblyDefinition.ReadAssembly(typeof(TypeDefinitionExtensionsTest).Assembly.Location); IEnumerable<TypeReference> _dependencies; [Test] public void EmptyTypeHasNoDependencies() { ReadDependenciesOfType<Empty>(); AssertDependencies(new Type[0]); } [Test] public void ReturnsDependenciesFromFieldType() { ReadDependenciesOfType<ContainsStringField>(); AssertDependencies(typeof(string)); } [Test] public void ReturnsDependenciesFromPropertyType() { ReadDependenciesOfType<ContainsStringProperty>(); AssertDependencies(typeof(string)); } [Test] public void ReturnsDependenciesFromPropertyMethod() { ReadDependenciesOfType<ContainsStringPropertyCallingInitializer>(); AssertDependencies(typeof(string), typeof(StringInitializer)); } [Test] public void ReturnsDependenciesFromLazyProperty() { ReadDependenciesOfType<ContainsStringPropertyWithLazyInitializerCall>(); _dependencies .Select(t => t.FullName) // There are too many references because of using Lazy<T>, we care only about // StringInitializer, which is used in lazy initialization method .Should().Contain(new[] {typeof (string).FullName, typeof (StringInitializer).FullName}); } [Test] public void ReturnsDependenciesFromFieldInitializer() { ReadDependenciesOfType<ContainsStringFieldWithInitializer>(); AssertDependencies(typeof(string), typeof(StringInitializer)); } [Test] public void ReturnsDependenciesFromMethodReturnType() { ReadDependenciesOfType<ContainsMethodReturningBool>(); AssertDependencies(typeof(bool)); } [Test] public void ReturnsDependenciesFromMethodParameters() { ReadDependenciesOfType<ContainsMethodWithInt32Argument>(); AssertDependencies(typeof(int)); } [Test] public void ReturnsDependenciesFromMethodVariables() { ReadDependenciesOfType<ContainsMethodWithDecimalVariable>(); // Compiler optimization in Release build omits variables which are // not used. We must therefore call Consumer to do something with the variable. AssertDependencies(typeof(decimal), typeof(Consumer)); } [Test] public void ReturnsDependenciesFromMethodInstructions() { ReadDependenciesOfType<ContainsMethodWithCallToStringInitializer>(); AssertDependencies(typeof(StringInitializer)); } [Test] public void ReturnsDependenciesFromBaseClass() { ReadDependenciesOfType<ClassWithBaseClassUsingString>(); AssertDependencies(typeof(ABaseClass), typeof(string)); } [Test] public void ReturnsDependenciesFromNestedClass() { ReadDependenciesOfType<ClassWithNestedClassUsingString>(); AssertDependencies(typeof(string)); } #region Helper Methods void ReadDependenciesOfType<T>() { _dependencies = GetTypeDefinition<T>().GetDependencies(); } TypeDefinition GetTypeDefinition<T>() { return _thisAssembly.MainModule.GetTypes().First(t => t.FullName == typeof(T).FullName); } void AssertDependencies(params Type[] expectedDependencies) { _dependencies .Select(t => t.FullName) .Where(d => d != typeof(object).FullName) // every object depends on System.Object .Should().BeEquivalentTo(expectedDependencies.Select(t => t.FullName)); } #endregion } }
using Zhouli.DAL.Interface; using Zhouli.DbEntity.Models; using System; using System.Collections.Generic; using System.Text; using System.Data; namespace Zhouli.DAL.Implements { public class SysAmRelatedDAL : BaseDAL<SysAmRelated>, ISysAmRelatedDAL { public SysAmRelatedDAL(ZhouLiContext db, IDbConnection dbConnection) : base(db, dbConnection) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO; using Google.Apis.Auth.OAuth2; using Google.Apis.Vision.v1; using Google.Apis.Http; using Google.Apis.Services; using Google.Apis.Vision.v1.Data; using Microsoft.Office.Interop.Excel; namespace Tarea2 { public class CloudVision { public CloudVision() { } public static GoogleCredential CreateCredentials() { string json = Properties.Settings.Default.json_google; string path = json; GoogleCredential credential; using (var stream = new FileStream(path, FileMode.Open, FileAccess.Read)) { var c = GoogleCredential.FromStream(stream); credential = c.CreateScoped(VisionService.Scope.CloudPlatform); } return credential; } public static VisionService CreateService(string applicationName, IConfigurableHttpClientInitializer credentials) { var service = new VisionService(new BaseClientService.Initializer() { ApplicationName = applicationName, HttpClientInitializer = credentials }); return service; } private static AnnotateImageRequest CreateAnnotationImageRequest(string path, string[] featureTypes) { if (!File.Exists(path)) { throw new FileNotFoundException("Archivo no encontrado.", path); } var request = new AnnotateImageRequest(); request.Image = new Google.Apis.Vision.v1.Data.Image(); var bytes = File.ReadAllBytes(path); request.Image.Content = Convert.ToBase64String(bytes); request.Features = new List<Feature>(); foreach (var featureType in featureTypes) { request.Features.Add(new Feature() { Type = featureType }); } return request; } public static async Task<AnnotateImageResponse> AnnotateAsync(VisionService service, FileInfo file, params string[] features) { var request = new BatchAnnotateImagesRequest(); request.Requests = new List<AnnotateImageRequest>(); request.Requests.Add(CreateAnnotationImageRequest(file.FullName, features)); var result = await service.Images.Annotate(request).ExecuteAsync(); if (result?.Responses?.Count > 0) { return result.Responses[0]; } return null; } public async Task DoWork(string path, Workbook wb) { var ext = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".png", ".jpg", ".jpeg", ".gif" }; var dir = path; var files = Directory .GetFiles(dir, "*.*", SearchOption.AllDirectories) .Where(f => ext.Contains(Path.GetExtension(f))) .Select(f => new FileInfo(f)) .ToArray(); //crear servicio var credentails = CreateCredentials(); var service = CreateService("CICLOPE", credentails); string[] features = new string[] { "LABEL_DETECTION", "TEXT_DETECTION", "LANDMARK_DETECTION", "LOGO_DETECTION", "IMAGE_PROPERTIES" }; string[] types = new string[] { "car", "truck", "van", "bus","vehicle","transport"}; string[] brands = new string[] { "seat", "renault", "peugeot", "dacia","citroen","opel", "alfa romeo", "skoda", "chevrolet", "porsche", "honda", "subaru", "mazda", "mitsubishi", "lexus", "toyota", "bmw","volkswagen","suzuki","mercedes","mercedes-benz","saab","audi","kia", "land rover","dodge","chrysler","ford","hummer","hyundai","infiniti","jaguar","jeep", "nissan","volvo","daewoo","fiat","rover" }; // Excel Worksheet ws = (Worksheet)wb.Worksheets.Add();//[1]; ws.Name = "Google Cloud Vision"; ws.Cells[1, 1] = "Imagen"; ws.Cells[1, 2] = "Tipo"; ws.Cells[1, 3] = "Color"; ws.Cells[1, 4] = "Otros Datos"; ws.Cells[1, 5] = "Tipo Imagen"; ws.Cells[1, 6] = "Tamaño Imagen"; ws.Cells[1, 7] = "Fecha Archivo"; ws.Cells[1, 8] = "Afuera/Adentro"; ws.Cells[1, 9] = "Texto(OCR)"; ws.Cells[1, 1].EntireRow.Font.Bold = true; int i = 2; //procesar cada archivo foreach (var file in files) { string f = file.FullName; Console.WriteLine("Reading " + f + ":"); using (var img = System.Drawing.Image.FromFile(file.FullName)) { var height = img.Height; var width = img.Width; ws.Cells[i, 6] = width + " x " + height; } ws.Cells[i, 1] = file.Name.Substring(0, file.Name.LastIndexOf(".")); ws.Cells[i, 7] = file.LastWriteTime.ToShortDateString(); ws.Cells[i, 8] = "N/A"; var task = await AnnotateAsync(service, file, features); var result = task.LabelAnnotations; var keywords = result?.Select(s => s.Description).ToArray(); //var words = String.Join(", ", keywords); //System.Diagnostics.Debug.WriteLine(words); string tipo = "N/A"; foreach (var key in keywords) { if (types.Contains(key)) { tipo = key; break; } } ws.Cells[i, 2] = tipo; //marcas string marca = "N/A"; foreach (var key in keywords) { if (brands.Contains(key)) { marca = key; break; } } ws.Cells[i, 4] = marca; var text = task.TextAnnotations; var keywords2 = text?.Select(s => s.Description).ToArray(); if (keywords2 != null && keywords2[0] != null) { ws.Cells[i, 9] = keywords2[0]; } // var words2 = String.Join(", ", keywords2); // System.Diagnostics.Debug.WriteLine(words2); /* var landmark = task.LandmarkAnnotations; var keywords3 = landmark?.Select(s => s.Description).ToArray(); if (keywords3 != null) { var words3 = String.Join(", ", keywords3); System.Diagnostics.Debug.WriteLine(words3); } */ var logo = task.LogoAnnotations; var keywords4 = logo?.Select(s => s.Description).ToArray(); if (keywords4 != null) { var words4 = String.Join(", ", keywords4); ws.Cells[i, 4] = ws.Cells[i, 4] +" Logos: " +words4; } var props = task.ImagePropertiesAnnotation; ColorInfo c = props?.DominantColors.Colors.FirstOrDefault(); float? r = c.Color.Red; float? g = c.Color.Green; float? b = c.Color.Blue; System.Drawing.Color color = System.Drawing.Color.FromArgb((int)r, (int)g, (int)b); if (ColorWithinRangeR(color)) { ws.Cells[i, 3] = "red" + " (" + color.R+" "+color.G+" "+color.B+")"; } else if (ColorWithinRangeG(color)) { ws.Cells[i, 3] = "green" + " (" + color.R + " " + color.G + " " + color.B + ")"; } else if (ColorWithinRangeB(color)) { ws.Cells[i, 3] = "blue" + " (" + color.R + " " + color.G + " " + color.B + ")"; } else if (ColorWithinRangeBL(color)) { ws.Cells[i, 3] = "black" + " (" + color.R + " " + color.G + " " + color.B + ")"; } else { ws.Cells[i, 3] = "white" + " (" + color.R + " " + color.G + " " + color.B + ")"; } //Console.WriteLine(r.ToString()+" "+g.ToString()+" "+b.ToString()); // escala de grises var keywords5 = props?.DominantColors.Colors.Select(s => s.Color.ToString()).ToArray(); bool byn = false; foreach (ColorInfo col in props?.DominantColors.Colors) { if ((col.Color.Red == col.Color.Green) && (col.Color.Red == col.Color.Blue) && (col.Color.Green == col.Color.Blue)) { byn = true; } else { byn = false; } } if (byn) { ws.Cells[i, 5] = "B&N"; } else { ws.Cells[i, 5] = "Color"; } i++; } ws.Columns.AutoFit(); } // red private readonly System.Drawing.Color r_from = System.Drawing.Color.FromArgb(50, 20, 20); private readonly System.Drawing.Color r_to = System.Drawing.Color.FromArgb(255, 105, 97); bool ColorWithinRangeR(System.Drawing.Color c) { return (r_from.R <= c.R && c.R <= r_to.R) && (r_from.G <= c.G && c.G <= r_to.G) && (r_from.B <= c.B && c.B <= r_to.B); } // blue private readonly System.Drawing.Color b_from = System.Drawing.Color.FromArgb(0, 35, 102); private readonly System.Drawing.Color b_to = System.Drawing.Color.FromArgb(204, 204, 255); bool ColorWithinRangeB(System.Drawing.Color c) { return (b_from.R <= c.R && c.R <= b_to.R) && (b_from.G <= c.G && c.G <= b_to.G) && (b_from.B <= c.B && c.B <= b_to.B); } // green private readonly System.Drawing.Color g_from = System.Drawing.Color.FromArgb(85, 107, 47); private readonly System.Drawing.Color g_to = System.Drawing.Color.FromArgb(178, 236, 93); bool ColorWithinRangeG(System.Drawing.Color c) { return (g_from.R <= c.R && c.R <= g_to.R) && (g_from.G <= c.G && c.G <= g_to.G) && (g_from.B <= c.B && c.B <= g_to.B); } // black private readonly System.Drawing.Color bl_from = System.Drawing.Color.FromArgb(0, 0, 0); private readonly System.Drawing.Color bl_to = System.Drawing.Color.FromArgb(85, 85, 85); bool ColorWithinRangeBL(System.Drawing.Color c) { return (bl_from.R <= c.R && c.R <= bl_to.R) && (bl_from.G <= c.G && c.G <= bl_to.G) && (bl_from.B <= c.B && c.B <= bl_to.B); } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using SFP.Persistencia.Dao; using SFP.Persistencia.Model; using SFP.SIT.SERV.Util; using SFP.SIT.SERV.Model.ADM; namespace SFP.SIT.SERV.Dao.ADM { public class SIT_ADM_USUARIOAREADao : BaseDao { public SIT_ADM_USUARIOAREADao(DbConnection cn, DbTransaction transaction, String dataAdapter) : base(cn, transaction, dataAdapter) { } public Object dmlAgregar(SIT_ADM_USUARIOAREA oDatos) { String sSQL = " INSERT INTO SIT_ADM_USUARIOAREA( usrclave, uarorigen, araclave) VALUES ( :P0, :P1, :P2) "; return EjecutaDML ( sSQL, oDatos.usrclave, oDatos.uarorigen, oDatos.araclave ); } public int dmlImportar( List<SIT_ADM_USUARIOAREA> lstDatos) { int iTotReg = 0; String sSQL = " INSERT INTO SIT_ADM_USUARIOAREA( usrclave, uarorigen, araclave) VALUES ( :P0, :P1, :P2) "; foreach (SIT_ADM_USUARIOAREA oDatos in lstDatos) { EjecutaDML ( sSQL, oDatos.usrclave, oDatos.uarorigen, oDatos.araclave ); iTotReg++; } return iTotReg; } public int dmlEditar(SIT_ADM_USUARIOAREA oDatos) { String sSQL = " UPDATE SIT_ADM_USUARIOAREA SET uarorigen = :P0 WHERE araclave = :P1 AND usrclave = :P2 "; return (int) EjecutaDML ( sSQL, oDatos.uarorigen, oDatos.araclave, oDatos.usrclave ); } public int dmlBorrar(SIT_ADM_USUARIOAREA oDatos) { String sSQL = " DELETE FROM SIT_ADM_USUARIOAREA WHERE araclave = :P0 AND usrclave = :P1 "; return (int) EjecutaDML ( sSQL, oDatos.araclave, oDatos.usrclave ); } public List<SIT_ADM_USUARIOAREA> dmlSelectTabla( ) { String sSQL = " SELECT * FROM SIT_ADM_USUARIOAREA "; return CrearListaMDL<SIT_ADM_USUARIOAREA>(ConsultaDML(sSQL) as DataTable); } public List<ComboMdl> dmlSelectCombo( ) { throw new NotImplementedException(); } public Dictionary<int, string> dmlSelectDiccionario( ) { throw new NotImplementedException(); } public SIT_ADM_USUARIOAREA dmlSelectID(SIT_ADM_USUARIOAREA oDatos ) { String sSQL = " SELECT * FROM SIT_ADM_USUARIOAREA WHERE araclave = :P0 AND usrclave = :P1 "; return CrearListaMDL<SIT_ADM_USUARIOAREA>(ConsultaDML ( sSQL, oDatos.araclave, oDatos.usrclave ) as DataTable)[0]; } public object dmlCRUD( Dictionary<string, object> dicParam ) { int iOper = (int)dicParam[CMD_OPERACION]; if (iOper == OPE_INSERTAR) return dmlAgregar(dicParam[CMD_ENTIDAD] as SIT_ADM_USUARIOAREA ); else if (iOper == OPE_EDITAR) return dmlEditar(dicParam[CMD_ENTIDAD] as SIT_ADM_USUARIOAREA ); else if (iOper == OPE_BORRAR) return dmlBorrar(dicParam[CMD_ENTIDAD] as SIT_ADM_USUARIOAREA ); else return 0; } /*INICIO*/ public const string PARAM_AREAS = "PARAM_AREAS"; public const string PARAM_FECHA = "PARAM_FECHA"; public Object dmlActualizarPerfil(Object oDatos) { Dictionary<string, object> dicParam = (Dictionary<string, object>)oDatos; // PRIMERO BORRAMOS LOS DATOS... EjecutaDML("DELETE FROM SIT_ADM_USUARIOAREA WHERE USRCLAVE = :P0", dicParam[DButil.SIT_ADM_USUARIO_COL.USRCLAVE]); String sqlQuery = " INSERT INTO SIT_ADM_USUARIOAREA ( USRCLAVE, araClave )" + " SELECT " + dicParam[DButil.SIT_ADM_USUARIO_COL.USRCLAVE] + ", araClave FROM SIT_adm_areahist " + " WHERE araClave in ( " + dicParam[PARAM_AREAS] + " )"; return EjecutaDML(sqlQuery); } public List<SIT_ADM_AREAHIST> dmlUsuarioArea(Dictionary<string, object> oDatos) { string sqlQuery = " select * from SIT_ADM_AREAHIST WHERE araclave in (SELECT araclave FROM SIT_ADM_USUARIOAREA WHERE USRCLAVE = :P0 ) " + " AND :P1 BETWEEN arhfecini and arhfecfin ORDER BY arhdescripcion"; return CrearListaMDL<SIT_ADM_AREAHIST>(ConsultaDML(sqlQuery, oDatos[DButil.SIT_ADM_USUARIO_COL.USRCLAVE], oDatos[PARAM_FECHA])); } //////public List<Tuple<int, string>> dmlUsuAreaDesc(int iClaUsu) //////{ ////// List<Tuple<int, string>> lstUsuPerArea = new List<Tuple<int, string>>(); ////// string sqlQuery = " SELECT perClave as id, arhSiglas as text FROM SIT_ADM_USUARIOAREA up, SIT_adm_areahist a " ////// + " WHERE up.ARACLAVE = a.ARACLAVE and USRCLAVE = :P0 GROUP BY perClave, arhSiglas "; ////// DataTable dtDatos = (DataTable)ConsultaDML(sqlQuery, iClaUsu); ////// for (int iIdx = 0; iIdx < dtDatos.Rows.Count; iIdx++) ////// { ////// lstUsuPerArea.Add(new Tuple<int, string>(Convert.ToInt32(dtDatos.Rows[iIdx][0]), dtDatos.Rows[iIdx][0].ToString())); ////// } ////// return lstUsuPerArea; //////} public DataTable dmlUPAarbol(int iClaUsu) { String sqlQuery = " SELECT area.araClave, araDescripcion, orgClaveReporta, area.perClave, upa.araClave as activo "; //// + " FROM SIT_adm_areahist area " //// + " LEFT JOIN SIT_ADM_Kperfil perfil ON area.perClave = perfil.perClave " //// + " LEFT JOIN SIT_ADM_USUARIOAREA upa ON USRCLAVE = :P0 " //// + " AND upa.perClave = perfil.perClave AND area.araClave = upa.araClave " //// + " WHERE " //// + " ka_fecbaja is null " //// + " AND perfil.perClave > 1 " //// + " order by kp_multiple, area.perClave "; return ConsultaDML(sqlQuery, iClaUsu); } public DataTable dmlTurnarArbol(int iClaUsu) { String sqlQuery = " SELECT area.araClave, araDescripcion, orgClaveReporta, area.perClave, upa.araClave as activo "; ////+ " FROM SIT_adm_areahist area " ////+ " LEFT JOIN SIT_ADM_Kperfil perfil ON area.perClave = perfil.perClave " ////+ " LEFT JOIN SIT_ADM_USUARIOAREA upa ON USRCLAVE = :P0 " ////+ " AND upa.perClave = perfil.perClave AND area.araClave = upa.araClave " ////+ " WHERE ka_fecbaja is null " ////+ " AND perfil.perClave = " + Util.Constantes.Perfil.UA ////+ " order by area.kta_clatipo_area, area.araDescripcion "; return ConsultaDML(sqlQuery, iClaUsu); } public DataTable dmlUsuarioAreas(int iClaUsu) { string sqlQuery = "select area.araClave as id, area.arhSiglas as text " + " from SIT_ADM_USUARIOAREA pua, SIT_adm_areahist area " + " WHERE pua.araClave = area.araClave and USRCLAVE = :P0 and area.araClave > 0" + " GROUP BY area.araClave, area.arhSiglas ORDER BY area.araClave "; return ConsultaDML(sqlQuery, iClaUsu); } public DataTable dmlOUsuarioAreas(int iClaArea) { string sqlQuery = " Select usrNombre || ' ' || usrPaterno || ' ' || usrmaterno as nombre, usrCorreo " + " from SIT_ADM_USUARIO usu, SIT_ADM_USUARIOAREA ua " + " where ua.araClave = :P0 " + " and usu.USRCLAVE = ua.USRCLAVE "; return ConsultaDML(sqlQuery, iClaArea); } public List<SIT_ADM_USUARIOAREA> dmlUsuarioAreasList(int iClaUsu) { string sqlQuery = " select* from SIT_ADM_USUARIOAREA WHERE USRCLAVE = :P0 "; return CrearListaMDL<SIT_ADM_USUARIOAREA>(ConsultaDML(sqlQuery, iClaUsu)); } public DataTable dmlSelectGrid(BasePagMdl baseMdl) { String sqlQuery = " WITH Resultado AS( select COUNT(*) OVER() RESULT_COUNT, rownum recid, a.* from ( " + " SELECT UPA.USRCLAVE, UPA.araClave, usrCorreo, araDescripcion " + " from SIT_ADM_USER_AREA UPA, SIT_ADM_USUARIO US, SIT_ADM_KAREA AR " + " WHERE US.USRCLAVE = UPA.USRCLAVE " + " AND AR.araClave = UPA.araClave " + " order by usrCorreo, UPA.araClave " + " ) a ) SELECT * from Resultado WHERE recid between :P0 and :P1 "; return (DataTable)ConsultaDML(sqlQuery, baseMdl.LimInf, baseMdl.LimSup); } /*FIN*/ } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace QuanLyQuanCafe { class Connect { SqlConnection con; SqlDataAdapter adapter; SqlCommand cmd; String strconnect = "Data Source=VINHTOAN-PC;Integrated Security=True"; void connect() { con = new SqlConnection(strconnect); } } }
namespace NetFabric.Hyperlinq.Benchmarks { public abstract class RandomSkipBenchmarksBase : SkipBenchmarksBase { public override void GlobalSetup() => Initialize(Utils.GetRandomValues(seed, Skip + Count)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UARTTest { class MeasurementHeadersCollectionClass { List<MeasurementHeaderClass> headers = new List<MeasurementHeaderClass>(); int count = 0; int currentFilledHeader = 0; public void Add(int addr) { headers.Add(new MeasurementHeaderClass(addr)); count++; } /// <summary> /// Get first empty header in list and throw if none is found /// </summary> /// <returns></returns> public MeasurementHeaderClass GetFirstEmpty() { foreach (var item in headers) { if (item.ready) { continue; } return item; } throw new Exception("No more empty headers"); } public MeasurementHeaderClass GetNextFilled() { if (headers[currentFilledHeader].ready != true) { throw new Exception("Fetching empty header"); } return headers[currentFilledHeader++]; } } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Reflection; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using Mono.Data.Sqlite; using MySql.Data.MySqlClient; using Terraria; using TerrariaApi.Server; using TShockAPI; using TShockAPI.DB; namespace InfiniteChests { [ApiVersion(1, 16)] public class InfiniteChests : TerrariaPlugin { IDbConnection Database; PlayerInfo[] Infos = new PlayerInfo[256]; System.Timers.Timer Timer = new System.Timers.Timer(1000); Dictionary<Point, int> Timers = new Dictionary<Point, int>(); public override string Author { get { return "MarioE"; } } public override string Description { get { return "Allows for infinite chests, and supports all chest control commands."; } } public override string Name { get { return "InfiniteChests"; } } public override Version Version { get { return Assembly.GetExecutingAssembly().GetName().Version; } } public InfiniteChests(Main game) : base(game) { for (int i = 0; i < 256; i++) { Infos[i] = new PlayerInfo(); } Order = 1; } protected override void Dispose(bool disposing) { if (disposing) { ServerApi.Hooks.NetGetData.Deregister(this, OnGetData); ServerApi.Hooks.GameInitialize.Deregister(this, OnInitialize); ServerApi.Hooks.GamePostInitialize.Deregister(this, OnPostInitialize); ServerApi.Hooks.ServerLeave.Deregister(this, OnLeave); Database.Dispose(); Timer.Dispose(); } } public override void Initialize() { ServerApi.Hooks.NetGetData.Register(this, OnGetData); ServerApi.Hooks.GameInitialize.Register(this, OnInitialize); ServerApi.Hooks.GamePostInitialize.Register(this, OnPostInitialize); ServerApi.Hooks.ServerLeave.Register(this, OnLeave); Timer.Elapsed += OnElapsed; Timer.Start(); } void OnElapsed(object o, ElapsedEventArgs e) { lock (Timers) { var newTimers = new Dictionary<Point, int>(Timers); foreach (Point p in Timers.Keys) { if (newTimers[p] == 0) newTimers.Remove(p); else newTimers[p]--; } Timers = newTimers; } } void OnGetData(GetDataEventArgs e) { if (!e.Handled) { int plr = e.Msg.whoAmI; using (var reader = new BinaryReader(new MemoryStream(e.Msg.readBuffer, e.Index, e.Length))) { switch (e.MsgID) { case PacketTypes.ChestGetContents: { int x = reader.ReadInt16(); int y = reader.ReadInt16(); Task.Factory.StartNew(() => GetChest(x, y, plr)); e.Handled = true; } break; case PacketTypes.ChestItem: { reader.ReadInt16(); byte slot = reader.ReadByte(); if (slot > 40) return; int stack = reader.ReadInt16(); byte prefix = reader.ReadByte(); int netID = reader.ReadInt16(); Task.Factory.StartNew(() => ModChest(plr, slot, netID, stack, prefix)); e.Handled = true; } break; case PacketTypes.ChestOpen: { reader.ReadInt16(); reader.ReadInt16(); reader.ReadInt16(); string name = reader.ReadString(); if (name.Length > 0) Task.Factory.StartNew(() => NameChest(Infos[plr].x, Infos[plr].y, plr, name)); } break; case PacketTypes.TileKill: { byte action = reader.ReadByte(); int x = reader.ReadInt16(); int y = reader.ReadInt16(); int style = reader.ReadInt16(); if (action == 0) { if (TShock.Regions.CanBuild(x, y, TShock.Players[plr])) { Task.Factory.StartNew(() => PlaceChest(x, y, plr)); WorldGen.PlaceChest(x, y, 21, false, style); NetMessage.SendData((int)PacketTypes.TileKill, -1, plr, "", 0, x, y, style, 1); NetMessage.SendData((int)PacketTypes.TileKill, plr, -1, "", 0, x, y, style, 0); e.Handled = true; } } else if (TShock.Regions.CanBuild(x, y, TShock.Players[plr]) && Main.tile[x, y].type == 21) { if (Main.tile[x, y].frameY % 36 != 0) y--; if (Main.tile[x, y].frameX % 36 != 0) x--; Task.Factory.StartNew(() => KillChest(x, y, plr)); e.Handled = true; } } break; } } } } void OnInitialize(EventArgs e) { Commands.ChatCommands.Add(new Command("infchests.chest.deselect", Deselect, "ccset")); Commands.ChatCommands.Add(new Command("infchests.admin.info", Info, "cinfo")); Commands.ChatCommands.Add(new Command("infchests.chest.lock", Lock, "clock") { DoLog = false }); Commands.ChatCommands.Add(new Command("infchests.admin.convert", ConvertChests, "convchests")); Commands.ChatCommands.Add(new Command("infchests.admin.prune", Prune, "prunechests")); Commands.ChatCommands.Add(new Command("infchests.chest.public", PublicProtect, "cpset")); Commands.ChatCommands.Add(new Command("infchests.admin.refill", Refill, "crefill")); Commands.ChatCommands.Add(new Command("infchests.chest.region", RegionProtect, "crset")); Commands.ChatCommands.Add(new Command("infchests.chest.protect", Protect, "cset")); Commands.ChatCommands.Add(new Command("infchests.chest.unlock", Unlock, "cunlock") { DoLog = false }); Commands.ChatCommands.Add(new Command("infchests.chest.unprotect", Unprotect, "cunset")); switch (TShock.Config.StorageType.ToLower()) { case "mysql": string[] host = TShock.Config.MySqlHost.Split(':'); Database = new MySqlConnection() { ConnectionString = string.Format("Server={0}; Port={1}; Database={2}; Uid={3}; Pwd={4};", host[0], host.Length == 1 ? "3306" : host[1], TShock.Config.MySqlDbName, TShock.Config.MySqlUsername, TShock.Config.MySqlPassword) }; break; case "sqlite": string sql = Path.Combine(TShock.SavePath, "chests.sqlite"); Database = new SqliteConnection(string.Format("uri=file://{0},Version=3", sql)); break; } SqlTableCreator sqlcreator = new SqlTableCreator(Database, Database.GetSqlType() == SqlType.Sqlite ? (IQueryBuilder)new SqliteQueryCreator() : new MysqlQueryCreator()); sqlcreator.EnsureExists(new SqlTable("Chests", new SqlColumn("X", MySqlDbType.Int32), new SqlColumn("Y", MySqlDbType.Int32), new SqlColumn("Name", MySqlDbType.Text), new SqlColumn("Account", MySqlDbType.Text), new SqlColumn("Items", MySqlDbType.Text), new SqlColumn("Flags", MySqlDbType.Int32), new SqlColumn("Password", MySqlDbType.Text), new SqlColumn("WorldID", MySqlDbType.Int32))); } void OnLeave(LeaveEventArgs e) { Infos[e.Who] = new PlayerInfo(); } void OnPostInitialize(EventArgs e) { int converted = 0; StringBuilder items = new StringBuilder(); for (int i = 0; i < 1000; i++) { Terraria.Chest c = Main.chest[i]; if (c != null) { for (int j = 0; j < 40; j++) items.Append("," + c.item[j].netID + "," + c.item[j].stack + "," + c.item[j].prefix); Database.Query("INSERT INTO Chests (X, Y, Account, Items, WorldID) VALUES (@0, @1, '', @2, @3)", c.x, c.y, items.ToString().Substring(1), Main.worldID); converted++; items.Clear(); Main.chest[i] = null; } } if (converted > 0) { TSPlayer.Server.SendSuccessMessage("[InfiniteChests] Converted {0} chest{1}.", converted, converted == 1 ? "" : "s"); WorldFile.saveWorld(); } } void GetChest(int x, int y, int plr) { Chest chest = null; using (QueryResult reader = Database.QueryReader("SELECT Account, Flags, Items, Name, Password FROM Chests WHERE X = @0 AND Y = @1 and WorldID = @2", x, y, Main.worldID)) { if (reader.Read()) { chest = new Chest { account = reader.Get<string>("Account"), flags = (ChestFlags)reader.Get<int>("Flags"), items = reader.Get<string>("Items"), name = reader.Get<string>("Name"), password = reader.Get<string>("Password") }; } } TSPlayer player = TShock.Players[plr]; if (chest != null) { switch (Infos[plr].action) { case ChestAction.INFO: player.SendInfoMessage("X: {0} Y: {1} Account: {2} {3}Refill: {4} ({5} second{6}) Region: {7}", x, y, chest.account == "" ? "N/A" : chest.account, ((chest.flags & ChestFlags.PUBLIC) != 0) ? "(public) " : "", (chest.flags & ChestFlags.REFILL) != 0, (int)chest.flags / 8, (int)chest.flags / 8 == 1 ? "" : "s", (chest.flags & ChestFlags.REGION) != 0); break; case ChestAction.PROTECT: if (chest.account != "") { player.SendErrorMessage("This chest is already protected."); break; } Database.Query("UPDATE Chests SET Account = @0 WHERE X = @1 AND Y = @2 AND WorldID = @3", player.UserAccountName, x, y, Main.worldID); player.SendSuccessMessage("This chest is now protected."); break; case ChestAction.PUBLIC: if (chest.account == "") { player.SendErrorMessage("This chest is not protected."); break; } if (chest.account != player.UserAccountName && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is not yours."); break; } Database.Query("UPDATE Chests SET Flags = ((~(Flags & 1)) & (Flags | 1)) WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID); player.SendSuccessMessage("This chest is now {0}.", (chest.flags & ChestFlags.PUBLIC) != 0 ? "private" : "public"); break; case ChestAction.REFILL: if (chest.account != player.UserAccountName && chest.account != "" && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is not yours."); break; } if (Infos[plr].time > 0) { Database.Query("UPDATE Chests SET Flags = @0 WHERE X = @1 AND Y = @2 AND WorldID = @3", ((int)chest.flags & 3) + (Infos[plr].time * 8) + 4, x, y, Main.worldID); player.SendSuccessMessage(string.Format("This chest will now refill with a delay of {0} second{1}.", Infos[plr].time, Infos[plr].time == 1 ? "" : "s")); } else { Database.Query("UPDATE Chests SET Flags = ((~(Flags & 4)) & (Flags | 4)) & 7 WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID); player.SendSuccessMessage("This chest will {0} refill.", (chest.flags & ChestFlags.REFILL) != 0 ? "no longer" : "now"); } break; case ChestAction.REGION: if (chest.account == "") { player.SendErrorMessage("This chest is not protected."); break; } if (chest.account != player.UserAccountName && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is not yours."); break; } Database.Query("UPDATE Chests SET Flags = ((~(Flags & 2)) & (Flags | 2)) WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID); player.SendSuccessMessage("This chest is {0} region shared.", (chest.flags & ChestFlags.REGION) != 0 ? "no longer" : "now"); break; case ChestAction.SETPASS: if (chest.account == "") { player.SendErrorMessage("This chest is not protected."); break; } if (chest.account != player.UserAccountName && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is not yours."); break; } if (Infos[plr].password.ToLower() == "remove") { Database.Query("UPDATE Chests SET Password = '' WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID); } else { Database.Query("UPDATE Chests SET Password = @0 WHERE X = @1 AND Y = @2 AND WorldID = @3", TShock.Utils.HashPassword(Infos[plr].password), x, y, Main.worldID); } player.SendSuccessMessage("This chest is now password protected."); break; case ChestAction.UNPROTECT: if (chest.account == "") { player.SendErrorMessage("This chest is not protected."); break; } if (chest.account != player.UserAccountName && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is not yours."); break; } Database.Query("UPDATE Chests SET Account = '' WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID); player.SendSuccessMessage("This chest is now un-protected."); break; default: bool isFree = chest.account == ""; bool isOwner = chest.account == player.UserAccountName || player.Group.HasPermission("infchests.admin.editall"); bool isPub = chest.flags.HasFlag(ChestFlags.PUBLIC); bool isRegion = chest.flags.HasFlag(ChestFlags.REGION) && TShock.Regions.CanBuild(x, y, player); if (!isFree && !isOwner && !isPub && !isRegion) { if (String.IsNullOrEmpty(chest.password)) { player.SendErrorMessage("This chest is protected."); break; } else if (TShock.Utils.HashPassword(Infos[plr].password) != chest.password) { player.SendErrorMessage("This chest is password protected."); break; } else { player.SendSuccessMessage("Chest unlocked."); Infos[plr].password = ""; } } int timeLeft; lock (Timers) { if (Timers.TryGetValue(new Point(x, y), out timeLeft) && timeLeft > 0) { player.SendErrorMessage("This chest will refill in {0} second{1}.", timeLeft, timeLeft == 1 ? "" : "s"); break; } } int[] itemArgs = new int[120]; string[] split = chest.items.Split(','); for (int i = 0; i < 120; i++) itemArgs[i] = Convert.ToInt32(split[i]); byte[] raw = new byte[] { 11, 0, 32, 0, 0, 255, 255, 255, 255, 255, 255 }; for (int i = 0; i < 40; i++) { raw[5] = (byte)i; raw[6] = (byte)itemArgs[i * 3 + 1]; raw[7] = (byte)(itemArgs[i * 3 + 1] >> 8); raw[8] = (byte)itemArgs[i * 3 + 2]; raw[9] = (byte)itemArgs[i * 3]; raw[10] = (byte)(itemArgs[i * 3] >> 8); player.SendRawData(raw); } byte[] raw2 = new byte[] { 10, 0, 33, 0, 0, 255, 255, 255, 255, 0 }; Buffer.BlockCopy(BitConverter.GetBytes((short)x), 0, raw2, 5, 2); Buffer.BlockCopy(BitConverter.GetBytes((short)y), 0, raw2, 7, 2); player.SendRawData(raw2); player.SendData(PacketTypes.ChestName, chest.name ?? "Chest", 0, x, y); Infos[plr].x = x; Infos[plr].y = y; break; } Infos[plr].action = ChestAction.NONE; } } void KillChest(int x, int y, int plr) { Chest chest = null; using (QueryResult reader = Database.QueryReader("SELECT Account, Items FROM Chests WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID)) { if (reader.Read()) chest = new Chest { account = reader.Get<string>("Account"), items = reader.Get<string>("Items") }; } TSPlayer player = TShock.Players[plr]; if (chest != null && chest.account != player.UserAccountName && chest.account != "" && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is protected."); player.SendTileSquare(x, y, 3); } else if (chest != null && chest.items != "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0," + "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0") { player.SendTileSquare(x, y, 3); } else { WorldGen.KillTile(x, y); Database.Query("DELETE FROM Chests WHERE X = @0 AND Y = @1 and WorldID = @2", x, y, Main.worldID); TSPlayer.All.SendData(PacketTypes.Tile, "", 0, x, y + 1); } } void NameChest(int x, int y, int plr, string name) { Chest chest = null; using (QueryResult reader = Database.QueryReader("SELECT Account FROM Chests WHERE X = @0 AND Y = @1 AND WorldID = @2", x, y, Main.worldID)) { if (reader.Read()) chest = new Chest { account = reader.Get<string>("Account") }; } TSPlayer player = TShock.Players[plr]; if (chest != null && chest.account != player.UserAccountName && chest.account != "" && !player.Group.HasPermission("infchests.admin.editall")) { player.SendErrorMessage("This chest is protected."); player.SendTileSquare(x, y, 3); } else Database.Query("UPDATE Chests SET Name = @0 WHERE X = @1 AND Y = @2 AND WorldID = @3", name, x, y, Main.worldID); } void ModChest(int plr, byte slot, int ID, int stack, byte prefix) { lock (Database) { Chest chest = null; using (QueryResult reader = Database.QueryReader("SELECT Account, Flags, Items FROM Chests WHERE X = @0 AND Y = @1 AND WorldID = @2", Infos[plr].x, Infos[plr].y, Main.worldID)) { if (reader.Read()) chest = new Chest { flags = (ChestFlags)reader.Get<int>("Flags"), items = reader.Get<string>("Items"), account = reader.Get<string>("Account") }; } TSPlayer player = TShock.Players[plr]; if (chest != null) { if ((chest.flags & ChestFlags.REFILL) != 0) { lock (Timers) { if (!Timers.ContainsKey(new Point(Infos[plr].x, Infos[plr].y))) Timers.Add(new Point(Infos[plr].x, Infos[plr].y), (int)chest.flags >> 3); } } else { int[] itemArgs = new int[120]; string[] split = chest.items.Split(','); for (int i = 0; i < 120; i++) { itemArgs[i] = Convert.ToInt32(split[i]); } itemArgs[slot * 3] = ID; itemArgs[slot * 3 + 1] = stack; itemArgs[slot * 3 + 2] = prefix; StringBuilder newItems = new StringBuilder(); for (int i = 0; i < 120; i++) newItems.Append("," + itemArgs[i]); Database.Query("UPDATE Chests SET Items = @0 WHERE X = @1 AND Y = @2 AND WorldID = @3", newItems.ToString().Substring(1), Infos[plr].x, Infos[plr].y, Main.worldID); for (int i = 0; i < 256; i++) { if (Infos[i].x == Infos[plr].x && Infos[i].y == Infos[plr].y && i != plr) { byte[] raw = new byte[] { 11, 0, 32, 0, 0, slot, (byte)stack, (byte)(stack >> 8), prefix, (byte)ID, (byte)(ID >> 8) }; TShock.Players[i].SendRawData(raw); } } } } } } void PlaceChest(int x, int y, int plr) { TSPlayer player = TShock.Players[plr]; Database.Query("INSERT INTO Chests (X, Y, Name, Account, Flags, Items, Password, WorldID) VALUES (@0, @1, @2, @3, @4, @5, \'\', @6)", x, y - 1, "Chest", (player.IsLoggedIn && player.Group.HasPermission("infchests.chest.protect")) ? player.UserAccountName : "", 0, "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0," + "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", Main.worldID); Main.chest[999] = null; } void ConvertChests(CommandArgs e) { Task.Factory.StartNew(() => { int converted = 0; StringBuilder items = new StringBuilder(); for (int i = 0; i < 1000; i++) { Terraria.Chest c = Main.chest[i]; if (c != null) { for (int j = 0; j < 40; j++) items.Append("," + c.item[j].netID + "," + c.item[j].stack + "," + c.item[j].prefix); Database.Query("INSERT INTO Chests (X, Y, Account, Items, WorldID) VALUES (@0, @1, '', @2, @3)", c.x, c.y, items.ToString().Substring(1), Main.worldID); converted++; items.Clear(); Main.chest[i] = null; } } e.Player.SendSuccessMessage("[InfiniteChests] Converted {0} chest{1}.", converted, converted == 1 ? "" : "s"); if (converted > 0) WorldFile.saveWorld(); }); } void Deselect(CommandArgs e) { Infos[e.Player.Index].action = ChestAction.NONE; e.Player.SendInfoMessage("Stopped selecting a chest."); } void Info(CommandArgs e) { Infos[e.Player.Index].action = ChestAction.INFO; e.Player.SendInfoMessage("Open a chest to get its info."); } void Lock(CommandArgs e) { if (e.Parameters.Count != 1) { e.Player.SendErrorMessage("Invalid syntax! Proper syntax: /clock <password>"); return; } Infos[e.Player.Index].action = ChestAction.SETPASS; Infos[e.Player.Index].password = e.Parameters[0]; if (e.Parameters[0].ToLower() == "remove") { e.Player.SendInfoMessage("Open chest to disable a password on it."); } else { e.Player.SendInfoMessage("Open chest to enable a password on it."); } } void Protect(CommandArgs e) { Infos[e.Player.Index].action = ChestAction.PROTECT; e.Player.SendInfoMessage("Open a chest to protect it."); } void Prune(CommandArgs e) { Task.Factory.StartNew(() => { using (var reader = Database.QueryReader("SELECT X, Y FROM Chests WHERE Items = @0 AND WorldID = @1", "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0," + "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", Main.worldID)) { while (reader.Read()) { int x = reader.Get<int>("X"); int y = reader.Get<int>("Y"); WorldGen.KillTile(x, y); TSPlayer.All.SendTileSquare(x, y, 3); } } int count = Database.Query("DELETE FROM Chests WHERE Items = @0 AND WorldID = @1", "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0," + "0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0", Main.worldID); e.Player.SendSuccessMessage("Pruned {0} chest{1}.", count, count == 1 ? "" : "s"); if (count > 0) WorldFile.saveWorld(); }); } void Refill(CommandArgs e) { if (e.Parameters.Count > 1) { e.Player.SendErrorMessage("Invalid syntax! Proper syntax: : /crefill [interval]"); return; } Infos[e.Player.Index].time = 0; if (e.Parameters.Count == 1) { int time; if (int.TryParse(e.Parameters[0], out time) && time > 0) { Infos[e.Player.Index].action = ChestAction.REFILL; Infos[e.Player.Index].time = time; e.Player.SendInfoMessage("Open a chest to make it refill with an interval of {0} second{1}.", time, time == 1 ? "" : "s"); return; } e.Player.SendErrorMessage("Invalid interval!"); } else { Infos[e.Player.Index].action = ChestAction.REFILL; e.Player.SendInfoMessage("Open a chest to toggle its refill status."); } } void PublicProtect(CommandArgs e) { Infos[e.Player.Index].action = ChestAction.PUBLIC; e.Player.SendInfoMessage("Open a chest to toggle its public status."); } void RegionProtect(CommandArgs e) { Infos[e.Player.Index].action = ChestAction.REGION; e.Player.SendInfoMessage("Open a chest to toggle its region share status."); } void Unlock(CommandArgs e) { if (e.Parameters.Count != 1) { e.Player.SendErrorMessage("Invalid syntax! Proper syntax: /cunlock <password>"); return; } Infos[e.Player.Index].password = e.Parameters[0]; e.Player.SendInfoMessage("Open chest to unlock it."); } void Unprotect(CommandArgs e) { Infos[e.Player.Index].action = ChestAction.UNPROTECT; e.Player.SendInfoMessage("Open a chest to unprotect it."); } } }
using UnityEngine; public class mapGenerator : MonoBehaviour { public GameObject[] units_of_pipe; public Camera mainCam; public GameObject bonus; public float exponent_move; public float _speed; private string GO_name = ""; private static int number_of_pipe = 8; private Vector3 startPosition; private float length_of_unit; private GameObject[] pipe = new GameObject[number_of_pipe]; [HideInInspector] public GameObject bonusPoint; [HideInInspector] public bool isBonusPoint = false; private float areaX, areaZ; private float speed, time; void Start() { time = 0f; areaX = GameObject.Find("Main Camera").GetComponent<Move>().areaX; areaZ = GameObject.Find("Main Camera").GetComponent<Move>().areaZ; length_of_unit = units_of_pipe[0].transform.localScale.y / 3 + 10.85f; startPosition = new Vector3(transform.position.x, transform.position.y, transform.position.z); bonusPoint = Instantiate(bonus, startPosition, Quaternion.identity); bonusPoint.SetActive(false); int j = -1; for (int i = 0; i < number_of_pipe; ++i) { if (j == units_of_pipe.Length - 1 || i == number_of_pipe - 2) { j = Random.Range(0, units_of_pipe.Length - 1); } else if (i == number_of_pipe - 1) { j = units_of_pipe.Length - 1; } else { j = Random.Range(0, units_of_pipe.Length); } pipe[i] = Instantiate(units_of_pipe[j], startPosition, Quaternion.identity); startPosition = new Vector3(startPosition.x, startPosition.y + length_of_unit, startPosition.z); } mainCam.transform.position = new Vector3(mainCam.transform.position.x, startPosition.y - length_of_unit + 100, mainCam.transform.position.z); } void FixedUpdate () { time += Time.fixedDeltaTime; speed = Mathf.Pow(time, exponent_move) * Time.fixedDeltaTime * _speed; Debug.Log(speed); bool check = false; for (int i = 0; i < number_of_pipe; ++i) { int j; if (pipe[i].transform.position.y >= mainCam.transform.position.y + 150) { Vector3 pos = new Vector3(pipe[i].transform.position.x, pipe[i].transform.position.y - length_of_unit * number_of_pipe, pipe[i].transform.position.z); //Debug.Log(GO_name); if (GO_name == "pipe_empty(Clone)" || GO_name == "") j = Random.Range(0, units_of_pipe.Length - 1); else j = Random.Range(0, units_of_pipe.Length); Destroy(pipe[i]); pipe[i] = Instantiate(units_of_pipe[j], pos, Quaternion.identity); GO_name = pipe[i].name; if (isBonusPoint) { bonusPoint.transform.position = new Vector3(Random.Range(0, areaX - 4), transform.position.y + Random.Range(0, length_of_unit / 2f), Random.Range(0, areaZ - 4)); bonusPoint.SetActive(true); isBonusPoint = false; } //continue; } if (!check && bonusPoint.activeInHierarchy) { check = true; bonusPoint.transform.position = new Vector3(bonusPoint.transform.position.x, bonusPoint.transform.position.y + speed, bonusPoint.transform.position.z); if (bonusPoint.transform.position.y >= mainCam.transform.position.y + 150) { bonusPoint.SetActive(false); } } //pipe[i].transform.position = new Vector3(pipe[i].transform.position.x, pipe[i].transform.position.y + speed, pipe[i].transform.position.z); pipe[i].transform.Translate(Vector3.up * speed); } } }
using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; [ExecuteInEditMode] public class Quiz : MonoBehaviour { public GameObject choices; public GameObject popupCanvas; public Text questionText; public Text popupCanvasText; public GameObject choicePrefab; public AudioSource audioSource; public AudioClip sfx_correct; public AudioClip sfx_wrong; public List<Question> questions; public int currentQuestionIndex; Question currentQuestion; public UnityEvent OnQuizFinished; public void LoadQuestion() { // Ensure currentQuestion is a valid index if (currentQuestionIndex < 0 || currentQuestionIndex >= questions.Count) { Debug.Log("currentQuestion does not fall under the range 0 to questions.Count"); return; } currentQuestion = questions[currentQuestionIndex]; // Set GUI text to string from question questionText.text = currentQuestion.text; // Ensure we have same number of buttons as choices if (choices.transform.childCount != currentQuestion.choices.Count) { Debug.Log(choices.transform.childCount + " buttons but " + currentQuestion.choices.Count + " choices."); return; } // Set each button text to current question choices text for (int i = 0; i < currentQuestion.choices.Count; i++) { ChoiceButton currentChoiceButton = choices.transform.GetChild(i).GetComponent<ChoiceButton>(); Choice currentChoice = currentQuestion.choices[i]; // Set button text to current choice text currentChoiceButton.label.text = currentChoice.text; // Will be used to set button colors ColorBlock colors = currentChoiceButton.button.colors; // Remove all listeners from button currentChoiceButton.button.onClick.RemoveAllListeners(); // Add listeners for right and wrong responses if (currentChoice.correct) { currentChoiceButton.button.onClick.AddListener(NextQuestion); colors.pressedColor = Color.green; } else { colors.pressedColor = Color.red; currentChoiceButton.button.onClick.AddListener(() => ShowPopup(currentChoice.correction_text)); } currentChoiceButton.button.colors = colors; } } public void NextQuestion() { audioSource.clip = sfx_correct; audioSource.Play(); // Increment our currentQuestionIndex currentQuestionIndex++; // End the quiz if we have reached the end of our list of questions if (currentQuestionIndex >= questions.Count) { EndQuiz(); return; } // otherwise, load the next question LoadQuestion(); } public void ShowPopup(string text) { audioSource.clip = sfx_wrong; audioSource.Play(); popupCanvasText.text = text; popupCanvas.SetActive(true); } void HidePopup() { popupCanvas.SetActive(false); } void EndQuiz() { if (OnQuizFinished != null) OnQuizFinished.Invoke(); } private void OnEnable() { LoadQuestion(); } private void OnGUI() { LoadQuestion(); } }
namespace Triton.Game.Mapping { using ns26; using System; [Attribute38("RotateByMovement")] public class RotateByMovement : MonoBehaviour { public RotateByMovement(IntPtr address) : this(address, "RotateByMovement") { } public RotateByMovement(IntPtr address, string className) : base(address, className) { } public void Update() { base.method_8("Update", Array.Empty<object>()); } public Vector3 m_previousPos { get { return base.method_2<Vector3>("m_previousPos"); } } public GameObject mParent { get { return base.method_3<GameObject>("mParent"); } } } }
using System; using System.Diagnostics; using System.Linq; using Microsoft.Extensions.Logging; namespace OmniSharp.Extensions.JsonRpc { public static class TimeLoggerExtensions { private class Disposable : IDisposable { private readonly IDisposable _disposable; private readonly Action<long> _action; private readonly Stopwatch _sw; public Disposable(IDisposable disposable, Action<long> action) { _disposable = disposable; _action = action; _sw = new Stopwatch(); _sw.Start(); } public void Dispose() { _sw.Stop(); _action(_sw.ElapsedMilliseconds); _disposable.Dispose(); } } /// <summary> /// Times the trace. /// </summary> /// <param name="logger">The logger.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> /// <returns>IDisposable.</returns> public static IDisposable TimeTrace(this ILogger logger, string message, params object[] args) { var scope = logger.BeginScope(new { }); logger.LogTrace($"Starting: {message}", args); return new Disposable( scope, elapsed => { var a = args.Concat(new object[] { elapsed }).ToArray(); logger.LogTrace($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); } ); } /// <summary> /// Times the debug. /// </summary> /// <param name="logger">The logger.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> /// <returns>IDisposable.</returns> public static IDisposable TimeDebug(this ILogger logger, string message, params object[] args) { var scope = logger.BeginScope(new { }); logger.LogDebug($"Starting: {message}", args); return new Disposable( scope, elapsed => { var a = args.Concat(new object[] { elapsed }).ToArray(); logger.LogDebug($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); } ); } /// <summary> /// Times the information. /// </summary> /// <param name="logger">The logger.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> /// <returns>IDisposable.</returns> public static IDisposable TimeInformation(this ILogger logger, string message, params object[] args) { var scope = logger.BeginScope(new { }); logger.LogInformation($"Starting: {message}", args); return new Disposable( scope, elapsed => { var a = args.Concat(new object[] { elapsed }).ToArray(); logger.LogInformation($"Finished: {message} in {{ElapsedMilliseconds}}ms", a); } ); } } }
using OPAM.Interface; using System; using System.Collections.Generic; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; namespace OPAM.Win.Common { /// <summary> /// This Class Implements the INavigator interface in Win 8.1 /// </summary> class NavigatorService : Frame, INavigator { #region Fields static NavigatorService frameNavigation; #endregion /// <summary> /// Dictionary with the Page List that value is Type of the Page /// </summary> public Dictionary<string, Type> PageList = new Dictionary<string, Type>() { { "AreaGridPage",typeof(View.AreaGridPage) }, { "HomePage",typeof(View.HomePage) }, { "TaskListPage",typeof(View.TaskListPage)}, { "TaskResultPage",typeof(View.TaskResultPage)} }; /// <summary> /// Default Constructor /// </summary> public NavigatorService() { } /// <summary> /// To create Singleton Instance /// </summary> /// <returns></returns> public static NavigatorService GetInstance() { if (frameNavigation != null) return frameNavigation; return frameNavigation = new NavigatorService(); } /// <summary> /// To Navigate To a given Page /// </summary> /// <param name="to">The page to be navigated To</param> public void NavigateTo(string to) { Type pageType; if (PageList.TryGetValue(to, out pageType)) ((Frame)Window.Current.Content).Navigate(pageType); } /// <summary> /// To Navigate To a given Page from another page /// </summary> /// <param name="from">The page to be navigated From</param> /// <param name="to">The page to be navigated To</param> public void NavigateTo(string from, string to) { Type pageType; if (PageList.TryGetValue(to, out pageType)) ((Frame)Window.Current.Content).Navigate(pageType); } } }
using System; using System.Collections.Generic; using System.Text; using ENTITY; //<summary> //Summary description for DesignationInfo //</summary> namespace ENTITY { public class DesignationInfo { private decimal _designationId; private string _designationName; private decimal _leaveDays; private decimal _advanceAmount; private string _narration; private DateTime _extraDate; private string _extra1; private string _extra2; public decimal DesignationId { get { return _designationId; } set { _designationId = value; } } public string DesignationName { get { return _designationName; } set { _designationName = value; } } public decimal LeaveDays { get { return _leaveDays; } set { _leaveDays = value; } } public decimal AdvanceAmount { get { return _advanceAmount; } set { _advanceAmount = value; } } public string Narration { get { return _narration; } set { _narration = value; } } public DateTime ExtraDate { get { return _extraDate; } set { _extraDate = value; } } public string Extra1 { get { return _extra1; } set { _extra1 = value; } } public string Extra2 { get { return _extra2; } set { _extra2 = value; } } } }
using System.Text.Json.Serialization; namespace Checkout.Payment.Processor.Application.Models.Enums { [JsonConverter(typeof(JsonStringEnumConverter))] public enum PaymentStatusModel { Processing, Failed, RejectedInsufficient, RejectedIncorrect, RejectedBlocked, Succeeded } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SkillTree : MonoBehaviour { public GameObject[] CardView; public void ShowTree(int TreeID) { if (TreeID == 0) { //for (int i = 0; i < onHand.Length; i++) //{ // onHand[i].SetActive(true); //} CardView[0].SetActive(true); CardView[1].SetActive(false); CardView[2].SetActive(false); } else if (TreeID == 1) { CardView[1].SetActive(true); CardView[0].SetActive(false); CardView[2].SetActive(false); } else if (TreeID == 2) { CardView[2].SetActive(true); CardView[0].SetActive(false); CardView[1].SetActive(false); } } }
using UnityEngine; using Zenject; namespace UI.Lives.Code { public class UILife : MonoBehaviour { public class Pool : MonoMemoryPool<UILife> { } } }
using Microsoft.AspNetCore.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CleanArch.Domain.Commands { public class CreateCategoryCommand : CategoryCommand { public CreateCategoryCommand(string name, string description, string imageUrl) { Name = name; Content = description; Image = imageUrl; } } }
using System; using Game.Difficult; using Game.Online.Multiplayer.Lobby; using UnityEngine; namespace Game { public class GameProvider : MonoBehaviour { public GameObject GameContainerPrefab; public void SetOnlineHost(Room room, Online.Player player) { var gamehost = new GameHost(room, player, GameContainerPrefab); } public void SetOfflineHost(BotDifficult difficult) { var gamehost = new GameHost(difficult, GameContainerPrefab); } } }
using System; namespace AlexTouch.Greystripe { public enum GSAdSize { Banner = 1, // 320x48 IPhoneFullScreen, // full screen IPadMediumRectangle, // 300x250 IPadLeaderboard, // 728x90 IPadWideSkyscraper // 160x600 } public enum GSAdError { NoError = 0, NoNetwork, NoAd, Timeout, ServerError, InvalidApplicationIdentifier, AdExpired, FetchLimitExceeded, Unknown } }
 #region Usings using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Zengo.WP8.FAS.Controls; using System; using System.Windows.Controls.Primitives; #endregion namespace Zengo.WP8.FAS.Helpers { public class PopupApplyingUpdatesHelper { #region Fields Popup popupControl; PopupAppyingUpdatesControl messageControl; #endregion #region Properties #endregion #region Constructors public PopupApplyingUpdatesHelper() { // Create the popups popupControl = new Popup(); messageControl = new PopupAppyingUpdatesControl(); popupControl.Child = messageControl; popupControl.VerticalOffset = 28; } #endregion internal void Show() { //try //{ // var currentPage = ((PhoneApplicationFrame)App.Current.RootVisual).Content; // if (currentPage is PhoneApplicationPage) // { // (currentPage as PhoneApplicationPage).ApplicationBar.IsVisible = false; // } //} //catch (Exception) //{ //} popupControl.IsOpen = true; } internal void Hide() { popupControl.IsOpen = false; //try //{ // var currentPage = ((PhoneApplicationFrame)App.Current.RootVisual).Content; // if (currentPage is PhoneApplicationPage) // { // (currentPage as PhoneApplicationPage).ApplicationBar.IsVisible = true; // } //} //catch (Exception) //{ //} } internal void SetProgress(int percent) { messageControl.SetProgress(percent); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading.Tasks; namespace Ornithology.Data { public interface IRepository<TEntity> where TEntity : class { IUnitOfWork UnitOfWork { get; } IEnumerable<TEntity> GetAll(); void Add(TEntity item); void AddRange(IList<TEntity> items); void Delete(TEntity item); void DeleteWhere(Expression<Func<TEntity, bool>> where); void Modify(TEntity item); void ModifyRange(IList<TEntity> items); IEnumerable<TEntity> GetFilteredElements(Expression<Func<TEntity, bool>> filter); IEnumerable<TEntity> GetFilteredElementsAsNoTracking(Expression<Func<TEntity, bool>> filter); Task<List<TEntity>> GetFilteredAsyncAsNoTracking(); Task<List<TEntity>> GetAllAsync(); Task<TEntity> GetFirstAsync(Expression<Func<TEntity, bool>> where); Task<List<TEntity>> GetManyAsync(Expression<Func<TEntity, bool>> where); Task<List<TEntity>> GetFilteredAsyncAsNoTracking(Expression<Func<TEntity, bool>> filter, params string[] include); } }
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // using Microsoft.PowerShell.EditorServices.Protocol.Client; using Microsoft.PowerShell.EditorServices.Protocol.DebugAdapter; using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol; using Microsoft.PowerShell.EditorServices.Protocol.MessageProtocol.Channel; using Microsoft.PowerShell.EditorServices.Test.Shared; using Microsoft.PowerShell.EditorServices.Utility; using System; using System.IO; using System.Threading.Tasks; using Xunit; namespace Microsoft.PowerShell.EditorServices.Test.Host { public class DebugAdapterTests : ServerTestsBase, IAsyncLifetime { private ILogger logger; private DebugAdapterClient debugAdapterClient; private string DebugScriptPath = Path.GetFullPath(TestUtilities.NormalizePath("../../../../PowerShellEditorServices.Test.Shared/Debugging/DebugTest.ps1")); public async Task InitializeAsync() { string testLogPath = Path.Combine( AppContext.BaseDirectory, "logs", this.GetType().Name, Guid.NewGuid().ToString().Substring(0, 8)); this.logger = Logging.CreateLogger() .LogLevel(LogLevel.Verbose) .AddLogFile(testLogPath + "-client.log") .Build(); testLogPath += "-server.log"; System.Console.WriteLine(" Output log at path: {0}", testLogPath); Tuple<string, string> pipeNames = await this.LaunchService( testLogPath, waitForDebugger: false); //waitForDebugger: true); this.debugAdapterClient = new DebugAdapterClient( await NamedPipeClientChannel.ConnectAsync( pipeNames.Item2, MessageProtocolType.DebugAdapter, this.logger), this.logger); this.messageSender = this.debugAdapterClient; this.messageHandlers = this.debugAdapterClient; await this.debugAdapterClient.StartAsync(); } public Task DisposeAsync() { this.debugAdapterClient.Stop(); this.KillService(); return Task.FromResult(true); } [Fact] public async Task DebugAdapterStopsOnLineBreakpoints() { await this.SendRequest( SetBreakpointsRequest.Type, new SetBreakpointsRequestArguments { Source = new Source { Path = DebugScriptPath }, Breakpoints = new [] { new SourceBreakpoint { Line = 5 }, new SourceBreakpoint { Line = 7 } } }); Task<StoppedEventBody> breakEventTask = this.WaitForEvent(StoppedEvent.Type); await this.LaunchScript(DebugScriptPath); // Wait for a couple breakpoints StoppedEventBody stoppedDetails = await breakEventTask; Assert.Equal(DebugScriptPath, stoppedDetails.Source.Path); var stackTraceResponse = await this.SendRequest( StackTraceRequest.Type, new StackTraceRequestArguments()); Assert.Equal(5, stackTraceResponse.StackFrames[0].Line); breakEventTask = this.WaitForEvent(StoppedEvent.Type); await this.SendRequest(ContinueRequest.Type, new object()); stoppedDetails = await breakEventTask; Assert.Equal(DebugScriptPath, stoppedDetails.Source.Path); stackTraceResponse = await this.SendRequest( StackTraceRequest.Type, new StackTraceRequestArguments()); Assert.Equal(7, stackTraceResponse.StackFrames[0].Line); // Abort script execution await this.SendRequest(DisconnectRequest.Type, new object()); } [Fact] public async Task DebugAdapterReceivesOutputEvents() { OutputReader outputReader = new OutputReader(this.debugAdapterClient); await this.LaunchScript(DebugScriptPath); // Skip the first 2 lines which just report the script // that is being executed await outputReader.ReadLines(2); // Make sure we're getting output from the script Assert.Equal("Output 1", await outputReader.ReadLine()); // Abort script execution await this.SendRequest(DisconnectRequest.Type, new object()); } private async Task LaunchScript(string scriptPath) { await this.debugAdapterClient.LaunchScriptAsync(scriptPath); } } }
using NChampions.Domain.Commands.Teams; using NChampions.Domain.Response; namespace NChampions.Domain.Handlers { public interface ITeamHandler : MediatR.IRequestHandler<CreateTeamCommand,ResponseApi>, MediatR.IRequestHandler<UpdateTeamCommand, ResponseApi> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Training_App.Classes; namespace Training_App { class Program { static void Main(string[] args) { var cube = new cube(); var square = new square(); cube.setL(2); square.setL(5); bool bExit = true; while (bExit) { var sh = new shape(); Console.WriteLine(@"Type your choice or type '0' to exit"); Console.WriteLine(@"Select shape to paint: 1 - square, 2 - cube"); string line = Console.ReadLine(); if (line == "0") { break; } switch (line) { case "1": sh = square; break; case "2": sh = cube; break; default: break; } sh.theArea(sh.getL()); } } } }
using MZcms.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MZcms.IServices { public interface IUserService : IService { Users GetUser(long userId); } }